diff --git a/src/C4Application.cpp b/src/C4Application.cpp index fde17f491..a5aaff8ef 100644 --- a/src/C4Application.cpp +++ b/src/C4Application.cpp @@ -83,7 +83,7 @@ bool C4Application::DoInit() assert(AppState == C4AS_None); // Config overwrite by parameter StdStrBuf sConfigFilename; - char szParameter[_MAX_PATH+1]; + char szParameter[_MAX_PATH+1]; for (int32_t iPar=0; SGetParameter(GetCommandLine(), iPar, szParameter, _MAX_PATH); iPar++) if (SEqual2NoCase(szParameter, "/config:")) sConfigFilename.Copy(szParameter + 8); @@ -499,19 +499,19 @@ void C4Application::Activate() // As this is officially not possible any more in new versions of Windows // (BringWindowTopTop alone won't have any effect if the calling process is // not in the foreground itself), we are using an ugly OS hack. - DWORD nForeThread = GetWindowThreadProcessId(GetForegroundWindow(), 0); - DWORD nAppThread = GetCurrentThreadId(); + DWORD nForeThread = GetWindowThreadProcessId(GetForegroundWindow(), 0); + DWORD nAppThread = GetCurrentThreadId(); if (nForeThread != nAppThread) { - AttachThreadInput(nForeThread, nAppThread, true); - BringWindowToTop(FullScreen.hWindow); - ShowWindow(FullScreen.hWindow, SW_SHOW); - AttachThreadInput(nForeThread, nAppThread, false); + AttachThreadInput(nForeThread, nAppThread, true); + BringWindowToTop(FullScreen.hWindow); + ShowWindow(FullScreen.hWindow, SW_SHOW); + AttachThreadInput(nForeThread, nAppThread, false); } - else + else { - BringWindowToTop(FullScreen.hWindow); - ShowWindow(FullScreen.hWindow, SW_SHOW); + BringWindowToTop(FullScreen.hWindow); + ShowWindow(FullScreen.hWindow, SW_SHOW); } #endif } diff --git a/src/C4FullScreen.cpp b/src/C4FullScreen.cpp index 87edccd9d..d672cef69 100644 --- a/src/C4FullScreen.cpp +++ b/src/C4FullScreen.cpp @@ -235,7 +235,7 @@ void C4FullScreen::HandleMessage (XEvent &e) ::GraphicsSystem.MouseMove(C4MC_Button_RightUp, e.xbutton.x, e.xbutton.y, e.xbutton.state, NULL); break; default: - break; + break; } break; case MotionNotify: @@ -257,75 +257,75 @@ void C4FullScreen::HandleMessage (XEvent &e) namespace { - void sdlToC4MCBtn(const SDL_MouseButtonEvent &e, - int32_t& button, DWORD& flags) - { - static int lastLeftClick = 0, lastRightClick = 0; + void sdlToC4MCBtn(const SDL_MouseButtonEvent &e, + int32_t& button, DWORD& flags) + { + static int lastLeftClick = 0, lastRightClick = 0; static int lastX = 0, lastY = 0; static const int clickDist = 2; - button = C4MC_Button_None; - flags = 0; + button = C4MC_Button_None; + flags = 0; - switch (e.button) - { - case SDL_BUTTON_LEFT: - if (e.state == SDL_PRESSED) - if (timeGetTime() - lastLeftClick < 400 && abs(lastX-e.x) <= clickDist && abs(lastY-e.y) <= clickDist) - { - lastLeftClick = 0; - button = C4MC_Button_LeftDouble; - } - else - { - lastLeftClick = timeGetTime(); - button = C4MC_Button_LeftDown; - } - else - button = C4MC_Button_LeftUp; - break; - case SDL_BUTTON_RIGHT: - if (e.state == SDL_PRESSED) - if (timeGetTime() - lastRightClick < 400) - { - lastRightClick = 0; - button = C4MC_Button_RightDouble; - } - else - { - lastRightClick = timeGetTime(); - button = C4MC_Button_RightDown; - } - else - button = C4MC_Button_RightUp; - break; - case SDL_BUTTON_MIDDLE: - if (e.state == SDL_PRESSED) - button = C4MC_Button_MiddleDown; - else - button = C4MC_Button_MiddleUp; - break; - case SDL_BUTTON_WHEELUP: - button = C4MC_Button_Wheel; - flags = (+32) << 16; - break; - case SDL_BUTTON_WHEELDOWN: - button = C4MC_Button_Wheel; - flags = (-32) << 16; - break; - } - lastX = e.x; - lastY = e.y; - } + switch (e.button) + { + case SDL_BUTTON_LEFT: + if (e.state == SDL_PRESSED) + if (timeGetTime() - lastLeftClick < 400 && abs(lastX-e.x) <= clickDist && abs(lastY-e.y) <= clickDist) + { + lastLeftClick = 0; + button = C4MC_Button_LeftDouble; + } + else + { + lastLeftClick = timeGetTime(); + button = C4MC_Button_LeftDown; + } + else + button = C4MC_Button_LeftUp; + break; + case SDL_BUTTON_RIGHT: + if (e.state == SDL_PRESSED) + if (timeGetTime() - lastRightClick < 400) + { + lastRightClick = 0; + button = C4MC_Button_RightDouble; + } + else + { + lastRightClick = timeGetTime(); + button = C4MC_Button_RightDown; + } + else + button = C4MC_Button_RightUp; + break; + case SDL_BUTTON_MIDDLE: + if (e.state == SDL_PRESSED) + button = C4MC_Button_MiddleDown; + else + button = C4MC_Button_MiddleUp; + break; + case SDL_BUTTON_WHEELUP: + button = C4MC_Button_Wheel; + flags = (+32) << 16; + break; + case SDL_BUTTON_WHEELDOWN: + button = C4MC_Button_Wheel; + flags = (-32) << 16; + break; + } + lastX = e.x; + lastY = e.y; + } - bool isSpecialKey(unsigned unicode) - { - if (unicode >= 0xe00) - return true; - if (unicode < 32 || unicode == 127) - return true; - return false; - } + bool isSpecialKey(unsigned unicode) + { + if (unicode >= 0xe00) + return true; + if (unicode < 32 || unicode == 127) + return true; + return false; + } } #include "StdGL.h" @@ -336,18 +336,18 @@ void C4FullScreen::HandleMessage (SDL_Event &e) { case SDL_KEYDOWN: { - #ifdef USE_GL - if (e.key.keysym.sym == SDLK_f && (e.key.keysym.mod & (KMOD_LMETA | KMOD_RMETA))) - { - Config.Graphics.Windowed = !Config.Graphics.Windowed; - if (pGL) pGL->fFullscreen = !Config.Graphics.Windowed; + #ifdef USE_GL + if (e.key.keysym.sym == SDLK_f && (e.key.keysym.mod & (KMOD_LMETA | KMOD_RMETA))) + { + Config.Graphics.Windowed = !Config.Graphics.Windowed; + if (pGL) pGL->fFullscreen = !Config.Graphics.Windowed; Application.SetVideoMode(Config.Graphics.ResX, Config.Graphics.ResY, Config.Graphics.BitDepth, Config.Graphics.Monitor, !Config.Graphics.Windowed); - lpDDraw->InvalidateDeviceObjects(); - lpDDraw->RestoreDeviceObjects(); + lpDDraw->InvalidateDeviceObjects(); + lpDDraw->RestoreDeviceObjects(); - break; - } - #endif + break; + } + #endif // Only forward real characters to UI. (Nothing outside of "private use" range.) // This works without iconv for some reason. Yay! @@ -417,7 +417,7 @@ void C4FullScreen::Execute() { // Execute menu if (pMenu) pMenu->Execute(); - // Draw + // Draw ::GraphicsSystem.Execute(); } diff --git a/src/C4Game.cpp b/src/C4Game.cpp index 92c2aae0f..5e02c088a 100644 --- a/src/C4Game.cpp +++ b/src/C4Game.cpp @@ -94,12 +94,12 @@ C4Game::C4Game() pSec1Timer(new C4GameSec1Timer()), fPreinited(false), StartupLogPos(0), QuitLogPos(0), fQuitWithError(false) - { + { Default(); - } + } C4Game::~C4Game() - { + { // remove timer delete pSec1Timer; pSec1Timer = NULL; // make sure no startup gfx remain loaded @@ -135,7 +135,7 @@ bool C4Game::InitDefs() // Check def engine version (should be done immediately on def load) iDefs=::Definitions.CheckEngineVersion(C4XVER1,C4XVER2,C4XVER3,C4XVER4); - if (iDefs>0) { LogF(LoadResStr("IDS_PRC_DEFSINVC4X"),iDefs); } + if (iDefs>0) { LogF(LoadResStr("IDS_PRC_DEFSINVC4X"),iDefs); } // Check for unmet requirements ::Definitions.CheckRequireDef(); @@ -147,12 +147,12 @@ bool C4Game::InitDefs() Particles.SetDefParticles(); // Done - return true; - } + return true; + } bool C4Game::OpenScenario() - { + { // Scenario from record stream if(RecordStream.getSize()) @@ -165,7 +165,7 @@ bool C4Game::OpenScenario() // Scenario filename check & log if (!ScenarioFilename[0]) { LogFatal(LoadResStr("IDS_PRC_NOC4S")); return false; } - LogF(LoadResStr("IDS_PRC_LOADC4S"),ScenarioFilename); + LogF(LoadResStr("IDS_PRC_LOADC4S"),ScenarioFilename); // get parent folder, if it's c4f pParentGroup = GroupSet.RegisterParentFolders(ScenarioFilename); @@ -185,8 +185,8 @@ bool C4Game::OpenScenario() // add scenario to group GroupSet.RegisterGroup(ScenarioFile, false, C4GSPrio_Scenario, C4GSCnt_Scenario); - // Read scenario core - if (!C4S.Load(ScenarioFile)) + // Read scenario core + if (!C4S.Load(ScenarioFile)) { LogFatal(LoadResStr("IDS_PRC_FILEINVALID")); return false; } // Check minimum engine version @@ -267,16 +267,16 @@ bool C4Game::OpenScenario() if(!ScenarioFile.IsPacked() && pFileMonitor) Game.pFileMonitor->AddDirectory(ScenarioFile.GetFullName().getData()); - return true; - } + return true; + } void C4Game::CloseScenario() - { + { // safe scenario file name char szSzenarioFile[_MAX_PATH + 1]; SCopy(ScenarioFile.GetFullName().getData(), szSzenarioFile, _MAX_PATH); // close scenario - ScenarioFile.Close(); + ScenarioFile.Close(); GroupSet.CloseFolders(); pParentGroup = NULL; // remove if temporary @@ -289,7 +289,7 @@ void C4Game::CloseScenario() // this removes any temp files, which may yet need to be used by any future features // so better don't do this too early (like, in C4Game::Clear) if (pScenarioSections) { delete pScenarioSections; pScenarioSections=pCurrentScenarioSection=NULL;} - } + } bool C4Game::PreInit() @@ -405,8 +405,8 @@ bool C4Game::Init() if(!OpenScenario()) return false; TempScenarioFile = true; - // get everything else - if(!Parameters.GameRes.RetrieveFiles()) return false; + // get everything else + if(!Parameters.GameRes.RetrieveFiles()) return false; // Check network game data scenario type (safety) if (!C4S.Head.NetworkGame) @@ -425,12 +425,12 @@ bool C4Game::Init() { LogFatal(LoadResStr("IDS_PRC_FAIL")); return false; } // init extra; needed for loader screen - Log(LoadResStr("IDS_PRC_INITEXTRA")); + Log(LoadResStr("IDS_PRC_INITEXTRA")); if (!Extra.Init()) { LogFatal(LoadResStr("IDS_PRC_ERREXTRA")); return false; } // init loader - if (Application.isFullScreen && !GraphicsSystem.InitLoaderScreen(C4S.Head.Loader, false)) + if (Application.isFullScreen && !GraphicsSystem.InitLoaderScreen(C4S.Head.Loader, false)) { LogFatal(LoadResStr("IDS_PRC_ERRLOADER")); return false; } // Init network @@ -582,7 +582,7 @@ void C4Game::Clear() RecordDumpFile.Clear(); RecordStream.Clear(); - PathFinder.Clear(); + PathFinder.Clear(); TransferZones.Clear(); #ifndef USE_CONSOLE FontLoader.Clear(); @@ -592,7 +592,7 @@ void C4Game::Clear() MainSysLangStringTable.Clear(); ScenarioLangStringTable.Clear(); ScenarioSysLangStringTable.Clear(); - CloseScenario(); + CloseScenario(); GroupSet.Clear(); KeyboardInput.Clear(); SetMusicLevel(100); @@ -621,7 +621,7 @@ void C4Game::Clear() QuitLogPos = GetLogPos(); fPreinited = false; - } + } bool C4Game::GameOverCheck() { @@ -645,7 +645,7 @@ bool C4Game::GameOverCheck() if (fDoGameOver) DoGameOver(); return GameOver; - } + } int32_t iLastControlSize=0; extern int32_t iPacketDelay; @@ -676,10 +676,10 @@ C4ST_NEW(ScriptStat, "C4Game::Execute Script.Execute") #endif bool C4Game::Execute() // Returns true if the game is over - { + { - // Let's go - GameGo = true; + // Let's go + GameGo = true; // Network Network.Execute(); @@ -738,7 +738,7 @@ bool C4Game::Execute() // Returns true if the game is over if (!GameOverDlgShown) ShowGameOverDlg(); } - // show stat each 1000 ticks + // show stat each 1000 ticks if(!(FrameCounter % 1000)) { C4ST_SHOWPARTSTAT(FrameCounter) @@ -751,8 +751,8 @@ bool C4Game::Execute() // Returns true if the game is over Landscape.DoRelights(); #endif - return true; - } + return true; + } void C4Game::InitFullscreenComponents(bool fRunning) { @@ -777,7 +777,7 @@ void C4Game::InitFullscreenComponents(bool fRunning) } bool C4Game::InitMaterialTexture() - { + { // Clear old data TextureMap.Clear(); @@ -851,8 +851,8 @@ bool C4Game::InitMaterialTexture() } // Logs - LogF(LoadResStr("IDS_PRC_TEXTURES"),tex_count); - LogF(LoadResStr("IDS_PRC_MATERIALS"),mat_count); + LogF(LoadResStr("IDS_PRC_TEXTURES"),tex_count); + LogF(LoadResStr("IDS_PRC_MATERIALS"),mat_count); // Load material enumeration if (!::MaterialMap.LoadEnumeration(ScenarioFile)) @@ -861,7 +861,7 @@ bool C4Game::InitMaterialTexture() // Initialize texture map TextureMap.Init(); - // Cross map mats (after texture init, because Material-Texture-combinations are used) + // Cross map mats (after texture init, because Material-Texture-combinations are used) if (!::MaterialMap.CrossMapMaterials()) return false; // mapping to landscape palette will occur when landscape has been created @@ -871,22 +871,22 @@ bool C4Game::InitMaterialTexture() // get material script funcs ::MaterialMap.UpdateScriptPointers(); - return true; - } + return true; + } void C4Game::ClearObjectPtrs(C4Object *pObj) - { + { // May not call Objects.ClearPointers() because that would // remove pObj from primary list and pObj is to be kept // until CheckObjectRemoval(). - C4Object *cObj; C4ObjectLink *clnk; - for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) + C4Object *cObj; C4ObjectLink *clnk; + for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) cObj->ClearPointers(pObj); // check in inactive objects as well - for (clnk=Objects.InactiveObjects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) + for (clnk=Objects.InactiveObjects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) cObj->ClearPointers(pObj); - Application.SoundSystem.ClearPointers(pObj); - } + Application.SoundSystem.ClearPointers(pObj); + } void C4Game::ClearPointers(C4PropList * PropList) { @@ -895,16 +895,16 @@ void C4Game::ClearPointers(C4PropList * PropList) ::Objects.BackObjects.ClearPointers(pObj); ::Objects.ForeObjects.ClearPointers(pObj); ::Messages.ClearPointers(pObj); - ClearObjectPtrs(pObj); - Players.ClearPointers(pObj); + ClearObjectPtrs(pObj); + Players.ClearPointers(pObj); GraphicsSystem.ClearPointers(pObj); MessageInput.ClearPointers(pObj); Console.ClearPointers(pObj); MouseControl.ClearPointers(pObj); TransferZones.ClearPointers(pObj); - if(pGlobalEffects) - pGlobalEffects->ClearPointers(pObj); - } + if(pGlobalEffects) + pGlobalEffects->ClearPointers(pObj); + } bool C4Game::TogglePause() { @@ -976,13 +976,13 @@ bool C4Game::IsPaused() C4Object* C4Game::NewObject( C4PropList *pDef, C4Object *pCreator, - int32_t iOwner, C4ObjectInfo *pInfo, - int32_t iX, int32_t iY, int32_t iR, - FIXED xdir, FIXED ydir, FIXED rdir, - int32_t iCon, int32_t iController) - { + int32_t iOwner, C4ObjectInfo *pInfo, + int32_t iX, int32_t iY, int32_t iR, + FIXED xdir, FIXED ydir, FIXED rdir, + int32_t iCon, int32_t iController) + { // Safety - if (!pDef) return NULL; + if (!pDef) return NULL; #ifdef DEBUGREC C4RCCreateObj rc; rc.id=pDef->Number; @@ -991,12 +991,12 @@ C4Object* C4Game::NewObject( C4PropList *pDef, C4Object *pCreator, AddDbgRec(RCT_CrObj, &rc, sizeof(rc)); #endif // Create object - C4Object *pObj; - if (!(pObj=new C4Object)) return NULL; + C4Object *pObj; + if (!(pObj=new C4Object)) return NULL; // Initialize object pObj->Init( pDef,pCreator,iOwner,pInfo,iX,iY,iR,xdir,ydir,rdir, iController ); // Add to object list - if (!Objects.Add(pObj)) { delete pObj; return NULL; } + if (!Objects.Add(pObj)) { delete pObj; return NULL; } // ---- From now on, object is ready to be used in scripts! // Construction callback C4AulParSet pars(C4VObj(pCreator)); @@ -1004,134 +1004,134 @@ C4Object* C4Game::NewObject( C4PropList *pDef, C4Object *pCreator, // AssignRemoval called? (Con 0) if(!pObj->Status) { return NULL; } // Do initial con - pObj->DoCon(iCon,true); + pObj->DoCon(iCon,true); // AssignRemoval called? (Con 0) if(!pObj->Status) { return NULL; } // Success - return pObj; - } + return pObj; + } void C4Game::DeleteObjects(bool fDeleteInactive) - { + { // del any objects ::Objects.DeleteObjects(fDeleteInactive); // reset resort flag fResortAnyObject = false; - } + } C4Object* C4Game::CreateObject(C4ID id, C4Object *pCreator, int32_t iOwner, - int32_t x, int32_t y, int32_t r, - FIXED xdir, FIXED ydir, FIXED rdir, int32_t iController) - { - C4Def *pDef; - // Get pDef - if (!(pDef=C4Id2Def(id))) return NULL; - // Create object - return NewObject(pDef,pCreator, - iOwner,NULL, - x,y,r, - xdir,ydir,rdir, - FullCon, iController); - } + int32_t x, int32_t y, int32_t r, + FIXED xdir, FIXED ydir, FIXED rdir, int32_t iController) + { + C4Def *pDef; + // Get pDef + if (!(pDef=C4Id2Def(id))) return NULL; + // Create object + return NewObject(pDef,pCreator, + iOwner,NULL, + x,y,r, + xdir,ydir,rdir, + FullCon, iController); + } C4Object* C4Game::CreateObject(C4PropList * PropList, C4Object *pCreator, int32_t iOwner, - int32_t x, int32_t y, int32_t r, - FIXED xdir, FIXED ydir, FIXED rdir, int32_t iController) - { - C4Def *pDef; - // Get pDef - if (!PropList || !(pDef=PropList->GetDef())) return NULL; - // Create object - return NewObject(pDef,pCreator, - iOwner,NULL, - x,y,r, - xdir,ydir,rdir, - FullCon, iController); - } + int32_t x, int32_t y, int32_t r, + FIXED xdir, FIXED ydir, FIXED rdir, int32_t iController) + { + C4Def *pDef; + // Get pDef + if (!PropList || !(pDef=PropList->GetDef())) return NULL; + // Create object + return NewObject(pDef,pCreator, + iOwner,NULL, + x,y,r, + xdir,ydir,rdir, + FullCon, iController); + } C4Object* C4Game::CreateInfoObject(C4ObjectInfo *cinf, int32_t iOwner, - int32_t tx, int32_t ty) - { - C4Def *def; - // Valid check - if (!cinf) return NULL; - // Get def - if (!(def=C4Id2Def(cinf->id))) return NULL; - // Create object - return NewObject( def,NULL, - iOwner,cinf, - tx,ty,0, - Fix0,Fix0,Fix0, - FullCon, NO_OWNER ); - } + int32_t tx, int32_t ty) + { + C4Def *def; + // Valid check + if (!cinf) return NULL; + // Get def + if (!(def=C4Id2Def(cinf->id))) return NULL; + // Create object + return NewObject( def,NULL, + iOwner,cinf, + tx,ty,0, + Fix0,Fix0,Fix0, + FullCon, NO_OWNER ); + } C4Object* C4Game::CreateObjectConstruction(C4PropList * PropList, - C4Object *pCreator, - int32_t iOwner, - int32_t iX, int32_t iBY, - int32_t iCon, - bool fTerrain) - { - C4Def *pDef; - C4Object *pObj; + C4Object *pCreator, + int32_t iOwner, + int32_t iX, int32_t iBY, + int32_t iCon, + bool fTerrain) + { + C4Def *pDef; + C4Object *pObj; - // Get def - if (!PropList) return NULL; - if (!(pDef=PropList->GetDef())) return NULL; + // Get def + if (!PropList) return NULL; + if (!(pDef=PropList->GetDef())) return NULL; - int32_t dx,dy,dwdt,dhgt; - dwdt=pDef->Shape.Wdt; dhgt=pDef->Shape.Hgt; - dx=iX-dwdt/2; dy=iBY-dhgt; + int32_t dx,dy,dwdt,dhgt; + dwdt=pDef->Shape.Wdt; dhgt=pDef->Shape.Hgt; + dx=iX-dwdt/2; dy=iBY-dhgt; - // Terrain - if (fTerrain) - { - // Clear site background (ignored for ultra-large structures) + // Terrain + if (fTerrain) + { + // Clear site background (ignored for ultra-large structures) if (dwdt*dhgt<12000) Landscape.DigFreeRect(dx,dy,dwdt,dhgt); - // Raise Terrain - Landscape.RaiseTerrain(dx,dy+dhgt,dwdt); - } + // Raise Terrain + Landscape.RaiseTerrain(dx,dy+dhgt,dwdt); + } - // Create object + // Create object if (!(pObj=NewObject(pDef, pCreator, - iOwner,NULL, - iX,iBY,0, - Fix0,Fix0,Fix0, - iCon, pCreator ? pCreator->Controller : NO_OWNER))) return NULL; + iOwner,NULL, + iX,iBY,0, + Fix0,Fix0,Fix0, + iCon, pCreator ? pCreator->Controller : NO_OWNER))) return NULL; - return pObj; - } + return pObj; + } void C4Game::BlastObjects(int32_t tx, int32_t ty, int32_t level, C4Object *inobj, int32_t iCausedBy, C4Object *pByObj) - { - C4Object *cObj; C4ObjectLink *clnk; + { + C4Object *cObj; C4ObjectLink *clnk; // layer check: Blast in same layer only if (pByObj) pByObj = pByObj->pLayer; - // Contained blast - if (inobj) - { - inobj->Blast(level,iCausedBy); - for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) - if (cObj->Status) if (cObj->Contained==inobj) if (cObj->pLayer==pByObj) - cObj->Blast(level,iCausedBy); - } + // Contained blast + if (inobj) + { + inobj->Blast(level,iCausedBy); + for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) + if (cObj->Status) if (cObj->Contained==inobj) if (cObj->pLayer==pByObj) + cObj->Blast(level,iCausedBy); + } - // Uncontained blast local outside objects - else - { - for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) - if (cObj->Status) if (!cObj->Contained) if (cObj->pLayer==pByObj) - { - // Direct hit (5 pixel range to all sides) - if (Inside( ty-(cObj->GetY()+cObj->Shape.y), -5, cObj->Shape.Hgt-1+10 )) - if (Inside( tx-(cObj->GetX()+cObj->Shape.x), -5, cObj->Shape.Wdt-1+10 )) - cObj->Blast(level,iCausedBy); - // Shock wave hit (if in level range, living, object and vehicle only. No structures/StatickBack, as this would mess up castles, elevators, etc.!) - if (cObj->Category & (C4D_Living | C4D_Object | C4D_Vehicle)) + // Uncontained blast local outside objects + else + { + for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) + if (cObj->Status) if (!cObj->Contained) if (cObj->pLayer==pByObj) + { + // Direct hit (5 pixel range to all sides) + if (Inside( ty-(cObj->GetY()+cObj->Shape.y), -5, cObj->Shape.Hgt-1+10 )) + if (Inside( tx-(cObj->GetX()+cObj->Shape.x), -5, cObj->Shape.Wdt-1+10 )) + cObj->Blast(level,iCausedBy); + // Shock wave hit (if in level range, living, object and vehicle only. No structures/StatickBack, as this would mess up castles, elevators, etc.!) + if (cObj->Category & (C4D_Living | C4D_Object | C4D_Vehicle)) if (!cObj->Def->NoHorizontalMove) if (Abs(ty-cObj->GetY())<=level) if (Abs(tx-cObj->GetX())<=level) @@ -1161,31 +1161,31 @@ void C4Game::BlastObjects(int32_t tx, int32_t ty, int32_t level, C4Object *inobj cObj->Fling( itofix(Sign(cObj->GetX()-tx+Rnd3())*(level-Abs(tx-cObj->GetX()))) / BoundBy(cObj->Mass/10, 4, (cObj->Category & C4D_Living) ? 8 : 20), itofix(-level+Abs(ty-cObj->GetY())) / BoundBy(cObj->Mass/10, 4, (cObj->Category & C4D_Living) ? 8 : 20), true ); } - } - } - } + } + } + } void C4Game::ShakeObjects(int32_t tx, int32_t ty, int32_t range) - { - C4Object *cObj; C4ObjectLink *clnk; + { + C4Object *cObj; C4ObjectLink *clnk; - for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) - if (cObj->Status) if (!cObj->Contained) - if (cObj->Category & C4D_Living) - if (Abs(ty-cObj->GetY())<=range) - if (Abs(tx-cObj->GetX())<=range) + for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) + if (cObj->Status) if (!cObj->Contained) + if (cObj->Category & C4D_Living) + if (Abs(ty-cObj->GetY())<=range) + if (Abs(tx-cObj->GetX())<=range) if (!Random(3)) if (cObj->Action.t_attach) if (!MatVehicle(cObj->Shape.AttachMat)) cObj->Fling(itofix(Rnd3()),Fix0,false); - } + } C4Object* C4Game::OverlapObject(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, int32_t category) - { - C4Object *cObj; C4ObjectLink *clnk; - C4Rect rect1,rect2; - rect1.x=tx; rect1.y=ty; rect1.Wdt=wdt; rect1.Hgt=hgt; + { + C4Object *cObj; C4ObjectLink *clnk; + C4Rect rect1,rect2; + rect1.x=tx; rect1.y=ty; rect1.Wdt=wdt; rect1.Hgt=hgt; C4LArea Area(&::Objects.Sectors, tx, ty, wdt, hgt); C4LSector *pSector; for (C4ObjectList *pObjs = Area.FirstObjectShapes(&pSector); pSector; pObjs = Area.NextObjectShapes(pObjs, &pSector)) for (clnk=pObjs->First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) @@ -1195,11 +1195,11 @@ C4Object* C4Game::OverlapObject(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt rect2=cObj->Shape; rect2.x+=cObj->GetX(); rect2.y+=cObj->GetY(); if (rect1.Overlap(rect2)) return cObj; } - return NULL; - } + return NULL; + } C4Object* C4Game::FindObject(C4ID id, - int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, + int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, DWORD ocf, const char *szAction, C4Object *pActionTarget, C4Object *pExclude, @@ -1381,34 +1381,34 @@ int32_t C4Game::ObjectCount(C4ID id) // Pointer clearance is done by AssignRemoval. void C4Game::ObjectRemovalCheck() // Every ::Game.iTick255 by ExecObjects - { - C4Object *cObj; C4ObjectLink *clnk,*next; - for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=next) - { - next=clnk->Next; - if (!cObj->Status && (cObj->RemovalDelay==0)) - { - Objects.Remove(cObj); - delete cObj; - } - } - } + { + C4Object *cObj; C4ObjectLink *clnk,*next; + for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=next) + { + next=clnk->Next; + if (!cObj->Status && (cObj->RemovalDelay==0)) + { + Objects.Remove(cObj); + delete cObj; + } + } + } void C4Game::ExecObjects() // Every Tick1 by Execute - { + { #ifdef DEBUGREC AddDbgRec(RCT_Block, "ObjEx", 6); #endif // Execute objects - reverse order to ensure - C4Object *cObj; C4ObjectLink *clnk; - for (clnk=Objects.Last; clnk && (cObj=clnk->Obj); clnk=clnk->Prev) - if (cObj->Status) + C4Object *cObj; C4ObjectLink *clnk; + for (clnk=Objects.Last; clnk && (cObj=clnk->Obj); clnk=clnk->Prev) + if (cObj->Status) // Execute object - cObj->Execute(); - else + cObj->Execute(); + else // Status reset: process removal delay - if (cObj->RemovalDelay>0) cObj->RemovalDelay--; + if (cObj->RemovalDelay>0) cObj->RemovalDelay--; #ifdef DEBUGREC AddDbgRec(RCT_Block, "ObjCC", 6); @@ -1418,15 +1418,15 @@ void C4Game::ExecObjects() // Every Tick1 by Execute Objects.LastUsedMarker = 0; // Cross check objects - Objects.CrossCheck(); + Objects.CrossCheck(); #ifdef DEBUGREC AddDbgRec(RCT_Block, "ObjRs", 6); #endif // Resort - if (fResortAnyObject) - { + if (fResortAnyObject) + { fResortAnyObject = false; Objects.ResortUnsorted(); } @@ -1437,8 +1437,8 @@ void C4Game::ExecObjects() // Every Tick1 by Execute #endif // Removal - if (!::Game.iTick255) ObjectRemovalCheck(); - } + if (!::Game.iTick255) ObjectRemovalCheck(); + } bool C4Game::CreateViewport(int32_t iPlayer, bool fSilent) { @@ -1555,18 +1555,18 @@ void C4Game::Default() ObjectEnumerationIndex=0; FullSpeed=false; FrameSkip=1; DoSkipFrame=false; - ::Definitions.Default(); - ::MaterialMap.Default(); - Objects.Default(); + ::Definitions.Default(); + ::MaterialMap.Default(); + Objects.Default(); Players.Default(); - Weather.Default(); - Landscape.Default(); - TextureMap.Default(); + Weather.Default(); + Landscape.Default(); + TextureMap.Default(); ::DefaultRanks.Default(); - MassMover.Default(); + MassMover.Default(); PXS.Default(); GraphicsSystem.Default(); - C4S.Default(); + C4S.Default(); ::Messages.Default(); MessageInput.Default(); Info.Default(); @@ -1613,7 +1613,7 @@ void C4Game::Evaluate() if(fLeague) Network.LeagueGameEvaluate(RecordName.getData(), RecordSHA); - // Players + // Players // saving local players only, because remote players will probably not rejoin after evaluation anyway) Players.Evaluate(); Players.Save(true); @@ -1628,11 +1628,11 @@ void C4Game::Evaluate() } void C4Game::DrawCursors(C4TargetFacet &cgo, int32_t iPlayer) - { + { // Draw cursor mark arrow & cursor object name - float cox,coy; - int32_t cphase; - C4Object *cursor; + float cox,coy; + int32_t cphase; + C4Object *cursor; C4Facet &fctCursor = GraphicsResource.fctCursor; for (C4Player *pPlr=Players.First; pPlr; pPlr=pPlr->Next) if (pPlr->Number == iPlayer || iPlayer==NO_OWNER) @@ -1665,7 +1665,7 @@ void C4Game::DrawCursors(C4TargetFacet &cgo, int32_t iPlayer) } } } - } + } void C4Game::Ticks() { @@ -1685,25 +1685,25 @@ void C4Game::Ticks() if (FrameCounter % FrameSkip) DoSkipFrame = true; // Control Control.Ticks(); - // Full speed + // Full speed if(GameGo) Application.NextTick(); // short-circuit the timer // statistics if (pNetworkStatistics) pNetworkStatistics->ExecuteFrame(); - } + } bool C4Game::Compile(const char *szSource) { - if(!szSource) return true; + if(!szSource) return true; // C4Game is not defaulted on compilation. // Loading of runtime data overrides only certain values. // Doesn't compile players; those will be done later - CompileSettings Settings(false, false, true); - if(!CompileFromBuf_LogWarn( - mkParAdapt(*this, Settings), - StdStrBuf(szSource), + CompileSettings Settings(false, false, true); + if(!CompileFromBuf_LogWarn( + mkParAdapt(*this, Settings), + StdStrBuf(szSource), C4CFN_Game)) - return false; - return true; + return false; + return true; } void C4Game::CompileFunc(StdCompiler *pComp, CompileSettings comp) @@ -1733,7 +1733,7 @@ void C4Game::CompileFunc(StdCompiler *pComp, CompileSettings comp) pComp->Value(mkNamingAdapt(NextMission, "NextMission", StdCopyStrBuf())); pComp->Value(mkNamingAdapt(NextMissionText, "NextMissionText", StdCopyStrBuf())); pComp->Value(mkNamingAdapt(NextMissionDesc, "NextMissionDesc", StdCopyStrBuf())); - pComp->NameEnd(); + pComp->NameEnd(); } pComp->Value(mkNamingAdapt(mkInsertAdapt(Script, ScriptEngine), "Script")); @@ -1773,7 +1773,7 @@ void SetClientPrefix(char *szFilename, const char *szClient); bool C4Game::Decompile(StdStrBuf &rBuf, bool fSaveSection, bool fSaveExact) { // Decompile (without players for scenario sections) - rBuf.Take(DecompileToBuf(mkParAdapt(*this, CompileSettings(fSaveSection, !fSaveSection && fSaveExact, fSaveExact)))); + rBuf.Take(DecompileToBuf(mkParAdapt(*this, CompileSettings(fSaveSection, !fSaveSection && fSaveExact, fSaveExact)))); return true; } @@ -1784,7 +1784,7 @@ bool C4Game::CompileRuntimeData(C4ComponentHost &rGameData) // Music System: Set play list Application.MusicSystem.SetPlayList(PlayList.getData()); // Success - return true; + return true; } bool C4Game::SaveData(C4Group &hGroup, bool fSaveSection, bool fInitial, bool fSaveExact) @@ -1800,7 +1800,7 @@ bool C4Game::SaveData(C4Group &hGroup, bool fSaveSection, bool fInitial, bool fS // Decompile StdStrBuf Buf; if(!Decompile(Buf,fSaveSection,fSaveExact)) - return false; + return false; // Denumerate pointers, if game is in denumerated state if (PointersDenumerated) @@ -1938,7 +1938,7 @@ bool C4Game::DoKeyboardInput(C4KeyCode vk_code, C4KeyEventType eEventType, bool // unprocessed key return false; - } + } bool C4Game::CanQuickSave() { @@ -2006,10 +2006,10 @@ bool C4Game::QuickSave(const char *strFilename, const char *strTitle, bool fForc } bool LandscapeFree(int32_t x, int32_t y) - { + { if (!Inside(x,0,GBackWdt-1) || !Inside(y,0,GBackHgt-1)) return false; - return !DensitySolid(GBackDensity(x,y)); - } + return !DensitySolid(GBackDensity(x,y)); + } static void FileMonitorCallback(const char * file, const char * extrafile) { @@ -2017,27 +2017,27 @@ static void FileMonitorCallback(const char * file, const char * extrafile) } bool C4Game::ReloadFile(const char *szFile) - { - // not in network - if(::Network.isEnabled()) return false; - const char *szRelativePath = Config.AtRelativePath(szFile); - // a definition? or part of a definition? - C4Def *pDef; - if((pDef = ::Definitions.GetByPath(szRelativePath))) - return ReloadDef(pDef->id); - // script? - if(ScriptEngine.ReloadScript(szRelativePath, &::Definitions)) - { - return true; - } - return true; - } + { + // not in network + if(::Network.isEnabled()) return false; + const char *szRelativePath = Config.AtRelativePath(szFile); + // a definition? or part of a definition? + C4Def *pDef; + if((pDef = ::Definitions.GetByPath(szRelativePath))) + return ReloadDef(pDef->id); + // script? + if(ScriptEngine.ReloadScript(szRelativePath, &::Definitions)) + { + return true; + } + return true; + } bool C4Game::ReloadDef(C4ID id) { bool fSucc; - // not in network - if(::Network.isEnabled()) return false; + // not in network + if(::Network.isEnabled()) return false; // syncronize (close menus with dead surfaces, etc.) // no need to sync back player files, though Synchronize(false); @@ -2082,8 +2082,8 @@ bool C4Game::ReloadDef(C4ID id) bool C4Game::ReloadParticle(const char *szName) { - // not in network - if(::Network.isEnabled()) return false; + // not in network + if(::Network.isEnabled()) return false; // safety if (!szName) return false; // get particle def @@ -2185,13 +2185,13 @@ bool C4Game::InitGame(C4Group &hGroup, bool fLoadSection, bool fLoadSky) // Landscape Log(LoadResStr("IDS_PRC_LANDSCAPE")); bool fLandscapeLoaded = false; - if (!Landscape.Init(hGroup, fLoadSection, fLoadSky, fLandscapeLoaded, !!C4S.Head.SaveGame)) + if (!Landscape.Init(hGroup, fLoadSection, fLoadSky, fLandscapeLoaded, !!C4S.Head.SaveGame)) { LogFatal(LoadResStr("IDS_ERR_GBACK")); return false; } SetInitProgress(88); // the savegame flag is set if runtime data is present, in which case this is to be used // except for scenario sections if (fLandscapeLoaded && (!C4S.Head.SaveGame || fLoadSection)) - Landscape.ScenarioInit(); + Landscape.ScenarioInit(); // clear old landscape data if (fLoadSection && fLandscapeLoaded) { PXS.Clear(); MassMover.Clear(); } SetInitProgress(89); @@ -2250,8 +2250,8 @@ bool C4Game::InitGame(C4Group &hGroup, bool fLoadSection, bool fLoadSky) } SetInitProgress(94); - // Weather - if (fLandscapeLoaded) Weather.Init(!C4S.Head.SaveGame); + // Weather + if (fLandscapeLoaded) Weather.Init(!C4S.Head.SaveGame); SetInitProgress(95); // FoW-color @@ -2261,7 +2261,7 @@ bool C4Game::InitGame(C4Group &hGroup, bool fLoadSection, bool fLoadSky) if (!fLoadSection) ScriptEngine.DenumerateVariablePointers(); if (!fLoadSection && pGlobalEffects) pGlobalEffects->DenumeratePointers(); - // Check object enumeration + // Check object enumeration if (!CheckObjectEnumeration()) return false; // Okay; everything in denumerated state from now on @@ -2391,7 +2391,7 @@ bool C4Game::InitPlayers() { LogFatal(LoadResStr("IDS_ERR_NOPLRFILERECR")); return false; } // recreate the files if (!LocalRestorePlayerInfos.RecreatePlayers()) - { LogFatal(LoadResStr("IDS_ERR_NOPLRNETRECR")); return false; } + { LogFatal(LoadResStr("IDS_ERR_NOPLRNETRECR")); return false; } } else if (RestorePlayerInfos.GetActivePlayerCount(true)) { @@ -2462,16 +2462,16 @@ bool C4Game::InitPlayers() bool C4Game::InitControl() { - // update random seed + // update random seed if(C4S.Head.NetworkGame || C4S.Head.Replay) - { + { RandomSeed = C4S.Head.RandomSeed; StartupPlayerCount = C4S.Head.StartupPlayerCount; - } + } // Randomize FixRandom(RandomSeed); - // Replay? + // Replay? if (C4S.Head.Replay) { // no joins @@ -2484,7 +2484,7 @@ bool C4Game::InitControl() } else if(Network.isEnabled()) { - // set startup player count + // set startup player count if (!C4S.Head.SaveGame && !C4S.Head.Replay) StartupPlayerCount = PlayerInfos.GetPlayerCount(); // initialize @@ -2522,37 +2522,37 @@ bool C4Game::InitControl() } int32_t ListExpandValids(C4IDList &rlist, - C4ID *idlist, int32_t maxidlist) - { - int32_t cnt,cnt2,ccount,cpos; - for (cpos=0,cnt=0; rlist.GetID(cnt); cnt++) - if (C4Id2Def(rlist.GetID(cnt,&ccount))) - for (cnt2=0; cnt2Placement) { @@ -2647,52 +2647,52 @@ C4Object* C4Game::PlaceAnimal(C4ID idAnimal) } // Create object return CreateObject(idAnimal,NULL,NO_OWNER,iX,iY); - } + } void C4Game::InitInEarth() - { - const int32_t maxvid=100; - int32_t cnt,vidnum; - C4ID vidlist[maxvid]; - // Amount - int32_t amt=(GBackWdt*GBackHgt/5000)*C4S.Landscape.InEarthLevel.Evaluate()/100; - // List all valid IDs from C4S - vidnum=ListExpandValids(C4S.Landscape.InEarth,vidlist,maxvid); - // Place - if (vidnum>0) - for (cnt=0; cnt0) + for (cnt=0; cnt0) - for (cnt=0; cnt0) + for (cnt=0; cntNext) - if(!pPlayer->Eliminated) - pPlayer->EvaluateLeague(false, true); + // Flag all surviving players as winners + for(C4Player *pPlayer = Players.First; pPlayer; pPlayer = pPlayer->Next) + if(!pPlayer->Eliminated) + pPlayer->EvaluateLeague(false, true); return true; } @@ -3301,7 +3301,7 @@ void C4Game::Synchronize(bool fSavePlayerFiles) C4Object* C4Game::FindObjectByCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int32_t iTy, C4Object *pTarget2, C4Object *pFindNext) { - C4Object *cObj; C4ObjectLink *clnk; + C4Object *cObj; C4ObjectLink *clnk; for (clnk=Objects.First; clnk && (cObj=clnk->Obj); clnk=clnk->Next) { // find next @@ -3334,10 +3334,10 @@ bool C4Game::InitNetworkFromAddress(const char *szAddress) !RefClient.SetServer(szAddress) || !RefClient.QueryReferences()) { LogFatal(FormatString(strRefQueryFailed.getData(), RefClient.GetError()).getData()); return false; } - // We have to wait for the answer - StdStrBuf Message = FormatString(LoadResStr("IDS_NET_REFQUERY_QUERYMSG"), szAddress); - Log(Message.getData()); - // Set up wait dialog + // We have to wait for the answer + StdStrBuf Message = FormatString(LoadResStr("IDS_NET_REFQUERY_QUERYMSG"), szAddress); + Log(Message.getData()); + // Set up wait dialog C4GUI::MessageDialog *pDlg = NULL; if(::pGUI && !Console.Active) { @@ -3348,20 +3348,20 @@ bool C4Game::InitNetworkFromAddress(const char *szAddress) } // Wait for response while(RefClient.isBusy()) - { - // Execute GUI + { + // Execute GUI if(!Application.ScheduleProcs(100) || - (pDlg && pDlg->IsAborted())) - { - if(::pGUI && pDlg) delete pDlg; + (pDlg && pDlg->IsAborted())) + { + if(::pGUI && pDlg) delete pDlg; return false; - } - // Check if reference is received - if(!RefClient.Execute(0)) - break; - } - // Close dialog - if(::pGUI && pDlg) delete pDlg; + } + // Check if reference is received + if(!RefClient.Execute(0)) + break; + } + // Close dialog + if(::pGUI && pDlg) delete pDlg; // Error? if(!RefClient.isSuccess()) { LogFatal(FormatString(strRefQueryFailed.getData(), RefClient.GetError()).getData()); return false; } @@ -3410,8 +3410,8 @@ bool C4Game::InitNetworkHost() { // Clear client list if(!C4S.Head.Replay) - Clients.Init(); - return true; + Clients.Init(); + return true; } // network not active? if(C4S.Head.NetworkGame) @@ -3423,7 +3423,7 @@ bool C4Game::InitNetworkHost() if(!Clients.Init()) return false; // init network as host - if(!Network.InitHost(fLobby)) return false; + if(!Network.InitHost(fLobby)) return false; // init control if(!Control.InitNetwork(Clients.getLocal())) return false; // init local player info list @@ -3448,8 +3448,8 @@ bool C4Game::CheckObjectEnumeration() { // Check valid & maximum number & duplicate numbers int32_t iMax = 0; - C4Object *cObj; C4ObjectLink *clnk; - C4Object *cObj2; C4ObjectLink *clnk2; + C4Object *cObj; C4ObjectLink *clnk; + C4Object *cObj2; C4ObjectLink *clnk2; clnk=Objects.First; if (!clnk) clnk=Objects.InactiveObjects.First; while (clnk) { @@ -3530,34 +3530,34 @@ void C4Game::InitValueOverloads() void C4Game::InitEnvironment() { - // Place environment objects - int32_t cnt,cnt2; - C4ID idType; int32_t iCount; - for (cnt=0; (idType=C4S.Environment.Objects.GetID(cnt,&iCount)); cnt++) - for (cnt2=0; cnt2(iCount,1); cnt2++) - CreateObject(idType,NULL); + // Place rule objects + int32_t cnt,cnt2; + C4ID idType; int32_t iCount; + for (cnt=0; (idType=Parameters.Rules.GetID(cnt,&iCount)); cnt++) + for (cnt2=0; cnt2(iCount,1); cnt2++) + CreateObject(idType,NULL); // Update rule flags UpdateRules(); } void C4Game::InitGoals() { - // Place goal objects - int32_t cnt,cnt2; - C4ID idType; int32_t iCount; - for (cnt=0; (idType=Parameters.Goals.GetID(cnt,&iCount)); cnt++) - for (cnt2=0; cnt2FindEntry(C4CFN_Sky ".*"); // re-init game in new section @@ -3764,7 +3764,7 @@ bool C4Game::ActivateMenu(const char *szCommand) // forward to primary player C4Player *pPlr=::Players.GetLocalByIndex(0); if (!pPlr) return false; - pPlr->Menu.ActivateCommand(pPlr->Number, szCommand); + pPlr->Menu.ActivateCommand(pPlr->Number, szCommand); return true; } diff --git a/src/C4Game.h b/src/C4Game.h index bce1c3702..86134685f 100644 --- a/src/C4Game.h +++ b/src/C4Game.h @@ -169,7 +169,7 @@ class C4Game bool Init(); bool PreInit(); void ParseCommandLine(const char *szCmdLine); - bool Execute(); + bool Execute(); class C4Player *JoinPlayer(const char *szFilename, int32_t iAtClient, const char *szAtClientName, C4PlayerInfo *pInfo); bool DoGameOver(); bool CanQuickSave(); @@ -197,18 +197,18 @@ class C4Game bool ReloadDef(C4ID id); bool ReloadParticle(const char *szName); // Object functions - void ClearPointers(C4PropList *cobj); - C4Object *CreateObject(C4PropList * type, C4Object *pCreator, int32_t owner=NO_OWNER, - int32_t x=50, int32_t y=50, int32_t r=0, - FIXED xdir=Fix0, FIXED ydir=Fix0, FIXED rdir=Fix0, int32_t iController=NO_OWNER); + void ClearPointers(C4PropList *cobj); + C4Object *CreateObject(C4PropList * type, C4Object *pCreator, int32_t owner=NO_OWNER, + int32_t x=50, int32_t y=50, int32_t r=0, + FIXED xdir=Fix0, FIXED ydir=Fix0, FIXED rdir=Fix0, int32_t iController=NO_OWNER); C4Object *CreateObject(C4ID type, C4Object *pCreator, int32_t owner=NO_OWNER, int32_t x=50, int32_t y=50, int32_t r=0, FIXED xdir=Fix0, FIXED ydir=Fix0, FIXED rdir=Fix0, int32_t iController=NO_OWNER); - C4Object *CreateObjectConstruction(C4PropList * type, + C4Object *CreateObjectConstruction(C4PropList * type, C4Object *pCreator, int32_t owner, int32_t ctx=0, int32_t bty=0, - int32_t con=1, bool terrain=false); + int32_t con=1, bool terrain=false); C4Object *CreateInfoObject(C4ObjectInfo *cinf, int32_t owner, int32_t tx=50, int32_t ty=50); void BlastObjects(int32_t tx, int32_t ty, int32_t level, C4Object *inobj, int32_t iCausedBy, C4Object *pByObj); @@ -228,7 +228,7 @@ class C4Game float iX, float iY, DWORD category, float gui_x, float gui_y); - /* int32_t ObjectCount(C4ID id, + /* int32_t ObjectCount(C4ID id, int32_t x=0, int32_t y=0, int32_t wdt=0, int32_t hgt=0, DWORD ocf=OCF_All, const char *szAction=NULL, C4Object *pActionTarget=NULL, @@ -262,9 +262,9 @@ class C4Game void InitValueOverloads(); void InitEnvironment(); void UpdateRules(); - void CloseScenario(); - void DeleteObjects(bool fDeleteInactive); - void ExecObjects(); + void CloseScenario(); + void DeleteObjects(bool fDeleteInactive); + void ExecObjects(); void Ticks(); const char *FoldersWithLocalsDefs(const char *szPath); bool CheckObjectEnumeration(); @@ -287,9 +287,9 @@ class C4Game bool LinkScriptEngine(); bool InitPlayers(); bool InitRecord(); - bool OpenScenario(); - bool InitDefs(); - bool InitMaterialTexture(); + bool OpenScenario(); + bool InitDefs(); + bool InitMaterialTexture(); bool GameOverCheck(); bool PlaceInEarth(C4ID id); bool Compile(const char *szSource); @@ -302,14 +302,14 @@ class C4Game bool StoreParticipantPlayers(); bool RecreatePlayerFiles(); - // Object function internals - C4Object *NewObject( C4PropList *ndef, C4Object *pCreator, - int32_t owner, C4ObjectInfo *info, - int32_t tx, int32_t ty, int32_t tr, - FIXED xdir, FIXED ydir, FIXED rdir, - int32_t con, int32_t iController); - void ClearObjectPtrs(C4Object *tptr); - void ObjectRemovalCheck(); + // Object function internals + C4Object *NewObject( C4PropList *ndef, C4Object *pCreator, + int32_t owner, C4ObjectInfo *info, + int32_t tx, int32_t ty, int32_t tr, + FIXED xdir, FIXED ydir, FIXED rdir, + int32_t con, int32_t iController); + void ClearObjectPtrs(C4Object *tptr); + void ObjectRemovalCheck(); bool ToggleDebugMode(); // dbg modeon/off if allowed bool ActivateMenu(const char *szCommand); // exec given menu command for first local player @@ -317,7 +317,7 @@ class C4Game public: bool ToggleChart(); // chart dlg on/off void SetMusicLevel(int32_t iToLvl); // change game music volume; multiplied by config volume for real volume - }; + }; const int32_t C4RULE_StructuresNeedEnergy = 1, diff --git a/src/C4GraphicsSystem.cpp b/src/C4GraphicsSystem.cpp index 20e53102c..73d84f452 100644 --- a/src/C4GraphicsSystem.cpp +++ b/src/C4GraphicsSystem.cpp @@ -804,12 +804,12 @@ int32_t C4GraphicsSystem::GetAudibility(int32_t iX, int32_t iY, int32_t *iPan, i // Accumulate audibility by viewports int32_t iAudible=0; *iPan = 0; for (C4Viewport *cvp=FirstViewport; cvp; cvp=cvp->Next) - { + { iAudible = Max( iAudible, BoundBy(100-100*Distance(cvp->ViewX+cvp->ViewWdt/2,cvp->ViewY+cvp->ViewHgt/2,iX,iY)/C4AudibilityRadius,0,100) ); - *iPan += (iX-(cvp->ViewX+cvp->ViewWdt/2)) / 5; - } - *iPan = BoundBy(*iPan, -100, 100); + *iPan += (iX-(cvp->ViewX+cvp->ViewWdt/2)) / 5; + } + *iPan = BoundBy(*iPan, -100, 100); return iAudible; } diff --git a/src/C4Version.h b/src/C4Version.h index 5988360dd..10e1bad81 100644 --- a/src/C4Version.h +++ b/src/C4Version.h @@ -49,9 +49,9 @@ // Build Options #ifdef _DEBUG - #define C4BUILDDEBUG " dbg" + #define C4BUILDDEBUG " dbg" #else - #define C4BUILDDEBUG + #define C4BUILDDEBUG #endif #define C4BUILDOPT C4BUILDDEBUG diff --git a/src/C4WinMain.cpp b/src/C4WinMain.cpp index e6c2493d2..e0bfc2b45 100644 --- a/src/C4WinMain.cpp +++ b/src/C4WinMain.cpp @@ -59,9 +59,9 @@ int GenerateDump(EXCEPTION_POINTERS* pExceptionPointers) // Write dump MINIDUMP_EXCEPTION_INFORMATION ExpParam; - ExpParam.ThreadId = GetCurrentThreadId(); - ExpParam.ExceptionPointers = pExceptionPointers; - ExpParam.ClientPointers = true; + ExpParam.ThreadId = GetCurrentThreadId(); + ExpParam.ExceptionPointers = pExceptionPointers; + ExpParam.ClientPointers = true; MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file, MiniDumpNormal, &ExpParam, NULL, NULL); @@ -76,12 +76,12 @@ int GenerateDump(EXCEPTION_POINTERS* pExceptionPointers) int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrevInstance, - LPSTR lpszCmdParam, + LPSTR lpszCmdParam, int nCmdShow) { #if defined(_DEBUG) && defined(_MSC_VER) // enable debugheap! - _CrtSetDbgFlag( _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); + _CrtSetDbgFlag( _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif #ifdef GENERATE_MINI_DUMP diff --git a/src/c4group/C4ComponentHost.cpp b/src/c4group/C4ComponentHost.cpp index e37695729..0921231c3 100644 --- a/src/c4group/C4ComponentHost.cpp +++ b/src/c4group/C4ComponentHost.cpp @@ -201,8 +201,8 @@ bool C4ComponentHost::Load(const char *szName, } // Truncate any additional segments from stored filename SReplaceChar(Filename, '|', 0); - // skip full path (unknown) - FilePath[0] = 0; + // skip full path (unknown) + FilePath[0] = 0; // Not loaded return false; } diff --git a/src/c4group/C4Components.h b/src/c4group/C4Components.h index 494273929..bcc4037e1 100644 --- a/src/c4group/C4Components.h +++ b/src/c4group/C4Components.h @@ -185,9 +185,9 @@ #define C4FLS_Folder "Folder.txt|Title*.txt|Info.txt|Desc*.rtf|Title.png|Title.bmp|Icon.png|Icon.bmp|Author.txt|Version.txt|*.c4s|Loader*.bmp|Loader*.png|Loader*.jpeg|Loader*.jpg|FolderMap.txt|FolderMap.png" #define C4FLS_Material "TexMap.txt|*.bmp|*.png|*.c4m" #define C4FLS_Graphics "Loader*.bmp|Loader*.png|Loader*.jpeg|Loader*.jpg|FontEndeavour12.png|FontEndeavour24.png|FontEndeavour16.png|FontEndeavour10.png|Font*.png"\ - "|*.pal|Control.png|Fire.png|Background.png|Flag.png|Crew.png|Score.png|Wealth.png|Player.png|Rank.png|Entry.png|Captain.png|Cursor.png|CursorSmall.png|CursorMedium.png|CursorLarge.png|SelectMark.png|MenuSymbol.png|Menu.png|Logo.png|Construction.png|Energy.png|Magic.png|Options.png|UpperBoard.png|Arrow.png|Exit.png|Hand.png|Gamepad.png|Build.png|Liquid.png"\ + "|*.pal|Control.png|Fire.png|Background.png|Flag.png|Crew.png|Score.png|Wealth.png|Player.png|Rank.png|Entry.png|Captain.png|Cursor.png|CursorSmall.png|CursorMedium.png|CursorLarge.png|SelectMark.png|MenuSymbol.png|Menu.png|Logo.png|Construction.png|Energy.png|Magic.png|Options.png|UpperBoard.png|Arrow.png|Exit.png|Hand.png|Gamepad.png|Build.png|Liquid.png"\ "|GUICaption.png|GUIButton.png|GUIButtonDown.png|GUIButtonHighlight.png|GUIIcons.png|GUIIcons2.png|GUIScroll.png|GUIContext.png|GUISubmenu.png|GUICheckBox.png|GUIBigArrows.png|GUIProgress.png"\ - "|StartupScenSelBG.*|StartupPlrSelBG.*|StartupPlrPropBG.*|StartupNetworkBG.*|StartupAboutBG.*|StartupBigButton.png|StartupBigButtonDown.png|StartupBookScroll.png|StartupContext.png|StartupScenSelIcons.png|StartupScenSelTitleOv.png|StartupDlgPaper.png|StartupOptionIcons.png|StartupTabClip.png|StartupNetGetRef.png" + "|StartupScenSelBG.*|StartupPlrSelBG.*|StartupPlrPropBG.*|StartupNetworkBG.*|StartupAboutBG.*|StartupBigButton.png|StartupBigButtonDown.png|StartupBookScroll.png|StartupContext.png|StartupScenSelIcons.png|StartupScenSelTitleOv.png|StartupDlgPaper.png|StartupOptionIcons.png|StartupTabClip.png|StartupNetGetRef.png" #define C4FLS_Objects "Names*.txt|Desc*.txt|*.c4d" #define C4FLS_Mouse "*.txt|*.rtf|Title.bmp|Title.png|Icon.bmp|Tutorial01.c4s|Tutorial02.c4s|Tutorial03.c4s|Objects.c4d" #define C4FLS_Keyboard "*.txt|*.rtf|Title.bmp|Title.png|Icon.bmp|Tutorial01.c4s|Tutorial02.c4s|Tutorial03.c4s|Tutorial04.c4s|Tutorial05.c4s|Tutorial06.c4s|Tutorial07.c4s|Tutorial08.c4s|Tutorial09.c4s|Tutorial10.c4s" diff --git a/src/c4group/C4Group.cpp b/src/c4group/C4Group.cpp index 8d22f0503..897bba856 100644 --- a/src/c4group/C4Group.cpp +++ b/src/c4group/C4Group.cpp @@ -367,41 +367,41 @@ bool C4Group_UnpackDirectory(const char *szFilename) return false; // Open group - C4Group hGroup; - if (!hGroup.Open(szFilename)) return false; + C4Group hGroup; + if (!hGroup.Open(szFilename)) return false; // Process message - if (C4Group_ProcessCallback) + if (C4Group_ProcessCallback) C4Group_ProcessCallback(szFilename,0); - // Create target directory + // Create target directory char szFoldername[_MAX_PATH+1]; - SCopy(szFilename,szFoldername,_MAX_PATH); - MakeTempFilename(szFoldername); - if (!CreatePath(szFoldername)) { hGroup.Close(); return false; } + SCopy(szFilename,szFoldername,_MAX_PATH); + MakeTempFilename(szFoldername); + if (!CreatePath(szFoldername)) { hGroup.Close(); return false; } - // Extract files to folder + // Extract files to folder if (!hGroup.Extract("*",szFoldername)) { hGroup.Close(); return false; } // Close group - hGroup.Close(); + hGroup.Close(); - // Rename group file + // Rename group file char szTempFilename[_MAX_PATH+1]; - SCopy(szFilename,szTempFilename,_MAX_PATH); - MakeTempFilename(szTempFilename); + SCopy(szFilename,szTempFilename,_MAX_PATH); + MakeTempFilename(szTempFilename); if (!RenameFile(szFilename, szTempFilename)) return false; - // Rename target directory - if (!RenameFile(szFoldername,szFilename)) return false; + // Rename target directory + if (!RenameFile(szFoldername,szFilename)) return false; // Delete renamed group file - return EraseItem(szTempFilename); - } + return EraseItem(szTempFilename); + } bool C4Group_ExplodeDirectory(const char *szFilename) { - // Ignore + // Ignore if (C4Group_TestIgnore(szFilename)) return true; // Unpack this directory @@ -474,7 +474,7 @@ bool C4Group_GetFileCRC(const char *szFilename, uint32_t *pCRC32) // okay *pCRC32 = iCRC32; return true; - } + } bool C4Group_GetFileSHA1(const char *szFilename, BYTE *pSHA1) { @@ -514,7 +514,7 @@ bool C4Group_GetFileSHA1(const char *szFilename, BYTE *pSHA1) // finish calculation SHA1_Final(pSHA1, &ctx); return true; - } + } void MemScramble(BYTE *bypBuffer, int iSize) { @@ -539,26 +539,26 @@ C4GroupHeader::C4GroupHeader() } void C4GroupHeader::Init() - { - SCopy(C4GroupFileID,id,sizeof(id)-1); - Ver1=C4GroupFileVer1; Ver2=C4GroupFileVer2; - Entries=0; - SCopy("New C4Group",Maker,C4GroupMaxMaker); - Password[0]=0; - } + { + SCopy(C4GroupFileID,id,sizeof(id)-1); + Ver1=C4GroupFileVer1; Ver2=C4GroupFileVer2; + Entries=0; + SCopy("New C4Group",Maker,C4GroupMaxMaker); + Password[0]=0; + } C4GroupEntryCore::C4GroupEntryCore() - { - ZeroMem(this,sizeof(C4GroupEntryCore)); - } + { + ZeroMem(this,sizeof(C4GroupEntryCore)); + } C4GroupEntry::C4GroupEntry() - { - ZeroMem(this,sizeof(C4GroupEntry)); - } + { + ZeroMem(this,sizeof(C4GroupEntry)); + } C4GroupEntry::~C4GroupEntry() - { + { if (HoldBuffer) if (bpMemBuf) { @@ -567,7 +567,7 @@ C4GroupEntry::~C4GroupEntry() else delete [] bpMemBuf; } - } + } #ifdef WIN32 #define stat _stat @@ -595,40 +595,40 @@ void C4GroupEntry::Set(const DirectoryIterator &iter, const char * path) } C4Group::C4Group() - { - Init(); - StdOutput=false; + { + Init(); + StdOutput=false; fnProcessCallback=NULL; MadeOriginal=false; NoSort=false; - } + } void C4Group::Init() - { - // General - Status=GRPF_Inactive; - FileName[0]=0; - // Child status - Mother=NULL; - ExclusiveChild=false; - // File only - FilePtr=0; - EntryOffset=0; - Modified=false; - Head.Init(); - FirstEntry=NULL; - SearchPtr=NULL; - // Folder only - //hFdt=-1; - FolderSearch.Reset(); - // Error status - SCopy("No Error",ErrorString,C4GroupMaxError); - } + { + // General + Status=GRPF_Inactive; + FileName[0]=0; + // Child status + Mother=NULL; + ExclusiveChild=false; + // File only + FilePtr=0; + EntryOffset=0; + Modified=false; + Head.Init(); + FirstEntry=NULL; + SearchPtr=NULL; + // Folder only + //hFdt=-1; + FolderSearch.Reset(); + // Error status + SCopy("No Error",ErrorString,C4GroupMaxError); + } C4Group::~C4Group() - { - Clear(); - } + { + Clear(); + } bool C4Group::Error(const char *szStatus) { @@ -637,60 +637,60 @@ bool C4Group::Error(const char *szStatus) } const char *C4Group::GetError() - { - return ErrorString; - } + { + return ErrorString; + } void C4Group::SetStdOutput(bool fStatus) - { - StdOutput=fStatus; - } + { + StdOutput=fStatus; + } bool C4Group::Open(const char *szGroupName, bool fCreate) - { - if (!szGroupName) return Error("Open: Null filename"); - if (!szGroupName[0]) return Error("Open: Empty filename"); + { + if (!szGroupName) return Error("Open: Null filename"); + if (!szGroupName[0]) return Error("Open: Empty filename"); char szGroupNameN[_MAX_FNAME]; SCopy(szGroupName,szGroupNameN,_MAX_FNAME); // Convert to native path SReplaceChar(szGroupNameN, '\\', DirectorySeparator); - // Real reference + // Real reference if (FileExists(szGroupNameN)) - { - // Init - Init(); - // Open group or folder + { + // Init + Init(); + // Open group or folder return OpenReal(szGroupNameN); - } + } - // If requested, try creating a new group file - if (fCreate) - { - CStdFile temp; + // If requested, try creating a new group file + if (fCreate) + { + CStdFile temp; if (temp.Create(szGroupNameN,false)) - { - // Temporary file has been created - temp.Close(); - // Init - Init(); - Status=GRPF_File; Modified=true; + { + // Temporary file has been created + temp.Close(); + // Init + Init(); + Status=GRPF_File; Modified=true; SCopy(szGroupNameN,FileName,_MAX_FNAME); - return true; - } - } + return true; + } + } - // While not a real reference (child group), trace back to mother group or folder. + // While not a real reference (child group), trace back to mother group or folder. // Open mother and child in exclusive mode. - char szRealGroup[_MAX_FNAME]; + char szRealGroup[_MAX_FNAME]; SCopy(szGroupNameN,szRealGroup,_MAX_FNAME); - do - { if (!TruncatePath(szRealGroup)) return Error("Open: File not found"); } - while (!FileExists(szRealGroup)); + do + { if (!TruncatePath(szRealGroup)) return Error("Open: File not found"); } + while (!FileExists(szRealGroup)); - // Open mother and child in exclusive mode - C4Group *pMother; + // Open mother and child in exclusive mode + C4Group *pMother; if (!(pMother=new C4Group)) return Error("Open: mem"); pMother->SetStdOutput(StdOutput); @@ -702,7 +702,7 @@ bool C4Group::Open(const char *szGroupName, bool fCreate) // Success return true; - } + } bool C4Group::OpenReal(const char *szFilename) { @@ -713,7 +713,7 @@ bool C4Group::OpenReal(const char *szFilename) // Folder if (DirectoryExists(FileName)) - { + { // Ignore if (C4Group_TestIgnore(szFilename)) return false; @@ -723,7 +723,7 @@ bool C4Group::OpenReal(const char *szFilename) ResetSearch(); // Success return true; - } + } // File: Try reading header and entries if (OpenRealGrpFile()) @@ -739,24 +739,24 @@ bool C4Group::OpenReal(const char *szFilename) } bool C4Group::OpenRealGrpFile() - { - int cnt,file_entries; - C4GroupEntryCore corebuf; + { + int cnt,file_entries; + C4GroupEntryCore corebuf; - // Open StdFile - if (!StdFile.Open(FileName,true)) return Error("OpenRealGrpFile: Cannot open standard file"); + // Open StdFile + if (!StdFile.Open(FileName,true)) return Error("OpenRealGrpFile: Cannot open standard file"); - // Read header - if (!StdFile.Read((BYTE*)&Head,sizeof(C4GroupHeader))) return Error("OpenRealGrpFile: Error reading header"); + // Read header + if (!StdFile.Read((BYTE*)&Head,sizeof(C4GroupHeader))) return Error("OpenRealGrpFile: Error reading header"); MemScramble((BYTE*)&Head,sizeof(C4GroupHeader)); - EntryOffset+=sizeof(C4GroupHeader); + EntryOffset+=sizeof(C4GroupHeader); - // Check Header - if (!SEqual(Head.id,C4GroupFileID) - || (Head.Ver1!=C4GroupFileVer1) || (Head.Ver2>C4GroupFileVer2)) - return Error("OpenRealGrpFile: Invalid header"); + // Check Header + if (!SEqual(Head.id,C4GroupFileID) + || (Head.Ver1!=C4GroupFileVer1) || (Head.Ver2>C4GroupFileVer2)) + return Error("OpenRealGrpFile: Invalid header"); - // Read Entries + // Read Entries file_entries=Head.Entries; Head.Entries=0; // Reset, will be recounted by AddEntry for (cnt=0; cntStatus=C4GRES_Deleted; Head.Entries--; } + // Delete existing entries of same name + centry=GetEntry(GetFilename(entryname ? entryname : fname)); + if (centry) { centry->Status=C4GRES_Deleted; Head.Entries--; } - // Allocate memory for new entry - if (!(nentry=new C4GroupEntry)) return false; //...theoretically, delete Hold buffer here + // Allocate memory for new entry + if (!(nentry=new C4GroupEntry)) return false; //...theoretically, delete Hold buffer here - // Find end of list - for (lentry=FirstEntry; lentry && lentry->Next; lentry=lentry->Next) {} + // Find end of list + for (lentry=FirstEntry; lentry && lentry->Next; lentry=lentry->Next) {} - // Init entry core data - if (entryname) SCopy(entryname,nentry->FileName,_MAX_FNAME); - else SCopy(GetFilename(fname),nentry->FileName,_MAX_FNAME); - nentry->Size=size; - nentry->Time = time + C4Group_AssumeTimeOffset; - nentry->ChildGroup=childgroup; - nentry->Offset=0; + // Init entry core data + if (entryname) SCopy(entryname,nentry->FileName,_MAX_FNAME); + else SCopy(GetFilename(fname),nentry->FileName,_MAX_FNAME); + nentry->Size=size; + nentry->Time = time + C4Group_AssumeTimeOffset; + nentry->ChildGroup=childgroup; + nentry->Offset=0; nentry->HasCRC=cCRC; nentry->CRC=iCRC; nentry->Executable=fExecutable; nentry->DeleteOnDisk=fDeleteOnDisk; nentry->HoldBuffer=fHoldBuffer; nentry->BufferIsStdbuf=fBufferIsStdbuf; - if (lentry) nentry->Offset=lentry->Offset+lentry->Size; + if (lentry) nentry->Offset=lentry->Offset+lentry->Size; - // Init list entry data - SCopy(fname,nentry->DiskPath,_MAX_FNAME); - nentry->Status=status; - nentry->bpMemBuf=membuf; - nentry->Next=NULL; + // Init list entry data + SCopy(fname,nentry->DiskPath,_MAX_FNAME); + nentry->Status=status; + nentry->bpMemBuf=membuf; + nentry->Next=NULL; nentry->NoSort = NoSort; - // Append entry to list - if (lentry) lentry->Next=nentry; - else FirstEntry=nentry; + // Append entry to list + if (lentry) lentry->Next=nentry; + else FirstEntry=nentry; - // Increase virtual file count of group - Head.Entries++; + // Increase virtual file count of group + Head.Entries++; - return true; - } + return true; + } C4GroupEntry* C4Group::GetEntry(const char *szName) - { - if (Status==GRPF_Folder) return NULL; - C4GroupEntry *centry; - for (centry=FirstEntry; centry; centry=centry->Next) - if (centry->Status!=C4GRES_Deleted) - if (WildcardMatch(szName,centry->FileName)) - return centry; - return NULL; - } + { + if (Status==GRPF_Folder) return NULL; + C4GroupEntry *centry; + for (centry=FirstEntry; centry; centry=centry->Next) + if (centry->Status!=C4GRES_Deleted) + if (WildcardMatch(szName,centry->FileName)) + return centry; + return NULL; + } bool C4Group::Close() - { - C4GroupEntry *centry; - bool fRewrite=false; + { + C4GroupEntry *centry; + bool fRewrite=false; - if (Status==GRPF_Inactive) return false; + if (Status==GRPF_Inactive) return false; - // Folder: just close - if (Status==GRPF_Folder) - { CloseExclusiveMother(); Clear(); return true; } + // Folder: just close + if (Status==GRPF_Folder) + { CloseExclusiveMother(); Clear(); return true; } - // Rewrite check - for (centry=FirstEntry; centry; centry=centry->Next) - if (centry->Status!=C4GRES_InGroup) - fRewrite=true; - if (Modified) fRewrite=true; - //if (Head.Entries==0) fRewrite=true; + // Rewrite check + for (centry=FirstEntry; centry; centry=centry->Next) + if (centry->Status!=C4GRES_InGroup) + fRewrite=true; + if (Modified) fRewrite=true; + //if (Head.Entries==0) fRewrite=true; - // No rewrite: just close - if (!fRewrite) - { CloseExclusiveMother(); Clear(); return true; } + // No rewrite: just close + if (!fRewrite) + { CloseExclusiveMother(); Clear(); return true; } - if (StdOutput) printf("Writing group file...\n"); + if (StdOutput) printf("Writing group file...\n"); // Set new version Head.Ver1=C4GroupFileVer1; @@ -947,24 +947,24 @@ bool C4Group::Close() bool C4Group::Save(bool fReOpen) { - int cscore; - C4GroupEntryCore *save_core; - C4GroupEntry *centry; - char szTempFileName[_MAX_FNAME+1],szGrpFileName[_MAX_FNAME+1]; + int cscore; + C4GroupEntryCore *save_core; + C4GroupEntry *centry; + char szTempFileName[_MAX_FNAME+1],szGrpFileName[_MAX_FNAME+1]; - // Create temporary core list with new actual offsets to be saved + // Create temporary core list with new actual offsets to be saved int32_t iContentsSize = 0; - save_core = new C4GroupEntryCore [Head.Entries]; - cscore=0; - for (centry=FirstEntry; centry; centry=centry->Next) - if (centry->Status!=C4GRES_Deleted) - { - save_core[cscore]=(C4GroupEntryCore)*centry; - // Make actual offset - save_core[cscore].Offset = iContentsSize; + save_core = new C4GroupEntryCore [Head.Entries]; + cscore=0; + for (centry=FirstEntry; centry; centry=centry->Next) + if (centry->Status!=C4GRES_Deleted) + { + save_core[cscore]=(C4GroupEntryCore)*centry; + // Make actual offset + save_core[cscore].Offset = iContentsSize; iContentsSize += centry->Size; - cscore++; - } + cscore++; + } // Hold contents in memory? bool fToMemory = !fReOpen && Mother && iContentsSize < C4GroupSwapThreshold; @@ -984,19 +984,19 @@ bool C4Group::Save(bool fReOpen) } // Create the new (temp) group file - CStdFile tfile; - if (!tfile.Create(szTempFileName,true,false,fToMemory)) - { delete [] save_core; return Error("Close: ..."); } + CStdFile tfile; + if (!tfile.Create(szTempFileName,true,false,fToMemory)) + { delete [] save_core; return Error("Close: ..."); } - // Save header and core list + // Save header and core list C4GroupHeader headbuf = Head; MemScramble((BYTE*)&headbuf,sizeof(C4GroupHeader)); - if (!tfile.Write((BYTE*)&headbuf,sizeof(C4GroupHeader)) - || !tfile.Write((BYTE*)save_core,Head.Entries*sizeof(C4GroupEntryCore))) - { tfile.Close(); delete [] save_core; return Error("Close: ..."); } - delete [] save_core; + if (!tfile.Write((BYTE*)&headbuf,sizeof(C4GroupHeader)) + || !tfile.Write((BYTE*)save_core,Head.Entries*sizeof(C4GroupEntryCore))) + { tfile.Close(); delete [] save_core; return Error("Close: ..."); } + delete [] save_core; - // Save Entries to temp file + // Save Entries to temp file int iTotalSize=0,iSizeDone=0; for (centry=FirstEntry; centry; centry=centry->Next) iTotalSize+=centry->Size; for (centry=FirstEntry; centry; centry=centry->Next) @@ -1030,9 +1030,9 @@ bool C4Group::Save(bool fReOpen) } // Clear (close file) - Clear(); + Clear(); - // Delete old group file, rename new file + // Delete old group file, rename new file if (!EraseFile(szGrpFileName)) return Error("Close: Cannot erase temp file"); if (!RenameFile(szTempFileName,szGrpFileName)) @@ -1056,67 +1056,67 @@ void C4Group::Default() } void C4Group::Clear() - { - // Delete entries - C4GroupEntry *next; - while (FirstEntry) - { - next=FirstEntry->Next; - delete FirstEntry; - FirstEntry=next; - } - // Close std file - StdFile.Close(); - // Delete mother - if (Mother && ExclusiveChild) - { - delete Mother; - Mother=NULL; - } - // done in init + { + // Delete entries + C4GroupEntry *next; + while (FirstEntry) + { + next=FirstEntry->Next; + delete FirstEntry; + FirstEntry=next; + } + // Close std file + StdFile.Close(); + // Delete mother + if (Mother && ExclusiveChild) + { + delete Mother; + Mother=NULL; + } + // done in init //FolderSearch.Reset(); - // Reset - Init(); - } + // Reset + Init(); + } bool C4Group::AppendEntry2StdFile(C4GroupEntry *centry, CStdFile &hTarget) - { - CStdFile hSource; - long csize; - BYTE fbuf; + { + CStdFile hSource; + long csize; + BYTE fbuf; - switch (centry->Status) - { + switch (centry->Status) + { - case C4GRES_InGroup: // Copy from group to std file - if (!SetFilePtr(centry->Offset)) - return Error("AE2S: Cannot set file pointer"); - for (csize=centry->Size; csize>0; csize--) + case C4GRES_InGroup: // Copy from group to std file + if (!SetFilePtr(centry->Offset)) + return Error("AE2S: Cannot set file pointer"); + for (csize=centry->Size; csize>0; csize--) { - if (!Read(&fbuf,1)) + if (!Read(&fbuf,1)) return Error("AE2S: Cannot read entry from group file"); if (!hTarget.Write(&fbuf,1)) - return Error("AE2S: Cannot write to target file"); + return Error("AE2S: Cannot write to target file"); } - break; + break; - case C4GRES_OnDisk: // Copy/move from disk item to std file + case C4GRES_OnDisk: // Copy/move from disk item to std file { - char szFileSource[_MAX_FNAME+1]; - SCopy(centry->DiskPath,szFileSource,_MAX_FNAME); + char szFileSource[_MAX_FNAME+1]; + SCopy(centry->DiskPath,szFileSource,_MAX_FNAME); - // Disk item is a directory - if (DirectoryExists(centry->DiskPath)) - return Error("AE2S: Cannot add directory to group file"); - /*{ - if (StdOutput) printf("Adding directory %s to group file...\n",centry->FileName); - // Temporary file name - MakeTempFilename(szFileSource); - // Create temporary copy of directory - if (!CopyItem(centry->DiskPath,szFileSource)) return Error("Cannot create temporary directory"); - // Convert directory to temporary group file - if (!Folder2Group(szFileSource)) return Error("Cannot convert directory to group file"); - }*/ + // Disk item is a directory + if (DirectoryExists(centry->DiskPath)) + return Error("AE2S: Cannot add directory to group file"); + /*{ + if (StdOutput) printf("Adding directory %s to group file...\n",centry->FileName); + // Temporary file name + MakeTempFilename(szFileSource); + // Create temporary copy of directory + if (!CopyItem(centry->DiskPath,szFileSource)) return Error("Cannot create temporary directory"); + // Convert directory to temporary group file + if (!Folder2Group(szFileSource)) return Error("Cannot convert directory to group file"); + }*/ // Resort group if neccessary // (The group might be renamed by adding, forcing a resort) @@ -1140,17 +1140,17 @@ bool C4Group::AppendEntry2StdFile(C4GroupEntry *centry, CStdFile &hTarget) SortGrp.Close(); } - // Append disk source to target file - if (!hSource.Open(szFileSource, !!centry->ChildGroup)) - return Error("AE2S: Cannot open on-disk file"); - for (csize=centry->Size; csize>0; csize--) + // Append disk source to target file + if (!hSource.Open(szFileSource, !!centry->ChildGroup)) + return Error("AE2S: Cannot open on-disk file"); + for (csize=centry->Size; csize>0; csize--) { - if (!hSource.Read(&fbuf,1)) - { hSource.Close(); return Error("AE2S: Cannot read on-disk file"); } + if (!hSource.Read(&fbuf,1)) + { hSource.Close(); return Error("AE2S: Cannot read on-disk file"); } if (!hTarget.Write(&fbuf,1)) - { hSource.Close(); return Error("AE2S: Cannot write to target file"); } + { hSource.Close(); return Error("AE2S: Cannot write to target file"); } } - hSource.Close(); + hSource.Close(); // Erase temp file if (fTempFile) @@ -1159,25 +1159,25 @@ bool C4Group::AppendEntry2StdFile(C4GroupEntry *centry, CStdFile &hTarget) if (centry->DeleteOnDisk) EraseItem(centry->DiskPath); - break; + break; } - case C4GRES_InMemory: // Copy from mem to std file - //if (StdOutput) printf("Saving InMem entry %d...\n",centry->Size); - if (!centry->bpMemBuf) return Error("AE2S: no buffer"); - if (!hTarget.Write(centry->bpMemBuf,centry->Size)) return Error("AE2S: writing error"); - break; + case C4GRES_InMemory: // Copy from mem to std file + //if (StdOutput) printf("Saving InMem entry %d...\n",centry->Size); + if (!centry->bpMemBuf) return Error("AE2S: no buffer"); + if (!hTarget.Write(centry->bpMemBuf,centry->Size)) return Error("AE2S: writing error"); + break; - case C4GRES_Deleted: // Don't save - break; + case C4GRES_Deleted: // Don't save + break; - default: // Unknown file status - return Error("AE2S: Unknown file status"); + default: // Unknown file status + return Error("AE2S: Unknown file status"); - } + } - return true; - } + return true; + } void C4Group::ResetSearch() { @@ -1209,65 +1209,65 @@ C4GroupEntry* C4Group::GetNextFolderEntry() { return NULL; } - } + } C4GroupEntry* C4Group::SearchNextEntry(const char *szName) - { + { // Wildcard "*.*" is expected to find all files: substitute correct wildcard "*" if (SEqual(szName, "*.*")) szName = "*"; // Search by group type - C4GroupEntry *pEntry; - switch (Status) - { + C4GroupEntry *pEntry; + switch (Status) + { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case GRPF_File: - for (pEntry=SearchPtr; pEntry; pEntry=pEntry->Next) - if (pEntry->Status!=C4GRES_Deleted) - if (WildcardMatch(szName,pEntry->FileName)) - { - SearchPtr=pEntry->Next; - return pEntry; - } - break; + case GRPF_File: + for (pEntry=SearchPtr; pEntry; pEntry=pEntry->Next) + if (pEntry->Status!=C4GRES_Deleted) + if (WildcardMatch(szName,pEntry->FileName)) + { + SearchPtr=pEntry->Next; + return pEntry; + } + break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case GRPF_Folder: - for (pEntry=SearchPtr; pEntry; pEntry=GetNextFolderEntry()) - if (WildcardMatch(szName,pEntry->FileName)) + case GRPF_Folder: + for (pEntry=SearchPtr; pEntry; pEntry=GetNextFolderEntry()) + if (WildcardMatch(szName,pEntry->FileName)) if (!C4Group_TestIgnore(pEntry->FileName)) - { - LastFolderSearchEntry=(*pEntry); - pEntry=&LastFolderSearchEntry; - SearchPtr=GetNextFolderEntry(); - return pEntry; - } - break; + { + LastFolderSearchEntry=(*pEntry); + pEntry=&LastFolderSearchEntry; + SearchPtr=GetNextFolderEntry(); + return pEntry; + } + break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } + } // No entry found: reset search pointer - SearchPtr=NULL; - return NULL; - } + SearchPtr=NULL; + return NULL; + } bool C4Group::SetFilePtr(int iOffset) - { + { - if (Status==GRPF_Folder) + if (Status==GRPF_Folder) return Error("SetFilePtr not implemented for Folders"); // ensure mother is at correct pos if (Mother) Mother->EnsureChildFilePtr(this); - // Rewind if necessary - if (FilePtr>iOffset) - if (!RewindFilePtr()) return false; + // Rewind if necessary + if (FilePtr>iOffset) + if (!RewindFilePtr()) return false; - // Advance to target pointer - if (FilePtrRead(pBuffer,iSize)) - { RewindFilePtr(); return Error("Read:"); } - } - // Regular group: read from standard file - else - { - if (!StdFile.Read(pBuffer,iSize)) - { RewindFilePtr(); return Error("Read:"); } - } - FilePtr+=iSize; - break; - case GRPF_Folder: - if (!StdFile.Read(pBuffer,iSize)) return Error("Read: Error reading from folder contents"); - break; - } + switch (Status) + { + case GRPF_File: + // Child group: read from mother group + if (Mother) + { + if (!Mother->Read(pBuffer,iSize)) + { RewindFilePtr(); return Error("Read:"); } + } + // Regular group: read from standard file + else + { + if (!StdFile.Read(pBuffer,iSize)) + { RewindFilePtr(); return Error("Read:"); } + } + FilePtr+=iSize; + break; + case GRPF_Folder: + if (!StdFile.Read(pBuffer,iSize)) return Error("Read: Error reading from folder contents"); + break; + } - return true; - } + return true; + } bool C4Group::AdvanceFilePtr(int iOffset, C4Group *pByChild) - { - // Child group file: pass command to mother - if ((Status==GRPF_File) && Mother) - { + { + // Child group file: pass command to mother + if ((Status==GRPF_File) && Mother) + { // Ensure mother file ptr for it may have been moved by foreign access to mother if (!Mother->EnsureChildFilePtr(this)) return false; - if (!Mother->AdvanceFilePtr(iOffset,this)) + if (!Mother->AdvanceFilePtr(iOffset,this)) return false; - } - // Regular group - else if (Status==GRPF_File) - { - if (!StdFile.Advance(iOffset)) + } + // Regular group + else if (Status==GRPF_File) + { + if (!StdFile.Advance(iOffset)) return false; - } + } // Open folder else { - if (!StdFile.Advance(iOffset)) + if (!StdFile.Advance(iOffset)) return false; } // Advanced - FilePtr+=iOffset; + FilePtr+=iOffset; - return true; - } + return true; + } bool C4Group::RewindFilePtr() - { + { #ifdef _DEBUG if (szCurrAccessedEntry && !iC4GroupRewindFilePtrNoWarn) @@ -1351,27 +1351,27 @@ bool C4Group::RewindFilePtr() } #endif - // Child group file: pass command to mother - if ((Status==GRPF_File) && Mother) - { - if (!Mother->SetFilePtr2Entry(FileName,this,true)) // Set to group file start + // Child group file: pass command to mother + if ((Status==GRPF_File) && Mother) + { + if (!Mother->SetFilePtr2Entry(FileName,this,true)) // Set to group file start return false; - if (!Mother->AdvanceFilePtr(EntryOffset,this)) // Advance data offset + if (!Mother->AdvanceFilePtr(EntryOffset,this)) // Advance data offset return false; - } - // Regular group or open folder: rewind standard file - else - { - if (!StdFile.Rewind()) // Set to group file start + } + // Regular group or open folder: rewind standard file + else + { + if (!StdFile.Rewind()) // Set to group file start return false; - if (!StdFile.Advance(EntryOffset)) // Advance data offset + if (!StdFile.Advance(EntryOffset)) // Advance data offset return false; - } + } - FilePtr=0; + FilePtr=0; - return true; - } + return true; + } bool C4Group::View(const char *szFiles) { @@ -1413,12 +1413,12 @@ bool C4Group::View(const char *szFiles) centry->Time = cur_time; printf(oformat, centry->FileName, - centry->Size, - coretm.tm_mday,coretm.tm_mon+1,coretm.tm_year%100, - coretm.tm_hour,coretm.tm_min,coretm.tm_sec, + centry->Size, + coretm.tm_mday,coretm.tm_mon+1,coretm.tm_year%100, + coretm.tm_hour,coretm.tm_min,coretm.tm_sec, centry->HasCRC ? ((centry->HasCRC == C4GECS_New) ? "!" : "~") : " ", centry->HasCRC ? centry->CRC : 0, - centry->ChildGroup ? "(Group)" : (centry->Executable ? "(Executable)" : "")); + centry->ChildGroup ? "(Group)" : (centry->Executable ? "(Executable)" : "")); } printf("%d Entries, %d Bytes\n",fcount,bcount); @@ -1427,7 +1427,7 @@ bool C4Group::View(const char *szFiles) } bool C4Group::Merge(const char *szFolders) - { + { bool fMove = true; if (StdOutput) printf("%s...\n",fMove ? "Moving" : "Adding"); @@ -1442,10 +1442,10 @@ bool C4Group::Merge(const char *szFolders) for (int cseg=0; SCopySegment(szFolders, cseg, szFileName, cSeparator); cseg++) { i.Reset(szFileName); - while (*i) + while (*i) { // File count - iFileCount++; + iFileCount++; // Process output & callback if (StdOutput) printf("%s\n",GetFilename(*i)); if (fnProcessCallback) @@ -1464,7 +1464,7 @@ bool C4Group::Merge(const char *szFolders) bool C4Group::AddEntryOnDisk(const char *szFilename, const char *szAddAs, bool fMove) - { + { // Do not process yourself if (ItemIdentical(szFilename,FileName)) return true; @@ -1501,42 +1501,42 @@ bool C4Group::AddEntryOnDisk(const char *szFilename, #endif // AddEntry - return AddEntry(C4GRES_OnDisk, - fIsGroup, - szFilename, - iSize, - FileTime(szFilename), + return AddEntry(C4GRES_OnDisk, + fIsGroup, + szFilename, + iSize, + FileTime(szFilename), false, 0, - szAddAs, + szAddAs, NULL, fMove, false, fExecutable); - } + } bool C4Group::Add(const char *szFile, const char *szAddAs) - { + { bool fMove = false; - if (StdOutput) printf("%s %s as %s...\n",fMove ? "Moving" : "Adding",GetFilename(szFile),szAddAs); + if (StdOutput) printf("%s %s as %s...\n",fMove ? "Moving" : "Adding",GetFilename(szFile),szAddAs); - return AddEntryOnDisk(szFile, szAddAs, fMove); - } + return AddEntryOnDisk(szFile, szAddAs, fMove); + } bool C4Group::Move(const char *szFile, const char *szAddAs) - { + { bool fMove = true; - if (StdOutput) printf("%s %s as %s...\n",fMove ? "Moving" : "Adding",GetFilename(szFile),szAddAs); + if (StdOutput) printf("%s %s as %s...\n",fMove ? "Moving" : "Adding",GetFilename(szFile),szAddAs); - return AddEntryOnDisk(szFile, szAddAs, fMove); - } + return AddEntryOnDisk(szFile, szAddAs, fMove); + } bool C4Group::Delete(const char *szFiles, bool fRecursive) - { - int fcount = 0; - C4GroupEntry *tentry; + { + int fcount = 0; + C4GroupEntry *tentry; // Segmented file specs if (SCharCount(';', szFiles) || SCharCount('|', szFiles)) @@ -1550,16 +1550,16 @@ bool C4Group::Delete(const char *szFiles, bool fRecursive) return success; // Would be nicer to return the file count and add up all counts from recursive actions... } - // Delete all matching Entries - ResetSearch(); - while ((tentry = SearchNextEntry(szFiles))) - { - // StdOutput - if (StdOutput) printf("%s\n",tentry->FileName); + // Delete all matching Entries + ResetSearch(); + while ((tentry = SearchNextEntry(szFiles))) + { + // StdOutput + if (StdOutput) printf("%s\n",tentry->FileName); if (!DeleteEntry(tentry->FileName)) return Error("Delete: Could not delete entry"); fcount++; - } + } // Recursive: process sub groups if (fRecursive) @@ -1576,33 +1576,33 @@ bool C4Group::Delete(const char *szFiles, bool fRecursive) } } - // StdOutput - if (StdOutput) + // StdOutput + if (StdOutput) printf("%d file(s) deleted.\n",fcount); - return true; // Would be nicer to return the file count and add up all counts from recursive actions... - } + return true; // Would be nicer to return the file count and add up all counts from recursive actions... + } bool C4Group::DeleteEntry(const char *szFilename, bool fRecycle) - { - switch (Status) - { - case GRPF_File: + { + switch (Status) + { + case GRPF_File: // Get entry C4GroupEntry *pEntry; if (!(pEntry=GetEntry(szFilename))) return false; - // Delete moved source files + // Delete moved source files if (pEntry->Status==C4GRES_OnDisk) if (pEntry->DeleteOnDisk) { EraseItem(pEntry->DiskPath); } // (moved buffers are deleted by ~C4GroupEntry) - // Delete status and update virtual file count - pEntry->Status=C4GRES_Deleted; - Head.Entries--; - break; - case GRPF_Folder: + // Delete status and update virtual file count + pEntry->Status=C4GRES_Deleted; + Head.Entries--; + break; + case GRPF_Folder: StdFile.Close(); char szPath[_MAX_FNAME+1]; sprintf(szPath,"%s%c%s",FileName,DirectorySeparator,szFilename); @@ -1615,40 +1615,40 @@ bool C4Group::DeleteEntry(const char *szFilename, bool fRecycle) { if (!EraseItem(szPath)) return false; } - break; - } - return true; - } + break; + } + return true; + } bool C4Group::Rename(const char *szFile, const char *szNewName) - { + { - if (StdOutput) printf("Renaming %s to %s...\n",szFile,szNewName); + if (StdOutput) printf("Renaming %s to %s...\n",szFile,szNewName); - switch (Status) - { - case GRPF_File: - // Get entry + switch (Status) + { + case GRPF_File: + // Get entry C4GroupEntry *pEntry; - if (!(pEntry=GetEntry(szFile))) return Error("Rename: File not found"); - // Check double name - if (GetEntry(szNewName) && !SEqualNoCase(szNewName, szFile)) return Error("Rename: File exists already"); - // Rename - SCopy(szNewName,pEntry->FileName,_MAX_FNAME); - Modified=true; - break; - case GRPF_Folder: + if (!(pEntry=GetEntry(szFile))) return Error("Rename: File not found"); + // Check double name + if (GetEntry(szNewName) && !SEqualNoCase(szNewName, szFile)) return Error("Rename: File exists already"); + // Rename + SCopy(szNewName,pEntry->FileName,_MAX_FNAME); + Modified=true; + break; + case GRPF_Folder: StdFile.Close(); - char path[_MAX_FNAME+1]; SCopy(FileName,path,_MAX_PATH-1); - AppendBackslash(path); SAppend(szFile,path,_MAX_PATH); - char path2[_MAX_FNAME+1]; SCopy(FileName,path2,_MAX_PATH-1); - AppendBackslash(path2); SAppend(szNewName,path2,_MAX_PATH); - if (!RenameFile(path,path2)) return Error("Rename: Failure"); - break; - } + char path[_MAX_FNAME+1]; SCopy(FileName,path,_MAX_PATH-1); + AppendBackslash(path); SAppend(szFile,path,_MAX_PATH); + char path2[_MAX_FNAME+1]; SCopy(FileName,path2,_MAX_PATH-1); + AppendBackslash(path2); SAppend(szNewName,path2,_MAX_PATH); + if (!RenameFile(path,path2)) return Error("Rename: Failure"); + break; + } - return true; - } + return true; + } bool C4Group_IsExcluded(const char *szFile, const char *szExcludeList) { @@ -1657,7 +1657,7 @@ bool C4Group_IsExcluded(const char *szFile, const char *szExcludeList) // Process segmented exclude list char cSeparator = (SCharCount(';', szExcludeList) ? ';' : '|'); char szSegment[_MAX_PATH + 1]; - for (int i = 0; SCopySegment(szExcludeList, i, szSegment, cSeparator); i++) + for (int i = 0; SCopySegment(szExcludeList, i, szSegment, cSeparator); i++) if (WildcardMatch(szSegment, GetFilename(szFile))) return true; // No match @@ -1665,26 +1665,26 @@ bool C4Group_IsExcluded(const char *szFile, const char *szExcludeList) } bool C4Group::Extract(const char *szFiles, const char *szExtractTo, const char *szExclude) - { + { - // StdOutput - if (StdOutput) - { - printf("Extracting"); - if (szExtractTo) printf(" to %s",szExtractTo); - printf("...\n"); - } + // StdOutput + if (StdOutput) + { + printf("Extracting"); + if (szExtractTo) printf(" to %s",szExtractTo); + printf("...\n"); + } - int fcount=0; + int fcount=0; int cbytes,tbytes; - C4GroupEntry *tentry; + C4GroupEntry *tentry; cbytes=0; tbytes=EntrySize(); // Process segmented list char cSeparator = (SCharCount(';', szFiles) ? ';' : '|'); char szFileName[_MAX_PATH + 1]; - for (int cseg=0; SCopySegment(szFiles, cseg, szFileName, cSeparator); cseg++) + for (int cseg=0; SCopySegment(szFiles, cseg, szFileName, cSeparator); cseg++) { // Search all entries ResetSearch(); @@ -1706,10 +1706,10 @@ bool C4Group::Extract(const char *szFiles, const char *szExtractTo, const char * } } - if (StdOutput) printf("%d file(s) extracted.\n",fcount); + if (StdOutput) printf("%d file(s) extracted.\n",fcount); - return true; - } + return true; + } bool C4Group::ExtractEntry(const char *szFilename, const char *szExtractTo) { @@ -1733,7 +1733,7 @@ bool C4Group::ExtractEntry(const char *szFilename, const char *szExtractTo) // Extract switch (Status) { - case GRPF_File: // Copy entry to target + case GRPF_File: // Copy entry to target // Get entry C4GroupEntry *pEntry; if (!(pEntry=GetEntry(szFilename))) return false; @@ -1789,58 +1789,58 @@ bool C4Group::ExtractEntry(const char *szFilename, const char *szExtractTo) bool C4Group::OpenAsChild(C4Group *pMother, const char *szEntryName, bool fExclusive, bool fCreate) - { + { - if (!pMother) return Error("OpenAsChild: No mother specified"); + if (!pMother) return Error("OpenAsChild: No mother specified"); - if (SCharCount('*',szEntryName)) return Error("OpenAsChild: No wildcards allowed"); + if (SCharCount('*',szEntryName)) return Error("OpenAsChild: No wildcards allowed"); - // Open nested child group check: If szEntryName is a reference to - // a nested group, open the first mother (in specified mode), then open the child - // in exclusive mode + // Open nested child group check: If szEntryName is a reference to + // a nested group, open the first mother (in specified mode), then open the child + // in exclusive mode - if (SCharCount(DirectorySeparator,szEntryName)) - { - char mothername[_MAX_FNAME+1]; - SCopyUntil(szEntryName,mothername,DirectorySeparator,_MAX_FNAME); + if (SCharCount(DirectorySeparator,szEntryName)) + { + char mothername[_MAX_FNAME+1]; + SCopyUntil(szEntryName,mothername,DirectorySeparator,_MAX_FNAME); - C4Group *pMother2; - pMother2 = new C4Group; - pMother2->SetStdOutput(StdOutput); - if (!pMother2->OpenAsChild(pMother, mothername, fExclusive)) + C4Group *pMother2; + pMother2 = new C4Group; + pMother2->SetStdOutput(StdOutput); + if (!pMother2->OpenAsChild(pMother, mothername, fExclusive)) { delete pMother2; return Error("OpenAsChild: Cannot open mother"); } - return OpenAsChild(pMother2, szEntryName + SLen(mothername) + 1, true); - } + return OpenAsChild(pMother2, szEntryName + SLen(mothername) + 1, true); + } - // Init + // Init Init(); - SCopy(szEntryName,FileName,_MAX_FNAME); - Mother=pMother; - ExclusiveChild=fExclusive; + SCopy(szEntryName,FileName,_MAX_FNAME); + Mother=pMother; + ExclusiveChild=fExclusive; - // Folder: Simply set status and return - char path[_MAX_FNAME+1]; + // Folder: Simply set status and return + char path[_MAX_FNAME+1]; SCopy( GetFullName().getData(), path, _MAX_FNAME); - if (DirectoryExists(path)) - { - SCopy(path,FileName, _MAX_FNAME); + if (DirectoryExists(path)) + { + SCopy(path,FileName, _MAX_FNAME); SCopy("Open directory",Head.Maker,C4GroupMaxMaker); - Status=GRPF_Folder; - ResetSearch(); - return true; - } + Status=GRPF_Folder; + ResetSearch(); + return true; + } // Get original entry name C4GroupEntry *centry; if ((centry = Mother->GetEntry(FileName))) SCopy(centry->FileName,FileName,_MAX_PATH); - // Access entry in mother group + // Access entry in mother group size_t iSize; - if ((!Mother->AccessEntry(FileName, &iSize, NULL, NULL, true))) + if ((!Mother->AccessEntry(FileName, &iSize, NULL, NULL, true))) { if(!fCreate) { CloseExclusiveMother(); Clear(); return Error("OpenAsChild: Entry not in mother group"); } @@ -1856,228 +1856,228 @@ bool C4Group::OpenAsChild(C4Group *pMother, if(centry && !centry->ChildGroup) { CloseExclusiveMother(); Clear(); return Error("OpenAsChild: Is not a child group"); } - // Read header + // Read header // Do not do size checks for packed subgroups of unpacked groups (there will be no entry), // because that would be the PACKED size which can actually be smaller than sizeof(C4GroupHeader)! if (iSize < sizeof(C4GroupHeader) && centry) { CloseExclusiveMother(); Clear(); return Error("OpenAsChild: Entry too small"); } - if (!Mother->Read(&Head,sizeof(C4GroupHeader))) + if (!Mother->Read(&Head,sizeof(C4GroupHeader))) { CloseExclusiveMother(); Clear(); return Error("OpenAsChild: Entry reading error"); } MemScramble((BYTE*)&Head,sizeof(C4GroupHeader)); - EntryOffset+=sizeof(C4GroupHeader); + EntryOffset+=sizeof(C4GroupHeader); - // Check Header - if (!SEqual(Head.id,C4GroupFileID) - || (Head.Ver1!=C4GroupFileVer1) || (Head.Ver2>C4GroupFileVer2)) + // Check Header + if (!SEqual(Head.id,C4GroupFileID) + || (Head.Ver1!=C4GroupFileVer1) || (Head.Ver2>C4GroupFileVer2)) { CloseExclusiveMother(); Clear(); return Error("OpenAsChild: Invalid Header"); } - // Read Entries - C4GroupEntryCore corebuf; + // Read Entries + C4GroupEntryCore corebuf; int file_entries=Head.Entries; Head.Entries=0; // Reset, will be recounted by AddEntry - for (int cnt=0; cntRead(&corebuf,sizeof(C4GroupEntryCore))) + for (int cnt=0; cntRead(&corebuf,sizeof(C4GroupEntryCore))) { CloseExclusiveMother(); Clear(); return Error("OpenAsChild: Entry reading error"); } - EntryOffset+=sizeof(C4GroupEntryCore); - if (!AddEntry(C4GRES_InGroup,!!corebuf.ChildGroup, - corebuf.FileName,corebuf.Size,corebuf.Time, + EntryOffset+=sizeof(C4GroupEntryCore); + if (!AddEntry(C4GRES_InGroup,!!corebuf.ChildGroup, + corebuf.FileName,corebuf.Size,corebuf.Time, corebuf.HasCRC, corebuf.CRC, NULL, NULL, false, false, !!corebuf.Executable)) { CloseExclusiveMother(); Clear(); return Error("OpenAsChild: Insufficient memory"); } - } + } - ResetSearch(); + ResetSearch(); - // File - Status=GRPF_File; + // File + Status=GRPF_File; // save position in mother group if (centry) MotherOffset = centry->Offset; - return true; - } + return true; + } bool C4Group::AccessEntry(const char *szWildCard, - size_t *iSize, char *sFileName, + size_t *iSize, char *sFileName, bool *fChild, bool NeedsToBeAGroup) - { + { #ifdef C4GROUP_DUMP_ACCESS LogF("Group access in %s: %s", GetFullName().getData(), szWildCard); #endif - char fname[_MAX_FNAME+1]; - if (!FindEntry(szWildCard,fname,&iCurrFileSize,fChild)) + char fname[_MAX_FNAME+1]; + if (!FindEntry(szWildCard,fname,&iCurrFileSize,fChild)) return false; #ifdef _DEBUG szCurrAccessedEntry = fname; #endif - bool fResult = SetFilePtr2Entry(fname, NULL, NeedsToBeAGroup); + bool fResult = SetFilePtr2Entry(fname, NULL, NeedsToBeAGroup); #ifdef _DEBUG szCurrAccessedEntry = NULL; #endif if (!fResult) return false; - if (sFileName) SCopy(fname,sFileName); + if (sFileName) SCopy(fname,sFileName); if (iSize) *iSize=iCurrFileSize; - return true; - } + return true; + } bool C4Group::AccessNextEntry(const char *szWildCard, - size_t *iSize, char *sFileName, + size_t *iSize, char *sFileName, bool *fChild) - { - char fname[_MAX_FNAME+1]; - if (!FindNextEntry(szWildCard,fname,&iCurrFileSize,fChild)) return false; + { + char fname[_MAX_FNAME+1]; + if (!FindNextEntry(szWildCard,fname,&iCurrFileSize,fChild)) return false; #ifdef _DEBUG szCurrAccessedEntry = fname; #endif - bool fResult = SetFilePtr2Entry(fname); + bool fResult = SetFilePtr2Entry(fname); #ifdef _DEBUG szCurrAccessedEntry = NULL; #endif if (!fResult) return false; - if (sFileName) SCopy(fname,sFileName); + if (sFileName) SCopy(fname,sFileName); if (iSize) *iSize=iCurrFileSize; - return true; - } + return true; + } bool C4Group::SetFilePtr2Entry(const char *szName, C4Group *pByChild, bool NeedsToBeAGroup) - { - switch (Status) - { + { + switch (Status) + { case GRPF_File: - C4GroupEntry *centry; - if (!(centry=GetEntry(szName))) return false; - if (centry->Status!=C4GRES_InGroup) return false; - return SetFilePtr(centry->Offset); + C4GroupEntry *centry; + if (!(centry=GetEntry(szName))) return false; + if (centry->Status!=C4GRES_InGroup) return false; + return SetFilePtr(centry->Offset); case GRPF_Folder: - StdFile.Close(); - char path[_MAX_FNAME+1]; SCopy(FileName,path,_MAX_FNAME); - AppendBackslash(path); SAppend(szName,path); - bool fSuccess = StdFile.Open(path, NeedsToBeAGroup); + StdFile.Close(); + char path[_MAX_FNAME+1]; SCopy(FileName,path,_MAX_FNAME); + AppendBackslash(path); SAppend(szName,path); + bool fSuccess = StdFile.Open(path, NeedsToBeAGroup); return fSuccess; } - return false; - } + return false; + } bool C4Group::FindEntry(const char *szWildCard, char *sFileName, size_t *iSize, bool *fChild) - { - ResetSearch(); - return FindNextEntry(szWildCard,sFileName,iSize,fChild); - } + { + ResetSearch(); + return FindNextEntry(szWildCard,sFileName,iSize,fChild); + } bool C4Group::FindNextEntry(const char *szWildCard, char *sFileName, size_t *iSize, bool *fChild, bool fStartAtFilename) - { - C4GroupEntry *centry; - if (!szWildCard) return false; + { + C4GroupEntry *centry; + if (!szWildCard) return false; // Reset search to specified position if (fStartAtFilename) FindEntry(sFileName); - if (!(centry=SearchNextEntry(szWildCard))) return false; - if (sFileName) SCopy(centry->FileName,sFileName); - if (iSize) *iSize=centry->Size; + if (!(centry=SearchNextEntry(szWildCard))) return false; + if (sFileName) SCopy(centry->FileName,sFileName); + if (iSize) *iSize=centry->Size; if (fChild) *fChild=!!centry->ChildGroup; - return true; - } + return true; + } #ifdef _WIN32 bool C4Group::Add(const char *szFiles) - { + { bool fMove = false; - if (StdOutput) printf("%s...\n",fMove ? "Moving" : "Adding"); + if (StdOutput) printf("%s...\n",fMove ? "Moving" : "Adding"); - // Add files & directories - char szFileName[_MAX_FNAME+1]; - int iFileCount = 0; - long lAttrib = 0x037; // _A_ALL - struct _finddata_t fdt; long fdthnd; + // Add files & directories + char szFileName[_MAX_FNAME+1]; + int iFileCount = 0; + long lAttrib = 0x037; // _A_ALL + struct _finddata_t fdt; long fdthnd; // Process segmented path & search wildcards char cSeparator = (SCharCount(';', szFiles) ? ';' : '|'); - for (int cseg=0; SCopySegment(szFiles, cseg, szFileName, cSeparator); cseg++) - if ((fdthnd=_findfirst( (char*) szFileName, &fdt))>=0) - { - do - { - if (fdt.attrib & lAttrib) - { + for (int cseg=0; SCopySegment(szFiles, cseg, szFileName, cSeparator); cseg++) + if ((fdthnd=_findfirst( (char*) szFileName, &fdt))>=0) + { + do + { + if (fdt.attrib & lAttrib) + { // ignore if(fdt.name[0] == '.') continue; // Compose item path - SCopy(szFiles,szFileName,_MAX_FNAME); *GetFilename(szFileName) = 0; - SAppend(fdt.name, szFileName, _MAX_FNAME); + SCopy(szFiles,szFileName,_MAX_FNAME); *GetFilename(szFileName) = 0; + SAppend(fdt.name, szFileName, _MAX_FNAME); // File count - iFileCount++; + iFileCount++; // Process output & callback - if (StdOutput) printf("%s\n",GetFilename(szFileName)); + if (StdOutput) printf("%s\n",GetFilename(szFileName)); if (fnProcessCallback) fnProcessCallback(GetFilename(szFileName),0); // cbytes/tbytes // AddEntryOnDisk - AddEntryOnDisk(szFileName, NULL, fMove); - } - } - while (_findnext(fdthnd,&fdt)==0); - _findclose(fdthnd); - } + AddEntryOnDisk(szFileName, NULL, fMove); + } + } + while (_findnext(fdthnd,&fdt)==0); + _findclose(fdthnd); + } if (StdOutput) printf("%d file(s) %s.\n",iFileCount,fMove ? "moved" : "added"); - return true; - } + return true; + } bool C4Group::Move(const char *szFiles) - { + { bool fMove = true; - if (StdOutput) printf("%s...\n",fMove ? "Moving" : "Adding"); + if (StdOutput) printf("%s...\n",fMove ? "Moving" : "Adding"); - // Add files & directories - char szFileName[_MAX_FNAME+1]; - int iFileCount = 0; - long lAttrib = 0x037; // _A_ALL - struct _finddata_t fdt; long fdthnd; + // Add files & directories + char szFileName[_MAX_FNAME+1]; + int iFileCount = 0; + long lAttrib = 0x037; // _A_ALL + struct _finddata_t fdt; long fdthnd; // Process segmented path & search wildcards char cSeparator = (SCharCount(';', szFiles) ? ';' : '|'); - for (int cseg=0; SCopySegment(szFiles, cseg, szFileName, cSeparator); cseg++) - if ((fdthnd=_findfirst( (char*) szFileName, &fdt))>=0) - { - do - { - if (fdt.attrib & lAttrib) - { + for (int cseg=0; SCopySegment(szFiles, cseg, szFileName, cSeparator); cseg++) + if ((fdthnd=_findfirst( (char*) szFileName, &fdt))>=0) + { + do + { + if (fdt.attrib & lAttrib) + { // ignore if(fdt.name[0] == '.') continue; // Compose item path - SCopy(szFiles,szFileName,_MAX_FNAME); *GetFilename(szFileName) = 0; - SAppend(fdt.name, szFileName, _MAX_FNAME); + SCopy(szFiles,szFileName,_MAX_FNAME); *GetFilename(szFileName) = 0; + SAppend(fdt.name, szFileName, _MAX_FNAME); // File count - iFileCount++; + iFileCount++; // Process output & callback - if (StdOutput) printf("%s\n",GetFilename(szFileName)); + if (StdOutput) printf("%s\n",GetFilename(szFileName)); if (fnProcessCallback) fnProcessCallback(GetFilename(szFileName),0); // cbytes/tbytes // AddEntryOnDisk - AddEntryOnDisk(szFileName, NULL, fMove); - } - } - while (_findnext(fdthnd,&fdt)==0); - _findclose(fdthnd); - } + AddEntryOnDisk(szFileName, NULL, fMove); + } + } + while (_findnext(fdthnd,&fdt)==0); + _findclose(fdthnd); + } if (StdOutput) printf("%d file(s) %s.\n",iFileCount,fMove ? "moved" : "added"); - return true; - } + return true; + } #endif bool C4Group::Add(const char *szName, void *pBuffer, int iSize, bool fChild, bool fHoldBuffer, int iTime, bool fExecutable) - { + { return AddEntry(C4GRES_InMemory, fChild, szName, @@ -2085,12 +2085,12 @@ bool C4Group::Add(const char *szName, void *pBuffer, int iSize, bool fChild, boo iTime ? iTime : time(NULL), false, 0, - szName, - (BYTE*) pBuffer, + szName, + (BYTE*) pBuffer, false, fHoldBuffer, fExecutable); - } + } bool C4Group::Add(const char *szName, StdBuf &pBuffer, bool fChild, bool fHoldBuffer, int iTime, bool fExecutable) { @@ -2101,8 +2101,8 @@ bool C4Group::Add(const char *szName, StdBuf &pBuffer, bool fChild, bool fHoldBu iTime ? iTime : time(NULL), false, 0, - szName, - (BYTE*) pBuffer.getData(), + szName, + (BYTE*) pBuffer.getData(), false, fHoldBuffer, fExecutable, @@ -2121,8 +2121,8 @@ bool C4Group::Add(const char *szName, StdStrBuf &pBuffer, bool fChild, bool fHol iTime ? iTime : time(NULL), false, 0, - szName, - (BYTE*) pBuffer.getData(), + szName, + (BYTE*) pBuffer.getData(), false, fHoldBuffer, fExecutable, @@ -2134,38 +2134,38 @@ bool C4Group::Add(const char *szName, StdStrBuf &pBuffer, bool fChild, bool fHol const char* C4Group::GetName() - { - return FileName; - } + { + return FileName; + } int C4Group::EntryCount(const char *szWildCard) - { - int fcount; - C4GroupEntry *tentry; - // All files if no wildcard - if (!szWildCard) szWildCard="*"; - // Match wildcard - ResetSearch(); fcount=0; - while ((tentry=SearchNextEntry(szWildCard))) fcount++; - return fcount; - } + { + int fcount; + C4GroupEntry *tentry; + // All files if no wildcard + if (!szWildCard) szWildCard="*"; + // Match wildcard + ResetSearch(); fcount=0; + while ((tentry=SearchNextEntry(szWildCard))) fcount++; + return fcount; + } int C4Group::EntrySize(const char *szWildCard) - { - int fsize; - C4GroupEntry *tentry; - // All files if no wildcard - if (!szWildCard) szWildCard="*"; - // Match wildcard - ResetSearch(); fsize=0; - while ((tentry=SearchNextEntry(szWildCard))) + { + int fsize; + C4GroupEntry *tentry; + // All files if no wildcard + if (!szWildCard) szWildCard="*"; + // Match wildcard + ResetSearch(); fsize=0; + while ((tentry=SearchNextEntry(szWildCard))) fsize+=tentry->Size; - return fsize; - } + return fsize; + } unsigned int C4Group::EntryCRC32(const char *szWildCard) - { - if(!szWildCard) szWildCard="*"; + { + if(!szWildCard) szWildCard="*"; // iterate thorugh child C4GroupEntry *pEntry; unsigned int iCRC = 0; ResetSearch(); @@ -2179,32 +2179,32 @@ unsigned int C4Group::EntryCRC32(const char *szWildCard) } int C4Group::EntryTime(const char *szFilename) - { + { int iTime = 0; - switch (Status) - { - case GRPF_File: + switch (Status) + { + case GRPF_File: C4GroupEntry *pEntry; pEntry = GetEntry(szFilename); if (pEntry) iTime = pEntry->Time; - break; - case GRPF_Folder: + break; + case GRPF_Folder: char szPath[_MAX_FNAME+1]; sprintf(szPath,"%s%c%s",FileName,DirectorySeparator,szFilename); - iTime = FileTime(szPath); - break; - } + iTime = FileTime(szPath); + break; + } return iTime; - } + } bool C4Group::LoadEntry(const char *szEntryName, char **lpbpBuf, size_t *ipSize, int iAppendZeros) - { - size_t size; + { + size_t size; - // Access entry, allocate buffer, read data - (*lpbpBuf)=NULL; if (ipSize) *ipSize=0; - if (!AccessEntry(szEntryName,&size)) return Error("LoadEntry: Not found"); - if (! ((*lpbpBuf)=new char[size+iAppendZeros]) ) return Error("LoadEntry: Insufficient memory"); - if (!Read(*lpbpBuf,size)) + // Access entry, allocate buffer, read data + (*lpbpBuf)=NULL; if (ipSize) *ipSize=0; + if (!AccessEntry(szEntryName,&size)) return Error("LoadEntry: Not found"); + if (! ((*lpbpBuf)=new char[size+iAppendZeros]) ) return Error("LoadEntry: Insufficient memory"); + if (!Read(*lpbpBuf,size)) { delete [] (*lpbpBuf); *lpbpBuf = NULL; return Error("LoadEntry: Reading error"); @@ -2215,8 +2215,8 @@ bool C4Group::LoadEntry(const char *szEntryName, char **lpbpBuf, size_t *ipSize, if (iAppendZeros) ZeroMem( (*lpbpBuf)+size, iAppendZeros ); - return true; - } + return true; + } bool C4Group::LoadEntry(const char *szEntryName, StdBuf &Buf) { @@ -2255,15 +2255,15 @@ bool C4Group::LoadEntryString(const char *szEntryName, StdStrBuf &Buf) } void C4Group::SetMaker(const char *szMaker) - { + { if (!SEqual(szMaker,Head.Maker)) Modified=true; - SCopy(szMaker,Head.Maker,C4GroupMaxMaker); + SCopy(szMaker,Head.Maker,C4GroupMaxMaker); } void C4Group::SetPassword(const char *szPassword) { if (!SEqual(szPassword,Head.Password)) Modified=true; - SCopy(szPassword,Head.Password,C4GroupMaxPassword); + SCopy(szPassword,Head.Password,C4GroupMaxPassword); } const char* C4Group::GetMaker() @@ -2305,7 +2305,7 @@ bool C4Group::Sort(const char *szSortList) if (!szSortList || !szSortList[0]) return false; - if (StdOutput) printf("Sorting...\n"); + if (StdOutput) printf("Sorting...\n"); do { @@ -2388,8 +2388,8 @@ bool C4Group::SortByList(const char **ppSortList, const char *szFilename) void C4Group::ProcessOut(const char *szMessage, int iProcess) { - if (fnProcessCallback) fnProcessCallback(szMessage,iProcess); - if (C4Group_ProcessCallback) C4Group_ProcessCallback(szMessage,iProcess); + if (fnProcessCallback) fnProcessCallback(szMessage,iProcess); + if (C4Group_ProcessCallback) C4Group_ProcessCallback(szMessage,iProcess); } bool C4Group::EnsureChildFilePtr(C4Group *pChild) diff --git a/src/c4group/C4Group.h b/src/c4group/C4Group.h index cadc34f9b..206a6701f 100644 --- a/src/c4group/C4Group.h +++ b/src/c4group/C4Group.h @@ -61,7 +61,7 @@ extern int iC4GroupRewindFilePtrNoWarn; const int C4GroupFileVer1=1, C4GroupFileVer2=2; const int C4GroupMaxMaker = 30, - C4GroupMaxPassword = 30, + C4GroupMaxPassword = 30, C4GroupMaxError = 100; const int32_t C4GroupSwapThreshold = 10 * 1024 * 1024; @@ -95,38 +95,38 @@ extern time_t C4Group_AssumeTimeOffset; #pragma pack (push, 1) class C4GroupHeader - { + { public: C4GroupHeader(); - public: - char id[24+4]; - int Ver1,Ver2; - int Entries; - char Maker[C4GroupMaxMaker+2]; - char Password[C4GroupMaxPassword+2]; + public: + char id[24+4]; + int Ver1,Ver2; + int Entries; + char Maker[C4GroupMaxMaker+2]; + char Password[C4GroupMaxPassword+2]; int Creation,Original; - BYTE fbuf[92]; - public: - void Init(); - }; + BYTE fbuf[92]; + public: + void Init(); + }; const char C4GECS_None = 0, C4GECS_Old = 1, C4GECS_New = 2; class C4GroupEntryCore - { + { public: C4GroupEntryCore(); - public: - char FileName[260]; - int32_t Packed,ChildGroup; - int32_t Size, __Unused, Offset; - uint32_t Time; + public: + char FileName[260]; + int32_t Packed,ChildGroup; + int32_t Size, __Unused, Offset; + uint32_t Time; char HasCRC; unsigned int CRC; char Executable; - BYTE fbuf[26]; - }; + BYTE fbuf[26]; + }; #pragma pack (pop) @@ -140,9 +140,9 @@ class C4GroupEntry: public C4GroupEntryCore public: C4GroupEntry(); ~C4GroupEntry(); - public: - char DiskPath[_MAX_PATH + 1]; - int Status; + public: + char DiskPath[_MAX_PATH + 1]; + int Status; bool DeleteOnDisk; bool HoldBuffer; bool BufferIsStdbuf; @@ -154,106 +154,106 @@ class C4GroupEntry: public C4GroupEntryCore }; const int GRPF_Inactive=0, - GRPF_File=1, - GRPF_Folder=2; + GRPF_File=1, + GRPF_Folder=2; class C4Group: public CStdStream - { - public: - C4Group(); - ~C4Group(); + { + public: + C4Group(); + ~C4Group(); - protected: - int Status; - char FileName[_MAX_PATH+1]; - // Parent status - C4Group *Mother; - bool ExclusiveChild; - // File & Folder - C4GroupEntry *SearchPtr; - CStdFile StdFile; + protected: + int Status; + char FileName[_MAX_PATH+1]; + // Parent status + C4Group *Mother; + bool ExclusiveChild; + // File & Folder + C4GroupEntry *SearchPtr; + CStdFile StdFile; size_t iCurrFileSize; // size of last accessed file - // File only - int FilePtr; - int MotherOffset; - int EntryOffset; - bool Modified; - C4GroupHeader Head; - C4GroupEntry *FirstEntry; - // Folder only - //struct _finddata_t Fdt; - //long hFdt; + // File only + int FilePtr; + int MotherOffset; + int EntryOffset; + bool Modified; + C4GroupHeader Head; + C4GroupEntry *FirstEntry; + // Folder only + //struct _finddata_t Fdt; + //long hFdt; DirectoryIterator FolderSearch; - C4GroupEntry FolderSearchEntry; - C4GroupEntry LastFolderSearchEntry; + C4GroupEntry FolderSearchEntry; + C4GroupEntry LastFolderSearchEntry; - bool StdOutput; + bool StdOutput; bool (*fnProcessCallback)(const char *, int); - char ErrorString[C4GroupMaxError+1]; + char ErrorString[C4GroupMaxError+1]; bool MadeOriginal; bool NoSort; // If this flag is set, all entries will be marked NoSort in AddEntry - public: + public: - bool Open(const char *szGroupName, bool fCreate=false); - bool Close(); + bool Open(const char *szGroupName, bool fCreate=false); + bool Close(); bool Save(bool fReOpen); - bool OpenAsChild(C4Group *pMother, const char *szEntryName, bool fExclusive=false, bool fCreate=false); + bool OpenAsChild(C4Group *pMother, const char *szEntryName, bool fExclusive=false, bool fCreate=false); bool OpenChild(const char* strEntry); bool OpenMother(); - bool Add(const char *szFiles); - bool Add(const char *szFile, const char *szAddAs); - bool Add(const char *szName, void *pBuffer, int iSize, bool fChild = false, bool fHoldBuffer = false, int iTime = 0, bool fExecutable = false); + bool Add(const char *szFiles); + bool Add(const char *szFile, const char *szAddAs); + bool Add(const char *szName, void *pBuffer, int iSize, bool fChild = false, bool fHoldBuffer = false, int iTime = 0, bool fExecutable = false); bool Add(const char *szName, StdBuf &pBuffer, bool fChild = false, bool fHoldBuffer = false, int iTime = 0, bool fExecutable = false); bool Add(const char *szName, StdStrBuf &pBuffer, bool fChild = false, bool fHoldBuffer = false, int iTime = 0, bool fExecutable = false); bool Add(const char *szEntryname, C4Group &hSource); - bool Merge(const char *szFolders); - bool Move(const char *szFiles); - bool Move(const char *szFile, const char *szAddAs); - bool Extract(const char *szFiles, const char *szExtractTo=NULL, const char *szExclude=NULL); - bool ExtractEntry(const char *szFilename, const char *szExtractTo=NULL); - bool Delete(const char *szFiles, bool fRecursive = false); - bool DeleteEntry(const char *szFilename, bool fRecycle=false); - bool Rename(const char *szFile, const char *szNewName); - bool Sort(const char *szSortList); + bool Merge(const char *szFolders); + bool Move(const char *szFiles); + bool Move(const char *szFile, const char *szAddAs); + bool Extract(const char *szFiles, const char *szExtractTo=NULL, const char *szExclude=NULL); + bool ExtractEntry(const char *szFilename, const char *szExtractTo=NULL); + bool Delete(const char *szFiles, bool fRecursive = false); + bool DeleteEntry(const char *szFilename, bool fRecycle=false); + bool Rename(const char *szFile, const char *szNewName); + bool Sort(const char *szSortList); bool SortByList(const char **ppSortList, const char *szFilename=NULL); - bool View(const char *szFiles); + bool View(const char *szFiles); bool GetOriginal(); - bool AccessEntry(const char *szWildCard, - size_t *iSize=NULL, char *sFileName=NULL, + bool AccessEntry(const char *szWildCard, + size_t *iSize=NULL, char *sFileName=NULL, bool *fChild=NULL, bool NeedsToBeAGroup = false); - bool AccessNextEntry(const char *szWildCard, - size_t *iSize=NULL, char *sFileName=NULL, + bool AccessNextEntry(const char *szWildCard, + size_t *iSize=NULL, char *sFileName=NULL, bool *fChild=NULL); - bool LoadEntry(const char *szEntryName, char **lpbpBuf, - size_t *ipSize=NULL, int iAppendZeros=0); - bool LoadEntry(const char *szEntryName, StdBuf &Buf); - bool LoadEntryString(const char *szEntryName, StdStrBuf &Buf); - bool FindEntry(const char *szWildCard, - char *sFileName=NULL, + bool LoadEntry(const char *szEntryName, char **lpbpBuf, + size_t *ipSize=NULL, int iAppendZeros=0); + bool LoadEntry(const char *szEntryName, StdBuf &Buf); + bool LoadEntryString(const char *szEntryName, StdStrBuf &Buf); + bool FindEntry(const char *szWildCard, + char *sFileName=NULL, size_t *iSize=NULL, bool *fChild=NULL); - bool FindNextEntry(const char *szWildCard, - char *sFileName=NULL, + bool FindNextEntry(const char *szWildCard, + char *sFileName=NULL, size_t *iSize=NULL, bool *fChild=NULL, bool fStartAtFilename=false); - bool Read(void *pBuffer, size_t iSize); + bool Read(void *pBuffer, size_t iSize); bool Advance(int iOffset); void SetMaker(const char *szMaker); void SetPassword(const char *szPassword); void SetStdOutput(bool fStatus); void SetProcessCallback(bool (*fnCallback)(const char *, int)); void MakeOriginal(bool fOriginal); - void ResetSearch(); - const char *GetError(); - const char *GetMaker(); - const char *GetPassword(); - const char *GetName(); + void ResetSearch(); + const char *GetError(); + const char *GetMaker(); + const char *GetPassword(); + const char *GetName(); StdStrBuf GetFullName() const; - int EntryCount(const char *szWildCard=NULL); - int EntrySize(const char *szWildCard=NULL); + int EntryCount(const char *szWildCard=NULL); + int EntrySize(const char *szWildCard=NULL); int AccessedEntrySize() { return iCurrFileSize; } // retrieve size of last accessed entry int EntryTime(const char *szFilename); unsigned int EntryCRC32(const char *szWildCard=NULL); @@ -269,39 +269,39 @@ class C4Group: public CStdStream void PrintInternals(const char *szIndent=NULL); #endif - protected: - void Init(); - void Default(); - void Clear(); + protected: + void Init(); + void Default(); + void Clear(); void ProcessOut(const char *szMessage, int iProcess=0); bool EnsureChildFilePtr(C4Group *pChild); bool CloseExclusiveMother(); - bool Error(const char *szStatus); - bool OpenReal(const char *szGroupName); - bool OpenRealGrpFile(); - bool SetFilePtr(int iOffset); - bool RewindFilePtr(); - bool AdvanceFilePtr(int iOffset, C4Group *pByChild=NULL); - bool AddEntry(int status, + bool Error(const char *szStatus); + bool OpenReal(const char *szGroupName); + bool OpenRealGrpFile(); + bool SetFilePtr(int iOffset); + bool RewindFilePtr(); + bool AdvanceFilePtr(int iOffset, C4Group *pByChild=NULL); + bool AddEntry(int status, bool childgroup, - const char *fname, + const char *fname, long size, time_t time, char cCRC, unsigned int iCRC, - const char *entryname = NULL, - BYTE *membuf = NULL, + const char *entryname = NULL, + BYTE *membuf = NULL, bool fDeleteOnDisk = false, bool fHoldBuffer = false, bool fExecutable = false, bool fBufferIsStdbuf = false); - bool AddEntryOnDisk(const char *szFilename, const char *szAddAs=NULL, bool fMove=false); - bool SetFilePtr2Entry(const char *szName, C4Group *pByChild=NULL, bool NeedsToBeAGroup = false); - bool AppendEntry2StdFile(C4GroupEntry *centry, CStdFile &stdfile); - C4GroupEntry *GetEntry(const char *szName); - C4GroupEntry *SearchNextEntry(const char *szName); - C4GroupEntry *GetNextFolderEntry(); + bool AddEntryOnDisk(const char *szFilename, const char *szAddAs=NULL, bool fMove=false); + bool SetFilePtr2Entry(const char *szName, C4Group *pByChild=NULL, bool NeedsToBeAGroup = false); + bool AppendEntry2StdFile(C4GroupEntry *centry, CStdFile &stdfile); + C4GroupEntry *GetEntry(const char *szName); + C4GroupEntry *SearchNextEntry(const char *szName); + C4GroupEntry *GetNextFolderEntry(); bool CalcCRC32(C4GroupEntry *pEntry); - }; + }; #endif diff --git a/src/c4group/C4Language.h b/src/c4group/C4Language.h index 427a47603..e39f8e572 100644 --- a/src/c4group/C4Language.h +++ b/src/c4group/C4Language.h @@ -48,16 +48,16 @@ class C4LanguageInfo class C4Language { - public: - C4Language(); - ~C4Language(); - protected: + public: + C4Language(); + ~C4Language(); + protected: C4Group PackDirectory; C4GroupSet Packs; C4GroupSet PackGroups; C4LanguageInfo* Infos; char PackGroupLocation[_MAX_FNAME + 1]; - public: + public: bool CloseGroup(const char *strPath); void ClearLanguage(); // Initialization diff --git a/src/c4group/C4Update.cpp b/src/c4group/C4Update.cpp index 102765c58..e26062c01 100644 --- a/src/c4group/C4Update.cpp +++ b/src/c4group/C4Update.cpp @@ -198,17 +198,17 @@ public: memcpy(&pCore->Time, &SavedCore.Time, (char *)&SavedCore + sizeof(SavedCore) - (char *)&SavedCore.Time); } - void SetEntryTime(const char *szEntry, int iEntryTime) - { + void SetEntryTime(const char *szEntry, int iEntryTime) + { C4GroupEntryCore *pCore = GetEntry(szEntry); - if(pCore) pCore->Time = iEntryTime; - } + if(pCore) pCore->Time = iEntryTime; + } - void SetNoSort(const char *szEntry) - { + void SetNoSort(const char *szEntry) + { C4GroupEntry *pEntry = GetEntry(szEntry); - if(pEntry) pEntry->NoSort = true; - } + if(pEntry) pEntry->NoSort = true; + } // close without header update bool Close(bool fHeaderUpdate) @@ -350,7 +350,7 @@ bool C4UpdatePackage::Execute(C4Group *pGroup) uint32_t iCRC32; if(!C4Group_GetFileCRC(TargetGrp.GetFullName().getData(), &iCRC32)) return false; - int i = 0; + int i = 0; for(; i < UpGrpCnt; i++) if(iCRC32 == GrpChks1[i]) break; @@ -463,7 +463,7 @@ int C4UpdatePackage::Check(C4Group *pGroup) // so there's nothing to do return C4UPD_CHK_ALREADY_UPDATED; // check if it's one of our registered sources - int i = 0; + int i = 0; for(; i < UpGrpCnt; i++) if(iCRC32 == GrpChks1[i]) break; @@ -521,7 +521,7 @@ bool C4UpdatePackage::DoUpdate(C4Group *pGrpFrom, C4GroupEx *pGrpTo, const char #ifdef _MSC_VER OutputDebugString(strMsg); #elif _DEBUG - puts(strMsg); + puts(strMsg); #endif if(!C4Group_CopyEntry(pGrpFrom, pGrpTo, strFileName)) return false; @@ -546,33 +546,33 @@ bool C4UpdatePackage::DoGrpUpdate(C4Group *pUpdateData, C4GroupEx *pGrpTo) { bool fGotIt = false; for(int i = 0; (fGotIt = SCopySegment(pData, i, strItemName2, '|', _MAX_FNAME)); i++) - { - // remove seperator - char *pSep = strchr(strItemName2, '='); - if(pSep) *pSep = '\0'; - // in list? + { + // remove seperator + char *pSep = strchr(strItemName2, '='); + if(pSep) *pSep = '\0'; + // in list? if(SEqual(strItemName, strItemName2)) break; - } + } if(!fGotIt) pGrpTo->DeleteEntry(strItemName); } - // set entry times, set sort list - char strSortList[32767] = ""; + // set entry times, set sort list + char strSortList[32767] = ""; for(int i = 0; SCopySegment(pData, i, strItemName, '|', _MAX_FNAME); i++) - { - // get time (if given) - char *pTime = strchr(strItemName, '='); - if(pTime) *pTime++ = '\0'; - // set - if(pTime) pGrpTo->SetEntryTime(strItemName, atoi(pTime)); + { + // get time (if given) + char *pTime = strchr(strItemName, '='); + if(pTime) *pTime++ = '\0'; + // set + if(pTime) pGrpTo->SetEntryTime(strItemName, atoi(pTime)); // update EntryCRC32. This will make updates to old groups invalid // however, it's needed so updates will update the EntryCRC of *unchanged* files correctly pGrpTo->EntryCRC32(strItemName); - // copy to sort list - SAppend(strItemName, strSortList); - SAppendChar('|', strSortList); - } + // copy to sort list + SAppend(strItemName, strSortList); + SAppendChar('|', strSortList); + } // sort by list pGrpTo->Sort(strSortList); delete[] pData; @@ -673,7 +673,7 @@ bool C4UpdatePackage::MakeUpdate(const char *strFile1, const char *strFile2, con // that would mess up the update result... { WriteLog("Error: could not add to update package - target groups don't match (checksum error)\n"); return false; } // already supported by this update? - int i = 0; + int i = 0; for(; i < UpGrpCnt; i++) if(GrpChks1[UpGrpCnt] == GrpChks1[i]) break; @@ -729,7 +729,7 @@ bool C4UpdatePackage::MkUp(C4Group *pGrp1, C4Group *pGrp2, C4GroupEx *pUpGrp, bo { // add to entry list if(!!EntryList) EntryList.AppendChar('|'); - EntryList.AppendFormat("%s=%d", strItemName, pGrp2->EntryTime(strItemName)); + EntryList.AppendFormat("%s=%d", strItemName, pGrp2->EntryTime(strItemName)); // no modification detected yet? then check order if(!*fModified) { diff --git a/src/c4group/C4Update.h b/src/c4group/C4Update.h index ff09937c6..bdcf4a589 100644 --- a/src/c4group/C4Update.h +++ b/src/c4group/C4Update.h @@ -31,7 +31,7 @@ class C4UpdatePackageCore public: C4UpdatePackageCore(); // ctor public: - int32_t RequireVersion[4]; + int32_t RequireVersion[4]; char Name[C4MaxName+1]; char DestPath[_MAX_PATH+1]; int32_t GrpUpdate; diff --git a/src/c4group/CStdFile.cpp b/src/c4group/CStdFile.cpp index 85c6b277e..6b9122ca9 100644 --- a/src/c4group/CStdFile.cpp +++ b/src/c4group/CStdFile.cpp @@ -34,20 +34,20 @@ #include CStdFile::CStdFile() - { - Status=false; - hFile=NULL; - hgzFile=NULL; + { + Status=false; + hFile=NULL; + hgzFile=NULL; pMemory=NULL; - ClearBuffer(); - ModeWrite=false; + ClearBuffer(); + ModeWrite=false; Name[0]=0; - } + } CStdFile::~CStdFile() - { - Close(); - } + { + Close(); + } bool CStdFile::Create(const char *szFilename, bool fCompressed, bool fExecutable, bool fMemory) { @@ -94,45 +94,45 @@ bool CStdFile::Create(const char *szFilename, bool fCompressed, bool fExecutable } bool CStdFile::Open(const char *szFilename, bool fCompressed) - { + { SCopy(szFilename,Name,_MAX_PATH); // Set modes - ModeWrite=false; + ModeWrite=false; // Open standard file if (fCompressed) { if (!(hgzFile=gzopen(Name,"rb"))) return false; } else { if (!(hFile=fopen(Name,"rb"))) return false; } // Reset buffer - ClearBuffer(); + ClearBuffer(); // Set status - Status=true; - return true; - } + Status=true; + return true; + } bool CStdFile::Append(const char *szFilename) - { + { SCopy(szFilename,Name,_MAX_PATH); // Set modes - ModeWrite=true; + ModeWrite=true; // Open standard file if (!(hFile=fopen(Name,"ab"))) return false; // Reset buffer - ClearBuffer(); + ClearBuffer(); // Set status - Status=true; - return true; - } + Status=true; + return true; + } bool CStdFile::Close(StdBuf **ppMemory) - { - bool rval=true; - Status=false; + { + bool rval=true; + Status=false; Name[0]=0; - // Save buffer if in write mode - if (ModeWrite && BufferLoad) if (!SaveBuffer()) rval=false; - // Close file(s) - if (hgzFile) if (gzclose(hgzFile)!=Z_OK) rval=false; + // Save buffer if in write mode + if (ModeWrite && BufferLoad) if (!SaveBuffer()) rval=false; + // Close file(s) + if (hgzFile) if (gzclose(hgzFile)!=Z_OK) rval=false; if (hFile) if (fclose(hFile)!=0) rval=false; if (pMemory) { @@ -144,11 +144,11 @@ bool CStdFile::Close(StdBuf **ppMemory) MemoryPtr=0; hgzFile=NULL; hFile=NULL; return !!rval; - } + } bool CStdFile::Default() { - Status=false; + Status=false; Name[0]=0; hgzFile=NULL; hFile=NULL; @@ -184,51 +184,51 @@ bool CStdFile::Read(void *pBuffer, size_t iSize, size_t *ipFSize) } int CStdFile::LoadBuffer() - { + { if (hFile) BufferLoad = fread(Buffer,1,CStdFileBufSize,hFile); - if (hgzFile) BufferLoad = gzread(hgzFile, Buffer,CStdFileBufSize); - BufferPtr=0; - return BufferLoad; - } + if (hgzFile) BufferLoad = gzread(hgzFile, Buffer,CStdFileBufSize); + BufferPtr=0; + return BufferLoad; + } bool CStdFile::SaveBuffer() - { - int saved = 0; + { + int saved = 0; if (hFile) saved=fwrite(Buffer,1,BufferLoad,hFile); if (hgzFile) saved=gzwrite(hgzFile,Buffer,BufferLoad); if (pMemory) { pMemory->Append(Buffer, BufferLoad); saved = BufferLoad; } if (saved!=BufferLoad) return false; BufferLoad=0; return true; - } + } void CStdFile::ClearBuffer() - { - BufferLoad=BufferPtr=0; - } + { + BufferLoad=BufferPtr=0; + } bool CStdFile::Write(const void *pBuffer, int iSize) - { - int transfer; - if (!pBuffer) return false; - if (!ModeWrite) return false; - BYTE *bypBuffer= (BYTE*) pBuffer; - while (iSize>0) - { - // Space in buffer: Transfer as much as possible - if (BufferLoad0) + { + // Space in buffer: Transfer as much as possible + if (BufferLoad=argc) || (argv[iArg+1][0]=='-')) - printf("Missing argument for add command\n"); - else - { - if ((argv[iArg][2]=='s') || (argv[iArg][2] && (argv[iArg][3]=='s')) ) - { - if ((iArg+2>=argc) || (argv[iArg+2][0]=='-')) - printf("Missing argument for add as command\n"); - else - { hGroup.Add(argv[iArg+1],argv[iArg+2]); iArg+=2; } - } - else + case 'a': + if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) + printf("Missing argument for add command\n"); + else + { + if ((argv[iArg][2]=='s') || (argv[iArg][2] && (argv[iArg][3]=='s')) ) + { + if ((iArg+2>=argc) || (argv[iArg+2][0]=='-')) + printf("Missing argument for add as command\n"); + else + { hGroup.Add(argv[iArg+1],argv[iArg+2]); iArg+=2; } + } + else #ifdef _WIN32 - { hGroup.Add(argv[iArg+1]); iArg++; } + { hGroup.Add(argv[iArg+1]); iArg++; } #else - { hGroup.Add(argv[iArg+1], argv[iArg+1]); iArg++; } + { hGroup.Add(argv[iArg+1], argv[iArg+1]); iArg++; } #endif - } - break; + } + break; // Move - case 'm': - if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) - printf("Missing argument for move command\n"); - else + case 'm': + if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) + printf("Missing argument for move command\n"); + else #ifdef _WIN32 { hGroup.Move(argv[iArg+1]); iArg++; } #else { hGroup.Move(argv[iArg+1], argv[iArg+1]); iArg++; } #endif - break; + break; // Extract - case 'e': - if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) - printf("Missing argument for extract command\n"); - else - { - if ((argv[iArg][2]=='t') || (argv[iArg][2] && (argv[iArg][3]=='s')) ) - { - if ((iArg+2>=argc) || (argv[iArg+2][0]=='-')) - printf("Missing argument for extract as command\n"); - else - { hGroup.Extract(argv[iArg+1],argv[iArg+2]); iArg+=2; } - } - else - { hGroup.Extract(argv[iArg+1]); iArg++; } - } - break; + case 'e': + if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) + printf("Missing argument for extract command\n"); + else + { + if ((argv[iArg][2]=='t') || (argv[iArg][2] && (argv[iArg][3]=='s')) ) + { + if ((iArg+2>=argc) || (argv[iArg+2][0]=='-')) + printf("Missing argument for extract as command\n"); + else + { hGroup.Extract(argv[iArg+1],argv[iArg+2]); iArg+=2; } + } + else + { hGroup.Extract(argv[iArg+1]); iArg++; } + } + break; // Delete - case 'd': - if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) - printf("Missing argument for delete command\n"); - else - { hGroup.Delete(argv[iArg+1], fRecursive); iArg++; } - break; + case 'd': + if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) + printf("Missing argument for delete command\n"); + else + { hGroup.Delete(argv[iArg+1], fRecursive); iArg++; } + break; // Sort - case 's': + case 's': // First sort parameter overrides default Clonk sort list C4Group_SetSortList(NULL); // Missing argument - if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) - printf("Missing argument for sort command\n"); + if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) + printf("Missing argument for sort command\n"); // Sort, advance to next argument - else - { hGroup.Sort(argv[iArg+1]); iArg++; } - break; + else + { hGroup.Sort(argv[iArg+1]); iArg++; } + break; // Rename - case 'r': - if ((iArg+2>=argc) || (argv[iArg+1][0]=='-') || (argv[iArg+2][0]=='-')) - printf("Missing argument(s) for rename command\n"); - else - { hGroup.Rename(argv[iArg+1],argv[iArg+2]); iArg+=2; } - break; + case 'r': + if ((iArg+2>=argc) || (argv[iArg+1][0]=='-') || (argv[iArg+2][0]=='-')) + printf("Missing argument(s) for rename command\n"); + else + { hGroup.Rename(argv[iArg+1],argv[iArg+2]); iArg+=2; } + break; // View - case 'v': - if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) - { hGroup.View("*"); } - else - { hGroup.View(argv[iArg+1]); iArg++; } - break; + case 'v': + if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) + { hGroup.View("*"); } + else + { hGroup.View(argv[iArg+1]); iArg++; } + break; // Make original - case 'o': - hGroup.MakeOriginal(true); - break; + case 'o': + hGroup.MakeOriginal(true); + break; // Pack - case 'p': + case 'p': printf("Packing...\n"); - // Close + // Close if (!hGroup.Close()) printf("Closing failed: %s\n",hGroup.GetError()); // Pack else if (!C4Group_PackDirectory(szFilename)) printf("Pack failed\n"); // Reopen else if (!hGroup.Open(szFilename)) printf("Reopen failed: %s\n",hGroup.GetError()); - break; + break; // Unpack - case 'u': + case 'u': printf("Unpacking...\n"); - // Close + // Close if (!hGroup.Close()) printf("Closing failed: %s\n",hGroup.GetError()); // Unpack else if (!C4Group_UnpackDirectory(szFilename)) printf("Unpack failed\n"); // Reopen else if (!hGroup.Open(szFilename)) printf("Reopen failed: %s\n",hGroup.GetError()); - break; + break; // Unpack - case 'x': + case 'x': printf("Exploding...\n"); - // Close + // Close if (!hGroup.Close()) printf("Closing failed: %s\n",hGroup.GetError()); // Explode else if (!C4Group_ExplodeDirectory(szFilename)) printf("Unpack failed\n"); // Reopen else if (!hGroup.Open(szFilename)) printf("Reopen failed: %s\n",hGroup.GetError()); - break; + break; // Print maker - case 'k': + case 'k': printf("%s\n",hGroup.GetMaker()); - break; + break; // Generate update case 'g': - if ((iArg + 3 >= argc) || (argv[iArg+1][0] == '-') || (argv[iArg+2][0] == '-') || (argv[iArg+3][0] == '-')) + if ((iArg + 3 >= argc) || (argv[iArg+1][0] == '-') || (argv[iArg+2][0] == '-') || (argv[iArg+3][0] == '-')) printf("Update generation failed: too few arguments\n"); else { @@ -261,11 +261,11 @@ bool ProcessGroup(const char *szFilename) break; // Optimize update generation target case 'z': - if ((iArg + 1 >= argc) || (argv[iArg+1][0] == '-')) + if ((iArg + 1 >= argc) || (argv[iArg+1][0] == '-')) printf("Missing parameter for optimization\n"); else { - printf("Optimizing %s...\n", argv[iArg+1]); + printf("Optimizing %s...\n", argv[iArg+1]); if(!C4UpdatePackage::Optimize(&hGroup, argv[iArg+1])) printf("Optimization failed.\n"); iArg++; @@ -278,11 +278,11 @@ bool ProcessGroup(const char *szFilename) break; #endif // Wait - case 'w': - if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) - printf("Missing argument for wait command\n"); - else - { + case 'w': + if ((iArg+1>=argc) || (argv[iArg+1][0]=='-')) + printf("Missing argument for wait command\n"); + else + { int iMilliseconds = 0; sscanf(argv[iArg+1], "%d", &iMilliseconds); // Wait for specified time @@ -303,28 +303,28 @@ bool ProcessGroup(const char *szFilename) printf("\n"); } iArg++; - } - break; - // Undefined - default: - printf("Unknown command: %s\n",argv[iArg]); - break; - } - } - else - { - printf("Invalid parameter %s\n",argv[iArg]); - } + } + break; + // Undefined + default: + printf("Unknown command: %s\n",argv[iArg]); + break; + } + } + else + { + printf("Invalid parameter %s\n",argv[iArg]); + } - } + } // Error: output status if (!SEqual(hGroup.GetError(),"No Error")) printf("Status: %s\n",hGroup.GetError()); - // Close group file - if (!hGroup.Close()) - printf("Closing: %s\n",hGroup.GetError()); + // Close group file + if (!hGroup.Close()) + printf("Closing: %s\n",hGroup.GetError()); // Delete group file if desired (i.e. after apply update) if (fDeleteGroup) @@ -333,13 +333,13 @@ bool ProcessGroup(const char *szFilename) EraseItem(szFilename); } - } + } // Couldn't open group - else - { - printf("Status: %s\n",hGroup.GetError()); - } + else + { + printf("Status: %s\n",hGroup.GetError()); + } // Done return true; @@ -405,7 +405,7 @@ int UnregisterShellExtensions() bool Log(const char *msg) { - if (!fQuiet) + if (!fQuiet) printf("%s\n", msg); return 1; } @@ -433,7 +433,7 @@ void StdCompilerWarnCallback(void *pData, const char *szPosition, const char *sz int main(int argc, char *argv[]) - { + { // Scan options (scan including first parameter - this means the group filename cannot start with a '/'...) for (int i = 1; i < argc; i++) @@ -506,18 +506,18 @@ int main(int argc, char *argv[]) printf("Error removing shell extensions.\n"); // At least one parameter (filename, not option or command): process file(s) - if ((argc>1) && (argv[1][0] != '/') && (argv[1][0] != '-')) // ...remember filenames cannot start with a forward slash because of options format - { + if ((argc>1) && (argv[1][0] != '/') && (argv[1][0] != '-')) // ...remember filenames cannot start with a forward slash because of options format + { // Wildcard in filename: use file search if (SCharCount('*',argv[1])) ForEachFile(argv[1], &ProcessGroup); // Only one file else ProcessGroup(argv[1]); - } + } // Too few parameters: output help (if we didn't register stuff) - else + else if (!fRegisterShell && !fUnregisterShell) { printf("\n"); @@ -568,6 +568,6 @@ int main(int argc, char *argv[]) } // Done - return iResult; + return iResult; - } + } diff --git a/src/c4group/c4group_ng.cpp b/src/c4group/c4group_ng.cpp index 73446cb49..2f5af7cb3 100644 --- a/src/c4group/c4group_ng.cpp +++ b/src/c4group/c4group_ng.cpp @@ -57,13 +57,13 @@ char strExecuteAtEnd[_MAX_PATH + 1] = ""; int iResult = 0; bool EraseItemSafe(const char *szFilename) { - return false; + return false; } bool Log(const char *msg) { - if (!fQuiet) - printf("%s\n", msg); - return 1; + if (!fQuiet) + printf("%s\n", msg); + return 1; } #define IMPLEMENT_LOGF(func) \ bool func(const char *msg, ...) { \ @@ -79,443 +79,443 @@ IMPLEMENT_LOGF(LogSilentF) bool ProcessGroup(const char *FilenamePar) { - C4Group hGroup; - hGroup.SetStdOutput(!fQuiet); + C4Group hGroup; + hGroup.SetStdOutput(!fQuiet); bool fDeleteGroup = false; - int argc = globalArgC; - char **argv = globalArgV; + int argc = globalArgC; + char **argv = globalArgV; - // Strip trailing slash - char * szFilename = strdup(FilenamePar); - size_t len = strlen(szFilename); - if (szFilename[len-1] == DirectorySeparator) szFilename[len-1] = 0; - // Current filename - LogF("Group: %s", szFilename); + // Strip trailing slash + char * szFilename = strdup(FilenamePar); + size_t len = strlen(szFilename); + if (szFilename[len-1] == DirectorySeparator) szFilename[len-1] = 0; + // Current filename + LogF("Group: %s", szFilename); - // Open group file - if (hGroup.Open(szFilename, true)) { - // No commands: display contents - if (iFirstCommand >= argc) { - hGroup.SetStdOutput(true); + // Open group file + if (hGroup.Open(szFilename, true)) { + // No commands: display contents + if (iFirstCommand >= argc) { + hGroup.SetStdOutput(true); hGroup.View("*"); - hGroup.SetStdOutput(!fQuiet); - } - // Process commands - else { - for (int iArg = iFirstCommand; iArg < argc; ++iArg) { - // This argument is a command - if (argv[iArg][0] == '-') { + hGroup.SetStdOutput(!fQuiet); + } + // Process commands + else { + for (int iArg = iFirstCommand; iArg < argc; ++iArg) { + // This argument is a command + if (argv[iArg][0] == '-') { // Handle commands - switch (argv[iArg][1]) { - // Add - case 'a': - if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) - fprintf(stderr, "Missing argument for add command\n"); - else { - if ((argv[iArg][2] == 's') || (argv[iArg][2] && (argv[iArg][3] == 's'))) { - if ((iArg + 2 >= argc) || (argv[iArg + 2][0] == '-')) { - fprintf(stderr, "Missing argument for add as command\n"); - } else { - hGroup.Add(argv[iArg + 1], argv[iArg + 2]); - iArg += 2; - } - } else { - while (iArg + 1 < argc && argv[iArg + 1][0] != '-') { - ++iArg; + switch (argv[iArg][1]) { + // Add + case 'a': + if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) + fprintf(stderr, "Missing argument for add command\n"); + else { + if ((argv[iArg][2] == 's') || (argv[iArg][2] && (argv[iArg][3] == 's'))) { + if ((iArg + 2 >= argc) || (argv[iArg + 2][0] == '-')) { + fprintf(stderr, "Missing argument for add as command\n"); + } else { + hGroup.Add(argv[iArg + 1], argv[iArg + 2]); + iArg += 2; + } + } else { + while (iArg + 1 < argc && argv[iArg + 1][0] != '-') { + ++iArg; #ifdef _WIN32 - // manually expand wildcards - hGroup.Add(argv[iArg]); + // manually expand wildcards + hGroup.Add(argv[iArg]); #else - hGroup.Add(argv[iArg], GetFilename(argv[iArg])); + hGroup.Add(argv[iArg], GetFilename(argv[iArg])); #endif - } - } - } - break; - // Move - case 'm': - if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { - fprintf(stderr, "Missing argument for move command\n"); - } else { - while (iArg + 1 < argc && argv[iArg + 1][0] != '-') { - ++iArg; + } + } + } + break; + // Move + case 'm': + if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { + fprintf(stderr, "Missing argument for move command\n"); + } else { + while (iArg + 1 < argc && argv[iArg + 1][0] != '-') { + ++iArg; #ifdef _WIN32 - // manually expand wildcards - hGroup.Move(argv[iArg]); + // manually expand wildcards + hGroup.Move(argv[iArg]); #else - hGroup.Move(argv[iArg], argv[iArg]); + hGroup.Move(argv[iArg], argv[iArg]); #endif - } - } - break; - // Extract - case 'e': - if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { - fprintf(stderr, "Missing argument for extract command\n"); - } else { - if ((argv[iArg][2] == 't') || (argv[iArg][2] && (argv[iArg][3] == 's'))) { - if ((iArg + 2 >= argc) || (argv[iArg + 2][0] == '-')) { - fprintf(stderr, "Missing argument for extract as command\n"); - } else { - hGroup.Extract(argv[iArg + 1], argv[iArg + 2]); - iArg += 2; - } - } else { - hGroup.Extract(argv[iArg + 1]); - iArg++; - } - } - break; - // Delete - case 'd': - if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { - fprintf(stderr, "Missing argument for delete command\n"); - } else { - hGroup.Delete(argv[iArg + 1], fRecursive); - iArg++; - } - break; - // Sort - case 's': - // First sort parameter overrides default Clonk sort list - C4Group_SetSortList(NULL); - // Missing argument - if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { - fprintf(stderr, "Missing argument for sort command\n"); - } - // Sort, advance to next argument - else { - hGroup.Sort(argv[iArg + 1]); - iArg++; - } - break; - // Rename - case 'r': - if ((iArg + 2 >= argc) || (argv[iArg + 1][0] == '-') - || (argv[iArg + 2][0] == '-')) { - fprintf(stderr, "Missing argument(s) for rename command\n"); - } else { - hGroup.Rename(argv[iArg + 1], argv[iArg + 2]); - iArg += 2; - } - break; - // View - case 'l': - hGroup.SetStdOutput(true); - if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { - hGroup.View("*"); - } else { - hGroup.View(argv[iArg + 1]); - iArg++; - } - hGroup.SetStdOutput(!fQuiet); - break; - // Make original - case 'o': - hGroup.MakeOriginal(true); - break; - // Pack - case 'p': - Log("Packing..."); - // Close - if (!hGroup.Close()) { - fprintf(stderr, "Closing failed: %s\n", hGroup.GetError()); - } - // Pack - else if (!C4Group_PackDirectory(szFilename)) { - fprintf(stderr, "Pack failed\n"); - } - // Reopen - else if (!hGroup.Open(szFilename)) { - fprintf(stderr, "Reopen failed: %s\n", hGroup.GetError()); - } - break; - // Unpack - case 'u': - LogF("Unpacking..."); - // Close - if (!hGroup.Close()) { - fprintf(stderr, "Closing failed: %s\n", hGroup.GetError()); - } - // Pack - else if (!C4Group_UnpackDirectory(szFilename)) { - fprintf(stderr, "Unpack failed\n"); - } - // Reopen - else if (!hGroup.Open(szFilename)) { - fprintf(stderr, "Reopen failed: %s\n", hGroup.GetError()); - } - break; - // Unpack - case 'x': - Log("Exploding..."); - // Close - if (!hGroup.Close()) { - fprintf(stderr, "Closing failed: %s\n", hGroup.GetError()); - } - // Pack - else if (!C4Group_ExplodeDirectory(szFilename)) { - fprintf(stderr, "Unpack failed\n"); - } - // Reopen - else if (!hGroup.Open(szFilename)) { - fprintf(stderr, "Reopen failed: %s\n", hGroup.GetError()); - } - break; - // Print maker - case 'k': - printf("%s\n", hGroup.GetMaker()); - break; - // Generate update - case 'g': - if ((iArg + 3 >= argc) || (argv[iArg + 1][0] == '-') - || (argv[iArg + 2][0] == '-') - || (argv[iArg + 3][0] == '-')) { - fprintf(stderr, "Update generation failed: too few arguments\n"); - } else { - C4UpdatePackage Upd; - // Close - if (!hGroup.Close()) { - fprintf(stderr, "Closing failed: %s\n", hGroup.GetError()); - } - // generate - else if (!Upd.MakeUpdate(argv[iArg + 1], argv[iArg + 2], szFilename, argv[iArg + 3])) { - fprintf(stderr, "Update generation failed.\n"); - } - // Reopen - else if (!hGroup.Open(szFilename)) { - fprintf(stderr, "Reopen failed: %s\n", hGroup.GetError()); - } - iArg += 3; - } - break; + } + } + break; + // Extract + case 'e': + if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { + fprintf(stderr, "Missing argument for extract command\n"); + } else { + if ((argv[iArg][2] == 't') || (argv[iArg][2] && (argv[iArg][3] == 's'))) { + if ((iArg + 2 >= argc) || (argv[iArg + 2][0] == '-')) { + fprintf(stderr, "Missing argument for extract as command\n"); + } else { + hGroup.Extract(argv[iArg + 1], argv[iArg + 2]); + iArg += 2; + } + } else { + hGroup.Extract(argv[iArg + 1]); + iArg++; + } + } + break; + // Delete + case 'd': + if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { + fprintf(stderr, "Missing argument for delete command\n"); + } else { + hGroup.Delete(argv[iArg + 1], fRecursive); + iArg++; + } + break; + // Sort + case 's': + // First sort parameter overrides default Clonk sort list + C4Group_SetSortList(NULL); + // Missing argument + if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { + fprintf(stderr, "Missing argument for sort command\n"); + } + // Sort, advance to next argument + else { + hGroup.Sort(argv[iArg + 1]); + iArg++; + } + break; + // Rename + case 'r': + if ((iArg + 2 >= argc) || (argv[iArg + 1][0] == '-') + || (argv[iArg + 2][0] == '-')) { + fprintf(stderr, "Missing argument(s) for rename command\n"); + } else { + hGroup.Rename(argv[iArg + 1], argv[iArg + 2]); + iArg += 2; + } + break; + // View + case 'l': + hGroup.SetStdOutput(true); + if ((iArg + 1 >= argc) || (argv[iArg + 1][0] == '-')) { + hGroup.View("*"); + } else { + hGroup.View(argv[iArg + 1]); + iArg++; + } + hGroup.SetStdOutput(!fQuiet); + break; + // Make original + case 'o': + hGroup.MakeOriginal(true); + break; + // Pack + case 'p': + Log("Packing..."); + // Close + if (!hGroup.Close()) { + fprintf(stderr, "Closing failed: %s\n", hGroup.GetError()); + } + // Pack + else if (!C4Group_PackDirectory(szFilename)) { + fprintf(stderr, "Pack failed\n"); + } + // Reopen + else if (!hGroup.Open(szFilename)) { + fprintf(stderr, "Reopen failed: %s\n", hGroup.GetError()); + } + break; + // Unpack + case 'u': + LogF("Unpacking..."); + // Close + if (!hGroup.Close()) { + fprintf(stderr, "Closing failed: %s\n", hGroup.GetError()); + } + // Pack + else if (!C4Group_UnpackDirectory(szFilename)) { + fprintf(stderr, "Unpack failed\n"); + } + // Reopen + else if (!hGroup.Open(szFilename)) { + fprintf(stderr, "Reopen failed: %s\n", hGroup.GetError()); + } + break; + // Unpack + case 'x': + Log("Exploding..."); + // Close + if (!hGroup.Close()) { + fprintf(stderr, "Closing failed: %s\n", hGroup.GetError()); + } + // Pack + else if (!C4Group_ExplodeDirectory(szFilename)) { + fprintf(stderr, "Unpack failed\n"); + } + // Reopen + else if (!hGroup.Open(szFilename)) { + fprintf(stderr, "Reopen failed: %s\n", hGroup.GetError()); + } + break; + // Print maker + case 'k': + printf("%s\n", hGroup.GetMaker()); + break; + // Generate update + case 'g': + if ((iArg + 3 >= argc) || (argv[iArg + 1][0] == '-') + || (argv[iArg + 2][0] == '-') + || (argv[iArg + 3][0] == '-')) { + fprintf(stderr, "Update generation failed: too few arguments\n"); + } else { + C4UpdatePackage Upd; + // Close + if (!hGroup.Close()) { + fprintf(stderr, "Closing failed: %s\n", hGroup.GetError()); + } + // generate + else if (!Upd.MakeUpdate(argv[iArg + 1], argv[iArg + 2], szFilename, argv[iArg + 3])) { + fprintf(stderr, "Update generation failed.\n"); + } + // Reopen + else if (!hGroup.Open(szFilename)) { + fprintf(stderr, "Reopen failed: %s\n", hGroup.GetError()); + } + iArg += 3; + } + break; - // Apply an update - case 'y': - Log("Applying update..."); - if (C4Group_ApplyUpdate(hGroup)) + // Apply an update + case 'y': + Log("Applying update..."); + if (C4Group_ApplyUpdate(hGroup)) { if (argv[iArg][2]=='d') fDeleteGroup = true; } else - fprintf(stderr,"Update failed.\n"); - break; + fprintf(stderr,"Update failed.\n"); + break; #ifdef _DEBUG - case 'z': - hGroup.PrintInternals(); - break; + case 'z': + hGroup.PrintInternals(); + break; #endif - // Undefined - default: - fprintf(stderr, "Unknown command: %s\n", argv[iArg]); - break; - } - } else { - fprintf(stderr, "Invalid parameter %s\n", argv[iArg]); - } + // Undefined + default: + fprintf(stderr, "Unknown command: %s\n", argv[iArg]); + break; + } + } else { + fprintf(stderr, "Invalid parameter %s\n", argv[iArg]); + } - } - } - // Error: output status - if (!SEqual(hGroup.GetError(), "No Error")) { - fprintf(stderr, "Status: %s\n", hGroup.GetError()); - } - // Close group file - if (!hGroup.Close()) { - fprintf(stderr, "Closing: %s\n", hGroup.GetError()); - } + } + } + // Error: output status + if (!SEqual(hGroup.GetError(), "No Error")) { + fprintf(stderr, "Status: %s\n", hGroup.GetError()); + } + // Close group file + if (!hGroup.Close()) { + fprintf(stderr, "Closing: %s\n", hGroup.GetError()); + } // Delete group file if desired (i.e. after apply update) if (fDeleteGroup) { LogF("Deleting %s...\n", GetFilename(szFilename)); EraseItem(szFilename); } - } - // Couldn't open group - else { - fprintf(stderr, "Status: %s\n", hGroup.GetError()); - } - free(szFilename); - // Done - return true; + } + // Couldn't open group + else { + fprintf(stderr, "Status: %s\n", hGroup.GetError()); + } + free(szFilename); + // Done + return true; } int RegisterShellExtensions() { #ifdef _WIN32 - char strModule[2048]; - char strCommand[2048]; - char strClass[128]; - int i; - GetModuleFileName(NULL, strModule, 2048); - // Groups - const char *strClasses = - "Clonk4.Definition;Clonk4.Folder;Clonk4.Group;Clonk4.Player;Clonk4.Scenario;Clonk4.Update;Clonk4.Weblink"; - for (i = 0; SCopySegment(strClasses, i, strClass); i++) { - // Unpack - sprintf(strCommand, "\"%s\" \"%%1\" \"-u\"", strModule); - if (!SetRegShell(strClass, "MakeFolder", "C4Group Unpack", strCommand)) - return 0; - // Explode - sprintf(strCommand, "\"%s\" \"%%1\" \"-x\"", strModule); - if (!SetRegShell(strClass, "ExplodeFolder", "C4Group Explode", strCommand)) - return 0; - } - // Directories - const char *strClasses2 = "Directory"; - for (i = 0; SCopySegment(strClasses2, i, strClass); i++) { - // Pack - sprintf(strCommand, "\"%s\" \"%%1\" \"-p\"", strModule); - if (!SetRegShell(strClass, "MakeGroupFile", "C4Group Pack", strCommand)) - return 0; - } - // Done + char strModule[2048]; + char strCommand[2048]; + char strClass[128]; + int i; + GetModuleFileName(NULL, strModule, 2048); + // Groups + const char *strClasses = + "Clonk4.Definition;Clonk4.Folder;Clonk4.Group;Clonk4.Player;Clonk4.Scenario;Clonk4.Update;Clonk4.Weblink"; + for (i = 0; SCopySegment(strClasses, i, strClass); i++) { + // Unpack + sprintf(strCommand, "\"%s\" \"%%1\" \"-u\"", strModule); + if (!SetRegShell(strClass, "MakeFolder", "C4Group Unpack", strCommand)) + return 0; + // Explode + sprintf(strCommand, "\"%s\" \"%%1\" \"-x\"", strModule); + if (!SetRegShell(strClass, "ExplodeFolder", "C4Group Explode", strCommand)) + return 0; + } + // Directories + const char *strClasses2 = "Directory"; + for (i = 0; SCopySegment(strClasses2, i, strClass); i++) { + // Pack + sprintf(strCommand, "\"%s\" \"%%1\" \"-p\"", strModule); + if (!SetRegShell(strClass, "MakeGroupFile", "C4Group Pack", strCommand)) + return 0; + } + // Done #endif - return 1; + return 1; } int UnregisterShellExtensions() { #ifdef _WIN32 - char strModule[2048]; - char strClass[128]; - int i; - GetModuleFileName(NULL, strModule, 2048); - // Groups - const char *strClasses = - "Clonk4.Definition;Clonk4.Folder;Clonk4.Group;Clonk4.Player;Clonk4.Scenario;Clonk4.Update;Clonk4.Weblink"; - for (i = 0; SCopySegment(strClasses, i, strClass); i++) { - // Unpack - if (!RemoveRegShell(strClass, "MakeFolder")) - return 0; - // Explode - if (!RemoveRegShell(strClass, "ExplodeFolder")) - return 0; - } - // Directories - const char *strClasses2 = "Directory"; - for (i = 0; SCopySegment(strClasses2, i, strClass); i++) { - // Pack - if (!RemoveRegShell(strClass, "MakeGroupFile")) - return 0; - } - // Done + char strModule[2048]; + char strClass[128]; + int i; + GetModuleFileName(NULL, strModule, 2048); + // Groups + const char *strClasses = + "Clonk4.Definition;Clonk4.Folder;Clonk4.Group;Clonk4.Player;Clonk4.Scenario;Clonk4.Update;Clonk4.Weblink"; + for (i = 0; SCopySegment(strClasses, i, strClass); i++) { + // Unpack + if (!RemoveRegShell(strClass, "MakeFolder")) + return 0; + // Explode + if (!RemoveRegShell(strClass, "ExplodeFolder")) + return 0; + } + // Directories + const char *strClasses2 = "Directory"; + for (i = 0; SCopySegment(strClasses2, i, strClass); i++) { + // Pack + if (!RemoveRegShell(strClass, "MakeGroupFile")) + return 0; + } + // Done #endif - return 1; + return 1; } int main(int argc, char *argv[]) { #ifndef WIN32 - // Always line buffer mode, even if the output is not sent to a terminal + // Always line buffer mode, even if the output is not sent to a terminal setvbuf(stdout, NULL, _IOLBF, 0); #endif - // Scan options - int iFirstGroup = 0; - for (int i = 1; i < argc; ++i) { - // Option encountered - if (argv[i][0] == '-') { - switch (argv[i][1]) { - // Quiet mode - case 'v': - fQuiet = false; - break; - // Silent mode - //case 's': fSilent=true; break; - // Recursive mode - case 'r': - fRecursive = true; - break; - // Register shell - case 'i': - fRegisterShell = true; - break; - // Unregister shell - case 'u': - fUnregisterShell = true; - break; + // Scan options + int iFirstGroup = 0; + for (int i = 1; i < argc; ++i) { + // Option encountered + if (argv[i][0] == '-') { + switch (argv[i][1]) { + // Quiet mode + case 'v': + fQuiet = false; + break; + // Silent mode + //case 's': fSilent=true; break; + // Recursive mode + case 'r': + fRecursive = true; + break; + // Register shell + case 'i': + fRegisterShell = true; + break; + // Unregister shell + case 'u': + fUnregisterShell = true; + break; // Execute at end case 'x': SCopy(argv[i] + 3, strExecuteAtEnd, _MAX_PATH); break; - // Unknown - default: - fprintf(stderr, "Unknown option %s\n", argv[i]); - break; - } - } else { - // filename encountered: no more options expected - iFirstGroup = i; - break; - } - } - iFirstCommand = iFirstGroup; - while (iFirstCommand < argc && argv[iFirstCommand][0] != '-') - ++iFirstCommand; + // Unknown + default: + fprintf(stderr, "Unknown option %s\n", argv[i]); + break; + } + } else { + // filename encountered: no more options expected + iFirstGroup = i; + break; + } + } + iFirstCommand = iFirstGroup; + while (iFirstCommand < argc && argv[iFirstCommand][0] != '-') + ++iFirstCommand; - // Program info - LogF("RedWolf Design C4Group %s", C4VERSION); + // Program info + LogF("RedWolf Design C4Group %s", C4VERSION); - // Registration check + // Registration check /* Config.Init(); - Config.Load(false);*/ + Config.Load(false);*/ - // Init C4Group + // Init C4Group /* C4Group_SetMaker(Config.General.Name); - C4Group_SetTempPath(Config.General.TempPath);*/ - C4Group_SetSortList(C4CFN_FLS); + C4Group_SetTempPath(Config.General.TempPath);*/ + C4Group_SetSortList(C4CFN_FLS); - // Store command line parameters - globalArgC = argc; - globalArgV = argv; + // Store command line parameters + globalArgC = argc; + globalArgV = argv; - // Register shell - if (fRegisterShell) { - if (RegisterShellExtensions()) - printf("Shell extensions registered.\n"); - else - printf("Error registering shell extensions.\n"); - } - // Unregister shell - if (fUnregisterShell) { - if (UnregisterShellExtensions()) - printf("Shell extensions removed.\n"); - else - printf("Error removing shell extensions.\n"); - } + // Register shell + if (fRegisterShell) { + if (RegisterShellExtensions()) + printf("Shell extensions registered.\n"); + else + printf("Error registering shell extensions.\n"); + } + // Unregister shell + if (fUnregisterShell) { + if (UnregisterShellExtensions()) + printf("Shell extensions removed.\n"); + else + printf("Error removing shell extensions.\n"); + } - // At least one parameter (filename, not option or command): process file(s) - if (iFirstGroup) { + // At least one parameter (filename, not option or command): process file(s) + if (iFirstGroup) { #ifdef _WIN32 - // Wildcard in filename: use file search - if (SCharCount('*', argv[1])) - ForEachFile(argv[1], &ProcessGroup); - // Only one file - else - ProcessGroup(argv[1]); + // Wildcard in filename: use file search + if (SCharCount('*', argv[1])) + ForEachFile(argv[1], &ProcessGroup); + // Only one file + else + ProcessGroup(argv[1]); #else - for (int i = iFirstGroup; i < argc && argv[i][0] != '-'; ++i) - ProcessGroup(argv[i]); + for (int i = iFirstGroup; i < argc && argv[i][0] != '-'; ++i) + ProcessGroup(argv[i]); #endif - } - // Too few parameters: output help (if we didn't register stuff) - else if (!fRegisterShell && !fUnregisterShell) { - printf("\n"); - printf("Usage: c4group [options] group(s) command(s)\n\n"); - printf("Commands: -a[s] Add [as] -m Move -e[t] Extract [to]\n"); - printf(" -l List -d Delete -r Rename -s Sort\n"); - printf(" -p Pack -u Unpack -x Explode\n"); - printf(" -k Print maker\n"); - printf(" -g [source] [target] [title] Make update\n"); - printf(" -y Apply update\n"); - printf("\n"); - printf("Options: -v Verbose -r Recursive\n"); - printf(" -i Register shell -u Unregister shell\n"); - printf(" -x: Execute shell command when done\n"); - printf("\n"); - printf("Examples: c4group pack.c4g -a myfile.dat -l \"*.dat\"\n"); - printf(" c4group pack.c4g -as myfile.dat myfile.bin\n"); - printf(" c4group -v pack.c4g -et \"*.dat\" \\data\\mydatfiles\\\n"); - printf(" c4group pack.c4g -et myfile.dat myfile.bak\n"); - printf(" c4group pack.c4g -s \"*.bin|*.dat\"\n"); - printf(" c4group pack.c4g -x\n"); - printf(" c4group pack.c4g -k\n"); - printf(" c4group update.c4u -g ver1.c4f ver2.c4f New_Version\n"); - printf(" c4group -i\n"); - } + } + // Too few parameters: output help (if we didn't register stuff) + else if (!fRegisterShell && !fUnregisterShell) { + printf("\n"); + printf("Usage: c4group [options] group(s) command(s)\n\n"); + printf("Commands: -a[s] Add [as] -m Move -e[t] Extract [to]\n"); + printf(" -l List -d Delete -r Rename -s Sort\n"); + printf(" -p Pack -u Unpack -x Explode\n"); + printf(" -k Print maker\n"); + printf(" -g [source] [target] [title] Make update\n"); + printf(" -y Apply update\n"); + printf("\n"); + printf("Options: -v Verbose -r Recursive\n"); + printf(" -i Register shell -u Unregister shell\n"); + printf(" -x: Execute shell command when done\n"); + printf("\n"); + printf("Examples: c4group pack.c4g -a myfile.dat -l \"*.dat\"\n"); + printf(" c4group pack.c4g -as myfile.dat myfile.bin\n"); + printf(" c4group -v pack.c4g -et \"*.dat\" \\data\\mydatfiles\\\n"); + printf(" c4group pack.c4g -et myfile.dat myfile.bak\n"); + printf(" c4group pack.c4g -s \"*.bin|*.dat\"\n"); + printf(" c4group pack.c4g -x\n"); + printf(" c4group pack.c4g -k\n"); + printf(" c4group update.c4u -g ver1.c4f ver2.c4f New_Version\n"); + printf(" c4group -i\n"); + } // Execute when done if (strExecuteAtEnd[0]) @@ -547,7 +547,7 @@ int main(int argc, char *argv[]) { } #endif } - // Done - return iResult; + // Done + return iResult; } diff --git a/src/config/C4Config.cpp b/src/config/C4Config.cpp index 65ca75cac..12cf80871 100644 --- a/src/config/C4Config.cpp +++ b/src/config/C4Config.cpp @@ -577,9 +577,9 @@ void C4ConfigGeneral::DeterminePaths(bool forceWorkingDirectory) else SCopy("/tmp/", TempPath); #else - // Mac: Just use the working directory as ExePath. + // Mac: Just use the working directory as ExePath. SCopy(GetWorkingDirectory(), ExePath); - AppendBackslash(ExePath); + AppendBackslash(ExePath); SCopy("/tmp/", TempPath); #endif // Force working directory to exe path if desired @@ -673,35 +673,35 @@ void C4ConfigGeneral::AddAdditionalDataPath(const char *szPath) char AtPathFilename[_MAX_PATH+1]; const char* C4Config::AtExePath(const char *szFilename) - { + { SCopy(General.ExePath,AtPathFilename,_MAX_PATH); SAppend(szFilename,AtPathFilename,_MAX_PATH); return AtPathFilename; } const char* C4Config::AtUserDataPath(const char *szFilename) - { + { SCopy(General.UserDataPath, AtPathFilename, _MAX_PATH); SAppend(szFilename, AtPathFilename, _MAX_PATH); return AtPathFilename; } const char* C4Config::AtSystemDataPath(const char *szFilename) - { + { SCopy(General.SystemDataPath, AtPathFilename, _MAX_PATH); SAppend(szFilename, AtPathFilename, _MAX_PATH); return AtPathFilename; } const char* C4Config::AtTempPath(const char *szFilename) - { + { SCopy(General.TempPath,AtPathFilename,_MAX_PATH); SAppend(szFilename,AtPathFilename,_MAX_PATH); return AtPathFilename; } const char* C4Config::AtNetworkPath(const char *szFilename) - { + { SCopy(General.UserDataPath,AtPathFilename,_MAX_PATH); SAppend(Network.WorkPath,AtPathFilename,_MAX_PATH); SAppend(szFilename,AtPathFilename,_MAX_PATH); diff --git a/src/config/C4Config.h b/src/config/C4Config.h index b4ac0918d..7eb63bea2 100644 --- a/src/config/C4Config.h +++ b/src/config/C4Config.h @@ -145,7 +145,7 @@ class C4ConfigGraphics class C4ConfigSound { public: - int32_t RXSound; + int32_t RXSound; int32_t RXMusic; int32_t FEMusic; int32_t FESamples; @@ -165,7 +165,7 @@ class C4ConfigNetwork int32_t NoRuntimeJoin; int32_t NoReferenceRequest; int32_t MaxResSearchRecursion; - char WorkPath[CFG_MaxString+1]; + char WorkPath[CFG_MaxString+1]; ValidatedStdCopyStrBuf Comment; int32_t MasterServerSignUp; int32_t MasterServerActive; @@ -233,18 +233,18 @@ class C4ConfigExplorer public: int32_t Mode; int32_t Run; - char Definitions[CFG_MaxString+1]; + char Definitions[CFG_MaxString+1]; char Engines[CFG_MaxString+1]; - char EditorBitmap[CFG_MaxString+1]; - char EditorPNG[CFG_MaxString+1]; - char EditorMusic[CFG_MaxString+1]; - char EditorRichText[CFG_MaxString+1]; - char EditorScript[CFG_MaxString+1]; - char EditorText[CFG_MaxString+1]; - char EditorSound[CFG_MaxString+1]; - char EditorZip[CFG_MaxString+1]; - char EditorDefinition[CFG_MaxString+1]; - char EditorHtml[CFG_MaxString+1]; + char EditorBitmap[CFG_MaxString+1]; + char EditorPNG[CFG_MaxString+1]; + char EditorMusic[CFG_MaxString+1]; + char EditorRichText[CFG_MaxString+1]; + char EditorScript[CFG_MaxString+1]; + char EditorText[CFG_MaxString+1]; + char EditorSound[CFG_MaxString+1]; + char EditorZip[CFG_MaxString+1]; + char EditorDefinition[CFG_MaxString+1]; + char EditorHtml[CFG_MaxString+1]; char CommandLine[CFG_MaxString+1]; int32_t EditorUseShell; int32_t Kindersicherung; @@ -275,7 +275,7 @@ class C4ConfigControls public: int32_t GamepadGuiControl; int32_t MouseAScroll; // auto scroll strength - int32_t Keyboard[C4MaxKeyboardSet][C4MaxKey]; + int32_t Keyboard[C4MaxKeyboardSet][C4MaxKey]; void CompileFunc(StdCompiler *pComp, bool fKeysOnly=false); void ResetKeys(); // reset all keys to default }; diff --git a/src/config/C4ConfigShareware.cpp b/src/config/C4ConfigShareware.cpp index 36930678d..d161910bb 100644 --- a/src/config/C4ConfigShareware.cpp +++ b/src/config/C4ConfigShareware.cpp @@ -63,7 +63,7 @@ EVP_PKEY* loadPublicKey(const char *memKey, bool deBase64 = false, bool deXOR = unsigned int keyDataLen; memset(keyData, 0, maxKeyDataLen + 1); - // De-base64 certificate + // De-base64 certificate if (deBase64) { // The man page says that the data memKey points to will not be modified by this @@ -80,7 +80,7 @@ EVP_PKEY* loadPublicKey(const char *memKey, bool deBase64 = false, bool deXOR = memcpy(keyData, memKey, keyDataLen); } - // De-XOR certificate + // De-XOR certificate if (deXOR) { int xorStrLen = strlen(strXOR); @@ -102,7 +102,7 @@ EVP_PKEY* loadPublicKey(const char *memKey, bool deBase64 = false, bool deXOR = void clearPublicKey(EVP_PKEY* pubKey) { - EVP_PKEY_free(pubKey); + EVP_PKEY_free(pubKey); } // Verifies the specified block of data using the public key provided. @@ -268,7 +268,7 @@ C4ConfigShareware::~C4ConfigShareware() void C4ConfigShareware::Default() { - ZeroMem(this, sizeof (C4ConfigShareware)); + ZeroMem(this, sizeof (C4ConfigShareware)); C4Config::Default(); } diff --git a/src/config/C4Constants.h b/src/config/C4Constants.h index 72d8257d7..83fd68c76 100644 --- a/src/config/C4Constants.h +++ b/src/config/C4Constants.h @@ -27,7 +27,7 @@ const size_t C4MaxTitle = 512; const int - C4MaxDefString = 100, + C4MaxDefString = 100, C4MaxMessage = 256, C4ViewDelay = 100, @@ -56,7 +56,7 @@ const int #define C4GRI_USER 8 const int C4M_MaxName = 15, - C4M_MaxDefName = 2*C4M_MaxName+1, + C4M_MaxDefName = 2*C4M_MaxName+1, C4M_MaxTexIndex = 127; // last texture map index is reserved for diff const int C4S_MaxPlayer = 4; @@ -74,10 +74,10 @@ const int C4P_MaxPosition = 4; const int C4P_Control_None = -1, C4P_Control_Keyboard1 = 0, - C4P_Control_Keyboard2 = 1, - C4P_Control_Keyboard3 = 2, - C4P_Control_Keyboard4 = 3, - C4P_Control_GamePad1 = 4, + C4P_Control_Keyboard2 = 1, + C4P_Control_Keyboard3 = 2, + C4P_Control_Keyboard4 = 3, + C4P_Control_GamePad1 = 4, C4P_Control_GamePad2 = 5, C4P_Control_GamePad3 = 6, C4P_Control_GamePad4 = 7, @@ -96,22 +96,22 @@ const int C4XRV_Completed = 0, const uint32_t OCF_None=0, OCF_All=~OCF_None, OCF_Normal=1, - OCF_Construct=1<<1, + OCF_Construct=1<<1, OCF_Grab=1<<2, OCF_Carryable=1<<3, - OCF_OnFire=1<<4, + OCF_OnFire=1<<4, OCF_HitSpeed1=1<<5, OCF_FullCon=1<<6, - OCF_Inflammable=1<<7, + OCF_Inflammable=1<<7, OCF_Chop=1<<8, OCF_Rotate=1<<9, - OCF_Exclusive=1<<10, + OCF_Exclusive=1<<10, OCF_Entrance=1<<11, - OCF_HitSpeed2=1<<12, + OCF_HitSpeed2=1<<12, OCF_HitSpeed3=1<<13, - OCF_Collection=1<<14, + OCF_Collection=1<<14, OCF_Living=1<<15, - OCF_HitSpeed4=1<<16, + OCF_HitSpeed4=1<<16, OCF_FightReady=1<<17, OCF_LineConstruct=1<<18, OCF_Prey=1<<19, @@ -134,7 +134,7 @@ const BYTE // Directional CNAT_None = 0, CNAT_Left = 1, CNAT_Right = 2, - CNAT_Top = 4, + CNAT_Top = 4, CNAT_Bottom = 8, CNAT_Center = 16, // Additional flags @@ -163,16 +163,16 @@ const int CON_CursorLeft = 0, //=================================== Control Commands ====================================================== const BYTE COM_Single = 64, - COM_Double = 128; + COM_Double = 128; const BYTE COM_None = 0; const BYTE COM_Left = 1, - COM_Right = 2, - COM_Up = 3, - COM_Down = 4, - COM_Throw = 5, - COM_Dig = 6, + COM_Right = 2, + COM_Up = 3, + COM_Down = 4, + COM_Throw = 5, + COM_Dig = 6, COM_Special = 7, COM_Special2 = 8, @@ -182,60 +182,60 @@ const BYTE COM_Left = 1, COM_WheelUp = 10, COM_WheelDown= 11, - COM_Left_R = COM_Left + 16, - COM_Right_R = COM_Right + 16, - COM_Up_R = COM_Up + 16, - COM_Down_R = COM_Down + 16, - COM_Throw_R = COM_Throw + 16, - COM_Dig_R = COM_Dig + 16, - COM_Special_R = COM_Special + 16, - COM_Special2_R = COM_Special2 + 16, - COM_ReleaseFirst = COM_Left_R, - COM_ReleaseLast = COM_Special2_R, + COM_Left_R = COM_Left + 16, + COM_Right_R = COM_Right + 16, + COM_Up_R = COM_Up + 16, + COM_Down_R = COM_Down + 16, + COM_Throw_R = COM_Throw + 16, + COM_Dig_R = COM_Dig + 16, + COM_Special_R = COM_Special + 16, + COM_Special2_R = COM_Special2 + 16, + COM_ReleaseFirst = COM_Left_R, + COM_ReleaseLast = COM_Special2_R, COM_Left_S = COM_Left | COM_Single, - COM_Right_S = COM_Right | COM_Single, - COM_Up_S = COM_Up | COM_Single, - COM_Down_S = COM_Down | COM_Single, + COM_Right_S = COM_Right | COM_Single, + COM_Up_S = COM_Up | COM_Single, + COM_Down_S = COM_Down | COM_Single, COM_Throw_S = COM_Throw | COM_Single, - COM_Dig_S = COM_Dig | COM_Single, - COM_Special_S = COM_Special | COM_Single, - COM_Special2_S = COM_Special2 | COM_Single, + COM_Dig_S = COM_Dig | COM_Single, + COM_Special_S = COM_Special | COM_Single, + COM_Special2_S = COM_Special2 | COM_Single, COM_Left_D = COM_Left | COM_Double, COM_Right_D = COM_Right | COM_Double, COM_Up_D = COM_Up | COM_Double, - COM_Down_D = COM_Down | COM_Double, + COM_Down_D = COM_Down | COM_Double, COM_Throw_D = COM_Throw | COM_Double, COM_Dig_D = COM_Dig | COM_Double, - COM_Special_D = COM_Special | COM_Double, - COM_Special2_D = COM_Special2 | COM_Double; + COM_Special_D = COM_Special | COM_Double, + COM_Special2_D = COM_Special2 | COM_Double; const BYTE COM_CursorLeft = 30, - COM_CursorRight = 31, - COM_CursorToggle = 32; + COM_CursorRight = 31, + COM_CursorToggle = 32; const BYTE COM_CursorToggle_D = COM_CursorToggle | COM_Double; const BYTE COM_Help = 35, COM_PlayerMenu = 36, - COM_Chat = 37; + COM_Chat = 37; const BYTE COM_MenuEnter = 38, - COM_MenuEnterAll = 39, - COM_MenuClose = 40, - COM_MenuShowText = 42, - COM_MenuLeft = 52, - COM_MenuRight = 53, - COM_MenuUp = 54, - COM_MenuDown = 55, - COM_MenuSelect = 60, + COM_MenuEnterAll = 39, + COM_MenuClose = 40, + COM_MenuShowText = 42, + COM_MenuLeft = 52, + COM_MenuRight = 53, + COM_MenuUp = 54, + COM_MenuDown = 55, + COM_MenuSelect = 60, - COM_MenuFirst = COM_MenuEnter, - COM_MenuLast = COM_MenuSelect, + COM_MenuFirst = COM_MenuEnter, + COM_MenuLast = COM_MenuSelect, - COM_MenuNavigation1 = COM_MenuShowText, - COM_MenuNavigation2 = COM_MenuSelect; + COM_MenuNavigation1 = COM_MenuShowText, + COM_MenuNavigation2 = COM_MenuSelect; //=================================== SendCommand ======================================== const int32_t C4P_Command_None = 0, @@ -247,7 +247,7 @@ const int32_t C4P_Command_None = 0, //=================================== Owners ============================================== const int NO_OWNER = -1, - ANY_OWNER = -2, + ANY_OWNER = -2, BY_OWNER = 10000, BY_HOSTILE_OWNER = 20000; @@ -255,9 +255,9 @@ const int NO_OWNER = -1, enum C4LeagueDisconnectReason { - C4LDR_Unknown, - C4LDR_ConnectionFailed, - C4LDR_Desync + C4LDR_Unknown, + C4LDR_ConnectionFailed, + C4LDR_Desync }; //=================================== Player (included by C4PlayerInfo and C4Player) @@ -265,7 +265,7 @@ enum C4LeagueDisconnectReason enum C4PlayerType { C4PT_None=0, - C4PT_User=1, // Normal player + C4PT_User=1, // Normal player C4PT_Script=2 // AI players, etc. }; diff --git a/src/control/C4Control.cpp b/src/control/C4Control.cpp index 73faef4bc..064252ec1 100644 --- a/src/control/C4Control.cpp +++ b/src/control/C4Control.cpp @@ -59,7 +59,7 @@ C4ControlPacket::~C4ControlPacket() bool C4ControlPacket::LocalControl() const { - return iByClient == ::Control.ClientID(); + return iByClient == ::Control.ClientID(); } void C4ControlPacket::SetByClient(int32_t inByClient) @@ -92,9 +92,9 @@ void C4Control::Clear() bool C4Control::PreExecute() const { - bool fReady = true; - for(C4IDPacket *pPkt = firstPkt(); pPkt; pPkt = nextPkt(pPkt)) - { + bool fReady = true; + for(C4IDPacket *pPkt = firstPkt(); pPkt; pPkt = nextPkt(pPkt)) + { // recheck packet type: Must be control if (pPkt->getPktType() & CID_First) { @@ -106,14 +106,14 @@ bool C4Control::PreExecute() const { LogF("C4Control::PreExecute: WARNING: Ignoring packet type %2x (not control.)", pPkt->getPktType()); } - } - return fReady; + } + return fReady; } void C4Control::Execute() const { - for(C4IDPacket *pPkt = firstPkt(); pPkt; pPkt = nextPkt(pPkt)) - { + for(C4IDPacket *pPkt = firstPkt(); pPkt; pPkt = nextPkt(pPkt)) + { // recheck packet type: Must be control if (pPkt->getPktType() & CID_First) { @@ -125,22 +125,22 @@ void C4Control::Execute() const { LogF("C4Control::Execute: WARNING: Ignoring packet type %2x (not control.)", pPkt->getPktType()); } - } + } } void C4Control::PreRec(C4Record *pRecord) const { - for(C4IDPacket *pPkt = firstPkt(); pPkt; pPkt = nextPkt(pPkt)) - { - C4ControlPacket *pCtrlPkt = static_cast(pPkt->getPkt()); - if(pCtrlPkt) - pCtrlPkt->PreRec(pRecord); - } + for(C4IDPacket *pPkt = firstPkt(); pPkt; pPkt = nextPkt(pPkt)) + { + C4ControlPacket *pCtrlPkt = static_cast(pPkt->getPkt()); + if(pCtrlPkt) + pCtrlPkt->PreRec(pRecord); + } } void C4Control::CompileFunc(StdCompiler *pComp) { - pComp->Value(Pkts); + pComp->Value(Pkts); } // *** C4ControlSet @@ -184,14 +184,14 @@ void C4ControlSet::Execute() const case C4CVT_MaxPlayer: // host only if(iByClient != C4ClientIDHost) break; - // not in league - if (Game.Parameters.isLeague()) - { - Log("/set maxplayer disabled in league!"); - C4GUI::GUISound("Error"); - break; - } - // set it + // not in league + if (Game.Parameters.isLeague()) + { + Log("/set maxplayer disabled in league!"); + C4GUI::GUISound("Error"); + break; + } + // set it Game.Parameters.MaxPlayers = iData; LogF("MaxPlayer = %d", (int)Game.Parameters.MaxPlayers); break; @@ -210,7 +210,7 @@ void C4ControlSet::Execute() const Game.Teams.SetTeamColors(!!iData); break; - case C4CVT_FairCrew: + case C4CVT_FairCrew: // host only if(!HostControl()) break; // deny setting if it's fixed by scenario @@ -219,17 +219,17 @@ void C4ControlSet::Execute() const if (::Control.isCtrlHost()) Log(LoadResStr("IDS_MSG_NOMODIFYFAIRCREW")); break; } - // set new value - if(iData < 0) - { - Game.Parameters.UseFairCrew = false; - Game.Parameters.FairCrewStrength = 0; - } - else - { - Game.Parameters.UseFairCrew = true; - Game.Parameters.FairCrewStrength = iData; - } + // set new value + if(iData < 0) + { + Game.Parameters.UseFairCrew = false; + Game.Parameters.FairCrewStrength = 0; + } + else + { + Game.Parameters.UseFairCrew = true; + Game.Parameters.FairCrewStrength = iData; + } // runtime updates for runtime fairness adjustments if (Game.IsRunning) { @@ -254,15 +254,15 @@ void C4ControlSet::Execute() const // this setting is part of the reference if (::Network.isEnabled() && ::Network.isHost()) ::Network.InvalidateReference(); - break; + break; } } void C4ControlSet::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntAdapt(eValType), "Type", C4CVT_None)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iData), "Data", 0)); - C4ControlPacket::CompileFunc(pComp); + pComp->Value(mkNamingAdapt(mkIntAdapt(eValType), "Type", C4CVT_None)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iData), "Data", 0)); + C4ControlPacket::CompileFunc(pComp); } // *** C4ControlScript @@ -311,10 +311,10 @@ void C4ControlScript::Execute() const void C4ControlScript::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(iTargetObj, "TargetObj", -1)); - pComp->Value(mkNamingAdapt(fInternal, "Internal", false)); - pComp->Value(mkNamingAdapt(Script, "Script", "")); - C4ControlPacket::CompileFunc(pComp); + pComp->Value(mkNamingAdapt(iTargetObj, "TargetObj", -1)); + pComp->Value(mkNamingAdapt(fInternal, "Internal", false)); + pComp->Value(mkNamingAdapt(Script, "Script", "")); + C4ControlPacket::CompileFunc(pComp); } // *** C4ControlPlayerSelect @@ -365,15 +365,15 @@ void C4ControlPlayerSelect::Execute() const void C4ControlPlayerSelect::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(iPlr, "Player", -1)); - pComp->Value(mkNamingAdapt(fIsAlt, "IsAlt", false)); - pComp->Value(mkNamingAdapt(iObjCnt, "ObjCnt", 0)); - // Compile array - if(pComp->isCompiler()) + pComp->Value(mkNamingAdapt(iPlr, "Player", -1)); + pComp->Value(mkNamingAdapt(fIsAlt, "IsAlt", false)); + pComp->Value(mkNamingAdapt(iObjCnt, "ObjCnt", 0)); + // Compile array + if(pComp->isCompiler()) { delete[] pObjNrs; pObjNrs = new int32_t [iObjCnt]; } - pComp->Value(mkNamingAdapt(mkArrayAdapt(pObjNrs, iObjCnt), "Objs", 0)); + pComp->Value(mkNamingAdapt(mkArrayAdapt(pObjNrs, iObjCnt), "Objs", 0)); - C4ControlPacket::CompileFunc(pComp); + C4ControlPacket::CompileFunc(pComp); } @@ -443,15 +443,15 @@ void C4ControlPlayerCommand::Execute() const void C4ControlPlayerCommand::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iPlr), "Player", -1)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iCmd), "Cmd", 0)); - pComp->Value(mkNamingAdapt(iX, "X", 0)); - pComp->Value(mkNamingAdapt(iY, "Y", 0)); - pComp->Value(mkNamingAdapt(iTarget, "Target", 0)); - pComp->Value(mkNamingAdapt(iTarget2, "Target2", 0)); - pComp->Value(mkNamingAdapt(iData, "Data", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iAddMode), "AddMode", 0)); - C4ControlPacket::CompileFunc(pComp); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iPlr), "Player", -1)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iCmd), "Cmd", 0)); + pComp->Value(mkNamingAdapt(iX, "X", 0)); + pComp->Value(mkNamingAdapt(iY, "Y", 0)); + pComp->Value(mkNamingAdapt(iTarget, "Target", 0)); + pComp->Value(mkNamingAdapt(iTarget2, "Target2", 0)); + pComp->Value(mkNamingAdapt(iData, "Data", 0)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iAddMode), "AddMode", 0)); + C4ControlPacket::CompileFunc(pComp); } // *** C4ControlSyncCheck @@ -464,7 +464,7 @@ void C4ControlSyncCheck::Set() { extern int32_t FRndPtr3; Frame = Game.FrameCounter; - ControlTick = ::Control.ControlTick; + ControlTick = ::Control.ControlTick; Random3 = FRndPtr3; RandomCount = ::RandomCount; AllCrewPosX = GetAllCrewPosX(); @@ -518,7 +518,7 @@ void C4ControlSyncCheck::Execute() const LogFatal(FormatString("Network: %s Frm %i Ctrl %i Rnc %i Rn3 %i Cpx %i PXS %i MMi %i Obc %i Oei %i Sct %i", szOther, SyncCheck.Frame,SyncCheck.ControlTick,SyncCheck.RandomCount,SyncCheck.Random3,SyncCheck.AllCrewPosX,SyncCheck.PXSCount,SyncCheck.MassMoverIndex,SyncCheck.ObjectCount,SyncCheck.ObjectEnumerationIndex, SyncCheck.SectShapeSum).getData()); StartSoundEffect("SyncError"); #ifdef _DEBUG - // Debug safe + // Debug safe C4GameSaveNetwork SaveGame(false); SaveGame.Save(Config.AtExePath("Desync.c4s")); #endif @@ -538,17 +538,17 @@ void C4ControlSyncCheck::Execute() const void C4ControlSyncCheck::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntPackAdapt(Frame), "Frame", -1)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(ControlTick), "ControlTick", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(Random3), "Random3", 0)); - pComp->Value(mkNamingAdapt(RandomCount, "RandomCount", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(AllCrewPosX), "AllCrewPosX", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(PXSCount), "PXSCount", 0)); - pComp->Value(mkNamingAdapt(MassMoverIndex, "MassMoverIndex", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(ObjectCount), "ObjectCount", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(ObjectEnumerationIndex), "ObjectEnumerationIndex", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(SectShapeSum), "SectShapeSum", 0)); - C4ControlPacket::CompileFunc(pComp); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(Frame), "Frame", -1)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(ControlTick), "ControlTick", 0)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(Random3), "Random3", 0)); + pComp->Value(mkNamingAdapt(RandomCount, "RandomCount", 0)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(AllCrewPosX), "AllCrewPosX", 0)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(PXSCount), "PXSCount", 0)); + pComp->Value(mkNamingAdapt(MassMoverIndex, "MassMoverIndex", 0)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(ObjectCount), "ObjectCount", 0)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(ObjectEnumerationIndex), "ObjectEnumerationIndex", 0)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(SectShapeSum), "SectShapeSum", 0)); + C4ControlPacket::CompileFunc(pComp); } // *** C4ControlSynchronize @@ -556,14 +556,14 @@ void C4ControlSyncCheck::CompileFunc(StdCompiler *pComp) void C4ControlSynchronize::Execute() const { Game.Synchronize(fSavePlrFiles); - if(fSyncClearance) Game.SyncClearance(); + if(fSyncClearance) Game.SyncClearance(); } void C4ControlSynchronize::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(fSavePlrFiles, "SavePlrs", false)); - pComp->Value(mkNamingAdapt(fSyncClearance, "SyncClear", false)); - C4ControlPacket::CompileFunc(pComp); + pComp->Value(mkNamingAdapt(fSavePlrFiles, "SavePlrs", false)); + pComp->Value(mkNamingAdapt(fSyncClearance, "SyncClear", false)); + C4ControlPacket::CompileFunc(pComp); } // *** C4ControlClientJoin @@ -608,7 +608,7 @@ void C4ControlClientUpdate::Execute() const // nothing to do? if(pClient->isActivated() == !!iData) break; // log - LogF(LoadResStr(iData ? "IDS_NET_CLIENT_ACTIVATED" : "IDS_NET_CLIENT_DEACTIVATED"), strClient.getData(), pClient->getName()); + LogF(LoadResStr(iData ? "IDS_NET_CLIENT_ACTIVATED" : "IDS_NET_CLIENT_DEACTIVATED"), strClient.getData(), pClient->getName()); // activate/deactivate pClient->SetActivated(!!iData); // local? @@ -619,7 +619,7 @@ void C4ControlClientUpdate::Execute() const // nothing to do? if(pClient->isObserver()) break; // log - LogF(LoadResStr("IDS_NET_CLIENT_OBSERVE"), strClient.getData(), pClient->getName()); + LogF(LoadResStr("IDS_NET_CLIENT_OBSERVE"), strClient.getData(), pClient->getName()); // set observer (will deactivate) pClient->SetObserver(); // local? @@ -670,7 +670,7 @@ void C4ControlClientRemove::Execute() const // remove client if(!Game.Clients.Remove(pClient)) return; // log - LogF(LoadResStr("IDS_NET_CLIENT_REMOVED"), strClient.getData(), pClient->getName(), strReason.getData()); + LogF(LoadResStr("IDS_NET_CLIENT_REMOVED"), strClient.getData(), pClient->getName(), strReason.getData()); // remove all players ::Players.RemoveAtClient(iID, true); // remove all resources @@ -762,8 +762,8 @@ void C4ControlJoinPlayer::Execute() const // Local player: Just join from local file Game.JoinPlayer(szFilename, iAtClient, pClient->getName(), pInfo); } - else if(!fByRes) - { + else if(!fByRes) + { if (PlrData.getSize()) { // create temp file @@ -788,7 +788,7 @@ void C4ControlJoinPlayer::Execute() const assert(false); return; } - } + } else if(::Control.isNetwork()) { // Find ressource @@ -811,12 +811,12 @@ void C4ControlJoinPlayer::Strip() { // By resource? Can't touch player file, then. if(fByRes) return; - // create temp file + // create temp file StdStrBuf PlayerFilename; PlayerFilename = GetFilename(Filename.getData()); - PlayerFilename = Config.AtTempPath(PlayerFilename.getData()); + PlayerFilename = Config.AtTempPath(PlayerFilename.getData()); // Copy to it - if(PlrData.SaveToFile(PlayerFilename.getData())) - { + if(PlrData.SaveToFile(PlayerFilename.getData())) + { // open as group C4Group Grp; if(!Grp.Open(PlayerFilename.getData())) @@ -836,29 +836,29 @@ void C4ControlJoinPlayer::Strip() PlrData = NewPlrData; // Done EraseFile(PlayerFilename.getData()); - } + } } bool C4ControlJoinPlayer::PreExecute() const { - // all data included in control packet? - if(!fByRes) return true; + // all data included in control packet? + if(!fByRes) return true; // client lost? if(!Game.Clients.getClientByID(iAtClient)) return true; - // network only + // network only if(!::Control.isNetwork()) return true; - // search ressource + // search ressource C4Network2Res::Ref pRes = ::Network.ResList.getRefRes(ResCore.getID()); // doesn't exist? start loading if(!pRes) { pRes = ::Network.ResList.AddByCore(ResCore, true); } if(!pRes) return true; - // is loading or removed? + // is loading or removed? return !pRes->isLoading(); } void C4ControlJoinPlayer::PreRec(C4Record *pRecord) { - if(!pRecord) return; + if(!pRecord) return; if (fByRes) { // get local file by id @@ -882,22 +882,22 @@ void C4ControlJoinPlayer::PreRec(C4Record *pRecord) void C4ControlJoinPlayer::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkNetFilenameAdapt(Filename), "Filename", "")); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iAtClient), "AtClient", -1)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(idInfo), "InfoID", -1)); - pComp->Value(mkNamingAdapt(fByRes, "ByRes", false)); - if(fByRes) - pComp->Value(mkNamingAdapt(ResCore, "ResCore")); - else - pComp->Value(mkNamingAdapt(PlrData, "PlrData")); - C4ControlPacket::CompileFunc(pComp); + pComp->Value(mkNamingAdapt(mkNetFilenameAdapt(Filename), "Filename", "")); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iAtClient), "AtClient", -1)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(idInfo), "InfoID", -1)); + pComp->Value(mkNamingAdapt(fByRes, "ByRes", false)); + if(fByRes) + pComp->Value(mkNamingAdapt(ResCore, "ResCore")); + else + pComp->Value(mkNamingAdapt(PlrData, "PlrData")); + C4ControlPacket::CompileFunc(pComp); } // *** C4ControlEMMoveObject C4ControlEMMoveObject::C4ControlEMMoveObject(C4ControlEMObjectAction eAction, int32_t tx, int32_t ty, C4Object *pTargetObj, int32_t iObjectNum, int32_t *pObjects, const char *szScript) - : eAction(eAction), tx(tx), ty(ty), iTargetObj(::Objects.ObjectNumber(pTargetObj)), + : eAction(eAction), tx(tx), ty(ty), iTargetObj(::Objects.ObjectNumber(pTargetObj)), iObjectNum(iObjectNum), pObjects(pObjects), Script(szScript, true) { @@ -953,26 +953,26 @@ void C4ControlEMMoveObject::Execute() const } // update status if (fLocalCall) - { + { Console.EditCursor.SetHold(true); Console.PropertyDlg.Update(Console.EditCursor.GetSelection()); - } + } } break; case EMMO_Script: { if(!pObjects) return; - // execute script ... - C4ControlScript ScriptCtrl(Script.getData(), C4ControlScript::SCOPE_Global, false); - ScriptCtrl.SetByClient(iByClient); - // ... for each object in selection + // execute script ... + C4ControlScript ScriptCtrl(Script.getData(), C4ControlScript::SCOPE_Global, false); + ScriptCtrl.SetByClient(iByClient); + // ... for each object in selection for (int i=0; iAssignRemoval(); } - break; // Here was fallthrough. Seemed wrong. ck. + break; // Here was fallthrough. Seemed wrong. ck. case EMMO_Exit: { if(!pObjects) return; @@ -992,12 +992,12 @@ void C4ControlEMMoveObject::Execute() const if ((pObj = ::Objects.SafeObjectPointer(pObjects[i]))) pObj->Exit(pObj->GetX(), pObj->GetY(), pObj->r); } - break; // Same. ck. - } + break; // Same. ck. + } // update property dlg & status bar if(fLocalCall) Console.EditCursor.OnSelectionChanged(); - } + } void C4ControlEMMoveObject::CompileFunc(StdCompiler *pComp) { @@ -1006,11 +1006,11 @@ void C4ControlEMMoveObject::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(ty, "ty", 0)); pComp->Value(mkNamingAdapt(iTargetObj, "TargetObj", -1)); pComp->Value(mkNamingAdapt(mkIntPackAdapt(iObjectNum), "ObjectNum", 0)); - if(pComp->isCompiler()) { delete [] pObjects; pObjects = new int32_t [iObjectNum]; } + if(pComp->isCompiler()) { delete [] pObjects; pObjects = new int32_t [iObjectNum]; } pComp->Value(mkNamingAdapt(mkArrayAdapt(pObjects, iObjectNum), "Objs", -1)); - if(eAction == EMMO_Script) - pComp->Value(mkNamingAdapt(Script, "Script", "")); - C4ControlPacket::CompileFunc(pComp); + if(eAction == EMMO_Script) + pComp->Value(mkNamingAdapt(Script, "Script", "")); + C4ControlPacket::CompileFunc(pComp); } // *** C4ControlEMDrawTool @@ -1098,7 +1098,7 @@ void C4ControlMessage::Execute() const C4GameLobby::MainDlg *pLobby = ::Network.GetLobby(); StdStrBuf str; switch(eType) - { + { case C4CMT_Normal: case C4CMT_Me: // log it @@ -1190,23 +1190,23 @@ void C4ControlMessage::Execute() const Application.NotifyUserIfInactive(); break; - case C4CMT_System: - // sender must be host - if(!HostControl()) break; - // show - LogF("Network: %s", szMessage); - break; + case C4CMT_System: + // sender must be host + if(!HostControl()) break; + // show + LogF("Network: %s", szMessage); + break; } } void C4ControlMessage::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntAdaptT(eType), "Type", C4CMT_Normal)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iPlayer), "Player", -1)); + pComp->Value(mkNamingAdapt(mkIntAdaptT(eType), "Type", C4CMT_Normal)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iPlayer), "Player", -1)); if(eType == C4CMT_Private) - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iToPlayer), "ToPlayer", -1)); - pComp->Value(mkNamingAdapt(Message, "Message", "")); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iToPlayer), "ToPlayer", -1)); + pComp->Value(mkNamingAdapt(Message, "Message", "")); C4ControlPacket::CompileFunc(pComp); } @@ -1234,8 +1234,8 @@ void C4ControlPlayerInfo::Execute() const void C4ControlPlayerInfo::CompileFunc(StdCompiler *pComp) { - pComp->Value(PlrInfo); - C4ControlPacket::CompileFunc(pComp); + pComp->Value(PlrInfo); + C4ControlPacket::CompileFunc(pComp); } // *** C4ControlRemovePlr @@ -1250,8 +1250,8 @@ void C4ControlRemovePlr::Execute() const void C4ControlRemovePlr::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iPlr), "Plr", -1)); - pComp->Value(mkNamingAdapt(fDisconnected, "Disconnected", false)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iPlr), "Plr", -1)); + pComp->Value(mkNamingAdapt(fDisconnected, "Disconnected", false)); C4ControlPacket::CompileFunc(pComp); } @@ -1264,7 +1264,7 @@ void C4ControlDebugRec::Execute() const void C4ControlDebugRec::CompileFunc(StdCompiler *pComp) { - pComp->Value(Data); + pComp->Value(Data); } // *** C4ControlVote @@ -1397,9 +1397,9 @@ void C4ControlVote::Execute() const void C4ControlVote::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntAdaptT(eType), "Type", VT_None)); - pComp->Value(mkNamingAdapt(fApprove, "Approve", true)); - pComp->Value(mkNamingAdapt(iData, "Data", 0)); + pComp->Value(mkNamingAdapt(mkIntAdaptT(eType), "Type", VT_None)); + pComp->Value(mkNamingAdapt(fApprove, "Approve", true)); + pComp->Value(mkNamingAdapt(iData, "Data", 0)); C4ControlPacket::CompileFunc(pComp); } diff --git a/src/control/C4Control.h b/src/control/C4Control.h index f43bc8952..63dab7f55 100644 --- a/src/control/C4Control.h +++ b/src/control/C4Control.h @@ -46,13 +46,13 @@ protected: public: int32_t getByClient() const { return iByClient; } bool LocalControl() const; - bool HostControl() const { return iByClient == C4ClientIDHost; } + bool HostControl() const { return iByClient == C4ClientIDHost; } void SetByClient(int32_t iByClient); virtual bool PreExecute() const { return true; } virtual void Execute() const = 0; - virtual void PreRec(C4Record *pRecord) { } + virtual void PreRec(C4Record *pRecord) { } // allowed in lobby (without dynamic loaded)? virtual bool Lobby() const { return false; } @@ -73,11 +73,11 @@ public: ~C4Control(); protected: - C4PacketList Pkts; + C4PacketList Pkts; public: - void Clear(); + void Clear(); // packet list wrappers C4IDPacket *firstPkt() const { return Pkts.firstPkt(); } @@ -86,9 +86,9 @@ public: void AddHead(C4PacketType eType, C4ControlPacket *pCtrl) { Pkts.AddHead(eType, pCtrl); } void Add(C4PacketType eType, C4ControlPacket *pCtrl) { Pkts.Add(eType, pCtrl); } - void Take(C4Control &Ctrl) { Pkts.Take(Ctrl.Pkts); } - void Append(const C4Control &Ctrl) { Pkts.Append(Ctrl.Pkts); } - void Copy(const C4Control &Ctrl) { Clear(); Pkts.Append(Ctrl.Pkts); } + void Take(C4Control &Ctrl) { Pkts.Take(Ctrl.Pkts); } + void Append(const C4Control &Ctrl) { Pkts.Append(Ctrl.Pkts); } + void Copy(const C4Control &Ctrl) { Clear(); Pkts.Append(Ctrl.Pkts); } void Remove(C4IDPacket *pPkt) { Pkts.Remove(pPkt); } void Delete(C4IDPacket *pPkt) { Pkts.Delete(pPkt); } @@ -104,21 +104,21 @@ public: enum C4CtrlValueType { - C4CVT_None = -1, + C4CVT_None = -1, C4CVT_ControlRate = 0, C4CVT_AllowDebug = 1, C4CVT_MaxPlayer = 2, C4CVT_TeamDistribution = 3, C4CVT_TeamColors = 4, - C4CVT_FairCrew = 5 + C4CVT_FairCrew = 5 }; class C4ControlSet : public C4ControlPacket // sync, lobby { public: - C4ControlSet() - : eValType(C4CVT_None), iData(0) - { } + C4ControlSet() + : eValType(C4CVT_None), iData(0) + { } C4ControlSet(C4CtrlValueType eValType, int32_t iData) : eValType(eValType), iData(iData) { } @@ -137,9 +137,9 @@ class C4ControlScript : public C4ControlPacket // sync public: enum { SCOPE_Console=-2, SCOPE_Global=-1 }; // special scopes to be passed as target objects - C4ControlScript() - : iTargetObj(-1), fInternal(true) - { } + C4ControlScript() + : iTargetObj(-1), fInternal(true) + { } C4ControlScript(const char *szScript, int32_t iTargetObj = SCOPE_Global, bool fInternal = true) : iTargetObj(iTargetObj), fInternal(fInternal), Script(szScript, true) { } @@ -155,8 +155,8 @@ public: class C4ControlPlayerSelect : public C4ControlPacket // sync { public: - C4ControlPlayerSelect() - : iPlr(-1), fIsAlt(false), iObjCnt(0), pObjNrs(NULL) { } + C4ControlPlayerSelect() + : iPlr(-1), fIsAlt(false), iObjCnt(0), pObjNrs(NULL) { } C4ControlPlayerSelect(int32_t iPlr, const C4ObjectList &Objs, bool fIsAlt); ~C4ControlPlayerSelect() { delete[] pObjNrs; } protected: @@ -204,8 +204,8 @@ public: class C4ControlPlayerCommand : public C4ControlPacket // sync { public: - C4ControlPlayerCommand() - : iPlr(-1), iCmd(-1) { } + C4ControlPlayerCommand() + : iPlr(-1), iCmd(-1) { } C4ControlPlayerCommand(int32_t iPlr, int32_t iCmd, int32_t iX, int32_t iY, C4Object *pTarget, C4Object *pTarget2, int32_t iData, int32_t iAddMode); protected: @@ -232,7 +232,7 @@ protected: public: void Set(); int32_t getFrame() const { return Frame; } - virtual bool Sync() const { return false; } + virtual bool Sync() const { return false; } DECLARE_C4CONTROL_VIRTUALS protected: static int32_t GetAllCrewPosX(); @@ -258,8 +258,8 @@ public: public: C4ClientCore Core; public: - virtual bool Sync() const { return false; } - virtual bool Lobby() const { return true; } + virtual bool Sync() const { return false; } + virtual bool Lobby() const { return true; } DECLARE_C4CONTROL_VIRTUALS }; @@ -280,8 +280,8 @@ public: C4ControlClientUpdType eType; int32_t iData; public: - virtual bool Sync() const { return false; } - virtual bool Lobby() const { return true; } + virtual bool Sync() const { return false; } + virtual bool Lobby() const { return true; } DECLARE_C4CONTROL_VIRTUALS }; @@ -294,8 +294,8 @@ public: int32_t iID; StdCopyStrBuf strReason; public: - virtual bool Sync() const { return false; } - virtual bool Lobby() const { return true; } + virtual bool Sync() const { return false; } + virtual bool Lobby() const { return true; } DECLARE_C4CONTROL_VIRTUALS }; @@ -303,29 +303,29 @@ public: class C4ControlPlayerInfo : public C4ControlPacket // not sync, lobby { public: - C4ControlPlayerInfo() - { } - C4ControlPlayerInfo(const C4ClientPlayerInfos &PlrInfo) - : PlrInfo(PlrInfo) - { } + C4ControlPlayerInfo() + { } + C4ControlPlayerInfo(const C4ClientPlayerInfos &PlrInfo) + : PlrInfo(PlrInfo) + { } protected: - C4ClientPlayerInfos PlrInfo; + C4ClientPlayerInfos PlrInfo; public: const C4ClientPlayerInfos &GetInfo() const { return PlrInfo; } - virtual bool Sync() const { return false; } - virtual bool Lobby() const { return true; } - DECLARE_C4CONTROL_VIRTUALS + virtual bool Sync() const { return false; } + virtual bool Lobby() const { return true; } + DECLARE_C4CONTROL_VIRTUALS }; struct C4ControlJoinPlayer : public C4ControlPacket // sync { public: - C4ControlJoinPlayer() : iAtClient(-1), idInfo(-1) { } + C4ControlJoinPlayer() : iAtClient(-1), idInfo(-1) { } C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo, const C4Network2ResCore &ResCore); C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo); protected: StdStrBuf Filename; - int32_t iAtClient; + int32_t iAtClient; int32_t idInfo; bool fByRes; StdBuf PlrData; // for fByRes == false @@ -350,7 +350,7 @@ enum C4ControlEMObjectAction class C4ControlEMMoveObject : public C4ControlPacket // sync { public: - C4ControlEMMoveObject() : pObjects(NULL) { } + C4ControlEMMoveObject() : pObjects(NULL) { } C4ControlEMMoveObject(C4ControlEMObjectAction eAction, int32_t tx, int32_t ty, C4Object *pTargetObj, int32_t iObjectNum = 0, int32_t *pObjects = NULL, const char *szScript = NULL); ~C4ControlEMMoveObject(); @@ -360,7 +360,7 @@ protected: int32_t iTargetObj; // enumerated ptr to target object int32_t iObjectNum; // number of objects moved int32_t *pObjects; // pointer on array of objects moved - StdStrBuf Script; // script to execute + StdStrBuf Script; // script to execute public: DECLARE_C4CONTROL_VIRTUALS }; @@ -377,7 +377,7 @@ enum C4ControlEMDrawAction class C4ControlEMDrawTool : public C4ControlPacket // sync { public: - C4ControlEMDrawTool() { } + C4ControlEMDrawTool() { } C4ControlEMDrawTool(C4ControlEMDrawAction eAction, int32_t iMode, int32_t iX=-1, int32_t iY=-1, int32_t iX2=-1, int32_t iY2=-1, int32_t iGrade=-1, bool fIFT=true, const char *szMaterial=NULL, const char *szTexture=NULL); @@ -407,8 +407,8 @@ enum C4ControlMessageType class C4ControlMessage : public C4ControlPacket // not sync, lobby { public: - C4ControlMessage() - : eType(C4CMT_Normal), iPlayer(-1) { } + C4ControlMessage() + : eType(C4CMT_Normal), iPlayer(-1) { } C4ControlMessage(C4ControlMessageType eType, const char *szMessage, int32_t iPlayer = -1, int32_t iToPlayer = -1) : eType(eType), iPlayer(iPlayer), iToPlayer(iToPlayer), Message(szMessage, true) { } @@ -417,16 +417,16 @@ protected: int32_t iPlayer, iToPlayer; StdStrBuf Message; public: - virtual bool Sync() const { return false; } - virtual bool Lobby() const { return true; } + virtual bool Sync() const { return false; } + virtual bool Lobby() const { return true; } DECLARE_C4CONTROL_VIRTUALS }; class C4ControlRemovePlr : public C4ControlPacket // sync { public: - C4ControlRemovePlr() - : iPlr(-1) { } + C4ControlRemovePlr() + : iPlr(-1) { } C4ControlRemovePlr(int32_t iPlr, bool fDisconnected) : iPlr(iPlr), fDisconnected(fDisconnected) { } protected: @@ -439,10 +439,10 @@ public: class C4ControlDebugRec : public C4ControlPacket // sync { public: - C4ControlDebugRec() - { } - C4ControlDebugRec(StdBuf &Data) - : Data(Data) { } + C4ControlDebugRec() + { } + C4ControlDebugRec(StdBuf &Data) + : Data(Data) { } protected: StdBuf Data; public: @@ -452,7 +452,7 @@ public: enum C4ControlVoteType { VT_None = -1, - VT_Cancel, + VT_Cancel, VT_Kick, VT_Pause }; @@ -477,7 +477,7 @@ public: StdStrBuf getDesc() const; StdStrBuf getDescWarning() const; - virtual bool Sync() const { return false; } + virtual bool Sync() const { return false; } DECLARE_C4CONTROL_VIRTUALS }; diff --git a/src/control/C4GameControl.cpp b/src/control/C4GameControl.cpp index 6e7f8d5b6..305dcf7c5 100644 --- a/src/control/C4GameControl.cpp +++ b/src/control/C4GameControl.cpp @@ -40,7 +40,7 @@ C4GameControl::C4GameControl() : Network(this) { - Default(); + Default(); } C4GameControl::~C4GameControl() @@ -121,7 +121,7 @@ void C4GameControl::ChangeToLocal() // (otherwise, clients start game when host disconnected!) if (!C4GameOverDlg::IsShown()) Game.HaltCount = 0; - // set status + // set status eMode = CM_Local; fHost = true; ControlRate = 1; } @@ -138,7 +138,7 @@ void C4GameControl::OnGameSynchronizing() bool C4GameControl::StartRecord(bool fInitial, bool fStreaming) { - assert(fInitComplete); + assert(fInitComplete); // already recording? if(pRecord) StopRecord(); // start @@ -170,7 +170,7 @@ void C4GameControl::StopRecord(StdStrBuf *pRecordName, BYTE *pRecordSHA1) if(pRecord) { ::Network.FinishStreaming(); - pRecord->Stop(pRecordName, pRecordSHA1); + pRecord->Stop(pRecordName, pRecordSHA1); // just delete delete pRecord; pRecord = NULL; } @@ -179,7 +179,7 @@ void C4GameControl::StopRecord(StdStrBuf *pRecordName, BYTE *pRecordSHA1) void C4GameControl::RequestRuntimeRecord() { if (!IsRuntimeRecordPossible()) return; // cannot record - fRecordNeeded = true; + fRecordNeeded = true; // request through a synchronize-call // currnetly do not request, but start record with next gamesync, so network runtime join can be debugged #ifndef DEBUGREC @@ -209,30 +209,30 @@ void C4GameControl::Clear() { StopRecord(); ChangeToLocal(); - Default(); + Default(); } void C4GameControl::Default() { Input.Clear(); - Network.Clear(); + Network.Clear(); eMode = CM_None; fHost = fPreInit = fInitComplete = false; iClientID = C4ClientIDUnknown; pRecord = NULL; pPlayback = NULL; - SyncChecks.Clear(); + SyncChecks.Clear(); ControlRate = BoundBy(Config.Network.ControlRate, 1, C4MaxControlRate); - ControlTick = 0; - SyncRate = C4SyncCheckRate; - DoSync = false; + ControlTick = 0; + SyncRate = C4SyncCheckRate; + DoSync = false; fRecordNeeded = false; pExecutingControl = NULL; } bool C4GameControl::Prepare() { - assert(fInitComplete); + assert(fInitComplete); // Prepare control, return true if everything is ready for GameGo. bool is_input_prepared = false; @@ -279,7 +279,7 @@ void C4GameControl::Execute() { // Execute all available control - assert(fInitComplete); + assert(fInitComplete); // control tick? replay must always be executed. if(!isReplay() && Game.FrameCounter % ControlRate) @@ -329,7 +329,7 @@ void C4GameControl::Execute() void C4GameControl::Ticks() { - assert(fInitComplete); + assert(fInitComplete); if(!(Game.FrameCounter % ControlRate)) ControlTick++; @@ -349,12 +349,12 @@ void C4GameControl::Ticks() bool C4GameControl::CtrlTickReached(int32_t iTick) { - // 1. control tick reached? - if(ControlTick < iTick) return false; + // 1. control tick reached? + if(ControlTick < iTick) return false; // 2. control tick? if(Game.FrameCounter % ControlRate) return false; - // ok then - return true; + // ok then + return true; } int32_t C4GameControl::getCtrlTick(int32_t iFrame) const @@ -388,7 +388,7 @@ void C4GameControl::DoInput(C4PacketType eCtrlType, C4ControlPacket *pPkt, C4Con { assert(fPreInit); - // check if the control can be executed + // check if the control can be executed if(eDelivery == CDT_Direct || eDelivery == CDT_Private) assert(!pPkt->Sync()); if(!fInitComplete) @@ -398,8 +398,8 @@ void C4GameControl::DoInput(C4PacketType eCtrlType, C4ControlPacket *pPkt, C4Con if(eDelivery == CDT_Decide) eDelivery = DecideControlDelivery(); - // queue? - if(eDelivery == CDT_Queue) + // queue? + if(eDelivery == CDT_Queue) { // add, will be executed/sent later Input.Add(eCtrlType, pPkt); @@ -447,9 +447,9 @@ C4ControlDeliveryType C4GameControl::DecideControlDelivery() void C4GameControl::DoSyncCheck() { - // only once - if(!DoSync) return; - DoSync = false; + // only once + if(!DoSync) return; + DoSync = false; // create sync check C4ControlSyncCheck *pSyncCheck = new C4ControlSyncCheck(); pSyncCheck->Set(); @@ -477,14 +477,14 @@ void C4GameControl::DoSyncCheck() void C4GameControl::ExecControl(const C4Control &rCtrl) { - // nothing to do? - if(!rCtrl.firstPkt()) return; - // execute it - if(!rCtrl.PreExecute()) Log("Control: PreExecute failed for sync control!"); - rCtrl.Execute(); - // record - if(pRecord) - pRecord->Rec(rCtrl, Game.FrameCounter); + // nothing to do? + if(!rCtrl.firstPkt()) return; + // execute it + if(!rCtrl.PreExecute()) Log("Control: PreExecute failed for sync control!"); + rCtrl.Execute(); + // record + if(pRecord) + pRecord->Rec(rCtrl, Game.FrameCounter); } void C4GameControl::ExecControlPacket(C4PacketType eCtrlType, C4ControlPacket *pPkt) diff --git a/src/control/C4GameControl.h b/src/control/C4GameControl.h index c9e8369e0..168c2bba8 100644 --- a/src/control/C4GameControl.h +++ b/src/control/C4GameControl.h @@ -35,12 +35,12 @@ enum C4ControlMode enum C4ControlDeliveryType { - CDT_Queue = 0, // Send in control queue (sync) - CDT_Sync = 1, // Send, delay execution until net is sync (sync) - CDT_Direct = 2, // Send directly to all clients (not sync) - CDT_Private = 3, // Send only to some clients (not sync, obviously) + CDT_Queue = 0, // Send in control queue (sync) + CDT_Sync = 1, // Send, delay execution until net is sync (sync) + CDT_Direct = 2, // Send directly to all clients (not sync) + CDT_Private = 3, // Send only to some clients (not sync, obviously) - CDT_Decide // Use whatever sync mode seems fastest atm (sync) + CDT_Decide // Use whatever sync mode seems fastest atm (sync) }; // Additional notes / requirements: @@ -72,7 +72,7 @@ public: protected: C4ControlMode eMode; - bool fPreInit, fInitComplete; + bool fPreInit, fInitComplete; bool fHost; // (set for local, too) bool fActivated; bool fRecordNeeded; @@ -83,7 +83,7 @@ protected: C4Control SyncChecks; - C4GameControlClient *pClients; + C4GameControlClient *pClients; C4Control *pExecutingControl; // Control that is in the process of being executed - needed by non-initial records @@ -96,7 +96,7 @@ public: public: - // configuration + // configuration bool isLocal() const { return eMode == CM_Local; } bool isNetwork() const { return eMode == CM_Network; } bool isReplay() const { return eMode == CM_Replay; } @@ -107,11 +107,11 @@ public: bool NoInput() const { return isReplay(); } - // client list - C4GameControlClient *getClient(int32_t iID); - C4GameControlClient *getClient(const char *szName); + // client list + C4GameControlClient *getClient(int32_t iID); + C4GameControlClient *getClient(const char *szName); - // initialization + // initialization bool InitLocal(C4Client *pLocal); bool InitNetwork(C4Client *pLocal); bool InitReplay(C4Group &rGroup); @@ -121,7 +121,7 @@ public: void Clear(); void Default(); - // records + // records bool StartRecord(bool fInitial, bool fStreaming); void StopRecord(StdStrBuf *pRecordName = NULL, BYTE *pRecordSHA1 = NULL); void RequestRuntimeRecord(); @@ -134,7 +134,7 @@ public: void Ticks(); // public helpers - bool CtrlTickReached(int32_t iTick); + bool CtrlTickReached(int32_t iTick); int32_t getCtrlTick(int32_t iFrame) const; int32_t getNextControlTick() const; @@ -146,13 +146,13 @@ public: // activation void SetActivated(bool fActivated); - // input - void DoInput(C4PacketType eCtrlType, C4ControlPacket *pPkt, C4ControlDeliveryType eDelivery); - void DbgRec(C4RecordChunkType eType, const uint8_t *pData=NULL, size_t iSize=0); // record debug stuff + // input + void DoInput(C4PacketType eCtrlType, C4ControlPacket *pPkt, C4ControlDeliveryType eDelivery); + void DbgRec(C4RecordChunkType eType, const uint8_t *pData=NULL, size_t iSize=0); // record debug stuff C4ControlDeliveryType DecideControlDelivery(); - // sync check - void DoSyncCheck(); + // sync check + void DoSyncCheck(); // execute and record control (by self or C4GameControlNetwork) void ExecControl(const C4Control &rCtrl); diff --git a/src/control/C4GameParameters.cpp b/src/control/C4GameParameters.cpp index ace842bd1..6bc4d993b 100644 --- a/src/control/C4GameParameters.cpp +++ b/src/control/C4GameParameters.cpp @@ -278,14 +278,14 @@ bool C4GameResList::InitNetwork(C4Network2ResList *pNetResList) void C4GameResList::CalcHashes() { - for (int32_t i = 0; i < iResCount; i++) + for (int32_t i = 0; i < iResCount; i++) pResList[i]->CalcHash(); } bool C4GameResList::RetrieveFiles() { // wait for all resources - for (int32_t i = 0; i < iResCount; i++) + for (int32_t i = 0; i < iResCount; i++) { const C4Network2ResCore &Core = *pResList[i]->getResCore(); StdStrBuf ResNameBuf = FormatString("%s: %s", LoadResStr("IDS_DLG_DEFINITION"), GetFilename(Core.getFileName())); @@ -513,7 +513,7 @@ void C4GameParameters::CompileFunc(StdCompiler *pComp, C4Scenario *pScenario) pComp->Value(mkNamingAdapt(Teams, "Teams" )); } - pComp->Value(Clients); + pComp->Value(Clients); } diff --git a/src/control/C4GameSave.cpp b/src/control/C4GameSave.cpp index 8becc7a71..2d607038a 100644 --- a/src/control/C4GameSave.cpp +++ b/src/control/C4GameSave.cpp @@ -66,7 +66,7 @@ bool C4GameSave::SaveCore() rC4S = Game.C4S; // Always mark current engine version rC4S.Head.C4XVer[0]=C4XVER1; rC4S.Head.C4XVer[1]=C4XVER2; - rC4S.Head.C4XVer[2]=C4XVER3; rC4S.Head.C4XVer[3]=C4XVER4; + rC4S.Head.C4XVer[2]=C4XVER3; rC4S.Head.C4XVer[3]=C4XVER4; // Some flags are not to be set for initial settings: // They depend on whether specific runtime data is present, which may simply not be stored into initial // saves, because they rely on any data present and up-to-date within the scenario! @@ -460,8 +460,8 @@ bool C4GameSave::Save(C4Group &hToGroup, bool fKeepGroup) pSaveGroup->Delete(C4CFN_Titles); pSaveGroup->Delete(C4CFN_Info); } - // Always save Game.txt; even for saved scenarios, because global effects need to be saved - if(!Game.SaveData(*pSaveGroup, false, fInitial, IsExact())) + // Always save Game.txt; even for saved scenarios, because global effects need to be saved + if(!Game.SaveData(*pSaveGroup, false, fInitial, IsExact())) { Log(LoadResStr("IDS_ERR_SAVE_RUNTIMEDATA")); return false; } // save additional runtime data if (GetSaveRuntimeData()) if (!SaveRuntimeData()) return false; diff --git a/src/control/C4GameSave.h b/src/control/C4GameSave.h index 2a67d85e5..0e660def7 100644 --- a/src/control/C4GameSave.h +++ b/src/control/C4GameSave.h @@ -66,7 +66,7 @@ class C4GameSave virtual bool GetCreateSmallFile() { return false; } // return whether file size should be minimized virtual bool GetForceExactLandscape() { return GetSaveRuntimeData() && IsExact(); } // whether exact landscape shall be saved virtual bool GetSaveOrigin() { return false; } // return whether C4S.Head.Origin shall be set - virtual bool GetClearOrigin() { return !GetSaveOrigin(); } // return whether C4S.Head.Origin shall be cleared if it's set + virtual bool GetClearOrigin() { return !GetSaveOrigin(); } // return whether C4S.Head.Origin shall be cleared if it's set virtual bool GetSaveUserPlayers() { return IsExact(); } // return whether joined user players shall be saved into SavePlayerInfos virtual bool GetSaveScriptPlayers() { return IsExact(); } // return whether joined script players shall be saved into SavePlayerInfos virtual bool GetSaveUserPlayerFiles() { return IsExact(); } // return whether .c4p files of joined user players shall be put into the scenario @@ -122,7 +122,7 @@ class C4GameSaveScenario : public C4GameSave bool fForceExactLandscape; bool fSaveOrigin; virtual bool GetSaveOrigin() { return fSaveOrigin; } - virtual bool GetClearOrigin() { return false; } // always keep existing origin + virtual bool GetClearOrigin() { return false; } // always keep existing origin virtual bool GetSaveDesc() { return false; } // should WriteDescData be executed in Save()-call? virtual bool GetForceExactLandscape() { return C4GameSave::GetForceExactLandscape() || fForceExactLandscape; } virtual bool GetSaveScriptPlayers() { return true; } // script players are also saved; but user players aren't! diff --git a/src/control/C4PlayerInfo.cpp b/src/control/C4PlayerInfo.cpp index c53543104..f5aa66f44 100644 --- a/src/control/C4PlayerInfo.cpp +++ b/src/control/C4PlayerInfo.cpp @@ -42,7 +42,7 @@ void C4PlayerInfo::Clear() // del temp file DeleteTempFile(); // clear fields - sName.Clear(); szFilename.Clear(); + sName.Clear(); szFilename.Clear(); pRes = NULL; ResCore.Clear(); // default fields @@ -66,7 +66,7 @@ void C4PlayerInfo::DeleteTempFile() EraseItem(szFilename.getData()); // reset flag and filename to prevent double deletion dwFlags &= ~PIF_TempFile; - szFilename.Clear(); + szFilename.Clear(); } } @@ -179,13 +179,13 @@ bool C4PlayerInfo::HasTeamWon() const } void C4PlayerInfo::CompileFunc(StdCompiler *pComp) - { - // Names - pComp->Value(mkNamingAdapt(sName, "Name", "")); + { + // Names + pComp->Value(mkNamingAdapt(sName, "Name", "")); pComp->Value(mkNamingAdapt(sForcedName, "ForcedName", "")); - pComp->Value(mkNamingAdapt(szFilename, "Filename", "")); + pComp->Value(mkNamingAdapt(szFilename, "Filename", "")); - // Flags + // Flags const StdBitfieldEntry Entries[] = { { "Joined", PIF_Joined }, @@ -202,9 +202,9 @@ void C4PlayerInfo::CompileFunc(StdCompiler *pComp) { "Invisible", PIF_Invisible}, { NULL, 0 }, }; - uint16_t dwSyncFlags = dwFlags & PIF_SyncFlags; // do not store local flags! - pComp->Value(mkNamingAdapt(mkBitfieldAdapt(dwSyncFlags, Entries), "Flags", 0u)); - if(pComp->isCompiler()) dwFlags = dwSyncFlags; + uint16_t dwSyncFlags = dwFlags & PIF_SyncFlags; // do not store local flags! + pComp->Value(mkNamingAdapt(mkBitfieldAdapt(dwSyncFlags, Entries), "Flags", 0u)); + if(pComp->isCompiler()) dwFlags = dwSyncFlags; pComp->Value(mkNamingAdapt(iID, "ID", 0)); // type @@ -224,7 +224,7 @@ void C4PlayerInfo::CompileFunc(StdCompiler *pComp) } // load colors - pComp->Value(mkNamingAdapt(dwColor, "Color", 0u)); + pComp->Value(mkNamingAdapt(dwColor, "Color", 0u)); pComp->Value(mkNamingAdapt(dwOriginalColor, "OriginalColor", dwColor)); // load savegame ID pComp->Value(mkNamingAdapt(mkIntPackAdapt(idSavegamePlayer), "SavgamePlayer", 0)); @@ -234,18 +234,18 @@ void C4PlayerInfo::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(szAuthID, "AUID", "")); // InGame info - if(dwFlags & PIF_Joined) - { + if(dwFlags & PIF_Joined) + { pComp->Value(mkNamingAdapt(iInGameNumber, "GameNumber", -1)); pComp->Value(mkNamingAdapt(iInGameJoinFrame, "GameJoinFrame", -1)); - } - else - iInGameNumber = iInGameJoinFrame = -1; + } + else + iInGameNumber = iInGameJoinFrame = -1; - if(dwFlags & PIF_Removed) + if(dwFlags & PIF_Removed) pComp->Value(mkNamingAdapt(iInGamePartFrame, "GamePartFrame", -1)); - else - iInGamePartFrame = -1; + else + iInGamePartFrame = -1; // script player extra data pComp->Value(mkNamingAdapt(idExtraData, "ExtraData", C4ID::None)); @@ -255,13 +255,13 @@ void C4PlayerInfo::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(mkIntPackAdapt(iLeagueScore), "LeagueScore", 0)); pComp->Value(mkNamingAdapt(mkIntPackAdapt(iLeagueRank), "LeagueRank", 0)); pComp->Value(mkNamingAdapt(mkIntPackAdapt(iLeagueRankSymbol), "LeagueRankSymbol", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iLeagueProjectedGain), "ProjectedGain", -1)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iLeagueProjectedGain), "ProjectedGain", -1)); pComp->Value(mkNamingAdapt(mkParAdapt(sClanTag, StdCompiler::RCT_All), "ClanTag", "")); // file resource if (dwFlags & PIF_HasRes) { - // ResCore + // ResCore if (pComp->isDecompiler() && pRes) { // ensure ResCore is up-to-date @@ -270,11 +270,11 @@ void C4PlayerInfo::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(ResCore, "ResCore")); } - } + } void C4PlayerInfo::SetFilename(const char *szToFilename) { - szFilename = szToFilename; + szFilename = szToFilename; } void C4PlayerInfo::SetToScenarioFilename(const char *szScenFilename) @@ -630,10 +630,10 @@ int32_t C4ClientPlayerInfos::GetJoinedPlayerCount() const } void C4ClientPlayerInfos::CompileFunc(StdCompiler *pComp) - { - bool fCompiler = pComp->isCompiler(); - if(fCompiler) Clear(); - pComp->Value(mkNamingAdapt(iClientID, "ID", C4ClientIDUnknown)); + { + bool fCompiler = pComp->isCompiler(); + if(fCompiler) Clear(); + pComp->Value(mkNamingAdapt(iClientID, "ID", C4ClientIDUnknown)); // Flags StdBitfieldEntry Entries[] = @@ -645,22 +645,22 @@ void C4ClientPlayerInfos::CompileFunc(StdCompiler *pComp) { NULL, 0 } }; - pComp->Value(mkNamingAdapt(mkBitfieldAdapt(dwFlags, Entries), "Flags", 0u)); + pComp->Value(mkNamingAdapt(mkBitfieldAdapt(dwFlags, Entries), "Flags", 0u)); - pComp->Value(mkNamingCountAdapt(iPlayerCount, "Player")); - if(iPlayerCount < 0 || iPlayerCount > C4MaxPlayer) + pComp->Value(mkNamingCountAdapt(iPlayerCount, "Player")); + if(iPlayerCount < 0 || iPlayerCount > C4MaxPlayer) { pComp->excCorrupt("player count out of range"); return; } - // Grow list, if necessary - if(fCompiler && iPlayerCount > iPlayerCapacity) - { - GrowList(iPlayerCount - iPlayerCapacity); - ZeroMem(ppPlayers, sizeof(*ppPlayers) * iPlayerCount); - } - // Compile - pComp->Value(mkNamingAdapt(mkArrayAdaptMap(ppPlayers, iPlayerCount, mkPtrAdaptNoNull), "Player")); - // Force specialization - mkPtrAdaptNoNull(*ppPlayers); - } + // Grow list, if necessary + if(fCompiler && iPlayerCount > iPlayerCapacity) + { + GrowList(iPlayerCount - iPlayerCapacity); + ZeroMem(ppPlayers, sizeof(*ppPlayers) * iPlayerCount); + } + // Compile + pComp->Value(mkNamingAdapt(mkArrayAdaptMap(ppPlayers, iPlayerCount, mkPtrAdaptNoNull), "Player")); + // Force specialization + mkPtrAdaptNoNull(*ppPlayers); + } void C4ClientPlayerInfos::LoadResources() { @@ -770,7 +770,7 @@ bool C4PlayerInfoList::DoLocalNonNetworkPlayerInfoUpdate(C4ClientPlayerInfos *pU UpdatePlayerAttributes(pUpdate, true); // add through queue: This will add directly, do the record and put player joins into the queue // in running mode, this call will also put the actual player joins into the queue - ::Control.DoInput(CID_PlrInfo, new C4ControlPlayerInfo(*pUpdate), Game.IsRunning ? CDT_Queue : CDT_Direct); + ::Control.DoInput(CID_PlrInfo, new C4ControlPlayerInfo(*pUpdate), Game.IsRunning ? CDT_Queue : CDT_Direct); // done, success return true; } @@ -1215,11 +1215,11 @@ bool C4PlayerInfoList::Load(C4Group &hGroup, const char *szFromFile, C4LangStrin return true; // replace strings if (pLang) pLang->ReplaceStrings(Buf); - // (try to) compile - if(!CompileFromBuf_LogWarn( - mkNamingAdapt(*this, "PlayerInfoList"), - Buf, szFromFile)) - return false; + // (try to) compile + if(!CompileFromBuf_LogWarn( + mkNamingAdapt(*this, "PlayerInfoList"), + Buf, szFromFile)) + return false; // done, success return true; } @@ -1231,16 +1231,16 @@ bool C4PlayerInfoList::Save(C4Group &hGroup, const char *szToFile) // anything to save? if (!iClientCount) return true; // save it - try - { - // decompile - StdStrBuf Buf = DecompileToBuf( - mkNamingAdapt(*this, "PlayerInfoList")); + try + { + // decompile + StdStrBuf Buf = DecompileToBuf( + mkNamingAdapt(*this, "PlayerInfoList")); // save buffer to group hGroup.Add(szToFile, Buf, false, true); - } - catch(StdCompiler::Exception *) - { return false; } + } + catch(StdCompiler::Exception *) + { return false; } // done, success return true; } @@ -1613,7 +1613,7 @@ bool C4PlayerInfoList::RecreatePlayers() { const char *szName = pInfo->GetName(); if (!::Network.RetrieveRes(pJoinRes->getCore(), C4NetResRetrieveTimeout, - FormatString(LoadResStr("IDS_NET_RES_PLRFILE"), szName).getData())) + FormatString(LoadResStr("IDS_NET_RES_PLRFILE"), szName).getData())) szFilename=NULL; } // file present? @@ -1757,49 +1757,49 @@ bool C4PlayerInfoList::SetAsRestoreInfos(C4PlayerInfoList &rFromPlayers, bool fS } void C4PlayerInfoList::ResetLeagueProjectedGain(bool fSetUpdated) - { + { C4ClientPlayerInfos *pClient; int iClient=0; while ((pClient = GetIndexedInfo(iClient++))) { C4PlayerInfo *pInfo; int iInfo = 0; while ((pInfo = pClient->GetPlayerInfo(iInfo++))) - if (pInfo->IsLeagueProjectedGainValid()) - { - pInfo->ResetLeagueProjectedGain(); - if (fSetUpdated) - pClient->SetUpdated(); - } - } - } + if (pInfo->IsLeagueProjectedGainValid()) + { + pInfo->ResetLeagueProjectedGain(); + if (fSetUpdated) + pClient->SetUpdated(); + } + } + } void C4PlayerInfoList::CompileFunc(StdCompiler *pComp) { bool fCompiler = pComp->isCompiler(); - if(fCompiler) Clear(); + if(fCompiler) Clear(); // skip compiling if there is nothing to compile (cosmentics) if(!fCompiler && pComp->hasNaming() && iLastPlayerID == 0 && iClientCount == 0) return; // header - pComp->Value(mkNamingAdapt(iLastPlayerID, "LastPlayerID", 0)); - // client count - int32_t iTemp = iClientCount; - pComp->Value(mkNamingCountAdapt(iTemp, "Client")); - if(iTemp < 0 || iTemp > C4MaxClient) + pComp->Value(mkNamingAdapt(iLastPlayerID, "LastPlayerID", 0)); + // client count + int32_t iTemp = iClientCount; + pComp->Value(mkNamingCountAdapt(iTemp, "Client")); + if(iTemp < 0 || iTemp > C4MaxClient) { pComp->excCorrupt("client count out of range"); return; } - // grow list - if(fCompiler) - { - if(iTemp > iClientCapacity) GrowList(iTemp - iClientCapacity); - iClientCount = iTemp; - ZeroMem(ppClients, sizeof(*ppClients) * iClientCount); - } + // grow list + if(fCompiler) + { + if(iTemp > iClientCapacity) GrowList(iTemp - iClientCapacity); + iClientCount = iTemp; + ZeroMem(ppClients, sizeof(*ppClients) * iClientCount); + } // client packets - pComp->Value( - mkNamingAdapt( - mkArrayAdaptMap(ppClients, iClientCount, mkPtrAdaptNoNull), - "Client")); - // force compiler to specialize - mkPtrAdaptNoNull(*ppClients); + pComp->Value( + mkNamingAdapt( + mkArrayAdaptMap(ppClients, iClientCount, mkPtrAdaptNoNull), + "Client")); + // force compiler to specialize + mkPtrAdaptNoNull(*ppClients); } int32_t C4PlayerInfoList::GetStartupCount() @@ -1839,12 +1839,12 @@ void C4PlayerInfoList::FixIDCounter() /* -- Player info packets -- */ void C4PacketPlayerInfoUpdRequest::CompileFunc(StdCompiler *pComp) - { - pComp->Value(Info); - } + { + pComp->Value(Info); + } void C4PacketPlayerInfo::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(fIsRecreationInfo, "Recreation", false)); - pComp->Value(mkNamingAdapt(Info, "Info")); - } + { + pComp->Value(mkNamingAdapt(fIsRecreationInfo, "Recreation", false)); + pComp->Value(mkNamingAdapt(Info, "Info")); + } diff --git a/src/control/C4PlayerInfo.h b/src/control/C4PlayerInfo.h index 31eb18868..ab2b6e2f5 100644 --- a/src/control/C4PlayerInfo.h +++ b/src/control/C4PlayerInfo.h @@ -55,9 +55,9 @@ class C4PlayerInfo PIF_TempFile = 1<<5, // player file is temporary and to be deleted after join recreation PIF_InScenarioFile = 1<<6, // player file is present within the scenario; res is not to be used PIF_JoinedForSavegameOnly = 1<<7, // player file has been specified to take over a savegame player; do not join as normal player if association fails - PIF_Disconnected = 1<<8, // the player was removed because his client disconnected - PIF_Won = 1<<9, // player survived until game end (for game evaluation only) - PIF_VotedOut = 1<<10, // player was removed from the round after a successful voting + PIF_Disconnected = 1<<8, // the player was removed because his client disconnected + PIF_Won = 1<<9, // player survived until game end (for game evaluation only) + PIF_VotedOut = 1<<10, // player was removed from the round after a successful voting PIF_AttributesFixed= 1<<11, // player color and name aren't changed on collision PIF_NoScenarioInit = 1<<12, // do not call ScenariInit for this player PIF_NoEliminationCheck = 1<<13, // do not eliminate player if crew is empty @@ -141,8 +141,8 @@ class C4PlayerInfo { dwFlags |= PIF_VotedOut; } void SetLeagueProjectedGain(int32_t iProjectedGain) { assert(iProjectedGain>=0); iLeagueProjectedGain = iProjectedGain; } - void ResetLeagueProjectedGain() - { iLeagueProjectedGain = -1; } + void ResetLeagueProjectedGain() + { iLeagueProjectedGain = -1; } void SetForcedName(const char *szNewName) { if (szNewName) sForcedName.CopyValidated(szNewName); else sForcedName.Clear(); } @@ -184,7 +184,7 @@ class C4PlayerInfo int32_t getLeagueRankSymbol() const { return iLeagueRankSymbol; } // returns rank symbol on league server (0 for not assigned) int32_t getLeagueScoreProjected() const { return iLeagueScoreProjected; } // returns score on league server in case of win (0 for not assigned) int32_t GetInGameNumber() const { return iInGameNumber; } // returns player number the player had in the game - bool IsLeagueProjectedGainValid() const { return iLeagueProjectedGain>=0; } + bool IsLeagueProjectedGainValid() const { return iLeagueProjectedGain>=0; } int32_t GetLeagueProjectedGain() const { return iLeagueProjectedGain; } // get score gain in primary league if this player's team wins int32_t GetID() const { return iID; } // get unique ID, if assigned @@ -193,8 +193,8 @@ class C4PlayerInfo DWORD GetFlags() { return dwFlags; } // for dbg print only - void SetDisconnected() { dwFlags |= PIF_Disconnected; } - void SetWinner() { dwFlags |= PIF_Won; } + void SetDisconnected() { dwFlags |= PIF_Disconnected; } + void SetWinner() { dwFlags |= PIF_Won; } bool LoadBigIcon(C4FacetSurface &fctTarget); // load BigIcon.png of player into target facet; return false if no bigicon present or player file not yet loaded }; @@ -412,7 +412,7 @@ class C4PlayerInfoList bool SetAsRestoreInfos(C4PlayerInfoList &rFromPlayers, bool fSaveUserPlrs, bool fSaveScriptPlrs, bool fSetUserPlrRefToLocalGroup, bool fSetScriptPlrRefToLocalGroup); // copy all joined players from player list bool RemoveUnassociatedPlayers(C4PlayerInfoList &rSavegamePlayers); // remove all savegame players that are not associated to this list from the game int32_t GetFreePlayerSlotCount(); // get number of players that may still join - void ResetLeagueProjectedGain(bool fSetUpdated); // reset known projected gains for all players (to be updated by league again) + void ResetLeagueProjectedGain(bool fSetUpdated); // reset known projected gains for all players (to be updated by league again) // network: Load all resources connected with the players that are not being loaded yet void LoadResources(); diff --git a/src/control/C4Record.cpp b/src/control/C4Record.cpp index 4eda8c69b..ad9985700 100644 --- a/src/control/C4Record.cpp +++ b/src/control/C4Record.cpp @@ -151,7 +151,7 @@ bool C4Record::Start(bool fInitial) Index++; // compose record filename - sFilename.Format("%s" DirSep "%03i-%s.c4s", sDemoFolder.getData(), Index, sScenName); + sFilename.Format("%s" DirSep "%03i-%s.c4s", sDemoFolder.getData(), Index, sScenName); // log StdStrBuf sLog; sLog.Format(LoadResStr("IDS_PRC_RECORDINGTO"),sFilename.getData()); @@ -185,9 +185,9 @@ bool C4Record::Start(bool fInitial) } bool C4Record::Stop(StdStrBuf *pRecordName, BYTE *pRecordSHA1) - { + { // safety - if (!fRecording) return false; + if (!fRecording) return false; if (!DirectoryExists(sFilename.getData())) return false; // streaming finished @@ -220,35 +220,35 @@ bool C4Record::Stop(StdStrBuf *pRecordName, BYTE *pRecordSHA1) if(!C4Group_GetFileSHA1(sFilename.getData(), pRecordSHA1)) return false; - // ok + // ok fRecording = false; - return true; - } + return true; + } bool C4Record::Rec(const C4Control &Ctrl, int iFrame) - { - if(!fRecording) return false; + { + if(!fRecording) return false; // don't record empty control if(!Ctrl.firstPkt()) return true; - // create copy - C4Control Cpy; Cpy.Copy(Ctrl); - // prepare it for record - Cpy.PreRec(this); - // record it - return Rec(iFrame, DecompileToBuf(Cpy), RCT_Ctrl); - } + // create copy + C4Control Cpy; Cpy.Copy(Ctrl); + // prepare it for record + Cpy.PreRec(this); + // record it + return Rec(iFrame, DecompileToBuf(Cpy), RCT_Ctrl); + } bool C4Record::Rec(C4PacketType eCtrlType, C4ControlPacket *pCtrl, int iFrame) - { - if(!fRecording) return false; - // create copy - C4IDPacket Pkt = C4IDPacket(eCtrlType, pCtrl, false); if(!Pkt.getPkt()) return false; - C4ControlPacket *pCtrlCpy = static_cast(Pkt.getPkt()); - // prepare for recording - pCtrlCpy->PreRec(this); - // record it - return Rec(iFrame, DecompileToBuf(Pkt), RCT_CtrlPkt); - } + { + if(!fRecording) return false; + // create copy + C4IDPacket Pkt = C4IDPacket(eCtrlType, pCtrl, false); if(!Pkt.getPkt()) return false; + C4ControlPacket *pCtrlCpy = static_cast(Pkt.getPkt()); + // prepare for recording + pCtrlCpy->PreRec(this); + // record it + return Rec(iFrame, DecompileToBuf(Pkt), RCT_CtrlPkt); + } bool C4Record::Rec(int iFrame, const StdBuf &sBuf, C4RecordChunkType eType) { @@ -399,7 +399,7 @@ C4Playback::~C4Playback() } bool C4Playback::Open(C4Group &rGrp) - { + { // clean up Clear(); fLoadSequential = !rGrp.IsPacked(); @@ -513,7 +513,7 @@ bool C4Playback::Open(C4Group &rGrp) #endif // ok return true; - } + } bool C4Playback::ReadBinary(const StdBuf &Buf) { @@ -784,7 +784,7 @@ void C4Playback::Strip() } break; default: - // TODO + // TODO break; } } @@ -817,7 +817,7 @@ void C4Playback::Strip() if (fStripMessages) fStripThis=true; break; default: - // TODO + // TODO break; } if (fStripThis) @@ -847,13 +847,13 @@ void C4Playback::Strip() bool C4Playback::ExecuteControl(C4Control *pCtrl, int iFrame) { - // still playbacking? + // still playbacking? if (currChunk == chunks.end()) return false; if (Finished) { Finish(); return false; } #ifdef DEBUGREC - if(DebugRec.firstPkt()) - DebugRecError("Debug rec overflow!"); - DebugRec.Clear(); + if(DebugRec.firstPkt()) + DebugRecError("Debug rec overflow!"); + DebugRec.Clear(); #endif // return all control until this frame while(currChunk != chunks.end() && currChunk->Frame <= iFrame) @@ -862,9 +862,9 @@ bool C4Playback::ExecuteControl(C4Control *pCtrl, int iFrame) { case RCT_Ctrl: pCtrl->Append(*currChunk->pCtrl); - break; + break; - case RCT_CtrlPkt: + case RCT_CtrlPkt: { C4IDPacket Packet(*currChunk->pPkt); pCtrl->Add(Packet.getPktType(), static_cast(Packet.getPkt())); @@ -878,7 +878,7 @@ bool C4Playback::ExecuteControl(C4Control *pCtrl, int iFrame) break; #ifdef DEBUGREC - default: // expect it to be debug rec + default: // expect it to be debug rec // append to debug rec buffer if (currChunk->pDbg) { @@ -886,20 +886,20 @@ bool C4Playback::ExecuteControl(C4Control *pCtrl, int iFrame) // the debugrec buffer is now responsible for deleting the packet currChunk->pDbg = NULL; } - break; + break; #endif } // next chunk NextChunk(); } - // Debug log + // Debug log #ifdef DEBUGREC //sprintf(OSTR, "-- Frame %d:", Game.FrameCounter); Log(OSTR); //char Indent[256+1]; strcpy(Indent, ""); //pCtrl->deb_print(Indent); #endif - return true; + return true; } void C4Playback::Finish() @@ -1127,7 +1127,7 @@ bool C4Playback::StreamToRecord(const char *szStream, StdStrBuf *pRecordFile) { // Initialize stream - z_stream strm; + z_stream strm; ZeroMem(&strm, sizeof strm); strm.next_in = getMBufPtr(CompressedData); strm.avail_in = CompressedData.getSize(); diff --git a/src/control/C4Record.h b/src/control/C4Record.h index c49dae75b..ebfee22f5 100644 --- a/src/control/C4Record.h +++ b/src/control/C4Record.h @@ -270,11 +270,11 @@ class C4Record // demo recording const StdBuf &GetStreamingBuf() const { return StreamingData; } bool Start(bool fInitial); - bool Stop(StdStrBuf *pRecordName = NULL, BYTE *pRecordSHA1 = NULL); + bool Stop(StdStrBuf *pRecordName = NULL, BYTE *pRecordSHA1 = NULL); - bool Rec(const C4Control &Ctrl, int iFrame); // record control - bool Rec(C4PacketType eCtrlType, C4ControlPacket *pCtrl, int iFrame); // record control packet - bool Rec(int iFrame, const StdBuf &sBuf, C4RecordChunkType eType); + bool Rec(const C4Control &Ctrl, int iFrame); // record control + bool Rec(C4PacketType eCtrlType, C4ControlPacket *pCtrl, int iFrame); // record control packet + bool Rec(int iFrame, const StdBuf &sBuf, C4RecordChunkType eType); bool AddFile(const char *szLocalFilename, const char *szAddAs, bool fDelete = false); @@ -300,7 +300,7 @@ class C4Playback // demo playback uint32_t iLastSequentialFrame; // frame number of last chunk read void Finish(); // end playback #ifdef DEBUGREC - C4PacketList DebugRec; + C4PacketList DebugRec; #endif public: C4Playback(); // constructor; init playback @@ -319,7 +319,7 @@ class C4Playback // demo playback void Clear(); #ifdef DEBUGREC void Check(C4RecordChunkType eType, const uint8_t *pData, int iSize); // compare with debugrec - void DebugRecError(const char *szError); + void DebugRecError(const char *szError); #endif static bool StreamToRecord(const char *szStream, StdStrBuf *pRecord); }; diff --git a/src/control/C4RoundResults.cpp b/src/control/C4RoundResults.cpp index f024fcdfb..1e9634044 100644 --- a/src/control/C4RoundResults.cpp +++ b/src/control/C4RoundResults.cpp @@ -42,12 +42,12 @@ void C4RoundResultsPlayer::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(iLeagueScoreGain, "GameScore", -1)); // name used in league reply! pComp->Value(mkNamingAdapt(iLeagueRankNew, "Rank", 0)); // name used in league reply! pComp->Value(mkNamingAdapt(iLeagueRankSymbolNew, "RankSymbol", 0)); // name used in league reply! - StdEnumEntry LeagueStatusEntries[] = - { - { "", RRPLS_Unknown }, - { "Lost", RRPLS_Lost }, - { "Won", RRPLS_Won }, - }; + StdEnumEntry LeagueStatusEntries[] = + { + { "", RRPLS_Unknown }, + { "Lost", RRPLS_Lost }, + { "Won", RRPLS_Won }, + }; pComp->Value(mkNamingAdapt(mkEnumAdaptT(eLeagueStatus, LeagueStatusEntries), "Status", RRPLS_Unknown)); // name used in league reply! } @@ -143,22 +143,22 @@ void C4RoundResultsPlayers::Clear() void C4RoundResultsPlayers::CompileFunc(StdCompiler *pComp) { bool fCompiler = pComp->isCompiler(); - if(fCompiler) Clear(); + if(fCompiler) Clear(); int32_t iTemp = iPlayerCount; - pComp->Value(mkNamingCountAdapt(iTemp, "Player")); - if(iTemp < 0 || iTemp > C4MaxPlayer) + pComp->Value(mkNamingCountAdapt(iTemp, "Player")); + if(iTemp < 0 || iTemp > C4MaxPlayer) { pComp->excCorrupt("player count out of range"); return; } - // Grow list, if necessary - if(fCompiler && iTemp > iPlayerCapacity) - { - GrowList(iTemp - iPlayerCapacity); + // Grow list, if necessary + if(fCompiler && iTemp > iPlayerCapacity) + { + GrowList(iTemp - iPlayerCapacity); iPlayerCount = iTemp; - ZeroMem(ppPlayers, sizeof(*ppPlayers) * iPlayerCount); - } - // Compile - pComp->Value(mkNamingAdapt(mkArrayAdaptMap(ppPlayers, iPlayerCount, mkPtrAdaptNoNull), "Player")); - // Force specialization - mkPtrAdaptNoNull(*ppPlayers); + ZeroMem(ppPlayers, sizeof(*ppPlayers) * iPlayerCount); + } + // Compile + pComp->Value(mkNamingAdapt(mkArrayAdaptMap(ppPlayers, iPlayerCount, mkPtrAdaptNoNull), "Player")); + // Force specialization + mkPtrAdaptNoNull(*ppPlayers); } C4RoundResultsPlayer *C4RoundResultsPlayers::GetByIndex(int32_t idx) const @@ -256,22 +256,22 @@ void C4RoundResults::Init() void C4RoundResults::CompileFunc(StdCompiler *pComp) { - bool fCompiler = pComp->isCompiler(); - if(fCompiler) Clear(); - pComp->Value(mkNamingAdapt(Goals, "Goals", C4IDList())); + bool fCompiler = pComp->isCompiler(); + if(fCompiler) Clear(); + pComp->Value(mkNamingAdapt(Goals, "Goals", C4IDList())); pComp->Value(mkNamingAdapt(iPlayingTime, "PlayingTime", 0u)); pComp->Value(mkNamingAdapt(fHideSettlementScore, "HideSettlementScore", Game.C4S.Game.IsMelee())); pComp->Value(mkNamingAdapt(sCustomEvaluationStrings, "CustomEvaluationStrings", StdCopyStrBuf())); pComp->Value(mkNamingAdapt(iLeaguePerformance, "LeaguePerformance", 0)); pComp->Value(mkNamingAdapt(Players, "PlayerInfos", C4RoundResultsPlayers())); pComp->Value(mkNamingAdapt(sNetResult, "NetResult", StdCopyStrBuf())); - StdEnumEntry NetResultEntries[] = - { - { "", NR_None }, - { "LeagueOK", NR_LeagueOK }, - { "LeagueError", NR_LeagueError}, + StdEnumEntry NetResultEntries[] = + { + { "", NR_None }, + { "LeagueOK", NR_LeagueOK }, + { "LeagueError", NR_LeagueError}, { "NetError", NR_NetError }, - }; + }; pComp->Value(mkNamingAdapt(mkEnumAdaptT(eNetResult, NetResultEntries), "NetResult", NR_None)); } @@ -397,16 +397,16 @@ bool C4RoundResults::Save(C4Group &hGroup, const char *szFilename) // remove previous entry from group hGroup.DeleteEntry(szFilename); // decompile - try - { - StdStrBuf Buf = DecompileToBuf(mkNamingAdapt(*this, "RoundResults")); + try + { + StdStrBuf Buf = DecompileToBuf(mkNamingAdapt(*this, "RoundResults")); // save it, if not empty if (Buf.getLength()) if (!hGroup.Add(szFilename, Buf, false, true)) return false; - } - catch(StdCompiler::Exception *) - { return false; } + } + catch(StdCompiler::Exception *) + { return false; } // done, success return true; } @@ -415,9 +415,9 @@ bool C4RoundResults::Save(C4Group &hGroup, const char *szFilename) // *** C4PacketLeagueRoundResults void C4PacketLeagueRoundResults::CompileFunc(StdCompiler *pComp) - { + { pComp->Value(mkNamingAdapt(fSuccess, "Success", false)); pComp->Value(mkNamingAdapt(sResultsString, "ResultString", StdCopyStrBuf())); - pComp->Value(Players); - } + pComp->Value(Players); + } diff --git a/src/control/C4Teams.cpp b/src/control/C4Teams.cpp index 3a9183ff4..39469ced1 100644 --- a/src/control/C4Teams.cpp +++ b/src/control/C4Teams.cpp @@ -131,12 +131,12 @@ int32_t C4Team::GetFirstUnjoinedPlayerID() const void C4Team::CompileFunc(StdCompiler *pComp) { if (pComp->isCompiler()) Clear(); - pComp->Value(mkNamingAdapt(iID, "id", 0)); - pComp->Value(mkNamingAdapt(mkStringAdaptMA(Name), "Name", "")); + pComp->Value(mkNamingAdapt(iID, "id", 0)); + pComp->Value(mkNamingAdapt(mkStringAdaptMA(Name), "Name", "")); pComp->Value(mkNamingAdapt(iPlrStartIndex, "PlrStartIndex", 0)); - pComp->Value(mkNamingAdapt(iPlayerCount, "PlayerCount", 0)); - if(pComp->isCompiler()) { delete [] piPlayers; piPlayers = new int32_t [iPlayerCapacity = iPlayerCount]; ZeroMem(piPlayers, sizeof(*piPlayers) * iPlayerCount); } - pComp->Value(mkNamingAdapt(mkArrayAdapt(piPlayers, iPlayerCount, -1), "Players")); + pComp->Value(mkNamingAdapt(iPlayerCount, "PlayerCount", 0)); + if(pComp->isCompiler()) { delete [] piPlayers; piPlayers = new int32_t [iPlayerCapacity = iPlayerCount]; ZeroMem(piPlayers, sizeof(*piPlayers) * iPlayerCount); } + pComp->Value(mkNamingAdapt(mkArrayAdapt(piPlayers, iPlayerCount, -1), "Players")); pComp->Value(mkNamingAdapt(dwClr, "Color", 0u)); pComp->Value(mkNamingAdapt(sIconSpec, "IconSpec", StdCopyStrBuf())); pComp->Value(mkNamingAdapt(iMaxPlayer, "MaxPlayer", 0)); @@ -542,12 +542,12 @@ bool C4TeamList::IsJoin2TeamAllowed(int32_t idTeam) void C4TeamList::CompileFunc(StdCompiler *pComp) { // if (pComp->isCompiler()) Clear(); - do not clear, because this would corrupt the fCustom-flag - pComp->Value(mkNamingAdapt(fActive, "Active", true)); - pComp->Value(mkNamingAdapt(fCustom, "Custom", true)); - pComp->Value(mkNamingAdapt(fAllowHostilityChange, "AllowHostilityChange", false)); + pComp->Value(mkNamingAdapt(fActive, "Active", true)); + pComp->Value(mkNamingAdapt(fCustom, "Custom", true)); + pComp->Value(mkNamingAdapt(fAllowHostilityChange, "AllowHostilityChange", false)); pComp->Value(mkNamingAdapt(fAllowTeamSwitch, "AllowTeamSwitch", false)); pComp->Value(mkNamingAdapt(fAutoGenerateTeams, "AutoGenerateTeams", false)); - pComp->Value(mkNamingAdapt(iLastTeamID, "LastTeamID", 0)); + pComp->Value(mkNamingAdapt(iLastTeamID, "LastTeamID", 0)); StdEnumEntry TeamDistEntries[] = { @@ -563,9 +563,9 @@ void C4TeamList::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(sScriptPlayerNames, "ScriptPlayerNames", StdStrBuf())); int32_t iOldTeamCount = iTeamCount; - pComp->Value(mkNamingCountAdapt(iTeamCount, "Team")); + pComp->Value(mkNamingCountAdapt(iTeamCount, "Team")); - if (pComp->isCompiler()) + if (pComp->isCompiler()) { while (iOldTeamCount--) delete ppList[iOldTeamCount]; delete [] ppList; @@ -646,14 +646,14 @@ bool C4TeamList::Save(C4Group &hGroup) // remove previous entry from group hGroup.DeleteEntry(C4CFN_Teams); // decompile - try - { - StdStrBuf Buf = DecompileToBuf(mkNamingAdapt(*this, "Teams")); + try + { + StdStrBuf Buf = DecompileToBuf(mkNamingAdapt(*this, "Teams")); // save it hGroup.Add(C4CFN_Teams, Buf, false, true); - } - catch(StdCompiler::Exception *) - { return false; } + } + catch(StdCompiler::Exception *) + { return false; } // done, success return true; } diff --git a/src/editor/C4Console.cpp b/src/editor/C4Console.cpp index e37695a63..15ddf9ae1 100644 --- a/src/editor/C4Console.cpp +++ b/src/editor/C4Console.cpp @@ -102,8 +102,8 @@ namespace { #endif #define FILE_SELECT_FILTER_FOR_C4S "Clonk 4 Scenario\0" \ - "*.c4s;*.c4f;Scenario.txt\0" \ - "\0" + "*.c4s;*.c4f;Scenario.txt\0" \ + "\0" C4Console::C4Console() { @@ -161,30 +161,30 @@ INT_PTR CALLBACK ConsoleDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lPara { switch (Msg) { - //------------------------------------------------------------------------------------------------------------ - case WM_ACTIVATEAPP: - Application.Active = wParam != 0; - return true; - //------------------------------------------------------------------------------------------------------------ - case WM_DESTROY: + //------------------------------------------------------------------------------------------------------------ + case WM_ACTIVATEAPP: + Application.Active = wParam != 0; + return true; + //------------------------------------------------------------------------------------------------------------ + case WM_DESTROY: StoreWindowPosition(hDlg, "Main", Config.GetSubkeyPath("Console"), false); Application.Quit(); return true; - //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ case WM_CLOSE: Console.Close(); return true; - //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ case MM_MCINOTIFY: if (wParam == MCI_NOTIFY_SUCCESSFUL) Application.MusicSystem.NotifySuccess(); return true; - //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ case WM_INITDIALOG: - SendMessage(hDlg,DM_SETDEFID,(WPARAM)IDOK,(LPARAM)0); + SendMessage(hDlg,DM_SETDEFID,(WPARAM)IDOK,(LPARAM)0); Console.UpdateMenuText(GetMenu(hDlg)); - return true; - //------------------------------------------------------------------------------------------------------------ + return true; + //------------------------------------------------------------------------------------------------------------ case WM_COMMAND: // Evaluate command switch (LOWORD(wParam)) @@ -269,25 +269,25 @@ INT_PTR CALLBACK ConsoleDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lPara return true; } return false; - //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ case WM_USER_LOG: if (SEqual2((const char *)lParam, "IDS_")) Log(LoadResStr((const char *)lParam)); else Log((const char *)lParam); return false; - //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ case WM_COPYDATA: - COPYDATASTRUCT* pcds = reinterpret_cast(lParam); - if(pcds->dwData == WM_USER_RELOADFILE) - { - // get path, ensure proper termination - const char *szPath = reinterpret_cast(pcds->lpData); - if(szPath[pcds->cbData - 1]) break; - // reload - Game.ReloadFile(szPath); - } - return false; + COPYDATASTRUCT* pcds = reinterpret_cast(lParam); + if(pcds->dwData == WM_USER_RELOADFILE) + { + // get path, ensure proper termination + const char *szPath = reinterpret_cast(pcds->lpData); + if(szPath[pcds->cbData - 1]) break; + // reload + Game.ReloadFile(szPath); + } + return false; } return false; @@ -1331,7 +1331,7 @@ void C4Console::EditScript() { if (::Network.isEnabled()) return; Game.Script.Open(); - ::ScriptEngine.ReLink(&::Definitions); + ::ScriptEngine.ReLink(&::Definitions); } void C4Console::EditInfo() diff --git a/src/editor/C4Console.h b/src/editor/C4Console.h index ea3b212cf..b639910ff 100644 --- a/src/editor/C4Console.h +++ b/src/editor/C4Console.h @@ -36,8 +36,8 @@ #endif const int C4CNS_ModePlay = 0, - C4CNS_ModeEdit = 1, - C4CNS_ModeDraw = 2; + C4CNS_ModeEdit = 1, + C4CNS_ModeDraw = 2; #define IDM_NET_CLIENT1 10000 #define IDM_NET_CLIENT2 10100 diff --git a/src/editor/C4EditCursor.cpp b/src/editor/C4EditCursor.cpp index ae353c096..381aa83f8 100644 --- a/src/editor/C4EditCursor.cpp +++ b/src/editor/C4EditCursor.cpp @@ -64,23 +64,23 @@ C4EditCursor::~C4EditCursor() void C4EditCursor::Execute() { - // alt check - bool fAltIsDown = Application.IsAltDown(); - if (fAltIsDown != fAltWasDown) + // alt check + bool fAltIsDown = Application.IsAltDown(); + if (fAltIsDown != fAltWasDown) { if ((fAltWasDown = fAltIsDown)) AltDown(); else AltUp(); } - // drawing + // drawing switch (Mode) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case C4CNS_ModeEdit: // Hold selection if (Hold) - EMMoveObject(EMMO_Move, 0, 0, NULL, &Selection); + EMMoveObject(EMMO_Move, 0, 0, NULL, &Selection); break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case C4CNS_ModeDraw: @@ -398,8 +398,8 @@ bool C4EditCursor::OpenPropTools() bool C4EditCursor::Duplicate() { - EMMoveObject(EMMO_Duplicate, 0, 0, NULL, &Selection); - return true; + EMMoveObject(EMMO_Duplicate, 0, 0, NULL, &Selection); + return true; } void C4EditCursor::Draw(C4TargetFacet &cgo, float Zoom) @@ -476,13 +476,13 @@ void C4EditCursor::DrawSelectMark(C4Facet &cgo, FLOAT_RECT frame) void C4EditCursor::MoveSelection(int32_t iXOff, int32_t iYOff) { - EMMoveObject(EMMO_Move, iXOff, iYOff, NULL, &Selection); + EMMoveObject(EMMO_Move, iXOff, iYOff, NULL, &Selection); } void C4EditCursor::FrameSelection() { Selection.Clear(); - C4Object *cobj; C4ObjectLink *clnk; + C4Object *cobj; C4ObjectLink *clnk; for (clnk=::Objects.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) if (cobj->Status) if (cobj->OCF & OCF_NotContained) { @@ -494,13 +494,13 @@ void C4EditCursor::FrameSelection() bool C4EditCursor::In(const char *szText) { - EMMoveObject(EMMO_Script, 0, 0, NULL, &Selection, szText); + EMMoveObject(EMMO_Script, 0, 0, NULL, &Selection, szText); return true; } void C4EditCursor::Default() { - fAltWasDown=false; + fAltWasDown=false; Mode=C4CNS_ModePlay; X=Y=X2=Y2=0; Target=DropTarget=NULL; @@ -587,7 +587,7 @@ void C4EditCursor::ApplyToolBrush() { if (!EditingOK()) return; C4ToolsDlg *pTools=&Console.ToolsDlg; - // execute/send control + // execute/send control EMControl(CID_EMDrawTool, new C4ControlEMDrawTool(EMDT_Brush, ::Landscape.Mode, X,Y,0,0, pTools->Grade, !!pTools->ModeIFT, pTools->Material,pTools->Texture)); } @@ -595,7 +595,7 @@ void C4EditCursor::ApplyToolLine() { if (!EditingOK()) return; C4ToolsDlg *pTools=&Console.ToolsDlg; - // execute/send control + // execute/send control EMControl(CID_EMDrawTool, new C4ControlEMDrawTool(EMDT_Line, ::Landscape.Mode, X,Y,X2,Y2, pTools->Grade, !!pTools->ModeIFT, pTools->Material,pTools->Texture)); } @@ -603,7 +603,7 @@ void C4EditCursor::ApplyToolRect() { if (!EditingOK()) return; C4ToolsDlg *pTools=&Console.ToolsDlg; - // execute/send control + // execute/send control EMControl(CID_EMDrawTool, new C4ControlEMDrawTool(EMDT_Rect, ::Landscape.Mode, X,Y,X2,Y2, pTools->Grade, !!pTools->ModeIFT, pTools->Material,pTools->Texture)); } @@ -611,7 +611,7 @@ void C4EditCursor::ApplyToolFill() { if (!EditingOK()) return; C4ToolsDlg *pTools=&Console.ToolsDlg; - // execute/send control + // execute/send control EMControl(CID_EMDrawTool, new C4ControlEMDrawTool(EMDT_Fill, ::Landscape.Mode, X,Y,0,Y2, pTools->Grade, false, pTools->Material)); } @@ -668,12 +668,12 @@ void C4EditCursor::GrabContents() Hold=true; // Exit all objects - EMMoveObject(EMMO_Exit, 0, 0, NULL, &Selection); + EMMoveObject(EMMO_Exit, 0, 0, NULL, &Selection); } void C4EditCursor::UpdateDropTarget(WORD wKeyFlags) { - C4Object *cobj; C4ObjectLink *clnk; + C4Object *cobj; C4ObjectLink *clnk; DropTarget=NULL; @@ -692,7 +692,7 @@ void C4EditCursor::UpdateDropTarget(WORD wKeyFlags) void C4EditCursor::PutContents() { if (!DropTarget) return; - EMMoveObject(EMMO_Enter, 0, 0, DropTarget, &Selection); + EMMoveObject(EMMO_Enter, 0, 0, DropTarget, &Selection); } C4Object *C4EditCursor::GetTarget() @@ -759,69 +759,69 @@ void C4EditCursor::ApplyToolPicker() } void C4EditCursor::EMMoveObject(C4ControlEMObjectAction eAction, int32_t tx, int32_t ty, C4Object *pTargetObj, const C4ObjectList *pObjs, const char *szScript) - { - // construct object list - int32_t iObjCnt = 0; int32_t *pObjIDs = NULL; - if(pObjs && (iObjCnt = pObjs->ObjectCount())) - { - pObjIDs = new int32_t [iObjCnt]; - // fill - int32_t i = 0; - for(C4ObjectLink *pLnk = pObjs->First; pLnk; pLnk = pLnk->Next, i++) - if(pLnk->Obj && pLnk->Obj->Status) - pObjIDs[i] = pLnk->Obj->Number; - } + { + // construct object list + int32_t iObjCnt = 0; int32_t *pObjIDs = NULL; + if(pObjs && (iObjCnt = pObjs->ObjectCount())) + { + pObjIDs = new int32_t [iObjCnt]; + // fill + int32_t i = 0; + for(C4ObjectLink *pLnk = pObjs->First; pLnk; pLnk = pLnk->Next, i++) + if(pLnk->Obj && pLnk->Obj->Status) + pObjIDs[i] = pLnk->Obj->Number; + } - // execute control - EMControl(CID_EMMoveObj, new C4ControlEMMoveObject(eAction, tx, ty, pTargetObj, iObjCnt, pObjIDs, szScript)); + // execute control + EMControl(CID_EMMoveObj, new C4ControlEMMoveObject(eAction, tx, ty, pTargetObj, iObjCnt, pObjIDs, szScript)); - } + } void C4EditCursor::EMControl(C4PacketType eCtrlType, C4ControlPacket *pCtrl) - { - ::Control.DoInput(eCtrlType, pCtrl, CDT_Decide); - } + { + ::Control.DoInput(eCtrlType, pCtrl, CDT_Decide); + } #ifdef WITH_DEVELOPER_MODE // GTK+ callbacks void C4EditCursor::OnDelete(GtkWidget* widget, gpointer data) { - static_cast(data)->Delete(); + static_cast(data)->Delete(); } void C4EditCursor::OnDuplicate(GtkWidget* widget, gpointer data) { - static_cast(data)->Duplicate(); + static_cast(data)->Duplicate(); } void C4EditCursor::OnGrabContents(GtkWidget* widget, gpointer data) { - static_cast(data)->GrabContents(); + static_cast(data)->GrabContents(); } void C4EditCursor::OnProperties(GtkWidget* widget, gpointer data) { - static_cast(data)->OpenPropTools(); + static_cast(data)->OpenPropTools(); } #endif bool C4EditCursor::AltDown() - { - // alt only has an effect in draw mode (picker) - if (Mode == C4CNS_ModeDraw) - { - Console.ToolsDlg.SetAlternateTool(); - } - // key not processed - allow further usages of Alt - return false; - } + { + // alt only has an effect in draw mode (picker) + if (Mode == C4CNS_ModeDraw) + { + Console.ToolsDlg.SetAlternateTool(); + } + // key not processed - allow further usages of Alt + return false; + } bool C4EditCursor::AltUp() - { - if (Mode == C4CNS_ModeDraw) - { - Console.ToolsDlg.ResetAlternateTool(); - } - // key not processed - allow further usages of Alt - return false; - } + { + if (Mode == C4CNS_ModeDraw) + { + Console.ToolsDlg.ResetAlternateTool(); + } + // key not processed - allow further usages of Alt + return false; + } diff --git a/src/editor/C4EditCursor.h b/src/editor/C4EditCursor.h index 73cccb816..b607e9d4d 100644 --- a/src/editor/C4EditCursor.h +++ b/src/editor/C4EditCursor.h @@ -36,7 +36,7 @@ class C4EditCursor C4EditCursor(); ~C4EditCursor(); protected: - bool fAltWasDown; + bool fAltWasDown; bool fSelectionChanged; int32_t Mode; int32_t X,Y,X2,Y2; @@ -79,8 +79,8 @@ class C4EditCursor C4ObjectList &GetSelection() { return Selection; } void SetHold(bool fToState) { Hold = fToState; } void OnSelectionChanged(); - bool AltDown(); - bool AltUp(); + bool AltDown(); + bool AltUp(); protected: bool UpdateStatusBar(); void ApplyToolPicker(); @@ -96,8 +96,8 @@ class C4EditCursor void DrawSelectMark(C4Facet &cgo, FLOAT_RECT r); void FrameSelection(); void MoveSelection(int32_t iXOff, int32_t iYOff); - void EMMoveObject(enum C4ControlEMObjectAction eAction, int32_t tx, int32_t ty, C4Object *pTargetObj, const C4ObjectList *pObjs = NULL, const char *szScript = NULL); - void EMControl(enum C4PacketType eCtrlType, class C4ControlPacket *pCtrl); + void EMMoveObject(enum C4ControlEMObjectAction eAction, int32_t tx, int32_t ty, C4Object *pTargetObj, const C4ObjectList *pObjs = NULL, const char *szScript = NULL); + void EMControl(enum C4PacketType eCtrlType, class C4ControlPacket *pCtrl); #ifdef WITH_DEVELOPER_MODE static void OnDelete(GtkWidget* widget, gpointer data); diff --git a/src/editor/C4ObjectListDlg.cpp b/src/editor/C4ObjectListDlg.cpp index fc39b0ea3..74a6aa053 100644 --- a/src/editor/C4ObjectListDlg.cpp +++ b/src/editor/C4ObjectListDlg.cpp @@ -253,7 +253,7 @@ c4_list_iter_children (GtkTreeModel * tree_model, GtkTreeIter * iter, GtkTreeIte // Return true if 'parent' has children. static gboolean c4_list_iter_has_child (GtkTreeModel *tree_model, - GtkTreeIter *parent) + GtkTreeIter *parent) { g_return_val_if_fail (parent == NULL || parent->user_data != NULL, false); g_return_val_if_fail (C4_IS_LIST (tree_model), false); diff --git a/src/editor/C4PropertyDlg.cpp b/src/editor/C4PropertyDlg.cpp index 3ab764581..71da5aae5 100644 --- a/src/editor/C4PropertyDlg.cpp +++ b/src/editor/C4PropertyDlg.cpp @@ -64,7 +64,7 @@ BOOL CALLBACK PropertyDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam) break; //------------------------------------------------------------------------------------------------ case WM_INITDIALOG: - SendMessage(hDlg,DM_SETDEFID,(WPARAM)IDOK,(LPARAM)0); + SendMessage(hDlg,DM_SETDEFID,(WPARAM)IDOK,(LPARAM)0); return true; //------------------------------------------------------------------------------------------------ case WM_COMMAND: @@ -86,7 +86,7 @@ BOOL CALLBACK PropertyDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } return false; - //----------------------------------------------------------------------------------------------- + //----------------------------------------------------------------------------------------------- } return false; } @@ -178,7 +178,7 @@ bool C4PropertyDlg::Update(C4ObjectList &rSelection) bool IsObjectPointer(int iValue) { - for (C4ObjectLink *cLnk=::Objects.First; cLnk; cLnk=cLnk->Next) + for (C4ObjectLink *cLnk=::Objects.First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj == (C4Object*) iValue) return true; return false; diff --git a/src/editor/C4ToolsDlg.cpp b/src/editor/C4ToolsDlg.cpp index 0c47a2b9c..a24ee68eb 100644 --- a/src/editor/C4ToolsDlg.cpp +++ b/src/editor/C4ToolsDlg.cpp @@ -457,7 +457,7 @@ void C4ToolsDlg::Clear() bool C4ToolsDlg::SetTool(int32_t iTool, bool fTemp) { Tool=iTool; - if (!fTemp) SelectedTool = Tool; + if (!fTemp) SelectedTool = Tool; UpdateToolCtrls(); UpdatePreview(); return true; @@ -680,7 +680,7 @@ void C4ToolsDlg::UpdatePreview() // Material-Texture else { - bCol=Mat2PixColDefault(::MaterialMap.Get(Material)); + bCol=Mat2PixColDefault(::MaterialMap.Get(Material)); // Get/Create TexMap entry BYTE iTex = ::TextureMap.GetIndex(Material, Texture, true); if (iTex) @@ -755,11 +755,11 @@ void C4ToolsDlg::InitGradeCtrl() #ifdef _WIN32 if (!hDialog) return; HWND hwndTrack = GetDlgItem(hDialog,IDC_SLIDERGRADE); - SendMessage(hwndTrack,TBM_SETPAGESIZE,0,(LPARAM)5); - SendMessage(hwndTrack,TBM_SETLINESIZE,0,(LPARAM)1); - SendMessage(hwndTrack,TBM_SETRANGE,(WPARAM)false, - (LPARAM) MAKELONG(C4TLS_GradeMin,C4TLS_GradeMax)); - SendMessage(hwndTrack,TBM_SETPOS,(WPARAM)true,(LPARAM)C4TLS_GradeMax-Grade); + SendMessage(hwndTrack,TBM_SETPAGESIZE,0,(LPARAM)5); + SendMessage(hwndTrack,TBM_SETLINESIZE,0,(LPARAM)1); + SendMessage(hwndTrack,TBM_SETRANGE,(WPARAM)false, + (LPARAM) MAKELONG(C4TLS_GradeMin,C4TLS_GradeMax)); + SendMessage(hwndTrack,TBM_SETPOS,(WPARAM)true,(LPARAM)C4TLS_GradeMax-Grade); UpdateWindow(hwndTrack); #else #ifdef WITH_DEVELOPER_MODE @@ -1034,16 +1034,16 @@ bool C4ToolsDlg::SelectMaterial(const char *szMaterial) } void C4ToolsDlg::SetAlternateTool() - { - // alternate tool is the picker in any mode - SetTool(C4TLS_Picker, true); - } + { + // alternate tool is the picker in any mode + SetTool(C4TLS_Picker, true); + } void C4ToolsDlg::ResetAlternateTool() - { - // reset tool to selected tool in case alternate tool was set - SetTool(SelectedTool, true); - } + { + // reset tool to selected tool in case alternate tool was set + SetTool(SelectedTool, true); + } #ifdef WITH_DEVELOPER_MODE // GTK+ callbacks diff --git a/src/editor/C4ToolsDlg.h b/src/editor/C4ToolsDlg.h index 79ec6cac6..f38e20cda 100644 --- a/src/editor/C4ToolsDlg.h +++ b/src/editor/C4ToolsDlg.h @@ -150,8 +150,8 @@ class C4ToolsDlg bool ToggleIFT() { return !!SetIFT(!ModeIFT); } bool SelectTexture(const char *szTexture); bool SelectMaterial(const char *szMaterial); - void SetAlternateTool(); - void ResetAlternateTool(); + void SetAlternateTool(); + void ResetAlternateTool(); protected: void AssertValidTexture(); void LoadBitmaps(); diff --git a/src/game/C4GameVersion.h b/src/game/C4GameVersion.h index 49eac6011..f9b37cd7b 100644 --- a/src/game/C4GameVersion.h +++ b/src/game/C4GameVersion.h @@ -54,13 +54,13 @@ struct C4GameVersion // helper inline int CompareVersion(int iVer1, int iVer2, int iVer3, int iVer4, - int iRVer1 = C4XVER1, int iRVer2 = C4XVER2, int iRVer3 = C4XVER3, int iRVer4 = C4XVER4) + int iRVer1 = C4XVER1, int iRVer2 = C4XVER2, int iRVer3 = C4XVER3, int iRVer4 = C4XVER4) { - if(iVer1 > iRVer1) return 1; if(iVer1 < iRVer1) return -1; - if(iVer2 > iRVer2) return 1; if(iVer2 < iRVer2) return -1; - if(iVer3 > iRVer3) return 1; if(iVer3 < iRVer3) return -1; - if(iVer4 > iRVer4) return 1; if(iVer4 < iRVer4) return -1; - return 0; + if(iVer1 > iRVer1) return 1; if(iVer1 < iRVer1) return -1; + if(iVer2 > iRVer2) return 1; if(iVer2 < iRVer2) return -1; + if(iVer3 > iRVer3) return 1; if(iVer3 < iRVer3) return -1; + if(iVer4 > iRVer4) return 1; if(iVer4 < iRVer4) return -1; + return 0; } #endif // C4GAMEVERSION_H diff --git a/src/game/landscape/C4Landscape.cpp b/src/game/landscape/C4Landscape.cpp index 1eecbaeb9..3cfe06bd3 100644 --- a/src/game/landscape/C4Landscape.cpp +++ b/src/game/landscape/C4Landscape.cpp @@ -56,17 +56,17 @@ const int C4LS_MaxLightDistY = 8; const int C4LS_MaxLightDistX = 1; C4Landscape::C4Landscape() - { + { Default(); - } + } C4Landscape::~C4Landscape() - { + { Clear(); } void C4Landscape::ScenarioInit() - { + { // Gravity Gravity = FIXED100(Game.C4S.Landscape.Gravity.Evaluate()) /5; // Opens @@ -74,81 +74,81 @@ void C4Landscape::ScenarioInit() RightOpen=Game.C4S.Landscape.RightOpen; TopOpen=Game.C4S.Landscape.TopOpen; BottomOpen=Game.C4S.Landscape.BottomOpen; - // Side open scan - if (Game.C4S.Landscape.AutoScanSideOpen) ScanSideOpen(); - } + // Side open scan + if (Game.C4S.Landscape.AutoScanSideOpen) ScanSideOpen(); + } void C4Landscape::Execute() - { - // Landscape scan + { + // Landscape scan if (!NoScan) - ExecuteScan(); + ExecuteScan(); // move sky Sky.Execute(); - // Side open scan - /*if (!::Game.iTick255) - if (Game.C4S.LScape.AutoScanSideOpen) - ScanSideOpen(); */ + // Side open scan + /*if (!::Game.iTick255) + if (Game.C4S.LScape.AutoScanSideOpen) + ScanSideOpen(); */ #ifdef _DEBUG /*if(!::Game.iTick255) UpdatePixCnt(C4Rect(0, 0, Width, Height), true); if(!::Game.iTick255) - { - DWORD MatCountCheck[C4MaxMaterial], EffectiveMatCountCheck[C4MaxMaterial]; - int32_t iMat; - for(iMat = 0; iMat < ::MaterialMap.Num; iMat++) - { - MatCountCheck[iMat] = MatCount[iMat]; - EffectiveMatCountCheck[iMat] = EffectiveMatCount[iMat]; - } - ClearMatCount(); - UpdateMatCnt(C4Rect(0,0,Width,Height), true); - for(iMat = 0; iMat < ::MaterialMap.Num; iMat++) - { - assert(MatCount[iMat] == MatCountCheck[iMat]); - assert(EffectiveMatCount[iMat] == EffectiveMatCountCheck[iMat]); - } - }*/ + { + DWORD MatCountCheck[C4MaxMaterial], EffectiveMatCountCheck[C4MaxMaterial]; + int32_t iMat; + for(iMat = 0; iMat < ::MaterialMap.Num; iMat++) + { + MatCountCheck[iMat] = MatCount[iMat]; + EffectiveMatCountCheck[iMat] = EffectiveMatCount[iMat]; + } + ClearMatCount(); + UpdateMatCnt(C4Rect(0,0,Width,Height), true); + for(iMat = 0; iMat < ::MaterialMap.Num; iMat++) + { + assert(MatCount[iMat] == MatCountCheck[iMat]); + assert(EffectiveMatCount[iMat] == EffectiveMatCountCheck[iMat]); + } + }*/ #endif // Relights - if (!::Game.iTick35) + if (!::Game.iTick35) DoRelights(); - } + } void C4Landscape::ExecuteScan() - { + { - int32_t cy,mat; + int32_t cy,mat; - // Check: Scan needed? + // Check: Scan needed? const int32_t iTemperature = ::Weather.GetTemperature(); - for(mat = 0; mat < ::MaterialMap.Num; mat++) - if(MatCount[mat]) - { - if(::MaterialMap.Map[mat].BelowTempConvertTo && - iTemperature < ::MaterialMap.Map[mat].BelowTempConvert) - break; - else if(::MaterialMap.Map[mat].AboveTempConvertTo && - iTemperature > ::MaterialMap.Map[mat].AboveTempConvert) - break; - } - if(mat >= ::MaterialMap.Num) - return; + for(mat = 0; mat < ::MaterialMap.Num; mat++) + if(MatCount[mat]) + { + if(::MaterialMap.Map[mat].BelowTempConvertTo && + iTemperature < ::MaterialMap.Map[mat].BelowTempConvert) + break; + else if(::MaterialMap.Map[mat].AboveTempConvertTo && + iTemperature > ::MaterialMap.Map[mat].AboveTempConvert) + break; + } + if(mat >= ::MaterialMap.Num) + return; #ifdef DEBUGREC_MATSCAN AddDbgRec(RCT_MatScan, &ScanX, sizeof(ScanX)); #endif - for (int32_t cnt=0; cnt=Width) - ScanX=0; + // Scan advance & rewind + ScanX++; + if (ScanX>=Width) + ScanX=0; - } + } - } + } #define PRETTY_TEMP_CONV int32_t C4Landscape::DoScan(int32_t cx, int32_t cy, int32_t mat, int32_t dir) { - int32_t conv_to_tex = 0; + int32_t conv_to_tex = 0; int32_t iTemperature = ::Weather.GetTemperature(); - // Check below conv - if(::MaterialMap.Map[mat].BelowTempConvertDir == dir) + // Check below conv + if(::MaterialMap.Map[mat].BelowTempConvertDir == dir) if (::MaterialMap.Map[mat].BelowTempConvertTo) if (iTemperature< ::MaterialMap.Map[mat].BelowTempConvert) conv_to_tex=::MaterialMap.Map[mat].BelowTempConvertTo; - // Check above conv - if(::MaterialMap.Map[mat].AboveTempConvertDir == dir) + // Check above conv + if(::MaterialMap.Map[mat].AboveTempConvertDir == dir) if (::MaterialMap.Map[mat].AboveTempConvertTo) if (iTemperature>::MaterialMap.Map[mat].AboveTempConvert) conv_to_tex=::MaterialMap.Map[mat].AboveTempConvertTo; @@ -193,7 +193,7 @@ int32_t C4Landscape::DoScan(int32_t cx, int32_t cy, int32_t mat, int32_t dir) int32_t conv_to = ::TextureMap.GetEntry(conv_to_tex)->GetMaterialIndex(); // find mat top int32_t mconv = ::MaterialMap.Map[mat].TempConvStrength, - mconvs = mconv; + mconvs = mconv; #ifdef DEBUGREC_MATSCAN C4RCMatScan rc = { cx, cy, mat, conv_to, dir, mconvs }; AddDbgRec(RCT_MatScanDo, &rc, sizeof(C4RCMatScan)); @@ -267,13 +267,13 @@ int32_t C4Landscape::DoScan(int32_t cx, int32_t cy, int32_t mat, int32_t dir) } void C4Landscape::ScanSideOpen() - { - int32_t cy; - for (cy=0; (cyActivateBlitModulation(Modulation); - // do relights - DoRelights(); + // do relights + DoRelights(); // blit landscape if (::GraphicsSystem.ShowSolidMask) Application.DDraw->Blit8Fast(Surface8, cgo.TargetX, cgo.TargetY, cgo.Surface, cgo.X,cgo.Y,cgo.Wdt,cgo.Hgt); @@ -329,7 +329,7 @@ int32_t C4Landscape::ChunkyRandom(int32_t &iOffset, int32_t iRange) } void C4Landscape::DrawChunk(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, int32_t mcol, int32_t iChunkType, int32_t cro) - { + { BYTE top_rough = 0; BYTE side_rough = 0; // what to do? switch(iChunkType) @@ -347,38 +347,38 @@ void C4Landscape::DrawChunk(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, in top_rough = 1; side_rough = 2; break; } - int vtcs[16]; - int32_t rx=Max(wdt/2,1); + int vtcs[16]; + int32_t rx=Max(wdt/2,1); - vtcs[0]=tx-ChunkyRandom(cro,rx/2); vtcs[1]=ty-ChunkyRandom(cro,rx/2*top_rough); - vtcs[2]=tx-ChunkyRandom(cro,rx*side_rough); vtcs[3]=ty+hgt/2; - vtcs[4]=tx-ChunkyRandom(cro,rx); vtcs[5]=ty+hgt+ChunkyRandom(cro,rx); - vtcs[6]=tx+wdt/2; vtcs[7]=ty+hgt+ChunkyRandom(cro,2*rx); - vtcs[8]=tx+wdt+ChunkyRandom(cro,rx); vtcs[9]=ty+hgt+ChunkyRandom(cro,rx); - vtcs[10]=tx+wdt+ChunkyRandom(cro,rx*side_rough); vtcs[11]=ty+hgt/2; - vtcs[12]=tx+wdt+ChunkyRandom(cro,rx/2); vtcs[13]=ty-ChunkyRandom(cro,rx/2*top_rough); - vtcs[14]=tx+wdt/2; vtcs[15]=ty-ChunkyRandom(cro,rx*top_rough); + vtcs[0]=tx-ChunkyRandom(cro,rx/2); vtcs[1]=ty-ChunkyRandom(cro,rx/2*top_rough); + vtcs[2]=tx-ChunkyRandom(cro,rx*side_rough); vtcs[3]=ty+hgt/2; + vtcs[4]=tx-ChunkyRandom(cro,rx); vtcs[5]=ty+hgt+ChunkyRandom(cro,rx); + vtcs[6]=tx+wdt/2; vtcs[7]=ty+hgt+ChunkyRandom(cro,2*rx); + vtcs[8]=tx+wdt+ChunkyRandom(cro,rx); vtcs[9]=ty+hgt+ChunkyRandom(cro,rx); + vtcs[10]=tx+wdt+ChunkyRandom(cro,rx*side_rough); vtcs[11]=ty+hgt/2; + vtcs[12]=tx+wdt+ChunkyRandom(cro,rx/2); vtcs[13]=ty-ChunkyRandom(cro,rx/2*top_rough); + vtcs[14]=tx+wdt/2; vtcs[15]=ty-ChunkyRandom(cro,rx*top_rough); - Surface8->Polygon(8,vtcs,mcol); - } + Surface8->Polygon(8,vtcs,mcol); + } void C4Landscape::DrawSmoothOChunk(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, int32_t mcol, BYTE flip, int32_t cro) - { - int vtcs[8]; - int32_t rx=Max(wdt/2,1); + { + int vtcs[8]; + int32_t rx=Max(wdt/2,1); - vtcs[0]=tx; vtcs[1]=ty-ChunkyRandom(cro,rx/2); - vtcs[2]=tx; vtcs[3]=ty+hgt; - vtcs[4]=tx+wdt; vtcs[5]=ty+hgt; - vtcs[6]=tx+wdt; vtcs[7]=ty-ChunkyRandom(cro,rx/2); + vtcs[0]=tx; vtcs[1]=ty-ChunkyRandom(cro,rx/2); + vtcs[2]=tx; vtcs[3]=ty+hgt; + vtcs[4]=tx+wdt; vtcs[5]=ty+hgt; + vtcs[6]=tx+wdt; vtcs[7]=ty-ChunkyRandom(cro,rx/2); - if (flip) - { vtcs[0]=tx+wdt/2; vtcs[1]=ty+hgt/3; } - else - { vtcs[6]=tx+wdt/2; vtcs[7]=ty+hgt/3; } + if (flip) + { vtcs[0]=tx+wdt/2; vtcs[1]=ty+hgt/3; } + else + { vtcs[6]=tx+wdt/2; vtcs[7]=ty+hgt/3; } - Surface8->Polygon(4,vtcs,mcol); - } + Surface8->Polygon(4,vtcs,mcol); + } void C4Landscape::ChunkOZoom(CSurface8 * sfcMap, int32_t iMapX, int32_t iMapY, int32_t iMapWdt, int32_t iMapHgt, int32_t iTexture, int32_t iOffX, int32_t iOffY) { @@ -508,11 +508,11 @@ bool C4Landscape::MapToSurface(CSurface8 * sfcMap, int32_t iMapX, int32_t iMapY, // Enlarge map segment for chunky rim iMapX-=2; iMapY-=2; iMapWdt+=4; iMapHgt+=4; - // Determine texture usage in map segment - DWORD dwTexUsage[C4M_MaxTexIndex]; - if (!GetTexUsage(sfcMap,iMapX,iMapY,iMapWdt,iMapHgt,dwTexUsage)) return false; - // Texture zoom map to landscape - if (!TexOZoom(sfcMap,iMapX,iMapY,iMapWdt,iMapHgt,dwTexUsage,iOffX,iOffY)) return false; + // Determine texture usage in map segment + DWORD dwTexUsage[C4M_MaxTexIndex]; + if (!GetTexUsage(sfcMap,iMapX,iMapY,iMapWdt,iMapHgt,dwTexUsage)) return false; + // Texture zoom map to landscape + if (!TexOZoom(sfcMap,iMapX,iMapY,iMapWdt,iMapHgt,dwTexUsage,iOffX,iOffY)) return false; // remove clipper Surface8->NoClip(); @@ -552,23 +552,23 @@ bool C4Landscape::MapToLandscape(CSurface8 * sfcMap, int32_t iMapX, int32_t iMap } CSurface8 * C4Landscape::CreateMap() - { - CSurface8 * sfcMap; - int32_t iWidth=0,iHeight=0; + { + CSurface8 * sfcMap; + int32_t iWidth=0,iHeight=0; - // Create map surface - Game.C4S.Landscape.GetMapSize(iWidth,iHeight,Game.StartupPlayerCount); - if (!(sfcMap=new CSurface8(iWidth,iHeight))) + // Create map surface + Game.C4S.Landscape.GetMapSize(iWidth,iHeight,Game.StartupPlayerCount); + if (!(sfcMap=new CSurface8(iWidth,iHeight))) return NULL; - // Fill sfcMap - C4MapCreator MapCreator; - MapCreator.Create(sfcMap, - Game.C4S.Landscape, ::TextureMap, - true,Game.StartupPlayerCount); + // Fill sfcMap + C4MapCreator MapCreator; + MapCreator.Create(sfcMap, + Game.C4S.Landscape, ::TextureMap, + true,Game.StartupPlayerCount); - return sfcMap; - } + return sfcMap; + } CSurface8 * C4Landscape::CreateMapS2(C4Group &ScenFile) { @@ -601,7 +601,7 @@ bool C4Landscape::PostInitMap() } bool C4Landscape::Init(C4Group &hGroup, bool fOverloadCurrent, bool fLoadSky, bool &rfLoaded, bool fSavegame) - { + { // set map seed, if not pre-assigned if (!MapSeed) MapSeed=Random(3133700); @@ -721,8 +721,8 @@ bool C4Landscape::Init(C4Group &hGroup, bool fOverloadCurrent, bool fLoadSky, bo // copy noscan-var NoScan=Game.C4S.Landscape.NoScan!=0; - // Scan settings - ScanSpeed=BoundBy(Width/500,2,15); + // Scan settings + ScanSpeed=BoundBy(Width/500,2,15); // create it if (!Game.C4S.Landscape.ExactLandscape) @@ -757,12 +757,12 @@ bool C4Landscape::Init(C4Group &hGroup, bool fOverloadCurrent, bool fLoadSky, bo PixCntPitch = (Height + 14) / 15; PixCnt = new uint8_t [PixCntWidth * PixCntPitch]; UpdatePixCnt(C4Rect(0, 0, Width, Height)); - ClearMatCount(); - UpdateMatCnt(C4Rect(0,0,Width,Height), true); + ClearMatCount(); + UpdateMatCnt(C4Rect(0,0,Width,Height), true); - // Save initial landscape - if(!SaveInitial()) - return false; + // Save initial landscape + if(!SaveInitial()) + return false; // Load diff, if existant ApplyDiff(hGroup); @@ -776,8 +776,8 @@ bool C4Landscape::Init(C4Group &hGroup, bool fOverloadCurrent, bool fLoadSky, bo // Success rfLoaded=true; - return true; - } + return true; + } bool C4Landscape::SetPix(int32_t x, int32_t y, BYTE npix) { @@ -811,69 +811,69 @@ bool C4Landscape::SetPixDw(int32_t x, int32_t y, DWORD dwPix) } bool C4Landscape::_SetPix(int32_t x, int32_t y, BYTE npix) - { + { #ifdef DEBUGREC C4RCSetPix rc; rc.x=x; rc.y=y; rc.clr=npix; AddDbgRec(RCT_SetPix, &rc, sizeof(rc)); #endif assert(x >= 0 && y >= 0 && x < Width && y < Height); - // get and check pixel - BYTE opix = _GetPix(x, y); - if(npix == opix) return true; + // get and check pixel + BYTE opix = _GetPix(x, y); + if(npix == opix) return true; // count pixels if(Pix2Dens[npix]) { if(!Pix2Dens[opix]) PixCnt[(y / 15) + (x / 17) * PixCntPitch]++; } else { if(Pix2Dens[opix]) PixCnt[(y / 15) + (x / 17) * PixCntPitch]--; } - // count material + // count material assert(!npix || MatValid(Pix2Mat[npix])); - int32_t omat = Pix2Mat[opix], nmat = Pix2Mat[npix]; - if(opix) MatCount[omat]--; - if(npix) MatCount[nmat]++; - // count effective material - if(omat != nmat) - { - if(npix && ::MaterialMap.Map[nmat].MinHeightCount) - { - // Check for material above & below - int iMinHeight = ::MaterialMap.Map[nmat].MinHeightCount, - iBelow = GetMatHeight(x, y+1, +1, nmat, iMinHeight), - iAbove = GetMatHeight(x, y-1, -1, nmat, iMinHeight); - // Will be above treshold? - if(iBelow + iAbove + 1 >= iMinHeight) - { - int iChange = 1; - // Check for heights below threshold - if(iBelow < iMinHeight) iChange += iBelow; - if(iAbove < iMinHeight) iChange += iAbove; - // Change - EffectiveMatCount[nmat] += iChange; - } - } - if(opix && ::MaterialMap.Map[omat].MinHeightCount) - { - // Check for material above & below - int iMinHeight = ::MaterialMap.Map[omat].MinHeightCount, - iBelow = GetMatHeight(x, y+1, +1, omat, iMinHeight), - iAbove = GetMatHeight(x, y-1, -1, omat, iMinHeight); - // Not already below threshold? - if(iBelow + iAbove + 1 >= iMinHeight) - { - int iChange = 1; - // Check for heights that will get below threshold - if(iBelow < iMinHeight) iChange += iBelow; - if(iAbove < iMinHeight) iChange += iAbove; - // Change - EffectiveMatCount[omat] -= iChange; - } - } - } + int32_t omat = Pix2Mat[opix], nmat = Pix2Mat[npix]; + if(opix) MatCount[omat]--; + if(npix) MatCount[nmat]++; + // count effective material + if(omat != nmat) + { + if(npix && ::MaterialMap.Map[nmat].MinHeightCount) + { + // Check for material above & below + int iMinHeight = ::MaterialMap.Map[nmat].MinHeightCount, + iBelow = GetMatHeight(x, y+1, +1, nmat, iMinHeight), + iAbove = GetMatHeight(x, y-1, -1, nmat, iMinHeight); + // Will be above treshold? + if(iBelow + iAbove + 1 >= iMinHeight) + { + int iChange = 1; + // Check for heights below threshold + if(iBelow < iMinHeight) iChange += iBelow; + if(iAbove < iMinHeight) iChange += iAbove; + // Change + EffectiveMatCount[nmat] += iChange; + } + } + if(opix && ::MaterialMap.Map[omat].MinHeightCount) + { + // Check for material above & below + int iMinHeight = ::MaterialMap.Map[omat].MinHeightCount, + iBelow = GetMatHeight(x, y+1, +1, omat, iMinHeight), + iAbove = GetMatHeight(x, y-1, -1, omat, iMinHeight); + // Not already below threshold? + if(iBelow + iAbove + 1 >= iMinHeight) + { + int iChange = 1; + // Check for heights that will get below threshold + if(iBelow < iMinHeight) iChange += iBelow; + if(iAbove < iMinHeight) iChange += iAbove; + // Change + EffectiveMatCount[omat] -= iChange; + } + } + } // set 8bpp-surface only! Surface8->SetPix(x,y,npix); // success return true; - } + } bool C4Landscape::_SetPixIfMask(int32_t x, int32_t y, BYTE npix, BYTE nMask) { @@ -886,34 +886,34 @@ bool C4Landscape::_SetPixIfMask(int32_t x, int32_t y, BYTE npix, BYTE nMask) bool C4Landscape::CheckInstability(int32_t tx, int32_t ty) - { - int32_t mat=GetMat(tx,ty); - if (MatValid(mat)) - if (::MaterialMap.Map[mat].Instable) - return ::MassMover.Create(tx,ty); - return false; - } + { + int32_t mat=GetMat(tx,ty); + if (MatValid(mat)) + if (::MaterialMap.Map[mat].Instable) + return ::MassMover.Create(tx,ty); + return false; + } void C4Landscape::CheckInstabilityRange(int32_t tx, int32_t ty) - { - if (!CheckInstability(tx,ty)) - { - CheckInstability(tx,ty-1); - CheckInstability(tx,ty-2); - CheckInstability(tx-1,ty); - CheckInstability(tx+1,ty); - } - } + { + if (!CheckInstability(tx,ty)) + { + CheckInstability(tx,ty-1); + CheckInstability(tx,ty-2); + CheckInstability(tx-1,ty); + CheckInstability(tx+1,ty); + } + } bool C4Landscape::ClearPix(int32_t tx, int32_t ty) - { - BYTE bcol; - if (GBackIFT(tx,ty)) - bcol=Mat2PixColDefault(MTunnel)+IFT; - else + { + BYTE bcol; + if (GBackIFT(tx,ty)) + bcol=Mat2PixColDefault(MTunnel)+IFT; + else bcol=0; - return SetPix(tx,ty,bcol); - } + return SetPix(tx,ty,bcol); + } bool C4Landscape::_PathFree(int32_t x, int32_t y, int32_t x2, int32_t y2) { @@ -944,265 +944,265 @@ bool C4Landscape::_PathFree(int32_t x, int32_t y, int32_t x2, int32_t y2) } int32_t C4Landscape::GetMatHeight(int32_t x, int32_t y, int32_t iYDir, int32_t iMat, int32_t iMax) - { - if(iYDir > 0) - { - iMax = Min(iMax, Height - y); - for(int32_t i = 0; i < iMax; i++) - if(_GetMat(x, y + i) != iMat) - return i; - } - else - { - iMax = Min(iMax, y + 1); - for(int32_t i = 0; i < iMax; i++) - if(_GetMat(x, y - i) != iMat) - return i; - } - return iMax; - } + { + if(iYDir > 0) + { + iMax = Min(iMax, Height - y); + for(int32_t i = 0; i < iMax; i++) + if(_GetMat(x, y + i) != iMat) + return i; + } + else + { + iMax = Min(iMax, y + 1); + for(int32_t i = 0; i < iMax; i++) + if(_GetMat(x, y - i) != iMat) + return i; + } + return iMax; + } int32_t C4Landscape::DigFreePix(int32_t tx, int32_t ty) - { - int32_t mat=GetMat(tx,ty); - if (mat!=MNone) - if (::MaterialMap.Map[mat].DigFree) - ClearPix(tx,ty); - CheckInstabilityRange(tx,ty); - return mat; - } + { + int32_t mat=GetMat(tx,ty); + if (mat!=MNone) + if (::MaterialMap.Map[mat].DigFree) + ClearPix(tx,ty); + CheckInstabilityRange(tx,ty); + return mat; + } int32_t C4Landscape::ShakeFreePix(int32_t tx, int32_t ty) - { - int32_t mat=GetMat(tx,ty); - if (mat!=MNone) - if (::MaterialMap.Map[mat].DigFree) + { + int32_t mat=GetMat(tx,ty); + if (mat!=MNone) + if (::MaterialMap.Map[mat].DigFree) { ClearPix(tx,ty); ::PXS.Create(mat,itofix(tx),itofix(ty)); } - CheckInstabilityRange(tx,ty); - return mat; - } + CheckInstabilityRange(tx,ty); + return mat; + } int32_t C4Landscape::BlastFreePix(int32_t tx, int32_t ty, int32_t grade, int32_t iBlastSize) - { - int32_t mat=GetMat(tx,ty); - if (MatValid(mat)) - { - // Blast Shift - if (::MaterialMap.Map[mat].BlastShiftTo) + { + int32_t mat=GetMat(tx,ty); + if (MatValid(mat)) + { + // Blast Shift + if (::MaterialMap.Map[mat].BlastShiftTo) { // blast free amount; always blast if 100% is to be blasted away //if (Random(BlastMatCount[mat]) < iBlastSize * grade / 6) SetPix(tx,ty,MatTex2PixCol(::MaterialMap.Map[mat].BlastShiftTo)+GBackIFT(tx,ty)); } - // Blast Free - if (::MaterialMap.Map[mat].BlastFree) ClearPix(tx,ty); - } + // Blast Free + if (::MaterialMap.Map[mat].BlastFree) ClearPix(tx,ty); + } - CheckInstabilityRange(tx,ty); + CheckInstabilityRange(tx,ty); - return mat; - } + return mat; + } void C4Landscape::DigFree(int32_t tx, int32_t ty, int32_t rad, bool fRequest, C4Object *pByObj) - { - int32_t ycnt,xcnt,iLineWidth = 0,iLineY,iMaterial; - // Dig free - for (ycnt=-rad; ycntAddMaterialContents(iMaterial,1); - // Clear single pixels - left and right - DigFreeSinglePix(tx - iLineWidth - 1, iLineY, -1, 0); - DigFreeSinglePix(tx + iLineWidth+(iLineWidth==0), iLineY, +1, 0); - } - // Clear single pixels - up and down - DigFreeSinglePix(tx, ty - rad - 1, 0, -1); - for (xcnt=-iLineWidth; xcntDigOutMaterialCast(fRequest); - } + { + int32_t ycnt,xcnt,iLineWidth = 0,iLineY,iMaterial; + // Dig free + for (ycnt=-rad; ycntAddMaterialContents(iMaterial,1); + // Clear single pixels - left and right + DigFreeSinglePix(tx - iLineWidth - 1, iLineY, -1, 0); + DigFreeSinglePix(tx + iLineWidth+(iLineWidth==0), iLineY, +1, 0); + } + // Clear single pixels - up and down + DigFreeSinglePix(tx, ty - rad - 1, 0, -1); + for (xcnt=-iLineWidth; xcntDigOutMaterialCast(fRequest); + } void C4Landscape::DigFreeRect(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, bool fRequest, C4Object *pByObj) - { + { // Dig free pixels - int32_t cx,cy,iMaterial; - for (cx=tx; cxAddMaterialContents(iMaterial,1); - // Clear single pixels + int32_t cx,cy,iMaterial; + for (cx=tx; cxAddMaterialContents(iMaterial,1); + // Clear single pixels - // Dig out material cast - if (!::Game.iTick5) if (pByObj) pByObj->DigOutMaterialCast(fRequest); - } + // Dig out material cast + if (!::Game.iTick5) if (pByObj) pByObj->DigOutMaterialCast(fRequest); + } void C4Landscape::ShakeFree(int32_t tx, int32_t ty, int32_t rad) - { - int32_t ycnt,xcnt,lwdt,dpy; - // Shake free pixels - for (ycnt=rad-1; ycnt>=-rad; ycnt--) - { - lwdt= (int32_t) sqrt(double(rad*rad-ycnt*ycnt)); - dpy=ty+ycnt; - for (xcnt=-lwdt; xcnt=-rad; ycnt--) + { + lwdt= (int32_t) sqrt(double(rad*rad-ycnt*ycnt)); + dpy=ty+ycnt; + for (xcnt=-lwdt; xcntGetDensity(cx,cy)) - || ((MatDensity(mat)==GetDensity(cx,cy)) && (MatDigFree(mat)<=MatDigFree(GetMat(cx,cy)))) ) - SetPix(cx,cy,Mat2PixColDefault(mat)+GBackIFT(cx,cy)); - } + { + int32_t cx,cy; + for (cy=ty; cyGetDensity(cx,cy)) + || ((MatDensity(mat)==GetDensity(cx,cy)) && (MatDigFree(mat)<=MatDigFree(GetMat(cx,cy)))) ) + SetPix(cx,cy,Mat2PixColDefault(mat)+GBackIFT(cx,cy)); + } void C4Landscape::RaiseTerrain(int32_t tx, int32_t ty, int32_t wdt) - { - int32_t cx,cy; - BYTE cpix; - for (cx=tx; cx=ty) { SetPix(cx,cy,cpix); cy--; } - } - } - } + } + } + } int32_t C4Landscape::AreaSolidCount(int32_t x, int32_t y, int32_t wdt, int32_t hgt) - { - int32_t cx,cy,ascnt=0; - for (cy=y; cy(tx,0,Width-1) || !Inside(ty,0,Height)) return false; if (Game.C4S.Game.Realism.LandscapePushPull) @@ -1228,8 +1228,8 @@ bool C4Landscape::InsertMaterial(int32_t mat, int32_t tx, int32_t ty, int32_t vx if (GetDensity(tx,ty)>mdens) return false; } - // Try slide - while (FindMatSlide(tx,ty,+1,mdens,::MaterialMap.Map[mat].MaxSlide)) + // Try slide + while (FindMatSlide(tx,ty,+1,mdens,::MaterialMap.Map[mat].MaxSlide)) if (GetDensity(tx,ty+1)=mdens) // Left clogged - fLeft=false; - else if (GetDensity(fx-cslide,fy+ydir)=mdens) // Right clogged - fRight=false; - else if (GetDensity(fx+cslide,fy+ydir)=mdens) // Left clogged + fLeft=false; + else if (GetDensity(fx-cslide,fy+ydir)=mdens) // Right clogged + fRight=false; + else if (GetDensity(fx+cslide,fy+ydir)=mdens && GetDensity(fx-cslide,fy+ydir)>=mdens) // Left clogged - fLeft=false; - else if (GetDensity(fx-cslide,fy+ydir)=mdens && GetDensity(fx-cslide,fy+ydir)>=mdens) // Left clogged + fLeft=false; + else if (GetDensity(fx-cslide,fy+ydir)=mdens && GetDensity(fx+cslide,fy+ydir)>=mdens) // Right clogged - fRight=false; - else if (GetDensity(fx+cslide,fy+ydir)=mdens && GetDensity(fx+cslide,fy+ydir)>=mdens) // Right clogged + fRight=false; + else if (GetDensity(fx+cslide,fy+ydir)Save(Config.AtTempPath(C4CFN_TempLandscape))) return false; @@ -1528,9 +1528,9 @@ bool C4Landscape::SaveDiff(C4Group &hGroup, bool fSyncSave) if (!hGroup.Move( Config.AtTempPath(C4CFN_TempLandscape), C4CFN_DiffLandscape )) return false; - } + } - // Restore landscape pixels + // Restore landscape pixels if(!fSyncSave) if(pInitial) for(int y = 0; y < Height; y++) @@ -1549,19 +1549,19 @@ bool C4Landscape::SaveDiff(C4Group &hGroup, bool fSyncSave) } bool C4Landscape::SaveInitial() - { + { - // Create array - delete [] pInitial; - pInitial = new BYTE [Width * Height]; + // Create array + delete [] pInitial; + pInitial = new BYTE [Width * Height]; - // Save material data - for(int y = 0; y < Height; y++) - for(int x = 0; x < Width; x++) - pInitial[y * Width + x] = _GetPix(x, y); + // Save material data + for(int y = 0; y < Height; y++) + for(int x = 0; x < Width; x++) + pInitial[y * Width + x] = _GetPix(x, y); - return true; - } + return true; + } bool C4Landscape::Load(C4Group &hGroup, bool fLoadSky, bool fSavegame) { @@ -1606,29 +1606,29 @@ bool C4Landscape::Load(C4Group &hGroup, bool fLoadSky, bool fSavegame) } // NewStyleLandscape-flag will be set in C4Landscape::Init later } - // New style landscape first generation: just correct - if(Game.C4S.Landscape.NewStyleLandscape == 1) - { + // New style landscape first generation: just correct + if(Game.C4S.Landscape.NewStyleLandscape == 1) + { // convert all pixels for (int32_t y=0; yGetPix(x, y); - int32_t iMat = PixCol2MatOld2(byPix); - if(MatValid(iMat)) - // insert pixel - Surface8->SetPix(x, y, Mat2PixColDefault(iMat) + (byPix & IFT)); - else - Surface8->SetPix(x, y, 0); - } - } + int32_t iMat = PixCol2MatOld2(byPix); + if(MatValid(iMat)) + // insert pixel + Surface8->SetPix(x, y, Mat2PixColDefault(iMat) + (byPix & IFT)); + else + Surface8->SetPix(x, y, 0); + } + } else { // Landscape should be in correct format: Make sure it is! for (int32_t y=0; yGetPix(x, y); - int32_t iMat = PixCol2Mat(byPix); + int32_t iMat = PixCol2Mat(byPix); if (byPix && !MatValid(iMat)) { LogFatal(FormatString("Landscape loading error at (%d/%d): Pixel value %d not a valid material!", (int) x, (int) y, (int) byPix).getData()); @@ -1655,7 +1655,7 @@ bool C4Landscape::ApplyDiff(C4Group &hGroup) // convert all pixels: keep if same material; re-set if different material BYTE byPix; for (int32_t y=0; yGetPix(x, y) != 0xff) + if (pDiff->GetPix(x, y) != 0xff) if (Surface8->GetPix(x,y) != (byPix=pDiff->GetPix(x,y))) // material has changed here: readjust with new texture SetPix(x,y, byPix); @@ -1691,12 +1691,12 @@ void C4Landscape::Default() void C4Landscape::ClearBlastMatCount() { - for (int32_t cnt=0; cnt=0) || (cy2=0) || (cy2=0) || (cy20) || (cx2=0) // Still going - { - if (AboveSolid(cx1,cy1)) rl1++; // Run okay - else rl1=0; // No run - } - // Right search - if (cx2=width) { rx=cx1+rl1/2; ry=cy1; fFound=true; break; } - if (rl2>=width) { rx=cx2-rl2/2; ry=cy2; fFound=true; break; } - } + for (cx1=cx2=rx,cy1=cy2=ry; (cx1>0) || (cx2=0) // Still going + { + if (AboveSolid(cx1,cy1)) rl1++; // Run okay + else rl1=0; // No run + } + // Right search + if (cx2=width) { rx=cx1+rl1/2; ry=cy1; fFound=true; break; } + if (rl2>=width) { rx=cx2-rl2/2; ry=cy2; fFound=true; break; } + } - if (fFound) AboveSemiSolid(rx,ry); + if (fFound) AboveSemiSolid(rx,ry); - return fFound; - } + return fFound; + } bool FindSurfaceLiquid(int32_t &rx, int32_t &ry, int32_t width, int32_t height) - { - bool fFound=false; + { + bool fFound=false; - int32_t cx1,cx2,cy1,cy2,rl1=0,rl2=0,cnt; + int32_t cx1,cx2,cy1,cy2,rl1=0,rl2=0,cnt; bool lokay; - for (cx1=cx2=rx,cy1=cy2=ry; (cx1>0) || (cx20) // Still going - { - if (!AboveSemiSolid(cx1,cy1)) cx1=-1; // Abort left - else + for (cx1=cx2=rx,cy1=cy2=ry; (cx1>0) || (cx20) // Still going + { + if (!AboveSemiSolid(cx1,cy1)) cx1=-1; // Abort left + else { for (lokay=true,cnt=0; cnt=width) { rx=cx1+rl1/2; ry=cy1; fFound=true; break; } - if (rl2>=width) { rx=cx2-rl2/2; ry=cy2; fFound=true; break; } - } + } + // Check runs + if (rl1>=width) { rx=cx1+rl1/2; ry=cy1; fFound=true; break; } + if (rl2>=width) { rx=cx2-rl2/2; ry=cy2; fFound=true; break; } + } - if (fFound) AboveSemiSolid(rx,ry); + if (fFound) AboveSemiSolid(rx,ry); - return fFound; - } + return fFound; + } bool FindLiquid(int32_t &rx, int32_t &ry, int32_t width, int32_t height) - { - int32_t cx1,cx2,cy1,cy2,rl1=0,rl2=0; + { + int32_t cx1,cx2,cy1,cy2,rl1=0,rl2=0; - for (cx1=cx2=rx,cy1=cy2=ry; (cx1>0) || (cx20) + for (cx1=cx2=rx,cy1=cy2=ry; (cx1>0) || (cx20) { if (FindLiquidHeight(cx1,cy1,height)) rl1++; else rl1=0; } - // Right search - if (cx2=width) { rx=cx1+rl1/2; ry=cy1; return true; } - if (rl2>=width) { rx=cx2-rl2/2; ry=cy2; return true; } - } + // Check runs + if (rl1>=width) { rx=cx1+rl1/2; ry=cy1; return true; } + if (rl2>=width) { rx=cx2-rl2/2; ry=cy2; return true; } + } - return false; - } + return false; + } // FindLevelGround: Starting from rx/ry, searches for a width @@ -1911,52 +1911,52 @@ bool FindLiquid(int32_t &rx, int32_t &ry, int32_t width, int32_t height) // Returns bottom center of surface found. bool FindLevelGround(int32_t &rx, int32_t &ry, int32_t width, int32_t hrange) - { - bool fFound=false; + { + bool fFound=false; - int32_t cx1,cx2,cy1,cy2,rh1,rh2,rl1,rl2; + int32_t cx1,cx2,cy1,cy2,rh1,rh2,rl1,rl2; - cx1=cx2=rx; cy1=cy2=ry; - rh1=cy1; rh2=cy2; - rl1=rl2=0; + cx1=cx2=rx; cy1=cy2=ry; + rh1=cy1; rh2=cy2; + rl1=rl2=0; - for (cx1--,cx2++; (cx1>0) || (cx20) // Still going - { - if (!AboveSemiSolid(cx1,cy1)) cx1=-1; // Abort left - else - { - if (GBackSolid(cx1,cy1+1) && (Abs(cy1-rh1)0) || (cx20) // Still going + { + if (!AboveSemiSolid(cx1,cy1)) cx1=-1; // Abort left + else + { + if (GBackSolid(cx1,cy1+1) && (Abs(cy1-rh1)=width) { rx=cx1+rl1/2; ry=cy1; fFound=true; break; } - if (rl2>=width) { rx=cx2-rl2/2; ry=cy2; fFound=true; break; } - } + // Check runs + if (rl1>=width) { rx=cx1+rl1/2; ry=cy1; fFound=true; break; } + if (rl2>=width) { rx=cx2-rl2/2; ry=cy2; fFound=true; break; } + } - if (fFound) AboveSemiSolid(rx,ry); + if (fFound) AboveSemiSolid(rx,ry); - return fFound; - } + return fFound; + } @@ -1965,14 +1965,14 @@ bool FindLevelGround(int32_t &rx, int32_t &ry, int32_t width, int32_t hrange) // Returns bottom center of surface found. bool FindConSiteSpot(int32_t &rx, int32_t &ry, int32_t wdt, int32_t hgt, - DWORD category, int32_t hrange) - { - bool fFound=false; + DWORD category, int32_t hrange) + { + bool fFound=false; - // No hrange limit, use standard smooth surface limit - if (hrange==-1) hrange=Max(wdt/4,5); + // No hrange limit, use standard smooth surface limit + if (hrange==-1) hrange=Max(wdt/4,5); - int32_t cx1,cx2,cy1,cy2,rh1,rh2,rl1,rl2; + int32_t cx1,cx2,cy1,cy2,rh1,rh2,rl1,rl2; // Left offset starting position cx1=Min(rx+wdt/2,GBackWdt-1); cy1=ry; @@ -1983,74 +1983,74 @@ bool FindConSiteSpot(int32_t &rx, int32_t &ry, int32_t wdt, int32_t hgt, // No good: use centered starting position if (!AboveSemiSolid(cx2,cy2)) { cx2=Min(rx,GBackWdt-1); cy2=ry; } - rh1=cy1; rh2=cy2; rl1=rl2=0; + rh1=cy1; rh2=cy2; rl1=rl2=0; - for (cx1--,cx2++; (cx1>0) || (cx20) // Still going - { - if (!AboveSemiSolid(cx1,cy1)) + for (cx1--,cx2++; (cx1>0) || (cx20) // Still going + { + if (!AboveSemiSolid(cx1,cy1)) cx1=-1; // Abort left - else - { - if (GBackSolid(cx1,cy1+1) && (Abs(cy1-rh1)=wdt) if (cx1>0) - if (!Game.OverlapObject(cx1,cy1-hgt-10,wdt,hgt+40,category)) - { rx=cx1+wdt/2; ry=cy1; fFound=true; break; } - if (rl2>=wdt) if (cx2=wdt) if (cx1>0) + if (!Game.OverlapObject(cx1,cy1-hgt-10,wdt,hgt+40,category)) + { rx=cx1+wdt/2; ry=cy1; fFound=true; break; } + if (rl2>=wdt) if (cx2= 0) - { - // Normal material counting - MatCount[iMat] += iMul * (iHgt + 1); - // Effective material counting enabled? - if(int32_t iMinHgt = ::MaterialMap.Map[iMat].MinHeightCount) - { - // First chunk? Add any material above when checking chunk height - int iAddedHeight = 0; - if(Rect.y && iHgt + 1 == y) - iAddedHeight = GetMatHeight(Rect.x+x, Rect.y-1, -1, iMat, iMinHgt); - // Check the chunk height - if(iHgt + 1 + iAddedHeight >= iMinHgt) - { - EffectiveMatCount[iMat] += iMul * (iHgt + 1); - if(iAddedHeight < iMinHgt) - EffectiveMatCount[iMat] += iMul * iAddedHeight; - } - } - } - // Next chunk of material - iHgt = 0; - } - } - // Check last pixel - int32_t iMat = _GetMat(Rect.x+x, Rect.y+Rect.Hgt-1); - if(iMat >= 0) - { - // Normal material counting - MatCount[iMat] += iMul * (iHgt + 1); - // Minimum height counting? - if(int32_t iMinHgt = ::MaterialMap.Map[iMat].MinHeightCount) - { - int iAddedHeight1 = 0, iAddedHeight2 = 0; - // Add any material above for chunk size check - if(Rect.y && iHgt + 1 == Rect.Hgt) - iAddedHeight1 = GetMatHeight(Rect.x+x, Rect.y-1, -1, iMat, iMinHgt); - // Add any material below for chunk size check - if(Rect.y+y < Height) - iAddedHeight2 = GetMatHeight(Rect.x+x, Rect.y+Rect.Hgt, 1, iMat, iMinHgt); - // Chunk tall enough? - if(iHgt + 1 + iAddedHeight1 + iAddedHeight2 >= ::MaterialMap.Map[iMat].MinHeightCount) - { - EffectiveMatCount[iMat] += iMul * (iHgt + 1); - if(iAddedHeight1 < iMinHgt) - EffectiveMatCount[iMat] += iMul * iAddedHeight1; - if(iAddedHeight2 < iMinHgt) - EffectiveMatCount[iMat] += iMul * iAddedHeight2; - } - } - } - } - } + for(y = 1; y < Rect.Hgt; y++) + { + int32_t iMat = _GetMat(Rect.x+x, Rect.y+y - 1); + // Same material? Count it. + if(iMat == _GetMat(Rect.x+x, Rect.y+y)) + iHgt++; + else + { + if(iMat >= 0) + { + // Normal material counting + MatCount[iMat] += iMul * (iHgt + 1); + // Effective material counting enabled? + if(int32_t iMinHgt = ::MaterialMap.Map[iMat].MinHeightCount) + { + // First chunk? Add any material above when checking chunk height + int iAddedHeight = 0; + if(Rect.y && iHgt + 1 == y) + iAddedHeight = GetMatHeight(Rect.x+x, Rect.y-1, -1, iMat, iMinHgt); + // Check the chunk height + if(iHgt + 1 + iAddedHeight >= iMinHgt) + { + EffectiveMatCount[iMat] += iMul * (iHgt + 1); + if(iAddedHeight < iMinHgt) + EffectiveMatCount[iMat] += iMul * iAddedHeight; + } + } + } + // Next chunk of material + iHgt = 0; + } + } + // Check last pixel + int32_t iMat = _GetMat(Rect.x+x, Rect.y+Rect.Hgt-1); + if(iMat >= 0) + { + // Normal material counting + MatCount[iMat] += iMul * (iHgt + 1); + // Minimum height counting? + if(int32_t iMinHgt = ::MaterialMap.Map[iMat].MinHeightCount) + { + int iAddedHeight1 = 0, iAddedHeight2 = 0; + // Add any material above for chunk size check + if(Rect.y && iHgt + 1 == Rect.Hgt) + iAddedHeight1 = GetMatHeight(Rect.x+x, Rect.y-1, -1, iMat, iMinHgt); + // Add any material below for chunk size check + if(Rect.y+y < Height) + iAddedHeight2 = GetMatHeight(Rect.x+x, Rect.y+Rect.Hgt, 1, iMat, iMinHgt); + // Chunk tall enough? + if(iHgt + 1 + iAddedHeight1 + iAddedHeight2 >= ::MaterialMap.Map[iMat].MinHeightCount) + { + EffectiveMatCount[iMat] += iMul * (iHgt + 1); + if(iAddedHeight1 < iMinHgt) + EffectiveMatCount[iMat] += iMul * iAddedHeight1; + if(iAddedHeight2 < iMinHgt) + EffectiveMatCount[iMat] += iMul * iAddedHeight2; + } + } + } + } + } void C4Landscape::CompileFunc(StdCompiler *pComp) - { + { pComp->Value(mkNamingAdapt(MapSeed, "MapSeed", 0)); pComp->Value(mkNamingAdapt(LeftOpen, "LeftOpen", 0)); pComp->Value(mkNamingAdapt(RightOpen, "RightOpen", 0)); @@ -3012,33 +3012,33 @@ void C4Landscape::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(mkCastIntAdapt(Gravity), "Gravity", FIXED100(20))); pComp->Value(mkNamingAdapt(Modulation, "MatModulation", 0U)); pComp->Value(mkNamingAdapt(Mode, "Mode", C4LSC_Undefined)); - } + } void C4Landscape::RemoveUnusedTexMapEntries() - { - // check usage in landscape - bool fTexUsage[128]; - int32_t iMatTex; - for (iMatTex = 0; iMatTex < 128; ++iMatTex) fTexUsage[iMatTex] = false; - for (int32_t y=0; yGetPix(x,y) & 0x7f] = true; - // check usage by materials - for (int32_t iMat = 0; iMat < ::MaterialMap.Num; ++iMat) - { - C4Material *pMat = ::MaterialMap.Map + iMat; - if (pMat->BlastShiftTo >= 0) fTexUsage[pMat->BlastShiftTo & 0x7f] = true; - if (pMat->BelowTempConvertTo >= 0) fTexUsage[pMat->BelowTempConvertTo & 0x7f] = true; - if (pMat->AboveTempConvertTo >= 0) fTexUsage[pMat->AboveTempConvertTo & 0x7f] = true; - if (pMat->DefaultMatTex >= 0) fTexUsage[pMat->DefaultMatTex & 0x7f] = true; - } - // remove unused - for (iMatTex = 1; iMatTex < C4M_MaxTexIndex; ++iMatTex) - if (!fTexUsage[iMatTex]) - ::TextureMap.RemoveEntry(iMatTex); - // flag rewrite - ::TextureMap.fEntriesAdded = true; - } + { + // check usage in landscape + bool fTexUsage[128]; + int32_t iMatTex; + for (iMatTex = 0; iMatTex < 128; ++iMatTex) fTexUsage[iMatTex] = false; + for (int32_t y=0; yGetPix(x,y) & 0x7f] = true; + // check usage by materials + for (int32_t iMat = 0; iMat < ::MaterialMap.Num; ++iMat) + { + C4Material *pMat = ::MaterialMap.Map + iMat; + if (pMat->BlastShiftTo >= 0) fTexUsage[pMat->BlastShiftTo & 0x7f] = true; + if (pMat->BelowTempConvertTo >= 0) fTexUsage[pMat->BelowTempConvertTo & 0x7f] = true; + if (pMat->AboveTempConvertTo >= 0) fTexUsage[pMat->AboveTempConvertTo & 0x7f] = true; + if (pMat->DefaultMatTex >= 0) fTexUsage[pMat->DefaultMatTex & 0x7f] = true; + } + // remove unused + for (iMatTex = 1; iMatTex < C4M_MaxTexIndex; ++iMatTex) + if (!fTexUsage[iMatTex]) + ::TextureMap.RemoveEntry(iMatTex); + // flag rewrite + ::TextureMap.fEntriesAdded = true; + } bool C4Landscape::DebugSave(const char *szFilename) { diff --git a/src/game/landscape/C4Landscape.h b/src/game/landscape/C4Landscape.h index fb1c9e8a9..208f6f21d 100644 --- a/src/game/landscape/C4Landscape.h +++ b/src/game/landscape/C4Landscape.h @@ -31,8 +31,8 @@ #include const uint8_t GBM = 128, - GBM_ColNum = 64, - IFT = 0x80, + GBM_ColNum = 64, + IFT = 0x80, IFTOld = GBM_ColNum; const uint8_t CSkyDef1=104,CSkyDef2=123; @@ -40,7 +40,7 @@ const uint8_t CSkyDef1=104,CSkyDef2=123; const int32_t C4MaxMaterial = 125; const int32_t C4LSC_Undefined = 0, - C4LSC_Dynamic = 1, + C4LSC_Dynamic = 1, C4LSC_Static = 2, C4LSC_Exact = 3; @@ -51,29 +51,29 @@ class C4Object; class C4PropList; class C4Landscape - { - public: - C4Landscape(); + { + public: + C4Landscape(); ~C4Landscape(); - public: + public: int32_t Mode; int32_t Width,Height; int32_t MapWidth,MapHeight,MapZoom; CSurface8 * Map; - DWORD MatCount[C4MaxMaterial]; // NoSave // - DWORD EffectiveMatCount[C4MaxMaterial]; // NoSave // + DWORD MatCount[C4MaxMaterial]; // NoSave // + DWORD EffectiveMatCount[C4MaxMaterial]; // NoSave // uint8_t *BridgeMatConversion[C4MaxMaterial]; // NoSave // int32_t BlastMatCount[C4MaxMaterial]; // SyncClearance-NoSave // bool NoScan; // ExecuteScan() disabled - int32_t ScanX,ScanSpeed; // SyncClearance-NoSave // + int32_t ScanX,ScanSpeed; // SyncClearance-NoSave // int32_t LeftOpen,RightOpen,TopOpen,BottomOpen; FIXED Gravity; uint32_t Modulation; // landscape blit modulation; 0 means normal int32_t MapSeed; // random seed for MapToLandscape - C4Sky Sky; + C4Sky Sky; C4MapCreatorS2 *pMapCreator; // map creator for script-generated maps bool fMapChanged; - BYTE *pInitial; // Initial landscape after creation - used for diff + BYTE *pInitial; // Initial landscape after creation - used for diff protected: CSurface * Surface32; CSurface8 * Surface8; @@ -84,15 +84,15 @@ class C4Landscape public: void Default(); void Clear(bool fClearMapCreator=true, bool fClearSky=true); - void Execute(); + void Execute(); void Synchronize(); void Draw(C4TargetFacet &cgo, int32_t iPlayer=-1); - void ScenarioInit(); + void ScenarioInit(); void ClearRect(int32_t iTx, int32_t iTy, int32_t iWdt, int32_t iHgt); void ClearRectDensity(int32_t iTx, int32_t iTy, int32_t iWdt, int32_t iHgt, int32_t iOfDensity); void ClearMatCount(); void ClearBlastMatCount(); - void ScanSideOpen(); + void ScanSideOpen(); void CheckInstabilityRange(int32_t tx, int32_t ty); void ShakeFree(int32_t tx, int32_t ty, int32_t rad); void DigFree(int32_t tx, int32_t ty, int32_t rad, bool fRequest=false, C4Object *pByObj=NULL); @@ -107,7 +107,7 @@ class C4Landscape bool Save(C4Group &hGroup); bool SaveDiff(C4Group &hGroup, bool fSyncSave); bool SaveMap(C4Group &hGroup); - bool SaveInitial(); + bool SaveInitial(); bool SaveTextures(C4Group &hGroup); bool Init(C4Group &hGroup, bool fOverloadCurrent, bool fLoadSky, bool &rfLoaded, bool fSavegame); bool MapToLandscape(); @@ -192,7 +192,7 @@ class C4Landscape inline int32_t GetPixMat(BYTE byPix) { return Pix2Mat[byPix]; } inline int32_t GetPixDensity(BYTE byPix) { return Pix2Dens[byPix]; } bool _PathFree(int32_t x, int32_t y, int32_t x2, int32_t y2); // quickly checks wether there *might* be pixel in the path. - int32_t GetMatHeight(int32_t x, int32_t y, int32_t iYDir, int32_t iMat, int32_t iMax); + int32_t GetMatHeight(int32_t x, int32_t y, int32_t iYDir, int32_t iMat, int32_t iMax); int32_t DigFreePix(int32_t tx, int32_t ty); int32_t ShakeFreePix(int32_t tx, int32_t ty); int32_t BlastFreePix(int32_t tx, int32_t ty, int32_t grade, int32_t iBlastSize); @@ -211,10 +211,10 @@ class C4Landscape void SetMapChanged() { fMapChanged = true; } void HandleTexMapUpdate(); void UpdatePixMaps(); - bool DoRelights(); - void RemoveUnusedTexMapEntries(); - protected: - void ExecuteScan(); + bool DoRelights(); + void RemoveUnusedTexMapEntries(); + protected: + void ExecuteScan(); int32_t DoScan(int32_t x, int32_t y, int32_t mat, int32_t dir); int32_t ChunkyRandom(int32_t &iOffset, int32_t iRange); // return static random value, according to offset and MapSeed void DrawChunk(int32_t tx, int32_t ty, int32_t wdt, int32_t hgt, int32_t mcol, int32_t iChunkType, int32_t cro); @@ -232,21 +232,21 @@ class C4Landscape bool ApplyLighting(C4Rect To); DWORD GetClrByTex(int32_t iX, int32_t iY); bool Mat2Pal(); // assign material colors to landscape palette - void DigFreeSinglePix(int32_t x, int32_t y, int32_t dx, int32_t dy) - { - if(GetDensity(x, y) > GetDensity(x + dx, y + dy)) - DigFreePix(x, y); - } + void DigFreeSinglePix(int32_t x, int32_t y, int32_t dx, int32_t dy) + { + if(GetDensity(x, y) > GetDensity(x + dx, y + dy)) + DigFreePix(x, y); + } void UpdatePixCnt(const class C4Rect &Rect, bool fCheck = false); void UpdateMatCnt(C4Rect Rect, bool fPlus); void PrepareChange(C4Rect BoundingBox); void FinishChange(C4Rect BoundingBox); - static bool DrawLineLandscape(int32_t iX, int32_t iY, int32_t iGrade); + static bool DrawLineLandscape(int32_t iX, int32_t iY, int32_t iGrade); uint8_t *GetBridgeMatConversion(int for_material); - public: - void CompileFunc(StdCompiler *pComp); // without landscape bitmaps and sky + public: + void CompileFunc(StdCompiler *pComp); // without landscape bitmaps and sky bool DebugSave(const char *szFilename); - }; + }; extern C4Landscape Landscape; @@ -277,31 +277,31 @@ int32_t PixCol2Mat(BYTE pixc); #define _SBackPixIfMask ::Landscape._SetPixIfMask inline bool DensitySolid(int32_t dens) - { - return (dens>=C4M_Solid); - } + { + return (dens>=C4M_Solid); + } inline bool DensitySemiSolid(int32_t dens) - { - return (dens>=C4M_SemiSolid); - } + { + return (dens>=C4M_SemiSolid); + } inline bool DensityLiquid(int32_t dens) - { - return ((dens>=C4M_Liquid) && (dens=C4M_Liquid) && (dens=GBM+IFTOld) return IFTOld; - return 0; - } + { + if (pixc>=GBM+IFTOld) return IFTOld; + return 0; + } inline int32_t PixCol2Tex(BYTE pixc) { @@ -314,32 +314,32 @@ inline int32_t PixCol2Tex(BYTE pixc) } inline BYTE GBackIFT(int32_t x, int32_t y) - { - return PixColIFT(GBackPix(x,y)); - } + { + return PixColIFT(GBackPix(x,y)); + } inline int32_t GBackMat(int32_t x, int32_t y) - { + { return ::Landscape.GetMat(x, y); - } + } inline int32_t GBackDensity(int32_t x, int32_t y) - { + { return ::Landscape.GetDensity(x, y); - } + } inline bool GBackSolid(int32_t x, int32_t y) - { - return DensitySolid(GBackDensity(x,y)); - } + { + return DensitySolid(GBackDensity(x,y)); + } inline bool GBackSemiSolid(int32_t x, int32_t y) - { - return DensitySemiSolid(GBackDensity(x,y)); - } + { + return DensitySemiSolid(GBackDensity(x,y)); + } inline bool GBackLiquid(int32_t x, int32_t y) - { - return DensityLiquid(GBackDensity(x,y)); - } + { + return DensityLiquid(GBackDensity(x,y)); + } #endif diff --git a/src/game/landscape/C4Map.cpp b/src/game/landscape/C4Map.cpp index 07d7cd90d..c53136986 100644 --- a/src/game/landscape/C4Map.cpp +++ b/src/game/landscape/C4Map.cpp @@ -31,128 +31,128 @@ #include C4MapCreator::C4MapCreator() - { - Reset(); - } + { + Reset(); + } void C4MapCreator::Reset() - { - MapIFT=128; - MapBuf=NULL; - Exclusive=-1; - } + { + MapIFT=128; + MapBuf=NULL; + Exclusive=-1; + } void C4MapCreator::SetPix(int32_t x, int32_t y, BYTE col) - { - // Safety - if (!Inside(x,0,MapWdt-1) || !Inside(y,0,MapHgt-1)) return; - // Exclusive - if (Exclusive>-1) if (GetPix(x,y)!=Exclusive) return; - // Set pix - MapBuf->SetPix(x,y,col); - } + { + // Safety + if (!Inside(x,0,MapWdt-1) || !Inside(y,0,MapHgt-1)) return; + // Exclusive + if (Exclusive>-1) if (GetPix(x,y)!=Exclusive) return; + // Set pix + MapBuf->SetPix(x,y,col); + } void C4MapCreator::SetSpot(int32_t x, int32_t y, int32_t rad, BYTE col) - { - int32_t ycnt,xcnt,lwdt,dpy; - for (ycnt=-rad; ycnt<=rad; ycnt++) - { - lwdt= (int32_t) sqrt(double(rad*rad-ycnt*ycnt)); dpy=y+ycnt; - for (xcnt=-lwdt; xcnt(x,0,MapWdt-1) || !Inside(y,0,MapHgt-1)) return 0; - // Get pix - return MapBuf->GetPix(x,y); - } + { + // Safety + if (!Inside(x,0,MapWdt-1) || !Inside(y,0,MapHgt-1)) return 0; + // Get pix + return MapBuf->GetPix(x,y); + } void C4MapCreator::Create(CSurface8 *sfcMap, C4SLandscape &rLScape, C4TextureMap &rTexMap, bool fLayers, int32_t iPlayerNum) - { - double fullperiod= 20.0 * pi; - BYTE ccol; - int32_t cx,cy; + { + double fullperiod= 20.0 * pi; + BYTE ccol; + int32_t cx,cy; - // Safeties - if (!sfcMap) return; - iPlayerNum=BoundBy(iPlayerNum,1,C4S_MaxPlayer); + // Safeties + if (!sfcMap) return; + iPlayerNum=BoundBy(iPlayerNum,1,C4S_MaxPlayer); - // Set creator variables - MapBuf = sfcMap; - MapWdt = MapBuf->Wdt; MapHgt = MapBuf->Hgt; + // Set creator variables + MapBuf = sfcMap; + MapWdt = MapBuf->Wdt; MapHgt = MapBuf->Hgt; - // Reset map (0 is sky) - MapBuf->ClearBox8Only(0,0,MapBuf->Wdt, MapBuf->Hgt); + // Reset map (0 is sky) + MapBuf->ClearBox8Only(0,0,MapBuf->Wdt, MapBuf->Hgt); - // Surface - ccol=rTexMap.GetIndexMatTex(rLScape.Material)+MapIFT; - float amplitude= (float) rLScape.Amplitude.Evaluate(); - float phase= (float) rLScape.Phase.Evaluate(); - float period= (float) rLScape.Period.Evaluate(); - if (rLScape.MapPlayerExtend) period *= Min(iPlayerNum, C4S_MaxMapPlayerExtend); - float natural= (float) rLScape.Random.Evaluate(); - int32_t level0= Min(MapWdt,MapHgt)/2; - int32_t maxrange= level0*3/4; - double cy_curve,cy_natural; // -1.0 - +1.0 ! + // Surface + ccol=rTexMap.GetIndexMatTex(rLScape.Material)+MapIFT; + float amplitude= (float) rLScape.Amplitude.Evaluate(); + float phase= (float) rLScape.Phase.Evaluate(); + float period= (float) rLScape.Period.Evaluate(); + if (rLScape.MapPlayerExtend) period *= Min(iPlayerNum, C4S_MaxMapPlayerExtend); + float natural= (float) rLScape.Random.Evaluate(); + int32_t level0= Min(MapWdt,MapHgt)/2; + int32_t maxrange= level0*3/4; + double cy_curve,cy_natural; // -1.0 - +1.0 ! - double rnd_cy,rnd_tend; // -1.0 - +1.0 ! - rnd_cy= (double) (Random(2000+1)-1000)/1000.0; - rnd_tend= (double) (Random(200+1)-100)/20000.0; + double rnd_cy,rnd_tend; // -1.0 - +1.0 ! + rnd_cy= (double) (Random(2000+1)-1000)/1000.0; + rnd_tend= (double) (Random(200+1)-100)/20000.0; - for (cx=0; cx+0.05) rnd_tend=+0.05; - if (rnd_tend<-0.05) rnd_tend=-0.05; - if (rnd_cy<-0.5) rnd_tend+=0.01; - if (rnd_cy>+0.5) rnd_tend-=0.01; + rnd_cy+=rnd_tend; + rnd_tend+= (double) (Random(100+1)-50)/10000; + if (rnd_tend>+0.05) rnd_tend=+0.05; + if (rnd_tend<-0.05) rnd_tend=-0.05; + if (rnd_cy<-0.5) rnd_tend+=0.01; + if (rnd_cy>+0.5) rnd_tend-=0.01; - cy_natural=rnd_cy*natural/100.0; - cy_curve=sin(fullperiod*period/100.0*(float)cx/(float)MapWdt - +2.0*pi*phase/100.0) * amplitude/100.0; + cy_natural=rnd_cy*natural/100.0; + cy_curve=sin(fullperiod*period/100.0*(float)cx/(float)MapWdt + +2.0*pi*phase/100.0) * amplitude/100.0; - cy=level0+BoundBy((int32_t)((float)maxrange*(cy_curve+cy_natural)), - -maxrange,+maxrange); + cy=level0+BoundBy((int32_t)((float)maxrange*(cy_curve+cy_natural)), + -maxrange,+maxrange); - SetPix(cx,cy,ccol); - } + SetPix(cx,cy,ccol); + } - // Raise bottom to surface - for (cx=0; cx=0) && !GetPix(cx,cy); cy--) - SetPix(cx,cy,ccol); - // Raise liquid level - Exclusive=0; - ccol=rTexMap.GetIndexMatTex(rLScape.Liquid); - int32_t wtr_level=rLScape.LiquidLevel.Evaluate(); - for (cx=0; cx=0) && !GetPix(cx,cy); cy--) + SetPix(cx,cy,ccol); + // Raise liquid level + Exclusive=0; + ccol=rTexMap.GetIndexMatTex(rLScape.Liquid); + int32_t wtr_level=rLScape.LiquidLevel.Evaluate(); + for (cx=0; cx>=2; val<<=2; val+=4; } - } + { + if (val%4) { val>>=2; val<<=2; val+=4; } + } BYTE *C4MapCreatorS2::RenderBuf(const char *szMapName, int32_t &sfcWdt, int32_t &sfcHgt) { @@ -1480,7 +1480,7 @@ bool AlgoChecker(C4MCOverlay *pOvrl, int32_t iX, int32_t iY) bool AlgoBozo(C4MCOverlay *pOvrl, int32_t iX, int32_t iY) { - // do some bozo stuff - keep it regular here, since it may be modified by turbulence + // do some bozo stuff - keep it regular here, since it may be modified by turbulence int32_t iXC=(iX/10+s+(iY/80))%(z*2)-z; int32_t iYC=(iY/10+s+(iX/80))%(z*2)-z; int32_t id=Abs(iXC*iYC); // ((iSeed^iX^iY)%z) diff --git a/src/game/landscape/C4MassMover.cpp b/src/game/landscape/C4MassMover.cpp index b167e9f71..114998d3d 100644 --- a/src/game/landscape/C4MassMover.cpp +++ b/src/game/landscape/C4MassMover.cpp @@ -42,19 +42,19 @@ // hardly ever exceeding 1000. October 1997 C4MassMoverSet::C4MassMoverSet() - { + { Default(); - } + } C4MassMoverSet::~C4MassMoverSet() - { - Clear(); - } + { + Clear(); + } void C4MassMoverSet::Clear() - { + { - } + } void C4MassMoverSet::Execute() { @@ -69,75 +69,75 @@ void C4MassMoverSet::Execute() if (cmm->Mat!=MNone) { Count++; cmm->Execute(); } } - } + } bool C4MassMoverSet::Create(int32_t x, int32_t y, bool fExecute) - { + { if(Count == C4MassMoverChunk) return false; #ifdef DEBUGREC C4RCMassMover rc; rc.x=x; rc.y=y; AddDbgRec(RCT_MMC, &rc, sizeof(rc)); #endif - int32_t cptr=CreatePtr; - do - { - cptr++; - if (cptr>=C4MassMoverChunk) cptr=0; - if (Set[cptr].Mat==MNone) - { - if (!Set[cptr].Init(x,y)) return false; - CreatePtr=cptr; + int32_t cptr=CreatePtr; + do + { + cptr++; + if (cptr>=C4MassMoverChunk) cptr=0; + if (Set[cptr].Mat==MNone) + { + if (!Set[cptr].Init(x,y)) return false; + CreatePtr=cptr; if (fExecute) Set[cptr].Execute(); return true; - } - } - while (cptr!=CreatePtr); - return false; - } + } + } + while (cptr!=CreatePtr); + return false; + } void C4MassMoverSet::Draw() - { - /*int32_t cnt; - for (cnt=0; cnt(tx,0,GBackWdt-1) || !Inside(ty,0,GBackHgt-1)) - return false; - // Check mat - Mat=GBackMat(tx,ty); - x=tx; y=ty; + { + // Out of bounds check + if (!Inside(tx,0,GBackWdt-1) || !Inside(ty,0,GBackHgt-1)) + return false; + // Check mat + Mat=GBackMat(tx,ty); + x=tx; y=ty; ::MassMover.Count++; - return (Mat!=MNone); - } + return (Mat!=MNone); + } void C4MassMover::Cease() - { + { #ifdef DEBUGREC C4RCMassMover rc; rc.x=x; rc.y=y; AddDbgRec(RCT_MMD, &rc, sizeof(rc)); #endif ::MassMover.Count--; - Mat=MNone; - } + Mat=MNone; + } bool C4MassMover::Execute() - { - int32_t tx,ty; + { + int32_t tx,ty; - // Lost target material - if (GBackMat(x,y)!=Mat) { Cease(); return false; } + // Lost target material + if (GBackMat(x,y)!=Mat) { Cease(); return false; } - // Check for transfer target space + // Check for transfer target space C4Material *pMat = ::MaterialMap.Map+Mat; - tx=x; ty=y; - if (!::Landscape.FindMatPath(tx,ty,+1,pMat->Density,pMat->MaxSlide)) - { + tx=x; ty=y; + if (!::Landscape.FindMatPath(tx,ty,+1,pMat->Density,pMat->MaxSlide)) + { // Contact material reaction check: corrosion/evaporation/inflammation/etc. if (Corrosion(+0,+1) || Corrosion(-1,+0) || Corrosion(+1,+0)) { @@ -163,7 +163,7 @@ bool C4MassMover::Execute() if (Game.C4S.Game.Realism.LandscapeInsertThrust) omat = GBackMat(tx, ty); - // Transfer mass + // Transfer mass if(Random(10)) SBackPix(tx,ty,Mat2PixColDefault(::Landscape.ExtractMaterial(x,y))+GBackIFT(tx,ty)); else @@ -173,11 +173,11 @@ bool C4MassMover::Execute() if(Game.C4S.Game.Realism.LandscapeInsertThrust && MatValid(omat) && ::MaterialMap.Map[omat].Density > 0) ::Landscape.InsertMaterial(omat, tx, ty + 1); - // Create new mover at target - ::MassMover.Create(tx,ty,!Rnd3()); + // Create new mover at target + ::MassMover.Create(tx,ty,!Rnd3()); - return true; - } + return true; + } bool C4MassMover::Corrosion(int32_t dx, int32_t dy) { @@ -195,10 +195,10 @@ bool C4MassMover::Corrosion(int32_t dx, int32_t dy) void C4MassMoverSet::Default() { - int32_t cnt; - for (cnt=0; cnt(*this, Source, Name.getData())) + if(!CompileFromBuf_LogWarn(*this, Source, Name.getData())) return false; // adjust placement, if not specified if (!Placement) @@ -218,7 +218,7 @@ void C4MaterialCore::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(BelowTempConvertDir, "BelowTempConvertDir",0 )); pComp->Value(mkNamingAdapt(mkParAdapt(sBelowTempConvertTo, StdCompiler::RCT_IdtfAllowEmpty),"BelowTempConvertTo", "" )); pComp->Value(mkNamingAdapt(MinHeightCount, "MinHeightCount", 0 )); - pComp->Value(mkNamingAdapt(SplashRate, "SplashRate", 10 )); + pComp->Value(mkNamingAdapt(SplashRate, "SplashRate", 10 )); pComp->NameEnd(); // material reactions pComp->Value(mkNamingAdapt( @@ -230,12 +230,12 @@ void C4MaterialCore::CompileFunc(StdCompiler *pComp) // -------------------------------------- C4Material C4Material::C4Material() - { - BlastShiftTo=0; - InMatConvertTo=MNone; - BelowTempConvertTo=0; - AboveTempConvertTo=0; - } + { + BlastShiftTo=0; + InMatConvertTo=MNone; + BelowTempConvertTo=0; + AboveTempConvertTo=0; + } void C4Material::UpdateScriptPointers() { @@ -248,35 +248,35 @@ void C4Material::UpdateScriptPointers() C4MaterialMap::C4MaterialMap() : DefReactConvert(&mrfConvert), DefReactPoof(&mrfPoof), DefReactCorrode(&mrfCorrode), DefReactIncinerate(&mrfIncinerate), DefReactInsert(&mrfInsert) - { + { Default(); - } + } C4MaterialMap::~C4MaterialMap() - { - Clear(); - } + { + Clear(); + } void C4MaterialMap::Clear() - { - if (Map) delete [] Map; Map=NULL; + { + if (Map) delete [] Map; Map=NULL; delete [] ppReactionMap; ppReactionMap = NULL; - } + } int32_t C4MaterialMap::Load(C4Group &hGroup) - { + { char entryname[256+1]; - // Determine number of materials in files - int32_t mat_num=hGroup.EntryCount(C4CFN_MaterialFiles); + // Determine number of materials in files + int32_t mat_num=hGroup.EntryCount(C4CFN_MaterialFiles); - // Allocate new map + // Allocate new map C4Material *pNewMap = new C4Material [mat_num + Num]; if(!pNewMap) return 0; - // Load material cores to map - hGroup.ResetSearch(); int32_t cnt=0; + // Load material cores to map + hGroup.ResetSearch(); int32_t cnt=0; while (hGroup.FindNextEntry(C4CFN_MaterialFiles,entryname)) { // Load mat @@ -298,8 +298,8 @@ int32_t C4MaterialMap::Load(C4Group &hGroup) // set material number Num+=cnt; - return cnt; - } + return cnt; + } bool C4MaterialMap::HasMaterials(C4Group &hGroup) const { @@ -307,13 +307,13 @@ bool C4MaterialMap::HasMaterials(C4Group &hGroup) const } int32_t C4MaterialMap::Get(const char *szMaterial) - { - int32_t cnt; - for (cnt=0; cnt= ::MaterialMap.Num) return MNone; return iMat; - } + } C4MaterialMap MaterialMap; diff --git a/src/game/landscape/C4Material.h b/src/game/landscape/C4Material.h index 259e52211..13d961ac9 100644 --- a/src/game/landscape/C4Material.h +++ b/src/game/landscape/C4Material.h @@ -74,87 +74,87 @@ struct C4MaterialReaction }; class C4MaterialCore - { + { public: C4MaterialCore(); ~C4MaterialCore() { Clear(); } public: std::vector CustomReactionList; - public: - char Name[C4M_MaxName+1]; - int32_t MapChunkType; - int32_t Density; - int32_t Friction; - int32_t DigFree; - int32_t BlastFree; - C4ID Dig2Object; - int32_t Dig2ObjectRatio; - int32_t Dig2ObjectOnRequestOnly; - C4ID Blast2Object; - int32_t Blast2ObjectRatio; - int32_t Blast2PXSRatio; - int32_t Instable; - int32_t MaxAirSpeed; - int32_t MaxSlide; - int32_t WindDrift; - int32_t Inflammable; - int32_t Incindiary; - int32_t Extinguisher; + public: + char Name[C4M_MaxName+1]; + int32_t MapChunkType; + int32_t Density; + int32_t Friction; + int32_t DigFree; + int32_t BlastFree; + C4ID Dig2Object; + int32_t Dig2ObjectRatio; + int32_t Dig2ObjectOnRequestOnly; + C4ID Blast2Object; + int32_t Blast2ObjectRatio; + int32_t Blast2PXSRatio; + int32_t Instable; + int32_t MaxAirSpeed; + int32_t MaxSlide; + int32_t WindDrift; + int32_t Inflammable; + int32_t Incindiary; + int32_t Extinguisher; int32_t Corrosive; int32_t Corrode; - int32_t Soil; + int32_t Soil; int32_t Placement; // placement order for landscape shading StdCopyStrBuf sTextureOverlay; // overlayed texture for this material int32_t OverlayType; // defines the way in which the overlay texture is applied StdCopyStrBuf sPXSGfx; // newgfx: picture used for loose pxs C4TargetRect PXSGfxRt; // newgfx: facet rect of pixture used for loose pixels int32_t PXSGfxSize; - StdCopyStrBuf sBlastShiftTo; - StdCopyStrBuf sInMatConvert; - StdCopyStrBuf sInMatConvertTo; + StdCopyStrBuf sBlastShiftTo; + StdCopyStrBuf sInMatConvert; + StdCopyStrBuf sInMatConvertTo; int32_t InMatConvertDepth; // material converts only if it finds the same material above - int32_t BelowTempConvert; - int32_t BelowTempConvertDir; - StdCopyStrBuf sBelowTempConvertTo; - int32_t AboveTempConvert; - int32_t AboveTempConvertDir; - StdCopyStrBuf sAboveTempConvertTo; + int32_t BelowTempConvert; + int32_t BelowTempConvertDir; + StdCopyStrBuf sBelowTempConvertTo; + int32_t AboveTempConvert; + int32_t AboveTempConvertDir; + StdCopyStrBuf sAboveTempConvertTo; int32_t ColorAnimation; int32_t TempConvStrength; int32_t MinHeightCount; // minimum material thickness in order for it to be counted - int32_t SplashRate; + int32_t SplashRate; public: void Clear(); void Default(); bool Load(C4Group &hGroup, const char *szEntryName); void CompileFunc(StdCompiler *pComp); - }; + }; class C4Material: public C4MaterialCore - { - public: - C4Material(); - public: + { + public: + C4Material(); + public: // Cross-mapped material values - int32_t BlastShiftTo; // MatTex - int32_t InMatConvertTo; // Mat - int32_t BelowTempConvertTo; // MatTex - int32_t AboveTempConvertTo; // MatTex + int32_t BlastShiftTo; // MatTex + int32_t InMatConvertTo; // Mat + int32_t BelowTempConvertTo; // MatTex + int32_t AboveTempConvertTo; // MatTex int32_t DefaultMatTex; // texture used for single pixel values C4Facet PXSFace; // loose pixel facet void UpdateScriptPointers(); // set all material script pointers - }; + }; class C4MaterialMap - { - public: - C4MaterialMap(); - ~C4MaterialMap(); - public: - int32_t Num; - C4Material *Map; + { + public: + C4MaterialMap(); + ~C4MaterialMap(); + public: + int32_t Num; + C4Material *Map; C4MaterialReaction **ppReactionMap; C4MaterialReaction DefReactConvert, DefReactPoof, DefReactCorrode, DefReactIncinerate, DefReactInsert; @@ -167,13 +167,13 @@ class C4MaterialMap static bool mrfInsert (C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged); // user-defined actions static bool mrfScript(C4MaterialReaction *pReaction, int32_t &iX, int32_t &iY, int32_t iLSPosX, int32_t iLSPosY, FIXED &fXDir, FIXED &fYDir, int32_t &iPxsMat, int32_t iLsMat, MaterialInteractionEvent evEvent, bool *pfPosChanged); - public: + public: void Default(); - void Clear(); - int32_t Load(C4Group &hGroup); + void Clear(); + int32_t Load(C4Group &hGroup); bool HasMaterials(C4Group &hGroup) const; - int32_t Get(const char *szMaterial); - bool SaveEnumeration(C4Group &hGroup); + int32_t Get(const char *szMaterial); + bool SaveEnumeration(C4Group &hGroup); bool LoadEnumeration(C4Group &hGroup); C4MaterialReaction *GetReactionUnsafe(int32_t iPXSMat, int32_t iLandscapeMat) { assert(ppReactionMap); assert(Inside(iPXSMat,-1,Num-1)); assert(Inside(iLandscapeMat,-1,Num-1)); @@ -181,24 +181,24 @@ class C4MaterialMap C4MaterialReaction *GetReaction(int32_t iPXSMat, int32_t iLandscapeMat); void UpdateScriptPointers(); // set all material script pointers bool CrossMapMaterials(); - protected: + protected: void SetMatReaction(int32_t iPXSMat, int32_t iLSMat, C4MaterialReaction *pReact); bool SortEnumeration(int32_t iMat, const char *szMatName); - }; + }; extern C4MaterialMap MaterialMap; const int32_t C4M_Flat = 0, - C4M_TopFlat = 1, - C4M_Smooth = 2, - C4M_Rough = 3, + C4M_TopFlat = 1, + C4M_Smooth = 2, + C4M_Rough = 3, - // Material Density Levels + // Material Density Levels C4M_Vehicle = 100, - C4M_Solid = 50, - C4M_SemiSolid = 25, - C4M_Liquid = 25, + C4M_Solid = 50, + C4M_SemiSolid = 25, + C4M_Liquid = 25, C4M_Background= 0; const int32_t MNone = -1; @@ -207,9 +207,9 @@ extern int32_t MVehic,MTunnel,MWater,MSnow,MEarth,MGranite,MFlyAshes; // presear extern BYTE MCVehic; // precalculated material color inline bool MatValid(int32_t mat) - { - return Inside(mat,0,::MaterialMap.Num-1); - } + { + return Inside(mat,0,::MaterialMap.Num-1); + } inline bool MatVehicle(int32_t iMat) { @@ -217,9 +217,9 @@ inline bool MatVehicle(int32_t iMat) } inline BYTE MatTex2PixCol(int32_t tex) - { + { return BYTE(tex); - } + } inline BYTE Mat2PixColDefault(int32_t mat) { @@ -227,22 +227,22 @@ inline BYTE Mat2PixColDefault(int32_t mat) } inline int32_t MatDensity(int32_t mat) - { - if (!MatValid(mat)) return 0; - return ::MaterialMap.Map[mat].Density; - } + { + if (!MatValid(mat)) return 0; + return ::MaterialMap.Map[mat].Density; + } inline int32_t MatPlacement(int32_t mat) - { - if (!MatValid(mat)) return 0; - return ::MaterialMap.Map[mat].Placement; - } + { + if (!MatValid(mat)) return 0; + return ::MaterialMap.Map[mat].Placement; + } inline int32_t MatDigFree(int32_t mat) - { - if (!MatValid(mat)) return 1; - return ::MaterialMap.Map[mat].DigFree; - } + { + if (!MatValid(mat)) return 1; + return ::MaterialMap.Map[mat].DigFree; + } int32_t PixCol2MatOld(BYTE pixc); int32_t PixCol2MatOld2(BYTE pixc); diff --git a/src/game/landscape/C4PXS.cpp b/src/game/landscape/C4PXS.cpp index 2a2b9c927..9e7002074 100644 --- a/src/game/landscape/C4PXS.cpp +++ b/src/game/landscape/C4PXS.cpp @@ -33,7 +33,7 @@ static const FIXED WindDrift_Factor = itofix(1, 800); void C4PXS::Execute() - { + { #ifdef DEBUGREC_PXS { C4RCExecPXS rc; @@ -132,19 +132,19 @@ void C4PXS::Execute() } #endif return; - } + } void C4PXS::Deactivate() - { + { #ifdef DEBUGREC_PXS C4RCExecPXS rc; rc.x=x; rc.y=y; rc.iMat=Mat; rc.pos = 2; AddDbgRec(RCT_ExecPXS, &rc, sizeof(rc)); #endif - Mat=MNone; + Mat=MNone; ::PXS.Delete(this); - } + } C4PXSSystem::C4PXSSystem() { @@ -177,19 +177,19 @@ void C4PXSSystem::Clear() } C4PXS* C4PXSSystem::New() - { - unsigned int cnt,cnt2; - C4PXS *pxp; - // Check chunks for available space - for (cnt=0; cntMat==MNone) @@ -198,20 +198,20 @@ C4PXS* C4PXSSystem::New() iChunkPXS[cnt]++; return pxp; } - } - return NULL; - } + } + return NULL; + } bool C4PXSSystem::Create(int32_t mat, FIXED ix, FIXED iy, FIXED ixdir, FIXED iydir) - { - C4PXS *pxp; - if (!MatValid(mat)) return false; - if (!(pxp=New())) return false; - pxp->Mat=mat; - pxp->x=ix; pxp->y=iy; - pxp->xdir=ixdir; pxp->ydir=iydir; - return true; - } + { + C4PXS *pxp; + if (!MatValid(mat)) return false; + if (!(pxp=New())) return false; + pxp->Mat=mat; + pxp->x=ix; pxp->y=iy; + pxp->xdir=ixdir; pxp->ydir=iydir; + return true; + } void C4PXSSystem::Execute() { @@ -316,17 +316,17 @@ void C4PXSSystem::Draw(C4TargetFacet &cgo) } } - } + } void C4PXSSystem::Cast(int32_t mat, int32_t num, int32_t tx, int32_t ty, int32_t level) - { - int32_t cnt; - for (cnt=0; cnt class C4PXS - { + { C4PXS(): Mat(MNone), x(Fix0), y(Fix0), xdir(Fix0), ydir(Fix0) {} friend class C4PXSSystem; - protected: - int32_t Mat; - FIXED x,y,xdir,ydir; - protected: - void Execute(); - void Deactivate(); - }; + protected: + int32_t Mat; + FIXED x,y,xdir,ydir; + protected: + void Execute(); + void Deactivate(); + }; const size_t PXSChunkSize=500,PXSMaxChunk=20; diff --git a/src/game/landscape/C4Particles.cpp b/src/game/landscape/C4Particles.cpp index 7df48f463..ae55c8d97 100644 --- a/src/game/landscape/C4Particles.cpp +++ b/src/game/landscape/C4Particles.cpp @@ -415,7 +415,7 @@ C4Particle *C4ParticleSystem::Create(C4ParticleDef *pOfDef, float x, float y, float xdir, float ydir, float a, int32_t b, C4ParticleList *pPxList, - C4Object *pObj) + C4Object *pObj) { // safety if (!pOfDef) return NULL; @@ -437,10 +437,10 @@ C4Particle *C4ParticleSystem::Create(C4ParticleDef *pOfDef, pPrt->xdir=xdir; pPrt->ydir=ydir; pPrt->a=a; pPrt->b=b; pPrt->pDef = pOfDef; - if(pPrt->pDef->Attach && pObj != NULL) { - pPrt->x -= pObj->GetX(); - pPrt->y -= pObj->GetY(); - } + if(pPrt->pDef->Attach && pObj != NULL) { + pPrt->x -= pObj->GetX(); + pPrt->y -= pObj->GetY(); + } // call initialization if (!pOfDef->InitProc(pPrt,pObj)) // failed :( @@ -651,16 +651,16 @@ bool fxStdInit(C4Particle *pPrt, C4Object *pTarget) bool fxStdExec(C4Particle *pPrt, C4Object *pTarget) { - float dx = pPrt->x, dy = pPrt->y; - float dxdir = pPrt->xdir, dydir = pPrt->ydir; - // rel. position & movement - if(pPrt->pDef->Attach && pTarget != NULL) - { - dx += pTarget->GetX(); - dy += pTarget->GetY(); - dxdir += fixtof(pTarget->xdir); - dydir += fixtof(pTarget->ydir); - } + float dx = pPrt->x, dy = pPrt->y; + float dxdir = pPrt->xdir, dydir = pPrt->ydir; + // rel. position & movement + if(pPrt->pDef->Attach && pTarget != NULL) + { + dx += pTarget->GetX(); + dy += pTarget->GetY(); + dxdir += fixtof(pTarget->xdir); + dydir += fixtof(pTarget->ydir); + } // move if (pPrt->xdir || pPrt->ydir) @@ -779,16 +779,16 @@ void fxStdDraw(C4Particle *pPrt, C4TargetFacet &cgo, C4Object *pTarget) int32_t tx=cgo.TargetX*pDef->Parallaxity[0]/100; int32_t ty=cgo.TargetY*pDef->Parallaxity[1]/100; - float dx = pPrt->x, dy = pPrt->y; - float dxdir = pPrt->xdir, dydir = pPrt->ydir; - // relative position & movement - if(pPrt->pDef->Attach && pTarget != NULL) - { - dx += pTarget->GetX(); - dy += pTarget->GetY(); - dxdir += fixtof(pTarget->xdir); - dydir += fixtof(pTarget->ydir); - } + float dx = pPrt->x, dy = pPrt->y; + float dxdir = pPrt->xdir, dydir = pPrt->ydir; + // relative position & movement + if(pPrt->pDef->Attach && pTarget != NULL) + { + dx += pTarget->GetX(); + dy += pTarget->GetY(); + dxdir += fixtof(pTarget->xdir); + dydir += fixtof(pTarget->ydir); + } // check if it's in screen range if (!Inside(dx, tx-pPrt->a, tx+cgo.Wdt+pPrt->a)) return; diff --git a/src/game/landscape/C4PathFinder.cpp b/src/game/landscape/C4PathFinder.cpp index 05d5d7811..2880f03d5 100644 --- a/src/game/landscape/C4PathFinder.cpp +++ b/src/game/landscape/C4PathFinder.cpp @@ -22,7 +22,7 @@ /* Notes - 09-30-99 + 09-30-99 I have had the concept for this code for more than two years now. Finally, it is written. @@ -287,15 +287,15 @@ void C4PathFinderRay::Draw(C4TargetFacet &cgo) bool C4PathFinderRay::PathFree(int32_t &rX, int32_t &rY, int32_t iToX, int32_t iToY, C4TransferZone **ppZone) { - int32_t d,dx,dy,aincr,bincr,xincr,yincr,x,y; + int32_t d,dx,dy,aincr,bincr,xincr,yincr,x,y; // Y based - if (Abs(iToX-rX)rX) ? +1 : -1; yincr=(iToY>rY) ? +1 : -1; - dy=Abs(iToY-rY); dx=Abs(iToX-rX); + if (Abs(iToX-rX)rX) ? +1 : -1; yincr=(iToY>rY) ? +1 : -1; + dy=Abs(iToY-rY); dx=Abs(iToX-rX); d=2*dx-dy; aincr=2*(dx-dy); bincr=2*dx; x=rX; y=rY; - for (y=rY; y!=iToY; y+=yincr) - { + for (y=rY; y!=iToY; y+=yincr) + { // Check point free if (PointFree(x,y)) { rY=y; rX=x; } else return false; // Check transfer zone intersection @@ -305,17 +305,17 @@ bool C4PathFinderRay::PathFree(int32_t &rX, int32_t &rY, int32_t iToX, int32_t i if ((*ppZone = pPathFinder->TransferZones->Find(rX,rY))) return false; // Advance - if (d>=0) { x+=xincr; d+=aincr; } else d+=bincr; - } - } + if (d>=0) { x+=xincr; d+=aincr; } else d+=bincr; + } + } // X based - else - { - yincr=(iToY>rY) ? +1 : -1; xincr=(iToX>rX) ? +1 : -1; + else + { + yincr=(iToY>rY) ? +1 : -1; xincr=(iToX>rX) ? +1 : -1; dx=Abs(iToX-rX); dy=Abs(iToY-rY); d=2*dy-dx; aincr=2*(dy-dx); bincr=2*dy; x=rX; y=rY; for (x=rX; x!=iToX; x+=xincr) - { + { // Check point free if (PointFree(x,y)) { rY=y; rX=x; } else return false; // Check transfer zone intersection @@ -325,42 +325,42 @@ bool C4PathFinderRay::PathFree(int32_t &rX, int32_t &rY, int32_t iToX, int32_t i if ((*ppZone = pPathFinder->TransferZones->Find(rX,rY))) return false; // Advance - if (d>=0) { y+=yincr; d+=aincr; } else d+=bincr; - } - } + if (d>=0) { y+=yincr; d+=aincr; } else d+=bincr; + } + } - return true; + return true; } /*void C4PathFinderRay::DrawLine(SURFACE sfcSurface, int32_t rX, int32_t rY, int32_t iToX, int32_t iToY, BYTE byCol) { - int32_t d,dx,dy,aincr,bincr,xincr,yincr,x,y; + int32_t d,dx,dy,aincr,bincr,xincr,yincr,x,y; // Y based - if (Abs(iToX-rX)rX) ? +1 : -1; + if (Abs(iToX-rX)rX) ? +1 : -1; yincr=(iToY>rY) ? +1 : -1; - dy=Abs(iToY-rY); dx=Abs(iToX-rX); + dy=Abs(iToY-rY); dx=Abs(iToX-rX); d=2*dx-dy; aincr=2*(dx-dy); bincr=2*dx; x=rX; y=rY; - for (y=rY; y!=iToY; y+=yincr) - { + for (y=rY; y!=iToY; y+=yincr) + { Application.DDraw->SetPixel(sfcSurface,x,y,byCol); - if (d>=0) { x+=xincr; d+=aincr; } else d+=bincr; - } - } + if (d>=0) { x+=xincr; d+=aincr; } else d+=bincr; + } + } // X based - else - { - yincr=(iToY>rY) ? +1 : -1; - xincr=(iToX>rX) ? +1 : -1; + else + { + yincr=(iToY>rY) ? +1 : -1; + xincr=(iToX>rX) ? +1 : -1; dx=Abs(iToX-rX); dy=Abs(iToY-rY); d=2*dy-dx; aincr=2*(dy-dx); bincr=2*dy; x=rX; y=rY; for (x=rX; x!=iToX; x+=xincr) - { + { Application.DDraw->SetPixel(sfcSurface,x,y,byCol); - if (d>=0) { y+=yincr; d+=aincr; } else d+=bincr; - } - } + if (d>=0) { y+=yincr; d+=aincr; } else d+=bincr; + } + } }*/ diff --git a/src/game/landscape/C4Scenario.cpp b/src/game/landscape/C4Scenario.cpp index 2c1718be9..fc55973e8 100644 --- a/src/game/landscape/C4Scenario.cpp +++ b/src/game/landscape/C4Scenario.cpp @@ -33,19 +33,19 @@ //==================================== C4SVal ============================================== C4SVal::C4SVal(int32_t std, int32_t rnd, int32_t min, int32_t max) - : Std(std), Rnd(rnd), Min(min), Max(max) - { - } + : Std(std), Rnd(rnd), Min(min), Max(max) + { + } void C4SVal::Set(int32_t std, int32_t rnd, int32_t min, int32_t max) - { - Std=std; Rnd=rnd; Min=min; Max=max; - } + { + Std=std; Rnd=rnd; Min=min; Max=max; + } int32_t C4SVal::Evaluate() - { - return BoundBy(Std+Random(2*Rnd+1)-Rnd,Min,Max); - } + { + return BoundBy(Std+Random(2*Rnd+1)-Rnd,Min,Max); + } void C4SVal::Default() { @@ -53,39 +53,39 @@ void C4SVal::Default() } void C4SVal::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkDefaultAdapt(Std, 0)); - if (!pComp->Seperator()) return; - pComp->Value(mkDefaultAdapt(Rnd, 0)); - if (!pComp->Seperator()) return; - pComp->Value(mkDefaultAdapt(Min, 0)); - if (!pComp->Seperator()) return; - pComp->Value(mkDefaultAdapt(Max, 100)); - } + { + pComp->Value(mkDefaultAdapt(Std, 0)); + if (!pComp->Seperator()) return; + pComp->Value(mkDefaultAdapt(Rnd, 0)); + if (!pComp->Seperator()) return; + pComp->Value(mkDefaultAdapt(Min, 0)); + if (!pComp->Seperator()) return; + pComp->Value(mkDefaultAdapt(Max, 100)); + } //================================ C4Scenario ========================================== C4Scenario::C4Scenario() - { - Default(); - } + { + Default(); + } void C4Scenario::Default() - { - int32_t cnt; - Head.Default(); + { + int32_t cnt; + Head.Default(); Definitions.Default(); - Game.Default(); - for (cnt=0; cntValue(mkNamingAdapt(mkParAdapt(Head, fSection), "Head")); - if (!fSection) pComp->Value(mkNamingAdapt(Definitions, "Definitions")); + { + pComp->Value(mkNamingAdapt(mkParAdapt(Head, fSection), "Head")); + if (!fSection) pComp->Value(mkNamingAdapt(Definitions, "Definitions")); pComp->Value(mkNamingAdapt(mkParAdapt(Game, fSection), "Game")); - for(int32_t i = 0; i < C4S_MaxPlayer; i++) - pComp->Value(mkNamingAdapt(PlrStart[i], FormatString("Player%d", i+1).getData())); - pComp->Value(mkNamingAdapt(Landscape, "Landscape")); - pComp->Value(mkNamingAdapt(Animals, "Animals")); - pComp->Value(mkNamingAdapt(Weather, "Weather")); - pComp->Value(mkNamingAdapt(Environment, "Environment")); - } + for(int32_t i = 0; i < C4S_MaxPlayer; i++) + pComp->Value(mkNamingAdapt(PlrStart[i], FormatString("Player%d", i+1).getData())); + pComp->Value(mkNamingAdapt(Landscape, "Landscape")); + pComp->Value(mkNamingAdapt(Animals, "Animals")); + pComp->Value(mkNamingAdapt(Weather, "Weather")); + pComp->Value(mkNamingAdapt(Environment, "Environment")); + } int32_t C4Scenario::GetMinPlayer() { @@ -132,7 +132,7 @@ int32_t C4Scenario::GetMinPlayer() } void C4SDefinitions::Default() - { + { LocalOnly=AllowUserChange=false; ZeroMem(Definition,sizeof (Definition)); SkipDefs.Default(); @@ -141,7 +141,7 @@ void C4SDefinitions::Default() const int32_t C4S_MaxPlayerDefault = 12; void C4SHead::Default() - { + { Origin.Clear(); Icon=18; *Title = *Loader = *Font = *Engine = *MissionAccess = '\0'; @@ -153,10 +153,10 @@ void C4SHead::Default() MaxPlayer=MaxPlayerLeague=C4S_MaxPlayerDefault; MinPlayer=0; // auto-determine by mode SCopy("Default Title",Title,C4MaxTitle); - } + } void C4SHead::CompileFunc(StdCompiler *pComp, bool fSection) - { + { if (!fSection) { pComp->Value(mkNamingAdapt(Icon, "Icon", 18)); @@ -187,17 +187,17 @@ void C4SHead::CompileFunc(StdCompiler *pComp, bool fSection) // windows needs backslashes in Origin; other systems use forward slashes if (pComp->isCompiler()) Origin.ReplaceChar(AltDirectorySeparator, DirectorySeparator); } - } + } void C4SGame::Default() - { + { Goals.Clear(); Rules.Clear(); FoWColor=0; - } + } void C4SGame::CompileFunc(StdCompiler *pComp, bool fSection) - { + { if (!fSection) { pComp->Value(mkNamingAdapt(Realism.ValueOverloads, "ValueOverloads", C4IDList())); @@ -205,27 +205,27 @@ void C4SGame::CompileFunc(StdCompiler *pComp, bool fSection) pComp->Value(mkNamingAdapt(mkRuntimeValueAdapt(Realism.LandscapePushPull), "LandscapePushPull", false)); pComp->Value(mkNamingAdapt(mkRuntimeValueAdapt(Realism.LandscapeInsertThrust), "LandscapeInsertThrust",true)); - pComp->Value(mkNamingAdapt(Goals, "Goals", C4IDList())); - pComp->Value(mkNamingAdapt(Rules, "Rules", C4IDList())); - pComp->Value(mkNamingAdapt(FoWColor, "FoWColor", 0u)); - } + pComp->Value(mkNamingAdapt(Goals, "Goals", C4IDList())); + pComp->Value(mkNamingAdapt(Rules, "Rules", C4IDList())); + pComp->Value(mkNamingAdapt(FoWColor, "FoWColor", 0u)); + } void C4SPlrStart::Default() - { + { NativeCrew=C4ID::None; - Crew.Set(1,0,1,10); - Wealth.Set(0,0,0,250); - Position[0]=Position[1]=-1; + Crew.Set(1,0,1,10); + Wealth.Set(0,0,0,250); + Position[0]=Position[1]=-1; EnforcePosition=0; ReadyCrew.Default(); - ReadyBase.Default(); - ReadyVehic.Default(); - ReadyMaterial.Default(); - BuildKnowledge.Default(); - HomeBaseMaterial.Default(); - HomeBaseProduction.Default(); + ReadyBase.Default(); + ReadyVehic.Default(); + ReadyMaterial.Default(); + BuildKnowledge.Default(); + HomeBaseMaterial.Default(); + HomeBaseProduction.Default(); Magic.Default(); - } + } bool C4SPlrStart::EquipmentEqual(C4SPlrStart &rhs) { @@ -248,44 +248,44 @@ bool C4SPlrStart::operator==(const C4SPlrStart& rhs) } void C4SPlrStart::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(NativeCrew, "StandardCrew", C4ID::None)); - pComp->Value(mkNamingAdapt(Crew, "Clonks", C4SVal(1, 0, 1, 10), true)); - pComp->Value(mkNamingAdapt(Wealth, "Wealth", C4SVal(0, 0, 0,250), true)); - pComp->Value(mkNamingAdapt(mkArrayAdaptDM(Position,-1), "Position" )); - pComp->Value(mkNamingAdapt(EnforcePosition, "EnforcePosition", 0)); - pComp->Value(mkNamingAdapt(ReadyCrew, "Crew", C4IDList())); - pComp->Value(mkNamingAdapt(ReadyBase, "Buildings", C4IDList())); - pComp->Value(mkNamingAdapt(ReadyVehic, "Vehicles", C4IDList())); - pComp->Value(mkNamingAdapt(ReadyMaterial, "Material", C4IDList())); - pComp->Value(mkNamingAdapt(BuildKnowledge, "Knowledge", C4IDList())); - pComp->Value(mkNamingAdapt(HomeBaseMaterial, "HomeBaseMaterial", C4IDList())); - pComp->Value(mkNamingAdapt(HomeBaseProduction, "HomeBaseProduction", C4IDList())); - pComp->Value(mkNamingAdapt(Magic, "Magic", C4IDList())); - } + { + pComp->Value(mkNamingAdapt(NativeCrew, "StandardCrew", C4ID::None)); + pComp->Value(mkNamingAdapt(Crew, "Clonks", C4SVal(1, 0, 1, 10), true)); + pComp->Value(mkNamingAdapt(Wealth, "Wealth", C4SVal(0, 0, 0,250), true)); + pComp->Value(mkNamingAdapt(mkArrayAdaptDM(Position,-1), "Position" )); + pComp->Value(mkNamingAdapt(EnforcePosition, "EnforcePosition", 0)); + pComp->Value(mkNamingAdapt(ReadyCrew, "Crew", C4IDList())); + pComp->Value(mkNamingAdapt(ReadyBase, "Buildings", C4IDList())); + pComp->Value(mkNamingAdapt(ReadyVehic, "Vehicles", C4IDList())); + pComp->Value(mkNamingAdapt(ReadyMaterial, "Material", C4IDList())); + pComp->Value(mkNamingAdapt(BuildKnowledge, "Knowledge", C4IDList())); + pComp->Value(mkNamingAdapt(HomeBaseMaterial, "HomeBaseMaterial", C4IDList())); + pComp->Value(mkNamingAdapt(HomeBaseProduction, "HomeBaseProduction", C4IDList())); + pComp->Value(mkNamingAdapt(Magic, "Magic", C4IDList())); + } void C4SLandscape::Default() - { - BottomOpen=0; TopOpen=1; - LeftOpen=0; RightOpen=0; - AutoScanSideOpen=1; - SkyDef[0]=0; + { + BottomOpen=0; TopOpen=1; + LeftOpen=0; RightOpen=0; + AutoScanSideOpen=1; + SkyDef[0]=0; NoSky=0; - for (int32_t cnt=0; cnt<6; cnt++) SkyDefFade[cnt]=0; - VegLevel.Set(50,30,0,100); - Vegetation.Default(); - InEarthLevel.Set(50,0,0,100); - InEarth.Default(); - MapWdt.Set(100,0,64,250); - MapHgt.Set(50,0,40,250); - MapZoom.Set(10,0,5,15); - Amplitude.Set(0,0); - Phase.Set(50); - Period.Set(15); - Random.Set(0); - LiquidLevel.Default(); - MapPlayerExtend=0; - Layers.Clear(); + for (int32_t cnt=0; cnt<6; cnt++) SkyDefFade[cnt]=0; + VegLevel.Set(50,30,0,100); + Vegetation.Default(); + InEarthLevel.Set(50,0,0,100); + InEarth.Default(); + MapWdt.Set(100,0,64,250); + MapHgt.Set(50,0,40,250); + MapZoom.Set(10,0,5,15); + Amplitude.Set(0,0); + Phase.Set(50); + Period.Set(15); + Random.Set(0); + LiquidLevel.Default(); + MapPlayerExtend=0; + Layers.Clear(); SCopy("Earth",Material,C4M_MaxName); SCopy("Water",Liquid,C4M_MaxName); ExactLandscape=0; @@ -307,109 +307,109 @@ void C4SLandscape::GetMapSize(int32_t &rWdt, int32_t &rHgt, int32_t iPlayerNum) } void C4SLandscape::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(ExactLandscape, "ExactLandscape", false)); - pComp->Value(mkNamingAdapt(Vegetation, "Vegetation", C4IDList())); - pComp->Value(mkNamingAdapt(VegLevel, "VegetationLevel", C4SVal(50,30,0,100), true)); - pComp->Value(mkNamingAdapt(InEarth, "InEarth", C4IDList())); - pComp->Value(mkNamingAdapt(InEarthLevel, "InEarthLevel", C4SVal(50,0,0,100), true)); - pComp->Value(mkNamingAdapt(mkStringAdaptMA(SkyDef), "Sky", "")); - pComp->Value(mkNamingAdapt(mkArrayAdaptDM(SkyDefFade,0),"SkyFade" )); - pComp->Value(mkNamingAdapt(NoSky, "NoSky", false)); - pComp->Value(mkNamingAdapt(BottomOpen, "BottomOpen", false)); - pComp->Value(mkNamingAdapt(TopOpen, "TopOpen", true)); - pComp->Value(mkNamingAdapt(LeftOpen, "LeftOpen", 0)); - pComp->Value(mkNamingAdapt(RightOpen, "RightOpen", 0)); - pComp->Value(mkNamingAdapt(AutoScanSideOpen, "AutoScanSideOpen", true)); - pComp->Value(mkNamingAdapt(MapWdt, "MapWidth", C4SVal(100,0,64,250), true)); - pComp->Value(mkNamingAdapt(MapHgt, "MapHeight", C4SVal(50,0,40,250), true)); + { + pComp->Value(mkNamingAdapt(ExactLandscape, "ExactLandscape", false)); + pComp->Value(mkNamingAdapt(Vegetation, "Vegetation", C4IDList())); + pComp->Value(mkNamingAdapt(VegLevel, "VegetationLevel", C4SVal(50,30,0,100), true)); + pComp->Value(mkNamingAdapt(InEarth, "InEarth", C4IDList())); + pComp->Value(mkNamingAdapt(InEarthLevel, "InEarthLevel", C4SVal(50,0,0,100), true)); + pComp->Value(mkNamingAdapt(mkStringAdaptMA(SkyDef), "Sky", "")); + pComp->Value(mkNamingAdapt(mkArrayAdaptDM(SkyDefFade,0),"SkyFade" )); + pComp->Value(mkNamingAdapt(NoSky, "NoSky", false)); + pComp->Value(mkNamingAdapt(BottomOpen, "BottomOpen", false)); + pComp->Value(mkNamingAdapt(TopOpen, "TopOpen", true)); + pComp->Value(mkNamingAdapt(LeftOpen, "LeftOpen", 0)); + pComp->Value(mkNamingAdapt(RightOpen, "RightOpen", 0)); + pComp->Value(mkNamingAdapt(AutoScanSideOpen, "AutoScanSideOpen", true)); + pComp->Value(mkNamingAdapt(MapWdt, "MapWidth", C4SVal(100,0,64,250), true)); + pComp->Value(mkNamingAdapt(MapHgt, "MapHeight", C4SVal(50,0,40,250), true)); pComp->Value(mkNamingAdapt(MapZoom, "MapZoom", C4SVal(10,0,5,15), true)); - pComp->Value(mkNamingAdapt(Amplitude, "Amplitude", C4SVal(0))); - pComp->Value(mkNamingAdapt(Phase, "Phase", C4SVal(50))); - pComp->Value(mkNamingAdapt(Period, "Period", C4SVal(15))); - pComp->Value(mkNamingAdapt(Random, "Random", C4SVal(0))); - pComp->Value(mkNamingAdapt(mkStringAdaptMA(Material),"Material", "Earth")); - pComp->Value(mkNamingAdapt(mkStringAdaptMA(Liquid), "Liquid", "Water")); - pComp->Value(mkNamingAdapt(LiquidLevel, "LiquidLevel", C4SVal())); - pComp->Value(mkNamingAdapt(MapPlayerExtend, "MapPlayerExtend", 0)); - pComp->Value(mkNamingAdapt(Layers, "Layers", C4NameList())); - pComp->Value(mkNamingAdapt(Gravity, "Gravity", C4SVal(100,0,10,200), true)); - pComp->Value(mkNamingAdapt(NoScan, "NoScan", false)); - pComp->Value(mkNamingAdapt(KeepMapCreator, "KeepMapCreator", false)); - pComp->Value(mkNamingAdapt(SkyScrollMode, "SkyScrollMode", 0)); - pComp->Value(mkNamingAdapt(NewStyleLandscape, "NewStyleLandscape", false)); + pComp->Value(mkNamingAdapt(Amplitude, "Amplitude", C4SVal(0))); + pComp->Value(mkNamingAdapt(Phase, "Phase", C4SVal(50))); + pComp->Value(mkNamingAdapt(Period, "Period", C4SVal(15))); + pComp->Value(mkNamingAdapt(Random, "Random", C4SVal(0))); + pComp->Value(mkNamingAdapt(mkStringAdaptMA(Material),"Material", "Earth")); + pComp->Value(mkNamingAdapt(mkStringAdaptMA(Liquid), "Liquid", "Water")); + pComp->Value(mkNamingAdapt(LiquidLevel, "LiquidLevel", C4SVal())); + pComp->Value(mkNamingAdapt(MapPlayerExtend, "MapPlayerExtend", 0)); + pComp->Value(mkNamingAdapt(Layers, "Layers", C4NameList())); + pComp->Value(mkNamingAdapt(Gravity, "Gravity", C4SVal(100,0,10,200), true)); + pComp->Value(mkNamingAdapt(NoScan, "NoScan", false)); + pComp->Value(mkNamingAdapt(KeepMapCreator, "KeepMapCreator", false)); + pComp->Value(mkNamingAdapt(SkyScrollMode, "SkyScrollMode", 0)); + pComp->Value(mkNamingAdapt(NewStyleLandscape, "NewStyleLandscape", false)); pComp->Value(mkNamingAdapt(FoWRes, "FoWRes", static_cast(CClrModAddMap::DefResolutionX))); - } + } void C4SWeather::Default() - { - Climate.Set(50,10); - StartSeason.Set(50,50); - YearSpeed.Set(50); - Rain.Default(); Wind.Set(0,70,-100,+100); + { + Climate.Set(50,10); + StartSeason.Set(50,50); + YearSpeed.Set(50); + Rain.Default(); Wind.Set(0,70,-100,+100); SCopy("Water",Precipitation,C4M_MaxName); NoGamma=1; - } + } void C4SWeather::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(Climate, "Climate", C4SVal(50,10), true)); - pComp->Value(mkNamingAdapt(StartSeason, "StartSeason", C4SVal(50,50), true)); - pComp->Value(mkNamingAdapt(YearSpeed, "YearSpeed", C4SVal(50))); - pComp->Value(mkNamingAdapt(Rain, "Rain", C4SVal())); - pComp->Value(mkNamingAdapt(Wind, "Wind", C4SVal(0,70,-100,+100), true)); - pComp->Value(mkNamingAdapt(mkStringAdaptMA(Precipitation),"Precipitation", "Water")); - pComp->Value(mkNamingAdapt(NoGamma, "NoGamma", true)); - } + { + pComp->Value(mkNamingAdapt(Climate, "Climate", C4SVal(50,10), true)); + pComp->Value(mkNamingAdapt(StartSeason, "StartSeason", C4SVal(50,50), true)); + pComp->Value(mkNamingAdapt(YearSpeed, "YearSpeed", C4SVal(50))); + pComp->Value(mkNamingAdapt(Rain, "Rain", C4SVal())); + pComp->Value(mkNamingAdapt(Wind, "Wind", C4SVal(0,70,-100,+100), true)); + pComp->Value(mkNamingAdapt(mkStringAdaptMA(Precipitation),"Precipitation", "Water")); + pComp->Value(mkNamingAdapt(NoGamma, "NoGamma", true)); + } void C4SAnimals::Default() - { - FreeLife.Clear(); - EarthNest.Clear(); - } + { + FreeLife.Clear(); + EarthNest.Clear(); + } void C4SAnimals::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(FreeLife, "Animal", C4IDList())); - pComp->Value(mkNamingAdapt(EarthNest, "Nest", C4IDList())); - } + { + pComp->Value(mkNamingAdapt(FreeLife, "Animal", C4IDList())); + pComp->Value(mkNamingAdapt(EarthNest, "Nest", C4IDList())); + } void C4SEnvironment::Default() - { - Objects.Clear(); - } + { + Objects.Clear(); + } void C4SEnvironment::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(Objects, "Objects", C4IDList())); - } + { + pComp->Value(mkNamingAdapt(Objects, "Objects", C4IDList())); + } void C4SRealism::Default() - { + { LandscapePushPull=0; LandscapeInsertThrust=0; ValueOverloads.Default(); - } + } bool C4Scenario::Compile(const char *szSource, bool fLoadSection) { if (!fLoadSection) Default(); - return CompileFromBuf_LogWarn(mkParAdapt(*this, fLoadSection), StdStrBuf(szSource), C4CFN_ScenarioCore); + return CompileFromBuf_LogWarn(mkParAdapt(*this, fLoadSection), StdStrBuf(szSource), C4CFN_ScenarioCore); } bool C4Scenario::Decompile(char **ppOutput, int32_t *ipSize, bool fSaveSection) { - try - { - // Decompile - StdStrBuf Buf = DecompileToBuf(mkParAdapt(*this, fSaveSection)); - // Return - *ppOutput = Buf.GrabPointer(); - *ipSize = Buf.getSize(); - } - catch(StdCompiler::Exception *) - { return false; } - return true; + try + { + // Decompile + StdStrBuf Buf = DecompileToBuf(mkParAdapt(*this, fSaveSection)); + // Return + *ppOutput = Buf.GrabPointer(); + *ipSize = Buf.getSize(); + } + catch(StdCompiler::Exception *) + { return false; } + return true; } void C4Scenario::Clear() @@ -522,13 +522,13 @@ bool C4SDefinitions::AssertModules(const char *szPath, char *sMissing) } void C4SDefinitions::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(LocalOnly, "LocalOnly", false)); + { + pComp->Value(mkNamingAdapt(LocalOnly, "LocalOnly", false)); pComp->Value(mkNamingAdapt(AllowUserChange, "AllowUserChange", false)); - for(int32_t i = 0; i < C4S_MaxDefinitions; i++) - pComp->Value(mkNamingAdapt(mkStringAdaptMA(Definition[i]), FormatString("Definition%i", i+1).getData(), "")); - pComp->Value(mkNamingAdapt(SkipDefs, "SkipDefs", C4IDList())); - } + for(int32_t i = 0; i < C4S_MaxDefinitions; i++) + pComp->Value(mkNamingAdapt(mkStringAdaptMA(Definition[i]), FormatString("Definition%i", i+1).getData(), "")); + pComp->Value(mkNamingAdapt(SkipDefs, "SkipDefs", C4IDList())); + } bool C4SGame::IsMelee() { diff --git a/src/game/landscape/C4Scenario.h b/src/game/landscape/C4Scenario.h index 6688dd419..4e6f06587 100644 --- a/src/game/landscape/C4Scenario.h +++ b/src/game/landscape/C4Scenario.h @@ -29,22 +29,22 @@ class C4Group; class C4SVal - { - public: - C4SVal(int32_t std=0, int32_t rnd=0, int32_t min=0, int32_t max=100); - public: - int32_t Std,Rnd,Min,Max; - public: + { + public: + C4SVal(int32_t std=0, int32_t rnd=0, int32_t min=0, int32_t max=100); + public: + int32_t Std,Rnd,Min,Max; + public: void Default(); - void Set(int32_t std=0, int32_t rnd=0, int32_t min=0, int32_t max=100); - int32_t Evaluate(); - void CompileFunc(StdCompiler *pComp); + void Set(int32_t std=0, int32_t rnd=0, int32_t min=0, int32_t max=100); + int32_t Evaluate(); + void CompileFunc(StdCompiler *pComp); public: inline bool operator==(const C4SVal &rhs) const { return rhs.Std == Std && rhs.Rnd == Rnd && rhs.Min == Min && rhs.Max == Max; } - }; + }; #define C4SGFXMODE_NEWGFX 1 #define C4SGFXMODE_OLDGFX 2 @@ -71,12 +71,12 @@ enum C4SFilmMode }; class C4SHead - { - public: + { + public: int32_t C4XVer[4]; - char Title[C4MaxTitle+1]; - char Loader[C4MaxTitle+1]; - char Font[C4MaxTitle+1]; // scenario specific font; may be 0 + char Title[C4MaxTitle+1]; + char Loader[C4MaxTitle+1]; + char Font[C4MaxTitle+1]; // scenario specific font; may be 0 int32_t Difficulty; int32_t Icon; int32_t NoInitialize; @@ -93,10 +93,10 @@ class C4SHead int32_t ForcedFairCrew; // 0: free; 1: force FairCrew; 2: force normal Crew (C4SForceFairCrew) int32_t FairCrewStrength; StdCopyStrBuf Origin; // original oath and filename to scenario (for records and savegames) - public: - void Default(); - void CompileFunc(StdCompiler *pComp, bool fSection); - }; + public: + void Default(); + void CompileFunc(StdCompiler *pComp, bool fSection); + }; const int32_t C4S_MaxDefinitions = 10; @@ -108,30 +108,30 @@ class C4SDefinitions int32_t AllowUserChange; char Definition[C4S_MaxDefinitions][_MAX_PATH+1]; C4IDList SkipDefs; - public: + public: void SetModules(const char *szList, const char *szRelativeToPath=NULL, const char *szRelativeToPath2=NULL); bool GetModules(StdStrBuf *psOutModules) const; bool AssertModules(const char *szPath=NULL, char *sMissing=NULL); - void Default(); - void CompileFunc(StdCompiler *pComp); + void Default(); + void CompileFunc(StdCompiler *pComp); }; class C4SRealism - { - public: + { + public: C4IDList ValueOverloads; int32_t LandscapePushPull; // Use new experimental push-pull-algorithms int32_t LandscapeInsertThrust; // Inserted material may thrust material of lower density aside - public: - void Default(); - }; + public: + void Default(); + }; class C4SGame - { - public: + { + public: C4IDList Goals; C4IDList Rules; @@ -139,10 +139,10 @@ class C4SGame C4SRealism Realism; - public: + public: bool IsMelee(); - void Default(); - void CompileFunc(StdCompiler *pComp, bool fSection); + void Default(); + void CompileFunc(StdCompiler *pComp, bool fSection); }; // Maximum map player extend factor @@ -150,120 +150,120 @@ class C4SGame const int32_t C4S_MaxMapPlayerExtend = 4; class C4SPlrStart - { - public: + { + public: C4ID NativeCrew; // Obsolete - C4SVal Crew; // Obsolete - C4SVal Wealth; - int32_t Position[2]; + C4SVal Crew; // Obsolete + C4SVal Wealth; + int32_t Position[2]; int32_t EnforcePosition; C4IDList ReadyCrew; - C4IDList ReadyBase; - C4IDList ReadyVehic; - C4IDList ReadyMaterial; - C4IDList BuildKnowledge; - C4IDList HomeBaseMaterial; - C4IDList HomeBaseProduction; + C4IDList ReadyBase; + C4IDList ReadyVehic; + C4IDList ReadyMaterial; + C4IDList BuildKnowledge; + C4IDList HomeBaseMaterial; + C4IDList HomeBaseProduction; C4IDList Magic; - public: - void Default(); + public: + void Default(); bool EquipmentEqual(C4SPlrStart &rhs); bool operator==(const C4SPlrStart& rhs); - void CompileFunc(StdCompiler *pComp); - }; + void CompileFunc(StdCompiler *pComp); + }; class C4SLandscape - { - public: + { + public: int32_t ExactLandscape; - C4SVal VegLevel; - C4IDList Vegetation; - C4SVal InEarthLevel; - C4IDList InEarth; - int32_t BottomOpen,TopOpen; - int32_t LeftOpen,RightOpen; - int32_t AutoScanSideOpen; - char SkyDef[C4MaxDefString+1]; - int32_t SkyDefFade[6]; + C4SVal VegLevel; + C4IDList Vegetation; + C4SVal InEarthLevel; + C4IDList InEarth; + int32_t BottomOpen,TopOpen; + int32_t LeftOpen,RightOpen; + int32_t AutoScanSideOpen; + char SkyDef[C4MaxDefString+1]; + int32_t SkyDefFade[6]; int32_t NoSky; int32_t NoScan; C4SVal Gravity; - // Dynamic map - C4SVal MapWdt,MapHgt,MapZoom; - C4SVal Amplitude,Phase,Period,Random; - C4SVal LiquidLevel; - int32_t MapPlayerExtend; - C4NameList Layers; + // Dynamic map + C4SVal MapWdt,MapHgt,MapZoom; + C4SVal Amplitude,Phase,Period,Random; + C4SVal LiquidLevel; + int32_t MapPlayerExtend; + C4NameList Layers; char Material[C4M_MaxDefName+1]; char Liquid[C4M_MaxDefName+1]; int32_t KeepMapCreator; // set if the mapcreator will be needed in the scenario (for DrawDefMap) int32_t SkyScrollMode; // sky scrolling mode for newgfx int32_t NewStyleLandscape; // if set to 2, the landscape uses up to 125 mat/texture pairs int32_t FoWRes; // chunk size of FoGOfWar - public: - void Default(); + public: + void Default(); void GetMapSize(int32_t &rWdt, int32_t &rHgt, int32_t iPlayerNum); - void CompileFunc(StdCompiler *pComp); - }; + void CompileFunc(StdCompiler *pComp); + }; class C4SWeather - { - public: - C4SVal Climate; - C4SVal StartSeason,YearSpeed; - C4SVal Rain,Wind; + { + public: + C4SVal Climate; + C4SVal StartSeason,YearSpeed; + C4SVal Rain,Wind; char Precipitation[C4M_MaxName+1]; int32_t NoGamma; - public: - void Default(); - void CompileFunc(StdCompiler *pComp); - }; + public: + void Default(); + void CompileFunc(StdCompiler *pComp); + }; class C4SAnimals - { - public: - C4IDList FreeLife; + { + public: + C4IDList FreeLife; C4IDList EarthNest; - public: - void Default(); - void CompileFunc(StdCompiler *pComp); - }; + public: + void Default(); + void CompileFunc(StdCompiler *pComp); + }; class C4SEnvironment - { - public: - C4IDList Objects; - public: - void Default(); - void CompileFunc(StdCompiler *pComp); - }; + { + public: + C4IDList Objects; + public: + void Default(); + void CompileFunc(StdCompiler *pComp); + }; class C4Scenario - { - public: - C4Scenario(); - public: - C4SHead Head; + { + public: + C4Scenario(); + public: + C4SHead Head; C4SDefinitions Definitions; - C4SGame Game; - C4SPlrStart PlrStart[C4S_MaxPlayer]; - C4SLandscape Landscape; - C4SAnimals Animals; - C4SWeather Weather; + C4SGame Game; + C4SPlrStart PlrStart[C4S_MaxPlayer]; + C4SLandscape Landscape; + C4SAnimals Animals; + C4SWeather Weather; C4SEnvironment Environment; - public: + public: void SetExactLandscape(); void Clear(); - void Default(); - bool Load(C4Group &hGroup, bool fLoadSection=false); + void Default(); + bool Load(C4Group &hGroup, bool fLoadSection=false); bool Save(C4Group &hGroup, bool fSaveSection=false); - void CompileFunc(StdCompiler *pComp, bool fSection); + void CompileFunc(StdCompiler *pComp, bool fSection); int32_t GetMinPlayer(); // will try to determine the minimum player count for this scenario protected: bool Compile(const char *szSource, bool fLoadSection=false); bool Decompile(char **ppOutput, int32_t *ipSize, bool fSaveSection=false); - }; + }; class C4ScenarioSection; diff --git a/src/game/landscape/C4Sky.cpp b/src/game/landscape/C4Sky.cpp index e13b21617..833c5fa60 100644 --- a/src/game/landscape/C4Sky.cpp +++ b/src/game/landscape/C4Sky.cpp @@ -60,21 +60,21 @@ static bool SurfaceEnsureSize(C4Surface **ppSfc, int iMinWdt, int iMinHgt) } void C4Sky::SetFadePalette(int32_t *ipColors) - { - // If colors all zero, use game palette default blue - if (ipColors[0]+ipColors[1]+ipColors[2]+ipColors[3]+ipColors[4]+ipColors[5]==0) - { + { + // If colors all zero, use game palette default blue + if (ipColors[0]+ipColors[1]+ipColors[2]+ipColors[3]+ipColors[4]+ipColors[5]==0) + { BYTE *pClr=::GraphicsResource.GamePalette+3*CSkyDef1; FadeClr1=C4RGB(pClr[0], pClr[1], pClr[2]); FadeClr2=C4RGB(pClr[3*19+0], pClr[3*19+1], pClr[3*19+2]); - } + } else { // set colors FadeClr1=C4RGB(ipColors[0], ipColors[1], ipColors[2]); FadeClr2=C4RGB(ipColors[3], ipColors[4], ipColors[5]); } - } + } bool C4Sky::Init(bool fSavegame) { @@ -165,8 +165,8 @@ bool C4Sky::Init(bool fSavegame) } // Success - return true; - } + return true; + } void C4Sky::Default() { @@ -261,7 +261,7 @@ bool C4Sky::SetModulation(DWORD dwWithClr, DWORD dwBackClr) } void C4Sky::CompileFunc(StdCompiler *pComp) - { + { pComp->Value(mkNamingAdapt(mkCastIntAdapt(x), "X", Fix0)); pComp->Value(mkNamingAdapt(mkCastIntAdapt(y), "Y", Fix0)); pComp->Value(mkNamingAdapt(mkCastIntAdapt(xdir),"XDir", Fix0)); @@ -272,4 +272,4 @@ void C4Sky::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(ParallaxMode, "ParMode", C4SkyPM_Fixed)); pComp->Value(mkNamingAdapt(BackClr, "BackClr", 0)); pComp->Value(mkNamingAdapt(BackClrEnabled, "BackClrEnabled", false)); - } + } diff --git a/src/game/landscape/C4SolidMask.cpp b/src/game/landscape/C4SolidMask.cpp index f2c814962..cd943457e 100644 --- a/src/game/landscape/C4SolidMask.cpp +++ b/src/game/landscape/C4SolidMask.cpp @@ -34,11 +34,11 @@ void C4SolidMask::Put(bool fCauseInstability, C4TargetRect *pClipRect, bool fRes // If not put, put mask to background, // storing background pixels in cSolidMask. - // No mask - if (!pSolidMask || !pSolidMaskMatBuff) { iAttachingObjectsCount = 0; return; } - // Contained - if (pForObject->Contained) { iAttachingObjectsCount = 0; return; } - // Mask is put + // No mask + if (!pSolidMask || !pSolidMaskMatBuff) { iAttachingObjectsCount = 0; return; } + // Contained + if (pForObject->Contained) { iAttachingObjectsCount = 0; return; } + // Mask is put if (fCauseInstability) CheckConsistency(); bool RegularPut; @@ -57,11 +57,11 @@ void C4SolidMask::Put(bool fCauseInstability, C4TargetRect *pClipRect, bool fRes if (!pClipRect->ClipBy(MaskPutRect)) return; RegularPut = false; } - // Lock mask surface - int iPitch = pForObject->SolidMask.Wdt; + // Lock mask surface + int iPitch = pForObject->SolidMask.Wdt; int xcnt,ycnt,iTx,iTy; // Put mask pixels - BYTE byPixel; + BYTE byPixel; // not rotated? if (!MaskPutRotation) { @@ -234,7 +234,7 @@ void C4SolidMask::Remove(bool fCauseInstability, bool fBackupAttachment) // If put, restore background pixels from buffer // Not put - if (!MaskPut || !pSolidMask || !pSolidMaskMatBuff) return; + if (!MaskPut || !pSolidMask || !pSolidMaskMatBuff) return; CheckConsistency(); diff --git a/src/game/landscape/C4Texture.cpp b/src/game/landscape/C4Texture.cpp index 12ff94203..c83c40bd4 100644 --- a/src/game/landscape/C4Texture.cpp +++ b/src/game/landscape/C4Texture.cpp @@ -36,16 +36,16 @@ #include C4Texture::C4Texture() - { - Name[0]=0; - Surface32=NULL; - Next=NULL; - } + { + Name[0]=0; + Surface32=NULL; + Next=NULL; + } C4Texture::~C4Texture() - { - delete Surface32; - } + { + delete Surface32; + } C4TexMapEntry::C4TexMapEntry() : iMaterialIndex(MNone), pMaterial(NULL) @@ -98,17 +98,17 @@ bool C4TexMapEntry::Init() } C4TextureMap::C4TextureMap() - { + { Default(); - } + } C4TextureMap::~C4TextureMap() - { - Clear(); - } + { + Clear(); + } bool C4TextureMap::AddEntry(BYTE byIndex, const char *szMaterial, const char *szTexture) - { + { // Security if(byIndex <= 0 || byIndex >= C4M_MaxTexIndex) return false; @@ -125,36 +125,36 @@ bool C4TextureMap::AddEntry(BYTE byIndex, const char *szMaterial, const char *sz // Landscape must be notified (new valid pixel clr) ::Landscape.HandleTexMapUpdate(); } - return true; - } + return true; + } bool C4TextureMap::AddTexture(const char *szTexture, CSurface * sfcSurface) - { - C4Texture *pTexture; - if (!(pTexture=new C4Texture)) return false; - SCopy(szTexture,pTexture->Name,C4M_MaxName); - pTexture->Surface32=sfcSurface; - pTexture->Next=FirstTexture; - FirstTexture=pTexture; - return true; - } + { + C4Texture *pTexture; + if (!(pTexture=new C4Texture)) return false; + SCopy(szTexture,pTexture->Name,C4M_MaxName); + pTexture->Surface32=sfcSurface; + pTexture->Next=FirstTexture; + FirstTexture=pTexture; + return true; + } void C4TextureMap::Clear() - { + { for(int32_t i = 1; i < C4M_MaxTexIndex; i++) Entry[i].Clear(); - C4Texture *ctex,*next2; - for (ctex=FirstTexture; ctex; ctex=next2) - { + C4Texture *ctex,*next2; + for (ctex=FirstTexture; ctex; ctex=next2) + { next2=ctex->Next; delete ctex; } - FirstTexture=NULL; + FirstTexture=NULL; fInitialized = false; - } + } bool C4TextureMap::LoadFlags(C4Group &hGroup, const char *szEntryName, bool *pOverloadMaterials, bool *pOverloadTextures) - { + { // Load the file StdStrBuf TexMap; if(!hGroup.LoadEntryString(szEntryName, TexMap)) @@ -175,20 +175,20 @@ bool C4TextureMap::LoadFlags(C4Group &hGroup, const char *szEntryName, bool *pOv } // Done return true; - } + } int32_t C4TextureMap::LoadMap(C4Group &hGroup, const char *szEntryName, bool *pOverloadMaterials, bool *pOverloadTextures) - { - char *bpMap; - char szLine[100+1]; - int32_t cnt, iIndex, iTextures = 0; - // Load text file into memory - if (!hGroup.LoadEntry(szEntryName,&bpMap,NULL,1)) return 0; - // Scan text buffer lines - for (cnt=0; SCopySegment(bpMap,cnt,szLine,0x0A,100); cnt++) - if ( (szLine[0]!='#') && (SCharCount('=',szLine)==1) ) - { - SReplaceChar(szLine,0x0D,0x00); + { + char *bpMap; + char szLine[100+1]; + int32_t cnt, iIndex, iTextures = 0; + // Load text file into memory + if (!hGroup.LoadEntry(szEntryName,&bpMap,NULL,1)) return 0; + // Scan text buffer lines + for (cnt=0; SCopySegment(bpMap,cnt,szLine,0x0A,100); cnt++) + if ( (szLine[0]!='#') && (SCharCount('=',szLine)==1) ) + { + SReplaceChar(szLine,0x0D,0x00); if (Inside( iIndex = strtol(szLine,NULL,10), 0, C4M_MaxTexIndex-1 )) { const char *szMapping = szLine+SCharPos('=',szLine)+1; @@ -197,17 +197,17 @@ int32_t C4TextureMap::LoadMap(C4Group &hGroup, const char *szEntryName, bool *pO if (AddEntry(iIndex, Material.getData(), Texture.getData())) iTextures++; } - } + } else { if (SEqual2(szLine, "OverloadMaterials")) { fOverloadMaterials = true; if(pOverloadMaterials) *pOverloadMaterials = true; } if (SEqual2(szLine, "OverloadTextures")) { fOverloadTextures = true; if(pOverloadTextures) *pOverloadTextures = true; } } - // Delete buffer, return entry count - delete [] bpMap; + // Delete buffer, return entry count + delete [] bpMap; fEntriesAdded=false; - return iTextures; - } + return iTextures; + } int32_t C4TextureMap::Init() { @@ -298,31 +298,31 @@ void C4TextureMap::MoveIndex(BYTE byOldIndex, BYTE byNewIndex) } int32_t C4TextureMap::GetIndex(const char *szMaterial, const char *szTexture, bool fAddIfNotExist, const char *szErrorIfFailed) - { - BYTE byIndex; - // Find existing + { + BYTE byIndex; + // Find existing for (byIndex = 1; byIndex < C4M_MaxTexIndex; byIndex++) if (!Entry[byIndex].isNull()) if (SEqualNoCase(Entry[byIndex].GetMaterialName(), szMaterial)) if (!szTexture || SEqualNoCase(Entry[byIndex].GetTextureName(), szTexture)) return byIndex; - // Add new entry - if (fAddIfNotExist) - for (byIndex=1; byIndexNext) - if (SEqualNoCase(pTexture->Name,szTexture)) - return pTexture; - return NULL; - } + { + C4Texture *pTexture; + for (pTexture=FirstTexture; pTexture; pTexture=pTexture->Next) + if (SEqualNoCase(pTexture->Name,szTexture)) + return pTexture; + return NULL; + } bool C4TextureMap::CheckTexture(const char *szTexture) - { - C4Texture *pTexture; - for (pTexture=FirstTexture; pTexture; pTexture=pTexture->Next) - if (SEqualNoCase(pTexture->Name,szTexture)) - return true; - return false; - } + { + C4Texture *pTexture; + for (pTexture=FirstTexture; pTexture; pTexture=pTexture->Next) + if (SEqualNoCase(pTexture->Name,szTexture)) + return true; + return false; + } const char* C4TextureMap::GetTexture(int32_t iIndex) { - C4Texture *pTexture; + C4Texture *pTexture; int32_t cindex; - for (pTexture=FirstTexture,cindex=0; pTexture; pTexture=pTexture->Next,cindex++) + for (pTexture=FirstTexture,cindex=0; pTexture; pTexture=pTexture->Next,cindex++) if (cindex==iIndex) return pTexture->Name; return NULL; @@ -379,7 +379,7 @@ const char* C4TextureMap::GetTexture(int32_t iIndex) void C4TextureMap::Default() { - FirstTexture=NULL; + FirstTexture=NULL; fEntriesAdded=false; fOverloadMaterials=false; fOverloadTextures=false; @@ -396,7 +396,7 @@ void C4TextureMap::StoreMapPalette(BYTE *bypPalette, C4MaterialMap &rMaterial) bypPalette[2]=252; // Material colors by texture map entries bool fSet[256]; - ZeroMem(&fSet, sizeof (fSet)); + ZeroMem(&fSet, sizeof (fSet)); int32_t i; for(i = 0; i < C4M_MaxTexIndex; i++) { @@ -410,24 +410,24 @@ void C4TextureMap::StoreMapPalette(BYTE *bypPalette, C4MaterialMap &rMaterial) bypPalette[3*(i+IFT)+2]=dwPix | 0x0F; // IFT arbitrarily gets more blue fSet[i] = fSet[i + IFT] = true; } - // Crosscheck colors, change equal palette entries - for(i = 0; i < 256; i++) if(fSet[i]) - for(;;) - { - // search equal entry + // Crosscheck colors, change equal palette entries + for(i = 0; i < 256; i++) if(fSet[i]) + for(;;) + { + // search equal entry int32_t j = 0; - for(; j < i; j++) if(fSet[j]) - if(bypPalette[3*i+0] == bypPalette[3*j+0] && - bypPalette[3*i+1] == bypPalette[3*j+1] && - bypPalette[3*i+2] == bypPalette[3*j+2]) - break; - // not found? ok then - if(j >= i) break; - // change randomly - if(rand() < RAND_MAX / 2) bypPalette[3*i+0] += 3; else bypPalette[3*i+0] -= 3; - if(rand() < RAND_MAX / 2) bypPalette[3*i+1] += 3; else bypPalette[3*i+1] -= 3; - if(rand() < RAND_MAX / 2) bypPalette[3*i+2] += 3; else bypPalette[3*i+2] -= 3; - } + for(; j < i; j++) if(fSet[j]) + if(bypPalette[3*i+0] == bypPalette[3*j+0] && + bypPalette[3*i+1] == bypPalette[3*j+1] && + bypPalette[3*i+2] == bypPalette[3*j+2]) + break; + // not found? ok then + if(j >= i) break; + // change randomly + if(rand() < RAND_MAX / 2) bypPalette[3*i+0] += 3; else bypPalette[3*i+0] -= 3; + if(rand() < RAND_MAX / 2) bypPalette[3*i+1] += 3; else bypPalette[3*i+1] -= 3; + if(rand() < RAND_MAX / 2) bypPalette[3*i+2] += 3; else bypPalette[3*i+2] -= 3; + } } C4TextureMap TextureMap; diff --git a/src/game/landscape/C4Texture.h b/src/game/landscape/C4Texture.h index 4087c3e3f..b4c20f212 100644 --- a/src/game/landscape/C4Texture.h +++ b/src/game/landscape/C4Texture.h @@ -28,24 +28,24 @@ #include class C4Texture - { - friend class C4TextureMap; - public: - C4Texture(); - ~C4Texture(); - CSurface * Surface32; - protected: - char Name[C4M_MaxName+1]; - C4Texture *Next; - }; + { + friend class C4TextureMap; + public: + C4Texture(); + ~C4Texture(); + CSurface * Surface32; + protected: + char Name[C4M_MaxName+1]; + C4Texture *Next; + }; class C4TexMapEntry - { - friend class C4TextureMap; + { + friend class C4TextureMap; public: C4TexMapEntry(); - private: - StdCopyStrBuf Material, Texture; + private: + StdCopyStrBuf Material, Texture; int32_t iMaterialIndex; C4Material *pMaterial; CPattern MatPattern; @@ -59,43 +59,43 @@ class C4TexMapEntry void Clear(); bool Create(const char *szMaterial, const char *szTexture); bool Init(); - }; + }; class C4TextureMap - { - public: - C4TextureMap(); - ~C4TextureMap(); - protected: - C4TexMapEntry Entry[C4M_MaxTexIndex]; - C4Texture *FirstTexture; + { + public: + C4TextureMap(); + ~C4TextureMap(); + protected: + C4TexMapEntry Entry[C4M_MaxTexIndex]; + C4Texture *FirstTexture; bool fOverloadMaterials; bool fOverloadTextures; bool fInitialized; // Set after Init() - newly added entries initialized automatically public: bool fEntriesAdded; - public: + public: const C4TexMapEntry *GetEntry(int32_t iIndex) const { return Inside(iIndex, 0, C4M_MaxTexIndex-1) ? &Entry[iIndex] : NULL; } - void RemoveEntry(int32_t iIndex) { if (Inside(iIndex, 1, C4M_MaxTexIndex-1)) Entry[iIndex].Clear(); } + void RemoveEntry(int32_t iIndex) { if (Inside(iIndex, 1, C4M_MaxTexIndex-1)) Entry[iIndex].Clear(); } void Default(); - void Clear(); + void Clear(); void StoreMapPalette(BYTE *bypPalette, C4MaterialMap &rMaterials); - static bool LoadFlags(C4Group &hGroup, const char *szEntryName, bool *pOverloadMaterials, bool *pOverloadTextures); - int32_t LoadMap(C4Group &hGroup, const char *szEntryName, bool *pOverloadMaterials, bool *pOverloadTextures); + static bool LoadFlags(C4Group &hGroup, const char *szEntryName, bool *pOverloadMaterials, bool *pOverloadTextures); + int32_t LoadMap(C4Group &hGroup, const char *szEntryName, bool *pOverloadMaterials, bool *pOverloadTextures); int32_t Init(); bool SaveMap(C4Group &hGroup, const char *szEntryName); - int32_t LoadTextures(C4Group &hGroup, C4Group* OverloadFile=0); + int32_t LoadTextures(C4Group &hGroup, C4Group* OverloadFile=0); bool HasTextures(C4Group &hGroup); const char *GetTexture(int32_t iIndex); void MoveIndex(BYTE byOldIndex, BYTE byNewIndex); // change index of texture - int32_t GetIndex(const char *szMaterial, const char *szTexture, bool fAddIfNotExist=true, const char *szErrorIfFailed=NULL); - int32_t GetIndexMatTex(const char *szMaterialTexture, const char *szDefaultTexture = NULL, bool fAddIfNotExist=true, const char *szErrorIfFailed=NULL); - C4Texture * GetTexture(const char *szTexture); + int32_t GetIndex(const char *szMaterial, const char *szTexture, bool fAddIfNotExist=true, const char *szErrorIfFailed=NULL); + int32_t GetIndexMatTex(const char *szMaterialTexture, const char *szDefaultTexture = NULL, bool fAddIfNotExist=true, const char *szErrorIfFailed=NULL); + C4Texture * GetTexture(const char *szTexture); bool CheckTexture(const char *szTexture); // return whether texture exists bool AddEntry(BYTE byIndex, const char *szMaterial, const char *szTexture); - protected: - bool AddTexture(const char *szTexture, CSurface * sfcSurface); - }; + protected: + bool AddTexture(const char *szTexture, CSurface * sfcSurface); + }; extern C4TextureMap TextureMap; diff --git a/src/game/landscape/C4Weather.cpp b/src/game/landscape/C4Weather.cpp index 68e15b3cd..b216e9078 100644 --- a/src/game/landscape/C4Weather.cpp +++ b/src/game/landscape/C4Weather.cpp @@ -30,9 +30,9 @@ #include C4Weather::C4Weather() - { + { Default(); - } + } C4Weather::~C4Weather() { @@ -40,67 +40,67 @@ C4Weather::~C4Weather() } void C4Weather::Init(bool fScenario) - { - if(fScenario) - { - // Season - Season=Game.C4S.Weather.StartSeason.Evaluate(); - YearSpeed=Game.C4S.Weather.YearSpeed.Evaluate(); - // Temperature - Climate=100-Game.C4S.Weather.Climate.Evaluate()-50; - Temperature=Climate; - // Wind - Wind=TargetWind=Game.C4S.Weather.Wind.Evaluate(); - // Precipitation + { + if(fScenario) + { + // Season + Season=Game.C4S.Weather.StartSeason.Evaluate(); + YearSpeed=Game.C4S.Weather.YearSpeed.Evaluate(); + // Temperature + Climate=100-Game.C4S.Weather.Climate.Evaluate()-50; + Temperature=Climate; + // Wind + Wind=TargetWind=Game.C4S.Weather.Wind.Evaluate(); + // Precipitation if (!Game.C4S.Head.NoInitialize) if (Game.C4S.Weather.Rain.Evaluate()) for (int32_t iClouds = Min(GBackWdt/500,5); iClouds>0; iClouds--) - { - volatile int iWidth = GBackWdt/15+Random(320); - volatile int iX = Random(GBackWdt); + { + volatile int iWidth = GBackWdt/15+Random(320); + volatile int iX = Random(GBackWdt); LaunchCloud(iX,-1,iWidth, Game.C4S.Weather.Rain.Evaluate(), Game.C4S.Weather.Precipitation); - } + } // gamma? NoGamma=Game.C4S.Weather.NoGamma; - } + } // set gamma SetSeasonGamma(); - } + } void C4Weather::Execute() - { - // Season - if (!::Game.iTick35) - { - SeasonDelay+=YearSpeed; - if (SeasonDelay>=200) - { - SeasonDelay=0; - Season++; - if (Season>Game.C4S.Weather.StartSeason.Max) - Season=Game.C4S.Weather.StartSeason.Min; - SetSeasonGamma(); - } - } - // Temperature - if (!::Game.iTick35) + { + // Season + if (!::Game.iTick35) { - int32_t iTemperature=Climate-(int32_t)(TemperatureRange*cos(6.28*(float)Season/100.0)); + SeasonDelay+=YearSpeed; + if (SeasonDelay>=200) + { + SeasonDelay=0; + Season++; + if (Season>Game.C4S.Weather.StartSeason.Max) + Season=Game.C4S.Weather.StartSeason.Min; + SetSeasonGamma(); + } + } + // Temperature + if (!::Game.iTick35) + { + int32_t iTemperature=Climate-(int32_t)(TemperatureRange*cos(6.28*(float)Season/100.0)); if (TemperatureiTemperature) Temperature--; } - // Wind - if (!::Game.iTick1000) - TargetWind=Game.C4S.Weather.Wind.Evaluate(); - if (!::Game.iTick10) - Wind=BoundBy(Wind+Sign(TargetWind-Wind), - Game.C4S.Weather.Wind.Min, - Game.C4S.Weather.Wind.Max); - if (!::Game.iTick10) - SoundLevel("Wind",NULL,Max(Abs(Wind)-30,0)*2); - } + // Wind + if (!::Game.iTick1000) + TargetWind=Game.C4S.Weather.Wind.Evaluate(); + if (!::Game.iTick10) + Wind=BoundBy(Wind+Sign(TargetWind-Wind), + Game.C4S.Weather.Wind.Min, + Game.C4S.Weather.Wind.Max); + if (!::Game.iTick10) + SoundLevel("Wind",NULL,Max(Abs(Wind)-30,0)*2); + } void C4Weather::Clear() { @@ -120,10 +120,10 @@ int32_t C4Weather::GetTemperature() void C4Weather::Default() { - Season=0; YearSpeed=0; SeasonDelay=0; - Wind=TargetWind=0; - Temperature=Climate=0; - TemperatureRange=30; + Season=0; YearSpeed=0; SeasonDelay=0; + Wind=TargetWind=0; + Temperature=Climate=0; + TemperatureRange=30; NoGamma=true; } @@ -211,7 +211,7 @@ void C4Weather::SetSeasonGamma() } void C4Weather::CompileFunc(StdCompiler *pComp) - { + { pComp->Value(mkNamingAdapt(Season, "Season", 0)); pComp->Value(mkNamingAdapt(YearSpeed, "YearSpeed", 0)); pComp->Value(mkNamingAdapt(SeasonDelay, "SeasonDelay", 0)); @@ -229,6 +229,6 @@ void C4Weather::CompileFunc(StdCompiler *pComp) dwGammaDefaults[i*3+2] = 0xffffff; } pComp->Value(mkNamingAdapt(mkArrayAdaptM(::GraphicsSystem.dwGamma), "Gamma", dwGammaDefaults)); - } + } C4Weather Weather; diff --git a/src/game/landscape/C4Weather.h b/src/game/landscape/C4Weather.h index f06725a86..3e65739df 100644 --- a/src/game/landscape/C4Weather.h +++ b/src/game/landscape/C4Weather.h @@ -24,23 +24,23 @@ #include class C4Weather - { - public: - C4Weather(); + { + public: + C4Weather(); ~C4Weather(); - public: - int32_t Season,YearSpeed,SeasonDelay; - int32_t Wind,TargetWind; - int32_t Temperature,TemperatureRange,Climate; + public: + int32_t Season,YearSpeed,SeasonDelay; + int32_t Wind,TargetWind; + int32_t Temperature,TemperatureRange,Climate; int32_t NoGamma; - public: + public: void Default(); void Clear(); - void Execute(); + void Execute(); void SetClimate(int32_t iClimate); void SetSeason(int32_t iSeason); void SetTemperature(int32_t iTemperature); - void Init(bool fScenario); + void Init(bool fScenario); void SetWind(int32_t iWind); int32_t GetWind(int32_t x, int32_t y); int32_t GetTemperature(); @@ -48,13 +48,13 @@ class C4Weather int32_t GetClimate(); bool LaunchCloud(int32_t iX, int32_t iY, int32_t iWidth, int32_t iStrength, const char *szPrecipitation); void SetSeasonGamma(); // set gamma adjustment for season - void CompileFunc(StdCompiler *pComp); - }; + void CompileFunc(StdCompiler *pComp); + }; extern C4Weather Weather; inline int32_t GBackWind(int32_t x, int32_t y) - { - return GBackIFT(x, y) ? 0: ::Weather.Wind; - } + { + return GBackIFT(x, y) ? 0: ::Weather.Wind; + } #endif diff --git a/src/game/object/C4Action.cpp b/src/game/object/C4Action.cpp index 74ec240a9..8d3314986 100644 --- a/src/game/object/C4Action.cpp +++ b/src/game/object/C4Action.cpp @@ -23,29 +23,29 @@ #include C4Action::C4Action() - { + { Default(); - } + } C4Action::~C4Action() - { + { - } + } void C4Action::Default() { //pActionDef = 0; - Dir=DIR_None; + Dir=DIR_None; DrawDir=Dir; - ComDir=COMD_None; - Time=0; - Data=0; - Target=Target2=NULL; - Phase=PhaseDelay=0; + ComDir=COMD_None; + Time=0; + Data=0; + Target=Target2=NULL; + Phase=PhaseDelay=0; Facet.Default(); - FacetX=FacetY=0; - t_attach=CNAT_None; - Animation = NULL; + FacetX=FacetY=0; + t_attach=CNAT_None; + Animation = NULL; } void C4Action::CompileFunc(StdCompiler *pComp) diff --git a/src/game/object/C4Command.cpp b/src/game/object/C4Command.cpp index 3160bcdd4..c1a520d7c 100644 --- a/src/game/object/C4Command.cpp +++ b/src/game/object/C4Command.cpp @@ -49,7 +49,7 @@ const int32_t LetGoHangleAngle=110; StdEnumAdapt::Entry EnumAdaptCommandEntries[C4CMD_Last - C4CMD_First + 2]; const char *CommandName(int32_t iCommand) - { + { static const char *szCommandName[] = { "None","Follow","MoveTo","Enter","Exit","Grab","Build","Throw","Chop", "UnGrab","Jump","Wait","Get","Put","Drop","Dig","Activate","PushTo", @@ -62,7 +62,7 @@ const char *CommandName(int32_t iCommand) } const char* CommandNameID(int32_t iCommand) - { + { static const char* dwCommandNameID[] = { "IDS_COMM_NONE","IDS_COMM_FOLLOW","IDS_COMM_MOVETO","IDS_COMM_ENTER", "IDS_COMM_EXIT","IDS_COMM_GRAB","IDS_COMM_BUILD","IDS_COMM_THROW","IDS_COMM_CHOP", @@ -78,15 +78,15 @@ const char* CommandNameID(int32_t iCommand) } bool InitEnumAdaptCommandEntries() - { - for(int32_t i = C4CMD_First; i <= C4CMD_Last; i++) - { - EnumAdaptCommandEntries[i - C4CMD_First].Name = CommandName(i); - EnumAdaptCommandEntries[i - C4CMD_First].Val = i; - } - EnumAdaptCommandEntries[C4CMD_Last - C4CMD_First + 1].Name = NULL; - return true; - } + { + for(int32_t i = C4CMD_First; i <= C4CMD_Last; i++) + { + EnumAdaptCommandEntries[i - C4CMD_First].Name = CommandName(i); + EnumAdaptCommandEntries[i - C4CMD_First].Val = i; + } + EnumAdaptCommandEntries[C4CMD_Last - C4CMD_First + 1].Name = NULL; + return true; + } const bool InitEnumAdaptCommandEntriesDummy = InitEnumAdaptCommandEntries(); int32_t CommandByName(const char *szCommand) @@ -163,32 +163,32 @@ int32_t SolidOnWhichSide(int32_t iX, int32_t iY) } C4Command::C4Command() - { + { Default(); - } + } C4Command::~C4Command() - { + { Clear(); - } + } void C4Command::Default() { - Command=C4CMD_None; + Command=C4CMD_None; cObj=NULL; - Evaluated=false; + Evaluated=false; PathChecked=false; Finished=false; Tx=C4VNull; Ty=0; - Target=Target2=NULL; + Target=Target2=NULL; Data.Set0(); - UpdateInterval=0; + UpdateInterval=0; Failures=0; Retries=0; Permit=0; Text=NULL; - Next=NULL; + Next=NULL; iExec=0; BaseMode=C4CMD_Mode_SilentSub; } @@ -201,7 +201,7 @@ static bool ObjectAddWaypoint(int32_t iX, int32_t iY, intptr_t iTransferTarget, if (iTransferTarget) return cObj->AddCommand(C4CMD_Transfer,(C4Object*)iTransferTarget,iX,iY,0,NULL,false); - // Solid offset + // Solid offset AdjustSolidOffset(iX,iY,cObj->Shape.Wdt/2,cObj->Shape.Hgt/2); // Standard movement waypoint update interval @@ -217,19 +217,19 @@ static bool ObjectAddWaypoint(int32_t iX, int32_t iY, intptr_t iTransferTarget, } void C4Command::MoveTo() - { + { // Determine move-to range int32_t iMoveToRange = MoveToRange; if (cObj->Def->MoveToRange > 0) iMoveToRange = cObj->Def->MoveToRange; // Current object position - int32_t cx,cy; cx=cObj->GetX(); cy=cObj->GetY(); + int32_t cx,cy; cx=cObj->GetX(); cy=cObj->GetY(); bool fWaypoint=false; if (Next && (Next->Command==C4CMD_MoveTo)) fWaypoint=true; - // Contained: exit - if (cObj->Contained) - { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } + // Contained: exit + if (cObj->Contained) + { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } // Check path (crew members or specific only) if ((cObj->OCF & OCF_CrewMember) || cObj->Def->Pathfinder) @@ -259,8 +259,8 @@ void C4Command::MoveTo() if (!::Game.iTick35) PathChecked=false; // Pushing grab only or not desired: let go (pulling, too?) - if (cObj->GetProcedure()==DFA_PUSH) - if (cObj->Action.Target) + if (cObj->GetProcedure()==DFA_PUSH) + if (cObj->Action.Target) if (cObj->Action.Target->Def->Grab == 2 || !(Data.getInt() & C4CMD_MoveTo_PushTarget)) { // Re-evaluate this command because vehicle control might have blocked evaluation @@ -299,85 +299,85 @@ void C4Command::MoveTo() { iRangeFactorTop=3; iRangeFactorSide=3; iRangeFactorBottom=2; } } - // Target reached (success) - if (Inside(cx-Tx._getInt(),-iRangeFactorSide*iTargetRange,+iRangeFactorSide*iTargetRange) + // Target reached (success) + if (Inside(cx-Tx._getInt(),-iRangeFactorSide*iTargetRange,+iRangeFactorSide*iTargetRange) && Inside(cy-Ty,-iRangeFactorBottom*iTargetRange,+iRangeFactorTop*iTargetRange)) - { + { cObj->Action.ComDir=COMD_Stop; Finish(true); return; - } + } - // Idles can't move to - if (!cObj->GetAction()) - { Finish(); return; } + // Idles can't move to + if (!cObj->GetAction()) + { Finish(); return; } - // Action - switch (cObj->GetProcedure()) - { + // Action + switch (cObj->GetProcedure()) + { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_WALK: - // Head to target - if (cxAction.ComDir=COMD_Right; - if (cx>Tx._getInt()+iTargetRange) cObj->Action.ComDir=COMD_Left; + case DFA_WALK: + // Head to target + if (cxAction.ComDir=COMD_Right; + if (cx>Tx._getInt()+iTargetRange) cObj->Action.ComDir=COMD_Left; // Flight control if (FlightControl()) return; // Jump control if (JumpControl()) return; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_PUSH: case DFA_PULL: - // Head to target - if (cxAction.ComDir=COMD_Right; - if (cx>Tx._getInt()+iTargetRange) cObj->Action.ComDir=COMD_Left; break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_SCALE: - // Head to target - if (cy>Ty+iTargetRange) cObj->Action.ComDir=COMD_Up; - if (cyAction.ComDir=COMD_Down; - // Let-Go Control - if (cObj->Action.Dir==DIR_Left) + case DFA_PUSH: case DFA_PULL: + // Head to target + if (cxAction.ComDir=COMD_Right; + if (cx>Tx._getInt()+iTargetRange) cObj->Action.ComDir=COMD_Left; + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_SCALE: + // Head to target + if (cy>Ty+iTargetRange) cObj->Action.ComDir=COMD_Up; + if (cyAction.ComDir=COMD_Down; + // Let-Go Control + if (cObj->Action.Dir==DIR_Left) { // Target direction - if ((Tx._getInt()>cx+LetGoRange1) && (Inside(cy-Ty,-LetGoRange2,+LetGoRange2))) - { ObjectComLetGo(cObj,+1); return; } + if ((Tx._getInt()>cx+LetGoRange1) && (Inside(cy-Ty,-LetGoRange2,+LetGoRange2))) + { ObjectComLetGo(cObj,+1); return; } // Contact (not if just started) if (cObj->Action.Time>2) if (cObj->t_contact/* & CNAT_Left*/) { ObjectComLetGo(cObj,+1); return; } } - if (cObj->Action.Dir==DIR_Right) + if (cObj->Action.Dir==DIR_Right) { // Target direction - if ((Tx._getInt()Action.Time>2) if (cObj->t_contact/* & CNAT_Right*/) { ObjectComLetGo(cObj,-1); return; } } - break; + break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_SWIM: - // Head to target - if (::Game.iTick2) - { if (cxAction.ComDir=COMD_Right; - if (cx>Tx._getInt()+iTargetRange) cObj->Action.ComDir=COMD_Left; } - else - { if (cyAction.ComDir=COMD_Down; - if (cy>Ty) cObj->Action.ComDir=COMD_Up; } - break; + case DFA_SWIM: + // Head to target + if (::Game.iTick2) + { if (cxAction.ComDir=COMD_Right; + if (cx>Tx._getInt()+iTargetRange) cObj->Action.ComDir=COMD_Left; } + else + { if (cyAction.ComDir=COMD_Down; + if (cy>Ty) cObj->Action.ComDir=COMD_Up; } + break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_HANGLE: - // Head to target - if (cxAction.ComDir=COMD_Right; - if (cx>Tx._getInt()+iTargetRange) cObj->Action.ComDir=COMD_Left; - // Let-Go Control + case DFA_HANGLE: + // Head to target + if (cxAction.ComDir=COMD_Right; + if (cx>Tx._getInt()+iTargetRange) cObj->Action.ComDir=COMD_Left; + // Let-Go Control if (Abs(Angle(cx,cy,Tx._getInt(),Ty))>LetGoHangleAngle) ObjectComLetGo(cObj,0); - break; + break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_FLOAT: + case DFA_FLOAT: { FIXED dx = itofix(Tx._getInt()) - cObj->fix_x, dy = itofix(Ty) - cObj->fix_y; // normalize @@ -396,36 +396,36 @@ void C4Command::MoveTo() else if(dx > 0 && dy < 0) cObj->Action.ComDir = COMD_UpRight; else cObj->Action.ComDir = COMD_UpLeft; } - break; + break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_FLIGHT: + case DFA_FLIGHT: // Flight control if (FlightControl()) return; - break; + break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } + } - } + } void C4Command::Dig() - { + { // Current object and target coordinates - int32_t cx,cy,tx,ty; - cx=cObj->GetX(); cy=cObj->GetY(); - tx=Tx._getInt(); ty=Ty+cObj->Shape.GetY() + 3; // Target coordinates are bottom center + int32_t cx,cy,tx,ty; + cx=cObj->GetX(); cy=cObj->GetY(); + tx=Tx._getInt(); ty=Ty+cObj->Shape.GetY() + 3; // Target coordinates are bottom center bool fDigOutMaterial=Data.getBool(); - // Grabbing: let go - if (cObj->GetProcedure()==DFA_PUSH) - { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } + // Grabbing: let go + if (cObj->GetProcedure()==DFA_PUSH) + { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } - // If contained: exit - if (cObj->Contained) - { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } + // If contained: exit + if (cObj->Contained) + { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } - // Building or chopping: stop - if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) - ObjectComStop(cObj); + // Building or chopping: stop + if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) + ObjectComStop(cObj); // Scaling or hangling: let go if ((cObj->GetProcedure()==DFA_SCALE) || (cObj->GetProcedure()==DFA_HANGLE)) @@ -435,13 +435,13 @@ void C4Command::Dig() int32_t iMoveToRange = MoveToRange; if (cObj->Def->MoveToRange > 0) iMoveToRange = cObj->Def->MoveToRange; - // Target reached: success - if (Inside(cx - tx, -iMoveToRange, +iMoveToRange) - && Inside(cy - ty, -iMoveToRange, +iMoveToRange)) - { + // Target reached: success + if (Inside(cx - tx, -iMoveToRange, +iMoveToRange) + && Inside(cy - ty, -iMoveToRange, +iMoveToRange)) + { ObjectComStop(cObj); - Finish(true); return; - } + Finish(true); return; + } // Can start digging only from walk if (cObj->GetProcedure()!=DFA_DIG) @@ -457,10 +457,10 @@ void C4Command::Dig() // Dig2Object if (fDigOutMaterial) cObj->Action.Data=1; - // Head to target - if (cxAction.ComDir=COMD_Right; - if (cx>tx+DigRange) cObj->Action.ComDir=COMD_Left; - if (cyAction.ComDir=COMD_Down; + // Head to target + if (cxAction.ComDir=COMD_Right; + if (cx>tx+DigRange) cObj->Action.ComDir=COMD_Left; + if (cyAction.ComDir=COMD_Down; if (cxAction.ComDir=COMD_DownRight; if (cx>tx-DigRange) if (cyAction.ComDir=COMD_DownLeft; if (cxty+DigRange) cObj->Action.ComDir=COMD_UpRight; @@ -470,42 +470,42 @@ void C4Command::Dig() void C4Command::Follow() - { + { - // If crew member, only selected objects can follow + // If crew member, only selected objects can follow if (cObj->Def->CrewMember) // Finish successfully to avoid fail message if (!cObj->Select && cObj->Owner != NO_OWNER) { Finish(true); return; } - // No-one to follow - if (!Target) { Finish(); return; } + // No-one to follow + if (!Target) { Finish(); return; } - // Follow containment - if (cObj->Contained!=Target->Contained) - { - // Only crew members can follow containment + // Follow containment + if (cObj->Contained!=Target->Contained) + { + // Only crew members can follow containment if (!cObj->Def->CrewMember) { Finish(); return; } // Exit/enter - if (cObj->Contained) cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); - else cObj->AddCommand(C4CMD_Enter,Target->Contained,0,0,50); - return; - } + if (cObj->Contained) cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); + else cObj->AddCommand(C4CMD_Enter,Target->Contained,0,0,50); + return; + } - // Follow target grabbing - if (Target->GetProcedure()==DFA_PUSH) - { - // Grabbing same: copy ComDir - if (cObj->GetProcedure()==DFA_PUSH) - if (cObj->Action.Target==Target->Action.Target) - { - cObj->Action.ComDir=Target->Action.ComDir; - return; - } - // Else, grab target's grab - cObj->AddCommand(C4CMD_Grab,Target->Action.Target); - return; - } + // Follow target grabbing + if (Target->GetProcedure()==DFA_PUSH) + { + // Grabbing same: copy ComDir + if (cObj->GetProcedure()==DFA_PUSH) + if (cObj->Action.Target==Target->Action.Target) + { + cObj->Action.ComDir=Target->Action.ComDir; + return; + } + // Else, grab target's grab + cObj->AddCommand(C4CMD_Grab,Target->Action.Target); + return; + } else if (cObj->GetProcedure()==DFA_PUSH) { // Follow ungrabbing @@ -513,108 +513,108 @@ void C4Command::Follow() return; } - // If in following range - if (Inside(cObj->GetX()-Target->GetX(),-FollowRange,+FollowRange) - && Inside(cObj->GetY()-Target->GetY(),-FollowRange,+FollowRange)) - { - // Copy target's Action.ComDir - cObj->Action.ComDir=Target->Action.ComDir; - } - else // Else, move to target - { - cObj->AddCommand(C4CMD_MoveTo,NULL,Target->GetX(),Target->GetY(),10); - } + // If in following range + if (Inside(cObj->GetX()-Target->GetX(),-FollowRange,+FollowRange) + && Inside(cObj->GetY()-Target->GetY(),-FollowRange,+FollowRange)) + { + // Copy target's Action.ComDir + cObj->Action.ComDir=Target->Action.ComDir; + } + else // Else, move to target + { + cObj->AddCommand(C4CMD_MoveTo,NULL,Target->GetX(),Target->GetY(),10); + } - } + } void C4Command::Enter() - { - DWORD ocf; + { + DWORD ocf; - // No object to enter or can't enter by def - if (!Target || cObj->Def->NoPushEnter) { Finish(); return; } + // No object to enter or can't enter by def + if (!Target || cObj->Def->NoPushEnter) { Finish(); return; } - // Already in target object - if (cObj->Contained==Target) { Finish(true); return; } + // Already in target object + if (cObj->Contained==Target) { Finish(true); return; } - // Building or chopping: stop - if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) - ObjectComStop(cObj); + // Building or chopping: stop + if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) + ObjectComStop(cObj); // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); // Pushing grab only or pushing not desired: let go - if (cObj->GetProcedure()==DFA_PUSH) - if (cObj->Action.Target) + if (cObj->GetProcedure()==DFA_PUSH) + if (cObj->Action.Target) if (cObj->Action.Target->Def->Grab == 2 || !(Data.getInt() & C4CMD_Enter_PushTarget)) { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } // Pushing target: let go - if (cObj->GetProcedure()==DFA_PUSH) - if (cObj->Action.Target==Target) + if (cObj->GetProcedure()==DFA_PUSH) + if (cObj->Action.Target==Target) { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } - // Grabbing overrides position for target - int32_t cx,cy; - cx=cObj->GetX(); cy=cObj->GetY(); - if (cObj->GetProcedure()==DFA_PUSH) - if (cObj->Action.Target) - { cx=cObj->Action.Target->GetX(); cy=cObj->Action.Target->GetY(); } + // Grabbing overrides position for target + int32_t cx,cy; + cx=cObj->GetX(); cy=cObj->GetY(); + if (cObj->GetProcedure()==DFA_PUSH) + if (cObj->Action.Target) + { cx=cObj->Action.Target->GetX(); cy=cObj->Action.Target->GetY(); } - // If in entrance range - ocf=OCF_Entrance; - if (!cObj->Contained && Target->At(cx,cy,ocf) && (ocf & OCF_Entrance)) - { + // If in entrance range + ocf=OCF_Entrance; + if (!cObj->Contained && Target->At(cx,cy,ocf) && (ocf & OCF_Entrance)) + { // Stop - cObj->Action.ComDir=COMD_Stop; - // Pushing: push target into entrance, then stop - if ((cObj->GetProcedure()==DFA_PUSH) && cObj->Action.Target) - { - cObj->Action.Target->SetCommand(C4CMD_Enter,Target); - Finish(true); return; - } - // Else, enter self - else - { - // If entrance open, enter object - if (Target->EntranceStatus!=0) - { - cObj->Enter(Target); - Finish(true); return; - } - else // Else, activate entrance - Target->ActivateEntrance(cObj->Controller,cObj); - } + cObj->Action.ComDir=COMD_Stop; + // Pushing: push target into entrance, then stop + if ((cObj->GetProcedure()==DFA_PUSH) && cObj->Action.Target) + { + cObj->Action.Target->SetCommand(C4CMD_Enter,Target); + Finish(true); return; + } + // Else, enter self + else + { + // If entrance open, enter object + if (Target->EntranceStatus!=0) + { + cObj->Enter(Target); + Finish(true); return; + } + else // Else, activate entrance + Target->ActivateEntrance(cObj->Controller,cObj); + } - } - else // Else, move to object's entrance - { - int32_t ex,ey,ewdt,ehgt; - if (Target->GetEntranceArea(ex,ey,ewdt,ehgt)) + } + else // Else, move to object's entrance + { + int32_t ex,ey,ewdt,ehgt; + if (Target->GetEntranceArea(ex,ey,ewdt,ehgt)) cObj->AddCommand(C4CMD_MoveTo,NULL,ex+ewdt/2,ey+ehgt/2,50, NULL, true, C4VInt((Data.getInt() & C4CMD_Enter_PushTarget) ? C4CMD_MoveTo_PushTarget : 0)); - } + } - } + } void C4Command::Exit() - { + { - // Outside: done - if (!cObj->Contained) { Finish(true); return; } + // Outside: done + if (!cObj->Contained) { Finish(true); return; } - // Building: stop - if (cObj->GetProcedure()==DFA_BUILD) - ObjectComStop(cObj); + // Building: stop + if (cObj->GetProcedure()==DFA_BUILD) + ObjectComStop(cObj); - // Entrance open, leave object - if (cObj->Contained->EntranceStatus) - { + // Entrance open, leave object + if (cObj->Contained->EntranceStatus) + { // Exit to container's container if (cObj->Contained->Contained) { cObj->Enter(cObj->Contained->Contained); Finish(true); return; } // Exit to entrance area - int32_t ex,ey,ewdt,ehgt; + int32_t ex,ey,ewdt,ehgt; if (cObj->Contained->OCF & OCF_Entrance) if (cObj->Contained->GetEntranceArea(ex,ey,ewdt,ehgt)) { cObj->Exit(ex+ewdt/2,ey+ehgt+cObj->Shape.GetY()-1); Finish(true); return; } @@ -627,63 +627,63 @@ void C4Command::Exit() Finish(true); return; } // Plain exit - cObj->Exit(cObj->GetX(),cObj->GetY()); + cObj->Exit(cObj->GetX(),cObj->GetY()); Finish(true); return; - } + } // Entrance closed, activate entrance - else - { - if (!cObj->Contained->ActivateEntrance(cObj->Controller,cObj)) + else + { + if (!cObj->Contained->ActivateEntrance(cObj->Controller,cObj)) // Entrance activation failed: fail - { Finish(); return; } - } - } + { Finish(); return; } + } + } void C4Command::Grab() - { - DWORD ocf; - // Command fulfilled - if (cObj->GetProcedure()==DFA_PUSH) - if (cObj->Action.Target==Target) - { Finish(true); return; } - // Building or chopping: stop - if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) - ObjectComStop(cObj); + { + DWORD ocf; + // Command fulfilled + if (cObj->GetProcedure()==DFA_PUSH) + if (cObj->Action.Target==Target) + { Finish(true); return; } + // Building or chopping: stop + if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) + ObjectComStop(cObj); // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); - // Grabbing: let go - if (cObj->GetProcedure()==DFA_PUSH) - { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } - // No target - if (!Target) { Finish(); return; } - // At target object: grab - ocf=OCF_All; - if (!cObj->Contained && Target->At(cObj->GetX(),cObj->GetY(),ocf)) - { + // Grabbing: let go + if (cObj->GetProcedure()==DFA_PUSH) + { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } + // No target + if (!Target) { Finish(); return; } + // At target object: grab + ocf=OCF_All; + if (!cObj->Contained && Target->At(cObj->GetX(),cObj->GetY(),ocf)) + { // Scaling or hangling: let go if ((cObj->GetProcedure()==DFA_SCALE) || (cObj->GetProcedure()==DFA_HANGLE)) ObjectComLetGo(cObj,(cObj->Action.Dir==DIR_Left) ? +1 : -1); // Grab - cObj->Action.ComDir=COMD_Stop; - ObjectComGrab(cObj,Target); - } - // Else, move to object + cObj->Action.ComDir=COMD_Stop; + ObjectComGrab(cObj,Target); + } + // Else, move to object else - { - cObj->AddCommand(C4CMD_MoveTo,NULL,Target->GetX()+Tx._getInt(),Target->GetY()+Ty,50); - } - } + { + cObj->AddCommand(C4CMD_MoveTo,NULL,Target->GetX()+Tx._getInt(),Target->GetY()+Ty,50); + } + } void C4Command::PushTo() - { + { // Target check if (!Target) { Finish(); return; } // Target is target self: fail if (Target==Target2) { Finish(); return; } - // Command fulfilled + // Command fulfilled if (Target2) { // Object in correct target container: success @@ -703,9 +703,9 @@ void C4Command::PushTo() } } - // Building or chopping: stop - if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) - ObjectComStop(cObj); + // Building or chopping: stop + if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) + ObjectComStop(cObj); // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); @@ -727,47 +727,47 @@ void C4Command::PushTo() } void C4Command::Chop() - { - DWORD ocf; - // No target: fail - if (!Target) { Finish(); return; } - // Can not chop: fail - if (!cObj->GetPhysical()->CanChop) - { Finish(); return; } - // Target not chopable: done (assume was successfully chopped) + { + DWORD ocf; + // No target: fail + if (!Target) { Finish(); return; } + // Can not chop: fail + if (!cObj->GetPhysical()->CanChop) + { Finish(); return; } + // Target not chopable: done (assume was successfully chopped) if (!(Target->OCF & OCF_Chop)) - { Finish(true); return; } - // Chopping target: wait - if ((cObj->GetProcedure()==DFA_CHOP) && (cObj->Action.Target==Target)) - return; - // Grabbing: let go - if (cObj->GetProcedure()==DFA_PUSH) - { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } + { Finish(true); return; } + // Chopping target: wait + if ((cObj->GetProcedure()==DFA_CHOP) && (cObj->Action.Target==Target)) + return; + // Grabbing: let go + if (cObj->GetProcedure()==DFA_PUSH) + { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } // Building, digging or chopping other: stop if ((cObj->GetProcedure()==DFA_DIG) || (cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD)) { ObjectComStop(cObj); return; } - // At target object, in correct shopping position - ocf=OCF_All; - if (!cObj->Contained && Target->At(cObj->GetX(),cObj->GetY(),ocf) && Inside(Abs(cObj->GetX() - Target->GetX()), 4, 9)) - { - cObj->Action.ComDir=COMD_Stop; - ObjectComChop(cObj,Target); - } - // Else, move to object + // At target object, in correct shopping position + ocf=OCF_All; + if (!cObj->Contained && Target->At(cObj->GetX(),cObj->GetY(),ocf) && Inside(Abs(cObj->GetX() - Target->GetX()), 4, 9)) + { + cObj->Action.ComDir=COMD_Stop; + ObjectComChop(cObj,Target); + } + // Else, move to object else - { - cObj->AddCommand(C4CMD_MoveTo, NULL, (cObj->GetX() > Target->GetX()) ? Target->GetX()+6 : Target->GetX()-6, Target->GetY(), 50); + { + cObj->AddCommand(C4CMD_MoveTo, NULL, (cObj->GetX() > Target->GetX()) ? Target->GetX()+6 : Target->GetX()-6, Target->GetY(), 50); // Too close? Move away first. if (Abs(cObj->GetX() - Target->GetX()) < 5) cObj->AddCommand(C4CMD_MoveTo, NULL, (cObj->GetX() > Target->GetX()) ? Target->GetX()+15 : Target->GetX()-15, Target->GetY(), 50); - } - } + } + } void C4Command::Build() - { - DWORD ocf; - // No target: cancel - if (!Target) + { + DWORD ocf; + // No target: cancel + if (!Target) { Finish(); return; } // Lost the ability to build? Fail. if (cObj->GetPhysical() && !cObj->GetPhysical()->CanConstruct) @@ -775,8 +775,8 @@ void C4Command::Build() Finish(false, FormatString(LoadResStr("IDS_TEXT_CANTBUILD"), cObj->GetName()).getData()); return; } - // Target complete: Command fulfilled - if (Target->GetCon()>=FullCon) + // Target complete: Command fulfilled + if (Target->GetCon()>=FullCon) { // Activate internal vehicles if (Target->Contained && (Target->Category & C4D_Vehicle)) @@ -801,51 +801,51 @@ void C4Command::Build() cObj->Action.ComDir=COMD_Stop; Finish(true); return; } - // Currently working on target: continue - if (cObj->GetProcedure()==DFA_BUILD) - if (cObj->Action.Target==Target) - return; - // Grabbing: let go - if (cObj->GetProcedure()==DFA_PUSH) - { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } + // Currently working on target: continue + if (cObj->GetProcedure()==DFA_BUILD) + if (cObj->Action.Target==Target) + return; + // Grabbing: let go + if (cObj->GetProcedure()==DFA_PUSH) + { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); - // Worker ist structure or static back: internal target build only (old stuff) - if ((cObj->Category & C4D_Structure) || (cObj->Category & C4D_StaticBack)) - { - // Target is internal - if (Target->Contained==cObj) - { ObjectComBuild(cObj,Target); return; } - // Target is not internal: cancel - Finish(); return; - } - // At target check - ocf=OCF_All; - if ( (Target->Contained && (cObj->Contained==Target->Contained)) + // Worker ist structure or static back: internal target build only (old stuff) + if ((cObj->Category & C4D_Structure) || (cObj->Category & C4D_StaticBack)) + { + // Target is internal + if (Target->Contained==cObj) + { ObjectComBuild(cObj,Target); return; } + // Target is not internal: cancel + Finish(); return; + } + // At target check + ocf=OCF_All; + if ( (Target->Contained && (cObj->Contained==Target->Contained)) || (Target->At(cObj->GetX(),cObj->GetY(),ocf) && (cObj->GetProcedure()==DFA_WALK)) ) - { - ObjectComStop(cObj); - ObjectComBuild(cObj,Target); - return; - } - // Else, move to object - else - { + { + ObjectComStop(cObj); + ObjectComBuild(cObj,Target); + return; + } + // Else, move to object + else + { if (Target->Contained) cObj->AddCommand(C4CMD_Enter,Target->Contained,0,0,50); - else cObj->AddCommand(C4CMD_MoveTo,NULL,Target->GetX(),Target->GetY(),50); - return; - } - } + else cObj->AddCommand(C4CMD_MoveTo,NULL,Target->GetX(),Target->GetY(),50); + return; + } + } void C4Command::UnGrab() - { - ObjectComUnGrab(cObj); - cObj->Action.ComDir=COMD_Stop; - Finish(true); - } + { + ObjectComUnGrab(cObj); + cObj->Action.ComDir=COMD_Stop; + Finish(true); + } void C4Command::Throw() - { + { // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); @@ -898,25 +898,25 @@ void C4Command::Throw() return; } - // Contained: put or take - if (cObj->Contained) - { - ObjectComPutTake(cObj,cObj->Contained,Target); - Finish(true); return; - } + // Contained: put or take + if (cObj->Contained) + { + ObjectComPutTake(cObj,cObj->Contained,Target); + Finish(true); return; + } - // Pushing: put or take - if (cObj->GetProcedure()==DFA_PUSH) - { - if (cObj->Action.Target) - ObjectComPutTake(cObj,cObj->Action.Target,Target); - Finish(true); return; - } + // Pushing: put or take + if (cObj->GetProcedure()==DFA_PUSH) + { + if (cObj->Action.Target) + ObjectComPutTake(cObj,cObj->Action.Target,Target); + Finish(true); return; + } - // Outside: Throw - ObjectComThrow(cObj,Target); - Finish(true); - } + // Outside: Throw + ObjectComThrow(cObj,Target); + Finish(true); + } void C4Command::Take() { @@ -931,7 +931,7 @@ void C4Command::Take2() } void C4Command::Drop() - { + { // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); @@ -967,28 +967,28 @@ void C4Command::Drop() return; } - // Contained: put - if (cObj->Contained) - { - ObjectComPutTake(cObj,cObj->Contained,Target); - Finish(true); return; - } + // Contained: put + if (cObj->Contained) + { + ObjectComPutTake(cObj,cObj->Contained,Target); + Finish(true); return; + } - // Pushing: put - if (cObj->GetProcedure()==DFA_PUSH) - { - if (cObj->Action.Target) - ObjectComPutTake(cObj,cObj->Action.Target,Target); - Finish(true); return; - } + // Pushing: put + if (cObj->GetProcedure()==DFA_PUSH) + { + if (cObj->Action.Target) + ObjectComPutTake(cObj,cObj->Action.Target,Target); + Finish(true); return; + } - // Outside: Drop - ObjectComDrop(cObj,Target); - Finish(true); - } + // Outside: Drop + ObjectComDrop(cObj,Target); + Finish(true); + } void C4Command::Jump() - { + { // Tx not default 0: adjust jump direction if (Tx._getInt()) { @@ -996,19 +996,19 @@ void C4Command::Jump() if (Tx._getInt()>cObj->GetX()) cObj->SetDir(DIR_Right); } // Jump - ObjectComJump(cObj); + ObjectComJump(cObj); // Done - Finish(true); - } + Finish(true); + } void C4Command::Wait() - { + { // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); - } + } void C4Command::Context() - { + { // Not context object specified (in Target2): fail if (!Target2) { Finish(); return; } // Open context menu for target @@ -1055,7 +1055,7 @@ bool C4Command::GetTryEnter() } void C4Command::Get() - { + { // Data set and target specified: open get menu & done (old style) if (((Data.getInt()==1) || (Data.getInt()==2)) && Target) @@ -1070,7 +1070,7 @@ void C4Command::Get() { Finish(); return; } // No target: failure - if (!Target) { Finish(); return; } + if (!Target) { Finish(); return; } // Target not carryable: failure if (!(Target->OCF & OCF_Carryable)) @@ -1087,8 +1087,8 @@ void C4Command::Get() { cObj->Action.ComDir=COMD_Stop; Finish(true); return; } } - // Grabbing other than target container: let go - if (cObj->GetProcedure()==DFA_PUSH) + // Grabbing other than target container: let go + if (cObj->GetProcedure()==DFA_PUSH) if (cObj->Action.Target!=Target->Contained) { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } @@ -1118,9 +1118,9 @@ void C4Command::Get() // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); - // Target contained - if (Target->Contained) - { + // Target contained + if (Target->Contained) + { // target can't be taken out of containers? if(Target->Def->NoGet) return; // In same container: grab target @@ -1132,7 +1132,7 @@ void C4Command::Get() } // Leave own container - if (cObj->Contained) + if (cObj->Contained) { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } // Target container has grab get: grab target container @@ -1157,16 +1157,16 @@ void C4Command::Get() // Can't get to target due to target container: fail Finish(); return; - } + } // Target outside // Leave own container - if (cObj->Contained) { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } + if (cObj->Contained) { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } // Outside if (!cObj->Contained) - { + { // Target in collection range DWORD ocf = OCF_Normal | OCF_Collection; @@ -1201,9 +1201,9 @@ void C4Command::Get() cObj->AddCommand(C4CMD_MoveTo,NULL,Target->GetX()+Random(15)-7,Target->GetY(),25,NULL); } - } + } - } + } bool C4Command::CheckMinimumCon (C4Object *pObj) { @@ -1219,7 +1219,7 @@ bool C4Command::CheckMinimumCon (C4Object *pObj) } void C4Command::Activate() - { + { // Container specified, but no Target & no type: open activate menu for container if (Target2 && !Target && !Data) @@ -1240,7 +1240,7 @@ void C4Command::Activate() Target2=Target->Contained; // No container specified: fail - if (!Target2) { Finish(); return; } + if (!Target2) { Finish(); return; } // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); @@ -1277,7 +1277,7 @@ void C4Command::Activate() } // Leave own container - if (cObj->Contained) + if (cObj->Contained) { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } // Target container has entrance: enter @@ -1287,13 +1287,13 @@ void C4Command::Activate() // Can't get to target due to target container: fail Finish(); - } + } void C4Command::Put() // Notice: Put command is currently using Ty as an internal reminder flag for letting go after putting... - { - // No target container: failure - if (!Target) { Finish(); return; } + { + // No target container: failure + if (!Target) { Finish(); return; } // Thing to put specified by type if (!Target2 && Data) @@ -1339,9 +1339,9 @@ void C4Command::Put() // Notice: Put command is currently using Ty as an interna // Digging: stop if (cObj->GetProcedure()==DFA_DIG) ObjectComStop(cObj); - // Grabbing other than target: let go + // Grabbing other than target: let go C4Object *pGrabbing=NULL; - if (cObj->GetProcedure()==DFA_PUSH) + if (cObj->GetProcedure()==DFA_PUSH) pGrabbing = cObj->Action.Target; if (pGrabbing && (pGrabbing!=Target)) { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } @@ -1356,7 +1356,7 @@ void C4Command::Put() // Notice: Put command is currently using Ty as an interna } // Leave own container - if (cObj->Contained) + if (cObj->Contained) { cObj->AddCommand(C4CMD_Exit,NULL,0,0,50); return; } // Target has collection: throw in if not fragile, not grabbing target and throwing position found @@ -1403,7 +1403,7 @@ void C4Command::Put() // Notice: Put command is currently using Ty as an interna if (Target->OCF & OCF_Entrance) { cObj->AddCommand(C4CMD_Enter,Target,0,0,50); return; } - } + } void C4Command::ClearPointers(C4Object *pObj) { @@ -1432,24 +1432,24 @@ void C4Command::Execute() { Finish(); return; } } - // Command update - if (UpdateInterval>0) - { - UpdateInterval--; - if (UpdateInterval==0) { + // Command update + if (UpdateInterval>0) + { + UpdateInterval--; + if (UpdateInterval==0) { Finish(true); return; } - } + } - // Initial command evaluation + // Initial command evaluation if (InitEvaluation()) return; // from now on, we are executing this command... and nobody // should dare deleting us iExec = 1; - // Execute - switch (Command) - { + // Execute + switch (Command) + { case C4CMD_Follow: Follow(); break; case C4CMD_MoveTo: MoveTo(); break; case C4CMD_Enter: Enter(); break; @@ -1480,8 +1480,8 @@ void C4Command::Execute() case C4CMD_Call: Call(); break; case C4CMD_Take: Take(); break; // carlo case C4CMD_Take2: Take2(); break; // carlo - default: Finish(); break; - } + default: Finish(); break; + } /* // Remember this command might have already been deleted through calls // made during execution. You must not do anything here... */ @@ -1517,12 +1517,12 @@ bool C4Command::InitEvaluation() // Already evaluated if (Evaluated) return false; // Set evaluation flag - Evaluated=true; + Evaluated=true; // Evaluate - switch (Command) - { + switch (Command) + { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case C4CMD_MoveTo: + case C4CMD_MoveTo: { // Target coordinates by Target if (Target) { Tx+=Target->GetX(); Ty+=Target->GetY(); Target=NULL; } @@ -1560,21 +1560,21 @@ bool C4Command::InitEvaluation() if (!Ty) Ty=250; return true; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } + } // Need not be evaluated - return false; + return false; } void C4Command::Clear() { - Command=C4CMD_None; + Command=C4CMD_None; cObj=NULL; - Evaluated=false; + Evaluated=false; PathChecked=false; Tx=C4VNull; Ty=0; - Target=Target2=NULL; - UpdateInterval=0; + Target=Target2=NULL; + UpdateInterval=0; if (Text) Text->DecRef(); Text=NULL; BaseMode=C4CMD_Mode_SilentSub; } @@ -1588,7 +1588,7 @@ void C4Command::Construct() return; } // No target type to construct: open menu & done - if (!Data) + if (!Data) { cObj->ActivateMenu(C4MN_Construction); Finish(true); return; @@ -1623,20 +1623,20 @@ void C4Command::Construct() return; } - // No valid target type: fail + // No valid target type: fail C4Def *pDef; if (!(pDef=C4Id2Def(Data.getC4ID()))) { Finish(); return; } // player has knowledge of this construction? C4Player *pPlayer = ::Players.Get(cObj->Owner); if(pPlayer) if(!pPlayer->Knowledge.GetIDCount(Data.getC4ID(), 1)) { Finish(); return; } - // Building, chopping, digging: stop - if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD) || (cObj->GetProcedure()==DFA_DIG)) - ObjectComStop(cObj); + // Building, chopping, digging: stop + if ((cObj->GetProcedure()==DFA_CHOP) || (cObj->GetProcedure()==DFA_BUILD) || (cObj->GetProcedure()==DFA_DIG)) + ObjectComStop(cObj); // Pushing: let go - if (cObj->GetProcedure()==DFA_PUSH) - if (cObj->Action.Target) + if (cObj->GetProcedure()==DFA_PUSH) + if (cObj->Action.Target) { cObj->AddCommand(C4CMD_UnGrab,NULL,0,0,50); return; } // No construction site specified: find one @@ -1654,7 +1654,7 @@ void C4Command::Construct() int32_t scriptresult = cObj->Call(PSF_ControlCommandConstruction, &C4AulParSet(C4VObj(Target), Tx, C4VInt(Ty), C4VObj(Target2), Data)).getInt (); // script call might have deleted object if (!cObj->Status) return; - if (1 == scriptresult) return; + if (1 == scriptresult) return; if (2 == scriptresult) { Finish(true); return; } if (3 == scriptresult) @@ -1801,8 +1801,8 @@ bool C4Command::JumpControl() // Called by DFA_WALK void C4Command::Transfer() { - // No target: failure - if (!Target) { Finish(); return; } + // No target: failure + if (!Target) { Finish(); return; } // Find transfer zone C4TransferZone *pZone; @@ -1835,8 +1835,8 @@ void C4Command::Transfer() void C4Command::Attack() { - // No target: failure - if (!Target) { Finish(); return; } + // No target: failure + if (!Target) { Finish(); return; } // Target is crew member if (Target->OCF & OCF_CrewMember) @@ -1903,7 +1903,7 @@ void C4Command::Acquire() // script call might have deleted object if (!cObj->Status) return; - if (1 == scriptresult) return; + if (1 == scriptresult) return; if (2 == scriptresult) { Finish(true); return; } if (3 == scriptresult) @@ -2220,7 +2220,7 @@ void C4Command::CompileFunc(StdCompiler *pComp) else { Text = Strings.RegString(TextBuf); Text->IncRef(); } } - } + } void C4Command::DenumeratePointers() { diff --git a/src/game/object/C4Command.h b/src/game/object/C4Command.h index c2ddfbe19..31fc95205 100644 --- a/src/game/object/C4Command.h +++ b/src/game/object/C4Command.h @@ -62,13 +62,13 @@ const int32_t C4CMD_First = C4CMD_Follow, C4CMD_Last = C4CMD_Take2; // carlo const int32_t C4CMD_Mode_SilentSub = 0, // subcommand; failure will cause base to fail (no message in case of failure) - C4CMD_Mode_Base = 1, // regular base command - C4CMD_Mode_SilentBase = 2, // silent base command (no message in case of failure) - C4CMD_Mode_Sub = 3; // subcommand; failure will cause base to fail + C4CMD_Mode_Base = 1, // regular base command + C4CMD_Mode_SilentBase = 2, // silent base command (no message in case of failure) + C4CMD_Mode_Sub = 3; // subcommand; failure will cause base to fail // MoveTo and Enter command options: Include push target const int32_t C4CMD_MoveTo_NoPosAdjust = 1, - C4CMD_MoveTo_PushTarget = 2; + C4CMD_MoveTo_PushTarget = 2; const int32_t C4CMD_Enter_PushTarget = 2; @@ -77,25 +77,25 @@ const char* CommandNameID(int32_t iCommand); int32_t CommandByName(const char *szCommand); class C4Command - { - public: - C4Command(); - ~C4Command(); - public: + { + public: + C4Command(); + ~C4Command(); + public: C4Object *cObj; - int32_t Command; + int32_t Command; C4Value Tx; int32_t Ty; - C4Object *Target,*Target2; + C4Object *Target,*Target2; C4Value Data; - int32_t UpdateInterval; - int32_t Evaluated,PathChecked,Finished; + int32_t UpdateInterval; + int32_t Evaluated,PathChecked,Finished; int32_t Failures,Retries,Permit; C4String *Text; - C4Command *Next; + C4Command *Next; int32_t iExec; // 0 = not executing, 1 = executing, 2 = executing, command should delete himself on finish int32_t BaseMode; // 0: subcommand/unmarked base (if failing, base will fail, too); 1: base command; 2: silent base command - public: + public: void Set(int32_t iCommand, C4Object *pObj, C4Object *pTarget, C4Value iTx, int32_t iTy, C4Object *pTarget2, C4Value iData, int32_t iUpdateInterval, bool fEvaluated, int32_t iRetries, C4String *szText, int32_t iBaseMode); void Clear(); void Execute(); @@ -103,8 +103,8 @@ class C4Command void Default(); void EnumeratePointers(); void DenumeratePointers(); - void CompileFunc(StdCompiler *pComp); - protected: + void CompileFunc(StdCompiler *pComp); + protected: void Call(); void Home(); void Retry(); @@ -117,33 +117,33 @@ class C4Command void Transfer(); void Construct(); void Finish(bool fSuccess=false, const char *szFailMessage=0); - void Follow(); - void MoveTo(); - void Enter(); - void Exit(); - void Grab(); - void UnGrab(); - void Throw(); - void Chop(); - void Build(); - void Jump(); - void Wait(); + void Follow(); + void MoveTo(); + void Enter(); + void Exit(); + void Grab(); + void UnGrab(); + void Throw(); + void Chop(); + void Build(); + void Jump(); + void Wait(); void Take(); void Take2(); bool GetTryEnter(); // at object pos during get-command: Try entering it - void Get(); - void Put(); - void Drop(); - void Dig(); - void Activate(); - void PushTo(); - void Context(); + void Get(); + void Put(); + void Drop(); + void Dig(); + void Activate(); + void PushTo(); + void Context(); int32_t CallFailed(); bool JumpControl(); bool FlightControl(); bool InitEvaluation(); int32_t GetExpGain(); // get control counts gained by this command; 1EXP=5 ControlCounts bool CheckMinimumCon (C4Object *pObj); - }; + }; #endif diff --git a/src/game/object/C4Def.cpp b/src/game/object/C4Def.cpp index f5cf3f538..5317efe48 100644 --- a/src/game/object/C4Def.cpp +++ b/src/game/object/C4Def.cpp @@ -68,19 +68,19 @@ const char *ProcedureName[C4D_MaxDFA]={ "WALK", //--------------------------------- C4DefCore ---------------------------------------------- void C4Def::DefaultDefCore() - { + { rC4XVer[0]=rC4XVer[1]=rC4XVer[2]=rC4XVer[3]=0; RequireDef.Clear(); Physical.Default(); - Shape.Default(); - Entrance.Default(); - Collection.Default(); - PictureRect.Default(); - SolidMask.Default(); - TopFace.Default(); - Component.Default(); - BurnTurnTo=C4ID::None; - BuildTurnTo=C4ID::None; + Shape.Default(); + Entrance.Default(); + Collection.Default(); + PictureRect.Default(); + SolidMask.Default(); + TopFace.Default(); + Component.Default(); + BurnTurnTo=C4ID::None; + BuildTurnTo=C4ID::None; STimerCall[0]=0; Timer=35; GrowthType=0; @@ -409,8 +409,8 @@ C4Def::C4Def() void C4Def::Default() { DefaultDefCore(); - Next=NULL; - Temporary=false; + Next=NULL; + Temporary=false; Maker[0]=0; Filename[0]=0; Creation=0; @@ -427,7 +427,7 @@ void C4Def::Default() PortraitCount = 0; Portraits = NULL; pFairCrewPhysical = NULL; - } + } C4Def::~C4Def() { @@ -435,7 +435,7 @@ C4Def::~C4Def() } void C4Def::Clear() - { + { Graphics.Clear(); @@ -455,10 +455,10 @@ void C4Def::Clear() } bool C4Def::Load(C4Group &hGroup, - DWORD dwLoadWhat, + DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem) - { + { bool fSuccess=true; bool AddFileMonitoring = false; @@ -493,7 +493,7 @@ bool C4Def::Load(C4Group &hGroup, } - // Read DefCore + // Read DefCore if (fSuccess) fSuccess=LoadDefCore(hGroup); // skip def: don't even read sounds! @@ -526,8 +526,8 @@ bool C4Def::Load(C4Group &hGroup, return false; } - // Read script - if (dwLoadWhat & C4D_Load_Script) + // Read script + if (dwLoadWhat & C4D_Load_Script) { // reg script to engine Script.Reg2List(&::ScriptEngine, &::ScriptEngine); @@ -608,8 +608,8 @@ bool C4Def::Load(C4Group &hGroup, } - // Read desc - if (dwLoadWhat & C4D_Load_Desc) + // Read desc + if (dwLoadWhat & C4D_Load_Desc) { Desc.LoadEx("Desc", hGroup, C4CFN_DefDesc, szLanguage); Desc.TrimSpaces(); @@ -621,7 +621,7 @@ bool C4Def::Load(C4Group &hGroup, if (pSoundSystem) pSoundSystem->LoadEffects(hGroup); - // Bitmap post-load settings + // Bitmap post-load settings if (Graphics.GetBitmap()) { // check SolidMask @@ -751,11 +751,11 @@ C4PhysicalInfo *C4Def::GetFairCrewPhysicals() } void C4Def::ClearFairCrewPhysicals() - { - // invalidate physicals so the next call to GetFairCrewPhysicals will - // reacreate them - delete pFairCrewPhysical; pFairCrewPhysical = NULL; - } + { + // invalidate physicals so the next call to GetFairCrewPhysicals will + // reacreate them + delete pFairCrewPhysical; pFairCrewPhysical = NULL; + } void C4Def::Synchronize() { @@ -768,24 +768,24 @@ void C4Def::Synchronize() //--------------------------------- C4DefList ---------------------------------------------- C4DefList::C4DefList() - { + { Default(); - } + } C4DefList::~C4DefList() - { - Clear(); - } + { + Clear(); + } int32_t C4DefList::Load(C4Group &hGroup, DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem, bool fOverload, bool fSearchMessage, int32_t iMinProgress, int32_t iMaxProgress, bool fLoadSysGroups) - { + { int32_t iResult=0; - C4Def *nDef; - char szEntryname[_MAX_FNAME+1]; + C4Def *nDef; + char szEntryname[_MAX_FNAME+1]; C4Group hChild; bool fPrimaryDef=false; bool fThisSearchMessage=false; @@ -852,8 +852,8 @@ int32_t C4DefList::Load(C4Group &hGroup, DWORD dwLoadWhat, // progress (could go down one level of recursion...) if (iMinProgress != iMaxProgress) Game.SetInitProgress(float(iMaxProgress)); - return iResult; - } + return iResult; + } int32_t C4DefList::LoadFolderLocal( const char *szPath, DWORD dwLoadWhat, const char *szLanguage, @@ -887,11 +887,11 @@ int32_t C4DefList::LoadFolderLocal( const char *szPath, extern bool C4EngineLoadProcess(const char *szMessage, int32_t iProcess); int32_t C4DefList::Load(const char *szSearch, - DWORD dwLoadWhat, const char *szLanguage, + DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem, bool fOverload, int32_t iMinProgress, int32_t iMaxProgress) - { - int32_t iResult=0; + { + int32_t iResult=0; // Empty if (!szSearch[0]) return iResult; @@ -956,14 +956,14 @@ int32_t C4DefList::Load(const char *szSearch, // progress (could go down one level of recursion...) if (iMinProgress != iMaxProgress) Game.SetInitProgress(float(iMaxProgress)); - return iResult; - } + return iResult; + } bool C4DefList::Add(C4Def *pDef, bool fOverload) - { - if (!pDef) return false; + { + if (!pDef) return false; - // Check old def to overload + // Check old def to overload C4Def *pLastDef = ID2Def(pDef->id); if (pLastDef && !fOverload) return false; @@ -979,42 +979,42 @@ bool C4DefList::Add(C4Def *pDef, bool fOverload) } } - // Remove old def + // Remove old def Remove(pDef->id); // Add new def - pDef->Next=FirstDef; - FirstDef=pDef; + pDef->Next=FirstDef; + FirstDef=pDef; return true; - } + } bool C4DefList::Remove(C4ID id) - { - C4Def *cdef,*prev; - for (cdef=FirstDef,prev=NULL; cdef; prev=cdef,cdef=cdef->Next) - if (cdef->id==id) - { - if (prev) prev->Next=cdef->Next; - else FirstDef=cdef->Next; - delete cdef; - return true; - } - return false; - } + { + C4Def *cdef,*prev; + for (cdef=FirstDef,prev=NULL; cdef; prev=cdef,cdef=cdef->Next) + if (cdef->id==id) + { + if (prev) prev->Next=cdef->Next; + else FirstDef=cdef->Next; + delete cdef; + return true; + } + return false; + } void C4DefList::Remove(C4Def *def) - { - C4Def *cdef,*prev; - for (cdef=FirstDef,prev=NULL; cdef; prev=cdef,cdef=cdef->Next) - if (cdef==def) - { - if (prev) prev->Next=cdef->Next; - else FirstDef=cdef->Next; - delete cdef; - return; - } - } + { + C4Def *cdef,*prev; + for (cdef=FirstDef,prev=NULL; cdef; prev=cdef,cdef=cdef->Next) + if (cdef==def) + { + if (prev) prev->Next=cdef->Next; + else FirstDef=cdef->Next; + delete cdef; + return; + } + } void C4DefList::Clear() { @@ -1050,92 +1050,92 @@ C4Def* C4DefList::ID2Def(C4ID id) } int32_t C4DefList::GetIndex(C4ID id) - { - C4Def *cdef; - int32_t cindex; - for (cdef=FirstDef,cindex=0; cdef; cdef=cdef->Next,cindex++) - if (cdef->id==id) return cindex; - return -1; - } + { + C4Def *cdef; + int32_t cindex; + for (cdef=FirstDef,cindex=0; cdef; cdef=cdef->Next,cindex++) + if (cdef->id==id) return cindex; + return -1; + } int32_t C4DefList::GetDefCount(DWORD dwCategory) { - C4Def *cdef; int32_t ccount=0; - for (cdef=FirstDef; cdef; cdef=cdef->Next) - if (cdef->Category & dwCategory) - ccount++; - return ccount; + C4Def *cdef; int32_t ccount=0; + for (cdef=FirstDef; cdef; cdef=cdef->Next) + if (cdef->Category & dwCategory) + ccount++; + return ccount; } C4Def* C4DefList::GetDef(int32_t iIndex, DWORD dwCategory) - { - C4Def *pDef; int32_t iCurrentIndex; - if (iIndex<0) return NULL; - for (pDef=FirstDef,iCurrentIndex=-1; pDef; pDef=pDef->Next) - if (pDef->Category & dwCategory) - { - iCurrentIndex++; - if (iCurrentIndex==iIndex) return pDef; - } - return NULL; - } + { + C4Def *pDef; int32_t iCurrentIndex; + if (iIndex<0) return NULL; + for (pDef=FirstDef,iCurrentIndex=-1; pDef; pDef=pDef->Next) + if (pDef->Category & dwCategory) + { + iCurrentIndex++; + if (iCurrentIndex==iIndex) return pDef; + } + return NULL; + } C4Def *C4DefList::GetByPath(const char *szPath) - { - // search defs - const char *szDefPath; - for(C4Def *pDef = FirstDef; pDef; pDef = pDef->Next) - if((szDefPath = Config.AtRelativePath(pDef->Filename))) - if(SEqual2NoCase(szPath, szDefPath)) - { - // the definition itself? - if(!szPath[SLen(szDefPath)]) - return pDef; - // or a component? - else if(szPath[SLen(szDefPath)] == '\\') - if(!strchr(szPath + SLen(szDefPath) + 1, '\\')) - return pDef; - } - // not found - return NULL; - } + { + // search defs + const char *szDefPath; + for(C4Def *pDef = FirstDef; pDef; pDef = pDef->Next) + if((szDefPath = Config.AtRelativePath(pDef->Filename))) + if(SEqual2NoCase(szPath, szDefPath)) + { + // the definition itself? + if(!szPath[SLen(szDefPath)]) + return pDef; + // or a component? + else if(szPath[SLen(szDefPath)] == '\\') + if(!strchr(szPath + SLen(szDefPath) + 1, '\\')) + return pDef; + } + // not found + return NULL; + } int32_t C4DefList::RemoveTemporary() - { - C4Def *cdef,*prev,*next; - int32_t removed=0; - for (cdef=FirstDef,prev=NULL; cdef; cdef=next) - { - next=cdef->Next; - if (cdef->Temporary) - { - if (prev) prev->Next=next; - else FirstDef=next; - delete cdef; - removed++; - } - else - prev=cdef; - } + { + C4Def *cdef,*prev,*next; + int32_t removed=0; + for (cdef=FirstDef,prev=NULL; cdef; cdef=next) + { + next=cdef->Next; + if (cdef->Temporary) + { + if (prev) prev->Next=next; + else FirstDef=next; + delete cdef; + removed++; + } + else + prev=cdef; + } // rebuild quick access table BuildTable(); - return removed; - } + return removed; + } int32_t C4DefList::CheckEngineVersion(int32_t ver1, int32_t ver2, int32_t ver3, int32_t ver4) { int32_t rcount=0; - C4Def *cdef,*prev,*next; - for (cdef=FirstDef,prev=NULL; cdef; cdef=next) + C4Def *cdef,*prev,*next; + for (cdef=FirstDef,prev=NULL; cdef; cdef=next) { next=cdef->Next; - if (CompareVersion(cdef->rC4XVer[0],cdef->rC4XVer[1],cdef->rC4XVer[2],cdef->rC4XVer[3],ver1,ver2,ver3,ver4) > 0) - { - if (prev) prev->Next=cdef->Next; - else FirstDef=cdef->Next; - delete cdef; + if (CompareVersion(cdef->rC4XVer[0],cdef->rC4XVer[1],cdef->rC4XVer[2],cdef->rC4XVer[3],ver1,ver2,ver3,ver4) > 0) + { + if (prev) prev->Next=cdef->Next; + else FirstDef=cdef->Next; + delete cdef; rcount++; - } + } else prev=cdef; } return rcount; @@ -1144,7 +1144,7 @@ int32_t C4DefList::CheckEngineVersion(int32_t ver1, int32_t ver2, int32_t ver3, int32_t C4DefList::CheckRequireDef() { int32_t rcount=0, rcount2; - C4Def *cdef,*prev,*next; + C4Def *cdef,*prev,*next; do { rcount2 = rcount; diff --git a/src/game/object/C4Def.h b/src/game/object/C4Def.h index 367ca2c05..78a6c9f46 100644 --- a/src/game/object/C4Def.h +++ b/src/game/object/C4Def.h @@ -139,47 +139,47 @@ const DWORD C4D_Load_None = 0, #define C4D_Blit_ModAdd 2 class C4Def: public C4PropList - { - public: - C4ID id; + { + public: + C4ID id; int32_t rC4XVer[4]; C4IDList RequireDef; C4PhysicalInfo Physical; - C4Shape Shape; - C4Rect Entrance; - C4Rect Collection; - C4Rect PictureRect; - C4TargetRect SolidMask; - C4TargetRect TopFace; - C4IDList Component; - C4ID BurnTurnTo; - C4ID BuildTurnTo; - int32_t GrowthType; - int32_t CrewMember; + C4Shape Shape; + C4Rect Entrance; + C4Rect Collection; + C4Rect PictureRect; + C4TargetRect SolidMask; + C4TargetRect TopFace; + C4IDList Component; + C4ID BurnTurnTo; + C4ID BuildTurnTo; + int32_t GrowthType; + int32_t CrewMember; int32_t NativeCrew; - int32_t Mass; - int32_t Value; - int32_t Exclusive; - int32_t Category; - int32_t Growth; - int32_t Rebuyable; - int32_t ContactIncinerate; // 0 off 1 high - 5 low - int32_t BlastIncinerate; // 0 off 1 - x if > damage - int32_t Constructable; - int32_t Grab; // 0 not 1 push 2 grab only - int32_t Carryable; - int32_t Rotateable; - int32_t Chopable; - int32_t Float; - int32_t ColorByOwner; - int32_t NoHorizontalMove; - int32_t BorderBound; - int32_t LiftTop; - int32_t GrabPutGet; - int32_t ContainBlast; - int32_t UprightAttach; - int32_t ContactFunctionCalls; - int32_t MaxUserSelect; + int32_t Mass; + int32_t Value; + int32_t Exclusive; + int32_t Category; + int32_t Growth; + int32_t Rebuyable; + int32_t ContactIncinerate; // 0 off 1 high - 5 low + int32_t BlastIncinerate; // 0 off 1 - x if > damage + int32_t Constructable; + int32_t Grab; // 0 not 1 push 2 grab only + int32_t Carryable; + int32_t Rotateable; + int32_t Chopable; + int32_t Float; + int32_t ColorByOwner; + int32_t NoHorizontalMove; + int32_t BorderBound; + int32_t LiftTop; + int32_t GrabPutGet; + int32_t ContainBlast; + int32_t UprightAttach; + int32_t ContactFunctionCalls; + int32_t MaxUserSelect; int32_t Line; int32_t LineConnect; int32_t LineIntersect; @@ -201,7 +201,7 @@ class C4Def: public C4PropList int32_t Timer; int32_t NoComponentMass; int32_t NoStabilize; - char STimerCall[C4AUL_MAX_Identifier]; + char STimerCall[C4AUL_MAX_Identifier]; int32_t ClosedContainer; // if set, contained objects are not damaged by lava/acid etc. 1: Contained objects can't view out; 2: They can int32_t SilentCommands; // if set, no command failure messages are printed int32_t NoBurnDamage; // if set, the object won't take damage when burning @@ -221,7 +221,7 @@ class C4Def: public C4PropList int32_t AllowPictureStack; // allow stacking of multiple items in menus even if some attributes do not match. APS_*-values public: void DefaultDefCore(); - bool LoadDefCore(C4Group &hGroup); + bool LoadDefCore(C4Group &hGroup); bool Save(C4Group &hGroup); void CompileFunc(StdCompiler *pComp); protected: @@ -230,11 +230,11 @@ class C4Def: public C4PropList // Here begins the C4Def - friend class C4DefList; - public: - C4Def(); - ~C4Def(); - public: + friend class C4DefList; + public: + C4Def(); + ~C4Def(); + public: char Maker[C4MaxName+1]; char Filename[_MAX_FNAME+1]; int32_t Creation; @@ -264,25 +264,25 @@ class C4Def: public C4PropList C4Facet MainFace; - protected: - C4Def *Next; - bool Temporary; + protected: + C4Def *Next; + bool Temporary; public: void Clear(); void Default(); - bool Load(C4Group &hGroup, - DWORD dwLoadWhat, const char *szLanguage, + bool Load(C4Group &hGroup, + DWORD dwLoadWhat, const char *szLanguage, class C4SoundSystem *pSoundSystem = NULL); void Draw(C4Facet &cgo, bool fSelected=false, DWORD iColor=0, C4Object *pObj=NULL, int32_t iPhaseX=0, int32_t iPhaseY=0); inline C4Facet &GetMainFace(C4DefGraphics *pGraphics, DWORD dwClr=0) { MainFace.Surface=pGraphics->GetBitmap(dwClr); return MainFace; } int32_t GetValue(C4Object *pInBase, int32_t iBuyPlayer); // get value of def; calling script functions if defined C4PhysicalInfo *GetFairCrewPhysicals(); // get fair crew physicals at current fair crew strength - void ClearFairCrewPhysicals(); // remove cached fair crew physicals, will be created fresh on demand + void ClearFairCrewPhysicals(); // remove cached fair crew physicals, will be created fresh on demand void Synchronize(); const char *GetDesc() { return Desc.GetData(); } virtual C4Def* GetDef() { return this; } - protected: + protected: bool LoadPortraits(C4Group &hGroup); bool LoadActMap(C4Group &hGroup); void CrossMapActMap(); @@ -299,34 +299,34 @@ class C4Def: public C4PropList C4PropList *GetActionByName(const char *actname); C4PropList *GetActionByName(C4String *actname); - }; + }; class C4DefList : public CStdFont::CustomImages - { - public: - C4DefList(); - virtual ~C4DefList(); + { + public: + C4DefList(); + virtual ~C4DefList(); public: bool LoadFailure; typedef std::map Table; Table table; - protected: - C4Def *FirstDef; - public: + protected: + C4Def *FirstDef; + public: void Default(); - void Clear(); - int32_t Load(C4Group &hGroup, - DWORD dwLoadWhat, const char *szLanguage, + void Clear(); + int32_t Load(C4Group &hGroup, + DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem = NULL, bool fOverload = false, bool fSearchMessage = false, int32_t iMinProgress=0, int32_t iMaxProgress=0, bool fLoadSysGroups = true); - int32_t Load(const char *szSearch, - DWORD dwLoadWhat, const char *szLanguage, + int32_t Load(const char *szSearch, + DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem = NULL, bool fOverload = false, int32_t iMinProgress=0, int32_t iMaxProgress=0); - int32_t LoadFolderLocal(const char *szPath, - DWORD dwLoadWhat, const char *szLanguage, + int32_t LoadFolderLocal(const char *szPath, + DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem = NULL, bool fOverload = false, char *szStoreName=NULL, int32_t iMinProgress=0, int32_t iMaxProgress=0); int32_t LoadForScenario(const char *szScenario, @@ -334,19 +334,19 @@ class C4DefList DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem = NULL, bool fOverload = false, int32_t iMinProgress=0, int32_t iMaxProgress=0); - C4Def *ID2Def(C4ID id); - C4Def *GetDef(int32_t Index, DWORD dwCategory = C4D_All); - C4Def *GetByPath(const char *szPath); + C4Def *ID2Def(C4ID id); + C4Def *GetDef(int32_t Index, DWORD dwCategory = C4D_All); + C4Def *GetByPath(const char *szPath); int32_t GetDefCount(DWORD dwCategory = C4D_All); - int32_t GetIndex(C4ID id); - int32_t RemoveTemporary(); + int32_t GetIndex(C4ID id); + int32_t RemoveTemporary(); int32_t CheckEngineVersion(int32_t ver1, int32_t ver2, int32_t ver3, int32_t ver4); int32_t CheckRequireDef(); void Draw(C4ID id, C4Facet &cgo, bool fSelected, int32_t iColor); - void Remove(C4Def *def); - bool Remove(C4ID id); + void Remove(C4Def *def); + bool Remove(C4ID id); bool Reload(C4Def *pDef, DWORD dwLoadWhat, const char *szLanguage, C4SoundSystem *pSoundSystem = NULL); - bool Add(C4Def *ndef, bool fOverload); + bool Add(C4Def *ndef, bool fOverload); void BuildTable(); void ResetIncludeDependencies(); // resets all pointers into foreign definitions caused by include chains void CallEveryDefinition(); @@ -354,7 +354,7 @@ class C4DefList // callback from font renderer: get ID image virtual bool GetFontImage(const char *szImageTag, CFacet &rOutImgFacet); - }; + }; extern C4DefList Definitions; diff --git a/src/game/object/C4GameObjects.cpp b/src/game/object/C4GameObjects.cpp index 96c7bbb1d..13f4906aa 100644 --- a/src/game/object/C4GameObjects.cpp +++ b/src/game/object/C4GameObjects.cpp @@ -453,8 +453,8 @@ C4ObjectList &C4GameObjects::ObjectsInt() void C4GameObjects::RemoveSolidMasks() { - C4ObjectLink *cLnk; - for (cLnk=First; cLnk; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj->Status) if (cLnk->Obj->pSolidMaskData) cLnk->Obj->pSolidMaskData->Remove(false, false); @@ -462,8 +462,8 @@ void C4GameObjects::RemoveSolidMasks() void C4GameObjects::PutSolidMasks() { - C4ObjectLink *cLnk; - for (cLnk=First; cLnk; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj->Status) cLnk->Obj->UpdateSolidMask(false); } @@ -478,13 +478,13 @@ void C4GameObjects::DeleteObjects(bool fDeleteInactive) } void C4GameObjects::Clear(bool fClearInactive) - { - DeleteObjects(fClearInactive); - if(fClearInactive) - InactiveObjects.Clear(); - ResortProc = NULL; + { + DeleteObjects(fClearInactive); + if(fClearInactive) + InactiveObjects.Clear(); + ResortProc = NULL; LastUsedMarker = 0; - } + } /* C4ObjResort */ @@ -696,26 +696,26 @@ int C4GameObjects::Load(C4Group &hGroup, bool fKeepInactive) Clear(!fKeepInactive); // Load data component - StdStrBuf Source; + StdStrBuf Source; if (!hGroup.LoadEntryString(C4CFN_ScenarioObjects, Source)) - return 0; + return 0; - // Compile + // Compile StdStrBuf Name = hGroup.GetFullName() + DirSep C4CFN_ScenarioObjects; - if(!CompileFromBuf_LogWarn( - mkParAdapt(*this, false), - Source, - Name.getData())) - return 0; + if(!CompileFromBuf_LogWarn( + mkParAdapt(*this, false), + Source, + Name.getData())) + return 0; // Process objects - C4ObjectLink *cLnk; - C4Object *pObj; - bool fObjectNumberCollision = false; - int32_t iMaxObjectNumber = 0; - for(cLnk = Last; cLnk; cLnk = cLnk->Prev) - { - C4Object *pObj = cLnk->Obj; + C4ObjectLink *cLnk; + C4Object *pObj; + bool fObjectNumberCollision = false; + int32_t iMaxObjectNumber = 0; + for(cLnk = Last; cLnk; cLnk = cLnk->Prev) + { + C4Object *pObj = cLnk->Obj; // check object number collision with inactive list if (fKeepInactive) { @@ -733,7 +733,7 @@ int C4GameObjects::Load(C4Group &hGroup, bool fKeepInactive) // Unterminate end } - // Denumerate pointers + // Denumerate pointers // if object numbers collideded, numbers will be adjusted afterwards // so fake inactive object list empty meanwhile C4ObjectLink *pInFirst = NULL; @@ -794,7 +794,7 @@ int C4GameObjects::Load(C4Group &hGroup, bool fKeepInactive) } } // sort out inactive objects - C4ObjectLink *cLnkNext; + C4ObjectLink *cLnkNext; for (cLnk=First; cLnk; cLnk=cLnkNext) { cLnkNext = cLnk->Next; @@ -827,7 +827,7 @@ int C4GameObjects::Load(C4Group &hGroup, bool fKeepInactive) //Sectors.Dump(); // misc updates - for (cLnk=First; cLnk; cLnk=cLnk->Next) + for (cLnk=First; cLnk; cLnk=cLnk->Next) if ((pObj=cLnk->Obj)->Status) { // add to plrview @@ -861,28 +861,28 @@ bool C4GameObjects::Save(const char *szFilename, bool fSaveGame, bool fSaveInact InactiveObjects.Enumerate(); // Decompile objects to buffer - StdStrBuf Buffer; - bool fSuccess = DecompileToBuf_Log(mkParAdapt(*this, !fSaveGame), &Buffer, szFilename); + StdStrBuf Buffer; + bool fSuccess = DecompileToBuf_Log(mkParAdapt(*this, !fSaveGame), &Buffer, szFilename); - // Decompile inactives - if(fSaveInactive) - { - StdStrBuf InactiveBuffer; - fSuccess &= DecompileToBuf_Log(mkParAdapt(InactiveObjects, false, !fSaveGame), &InactiveBuffer, szFilename); - Buffer.Append("\r\n"); - Buffer.Append(InactiveBuffer); - } + // Decompile inactives + if(fSaveInactive) + { + StdStrBuf InactiveBuffer; + fSuccess &= DecompileToBuf_Log(mkParAdapt(InactiveObjects, false, !fSaveGame), &InactiveBuffer, szFilename); + Buffer.Append("\r\n"); + Buffer.Append(InactiveBuffer); + } - // Denumerate + // Denumerate InactiveObjects.Denumerate(); Denumerate(); - // Error? - if(!fSuccess) - return false; + // Error? + if(!fSuccess) + return false; - // Write - return Buffer.SaveToFile(szFilename); + // Write + return Buffer.SaveToFile(szFilename); } void C4GameObjects::UpdateScriptPointers() @@ -1017,14 +1017,14 @@ void C4GameObjects::FixObjectOrder() void C4GameObjects::ResortUnsorted() { - C4ObjectLink *clnk=First; C4Object *cObj; - while (clnk && (cObj=clnk->Obj)) - { - clnk=clnk->Next; - if (cObj->Unsorted) - { + C4ObjectLink *clnk=First; C4Object *cObj; + while (clnk && (cObj=clnk->Obj)) + { + clnk=clnk->Next; + if (cObj->Unsorted) + { // readd to main object list - Remove(cObj); + Remove(cObj); cObj->Unsorted=false; if (!Add(cObj)) { @@ -1032,9 +1032,9 @@ void C4GameObjects::ResortUnsorted() Game.ClearPointers(cObj); delete cObj; } - } - } - } + } + } + } void C4GameObjects::ExecuteResorts() { diff --git a/src/game/object/C4IDList.cpp b/src/game/object/C4IDList.cpp index 702404e7c..386abc5b6 100644 --- a/src/game/object/C4IDList.cpp +++ b/src/game/object/C4IDList.cpp @@ -53,9 +53,9 @@ void C4IDListChunk::Clear() } C4IDList::C4IDList() : C4IDListChunk() - { - Default(); - } + { + Default(); + } C4IDList::C4IDList(const C4IDList &rCopy): C4IDListChunk() { @@ -95,48 +95,48 @@ void C4IDList::Clear() } bool C4IDList::IsClear() const - { + { return !Count; - } + } C4ID C4IDList::GetID(size_t index, int32_t *ipCount) const - { + { // outside list? if (!Inside(index,0,Count-1)) return C4ID::None; // get chunk to query const C4IDListChunk *pQueryChunk=this; while (index>=C4IDListChunkSize) { pQueryChunk=pQueryChunk->pNext; index-=C4IDListChunkSize; } // query it - if (ipCount) *ipCount=pQueryChunk->Count[index]; - return pQueryChunk->id[index]; - } + if (ipCount) *ipCount=pQueryChunk->Count[index]; + return pQueryChunk->id[index]; + } int32_t C4IDList::GetCount(size_t index) const - { + { // outside list? - if (!Inside(index,0,Count-1)) return 0; + if (!Inside(index,0,Count-1)) return 0; // get chunk to query const C4IDListChunk *pQueryChunk=this; while (index>=C4IDListChunkSize) { pQueryChunk=pQueryChunk->pNext; index-=C4IDListChunkSize; } // query it - return pQueryChunk->Count[index]; - } + return pQueryChunk->Count[index]; + } bool C4IDList::SetCount(size_t index, int32_t iCount) - { + { // outside list? - if (!Inside(index,0,Count-1)) return false; + if (!Inside(index,0,Count-1)) return false; // get chunk to set in C4IDListChunk *pQueryChunk=this; while (index>=C4IDListChunkSize) { pQueryChunk=pQueryChunk->pNext; index-=C4IDListChunkSize; } // set it - pQueryChunk->Count[index]=iCount; + pQueryChunk->Count[index]=iCount; // success - return true; - } + return true; + } int32_t C4IDList::GetIDCount(C4ID c_id, int32_t iZeroDefVal) const - { + { // find id const C4IDListChunk *pQueryChunk=this; size_t cnt=Count,cntl=0; @@ -154,11 +154,11 @@ int32_t C4IDList::GetIDCount(C4ID c_id, int32_t iZeroDefVal) const } } // none found - return 0; - } + return 0; + } bool C4IDList::SetIDCount(C4ID c_id, int32_t iCount, bool fAddNewID) - { + { // find id C4IDListChunk *pQueryChunk=this; size_t cnt=Count,cntl=0; @@ -194,13 +194,13 @@ bool C4IDList::SetIDCount(C4ID c_id, int32_t iCount, bool fAddNewID) return true; } // failure - return false; - } + return false; + } int32_t C4IDList::GetNumberOfIDs() const - { + { return Count; - } + } int32_t C4IDList::GetIndex(C4ID c_id) const { @@ -221,7 +221,7 @@ int32_t C4IDList::GetIndex(C4ID c_id) const } bool C4IDList::IncreaseIDCount(C4ID c_id, bool fAddNewID, int32_t IncreaseBy, bool fRemoveEmpty) - { + { // find id in list C4IDListChunk *pQueryChunk=this; size_t cnt=Count,cntl=0; @@ -264,64 +264,64 @@ bool C4IDList::IncreaseIDCount(C4ID c_id, bool fAddNewID, int32_t IncreaseBy, bo // Access by category-sorted index C4ID C4IDList::GetID(C4DefList &rDefs, int32_t dwCategory, int32_t index, int32_t *ipCount) const - { - int32_t cindex=-1; - C4Def *cDef; - if (ipCount) *ipCount=0; + { + int32_t cindex=-1; + C4Def *cDef; + if (ipCount) *ipCount=0; // find id const C4IDListChunk *pQueryChunk=this; size_t cnt=Count,cntl=0; while (cnt--) { if ((dwCategory==C4D_All) || ( (cDef=rDefs.ID2Def(pQueryChunk->id[cntl])) && (cDef->Category & dwCategory) ) ) - { - cindex++; - if (cindex==index) { if (ipCount) *ipCount=pQueryChunk->Count[cntl]; return pQueryChunk->id[cntl]; } - } + { + cindex++; + if (cindex==index) { if (ipCount) *ipCount=pQueryChunk->Count[cntl]; return pQueryChunk->id[cntl]; } + } if (++cntl==C4IDListChunkSize) { pQueryChunk=pQueryChunk->pNext; cntl=0; } } - return C4ID::None; - } + return C4ID::None; + } int32_t C4IDList::GetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index) const - { - int32_t cindex=-1; - C4Def *cDef; + { + int32_t cindex=-1; + C4Def *cDef; const C4IDListChunk *pQueryChunk=this; size_t cnt=Count,cntl=0; while (cnt--) { if ((dwCategory==C4D_All) || ( (cDef=rDefs.ID2Def(pQueryChunk->id[cntl])) && (cDef->Category & dwCategory) ) ) - { - cindex++; - if (cindex==index) return pQueryChunk->Count[cntl]; - } + { + cindex++; + if (cindex==index) return pQueryChunk->Count[cntl]; + } if (++cntl==C4IDListChunkSize) { pQueryChunk=pQueryChunk->pNext; cntl=0; } } - return 0; - } + return 0; + } bool C4IDList::SetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index, int32_t iCount) - { - int32_t cindex=-1; - C4Def *cDef; + { + int32_t cindex=-1; + C4Def *cDef; C4IDListChunk *pQueryChunk=this; size_t cnt=Count,cntl=0; while (cnt--) { if ((dwCategory==C4D_All) || ( (cDef=rDefs.ID2Def(pQueryChunk->id[cntl])) && (cDef->Category & dwCategory) ) ) - { - cindex++; - if (cindex==index) { pQueryChunk->Count[cntl]=iCount; return true; } - } + { + cindex++; + if (cindex==index) { pQueryChunk->Count[cntl]=iCount; return true; } + } if (++cntl==C4IDListChunkSize) { pQueryChunk=pQueryChunk->pNext; @@ -329,26 +329,26 @@ bool C4IDList::SetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index, int } } return false; - } + } int32_t C4IDList::GetNumberOfIDs(C4DefList &rDefs, int32_t dwCategory) const - { - int32_t idnum=0; - C4Def *cDef; + { + int32_t idnum=0; + C4Def *cDef; const C4IDListChunk *pQueryChunk=this; size_t cnt=Count,cntl=0; while (cnt--) { if ((dwCategory==C4D_All) || ( (cDef=rDefs.ID2Def(pQueryChunk->id[cntl])) && (cDef->Category & dwCategory) ) ) - idnum++; + idnum++; if (++cntl==C4IDListChunkSize) { pQueryChunk=pQueryChunk->pNext; cntl=0; } } - return idnum; - } + return idnum; + } // IDList merge bool C4IDList::Add(C4IDList &rList) @@ -370,13 +370,13 @@ bool C4IDList::Add(C4IDList &rList) // Removes all empty id gaps from the list. bool C4IDList::Consolidate() - { + { // however, there ain't be any of those crappy gaps! - return false; - } + return false; + } bool C4IDList::ConsolidateValids(C4DefList &rDefs, int32_t dwCategory) - { + { bool fIDsRemoved=false; C4IDListChunk *pQueryChunk=this; size_t cnt=Count,cntl=0; @@ -400,7 +400,7 @@ bool C4IDList::ConsolidateValids(C4DefList &rDefs, int32_t dwCategory) } } return fIDsRemoved; - } + } void C4IDList::SortByCategory(C4DefList &rDefs) { @@ -443,7 +443,7 @@ void C4IDList::SortByValue(C4DefList &rDefs) void C4IDList::Load(C4DefList &rDefs, int32_t dwCategory) { - // (deprecated, use StdCompiler instead) + // (deprecated, use StdCompiler instead) C4Def *cdef; size_t cntl=0,cnt=0; // clear list Clear(); @@ -484,9 +484,9 @@ void C4IDList::Draw(C4Facet &cgo, int32_t iSelection, { cgo2 = cgo.TruncateSection(iAlign); rDefs.Draw(c_id,cgo2,(firstid+cnt==iSelection),0); - sprintf(buf,"%dx",idcount); - if (fCounts) Application.DDraw->TextOut(buf, ::GraphicsResource.FontRegular, 1.0, cgo2.Surface,cgo2.X+cgo2.Wdt-1, cgo2.Y + cgo2.Hgt - 1 - ::GraphicsResource.FontRegular.iLineHgt,CStdDDraw::DEFAULT_MESSAGE_COLOR,ARight); - } + sprintf(buf,"%dx",idcount); + if (fCounts) Application.DDraw->TextOut(buf, ::GraphicsResource.FontRegular, 1.0, cgo2.Surface,cgo2.X+cgo2.Wdt-1, cgo2.Y + cgo2.Hgt - 1 - ::GraphicsResource.FontRegular.iLineHgt,CStdDDraw::DEFAULT_MESSAGE_COLOR,ARight); + } } @@ -592,64 +592,64 @@ bool C4IDList::operator==(const C4IDList& rhs) const } void C4IDList::CompileFunc(StdCompiler *pComp, bool fValues) - { - // Get compiler characteristics - bool fCompiler = pComp->isCompiler(); - bool fNaming = pComp->hasNaming(); - // Compiling: Clear existing data first - if(fCompiler) Clear(); - // Start - C4IDListChunk *pChunk = this; - size_t iNr = 0, iCNr = 0; - // Without naming: Compile Count + { + // Get compiler characteristics + bool fCompiler = pComp->isCompiler(); + bool fNaming = pComp->hasNaming(); + // Compiling: Clear existing data first + if(fCompiler) Clear(); + // Start + C4IDListChunk *pChunk = this; + size_t iNr = 0, iCNr = 0; + // Without naming: Compile Count int32_t iCount = Count; - if(!fNaming) pComp->Value(iCount); + if(!fNaming) pComp->Value(iCount); Count = iCount; - // Read - for(;;) - { - // Prepare compiling of single mapping - if(!fCompiler) - { - // End of list? - if(iNr >= Count) break; - // End of chunk? - if(iCNr >= C4IDListChunkSize) - { - pChunk = pChunk->pNext; - iCNr = 0; - } - } - else - { - // End of list? - if(!fNaming) if(iNr >= Count) break; - // End of chunk? - if(iCNr >= C4IDListChunkSize) - { - pChunk = pChunk->pNext = new C4IDListChunk(); - iCNr = 0; - } - } - // Seperator (';') - if(iNr > 0) if(!pComp->Seperator(StdCompiler::SEP_SEP2)) break; - // ID - pComp->Value(mkDefaultAdapt(pChunk->id[iCNr], C4ID::None)); - // ID not valid? Note that C4ID::None is invalid. + // Read + for(;;) + { + // Prepare compiling of single mapping + if(!fCompiler) + { + // End of list? + if(iNr >= Count) break; + // End of chunk? + if(iCNr >= C4IDListChunkSize) + { + pChunk = pChunk->pNext; + iCNr = 0; + } + } + else + { + // End of list? + if(!fNaming) if(iNr >= Count) break; + // End of chunk? + if(iCNr >= C4IDListChunkSize) + { + pChunk = pChunk->pNext = new C4IDListChunk(); + iCNr = 0; + } + } + // Seperator (';') + if(iNr > 0) if(!pComp->Seperator(StdCompiler::SEP_SEP2)) break; + // ID + pComp->Value(mkDefaultAdapt(pChunk->id[iCNr], C4ID::None)); + // ID not valid? Note that C4ID::None is invalid. if(pChunk->id[iCNr] == C4ID::None) break; - // Value: Skip this part if requested - if(fValues) - { - // Seperator ('=') - if(pComp->Seperator(StdCompiler::SEP_SET)) + // Value: Skip this part if requested + if(fValues) + { + // Seperator ('=') + if(pComp->Seperator(StdCompiler::SEP_SET)) // Count pComp->Value(mkDefaultAdapt(pChunk->Count[iCNr], 0)); - } - else if(fCompiler) - pChunk->Count[iCNr] = 0; - // Goto next entry - iNr++; iCNr++; - // Save back count - if(fCompiler && fNaming) Count = iNr; - } - } + } + else if(fCompiler) + pChunk->Count[iCNr] = 0; + // Goto next entry + iNr++; iCNr++; + // Save back count + if(fCompiler && fNaming) Count = iNr; + } + } diff --git a/src/game/object/C4IDList.h b/src/game/object/C4IDList.h index 80ef8e835..ac98f9e25 100644 --- a/src/game/object/C4IDList.h +++ b/src/game/object/C4IDList.h @@ -35,7 +35,7 @@ const size_t C4IDListChunkSize = 5; // size of id-chunks class C4IDListChunk { - public: + public: C4ID id[C4IDListChunkSize]; int32_t Count[C4IDListChunkSize]; @@ -50,9 +50,9 @@ class C4IDListChunk }; class C4IDList : protected C4IDListChunk - { - public: - C4IDList(); + { + public: + C4IDList(); C4IDList(const C4IDList &rCopy); // copy ctor C4IDList &operator = (const C4IDList &rCopy); // assignment ~C4IDList(); @@ -61,37 +61,37 @@ class C4IDList : protected C4IDListChunk ALLOW_TEMP_TO_REF(C4IDList) protected: size_t Count; // number of IDs in this list - public: + public: // General void Default(); - void Clear(); + void Clear(); bool IsClear() const; - // Access by direct index - C4ID GetID(size_t index, int32_t *ipCount=NULL) const; - int32_t GetCount(size_t index) const; - bool SetCount(size_t index, int32_t iCount); - // Access by ID - int32_t GetIDCount(C4ID c_id, int32_t iZeroDefVal=0) const; + // Access by direct index + C4ID GetID(size_t index, int32_t *ipCount=NULL) const; + int32_t GetCount(size_t index) const; + bool SetCount(size_t index, int32_t iCount); + // Access by ID + int32_t GetIDCount(C4ID c_id, int32_t iZeroDefVal=0) const; bool SetIDCount(C4ID c_id, int32_t iCount, bool fAddNewID=false); - bool IncreaseIDCount(C4ID c_id, bool fAddNewID=true, int32_t IncreaseBy=1, bool fRemoveEmpty=false); - bool DecreaseIDCount(C4ID c_id, bool fRemoveEmptyID=true) + bool IncreaseIDCount(C4ID c_id, bool fAddNewID=true, int32_t IncreaseBy=1, bool fRemoveEmpty=false); + bool DecreaseIDCount(C4ID c_id, bool fRemoveEmptyID=true) { return IncreaseIDCount(c_id, false, -1, fRemoveEmptyID); } - int32_t GetNumberOfIDs() const; + int32_t GetNumberOfIDs() const; int32_t GetIndex(C4ID c_id) const; - // Access by category-sorted index - C4ID GetID(C4DefList &rDefs, int32_t dwCategory, int32_t index, int32_t *ipCount=NULL) const; - int32_t GetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index) const; - bool SetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index, int32_t iCount); - int32_t GetNumberOfIDs(C4DefList &rDefs, int32_t dwCategory) const; + // Access by category-sorted index + C4ID GetID(C4DefList &rDefs, int32_t dwCategory, int32_t index, int32_t *ipCount=NULL) const; + int32_t GetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index) const; + bool SetCount(C4DefList &rDefs, int32_t dwCategory, int32_t index, int32_t iCount); + int32_t GetNumberOfIDs(C4DefList &rDefs, int32_t dwCategory) const; // IDList merge bool Add(C4IDList &rList); - // Aux - bool Consolidate(); - bool ConsolidateValids(C4DefList &rDefs, int32_t dwCategory = 0); + // Aux + bool Consolidate(); + bool ConsolidateValids(C4DefList &rDefs, int32_t dwCategory = 0); bool ConsolidateCounts(); void SortByCategory(C4DefList &rDefs); void SortByValue(C4DefList &rDefs); - void Load(C4DefList &rDefs, int32_t dwCategory); + void Load(C4DefList &rDefs, int32_t dwCategory); // Item operation bool DeleteItem(size_t iIndex); bool SwapItems(size_t iIndex1, size_t iIndex2); @@ -99,8 +99,8 @@ class C4IDList : protected C4IDListChunk void Draw(C4Facet &cgo, int32_t iSelection, C4DefList &rDefs, DWORD dwCategory, bool fCounts=true, int32_t iAlign=0) const; - // Compiling - void CompileFunc(StdCompiler *pComp, bool fValues = true); - }; + // Compiling + void CompileFunc(StdCompiler *pComp, bool fValues = true); + }; #endif diff --git a/src/game/object/C4InfoCore.cpp b/src/game/object/C4InfoCore.cpp index 40d53d2e3..dfb80561d 100644 --- a/src/game/object/C4InfoCore.cpp +++ b/src/game/object/C4InfoCore.cpp @@ -37,10 +37,10 @@ //------------------------------- Player Info ---------------------------------------- C4PlayerInfoCore::C4PlayerInfoCore() - { - ZeroMem(this,sizeof(C4PlayerInfoCore)); + { + ZeroMem(this,sizeof(C4PlayerInfoCore)); Default(); - } + } void C4PlayerInfoCore::Default(C4RankSystem *pRanks) { @@ -74,7 +74,7 @@ DWORD C4PlayerInfoCore::GetPrefColorValue(int32_t iPrefColor) } bool C4PlayerInfoCore::Load(C4Group &hGroup) - { + { // New version StdStrBuf Source; if (hGroup.LoadEntryString(C4CFN_PlayerInfoCore,Source)) @@ -99,11 +99,11 @@ bool C4PlayerInfoCore::Load(C4Group &hGroup) } // Old version no longer supported - sorry - return false; - } + return false; + } bool C4PlayerInfoCore::Save(C4Group &hGroup) - { + { StdStrBuf Source, Name = hGroup.GetFullName(); Name.Append(DirSep C4CFN_PlayerInfoCore); if(!DecompileToBuf_Log(*this, &Source, Name.getData())) return false; @@ -349,14 +349,14 @@ void C4PhysicalChange::CompileFunc(StdCompiler *pComp) //------------------------------- Object Info ---------------------------------------- C4ObjectInfoCore::C4ObjectInfoCore() - { + { Default(); - } + } void C4ObjectInfoCore::Default(C4ID n_id, C4DefList *pDefs, const char *cpNames) - { + { // Def C4Def *pDef=NULL; @@ -364,8 +364,8 @@ void C4ObjectInfoCore::Default(C4ID n_id, // Defaults id=n_id; - Participation=1; - Rank=0; + Participation=1; + Rank=0; Experience=0; Rounds=0; DeathCount=0; diff --git a/src/game/object/C4InfoCore.h b/src/game/object/C4InfoCore.h index 142109c30..8e164687d 100644 --- a/src/game/object/C4InfoCore.h +++ b/src/game/object/C4InfoCore.h @@ -31,31 +31,31 @@ const int32_t C4MaxPhysical = 100000, C4MaxDeathMsg = 75; class C4PhysicalInfo - { - public: + { + public: C4PhysicalInfo(); typedef int32_t C4PhysicalInfo::* Offset; - public: - int32_t Energy; + public: + int32_t Energy; int32_t Breath; - int32_t Walk; + int32_t Walk; int32_t Jump; int32_t Scale; int32_t Hangle; int32_t Dig; int32_t Swim; - int32_t Throw; + int32_t Throw; int32_t Push; int32_t Fight; int32_t Magic; - int32_t CanScale; + int32_t CanScale; int32_t CanHangle; - int32_t CanDig; + int32_t CanDig; int32_t CanConstruct; int32_t CanChop; - int32_t CanSwimDig; + int32_t CanSwimDig; int32_t CanFly; int32_t CorrosionResist; int32_t BreatheWater; @@ -78,7 +78,7 @@ class C4PhysicalInfo static void TrainValue(int32_t *piVal, int32_t iTrainBy, int32_t iMaxTrain); public: void Train(Offset mpiOffset, int32_t iTrainBy, int32_t iMaxTrain); - }; + }; class C4PhysicalChange { @@ -125,33 +125,33 @@ class C4TempPhysicalInfo : public C4PhysicalInfo }; class C4ObjectInfoCore - { - public: - C4ObjectInfoCore(); - public: - C4ID id; - char Name[C4MaxName+1]; - int32_t Participation; - int32_t Rank; + { + public: + C4ObjectInfoCore(); + public: + C4ID id; + char Name[C4MaxName+1]; + int32_t Participation; + int32_t Rank; StdStrBuf sRankName; StdStrBuf sNextRankName; int32_t NextRankExp; // EXP_NoPromotion for no more promotion; 0 if standard rank system is used - int32_t Experience,Rounds; - int32_t DeathCount; + int32_t Experience,Rounds; + int32_t DeathCount; char TypeName[C4MaxName+1+1]; int32_t Birthday,TotalPlayingTime; int32_t Age; char DeathMessage[C4MaxDeathMsg+1]; char PortraitFile[C4MaxName+2+4+1]; // used portrait - C4PhysicalInfo Physical; + C4PhysicalInfo Physical; C4ValueMapData ExtraData; bool NoSave; // set for _XYZ-CrewMembers - public: + public: bool Save(C4Group &hGroup, class C4DefList *pDefs); bool Load(C4Group &hGroup); - void Default(C4ID n_id=C4ID::None, class C4DefList *pDefs=NULL, const char *cpNames=NULL); - //bool LoadNext(C4Group &hGroup); Old c4o support disabled... - //bool Add(C4Group &hGroup); + void Default(C4ID n_id=C4ID::None, class C4DefList *pDefs=NULL, const char *cpNames=NULL); + //bool LoadNext(C4Group &hGroup); Old c4o support disabled... + //bool Add(C4Group &hGroup); void Promote(int32_t iRank, C4RankSystem &rRanks, bool fForceRankName); bool GetNextRankInfo(C4RankSystem &rDefaultRanks, int32_t *piNextRankExp, StdStrBuf *psNextRankName); void CompileFunc(StdCompiler *pComp); @@ -160,24 +160,24 @@ class C4ObjectInfoCore bool Decompile(char **ppOutput, size_t *ipSize); void UpdateCustomRanks(C4DefList *pDefs); // sets NextRankName and NextRankExp - }; + }; class C4RoundResult - { + { public: C4RoundResult(); - public: - StdCopyStrBuf Title; - uint32_t Date; - int32_t Duration; - int32_t Won; - int32_t Score,FinalScore,TotalScore; + public: + StdCopyStrBuf Title; + uint32_t Date; + int32_t Duration; + int32_t Won; + int32_t Score,FinalScore,TotalScore; int32_t Bonus; int32_t Level; public: void Default(); void CompileFunc(StdCompiler *pComp); - }; + }; class C4PlayerInfoCore { diff --git a/src/game/object/C4Movement.cpp b/src/game/object/C4Movement.cpp index da6722916..74f599059 100644 --- a/src/game/object/C4Movement.cpp +++ b/src/game/object/C4Movement.cpp @@ -49,74 +49,74 @@ const FIXED HitSpeed4=itofix(8); // Flat /* Some helper functions */ void RedirectForce(FIXED &from, FIXED &to, int32_t tdir) - { - FIXED fred; - fred=Min(Abs(from), FRedirect); - from-=fred*Sign(from); - to+=fred*tdir; - } + { + FIXED fred; + fred=Min(Abs(from), FRedirect); + from-=fred*Sign(from); + to+=fred*tdir; + } void ApplyFriction(FIXED &tval, int32_t percent) - { - FIXED ffric=FFriction*percent/100; - if (tval>+ffric) { tval-=ffric; return; } - if (tval<-ffric) { tval+=ffric; return; } - tval=0; - } + { + FIXED ffric=FFriction*percent/100; + if (tval>+ffric) { tval-=ffric; return; } + if (tval<-ffric) { tval+=ffric; return; } + tval=0; + } // Compares all Shape.VtxContactCNAT[] CNAT flags to search flag. // Returns true if CNAT match has been found. bool ContactVtxCNAT(C4Object *cobj, BYTE cnat_dir) - { - int32_t cnt; - bool fcontact=false; - for (cnt=0; cntShape.VtxNum; cnt++) - if (cobj->Shape.VtxContactCNAT[cnt] & cnat_dir) - fcontact=true; - return fcontact; - } + { + int32_t cnt; + bool fcontact=false; + for (cnt=0; cntShape.VtxNum; cnt++) + if (cobj->Shape.VtxContactCNAT[cnt] & cnat_dir) + fcontact=true; + return fcontact; + } // Finds first vertex with contact flag set. // Returns -1/0/+1 for relation on vertex to object center. int32_t ContactVtxWeight(C4Object *cobj) - { - int32_t cnt; - for (cnt=0; cntShape.VtxNum; cnt++) - if (cobj->Shape.VtxContactCNAT[cnt]) - { - if (cobj->Shape.VtxX[cnt]<0) return -1; - if (cobj->Shape.VtxX[cnt]>0) return +1; - } - return 0; - } + { + int32_t cnt; + for (cnt=0; cntShape.VtxNum; cnt++) + if (cobj->Shape.VtxContactCNAT[cnt]) + { + if (cobj->Shape.VtxX[cnt]<0) return -1; + if (cobj->Shape.VtxX[cnt]>0) return +1; + } + return 0; + } // ContactVtxFriction: Returns 0-100 friction value of first // contacted vertex; int32_t ContactVtxFriction(C4Object *cobj) - { - int32_t cnt; - for (cnt=0; cntShape.VtxNum; cnt++) - if (cobj->Shape.VtxContactCNAT[cnt]) - return cobj->Shape.VtxFriction[cnt]; - return 0; - } + { + int32_t cnt; + for (cnt=0; cntShape.VtxNum; cnt++) + if (cobj->Shape.VtxContactCNAT[cnt]) + return cobj->Shape.VtxFriction[cnt]; + return 0; + } const char *CNATName(int32_t cnat) - { - switch (cnat) - { - case CNAT_None: return "None"; - case CNAT_Left: return "Left"; - case CNAT_Right: return "Right"; - case CNAT_Top: return "Top"; - case CNAT_Bottom: return "Bottom"; - case CNAT_Center: return "Center"; - } - return "Undefined"; - } + { + switch (cnat) + { + case CNAT_None: return "None"; + case CNAT_Left: return "Left"; + case CNAT_Right: return "Right"; + case CNAT_Top: return "Top"; + case CNAT_Bottom: return "Bottom"; + case CNAT_Center: return "Center"; + } + return "Undefined"; + } bool C4Object::Contact(int32_t iCNAT) { @@ -124,14 +124,14 @@ bool C4Object::Contact(int32_t iCNAT) { return !! Call(FormatString(PSF_Contact, CNATName(iCNAT)).getData()); } - return false; + return false; } void C4Object::DoMotion(int32_t mx, int32_t my) - { - if (pSolidMaskData) pSolidMaskData->Remove(true, true); - fix_x += mx; fix_y += my; - } + { + if (pSolidMaskData) pSolidMaskData->Remove(true, true); + fix_x += mx; fix_y += my; + } static inline int32_t ForceLimits(FIXED &rVal, int32_t iLow, int32_t iHi) { @@ -167,10 +167,10 @@ int32_t C4Object::ContactCheck(int32_t iAtX, int32_t iAtY) // Store shape contact values in object t_contact t_contact=Shape.ContactCNAT; - // Contact script call for the first contacted cnat - if (Shape.ContactCNAT) - for (int32_t ccnat=0; ccnat<4; ccnat++) // Left, right, top bottom - if (Shape.ContactCNAT & (1<BorderBound & C4D_Border_Sides) + if (Def->BorderBound & C4D_Border_Sides) TargetBounds(ctcox,0-Shape.GetX(),GBackWdt+Shape.GetX(),CNAT_Left,CNAT_Right); } @@ -212,9 +212,9 @@ void C4Object::VerticalBounds(FIXED &ctcoy) } } // landscape bounds - if (Def->BorderBound & C4D_Border_Top) + if (Def->BorderBound & C4D_Border_Top) TargetBounds(ctcoy,0-Shape.GetY(),+1000000,CNAT_Top,CNAT_Bottom); - if (Def->BorderBound & C4D_Border_Bottom) + if (Def->BorderBound & C4D_Border_Bottom) TargetBounds(ctcoy,-1000000,GBackHgt+Shape.GetY(),CNAT_Top,CNAT_Bottom); } @@ -465,32 +465,32 @@ void C4Object::DoMovement() } void C4Object::Stabilize() - { + { // def allows stabilization? if (Def->NoStabilize) return; // normalize angle int32_t nr = r; while(nr < -180) nr+=360; while(nr > 180) nr-=360; if (nr!=0) - if (Inside(nr,-StableRange,+StableRange)) - { - // Save step undos - int32_t lcobjr=r; - C4Shape lshape=Shape; - // Try rotation - r=0; - UpdateShape(); - if (ContactCheck(GetX(),GetY())) - { // Undo rotation - Shape=lshape; - r=lcobjr; - } - else - { // Stabilization okay - fix_r=itofix(r); - UpdateFace(true); - } - } - } + if (Inside(nr,-StableRange,+StableRange)) + { + // Save step undos + int32_t lcobjr=r; + C4Shape lshape=Shape; + // Try rotation + r=0; + UpdateShape(); + if (ContactCheck(GetX(),GetY())) + { // Undo rotation + Shape=lshape; + r=lcobjr; + } + else + { // Stabilization okay + fix_r=itofix(r); + UpdateFace(true); + } + } + } void C4Object::CopyMotion(C4Object *from) { @@ -523,48 +523,48 @@ void C4Object::MovePosition(int32_t dx, int32_t dy) bool C4Object::ExecMovement() // Every Tick1 by Execute - { + { - // Containment check - if (Contained) - { - CopyMotion(Contained); + // Containment check + if (Contained) + { + CopyMotion(Contained); - return true; - } + return true; + } - // General mobility check - if (Category & C4D_StaticBack) return false; + // General mobility check + if (Category & C4D_StaticBack) return false; - // Movement execution - if (Mobile) // Object is moving - { - // Move object - DoMovement(); - // Demobilization check - if ((xdir==0) && (ydir==0) && (rdir==0)) Mobile=0; - // Check for stabilization - if (rdir==0) Stabilize(); - } - else // Object is static - { - // Check for stabilization - Stabilize(); - // Check for mobilization - if (!::Game.iTick10) - { - // Gravity mobilization - xdir=ydir=rdir=0; - fix_r=itofix(r); - Mobile=1; - } - } + // Movement execution + if (Mobile) // Object is moving + { + // Move object + DoMovement(); + // Demobilization check + if ((xdir==0) && (ydir==0) && (rdir==0)) Mobile=0; + // Check for stabilization + if (rdir==0) Stabilize(); + } + else // Object is static + { + // Check for stabilization + Stabilize(); + // Check for mobilization + if (!::Game.iTick10) + { + // Gravity mobilization + xdir=ydir=rdir=0; + fix_r=itofix(r); + Mobile=1; + } + } - // Enforce zero rotation - if (!Def->Rotateable) r=0; + // Enforce zero rotation + if (!Def->Rotateable) r=0; - // Out of bounds check - if ((!Inside(GetX(),0,GBackWdt) && !(Def->BorderBound & C4D_Border_Sides)) || (GetY()>GBackHgt && !(Def->BorderBound & C4D_Border_Bottom))) + // Out of bounds check + if ((!Inside(GetX(),0,GBackWdt) && !(Def->BorderBound & C4D_Border_Sides)) || (GetY()>GBackHgt && !(Def->BorderBound & C4D_Border_Bottom))) { C4PropList* pActionDef = GetAction(); // Never remove attached objects: If they are truly outside landscape, their target will be removed, @@ -589,35 +589,35 @@ bool C4Object::ExecMovement() // Every Tick1 by Execute } } } - return true; - } + return true; + } bool SimFlight(FIXED &x, FIXED &y, FIXED &xdir, FIXED &ydir, int32_t iDensityMin, int32_t iDensityMax, int32_t iIter) { - bool fBreak = false; + bool fBreak = false; int32_t ctcox,ctcoy,cx,cy; cx = fixtoi(x); cy = fixtoi(y); - do + do { if(!iIter--) return false; - // Set target position by momentum - x+=xdir; y+=ydir; - // Movement to target - ctcox=fixtoi(x); ctcoy=fixtoi(y); - // Bounds - if (!Inside(ctcox,0,GBackWdt) || (ctcoy>=GBackHgt)) return false; - // Move to target - do - { - // Set next step target - cx+=Sign(ctcox-cx); cy+=Sign(ctcoy-cy); - // Contact check - if(Inside(GBackDensity(cx,cy), iDensityMin, iDensityMax)) + // Set target position by momentum + x+=xdir; y+=ydir; + // Movement to target + ctcox=fixtoi(x); ctcoy=fixtoi(y); + // Bounds + if (!Inside(ctcox,0,GBackWdt) || (ctcoy>=GBackHgt)) return false; + // Move to target + do + { + // Set next step target + cx+=Sign(ctcox-cx); cy+=Sign(ctcoy-cy); + // Contact check + if(Inside(GBackDensity(cx,cy), iDensityMin, iDensityMax)) { fBreak = true; break; } - } - while ((cx!=ctcox) || (cy!=ctcoy)); - // Adjust GravAccel once per frame - ydir+=GravAccel; + } + while ((cx!=ctcox) || (cy!=ctcoy)); + // Adjust GravAccel once per frame + ydir+=GravAccel; } while(!fBreak); // write position back @@ -627,7 +627,7 @@ bool SimFlight(FIXED &x, FIXED &y, FIXED &xdir, FIXED &ydir, int32_t iDensityMin } bool SimFlightHitsLiquid(FIXED fcx, FIXED fcy, FIXED xdir, FIXED ydir) - { + { // Start in water? if(DensityLiquid(GBackDensity(fixtoi(fcx), fixtoi(fcy)))) if(!SimFlight(fcx, fcy, xdir, ydir, 0, C4M_Liquid - 1, 10)) @@ -637,5 +637,5 @@ bool SimFlightHitsLiquid(FIXED fcx, FIXED fcy, FIXED xdir, FIXED ydir) return false; // liquid & deep enough? return GBackLiquid(fixtoi(fcx), fixtoi(fcy)) && GBackLiquid(fixtoi(fcx), fixtoi(fcy) + 9); - } + } diff --git a/src/game/object/C4Object.cpp b/src/game/object/C4Object.cpp index e84afa151..ab1d0138a 100644 --- a/src/game/object/C4Object.cpp +++ b/src/game/object/C4Object.cpp @@ -54,14 +54,14 @@ #include void DrawVertex(C4Facet &cgo, int32_t tx, int32_t ty, int32_t col, int32_t contact) - { - if (Inside(tx,1,cgo.Wdt-2) && Inside(ty,1,cgo.Hgt-2)) - { - Application.DDraw->DrawHorizontalLine(cgo.Surface,cgo.X+tx-1,cgo.X+tx+1,cgo.Y+ty,col); - Application.DDraw->DrawVerticalLine(cgo.Surface,cgo.X+tx,cgo.Y+ty-1,cgo.Y+ty+1,col); - if (contact) Application.DDraw->DrawFrame(cgo.Surface,cgo.X+tx-2,cgo.Y+ty-2,cgo.X+tx+2,cgo.Y+ty+2,CWhite); - } - } + { + if (Inside(tx,1,cgo.Wdt-2) && Inside(ty,1,cgo.Hgt-2)) + { + Application.DDraw->DrawHorizontalLine(cgo.Surface,cgo.X+tx-1,cgo.X+tx+1,cgo.Y+ty,col); + Application.DDraw->DrawVerticalLine(cgo.Surface,cgo.X+tx,cgo.Y+ty-1,cgo.Y+ty+1,col); + if (contact) Application.DDraw->DrawFrame(cgo.Surface,cgo.X+tx-2,cgo.Y+ty-2,cgo.X+tx+2,cgo.Y+ty+2,CWhite); + } + } void C4Action::SetBridgeData(int32_t iBridgeTime, bool fMoveClonk, bool fWall, int32_t iBridgeMaterial) { @@ -112,30 +112,30 @@ void C4Object::Default() ViewEnergy=0; PlrViewRange=0; fix_x=fix_y=fix_r=0; - xdir=ydir=rdir=0; - Mobile=0; - Select=0; + xdir=ydir=rdir=0; + Mobile=0; + Select=0; Unsorted=false; Initializing=false; - OnFire=0; - InLiquid=0; - EntranceStatus=0; - Audible=0; + OnFire=0; + InLiquid=0; + EntranceStatus=0; + Audible=0; NeedEnergy=0; Timer=0; - t_contact=0; - OCF=0; - Action.Default(); - Shape.Default(); + t_contact=0; + OCF=0; + Action.Default(); + Shape.Default(); fOwnVertices=0; - Contents.Default(); - Component.Default(); + Contents.Default(); + Component.Default(); SolidMask.Default(); PictureRect.Default(); Def=NULL; - Info=NULL; - Command=NULL; - Contained=NULL; + Info=NULL; + Command=NULL; + Contained=NULL; TopFace.Default(); nContained=nActionTarget1=nActionTarget2=0; Menu=NULL; @@ -161,21 +161,21 @@ bool C4Object::Init(C4PropList *pDef, C4Object *pCreator, int32_t iOwner, C4ObjectInfo *pInfo, int32_t nx, int32_t ny, int32_t nr, FIXED nxdir, FIXED nydir, FIXED nrdir, int32_t iController) - { + { C4PropListNumbered::AcquireNumber(); // currently initializing Initializing=true; // Def & basics - Owner=iOwner; + Owner=iOwner; if (iController > NO_OWNER) Controller = iController; else Controller=iOwner; LastEnergyLossCausePlayer=NO_OWNER; - Info=pInfo; - Def=pDef->GetDef();assert(Def); + Info=pInfo; + Def=pDef->GetDef();assert(Def); SetProperty(Strings.P[P_Prototype], C4VPropList(pDef)); id=Def->id; if (Info) SetName(pInfo->Name); - Category=Def->Category; + Category=Def->Category; Def->Count++; if (pCreator) pLayer=pCreator->pLayer; @@ -197,30 +197,30 @@ bool C4Object::Init(C4PropList *pDef, C4Object *pCreator, if (!Def->Rotateable) { nr=0; nrdir=0; } fix_x=itofix(nx); fix_y=itofix(ny); - r=nr; + r=nr; fix_r=itofix(r); xdir=nxdir; ydir=nydir; rdir=nrdir; // Initial mobility if (Category!=C4D_StaticBack) - if (!!xdir || !!ydir || !!rdir) - Mobile=1; + if (!!xdir || !!ydir || !!rdir) + Mobile=1; // Mass - Mass=Max(Def->Mass*Con/FullCon,1); + Mass=Max(Def->Mass*Con/FullCon,1); // Life, energy, breath if (Category & C4D_Living) Alive=1; - if (Alive) Energy=GetPhysical()->Energy; - Breath=GetPhysical()->Breath; + if (Alive) Energy=GetPhysical()->Energy; + Breath=GetPhysical()->Breath; // Components - Component=Def->Component; - ComponentConCutoff(); + Component=Def->Component; + ComponentConCutoff(); // Color - if (Def->ColorByOwner) - if (ValidPlr(Owner)) + if (Def->ColorByOwner) + if (ValidPlr(Owner)) Color=::Players.Get(Owner)->ColorDw; // Shape & face @@ -228,10 +228,10 @@ bool C4Object::Init(C4PropList *pDef, C4Object *pCreator, SolidMask=Def->SolidMask; CheckSolidMaskRect(); UpdateGraphics(false); - UpdateFace(true); + UpdateFace(true); - // Initial audibility - Audible=::GraphicsSystem.GetAudibility(GetX(), GetY(), &AudiblePan); + // Initial audibility + Audible=::GraphicsSystem.GetAudibility(GetX(), GetY(), &AudiblePan); // Initial OCF SetOCF(); @@ -242,18 +242,18 @@ bool C4Object::Init(C4PropList *pDef, C4Object *pCreator, // finished initializing Initializing=false; - return true; - } + return true; + } C4Object::~C4Object() - { + { Clear(); #if defined(_DEBUG) // debug: mustn't be listed in any list now ::Objects.Sectors.AssertObjectNotInList(this); #endif - } + } void C4Object::AssignRemoval(bool fExitContents) { @@ -276,8 +276,8 @@ void C4Object::AssignRemoval(bool fExitContents) Call(PSF_Destruction); // Destruction-callback might have deleted the object already if (!Status) return; - // remove all effects (extinguishes as well) - if (pEffects) + // remove all effects (extinguishes as well) + if (pEffects) { pEffects->ClearAll(this, C4FxCall_RemoveClear); // Effect-callback might actually have deleted the object already @@ -302,14 +302,14 @@ void C4Object::AssignRemoval(bool fExitContents) Status = C4OS_NORMAL; ::Objects.Add(this); } - Status=0; + Status=0; // count decrease Def->Count--; - // Kill contents - C4Object *cobj; C4ObjectLink *clnk,*next; - for (clnk=Contents.First; clnk && (cobj=clnk->Obj); clnk=next) - { - next=clnk->Next; + // Kill contents + C4Object *cobj; C4ObjectLink *clnk,*next; + for (clnk=Contents.First; clnk && (cobj=clnk->Obj); clnk=next) + { + next=clnk->Next; if (fExitContents) cobj->Exit(GetX(), GetY()); else @@ -317,7 +317,7 @@ void C4Object::AssignRemoval(bool fExitContents) Contents.Remove(cobj); cobj->AssignRemoval(); } - } + } // remove from container *after* contents have been removed! C4Object *pCont; if ((pCont=Contained)) @@ -327,12 +327,12 @@ void C4Object::AssignRemoval(bool fExitContents) pCont->SetOCF(); Contained=NULL; } - // Object info - if (Info) Info->Retire(); + // Object info + if (Info) Info->Retire(); Info = NULL; // Object system operation C4PropList::AssignRemoval(); - ClearCommands(); + ClearCommands(); if (pSolidMaskData) { pSolidMaskData->Remove(true, false); @@ -340,11 +340,11 @@ void C4Object::AssignRemoval(bool fExitContents) pSolidMaskData = NULL; } SolidMask.Wdt = 0; - RemovalDelay=2; - } + RemovalDelay=2; + } void C4Object::UpdateShape(bool bUpdateVertices) - { + { // Line shape independent if (Def->Line) return; @@ -352,23 +352,23 @@ void C4Object::UpdateShape(bool bUpdateVertices) // Copy shape from def Shape.CopyFrom(Def->Shape, bUpdateVertices, !!fOwnVertices); - // Construction zoom - if (Con!=FullCon) - { - if (Def->GrowthType) - Shape.Stretch(Con, bUpdateVertices); - else - Shape.Jolt(Con, bUpdateVertices); - } + // Construction zoom + if (Con!=FullCon) + { + if (Def->GrowthType) + Shape.Stretch(Con, bUpdateVertices); + else + Shape.Jolt(Con, bUpdateVertices); + } - // Rotation - if (Def->Rotateable) - if (r!=0) - Shape.Rotate(r, bUpdateVertices); + // Rotation + if (Def->Rotateable) + if (r!=0) + Shape.Rotate(r, bUpdateVertices); // covered area changed? to be on the save side, update pos UpdatePos(); - } + } void C4Object::UpdatePos() { @@ -379,22 +379,22 @@ void C4Object::UpdatePos() } void C4Object::UpdateFace(bool bUpdateShape, bool fTemp) - { + { - // Update shape - NOT for temp call, because temnp calls are done in drawing routine + // Update shape - NOT for temp call, because temnp calls are done in drawing routine // must not change sync relevant data here (although the shape and pos *should* be updated at that time anyway, // because a runtime join would desync otherwise) - if (!fTemp) { if (bUpdateShape) UpdateShape(); else UpdatePos(); } + if (!fTemp) { if (bUpdateShape) UpdateShape(); else UpdatePos(); } - // SolidMask - if (!fTemp) UpdateSolidMask(false); + // SolidMask + if (!fTemp) UpdateSolidMask(false); - // Null defaults + // Null defaults TopFace.Default(); // newgfx: TopFace only - if (Con>=FullCon || Def->GrowthType) - if (!Def->Rotateable || (r==0)) + if (Con>=FullCon || Def->GrowthType) + if (!Def->Rotateable || (r==0)) if (Def->TopFace.Wdt>0) // Fullcon & no rotation TopFace.Set(GetGraphics()->GetBitmap(Color), Def->TopFace.x,Def->TopFace.y, @@ -634,42 +634,42 @@ void C4Object::DrawActionFace(C4TargetFacet &cgo, float offX, float offY) } void C4Object::UpdateMass() - { - Mass=Max((Def->Mass+OwnMass)*Con/FullCon,1); - if (!Def->NoComponentMass) Mass+=Contents.Mass; - if (Contained) - { - Contained->Contents.MassCount(); - Contained->UpdateMass(); - } - } + { + Mass=Max((Def->Mass+OwnMass)*Con/FullCon,1); + if (!Def->NoComponentMass) Mass+=Contents.Mass; + if (Contained) + { + Contained->Contents.MassCount(); + Contained->UpdateMass(); + } + } void C4Object::ComponentConCutoff() - { + { // this is not ideal, since it does not know about custom builder components - int32_t cnt; - for (cnt=0; Component.GetID(cnt); cnt++) - Component.SetCount(cnt, - Min(Component.GetCount(cnt),Def->Component.GetCount(cnt)*Con/FullCon)); - } + int32_t cnt; + for (cnt=0; Component.GetID(cnt); cnt++) + Component.SetCount(cnt, + Min(Component.GetCount(cnt),Def->Component.GetCount(cnt)*Con/FullCon)); + } void C4Object::ComponentConGain() - { + { // this is not ideal, since it does not know about custom builder components - int32_t cnt; - for (cnt=0; Component.GetID(cnt); cnt++) - Component.SetCount(cnt, - Max(Component.GetCount(cnt),Def->Component.GetCount(cnt)*Con/FullCon)); - } + int32_t cnt; + for (cnt=0; Component.GetID(cnt); cnt++) + Component.SetCount(cnt, + Max(Component.GetCount(cnt),Def->Component.GetCount(cnt)*Con/FullCon)); + } void C4Object::SetOCF() - { + { C4PropList* pActionDef = GetAction(); #ifdef DEBUGREC_OCF uint32_t dwOCFOld = OCF; #endif // Update the object character flag according to the object's current situation - FIXED cspeed=GetSpeed(); + FIXED cspeed=GetSpeed(); #ifdef _DEBUG if(Contained && !::Objects.ObjectNumber(Contained)) { LogF("Warning: contained in wild object %p!", static_cast(Contained)); } @@ -681,70 +681,70 @@ void C4Object::SetOCF() else InMat = GBackMat(GetX(), GetY()); // OCF_Normal: The OCF is never zero - OCF=OCF_Normal; - // OCF_Construct: Can be built outside - if (Def->Constructable && (ConGrab && !(Category & C4D_StaticBack)) - OCF|=OCF_Grab; - // OCF_Carryable: Can be picked up - if (GetPropertyInt(P_Collectible)) - OCF|=OCF_Carryable; - // OCF_OnFire: Is burning - if (OnFire) - OCF|=OCF_OnFire; - // OCF_Inflammable: Is not burning and is inflammable - if (!OnFire && Def->ContactIncinerate>0) + OCF=OCF_Normal; + // OCF_Construct: Can be built outside + if (Def->Constructable && (ConGrab && !(Category & C4D_StaticBack)) + OCF|=OCF_Grab; + // OCF_Carryable: Can be picked up + if (GetPropertyInt(P_Collectible)) + OCF|=OCF_Carryable; + // OCF_OnFire: Is burning + if (OnFire) + OCF|=OCF_OnFire; + // OCF_Inflammable: Is not burning and is inflammable + if (!OnFire && Def->ContactIncinerate>0) // Is not a dead living - if (!(Category & C4D_Living) || Alive) - OCF|=OCF_Inflammable; - // OCF_FullCon: Is fully completed/grown - if (Con>=FullCon) - OCF|=OCF_FullCon; - // OCF_Chop: Can be chopped + if (!(Category & C4D_Living) || Alive) + OCF|=OCF_Inflammable; + // OCF_FullCon: Is fully completed/grown + if (Con>=FullCon) + OCF|=OCF_FullCon; + // OCF_Chop: Can be chopped DWORD cocf = OCF_Exclusive; - if (Def->Chopable) - if (Category & C4D_StaticBack) // Must be static back: this excludes trees that have already been chopped + if (Def->Chopable) + if (Category & C4D_StaticBack) // Must be static back: this excludes trees that have already been chopped if (!::Objects.AtObject(GetX(), GetY(), cocf)) // Can only be chopped if the center is not blocked by an exclusive object OCF|=OCF_Chop; - // OCF_Rotate: Can be rotated - if (Def->Rotateable) + // OCF_Rotate: Can be rotated + if (Def->Rotateable) // Don't rotate minimum (invisible) construction sites - if (Con>100) - OCF|=OCF_Rotate; - // OCF_Exclusive: No action through this, no construction in front of this - if (Def->Exclusive) - OCF|=OCF_Exclusive; - // OCF_Entrance: Can currently be entered/activated - if ((Def->Entrance.Wdt>0) && (Def->Entrance.Hgt>0)) - if ((OCF & OCF_FullCon) && ((Def->RotatedEntrance == 1) || (r <= Def->RotatedEntrance))) - OCF|=OCF_Entrance; - // HitSpeeds - if (cspeed>=HitSpeed1) OCF|=OCF_HitSpeed1; - if (cspeed>=HitSpeed2) OCF|=OCF_HitSpeed2; - if (cspeed>=HitSpeed3) OCF|=OCF_HitSpeed3; - if (cspeed>=HitSpeed4) OCF|=OCF_HitSpeed4; - // OCF_Collection - if ((OCF & OCF_FullCon) || Def->IncompleteActivity) - if ((Def->Collection.Wdt>0) && (Def->Collection.Hgt>0)) - if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled))) - if (NoCollectDelay==0) - OCF|=OCF_Collection; - // OCF_Living + if (Con>100) + OCF|=OCF_Rotate; + // OCF_Exclusive: No action through this, no construction in front of this + if (Def->Exclusive) + OCF|=OCF_Exclusive; + // OCF_Entrance: Can currently be entered/activated + if ((Def->Entrance.Wdt>0) && (Def->Entrance.Hgt>0)) + if ((OCF & OCF_FullCon) && ((Def->RotatedEntrance == 1) || (r <= Def->RotatedEntrance))) + OCF|=OCF_Entrance; + // HitSpeeds + if (cspeed>=HitSpeed1) OCF|=OCF_HitSpeed1; + if (cspeed>=HitSpeed2) OCF|=OCF_HitSpeed2; + if (cspeed>=HitSpeed3) OCF|=OCF_HitSpeed3; + if (cspeed>=HitSpeed4) OCF|=OCF_HitSpeed4; + // OCF_Collection + if ((OCF & OCF_FullCon) || Def->IncompleteActivity) + if ((Def->Collection.Wdt>0) && (Def->Collection.Hgt>0)) + if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled))) + if (NoCollectDelay==0) + OCF|=OCF_Collection; + // OCF_Living if (Category & C4D_Living) { - OCF|=OCF_Living; + OCF|=OCF_Living; if (Alive) OCF|=OCF_Alive; } - // OCF_FightReady - if (OCF & OCF_Alive) - if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled))) + // OCF_FightReady + if (OCF & OCF_Alive) + if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled))) if (!Def->NoFight) OCF|=OCF_FightReady; // OCF_LineConstruct - if (OCF & OCF_FullCon) + if (OCF & OCF_FullCon) if (Def->LineConnect) OCF|=OCF_LineConstruct; // OCF_Prey @@ -798,17 +798,17 @@ void C4Object::SetOCF() C4RCOCF rc = { dwOCFOld, OCF, false }; AddDbgRec(RCT_OCF, &rc, sizeof(rc)); #endif - } + } void C4Object::UpdateOCF() - { + { C4PropList* pActionDef = GetAction(); #ifdef DEBUGREC_OCF uint32_t dwOCFOld = OCF; #endif // Update the object character flag according to the object's current situation - FIXED cspeed=GetSpeed(); + FIXED cspeed=GetSpeed(); #ifdef _DEBUG if(Contained && !::Objects.ObjectNumber(Contained)) { LogF("Warning: contained in wild object %p!", static_cast(Contained)); } @@ -825,37 +825,37 @@ void C4Object::UpdateOCF() | OCF_Rotate | OCF_OnFire | OCF_Inflammable | OCF_Living | OCF_Alive | OCF_LineConstruct | OCF_Prey | OCF_CrewMember | OCF_AttractLightning | OCF_PowerConsumer); - // OCF_Carryable: Can be picked up - if (GetPropertyInt(P_Collectible)) - OCF|=OCF_Carryable; - // OCF_Construct: Can be built outside - if (Def->Constructable && (ConEntrance.Wdt>0) && (Def->Entrance.Hgt>0)) - if ((OCF & OCF_FullCon) && ((Def->RotatedEntrance == 1) || (r <= Def->RotatedEntrance))) - OCF|=OCF_Entrance; - // OCF_Chop: Can be chopped + // OCF_Carryable: Can be picked up + if (GetPropertyInt(P_Collectible)) + OCF|=OCF_Carryable; + // OCF_Construct: Can be built outside + if (Def->Constructable && (ConEntrance.Wdt>0) && (Def->Entrance.Hgt>0)) + if ((OCF & OCF_FullCon) && ((Def->RotatedEntrance == 1) || (r <= Def->RotatedEntrance))) + OCF|=OCF_Entrance; + // OCF_Chop: Can be chopped DWORD cocf = OCF_Exclusive; - if (Def->Chopable) - if (Category & C4D_StaticBack) // Must be static back: this excludes trees that have already been chopped + if (Def->Chopable) + if (Category & C4D_StaticBack) // Must be static back: this excludes trees that have already been chopped if (!::Objects.AtObject(GetX(), GetY(), cocf)) // Can only be chopped if the center is not blocked by an exclusive object OCF|=OCF_Chop; - // HitSpeeds - if (cspeed>=HitSpeed1) OCF|=OCF_HitSpeed1; - if (cspeed>=HitSpeed2) OCF|=OCF_HitSpeed2; - if (cspeed>=HitSpeed3) OCF|=OCF_HitSpeed3; - if (cspeed>=HitSpeed4) OCF|=OCF_HitSpeed4; - // OCF_Collection - if ((OCF & OCF_FullCon) || Def->IncompleteActivity) - if ((Def->Collection.Wdt>0) && (Def->Collection.Hgt>0)) - if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled))) - if (NoCollectDelay==0) - OCF|=OCF_Collection; - // OCF_FightReady - if (OCF & OCF_Alive) - if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled))) + // HitSpeeds + if (cspeed>=HitSpeed1) OCF|=OCF_HitSpeed1; + if (cspeed>=HitSpeed2) OCF|=OCF_HitSpeed2; + if (cspeed>=HitSpeed3) OCF|=OCF_HitSpeed3; + if (cspeed>=HitSpeed4) OCF|=OCF_HitSpeed4; + // OCF_Collection + if ((OCF & OCF_FullCon) || Def->IncompleteActivity) + if ((Def->Collection.Wdt>0) && (Def->Collection.Hgt>0)) + if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled))) + if (NoCollectDelay==0) + OCF|=OCF_Collection; + // OCF_FightReady + if (OCF & OCF_Alive) + if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled))) if (!Def->NoFight) OCF|=OCF_FightReady; // OCF_NotContained @@ -896,21 +896,21 @@ void C4Object::UpdateOCF() assert (updateOCF == OCF); DEBUGREC_ON #endif - } + } bool C4Object::ExecFire(int32_t iFireNumber, int32_t iCausedByPlr) - { - // Fire Phase - FirePhase++; if (FirePhase>=MaxFirePhase) FirePhase=0; - // Decay + { + // Fire Phase + FirePhase++; if (FirePhase>=MaxFirePhase) FirePhase=0; + // Decay if (!Def->NoBurnDecay) DoCon(-100); - // Damage - if (!::Game.iTick10) if (!Def->NoBurnDamage) DoDamage(+2,iCausedByPlr,C4FxCall_DmgFire); - // Energy - if (!::Game.iTick5) DoEnergy(-1,false,C4FxCall_EngFire, iCausedByPlr); - // Effects - int32_t smoke_level=2*Shape.Wdt/3; + // Damage + if (!::Game.iTick10) if (!Def->NoBurnDamage) DoDamage(+2,iCausedByPlr,C4FxCall_DmgFire); + // Energy + if (!::Game.iTick5) DoEnergy(-1,false,C4FxCall_EngFire, iCausedByPlr); + // Effects + int32_t smoke_level=2*Shape.Wdt/3; int32_t smoke_rate=Def->SmokeRate; if (smoke_rate) { @@ -918,31 +918,31 @@ bool C4Object::ExecFire(int32_t iFireNumber, int32_t iCausedByPlr) if (!((Game.FrameCounter+(Number*7))%Max(smoke_rate,3)) || (Abs(xdir)>2)) Smoke(GetX(), GetY(),smoke_level); } - // Background Effects - if (!::Game.iTick5) - { - int32_t mat; - if (MatValid(mat=GBackMat(GetX(), GetY()))) - { + // Background Effects + if (!::Game.iTick5) + { + int32_t mat; + if (MatValid(mat=GBackMat(GetX(), GetY()))) + { // Extinguish - if (::MaterialMap.Map[mat].Extinguisher) - { Extinguish(iFireNumber); if (GBackLiquid(GetX(), GetY())) StartSoundEffect("Pshshsh",false,100,this); } + if (::MaterialMap.Map[mat].Extinguisher) + { Extinguish(iFireNumber); if (GBackLiquid(GetX(), GetY())) StartSoundEffect("Pshshsh",false,100,this); } // Inflame if (!Random(3)) ::Landscape.Incinerate(GetX(), GetY()); - } - } + } + } - return true; - } + return true; + } bool C4Object::ExecLife() - { + { - // Growth - if (!::Game.iTick35) + // Growth + if (!::Game.iTick35) // Growth specified by definition - if (Def->Growth) + if (Def->Growth) // Alive livings && trees only if ( ((Category & C4D_Living) && Alive) || (Category & C4D_StaticBack) ) @@ -953,16 +953,16 @@ bool C4Object::ExecLife() // Grow DoCon(Def->Growth*100); - // Magic reload - int32_t transfer; - if (!::Game.iTick3) if (Alive) - if (Contained) - if (!Hostile(Owner,Contained->Owner)) - if (MagicEnergyMagic) - { - transfer=Min(Min(2*MagicPhysicalFactor,Contained->MagicEnergy),GetPhysical()->Magic-MagicEnergy) / MagicPhysicalFactor; - if (transfer) - { + // Magic reload + int32_t transfer; + if (!::Game.iTick3) if (Alive) + if (Contained) + if (!Hostile(Owner,Contained->Owner)) + if (MagicEnergyMagic) + { + transfer=Min(Min(2*MagicPhysicalFactor,Contained->MagicEnergy),GetPhysical()->Magic-MagicEnergy) / MagicPhysicalFactor; + if (transfer) + { // do energy transfer via script, so it can be overloaded by No-Magic-Energy-rule // always use global func instead of local to save double search C4AulFunc *pMagicEnergyFn = ::ScriptEngine.GetFuncRecursive(PSF_DoMagicEnergy); @@ -975,12 +975,12 @@ bool C4Object::ExecLife() pMagicEnergyFn->Exec(NULL, &pars); } } - } - } + } + } - // Breathing - if (!::Game.iTick5) - if (Alive && !Def->NoBreath) + // Breathing + if (!::Game.iTick5) + if (Alive && !Def->NoBreath) { // Supply check bool Breathe=false; @@ -992,42 +992,42 @@ bool C4Object::ExecLife() else { if (!GBackSemiSolid(GetX(), GetY()+Shape.GetY()/2)) Breathe=true; } if (Contained) Breathe=true; - // No supply - if (!Breathe) - { + // No supply + if (!Breathe) + { // Reduce breath, then energy, bubble - if (Breath > 0) DoBreath(-2); - else DoEnergy(-1,false,C4FxCall_EngAsphyxiation, NO_OWNER); - BubbleOut(GetX() + Random(5) - 2, GetY() + Shape.GetY() / 2); + if (Breath > 0) DoBreath(-2); + else DoEnergy(-1,false,C4FxCall_EngAsphyxiation, NO_OWNER); + BubbleOut(GetX() + Random(5) - 2, GetY() + Shape.GetY() / 2); ViewEnergy = C4ViewDelay; // Physical training TrainPhysical(&C4PhysicalInfo::Breath, 2, C4MaxPhysical); } - // Supply - else - { + // Supply + else + { // Take breath - int32_t takebreath=GetPhysical()->Breath-Breath; + int32_t takebreath=GetPhysical()->Breath-Breath; if(takebreath > 0) DoBreath(takebreath); - } + } } // Corrosion energy loss - if (!::Game.iTick10) - if (Alive) + if (!::Game.iTick10) + if (Alive) if (InMat!=MNone) if (::MaterialMap.Map[InMat].Corrosive) if (!GetPhysical()->CorrosionResist) DoEnergy(-::MaterialMap.Map[InMat].Corrosive/15,false,C4FxCall_EngCorrosion, NO_OWNER); // InMat incineration - if (!::Game.iTick10) + if (!::Game.iTick10) if (InMat!=MNone) if (::MaterialMap.Map[InMat].Incindiary) if (Def->ContactIncinerate) Incinerate(NO_OWNER); - // Nonlife normal energy loss + // Nonlife normal energy loss if (!::Game.iTick10) if (Energy) if (!(Category & C4D_Living)) // don't loose if assigned as Energy-holder @@ -1055,24 +1055,24 @@ bool C4Object::ExecLife() } - return true; - } + return true; + } void C4Object::ExecBase() - { - // Environmental action - if (!::Game.iTick35) - { - // Structures dig free snow - if ((Category & C4D_Structure) && !(Game.Rules & C4RULE_StructuresSnowIn)) - if (r==0) + { + // Environmental action + if (!::Game.iTick35) + { + // Structures dig free snow + if ((Category & C4D_Structure) && !(Game.Rules & C4RULE_StructuresSnowIn)) + if (r==0) { ::Landscape.DigFreeMat(GetX() + Shape.GetX(), GetY() + Shape.GetY(), Shape.Wdt, Shape.Hgt, MSnow); ::Landscape.DigFreeMat(GetX() + Shape.GetX(), GetY() + Shape.GetY(), Shape.Wdt, Shape.Hgt, MFlyAshes); } - } + } - } + } void C4Object::Execute() { @@ -1170,10 +1170,10 @@ void C4Object::GetOCFForPos(int32_t ctx, int32_t cty, DWORD &ocf) } void C4Object::AssignDeath(bool fForced) - { - C4Object *thing; + { + C4Object *thing; // Alive objects only - if (!Alive) return; + if (!Alive) return; // clear all effects // do not delete effects afterwards, because they might have denied removal // set alive-flag before, so objects know what's up @@ -1185,39 +1185,39 @@ void C4Object::AssignDeath(bool fForced) // if the object is alive again, abort here if the kill is not forced if (Alive && !fForced) return; // Action - SetActionByName("Dead"); + SetActionByName("Dead"); // Values - Select=0; + Select=0; Alive=0; - ClearCommands(); + ClearCommands(); if (Info) { Info->HasDied=true; ++Info->DeathCount; Info->Retire(); } - // Lose contents - while ((thing=Contents.GetObject())) thing->Exit(thing->GetX(),thing->GetY()); - // Remove from crew/cursor/view + // Lose contents + while ((thing=Contents.GetObject())) thing->Exit(thing->GetX(),thing->GetY()); + // Remove from crew/cursor/view C4Player *pPlr = ::Players.Get(Owner); - if (pPlr) pPlr->ClearPointers(this, true); + if (pPlr) pPlr->ClearPointers(this, true); // ensure objects that won't be affected by dead-plrview-decay are handled properly if (!pPlr || !(Category & C4D_Living) || !pPlr->FoWViewObjs.IsContained(this)) SetPlrViewRange(0); // Engine script call C4AulParSet pars(C4VInt(iDeathCausingPlayer)); - Call(PSF_Death, &pars); + Call(PSF_Death, &pars); // Update OCF. Done here because previously it would have been done in the next frame // Whats worse: Having the OCF change because of some unrelated script-call like // SetCategory, or slightly breaking compatibility? SetOCF(); - } + } bool C4Object::ChangeDef(C4ID idNew) - { - // Get new definition - C4Def *pDef=C4Id2Def(idNew); - if (!pDef) return false; + { + // Get new definition + C4Def *pDef=C4Id2Def(idNew); + if (!pDef) return false; // Containment storage C4Object *pContainer=Contained; // Exit container (no Ejection/Departure) @@ -1226,10 +1226,10 @@ bool C4Object::ChangeDef(C4ID idNew) SetAction(0); ResetProperty(::Strings.P[P_Action]); // Enforce ActIdle because SetAction may have failed due to NoOtherAction SetDir(0); // will drop any outdated flipdir - if (pSolidMaskData) { pSolidMaskData->Remove(true, false); delete pSolidMaskData; pSolidMaskData=NULL; } + if (pSolidMaskData) { pSolidMaskData->Remove(true, false); delete pSolidMaskData; pSolidMaskData=NULL; } Def->Count--; - // Def change - Def=pDef; + // Def change + Def=pDef; SetProperty(Strings.P[P_Prototype], C4VPropList(pDef)); id=pDef->id; Def->Count++; @@ -1260,8 +1260,8 @@ bool C4Object::ChangeDef(C4ID idNew) // Containment (no Entrance) if (pContainer) Enter(pContainer,false); // Done - return true; - } + return true; + } bool C4Object::Incinerate(int32_t iCausedBy, bool fBlasted, C4Object *pIncineratingObject) { @@ -1277,9 +1277,9 @@ bool C4Object::Incinerate(int32_t iCausedBy, bool fBlasted, C4Object *pIncinerat } bool C4Object::Extinguish(int32_t iFireNumber) - { + { // any effects? - if (!pEffects) return false; + if (!pEffects) return false; // fire number known: extinguish that fire C4Effect *pEffFire; if (iFireNumber) @@ -1291,7 +1291,7 @@ bool C4Object::Extinguish(int32_t iFireNumber) else { // otherwise, kill all fires - // (keep checking from beginning of pEffects, as Kill might delete or change effects) + // (keep checking from beginning of pEffects, as Kill might delete or change effects) int32_t iFiresKilled = 0; while (pEffects && (pEffFire = pEffects->Get(C4Fx_AnyFire))) { @@ -1307,11 +1307,11 @@ bool C4Object::Extinguish(int32_t iFireNumber) if (!iFiresKilled) return false; } // done, success - return true; - } + return true; + } void C4Object::DoDamage(int32_t iChange, int32_t iCausedBy, int32_t iCause) - { + { // non-living: ask effects first if (pEffects && !Alive) { @@ -1319,17 +1319,17 @@ void C4Object::DoDamage(int32_t iChange, int32_t iCausedBy, int32_t iCause) if (!iChange) return; } // Change value - Damage = Max( Damage+iChange, 0 ); + Damage = Max( Damage+iChange, 0 ); // Engine script call - Call(PSF_Damage,&C4AulParSet(C4VInt(iChange), C4VInt(iCausedBy))); - } + Call(PSF_Damage,&C4AulParSet(C4VInt(iChange), C4VInt(iCausedBy))); + } void C4Object::DoEnergy(int32_t iChange, bool fExact, int32_t iCause, int32_t iCausedByPlr) - { + { // iChange 100% = Physical 100000 - if (!fExact) iChange=iChange*C4MaxPhysical/100; + if (!fExact) iChange=iChange*C4MaxPhysical/100; // Was zero? - bool fWasZero=(Energy==0); + bool fWasZero=(Energy==0); // Mark last damage causing player to trace kills if (iChange < 0) UpdatLastEnergyLossCause(iCausedByPlr); // Living things: ask effects for change first @@ -1340,14 +1340,14 @@ void C4Object::DoEnergy(int32_t iChange, bool fExact, int32_t iCause, int32_t iC } // Do change iChange = BoundBy(iChange, -Energy, GetPhysical()->Energy - Energy); - Energy += iChange; + Energy += iChange; // call to object Call(PSF_EnergyChange,&C4AulParSet(C4VInt(iChange), C4VInt(iCause), C4VInt(iCausedByPlr))); // Alive and energy reduced to zero: death - if (Alive) if (Energy==0) if (!fWasZero) AssignDeath(false); + if (Alive) if (Energy==0) if (!fWasZero) AssignDeath(false); // View change ViewEnergy = C4ViewDelay; - } + } void C4Object::UpdatLastEnergyLossCause(int32_t iNewCausePlr) { @@ -1361,29 +1361,29 @@ void C4Object::UpdatLastEnergyLossCause(int32_t iNewCausePlr) } void C4Object::DoBreath(int32_t iChange) - { + { // iChange 100% = Physical 100000 - iChange=iChange*C4MaxPhysical/100; + iChange=iChange*C4MaxPhysical/100; // Do change iChange = BoundBy(iChange, -Breath, GetPhysical()->Breath - Breath); - Breath += iChange; + Breath += iChange; // call to object Call(PSF_BreathChange,&C4AulParSet(C4VInt(iChange))); // View change ViewEnergy = C4ViewDelay; - } + } void C4Object::Blast(int32_t iLevel, int32_t iCausedBy) - { + { // Damage - DoDamage(iLevel,iCausedBy,C4FxCall_DmgBlast); + DoDamage(iLevel,iCausedBy,C4FxCall_DmgBlast); // Energy (alive objects) - if (Alive) DoEnergy(-iLevel/3,false,C4FxCall_EngBlast, iCausedBy); - // Incinerate - if (Def->BlastIncinerate) - if (Damage>=Def->BlastIncinerate) - Incinerate(iCausedBy,true); - } + if (Alive) DoEnergy(-iLevel/3,false,C4FxCall_EngBlast, iCausedBy); + // Incinerate + if (Def->BlastIncinerate) + if (Damage>=Def->BlastIncinerate) + Incinerate(iCausedBy,true); + } void C4Object::DoCon(int32_t iChange, bool fInitial, bool fNoComponentChange) { @@ -1403,16 +1403,16 @@ void C4Object::DoCon(int32_t iChange, bool fInitial, bool fNoComponentChange) // Update OCF SetOCF(); - // If step changed or limit reached or degraded from full: update mass, face, components, etc. - if ( iStepDiff || (Con>=FullCon) || (Con==0) || (fWasFull && (ConRemove(true, false); - // Face - UpdateFace(true); + // If step changed or limit reached or degraded from full: update mass, face, components, etc. + if ( iStepDiff || (Con>=FullCon) || (Con==0) || (fWasFull && (ConRemove(true, false); + // Face + UpdateFace(true); // component update if (!fNoComponentChange) { @@ -1423,8 +1423,8 @@ void C4Object::DoCon(int32_t iChange, bool fInitial, bool fNoComponentChange) else ComponentConGain(); } - // Unfullcon - if (ConIncompleteActivity) @@ -1477,21 +1477,21 @@ void C4Object::DoCon(int32_t iChange, bool fInitial, bool fNoComponentChange) } void C4Object::DoExperience(int32_t change) - { - const int32_t MaxExperience = 100000000; + { + const int32_t MaxExperience = 100000000; - if (!Info) return; + if (!Info) return; - Info->Experience=BoundBy(Info->Experience+change,0,MaxExperience); + Info->Experience=BoundBy(Info->Experience+change,0,MaxExperience); - // Promotion check + // Promotion check if (Info->ExperienceExperience>=::DefaultRanks.Experience(Info->Rank+1)) Promote(Info->Rank+1, false, false); - } + } bool C4Object::Exit(int32_t iX, int32_t iY, int32_t iR, FIXED iXDir, FIXED iYDir, FIXED iRDir, bool fCalls) - { + { // 1. Exit the current container. // 2. Update Contents of container object and set Contained to NULL. // 3. Set offset position/motion if desired. @@ -1499,30 +1499,30 @@ bool C4Object::Exit(int32_t iX, int32_t iY, int32_t iR, FIXED iXDir, FIXED iYDir // Not contained C4Object *pContainer=Contained; - if (!pContainer) return false; - // Remove object from container - pContainer->Contents.Remove(this); - pContainer->UpdateMass(); - pContainer->SetOCF(); - // No container - Contained=NULL; + if (!pContainer) return false; + // Remove object from container + pContainer->Contents.Remove(this); + pContainer->UpdateMass(); + pContainer->SetOCF(); + // No container + Contained=NULL; // Position/motion r=iR; fix_x=itofix(iX); fix_y=itofix(iY); fix_r=itofix(r); BoundsCheck(fix_x, fix_y); xdir=iXDir; ydir=iYDir; rdir=iRDir; // Misc updates - Mobile=1; - InLiquid=0; - CloseMenu(true); - UpdateFace(true); - SetOCF(); + Mobile=1; + InLiquid=0; + CloseMenu(true); + UpdateFace(true); + SetOCF(); // Engine calls if (fCalls) pContainer->Call(PSF_Ejection,&C4AulParSet(C4VObj(this))); if (fCalls) Call(PSF_Departure,&C4AulParSet(C4VObj(pContainer))); // Success (if the obj wasn't "re-entered" by script) - return !Contained; - } + return !Contained; + } bool C4Object::Enter(C4Object *pTarget, bool fCalls, bool fCopyMotion, bool *pfRejectCollect) { @@ -1579,10 +1579,10 @@ bool C4Object::Enter(C4Object *pTarget, bool fCalls, bool fCopyMotion, bool *pfR CopyMotion(Contained); } SetOCF(); - UpdateFace(true); - // Update container - Contained->UpdateMass(); - Contained->SetOCF(); + UpdateFace(true); + // Update container + Contained->UpdateMass(); + Contained->SetOCF(); // Collection call if (fCalls) pTarget->Call(PSF_Collection2,&C4AulParSet(C4VObj(this))); if (!Contained || !Contained->Status || !pTarget->Status) return true; @@ -1590,61 +1590,61 @@ bool C4Object::Enter(C4Object *pTarget, bool fCalls, bool fCopyMotion, bool *pfR if (fCalls) Call(PSF_Entrance,&C4AulParSet(C4VObj(Contained))); if (!Contained || !Contained->Status || !pTarget->Status) return true; // Success - return true; - } + return true; + } void C4Object::Fling(FIXED txdir, FIXED tydir, bool fAddSpeed) - { + { if (fAddSpeed) { txdir+=xdir/2; tydir+=ydir/2; } - if (!ObjectActionTumble(this,(txdir<0),txdir,tydir)) - if (!ObjectActionJump(this,txdir,tydir,false)) + if (!ObjectActionTumble(this,(txdir<0),txdir,tydir)) + if (!ObjectActionJump(this,txdir,tydir,false)) { xdir=txdir; ydir=tydir; Mobile=1; Action.t_attach&=~CNAT_Bottom; } - } + } bool C4Object::ActivateEntrance(int32_t by_plr, C4Object *by_obj) - { + { - // Try entrance activation - if (OCF & OCF_Entrance) - if (!! Call(PSF_ActivateEntrance,&C4AulParSet(C4VObj(by_obj)))) - return true; + // Try entrance activation + if (OCF & OCF_Entrance) + if (!! Call(PSF_ActivateEntrance,&C4AulParSet(C4VObj(by_obj)))) + return true; // Failure - return false; - } + return false; + } bool C4Object::Build(int32_t iLevel, C4Object *pBuilder) - { + { int32_t cnt; C4ID NeededMaterial; int32_t NeededMaterialCount = 0; C4Object *pMaterial; - // Invalid or complete: no build - if (!Status || !Def || (Con>=FullCon)) return false; + // Invalid or complete: no build + if (!Status || !Def || (Con>=FullCon)) return false; - // Material check (if rule set or any other than structure or castle-part) + // Material check (if rule set or any other than structure or castle-part) bool fNeedMaterial = (Game.Rules & C4RULE_ConstructionNeedsMaterial) || !(Category & (C4D_Structure|C4D_StaticBack)); - if (fNeedMaterial) - { + if (fNeedMaterial) + { // Determine needed components (may be overloaded) C4IDList NeededComponents; Def->GetComponents(&NeededComponents, NULL, pBuilder); - // Grab any needed components from builder + // Grab any needed components from builder C4ID idMat; - for (cnt=0; (idMat=NeededComponents.GetID(cnt)); cnt++) - if (Component.GetIDCount(idMat)Contents.Find(idMat))) - if (!pMaterial->OnFire) if (pMaterial->OCF & OCF_FullCon) - { - Component.SetIDCount(idMat,Component.GetIDCount(idMat)+1, true); - pBuilder->Contents.Remove(pMaterial); - pMaterial->AssignRemoval(); - } + for (cnt=0; (idMat=NeededComponents.GetID(cnt)); cnt++) + if (Component.GetIDCount(idMat)Contents.Find(idMat))) + if (!pMaterial->OnFire) if (pMaterial->OCF & OCF_FullCon) + { + Component.SetIDCount(idMat,Component.GetIDCount(idMat)+1, true); + pBuilder->Contents.Remove(pMaterial); + pMaterial->AssignRemoval(); + } // Grab any needed components from container if (Contained) for (cnt=0; (idMat=NeededComponents.GetID(cnt)); cnt++) @@ -1656,7 +1656,7 @@ bool C4Object::Build(int32_t iLevel, C4Object *pBuilder) Contained->Contents.Remove(pMaterial); pMaterial->AssignRemoval(); } - // Check for needed components at current con + // Check for needed components at current con for (cnt=0; (idMat=NeededComponents.GetID(cnt)); cnt++) if (NeededComponents.GetCount(cnt)!=0) if ( (100*Component.GetIDCount(idMat)/NeededComponents.GetCount(cnt)) < (100*Con/FullCon) ) @@ -1683,7 +1683,7 @@ bool C4Object::Build(int32_t iLevel, C4Object *pBuilder) } // Still in need: done/fail return false; - } + } // Do con (mass- and builder-relative) int32_t iBuildSpeed=100; C4PhysicalInfo *pPhys; @@ -1711,114 +1711,114 @@ bool C4Object::Build(int32_t iLevel, C4Object *pBuilder) } bool C4Object::Chop(C4Object *pByObject) - { - // Valid check - if (!Status || !Def || Contained || !(OCF & OCF_Chop)) - return false; - // Chop - if (!::Game.iTick10) DoDamage( +10, pByObject ? pByObject->Owner : NO_OWNER, C4FxCall_DmgChop); - return true; - } + { + // Valid check + if (!Status || !Def || Contained || !(OCF & OCF_Chop)) + return false; + // Chop + if (!::Game.iTick10) DoDamage( +10, pByObject ? pByObject->Owner : NO_OWNER, C4FxCall_DmgChop); + return true; + } bool C4Object::Push(FIXED txdir, FIXED dforce, bool fStraighten) - { - // Valid check - if (!Status || !Def || Contained || !(OCF & OCF_Grab)) return false; - // Grabbing okay, no pushing - if (Def->Grab==2) return true; - // Mobilization check (pre-mobilization zero) - if (!Mobile) - { xdir=ydir=Fix0; } - // General pushing force vs. object mass - dforce=dforce*100/Mass; - // Set dir - if (xdir<0) SetDir(DIR_Left); - if (xdir>0) SetDir(DIR_Right); - // Work towards txdir - if (Abs(xdir-txdir)<=dforce) // Close-enough-set - { xdir=txdir; } - else // Work towards - { - if (xdirtxdir) xdir-=dforce; - } - // Straighten - if (fStraighten) - { - if (Inside(r,-StableRange,+StableRange)) - { - rdir=0; // cheap way out - } - else - { - if (r>0) { if (rdir>-RotateAccel) rdir-=dforce; } - else { if (rdir<+RotateAccel) rdir+=dforce; } - } - } + { + // Valid check + if (!Status || !Def || Contained || !(OCF & OCF_Grab)) return false; + // Grabbing okay, no pushing + if (Def->Grab==2) return true; + // Mobilization check (pre-mobilization zero) + if (!Mobile) + { xdir=ydir=Fix0; } + // General pushing force vs. object mass + dforce=dforce*100/Mass; + // Set dir + if (xdir<0) SetDir(DIR_Left); + if (xdir>0) SetDir(DIR_Right); + // Work towards txdir + if (Abs(xdir-txdir)<=dforce) // Close-enough-set + { xdir=txdir; } + else // Work towards + { + if (xdirtxdir) xdir-=dforce; + } + // Straighten + if (fStraighten) + { + if (Inside(r,-StableRange,+StableRange)) + { + rdir=0; // cheap way out + } + else + { + if (r>0) { if (rdir>-RotateAccel) rdir-=dforce; } + else { if (rdir<+RotateAccel) rdir+=dforce; } + } + } - // Mobilization check - if (!!xdir || !!ydir || !!rdir) Mobile=1; + // Mobilization check + if (!!xdir || !!ydir || !!rdir) Mobile=1; - // Stuck check - if (!::Game.iTick35) if (txdir) if (!Def->NoHorizontalMove) - if (ContactCheck(GetX(), GetY())) // Resets t_contact - { + // Stuck check + if (!::Game.iTick35) if (txdir) if (!Def->NoHorizontalMove) + if (ContactCheck(GetX(), GetY())) // Resets t_contact + { GameMsgObject(FormatString(LoadResStr("IDS_OBJ_STUCK"),GetName()).getData(),this); - Call(PSF_Stuck); - } + Call(PSF_Stuck); + } - return true; - } + return true; + } bool C4Object::Lift(FIXED tydir, FIXED dforce) - { - // Valid check - if (!Status || !Def || Contained) return false; - // Mobilization check - if (!Mobile) - { xdir=ydir=Fix0; Mobile=1; } - // General pushing force vs. object mass - dforce=dforce*100/Mass; - // If close enough, set tydir - if (Abs(tydir-ydir)<=Abs(dforce)) - ydir=tydir; - else // Work towards tydir - { - if (ydirtydir) ydir-=dforce; - } - // Stuck check - if (tydir != -GravAccel) - if (ContactCheck(GetX(), GetY())) // Resets t_contact - { + { + // Valid check + if (!Status || !Def || Contained) return false; + // Mobilization check + if (!Mobile) + { xdir=ydir=Fix0; Mobile=1; } + // General pushing force vs. object mass + dforce=dforce*100/Mass; + // If close enough, set tydir + if (Abs(tydir-ydir)<=Abs(dforce)) + ydir=tydir; + else // Work towards tydir + { + if (ydirtydir) ydir-=dforce; + } + // Stuck check + if (tydir != -GravAccel) + if (ContactCheck(GetX(), GetY())) // Resets t_contact + { GameMsgObject(FormatString(LoadResStr("IDS_OBJ_STUCK"),GetName()).getData(),this); - Call(PSF_Stuck); - } - return true; - } + Call(PSF_Stuck); + } + return true; + } C4Object* C4Object::CreateContents(C4PropList * PropList) - { - C4Object *nobj; - if (!(nobj=Game.CreateObject(PropList,this,Owner))) return NULL; - if (!nobj->Enter(this)) { nobj->AssignRemoval(); return NULL; } - return nobj; - } + { + C4Object *nobj; + if (!(nobj=Game.CreateObject(PropList,this,Owner))) return NULL; + if (!nobj->Enter(this)) { nobj->AssignRemoval(); return NULL; } + return nobj; + } bool C4Object::CreateContentsByList(C4IDList &idlist) - { - int32_t cnt,cnt2; - for (cnt=0; idlist.GetID(cnt); cnt++) - for (cnt2=0; cnt2IsActive()) if (!Menu->TryClose(fForce, false)) return false; if (!Menu->IsCloseQuerying()) { delete Menu; Menu=NULL; } // protect menu deletion from recursive menu operation calls } return true; - } + } void C4Object::AutoContextMenu(int32_t iMenuSelect) { @@ -2030,20 +2030,20 @@ BYTE C4Object::GetEntranceArea(int32_t &aX, int32_t &aY, int32_t &aWdt, int32_t } BYTE C4Object::GetMomentum(FIXED &rxdir, FIXED &rydir) - { - rxdir=rydir=0; - if (!Status || !Def) return 0; - rxdir=xdir; rydir=ydir; - return 1; - } + { + rxdir=rydir=0; + if (!Status || !Def) return 0; + rxdir=xdir; rydir=ydir; + return 1; + } FIXED C4Object::GetSpeed() - { - FIXED cobjspd=Fix0; - if (xdir<0) cobjspd-=xdir; else cobjspd+=xdir; - if (ydir<0) cobjspd-=ydir; else cobjspd+=ydir; - return cobjspd; - } + { + FIXED cobjspd=Fix0; + if (xdir<0) cobjspd-=xdir; else cobjspd+=xdir; + if (ydir<0) cobjspd-=ydir; else cobjspd+=ydir; + return cobjspd; + } void C4Object::SetName(const char * NewName) { @@ -2054,7 +2054,7 @@ void C4Object::SetName(const char * NewName) } int32_t C4Object::GetValue(C4Object *pInBase, int32_t iForPlayer) - { + { int32_t iValue; // value by script? @@ -2067,8 +2067,8 @@ int32_t C4Object::GetValue(C4Object *pInBase, int32_t iForPlayer) // - and not the value if you had to buy the object in this particular base iValue=Def->GetValue(NULL, iForPlayer); } - // Con percentage - iValue=iValue*Con/FullCon; + // Con percentage + iValue=iValue*Con/FullCon; // value adjustments buy base function if (pInBase) { @@ -2077,15 +2077,15 @@ int32_t C4Object::GetValue(C4Object *pInBase, int32_t iForPlayer) iValue = pFn->Exec(pInBase, &C4AulParSet(C4VObj(this), C4VInt(iValue))).getInt(); } // Return value - return iValue; - } + return iValue; + } C4PhysicalInfo* C4Object::GetPhysical(bool fPermanent) - { + { // Temporary physical if (PhysicalTemporary && !fPermanent) return &TemporaryPhysical; // Info physical: Available only if there's an info and it should be used - if (Info) + if (Info) { if (!Game.Parameters.UseFairCrew) return &(Info->Physical); @@ -2097,8 +2097,8 @@ C4PhysicalInfo* C4Object::GetPhysical(bool fPermanent) return Def->GetFairCrewPhysicals(); } // Definition physical - return &(Def->Physical); - } + return &(Def->Physical); + } bool C4Object::TrainPhysical(C4PhysicalInfo::Offset mpiOffset, int32_t iTrainBy, int32_t iMaxTrain) { @@ -2166,16 +2166,16 @@ bool C4Object::Promote(int32_t torank, bool exception, bool fForceRankName) } void C4Object::ClearPointers(C4Object *pObj) - { + { // effects if (pEffects) pEffects->ClearPointers(pObj); // contents/contained: not necessary, because it's done in AssignRemoval and StatusDeactivate // Action targets - if (Action.Target==pObj) Action.Target=NULL; - if (Action.Target2==pObj) Action.Target2=NULL; + if (Action.Target==pObj) Action.Target=NULL; + if (Action.Target2==pObj) Action.Target2=NULL; // Commands C4Command *cCom; - for (cCom=Command; cCom; cCom=cCom->Next) + for (cCom=Command; cCom; cCom=cCom->Next) cCom->ClearPointers(pObj); // Menu if (Menu) Menu->ClearPointers(pObj); @@ -2193,7 +2193,7 @@ void C4Object::ClearPointers(C4Object *pObj) RemoveGraphicsOverlay(pGfxOvrl->GetID()); } } - } + } C4Value C4Object::Call(const char *szFunctionCall, C4AulParSet *pPars, bool fPassError) { @@ -2242,7 +2242,7 @@ void C4Object::Draw(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode) // Set audibility if (!eDrawMode) SetAudibilityAt(cgo, GetX(), GetY()); - // Output boundary + // Output boundary if (!fYStretchObject && !eDrawMode) { if (pActionDef && !r && !pActionDef->GetPropertyInt(P_FacetBase) && Con<=FullCon) @@ -2263,33 +2263,33 @@ void C4Object::Draw(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode) if (GetGraphics()->Type == C4DefGraphics::TYPE_Bitmap) if (GetGraphics()->Bmp.BitmapClr) GetGraphics()->Bmp.BitmapClr->SetClr(Color); - // Debug Display ////////////////////////////////////////////////////////////////////// - if (::GraphicsSystem.ShowCommand && !eDrawMode) - { - C4Command *pCom; - int32_t ccx=GetX(),ccy=GetY(); - int32_t x1,y1,x2,y2; - char szCommand[200]; - StdStrBuf Cmds; + // Debug Display ////////////////////////////////////////////////////////////////////// + if (::GraphicsSystem.ShowCommand && !eDrawMode) + { + C4Command *pCom; + int32_t ccx=GetX(),ccy=GetY(); + int32_t x1,y1,x2,y2; + char szCommand[200]; + StdStrBuf Cmds; int32_t iMoveTos=0; - for (pCom=Command; pCom; pCom=pCom->Next) - { + for (pCom=Command; pCom; pCom=pCom->Next) + { switch (pCom->Command) - { - case C4CMD_MoveTo: + { + case C4CMD_MoveTo: // Angle int32_t iAngle; iAngle=Angle(ccx,ccy,pCom->Tx._getInt(),pCom->Ty); while (iAngle>180) iAngle-=360; // Path - x1=ccx-cotx; y1=ccy-coty; - x2=pCom->Tx._getInt()-cotx; y2=pCom->Ty-coty; - Application.DDraw->DrawLine(cgo.Surface,cgo.X+x1,cgo.Y+y1,cgo.X+x2,cgo.Y+y2,CRed); - Application.DDraw->DrawFrame(cgo.Surface,cgo.X+x2-1,cgo.Y+y2-1,cgo.X+x2+1,cgo.Y+y2+1,CRed); - if (x1>x2) Swap(x1,x2); if (y1>y2) Swap(y1,y2); - ccx=pCom->Tx._getInt(); ccy=pCom->Ty; + x1=ccx-cotx; y1=ccy-coty; + x2=pCom->Tx._getInt()-cotx; y2=pCom->Ty-coty; + Application.DDraw->DrawLine(cgo.Surface,cgo.X+x1,cgo.Y+y1,cgo.X+x2,cgo.Y+y2,CRed); + Application.DDraw->DrawFrame(cgo.Surface,cgo.X+x2-1,cgo.Y+y2-1,cgo.X+x2+1,cgo.Y+y2+1,CRed); + if (x1>x2) Swap(x1,x2); if (y1>y2) Swap(y1,y2); + ccx=pCom->Tx._getInt(); ccy=pCom->Ty; // Message iMoveTos++; szCommand[0]=0; //sprintf(szCommand,"%s %d/%d",CommandName(pCom->Command),pCom->Tx,pCom->Ty,iAngle); - break; + break; case C4CMD_Put: sprintf(szCommand,"%s %s to %s",CommandName(pCom->Command),pCom->Target2 ? pCom->Target2->GetName() : pCom->Data ? pCom->Data.getC4ID().ToString() : "Content",pCom->Target ? pCom->Target->GetName() : ""); break; @@ -2311,19 +2311,19 @@ void C4Object::Draw(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode) break; case C4CMD_Transfer: // Path - x1=ccx-cotx; y1=ccy-coty; - x2=pCom->Tx._getInt()-cotx; y2=pCom->Ty-coty; - Application.DDraw->DrawLine(cgo.Surface,cgo.X+x1,cgo.Y+y1,cgo.X+x2,cgo.Y+y2,CGreen); - Application.DDraw->DrawFrame(cgo.Surface,cgo.X+x2-1,cgo.Y+y2-1,cgo.X+x2+1,cgo.Y+y2+1,CGreen); - if (x1>x2) Swap(x1,x2); if (y1>y2) Swap(y1,y2); - ccx=pCom->Tx._getInt(); ccy=pCom->Ty; + x1=ccx-cotx; y1=ccy-coty; + x2=pCom->Tx._getInt()-cotx; y2=pCom->Ty-coty; + Application.DDraw->DrawLine(cgo.Surface,cgo.X+x1,cgo.Y+y1,cgo.X+x2,cgo.Y+y2,CGreen); + Application.DDraw->DrawFrame(cgo.Surface,cgo.X+x2-1,cgo.Y+y2-1,cgo.X+x2+1,cgo.Y+y2+1,CGreen); + if (x1>x2) Swap(x1,x2); if (y1>y2) Swap(y1,y2); + ccx=pCom->Tx._getInt(); ccy=pCom->Ty; // Message sprintf(szCommand,"%s %s",CommandName(pCom->Command),pCom->Target ? pCom->Target->GetName() : ""); break; default: sprintf(szCommand,"%s %s",CommandName(pCom->Command),pCom->Target ? pCom->Target->GetName() : ""); break; - } + } // Compose command stack message if (szCommand[0]) { @@ -2332,17 +2332,17 @@ void C4Object::Draw(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode) // Current message Cmds.AppendChar('|'); if (pCom->Finished) Cmds.Append(""); - Cmds.Append(szCommand); + Cmds.Append(szCommand); if (pCom->Finished) Cmds.Append(""); } - } + } // Open MoveTo stack if (iMoveTos) { Cmds.AppendChar('|'); Cmds.AppendFormat("%dx MoveTo",iMoveTos); iMoveTos=0; } // Draw message int32_t cmwdt,cmhgt; ::GraphicsResource.FontRegular.GetTextExtent(Cmds.getData(),cmwdt,cmhgt,true); Application.DDraw->TextOut(Cmds.getData(), ::GraphicsResource.FontRegular, 1.0, cgo.Surface,cgo.X+cox-Shape.GetX(),cgo.Y+coy-10-cmhgt,CStdDDraw::DEFAULT_MESSAGE_COLOR,ACenter); - } - // Debug Display /////////////////////////////////////////////////////////////////////////////// + } + // Debug Display /////////////////////////////////////////////////////////////////////////////// // Don't draw (show solidmask) if (::GraphicsSystem.ShowSolidMask) @@ -2429,8 +2429,8 @@ void C4Object::Draw(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode) // local particles in front of the object if (FrontParticles) if (eDrawMode!=ODM_BaseOnly) FrontParticles.Draw(cgo,this); - // Select Mark - if (Select) + // Select Mark + if (Select) if (eDrawMode!=ODM_BaseOnly) if (ValidPlr(Owner)) if (Owner == iByPlayer) @@ -2487,17 +2487,17 @@ void C4Object::Draw(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode) Application.DDraw->TextOut(str.getData(), ::GraphicsResource.FontRegular, 1.0, cgo.Surface,cgo.X+cox-Shape.GetX(),cgo.Y+coy-cmhgt,InLiquid ? 0xfa0000FF : CStdDDraw::DEFAULT_MESSAGE_COLOR,ACenter); } } - // Debug Display /////////////////////////////////////////////////////////////////////// + // Debug Display /////////////////////////////////////////////////////////////////////// // Restore visibility inside FoW if (fOldClrModEnabled) lpDDraw->SetClrModMapEnabled(fOldClrModEnabled); - } + } void C4Object::DrawTopFace(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode) - { + { // Status - if (!Status || !Def) return; + if (!Status || !Def) return; // visible? if(!IsVisible(iByPlayer, eDrawMode==ODM_Overlay)) return; // target pos (parallax) @@ -2542,7 +2542,7 @@ void C4Object::DrawTopFace(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDraw // TopFace if (!(TopFace.Surface || (OCF & OCF_Construct))) return; // Output position - float offX = cgo.X + fixtof(fix_x) - cotx, offY = cgo.Y + fixtof(fix_y) - coty; + float offX = cgo.X + fixtof(fix_x) - cotx, offY = cgo.Y + fixtof(fix_y) - coty; float cox = fixtof(fix_x) + Shape.GetX() - cotx, coy = fixtof(fix_y) + Shape.GetY() - coty; // Output bounds check if (!Inside(cox,1-Shape.Wdt,cgo.Wdt) @@ -2598,7 +2598,7 @@ void C4Object::DrawTopFace(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDraw true, pDrawTransform ? &C4DrawTransform(*pDrawTransform, offX, offY) : NULL); // end of color modulation if (!eDrawMode) FinishedDrawing(); - } + } void C4Object::DrawLine(C4TargetFacet &cgo) { @@ -2615,7 +2615,7 @@ void C4Object::DrawLine(C4TargetFacet &cgo) { color0 = colors->GetItem(0).getInt(); color1 = colors->GetItem(1).getInt(); } - for (int32_t vtx=0; vtx+1Line) { case C4D_Line_Power: @@ -2635,9 +2635,9 @@ void C4Object::DrawLine(C4TargetFacet &cgo) void C4Object::CompileFunc(StdCompiler *pComp) { - bool fCompiler = pComp->isCompiler(); - if(fCompiler) - Clear(); + bool fCompiler = pComp->isCompiler(); + if(fCompiler) + Clear(); // Compile ID, search definition pComp->Value(mkNamingAdapt(id, "id", C4ID::None )); @@ -2989,7 +2989,7 @@ C4Object *C4Object::ComposeContents(C4ID id) C4IDList NeededComponents; pDef->GetComponents(&NeededComponents, NULL, this); // Check for sufficient components - StdStrBuf Needs; Needs.Format(LoadResStr("IDS_CON_BUILDMATNEED"),pDef->GetName()); + StdStrBuf Needs; Needs.Format(LoadResStr("IDS_CON_BUILDMATNEED"),pDef->GetName()); for (cnt=0; (c_id=NeededComponents.GetID(cnt)); cnt++) if (NeededComponents.GetCount(cnt) > Contents.ObjectCount(c_id)) { @@ -3088,33 +3088,33 @@ void C4Object::DrawSelectMark(C4TargetFacet &cgo, float Zoom) void C4Object::ClearCommands() { - C4Command *pNext; - while (Command) - { + C4Command *pNext; + while (Command) + { pNext=Command->Next; - if(!Command->iExec) + if(!Command->iExec) delete Command; else Command->iExec = 2; - Command=pNext; - } + Command=pNext; + } } void C4Object::ClearCommand(C4Command *pUntil) { - C4Command *pCom,*pNext; - for (pCom=Command; pCom; pCom=pNext) - { + C4Command *pCom,*pNext; + for (pCom=Command; pCom; pCom=pNext) + { // Last one to clear - if (pCom==pUntil) pNext=NULL; + if (pCom==pUntil) pNext=NULL; // Next one to clear after this - else pNext=pCom->Next; - Command=pCom->Next; + else pNext=pCom->Next; + Command=pCom->Next; if(!pCom->iExec) delete pCom; else pCom->iExec = 2; - } + } } bool C4Object::AddCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int32_t iTy, @@ -3130,7 +3130,7 @@ bool C4Object::AddCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int3 // Valid command safety if (!Inside(iCommand,C4CMD_First,C4CMD_Last)) return false; // Allocate and set new command - if (!(pCom=new C4Command)) return false; + if (!(pCom=new C4Command)) return false; pCom->Set(iCommand,this,pTarget,iTx,iTy,pTarget2,iData, iUpdateInterval,!fInitEvaluation,iRetries,szText,iBaseMode); // Append to bottom of stack @@ -3140,7 +3140,7 @@ bool C4Object::AddCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int3 if (pLast) pLast->Next=pCom; else Command=pCom; } - // Add to top of command stack + // Add to top of command stack else { pCom->Next=Command; @@ -3148,17 +3148,17 @@ bool C4Object::AddCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int3 } // Success //sprintf(OSTR,"%s command %s added: %i/%i %s %s (%i)",GetName(),CommandName(iCommand),iTx,iTy,pTarget ? pTarget->GetName() : "O",pTarget2 ? pTarget2->GetName() : "O",iUpdateInterval); Log(OSTR); - return true; + return true; } void C4Object::SetCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int32_t iTy, C4Object *pTarget2, bool fControl, C4Value iData, int32_t iRetries, C4String *szText) { - // Decrease NoCollectDelay - if (NoCollectDelay>0) NoCollectDelay--; + // Decrease NoCollectDelay + if (NoCollectDelay>0) NoCollectDelay--; // Clear stack - ClearCommands(); + ClearCommands(); // Close menu if (fControl) if (!CloseMenu(false)) return; @@ -3172,7 +3172,7 @@ void C4Object::SetCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int3 iData))) return; // Inside vehicle control overload - if (Contained) + if (Contained) if (Contained->Def->VehicleControl & C4D_VehicleControl_Inside) { Contained->Controller=Controller; @@ -3182,7 +3182,7 @@ void C4Object::SetCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int3 C4VInt(iTy), C4VObj(pTarget2), iData, - C4VObj(this)))) + C4VObj(this)))) return; } // Outside vehicle control overload @@ -3236,16 +3236,16 @@ void C4Object::DigOutMaterialCast(bool fRequest) { // Check material contents for sufficient object cast amounts if (!MaterialContents) return; - for (int32_t iMaterial=0; iMaterial< ::MaterialMap.Num; iMaterial++) - if (MaterialContents->Amount[iMaterial]) - if (::MaterialMap.Map[iMaterial].Dig2Object!=C4ID::None) - if (::MaterialMap.Map[iMaterial].Dig2ObjectRatio!=0) - if (fRequest || !::MaterialMap.Map[iMaterial].Dig2ObjectOnRequestOnly) - if (MaterialContents->Amount[iMaterial]>=::MaterialMap.Map[iMaterial].Dig2ObjectRatio) - { - Game.CreateObject(::MaterialMap.Map[iMaterial].Dig2Object,this,NO_OWNER,GetX(), GetY()+Shape.GetY()+Shape.Hgt,Random(360)); - MaterialContents->Amount[iMaterial]=0; - } + for (int32_t iMaterial=0; iMaterial< ::MaterialMap.Num; iMaterial++) + if (MaterialContents->Amount[iMaterial]) + if (::MaterialMap.Map[iMaterial].Dig2Object!=C4ID::None) + if (::MaterialMap.Map[iMaterial].Dig2ObjectRatio!=0) + if (fRequest || !::MaterialMap.Map[iMaterial].Dig2ObjectOnRequestOnly) + if (MaterialContents->Amount[iMaterial]>=::MaterialMap.Map[iMaterial].Dig2ObjectRatio) + { + Game.CreateObject(::MaterialMap.Map[iMaterial].Dig2Object,this,NO_OWNER,GetX(), GetY()+Shape.GetY()+Shape.Hgt,Random(360)); + MaterialContents->Amount[iMaterial]=0; + } } void C4Object::Resort() @@ -3409,7 +3409,7 @@ bool C4Object::SetActionByName(const char * szActName, } void C4Object::SetDir(int32_t iDir) - { + { // Not active C4PropList* pActionDef = GetAction(); if (!pActionDef) return; @@ -3426,7 +3426,7 @@ void C4Object::SetDir(int32_t iDir) UpdateFlipDir(); else Action.DrawDir=iDir; - } + } int32_t C4Object::GetProcedure() { @@ -3482,7 +3482,7 @@ void C4Object::NoAttachAction() DoGravity(this); Mobile=1; } - } + } bool ContactVtxCNAT(C4Object *cobj, BYTE cnat_dir); @@ -3717,14 +3717,14 @@ void C4Object::ContactAction() } void Towards(FIXED &val, FIXED target, FIXED step) - { - if (val==target) return; - if (Abs(val-target)<=step) { val=target; return; } - if (valAction.GetBridgeData(iBridgeTime, fMoveClonk, fWall, iBridgeMaterial); if (!iBridgeTime) iBridgeTime = 100; // default bridge time @@ -3748,7 +3748,7 @@ bool DoBridge(C4Object *clk) if (clk->Action.Time % dtp) return true; // no advancement in this frame // get target pos for Clonk and bridge int32_t cx=clk->GetX(), cy=clk->GetY(), cw=clk->Shape.Wdt, ch=clk->Shape.Hgt; - int32_t tx=cx,ty=cy+ch/2; + int32_t tx=cx,ty=cy+ch/2; int32_t dt; if (fMoveClonk) dt = 0; else dt = clk->Action.Time / dtp; if (fWall) switch (clk->Action.ComDir) @@ -3793,39 +3793,39 @@ bool DoBridge(C4Object *clk) } } // draw bridge into landscape - ::Landscape.DrawMaterialRect(iBridgeMaterial,tx-2,ty,4,3); + ::Landscape.DrawMaterialRect(iBridgeMaterial,tx-2,ty,4,3); // Move Clonk if (fMoveClonk) clk->MovePosition(cx-clk->GetX(), cy-clk->GetY()); return true; - } + } void DoGravity(C4Object *cobj, bool fFloatFriction) - { + { // Floatation in liquids - if (cobj->InLiquid && cobj->Def->Float) - { - cobj->ydir-=FloatAccel; - if (cobj->ydirydir=FloatAccel*-10; - if (fFloatFriction) - { - if (cobj->xdir<-FloatFriction) cobj->xdir+=FloatFriction; - if (cobj->xdir>+FloatFriction) cobj->xdir-=FloatFriction; - if (cobj->rdir<-FloatFriction) cobj->rdir+=FloatFriction; - if (cobj->rdir>+FloatFriction) cobj->rdir-=FloatFriction; - } - if (!GBackLiquid(cobj->GetX(),cobj->GetY()-1+ cobj->Def->Float*cobj->GetCon()/FullCon -1 )) - if (cobj->ydir<0) cobj->ydir=0; - } + if (cobj->InLiquid && cobj->Def->Float) + { + cobj->ydir-=FloatAccel; + if (cobj->ydirydir=FloatAccel*-10; + if (fFloatFriction) + { + if (cobj->xdir<-FloatFriction) cobj->xdir+=FloatFriction; + if (cobj->xdir>+FloatFriction) cobj->xdir-=FloatFriction; + if (cobj->rdir<-FloatFriction) cobj->rdir+=FloatFriction; + if (cobj->rdir>+FloatFriction) cobj->rdir-=FloatFriction; + } + if (!GBackLiquid(cobj->GetX(),cobj->GetY()-1+ cobj->Def->Float*cobj->GetCon()/FullCon -1 )) + if (cobj->ydir<0) cobj->ydir=0; + } // Free fall gravity - else if (~cobj->Category & C4D_StaticBack) - cobj->ydir+=GravAccel; - } + else if (~cobj->Category & C4D_StaticBack) + cobj->ydir+=GravAccel; + } void StopActionDelayCommand(C4Object *cobj) - { - ObjectComStop(cobj); - cobj->AddCommand(C4CMD_Wait,NULL,0,0,50); - } + { + ObjectComStop(cobj); + cobj->AddCommand(C4CMD_Wait,NULL,0,0,50); + } bool ReduceLineSegments(C4Shape &rShape, bool fAlternate) { @@ -3842,25 +3842,25 @@ bool ReduceLineSegments(C4Shape &rShape, bool fAlternate) } void C4Object::ExecAction() - { - Action.t_attach=CNAT_None; - DWORD ocf; + { + Action.t_attach=CNAT_None; + DWORD ocf; FIXED iTXDir; FIXED lftspeed,tydir; int32_t iTargetX; int32_t iPushRange,iPushDistance; // Standard phase advance - int32_t iPhaseAdvance=1; + int32_t iPhaseAdvance=1; - // Upright attachment check - if (!Mobile) - if (Def->UprightAttach) - if (Inside(r,-StableRange,+StableRange)) - { - Action.t_attach|=Def->UprightAttach; - Mobile=1; - } + // Upright attachment check + if (!Mobile) + if (Def->UprightAttach) + if (Inside(r,-StableRange,+StableRange)) + { + Action.t_attach|=Def->UprightAttach; + Mobile=1; + } // Idle objects do natural gravity only C4PropList* pActionDef = GetAction(); @@ -3934,54 +3934,54 @@ void C4Object::ExecAction() switch (pActionDef->GetPropertyInt(P_Procedure)) { - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_WALK: - lLimit=ValByPhysical(280, pPhysical->Walk); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_WALK: + lLimit=ValByPhysical(280, pPhysical->Walk); - switch (Action.ComDir) - { - case COMD_Left: case COMD_UpLeft: case COMD_DownLeft: + switch (Action.ComDir) + { + case COMD_Left: case COMD_UpLeft: case COMD_DownLeft: // breaaak!!! if (dir == DIR_Right) accel = WalkBreak; - xdir-=accel; if (xdir<-lLimit) xdir=-lLimit; - break; - case COMD_Right: case COMD_UpRight: case COMD_DownRight: + xdir-=accel; if (xdir<-lLimit) xdir=-lLimit; + break; + case COMD_Right: case COMD_UpRight: case COMD_DownRight: if (dir == DIR_Left) accel = WalkBreak; - xdir+=accel; if (xdir>+lLimit) xdir=+lLimit; - break; - case COMD_Stop: case COMD_Up: case COMD_Down: - if (xdir<0) xdir+=WalkBreak; - if (xdir>0) xdir-=WalkBreak; - if ((xdir>-WalkBreak) && (xdir<+WalkBreak)) xdir=0; - break; - } - iPhaseAdvance=0; - if (xdir<0) + xdir+=accel; if (xdir>+lLimit) xdir=+lLimit; + break; + case COMD_Stop: case COMD_Up: case COMD_Down: + if (xdir<0) xdir+=WalkBreak; + if (xdir>0) xdir-=WalkBreak; + if ((xdir>-WalkBreak) && (xdir<+WalkBreak)) xdir=0; + break; + } + iPhaseAdvance=0; + if (xdir<0) { if(dir != DIR_Left) { SetDir(DIR_Left); xdir = -1; } iPhaseAdvance=-fixtoi(xdir*10); } - if (xdir>0) + if (xdir>0) { if(dir != DIR_Right) { SetDir(DIR_Right); xdir = 1; } iPhaseAdvance=+fixtoi(xdir*10); } - Action.t_attach|=CNAT_Bottom; - Mobile=1; + Action.t_attach|=CNAT_Bottom; + Mobile=1; // object is rotateable? adjust to ground, if in horizontal movement or not attached to the center vertex if (Def->Rotateable && Shape.AttachMat != MNone && (!!xdir || Def->Shape.VtxX[Shape.iAttachVtx])) AdjustWalkRotation(20, 20, 100); else rdir=0; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_KNEEL: - ydir=0; - Action.t_attach|=CNAT_Bottom; - Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_KNEEL: + ydir=0; + Action.t_attach|=CNAT_Bottom; + Mobile=1; + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_SCALE: { lLimit=ValByPhysical(200, pPhysical->Scale); @@ -4052,11 +4052,11 @@ void C4Object::ExecAction() Action.t_attach|=CNAT_Top; Mobile=1; break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_FLIGHT: + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_FLIGHT: // Contained: fall out (one try only) - if (!::Game.iTick10) - if (Contained) + if (!::Game.iTick10) + if (Contained) { StopActionDelayCommand(this); SetCommand(C4CMD_Exit); @@ -4077,10 +4077,10 @@ void C4Object::ExecAction() } // Gravity/mobile - DoGravity(this); - Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + DoGravity(this); + Mobile=1; + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_DIG: { if (pActionDef->GetPropertyInt(P_Attach)) @@ -4107,39 +4107,39 @@ void C4Object::ExecAction() Mobile=1; break; } - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_SWIM: - lLimit=ValByPhysical(160, pPhysical->Swim); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_SWIM: + lLimit=ValByPhysical(160, pPhysical->Swim); - // Physical training + // Physical training if (!::Game.iTick10) if (Abs(xdir)==lLimit) TrainPhysical(&C4PhysicalInfo::Swim, 1, C4MaxPhysical); - // ComDir changes xdir/ydir - switch (Action.ComDir) - { - case COMD_Up: ydir-=SwimAccel; break; - case COMD_UpRight: ydir-=SwimAccel; xdir+=SwimAccel; break; - case COMD_Right: xdir+=SwimAccel; break; - case COMD_DownRight:ydir+=SwimAccel; xdir+=SwimAccel; break; - case COMD_Down: ydir+=SwimAccel; break; - case COMD_DownLeft: ydir+=SwimAccel; xdir-=SwimAccel; break; - case COMD_Left: xdir-=SwimAccel; break; - case COMD_UpLeft: ydir-=SwimAccel; xdir-=SwimAccel; break; - case COMD_Stop: - if (xdir<0) xdir+=SwimAccel; - if (xdir>0) xdir-=SwimAccel; - if ((xdir>-SwimAccel) && (xdir<+SwimAccel)) xdir=0; - if (ydir<0) ydir+=SwimAccel; - if (ydir>0) ydir-=SwimAccel; - if ((ydir>-SwimAccel) && (ydir<+SwimAccel)) ydir=0; + // ComDir changes xdir/ydir + switch (Action.ComDir) + { + case COMD_Up: ydir-=SwimAccel; break; + case COMD_UpRight: ydir-=SwimAccel; xdir+=SwimAccel; break; + case COMD_Right: xdir+=SwimAccel; break; + case COMD_DownRight:ydir+=SwimAccel; xdir+=SwimAccel; break; + case COMD_Down: ydir+=SwimAccel; break; + case COMD_DownLeft: ydir+=SwimAccel; xdir-=SwimAccel; break; + case COMD_Left: xdir-=SwimAccel; break; + case COMD_UpLeft: ydir-=SwimAccel; xdir-=SwimAccel; break; + case COMD_Stop: + if (xdir<0) xdir+=SwimAccel; + if (xdir>0) xdir-=SwimAccel; + if ((xdir>-SwimAccel) && (xdir<+SwimAccel)) xdir=0; + if (ydir<0) ydir+=SwimAccel; + if (ydir>0) ydir-=SwimAccel; + if ((ydir>-SwimAccel) && (ydir<+SwimAccel)) ydir=0; break; - } + } // Out of liquid check if (!InLiquid) - { + { // Just above liquid: move down if (GBackLiquid(GetX(),GetY()+1+Def->Float*Con/FullCon-1)) ydir=+SwimAccel; // Free fall: walk @@ -4147,117 +4147,117 @@ void C4Object::ExecAction() } // xdir/ydir bounds - if (ydir<-lLimit) ydir=-lLimit; if (ydir>+lLimit) ydir=+lLimit; - if (xdir>+lLimit) xdir=+lLimit; if (xdir<-lLimit) xdir=-lLimit; + if (ydir<-lLimit) ydir=-lLimit; if (ydir>+lLimit) ydir=+lLimit; + if (xdir>+lLimit) xdir=+lLimit; if (xdir<-lLimit) xdir=-lLimit; // Surface dir bound if (!GBackLiquid(GetX(),GetY()-1+Def->Float*Con/FullCon-1)) if (ydir<0) ydir=0; - // Dir, Phase, Attach - if (xdir<0) SetDir(DIR_Left); - if (xdir>0) SetDir(DIR_Right); - iPhaseAdvance=fixtoi(lLimit*10); - Action.t_attach=CNAT_None; - Mobile=1; + // Dir, Phase, Attach + if (xdir<0) SetDir(DIR_Left); + if (xdir>0) SetDir(DIR_Right); + iPhaseAdvance=fixtoi(lLimit*10); + Action.t_attach=CNAT_None; + Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_THROW: - //ydir=0; xdir=0; - Action.t_attach|=CNAT_Bottom; - Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_BRIDGE: + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_THROW: + //ydir=0; xdir=0; + Action.t_attach|=CNAT_Bottom; + Mobile=1; + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_BRIDGE: { if (!DoBridge(this)) return; - switch (Action.ComDir) - { - case COMD_Left: case COMD_UpLeft: SetDir(DIR_Left); break; - case COMD_Right: case COMD_UpRight: SetDir(DIR_Right); break; - } - ydir=0; xdir=0; - Action.t_attach|=CNAT_Bottom; - Mobile=1; + switch (Action.ComDir) + { + case COMD_Left: case COMD_UpLeft: SetDir(DIR_Left); break; + case COMD_Right: case COMD_UpRight: SetDir(DIR_Right); break; + } + ydir=0; xdir=0; + Action.t_attach|=CNAT_Bottom; + Mobile=1; } - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_BUILD: + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_BUILD: // Woa, structures can build without target if ((Category & C4D_Structure) || (Category & C4D_StaticBack)) if (!Action.Target) break; - // No target - if (!Action.Target) { ObjectComStop(this); return; } + // No target + if (!Action.Target) { ObjectComStop(this); return; } // Target internal: container needs to support by own DFA_BUILD if (Action.Target->Contained) if ( (Action.Target->Contained->GetProcedure()!=DFA_BUILD) || (Action.Target->Contained->NeedEnergy) ) return; - // Build speed - int32_t iLevel; + // Build speed + int32_t iLevel; // Clonk-standard iLevel=10; // Internal builds slower - if (Action.Target->Contained) iLevel=1; + if (Action.Target->Contained) iLevel=1; // Out of target area: stop if ( !Inside(GetX()-(Action.Target->GetX()+Action.Target->Shape.GetX()),0,Action.Target->Shape.Wdt) || !Inside(GetY()-(Action.Target->GetY()+Action.Target->Shape.GetY()),-16,Action.Target->Shape.Hgt+16) ) { ObjectComStop(this); return; } - // Build target - if (!Action.Target->Build(iLevel,this)) - { - // Cannot build because target is complete (or removed, ugh): we're done - if (!Action.Target || Action.Target->Con>=FullCon) - { - // Stop - ObjectComStop(this); - // Exit target if internal - if (Action.Target) if (Action.Target->Contained==this) - Action.Target->SetCommand(C4CMD_Exit); - } + // Build target + if (!Action.Target->Build(iLevel,this)) + { + // Cannot build because target is complete (or removed, ugh): we're done + if (!Action.Target || Action.Target->Con>=FullCon) + { + // Stop + ObjectComStop(this); + // Exit target if internal + if (Action.Target) if (Action.Target->Contained==this) + Action.Target->SetCommand(C4CMD_Exit); + } // Cannot build because target needs material (assumeably) - else + else { // Stop ObjectComStop(this); } - return; - } - xdir=ydir=0; - Action.t_attach|=CNAT_Bottom; - Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_PUSH: - // No target - if (!Action.Target) { StopActionDelayCommand(this); return; } - // Inside target - if (Contained==Action.Target) { StopActionDelayCommand(this); return; } - // Target pushing force - bool fStraighten; - iTXDir=0; fStraighten=false; - lLimit=ValByPhysical(280, pPhysical->Walk); - switch (Action.ComDir) - { - case COMD_Left: case COMD_DownLeft: iTXDir=-lLimit; break; - case COMD_UpLeft: fStraighten=1; iTXDir=-lLimit; break; - case COMD_Right: case COMD_DownRight: iTXDir=+lLimit; break; - case COMD_UpRight: fStraighten=1; iTXDir=+lLimit; break; - case COMD_Up: fStraighten=1; break; - case COMD_Stop: case COMD_Down: iTXDir=0; break; - } - // Push object - if (!Action.Target->Push(iTXDir,ValByPhysical(250, pPhysical->Push),fStraighten)) - { StopActionDelayCommand(this); return; } + return; + } + xdir=ydir=0; + Action.t_attach|=CNAT_Bottom; + Mobile=1; + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_PUSH: + // No target + if (!Action.Target) { StopActionDelayCommand(this); return; } + // Inside target + if (Contained==Action.Target) { StopActionDelayCommand(this); return; } + // Target pushing force + bool fStraighten; + iTXDir=0; fStraighten=false; + lLimit=ValByPhysical(280, pPhysical->Walk); + switch (Action.ComDir) + { + case COMD_Left: case COMD_DownLeft: iTXDir=-lLimit; break; + case COMD_UpLeft: fStraighten=1; iTXDir=-lLimit; break; + case COMD_Right: case COMD_DownRight: iTXDir=+lLimit; break; + case COMD_UpRight: fStraighten=1; iTXDir=+lLimit; break; + case COMD_Up: fStraighten=1; break; + case COMD_Stop: case COMD_Down: iTXDir=0; break; + } + // Push object + if (!Action.Target->Push(iTXDir,ValByPhysical(250, pPhysical->Push),fStraighten)) + { StopActionDelayCommand(this); return; } // Set target controller Action.Target->Controller=Controller; - // ObjectAction got hold check + // ObjectAction got hold check iPushDistance = Max(Shape.Wdt/2-8,0); iPushRange = iPushDistance + 10; - int32_t sax,say,sawdt,sahgt; - Action.Target->GetArea(sax,say,sawdt,sahgt); + int32_t sax,say,sawdt,sahgt; + Action.Target->GetArea(sax,say,sawdt,sahgt); // Object lost - if (!Inside(GetX()-sax,-iPushRange,sawdt-1+iPushRange) - || !Inside(GetY()-say,-iPushRange,sahgt-1+iPushRange)) - { + if (!Inside(GetX()-sax,-iPushRange,sawdt-1+iPushRange) + || !Inside(GetY()-say,-iPushRange,sahgt-1+iPushRange)) + { // Wait command (why, anyway?) StopActionDelayCommand(this); // Grab lost action @@ -4265,31 +4265,31 @@ void C4Object::ExecAction() // Done return; } - // Follow object (full xdir reset) + // Follow object (full xdir reset) // Vertical follow: If object moves out at top, assume it's being pushed upwards and the Clonk must run after it if (GetY()-iPushDistance > say+sahgt && iTXDir) { if (iTXDir>0) sax+=sawdt/2; sawdt/=2; } // Horizontal follow - iTargetX=BoundBy(GetX(),sax-iPushDistance,sax+sawdt-1+iPushDistance); - if (GetX()==iTargetX) xdir=0; - else { if (GetX()iTargetX) xdir=-lLimit; } - // Phase by XDir - if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); } - if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); } + iTargetX=BoundBy(GetX(),sax-iPushDistance,sax+sawdt-1+iPushDistance); + if (GetX()==iTargetX) xdir=0; + else { if (GetX()iTargetX) xdir=-lLimit; } + // Phase by XDir + if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); } + if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); } // No YDir - ydir=0; + ydir=0; // Attachment - Action.t_attach|=CNAT_Bottom; + Action.t_attach|=CNAT_Bottom; // Mobile - Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_PULL: - // No target - if (!Action.Target) { StopActionDelayCommand(this); return; } - // Inside target - if (Contained==Action.Target) { StopActionDelayCommand(this); return; } - // Target contained - if (Action.Target->Contained) { StopActionDelayCommand(this); return; } + Mobile=1; + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_PULL: + // No target + if (!Action.Target) { StopActionDelayCommand(this); return; } + // Inside target + if (Contained==Action.Target) { StopActionDelayCommand(this); return; } + // Target contained + if (Action.Target->Contained) { StopActionDelayCommand(this); return; } int32_t iPullDistance; int32_t iPullX; @@ -4312,7 +4312,7 @@ void C4Object::ExecAction() iTXDir = fMove + fWalk * BoundBy(iPullX-Action.Target->GetX(),-10,+10) / 10; - // Push object + // Push object if (!Action.Target->Push(iTXDir,ValByPhysical(250, pPhysical->Push),false)) { StopActionDelayCommand(this); return; } // Set target controller @@ -4330,11 +4330,11 @@ void C4Object::ExecAction() // Pulling range iPushDistance = Max(Shape.Wdt/2-8,0); iPushRange = iPushDistance + 20; - Action.Target->GetArea(sax,say,sawdt,sahgt); + Action.Target->GetArea(sax,say,sawdt,sahgt); // Object lost - if (!Inside(GetX()-sax,-iPushRange,sawdt-1+iPushRange) - || !Inside(GetY()-say,-iPushRange,sahgt-1+iPushRange)) - { + if (!Inside(GetX()-sax,-iPushRange,sawdt-1+iPushRange) + || !Inside(GetY()-say,-iPushRange,sahgt-1+iPushRange)) + { // Wait command (why, anyway?) StopActionDelayCommand(this); // Grab lost action @@ -4348,128 +4348,128 @@ void C4Object::ExecAction() // Move to pulling position xdir = fMove + fWalk * BoundBy(iTargetX-GetX(),-10,+10) / 10; - // Phase by XDir + // Phase by XDir iPhaseAdvance=0; - if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); } - if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); } + if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); } + if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); } // No YDir - ydir=0; + ydir=0; // Attachment - Action.t_attach|=CNAT_Bottom; + Action.t_attach|=CNAT_Bottom; // Mobile - Mobile=1; + Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_CHOP: - // Valid check - if (!Action.Target) { ObjectActionStand(this); return; } - // Chop - if (!::Game.iTick3) - if (!Action.Target->Chop(this)) - { ObjectActionStand(this); return; } - // Valid check (again, target might have been destroyed) - if (!Action.Target) { ObjectActionStand(this); return; } - // AtObject check - ocf=OCF_Chop; - if (!Action.Target->At(GetX(),GetY(),ocf)) { ObjectActionStand(this); return; } - // Position + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_CHOP: + // Valid check + if (!Action.Target) { ObjectActionStand(this); return; } + // Chop + if (!::Game.iTick3) + if (!Action.Target->Chop(this)) + { ObjectActionStand(this); return; } + // Valid check (again, target might have been destroyed) + if (!Action.Target) { ObjectActionStand(this); return; } + // AtObject check + ocf=OCF_Chop; + if (!Action.Target->At(GetX(),GetY(),ocf)) { ObjectActionStand(this); return; } + // Position SetDir( (GetX()>Action.Target->GetX()) ? DIR_Left : DIR_Right ); - xdir=ydir=0; - Action.t_attach|=CNAT_Bottom; - Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_FIGHT: - // Valid check - if (!Action.Target || (Action.Target->GetProcedure()!=DFA_FIGHT)) - { ObjectActionStand(this); return; } + xdir=ydir=0; + Action.t_attach|=CNAT_Bottom; + Mobile=1; + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_FIGHT: + // Valid check + if (!Action.Target || (Action.Target->GetProcedure()!=DFA_FIGHT)) + { ObjectActionStand(this); return; } // Fighting through doors only if doors open if (Action.Target->Contained != Contained) if ((Contained && !Contained->EntranceStatus) || (Action.Target->Contained && !Action.Target->Contained->EntranceStatus)) { ObjectActionStand(this); return; } - // Physical training + // Physical training if (!::Game.iTick5) TrainPhysical(&C4PhysicalInfo::Fight, 1, C4MaxPhysical); // Direction - if (Action.Target->GetX()>GetX()) SetDir(DIR_Right); - if (Action.Target->GetX()GetX()+Action.Target->Shape.Wdt/2+2; - if (Action.Dir==DIR_Right) iTargetX=Action.Target->GetX()-Action.Target->Shape.Wdt/2-2; - lLimit=ValByPhysical(95, pPhysical->Walk); - if (GetX()==iTargetX) Towards(xdir,Fix0,lLimit); - if (GetX()iTargetX) Towards(xdir,-lLimit,lLimit); - // Distance check + if (Action.Target->GetX()>GetX()) SetDir(DIR_Right); + if (Action.Target->GetX()GetX()+Action.Target->Shape.Wdt/2+2; + if (Action.Dir==DIR_Right) iTargetX=Action.Target->GetX()-Action.Target->Shape.Wdt/2-2; + lLimit=ValByPhysical(95, pPhysical->Walk); + if (GetX()==iTargetX) Towards(xdir,Fix0,lLimit); + if (GetX()iTargetX) Towards(xdir,-lLimit,lLimit); + // Distance check if ( (Abs(GetX()-Action.Target->GetX())>Shape.Wdt) || (Abs(GetY()-Action.Target->GetY())>Shape.Wdt) ) { ObjectActionStand(this); return; } - // Other - Action.t_attach|=CNAT_Bottom; - ydir=0; - Mobile=1; + // Other + Action.t_attach|=CNAT_Bottom; + ydir=0; + Mobile=1; // Experience if (!::Game.iTick35) DoExperience(+2); - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_LIFT: - // Valid check - if (!Action.Target) { SetAction(0); return; } - // Target lifting force - lftspeed=itofix(2); tydir=0; - switch (Action.ComDir) - { - case COMD_Up: tydir=-lftspeed; break; - case COMD_Stop: tydir=-GravAccel; break; - case COMD_Down: tydir=+lftspeed; break; - } - // Lift object - if (!Action.Target->Lift(tydir,FIXED100(50))) - { SetAction(0); return; } - // Check LiftTop - if (Def->LiftTop) - if (Action.Target->GetY()<=(GetY()+Def->LiftTop)) - if (Action.ComDir==COMD_Up) - Call(PSF_LiftTop); - // General - DoGravity(this); - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_FLOAT: - // Float speed - lLimit=FIXED100(pPhysical->Float); + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_LIFT: + // Valid check + if (!Action.Target) { SetAction(0); return; } + // Target lifting force + lftspeed=itofix(2); tydir=0; + switch (Action.ComDir) + { + case COMD_Up: tydir=-lftspeed; break; + case COMD_Stop: tydir=-GravAccel; break; + case COMD_Down: tydir=+lftspeed; break; + } + // Lift object + if (!Action.Target->Lift(tydir,FIXED100(50))) + { SetAction(0); return; } + // Check LiftTop + if (Def->LiftTop) + if (Action.Target->GetY()<=(GetY()+Def->LiftTop)) + if (Action.ComDir==COMD_Up) + Call(PSF_LiftTop); + // General + DoGravity(this); + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + case DFA_FLOAT: + // Float speed + lLimit=FIXED100(pPhysical->Float); xlFloatAccel = Max(Min(lLimit+xdir,FloatAccel),itofix(0)); xrFloatAccel = Max(Min(lLimit-xdir,FloatAccel),itofix(0)); yuFloatAccel = Max(Min(lLimit+ydir,FloatAccel),itofix(0)); ydFloatAccel = Max(Min(lLimit-ydir,FloatAccel),itofix(0)); - // ComDir changes xdir/ydir - switch (Action.ComDir) - { - case COMD_Up: ydir-=yuFloatAccel; break; - case COMD_Down: ydir+=ydFloatAccel; break; - case COMD_Right: xdir+=xrFloatAccel; break; - case COMD_Left: xdir-=xlFloatAccel; break; - case COMD_UpRight: ydir-=yuFloatAccel; xdir+=xrFloatAccel; break; - case COMD_DownRight: ydir+=ydFloatAccel; xdir+=xrFloatAccel; break; - case COMD_DownLeft: ydir+=ydFloatAccel; xdir-=xlFloatAccel; break; - case COMD_UpLeft: ydir-=yuFloatAccel; xdir-=xlFloatAccel; break; - } - Mobile=1; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // ATTACH: Force position to target object + // ComDir changes xdir/ydir + switch (Action.ComDir) + { + case COMD_Up: ydir-=yuFloatAccel; break; + case COMD_Down: ydir+=ydFloatAccel; break; + case COMD_Right: xdir+=xrFloatAccel; break; + case COMD_Left: xdir-=xlFloatAccel; break; + case COMD_UpRight: ydir-=yuFloatAccel; xdir+=xrFloatAccel; break; + case COMD_DownRight: ydir+=ydFloatAccel; xdir+=xrFloatAccel; break; + case COMD_DownLeft: ydir+=ydFloatAccel; xdir-=xlFloatAccel; break; + case COMD_UpLeft: ydir-=yuFloatAccel; xdir-=xlFloatAccel; break; + } + Mobile=1; + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // ATTACH: Force position to target object // own vertex index is determined by high-order byte of action data // target vertex index is determined by low-order byte of action data - case DFA_ATTACH: + case DFA_ATTACH: // No target - if (!Action.Target) + if (!Action.Target) { if (Status) { @@ -4484,25 +4484,25 @@ void C4Object::ExecAction() if (!Action.Target->Def->IncompleteActivity) { SetAction(0); return; } - // Force containment - if (Action.Target->Contained!=Contained) - { - if (Action.Target->Contained) - Enter(Action.Target->Contained); - else - Exit(GetX(),GetY(),r); - } + // Force containment + if (Action.Target->Contained!=Contained) + { + if (Action.Target->Contained) + Enter(Action.Target->Contained); + else + Exit(GetX(),GetY(),r); + } - // Force position - ForcePosition(Action.Target->GetX()+Action.Target->Shape.VtxX[Action.Data&255] - -Shape.VtxX[Action.Data>>8], - Action.Target->GetY()+Action.Target->Shape.VtxY[Action.Data&255] - -Shape.VtxY[Action.Data>>8]); + // Force position + ForcePosition(Action.Target->GetX()+Action.Target->Shape.VtxX[Action.Data&255] + -Shape.VtxX[Action.Data>>8], + Action.Target->GetY()+Action.Target->Shape.VtxY[Action.Data&255] + -Shape.VtxY[Action.Data>>8]); // must zero motion... xdir=ydir=0; - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case DFA_CONNECT: bool fBroke; @@ -4588,8 +4588,8 @@ void C4Object::ExecAction() ReduceLineSegments(Shape, !::Game.iTick2); break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - default: + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + default: // Attach if (pActionDef->GetPropertyInt(P_Attach)) { @@ -4600,9 +4600,9 @@ void C4Object::ExecAction() // Free gravity else DoGravity(this); - break; - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } + break; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + } // Phase Advance (zero delay means no phase advance) if (pActionDef->GetPropertyInt(P_Delay)) @@ -4688,7 +4688,7 @@ bool C4Object::SetOwner(int32_t iOwner) while (pPlr->FoWViewObjs.Remove(this)) {} // set new owner int32_t iOldOwner=Owner; - Owner=iOwner; + Owner=iOwner; if (Owner != NO_OWNER) // add to plr view PlrFoWActualize(); @@ -4697,7 +4697,7 @@ bool C4Object::SetOwner(int32_t iOwner) // script callback Call(PSF_OnOwnerChanged, &C4AulParSet(C4VInt(Owner), C4VInt(iOldOwner))); // done - return true; + return true; } @@ -4800,8 +4800,8 @@ void C4Object::SetRotation(int32_t nr) // remove solid mask if (pSolidMaskData) pSolidMaskData->Remove(true, false); // set rotation - r=nr; - fix_r=itofix(nr); + r=nr; + fix_r=itofix(nr); // Update face UpdateFace(true); } @@ -5211,13 +5211,13 @@ bool C4Object::StatusDeactivate(bool fClearPointers) void C4Object::ClearContentsAndContained(bool fDoCalls) { - // exit contents from container - C4Object *cobj; C4ObjectLink *clnk,*next; - for (clnk=Contents.First; clnk && (cobj=clnk->Obj); clnk=next) - { - next=clnk->Next; + // exit contents from container + C4Object *cobj; C4ObjectLink *clnk,*next; + for (clnk=Contents.First; clnk && (cobj=clnk->Obj); clnk=next) + { + next=clnk->Next; cobj->Exit(GetX(), GetY(), 0,Fix0,Fix0,Fix0, fDoCalls); - } + } // remove from container *after* contents have been removed! if (Contained) Exit(GetX(), GetY(), 0, Fix0, Fix0, Fix0, fDoCalls); } @@ -5285,21 +5285,21 @@ bool C4Object::AdjustWalkRotation(int32_t iRangeX, int32_t iRangeY, int32_t iSpe void C4Object::UpdateInLiquid() { - // InLiquid check - if (IsInLiquidCheck()) // In Liquid - { - if (!InLiquid) // Enter liquid - { - if (OCF & OCF_HitSpeed2) if (Mass>3) - Splash(GetX(),GetY()+1,Min(Shape.Wdt*Shape.Hgt/10,20),this); - InLiquid=1; - } - } - else // Out of liquid - { - if (InLiquid) // Leave liquid - InLiquid=0; - } + // InLiquid check + if (IsInLiquidCheck()) // In Liquid + { + if (!InLiquid) // Enter liquid + { + if (OCF & OCF_HitSpeed2) if (Mass>3) + Splash(GetX(),GetY()+1,Min(Shape.Wdt*Shape.Hgt/10,20),this); + InLiquid=1; + } + } + else // Out of liquid + { + if (InLiquid) // Leave liquid + InLiquid=0; + } } StdStrBuf C4Object::GetInfoString() @@ -5423,7 +5423,7 @@ StdStrBuf C4Object::GetNeededMatStr(C4Object *pBuilder) if(ncnt > 0) { //if(!NeededMats) NeededMats.Append(", "); what was this for...? - NeededMats.AppendFormat("|%dx ", ncnt); + NeededMats.AppendFormat("|%dx ", ncnt); if((pComponent = C4Id2Def(idComponent))) NeededMats.Append(pComponent->GetName()); else diff --git a/src/game/object/C4Object.h b/src/game/object/C4Object.h index 393693c85..b7d3eaec2 100644 --- a/src/game/object/C4Object.h +++ b/src/game/object/C4Object.h @@ -91,25 +91,25 @@ class C4Action ~C4Action(); public: //C4PropList * pActionDef; - int32_t Dir; + int32_t Dir; int32_t DrawDir; // NoSave // - needs to be calculated for old-style objects.txt anyway - int32_t ComDir; - int32_t Time; - int32_t Data; - int32_t Phase,PhaseDelay; - int32_t t_attach; // SyncClearance-NoSave // - C4Object *Target,*Target2; - C4Facet Facet; // NoSave // - int32_t FacetX,FacetY; // NoSave // - StdMeshInstance::AnimationNode* Animation; // NoSave // - public: + int32_t ComDir; + int32_t Time; + int32_t Data; + int32_t Phase,PhaseDelay; + int32_t t_attach; // SyncClearance-NoSave // + C4Object *Target,*Target2; + C4Facet Facet; // NoSave // + int32_t FacetX,FacetY; // NoSave // + StdMeshInstance::AnimationNode* Animation; // NoSave // + public: void Default(); void CompileFunc(StdCompiler *pComp); // BRIDGE procedure: data mask void SetBridgeData(int32_t iBridgeTime, bool fMoveClonk, bool fWall, int32_t iBridgeMaterial); void GetBridgeData(int32_t &riBridgeTime, bool &rfMoveClonk, bool &rfWall, int32_t &riBridgeMaterial); - }; + }; class C4Object: public C4PropListNumbered { @@ -420,6 +420,6 @@ class C4Object: public C4PropListNumbered // overloaded from C4PropList virtual C4Object * GetObject() { return this; } - }; + }; #endif diff --git a/src/game/object/C4ObjectCom.cpp b/src/game/object/C4ObjectCom.cpp index 378b042f0..31391921e 100644 --- a/src/game/object/C4ObjectCom.cpp +++ b/src/game/object/C4ObjectCom.cpp @@ -44,153 +44,153 @@ bool SimFlightHitsLiquid(FIXED fcx, FIXED fcy, FIXED xdir, FIXED ydir); bool CreateConstructionSite(int32_t ctx, int32_t bty, C4ID strid, int32_t owner, C4Object *pByObj); bool ObjectActionWalk(C4Object *cObj) - { - if (!cObj->SetActionByName("Walk")) return false; - cObj->xdir=cObj->ydir=0; - return true; - } + { + if (!cObj->SetActionByName("Walk")) return false; + cObj->xdir=cObj->ydir=0; + return true; + } bool ObjectActionStand(C4Object *cObj) - { - cObj->Action.ComDir=COMD_Stop; - if (!ObjectActionWalk(cObj)) return false; - return true; - } + { + cObj->Action.ComDir=COMD_Stop; + if (!ObjectActionWalk(cObj)) return false; + return true; + } bool ObjectActionJump(C4Object *cObj, FIXED xdir, FIXED ydir, bool fByCom) - { + { // scripted jump? assert(cObj); C4AulParSet pars(C4VInt(fixtoi(xdir, 100)), C4VInt(fixtoi(ydir, 100)), C4VBool(fByCom)); if (!!cObj->Call(PSF_OnActionJump, &pars)) return true; // hardcoded jump by action - if (!cObj->SetActionByName("Jump")) return false; - cObj->xdir=xdir; cObj->ydir=ydir; - cObj->Mobile=1; + if (!cObj->SetActionByName("Jump")) return false; + cObj->xdir=xdir; cObj->ydir=ydir; + cObj->Mobile=1; // unstick from ground, because jump command may be issued in an Action-callback, // where attach-values have already been determined for that frame cObj->Action.t_attach&=~CNAT_Bottom; - return true; - } + return true; + } bool ObjectActionDive(C4Object *cObj, FIXED xdir, FIXED ydir) - { - if (!cObj->SetActionByName("Dive")) return false; - cObj->xdir=xdir; cObj->ydir=ydir; - cObj->Mobile=1; + { + if (!cObj->SetActionByName("Dive")) return false; + cObj->xdir=xdir; cObj->ydir=ydir; + cObj->Mobile=1; // unstick from ground, because jump command may be issued in an Action-callback, // where attach-values have already been determined for that frame cObj->Action.t_attach&=~CNAT_Bottom; - return true; - } + return true; + } bool ObjectActionTumble(C4Object *cObj, int32_t dir, FIXED xdir, FIXED ydir) - { - if (!cObj->SetActionByName("Tumble")) return false; - cObj->SetDir(dir); - cObj->xdir=xdir; cObj->ydir=ydir; - return true; - } + { + if (!cObj->SetActionByName("Tumble")) return false; + cObj->SetDir(dir); + cObj->xdir=xdir; cObj->ydir=ydir; + return true; + } bool ObjectActionGetPunched(C4Object *cObj, FIXED xdir, FIXED ydir) - { - if (!cObj->SetActionByName("GetPunched")) return false; - cObj->xdir=xdir; cObj->ydir=ydir; - return true; - } + { + if (!cObj->SetActionByName("GetPunched")) return false; + cObj->xdir=xdir; cObj->ydir=ydir; + return true; + } bool ObjectActionKneel(C4Object *cObj) - { - if (!cObj->SetActionByName("KneelDown")) return false; - cObj->xdir=cObj->ydir=0; - return true; - } + { + if (!cObj->SetActionByName("KneelDown")) return false; + cObj->xdir=cObj->ydir=0; + return true; + } bool ObjectActionFlat(C4Object *cObj, int32_t dir) - { - if (!cObj->SetActionByName("FlatUp")) return false; - cObj->xdir=cObj->ydir=0; - cObj->SetDir(dir); - return true; - } + { + if (!cObj->SetActionByName("FlatUp")) return false; + cObj->xdir=cObj->ydir=0; + cObj->SetDir(dir); + return true; + } bool ObjectActionScale(C4Object *cObj, int32_t dir) - { - if (!cObj->SetActionByName("Scale")) return false; - cObj->xdir=cObj->ydir=0; - cObj->SetDir(dir); - return true; - } + { + if (!cObj->SetActionByName("Scale")) return false; + cObj->xdir=cObj->ydir=0; + cObj->SetDir(dir); + return true; + } bool ObjectActionHangle(C4Object *cObj, int32_t dir) - { - if (!cObj->SetActionByName("Hangle")) return false; - cObj->xdir=cObj->ydir=0; - cObj->SetDir(dir); - return true; - } + { + if (!cObj->SetActionByName("Hangle")) return false; + cObj->xdir=cObj->ydir=0; + cObj->SetDir(dir); + return true; + } bool ObjectActionThrow(C4Object *cObj, C4Object *pThing) - { - // No object specified, first from contents + { + // No object specified, first from contents if (!pThing) pThing = cObj->Contents.GetObject(); // Nothing to throw if (!pThing) return false; // Force and direction - FIXED pthrow=ValByPhysical(400, cObj->GetPhysical()->Throw); - int32_t iDir=1; if (cObj->Action.Dir==DIR_Left) iDir=-1; + FIXED pthrow=ValByPhysical(400, cObj->GetPhysical()->Throw); + int32_t iDir=1; if (cObj->Action.Dir==DIR_Left) iDir=-1; // Set action - if (!cObj->SetActionByName("Throw")) return false; + if (!cObj->SetActionByName("Throw")) return false; // Exit object pThing->Exit(cObj->GetX(), - cObj->GetY()+cObj->Shape.y-1, - Random(360), - pthrow*iDir+cObj->xdir,-pthrow+cObj->ydir,pthrow*iDir); + cObj->GetY()+cObj->Shape.y-1, + Random(360), + pthrow*iDir+cObj->xdir,-pthrow+cObj->ydir,pthrow*iDir); // Success - return true; - } + return true; + } bool ObjectActionDig(C4Object *cObj) - { - if (!cObj->SetActionByName("Dig")) return false; - cObj->Action.Data=0; // Material Dig2Object request - return true; - } + { + if (!cObj->SetActionByName("Dig")) return false; + cObj->Action.Data=0; // Material Dig2Object request + return true; + } bool ObjectActionBuild(C4Object *cObj, C4Object *target) - { - return cObj->SetActionByName("Build",target); - } + { + return cObj->SetActionByName("Build",target); + } bool ObjectActionPush(C4Object *cObj, C4Object *target) - { - return cObj->SetActionByName("Push",target); - } + { + return cObj->SetActionByName("Push",target); + } bool ObjectActionFight(C4Object *cObj, C4Object *target) - { - return cObj->SetActionByName("Fight",target); - } + { + return cObj->SetActionByName("Fight",target); + } bool ObjectActionChop(C4Object *cObj, C4Object *target) - { - return cObj->SetActionByName("Chop",target); - } + { + return cObj->SetActionByName("Chop",target); + } bool CornerScaleOkay(C4Object *cObj, int32_t iRangeX, int32_t iRangeY) - { - int32_t ctx,cty; - cty=cObj->GetY()-iRangeY; - if (cObj->Action.Dir==DIR_Left) ctx=cObj->GetX()-iRangeX; - else ctx=cObj->GetX()+iRangeX; - cObj->ContactCheck(ctx,cty); // (resets VtxContact & t_contact) - if (!(cObj->t_contact & CNAT_Top)) - if (!(cObj->t_contact & CNAT_Left)) - if (!(cObj->t_contact & CNAT_Right)) + { + int32_t ctx,cty; + cty=cObj->GetY()-iRangeY; + if (cObj->Action.Dir==DIR_Left) ctx=cObj->GetX()-iRangeX; + else ctx=cObj->GetX()+iRangeX; + cObj->ContactCheck(ctx,cty); // (resets VtxContact & t_contact) + if (!(cObj->t_contact & CNAT_Top)) + if (!(cObj->t_contact & CNAT_Left)) + if (!(cObj->t_contact & CNAT_Right)) if (!(cObj->t_contact & CNAT_Bottom)) return true; - return false; - } + return false; + } bool CheckCornerScale(C4Object *cObj, int32_t &iRangeX, int32_t &iRangeY) { @@ -202,7 +202,7 @@ bool CheckCornerScale(C4Object *cObj, int32_t &iRangeX, int32_t &iRangeY) } bool ObjectActionCornerScale(C4Object *cObj) - { + { int32_t iRangeX,iRangeY; // Scaling: check range max to min if (cObj->GetProcedure()==DFA_SCALE) @@ -229,10 +229,10 @@ bool ObjectActionCornerScale(C4Object *cObj) } bool ObjectComMovement(C4Object *cObj, int32_t comdir) - { - cObj->Action.ComDir=comdir; + { + cObj->Action.ComDir=comdir; - PlayerObjectCommand(cObj->Owner,C4CMD_Follow,cObj); + PlayerObjectCommand(cObj->Owner,C4CMD_Follow,cObj); // direkt turnaround if standing still if (!cObj->xdir && (cObj->GetProcedure() == DFA_WALK || cObj->GetProcedure() == DFA_HANGLE)) switch (comdir) @@ -244,8 +244,8 @@ bool ObjectComMovement(C4Object *cObj, int32_t comdir) cObj->SetDir(DIR_Right); break; } - return true; - } + return true; + } bool ObjectComTurn(C4Object *cObj) { @@ -259,12 +259,12 @@ bool ObjectComTurn(C4Object *cObj) } bool ObjectComStop(C4Object *cObj) - { - // Cease current action - cObj->SetActionByName("Idle"); - // Action walk if possible - return ObjectActionStand(cObj); - } + { + // Cease current action + cObj->SetActionByName("Idle"); + // Action walk if possible + return ObjectActionStand(cObj); + } bool ObjectComGrab(C4Object *cObj, C4Object *pTarget) { @@ -297,7 +297,7 @@ bool ObjectComUnGrab(C4Object *cObj) } bool ObjectComJump(C4Object *cObj) // by ObjectComUp, ExecCMDFMoveTo, FnJump - { + { // Only if walking if (cObj->GetProcedure()!=DFA_WALK) return false; // Calculate direction & forces @@ -322,61 +322,61 @@ bool ObjectComJump(C4Object *cObj) // by ObjectComUp, ExecCMDFMoveTo, FnJump if (SimFlightHitsLiquid(x,y,TXDir,-iPhysicalJump)) if (ObjectActionDive(cObj,TXDir,-iPhysicalJump)) return true; - // Regular jump - return ObjectActionJump(cObj,TXDir,-iPhysicalJump,true); - } + // Regular jump + return ObjectActionJump(cObj,TXDir,-iPhysicalJump,true); + } bool ObjectComLetGo(C4Object *cObj, int32_t xdirf) - { // by ACTSCALE, ACTHANGLE or ExecCMDFMoveTo - return ObjectActionJump(cObj,itofix(xdirf),Fix0,true); - } + { // by ACTSCALE, ACTHANGLE or ExecCMDFMoveTo + return ObjectActionJump(cObj,itofix(xdirf),Fix0,true); + } bool ObjectComEnter(C4Object *cObj) // by pusher - { - if (!cObj) return false; + { + if (!cObj) return false; // NoPushEnter if (cObj->Def->NoPushEnter) return false; - // Check object entrance, try command enter - C4Object *pTarget; - DWORD ocf=OCF_Entrance; - if ((pTarget=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj))) - if (ocf & OCF_Entrance) - { cObj->SetCommand(C4CMD_Enter,pTarget); return true; } + // Check object entrance, try command enter + C4Object *pTarget; + DWORD ocf=OCF_Entrance; + if ((pTarget=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj))) + if (ocf & OCF_Entrance) + { cObj->SetCommand(C4CMD_Enter,pTarget); return true; } - return false; - } + return false; + } bool ObjectComUp(C4Object *cObj) // by DFA_WALK or DFA_SWIM - { - if (!cObj) return false; + { + if (!cObj) return false; - // Check object entrance, try command enter - C4Object *pTarget; - DWORD ocf=OCF_Entrance; - if ((pTarget=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj))) - if (ocf & OCF_Entrance) - return PlayerObjectCommand(cObj->Owner,C4CMD_Enter,pTarget); + // Check object entrance, try command enter + C4Object *pTarget; + DWORD ocf=OCF_Entrance; + if ((pTarget=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj))) + if (ocf & OCF_Entrance) + return PlayerObjectCommand(cObj->Owner,C4CMD_Enter,pTarget); - // Try jump + // Try jump if (cObj->GetProcedure()==DFA_WALK) return PlayerObjectCommand(cObj->Owner,C4CMD_Jump); return false; - } + } bool ObjectComDig(C4Object *cObj) // by DFA_WALK - { - C4PhysicalInfo *phys=cObj->GetPhysical(); - if (!phys->CanDig || !ObjectActionDig(cObj)) - { + { + C4PhysicalInfo *phys=cObj->GetPhysical(); + if (!phys->CanDig || !ObjectActionDig(cObj)) + { GameMsgObject(FormatString(LoadResStr("IDS_OBJ_NODIG"),cObj->GetName()).getData(),cObj); - return false; - } - return true; - } + return false; + } + return true; + } C4Object *CreateLine(C4ID idType, int32_t iOwner, C4Object *pFrom, C4Object *pTo) { @@ -398,10 +398,10 @@ bool ObjectComLineConstruction(C4Object *cObj) C4Object *linekit,*tstruct,*cline; DWORD ocf; - ObjectActionStand(cObj); + ObjectActionStand(cObj); - // Check physical - if (!cObj->GetPhysical()->CanConstruct) + // Check physical + if (!cObj->GetPhysical()->CanConstruct) { GameMsgObject(FormatString(LoadResStr("IDS_OBJ_NOLINECONSTRUCT"),cObj->GetName()).getData(),cObj); return false; } @@ -411,7 +411,7 @@ bool ObjectComLineConstruction(C4Object *cObj) // Check for linekit if (!(linekit=cObj->Contents.Find(C4ID::Linekit))) { - // Check line pickup + // Check line pickup ocf=OCF_LineConstruct; tstruct=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj); if (!tstruct || !(ocf & OCF_LineConstruct)) return false; @@ -424,7 +424,7 @@ bool ObjectComLineConstruction(C4Object *cObj) GameMsgObject(FormatString(LoadResStr("IDS_OBJ_NODOUBLEKIT"),cline->GetName()).getData(),cObj); return false; } // Create new linekit - if (!(linekit=Game.CreateObject(C4ID::Linekit,cObj,cline->Owner))) return false; + if (!(linekit=Game.CreateObject(C4ID::Linekit,cObj,cline->Owner))) return false; // Enter linekit into clonk bool fRejectCollect; if (!linekit->Enter(cObj, true, true, &fRejectCollect)) @@ -546,10 +546,10 @@ bool ObjectComLineConstruction(C4Object *cObj) } void ObjectComDigDouble(C4Object *cObj) // "Activation" by DFA_WALK, DFA_DIG, DFA_SWIM - { + { C4Object *pTarget; - DWORD ocf; - C4PhysicalInfo *phys=cObj->GetPhysical(); + DWORD ocf; + C4PhysicalInfo *phys=cObj->GetPhysical(); // Contents activation (first contents object only) if (cObj->Contents.GetObject()) @@ -557,15 +557,15 @@ void ObjectComDigDouble(C4Object *cObj) // "Activation" by DFA_WALK, DFA_DIG, DF return; // Linekit: Line construction (move to linekit script...) - if (cObj->Contents.GetObject() && (cObj->Contents.GetObject()->id==C4ID::Linekit)) - { + if (cObj->Contents.GetObject() && (cObj->Contents.GetObject()->id==C4ID::Linekit)) + { ObjectComLineConstruction(cObj); return; - } + } // Chop - ocf=OCF_Chop; - if (phys->CanChop) + ocf=OCF_Chop; + if (phys->CanChop) if (cObj->GetProcedure()!=DFA_SWIM) if ((pTarget=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj))) if (ocf & OCF_Chop) @@ -575,64 +575,64 @@ void ObjectComDigDouble(C4Object *cObj) // "Activation" by DFA_WALK, DFA_DIG, DF } // Line construction pick up - ocf=OCF_LineConstruct; - if (phys->CanConstruct) + ocf=OCF_LineConstruct; + if (phys->CanConstruct) if (!cObj->Contents.GetObject()) if ((pTarget=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj))) if (ocf & OCF_LineConstruct) if (ObjectComLineConstruction(cObj)) return; - // Own activation call - if (!! cObj->Call(PSF_Activate, &C4AulParSet(C4VObj(cObj)))) return; + // Own activation call + if (!! cObj->Call(PSF_Activate, &C4AulParSet(C4VObj(cObj)))) return; - } + } bool ObjectComDownDouble(C4Object *cObj) // by DFA_WALK - { - C4Object *pTarget; - DWORD ocf= OCF_Construct | OCF_Grab; - if ((pTarget=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj))) - { - if (ocf & OCF_Construct) - { PlayerObjectCommand(cObj->Owner,C4CMD_Build,pTarget); return true; } - if (ocf & OCF_Grab) - { PlayerObjectCommand(cObj->Owner,C4CMD_Grab,pTarget); return true; } - } - return false; - } + { + C4Object *pTarget; + DWORD ocf= OCF_Construct | OCF_Grab; + if ((pTarget=::Objects.AtObject(cObj->GetX(),cObj->GetY(),ocf,cObj))) + { + if (ocf & OCF_Construct) + { PlayerObjectCommand(cObj->Owner,C4CMD_Build,pTarget); return true; } + if (ocf & OCF_Grab) + { PlayerObjectCommand(cObj->Owner,C4CMD_Grab,pTarget); return true; } + } + return false; + } bool ObjectComPut(C4Object *cObj, C4Object *pTarget, C4Object *pThing) - { - // No object specified, first from contents + { + // No object specified, first from contents if (!pThing) pThing = cObj->Contents.GetObject(); // Nothing to put if (!pThing) return false; // No target - if (!pTarget) return false; - // Grabbing: check C4D_Grab_Put - if (pTarget!=cObj->Contained) - if (!(pTarget->Def->GrabPutGet & C4D_Grab_Put)) - { - // Was meant to be a drop anyway - probably obsolete as controls are being revised - //if (ValidPlr(cObj->Owner)) - // if (Game.Players.Get(cObj->Owner)->LastComDownDouble) - // return ObjectComDrop(cObj, pThing); - // No grab put: fail - return false; - } - // Target no fullcon - if (!(pTarget->OCF & OCF_FullCon)) return false; - // Transfer thing + if (!pTarget) return false; + // Grabbing: check C4D_Grab_Put + if (pTarget!=cObj->Contained) + if (!(pTarget->Def->GrabPutGet & C4D_Grab_Put)) + { + // Was meant to be a drop anyway - probably obsolete as controls are being revised + //if (ValidPlr(cObj->Owner)) + // if (Game.Players.Get(cObj->Owner)->LastComDownDouble) + // return ObjectComDrop(cObj, pThing); + // No grab put: fail + return false; + } + // Target no fullcon + if (!(pTarget->OCF & OCF_FullCon)) return false; + // Transfer thing bool fRejectCollect; - if (!pThing->Enter(pTarget, true, true, &fRejectCollect)) return false; + if (!pThing->Enter(pTarget, true, true, &fRejectCollect)) return false; // Put call to object script - cObj->Call(PSF_Put); + cObj->Call(PSF_Put); // Target collection call - pTarget->Call(PSF_Collection,&C4AulParSet(C4VObj(pThing), C4VBool(true))); + pTarget->Call(PSF_Collection,&C4AulParSet(C4VObj(pThing), C4VBool(true))); // Success - return true; - } + return true; + } bool ObjectComThrow(C4Object *cObj, C4Object *pThing) { @@ -650,8 +650,8 @@ bool ObjectComThrow(C4Object *cObj, C4Object *pThing) } bool ObjectComDrop(C4Object *cObj, C4Object *pThing) - { - // No object specified, first from contents + { + // No object specified, first from contents if (!pThing) pThing = cObj->Contents.GetObject(); // Nothing to throw if (!pThing) return false; @@ -659,8 +659,8 @@ bool ObjectComDrop(C4Object *cObj, C4Object *pThing) // When dropping diagonally, drop from edge of shape // When doing a diagonal forward drop during flight, exit a bit closer to the Clonk to allow planned tumbling // Except when hangling, so you can mine effectively form the ceiling, and when swimming because you cannot tumble then - FIXED pthrow=ValByPhysical(400, cObj->GetPhysical()->Throw); - int32_t tdir=0; int right=0; + FIXED pthrow=ValByPhysical(400, cObj->GetPhysical()->Throw); + int32_t tdir=0; int right=0; bool isHanglingOrSwimming = false; int32_t iProc = DFA_NONE; C4PropList* pActionDef = cObj->GetAction(); @@ -683,54 +683,54 @@ bool ObjectComDrop(C4Object *cObj, C4Object *pThing) // Update OCF cObj->SetOCF(); // Ungrab - ObjectComUnGrab(cObj); + ObjectComUnGrab(cObj); // Done - return true; - } + return true; + } bool ObjectComChop(C4Object *cObj, C4Object *pTarget) - { - if (!pTarget) return false; - if (!cObj->GetPhysical()->CanChop) + { + if (!pTarget) return false; + if (!cObj->GetPhysical()->CanChop) { - GameMsgObject(FormatString(LoadResStr("IDS_OBJ_NOCHOP"),cObj->GetName()).getData(),cObj); + GameMsgObject(FormatString(LoadResStr("IDS_OBJ_NOCHOP"),cObj->GetName()).getData(),cObj); return false; } - if (cObj->GetProcedure()!=DFA_WALK) return false; - return ObjectActionChop(cObj,pTarget); - } + if (cObj->GetProcedure()!=DFA_WALK) return false; + return ObjectActionChop(cObj,pTarget); + } bool ObjectComBuild(C4Object *cObj, C4Object *pTarget) - { - if (!pTarget) return false; - // Needs to be idle or walking - if (cObj->GetAction()) - if (cObj->GetProcedure()!=DFA_WALK) - return false; - return ObjectActionBuild(cObj,pTarget); - } + { + if (!pTarget) return false; + // Needs to be idle or walking + if (cObj->GetAction()) + if (cObj->GetProcedure()!=DFA_WALK) + return false; + return ObjectActionBuild(cObj,pTarget); + } bool ObjectComPutTake(C4Object *cObj, C4Object *pTarget, C4Object *pThing) // by C4CMD_Throw - { // by C4CMD_Drop - // Valid checks - if (!pTarget) return false; - // No object specified, first from contents + { // by C4CMD_Drop + // Valid checks + if (!pTarget) return false; + // No object specified, first from contents if (!pThing) pThing = cObj->Contents.GetObject(); - // Has thing, put to target - if (pThing) - return ObjectComPut(cObj,pTarget,pThing); - // If target is own container, activate activation menu - if (pTarget==cObj->Contained) + // Has thing, put to target + if (pThing) + return ObjectComPut(cObj,pTarget,pThing); + // If target is own container, activate activation menu + if (pTarget==cObj->Contained) return ObjectComTake(cObj); // carlo - // Assuming target is grabbed, check for grab get - if (pTarget->Def->GrabPutGet & C4D_Grab_Get) - { - // Activate get menu - return cObj->ActivateMenu(C4MN_Get,0,0,0,pTarget); - } - // Failure - return false; - } + // Assuming target is grabbed, check for grab get + if (pTarget->Def->GrabPutGet & C4D_Grab_Get) + { + // Activate get menu + return cObj->ActivateMenu(C4MN_Get,0,0,0,pTarget); + } + // Failure + return false; + } // carlo bool ObjectComTake(C4Object *cObj) // by C4CMD_Take @@ -745,8 +745,8 @@ bool ObjectComTake2(C4Object *cObj) // by C4CMD_Take2 } bool ObjectComPunch(C4Object *cObj, C4Object *pTarget, int32_t punch) - { - if (!cObj || !pTarget) return false; + { + if (!cObj || !pTarget) return false; if (!punch) if (pTarget->GetPhysical()->Fight) punch=BoundBy(5*cObj->GetPhysical()->Fight/pTarget->GetPhysical()->Fight,0,10); @@ -754,32 +754,32 @@ bool ObjectComPunch(C4Object *cObj, C4Object *pTarget, int32_t punch) bool fBlowStopped = !!pTarget->Call(PSF_QueryCatchBlow,&C4AulParSet(C4VObj(cObj))); if (fBlowStopped && punch>1) punch=punch/2; // half damage for caught blow, so shield+armor help in fistfight and vs monsters pTarget->DoEnergy(-punch, false, C4FxCall_EngGetPunched, cObj->Controller); - int32_t tdir=+1; if (cObj->Action.Dir==DIR_Left) tdir=-1; - pTarget->Action.ComDir=COMD_Stop; + int32_t tdir=+1; if (cObj->Action.Dir==DIR_Left) tdir=-1; + pTarget->Action.ComDir=COMD_Stop; // No tumbles when blow was caught if (fBlowStopped) return false; - // Hard punch - if (punch>=10) - if (ObjectActionTumble(pTarget,pTarget->Action.Dir,FIXED100(150)*tdir,itofix(-2))) + // Hard punch + if (punch>=10) + if (ObjectActionTumble(pTarget,pTarget->Action.Dir,FIXED100(150)*tdir,itofix(-2))) { pTarget->Call(PSF_CatchBlow,&C4AulParSet(C4VInt(punch), C4VObj(cObj))); return true; } - // Regular punch - if (ObjectActionGetPunched(pTarget,FIXED100(250)*tdir,Fix0)) + // Regular punch + if (ObjectActionGetPunched(pTarget,FIXED100(250)*tdir,Fix0)) { pTarget->Call(PSF_CatchBlow,&C4AulParSet(C4VInt(punch), C4VObj(cObj))); return true; } return false; - } + } bool ObjectComCancelAttach(C4Object *cObj) - { - if (cObj->GetProcedure()==DFA_ATTACH) - return cObj->SetAction(0); - return false; - } + { + if (cObj->GetProcedure()==DFA_ATTACH) + return cObj->SetAction(0); + return false; + } void ObjectComStopDig(C4Object *cObj) { @@ -808,66 +808,66 @@ int32_t ComOrder(int32_t iIndex) } const char *ComName(int32_t iCom) - { - switch (iCom) - { - case COM_Up: return "Up"; - case COM_Up_S: return "UpSingle"; - case COM_Up_D: return "UpDouble"; - case COM_Up_R: return "UpReleased"; - case COM_Down: return "Down"; - case COM_Down_S: return "DownSingle"; - case COM_Down_D: return "DownDouble"; - case COM_Down_R: return "DownReleased"; - case COM_Left: return "Left"; - case COM_Left_S: return "LeftSingle"; - case COM_Left_D: return "LeftDouble"; - case COM_Left_R: return "LeftReleased"; - case COM_Right: return "Right"; - case COM_Right_S: return "RightSingle"; - case COM_Right_D: return "RightDouble"; - case COM_Right_R: return "RightReleased"; - case COM_Dig: return "Dig"; - case COM_Dig_S: return "DigSingle"; - case COM_Dig_D: return "DigDouble"; - case COM_Dig_R: return "DigReleased"; - case COM_Throw: return "Throw"; - case COM_Throw_S: return "ThrowSingle"; - case COM_Throw_D: return "ThrowDouble"; - case COM_Throw_R: return "ThrowReleased"; - case COM_Special: return "Special"; - case COM_Special_S: return "SpecialSingle"; - case COM_Special_D: return "SpecialDouble"; - case COM_Special_R: return "SpecialReleased"; - case COM_Special2: return "Special2"; - case COM_Special2_S: return "Special2Single"; - case COM_Special2_D: return "Special2Double"; - case COM_Special2_R: return "Special2Released"; - case COM_WheelUp: return "WheelUp"; - case COM_WheelDown: return "WheelDown"; - } - return "Undefined"; - } + { + switch (iCom) + { + case COM_Up: return "Up"; + case COM_Up_S: return "UpSingle"; + case COM_Up_D: return "UpDouble"; + case COM_Up_R: return "UpReleased"; + case COM_Down: return "Down"; + case COM_Down_S: return "DownSingle"; + case COM_Down_D: return "DownDouble"; + case COM_Down_R: return "DownReleased"; + case COM_Left: return "Left"; + case COM_Left_S: return "LeftSingle"; + case COM_Left_D: return "LeftDouble"; + case COM_Left_R: return "LeftReleased"; + case COM_Right: return "Right"; + case COM_Right_S: return "RightSingle"; + case COM_Right_D: return "RightDouble"; + case COM_Right_R: return "RightReleased"; + case COM_Dig: return "Dig"; + case COM_Dig_S: return "DigSingle"; + case COM_Dig_D: return "DigDouble"; + case COM_Dig_R: return "DigReleased"; + case COM_Throw: return "Throw"; + case COM_Throw_S: return "ThrowSingle"; + case COM_Throw_D: return "ThrowDouble"; + case COM_Throw_R: return "ThrowReleased"; + case COM_Special: return "Special"; + case COM_Special_S: return "SpecialSingle"; + case COM_Special_D: return "SpecialDouble"; + case COM_Special_R: return "SpecialReleased"; + case COM_Special2: return "Special2"; + case COM_Special2_S: return "Special2Single"; + case COM_Special2_D: return "Special2Double"; + case COM_Special2_R: return "Special2Released"; + case COM_WheelUp: return "WheelUp"; + case COM_WheelDown: return "WheelDown"; + } + return "Undefined"; + } int32_t Com2Control(int32_t iCom) - { + { iCom = iCom & ~(COM_Double | COM_Single); - switch (iCom) - { - case COM_CursorLeft: return CON_CursorLeft; - case COM_CursorToggle: return CON_CursorToggle; - case COM_CursorRight: return CON_CursorRight; - case COM_Throw: return CON_Throw; - case COM_Up: return CON_Up; - case COM_Dig: return CON_Dig; - case COM_Left: return CON_Left; - case COM_Down: return CON_Down; - case COM_Right: return CON_Right; - case COM_Special: return CON_Special; - case COM_Special2: return CON_Special2; - } + switch (iCom) + { + case COM_CursorLeft: return CON_CursorLeft; + case COM_CursorToggle: return CON_CursorToggle; + case COM_CursorRight: return CON_CursorRight; + case COM_Throw: return CON_Throw; + case COM_Up: return CON_Up; + case COM_Dig: return CON_Dig; + case COM_Left: return CON_Left; + case COM_Down: return CON_Down; + case COM_Right: return CON_Right; + case COM_Special: return CON_Special; + case COM_Special2: return CON_Special2; + } return CON_Menu; - } + } int32_t Control2Com(int32_t iControl, bool fUp) { diff --git a/src/game/object/C4ObjectInfo.cpp b/src/game/object/C4ObjectInfo.cpp index 1113030f7..09fbc0e7b 100644 --- a/src/game/object/C4ObjectInfo.cpp +++ b/src/game/object/C4ObjectInfo.cpp @@ -58,7 +58,7 @@ void C4ObjectInfo::Default() HasDied=false; ControlCount=0; Filename[0]=0; - Next=NULL; + Next=NULL; pDef = NULL; Portrait.Default(); pNewPortrait = NULL; @@ -289,7 +289,7 @@ bool C4ObjectInfo::Save(C4Group &hGroup, bool fStoreTiny, C4DefList *pDefs) void C4ObjectInfo::Evaluate() { Retire(); - if (WasInAction) Rounds++; + if (WasInAction) Rounds++; } void C4ObjectInfo::Clear() @@ -304,8 +304,8 @@ void C4ObjectInfo::Recruit() { // already recruited? if (InAction) return; - WasInAction=true; - InAction=true; + WasInAction=true; + InAction=true; InActionTime=Game.Time; // rank name overload by def? C4Def *pDef=::Definitions.ID2Def(id); diff --git a/src/game/object/C4ObjectInfo.h b/src/game/object/C4ObjectInfo.h index 1aebba0b1..2d79815b1 100644 --- a/src/game/object/C4ObjectInfo.h +++ b/src/game/object/C4ObjectInfo.h @@ -28,13 +28,13 @@ #include class C4ObjectInfo: public C4ObjectInfoCore - { - public: + { + public: C4ObjectInfo(); ~C4ObjectInfo(); - public: - bool WasInAction; - bool InAction; + public: + bool WasInAction; + bool InAction; int32_t InActionTime; bool HasDied; int32_t ControlCount; @@ -43,8 +43,8 @@ class C4ObjectInfo: public C4ObjectInfoCore C4Portrait *pNewPortrait; // new permanent portrait link (usually to def graphics) C4Portrait *pCustomPortrait; // if assigned, the Clonk has a custom portrait to be set via SetPortrait("custom") char Filename[_MAX_PATH+1]; - C4ObjectInfo *Next; - public: + C4ObjectInfo *Next; + public: void Default(); void Clear(); void Evaluate(); @@ -58,6 +58,6 @@ class C4ObjectInfo: public C4ObjectInfoCore bool SetPortrait(const char *szPortraitName, C4Def *pSourceDef, bool fAssignPermanently, bool fCopyFile); bool SetPortrait(C4PortraitGraphics *pNewPortraitGfx, bool fAssignPermanently, bool fCopyFile); bool ClearPortrait(bool fPermanently); - }; + }; #endif diff --git a/src/game/object/C4ObjectInfoList.cpp b/src/game/object/C4ObjectInfoList.cpp index 013471501..2e9460f0f 100644 --- a/src/game/object/C4ObjectInfoList.cpp +++ b/src/game/object/C4ObjectInfoList.cpp @@ -60,22 +60,22 @@ void C4ObjectInfoList::Clear() int32_t C4ObjectInfoList::Load(C4Group &hGroup, bool fLoadPortraits) { - C4ObjectInfo *ninf; - int32_t infn=0; - char entryname[256+1]; + C4ObjectInfo *ninf; + int32_t infn=0; + char entryname[256+1]; - // Search all c4i files + // Search all c4i files hGroup.ResetSearch(); - while (hGroup.FindNextEntry(C4CFN_ObjectInfoFiles,entryname)) + while (hGroup.FindNextEntry(C4CFN_ObjectInfoFiles,entryname)) if ((ninf=new C4ObjectInfo)) { if (ninf->Load(hGroup,entryname,fLoadPortraits)) { Add(ninf); infn++; } else delete ninf; } - // Search all c4o files + // Search all c4o files /*hGroup.ResetSearch(); - while (hGroup.FindNextEntry("*.c4o",entryname)) + while (hGroup.FindNextEntry("*.c4o",entryname)) if (ninf=new C4ObjectInfo) if (ninf->Load(hGroup,entryname)) { Add(ninf); infn++; } else delete ninf;*/ @@ -89,7 +89,7 @@ int32_t C4ObjectInfoList::Load(C4Group &hGroup, bool fLoadPortraits) Load(ItemGroup, fLoadPortraits); } - return infn; + return infn; } bool C4ObjectInfoList::Add(C4ObjectInfo *pInfo) @@ -103,28 +103,28 @@ bool C4ObjectInfoList::Add(C4ObjectInfo *pInfo) void C4ObjectInfoList::MakeValidName(char *sName) { char tstr[_MAX_PATH]; - int32_t iname,namelen=SLen(sName); - for (iname=2; NameExists(sName); iname++) - { - sprintf(tstr," %d",iname); - SCopy(tstr,sName+Min(namelen,C4MaxName-SLen(tstr))); - } + int32_t iname,namelen=SLen(sName); + for (iname=2; NameExists(sName); iname++) + { + sprintf(tstr," %d",iname); + SCopy(tstr,sName+Min(namelen,C4MaxName-SLen(tstr))); + } } bool C4ObjectInfoList::NameExists(const char *szName) { - C4ObjectInfo *cinf; - for (cinf=First; cinf; cinf=cinf->Next) - if (SEqualNoCase(szName,cinf->Name)) - return true; - return false; + C4ObjectInfo *cinf; + for (cinf=First; cinf; cinf=cinf->Next) + if (SEqualNoCase(szName,cinf->Name)) + return true; + return false; } C4ObjectInfo* C4ObjectInfoList::GetIdle(C4ID c_id, C4DefList &rDefs) { C4Def *pDef; - C4ObjectInfo *pInfo; - C4ObjectInfo *pHiExp=NULL; + C4ObjectInfo *pInfo; + C4ObjectInfo *pHiExp=NULL; // Search list for (pInfo=First; pInfo; pInfo=pInfo->Next) @@ -143,20 +143,20 @@ C4ObjectInfo* C4ObjectInfoList::GetIdle(C4ID c_id, C4DefList &rDefs) // Found if (pHiExp) - { + { pHiExp->Recruit(); - return pHiExp; - } + return pHiExp; + } - return NULL; + return NULL; } C4ObjectInfo* C4ObjectInfoList::New(C4ID n_id, C4DefList *pDefs) { - C4ObjectInfo *pInfo; + C4ObjectInfo *pInfo; // Create new info object - if (!(pInfo = new C4ObjectInfo)) return NULL; - // Default type clonk if none specified + if (!(pInfo = new C4ObjectInfo)) return NULL; + // Default type clonk if none specified if (n_id == C4ID::None) n_id = C4ID::Clonk; // Check type valid and def available C4Def *pDef = NULL; @@ -167,7 +167,7 @@ C4ObjectInfo* C4ObjectInfoList::New(C4ID n_id, C4DefList *pDefs) const char *cpNames = Game.Names.GetData(); if (pDef->pClonkNames) cpNames = pDef->pClonkNames->GetData(); // Default by type - ((C4ObjectInfoCore*)pInfo)->Default(n_id, pDefs, cpNames); + ((C4ObjectInfoCore*)pInfo)->Default(n_id, pDefs, cpNames); // Set birthday pInfo->Birthday=time(NULL); // Make valid names @@ -175,16 +175,16 @@ C4ObjectInfo* C4ObjectInfoList::New(C4ID n_id, C4DefList *pDefs) // Add new portrait (permanently w/o copying file) if (Config.Graphics.AddNewCrewPortraits) pInfo->SetRandomPortrait(C4ID::None, true, false); - // Add + // Add Add(pInfo); ++iNumCreated; - return pInfo; + return pInfo; } void C4ObjectInfoList::Evaluate() { C4ObjectInfo *cinf; - for (cinf=First; cinf; cinf=cinf->Next) + for (cinf=First; cinf; cinf=cinf->Next) cinf->Evaluate(); } @@ -192,7 +192,7 @@ bool C4ObjectInfoList::Save(C4Group &hGroup, bool fSavegame, bool fStoreTiny, C4 { // Save in opposite order (for identical crew order on load) C4ObjectInfo *pInfo; - for (pInfo = GetLast(); pInfo; pInfo = GetPrevious(pInfo)) + for (pInfo = GetLast(); pInfo; pInfo = GetPrevious(pInfo)) { // don't safe TemporaryCrew in regular player files if (!fSavegame) @@ -209,9 +209,9 @@ bool C4ObjectInfoList::Save(C4Group &hGroup, bool fSavegame, bool fStoreTiny, C4 C4ObjectInfo* C4ObjectInfoList::GetIdle(const char *szByName) { - C4ObjectInfo *pInfo; + C4ObjectInfo *pInfo; // Find matching name, participating, alive and not in action - for (pInfo=First; pInfo; pInfo=pInfo->Next) + for (pInfo=First; pInfo; pInfo=pInfo->Next) if (SEqualNoCase(pInfo->Name,szByName)) if (pInfo->Participation) if (!pInfo->InAction) if (!pInfo->HasDied) @@ -224,8 +224,8 @@ C4ObjectInfo* C4ObjectInfoList::GetIdle(const char *szByName) void C4ObjectInfoList::DetachFromObjects() { - C4ObjectInfo *cinf; - for (cinf=First; cinf; cinf=cinf->Next) + C4ObjectInfo *cinf; + for (cinf=First; cinf; cinf=cinf->Next) ::Objects.ClearInfo(cinf); } @@ -253,7 +253,7 @@ bool C4ObjectInfoList::IsElement(C4ObjectInfo *pInfo) void C4ObjectInfoList::Strip(C4DefList &rDefs) { - C4ObjectInfo *pInfo, *pPrev; + C4ObjectInfo *pInfo, *pPrev; // Search list for (pInfo=First, pPrev=NULL; pInfo; ) { diff --git a/src/game/object/C4ObjectList.cpp b/src/game/object/C4ObjectList.cpp index e9124a218..7de7e2eae 100644 --- a/src/game/object/C4ObjectList.cpp +++ b/src/game/object/C4ObjectList.cpp @@ -33,29 +33,29 @@ #include C4ObjectList::C4ObjectList(): FirstIter(0) - { + { Default(); - } + } C4ObjectList::C4ObjectList(const C4ObjectList &List): FirstIter(0) { - Default(); + Default(); Copy(List); } C4ObjectList::~C4ObjectList() - { - Clear(); - } + { + Clear(); + } void C4ObjectList::Clear() - { - C4ObjectLink *cLnk,*nextLnk; - for (cLnk=First; cLnk; cLnk=nextLnk) - { nextLnk=cLnk->Next; delete cLnk; } - First=Last=NULL; + { + C4ObjectLink *cLnk,*nextLnk; + for (cLnk=First; cLnk; cLnk=nextLnk) + { nextLnk=cLnk->Next; delete cLnk; } + First=Last=NULL; if (pEnumerated) delete pEnumerated; pEnumerated=NULL; - } + } const int MaxTempListID = 500; C4ID TempListID[MaxTempListID]; @@ -68,7 +68,7 @@ C4ID C4ObjectList::GetListID(int32_t dwCategory, int Index) // Create a temporary list of all id's and counts for (clid=0; clidObj; clnk=clnk->Next) + for (clnk=First; clnk && clnk->Obj; clnk=clnk->Next) if (clnk->Obj->Status) if ((dwCategory==C4D_All) || ( (cdef=C4Id2Def(clnk->Obj->Def->id)) && (cdef->Category & dwCategory) )) for (clid=0; clidObj; clnk=clnk->Next) + for (clnk=First; clnk && clnk->Obj; clnk=clnk->Next) if (clnk->Obj->Status) if ((dwCategory==C4D_All) || ( (cdef=C4Id2Def(clnk->Obj->Def->id)) && (cdef->Category & dwCategory) )) for (clid=0; clidDef || !nObj->Status) return false; + { + C4ObjectLink *nLnk; + if (!nObj || !nObj->Def || !nObj->Status) return false; #ifdef _DEBUG if (eSort==stMain) @@ -134,10 +134,10 @@ bool C4ObjectList::Add(C4Object *nObj, SortType eSort, C4ObjectList *pLstSorted) // no self-sort assert(pLstSorted != this); - // Allocate new link - if (!(nLnk=new C4ObjectLink)) return false; - // Set link - nLnk->Obj=nObj; + // Allocate new link + if (!(nLnk=new C4ObjectLink)) return false; + // Set link + nLnk->Obj=nObj; // Search insert position (default: end of list) C4ObjectLink *cLnk = NULL, *cPrev = Last; @@ -242,11 +242,11 @@ bool C4ObjectList::Add(C4Object *nObj, SortType eSort, C4ObjectList *pLstSorted) } #endif - // Add mass - Mass+=nObj->Mass; + // Add mass + Mass+=nObj->Mass; - return true; - } + return true; + } bool C4ObjectList::Remove(C4Object *pObj) { @@ -280,76 +280,76 @@ bool C4ObjectList::Remove(C4Object *pObj) } C4Object* C4ObjectList::Find(C4ID id, int owner, DWORD dwOCF) - { - C4ObjectLink *cLnk; - // Find link and object - for (cLnk=First; cLnk; cLnk=cLnk->Next) - if (cLnk->Obj->Status) - if (cLnk->Obj->Def->id==id) - if ((owner==ANY_OWNER) || (cLnk->Obj->Owner==owner)) + { + C4ObjectLink *cLnk; + // Find link and object + for (cLnk=First; cLnk; cLnk=cLnk->Next) + if (cLnk->Obj->Status) + if (cLnk->Obj->Def->id==id) + if ((owner==ANY_OWNER) || (cLnk->Obj->Owner==owner)) if (dwOCF & cLnk->Obj->OCF) return cLnk->Obj; - return NULL; - } + return NULL; + } C4Object* C4ObjectList::FindOther(C4ID id, int owner) - { - C4ObjectLink *cLnk; - // Find link and object - for (cLnk=First; cLnk; cLnk=cLnk->Next) - if (cLnk->Obj->Status) - if (cLnk->Obj->Def->id!=id) - if ((owner==ANY_OWNER) || (cLnk->Obj->Owner==owner)) - return cLnk->Obj; - return NULL; - } + { + C4ObjectLink *cLnk; + // Find link and object + for (cLnk=First; cLnk; cLnk=cLnk->Next) + if (cLnk->Obj->Status) + if (cLnk->Obj->Def->id!=id) + if ((owner==ANY_OWNER) || (cLnk->Obj->Owner==owner)) + return cLnk->Obj; + return NULL; + } C4Object* C4ObjectList::GetObject(int Index) - { - int cIdx; - C4ObjectLink *cLnk; - // Find link and object - for (cLnk=First,cIdx=0; cLnk; cLnk=cLnk->Next) - if (cLnk->Obj->Status) - { - if (cIdx==Index) return cLnk->Obj; - cIdx++; - } - return NULL; - } + { + int cIdx; + C4ObjectLink *cLnk; + // Find link and object + for (cLnk=First,cIdx=0; cLnk; cLnk=cLnk->Next) + if (cLnk->Obj->Status) + { + if (cIdx==Index) return cLnk->Obj; + cIdx++; + } + return NULL; + } C4ObjectLink* C4ObjectList::GetLink(C4Object *pObj) - { + { if (!pObj) return NULL; C4ObjectLink *cLnk; for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj==pObj) return cLnk; return NULL; - } + } int C4ObjectList::ObjectCount(C4ID id, int32_t dwCategory) const - { - C4ObjectLink *cLnk; - int iCount=0; - for (cLnk=First; cLnk; cLnk=cLnk->Next) - if (cLnk->Obj->Status) - if ( (id==C4ID::None) || (cLnk->Obj->Def->id==id) ) + { + C4ObjectLink *cLnk; + int iCount=0; + for (cLnk=First; cLnk; cLnk=cLnk->Next) + if (cLnk->Obj->Status) + if ( (id==C4ID::None) || (cLnk->Obj->Def->id==id) ) if ( (dwCategory==C4D_All) || (cLnk->Obj->Category & dwCategory) ) iCount++; - return iCount; - } + return iCount; + } int C4ObjectList::MassCount() - { - C4ObjectLink *cLnk; - int iMass=0; - for (cLnk=First; cLnk; cLnk=cLnk->Next) - if (cLnk->Obj->Status) - iMass+=cLnk->Obj->Mass; - Mass=iMass; - return iMass; - } + { + C4ObjectLink *cLnk; + int iMass=0; + for (cLnk=First; cLnk; cLnk=cLnk->Next) + if (cLnk->Obj->Status) + iMass+=cLnk->Obj->Mass; + Mass=iMass; + return iMass; + } void C4ObjectList::DrawIDList(C4Facet &cgo, int iSelection, C4DefList &rDefs, int32_t dwCategory, @@ -360,7 +360,7 @@ void C4ObjectList::DrawIDList(C4Facet &cgo, int iSelection, /*int iSections = cgo.GetSectionCount(); int iItems = ListIDCount(dwCategory);*/ //int iFirstItem = BoundBy(iSelection-iSections/2,0,Max(iItems-iSections,0)); - int32_t cSec = 0; + int32_t cSec = 0; int32_t iCount; C4Facet cgo2; C4Object *pFirstObj; @@ -383,8 +383,8 @@ void C4ObjectList::DrawIDList(C4Facet &cgo, int iSelection, cSec++; } // Draw by list sorted ids - /* for (cPos=0; c_id=GetListID(dwCategory,cPos); cPos++) - if (Inside(cPos,iFirstItem,iFirstItem+iSections-1)) + /* for (cPos=0; c_id=GetListID(dwCategory,cPos); cPos++) + if (Inside(cPos,iFirstItem,iFirstItem+iSections-1)) { // First object of this type pFirstObj = Find(c_id); @@ -401,8 +401,8 @@ void C4ObjectList::DrawIDList(C4Facet &cgo, int iSelection, // Region if (pRegions) pRegions->Add(cgo2.X,cgo2.Y,cgo2.Wdt,cgo2.Hgt,pFirstObj->GetName(),iRegionCom,pFirstObj,COM_None,COM_None,pFirstObj->id); // Next section - cSec++; - } */ + cSec++; + } */ } int C4ObjectList::ClearPointers(C4Object *pObj) @@ -411,62 +411,62 @@ int C4ObjectList::ClearPointers(C4Object *pObj) // Clear all primary list pointers while (Remove(pObj)) rval++; // Clear all sub pointers - C4Object *cobj; C4ObjectLink *clnk; - for (clnk=First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) + C4Object *cobj; C4ObjectLink *clnk; + for (clnk=First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) cobj->ClearPointers(pObj); return rval; } void C4ObjectList::DrawAll(C4TargetFacet &cgo, int iPlayer) { - C4ObjectLink *clnk; - // Draw objects (base) - for (clnk=Last; clnk; clnk=clnk->Prev) + C4ObjectLink *clnk; + // Draw objects (base) + for (clnk=Last; clnk; clnk=clnk->Prev) clnk->Obj->Draw(cgo, iPlayer); - // Draw objects (top face) - for (clnk=Last; clnk; clnk=clnk->Prev) + // Draw objects (top face) + for (clnk=Last; clnk; clnk=clnk->Prev) clnk->Obj->DrawTopFace(cgo, iPlayer); } void C4ObjectList::DrawIfCategory(C4TargetFacet &cgo, int iPlayer, uint32_t dwCat, bool fInvert) { - C4ObjectLink *clnk; - // Draw objects (base) - for (clnk=Last; clnk; clnk=clnk->Prev) + C4ObjectLink *clnk; + // Draw objects (base) + for (clnk=Last; clnk; clnk=clnk->Prev) if (!(clnk->Obj->Category & dwCat) == fInvert) clnk->Obj->Draw(cgo, iPlayer); - // Draw objects (top face) - for (clnk=Last; clnk; clnk=clnk->Prev) + // Draw objects (top face) + for (clnk=Last; clnk; clnk=clnk->Prev) if (!(clnk->Obj->Category & dwCat) == fInvert) clnk->Obj->DrawTopFace(cgo, iPlayer); } void C4ObjectList::Draw(C4TargetFacet &cgo, int iPlayer) { - C4ObjectLink *clnk; - // Draw objects (base) - for (clnk=Last; clnk; clnk=clnk->Prev) + C4ObjectLink *clnk; + // Draw objects (base) + for (clnk=Last; clnk; clnk=clnk->Prev) if (!(clnk->Obj->Category & C4D_BackgroundOrForeground)) clnk->Obj->Draw(cgo, iPlayer); - // Draw objects (top face) - for (clnk=Last; clnk; clnk=clnk->Prev) + // Draw objects (top face) + for (clnk=Last; clnk; clnk=clnk->Prev) if (!(clnk->Obj->Category & C4D_BackgroundOrForeground)) clnk->Obj->DrawTopFace(cgo, iPlayer); } void C4ObjectList::Enumerate() { - C4ObjectLink *cLnk; + C4ObjectLink *cLnk; // Enumerate object pointers - for (cLnk=First; cLnk; cLnk=cLnk->Next) + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj->Status) cLnk->Obj->EnumeratePointers(); } bool C4ObjectList::IsContained(C4Object *pObj) { - C4ObjectLink *cLnk; - for (cLnk=First; cLnk; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj==pObj) return true; return false; @@ -492,8 +492,8 @@ bool C4ObjectList::Write(char *szTarget) { char ostr[25]; szTarget[0]=0; - C4ObjectLink *cLnk; - for (cLnk=First; cLnk && cLnk->Obj; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk && cLnk->Obj; cLnk=cLnk->Next) if (cLnk->Obj->Status) { sprintf(ostr,"%d;",cLnk->Obj->Number); @@ -504,16 +504,16 @@ bool C4ObjectList::Write(char *szTarget) void C4ObjectList::Denumerate() { - C4ObjectLink *cLnk; - for (cLnk=First; cLnk; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj->Status) cLnk->Obj->DenumeratePointers(); } void C4ObjectList::CompileFunc(StdCompiler *pComp, bool fSaveRefs, bool fSkipPlayerObjects) { - if(fSaveRefs) - { + if(fSaveRefs) + { // this mode not supported assert(!fSkipPlayerObjects); // (Re)create list @@ -529,35 +529,35 @@ void C4ObjectList::CompileFunc(StdCompiler *pComp, bool fSaveRefs, bool fSkipPla if(!pComp->isCompiler()) { delete pEnumerated; pEnumerated = NULL; } // Compiling: Nothing to do - list will e denumerated later - } - else - { - if(pComp->isDecompiler()) - { + } + else + { + if(pComp->isDecompiler()) + { // skipping player objects would screw object counting in non-naming compilers assert(!fSkipPlayerObjects || pComp->hasNaming()); - // Put object count - int32_t iObjCnt = ObjectCount(); - pComp->Value(mkNamingCountAdapt(iObjCnt, "Object")); - // Decompile all objects in reverse order + // Put object count + int32_t iObjCnt = ObjectCount(); + pComp->Value(mkNamingCountAdapt(iObjCnt, "Object")); + // Decompile all objects in reverse order for(C4ObjectLink *pPos = Last; pPos; pPos = pPos->Prev) if(pPos->Obj->Status) if (!fSkipPlayerObjects || !pPos->Obj->IsUserPlayerObject()) pComp->Value(mkNamingAdapt(*pPos->Obj, "Object")); - } - else - { + } + else + { // this mode not supported assert(!fSkipPlayerObjects); - // Remove previous data - Clear(); - // Get "Object" section count - int32_t iObjCnt; - pComp->Value(mkNamingCountAdapt(iObjCnt, "Object")); - // Load objects, add them to the list. - for(int i = 0; i < iObjCnt; i++) - { - C4Object *pObj = NULL; + // Remove previous data + Clear(); + // Get "Object" section count + int32_t iObjCnt; + pComp->Value(mkNamingCountAdapt(iObjCnt, "Object")); + // Load objects, add them to the list. + for(int i = 0; i < iObjCnt; i++) + { + C4Object *pObj = NULL; try { pComp->Value(mkNamingAdapt(mkPtrAdaptNoNull(pObj), "Object")); @@ -572,9 +572,9 @@ void C4ObjectList::CompileFunc(StdCompiler *pComp, bool fSaveRefs, bool fSkipPla LogF("ERROR: Object loading(%s): %s", pExc->Pos.getData(), pExc->Msg.getData()); delete pExc; } - } - } - } + } + } + } } StdStrBuf C4ObjectList::GetNameList(C4DefList &rDefs, DWORD dwCategory) @@ -583,7 +583,7 @@ StdStrBuf C4ObjectList::GetNameList(C4DefList &rDefs, DWORD dwCategory) C4ID c_id; C4Def *cdef; StdStrBuf Buf; - for (cpos=0; (c_id=GetListID(dwCategory,cpos)); cpos++) + for (cpos=0; (c_id=GetListID(dwCategory,cpos)); cpos++) if ((cdef=rDefs.ID2Def(c_id))) { idcount=ObjectCount(c_id); @@ -595,8 +595,8 @@ StdStrBuf C4ObjectList::GetNameList(C4DefList &rDefs, DWORD dwCategory) bool C4ObjectList::ValidateOwners() { - C4ObjectLink *cLnk; - for (cLnk=First; cLnk; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj->Status) cLnk->Obj->ValidateOwner(); return true; @@ -607,8 +607,8 @@ bool C4ObjectList::AssignInfo() // the list seems to be traced backwards here, to ensure crew objects are added in correct order // (or semi-correct, because this will work only if the crew order matches the main object list order) // this is obsolete now, because the crew list is stored in the savegame - C4ObjectLink *cLnk; - for (cLnk=Last; cLnk; cLnk=cLnk->Prev) + C4ObjectLink *cLnk; + for (cLnk=Last; cLnk; cLnk=cLnk->Prev) if (cLnk->Obj->Status) cLnk->Obj->AssignInfo(); return true; @@ -616,8 +616,8 @@ bool C4ObjectList::AssignInfo() void C4ObjectList::ClearInfo(C4ObjectInfo *pInfo) { - C4ObjectLink *cLnk; - for (cLnk=First; cLnk; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj->Status) cLnk->Obj->ClearInfo(pInfo); } @@ -629,8 +629,8 @@ void C4ObjectList::DrawList(C4Facet &cgo, int iSelection, DWORD dwCategory) int iFirstVisible = BoundBy(iSelection-iSections/2,0,Max(iObjects-iSections,0)); C4Facet cgo2; int iObj=0,iSec=0; - C4ObjectLink *cLnk; C4Object *cObj; - for (cLnk=First; cLnk && (cObj=cLnk->Obj); cLnk=cLnk->Next) + C4ObjectLink *cLnk; C4Object *cObj; + for (cLnk=First; cLnk && (cObj=cLnk->Obj); cLnk=cLnk->Next) if (cObj->Status && (cObj->Category && dwCategory)) { if (Inside(iObj,iFirstVisible,iFirstVisible+iSections-1)) @@ -644,7 +644,7 @@ void C4ObjectList::DrawList(C4Facet &cgo, int iSelection, DWORD dwCategory) void C4ObjectList::Sort() { - C4ObjectLink *cLnk; + C4ObjectLink *cLnk; bool fSorted; // Sort by id do @@ -725,45 +725,45 @@ void C4NotifyingObjectList::RemoveLink(C4ObjectLink *pLnk) void C4ObjectList::UpdateGraphics(bool fGraphicsChanged) { - C4ObjectLink *cLnk; - for (cLnk=First; cLnk; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj->Status) cLnk->Obj->UpdateGraphics(fGraphicsChanged); } void C4ObjectList::UpdateFaces(bool bUpdateShapes) { - C4ObjectLink *cLnk; - for (cLnk=First; cLnk; cLnk=cLnk->Next) + C4ObjectLink *cLnk; + for (cLnk=First; cLnk; cLnk=cLnk->Next) if (cLnk->Obj->Status) cLnk->Obj->UpdateFace(bUpdateShapes); } void C4ObjectList::DrawSelectMark(C4TargetFacet &cgo, float Zoom) { - C4ObjectLink *cLnk; - for (cLnk=Last; cLnk; cLnk=cLnk->Prev) + C4ObjectLink *cLnk; + for (cLnk=Last; cLnk; cLnk=cLnk->Prev) cLnk->Obj->DrawSelectMark(cgo, Zoom); } void C4ObjectList::CloseMenus() { - C4Object *cobj; C4ObjectLink *clnk; - for (clnk=First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) - cobj->CloseMenu(true); + C4Object *cobj; C4ObjectLink *clnk; + for (clnk=First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) + cobj->CloseMenu(true); } void C4ObjectList::Copy(const C4ObjectList &rList) { Clear(); Default(); - C4ObjectLink *cLnk; - for (cLnk=rList.First; cLnk; cLnk=cLnk->Next) Add(cLnk->Obj, C4ObjectList::stNone); + C4ObjectLink *cLnk; + for (cLnk=rList.First; cLnk; cLnk=cLnk->Next) Add(cLnk->Obj, C4ObjectList::stNone); } void C4ObjectList::Default() { - First=Last=NULL; - Mass=0; + First=Last=NULL; + Mass=0; pEnumerated=NULL; } diff --git a/src/game/object/C4ObjectMenu.cpp b/src/game/object/C4ObjectMenu.cpp index 9e64a6060..c5650dd5e 100644 --- a/src/game/object/C4ObjectMenu.cpp +++ b/src/game/object/C4ObjectMenu.cpp @@ -116,7 +116,7 @@ void C4ObjectMenu::ClearPointers(C4Object *pObj) C4Object* C4ObjectMenu::GetParentObject() { - C4Object *cObj; C4ObjectLink *cLnk; + C4Object *cObj; C4ObjectLink *cLnk; for (cLnk=::Objects.First; cLnk && (cObj=cLnk->Obj); cLnk=cLnk->Next) if ( cObj->Menu == this ) return cObj; diff --git a/src/game/object/C4Shape.cpp b/src/game/object/C4Shape.cpp index 6fafd34fc..e11254dea 100644 --- a/src/game/object/C4Shape.cpp +++ b/src/game/object/C4Shape.cpp @@ -55,7 +55,7 @@ void C4Shape::Clear() } void C4Shape::Rotate(int32_t iAngle, bool bUpdateVertices) - { + { #ifdef DEBUGREC C4RCRotVtx rc; rc.x=x; rc.y=y; rc.wdt=Wdt; rc.hgt=Hgt; rc.r=iAngle; @@ -64,11 +64,11 @@ void C4Shape::Rotate(int32_t iAngle, bool bUpdateVertices) { rc.VtxX[i]=VtxX[i]; rc.VtxY[i]=VtxY[i]; } AddDbgRec(RCT_RotVtx1, &rc, sizeof(rc)); #endif - int32_t cnt,nvtx,nvty,rdia; + int32_t cnt,nvtx,nvty,rdia; //int32_t *vtx=VtxX; //int32_t *vty=VtxY; - FIXED mtx[4]; + FIXED mtx[4]; FIXED fAngle = itofix(iAngle); if (bUpdateVertices) @@ -104,89 +104,89 @@ void C4Shape::Rotate(int32_t iAngle, bool bUpdateVertices) } - // Enlarge Rect - rdia= (int32_t) sqrt(double(x*x+y*y)) + 2; - x=-rdia; - y=-rdia; - Wdt=2*rdia; - Hgt=2*rdia; + // Enlarge Rect + rdia= (int32_t) sqrt(double(x*x+y*y)) + 2; + x=-rdia; + y=-rdia; + Wdt=2*rdia; + Hgt=2*rdia; #ifdef DEBUGREC rc.x=x; rc.y=y; rc.wdt=Wdt; rc.hgt=Hgt; for (i=0; i<4; ++i) { rc.VtxX[i]=VtxX[i]; rc.VtxY[i]=VtxY[i]; } AddDbgRec(RCT_RotVtx2, &rc, sizeof(rc)); #endif - } + } void C4Shape::Stretch(int32_t iCon, bool bUpdateVertices) - { - int32_t cnt; - x=x*iCon/FullCon; - y=y*iCon/FullCon; - Wdt=Wdt*iCon/FullCon; - Hgt=Hgt*iCon/FullCon; - FireTop=FireTop*iCon/FullCon; + { + int32_t cnt; + x=x*iCon/FullCon; + y=y*iCon/FullCon; + Wdt=Wdt*iCon/FullCon; + Hgt=Hgt*iCon/FullCon; + FireTop=FireTop*iCon/FullCon; if (bUpdateVertices) for (cnt=0; cntrRect.x+rRect.Wdt) - { rRect.Wdt=VtxX[cnt]-rRect.x; } + else if (VtxX[cnt]>rRect.x+rRect.Wdt) + { rRect.Wdt=VtxX[cnt]-rRect.x; } // Extend up - if (VtxY[cnt]rRect.y+rRect.Hgt) - { rRect.Hgt=VtxY[cnt]-rRect.y; } - } + else if (VtxY[cnt]>rRect.y+rRect.Hgt) + { rRect.Hgt=VtxY[cnt]-rRect.y; } + } - rRect.Hgt+=rRect.y-y; - rRect.y=y; + rRect.Hgt+=rRect.y-y; + rRect.y=y; - } + } bool C4Shape::Attach(int32_t &cx, int32_t &cy, BYTE cnat_pos) - { + { // Adjust given position to one pixel before contact // at vertices matching CNAT request. - bool fAttached=false; + bool fAttached=false; - int32_t vtx,xcnt,ycnt,xcrng,ycrng,xcd,ycd; + int32_t vtx,xcnt,ycnt,xcrng,ycrng,xcd,ycd; BYTE cpix; // reset attached material @@ -244,8 +244,8 @@ bool C4Shape::Attach(int32_t &cx, int32_t &cy, BYTE cnat_pos) } } - return fAttached; - } + return fAttached; + } bool C4Shape::LineConnect(int32_t tx, int32_t ty, int32_t cvtx, int32_t ld, int32_t oldx, int32_t oldy) @@ -335,14 +335,14 @@ bool C4Shape::CheckContact(int32_t cx, int32_t cy) // Return true on any contact. - for (int32_t cvtx=0; cvtx= ContactDensity) return true; - return false; - } + return false; + } bool C4Shape::ContactCheck(int32_t cx, int32_t cy) { @@ -352,10 +352,10 @@ bool C4Shape::ContactCheck(int32_t cx, int32_t cy) // Return true on any contact. - ContactCNAT=CNAT_None; + ContactCNAT=CNAT_None; ContactCount=0; - for (int32_t cvtx=0; cvtxObj); clnk=clnk->Next) - if (cobj==tobj) return true; - return false; - } + { + C4Object *cobj; C4ObjectLink *clnk; + if (!tobj) return false; + for (clnk=Crew.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) + if (cobj==tobj) return true; + return false; + } void C4Player::ClearPointers(C4Object *pObj, bool fDeath) - { + { // Crew while (Crew.Remove(pObj)) {} - // Cursor - if (Cursor==pObj) - { + // Cursor + if (Cursor==pObj) + { // object is to be deleted; do NOT do script calls (like in Cursor->UnSelect(true)) - Cursor=NULL; AdjustCursorCommand(); // also selects and eventually does a script call! - } - // View-Cursor - if (ViewCursor==pObj) ViewCursor = NULL; - // View - if (ViewTarget==pObj) ViewTarget=NULL; + Cursor=NULL; AdjustCursorCommand(); // also selects and eventually does a script call! + } + // View-Cursor + if (ViewCursor==pObj) ViewCursor = NULL; + // View + if (ViewTarget==pObj) ViewTarget=NULL; // FoW // (do not clear locals!) // no clear when death to do normal decay @@ -93,34 +93,34 @@ void C4Player::ClearPointers(C4Object *pObj, bool fDeath) Menu.ClearPointers(pObj); // messageboard-queries RemoveMessageBoardQuery(pObj); - } + } void C4Player::UpdateValue() - { - int32_t lval=ValueGain,lobj=ObjectsOwned; - Value=0; ObjectsOwned=0; + { + int32_t lval=ValueGain,lobj=ObjectsOwned; + Value=0; ObjectsOwned=0; // Points Value+=Points; - // Wealth - Value+=Wealth; + // Wealth + Value+=Wealth; - // Asset all owned objects - C4Object *cobj; C4ObjectLink *clnk; - for (clnk=::Objects.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) - if (cobj->Owner==Number && cobj->Status) - { - ObjectsOwned++; - Value+=cobj->GetValue(NULL, Number); - } + // Asset all owned objects + C4Object *cobj; C4ObjectLink *clnk; + for (clnk=::Objects.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) + if (cobj->Owner==Number && cobj->Status) + { + ObjectsOwned++; + Value+=cobj->GetValue(NULL, Number); + } - // Value gain (always positive) - ValueGain=Value-InitialValue; + // Value gain (always positive) + ValueGain=Value-InitialValue; - // Update - if ((ValueGain!=lval) || (ObjectsOwned!=lobj)) ViewValue=C4ViewDelay; - } + // Update + if ((ValueGain!=lval) || (ObjectsOwned!=lobj)) ViewValue=C4ViewDelay; + } bool C4Player::ScenarioAndTeamInit(int32_t idTeam) { @@ -258,7 +258,7 @@ void C4Player::Execute() bool C4Player::Init(int32_t iNumber, int32_t iAtClient, const char *szAtClientName, const char *szFilename, bool fScenarioInit, class C4PlayerInfo *pInfo) - { + { // safety if (!pInfo) { @@ -267,7 +267,7 @@ bool C4Player::Init(int32_t iNumber, int32_t iAtClient, const char *szAtClientNa return false; } // Status init - Status=PS_Normal; + Status=PS_Normal; if (szFilename) SCopy(Config.AtDataReadPath(szFilename),Filename); else @@ -367,7 +367,7 @@ bool C4Player::Init(int32_t iNumber, int32_t iAtClient, const char *szAtClientNa } } - // Load runtime data + // Load runtime data else { assert(pInfo->IsJoined()); @@ -416,67 +416,67 @@ bool C4Player::Init(int32_t iNumber, int32_t iAtClient, const char *szAtClientNa // init graphs if (Game.pNetworkStatistics) CreateGraphs(); - return true; - } + return true; + } bool C4Player::Save() - { - C4Group hGroup; + { + C4Group hGroup; // Regular player saving need not be done for script players if (GetType() == C4PT_Script) return false; // Log LogF(LoadResStr("IDS_PRC_SAVEPLR"), Config.AtRelativePath(Filename)); ::GraphicsSystem.MessageBoard.EnsureLastMessage(); // copy player to save somewhere else - char szPath[_MAX_PATH + 1]; - SCopy(Config.AtTempPath(C4CFN_TempPlayer), szPath, _MAX_PATH); - MakeTempFilename(szPath); + char szPath[_MAX_PATH + 1]; + SCopy(Config.AtTempPath(C4CFN_TempPlayer), szPath, _MAX_PATH); + MakeTempFilename(szPath); // so full hard (flgr stupid) disks won't corrupt any player files... C4Group_CopyItem(Filename, szPath); // Open group - if (!hGroup.Open(szPath,true)) - return false; + if (!hGroup.Open(szPath,true)) + return false; // Save if (!Save(hGroup, false, !LocalControl)) - { hGroup.Close(); return false; } + { hGroup.Close(); return false; } // Close group - if (!hGroup.Close()) return false; - // resource + if (!hGroup.Close()) return false; + // resource C4Network2Res::Ref pRes = ::Network.ResList.getRefRes(Filename), pDRes = NULL; - bool fOfficial = pRes && ::Control.isCtrlHost(); - if(pRes) pDRes = pRes->Derive(); + bool fOfficial = pRes && ::Control.isCtrlHost(); + if(pRes) pDRes = pRes->Derive(); // move back if (ItemExists(Filename)) EraseItem(Filename); - if (!C4Group_MoveItem(szPath, Filename)) return false; - // finish update - if(pDRes && fOfficial) pDRes->FinishDerive(); + if (!C4Group_MoveItem(szPath, Filename)) return false; + // finish update + if(pDRes && fOfficial) pDRes->FinishDerive(); // Add to reload list if (LocalControl) SAddModule(Config.Explorer.Reload,Filename); // Success - return true; - } + return true; + } bool C4Player::Save(C4Group &hGroup, bool fSavegame, bool fStoreTiny) - { + { // Save core - if (!C4PlayerInfoCore::Save(hGroup)) - return false; + if (!C4PlayerInfoCore::Save(hGroup)) + return false; // Save crew C4DefList *pDefs = &::Definitions; if (!CrewInfoList.Save(hGroup, fSavegame, fStoreTiny, pDefs)) - { hGroup.Close(); return false; } + { hGroup.Close(); return false; } // Sort hGroup.Sort(C4FLS_Player); return true; - } + } void C4Player::PlaceReadyCrew(int32_t tx1, int32_t tx2, int32_t ty, C4Object *FirstBase) - { - int32_t cnt,crewnum,ctx,cty; - C4Object *nobj; - C4ObjectInfo *pInfo; - C4Def *pDef; + { + int32_t cnt,crewnum,ctx,cty; + C4Object *nobj; + C4ObjectInfo *pInfo; + C4Def *pDef; // Old specification if (Game.C4S.PlrStart[PlrStartIndex].ReadyCrew.IsClear()) @@ -563,7 +563,7 @@ void C4Player::PlaceReadyCrew(int32_t tx1, int32_t tx2, int32_t ty, C4Object *Fi } } - } + } C4Object *CreateLine(C4ID linetype, int32_t owner, C4Object *fobj, C4Object *tobj); @@ -574,31 +574,31 @@ bool CreatePowerConnection(C4Object *fbase, C4Object *tbase) } void C4Player::PlaceReadyBase(int32_t &tx, int32_t &ty, C4Object **pFirstBase) - { - int32_t cnt,cnt2,ctx,cty; - C4Def *def; - C4ID cid; - C4Object *cbase,*fpower=NULL; - // Create ready base structures - for (cnt=0; (cid=Game.C4S.PlrStart[PlrStartIndex].ReadyBase.GetID(cnt)); cnt++) - { - if ((def=C4Id2Def(cid))) - for (cnt2=0; cnt2Shape.Wdt,def->Shape.Hgt,def->Category,20)) - if ((cbase=Game.CreateObjectConstruction(C4Id2Def(cid),NULL,Number,ctx,cty,FullCon,true))) - { + || FindConSiteSpot(ctx,cty,def->Shape.Wdt,def->Shape.Hgt,def->Category,20)) + if ((cbase=Game.CreateObjectConstruction(C4Id2Def(cid),NULL,Number,ctx,cty,FullCon,true))) + { // FirstBase - if (!(*pFirstBase)) if ((cbase->Def->Entrance.Wdt>0) && (cbase->Def->Entrance.Hgt>0)) - { *pFirstBase=cbase; tx=(*pFirstBase)->GetX(); ty=(*pFirstBase)->GetY(); } + if (!(*pFirstBase)) if ((cbase->Def->Entrance.Wdt>0) && (cbase->Def->Entrance.Hgt>0)) + { *pFirstBase=cbase; tx=(*pFirstBase)->GetX(); ty=(*pFirstBase)->GetY(); } // First power plant if (cbase->Def->LineConnect & C4D_Power_Generator) if (!fpower) fpower=cbase; - } - } - } + } + } + } // Power connections C4ObjectLink *clnk; C4Object *cobj; @@ -608,56 +608,56 @@ void C4Player::PlaceReadyBase(int32_t &tx, int32_t &ty, C4Object **pFirstBase) if (cobj->Owner==Number) if (cobj->Def->LineConnect & C4D_Power_Consumer) CreatePowerConnection(fpower,cobj); - } + } void C4Player::PlaceReadyVehic(int32_t tx1, int32_t tx2, int32_t ty, C4Object *FirstBase) - { - int32_t cnt,cnt2,ctx,cty; - C4Def *def; C4ID cid; C4Object *cobj; - for (cnt=0; (cid=Game.C4S.PlrStart[PlrStartIndex].ReadyVehic.GetID(cnt)); cnt++) - { - if ((def=C4Id2Def(cid))) - for (cnt2=0; cnt2Shape.Wdt,6); - if ((cobj=Game.CreateObject(cid,NULL,Number,ctx,cty))) - { - if (FirstBase) // First base overrides target location - { cobj->Enter(FirstBase); cobj->SetCommand(C4CMD_Exit); } - } - } - } - } + if ((cobj=Game.CreateObject(cid,NULL,Number,ctx,cty))) + { + if (FirstBase) // First base overrides target location + { cobj->Enter(FirstBase); cobj->SetCommand(C4CMD_Exit); } + } + } + } + } void C4Player::PlaceReadyMaterial(int32_t tx1, int32_t tx2, int32_t ty, C4Object *FirstBase) - { - int32_t cnt,cnt2,ctx,cty; - C4Def *def; C4ID cid; + { + int32_t cnt,cnt2,ctx,cty; + C4Def *def; C4ID cid; - // In base - if (FirstBase) - { - FirstBase->CreateContentsByList(Game.C4S.PlrStart[PlrStartIndex].ReadyMaterial); - } + // In base + if (FirstBase) + { + FirstBase->CreateContentsByList(Game.C4S.PlrStart[PlrStartIndex].ReadyMaterial); + } - // Outside - else - { - for (cnt=0; (cid=Game.C4S.PlrStart[PlrStartIndex].ReadyMaterial.GetID(cnt)); cnt++) - { - if ((def=C4Id2Def(cid))) - for (cnt2=0; cnt2Shape.Wdt); - Game.CreateObject(cid,NULL,Number,ctx,cty); - } - } - } - } + Game.CreateObject(cid,NULL,Number,ctx,cty); + } + } + } + } DWORD RandomPlayerColor() // generate a random player color { @@ -666,17 +666,17 @@ DWORD RandomPlayerColor() // generate a random player color bool C4Player::ScenarioInit() { - int32_t ptx,pty; + int32_t ptx,pty; // player start index by team, if specified. Otherwise by player number PlrStartIndex = Number % C4S_MaxPlayer; C4Team *pTeam; int32_t i; if (Team && (pTeam = Game.Teams.GetTeamByID(Team))) if ((i=pTeam->GetPlrStartIndex())) PlrStartIndex=i-1; - // Set color - int32_t iColor=BoundBy(PrefColor,0,C4MaxColor-1); - while (::Players.ColorTaken(iColor)) - { ++iColor%=C4MaxColor; if (iColor==PrefColor) break; } + // Set color + int32_t iColor=BoundBy(PrefColor,0,C4MaxColor-1); + while (::Players.ColorTaken(iColor)) + { ++iColor%=C4MaxColor; if (iColor==PrefColor) break; } Color=iColor; C4PlayerInfo *pInfo = GetInfo(); @@ -689,46 +689,46 @@ bool C4Player::ScenarioInit() // any team selection is over now Status = PS_Normal; - // Wealth, home base materials, abilities - Wealth=Game.C4S.PlrStart[PlrStartIndex].Wealth.Evaluate(); - HomeBaseMaterial=Game.C4S.PlrStart[PlrStartIndex].HomeBaseMaterial; - HomeBaseMaterial.ConsolidateValids(::Definitions); - HomeBaseProduction=Game.C4S.PlrStart[PlrStartIndex].HomeBaseProduction; - HomeBaseProduction.ConsolidateValids(::Definitions); - Knowledge=Game.C4S.PlrStart[PlrStartIndex].BuildKnowledge; - Knowledge.ConsolidateValids(::Definitions); + // Wealth, home base materials, abilities + Wealth=Game.C4S.PlrStart[PlrStartIndex].Wealth.Evaluate(); + HomeBaseMaterial=Game.C4S.PlrStart[PlrStartIndex].HomeBaseMaterial; + HomeBaseMaterial.ConsolidateValids(::Definitions); + HomeBaseProduction=Game.C4S.PlrStart[PlrStartIndex].HomeBaseProduction; + HomeBaseProduction.ConsolidateValids(::Definitions); + Knowledge=Game.C4S.PlrStart[PlrStartIndex].BuildKnowledge; + Knowledge.ConsolidateValids(::Definitions); Magic=Game.C4S.PlrStart[PlrStartIndex].Magic; Magic.ConsolidateValids(::Definitions); if (Magic.IsClear()) Magic.Load(::Definitions,C4D_Magic); // All magic default if empty Magic.SortByValue(::Definitions); - // Starting position - ptx = Game.C4S.PlrStart[PlrStartIndex].Position[0]; - pty = Game.C4S.PlrStart[PlrStartIndex].Position[1]; + // Starting position + ptx = Game.C4S.PlrStart[PlrStartIndex].Position[0]; + pty = Game.C4S.PlrStart[PlrStartIndex].Position[1]; // Zoomed position if (ptx>-1) ptx = BoundBy( ptx * Game.C4S.Landscape.MapZoom.Evaluate(), 0, GBackWdt-1 ); if (pty>-1) pty = BoundBy( pty * Game.C4S.Landscape.MapZoom.Evaluate(), 0, GBackHgt-1 ); - // Standard position (PrefPosition) - if (ptx<0) - if (Game.StartupPlayerCount>=2) - { - int32_t iMaxPos=Game.StartupPlayerCount; - // Map preferred position to available positions + // Standard position (PrefPosition) + if (ptx<0) + if (Game.StartupPlayerCount>=2) + { + int32_t iMaxPos=Game.StartupPlayerCount; + // Map preferred position to available positions int32_t iStartPos=BoundBy(PrefPosition*iMaxPos/C4P_MaxPosition,0,iMaxPos-1); - int32_t iPosition=iStartPos; - // Distribute according to availability - while (::Players.PositionTaken(iPosition)) - { ++iPosition%=iMaxPos; if (iPosition==iStartPos) break; } + int32_t iPosition=iStartPos; + // Distribute according to availability + while (::Players.PositionTaken(iPosition)) + { ++iPosition%=iMaxPos; if (iPosition==iStartPos) break; } Position=iPosition; - // Set x position - ptx=BoundBy(16+Position*(GBackWdt-32)/(iMaxPos-1),0,GBackWdt-16); - } + // Set x position + ptx=BoundBy(16+Position*(GBackWdt-32)/(iMaxPos-1),0,GBackWdt-16); + } - // All-random position - if (ptx<0) ptx=16+Random(GBackWdt-32); - if (pty<0) pty=16+Random(GBackHgt-32); + // All-random position + if (ptx<0) ptx=16+Random(GBackWdt-32); + if (pty<0) pty=16+Random(GBackHgt-32); // Place to solid ground if (!Game.C4S.PlrStart[PlrStartIndex].EnforcePosition) @@ -739,12 +739,12 @@ bool C4Player::ScenarioInit() FindConSiteSpot(ptx, pty, 30,50,C4D_Structure, 400); } - // Place Readies + // Place Readies C4Object *FirstBase = NULL; PlaceReadyBase(ptx,pty,&FirstBase); PlaceReadyMaterial(ptx-10,ptx+10,pty,FirstBase); PlaceReadyVehic(ptx-30,ptx+30,pty,FirstBase); - PlaceReadyCrew(ptx-30,ptx+30,pty,FirstBase); + PlaceReadyCrew(ptx-30,ptx+30,pty,FirstBase); // set initial hostility by team info if (Team) SetTeamHostility(); @@ -764,11 +764,11 @@ bool C4Player::ScenarioInit() C4VInt(Team), C4VID(GetInfo()->GetScriptPlayerExtraID()))); return true; - } + } bool C4Player::FinalInit(bool fInitialValue) - { - if (!Status) return true; + { + if (!Status) return true; // Init player's mouse control if (LocalControl) @@ -784,7 +784,7 @@ bool C4Player::FinalInit(bool fInitialValue) // Update counts, pointers, views, value UpdateValue(); - Execute(); + Execute(); // Restore FoW after savegame if (fFogOfWar && !fFogOfWarInitialized) @@ -807,7 +807,7 @@ void C4Player::SetFoW(bool fEnable) } bool C4Player::DoWealth(int32_t iChange) - { + { if (LocalControl) { if (iChange>0) StartSoundEffect("Cash"); @@ -815,26 +815,26 @@ bool C4Player::DoWealth(int32_t iChange) } SetWealth(Wealth+iChange); - return true; - } + return true; + } bool C4Player::SetWealth(int32_t iVal) - { + { if(iVal == Wealth) return true; - Wealth=BoundBy(iVal,0,10000); + Wealth=BoundBy(iVal,0,10000); ViewWealth = C4ViewDelay; Game.Script.GRBroadcast(PSF_OnWealthChanged,&C4AulParSet(C4VInt(Number))); - return true; - } + return true; + } void C4Player::SetViewMode(int32_t iMode, C4Object *pTarget) - { + { // safe back - ViewMode=iMode; ViewTarget=pTarget; - } + ViewMode=iMode; ViewTarget=pTarget; + } void C4Player::ResetCursorView() { @@ -844,17 +844,17 @@ void C4Player::ResetCursorView() } void C4Player::Evaluate() - { + { // do not evaluate twice if (Evaluated) return; - const int32_t SuccessBonus=100; + const int32_t SuccessBonus=100; - // Set last round - LastRound.Title = Game.ScenarioTitle; - time(reinterpret_cast(&LastRound.Date)); - LastRound.Duration = Game.Time; - LastRound.Won = !Eliminated; + // Set last round + LastRound.Title = Game.ScenarioTitle; + time(reinterpret_cast(&LastRound.Date)); + LastRound.Duration = Game.Time; + LastRound.Won = !Eliminated; // Melee: personal value gain score ...check ::Objects(C4D_Goal) if (Game.C4S.Game.IsMelee()) LastRound.Score = Max(ValueGain,0); // Cooperative: shared score @@ -865,37 +865,37 @@ void C4Player::Evaluate() LastRound.TotalScore = Score + LastRound.FinalScore; // Update player - Rounds++; - if (LastRound.Won) RoundsWon++; else RoundsLost++; - Score=LastRound.TotalScore; - TotalPlayingTime+=Game.Time-GameJoinTime; + Rounds++; + if (LastRound.Won) RoundsWon++; else RoundsLost++; + Score=LastRound.TotalScore; + TotalPlayingTime+=Game.Time-GameJoinTime; - // Crew + // Crew CrewInfoList.Evaluate(); // league if (Game.Parameters.isLeague()) - EvaluateLeague(false, Game.GameOver && !Eliminated); + EvaluateLeague(false, Game.GameOver && !Eliminated); // Player is now evaluated Evaluated = true; // round results Game.RoundResults.EvaluatePlayer(this); - } + } void C4Player::Surrender() - { + { if (Surrendered) return; - Surrendered=true; - Eliminated=true; + Surrendered=true; + Eliminated=true; RetireDelay=C4RetireDelay; - StartSoundEffect("Eliminated"); + StartSoundEffect("Eliminated"); Log(FormatString(LoadResStr("IDS_PRC_PLRSURRENDERED"),GetName()).getData()); - } + } bool C4Player::SetHostility(int32_t iOpponent, int32_t hostile, bool fSilent) - { + { assert(hostile == 0 || hostile == 1); // Check opponent valid C4Player *opponent = ::Players.Get(iOpponent); @@ -913,8 +913,8 @@ bool C4Player::SetHostility(int32_t iOpponent, int32_t hostile, bool fSilent) Log(FormatString(LoadResStr(hostile ? "IDS_PLR_HOSTILITY" : "IDS_PLR_NOHOSTILITY"), GetName(),opponent->GetName()).getData()); // Success - return true; - } + return true; + } bool C4Player::IsHostileTowards(const C4Player *plr) const { @@ -1046,13 +1046,13 @@ bool C4Player::Load(const char *szFilename, bool fSavegame, bool fLoadPortraits) { C4Group hGroup; // Open group - if (!hGroup.Open(szFilename)) return false; + if (!hGroup.Open(szFilename)) return false; // Load core - if (!C4PlayerInfoCore::Load(hGroup)) + if (!C4PlayerInfoCore::Load(hGroup)) { hGroup.Close(); return false; } // Load BigIcon if (hGroup.FindEntry(C4CFN_BigIcon)) BigIcon.Load(hGroup, C4CFN_BigIcon); - // Load crew info list + // Load crew info list CrewInfoList.Load(hGroup, fLoadPortraits); // Close group hGroup.Close(); @@ -1157,20 +1157,20 @@ bool C4Player::MakeCrewMember(C4Object *pObj, bool fForceInfo, bool fDoCalls) } void C4Player::ExecuteControl() - { - Control.Execute(); - } + { + Control.Execute(); + } void C4Player::AdjustCursorCommand() - { - // Reset view - ResetCursorView(); - // Set cursor to hirank Select clonk - C4Object *pHiRank=NULL; - // Find hirank Select + { + // Reset view + ResetCursorView(); + // Set cursor to hirank Select clonk + C4Object *pHiRank=NULL; + // Find hirank Select pHiRank = GetHiRankActiveCrew(true); - // If none, check non-Selects as well - if (!pHiRank) + // If none, check non-Selects as well + if (!pHiRank) pHiRank = GetHiRankActiveCrew(false); // The cursor is on someone else: set the cursor to the hirank C4Object* pPrev = Cursor; @@ -1183,148 +1183,148 @@ void C4Player::AdjustCursorCommand() if (pPrev && pPrev != Cursor) pPrev->UnSelect(true); // We have a cursor: do select it if (Cursor) { /*Cursor->DoSelect(true);*/ Cursor->DoSelect(); } // Hmm, why DoSelect() twice? I hope the second one is the correct one... - // Updates - CursorFlash=30; - } + // Updates + CursorFlash=30; + } void C4Player::CursorRight() - { - C4ObjectLink *cLnk; - // Get next crew member - if ((cLnk=Crew.GetLink(Cursor))) - for (cLnk=cLnk->Next; cLnk; cLnk=cLnk->Next) - if (cLnk->Obj->Status && !cLnk->Obj->CrewDisabled) break; - if (!cLnk) - for (cLnk=Crew.First; cLnk; cLnk=cLnk->Next) - if (cLnk->Obj->Status && !cLnk->Obj->CrewDisabled) break; + { + C4ObjectLink *cLnk; + // Get next crew member + if ((cLnk=Crew.GetLink(Cursor))) + for (cLnk=cLnk->Next; cLnk; cLnk=cLnk->Next) + if (cLnk->Obj->Status && !cLnk->Obj->CrewDisabled) break; + if (!cLnk) + for (cLnk=Crew.First; cLnk; cLnk=cLnk->Next) + if (cLnk->Obj->Status && !cLnk->Obj->CrewDisabled) break; if (cLnk) SetCursor(cLnk->Obj, false, true); - // Updates - CursorFlash=30; - CursorSelection=1; + // Updates + CursorFlash=30; + CursorSelection=1; UpdateView(); - } + } void C4Player::CursorLeft() - { - C4ObjectLink *cLnk; - // Get prev crew member - if ((cLnk=Crew.GetLink(Cursor))) - for (cLnk=cLnk->Prev; cLnk; cLnk=cLnk->Prev) - if (cLnk->Obj->Status && !cLnk->Obj->CrewDisabled) break; - if (!cLnk) - for (cLnk=Crew.Last; cLnk; cLnk=cLnk->Prev) - if (cLnk->Obj->Status && !cLnk->Obj->CrewDisabled) break; - if (cLnk) SetCursor(cLnk->Obj, false, true); - // Updates - CursorFlash=30; - CursorSelection=1; + { + C4ObjectLink *cLnk; + // Get prev crew member + if ((cLnk=Crew.GetLink(Cursor))) + for (cLnk=cLnk->Prev; cLnk; cLnk=cLnk->Prev) + if (cLnk->Obj->Status && !cLnk->Obj->CrewDisabled) break; + if (!cLnk) + for (cLnk=Crew.Last; cLnk; cLnk=cLnk->Prev) + if (cLnk->Obj->Status && !cLnk->Obj->CrewDisabled) break; + if (cLnk) SetCursor(cLnk->Obj, false, true); + // Updates + CursorFlash=30; + CursorSelection=1; UpdateView(); - } + } void C4Player::UnselectCrew() - { - C4Object *cObj; C4ObjectLink *cLnk; bool fCursorDeselected = false; - for (cLnk=Crew.First; cLnk && (cObj=cLnk->Obj); cLnk=cLnk->Next) + { + C4Object *cObj; C4ObjectLink *cLnk; bool fCursorDeselected = false; + for (cLnk=Crew.First; cLnk && (cObj=cLnk->Obj); cLnk=cLnk->Next) { if (Cursor == cObj) fCursorDeselected = true; - if (cObj->Status) - cObj->UnSelect(); + if (cObj->Status) + cObj->UnSelect(); } // if cursor is outside crew (done by some scenarios), unselect that one, too! (script callback) if (Cursor && !fCursorDeselected) Cursor->UnSelect(); - } + } void C4Player::SelectSingleByCursor() - { - // Unselect crew - UnselectCrew(); - // Select cursor - if (Cursor) Cursor->DoSelect(); - // Updates - SelectFlash=30; - AdjustCursorCommand(); - } + { + // Unselect crew + UnselectCrew(); + // Select cursor + if (Cursor) Cursor->DoSelect(); + // Updates + SelectFlash=30; + AdjustCursorCommand(); + } void C4Player::SelectSingle(C4Object *tobj) - { + { // clear previous cursor if (Cursor) Cursor->UnSelect(true); - // Set cursor - Cursor=tobj; + // Set cursor + Cursor=tobj; if (Cursor) Cursor->DoSelect(true); - // Now use PlayerSelectSingleByCursor - SelectSingleByCursor(); - } + // Now use PlayerSelectSingleByCursor + SelectSingleByCursor(); + } void C4Player::CursorToggle() - { - C4ObjectLink *clnk; + { + C4ObjectLink *clnk; // Selection mode: toggle cursor select - if (CursorSelection) - { - if (Cursor) + if (CursorSelection) + { + if (Cursor) { if (Cursor->Select) Cursor->UnSelect(); else Cursor->DoSelect(); } - CursorToggled=1; - } + CursorToggled=1; + } // Pure toggle: toggle all Select - else - { - for (clnk=Crew.First; clnk; clnk=clnk->Next) + else + { + for (clnk=Crew.First; clnk; clnk=clnk->Next) if (!clnk->Obj->CrewDisabled) { if (clnk->Obj->Select) clnk->Obj->UnSelect(); else clnk->Obj->DoSelect(); } - AdjustCursorCommand(); - } - // Updates - SelectFlash=30; - } + AdjustCursorCommand(); + } + // Updates + SelectFlash=30; + } void C4Player::SelectAllCrew() - { - C4ObjectLink *clnk; - // Select all crew - for (clnk=Crew.First; clnk; clnk=clnk->Next) - clnk->Obj->DoSelect(); - // Updates - AdjustCursorCommand(); - CursorSelection=CursorToggled=0; - SelectFlash=30; - // Game display - if (LocalControl) StartSoundEffect("Ding"); - } + { + C4ObjectLink *clnk; + // Select all crew + for (clnk=Crew.First; clnk; clnk=clnk->Next) + clnk->Obj->DoSelect(); + // Updates + AdjustCursorCommand(); + CursorSelection=CursorToggled=0; + SelectFlash=30; + // Game display + if (LocalControl) StartSoundEffect("Ding"); + } void C4Player::UpdateSelectionToggleStatus() - { - if (CursorSelection) - { + { + if (CursorSelection) + { // Select toggled: cursor to hirank - if (CursorToggled) - AdjustCursorCommand(); + if (CursorToggled) + AdjustCursorCommand(); // Cursor select only: single control - else - SelectSingleByCursor(); - } - CursorSelection=0; - CursorToggled=0; - } + else + SelectSingleByCursor(); + } + CursorSelection=0; + CursorToggled=0; + } bool C4Player::ObjectCommand(int32_t iCommand, C4Object *pTarget, int32_t iX, int32_t iY, C4Object *pTarget2, C4Value iData, int32_t iMode) - { + { // Eliminated - if (Eliminated) return false; - // Hide startup - if (ShowStartup) ShowStartup=false; + if (Eliminated) return false; + // Hide startup + if (ShowStartup) ShowStartup=false; // Update selection & toggle status - UpdateSelectionToggleStatus(); - // Apply to all selected crew members (in cursor range) except pTarget. + UpdateSelectionToggleStatus(); + // Apply to all selected crew members (in cursor range) except pTarget. // Set, Add, Append mode flags may be combined and have a priority order. - C4ObjectLink *cLnk; C4Object *cObj; bool fCursorProcessed = false; - for (cLnk=Crew.First; cLnk && (cObj=cLnk->Obj); cLnk=cLnk->Next) + C4ObjectLink *cLnk; C4Object *cObj; bool fCursorProcessed = false; + for (cLnk=Crew.First; cLnk && (cObj=cLnk->Obj); cLnk=cLnk->Next) { if (cObj == Cursor) fCursorProcessed = true; if (cObj->Status) if (cObj->Select) @@ -1358,8 +1358,8 @@ bool C4Player::ObjectCommand(int32_t iCommand, C4Object *pTarget, int32_t iX, in ObjectCommand2Obj(Cursor, iCommand, pTarget, iX, iY, pTarget2, iData, iMode); // Success - return true; - } + return true; + } void C4Player::ObjectCommand2Obj(C4Object *cObj, int32_t iCommand, C4Object *pTarget, int32_t iX, int32_t iY, C4Object *pTarget2, C4Value iData, int32_t iMode) { @@ -1426,7 +1426,7 @@ void C4Player::CompileFunc(StdCompiler *pComp, bool fExact) // Keys held down pComp->Value(Control); - } + } bool C4Player::LoadRuntimeData(C4Group &hGroup) { @@ -1438,7 +1438,7 @@ bool C4Player::LoadRuntimeData(C4Group &hGroup) // Compile (Search player section - runtime data is stored by unique player ID) // Always compile exact. Exact data will not be present for savegame load, so it does not matter assert(ID); - if(!CompileFromBuf_LogWarn( + if(!CompileFromBuf_LogWarn( mkNamingAdapt(mkParAdapt(*this, true), FormatString("Player%i", ID).getData()), StdStrBuf(pSource), Game.GameText.GetFilePath())) @@ -1452,33 +1452,33 @@ bool C4Player::LoadRuntimeData(C4Group &hGroup) void C4Player::ExecHomeBaseProduction() { const int32_t MaxHomeBaseProduction = 25; - ProductionDelay++; - if (ProductionDelay>=60) // Minute Production Unit - { - ProductionDelay=0; ProductionUnit++; - for (int32_t cnt=0; HomeBaseProduction.GetID(cnt); cnt++) - if (HomeBaseProduction.GetCount(cnt)>0) - if (ProductionUnit % BoundBy(11-HomeBaseProduction.GetCount(cnt),1,10) ==0) + ProductionDelay++; + if (ProductionDelay>=60) // Minute Production Unit + { + ProductionDelay=0; ProductionUnit++; + for (int32_t cnt=0; HomeBaseProduction.GetID(cnt); cnt++) + if (HomeBaseProduction.GetCount(cnt)>0) + if (ProductionUnit % BoundBy(11-HomeBaseProduction.GetCount(cnt),1,10) ==0) if (HomeBaseMaterial.GetIDCount(HomeBaseProduction.GetID(cnt))Obj); clnk=clnk->Next) - { nclkcnt++; if (cobj->Select) nselcnt++; } - if (CrewCnt!=nclkcnt) CrewCnt=nclkcnt; - if (SelectCount!=nselcnt) SelectCount=nselcnt; + int32_t nclkcnt,nselcnt; + C4Object *cobj; C4ObjectLink *clnk; + nclkcnt=nselcnt=0; + for (clnk=Crew.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) + { nclkcnt++; if (cobj->Select) nselcnt++; } + if (CrewCnt!=nclkcnt) CrewCnt=nclkcnt; + if (SelectCount!=nselcnt) SelectCount=nselcnt; } void C4Player::CheckElimination() { // Standard elimination: no crew - if (CrewCnt<=0) + if (CrewCnt<=0) // Already eliminated safety if (!Eliminated) // No automatic elimination desired? @@ -1490,27 +1490,27 @@ void C4Player::CheckElimination() void C4Player::UpdateView() { // view target/cursor - switch (ViewMode) - { - case C4PVM_Cursor: + switch (ViewMode) + { + case C4PVM_Cursor: { C4Object *pViewObj; if (!(pViewObj=ViewCursor)) pViewObj=Cursor; - if (pViewObj) + if (pViewObj) { ViewX=pViewObj->GetX(); ViewY=pViewObj->GetY(); } - break; + break; } - case C4PVM_Target: - if (ViewTarget) + case C4PVM_Target: + if (ViewTarget) { ViewX=ViewTarget->GetX(); ViewY=ViewTarget->GetY(); } - break; + break; case C4PVM_Scrolling: break; - } + } } void C4Player::DefaultRuntimeData() @@ -1599,7 +1599,7 @@ void C4Player::DenumeratePointers() void C4Player::RemoveCrewObjects() { - C4Object *pCrew; + C4Object *pCrew; // Remove all crew objects while ((pCrew = Crew.GetObject())) pCrew->AssignRemoval(true); @@ -1607,7 +1607,7 @@ void C4Player::RemoveCrewObjects() void C4Player::NotifyOwnedObjects() { - C4Object *cobj; C4ObjectLink *clnk; + C4Object *cobj; C4ObjectLink *clnk; // notify objects in all object lists for (C4ObjectList *pList = &::Objects; pList; pList = ((pList == &::Objects) ? &::Objects.InactiveObjects : NULL)) @@ -1636,29 +1636,29 @@ void C4Player::SetCursor(C4Object *pObj, bool fSelectFlash, bool fSelectArrow) bool fChanged = pObj != Cursor; C4Object *pPrev = Cursor; // Set cursor - Cursor=pObj; + Cursor=pObj; // unselect previous if (pPrev && fChanged) pPrev->UnSelect(true); // Select object - if (Cursor) { Cursor->DoSelect(true); /*Cursor->DoSelect();*/ } // Sven2: why the second DoSelect()? - it breaks cursor-toggle-selection + if (Cursor) { Cursor->DoSelect(true); /*Cursor->DoSelect();*/ } // Sven2: why the second DoSelect()? - it breaks cursor-toggle-selection // View flash - if (fSelectArrow) CursorFlash=30; + if (fSelectArrow) CursorFlash=30; if (fSelectFlash) SelectFlash=30; } void C4Player::SelectCrew(C4ObjectList &rList) { - // Unselect + // Unselect UnselectCrew(); // Select (does not check whether objects are in crew) - C4ObjectLink *clnk; - for (clnk=rList.First; clnk; clnk=clnk->Next) + C4ObjectLink *clnk; + for (clnk=rList.First; clnk; clnk=clnk->Next) if (clnk->Obj->Status) clnk->Obj->DoSelect(); // Updates - AdjustCursorCommand(); - CursorSelection=CursorToggled=0; - SelectFlash=30; + AdjustCursorCommand(); + CursorSelection=CursorToggled=0; + SelectFlash=30; } void C4Player::ScrollView(int32_t iX, int32_t iY, int32_t ViewWdt, int32_t ViewHgt) @@ -1759,8 +1759,8 @@ void C4Player::FoW2Map(CClrModAddMap &rMap, int iOffX, int iOffY) // Add view for all FoW-repellers - keep track of FoW-generators, which should be avaluated finally // so they override repellers bool fAnyGenerators = false; - C4Object *cobj; C4ObjectLink *clnk; - for (clnk=FoWViewObjs.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) + C4Object *cobj; C4ObjectLink *clnk; + for (clnk=FoWViewObjs.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) if (!cobj->Contained || cobj->Contained->Def->ClosedContainer != 1) { if (cobj->PlrViewRange > 0) @@ -1787,7 +1787,7 @@ void C4Player::FoWGenerators2Map(CClrModAddMap &rMap, int iOffX, int iOffY) { // add fog to any generator pos (view range C4Object *cobj; C4ObjectLink *clnk; - for (clnk=FoWViewObjs.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) + for (clnk=FoWViewObjs.First; clnk && (cobj=clnk->Obj); clnk=clnk->Next) if (!cobj->Contained || cobj->Contained->Def->ClosedContainer != 1) if (cobj->PlrViewRange < 0) rMap.AddModulation(cobj->GetX() + iOffX, cobj->GetY() + iOffY,-cobj->PlrViewRange, ((uint32_t)cobj->ColorMod)>>24); @@ -1798,7 +1798,7 @@ bool C4Player::FoWIsVisible(int32_t x, int32_t y) // check repellers and generators and ViewTarget bool fSeen=false; C4Object *cobj=NULL; C4ObjectLink *clnk; - clnk=FoWViewObjs.First; + clnk=FoWViewObjs.First; int32_t iRange; for(;;) { @@ -1821,10 +1821,10 @@ bool C4Player::FoWIsVisible(int32_t x, int32_t y) if (Distance(cobj->GetX(), cobj->GetY(), x, y) < Abs(iRange)) { if (iRange < 0) - { - if ((cobj->ColorMod & 0xff000000) != 0xff000000) // faded generators generate darkness only; no FoW blocking + { + if ((cobj->ColorMod & 0xff000000) != 0xff000000) // faded generators generate darkness only; no FoW blocking return false; // shadowed by FoW-generator - } + } else fSeen = true; // made visible by FoW-repeller } @@ -1836,13 +1836,13 @@ void C4Player::SelectCrew(C4Object *pObj, bool fSelect) { // Not a valid crew member if (!pObj || !Crew.GetLink(pObj)) return; - // Select/unselect + // Select/unselect if (fSelect) pObj->DoSelect(); else pObj->UnSelect(); - // Updates - SelectFlash=30; - CursorSelection=CursorToggled=0; - AdjustCursorCommand(); + // Updates + SelectFlash=30; + CursorSelection=CursorToggled=0; + AdjustCursorCommand(); } void C4Player::CloseMenu() @@ -1852,11 +1852,11 @@ void C4Player::CloseMenu() } void C4Player::Eliminate() - { + { if (Eliminated) return; - Eliminated=true; + Eliminated=true; RetireDelay=C4RetireDelay; - StartSoundEffect("Eliminated"); + StartSoundEffect("Eliminated"); Log(FormatString(LoadResStr("IDS_PRC_PLRELIMINATED"),GetName()).getData()); // Early client deactivation check @@ -1873,7 +1873,7 @@ void C4Player::Eliminate() new C4ControlClientUpdate(AtClient, CUT_Activate, false), CDT_Sync); } - } + } int32_t C4Player::ActiveCrewCount() { @@ -1905,15 +1905,15 @@ void C4Player::EvaluateLeague(bool fDisconnected, bool fWon) { // already evaluated? if (LeagueEvaluated) return; LeagueEvaluated=true; - // set fate - C4PlayerInfo *pInfo = GetInfo(); - if(pInfo) - { - if(fDisconnected) - pInfo->SetDisconnected(); - if(fWon) - pInfo->SetWinner(); - } + // set fate + C4PlayerInfo *pInfo = GetInfo(); + if(pInfo) + { + if(fDisconnected) + pInfo->SetDisconnected(); + if(fWon) + pInfo->SetWinner(); + } } bool C4Player::LocalSync() diff --git a/src/game/player/C4PlayerList.cpp b/src/game/player/C4PlayerList.cpp index aa820065c..a1a613517 100644 --- a/src/game/player/C4PlayerList.cpp +++ b/src/game/player/C4PlayerList.cpp @@ -110,32 +110,32 @@ bool C4PlayerList::HostilityDeclared(int iPlayer1, int iPlayer2) const } bool C4PlayerList::PositionTaken(int iPosition) const - { + { for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) - if (pPlr->Position==iPosition) - return true; - return false; - } + if (pPlr->Position==iPosition) + return true; + return false; + } bool C4PlayerList::ColorTaken(int iColor) const - { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) - if (pPlr->Color==iColor) - return true; - return false; - } + { + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + if (pPlr->Color==iColor) + return true; + return false; + } int C4PlayerList::CheckColorDw(DWORD dwColor, C4Player *pExclude) { // maximum difference int iDiff=255+255+255; // check all player's color difference - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr != pExclude) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr != pExclude) { // get color DWORD dwClr2=pPlr->ColorDw; // assign difference, if less than smallest difference found - iDiff=Min(iDiff, + iDiff=Min(iDiff, Abs(GetRValue(dwColor) - GetRValue(dwClr2)) + Abs(GetGValue(dwColor) - GetGValue(dwClr2)) + Abs(GetBValue(dwColor) - GetBValue(dwClr2))); @@ -146,7 +146,7 @@ int C4PlayerList::CheckColorDw(DWORD dwColor, C4Player *pExclude) C4Player* C4PlayerList::Get(int iNumber) const { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr->Number==iNumber) return pPlr; return NULL; @@ -155,7 +155,7 @@ C4Player* C4PlayerList::Get(int iNumber) const int C4PlayerList::GetIndex(C4Player *tPlr) const { int cindex=0; - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next, cindex++) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next, cindex++) if (pPlr==tPlr) return cindex; return -1; @@ -163,7 +163,7 @@ int C4PlayerList::GetIndex(C4Player *tPlr) const C4Player* C4PlayerList::GetByIndex(int iIndex) const { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (!iIndex--) return pPlr; return NULL; @@ -171,7 +171,7 @@ C4Player* C4PlayerList::GetByIndex(int iIndex) const C4Player* C4PlayerList::GetByIndex(int iIndex, C4PlayerType eType) const { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr->GetType() == eType) if (!iIndex--) return pPlr; @@ -180,7 +180,7 @@ C4Player* C4PlayerList::GetByIndex(int iIndex, C4PlayerType eType) const C4Player *C4PlayerList::GetByInfoID(int iInfoID) const { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr->ID == iInfoID) return pPlr; return NULL; } @@ -188,7 +188,7 @@ C4Player *C4PlayerList::GetByInfoID(int iInfoID) const int C4PlayerList::GetCount() const { int iCount = 0; - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) iCount++; return iCount; } @@ -196,7 +196,7 @@ int C4PlayerList::GetCount() const int C4PlayerList::GetCount(C4PlayerType eType) const { int iCount = 0; - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr->GetType() == eType) iCount++; return iCount; @@ -249,11 +249,11 @@ bool C4PlayerList::Remove(C4Player *pPlr, bool fDisconnect, bool fNoCalls) { C4PlayerInfo *pInfo = Game.PlayerInfos.GetPlayerInfoByID(pPlr->ID); if (pInfo) - { - pInfo->SetRemoved(); - if(fDisconnect) - pInfo->SetDisconnected(); - } + { + pInfo->SetRemoved(); + if(fDisconnect) + pInfo->SetDisconnected(); + } // if player wasn't evaluated, store round results anyway if (!pPlr->Evaluated) Game.RoundResults.EvaluatePlayer(pPlr); } @@ -454,7 +454,7 @@ int C4PlayerList::AverageValueGain() const C4Player* C4PlayerList::GetByName(const char *szName, int iExcluding) const { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (SEqual(pPlr->GetName(),szName)) if (pPlr->Number!=iExcluding) return pPlr; @@ -485,7 +485,7 @@ bool C4PlayerList::FileInUse(const char *szFilename) const C4Player* C4PlayerList::GetLocalByIndex(int iIndex) const { int cindex=0; - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr->LocalControl) { if (cindex==iIndex) return pPlr; @@ -552,7 +552,7 @@ bool C4PlayerList::CtrlRemoveAtClient(const char *szName, bool fDisconnect) C4Player* C4PlayerList::GetAtClient(int iClient, int iIndex) const { int cindex=0; - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr->AtClient == iClient) { if (cindex==iIndex) return pPlr; @@ -564,7 +564,7 @@ C4Player* C4PlayerList::GetAtClient(int iClient, int iIndex) const C4Player* C4PlayerList::GetAtClient(const char *szName, int iIndex) const { int cindex=0; - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (SEqualNoCase(pPlr->AtClientName,szName)) { if (cindex==iIndex) return pPlr; @@ -590,7 +590,7 @@ bool C4PlayerList::RemoveAtRemoteClient(bool fDisconnect, bool fNoCalls) C4Player* C4PlayerList::GetAtRemoteClient(int iIndex) const { int cindex=0; - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (pPlr->AtClient != ::Control.ClientID()) { if (cindex==iIndex) return pPlr; @@ -620,29 +620,29 @@ bool C4PlayerList::RemoveLocal(bool fDisconnect, bool fNoCalls) void C4PlayerList::EnumeratePointers() { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) pPlr->EnumeratePointers(); } void C4PlayerList::DenumeratePointers() { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) pPlr->DenumeratePointers(); } bool C4PlayerList::MouseControlTaken() const { - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) - if (pPlr->MouseControl) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + if (pPlr->MouseControl) if (pPlr->LocalControl) return true; - return false; + return false; } int C4PlayerList::GetCountNotEliminated() const { int iCount = 0; - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) if (!pPlr->Eliminated) iCount++; return iCount; @@ -654,7 +654,7 @@ bool C4PlayerList::SynchronizeLocalFiles() Log(LoadResStr("IDS_PRC_SYNCPLRS")); bool fSuccess = true; // check all players - for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) + for (C4Player *pPlr=First; pPlr; pPlr=pPlr->Next) // eliminated players will be saved soon, anyway if (!pPlr->Eliminated) if (!pPlr->LocalSync()) fSuccess = false; diff --git a/src/game/player/C4RankSystem.cpp b/src/game/player/C4RankSystem.cpp index ef38e470b..dc864936b 100644 --- a/src/game/player/C4RankSystem.cpp +++ b/src/game/player/C4RankSystem.cpp @@ -33,14 +33,14 @@ #include C4RankSystem::C4RankSystem() - { + { Default(); - } + } int C4RankSystem::Init(const char *szRegister, const char *szDefRanks, int iRankBase) - { + { // Init SCopy(szRegister,Register,256); @@ -94,7 +94,7 @@ int C4RankSystem::Init(const char *szRegister, } return iRankNum; #endif - } + } bool C4RankSystem::Load(C4Group &hGroup, const char *szFilenames, int DefRankBase, const char *szLanguage) { @@ -187,8 +187,8 @@ bool C4RankSystem::Load(C4Group &hGroup, const char *szFilenames, int DefRankBas } StdStrBuf C4RankSystem::GetRankName(int iRank, bool fReturnLastIfOver) - { - if (iRank<0) return StdStrBuf(); + { + if (iRank<0) return StdStrBuf(); // if a new-style ranklist is loaded, seek there if (pszRankNames) { @@ -227,14 +227,14 @@ StdStrBuf C4RankSystem::GetRankName(int iRank, bool fReturnLastIfOver) --iRank; } #endif - return StdStrBuf(); + return StdStrBuf(); } int C4RankSystem::Experience(int iRank) - { - if (iRank<0) return 0; - return (int) ( pow (double(iRank), 1.5) * RankBase ); - } + { + if (iRank<0) return 0; + return (int) ( pow (double(iRank), 1.5) * RankBase ); + } int C4RankSystem::RankByExperience(int iExp) { diff --git a/src/game/player/C4RankSystem.h b/src/game/player/C4RankSystem.h index 62fbd750c..c9d823bf7 100644 --- a/src/game/player/C4RankSystem.h +++ b/src/game/player/C4RankSystem.h @@ -29,14 +29,14 @@ class C4Facet; class C4FacetSurface; class C4RankSystem - { - public: - C4RankSystem(); + { + public: + C4RankSystem(); ~C4RankSystem() { Clear(); } enum { EXP_NoPromotion = -1 }; // experience value for NextRankExp: No more promotion possible - protected: + protected: char Register[256+1]; char RankName[C4MaxName+1]; int RankBase; @@ -45,20 +45,20 @@ class C4RankSystem int iRankNum; // number of ranks for loaded rank-names char **pszRankExtensions; // rank extensions (e.g. "%s First class") for even more ranks! int iRankExtNum; // number of rank extensions - public: + public: void Default(); void Clear(); - int Init(const char *szRegister, const char *szDefRanks, int iRankBase); + int Init(const char *szRegister, const char *szDefRanks, int iRankBase); bool Load(C4Group &hGroup, const char *szFilenames, int DefRankBase, const char *szLanguage); // init based on nk file in group - int Experience(int iRank); + int Experience(int iRank); int RankByExperience(int iExp); // get rank by experience - StdStrBuf GetRankName(int iRank, bool fReturnLastIfOver); + StdStrBuf GetRankName(int iRank, bool fReturnLastIfOver); bool Check(int iRank, const char *szDefRankName); int32_t GetExtendedRankNum() const { return iRankExtNum; } int32_t GetBaseRankNum() const { return iRankNum; } //void Reset(const char *szDefRanks); static bool DrawRankSymbol(C4FacetSurface *fctSymbol, int32_t iRank, C4Facet *pfctRankSymbols, int32_t iRankSymbolCount, bool fOwnSurface, int32_t iXOff=0, C4Facet *cgoDrawDirect=NULL); // create facet from rank symbol for definition - use custom rank facets if present - }; + }; extern C4RankSystem DefaultRanks; diff --git a/src/game/script/C4Effect.cpp b/src/game/script/C4Effect.cpp index 7f1deb6a4..4b82e4fe2 100644 --- a/src/game/script/C4Effect.cpp +++ b/src/game/script/C4Effect.cpp @@ -568,16 +568,16 @@ int32_t FnFxFireStart(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_ // In extinguishing material bool fFireCaused=true; int32_t iMat; - if (MatValid(iMat=GBackMat(pObj->GetX(),pObj->GetY()))) - if (::MaterialMap.Map[iMat].Extinguisher) + if (MatValid(iMat=GBackMat(pObj->GetX(),pObj->GetY()))) + if (::MaterialMap.Map[iMat].Extinguisher) { // blasts should changedef in water, too! if (fBlasted) if (pObj->Def->BurnTurnTo!=C4ID::None) pObj->ChangeDef(pObj->Def->BurnTurnTo); // no fire caused fFireCaused = false; } - // BurnTurnTo - if (fFireCaused) if (pObj->Def->BurnTurnTo!=C4ID::None) pObj->ChangeDef(pObj->Def->BurnTurnTo); + // BurnTurnTo + if (fFireCaused) if (pObj->Def->BurnTurnTo!=C4ID::None) pObj->ChangeDef(pObj->Def->BurnTurnTo); // eject contents C4Object *cobj; if (!pObj->Def->IncompleteActivity && !pObj->Def->NoBurnDecay) @@ -610,8 +610,8 @@ int32_t FnFxFireStart(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_ if (dwCat & (C4D_Living | C4D_StaticBack)) // Tiere, Bäume iFireMode = C4Fx_FireMode_LivingVeg; else if (dwCat & (C4D_Structure | C4D_Vehicle)) // Gebäude und Fahrzeuge sind unten meist kantig - iFireMode = C4Fx_FireMode_StructVeh; - else + iFireMode = C4Fx_FireMode_StructVeh; + else iFireMode = C4Fx_FireMode_Object; } else if (!Inside(iFireMode, 1, C4Fx_FireMode_Last)) @@ -631,7 +631,7 @@ int32_t FnFxFireStart(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_ // Engine script call pObj->Call(PSF_Incineration,&C4AulParSet(C4VInt(iCausedBy))); // Done, success - return C4Fx_OK; + return C4Fx_OK; } int32_t FnFxFireTimer(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_t iTime) @@ -686,9 +686,9 @@ int32_t FnFxFireTimer(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_ // get remainign size (%) iCon=iWdtCon=Max((100*pObj->GetCon())/FullCon, 1); - if(!pObj->Def->GrowthType) + if(!pObj->Def->GrowthType) // fixed width for not-stretched-objects - if(iWdtCon<100) iWdtCon=100; + if(iWdtCon<100) iWdtCon=100; // regard non-center object offsets iX += pObj->Shape.x + pObj->Shape.Wdt/2; @@ -707,10 +707,10 @@ int32_t FnFxFireTimer(C4AulContext *ctx, C4Object *pObj, int32_t iNumber, int32_ } // Adjust particle number by con - iCount = Max(2, iCount*iWdtCon/100); + iCount = Max(2, iCount*iWdtCon/100); // calc base for particle size parameter - iA=(int32_t) (sqrt(sqrt(double(iWidth * iHeight))*(iCon+20)/120)*iRelParticleSize); + iA=(int32_t) (sqrt(sqrt(double(iWidth * iHeight))*(iCon+20)/120)*iRelParticleSize); // create a double set of particles; first quarter normal (Fire); remaining three quarters additive (Fire2) for(int32_t i=0; i=20) + // Splash sound + if (amt>=20) StartSoundEffect("Splash2",false,100,pByObj); - else + else if (amt>1) StartSoundEffect("Splash1",false,100,pByObj); - } + } int32_t GetSmokeLevel() { @@ -826,7 +826,7 @@ int32_t GetSmokeLevel() } void BubbleOut(int32_t tx, int32_t ty) - { + { // No bubbles from nowhere if (!GBackSemiSolid(tx,ty)) return; // User-defined smoke level @@ -835,10 +835,10 @@ void BubbleOut(int32_t tx, int32_t ty) if (::Objects.ObjectCount(C4ID("FXU1")) >= SmokeLevel) return; // Create bubble Game.CreateObject(C4ID("FXU1"),NULL,NO_OWNER,tx,ty); - } + } void Smoke(int32_t tx, int32_t ty, int32_t level, DWORD dwClr) - { + { if (::Particles.pSmoke) { ::Particles.Create(::Particles.pSmoke, float(tx), float(ty)-level/2, 0.0f, 0.0f, float(level), dwClr); @@ -853,22 +853,22 @@ void Smoke(int32_t tx, int32_t ty, int32_t level, DWORD dwClr) C4Object *pObj; if ((pObj = Game.CreateObjectConstruction(C4Id2Def(C4ID("FXS1")),NULL,NO_OWNER,tx,ty,FullCon*level/32))) pObj->Call(PSF_Activate); - } + } void Explosion(int32_t tx, int32_t ty, int32_t level, C4Object *inobj, int32_t iCausedBy, C4Object *pByObj, C4ID idEffect, const char *szEffect) - { - int32_t grade=BoundBy((level/10)-1,1,3); - // Sound - StdStrBuf sound = FormatString("Blast%c", '0'+grade); - StartSoundEffect(sound.getData(),false,100,pByObj); + { + int32_t grade=BoundBy((level/10)-1,1,3); + // Sound + StdStrBuf sound = FormatString("Blast%c", '0'+grade); + StartSoundEffect(sound.getData(),false,100,pByObj); // Check blast containment - C4Object *container=inobj; - while (container && !container->Def->ContainBlast) container=container->Contained; - // Uncontained blast effects - if (!container) - { + C4Object *container=inobj; + while (container && !container->Def->ContainBlast) container=container->Contained; + // Uncontained blast effects + if (!container) + { // Incinerate landscape - if (!::Landscape.Incinerate(tx,ty)) + if (!::Landscape.Incinerate(tx,ty)) if (!::Landscape.Incinerate(tx,ty-10)) if (!::Landscape.Incinerate(tx-5,ty-5)) ::Landscape.Incinerate(tx+5,ty-5); @@ -892,14 +892,14 @@ void Explosion(int32_t tx, int32_t ty, int32_t level, C4Object *inobj, int32_t i else if ((pBlast = Game.CreateObjectConstruction(C4Id2Def(idEffect ? idEffect : C4ID("FXB1")),pByObj,iCausedBy,tx,ty+level,FullCon*level/20))) pBlast->Call(PSF_Activate); - } - // Blast objects - Game.BlastObjects(tx,ty,level,inobj,iCausedBy,pByObj); - if (container!=inobj) Game.BlastObjects(tx,ty,level,container,iCausedBy,pByObj); + } + // Blast objects + Game.BlastObjects(tx,ty,level,inobj,iCausedBy,pByObj); + if (container!=inobj) Game.BlastObjects(tx,ty,level,container,iCausedBy,pByObj); if (!container) { // Blast free landscape. After blasting objects so newly mined materials don't get flinged ::Landscape.BlastFree(tx,ty,level,grade, iCausedBy); } - } + } diff --git a/src/game/script/C4Script.cpp b/src/game/script/C4Script.cpp index bad5db089..fa6088894 100644 --- a/src/game/script/C4Script.cpp +++ b/src/game/script/C4Script.cpp @@ -169,8 +169,8 @@ bool CheckEnergyNeedChain(C4Object *pObj, C4ObjectList &rEnergyChainChecked) return true; // Check all power line connected structures - C4Object *cline; C4ObjectLink *clnk; - for (clnk=::Objects.First; clnk && (cline=clnk->Obj); clnk=clnk->Next) + C4Object *cline; C4ObjectLink *clnk; + for (clnk=::Objects.First; clnk && (cline=clnk->Obj); clnk=clnk->Next) if (cline->Status) if (cline->Def->id==C4ID::PowerLine) if (cline->Action.Target==pObj) if (CheckEnergyNeedChain(cline->Action.Target2,rEnergyChainChecked)) @@ -292,7 +292,7 @@ typedef Nillable C4Void; bool C4ValueToMatrix(C4Value& value, StdMeshMatrix* matrix) { - //if(value.GetType() != C4V_Array) return false; + //if(value.GetType() != C4V_Array) return false; const C4ValueArray* array = value.getArray(); if(!array) return false; return C4ValueToMatrix(*array, matrix); @@ -964,7 +964,7 @@ static bool FnFinishCommand(C4AulObjectContext *cthr, bool fSuccess, long iComma } static C4Value FnPlayerObjectCommand(C4AulContext *cthr, C4Value *pPars) - { + { PAR(int, iPlr); PAR(string, szCommand); PAR(object, pTarget); PAR(any, Tx); PAR(int, iTy); PAR(object, pTarget2); PAR(any, Data); // Player @@ -987,12 +987,12 @@ static C4Value FnPlayerObjectCommand(C4AulContext *cthr, C4Value *pPars) // Set pPlr->ObjectCommand(iCommand, pTarget, iTx, iTy, pTarget2, Data, C4P_Command_Set); // Success - return C4VTrue; - } + return C4VTrue; + } static C4String *FnGetAction(C4AulObjectContext *cthr) { - C4PropList* pActionDef = cthr->Obj->GetAction(); + C4PropList* pActionDef = cthr->Obj->GetAction(); if (!pActionDef) return String("Idle"); return String(pActionDef->GetName()); } @@ -1136,7 +1136,7 @@ static long FnGetDir(C4AulObjectContext *cthr) static bool FnGetEntrance(C4AulObjectContext *cthr) { - return cthr->Obj->EntranceStatus; + return cthr->Obj->EntranceStatus; } static long FnGetPhase(C4AulObjectContext *cthr) @@ -1392,8 +1392,8 @@ static Nillable FnGetMenu(C4AulObjectContext *cthr) } static bool FnCreateMenu(C4AulObjectContext *cthr, C4ID iSymbol, C4Object *pCommandObj, - long iExtra, C4String *szCaption, long iExtraData, - long iStyle, bool fPermanent, C4ID idMenuID) + long iExtra, C4String *szCaption, long iExtraData, + long iStyle, bool fPermanent, C4ID idMenuID) { if (pCommandObj) // object menu: Validate object @@ -1425,7 +1425,7 @@ const int C4MN_Add_ImgRank = 1, C4MN_Add_ImgColor = 6, C4MN_Add_MaxImage = 127, // mask for param which decides what to draw as the menu symbol C4MN_Add_PassValue = 128, - C4MN_Add_ForceCount = 256, + C4MN_Add_ForceCount = 256, C4MN_Add_ForceNoDesc = 512; #ifndef _MSC_VER @@ -1499,10 +1499,10 @@ static C4Value FnAddMenuItem(C4AulContext *cthr, C4Value *pPars) sprintf(parameter, "C4Id(\"%s\")", Parameter.getPropList()->GetDef()->id.ToString()); break; case C4V_String: - // note this breaks if there is '"' in the string. - parameter[0] = '"'; - SCopy(Parameter.getStr()->GetCStr(), parameter + 1, sizeof(command)-3); - SAppendChar('"', command); + // note this breaks if there is '"' in the string. + parameter[0] = '"'; + SCopy(Parameter.getStr()->GetCStr(), parameter + 1, sizeof(command)-3); + SAppendChar('"', command); break; case C4V_Any: SCopy("nil", parameter); @@ -1846,8 +1846,8 @@ static bool FnComponentAll(C4AulObjectContext *cthr, C4ID c_id) } static C4Object *FnCreateObject(C4AulContext *cthr, - C4PropList * PropList, long iXOffset, long iYOffset, Nillable owner) - { + C4PropList * PropList, long iXOffset, long iYOffset, Nillable owner) + { if (cthr->Obj) // Local object calls override { iXOffset+=cthr->Obj->GetX(); @@ -1863,18 +1863,18 @@ static C4Object *FnCreateObject(C4AulContext *cthr, iOwner = NO_OWNER; } - C4Object *pNewObj = Game.CreateObject(PropList,cthr->Obj,iOwner,iXOffset,iYOffset); + C4Object *pNewObj = Game.CreateObject(PropList,cthr->Obj,iOwner,iXOffset,iYOffset); // Set initial controller to creating controller, so more complicated cause-effect-chains can be traced back to the causing player if (pNewObj && cthr->Obj && cthr->Obj->Controller > NO_OWNER) pNewObj->Controller = cthr->Obj->Controller; return pNewObj; - } + } static C4Object *FnCreateConstruction(C4AulContext *cthr, - C4PropList * PropList, long iXOffset, long iYOffset, Nillable owner, + C4PropList * PropList, long iXOffset, long iYOffset, Nillable owner, long iCompletion, bool fTerrain, bool fCheckSite) - { + { // Local object calls override position offset, owner if (cthr->Obj) { @@ -1903,7 +1903,7 @@ static C4Object *FnCreateConstruction(C4AulContext *cthr, if (pNewObj && cthr->Obj && cthr->Obj->Controller>NO_OWNER) pNewObj->Controller = cthr->Obj->Controller; return pNewObj; - } + } static C4Object *FnCreateContents(C4AulObjectContext *cthr, C4PropList * PropList, Nillable iCount) { @@ -1923,26 +1923,26 @@ static C4Object *FnComposeContents(C4AulObjectContext *cthr, C4ID c_id) } static bool FnFindConstructionSite(C4AulContext *cthr, C4PropList * PropList, C4Value * VarX, C4Value * VarY) - { + { // Get def Old-style implementation (fixed)... - C4Def *pDef; - if (!(pDef=PropList->GetDef())) return false; + C4Def *pDef; + if (!(pDef=PropList->GetDef())) return false; // Get thread vars if(!cthr->Caller) return false; - C4Value V1 = VarX->GetRefValConst(); + C4Value V1 = VarX->GetRefValConst(); C4Value V2 = VarY->GetRefValConst(); - // Construction check at starting position - if (ConstructionCheck(PropList,V1.getInt(),V2.getInt())) - return true; - // Search for real - int32_t v1 = V1.getInt(), v2 = V2.getInt(); - bool result = !!FindConSiteSpot(v1, v2, - pDef->Shape.Wdt,pDef->Shape.Hgt, - pDef->Category, - 20); - *VarX = C4VInt(v1); *VarY = C4VInt(v2); - return result; - } + // Construction check at starting position + if (ConstructionCheck(PropList,V1.getInt(),V2.getInt())) + return true; + // Search for real + int32_t v1 = V1.getInt(), v2 = V2.getInt(); + bool result = !!FindConSiteSpot(v1, v2, + pDef->Shape.Wdt,pDef->Shape.Hgt, + pDef->Category, + 20); + *VarX = C4VInt(v1); *VarY = C4VInt(v2); + return result; + } C4FindObject *CreateCriterionsFromPars(C4Value *pPars, C4FindObject **pFOs, C4SortObject **pSOs) { @@ -2032,7 +2032,7 @@ static C4Value FnFindObject(C4AulContext *cthr, C4Value *pPars) } static C4Value FnFindObjects(C4AulContext *cthr, C4Value *pPars) - { + { // Create FindObject-structure C4FindObject *pFOs[C4AUL_MAX_Par]; C4SortObject *pSOs[C4AUL_MAX_Par]; @@ -2057,18 +2057,18 @@ static bool FnGrabObjectInfo(C4AulObjectContext *cthr, C4Object *pFrom) } static bool FnSmoke(C4AulContext *cthr, long tx, long ty, long level, long dwClr) - { + { if (cthr->Obj) { tx+=cthr->Obj->GetX(); ty+=cthr->Obj->GetY(); } - Smoke(tx,ty,level,dwClr); - return true; - } + Smoke(tx,ty,level,dwClr); + return true; + } static bool FnBubble(C4AulContext *cthr, long tx, long ty) - { + { if (cthr->Obj) { tx+=cthr->Obj->GetX(); ty+=cthr->Obj->GetY(); } - BubbleOut(tx,ty); - return true; - } + BubbleOut(tx,ty); + return true; + } static bool FnInsertMaterial(C4AulContext *cthr, long mat, long x, long y, long vx, long vy) { @@ -2078,10 +2078,10 @@ static bool FnInsertMaterial(C4AulContext *cthr, long mat, long x, long y, long static long FnGetMaterialCount(C4AulContext *cthr, long iMaterial, bool fReal) { - if(!MatValid(iMaterial)) return -1; - if(fReal || !::MaterialMap.Map[iMaterial].MinHeightCount) - return ::Landscape.MatCount[iMaterial]; - else + if(!MatValid(iMaterial)) return -1; + if(fReal || !::MaterialMap.Map[iMaterial].MinHeightCount) + return ::Landscape.MatCount[iMaterial]; + else return ::Landscape.EffectiveMatCount[iMaterial]; } @@ -2213,7 +2213,7 @@ static bool FnMusic(C4AulContext *cthr, C4String *szSongname, bool fLoop) } if(::Control.SyncMode()) return true; return success; - } + } static long FnMusicLevel(C4AulContext *cthr, long iLevel) { @@ -2359,16 +2359,16 @@ static long FnMaterial(C4AulContext *cthr, C4String *mat_name) } C4Object* FnPlaceVegetation(C4AulContext *cthr, C4ID id, long iX, long iY, long iWdt, long iHgt, long iGrowth) - { + { // Local call: relative coordinates if (cthr->Obj) { iX+=cthr->Obj->GetX(); iY+=cthr->Obj->GetY(); } // Place vegetation - return Game.PlaceVegetation(id,iX,iY,iWdt,iHgt,iGrowth); + return Game.PlaceVegetation(id,iX,iY,iWdt,iHgt,iGrowth); } C4Object* FnPlaceAnimal(C4AulContext *cthr, C4ID id) - { - return Game.PlaceAnimal(id); + { + return Game.PlaceAnimal(id); } static bool FnDrawVolcanoBranch(C4AulContext *cthr, long mat, long fx, long fy, long tx, long ty, long size) @@ -2384,17 +2384,17 @@ static bool FnDrawVolcanoBranch(C4AulContext *cthr, long mat, long fx, long fy, } static bool FnHostile(C4AulContext *cthr, long iPlr1, long iPlr2, bool fCheckOneWayOnly) - { + { if (fCheckOneWayOnly) { return ::Players.HostilityDeclared(iPlr1,iPlr2); } else return !!Hostile(iPlr1,iPlr2); - } + } static bool FnSetHostility(C4AulContext *cthr, long iPlr, long iPlr2, bool fHostile, bool fSilent, bool fNoCalls) - { + { C4Player *pPlr = ::Players.Get(iPlr); if (!pPlr) return false; // do rejection test first @@ -2409,26 +2409,26 @@ static bool FnSetHostility(C4AulContext *cthr, long iPlr, long iPlr2, bool fHost // calls afterwards Game.Script.GRBroadcast(PSF_OnHostilityChange, &C4AulParSet(C4VInt(iPlr), C4VInt(iPlr2), C4VBool(fHostile), C4VBool(fOldHostility)), true); return true; - } + } static bool FnSetPlrView(C4AulContext *cthr, long iPlr, C4Object *tobj) - { - if (!ValidPlr(iPlr)) return false; - ::Players.Get(iPlr)->SetViewMode(C4PVM_Target,tobj); - return true; - } + { + if (!ValidPlr(iPlr)) return false; + ::Players.Get(iPlr)->SetViewMode(C4PVM_Target,tobj); + return true; + } static C4String *FnGetPlrControlName(C4AulContext *cthr, long iPlr, long iCon, bool fShort) - { - return String(PlrControlKeyName(iPlr,iCon,fShort).getData()); - } + { + return String(PlrControlKeyName(iPlr,iCon,fShort).getData()); + } static long FnGetPlrViewMode(C4AulContext *cthr, long iPlr) - { - if (!ValidPlr(iPlr)) return -1; + { + if (!ValidPlr(iPlr)) return -1; if (::Control.SyncMode()) return -1; - return ::Players.Get(iPlr)->ViewMode; - } + return ::Players.Get(iPlr)->ViewMode; + } static C4Void FnResetCursorView(C4AulContext *cthr, long plr) { @@ -2438,38 +2438,38 @@ static C4Void FnResetCursorView(C4AulContext *cthr, long plr) } static C4Object *FnGetPlrView(C4AulContext *cthr, long iPlr) - { + { C4Player *pPlr = ::Players.Get(iPlr); - if (!pPlr || pPlr->ViewMode != C4PVM_Target) return NULL; - return pPlr->ViewTarget; - } + if (!pPlr || pPlr->ViewMode != C4PVM_Target) return NULL; + return pPlr->ViewTarget; + } static bool FnDoHomebaseMaterial(C4AulContext *cthr, long iPlr, C4ID id, long iChange) { // validity check - if (!ValidPlr(iPlr)) return false; + if (!ValidPlr(iPlr)) return false; C4Def *pDef = C4Id2Def(id); if (!pDef) return false; // add to material long iLastcount = ::Players.Get(iPlr)->HomeBaseMaterial.GetIDCount(id); - return ::Players.Get(iPlr)->HomeBaseMaterial.SetIDCount(id,iLastcount+iChange,true); + return ::Players.Get(iPlr)->HomeBaseMaterial.SetIDCount(id,iLastcount+iChange,true); } static bool FnDoHomebaseProduction(C4AulContext *cthr, long iPlr, C4ID id, long iChange) { // validity check - if (!ValidPlr(iPlr)) return false; + if (!ValidPlr(iPlr)) return false; C4Def *pDef = C4Id2Def(id); if (!pDef) return false; // add to material long iLastcount = ::Players.Get(iPlr)->HomeBaseProduction.GetIDCount(id); - return ::Players.Get(iPlr)->HomeBaseProduction.SetIDCount(id,iLastcount+iChange,true); + return ::Players.Get(iPlr)->HomeBaseProduction.SetIDCount(id,iLastcount+iChange,true); } static bool FnSetPlrKnowledge(C4AulContext *cthr, long iPlr, C4ID id, bool fRemove) - { + { C4Player *pPlr=::Players.Get(iPlr); - if (!pPlr) return false; + if (!pPlr) return false; if (fRemove) { long iIndex=pPlr->Knowledge.GetIndex(id); @@ -2481,7 +2481,7 @@ static bool FnSetPlrKnowledge(C4AulContext *cthr, long iPlr, C4ID id, bool fRemo if(!C4Id2Def(id)) return false; return pPlr->Knowledge.SetIDCount(id,1,true); } - } + } static bool FnSetComponent(C4AulObjectContext *cthr, C4ID idComponent, long iCount) { @@ -2489,17 +2489,17 @@ static bool FnSetComponent(C4AulObjectContext *cthr, C4ID idComponent, long iCou } static C4Value FnGetPlrKnowledge_C4V(C4AulContext *cthr, C4Value* iPlr_C4V, C4Value* id_C4V, C4Value* iIndex_C4V, C4Value* dwCategory_C4V) - { + { long iPlr = iPlr_C4V->getInt(); C4ID id = id_C4V->getC4ID(); long iIndex = iIndex_C4V->getInt(); DWORD dwCategory = dwCategory_C4V->getInt(); - if (!ValidPlr(iPlr)) return C4VBool(false); + if (!ValidPlr(iPlr)) return C4VBool(false); // Search by id, check if available, return bool if (id) return C4VBool(::Players.Get(iPlr)->Knowledge.GetIDCount(id,1) != 0); // Search indexed item of given category, return C4ID return C4VID(::Players.Get(iPlr)->Knowledge.GetID( ::Definitions, dwCategory, iIndex )); - } + } static C4ID FnGetDefinition(C4AulContext *cthr, long iIndex, long dwCategory) { @@ -2513,7 +2513,7 @@ static C4ID FnGetDefinition(C4AulContext *cthr, long iIndex, long dwCategory) } static C4Value FnGetComponent_C4V(C4AulContext *cthr, C4Value* idComponent_C4V, C4Value* iIndex_C4V, C4Value* pObj_C4V, C4Value* idDef_C4V) - { + { C4ID idComponent = idComponent_C4V->getC4ID(); long iIndex = iIndex_C4V->getInt(); C4Object *pObj = pObj_C4V->getObj(); @@ -2540,7 +2540,7 @@ static C4Value FnGetComponent_C4V(C4AulContext *cthr, C4Value* idComponent_C4V, return C4VID(pObj->Component.GetID(iIndex)); } return C4Value(); - } + } static C4Value FnGetHomebaseMaterial_C4V(C4AulContext *cthr, C4Value* iPlr_C4V, C4Value* id_C4V, C4Value* iIndex_C4V, C4Value* dwCategory_C4V) { @@ -2549,7 +2549,7 @@ static C4Value FnGetHomebaseMaterial_C4V(C4AulContext *cthr, C4Value* iPlr_C4V, long iIndex = iIndex_C4V->getInt(); DWORD dwCategory = dwCategory_C4V->getInt(); - if (!ValidPlr(iPlr)) return C4VBool(false); + if (!ValidPlr(iPlr)) return C4VBool(false); // Search by id, return available count if (id) return C4VInt(::Players.Get(iPlr)->HomeBaseMaterial.GetIDCount(id)); // Search indexed item of given category, return C4ID @@ -2563,7 +2563,7 @@ static C4Value FnGetHomebaseProduction_C4V(C4AulContext *cthr, C4Value* iPlr_C4V long iIndex = iIndex_C4V->getInt(); DWORD dwCategory = dwCategory_C4V->getInt(); - if (!ValidPlr(iPlr)) return C4VBool(false); + if (!ValidPlr(iPlr)) return C4VBool(false); // Search by id, return available count if (id) return C4VInt(::Players.Get(iPlr)->HomeBaseProduction.GetIDCount(id)); // Search indexed item of given category, return C4ID @@ -2571,9 +2571,9 @@ static C4Value FnGetHomebaseProduction_C4V(C4AulContext *cthr, C4Value* iPlr_C4V } static long FnSetPlrMagic(C4AulContext *cthr, long iPlr, C4ID id, bool fRemove) - { + { C4Player *pPlr=::Players.Get(iPlr); - if (!pPlr) return false; + if (!pPlr) return false; if (fRemove) { long iIndex=pPlr->Magic.GetIndex(id); @@ -2585,83 +2585,83 @@ static long FnSetPlrMagic(C4AulContext *cthr, long iPlr, C4ID id, bool fRemove) if(!C4Id2Def(id)) return false; return pPlr->Magic.SetIDCount(id,1,true); } - } + } static C4Value FnGetPlrMagic_C4V(C4AulContext *cthr, C4Value* iPlr_C4V, C4Value* id_C4V, C4Value* iIndex_C4V) - { + { long iPlr = iPlr_C4V->getInt(); C4ID id = id_C4V->getC4ID(); long iIndex = iIndex_C4V->getInt(); - if (!ValidPlr(iPlr)) return C4VBool(false); + if (!ValidPlr(iPlr)) return C4VBool(false); // Search by id, check if available, return bool if (id) return C4VBool(::Players.Get(iPlr)->Magic.GetIDCount(id,1) != 0); // Search indexed item of given category, return C4ID return C4VID(::Players.Get(iPlr)->Magic.GetID( ::Definitions, C4D_Magic, iIndex )); - } + } static long FnGetWealth(C4AulContext *cthr, long iPlr) - { - if (!ValidPlr(iPlr)) return 0; - return ::Players.Get(iPlr)->Wealth; - } + { + if (!ValidPlr(iPlr)) return 0; + return ::Players.Get(iPlr)->Wealth; + } static bool FnSetWealth(C4AulContext *cthr, long iPlr, long iValue) - { - if (!ValidPlr(iPlr)) return false; - ::Players.Get(iPlr)->SetWealth(iValue); + { + if (!ValidPlr(iPlr)) return false; + ::Players.Get(iPlr)->SetWealth(iValue); return true; - } + } static long FnDoScore(C4AulContext *cthr, long iPlr, long iChange) - { - if (!ValidPlr(iPlr)) return false; - return ::Players.Get(iPlr)->DoPoints(iChange); - } + { + if (!ValidPlr(iPlr)) return false; + return ::Players.Get(iPlr)->DoPoints(iChange); + } static long FnGetPlrValue(C4AulContext *cthr, long iPlr) - { - if (!ValidPlr(iPlr)) return 0; - return ::Players.Get(iPlr)->Value; - } + { + if (!ValidPlr(iPlr)) return 0; + return ::Players.Get(iPlr)->Value; + } static long FnGetPlrValueGain(C4AulContext *cthr, long iPlr) - { - if (!ValidPlr(iPlr)) return 0; - return ::Players.Get(iPlr)->ValueGain; - } + { + if (!ValidPlr(iPlr)) return 0; + return ::Players.Get(iPlr)->ValueGain; + } static long FnGetScore(C4AulContext *cthr, long iPlr) - { - if (!ValidPlr(iPlr)) return 0; - return ::Players.Get(iPlr)->Points; - } + { + if (!ValidPlr(iPlr)) return 0; + return ::Players.Get(iPlr)->Points; + } static C4Object *FnGetHiRank(C4AulContext *cthr, long iPlr) - { - if (!ValidPlr(iPlr)) return false; - return ::Players.Get(iPlr)->GetHiRankActiveCrew(false); - } + { + if (!ValidPlr(iPlr)) return false; + return ::Players.Get(iPlr)->GetHiRankActiveCrew(false); + } static C4Object *FnGetCrew(C4AulContext *cthr, long iPlr, long index) - { - if (!ValidPlr(iPlr)) return false; - return ::Players.Get(iPlr)->Crew.GetObject(index); - } + { + if (!ValidPlr(iPlr)) return false; + return ::Players.Get(iPlr)->Crew.GetObject(index); + } static long FnGetCrewCount(C4AulContext *cthr, long iPlr) - { - if (!ValidPlr(iPlr)) return 0; - return ::Players.Get(iPlr)->Crew.ObjectCount(); - } + { + if (!ValidPlr(iPlr)) return 0; + return ::Players.Get(iPlr)->Crew.ObjectCount(); + } static long FnGetPlayerCount(C4AulContext *cthr, long iType) - { + { if (!iType) return ::Players.GetCount(); else return ::Players.GetCount((C4PlayerType) iType); - } + } static long FnGetPlayerByIndex(C4AulContext *cthr, long iIndex, long iType) { @@ -2675,7 +2675,7 @@ static long FnGetPlayerByIndex(C4AulContext *cthr, long iIndex, long iType) } static long FnEliminatePlayer(C4AulContext *cthr, long iPlr, bool fRemoveDirect) - { + { C4Player *pPlr=::Players.Get(iPlr); if (!pPlr) return false; // direct removal? @@ -2691,16 +2691,16 @@ static long FnEliminatePlayer(C4AulContext *cthr, long iPlr, bool fRemoveDirect) pPlr->Eliminate(); } return true; - } + } static bool FnSurrenderPlayer(C4AulContext *cthr, long iPlr) - { + { C4Player *pPlr=::Players.Get(iPlr); if (!pPlr) return false; if (pPlr->Eliminated) return false; - pPlr->Surrender(); + pPlr->Surrender(); return true; - } + } static bool FnSetLeaguePerformance(C4AulContext *cthr, long iScore) { @@ -2709,7 +2709,7 @@ static bool FnSetLeaguePerformance(C4AulContext *cthr, long iScore) } static const int32_t CSPF_FixedAttributes = 1<<0, - CSPF_NoScenarioInit = 1<<1, + CSPF_NoScenarioInit = 1<<1, CSPF_NoEliminationCheck = 1<<2, CSPF_Invisible = 1<<3; @@ -2737,13 +2737,13 @@ static bool FnCreateScriptPlayer(C4AulContext *cthr, C4String *szName, long dwCo } static C4Object *FnGetCursor(C4AulContext *cthr, long iPlr, long iIndex) - { + { // get player C4Player *pPlr = ::Players.Get(iPlr); // invalid player? if (!pPlr) return NULL; // first index is always the cursor - if (!iIndex) return pPlr->Cursor; + if (!iIndex) return pPlr->Cursor; // iterate through selected crew for iIndex times // status needs not be checked, as dead objects are never in Crew list C4Object *pCrew; @@ -2760,10 +2760,10 @@ static C4Object *FnGetCursor(C4AulContext *cthr, long iPlr, long iIndex) return pCrew; // nothing found at that index return NULL; - } + } static C4Object *FnGetViewCursor(C4AulContext *cthr, long iPlr) - { + { // get player C4Player *pPlr = ::Players.Get(iPlr); // get viewcursor @@ -2771,16 +2771,16 @@ static C4Object *FnGetViewCursor(C4AulContext *cthr, long iPlr) } static bool FnSetCursor(C4AulContext *cthr, long iPlr, C4Object *pObj, bool fNoSelectMark, bool fNoSelectArrow, bool fNoSelectCrew) - { + { C4Player *pPlr = ::Players.Get(iPlr); if (!pPlr || (pObj && !pObj->Status) || (pObj && pObj->CrewDisabled)) return false; pPlr->SetCursor(pObj, !fNoSelectMark, !fNoSelectArrow); if (!fNoSelectCrew) pPlr->SelectCrew(pObj, true); return true; - } + } static bool FnSetViewCursor(C4AulContext *cthr, long iPlr, C4Object *pObj) - { + { // get player C4Player *pPlr = ::Players.Get(iPlr); // invalid player? @@ -2791,7 +2791,7 @@ static bool FnSetViewCursor(C4AulContext *cthr, long iPlr, C4Object *pObj) } static bool FnSelectCrew(C4AulContext *cthr, long iPlr, C4Object *pObj, bool fSelect, bool fNoCursorAdjust) - { + { C4Player *pPlr = ::Players.Get(iPlr); if (!pPlr || !pObj) return false; if (fNoCursorAdjust) @@ -2799,7 +2799,7 @@ static bool FnSelectCrew(C4AulContext *cthr, long iPlr, C4Object *pObj, bool fSe else pPlr->SelectCrew(pObj,fSelect); return true; - } + } static bool FnGetCrewSelected(C4AulObjectContext *cthr) { @@ -2807,10 +2807,10 @@ static bool FnGetCrewSelected(C4AulObjectContext *cthr) } static long FnGetSelectCount(C4AulContext *cthr, long iPlr) - { - if (!ValidPlr(iPlr)) return false; - return ::Players.Get(iPlr)->SelectCount; - } + { + if (!ValidPlr(iPlr)) return false; + return ::Players.Get(iPlr)->SelectCount; + } static bool FnSetCrewStatus(C4AulObjectContext *cthr, long iPlr, bool fInCrew) { @@ -2822,13 +2822,13 @@ static bool FnSetCrewStatus(C4AulObjectContext *cthr, long iPlr, bool fInCrew) } static long FnGetWind(C4AulContext *cthr, long x, long y, bool fGlobal) - { + { // global wind if (fGlobal) return ::Weather.Wind; // local wind if (cthr->Obj) { x+=cthr->Obj->GetX(); y+=cthr->Obj->GetY(); } - return ::Weather.GetWind(x,y); - } + return ::Weather.GetWind(x,y); + } static C4Void FnSetWind(C4AulContext *cthr, long iWind) { @@ -2843,9 +2843,9 @@ static C4Void FnSetTemperature(C4AulContext *cthr, long iTemperature) } static long FnGetTemperature(C4AulContext *cthr) - { - return ::Weather.GetTemperature(); - } + { + return ::Weather.GetTemperature(); + } static C4Void FnSetSeason(C4AulContext *cthr, long iSeason) { @@ -2854,9 +2854,9 @@ static C4Void FnSetSeason(C4AulContext *cthr, long iSeason) } static long FnGetSeason(C4AulContext *cthr) - { - return ::Weather.GetSeason(); - } + { + return ::Weather.GetSeason(); + } static C4Void FnSetClimate(C4AulContext *cthr, long iClimate) { @@ -2865,9 +2865,9 @@ static C4Void FnSetClimate(C4AulContext *cthr, long iClimate) } static long FnGetClimate(C4AulContext *cthr) - { - return ::Weather.GetClimate(); - } + { + return ::Weather.GetClimate(); + } static long FnLandscapeWidth(C4AulContext *cthr) { @@ -2938,14 +2938,14 @@ static long FnSetTransferZone(C4AulObjectContext *cthr, long iX, long iY, long i } static C4Value FnEqual_C4V(C4AulContext *cthr, C4Value * Val1, C4Value * Val2) - { - return C4VBool(Val1->GetData()==Val2->GetData()); - } + { + return C4VBool(Val1->GetData()==Val2->GetData()); + } static long FnAbs(C4AulContext *cthr, long iVal) - { - return Abs(iVal); - } + { + return Abs(iVal); + } static long FnSin(C4AulContext *cthr, long iAngle, long iRadius, long iPrec) { @@ -3032,14 +3032,14 @@ static long FnArcCos(C4AulContext *cthr, long iVal, long iRadius) } static long FnMin(C4AulContext *cthr, long iVal1, long iVal2) - { - return Min(iVal1,iVal2); - } + { + return Min(iVal1,iVal2); + } static long FnMax(C4AulContext *cthr, long iVal1, long iVal2) - { - return Max(iVal1,iVal2); - } + { + return Max(iVal1,iVal2); + } static long FnDistance(C4AulContext *cthr, long iX1, long iY1, long iX2, long iY2) { @@ -3069,47 +3069,47 @@ static long FnShowInfo(C4AulObjectContext *cthr, C4Object *pObj) } static long FnBoundBy(C4AulContext *cthr, long iVal, long iRange1, long iRange2) - { - return BoundBy(iVal,iRange1,iRange2); - } + { + return BoundBy(iVal,iRange1,iRange2); + } static bool FnInside(C4AulContext *cthr, long iVal, long iRange1, long iRange2) - { - return Inside(iVal,iRange1,iRange2); - } + { + return Inside(iVal,iRange1,iRange2); + } static long FnRandom(C4AulContext *cthr, long iRange) - { - return Random(iRange); - } + { + return Random(iRange); + } static long FnAsyncRandom(C4AulContext *cthr, long iRange) - { - return SafeRandom(iRange); - } + { + return SafeRandom(iRange); + } static C4Value FnCall_C4V(C4AulContext *cthr, C4Value* szFunction_C4V, - C4Value* par0, C4Value* par1, C4Value* par2, C4Value* par3, C4Value* par4, + C4Value* par0, C4Value* par1, C4Value* par2, C4Value* par3, C4Value* par4, C4Value* par5, C4Value* par6, C4Value* par7, C4Value* par8/*, C4Value* par9*/) - { + { // safety C4String *szFunction = szFunction_C4V->getStr(); - if (!szFunction || !cthr->Obj) return C4Value(); + if (!szFunction || !cthr->Obj) return C4Value(); C4AulParSet Pars; Copy2ParSet9(Pars, *par); - return cthr->Obj->Call(FnStringPar(szFunction),&Pars, true); - } + return cthr->Obj->Call(FnStringPar(szFunction),&Pars, true); + } static C4Value FnDefinitionCall_C4V(C4AulContext *cthr, C4Value* idID_C4V, C4Value* szFunction_C4V, C4Value* par0, C4Value* par1, C4Value* par2, C4Value* par3, C4Value* par4, C4Value* par5, C4Value* par6, C4Value* par7/*, C4Value* par8, C4Value* par9*/) - { + { C4ID idID = idID_C4V->getC4ID(); C4String *szFunction = szFunction_C4V->getStr(); - if (!idID || !szFunction) return C4Value(); + if (!idID || !szFunction) return C4Value(); // Make failsafe char szFunc2[500+1]; sprintf(szFunc2,"~%s",FnStringPar(szFunction)); // Get definition @@ -3119,52 +3119,52 @@ static C4Value FnDefinitionCall_C4V(C4AulContext *cthr, C4AulParSet Pars; Copy2ParSet8(Pars, *par); // Call - return pDef->Script.Call(szFunc2, 0, &Pars, true); - } + return pDef->Script.Call(szFunc2, 0, &Pars, true); + } static C4Value FnGameCall_C4V(C4AulContext *cthr, - C4Value* szFunction_C4V, + C4Value* szFunction_C4V, C4Value* par0, C4Value* par1, C4Value* par2, C4Value* par3, C4Value* par4, C4Value* par5, C4Value* par6, C4Value* par7, C4Value* par8/*, C4Value* par9*/) - { + { C4String *szFunction = szFunction_C4V->getStr(); - if (!szFunction) return C4Value(); + if (!szFunction) return C4Value(); // Make failsafe char szFunc2[500+1]; sprintf(szFunc2,"~%s",FnStringPar(szFunction)); // copy parameters C4AulParSet Pars; Copy2ParSet9(Pars, *par); // Call - return Game.Script.Call(szFunc2, 0, &Pars, true); - } + return Game.Script.Call(szFunc2, 0, &Pars, true); + } static C4Value FnGameCallEx_C4V(C4AulContext *cthr, - C4Value* szFunction_C4V, + C4Value* szFunction_C4V, C4Value* par0, C4Value* par1, C4Value* par2, C4Value* par3, C4Value* par4, C4Value* par5, C4Value* par6, C4Value* par7, C4Value* par8/*, C4Value* par9*/) - { + { C4String *szFunction = szFunction_C4V->getStr(); - if (!szFunction) return C4Value(); + if (!szFunction) return C4Value(); // Make failsafe char szFunc2[500+1]; sprintf(szFunc2,"~%s",FnStringPar(szFunction)); // copy parameters C4AulParSet Pars; Copy2ParSet9(Pars, *par); // Call - return Game.Script.GRBroadcast(szFunc2,&Pars, true); - } + return Game.Script.GRBroadcast(szFunc2,&Pars, true); + } static C4Value FnProtectedCall_C4V(C4AulContext *cthr, - C4Value* pObj_C4V, C4Value* szFunction_C4V, + C4Value* pObj_C4V, C4Value* szFunction_C4V, C4Value* par0, C4Value* par1, C4Value* par2, C4Value* par3, C4Value* par4, C4Value* par5, C4Value* par6, C4Value* par7/*, C4Value* par8, C4Value* par9*/) - { + { C4Object *pObj = pObj_C4V->getObj(); C4String *szFunction = szFunction_C4V->getStr(); - if (!pObj || !szFunction) return C4Value(); + if (!pObj || !szFunction) return C4Value(); if (!pObj->Def) return C4Value(); // get func C4AulScriptFunc *f; @@ -3173,19 +3173,19 @@ static C4Value FnProtectedCall_C4V(C4AulContext *cthr, C4AulParSet Pars; Copy2ParSet8(Pars, *par); // exec - return f->Exec(pObj,&Pars, true); - } + return f->Exec(pObj,&Pars, true); + } static C4Value FnPrivateCall_C4V(C4AulContext *cthr, - C4Value* pObj_C4V, C4Value* szFunction_C4V, + C4Value* pObj_C4V, C4Value* szFunction_C4V, C4Value* par0, C4Value* par1, C4Value* par2, C4Value* par3, C4Value* par4, C4Value* par5, C4Value* par6, C4Value* par7/*, C4Value* par8, C4Value* par9*/) - { + { C4Object *pObj = pObj_C4V->getObj(); C4String *szFunction = szFunction_C4V->getStr(); - if (!pObj || !szFunction) return C4Value(); + if (!pObj || !szFunction) return C4Value(); if (!pObj->Def) return C4Value(); // get func C4AulScriptFunc *f; @@ -3194,8 +3194,8 @@ static C4Value FnPrivateCall_C4V(C4AulContext *cthr, C4AulParSet Pars; Copy2ParSet8(Pars, *par); // exec - return f->Exec(pObj,&Pars, true); - } + return f->Exec(pObj,&Pars, true); + } static C4Value FnEditCursor(C4AulContext *cth, C4Value *pPars) { @@ -3205,7 +3205,7 @@ static C4Value FnEditCursor(C4AulContext *cth, C4Value *pPars) static bool FnResort(C4AulContext *cthr, C4Object *pObj) { - if (!pObj) pObj=cthr->Obj; + if (!pObj) pObj=cthr->Obj; // Resort single object if (pObj) pObj->Resort(); @@ -3238,7 +3238,7 @@ static bool FnTestMessageBoard(C4AulContext *cthr, long iForPlr, bool fTestIfInU static bool FnCallMessageBoard(C4AulContext *cthr, C4Object *pObj, bool fUpperCase, C4String *szQueryString, long iForPlr) { - if (!pObj) pObj=cthr->Obj; + if (!pObj) pObj=cthr->Obj; if (pObj && !pObj->Status) return false; // check player C4Player *pPlr = ::Players.Get(iForPlr); @@ -3250,7 +3250,7 @@ static bool FnCallMessageBoard(C4AulContext *cthr, C4Object *pObj, bool fUpperCa static bool FnAbortMessageBoard(C4AulContext *cthr, C4Object *pObj, long iForPlr) { - if (!pObj) pObj=cthr->Obj; + if (!pObj) pObj=cthr->Obj; // check player C4Player *pPlr = ::Players.Get(iForPlr); if (!pPlr) return false; @@ -3481,30 +3481,30 @@ static bool FnGetMissionAccess(C4AulContext *cthr, C4String *strMissionAccess) class C4ValueCompiler : public StdCompiler { public: - C4ValueCompiler(const char **pszNames, int iNameCnt, int iEntryNr) - : pszNames(pszNames), iNameCnt(iNameCnt), iEntryNr(iEntryNr) - { } + C4ValueCompiler(const char **pszNames, int iNameCnt, int iEntryNr) + : pszNames(pszNames), iNameCnt(iNameCnt), iEntryNr(iEntryNr) + { } - virtual bool isCompiler() { return false; } - virtual bool hasNaming() { return true; } + virtual bool isCompiler() { return false; } + virtual bool hasNaming() { return true; } virtual bool isVerbose() { return false; } - virtual bool Name(const char *szName) - { - // match possible? (no match yet / continued match) - if(!iMatchStart || haveCurrentMatch()) - // already got all names? - if(!haveCompleteMatch()) - // check name - if(SEqual(pszNames[iMatchCount], szName)) - { - // got match - if(!iMatchCount) iMatchStart = iDepth + 1; - iMatchCount++; - } - iDepth++; - return true; - } + virtual bool Name(const char *szName) + { + // match possible? (no match yet / continued match) + if(!iMatchStart || haveCurrentMatch()) + // already got all names? + if(!haveCompleteMatch()) + // check name + if(SEqual(pszNames[iMatchCount], szName)) + { + // got match + if(!iMatchCount) iMatchStart = iDepth + 1; + iMatchCount++; + } + iDepth++; + return true; + } virtual bool Default(const char *szName) { @@ -3512,22 +3512,22 @@ public: return false; } - virtual void NameEnd(bool fBreak = false) - { - // end of matched name section? - if(haveCurrentMatch()) - { - iMatchCount--; - if(!iMatchCount) iMatchStart = 0; - } - iDepth--; - } + virtual void NameEnd(bool fBreak = false) + { + // end of matched name section? + if(haveCurrentMatch()) + { + iMatchCount--; + if(!iMatchCount) iMatchStart = 0; + } + iDepth--; + } - virtual void Begin() - { - // set up - iDepth = iMatchStart = iMatchCount = 0; - } + virtual void Begin() + { + // set up + iDepth = iMatchStart = iMatchCount = 0; + } protected: // value function forward to be overwritten by get or set compiler @@ -3538,57 +3538,57 @@ protected: virtual void ProcessString(char **pszString, bool fIsID) = 0; public: - // value functions - virtual void DWord(int32_t &rInt) { if(haveCompleteMatch()) if(!iEntryNr--) ProcessInt(rInt); } - virtual void DWord(uint32_t &rInt) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rInt; ProcessInt(i); rInt =i; } } - virtual void Word(int16_t &rShort) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rShort; ProcessInt(i); rShort=i; } } - virtual void Word(uint16_t &rShort) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rShort; ProcessInt(i); rShort=i; } } - virtual void Byte(int8_t &rByte) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rByte; ProcessInt(i); rByte =i; } } - virtual void Byte(uint8_t &rByte) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rByte; ProcessInt(i); rByte =i; } } - virtual void Boolean(bool &rBool) { if(haveCompleteMatch()) if(!iEntryNr--) ProcessBool(rBool); } - virtual void Character(char &rChar) { if(haveCompleteMatch()) if(!iEntryNr--) ProcessChar(rChar); } + // value functions + virtual void DWord(int32_t &rInt) { if(haveCompleteMatch()) if(!iEntryNr--) ProcessInt(rInt); } + virtual void DWord(uint32_t &rInt) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rInt; ProcessInt(i); rInt =i; } } + virtual void Word(int16_t &rShort) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rShort; ProcessInt(i); rShort=i; } } + virtual void Word(uint16_t &rShort) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rShort; ProcessInt(i); rShort=i; } } + virtual void Byte(int8_t &rByte) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rByte; ProcessInt(i); rByte =i; } } + virtual void Byte(uint8_t &rByte) { if(haveCompleteMatch()) if(!iEntryNr--) { int32_t i=rByte; ProcessInt(i); rByte =i; } } + virtual void Boolean(bool &rBool) { if(haveCompleteMatch()) if(!iEntryNr--) ProcessBool(rBool); } + virtual void Character(char &rChar) { if(haveCompleteMatch()) if(!iEntryNr--) ProcessChar(rChar); } - // The C4ID-Adaptor will set RCT_ID for it's strings (see C4Id.h), so we don't have to guess the type. - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType) - { if(haveCompleteMatch()) if(!iEntryNr--) ProcessString(szString, iMaxLength, eType == StdCompiler::RCT_ID); } - virtual void String(char **pszString, RawCompileType eType) - { if(haveCompleteMatch()) if(!iEntryNr--) ProcessString(pszString, eType == StdCompiler::RCT_ID); } - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped) - { /* C4Script can't handle this */ } + // The C4ID-Adaptor will set RCT_ID for it's strings (see C4Id.h), so we don't have to guess the type. + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType) + { if(haveCompleteMatch()) if(!iEntryNr--) ProcessString(szString, iMaxLength, eType == StdCompiler::RCT_ID); } + virtual void String(char **pszString, RawCompileType eType) + { if(haveCompleteMatch()) if(!iEntryNr--) ProcessString(pszString, eType == StdCompiler::RCT_ID); } + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped) + { /* C4Script can't handle this */ } private: - // Name(s) of the entry to read - const char **pszNames; - int iNameCnt; - // Number of the element that is to be read - int iEntryNr; + // Name(s) of the entry to read + const char **pszNames; + int iNameCnt; + // Number of the element that is to be read + int iEntryNr; - // current depth - int iDepth; - // match start (where did the first name match?), - // match count (how many names did match, from that point?) - int iMatchStart, iMatchCount; + // current depth + int iDepth; + // match start (where did the first name match?), + // match count (how many names did match, from that point?) + int iMatchStart, iMatchCount; private: - // match active? - bool haveCurrentMatch() const { return iDepth + 1 == iMatchStart + iMatchCount; } - // match complete? - bool haveCompleteMatch() const { return haveCurrentMatch() && iMatchCount == iNameCnt; } + // match active? + bool haveCurrentMatch() const { return iDepth + 1 == iMatchStart + iMatchCount; } + // match complete? + bool haveCompleteMatch() const { return haveCurrentMatch() && iMatchCount == iNameCnt; } }; class C4ValueGetCompiler : public C4ValueCompiler { private: - // Result - C4Value Res; + // Result + C4Value Res; public: C4ValueGetCompiler(const char **pszNames, int iNameCnt, int iEntryNr) - : C4ValueCompiler(pszNames, iNameCnt, iEntryNr) - { } + : C4ValueCompiler(pszNames, iNameCnt, iEntryNr) + { } - // Result-getter - const C4Value &getResult() const { return Res; } + // Result-getter + const C4Value &getResult() const { return Res; } protected: // get values as C4Value @@ -3673,7 +3673,7 @@ static C4Value FnGetScenarioVal(C4AulContext* cthr, C4Value* strEntry_C4V, C4Val const char *strSection = FnStringPar(strSection_C4V->getStr()); long iEntryNr = iEntryNr_C4V->getInt(); - if(strSection && !*strSection) strSection = NULL; + if(strSection && !*strSection) strSection = NULL; return GetValByStdCompiler(strEntry, strSection, iEntryNr, mkParAdapt(Game.C4S, false)); } @@ -4131,7 +4131,7 @@ static C4Value FnSetPlrExtraData(C4AulContext *cthr, C4Value *iPlayer_C4V, C4Val pPlayer->ExtraData[ival] = *Data; } // ok, return the value that has been set - return *Data; + return *Data; } static C4Value FnGetPlrExtraData(C4AulContext *cthr, C4Value *iPlayer_C4V, C4Value *strDataName_C4V) @@ -4181,7 +4181,7 @@ static C4Value FnSetCrewExtraData(C4AulContext *cthr, C4Value *strDataName_C4V, pInfo->ExtraData[ival] = *Data; } // ok, return the value that has been set - return *Data; + return *Data; } static C4Value FnGetCrewExtraData(C4AulContext *cthr, C4Value *strDataName_C4V) @@ -4472,10 +4472,10 @@ static long FnSetTextureIndex(C4AulContext *ctx, C4String *psMatTex, long iNewIn } static long FnRemoveUnusedTexMapEntries(C4AulContext *ctx) - { - ::Landscape.RemoveUnusedTexMapEntries(); - return true; - } + { + ::Landscape.RemoveUnusedTexMapEntries(); + return true; + } static bool FnSetLandscapePixel(C4AulContext* ctx, long iX, long iY, long dwValue) { @@ -4507,8 +4507,8 @@ static bool FnSetObjectOrder(C4AulContext* ctx, C4Object *pObjBeforeOrAfter, C4O } static const int32_t DMQ_Sky = 0, // draw w/ sky IFT - DMQ_Sub = 1, // draw w/ tunnel IFT - DMQ_Bridge = 2; // draw only over materials you can bridge over + DMQ_Sub = 1, // draw w/ tunnel IFT + DMQ_Bridge = 2; // draw only over materials you can bridge over static bool FnDrawMaterialQuad(C4AulContext* ctx, C4String *szMaterial, long iX1, long iY1, long iX2, long iY2, long iX3, long iY3, long iX4, long iY4, int draw_mode) { @@ -4692,7 +4692,7 @@ static bool FnSetObjDrawTransform2(C4AulObjectContext *ctx, long iA, long iB, lo #define COPY_C4V_PAR(Var, Par, ParType, Std) \ Var = (Par && Par->GetType() == ParType \ - ? Par->GetData().Int \ + ? Par->GetData().Int \ : Std) bool SimFlight(FIXED &x, FIXED &y, FIXED &xdir, FIXED &ydir, int32_t iDensityMin, int32_t iDensityMax, int32_t iIter); @@ -4971,7 +4971,7 @@ static long FnGetEffectCount(C4AulContext *ctx, C4String *psEffectName, C4Object } static C4Value FnEffectVar_C4V(C4AulContext *cthr, C4Value *pviVarIndex, C4Value *pvpObj, C4Value *pviEffectNumber) - { + { // get parameters C4Object *pObj = pvpObj->getObj(); long iVarIndex = pviVarIndex->getInt(), iEffectNumber = pviEffectNumber->getInt(); @@ -4982,8 +4982,8 @@ static C4Value FnEffectVar_C4V(C4AulContext *cthr, C4Value *pviVarIndex, C4Value if (!pEffect) return C4Value(); if (!(pEffect = pEffect->Get(iEffectNumber, true))) return C4Value(); // return ref to var - return pEffect->EffectVars[iVarIndex].GetRef(); - } + return pEffect->EffectVars[iVarIndex].GetRef(); + } static C4Value FnEffectCall_C4V(C4AulContext *ctx, C4Value *pvpTarget, C4Value *pviNumber, C4Value *pvsCallFn, C4Value *pvVal1, C4Value *pvVal2, C4Value *pvVal3, C4Value *pvVal4, C4Value *pvVal5, C4Value *pvVal6, C4Value *pvVal7) { @@ -5084,20 +5084,20 @@ static Nillable FnGetObjectBlitMode(C4AulObjectContext *ctx, long iOverlay } static bool FnSetViewOffset(C4AulContext *ctx, long iPlayer, long iX, long iY) - { - if(!ValidPlr(iPlayer)) return 0; - // get player viewport - C4Viewport *pView = ::GraphicsSystem.GetViewport(iPlayer); - if(!pView) return 1; // sync safety - // set - pView->ViewOffsX = iX; - pView->ViewOffsY = iY; - // ok - return 1; - } + { + if(!ValidPlr(iPlayer)) return 0; + // get player viewport + C4Viewport *pView = ::GraphicsSystem.GetViewport(iPlayer); + if(!pView) return 1; // sync safety + // set + pView->ViewOffsX = iX; + pView->ViewOffsY = iY; + // ok + return 1; + } static bool FnSetPreSend(C4AulContext *cthr, long iToVal, C4String *pNewName) - { + { if (!::Control.isNetwork()) return true; // dbg: manual presend const char *szClient = FnStringPar(pNewName); @@ -5107,7 +5107,7 @@ static bool FnSetPreSend(C4AulContext *cthr, long iToVal, C4String *pNewName) ::GraphicsSystem.FlashMessage(FormatString("TargetFPS: %ld", iToVal).getData()); } return true; - } + } static long FnGetPlayerID(C4AulContext *cthr, long iPlayer) { @@ -5201,14 +5201,14 @@ static long FnGetTeamConfig(C4AulContext *cthr, long iConfigValue) } static C4String *FnGetTeamName(C4AulContext *cthr, long iTeam) - { + { C4Team *pTeam = Game.Teams.GetTeamByID(iTeam); if (!pTeam) return NULL; return String(pTeam->GetName()); } static long FnGetTeamColor(C4AulContext *cthr, long iTeam) - { + { C4Team *pTeam = Game.Teams.GetTeamByID(iTeam); return pTeam ? pTeam->GetColor() : 0u; } @@ -6169,7 +6169,7 @@ void InitFunctionMap(C4AulScriptEngine *pEngine) AddFunc(pEngine, "GetScore", FnGetScore); AddFunc(pEngine, "GetPlrValue", FnGetPlrValue); AddFunc(pEngine, "GetPlrValueGain", FnGetPlrValueGain); - AddFunc(pEngine, "GetPlrControlName", FnGetPlrControlName); + AddFunc(pEngine, "GetPlrControlName", FnGetPlrControlName); AddFunc(pEngine, "GetWind", FnGetWind); AddFunc(pEngine, "SetWind", FnSetWind); AddFunc(pEngine, "GetTemperature", FnGetTemperature); @@ -6311,7 +6311,7 @@ void InitFunctionMap(C4AulScriptEngine *pEngine) AddFunc(pEngine, "DrawMatChunks", FnDrawMatChunks, false); AddFunc(pEngine, "GetPathLength", FnGetPathLength); AddFunc(pEngine, "SetTextureIndex", FnSetTextureIndex, false); - AddFunc(pEngine, "RemoveUnusedTexMapEntries", FnRemoveUnusedTexMapEntries, false); + AddFunc(pEngine, "RemoveUnusedTexMapEntries", FnRemoveUnusedTexMapEntries, false); AddFunc(pEngine, "SetObjDrawTransform", FnSetObjDrawTransform); AddFunc(pEngine, "SetObjDrawTransform2", FnSetObjDrawTransform2, false); AddFunc(pEngine, "SetPortrait", FnSetPortrait); @@ -6471,18 +6471,18 @@ C4ScriptConstDef C4ScriptConstMap[]={ { "DIR_Left" ,C4V_Int, DIR_Left}, { "DIR_Right" ,C4V_Int, DIR_Right}, - { "CON_CursorLeft" ,C4V_Int, CON_CursorLeft}, - { "CON_CursorToggle" ,C4V_Int, CON_CursorToggle}, - { "CON_CursorRight" ,C4V_Int, CON_CursorRight}, - { "CON_Throw" ,C4V_Int, CON_Throw}, - { "CON_Up" ,C4V_Int, CON_Up}, - { "CON_Dig" ,C4V_Int, CON_Dig}, - { "CON_Left" ,C4V_Int, CON_Left}, - { "CON_Down" ,C4V_Int, CON_Down}, - { "CON_Right" ,C4V_Int, CON_Right}, - { "CON_Menu" ,C4V_Int, CON_Menu}, - { "CON_Special" ,C4V_Int, CON_Special}, - { "CON_Special2" ,C4V_Int, CON_Special2}, + { "CON_CursorLeft" ,C4V_Int, CON_CursorLeft}, + { "CON_CursorToggle" ,C4V_Int, CON_CursorToggle}, + { "CON_CursorRight" ,C4V_Int, CON_CursorRight}, + { "CON_Throw" ,C4V_Int, CON_Throw}, + { "CON_Up" ,C4V_Int, CON_Up}, + { "CON_Dig" ,C4V_Int, CON_Dig}, + { "CON_Left" ,C4V_Int, CON_Left}, + { "CON_Down" ,C4V_Int, CON_Down}, + { "CON_Right" ,C4V_Int, CON_Right}, + { "CON_Menu" ,C4V_Int, CON_Menu}, + { "CON_Special" ,C4V_Int, CON_Special}, + { "CON_Special2" ,C4V_Int, CON_Special2}, { "OCF_Construct" ,C4V_Int, OCF_Construct}, { "OCF_Grab" ,C4V_Int, OCF_Grab}, @@ -6709,7 +6709,7 @@ C4ScriptConstDef C4ScriptConstMap[]={ { "TEAMID_New" ,C4V_Int, TEAMID_New }, - { "MSG_NoLinebreak" ,C4V_Int, C4GM_NoBreak }, + { "MSG_NoLinebreak" ,C4V_Int, C4GM_NoBreak }, { "MSG_Bottom" ,C4V_Int, C4GM_Bottom }, { "MSG_Multiple" ,C4V_Int, C4GM_Multiple }, { "MSG_Top" ,C4V_Int, C4GM_Top }, @@ -6756,78 +6756,78 @@ C4ScriptConstDef C4ScriptConstMap[]={ { NULL, C4V_Any, 0} }; #define MkFnC4V (C4Value (*)(C4AulContext *cthr, C4Value*, C4Value*, C4Value*, C4Value*, C4Value*,\ - C4Value*, C4Value*, C4Value*, C4Value*, C4Value*)) + C4Value*, C4Value*, C4Value*, C4Value*, C4Value*)) C4ScriptFnDef C4ScriptFnMap[]={ - { "Equal", 1 ,C4V_Any ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnEqual_C4V , 0 }, - { "SetProperty", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_PropList,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnSetProperty_C4V , 0 }, - { "GetProperty", 1 ,C4V_Any ,{ C4V_String ,C4V_PropList,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetProperty_C4V , 0 }, - { "PlayerObjectCommand", 1 ,C4V_Bool ,{ C4V_Int ,C4V_String ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_Any ,C4V_Any} ,0 , FnPlayerObjectCommand }, - { "SetCommand", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnSetCommand }, - { "AddCommand", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_C4Object,C4V_Int ,C4V_Any ,C4V_Int ,C4V_Int ,C4V_Any} ,0 , FnAddCommand }, - { "AppendCommand", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_C4Object,C4V_Int ,C4V_Any ,C4V_Int ,C4V_Int ,C4V_Any} ,0 , FnAppendCommand }, - { "GetCommand", 1 ,C4V_Any ,{ C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnGetCommand }, - { "PathFree2", 1 ,C4V_Bool ,{ C4V_Ref ,C4V_Ref ,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnPathFree2_C4V , 0 }, - { "FindObject", 1 ,C4V_C4Object ,{ C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnFindObject }, - { "FindObjects", 1 ,C4V_Array ,{ C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnFindObjects }, - { "ObjectCount", 1 ,C4V_Int ,{ C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnObjectCount }, - { "ProtectedCall", 1 ,C4V_Any ,{ C4V_C4Object,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnProtectedCall_C4V , 0 }, - { "PrivateCall", 1 ,C4V_Any ,{ C4V_C4Object,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnPrivateCall_C4V , 0 }, - { "GameCall", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGameCall_C4V , 0 }, - { "GameCallEx", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGameCallEx_C4V , 0 }, - { "DefinitionCall", 1 ,C4V_Any ,{ C4V_PropList,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnDefinitionCall_C4V , 0 }, - { "Call", 0 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnCall_C4V , 0 }, - { "GetPlrKnowledge", 1 ,C4V_Int ,{ C4V_Int ,C4V_PropList,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlrKnowledge_C4V , 0 }, - { "GetPlrMagic", 1 ,C4V_Int ,{ C4V_Int ,C4V_PropList,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlrMagic_C4V , 0 }, - { "GetComponent", 1 ,C4V_Int ,{ C4V_PropList,C4V_Int ,C4V_C4Object,C4V_PropList,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetComponent_C4V , 0 }, - { "PlayerMessage", 1 ,C4V_Int ,{ C4V_Int ,C4V_String ,C4V_C4Object,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnPlayerMessage_C4V, 0 }, - { "Message", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnMessage_C4V, 0 }, - { "AddMessage", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnAddMessage_C4V, 0 }, - { "PlrMessage", 1 ,C4V_Bool ,{ C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnPlrMessage_C4V, 0 }, - { "Log", 1 ,C4V_Bool ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnLog_C4V, 0 }, - { "DebugLog", 1 ,C4V_Bool ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnDebugLog_C4V, 0 }, - { "Format", 1 ,C4V_String ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnFormat_C4V, 0 }, - { "EditCursor", 1 ,C4V_C4Object ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnEditCursor }, - { "AddMenuItem", 1 ,C4V_Bool ,{ C4V_String ,C4V_String ,C4V_PropList,C4V_Int ,C4V_Any ,C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnAddMenuItem }, - { "GetHomebaseMaterial", 1 ,C4V_Int ,{ C4V_Int ,C4V_PropList,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetHomebaseMaterial_C4V , 0 }, - { "GetHomebaseProduction",1 ,C4V_Int ,{ C4V_Int ,C4V_PropList,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetHomebaseProduction_C4V , 0 }, + { "Equal", 1 ,C4V_Any ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnEqual_C4V , 0 }, + { "SetProperty", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_PropList,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnSetProperty_C4V , 0 }, + { "GetProperty", 1 ,C4V_Any ,{ C4V_String ,C4V_PropList,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetProperty_C4V , 0 }, + { "PlayerObjectCommand", 1 ,C4V_Bool ,{ C4V_Int ,C4V_String ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_Any ,C4V_Any} ,0 , FnPlayerObjectCommand }, + { "SetCommand", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnSetCommand }, + { "AddCommand", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_C4Object,C4V_Int ,C4V_Any ,C4V_Int ,C4V_Int ,C4V_Any} ,0 , FnAddCommand }, + { "AppendCommand", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Int ,C4V_C4Object,C4V_Int ,C4V_Any ,C4V_Int ,C4V_Int ,C4V_Any} ,0 , FnAppendCommand }, + { "GetCommand", 1 ,C4V_Any ,{ C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnGetCommand }, + { "PathFree2", 1 ,C4V_Bool ,{ C4V_Ref ,C4V_Ref ,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnPathFree2_C4V , 0 }, + { "FindObject", 1 ,C4V_C4Object ,{ C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnFindObject }, + { "FindObjects", 1 ,C4V_Array ,{ C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnFindObjects }, + { "ObjectCount", 1 ,C4V_Int ,{ C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnObjectCount }, + { "ProtectedCall", 1 ,C4V_Any ,{ C4V_C4Object,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnProtectedCall_C4V , 0 }, + { "PrivateCall", 1 ,C4V_Any ,{ C4V_C4Object,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnPrivateCall_C4V , 0 }, + { "GameCall", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGameCall_C4V , 0 }, + { "GameCallEx", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGameCallEx_C4V , 0 }, + { "DefinitionCall", 1 ,C4V_Any ,{ C4V_PropList,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnDefinitionCall_C4V , 0 }, + { "Call", 0 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnCall_C4V , 0 }, + { "GetPlrKnowledge", 1 ,C4V_Int ,{ C4V_Int ,C4V_PropList,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlrKnowledge_C4V , 0 }, + { "GetPlrMagic", 1 ,C4V_Int ,{ C4V_Int ,C4V_PropList,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlrMagic_C4V , 0 }, + { "GetComponent", 1 ,C4V_Int ,{ C4V_PropList,C4V_Int ,C4V_C4Object,C4V_PropList,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetComponent_C4V , 0 }, + { "PlayerMessage", 1 ,C4V_Int ,{ C4V_Int ,C4V_String ,C4V_C4Object,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnPlayerMessage_C4V, 0 }, + { "Message", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnMessage_C4V, 0 }, + { "AddMessage", 1 ,C4V_Bool ,{ C4V_String ,C4V_C4Object,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnAddMessage_C4V, 0 }, + { "PlrMessage", 1 ,C4V_Bool ,{ C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnPlrMessage_C4V, 0 }, + { "Log", 1 ,C4V_Bool ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnLog_C4V, 0 }, + { "DebugLog", 1 ,C4V_Bool ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnDebugLog_C4V, 0 }, + { "Format", 1 ,C4V_String ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V &FnFormat_C4V, 0 }, + { "EditCursor", 1 ,C4V_C4Object ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnEditCursor }, + { "AddMenuItem", 1 ,C4V_Bool ,{ C4V_String ,C4V_String ,C4V_PropList,C4V_Int ,C4V_Any ,C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnAddMenuItem }, + { "GetHomebaseMaterial", 1 ,C4V_Int ,{ C4V_Int ,C4V_PropList,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetHomebaseMaterial_C4V , 0 }, + { "GetHomebaseProduction",1 ,C4V_Int ,{ C4V_Int ,C4V_PropList,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetHomebaseProduction_C4V , 0 }, - { "IsRef", 1 ,C4V_Bool ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnIsRef, 0 }, - { "GetType", 1 ,C4V_Int ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetType, 0 }, + { "IsRef", 1 ,C4V_Bool ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnIsRef, 0 }, + { "GetType", 1 ,C4V_Int ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetType, 0 }, - { "CreateArray", 1 ,C4V_Array ,{ C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0, FnCreateArray }, - { "GetLength", 1 ,C4V_Int ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0, FnGetLength }, - { "GetIndexOf", 1 ,C4V_Int ,{ C4V_Any ,C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0, FnGetIndexOf }, + { "CreateArray", 1 ,C4V_Array ,{ C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0, FnCreateArray }, + { "GetLength", 1 ,C4V_Int ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0, FnGetLength }, + { "GetIndexOf", 1 ,C4V_Int ,{ C4V_Any ,C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0, FnGetIndexOf }, - { "GetDefCoreVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetDefCoreVal, 0 }, - { "GetObjectVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetObjectVal, 0 }, - { "GetObjectInfoCoreVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetObjectInfoCoreVal, 0 }, - { "GetScenarioVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetScenarioVal, 0 }, - { "GetPlayerVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlayerVal, 0 }, - { "GetPlayerInfoCoreVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlayerInfoCoreVal, 0 }, - { "GetMaterialVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetMaterialVal, 0 }, + { "GetDefCoreVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetDefCoreVal, 0 }, + { "GetObjectVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetObjectVal, 0 }, + { "GetObjectInfoCoreVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetObjectInfoCoreVal, 0 }, + { "GetScenarioVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetScenarioVal, 0 }, + { "GetPlayerVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlayerVal, 0 }, + { "GetPlayerInfoCoreVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlayerInfoCoreVal, 0 }, + { "GetMaterialVal", 1 ,C4V_Any ,{ C4V_String ,C4V_String ,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetMaterialVal, 0 }, - { "SetPlrExtraData", 1 ,C4V_Any ,{ C4V_Int ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnSetPlrExtraData, 0 }, - { "GetPlrExtraData", 1 ,C4V_Any ,{ C4V_Int ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlrExtraData, 0 }, - { "SetCrewExtraData", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnSetCrewExtraData, 0 }, - { "GetCrewExtraData", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetCrewExtraData, 0 }, - { "SimFlight", 1 ,C4V_Bool ,{ C4V_Ref ,C4V_Ref ,C4V_Ref ,C4V_Ref ,C4V_Int ,C4V_Int ,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any} ,MkFnC4V FnSimFlight, 0 }, - { "GetPortrait", 1 ,C4V_Any ,{ C4V_C4Object,C4V_Bool ,C4V_Bool ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPortrait, 0 }, - { "AddEffect", 1 ,C4V_Int ,{ C4V_String ,C4V_C4Object,C4V_Int ,C4V_Int ,C4V_C4Object,C4V_PropList,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnAddEffect_C4V, 0 }, - { "GetEffect", 1 ,C4V_Any ,{ C4V_String ,C4V_C4Object,C4V_Int ,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetEffect_C4V, 0 }, - { "CheckEffect", 1 ,C4V_Int ,{ C4V_String ,C4V_C4Object,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnCheckEffect_C4V, 0 }, - { "EffectCall", 1 ,C4V_Any ,{ C4V_C4Object,C4V_Int ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnEffectCall_C4V, 0 }, - { "EffectVar", 1 ,C4V_Ref ,{ C4V_Int ,C4V_C4Object,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnEffectVar_C4V, 0 }, + { "SetPlrExtraData", 1 ,C4V_Any ,{ C4V_Int ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnSetPlrExtraData, 0 }, + { "GetPlrExtraData", 1 ,C4V_Any ,{ C4V_Int ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPlrExtraData, 0 }, + { "SetCrewExtraData", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnSetCrewExtraData, 0 }, + { "GetCrewExtraData", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetCrewExtraData, 0 }, + { "SimFlight", 1 ,C4V_Bool ,{ C4V_Ref ,C4V_Ref ,C4V_Ref ,C4V_Ref ,C4V_Int ,C4V_Int ,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any} ,MkFnC4V FnSimFlight, 0 }, + { "GetPortrait", 1 ,C4V_Any ,{ C4V_C4Object,C4V_Bool ,C4V_Bool ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetPortrait, 0 }, + { "AddEffect", 1 ,C4V_Int ,{ C4V_String ,C4V_C4Object,C4V_Int ,C4V_Int ,C4V_C4Object,C4V_PropList,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnAddEffect_C4V, 0 }, + { "GetEffect", 1 ,C4V_Any ,{ C4V_String ,C4V_C4Object,C4V_Int ,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGetEffect_C4V, 0 }, + { "CheckEffect", 1 ,C4V_Int ,{ C4V_String ,C4V_C4Object,C4V_Int ,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnCheckEffect_C4V, 0 }, + { "EffectCall", 1 ,C4V_Any ,{ C4V_C4Object,C4V_Int ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnEffectCall_C4V, 0 }, + { "EffectVar", 1 ,C4V_Ref ,{ C4V_Int ,C4V_C4Object,C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnEffectVar_C4V, 0 }, - { "AttachMesh", 1 ,C4V_Int ,{ C4V_Any ,C4V_String ,C4V_String ,C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnAttachMesh }, + { "AttachMesh", 1 ,C4V_Int ,{ C4V_Any ,C4V_String ,C4V_String ,C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0 , FnAttachMesh }, - { "eval", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnEval, 0 }, + { "eval", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnEval, 0 }, - { "VarN", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnVarN, 0 }, - { "LocalN", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnLocalN, 0 }, - { "GlobalN", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGlobalN, 0 }, + { "VarN", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnVarN, 0 }, + { "LocalN", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnLocalN, 0 }, + { "GlobalN", 1 ,C4V_Any ,{ C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,MkFnC4V FnGlobalN, 0 }, - { NULL, 0 ,C4V_Any ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0, 0 } + { NULL, 0 ,C4V_Any ,{ C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any} ,0, 0 } - }; + }; diff --git a/src/game/script/C4Script.h b/src/game/script/C4Script.h index 92273eb6f..ddfee20a2 100644 --- a/src/game/script/C4Script.h +++ b/src/game/script/C4Script.h @@ -52,15 +52,15 @@ struct C4ScriptConstDef // * the second (C4V2) takes an array of 10 parameters // only one may be set. struct C4ScriptFnDef - { - const char* Identifier; // the name of the func in the script + { + const char* Identifier; // the name of the func in the script bool Public; C4V_Type RetType; // type returned. ignored when C4V C4V_Type ParType[10];// type of the parameters. error when wrong parameter type. C4Value (*FunctionC4V)(C4AulContext *cthr, C4Value*, C4Value*, C4Value*, C4Value*, C4Value*, C4Value*, C4Value*, C4Value*, C4Value*, C4Value*); C4Value (*FunctionC4V2)(struct C4AulContext *, C4Value *); - }; + }; extern C4ScriptConstDef C4ScriptConstMap[]; extern C4ScriptFnDef C4ScriptFnMap[]; diff --git a/src/gui/C4ChatDlg.cpp b/src/gui/C4ChatDlg.cpp index dd01e2061..8c39d1c93 100644 --- a/src/gui/C4ChatDlg.cpp +++ b/src/gui/C4ChatDlg.cpp @@ -388,13 +388,13 @@ C4ChatControl::C4ChatControl(C4Network2IRCClient *pnIRCClient) : C4GUI::Window() pEdtLoginChannel->SetText(Config.IRC.Channel, false); // initial sheets ClearChatSheets(); - // set IRC event callback - Application.InteractiveThread.SetCallback(Ev_IRC_Message, this); + // set IRC event callback + Application.InteractiveThread.SetCallback(Ev_IRC_Message, this); } C4ChatControl::~C4ChatControl() { - Application.InteractiveThread.ClearCallback(Ev_IRC_Message, this); + Application.InteractiveThread.ClearCallback(Ev_IRC_Message, this); delete pTitleChangeBC; } @@ -540,16 +540,16 @@ void C4ChatControl::OnConnectBtn(C4GUI::Control *btn) sWarnMsg.Format(LoadResStr("IDS_MSG_YOUAREABOUTTOCONNECTTOAPU"), sServer.getData()); if (!GetScreen()->ShowMessageModal(sWarnMsg.getData(), LoadResStr("IDS_MSG_CHATDISCLAIMER"), C4GUI::MessageDialog::btnOKAbort, C4GUI::Ico_Notify, &Config.Startup.HideMsgIRCDangerous)) return; - // set up IRC callback - pIRCClient->SetNotify(&Application.InteractiveThread); + // set up IRC callback + pIRCClient->SetNotify(&Application.InteractiveThread); // initiate connection if (!pIRCClient->Connect(sServer.getData(), sNick.getData(), sRealName.getData(), sPass.getData(), sChannel.getData())) { GetScreen()->ShowErrorMessage(FormatString(LoadResStr("IDS_ERR_IRCCONNECTIONFAILED"), pIRCClient->GetError()).getData()); return; } - // enable client execution - Application.InteractiveThread.AddProc(pIRCClient); + // enable client execution + Application.InteractiveThread.AddProc(pIRCClient); // reset chat sheets (close queries, etc.) ClearChatSheets(); // connection message @@ -619,8 +619,8 @@ void C4ChatControl::Update() --i; } } - // retrieve messages: All messages in initial update; only unread in subsequent calls - C4Network2IRCMessage *pMsg; + // retrieve messages: All messages in initial update; only unread in subsequent calls + C4Network2IRCMessage *pMsg; if (fInitialMessagesReceived) { pMsg = pIRCClient->getUnreadMessageLog(); @@ -668,7 +668,7 @@ void C4ChatControl::Update() pChatSheet = GetServerSheet(); } else if (sUser == pIRCClient->getUserName()) - { + { // private message by myself // message to a service into service window; otherwise (new) query if (IsServiceName(pMsg->getTarget())) @@ -681,8 +681,8 @@ void C4ChatControl::Update() pChatSheet = OpenQuery(pMsg->getTarget(), true, NULL); if (pChatSheet) pChatSheet->SetChatTitle(pMsg->getTarget()); } - } - else + } + else { // private message pChatSheet = OpenQuery(sUser.getData(), false, sIdent.getData()); @@ -706,9 +706,9 @@ void C4ChatControl::Update() case MSG_Notice: if (sUser.getLength()) - if (sUser != pIRCClient->getUserName()) + if (sUser != pIRCClient->getUserName()) sMsg.Format("-%s- %s", sUser.getData(), pMsg->getData()); - else + else sMsg.Format("-> -%s- %s", pMsg->getTarget(), pMsg->getData()); else sMsg.Format("* %s", pMsg->getData()); @@ -905,8 +905,8 @@ bool C4ChatControl::ProcessInput(const char *szInput, ChatSheet *pChatSheet) { if (C4InVal::ValidateString(sParam, C4InVal::VAL_IRCName)) pChatSheet->DoError(FormatString(LoadResStr("IDS_ERR_INVALIDNICKNAME2"), sCommand.getData()).getData()); - else - fIRCSuccess = pIRCClient->ChangeNick(sParam.getData()); + else + fIRCSuccess = pIRCClient->ChangeNick(sParam.getData()); } else { @@ -926,9 +926,9 @@ bool C4ChatControl::ProcessInput(const char *szInput, ChatSheet *pChatSheet) else { szMsgTarget = pChatSheet->GetTitle(); - if (*szInput == '/') // action + if (*szInput == '/') // action fIRCSuccess = pIRCClient->Action(szMsgTarget, szInput+4); - else + else fIRCSuccess = pIRCClient->Message(szMsgTarget, szInput); } } @@ -1016,7 +1016,7 @@ bool C4ChatDlg::IsChatActive() // not if chat is disabled if (!IsChatEnabled()) return false; // check whether IRC is connected - return Application.IRCClient.IsActive(); + return Application.IRCClient.IsActive(); } bool C4ChatDlg::IsChatEnabled() diff --git a/src/gui/C4ChatDlg.h b/src/gui/C4ChatDlg.h index 113833135..eb4316ea9 100644 --- a/src/gui/C4ChatDlg.h +++ b/src/gui/C4ChatDlg.h @@ -117,7 +117,7 @@ class C4ChatControl : public C4GUI::Window, private C4InteractiveThread::Callbac StdStrBuf sTitle; C4GUI::BaseInputCallback *pTitleChangeBC; - C4Network2IRCClient *pIRCClient; + C4Network2IRCClient *pIRCClient; bool fInitialMessagesReceived; // set after initial update call, which fetches all messages. Subsequent calls fetch only unread messages public: @@ -131,7 +131,7 @@ class C4ChatControl : public C4GUI::Window, private C4InteractiveThread::Callbac public: virtual class C4GUI::Control *GetDefaultControl(); - C4Network2IRCClient *getIRCClient() { return pIRCClient; } + C4Network2IRCClient *getIRCClient() { return pIRCClient; } void SetTitleChangeCB(C4GUI::BaseInputCallback *pNewCB); virtual void OnShown(); // callback when shown @@ -153,8 +153,8 @@ class C4ChatControl : public C4GUI::Window, private C4InteractiveThread::Callbac ChatSheet *GetServerSheet(); void ClearChatSheets(); - // IRC event hook - virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData) { if(pEventData == pIRCClient) Update(); } + // IRC event hook + virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData) { if(pEventData == pIRCClient) Update(); } }; diff --git a/src/gui/C4DownloadDlg.cpp b/src/gui/C4DownloadDlg.cpp index ef123f344..060d2d087 100644 --- a/src/gui/C4DownloadDlg.cpp +++ b/src/gui/C4DownloadDlg.cpp @@ -89,7 +89,7 @@ void C4DownloadDlg::SetStatus(const char *szNewText, int32_t iProgressPercent) } void C4DownloadDlg::OnIdle() - { + { // continue query process if (!HTTPClient.Execute()) { @@ -138,7 +138,7 @@ void C4DownloadDlg::OnIdle() } void C4DownloadDlg::UserClose(bool fOK) - { + { // user cancelled HTTPClient.Cancel(LoadResStr("IDS_ERR_USERCANCEL")); } diff --git a/src/gui/C4DownloadDlg.h b/src/gui/C4DownloadDlg.h index b6022d6ca..21b911bfc 100644 --- a/src/gui/C4DownloadDlg.h +++ b/src/gui/C4DownloadDlg.h @@ -26,7 +26,7 @@ // dialog to download a file class C4DownloadDlg : public C4GUI::Dialog - { + { private: C4Network2HTTPClient HTTPClient; diff --git a/src/gui/C4Folder.cpp b/src/gui/C4Folder.cpp index d18b59694..b712a9ba3 100644 --- a/src/gui/C4Folder.cpp +++ b/src/gui/C4Folder.cpp @@ -30,31 +30,31 @@ //================= C4FolderHead ==================== void C4FolderHead::Default() - { + { Index = 0; Sort[0] = 0; - } + } void C4FolderHead::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(Index, "Index", 0)); - pComp->Value(mkNamingAdapt(mkStringAdaptMA(Sort), "Sort", "")); - } + { + pComp->Value(mkNamingAdapt(Index, "Index", 0)); + pComp->Value(mkNamingAdapt(mkStringAdaptMA(Sort), "Sort", "")); + } //=================== C4Folder ====================== C4Folder::C4Folder() - { - Default(); - } + { + Default(); + } void C4Folder::Default() - { + { Head.Default(); - } + } bool C4Folder::Load(C4Group &hGroup) - { + { char *pSource; // Load if (!hGroup.LoadEntry(C4CFN_FolderCore, &pSource, NULL, 1)) return false; @@ -63,7 +63,7 @@ bool C4Folder::Load(C4Group &hGroup) delete [] pSource; // Success return true; - } + } /*bool C4Folder::Save(C4Group &hGroup) { @@ -76,13 +76,13 @@ bool C4Folder::Load(C4Group &hGroup) }*/ void C4Folder::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(Head, "Head")); - } + { + pComp->Value(mkNamingAdapt(Head, "Head")); + } bool C4Folder::Compile(const char *szSource) { Default(); - return CompileFromBuf_LogWarn(*this, StdStrBuf(szSource), C4CFN_FolderCore); + return CompileFromBuf_LogWarn(*this, StdStrBuf(szSource), C4CFN_FolderCore); } diff --git a/src/gui/C4Folder.h b/src/gui/C4Folder.h index f6da6167b..e54cf5e93 100644 --- a/src/gui/C4Folder.h +++ b/src/gui/C4Folder.h @@ -27,30 +27,30 @@ class C4Group; const int C4MaxFolderSort = 4096; class C4FolderHead - { - public: + { + public: int32_t Index; // Folder index in scenario selection dialog - char Sort[C4MaxFolderSort + 1]; // Folder-defined group sort list (to be used for folder maps) - public: - void Default(); - void CompileFunc(StdCompiler *pComp); - }; + char Sort[C4MaxFolderSort + 1]; // Folder-defined group sort list (to be used for folder maps) + public: + void Default(); + void CompileFunc(StdCompiler *pComp); + }; class C4Folder - { - public: + { + public: C4Folder(); public: C4FolderHead Head; - public: - void Default(); + public: + void Default(); //void Clear(); - bool Load(C4Group &hGroup); + bool Load(C4Group &hGroup); //bool Save(C4Group &hGroup); - void CompileFunc(StdCompiler *pComp); + void CompileFunc(StdCompiler *pComp); protected: bool Compile(const char *szSource); //bool Decompile(char **ppOutput, int32_t *ipSize); - }; + }; #endif // INC_C4Folder diff --git a/src/gui/C4GameDialogs.cpp b/src/gui/C4GameDialogs.cpp index adce3ab97..936f63f4e 100644 --- a/src/gui/C4GameDialogs.cpp +++ b/src/gui/C4GameDialogs.cpp @@ -41,7 +41,7 @@ C4AbortGameDialog::C4AbortGameDialog() MessageDialog::btnYesNo, true, C4GUI::Ico_Exit), - fGameHalted(false) + fGameHalted(false) { is_shown = true; // assume dlg will be shown, soon } diff --git a/src/gui/C4GameLobby.cpp b/src/gui/C4GameLobby.cpp index d2f0b0036..d8ed871a9 100644 --- a/src/gui/C4GameLobby.cpp +++ b/src/gui/C4GameLobby.cpp @@ -43,7 +43,7 @@ namespace C4GameLobby { void C4PacketCountdown::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(iCountdown, "Countdown", 0)); + pComp->Value(mkNamingAdapt(iCountdown, "Countdown", 0)); } StdStrBuf C4PacketCountdown::GetCountdownMsg(bool fInitialMsg) const @@ -64,7 +64,7 @@ ScenDesc::ScenDesc(const C4Rect &rcBounds, bool fActive) : C4GUI::Window(), fDes C4GUI::ComponentAligner caMain(GetClientRect(), 0,0, true); //AddElement(pTitle = new C4GUI::Label("", caMain.GetFromTop(rTitleFont.GetLineHeight()), ALeft, C4GUI_CaptionFontClr, &rTitleFont, true)); AddElement(pDescBox = new C4GUI::TextWindow(caMain.GetAll(), 0, 0, 0, 100, 4096, "", true)); - pDescBox->SetDecoration(false, false, NULL, true); + pDescBox->SetDecoration(false, false, NULL, true); //pDescBox->SetToolTip(LoadResStr("IDS_MSG_SCENARIODESC")); annoying when scrolling through desc... // initial update to set current data if (fActive) Activate(); @@ -109,7 +109,7 @@ void ScenDesc::Update() else { pDescBox->AddTextLine(FormatString(LoadResStr("IDS_MSG_SCENARIODESC_LOADING"), (int) pRes->getPresentPercent()).getData(), - &rTextFont, C4GUI_MessageFontClr, false, true); + &rTextFont, C4GUI_MessageFontClr, false, true); } pDescBox->UpdateHeight(); } @@ -724,11 +724,11 @@ C4GUI::ContextMenu *MainDlg::OnRightTabContext(C4GUI::Element *pLabel, int32_t i pMenu->AddItem(pPlayerSheet->GetTitle(), pPlayerSheet->GetToolTip(), C4GUI::Ico_Player, new C4GUI::CBMenuHandler(this, &MainDlg::OnCtxTabPlayers)); if (Game.Teams.IsMultiTeams()) - { - StdCopyStrBuf strShowTeamsDesc(LoadResStr("IDS_MSG_SHOWTEAMS_DESC")); + { + StdCopyStrBuf strShowTeamsDesc(LoadResStr("IDS_MSG_SHOWTEAMS_DESC")); pMenu->AddItem(LoadResStr("IDS_MSG_SHOWTEAMS"), strShowTeamsDesc.getData(), C4GUI::Ico_Team, new C4GUI::CBMenuHandler(this, &MainDlg::OnCtxTabTeams)); - } + } pMenu->AddItem(pResSheet->GetTitle(), pResSheet->GetToolTip(), C4GUI::Ico_Resource, new C4GUI::CBMenuHandler(this, &MainDlg::OnCtxTabRes)); pMenu->AddItem(pOptionsSheet->GetTitle(), pOptionsSheet->GetToolTip(), C4GUI::Ico_Options, diff --git a/src/gui/C4GameMessage.cpp b/src/gui/C4GameMessage.cpp index 0252ebe9e..694f4187f 100644 --- a/src/gui/C4GameMessage.cpp +++ b/src/gui/C4GameMessage.cpp @@ -55,7 +55,7 @@ void C4GameMessage::Init(int32_t iType, const StdStrBuf & sText, C4Object *pTarg Type=iType; Delay=Max(C4GM_MinDelay, Text.getLength() * TextMsgDelayFactor); DecoID=idDecoID; - this->dwFlags=dwFlags; + this->dwFlags=dwFlags; if (szPortraitDef && *szPortraitDef) PortraitDef.Copy(szPortraitDef); else PortraitDef.Clear(); // Permanent message if ('@' == Text[0]) @@ -344,13 +344,13 @@ bool C4GameMessageList::New(int32_t iType, const StdStrBuf & sText, C4Object *pT bool C4GameMessageList::Append(int32_t iType, const char *szText, C4Object *pTarget, int32_t iPlayer, int32_t iX, int32_t iY, uint8_t bCol, bool fNoDuplicates) { C4GameMessage *cmsg = NULL; - if (iType == C4GM_Target) + if (iType == C4GM_Target) { for (cmsg=::Messages.First; cmsg; cmsg=cmsg->Next) if (pTarget == cmsg->Target) break; } - if (iType == C4GM_Global || iType == C4GM_GlobalPlayer) + if (iType == C4GM_Global || iType == C4GM_GlobalPlayer) { for (cmsg=::Messages.First; cmsg; cmsg=cmsg->Next) if (iPlayer == cmsg->Player) diff --git a/src/gui/C4GameMessage.h b/src/gui/C4GameMessage.h index 34ac330df..90a5c25ef 100644 --- a/src/gui/C4GameMessage.h +++ b/src/gui/C4GameMessage.h @@ -28,25 +28,25 @@ #include const int32_t C4GM_MaxText = 256, - C4GM_MinDelay = 20; + C4GM_MinDelay = 20; const int32_t C4GM_Global = 1, - C4GM_GlobalPlayer = 2, - C4GM_Target = 3, - C4GM_TargetPlayer = 4; + C4GM_GlobalPlayer = 2, + C4GM_Target = 3, + C4GM_TargetPlayer = 4; const int32_t C4GM_NoBreak = 1<<0, - C4GM_Bottom = 1<<1, // message placed at bottom of screen - C4GM_Multiple= 1<<2, - C4GM_Top = 1<<3, - C4GM_Left = 1<<4, - C4GM_Right = 1<<5, - C4GM_HCenter = 1<<6, - C4GM_VCenter = 1<<7, - C4GM_DropSpeech = 1<<8, // cut any text after '$' - C4GM_WidthRel = 1<<9, - C4GM_XRel = 1<<10, - C4GM_YRel = 1<<11; + C4GM_Bottom = 1<<1, // message placed at bottom of screen + C4GM_Multiple= 1<<2, + C4GM_Top = 1<<3, + C4GM_Left = 1<<4, + C4GM_Right = 1<<5, + C4GM_HCenter = 1<<6, + C4GM_VCenter = 1<<7, + C4GM_DropSpeech = 1<<8, // cut any text after '$' + C4GM_WidthRel = 1<<9, + C4GM_XRel = 1<<10, + C4GM_YRel = 1<<11; const int32_t C4GM_PositioningFlags = C4GM_Bottom | C4GM_Top | C4GM_Left | C4GM_Right | C4GM_HCenter | C4GM_VCenter; @@ -68,12 +68,12 @@ class C4GameMessage C4GameMessage *Next; C4ID DecoID; StdStrBuf PortraitDef; C4GUI::FrameDecoration *pFrameDeco; - uint32_t dwFlags; + uint32_t dwFlags; protected: void Init(int32_t iType, const StdStrBuf & Text, C4Object *pTarget, int32_t iPlayer, int32_t iX, int32_t iY, uint32_t dwCol, C4ID idDecoID, const char *szPortraitDef, uint32_t dwFlags, int width); void Append(const char *szText, bool fNoDuplicates = false); bool Execute(); - const char *WordWrap(int32_t iMaxWidth); + const char *WordWrap(int32_t iMaxWidth); void UpdateDef(C4ID idUpdDef); public: diff --git a/src/gui/C4GameOptions.cpp b/src/gui/C4GameOptions.cpp index 6a6798ca8..e29c00cd6 100644 --- a/src/gui/C4GameOptions.cpp +++ b/src/gui/C4GameOptions.cpp @@ -222,7 +222,7 @@ C4GameOptionsList::OptionTeamColors::OptionTeamColors(class C4GameOptionsList *p void C4GameOptionsList::OptionTeamColors::DoDropdownFill(C4GUI::ComboBox_FillCB *pFiller) { pFiller->AddEntry(LoadResStr("IDS_MSG_ENABLED"), 1); - pFiller->AddEntry(LoadResStr("IDS_MSG_DISABLED"), 0); + pFiller->AddEntry(LoadResStr("IDS_MSG_DISABLED"), 0); } void C4GameOptionsList::OptionTeamColors::DoDropdownSelChange(int32_t idNewSelection) diff --git a/src/gui/C4Gui.cpp b/src/gui/C4Gui.cpp index f802ce99a..ee2604980 100644 --- a/src/gui/C4Gui.cpp +++ b/src/gui/C4Gui.cpp @@ -76,12 +76,12 @@ DWORD MakeColorReadableOnBlack(DWORD &rdwClr) // max alpha DWORD dwAlpha = Max(rdwClr>>24&255, 0xff)<<24; rdwClr &= 0xffffff; - // determine brightness - // 50% red, 87% green, 27% blue (max 164 * 255) - DWORD r=(rdwClr>>16&255), g=(rdwClr>>8&255), b=(rdwClr&255); - int32_t iLightness = r*50 + g*87 + b*27; - // above 65/164 (*255) is OK - if (iLightness < 16575) + // determine brightness + // 50% red, 87% green, 27% blue (max 164 * 255) + DWORD r=(rdwClr>>16&255), g=(rdwClr>>8&255), b=(rdwClr&255); + int32_t iLightness = r*50 + g*87 + b*27; + // above 65/164 (*255) is OK + if (iLightness < 16575) { int32_t iInc = (16575-iLightness) / 164; // otherwise, lighten diff --git a/src/gui/C4GuiDialogs.cpp b/src/gui/C4GuiDialogs.cpp index 6bffb75de..d1f82dd4e 100644 --- a/src/gui/C4GuiDialogs.cpp +++ b/src/gui/C4GuiDialogs.cpp @@ -202,11 +202,11 @@ CStdWindow * DialogWindow::Init(CStdApp * pApp, const char * Title, CStdWindow * // create it! if (!Title || !*Title) Title = "???"; hWindow = ::CreateWindowEx ( - 0, + 0, ConsoleDlgClassName, Title, - ConsoleDlgWindowStyle, - CW_USEDEFAULT,CW_USEDEFAULT,rtSize.right-rtSize.left,rtSize.bottom-rtSize.top, - pParent->hWindow,NULL,pApp->GetInstance(),NULL); + ConsoleDlgWindowStyle, + CW_USEDEFAULT,CW_USEDEFAULT,rtSize.right-rtSize.left,rtSize.bottom-rtSize.top, + pParent->hWindow,NULL,pApp->GetInstance(),NULL); if (hWindow) { // update pos @@ -227,22 +227,22 @@ LRESULT APIENTRY DialogWinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lPara if (!pDlg) return DefWindowProc(hwnd, uMsg, wParam, lParam); // Process message - switch (uMsg) - { - //--------------------------------------------------------------------------------------------------------------------------- - case WM_KEYDOWN: + switch (uMsg) + { + //--------------------------------------------------------------------------------------------------------------------------- + case WM_KEYDOWN: if (Game.DoKeyboardInput(wParam, KEYEV_Down, !!(lParam & 0x20000000), Application.IsControlDown(), Application.IsShiftDown(), !!(lParam & 0x40000000), pDlg)) return 0; break; - //--------------------------------------------------------------------------------------------------------------------------- - case WM_KEYUP: + //--------------------------------------------------------------------------------------------------------------------------- + case WM_KEYUP: if (Game.DoKeyboardInput(wParam, KEYEV_Up, !!(lParam & 0x20000000), Application.IsControlDown(), Application.IsShiftDown(), false, pDlg)) return 0; break; - //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ case WM_SYSKEYDOWN: if (wParam == 18) break; if (Game.DoKeyboardInput(wParam, KEYEV_Down, !!(lParam & 0x20000000), Application.IsControlDown(), Application.IsShiftDown(), !!(lParam & 0x40000000), pDlg)) return 0; break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_DESTROY: { const char *szID = pDlg->GetID(); @@ -250,21 +250,21 @@ LRESULT APIENTRY DialogWinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lPara StoreWindowPosition(hwnd, FormatString("ConsoleGUI_%s", szID).getData(), Config.GetSubkeyPath("Console"), false); } break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_CLOSE: pDlg->Close(false); break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_SIZE: // UpdateOutputSize break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_PAINT: // 2do: only draw specific dlg? //::GraphicsSystem.Execute(); break; return 0; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_LBUTTONDOWN: ::pGUI->MouseInput(C4MC_Button_LeftDown,LOWORD(lParam),HIWORD(lParam),wParam, pDlg, NULL); break; //---------------------------------------------------------------------------------------------------------------------------------- case WM_LBUTTONUP: ::pGUI->MouseInput(C4MC_Button_LeftUp,LOWORD(lParam),HIWORD(lParam),wParam, pDlg, NULL); break; @@ -838,9 +838,9 @@ void Dialog::OnClosed(bool fOK) bool Dialog::DoModal() { - // main message loop - while (fShow) - { + // main message loop + while (fShow) + { while (fShow) { // dialog idle proc diff --git a/src/gui/C4GuiMenu.cpp b/src/gui/C4GuiMenu.cpp index bde7dcbea..4ac687995 100644 --- a/src/gui/C4GuiMenu.cpp +++ b/src/gui/C4GuiMenu.cpp @@ -388,8 +388,8 @@ bool ContextMenu::AddElement(Element *pChild) { // add it Window::AddElement(pChild); - // update own size and positions - UpdateElementPositions(); + // update own size and positions + UpdateElementPositions(); // success return true; } @@ -398,8 +398,8 @@ bool ContextMenu::InsertElement(Element *pChild, Element *pInsertBefore) { // insert it Window::InsertElement(pChild, pInsertBefore); - // update own size and positions - UpdateElementPositions(); + // update own size and positions + UpdateElementPositions(); // success return true; } diff --git a/src/gui/C4KeyboardInput.cpp b/src/gui/C4KeyboardInput.cpp index 20f2879e6..ff1d1c41a 100644 --- a/src/gui/C4KeyboardInput.cpp +++ b/src/gui/C4KeyboardInput.cpp @@ -42,12 +42,12 @@ namespace { - std::string getKeyName(C4KeyCode k) - { - std::string result = SDL_GetKeyName(static_cast(k)); + std::string getKeyName(C4KeyCode k) + { + std::string result = SDL_GetKeyName(static_cast(k)); // unknown key - if (result == "unknown key") - result = FormatString("\\x%x", (DWORD) k).getData(); + if (result == "unknown key") + result = FormatString("\\x%x", (DWORD) k).getData(); // some special cases if (result == "world 0") result = "´"; if (result == "world 1") result = "ß"; @@ -57,8 +57,8 @@ namespace // capitalize first letter result[0] = toupper(result[0]); // return key name - return result; - } + return result; + } } #endif @@ -997,7 +997,7 @@ void C4KeyboardInput::CompileFunc(StdCompiler *pComp) if (!(OldCodes == rNewCodes)) UpdateKeyCodes(i->second, OldCodes, rNewCodes); } } - } + } catch(StdCompiler::Exception *pEx) { pComp->NameEnd(true); @@ -1014,7 +1014,7 @@ bool C4KeyboardInput::LoadCustomConfig() StdBuf sFileContents; if (!GrpExtra.LoadEntry(C4CFN_KeyConfig, sFileContents)) return false; StdStrBuf sFileContentsString((const char *) sFileContents.getData()); - if(!CompileFromBuf_LogWarn(*this, sFileContentsString, "Custom keys from" C4CFN_Extra DirSep C4CFN_KeyConfig)) + if(!CompileFromBuf_LogWarn(*this, sFileContentsString, "Custom keys from" C4CFN_Extra DirSep C4CFN_KeyConfig)) return false; LogF(LoadResStr("IDS_PRC_LOADEDKEYCONF"), C4CFN_Extra DirSep C4CFN_KeyConfig); return true; diff --git a/src/gui/C4KeyboardInput.h b/src/gui/C4KeyboardInput.h index cb83762b3..51dbcd3af 100644 --- a/src/gui/C4KeyboardInput.h +++ b/src/gui/C4KeyboardInput.h @@ -62,36 +62,36 @@ const C4KeyCode KEY_JOY_Mask = 0x420000; const C4KeyCode KEY_MOUSE_Mask = 0x430000; const C4KeyCode KEY_Default = 0, // no key - KEY_Any = ~0, // used for default key processing - KEY_Undefined = (~0)^1, // used to indicate an unknown key - KEY_JOY_Left = 1, // joypad axis control: Any x axis min - KEY_JOY_Up = 2, // joypad axis control: Any y axis min - KEY_JOY_Right = 3, // joypad axis control: Any x axis max - KEY_JOY_Down = 4, // joypad axis control: Any y axis max - KEY_JOY_Button1 = 0x10, // key index of joypad buttons + button index for more buttons - KEY_JOY_ButtonMax = KEY_JOY_Button1+0x1f, // maximum number of supported buttons on a gamepad - KEY_JOY_Axis1Min = 0x30, - KEY_JOY_Axis1Max = 0x31, - KEY_JOY_AxisMax = KEY_JOY_Axis1Min + 0x20, - KEY_JOY_AnyButton = 0xff, // any joypad button (not axis) - KEY_JOY_AnyOddButton = 0xfe, // joypad buttons 1, 3, 5, etc. - KEY_JOY_AnyEvenButton = 0xfd, // joypad buttons 2, 4, 6, etc. - KEY_JOY_AnyLowButton = 0xfc, // joypad buttons 1 - 4 - KEY_JOY_AnyHighButton = 0xfb, // joypad buttons > 4 - KEY_MOUSE_Move = 1, // mouse control: mouse movement - KEY_MOUSE_Button1 = 0x10, // key index of mouse buttons + button index for more buttons - KEY_MOUSE_ButtonLeft = KEY_MOUSE_Button1 + 0, - KEY_MOUSE_ButtonRight = KEY_MOUSE_Button1 + 1, - KEY_MOUSE_ButtonMiddle= KEY_MOUSE_Button1 + 2, - KEY_MOUSE_ButtonMax = KEY_MOUSE_Button1 + 0x1f, // max number of supported mouse buttons - KEY_MOUSE_Button1Double = 0x30, // double clicks have special events because double click speed is issued by OS - KEY_MOUSE_ButtonLeftDouble = KEY_MOUSE_Button1Double + 0, - KEY_MOUSE_ButtonRightDouble = KEY_MOUSE_Button1Double + 1, - KEY_MOUSE_ButtonMiddleDouble= KEY_MOUSE_Button1Double + 2, - KEY_MOUSE_ButtonMaxDouble = KEY_MOUSE_Button1Double + 0x1f, // max number of supported mouse buttons - KEY_MOUSE_Wheel1Up = 0x40, // mouse control: wheel up - KEY_MOUSE_Wheel1Down = 0x41, // mouse control: wheel down - KEY_MOUSE_GameMask = 0x80; // if set, contorl is sent in game coordinates + KEY_Any = ~0, // used for default key processing + KEY_Undefined = (~0)^1, // used to indicate an unknown key + KEY_JOY_Left = 1, // joypad axis control: Any x axis min + KEY_JOY_Up = 2, // joypad axis control: Any y axis min + KEY_JOY_Right = 3, // joypad axis control: Any x axis max + KEY_JOY_Down = 4, // joypad axis control: Any y axis max + KEY_JOY_Button1 = 0x10, // key index of joypad buttons + button index for more buttons + KEY_JOY_ButtonMax = KEY_JOY_Button1+0x1f, // maximum number of supported buttons on a gamepad + KEY_JOY_Axis1Min = 0x30, + KEY_JOY_Axis1Max = 0x31, + KEY_JOY_AxisMax = KEY_JOY_Axis1Min + 0x20, + KEY_JOY_AnyButton = 0xff, // any joypad button (not axis) + KEY_JOY_AnyOddButton = 0xfe, // joypad buttons 1, 3, 5, etc. + KEY_JOY_AnyEvenButton = 0xfd, // joypad buttons 2, 4, 6, etc. + KEY_JOY_AnyLowButton = 0xfc, // joypad buttons 1 - 4 + KEY_JOY_AnyHighButton = 0xfb, // joypad buttons > 4 + KEY_MOUSE_Move = 1, // mouse control: mouse movement + KEY_MOUSE_Button1 = 0x10, // key index of mouse buttons + button index for more buttons + KEY_MOUSE_ButtonLeft = KEY_MOUSE_Button1 + 0, + KEY_MOUSE_ButtonRight = KEY_MOUSE_Button1 + 1, + KEY_MOUSE_ButtonMiddle= KEY_MOUSE_Button1 + 2, + KEY_MOUSE_ButtonMax = KEY_MOUSE_Button1 + 0x1f, // max number of supported mouse buttons + KEY_MOUSE_Button1Double = 0x30, // double clicks have special events because double click speed is issued by OS + KEY_MOUSE_ButtonLeftDouble = KEY_MOUSE_Button1Double + 0, + KEY_MOUSE_ButtonRightDouble = KEY_MOUSE_Button1Double + 1, + KEY_MOUSE_ButtonMiddleDouble= KEY_MOUSE_Button1Double + 2, + KEY_MOUSE_ButtonMaxDouble = KEY_MOUSE_Button1Double + 0x1f, // max number of supported mouse buttons + KEY_MOUSE_Wheel1Up = 0x40, // mouse control: wheel up + KEY_MOUSE_Wheel1Down = 0x41, // mouse control: wheel down + KEY_MOUSE_GameMask = 0x80; // if set, contorl is sent in game coordinates inline uint8_t KEY_JOY_Button(uint8_t idx) { return KEY_JOY_Button1+idx; } inline uint8_t KEY_JOY_Axis(uint8_t idx, bool fMax) { return KEY_JOY_Axis1Min+2*idx+fMax; } @@ -340,7 +340,7 @@ template class C4KeyCBEx : public C4Key case KEYEV_Down: return pFuncDown ? (rTarget.*pFuncDown)(par) : false; case KEYEV_Up: return pFuncUp ? (rTarget.*pFuncUp)(par) : false; case KEYEV_Pressed: return pFuncPressed ? (rTarget.*pFuncPressed)(par) : false; - default: return false; + default: return false; } } diff --git a/src/gui/C4MainMenu.cpp b/src/gui/C4MainMenu.cpp index 8ced8b434..c4b4fa2b4 100644 --- a/src/gui/C4MainMenu.cpp +++ b/src/gui/C4MainMenu.cpp @@ -717,11 +717,11 @@ bool C4MainMenu::MenuCommand(const char *szCommand, bool fIsCloseCommand) { // only if allowed if (!Game.Teams.IsHostilityChangeAllowed()) return false; - int32_t iOpponent; sscanf(szCommand+13,"%i",&iOpponent); + int32_t iOpponent; sscanf(szCommand+13,"%i",&iOpponent); C4Player *pOpponent = ::Players.Get(iOpponent); if (!pOpponent || pOpponent->GetType() != C4PT_User) return false; // TODO: doesn't really work - Game.Input.Add(CID_Script, new C4ControlScript(FormatString("SetHostility(%d, %d, !Hostile(%d, %d, true))", Player, iOpponent, Player, iOpponent).getData(), C4ControlScript::SCOPE_Global, true)); + Game.Input.Add(CID_Script, new C4ControlScript(FormatString("SetHostility(%d, %d, !Hostile(%d, %d, true))", Player, iOpponent, Player, iOpponent).getData(), C4ControlScript::SCOPE_Global, true)); return true; } // Abort diff --git a/src/gui/C4Menu.cpp b/src/gui/C4Menu.cpp index 27dd39d30..fa728110b 100644 --- a/src/gui/C4Menu.cpp +++ b/src/gui/C4Menu.cpp @@ -151,7 +151,7 @@ bool C4MenuItem::IsDragElement() } int32_t C4MenuItem::GetSymbolWidth(int32_t iForHeight) - { + { // Context or dialog menus if (iStyle==C4MN_Style_Context || (iStyle==C4MN_Style_Dialog && Symbol.Surface)) return Max(Symbol.Wdt * iForHeight / Max(Symbol.Hgt, 1), iForHeight); @@ -323,7 +323,7 @@ void C4Menu::Default() void C4Menu::Clear() { - Close(false); + Close(false); Symbol.Clear(); ClearItems(); ClearFrameDeco(); @@ -538,7 +538,7 @@ bool C4Menu::Enter(bool fRight) return true; } // Copy command to buffer (menu might be cleared) - char szCommand[_MAX_FNAME+30+1]; + char szCommand[_MAX_FNAME+30+1]; SCopy(pItem->Command,szCommand); if (fRight && pItem->Command2[0]) SCopy(pItem->Command2,szCommand); @@ -951,7 +951,7 @@ void C4Menu::SetPermanent(bool fPermanent) } bool C4Menu::RefillInternal() - { + { // Reset flag NeedRefill=false; @@ -976,7 +976,7 @@ bool C4Menu::RefillInternal() } // Success return true; - } + } void C4Menu::ClearItems(bool fResetSelection) { diff --git a/src/gui/C4MessageInput.cpp b/src/gui/C4MessageInput.cpp index 05ed5cf1d..1b24f34d5 100644 --- a/src/gui/C4MessageInput.cpp +++ b/src/gui/C4MessageInput.cpp @@ -334,15 +334,15 @@ bool C4MessageInput::IsTypeIn() bool C4MessageInput::ProcessInput(const char *szText) { - // helper variables + // helper variables char OSTR[402]; // cba - C4ControlMessageType eMsgType; - const char *szMsg = NULL; - int32_t iToPlayer = -1; + C4ControlMessageType eMsgType; + const char *szMsg = NULL; + int32_t iToPlayer = -1; - // Starts with '^', "team:" or "/team ": Team message - if(szText[0] == '^' || SEqual2NoCase(szText, "team:") || SEqual2NoCase(szText, "/team ")) - { + // Starts with '^', "team:" or "/team ": Team message + if(szText[0] == '^' || SEqual2NoCase(szText, "team:") || SEqual2NoCase(szText, "/team ")) + { if (!Game.Teams.IsTeamVisible()) { // team not known; can't send! @@ -355,65 +355,65 @@ bool C4MessageInput::ProcessInput(const char *szText) szMsg = szText[0] == '^' ? szText+1 : szText[0] == '/' ? szText+6 : szText+5; } - } + } // Starts with "/private ": Private message (running game only) else if(Game.IsRunning && SEqual2NoCase(szText, "/private ")) { - // get target name - char szTargetPlr[C4MaxName + 1]; - SCopyUntil(szText + 9, szTargetPlr, ' ', C4MaxName); - // search player - C4Player *pToPlr = ::Players.GetByName(szTargetPlr); - if(!pToPlr) return false; - // set - eMsgType = C4CMT_Private; + // get target name + char szTargetPlr[C4MaxName + 1]; + SCopyUntil(szText + 9, szTargetPlr, ' ', C4MaxName); + // search player + C4Player *pToPlr = ::Players.GetByName(szTargetPlr); + if(!pToPlr) return false; + // set + eMsgType = C4CMT_Private; iToPlayer = pToPlr->Number; - szMsg = szText + 10 + SLen(szText); - if(szMsg > szText + SLen(szText)) return false; + szMsg = szText + 10 + SLen(szText); + if(szMsg > szText + SLen(szText)) return false; } - // Starts with "/me ": Me-Message - else if(SEqual2NoCase(szText, "/me ")) - { - eMsgType = C4CMT_Me; - szMsg = szText+4; - } - // Starts with "/sound ": Sound-Message - else if(SEqual2NoCase(szText, "/sound ")) - { - eMsgType = C4CMT_Sound; - szMsg = szText+7; - } - // Starts with "/alert": Taskbar flash (message optional) - else if(SEqual2NoCase(szText, "/alert ") || SEqualNoCase(szText, "/alert")) - { - eMsgType = C4CMT_Alert; - szMsg = szText+6; + // Starts with "/me ": Me-Message + else if(SEqual2NoCase(szText, "/me ")) + { + eMsgType = C4CMT_Me; + szMsg = szText+4; + } + // Starts with "/sound ": Sound-Message + else if(SEqual2NoCase(szText, "/sound ")) + { + eMsgType = C4CMT_Sound; + szMsg = szText+7; + } + // Starts with "/alert": Taskbar flash (message optional) + else if(SEqual2NoCase(szText, "/alert ") || SEqualNoCase(szText, "/alert")) + { + eMsgType = C4CMT_Alert; + szMsg = szText+6; if (*szMsg) ++szMsg; - } - // Starts with '"': Let the clonk say it - else if(Game.IsRunning && szText[0] == '"') - { - eMsgType = C4CMT_Say; - // Append '"', if neccessary + } + // Starts with '"': Let the clonk say it + else if(Game.IsRunning && szText[0] == '"') + { + eMsgType = C4CMT_Say; + // Append '"', if neccessary StdStrBuf text(szText); - SCopy(szText, OSTR, 400); - char *pEnd = OSTR + SLen(OSTR) - 1; - if(*pEnd != '"') { *++pEnd = '"'; *++pEnd = 0; } - szMsg = OSTR; - } + SCopy(szText, OSTR, 400); + char *pEnd = OSTR + SLen(OSTR) - 1; + if(*pEnd != '"') { *++pEnd = '"'; *++pEnd = 0; } + szMsg = OSTR; + } // Starts with '/': Command else if(szText[0] == '/') return ProcessCommand(szText); - // Regular message - else - { - eMsgType = C4CMT_Normal; - szMsg = szText; - } + // Regular message + else + { + eMsgType = C4CMT_Normal; + szMsg = szText; + } - // message? - if(szMsg) - { + // message? + if(szMsg) + { char szMessage[C4MaxMessage + 1]; // go over whitespaces, check empty message while(IsWhiteSpace(*szMsg)) szMsg++; @@ -435,13 +435,13 @@ bool C4MessageInput::ProcessInput(const char *szText) // get message SCopy(szMsg, szMessage, Min(C4MaxMessage, szEnd - szMsg + 1)); } - // get sending player (if any) + // get sending player (if any) C4Player *pPlr = Game.IsRunning ? ::Players.GetLocalByIndex(0) : NULL; - // send - ::Control.DoInput(CID_Message, - new C4ControlMessage(eMsgType, szMessage, pPlr ? pPlr->Number : -1, iToPlayer), - CDT_Private); - } + // send + ::Control.DoInput(CID_Message, + new C4ControlMessage(eMsgType, szMessage, pPlr ? pPlr->Number : -1, iToPlayer), + CDT_Private); + } return true; } @@ -484,9 +484,9 @@ bool C4MessageInput::ProcessCommand(const char *szCommand) if (!Game.IsRunning) return false; if (!Game.DebugMode) return false; if (!::Network.isEnabled() && !SEqual(Game.ScenarioFile.GetMaker(), Config.General.Name) && Game.ScenarioFile.GetStatus() != GRPF_Folder) return false; - if (::Network.isEnabled() && !::Network.isHost()) return false; + if (::Network.isEnabled() && !::Network.isHost()) return false; - ::Control.DoInput(CID_Script, new C4ControlScript(pCmdPar, C4ControlScript::SCOPE_Console, false), CDT_Decide); + ::Control.DoInput(CID_Script, new C4ControlScript(pCmdPar, C4ControlScript::SCOPE_Console, false), CDT_Decide); return true; } // set runtimte properties @@ -510,9 +510,9 @@ bool C4MessageInput::ProcessCommand(const char *szCommand) if(SEqual2(pCmdPar, "comment ") || SEqual(pCmdPar, "comment")) { if(!::Network.isEnabled() || !::Network.isHost()) return false; - // Set in configuration, update reference + // Set in configuration, update reference Config.Network.Comment.CopyValidated(pCmdPar[7] ? (pCmdPar+8) : ""); - ::Network.InvalidateReference(); + ::Network.InvalidateReference(); Log(LoadResStr("IDS_NET_COMMENTCHANGED")); return true; } @@ -523,20 +523,20 @@ bool C4MessageInput::ProcessCommand(const char *szCommand) if (pLobby) pLobby->UpdatePassword(); return true; } - if(SEqual2(pCmdPar, "faircrew ")) - { - C4ControlSet *pSet = NULL; - if(SEqual(pCmdPar + 9, "on")) - pSet = new C4ControlSet(C4CVT_FairCrew, Config.General.FairCrewStrength); - else if(SEqual(pCmdPar + 9, "off")) - pSet = new C4ControlSet(C4CVT_FairCrew, -1); - else if(isdigit((unsigned char)pCmdPar[9])) - pSet = new C4ControlSet(C4CVT_FairCrew, atoi(pCmdPar + 9)); - else - return false; - ::Control.DoInput(CID_Set, pSet, CDT_Decide); - return true; - } + if(SEqual2(pCmdPar, "faircrew ")) + { + C4ControlSet *pSet = NULL; + if(SEqual(pCmdPar + 9, "on")) + pSet = new C4ControlSet(C4CVT_FairCrew, Config.General.FairCrewStrength); + else if(SEqual(pCmdPar + 9, "off")) + pSet = new C4ControlSet(C4CVT_FairCrew, -1); + else if(isdigit((unsigned char)pCmdPar[9])) + pSet = new C4ControlSet(C4CVT_FairCrew, atoi(pCmdPar + 9)); + else + return false; + ::Control.DoInput(CID_Set, pSet, CDT_Decide); + return true; + } // unknown property return false; } @@ -647,8 +647,8 @@ bool C4MessageInput::ProcessCommand(const char *szCommand) // kick/activate/deactivate/observer if(SEqual(szCmdName, "activate") || SEqual(szCmdName, "deactivate") || SEqual(szCmdName, "observer")) { - if (!::Network.isEnabled() || !::Network.isHost()) - { Log(LoadResStr("IDS_MSG_CMD_HOSTONLY")); return false; } + if (!::Network.isEnabled() || !::Network.isHost()) + { Log(LoadResStr("IDS_MSG_CMD_HOSTONLY")); return false; } // search for client C4Client *pClient = Game.Clients.getClientByName(pCmdPar); if (!pClient) @@ -674,12 +674,12 @@ bool C4MessageInput::ProcessCommand(const char *szCommand) // control mode if(SEqual(szCmdName, "centralctrl") || SEqual(szCmdName, "decentralctrl") || SEqual(szCmdName, "asyncctrl")) - { - if (!::Network.isEnabled() || !::Network.isHost()) - { Log(LoadResStr("IDS_MSG_CMD_HOSTONLY")); return false; } - ::Network.SetCtrlMode(*szCmdName == 'c' ? CNM_Central : *szCmdName == 'd' ? CNM_Decentral : CNM_Async); + { + if (!::Network.isEnabled() || !::Network.isHost()) + { Log(LoadResStr("IDS_MSG_CMD_HOSTONLY")); return false; } + ::Network.SetCtrlMode(*szCmdName == 'c' ? CNM_Central : *szCmdName == 'd' ? CNM_Decentral : CNM_Async); return true; - } + } // show chart if (Game.IsRunning) if (SEqual(szCmdName, "chart")) @@ -786,7 +786,7 @@ void C4MessageInput::ClearPointers(C4Object *pObj) } void C4MessageInput::AbortMsgBoardQuery(C4Object *pObj, int32_t iPlr) - { + { // close typein if it is used for the given parameters C4ChatInputDialog *pDlg = GetTypeIn(); if (pDlg && pDlg->IsScriptQueried() && pDlg->GetScriptTargetObject() == pObj && pDlg->GetScriptTargetPlayer() == iPlr) CloseTypeIn(); diff --git a/src/gui/C4PlayerInfoListBox.cpp b/src/gui/C4PlayerInfoListBox.cpp index 418444f51..476aad6a3 100644 --- a/src/gui/C4PlayerInfoListBox.cpp +++ b/src/gui/C4PlayerInfoListBox.cpp @@ -496,7 +496,7 @@ C4GUI::ContextMenu *C4PlayerInfoListBox::PlayerListItem::OnContext(C4GUI::Elemen pMenu->AddItem(strTakeOver.getData(), LoadResStr("IDS_MSG_TAKEOVERPLR_DESC"), C4GUI::Ico_Player, NULL, new C4GUI::CBContextHandler(this, &PlayerListItem::OnContextTakeOver)); } - } + } else { // owned players or host can manipulate players @@ -897,16 +897,16 @@ C4GUI::ContextMenu *C4PlayerInfoListBox::ClientListItem::OnContext(C4GUI::Elemen // host options if (::Network.isHost() && GetNetClient()) { - StdCopyStrBuf strKickDesc(LoadResStr("IDS_NET_KICKCLIENT_DESC")); + StdCopyStrBuf strKickDesc(LoadResStr("IDS_NET_KICKCLIENT_DESC")); pMenu->AddItem(LoadResStr("IDS_NET_KICKCLIENT"), strKickDesc.getData(), C4GUI::Ico_None, new C4GUI::CBMenuHandler(this, &ClientListItem::OnCtxKick)); - StdCopyStrBuf strActivateDesc(LoadResStr("IDS_NET_ACTIVATECLIENT_DESC")); + StdCopyStrBuf strActivateDesc(LoadResStr("IDS_NET_ACTIVATECLIENT_DESC")); pMenu->AddItem(LoadResStr(pClient->isActivated() ? "IDS_NET_DEACTIVATECLIENT" : "IDS_NET_ACTIVATECLIENT"), - strActivateDesc.getData(), C4GUI::Ico_None, + strActivateDesc.getData(), C4GUI::Ico_None, new C4GUI::CBMenuHandler(this, &ClientListItem::OnCtxActivate)); } // info - StdCopyStrBuf strClientInfoDesc(LoadResStr("IDS_NET_CLIENTINFO_DESC")); + StdCopyStrBuf strClientInfoDesc(LoadResStr("IDS_NET_CLIENTINFO_DESC")); pMenu->AddItem(LoadResStr("IDS_NET_CLIENTINFO"), strClientInfoDesc.getData(), C4GUI::Ico_None, new C4GUI::CBMenuHandler(this, &ClientListItem::OnCtxInfo)); // open it diff --git a/src/gui/C4Scoreboard.cpp b/src/gui/C4Scoreboard.cpp index b82258cff..db784287c 100644 --- a/src/gui/C4Scoreboard.cpp +++ b/src/gui/C4Scoreboard.cpp @@ -293,25 +293,25 @@ void C4Scoreboard::HideDlg() void C4Scoreboard::CompileFunc(StdCompiler *pComp) { - bool fCompiler = pComp->isCompiler(); - if(fCompiler) Clear(); - pComp->Value(mkNamingAdapt(iRows, "Rows", 0)); - pComp->Value(mkNamingAdapt(iCols, "Cols", 0)); - pComp->Value(mkNamingAdapt(iDlgShow, "DlgShow", 0)); + bool fCompiler = pComp->isCompiler(); + if(fCompiler) Clear(); + pComp->Value(mkNamingAdapt(iRows, "Rows", 0)); + pComp->Value(mkNamingAdapt(iCols, "Cols", 0)); + pComp->Value(mkNamingAdapt(iDlgShow, "DlgShow", 0)); if (iRows * iCols) { if (fCompiler) pEntries = new Entry[iRows * iCols]; - for (int32_t iRow = 0; iRow < iRows; ++iRow) + for (int32_t iRow = 0; iRow < iRows; ++iRow) for (int32_t iCol = 0; iCol < iCols; ++iCol) { Entry *pEnt = GetCell(iCol, iRow); - pComp->Value(mkNamingAdapt(pEnt->Text, FormatString("Cell%i_%iString", iCol, iRow).getData())); - pComp->Value(mkNamingAdapt(pEnt->iVal, FormatString("Cell%i_%iValue", iCol, iRow).getData())); + pComp->Value(mkNamingAdapt(pEnt->Text, FormatString("Cell%i_%iString", iCol, iRow).getData())); + pComp->Value(mkNamingAdapt(pEnt->iVal, FormatString("Cell%i_%iValue", iCol, iRow).getData())); } // recheck dlg show in read mode // will usually not do anything, because reading is done before enetering shared mode if (pComp->isCompiler()) DoDlgShow(0, false); - } + } } diff --git a/src/gui/C4Startup.h b/src/gui/C4Startup.h index 762d6b5de..f5130b6d8 100644 --- a/src/gui/C4Startup.h +++ b/src/gui/C4Startup.h @@ -27,10 +27,10 @@ // special colors for startup designs const int32_t C4StartupFontClr = 0xff000000, - C4StartupFontClrDisabled = 0xff7f7f7f, - C4StartupEditBGColor = 0x00000000, + C4StartupFontClrDisabled = 0xff7f7f7f, + C4StartupEditBGColor = 0x00000000, C4StartupEditBorderColor = 0xffa4947a, - C4StartupBtnFontClr = 0xff202020, + C4StartupBtnFontClr = 0xff202020, C4StartupBtnBorderColor1 = 0xffccc3b4, C4StartupBtnBorderColor2 = 0xff94846a; diff --git a/src/gui/C4StartupNetDlg.cpp b/src/gui/C4StartupNetDlg.cpp index fada023ac..77bc38225 100644 --- a/src/gui/C4StartupNetDlg.cpp +++ b/src/gui/C4StartupNetDlg.cpp @@ -103,14 +103,14 @@ void C4StartupNetListEntry::DrawElement(C4TargetFacet &cgo) } void C4StartupNetListEntry::ClearRef() - { + { // del old ref data if (pRefClient) - { - C4InteractiveThread &Thread = Application.InteractiveThread; - Thread.RemoveProc(pRefClient); - delete pRefClient; pRefClient = NULL; - } + { + C4InteractiveThread &Thread = Application.InteractiveThread; + Thread.RemoveProc(pRefClient); + delete pRefClient; pRefClient = NULL; + } if (pRef) { delete pRef; pRef = NULL; } eQueryType = NRQT_Unknown; iTimeout = iRequestTimeout = 0; @@ -162,9 +162,9 @@ void C4StartupNetListEntry::SetRefQuery(const char *szAddress, enum QueryType eQ // masterserver: always on top if (eQueryType == NRQT_Masterserver) iSortOrder = 100; - // register proc - C4InteractiveThread &Thread = Application.InteractiveThread; - Thread.AddProc(pRefClient); + // register proc + C4InteractiveThread &Thread = Application.InteractiveThread; + Thread.AddProc(pRefClient); // start querying! QueryReferences(); } @@ -215,24 +215,24 @@ bool C4StartupNetListEntry::Execute() if (pRefClient->isBusy()) // still requesting - but do not wait forever if (time(NULL) >= iRequestTimeout) - { + { SetError(LoadResStr("IDS_NET_ERR_REFREQTIMEOUT"), TT_RefReqWait); - pRefClient->Cancel("Timeout"); - } - return true; + pRefClient->Cancel("Timeout"); + } + return true; } bool C4StartupNetListEntry::OnReference() - { - // wrong type / still busy? - if (!pRefClient || pRefClient->isBusy()) - return true; + { + // wrong type / still busy? + if (!pRefClient || pRefClient->isBusy()) + return true; // successful? if (!pRefClient->isSuccess()) { // couldn't get references SetError(pRefClient->GetError(), TT_RefReqWait); - return true; + return true; } // Ref getting done! pIcon->SetAnimated(false, 1); @@ -286,8 +286,8 @@ bool C4StartupNetListEntry::OnReference() else // no ref found on custom adress: Schedule re-check SetTimeout(TT_RefReqWait); - return true; - } + return true; + } C4GUI::Element* C4StartupNetListEntry::GetNextLower(int32_t sortOrder) { @@ -660,7 +660,7 @@ C4StartupNetDlg::C4StartupNetDlg() : C4StartupDlg(LoadResStr("IDS_DLG_NETSTART") pChatGroup->SetColors(0u, C4GUI_CaptionFontClr, C4GUI_StandardBGColor); pChatGroup->SetMargin(2); pSheetChat->AddElement(pChatGroup); - pChatCtrl = new C4ChatControl(&Application.IRCClient); + pChatCtrl = new C4ChatControl(&Application.IRCClient); pChatCtrl->SetBounds(pChatGroup->GetContainedClientRect()); pChatCtrl->SetTitleChangeCB(new C4GUI::InputCallback(this, &C4StartupNetDlg::OnChatTitleChange)); StdStrBuf sCurrTitle; sCurrTitle.Ref(pChatCtrl->GetTitle()); OnChatTitleChange(sCurrTitle); @@ -707,15 +707,15 @@ C4StartupNetDlg::C4StartupNetDlg() : C4StartupDlg(LoadResStr("IDS_DLG_NETSTART") // register timer Application.Add(this); - // register as receiver of reference notifies - Application.InteractiveThread.SetCallback(Ev_HTTP_Response, this); + // register as receiver of reference notifies + Application.InteractiveThread.SetCallback(Ev_HTTP_Response, this); } C4StartupNetDlg::~C4StartupNetDlg() { - // disable notifies - Application.InteractiveThread.ClearCallback(Ev_HTTP_Response, this); + // disable notifies + Application.InteractiveThread.ClearCallback(Ev_HTTP_Response, this); DiscoverClient.Close(); Application.Remove(this); if (pMasterserverClient) delete pMasterserverClient; @@ -852,12 +852,12 @@ void C4StartupNetDlg::UpdateList(bool fGotReference) { pNextElem = pElem->GetNext(); // determine next exec element now - execution C4StartupNetListEntry *pEntry = static_cast(pElem); - // do item updates - bool fKeepEntry = true; - if(fGotReference) - fKeepEntry = pEntry->OnReference(); - if(fKeepEntry) - fKeepEntry = pEntry->Execute(); + // do item updates + bool fKeepEntry = true; + if(fGotReference) + fKeepEntry = pEntry->OnReference(); + if(fKeepEntry) + fKeepEntry = pEntry->Execute(); // remove? if (!fKeepEntry) { @@ -942,9 +942,9 @@ C4StartupNetDlg::DlgMode C4StartupNetDlg::GetDlgMode() } void C4StartupNetDlg::OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData) - { - UpdateList(true); - } + { + UpdateList(true); + } bool C4StartupNetDlg::DoOK() { @@ -985,7 +985,7 @@ bool C4StartupNetDlg::DoOK() } // get currently selected item C4GUI::Element *pSelection = pGameSelList->GetSelectedItem(); - StdCopyStrBuf strNoJoin(LoadResStr("IDS_NET_NOJOIN")); + StdCopyStrBuf strNoJoin(LoadResStr("IDS_NET_NOJOIN")); if(!pSelection) { // no ref selected: Oh noes! @@ -1029,8 +1029,8 @@ bool C4StartupNetDlg::DoOK() { ::pGUI->ShowMessageModal( FormatString(LoadResStr("IDS_NET_NOJOIN_BADVER"), - pRef->getGameVersion().GetString().getData(), - verThis.GetString().getData()).getData(), + pRef->getGameVersion().GetString().getData(), + verThis.GetString().getData()).getData(), strNoJoin.getData(), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error); @@ -1088,7 +1088,7 @@ void C4StartupNetDlg::DoRefresh() // (Re-)Start discovery if(!DiscoverClient.StartDiscovery()) { - StdCopyStrBuf strNoDiscovery(LoadResStr("IDS_NET_NODISCOVERY")); + StdCopyStrBuf strNoDiscovery(LoadResStr("IDS_NET_NODISCOVERY")); ::pGUI->ShowMessageModal( FormatString(LoadResStr("IDS_NET_NODISCOVERY_DESC"), DiscoverClient.GetError()).getData(), strNoDiscovery.getData(), diff --git a/src/gui/C4StartupNetDlg.h b/src/gui/C4StartupNetDlg.h index 3818c4ba1..2e2092ebc 100644 --- a/src/gui/C4StartupNetDlg.h +++ b/src/gui/C4StartupNetDlg.h @@ -109,7 +109,7 @@ class C4StartupNetListEntry : public C4GUI::Window void SetReference(C4Network2Reference *pNewRef); // replace the reference bool Execute(); // update stuff - if false is returned, the item is to be removed - bool OnReference(); // like Execute(), but only called if some reference was received + bool OnReference(); // like Execute(), but only called if some reference was received void UpdateCollapsed(bool fToCollapseValue); const char *GetError() { return fError ? sError.getData() : NULL; } // return error message, if any is set @@ -191,8 +191,8 @@ class C4StartupNetDlg : public C4StartupDlg, private C4InteractiveThread::Callba DlgMode GetDlgMode(); - // callback from C4Network2ReferenceClient - virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData); + // callback from C4Network2ReferenceClient + virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData); public: bool DoOK(); // join currently selected item diff --git a/src/gui/C4StartupOptionsDlg.cpp b/src/gui/C4StartupOptionsDlg.cpp index 10a293b2f..92f4d34e7 100644 --- a/src/gui/C4StartupOptionsDlg.cpp +++ b/src/gui/C4StartupOptionsDlg.cpp @@ -105,8 +105,8 @@ C4StartupOptionsDlg::ResChangeConfirmDlg::ResChangeConfirmDlg() C4GUI::Label *pLblMessage = new C4GUI::Label(sMsgBroken.getData(), caMain.GetFromTop(iMsgHeight), ACenter, C4GUI_MessageFontClr, &C4GUI::GetRes()->TextFont, false); AddElement(pLblMessage); iMsgHeight = C4GUI::GetRes()->TextFont.BreakMessage(FormatString(LoadResStr("IDS_MNU_SWITCHRESOLUTION_UNDO"), - (int)iResChangeSwitchTime).getData(), - caMain.GetInnerWidth(), &sMsgBroken, true); + (int)iResChangeSwitchTime).getData(), + caMain.GetInnerWidth(), &sMsgBroken, true); pOperationCancelLabel = new C4GUI::Label(sMsgBroken.getData(), caMain.GetFromTop(iMsgHeight), ACenter, C4GUI_MessageFontClr, &C4GUI::GetRes()->TextFont, false, false); AddElement(pOperationCancelLabel); // place buttons @@ -142,8 +142,8 @@ void C4StartupOptionsDlg::ResChangeConfirmDlg::OnSec1Timer() // update timer label StdStrBuf sTimerText; C4GUI::GetRes()->TextFont.BreakMessage(FormatString(LoadResStr("IDS_MNU_SWITCHRESOLUTION_UNDO"), - (int)iResChangeSwitchTime).getData(), - pOperationCancelLabel->GetBounds().Wdt, &sTimerText, true); + (int)iResChangeSwitchTime).getData(), + pOperationCancelLabel->GetBounds().Wdt, &sTimerText, true); pOperationCancelLabel->SetText(sTimerText.getData()); } @@ -163,9 +163,9 @@ const char *KeyID2Desc(int32_t iKeyID) C4StartupOptionsDlg::KeySelDialog::KeySelDialog(int32_t iKeyID, int32_t iCtrlSet, bool fGamepad) : C4GUI::MessageDialog(FormatString(LoadResStr(!fGamepad ? "IDS_MSG_PRESSKEY" : "IDS_MSG_PRESSBTN"), - KeyID2Desc(iKeyID), iCtrlSet+1).getData(), LoadResStr("IDS_MSG_DEFINEKEY"), + KeyID2Desc(iKeyID), iCtrlSet+1).getData(), LoadResStr("IDS_MSG_DEFINEKEY"), C4GUI::MessageDialog::btnAbort, fGamepad ? C4GUI::Ico_Gamepad : C4GUI::Ico_Keyboard, C4GUI::MessageDialog::dsRegular), - key(KEY_Undefined), fGamepad(fGamepad), iCtrlSet(iCtrlSet) + key(KEY_Undefined), fGamepad(fGamepad), iCtrlSet(iCtrlSet) { pKeyListener = new C4KeyBinding(C4KeyCodeEx(KEY_Any, KEYS_None), "DefineKey", KEYSCOPE_Gui, new C4GUI::DlgKeyCBPassKey(*this, &C4StartupOptionsDlg::KeySelDialog::KeyDown), C4CustomKey::PRIO_PlrControl); } @@ -195,7 +195,7 @@ bool C4StartupOptionsDlg::KeySelDialog::KeyDown(const C4KeyCodeEx &key) // every key from 0 to C4MaxKey-1 MUST BE present here, or the engine will crash const int32_t iKeyPosMaxX = 3, iKeyPosMaxY = 4; // arrange keys in a 4-by-5-array const int32_t iKeyPosis[iKeyPosMaxY][iKeyPosMaxX] = { - { 0, 1, 2 }, + { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 9,10,11 } }; @@ -571,7 +571,7 @@ void C4StartupOptionsDlg::BoolConfig::OnCheckChange(C4GUI::Element *pCheckBox) if (pbVal) *pbVal = (GetChecked() != fInvert); if (piVal) *piVal = (GetChecked() != fInvert); if (piRestartChangeCfgVal) GetScreen()->ShowMessage(LoadResStr("IDS_MSG_RESTARTCHANGECFG"), GetText(), - C4GUI::Ico_Notify, piRestartChangeCfgVal); + C4GUI::Ico_Notify, piRestartChangeCfgVal); } // ------------------------------------------------ diff --git a/src/gui/C4StartupPlrSelDlg.cpp b/src/gui/C4StartupPlrSelDlg.cpp index 93883436d..d325ceaf5 100644 --- a/src/gui/C4StartupPlrSelDlg.cpp +++ b/src/gui/C4StartupPlrSelDlg.cpp @@ -55,7 +55,7 @@ StdStrBuf DateString(int iTime) if (!iTime) return StdStrBuf("", true); time_t tTime = iTime; //time(&tTime); struct tm *pLocalTime; - pLocalTime=localtime(&tTime); + pLocalTime=localtime(&tTime); return FormatString( "%02d.%02d.%d %02d:%02d", pLocalTime->tm_mday, pLocalTime->tm_mon+1, @@ -959,7 +959,7 @@ void C4StartupPlrSelDlg::SetCrewMode(PlayerListItem *pSel) if (!CurrPlayer.Grp.Open(pSel->GetFilename().getData())) return; if (!CurrPlayer.Grp.FindEntry(C4CFN_ObjectInfoFiles)) { - StdCopyStrBuf strCrew(FormatString("%s %s", LoadResStrNoAmp("IDS_CTL_CREW"), CurrPlayer.Core.PrefName)); + StdCopyStrBuf strCrew(FormatString("%s %s", LoadResStrNoAmp("IDS_CTL_CREW"), CurrPlayer.Core.PrefName)); // player has no crew! GetScreen()->ShowMessage(FormatString(LoadResStr("IDS_ERR_PLRNOCREW"), CurrPlayer.Core.PrefName).getData(), diff --git a/src/gui/C4StartupScenSelDlg.cpp b/src/gui/C4StartupScenSelDlg.cpp index 1c597a75d..2635649c6 100644 --- a/src/gui/C4StartupScenSelDlg.cpp +++ b/src/gui/C4StartupScenSelDlg.cpp @@ -200,7 +200,7 @@ void C4MapFolderData::CompileFunc(StdCompiler *pComp) // compile scenario list int32_t iOldScenCount = iScenCount; pComp->Value(mkNamingCountAdapt(iScenCount, "Scenario")); - if (pComp->isCompiler()) + if (pComp->isCompiler()) { while (iOldScenCount--) delete ppScenList[iOldScenCount]; delete [] ppScenList; @@ -220,7 +220,7 @@ void C4MapFolderData::CompileFunc(StdCompiler *pComp) // compile access gfx list int32_t iOldAccesGfxCount = iAccessGfxCount; pComp->Value(mkNamingCountAdapt(iAccessGfxCount, "AccessGfx")); - if (pComp->isCompiler()) + if (pComp->isCompiler()) { while (iOldAccesGfxCount--) delete ppAccessGfxList[iOldAccesGfxCount]; delete [] ppAccessGfxList; @@ -615,7 +615,7 @@ bool C4ScenarioListLoader::Entry::RenameTo(const char *szNewName) SCopy(sFilename.getData(), fullfn, _MAX_PATH); char *fullfn_fn = GetFilename(fullfn); SCopy(fn, fullfn_fn, _MAX_PATH - (fullfn_fn - fullfn)); - StdCopyStrBuf strErr(LoadResStr("IDS_FAIL_RENAME")); + StdCopyStrBuf strErr(LoadResStr("IDS_FAIL_RENAME")); // check if a rename is due if (!ItemIdentical(sFilename.getData(), fullfn)) { @@ -697,7 +697,7 @@ bool C4ScenarioListLoader::Scenario::LoadCustomPre(C4Group &rGrp) // load scenario core first StdStrBuf sFileContents; if (!rGrp.LoadEntryString(C4CFN_ScenarioCore, sFileContents)) return false; - if(!CompileFromBuf_LogWarn(mkParAdapt(C4S, false), sFileContents, (rGrp.GetFullName() + DirSep C4CFN_ScenarioCore).getData())) + if(!CompileFromBuf_LogWarn(mkParAdapt(C4S, false), sFileContents, (rGrp.GetFullName() + DirSep C4CFN_ScenarioCore).getData())) return false; return true; } @@ -1243,8 +1243,8 @@ bool C4ScenarioListLoader::ReloadCurrent() // font clrs const uint32_t ClrScenarioItem = 0xff000000, - ClrScenarioItemXtra = 0x7f000000, - ClrScenarioItemDisabled = 0x7f000000; + ClrScenarioItemXtra = 0x7f000000, + ClrScenarioItemDisabled = 0x7f000000; // ------------------------------------------------ // --- C4StartupScenSelDlg::ScenListItem diff --git a/src/gui/C4StartupScenSelDlg.h b/src/gui/C4StartupScenSelDlg.h index bdf9099dc..6ab1f3274 100644 --- a/src/gui/C4StartupScenSelDlg.h +++ b/src/gui/C4StartupScenSelDlg.h @@ -34,12 +34,12 @@ class C4StartupScenSelDlg; const int32_t C4StartupScenSel_DefaultIcon_Scenario = 14, C4StartupScenSel_DefaultIcon_Folder = 0, - C4StartupScenSel_DefaultIcon_WinFolder = 44, + C4StartupScenSel_DefaultIcon_WinFolder = 44, C4StartupScenSel_DefaultIcon_OldIconBG = 18, C4StartupScenSel_IconCount = 45, C4StartupScenSel_TitlePictureWdt = 200, C4StartupScenSel_TitlePictureHgt = 150, - C4StartupScenSel_TitlePicturePadding = 10, + C4StartupScenSel_TitlePicturePadding = 10, C4StartupScenSel_TitleOverlayMargin = 10; // number of pixels to each side of title overlay picture // a list of loaded scenarios @@ -242,7 +242,7 @@ class C4ScenarioListLoader int32_t GetProgress() const { return iProgress; } int32_t GetMaxProgress() const { return iMaxProgress; } - int32_t GetProgressPercent() const { return iProgress * 100 / Max(iMaxProgress, 1); } + int32_t GetProgressPercent() const { return iProgress * 100 / Max(iMaxProgress, 1); } }; diff --git a/src/gui/C4UpdateDlg.cpp b/src/gui/C4UpdateDlg.cpp index 98c12970e..1e15fb9a2 100644 --- a/src/gui/C4UpdateDlg.cpp +++ b/src/gui/C4UpdateDlg.cpp @@ -363,8 +363,8 @@ bool C4UpdateDlg::CheckForUpdates(C4GUI::Screen *pScreen, bool fAutomatic) bool C4Network2VersionInfoClient::QueryVersion() { - // Perform an Query query - return Query(NULL, false); + // Perform an Query query + return Query(NULL, false); } bool C4Network2VersionInfoClient::GetVersion(C4GameVersion *piVerOut) diff --git a/src/gui/C4UpdateDlg.h b/src/gui/C4UpdateDlg.h index 15d817b82..d4cd1a643 100644 --- a/src/gui/C4UpdateDlg.h +++ b/src/gui/C4UpdateDlg.h @@ -64,7 +64,7 @@ protected: public: C4Network2VersionInfoClient() : C4Network2HTTPClient() {} - bool QueryVersion(); + bool QueryVersion(); bool GetVersion(C4GameVersion *pSaveToVer); }; diff --git a/src/gui/C4UpperBoard.cpp b/src/gui/C4UpperBoard.cpp index 9a8601844..13b244434 100644 --- a/src/gui/C4UpperBoard.cpp +++ b/src/gui/C4UpperBoard.cpp @@ -57,7 +57,7 @@ void C4UpperBoard::Draw(C4Facet &cgo) if(!cgo.Surface) return; // Background Application.DDraw->BlitSurfaceTile(::GraphicsResource.fctUpperBoard.Surface,Output.Surface,0,0,Output.Wdt,Output.Hgt); - // Logo + // Logo C4Facet cgo2; float fLogoZoom = 0.75f; cgo2.Set(cgo.Surface, (int32_t)(cgo.Wdt/2-(::GraphicsResource.fctLogo.Wdt/2)*fLogoZoom), 0, diff --git a/src/gui/C4Viewport.cpp b/src/gui/C4Viewport.cpp index 25c441951..77f8a57e1 100644 --- a/src/gui/C4Viewport.cpp +++ b/src/gui/C4Viewport.cpp @@ -83,17 +83,17 @@ double round(double x) #include LRESULT APIENTRY ViewportWinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) - { + { // Determine viewport C4Viewport *cvp; if (!(cvp=::GraphicsSystem.GetViewport(hwnd))) return DefWindowProc(hwnd, uMsg, wParam, lParam); // Process message - switch (uMsg) - { - //--------------------------------------------------------------------------------------------------------------------------- - case WM_KEYDOWN: + switch (uMsg) + { + //--------------------------------------------------------------------------------------------------------------------------- + case WM_KEYDOWN: // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - switch (wParam) { @@ -108,42 +108,42 @@ LRESULT APIENTRY ViewportWinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lPa break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } - break; - //--------------------------------------------------------------------------------------------------------------------------- - case WM_KEYUP: + break; + //--------------------------------------------------------------------------------------------------------------------------- + case WM_KEYUP: if (Game.DoKeyboardInput(wParam, KEYEV_Up, !!(lParam & 0x20000000), Application.IsControlDown(), Application.IsShiftDown(), false, NULL)) return 0; break; - //------------------------------------------------------------------------------------------------------------ + //------------------------------------------------------------------------------------------------------------ case WM_SYSKEYDOWN: if (wParam == 18) break; if (Game.DoKeyboardInput(wParam, KEYEV_Down, !!(lParam & 0x20000000), Application.IsControlDown(), Application.IsShiftDown(), !!(lParam & 0x40000000), NULL)) return 0; break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_DESTROY: StoreWindowPosition(hwnd, FormatString("Viewport%i",cvp->Player+1).getData(), Config.GetSubkeyPath("Console")); break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_CLOSE: cvp->pWindow->Close(); break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_DROPFILES: cvp->DropFiles((HANDLE) wParam); break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_USER_DROPDEF: Game.DropDef(C4ID(lParam),cvp->ViewX+float(LOWORD(wParam))/cvp->Zoom,cvp->ViewY+float(HIWORD(wParam)/cvp->Zoom)); break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_SIZE: cvp->UpdateOutputSize(); break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_PAINT: ::GraphicsSystem.Execute(); break; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_HSCROLL: switch (LOWORD(wParam)) { @@ -156,7 +156,7 @@ LRESULT APIENTRY ViewportWinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lPa cvp->Execute(); cvp->ScrollBarsByViewPosition(); return 0; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_VSCROLL: switch (LOWORD(wParam)) { @@ -169,7 +169,7 @@ LRESULT APIENTRY ViewportWinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lPa cvp->Execute(); cvp->ScrollBarsByViewPosition(); return 0; - //---------------------------------------------------------------------------------------------------------------------------------- + //---------------------------------------------------------------------------------------------------------------------------------- case WM_ACTIVATE: // Keep editing dialogs on top of the current viewport, but don't make them // float on other windows (i.e., no HWND_TOPMOST). @@ -192,8 +192,8 @@ LRESULT APIENTRY ViewportWinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lPa SetWindowLongPtr(Console.ToolsDlg.hDialog, GWLP_HWNDPARENT, reinterpret_cast(hwnd)); } break; - //---------------------------------------------------------------------------------------------------------------------------------- - } + //---------------------------------------------------------------------------------------------------------------------------------- + } // Viewport mouse control if (::MouseControl.IsViewport(cvp) && (Console.EditCursor.GetMode()==C4CNS_ModePlay)) @@ -249,17 +249,17 @@ LRESULT APIENTRY ViewportWinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lPa } } - return DefWindowProc(hwnd, uMsg, wParam, lParam); - } + return DefWindowProc(hwnd, uMsg, wParam, lParam); + } CStdWindow * C4ViewportWindow::Init(CStdApp * pApp, const char * Title, CStdWindow * pParent, bool) { Active = true; // Create window hWindow = CreateWindowEx ( - WS_EX_ACCEPTFILES, + WS_EX_ACCEPTFILES, C4ViewportClassName, Title, C4ViewportWindowStyle, - CW_USEDEFAULT,CW_USEDEFAULT,400,250, - pParent->hWindow,NULL,pApp->GetInstance(),NULL); + CW_USEDEFAULT,CW_USEDEFAULT,400,250, + pParent->hWindow,NULL,pApp->GetInstance(),NULL); return hWindow ? this : 0; } @@ -852,7 +852,7 @@ void C4Viewport::Clear() OutX=OutY=ViewWdt=ViewHgt=0; DrawX=DrawY=0; Regions.Clear(); - ViewOffsX = ViewOffsY = 0; + ViewOffsX = ViewOffsY = 0; } void C4Viewport::DrawOverlay(C4TargetFacet &cgo, const ZoomData &GameZoom) @@ -1171,7 +1171,7 @@ void C4Viewport::AdjustPosition() } // NO_OWNER can't scroll if (fIsNoOwnerViewport) { ViewOffsX=0; ViewOffsY=0; } - // clip at borders, update vars + // clip at borders, update vars UpdateViewPosition(); #ifdef WITH_DEVELOPER_MODE //ScrollBarsByViewPosition(); diff --git a/src/lib/C4InputValidation.h b/src/lib/C4InputValidation.h index a8bde821c..39e9a0ef9 100644 --- a/src/lib/C4InputValidation.h +++ b/src/lib/C4InputValidation.h @@ -57,16 +57,16 @@ namespace C4InVal // Validation adapter: Call ValidateString on string after compiling it template struct C4StrValAdapt { - T &rValue; C4InVal::ValidationOption eValType; - explicit C4StrValAdapt(T &rValue, C4InVal::ValidationOption eValType) : rValue(rValue), eValType(eValType) { } - inline void CompileFunc(StdCompiler *pComp) - { - pComp->Value(rValue); + T &rValue; C4InVal::ValidationOption eValType; + explicit C4StrValAdapt(T &rValue, C4InVal::ValidationOption eValType) : rValue(rValue), eValType(eValType) { } + inline void CompileFunc(StdCompiler *pComp) + { + pComp->Value(rValue); if (pComp->isCompiler()) C4InVal::ValidateString(rValue.GetObj(), eValType); // works on Par adapt only :( - } + } template inline bool operator == (const D &nValue) const { return rValue == nValue; } template inline C4StrValAdapt &operator = (const D &nValue) { rValue = nValue; return *this; } - ALLOW_TEMP_TO_REF(C4StrValAdapt) + ALLOW_TEMP_TO_REF(C4StrValAdapt) }; template inline C4StrValAdapt mkStrValAdapt(T RREF rValue, C4InVal::ValidationOption eValType) { return C4StrValAdapt(rValue, eValType); } @@ -76,11 +76,11 @@ struct ValidatedStdCopyStrBufBase : public StdCopyStrBuf ValidatedStdCopyStrBufBase(const char *szCopy) : StdCopyStrBuf(szCopy) {} ValidatedStdCopyStrBufBase() : StdCopyStrBuf() {} - inline void CompileFunc(StdCompiler *pComp, int iRawType = 0) - { - pComp->Value(mkParAdapt(static_cast(*this), iRawType)); + inline void CompileFunc(StdCompiler *pComp, int iRawType = 0) + { + pComp->Value(mkParAdapt(static_cast(*this), iRawType)); if (pComp->isCompiler()) Validate(); - } + } virtual bool Validate() = 0; diff --git a/src/lib/C4NameList.cpp b/src/lib/C4NameList.cpp index 156cb8a5c..902be2697 100644 --- a/src/lib/C4NameList.cpp +++ b/src/lib/C4NameList.cpp @@ -24,12 +24,12 @@ #include C4NameList::C4NameList() - { - Clear(); - } + { + Clear(); + } void C4NameList::Clear() - { + { ZeroMem(this,sizeof(C4NameList)); } @@ -113,19 +113,19 @@ bool C4NameList::IsEmpty() } void C4NameList::CompileFunc(StdCompiler *pComp, bool fValues) - { - bool fCompiler = pComp->isCompiler(); + { + bool fCompiler = pComp->isCompiler(); for (int32_t cnt=0; cntSeperator(StdCompiler::SEP_SEP2); - // Name - pComp->Value(mkDefaultAdapt(mkStringAdapt(Name[cnt], C4MaxName, StdCompiler::RCT_Idtf), "")); - // Value - if(fValues) - { - pComp->Seperator(StdCompiler::SEP_SET); - pComp->Value(mkDefaultAdapt(Count[cnt], 0)); - } - } - } + if(fCompiler || Name[cnt][0]) + { + if(cnt) pComp->Seperator(StdCompiler::SEP_SEP2); + // Name + pComp->Value(mkDefaultAdapt(mkStringAdapt(Name[cnt], C4MaxName, StdCompiler::RCT_Idtf), "")); + // Value + if(fValues) + { + pComp->Seperator(StdCompiler::SEP_SET); + pComp->Value(mkDefaultAdapt(Count[cnt], 0)); + } + } + } diff --git a/src/lib/C4NameList.h b/src/lib/C4NameList.h index 0d6230042..60603c624 100644 --- a/src/lib/C4NameList.h +++ b/src/lib/C4NameList.h @@ -29,14 +29,14 @@ const int C4MaxNameList = 10; #include class C4NameList - { - public: - C4NameList(); - public: - char Name[C4MaxNameList][C4MaxName+1]; - int32_t Count[C4MaxNameList]; - public: - void Clear(); + { + public: + C4NameList(); + public: + char Name[C4MaxNameList][C4MaxName+1]; + int32_t Count[C4MaxNameList]; + public: + void Clear(); bool Add(const char *szName, int32_t iCount=0); bool Set(const char *szName, int32_t iCount); bool Read(const char *szSource, int32_t iDefValue=0); @@ -45,7 +45,7 @@ class C4NameList bool IsEmpty(); bool operator==(const C4NameList& rhs) { return !std::memcmp((const uint8_t*)this,(const uint8_t*)&rhs,sizeof(C4NameList)); } - void CompileFunc(StdCompiler *pComp, bool fValues = true); - }; + void CompileFunc(StdCompiler *pComp, bool fValues = true); + }; #endif diff --git a/src/lib/C4RTF.cpp b/src/lib/C4RTF.cpp index 9eea3b893..1b81dd154 100644 --- a/src/lib/C4RTF.cpp +++ b/src/lib/C4RTF.cpp @@ -212,15 +212,15 @@ void C4RTFFile::ParseChars(StdStrBuf &sResult, const char *szChars) void C4RTFFile::ParseHexChar(StdStrBuf &sResult, char c) { pState->bHex = pState->bHex << 4; - if (isdigit((unsigned char)c)) + if (isdigit((unsigned char)c)) pState->bHex += c - '0'; - else if (Inside(c, 'a', 'f')) + else if (Inside(c, 'a', 'f')) pState->bHex += c - 'a' + 10; - else if (Inside(c, 'A', 'F')) + else if (Inside(c, 'A', 'F')) pState->bHex += c - 'A' + 10; else throw new ParserError("Invalid hex character"); - if (!--pState->iHexBinCnt) + if (!--pState->iHexBinCnt) { pState->eState = psNormal; ParseChar(sResult, pState->bHex); @@ -281,8 +281,8 @@ StdStrBuf C4RTFFile::GetPlainText() case '\\': ParseKeyword(sResult, iPos); break; - case 0x0d: case 0x0a: // ignored chars - break; + case 0x0d: case 0x0a: // ignored chars + break; default: // regular char parsing if (pState->eState == psNormal) @@ -321,56 +321,56 @@ StdStrBuf C4RTFFile::GetPlainText() // Keyword descriptions C4RTFFile::KeywordTableEntry RTFKeywordTable [] = { // keyword iDefaultPar fForceDef eType idx - { "par", 0, false, kwdChars, "\n", 0 }, - { "\0x0a", 0, false, kwdChars, "\n", 0 }, - { "\0x0d", 0, false, kwdChars, "\n", 0 }, - { "tab", 0, false, kwdChars, "\t", 0 }, - { "ldblquote",0, false, kwdChars, "\x93", 0 }, - { "rdblquote",0, false, kwdChars, "\x94", 0 }, - { "lquote", 0, false, kwdChars, "\x91", 0 }, - { "rquote", 0, false, kwdChars, "\x92", 0 }, - { "bullet", 0, false, kwdChars, "\x95", 0 }, - { "endash", 0, false, kwdChars, "\x96", 0 }, - { "emdash", 0, false, kwdChars, "\x97", 0 }, - { "bin", 0, false, kwdSpec, NULL, C4RTFFile::specBin }, - { "*", 0, false, kwdSpec, NULL, C4RTFFile::specSkipDest }, - { "'", 0, false, kwdSpec, NULL, C4RTFFile::specHex }, - { "ansicpg", 0, false, kwdSpec, NULL, C4RTFFile::specAnsicpg }, - { "author", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "buptim", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "colortbl", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "comment", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "creatim", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "doccomm", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "fonttbl", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "footer", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "footerf", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "footerl", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "footerr", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "footnote", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "ftncn", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "ftnsep", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "ftnsepc", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "header", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "headerf", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "headerl", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "headerr", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "info", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "keywords", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "operator", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "pict", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "printim", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "private1", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "revtim", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "rxe", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "stylesheet",0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "subject", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "tc", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "title", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "txe", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "xe", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, - { "{", 0, false, kwdChars, "{", 0 }, - { "}", 0, false, kwdChars, "}", 0 }, - { "\\", 0, false, kwdChars, "\\", 0 }, - { NULL, 0, false, kwdChars, NULL, 0 } - }; + { "par", 0, false, kwdChars, "\n", 0 }, + { "\0x0a", 0, false, kwdChars, "\n", 0 }, + { "\0x0d", 0, false, kwdChars, "\n", 0 }, + { "tab", 0, false, kwdChars, "\t", 0 }, + { "ldblquote",0, false, kwdChars, "\x93", 0 }, + { "rdblquote",0, false, kwdChars, "\x94", 0 }, + { "lquote", 0, false, kwdChars, "\x91", 0 }, + { "rquote", 0, false, kwdChars, "\x92", 0 }, + { "bullet", 0, false, kwdChars, "\x95", 0 }, + { "endash", 0, false, kwdChars, "\x96", 0 }, + { "emdash", 0, false, kwdChars, "\x97", 0 }, + { "bin", 0, false, kwdSpec, NULL, C4RTFFile::specBin }, + { "*", 0, false, kwdSpec, NULL, C4RTFFile::specSkipDest }, + { "'", 0, false, kwdSpec, NULL, C4RTFFile::specHex }, + { "ansicpg", 0, false, kwdSpec, NULL, C4RTFFile::specAnsicpg }, + { "author", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "buptim", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "colortbl", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "comment", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "creatim", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "doccomm", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "fonttbl", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "footer", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "footerf", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "footerl", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "footerr", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "footnote", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "ftncn", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "ftnsep", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "ftnsepc", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "header", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "headerf", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "headerl", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "headerr", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "info", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "keywords", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "operator", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "pict", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "printim", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "private1", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "revtim", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "rxe", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "stylesheet",0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "subject", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "tc", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "title", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "txe", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "xe", 0, false, kwdDest, NULL, C4RTFFile::dsSkip }, + { "{", 0, false, kwdChars, "{", 0 }, + { "}", 0, false, kwdChars, "}", 0 }, + { "\\", 0, false, kwdChars, "\\", 0 }, + { NULL, 0, false, kwdChars, NULL, 0 } + }; diff --git a/src/lib/C4Random.cpp b/src/lib/C4Random.cpp index 1b9d54cb0..03abcc1fd 100644 --- a/src/lib/C4Random.cpp +++ b/src/lib/C4Random.cpp @@ -33,23 +33,23 @@ int32_t FRndBuf3[FRndRes]; int32_t FRndPtr3; void Randomize3() - { - FRndPtr3 = 0; - for (int cnt=0; cnt=rTarget.x+rTarget.Wdt) return false; - if (y+Hgt<=rTarget.y) return false; - if (y>=rTarget.y+rTarget.Hgt) return false; - return true; - } + { + if (x+Wdt<=rTarget.x) return false; + if (x>=rTarget.x+rTarget.Wdt) return false; + if (y+Hgt<=rTarget.y) return false; + if (y>=rTarget.y+rTarget.Hgt) return false; + return true; + } void C4Rect::Intersect(const C4Rect &r2) { diff --git a/src/lib/C4Rect.h b/src/lib/C4Rect.h index 6c85a82ad..fa9fbec41 100644 --- a/src/lib/C4Rect.h +++ b/src/lib/C4Rect.h @@ -34,9 +34,9 @@ struct FLOAT_RECT { float left,right,top,bottom; }; class C4TargetFacet; class C4Rect - { - public: - int32_t x,y,Wdt,Hgt; + { + public: + int32_t x,y,Wdt,Hgt; public: void Set(int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt); void Default(); @@ -57,8 +57,8 @@ class C4Rect void Normalize() { if(Wdt < 0) { x+=Wdt+1; Wdt=-Wdt; } if(Hgt < 0) { y+=Hgt+1; Hgt=-Hgt; } } - void Enlarge(int32_t iBy) - { x -= iBy; y -= iBy; Wdt += 2*iBy; Hgt += 2*iBy; } + void Enlarge(int32_t iBy) + { x -= iBy; y -= iBy; Wdt += 2*iBy; Hgt += 2*iBy; } int32_t GetMiddleX() { return x+Wdt/2; } int32_t GetMiddleY() { return y+Hgt/2; } @@ -73,13 +73,13 @@ class C4Rect Hgt=static_cast(ceilf(rcfOuter.bottom)-floorf(rcfOuter.top)); } void CompileFunc(StdCompiler *pComp); - }; + }; class C4TargetRect: public C4Rect - { - public: - int32_t tx,ty; - public: + { + public: + int32_t tx,ty; + public: C4TargetRect(int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, int32_t iTX, int32_t iTY) : C4Rect(iX, iY, iWdt, iHgt), tx(iTX), ty(iTY) { } C4TargetRect() { } // default ctor; doesn't initialize @@ -90,7 +90,7 @@ class C4TargetRect: public C4Rect void Set(const C4TargetFacet &rSrc); // copy contents from facet void CompileFunc(StdCompiler *pComp); - }; + }; const C4Rect Rect0(0,0,0,0); const C4TargetRect TargetRect0(0,0,0,0,0,0); diff --git a/src/lib/PathFinder.cpp b/src/lib/PathFinder.cpp index 2e8efe4dc..16d8830f1 100644 --- a/src/lib/PathFinder.cpp +++ b/src/lib/PathFinder.cpp @@ -194,38 +194,38 @@ bool CPathFinderRay::Execute() bool CPathFinderRay::PathFree(int &rX, int &rY, int iToX, int iToY) { - int d,dx,dy,aincr,bincr,xincr,yincr,x,y; + int d,dx,dy,aincr,bincr,xincr,yincr,x,y; // Y based - if (Abs(iToX-rX)rX) ? +1 : -1; + if (Abs(iToX-rX)rX) ? +1 : -1; yincr=(iToY>rY) ? +1 : -1; - dy=Abs(iToY-rY); dx=Abs(iToX-rX); + dy=Abs(iToY-rY); dx=Abs(iToX-rX); d=2*dx-dy; aincr=2*(dx-dy); bincr=2*dx; x=rX; y=rY; - for (y=rY; y!=iToY; y+=yincr) - { + for (y=rY; y!=iToY; y+=yincr) + { if (PointFree(x,y)) { rY=y; rX=x; } else return false; - if (d>=0) { x+=xincr; d+=aincr; } else d+=bincr; - } - } + if (d>=0) { x+=xincr; d+=aincr; } else d+=bincr; + } + } // X based - else - { - yincr=(iToY>rY) ? +1 : -1; - xincr=(iToX>rX) ? +1 : -1; + else + { + yincr=(iToY>rY) ? +1 : -1; + xincr=(iToX>rX) ? +1 : -1; dx=Abs(iToX-rX); dy=Abs(iToY-rY); d=2*dy-dx; aincr=2*(dy-dx); bincr=2*dy; x=rX; y=rY; for (x=rX; x!=iToX; x+=xincr) - { + { if (PointFree(x,y)) { rY=y; rX=x; } else return false; - if (d>=0) { y+=yincr; d+=aincr; } - else d+=bincr; - } - } + if (d>=0) { y+=yincr; d+=aincr; } + else d+=bincr; + } + } - return true; + return true; } bool CPathFinderRay::Crawl() diff --git a/src/lib/Standard.cpp b/src/lib/Standard.cpp index 5d133ce47..7d82871bf 100644 --- a/src/lib/Standard.cpp +++ b/src/lib/Standard.cpp @@ -71,77 +71,77 @@ int Pow(int base, int exponent) } bool ForLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - bool (*fnCallback)(int32_t, int32_t, int32_t), int32_t iPar, + bool (*fnCallback)(int32_t, int32_t, int32_t), int32_t iPar, int32_t *lastx, int32_t *lasty) - { - int d,dx,dy,aincr,bincr,xincr,yincr,x,y; - if (Abs(x2-x1)y2) { Swap(x1,x2); Swap(y1,y2); } - xincr=(x2>x1) ? 1 : -1; - dy=y2-y1; dx=Abs(x2-x1); - d=2*dx-dy; aincr=2*(dx-dy); bincr=2*dx; x=x1; y=y1; - if (!fnCallback(x,y,iPar)) + { + int d,dx,dy,aincr,bincr,xincr,yincr,x,y; + if (Abs(x2-x1)y2) { Swap(x1,x2); Swap(y1,y2); } + xincr=(x2>x1) ? 1 : -1; + dy=y2-y1; dx=Abs(x2-x1); + d=2*dx-dy; aincr=2*(dx-dy); bincr=2*dx; x=x1; y=y1; + if (!fnCallback(x,y,iPar)) { if (lastx) *lastx=x; if (lasty) *lasty=y; return false; } - for (y=y1+1; y<=y2; ++y) - { - if (d>=0) { x+=xincr; d+=aincr; } - else d+=bincr; - if (!fnCallback(x,y,iPar)) + for (y=y1+1; y<=y2; ++y) + { + if (d>=0) { x+=xincr; d+=aincr; } + else d+=bincr; + if (!fnCallback(x,y,iPar)) { if (lastx) *lastx=x; if (lasty) *lasty=y; return false; } - } - } - else - { - if (x1>x2) { Swap(x1,x2); Swap(y1,y2); } - yincr=(y2>y1) ? 1 : -1; - dx=x2-x1; dy=Abs(y2-y1); - d=2*dy-dx; aincr=2*(dy-dx); bincr=2*dy; x=x1; y=y1; - if (!fnCallback(x,y,iPar)) + } + } + else + { + if (x1>x2) { Swap(x1,x2); Swap(y1,y2); } + yincr=(y2>y1) ? 1 : -1; + dx=x2-x1; dy=Abs(y2-y1); + d=2*dy-dx; aincr=2*(dy-dx); bincr=2*dy; x=x1; y=y1; + if (!fnCallback(x,y,iPar)) { if (lastx) *lastx=x; if (lasty) *lasty=y; return false; } - for (x=x1+1; x<=x2; ++x) - { - if (d>=0) { y+=yincr; d+=aincr; } - else d+=bincr; - if (!fnCallback(x,y,iPar)) + for (x=x1+1; x<=x2; ++x) + { + if (d>=0) { y+=yincr; d+=aincr; } + else d+=bincr; + if (!fnCallback(x,y,iPar)) { if (lastx) *lastx=x; if (lasty) *lasty=y; return false; } - } - } - return true; - } + } + } + return true; + } //--------------------------------- Characters ------------------------------------------ bool IsIdentifier(char cChar) { - if (Inside(cChar,'A','Z')) return true; - if (Inside(cChar,'a','z')) return true; - if (Inside(cChar,'0','9')) return true; - if (cChar=='_') return true; - if (cChar=='~') return true; - if (cChar=='+') return true; - if (cChar=='-') return true; + if (Inside(cChar,'A','Z')) return true; + if (Inside(cChar,'a','z')) return true; + if (Inside(cChar,'0','9')) return true; + if (cChar=='_') return true; + if (cChar=='~') return true; + if (cChar=='+') return true; + if (cChar=='-') return true; return false; } //------------------------------- Strings ------------------------------------------------ void SCopyL(const char *szSource, char *sTarget, int iMaxL) - { - if (szSource == sTarget) return; - if (!sTarget) return; *sTarget=0; if (!szSource) return; - while (*szSource && (iMaxL>0)) - { *sTarget=*szSource; iMaxL--; szSource++; sTarget++; } - *sTarget=0; - } + { + if (szSource == sTarget) return; + if (!sTarget) return; *sTarget=0; if (!szSource) return; + while (*szSource && (iMaxL>0)) + { *sTarget=*szSource; iMaxL--; szSource++; sTarget++; } + *sTarget=0; + } void SCopy(const char *szSource, char *sTarget, int iMaxL) - { - if (szSource == sTarget) return; + { + if (szSource == sTarget) return; if (iMaxL==-1) { if (!sTarget) return; *sTarget=0; if (!szSource) return; @@ -149,16 +149,16 @@ void SCopy(const char *szSource, char *sTarget, int iMaxL) } else SCopyL(szSource,sTarget,iMaxL); - } + } void SCopyUntil(const char *szSource, char *sTarget, char cUntil, int iMaxL, int iIndex) - { - if (szSource == sTarget) return; - if (!sTarget) return; *sTarget=0; if (!szSource) return; - while ( *szSource && ((*szSource!=cUntil) || (iIndex>0)) && (iMaxL!=0) ) - { *sTarget=*szSource; if (*szSource==cUntil) iIndex--; szSource++; sTarget++; iMaxL--; } - *sTarget=0; - } + { + if (szSource == sTarget) return; + if (!sTarget) return; *sTarget=0; if (!szSource) return; + while ( *szSource && ((*szSource!=cUntil) || (iIndex>0)) && (iMaxL!=0) ) + { *sTarget=*szSource; if (*szSource==cUntil) iIndex--; szSource++; sTarget++; iMaxL--; } + *sTarget=0; + } void SCopyUntil(const char *szSource, char *sTarget, const char * sUntil, size_t iMaxL) { @@ -168,85 +168,85 @@ void SCopyUntil(const char *szSource, char *sTarget, const char * sUntil, size_t } bool SEqualUntil(const char *szStr1, const char *szStr2, char cWild) - { - if (!szStr1 || !szStr2) return false; - while (*szStr1 || *szStr2) - { - if ((*szStr1==cWild) || (*szStr2==cWild)) return true; - if (*szStr1!=*szStr2) return false; - szStr1++; szStr2++; - } - return true; - } + { + if (!szStr1 || !szStr2) return false; + while (*szStr1 || *szStr2) + { + if ((*szStr1==cWild) || (*szStr2==cWild)) return true; + if (*szStr1!=*szStr2) return false; + szStr1++; szStr2++; + } + return true; + } // Beginning of string 1 needs to match string 2. bool SEqual2(const char *szStr1, const char *szStr2) - { - if (!szStr1 || !szStr2) return false; - while (*szStr1 && *szStr2) - if (*szStr1++ != *szStr2++) return false; - if (*szStr2) return false; // Str1 is shorter - return true; - } + { + if (!szStr1 || !szStr2) return false; + while (*szStr1 && *szStr2) + if (*szStr1++ != *szStr2++) return false; + if (*szStr2) return false; // Str1 is shorter + return true; + } bool SEqualNoCase(const char *szStr1, const char *szStr2, int iLen) - { - if (!szStr1 || !szStr2) return false; + { + if (!szStr1 || !szStr2) return false; if (iLen==0) return true; - while (*szStr1 && *szStr2) + while (*szStr1 && *szStr2) { if ( CharCapital(*szStr1++) != CharCapital(*szStr2++)) return false; if (iLen>0) { iLen--; if (iLen==0) return true; } } - if (*szStr1 || *szStr2) return false; - return true; - } + if (*szStr1 || *szStr2) return false; + return true; + } bool SEqual2NoCase(const char *szStr1, const char *szStr2, int iLen) - { - if (!szStr1 || !szStr2) return false; + { + if (!szStr1 || !szStr2) return false; if (iLen==0) return true; - while (*szStr1 && *szStr2) + while (*szStr1 && *szStr2) { if ( CharCapital(*szStr1++) != CharCapital(*szStr2++)) return false; if (iLen>0) { iLen--; if (iLen==0) return true; } } if (*szStr2) return false; // Str1 is shorter - return true; - } + return true; + } int SCharPos(char cTarget, const char *szInStr, int iIndex) - { - const char *cpos; - int ccpos; - if (!szInStr) return -1; - for (cpos=szInStr,ccpos=0; *cpos; cpos++,ccpos++) - if (*cpos==cTarget) + { + const char *cpos; + int ccpos; + if (!szInStr) return -1; + for (cpos=szInStr,ccpos=0; *cpos; cpos++,ccpos++) + if (*cpos==cTarget) { if (iIndex==0) return ccpos; else iIndex--; } - return -1; - } + return -1; + } int SCharLastPos(char cTarget, const char *szInStr) - { - const char *cpos; - int ccpos,lcpos; - if (!szInStr) return -1; - for (cpos=szInStr,ccpos=0,lcpos=-1; *cpos; cpos++,ccpos++) - if (*cpos==cTarget) lcpos=ccpos; - return lcpos; - } + { + const char *cpos; + int ccpos,lcpos; + if (!szInStr) return -1; + for (cpos=szInStr,ccpos=0,lcpos=-1; *cpos; cpos++,ccpos++) + if (*cpos==cTarget) lcpos=ccpos; + return lcpos; + } void SAppend(const char *szSource, char *szTarget, int iMaxL) - { + { if (iMaxL == -1) SCopy(szSource, szTarget + SLen(szTarget)); else SCopy(szSource, szTarget + SLen(szTarget), iMaxL - SLen(szTarget)); - } + } void SAppendChar(char cChar, char *szStr) { @@ -257,83 +257,83 @@ void SAppendChar(char cChar, char *szStr) } bool SCopySegment(const char *szString, int iSegment, char *sTarget, - char cSeparator, int iMaxL, bool fSkipWhitespace) - { + char cSeparator, int iMaxL, bool fSkipWhitespace) + { // Advance to indexed segment - while (iSegment>0) - { - if (SCharPos(cSeparator,szString) == -1) + while (iSegment>0) + { + if (SCharPos(cSeparator,szString) == -1) { sTarget[0]=0; return false; } - szString += SCharPos(cSeparator,szString)+1; - iSegment--; - } + szString += SCharPos(cSeparator,szString)+1; + iSegment--; + } // Advance whitespace if (fSkipWhitespace) szString = SAdvanceSpace(szString); // Copy segment contents - SCopyUntil(szString,sTarget,cSeparator,iMaxL); - return true; - } + SCopyUntil(szString,sTarget,cSeparator,iMaxL); + return true; + } bool SCopySegmentEx(const char *szString, int iSegment, char *sTarget, - char cSep1, char cSep2, int iMaxL, bool fSkipWhitespace) - { + char cSep1, char cSep2, int iMaxL, bool fSkipWhitespace) + { // Advance to indexed segment - while (iSegment>0) - { + while (iSegment>0) + { // use the seperator that's closer int iPos1 = SCharPos(cSep1,szString), iPos2 = SCharPos(cSep2,szString); - if (iPos1 == -1) + if (iPos1 == -1) if (iPos2 == -1) { sTarget[0]=0; return false; } else iPos1=iPos2; else if (iPos2 != -1 && iPos2 < iPos1) iPos1 = iPos2; - szString += iPos1+1; - iSegment--; - } + szString += iPos1+1; + iSegment--; + } // Advance whitespace if (fSkipWhitespace) szString = SAdvanceSpace(szString); // Copy segment contents; use seperator that's closer int iPos1 = SCharPos(cSep1,szString), iPos2 = SCharPos(cSep2,szString); if (iPos2 != -1 && (iPos2 < iPos1 || iPos1 == -1)) cSep1 = cSep2; - SCopyUntil(szString,sTarget,cSep1,iMaxL); - return true; - } + SCopyUntil(szString,sTarget,cSep1,iMaxL); + return true; + } bool SCopyNamedSegment(const char *szString, const char *szName, char *sTarget, char cSeparator, char cNameSeparator, int iMaxL) - { + { // Advance to named segment - while (!( SEqual2(szString,szName) && (szString[SLen(szName)]==cNameSeparator) )) - { - if (SCharPos(cSeparator,szString)==-1) { sTarget[0]=0; return false; } // No more segments - szString += SCharPos(cSeparator,szString)+1; - } + while (!( SEqual2(szString,szName) && (szString[SLen(szName)]==cNameSeparator) )) + { + if (SCharPos(cSeparator,szString)==-1) { sTarget[0]=0; return false; } // No more segments + szString += SCharPos(cSeparator,szString)+1; + } // Copy segment contents - SCopyUntil(szString+SLen(szName)+1,sTarget,cSeparator,iMaxL); - return true; - } + SCopyUntil(szString+SLen(szName)+1,sTarget,cSeparator,iMaxL); + return true; + } int SCharCount(char cTarget, const char *szInStr, const char *cpUntil) - { - int iResult=0; + { + int iResult=0; // Scan string - while (*szInStr) - { + while (*szInStr) + { // End position reached (end character is not included) if (szInStr==cpUntil) return iResult; // Character found - if (*szInStr==cTarget) iResult++; + if (*szInStr==cTarget) iResult++; // Advance - szInStr++; - } + szInStr++; + } // Done - return iResult; - } + return iResult; + } int SCharCountEx(const char *szString, const char *szCharList) { @@ -347,140 +347,140 @@ int SCharCountEx(const char *szString, const char *szCharList) } void SReplaceChar(char *str, char fc, char tc) - { - while (str && *str) - { if (*str==fc) *str=tc; str++; } - } + { + while (str && *str) + { if (*str==fc) *str=tc; str++; } + } void SCapitalize(char *str) - { - while (str && *str) - { + { + while (str && *str) + { *str=CharCapital(*str); - str++; - } - } + str++; + } + } const char *SSearchIdentifier(const char *szString, const char *szIndex) { // Does not check whether szIndex itself is an identifier. // Just checks for space in front and back. - const char *cscr; - int indexlen,match=0; + const char *cscr; + int indexlen,match=0; bool frontok=true; - if (!szString || !szIndex) return NULL; - indexlen=SLen(szIndex); - for (cscr=szString; cscr && *cscr; cscr++) - { + if (!szString || !szIndex) return NULL; + indexlen=SLen(szIndex); + for (cscr=szString; cscr && *cscr; cscr++) + { // Match length if (*cscr==szIndex[match]) match++; - else match=0; - // String is matched, front and back ok? + else match=0; + // String is matched, front and back ok? if (match>=indexlen) if (frontok) if (!IsIdentifier(*(cscr+1))) return cscr+1; - // Currently no match, check for frontok + // Currently no match, check for frontok if (match==0) { if (IsIdentifier(*cscr)) frontok=false; else frontok=true; } } - return NULL; + return NULL; } const char *SSearch(const char *szString, const char *szIndex) - { - const char *cscr; - int indexlen,match=0; - if (!szString || !szIndex) return NULL; - indexlen=SLen(szIndex); - for (cscr=szString; cscr && *cscr; cscr++) - { - if (*cscr==szIndex[match]) match++; - else match=0; - if (match>=indexlen) return cscr+1; - } - return NULL; - } + { + const char *cscr; + int indexlen,match=0; + if (!szString || !szIndex) return NULL; + indexlen=SLen(szIndex); + for (cscr=szString; cscr && *cscr; cscr++) + { + if (*cscr==szIndex[match]) match++; + else match=0; + if (match>=indexlen) return cscr+1; + } + return NULL; + } const char *SSearchNoCase(const char *szString, const char *szIndex) - { - const char *cscr; - int indexlen,match=0; - if (!szString || !szIndex) return NULL; - indexlen=SLen(szIndex); - for (cscr=szString; cscr && *cscr; cscr++) - { - if (CharCapital(*cscr)==CharCapital(szIndex[match])) match++; - else match=0; - if (match>=indexlen) return cscr+1; - } - return NULL; - } + { + const char *cscr; + int indexlen,match=0; + if (!szString || !szIndex) return NULL; + indexlen=SLen(szIndex); + for (cscr=szString; cscr && *cscr; cscr++) + { + if (CharCapital(*cscr)==CharCapital(szIndex[match])) match++; + else match=0; + if (match>=indexlen) return cscr+1; + } + return NULL; + } void SWordWrap(char *szText, char cSpace, char cSepa, int iMaxLine) - { - if (!szText) return; - // Scan string - char *cPos,*cpLastSpace=NULL; - int iLineRun=0; - for (cPos=szText; *cPos; cPos++) - { + { + if (!szText) return; + // Scan string + char *cPos,*cpLastSpace=NULL; + int iLineRun=0; + for (cPos=szText; *cPos; cPos++) + { // Store last space - if (*cPos==cSpace) cpLastSpace=cPos; + if (*cPos==cSpace) cpLastSpace=cPos; // Separator encountered: reset line run if (*cPos==cSepa) iLineRun=0; // Need a break, insert at last space - if (iLineRun>=iMaxLine) - if (cpLastSpace) - { *cpLastSpace=cSepa; iLineRun=cPos - cpLastSpace; } + if (iLineRun>=iMaxLine) + if (cpLastSpace) + { *cpLastSpace=cSepa; iLineRun=cPos - cpLastSpace; } // Line run - iLineRun++; - } - } + iLineRun++; + } + } const char *SAdvanceSpace(const char *szSPos) - { - if (!szSPos) return NULL; - while (IsWhiteSpace(*szSPos)) szSPos++; - return szSPos; - } + { + if (!szSPos) return NULL; + while (IsWhiteSpace(*szSPos)) szSPos++; + return szSPos; + } const char *SRewindSpace(const char *szSPos, const char *pBegin) - { - if (!szSPos || !pBegin) return NULL; - while (IsWhiteSpace(*szSPos)) + { + if (!szSPos || !pBegin) return NULL; + while (IsWhiteSpace(*szSPos)) { szSPos--; if (szSPosszString) && (*cpos==cClear); cpos--,cleared++) *cpos=0x00; - return cleared; + return cleared; } void SNewSegment(char *szStr, const char *szSepa) @@ -570,7 +570,7 @@ bool SCopyPrecedingIdentifier(const char *pBegin, const char *pIdentifier, char const char *cPos; if (!(cPos = SRewindSpace(pIdentifier-1,pBegin))) return false; // Rewind to beginning of identifier - while ((cPos>pBegin) && IsIdentifier(cPos[-1])) cPos--; + while ((cPos>pBegin) && IsIdentifier(cPos[-1])) cPos--; // Copy identifier SCopyIdentifier(cPos,sTarget,iSize); // Success @@ -717,31 +717,31 @@ int SModuleCount(const char *szList) } bool SWildcardMatchEx(const char *szString, const char *szWildcard) - { + { // safety if(!szString || !szWildcard) return false; - // match char-wise - const char *pWild = szWildcard, *pPos = szString; - const char *pLWild = NULL, *pLPos = NULL; // backtracking - while(*pWild || pLWild) - // string wildcard? - if(*pWild == '*') - { pLWild = ++pWild; pLPos = pPos; } - // nothing left to match? - else if(!*pPos) - break; - // equal or one-character-wildcard? proceed - else if(*pWild == '?' || *pWild == *pPos) - { pWild++; pPos++; } - // backtrack possible? - else if(pLPos) - { pWild = pLWild; pPos = ++pLPos; } - // match failed - else - return false; - // match complete if both strings are fully matched - return !*pWild && !*pPos; - } + // match char-wise + const char *pWild = szWildcard, *pPos = szString; + const char *pLWild = NULL, *pLPos = NULL; // backtracking + while(*pWild || pLWild) + // string wildcard? + if(*pWild == '*') + { pLWild = ++pWild; pLPos = pPos; } + // nothing left to match? + else if(!*pPos) + break; + // equal or one-character-wildcard? proceed + else if(*pWild == '?' || *pWild == *pPos) + { pWild++; pPos++; } + // backtrack possible? + else if(pLPos) + { pWild = pLWild; pPos = ++pLPos; } + // match failed + else + return false; + // match complete if both strings are fully matched + return !*pWild && !*pPos; + } const char* SGetParameter(const char *strCommandLine, int iParameter, char *strTarget, int iSize, bool *pWasQuoted) { @@ -807,10 +807,10 @@ long InterlockedDecrement(long * var) #include unsigned long timeGetTime(void) { - static time_t sec_offset; - timeval tv; - gettimeofday(&tv, 0); - if (!sec_offset) sec_offset = tv.tv_sec; - return (tv.tv_sec - sec_offset) * 1000 + tv.tv_usec / 1000; + static time_t sec_offset; + timeval tv; + gettimeofday(&tv, 0); + if (!sec_offset) sec_offset = tv.tv_sec; + return (tv.tv_sec - sec_offset) * 1000 + tv.tv_usec / 1000; } #endif diff --git a/src/lib/Standard.h b/src/lib/Standard.h index efc4951b7..24330c7f6 100644 --- a/src/lib/Standard.h +++ b/src/lib/Standard.h @@ -41,10 +41,10 @@ template inline void Toggle(T &v) { v = !v; } const double pi = 3.14159265358979323846; inline int DWordAligned(int val) - { - if (val%4) { val>>=2; val<<=2; val+=4; } + { + if (val%4) { val>>=2; val<<=2; val+=4; } return val; - } + } int32_t Distance(int32_t iX1, int32_t iY1, int32_t iX2, int32_t iY2); int Angle(int iX1, int iY1, int iX2, int iY2); @@ -52,17 +52,17 @@ int Pow(int base, int exponent); #include inline void ZeroMem(void *lpMem, size_t dwSize) - { + { std::memset(lpMem,'\0',dwSize); - } + } inline void MemCopy(const void *lpMem1, void *lpMem2, size_t dwSize) - { + { std::memmove(lpMem2,lpMem1,dwSize); } bool ForLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, - bool (*fnCallback)(int32_t, int32_t, int32_t), int32_t iPar=0, + bool (*fnCallback)(int32_t, int32_t, int32_t), int32_t iPar=0, int32_t *lastx=NULL, int32_t *lasty=NULL); #include @@ -151,8 +151,8 @@ bool SWildcardMatchEx(const char *szString, const char *szWildcard); inline int osprintf(char *str, const char *fmt, ...) GNUC_FORMAT_ATTRIBUTE_O; inline int osprintf(char *str, const char *fmt, ...) { - va_list args; va_start(args, fmt); - return vsprintf(str, fmt, args); + va_list args; va_start(args, fmt); + return vsprintf(str, fmt, args); } // wrapper to detect "char *" @@ -162,16 +162,16 @@ template <> struct NoPointer { }; // secure sprintf #define sprintf ssprintf template - inline int ssprintf(T &str, const char *fmt, ...) GNUC_FORMAT_ATTRIBUTE_O; + inline int ssprintf(T &str, const char *fmt, ...) GNUC_FORMAT_ATTRIBUTE_O; template - inline int ssprintf(T &str, const char *fmt, ...) - { - NoPointer::noPointer(); - int n = sizeof(str); - va_list args; va_start(args, fmt); - int m = vsnprintf(str, n, fmt, args); + inline int ssprintf(T &str, const char *fmt, ...) + { + NoPointer::noPointer(); + int n = sizeof(str); + va_list args; va_start(args, fmt); + int m = vsnprintf(str, n, fmt, args); if(m >= n) { m = n-1; str[m] = 0; } return m; - } + } #endif // INC_STANDARD diff --git a/src/lib/StdAdaptors.h b/src/lib/StdAdaptors.h index 07158ae3a..d05822546 100644 --- a/src/lib/StdAdaptors.h +++ b/src/lib/StdAdaptors.h @@ -45,29 +45,29 @@ struct StdNullAdapt template struct StdDefaultAdapt { - T &rValue; const D &rDefault; - StdDefaultAdapt(T &rValue, const D &rDefault) : rValue(rValue), rDefault(rDefault) { } - inline void CompileFunc(StdCompiler *pComp) const - { - try - { + T &rValue; const D &rDefault; + StdDefaultAdapt(T &rValue, const D &rDefault) : rValue(rValue), rDefault(rDefault) { } + inline void CompileFunc(StdCompiler *pComp) const + { + try + { #ifdef STDCOMPILER_EXCEPTION_WORKAROUND if(!pComp->ValueSafe(rValue)) rValue = rDefault; #else - pComp->Value(rValue); + pComp->Value(rValue); #endif - } - catch(StdCompiler::NotFoundException *pEx) - { - rValue = rDefault; - delete pEx; - } - } - ALLOW_TEMP_TO_REF(StdDefaultAdapt) + } + catch(StdCompiler::NotFoundException *pEx) + { + rValue = rDefault; + delete pEx; + } + } + ALLOW_TEMP_TO_REF(StdDefaultAdapt) }; template - inline StdDefaultAdapt mkDefaultAdapt(T RREF rValue, const D &rDefault) { return StdDefaultAdapt(rValue, rDefault); } + inline StdDefaultAdapt mkDefaultAdapt(T RREF rValue, const D &rDefault) { return StdDefaultAdapt(rValue, rDefault); } // * Naming Adaptor // Embeds a value into a named section, failsafe @@ -75,40 +75,40 @@ template template struct StdNamingAdapt { - T &rValue; const char *szName; - StdNamingAdapt(T &rValue, const char *szName) : rValue(rValue), szName(szName) { } - inline void CompileFunc(StdCompiler *pComp) const - { - pComp->Name(szName); - try - { - pComp->Value(rValue); - } - catch(StdCompiler::Exception *) - { - pComp->NameEnd(true); - throw; - } - pComp->NameEnd(); - } + T &rValue; const char *szName; + StdNamingAdapt(T &rValue, const char *szName) : rValue(rValue), szName(szName) { } + inline void CompileFunc(StdCompiler *pComp) const + { + pComp->Name(szName); + try + { + pComp->Value(rValue); + } + catch(StdCompiler::Exception *) + { + pComp->NameEnd(true); + throw; + } + pComp->NameEnd(); + } template inline bool operator == (const D &nValue) const { return rValue == nValue; } template inline StdNamingAdapt &operator = (const D &nValue) { rValue = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdNamingAdapt) + ALLOW_TEMP_TO_REF(StdNamingAdapt) }; template - inline StdNamingAdapt mkNamingAdapt(T RREF rValue, const char *szName) { return StdNamingAdapt(rValue, szName); } + inline StdNamingAdapt mkNamingAdapt(T RREF rValue, const char *szName) { return StdNamingAdapt(rValue, szName); } // * Naming Adaptor (defaulting) // Embeds a value into a named section, sets default on fail template struct StdNamingDefaultAdapt { - T &rValue; const char *szName; const D &rDefault; bool fPrefillDefault; bool fStoreDefault; - StdNamingDefaultAdapt(T &rValue, const char *szName, const D &rDefault, bool fPrefillDefault, bool fStoreDefault) : rValue(rValue), szName(szName), rDefault(rDefault), fPrefillDefault(fPrefillDefault), fStoreDefault(fStoreDefault) { } - inline void CompileFunc(StdCompiler *pComp) const - { - // Default check - if(pComp->hasNaming() && pComp->isDecompiler() && rValue == rDefault && !fStoreDefault) + T &rValue; const char *szName; const D &rDefault; bool fPrefillDefault; bool fStoreDefault; + StdNamingDefaultAdapt(T &rValue, const char *szName, const D &rDefault, bool fPrefillDefault, bool fStoreDefault) : rValue(rValue), szName(szName), rDefault(rDefault), fPrefillDefault(fPrefillDefault), fStoreDefault(fStoreDefault) { } + inline void CompileFunc(StdCompiler *pComp) const + { + // Default check + if(pComp->hasNaming() && pComp->isDecompiler() && rValue == rDefault && !fStoreDefault) { if (pComp->Default(szName)) return; } @@ -128,67 +128,67 @@ struct StdNamingDefaultAdapt pComp->NameEnd(true); throw; } - // End section - pComp->NameEnd(); - } - ALLOW_TEMP_TO_REF(StdNamingDefaultAdapt) + // End section + pComp->NameEnd(); + } + ALLOW_TEMP_TO_REF(StdNamingDefaultAdapt) }; template - inline StdNamingDefaultAdapt mkNamingAdapt(T RREF rValue, const char *szName, const D &rDefault, bool fPrefillDefault=false, bool fStoreDefault=false) { return StdNamingDefaultAdapt(rValue, szName, rDefault, fPrefillDefault, fStoreDefault); } + inline StdNamingDefaultAdapt mkNamingAdapt(T RREF rValue, const char *szName, const D &rDefault, bool fPrefillDefault=false, bool fStoreDefault=false) { return StdNamingDefaultAdapt(rValue, szName, rDefault, fPrefillDefault, fStoreDefault); } // * Decompiling Adaptor // Allows to use const objects if the compiler won't change the targets template struct StdDecompileAdapt { - const T &rValue; - explicit StdDecompileAdapt(const T &rValue) : rValue(rValue) { } - inline void CompileFunc(StdCompiler *pComp) const - { - assert(pComp->isDecompiler()); - pComp->Value(const_cast(rValue)); - } - ALLOW_TEMP_TO_REF(StdDecompileAdapt) + const T &rValue; + explicit StdDecompileAdapt(const T &rValue) : rValue(rValue) { } + inline void CompileFunc(StdCompiler *pComp) const + { + assert(pComp->isDecompiler()); + pComp->Value(const_cast(rValue)); + } + ALLOW_TEMP_TO_REF(StdDecompileAdapt) }; template - inline StdDecompileAdapt mkDecompileAdapt(const T &rValue) { return StdDecompileAdapt(rValue); } + inline StdDecompileAdapt mkDecompileAdapt(const T &rValue) { return StdDecompileAdapt(rValue); } // * Runtime value Adaptor // Allows the C4ValueSetCompiler to set the value template struct StdRuntimeValueAdapt { - T &rValue; - explicit StdRuntimeValueAdapt(T &rValue) : rValue(rValue) { } - inline void CompileFunc(StdCompiler *pComp) const - { - pComp->setRuntimeWritesAllowed(+1); - pComp->Value(rValue); + T &rValue; + explicit StdRuntimeValueAdapt(T &rValue) : rValue(rValue) { } + inline void CompileFunc(StdCompiler *pComp) const + { + pComp->setRuntimeWritesAllowed(+1); + pComp->Value(rValue); pComp->setRuntimeWritesAllowed(-1); - } + } template inline bool operator == (const D &nValue) const { return rValue == nValue; } template inline StdRuntimeValueAdapt &operator = (const D &nValue) { rValue = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdRuntimeValueAdapt) + ALLOW_TEMP_TO_REF(StdRuntimeValueAdapt) }; template - inline StdRuntimeValueAdapt mkRuntimeValueAdapt(T RREF rValue) { return StdRuntimeValueAdapt(rValue); } + inline StdRuntimeValueAdapt mkRuntimeValueAdapt(T RREF rValue) { return StdRuntimeValueAdapt(rValue); } // * String adaptor struct StdStringAdapt { - char *szString; int iMaxLength; StdCompiler::RawCompileType eRawType; - StdStringAdapt(char *szString, int iMaxLength, StdCompiler::RawCompileType eRawType = StdCompiler::RCT_Escaped) - : szString(szString), iMaxLength(iMaxLength), eRawType(eRawType) { } - inline void CompileFunc(StdCompiler *pComp) const - { - pComp->String(szString, iMaxLength, eRawType); - } + char *szString; int iMaxLength; StdCompiler::RawCompileType eRawType; + StdStringAdapt(char *szString, int iMaxLength, StdCompiler::RawCompileType eRawType = StdCompiler::RCT_Escaped) + : szString(szString), iMaxLength(iMaxLength), eRawType(eRawType) { } + inline void CompileFunc(StdCompiler *pComp) const + { + pComp->String(szString, iMaxLength, eRawType); + } inline bool operator == (const char *szDefault) const { return SEqual(szString, szDefault); } inline StdStringAdapt &operator = (const char *szDefault) { SCopy(szDefault, szString, iMaxLength); return *this; } - ALLOW_TEMP_TO_REF(StdStringAdapt) + ALLOW_TEMP_TO_REF(StdStringAdapt) }; inline StdStringAdapt mkStringAdapt(char *szString, int iMaxLength, StdCompiler::RawCompileType eRawType = StdCompiler::RCT_Escaped) - { return StdStringAdapt(szString, iMaxLength, eRawType); } + { return StdStringAdapt(szString, iMaxLength, eRawType); } #define mkStringAdaptM(szString) mkStringAdapt(szString, (sizeof(szString) / sizeof(*szString)) - 1) #define mkStringAdaptMA(szString) mkStringAdapt(szString, (sizeof(szString) / sizeof(*szString)) - 1, StdCompiler::RCT_All) #define mkStringAdaptMI(szString) mkStringAdapt(szString, (sizeof(szString) / sizeof(*szString)) - 1, StdCompiler::RCT_Idtf) @@ -197,18 +197,18 @@ inline StdStringAdapt mkStringAdapt(char *szString, int iMaxLength, StdCompiler: // * Raw adaptor struct StdRawAdapt { - void *pData; size_t iSize; StdCompiler::RawCompileType eRawType; - StdRawAdapt(void *pData, size_t iSize, StdCompiler::RawCompileType eRawType = StdCompiler::RCT_Escaped) - : pData(pData), iSize(iSize), eRawType(eRawType) { } - inline void CompileFunc(StdCompiler *pComp) const - { - pComp->Raw(pData, iSize, eRawType); - } + void *pData; size_t iSize; StdCompiler::RawCompileType eRawType; + StdRawAdapt(void *pData, size_t iSize, StdCompiler::RawCompileType eRawType = StdCompiler::RCT_Escaped) + : pData(pData), iSize(iSize), eRawType(eRawType) { } + inline void CompileFunc(StdCompiler *pComp) const + { + pComp->Raw(pData, iSize, eRawType); + } inline bool operator == (const void *pDefault) const { return !memcmp(pDefault, pData, iSize); } inline StdRawAdapt &operator = (const void *pDefault) { memcpy(pData, pDefault, iSize); return *this; } }; inline StdRawAdapt mkRawAdapt(void *pData, size_t iSize, StdCompiler::RawCompileType eRawType = StdCompiler::RCT_Escaped) - { return StdRawAdapt(pData, iSize, eRawType); } + { return StdRawAdapt(pData, iSize, eRawType); } #define mkRawAdaptM(X) mkRawAdapt(&X, sizeof(X)) // * Integer Adaptor @@ -228,7 +228,7 @@ struct StdIntAdapt // Operators for default checking/setting template inline bool operator == (const D &nValue) const { return rValue == nValue; } template inline StdIntAdapt &operator = (const D &nValue) { rValue = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdIntAdapt) + ALLOW_TEMP_TO_REF(StdIntAdapt) }; template inline StdIntAdapt mkIntAdapt(T &rValue) { return StdIntAdapt(rValue); } @@ -252,7 +252,7 @@ struct StdCastAdapt // Operators for default checking/setting template inline bool operator == (const D &nValue) const { return rValue == nValue; } template inline StdCastAdapt &operator = (const D &nValue) { rValue = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdCastAdapt) + ALLOW_TEMP_TO_REF(StdCastAdapt) }; template StdCastAdapt mkCastAdapt(T &rValue) { return StdCastAdapt(rValue); } @@ -262,7 +262,7 @@ template StdCastAdapt mkCastIntAdapt(T &rValue) { return S template struct _IdFuncClass { - T &operator ()(T &rValue) const { return rValue; } + T &operator ()(T &rValue) const { return rValue; } }; // * Array Adaptor @@ -270,52 +270,52 @@ struct _IdFuncClass template > struct StdArrayAdapt { - StdArrayAdapt(T *pArray, int iSize, M map = M()) - : pArray(pArray), iSize(iSize), map(map) - { } - T *pArray; int iSize; M map; - inline void CompileFunc(StdCompiler *pComp) const - { - for(int i = 0; i < iSize; i++) - { - if(i) pComp->Seperator(StdCompiler::SEP_SEP); - pComp->Value(map(pArray[i])); - } - } + StdArrayAdapt(T *pArray, int iSize, M map = M()) + : pArray(pArray), iSize(iSize), map(map) + { } + T *pArray; int iSize; M map; + inline void CompileFunc(StdCompiler *pComp) const + { + for(int i = 0; i < iSize; i++) + { + if(i) pComp->Seperator(StdCompiler::SEP_SEP); + pComp->Value(map(pArray[i])); + } + } // Operators for default checking/setting - inline bool operator == (const T &rDefault) const - { - for(int i = 0; i < iSize; i++) - if(pArray[i] != rDefault) - return false; - return true; - } - inline StdArrayAdapt &operator = (const T &rDefault) - { - for(int i = 0; i < iSize; i++) - pArray[i] = rDefault; - return *this; - } - inline bool operator == (const T *pDefaults) const - { - for(int i = 0; i < iSize; i++) - if(pArray[i] != pDefaults[i]) - return false; - return true; - } - inline StdArrayAdapt &operator = (const T *pDefaults) - { - for(int i = 0; i < iSize; i++) - pArray[i] = pDefaults[i]; - return *this; - } - ALLOW_TEMP_TO_REF(StdArrayAdapt) + inline bool operator == (const T &rDefault) const + { + for(int i = 0; i < iSize; i++) + if(pArray[i] != rDefault) + return false; + return true; + } + inline StdArrayAdapt &operator = (const T &rDefault) + { + for(int i = 0; i < iSize; i++) + pArray[i] = rDefault; + return *this; + } + inline bool operator == (const T *pDefaults) const + { + for(int i = 0; i < iSize; i++) + if(pArray[i] != pDefaults[i]) + return false; + return true; + } + inline StdArrayAdapt &operator = (const T *pDefaults) + { + for(int i = 0; i < iSize; i++) + pArray[i] = pDefaults[i]; + return *this; + } + ALLOW_TEMP_TO_REF(StdArrayAdapt) }; template - inline StdArrayAdapt mkArrayAdapt(T *pArray, int iSize) { return StdArrayAdapt(pArray, iSize); } + inline StdArrayAdapt mkArrayAdapt(T *pArray, int iSize) { return StdArrayAdapt(pArray, iSize); } #define mkArrayAdaptM(A) mkArrayAdapt(A, sizeof(A) / sizeof(*(A))) template - inline StdArrayAdapt mkArrayAdaptMap(T *pArray, int iSize, M map) { return StdArrayAdapt(pArray, iSize, map); } + inline StdArrayAdapt mkArrayAdaptMap(T *pArray, int iSize, M map) { return StdArrayAdapt(pArray, iSize, map); } #define mkArrayAdaptMapM(A, M) mkArrayAdaptMap(A, sizeof(A) / sizeof(*(A)), M) // * Array Adaptor (defaulting) @@ -323,52 +323,52 @@ template template > struct StdArrayDefaultAdapt { - StdArrayDefaultAdapt(T *pArray, size_t iSize, const D &rDefault, const M &map = M()) - : pArray(pArray), iSize(iSize), rDefault(rDefault), map(map) - { } - T *pArray; size_t iSize; const D &rDefault; const M map; - inline void CompileFunc(StdCompiler *pComp) const - { - size_t i, iWrite = iSize; - bool fCompiler = pComp->isCompiler(); - // Decompiling: Omit defaults - if(!fCompiler && pComp->hasNaming()) - while(iWrite > 0 && pArray[iWrite - 1] == rDefault) - iWrite--; - // Read/write values - for(i = 0; i < iWrite; i++) - { - // Seperator? - if(i) if(!pComp->Seperator(StdCompiler::SEP_SEP)) break; - // Expect a value. Default if not found. - pComp->Value(mkDefaultAdapt(map(pArray[i]), rDefault)); - } - // Fill rest of array - if(fCompiler) - for(; i < iSize; i++) - pArray[i] = rDefault; - } + StdArrayDefaultAdapt(T *pArray, size_t iSize, const D &rDefault, const M &map = M()) + : pArray(pArray), iSize(iSize), rDefault(rDefault), map(map) + { } + T *pArray; size_t iSize; const D &rDefault; const M map; + inline void CompileFunc(StdCompiler *pComp) const + { + size_t i, iWrite = iSize; + bool fCompiler = pComp->isCompiler(); + // Decompiling: Omit defaults + if(!fCompiler && pComp->hasNaming()) + while(iWrite > 0 && pArray[iWrite - 1] == rDefault) + iWrite--; + // Read/write values + for(i = 0; i < iWrite; i++) + { + // Seperator? + if(i) if(!pComp->Seperator(StdCompiler::SEP_SEP)) break; + // Expect a value. Default if not found. + pComp->Value(mkDefaultAdapt(map(pArray[i]), rDefault)); + } + // Fill rest of array + if(fCompiler) + for(; i < iSize; i++) + pArray[i] = rDefault; + } // Additional defaulting (whole array) - inline bool operator == (const T *pDefaults) const - { - for(size_t i = 0; i < iSize; i++) - if(pArray[i] != pDefaults[i]) - return false; - return true; - } - inline StdArrayDefaultAdapt &operator = (const T *pDefaults) - { - for(size_t i = 0; i < iSize; i++) - pArray[i] = pDefaults[i]; - return *this; - } - ALLOW_TEMP_TO_REF(StdArrayDefaultAdapt) + inline bool operator == (const T *pDefaults) const + { + for(size_t i = 0; i < iSize; i++) + if(pArray[i] != pDefaults[i]) + return false; + return true; + } + inline StdArrayDefaultAdapt &operator = (const T *pDefaults) + { + for(size_t i = 0; i < iSize; i++) + pArray[i] = pDefaults[i]; + return *this; + } + ALLOW_TEMP_TO_REF(StdArrayDefaultAdapt) }; template - inline StdArrayDefaultAdapt mkArrayAdapt(T *pArray, size_t iSize, const D &rDefault) { return StdArrayDefaultAdapt(pArray, iSize, rDefault); } + inline StdArrayDefaultAdapt mkArrayAdapt(T *pArray, size_t iSize, const D &rDefault) { return StdArrayDefaultAdapt(pArray, iSize, rDefault); } #define mkArrayAdaptDM(A, D) mkArrayAdapt(A, sizeof(A) / sizeof(*(A)), D) template - inline StdArrayDefaultAdapt mkArrayAdaptMap(T *pArray, size_t iSize, const D &rDefault, M map) { return StdArrayDefaultAdapt(pArray, iSize, rDefault, map); } + inline StdArrayDefaultAdapt mkArrayAdaptMap(T *pArray, size_t iSize, const D &rDefault, M map) { return StdArrayDefaultAdapt(pArray, iSize, rDefault, map); } #define mkArrayAdaptMapDM(A, D, M) mkArrayAdaptMap(A, sizeof(A) / sizeof(*(A)), D, M) // * Insertion Adaptor @@ -376,32 +376,32 @@ template template struct StdInsertAdapt { - StdInsertAdapt(T &rObj, I &rIns, bool fBefore = true) - : rObj(rObj), rIns(rIns), fBefore(fBefore) - { } - T &rObj; I &rIns; bool fBefore; - void CompileFunc(StdCompiler *pComp) const - { - if(fBefore) pComp->Value(rIns); - pComp->Value(rObj); - if(!fBefore) pComp->Value(rIns); - } - ALLOW_TEMP_TO_REF(StdInsertAdapt) + StdInsertAdapt(T &rObj, I &rIns, bool fBefore = true) + : rObj(rObj), rIns(rIns), fBefore(fBefore) + { } + T &rObj; I &rIns; bool fBefore; + void CompileFunc(StdCompiler *pComp) const + { + if(fBefore) pComp->Value(rIns); + pComp->Value(rObj); + if(!fBefore) pComp->Value(rIns); + } + ALLOW_TEMP_TO_REF(StdInsertAdapt) }; template - inline StdInsertAdapt mkInsertAdapt(T RREF rObj, I RREF rIns, bool fBefore = true) { return StdInsertAdapt(rObj, rIns, fBefore); } + inline StdInsertAdapt mkInsertAdapt(T RREF rObj, I RREF rIns, bool fBefore = true) { return StdInsertAdapt(rObj, rIns, fBefore); } // * Parameter Adaptor // Specify a second parameter for the CompileFunc template struct StdParameterAdapt { - StdParameterAdapt(T &rObj, const P &rPar) : rObj(rObj), Par(rPar) { } - T &rObj; const P Par; - void CompileFunc(StdCompiler *pComp) const - { - rObj.CompileFunc(pComp, Par); - } + StdParameterAdapt(T &rObj, const P &rPar) : rObj(rObj), Par(rPar) { } + T &rObj; const P Par; + void CompileFunc(StdCompiler *pComp) const + { + rObj.CompileFunc(pComp, Par); + } // Operators for default checking/setting template inline bool operator == (const D &nValue) const { return rObj == nValue; } template inline StdParameterAdapt &operator = (const D &nValue) { rObj = nValue; return *this; } @@ -409,29 +409,29 @@ struct StdParameterAdapt // getting value inline T &GetObj() { return rObj; } - ALLOW_TEMP_TO_REF(StdParameterAdapt) + ALLOW_TEMP_TO_REF(StdParameterAdapt) }; template - inline StdParameterAdapt mkParAdapt(T &rObj, const P &rPar) { return StdParameterAdapt(rObj, rPar); } + inline StdParameterAdapt mkParAdapt(T &rObj, const P &rPar) { return StdParameterAdapt(rObj, rPar); } // * Parameter Adaptor 2 // Specify a second and a third parameter for the CompileFunc template struct StdParameter2Adapt { - StdParameter2Adapt(T &rObj, const P1 &rPar1, const P2 &rPar2) : rObj(rObj), rPar1(rPar1), rPar2(rPar2) { } - T &rObj; const P1 &rPar1; const P2 &rPar2; - void CompileFunc(StdCompiler *pComp) const - { - rObj.CompileFunc(pComp, rPar1, rPar2); - } + StdParameter2Adapt(T &rObj, const P1 &rPar1, const P2 &rPar2) : rObj(rObj), rPar1(rPar1), rPar2(rPar2) { } + T &rObj; const P1 &rPar1; const P2 &rPar2; + void CompileFunc(StdCompiler *pComp) const + { + rObj.CompileFunc(pComp, rPar1, rPar2); + } // Operators for default checking/setting template inline bool operator == (const D &nValue) const { return rObj == nValue; } template inline StdParameter2Adapt &operator = (const D &nValue) { rObj = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdParameter2Adapt) + ALLOW_TEMP_TO_REF(StdParameter2Adapt) }; template - inline StdParameter2Adapt mkParAdapt(T &rObj, const P1 &rPar1, const P2 &rPar2) { return StdParameter2Adapt(rObj, rPar1, rPar2); } + inline StdParameter2Adapt mkParAdapt(T &rObj, const P1 &rPar1, const P2 &rPar2) { return StdParameter2Adapt(rObj, rPar1, rPar2); } // * Store pointer (contents) @@ -439,36 +439,36 @@ template template struct StdPtrAdapt { - StdPtrAdapt(T *&rpObj, bool fAllowNull = true, const char *szNaming = "Data") + StdPtrAdapt(T *&rpObj, bool fAllowNull = true, const char *szNaming = "Data") : rpObj(rpObj), fAllowNull(fAllowNull), szNaming(szNaming) { } - T *&rpObj; bool fAllowNull; const char *szNaming; - void CompileFunc(StdCompiler *pComp) const - { - bool fCompiler = pComp->isCompiler(), - fNaming = pComp->hasNaming(); - // Compiling? Clear object before - if(fCompiler) { delete rpObj; rpObj = NULL; } - // Null checks - different with naming support. - if(fAllowNull) - if(fNaming) - { - // Null check: just omit when writing - if(!fCompiler && !rpObj) return; - // Set up naming - if(!pComp->Name(szNaming)) { assert(fCompiler); pComp->NameEnd(); return; } - } - else - { - bool fNull = !! rpObj; - pComp->Value(fNull); - // Null? Nothing further to do - if(fNull) return; - } - else if(!fCompiler) - assert(rpObj); - // Compile value - if(fCompiler) + T *&rpObj; bool fAllowNull; const char *szNaming; + void CompileFunc(StdCompiler *pComp) const + { + bool fCompiler = pComp->isCompiler(), + fNaming = pComp->hasNaming(); + // Compiling? Clear object before + if(fCompiler) { delete rpObj; rpObj = NULL; } + // Null checks - different with naming support. + if(fAllowNull) + if(fNaming) + { + // Null check: just omit when writing + if(!fCompiler && !rpObj) return; + // Set up naming + if(!pComp->Name(szNaming)) { assert(fCompiler); pComp->NameEnd(); return; } + } + else + { + bool fNull = !! rpObj; + pComp->Value(fNull); + // Null? Nothing further to do + if(fNull) return; + } + else if(!fCompiler) + assert(rpObj); + // Compile value + if(fCompiler) { T *rpnObj; CompileNewFunc(rpnObj, pComp); @@ -476,22 +476,22 @@ struct StdPtrAdapt } else pComp->Value(mkDecompileAdapt(*rpObj)); - // Close naming - if(fAllowNull && fNaming) pComp->NameEnd(); - } + // Close naming + if(fAllowNull && fNaming) pComp->NameEnd(); + } // Operators for default checking/setting inline bool operator == (const T &nValue) const { return rpObj && *rpObj == nValue; } inline StdPtrAdapt &operator = (const T &nValue) { delete rpObj; rpObj = new T(nValue); return *this; } inline bool operator == (const T *pValue) const { return rpObj == pValue; } inline StdPtrAdapt &operator = (const T *pValue) { delete rpObj; rpObj = pValue; return *this; } - ALLOW_TEMP_TO_REF(StdPtrAdapt) + ALLOW_TEMP_TO_REF(StdPtrAdapt) }; template - inline StdPtrAdapt mkPtrAdapt(T *&rpObj, bool fAllowNull = true) { return StdPtrAdapt(rpObj, fAllowNull); } + inline StdPtrAdapt mkPtrAdapt(T *&rpObj, bool fAllowNull = true) { return StdPtrAdapt(rpObj, fAllowNull); } template - inline StdPtrAdapt mkNamingPtrAdapt(T *&rpObj, const char *szNaming) { return StdPtrAdapt(rpObj, true, szNaming); } + inline StdPtrAdapt mkNamingPtrAdapt(T *&rpObj, const char *szNaming) { return StdPtrAdapt(rpObj, true, szNaming); } template - inline StdPtrAdapt mkPtrAdaptNoNull(T *&rpObj) { return mkPtrAdapt(rpObj, false); } + inline StdPtrAdapt mkPtrAdaptNoNull(T *&rpObj) { return mkPtrAdapt(rpObj, false); } // * Adaptor for STL containers // Writes a comma-seperated list for compilers that support it. Otherwise, the size is calculated and safed. @@ -500,10 +500,10 @@ template struct StdSTLContainerAdapt { StdSTLContainerAdapt(C &rStruct, StdCompiler::Sep eSep = StdCompiler::SEP_SEP) - : rStruct(rStruct), eSep(eSep) { } + : rStruct(rStruct), eSep(eSep) { } C &rStruct; const StdCompiler::Sep eSep; - inline void CompileFunc(StdCompiler *pComp) const - { + inline void CompileFunc(StdCompiler *pComp) const + { typedef typename C::value_type T; // Get compiler specs bool fCompiler = pComp->isCompiler(); @@ -557,7 +557,7 @@ struct StdSTLContainerAdapt // Operators for default checking/setting inline bool operator == (const C &nValue) const { return rStruct == nValue; } inline StdSTLContainerAdapt &operator = (const C &nValue) { rStruct = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdSTLContainerAdapt) + ALLOW_TEMP_TO_REF(StdSTLContainerAdapt) }; template inline StdSTLContainerAdapt mkSTLContainerAdapt(C &rTarget, StdCompiler::Sep eSep = StdCompiler::SEP_SEP) { return StdSTLContainerAdapt(rTarget, eSep); } @@ -636,7 +636,7 @@ struct StdIntPackAdapt } template inline bool operator == (const D &nValue) const { return rVal == nValue; } template inline StdIntPackAdapt &operator = (const D &nValue) { rVal = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdIntPackAdapt) + ALLOW_TEMP_TO_REF(StdIntPackAdapt) }; template StdIntPackAdapt mkIntPackAdapt(T &rVal) { return StdIntPackAdapt(rVal); } @@ -723,7 +723,7 @@ struct StdEnumAdapt template inline bool operator == (const D &nValue) const { return rVal == nValue; } template inline StdEnumAdapt &operator = (const D &nValue) { rVal = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdEnumAdapt) + ALLOW_TEMP_TO_REF(StdEnumAdapt) }; template StdEnumAdapt mkEnumAdapt(T &rVal, const StdEnumEntry *pNames) { return StdEnumAdapt(rVal, pNames); } @@ -830,7 +830,7 @@ struct StdBitfieldAdapt template inline bool operator == (const D &nValue) const { return rVal == nValue; } template inline StdBitfieldAdapt &operator = (const D &nValue) { rVal = nValue; return *this; } - ALLOW_TEMP_TO_REF(StdBitfieldAdapt) + ALLOW_TEMP_TO_REF(StdBitfieldAdapt) }; template StdBitfieldAdapt mkBitfieldAdapt(T &rVal, const StdBitfieldEntry *pNames) { return StdBitfieldAdapt(rVal, pNames); } @@ -843,9 +843,9 @@ template struct StdNamingCountAdapt { int_t &iCount; const char *szName; - StdNamingCountAdapt(int_t &iCount, const char *szName) : iCount(iCount), szName(szName) { } - inline void CompileFunc(StdCompiler *pComp) const - { + StdNamingCountAdapt(int_t &iCount, const char *szName) : iCount(iCount), szName(szName) { } + inline void CompileFunc(StdCompiler *pComp) const + { if(pComp->hasNaming()) { if(pComp->isCompiler()) @@ -853,8 +853,8 @@ struct StdNamingCountAdapt } else pComp->Value(mkIntPackAdapt(iCount)); - } - ALLOW_TEMP_TO_REF(StdNamingCountAdapt) + } + ALLOW_TEMP_TO_REF(StdNamingCountAdapt) }; template inline StdNamingCountAdapt mkNamingCountAdapt(int_t &iCount, const char *szName) { return StdNamingCountAdapt(iCount, szName); } diff --git a/src/lib/StdBuf.cpp b/src/lib/StdBuf.cpp index 50c99cdd6..7b9cee002 100644 --- a/src/lib/StdBuf.cpp +++ b/src/lib/StdBuf.cpp @@ -43,85 +43,85 @@ bool StdBuf::LoadFromFile(const char *szFile) { - // Open file - int fh = open(szFile, O_BINARY | O_RDONLY | O_SEQUENTIAL, S_IREAD | S_IWRITE); - if(fh < 0) return false; - // Create buf - New(FileSize(fh)); - // Read - if(read(fh, getMData(), getSize()) != (signed int) getSize()) - { - close(fh); - return false; - } - close(fh); - // Ok - return true; + // Open file + int fh = open(szFile, O_BINARY | O_RDONLY | O_SEQUENTIAL, S_IREAD | S_IWRITE); + if(fh < 0) return false; + // Create buf + New(FileSize(fh)); + // Read + if(read(fh, getMData(), getSize()) != (signed int) getSize()) + { + close(fh); + return false; + } + close(fh); + // Ok + return true; } bool StdBuf::SaveToFile(const char *szFile) const { - // Open file - int fh = open(szFile, O_BINARY | O_CREAT | O_WRONLY | O_SEQUENTIAL | O_TRUNC, S_IREAD | S_IWRITE); - if(fh < 0) return false; - // Write data - if(write(fh, getData(), getSize()) != (signed int) getSize()) - { - close(fh); - return false; - } - close(fh); - // Ok - return true; + // Open file + int fh = open(szFile, O_BINARY | O_CREAT | O_WRONLY | O_SEQUENTIAL | O_TRUNC, S_IREAD | S_IWRITE); + if(fh < 0) return false; + // Write data + if(write(fh, getData(), getSize()) != (signed int) getSize()) + { + close(fh); + return false; + } + close(fh); + // Ok + return true; } bool StdStrBuf::LoadFromFile(const char *szFile) { - // Open file - int fh = open(szFile, O_BINARY | O_RDONLY | O_SEQUENTIAL, S_IREAD | S_IWRITE); - if(fh < 0) return false; - // Create buf - SetLength(FileSize(fh)); - // Read - if(read(fh, getMData(), getLength()) != (ssize_t) getLength()) - { - close(fh); - return false; - } - close(fh); - // Ok - return true; + // Open file + int fh = open(szFile, O_BINARY | O_RDONLY | O_SEQUENTIAL, S_IREAD | S_IWRITE); + if(fh < 0) return false; + // Create buf + SetLength(FileSize(fh)); + // Read + if(read(fh, getMData(), getLength()) != (ssize_t) getLength()) + { + close(fh); + return false; + } + close(fh); + // Ok + return true; } bool StdStrBuf::SaveToFile(const char *szFile) const { - // Open file - int fh = open(szFile, O_BINARY | O_CREAT | O_WRONLY | O_SEQUENTIAL | O_TRUNC, S_IREAD | S_IWRITE); - if(fh < 0) return false; - // Write data - if(write(fh, getData(), getLength()) != (ssize_t) getLength()) - { - close(fh); - return false; - } - close(fh); - // Ok - return true; + // Open file + int fh = open(szFile, O_BINARY | O_CREAT | O_WRONLY | O_SEQUENTIAL | O_TRUNC, S_IREAD | S_IWRITE); + if(fh < 0) return false; + // Write data + if(write(fh, getData(), getLength()) != (ssize_t) getLength()) + { + close(fh); + return false; + } + close(fh); + // Ok + return true; } void StdBuf::CompileFunc(StdCompiler *pComp, int iType) { - // Size (guess it is a small value most of the time - if it's big, an extra byte won't hurt anyway) + // Size (guess it is a small value most of the time - if it's big, an extra byte won't hurt anyway) uint32_t tmp = iSize; pComp->Value(mkIntPackAdapt(tmp)); iSize = tmp; - pComp->Seperator(StdCompiler::SEP_PART2); - // Read/write data + pComp->Seperator(StdCompiler::SEP_PART2); + // Read/write data if(pComp->isCompiler()) - { - New(iSize); - pComp->Raw(getMData(), iSize, StdCompiler::RawCompileType(iType)); - } - else - { - pComp->Raw(const_cast(getData()), iSize, StdCompiler::RawCompileType(iType)); - } + { + New(iSize); + pComp->Raw(getMData(), iSize, StdCompiler::RawCompileType(iType)); + } + else + { + pComp->Raw(const_cast(getData()), iSize, StdCompiler::RawCompileType(iType)); + } } // *** StdStringBuf @@ -129,7 +129,7 @@ void StdBuf::CompileFunc(StdCompiler *pComp, int iType) void StdStrBuf::Format(const char *szFmt, ...) { // Create argument list - va_list args; va_start(args, szFmt); + va_list args; va_start(args, szFmt); // Format FormatV(szFmt, args); } @@ -145,7 +145,7 @@ void StdStrBuf::FormatV(const char *szFmt, va_list args) void StdStrBuf::AppendFormat(const char *szFmt, ...) { // Create argument list - va_list args; va_start(args, szFmt); + va_list args; va_start(args, szFmt); // Format AppendFormatV(szFmt, args); } @@ -167,12 +167,12 @@ void StdStrBuf::AppendFormatV(const char *szFmt, va_list args) #elif defined(HAVE_VSCPRINTF) // Save append start int iStart = getLength(); - // Calculate size, allocate - int iLength = vscprintf(szFmt, args); - Grow(iLength); - // Format - char *pPos = getMElem(*this, iSize - iLength - 1); - vsprintf(getMPtr(iStart), szFmt, args); + // Calculate size, allocate + int iLength = vscprintf(szFmt, args); + Grow(iLength); + // Format + char *pPos = getMElem(*this, iSize - iLength - 1); + vsprintf(getMPtr(iStart), szFmt, args); #else // Save append start int iStart = getLength(), iBytes; @@ -193,31 +193,31 @@ void StdStrBuf::AppendFormatV(const char *szFmt, va_list args) void StdStrBuf::CompileFunc(StdCompiler *pComp, int iRawType) { - if(pComp->isCompiler()) - { - char *pnData; - pComp->String(&pnData, StdCompiler::RawCompileType(iRawType)); - Take(pnData); - } - else - { - char *pData = const_cast(getData()); - if (!pData) pData = const_cast(""); - pComp->String(&pData, StdCompiler::RawCompileType(iRawType)); - } + if(pComp->isCompiler()) + { + char *pnData; + pComp->String(&pnData, StdCompiler::RawCompileType(iRawType)); + Take(pnData); + } + else + { + char *pData = const_cast(getData()); + if (!pData) pData = const_cast(""); + pComp->String(&pData, StdCompiler::RawCompileType(iRawType)); + } } StdStrBuf FormatString(const char *szFmt, ...) { - va_list args; va_start(args, szFmt); - return FormatStringV(szFmt, args); + va_list args; va_start(args, szFmt); + return FormatStringV(szFmt, args); } StdStrBuf FormatStringV(const char *szFmt, va_list args) { - StdStrBuf Buf; - Buf.FormatV(szFmt, args); - return Buf; + StdStrBuf Buf; + Buf.FormatV(szFmt, args); + return Buf; } // replace all occurences of one string with another. Return number of replacements. diff --git a/src/lib/StdBuf.h b/src/lib/StdBuf.h index bfbb2e362..269a4cd09 100644 --- a/src/lib/StdBuf.h +++ b/src/lib/StdBuf.h @@ -40,101 +40,101 @@ class StdBuf { public: - // *** Construction - // Standard constructor - StdBuf() : fRef(true), pData(NULL), iSize(0) { } + // *** Construction + // Standard constructor + StdBuf() : fRef(true), pData(NULL), iSize(0) { } - // Constructor from other buffer (copy construction): - // Will take over buffer ownership. Copies data if specified. - // Note: Construct with Buf2.getRef() to construct a reference (This will work for a constant Buf2, too) + // Constructor from other buffer (copy construction): + // Will take over buffer ownership. Copies data if specified. + // Note: Construct with Buf2.getRef() to construct a reference (This will work for a constant Buf2, too) StdBuf(StdBuf RREF Buf2, bool fCopy = false) - : fRef(true), pData(NULL), iSize(0) - { - if(fCopy) - Copy(Buf2); - else if(!Buf2.isRef()) + : fRef(true), pData(NULL), iSize(0) + { + if(fCopy) + Copy(Buf2); + else if(!Buf2.isRef()) Take(std::move(Buf2)); - else - Ref(Buf2); - } + else + Ref(Buf2); + } #ifdef HAVE_RVALUE_REF - StdBuf(const StdBuf & Buf2, bool fCopy = true) - : fRef(true), pData(NULL), iSize(0) - { - if(fCopy) - Copy(Buf2); - else - Ref(Buf2); - } + StdBuf(const StdBuf & Buf2, bool fCopy = true) + : fRef(true), pData(NULL), iSize(0) + { + if(fCopy) + Copy(Buf2); + else + Ref(Buf2); + } #endif - // Set by constant data. Copies data if desired. - StdBuf(const void *pData, size_t iSize, bool fCopy = false) - : fRef(true), pData(pData), iSize(iSize) - { - if(fCopy) Copy(); - } + // Set by constant data. Copies data if desired. + StdBuf(const void *pData, size_t iSize, bool fCopy = false) + : fRef(true), pData(pData), iSize(iSize) + { + if(fCopy) Copy(); + } - ~StdBuf() - { - Clear(); - } + ~StdBuf() + { + Clear(); + } ALLOW_TEMP_TO_REF(StdBuf) protected: - // Reference? Otherwise, this object holds the data. - bool fRef; - // Data - union - { - const void *pData; - void *pMData; + // Reference? Otherwise, this object holds the data. + bool fRef; + // Data + union + { + const void *pData; + void *pMData; #if defined(_DEBUG) char *szString; // for debugger preview #endif - }; - size_t iSize; + }; + size_t iSize; public: - // *** Getters + // *** Getters bool isNull() const { return ! getData(); } - const void *getData() const { return fRef ? pData : pMData; } - void *getMData() { assert(!fRef); return pMData; } - size_t getSize() const { return iSize; } - bool isRef() const { return fRef; } + const void *getData() const { return fRef ? pData : pMData; } + void *getMData() { assert(!fRef); return pMData; } + size_t getSize() const { return iSize; } + bool isRef() const { return fRef; } - const void *getPtr(size_t i) const { return reinterpret_cast(getData()) + i; } - void *getMPtr(size_t i) { return reinterpret_cast(getMData()) + i; } + const void *getPtr(size_t i) const { return reinterpret_cast(getData()) + i; } + void *getMPtr(size_t i) { return reinterpret_cast(getMData()) + i; } - StdBuf getPart(size_t iStart, size_t inSize) const - { - assert(iStart + inSize <= iSize); - return StdBuf(getPtr(iStart), inSize); - } + StdBuf getPart(size_t iStart, size_t inSize) const + { + assert(iStart + inSize <= iSize); + return StdBuf(getPtr(iStart), inSize); + } - // *** Setters + // *** Setters - // * Direct setters + // * Direct setters - // Reference given data - void Ref(const void *pnData, size_t inSize) - { - Clear(); - fRef = true; pData = pnData; iSize = inSize; - } - // Take over data (hold it) - void Take(void *pnData, size_t inSize) - { - Clear(); - if(pnData) - { - fRef = false; pMData = pnData; iSize = inSize; - } - } + // Reference given data + void Ref(const void *pnData, size_t inSize) + { + Clear(); + fRef = true; pData = pnData; iSize = inSize; + } + // Take over data (hold it) + void Take(void *pnData, size_t inSize) + { + Clear(); + if(pnData) + { + fRef = false; pMData = pnData; iSize = inSize; + } + } // Transfer puffer ownership to the caller void *GrabPointer() { @@ -146,130 +146,130 @@ public: return pMData; } - // * Buffer data operations + // * Buffer data operations - // Create new buffer with given size - void New(size_t inSize) - { - Clear(); - pMData = malloc(iSize = inSize); - fRef = false; - } - // Write data into the buffer - void Write(const void *pnData, size_t inSize, size_t iAt = 0) - { - assert(iAt + inSize <= iSize); - if(pnData && inSize) memcpy(getMPtr(iAt), pnData, inSize); - } - // Move data around inside the buffer (checks overlap) - void Move(size_t iFrom, size_t inSize, size_t iTo = 0) - { - assert(iFrom + inSize <= iSize); assert(iTo + inSize <= iSize); - memmove(getMPtr(iTo), getPtr(iFrom), inSize); - } + // Create new buffer with given size + void New(size_t inSize) + { + Clear(); + pMData = malloc(iSize = inSize); + fRef = false; + } + // Write data into the buffer + void Write(const void *pnData, size_t inSize, size_t iAt = 0) + { + assert(iAt + inSize <= iSize); + if(pnData && inSize) memcpy(getMPtr(iAt), pnData, inSize); + } + // Move data around inside the buffer (checks overlap) + void Move(size_t iFrom, size_t inSize, size_t iTo = 0) + { + assert(iFrom + inSize <= iSize); assert(iTo + inSize <= iSize); + memmove(getMPtr(iTo), getPtr(iFrom), inSize); + } // Compare to memory int Compare(const void *pCData, size_t iCSize, size_t iAt = 0) const { assert(iAt + iCSize <= getSize()); return memcmp(getPtr(iAt), pCData, iCSize); } - // Grow the buffer - void Grow(size_t iGrow) - { - // Grow dereferences - if(fRef) { Copy(iSize + iGrow); return; } - if(!iGrow) return; - // Realloc - pMData = realloc(pMData, iSize += iGrow); - } - // Shrink the buffer - void Shrink(size_t iShrink) - { - assert(iSize >= iShrink); - // Shrink dereferences - if(fRef) { Copy(iSize - iShrink); return; } - if(!iShrink) return; - // Realloc - pMData = realloc(pMData, iSize -= iShrink); - } - // Clear buffer - void Clear() - { - if(!fRef) free(pMData); - pMData = NULL; fRef = true; iSize = 0; - } + // Grow the buffer + void Grow(size_t iGrow) + { + // Grow dereferences + if(fRef) { Copy(iSize + iGrow); return; } + if(!iGrow) return; + // Realloc + pMData = realloc(pMData, iSize += iGrow); + } + // Shrink the buffer + void Shrink(size_t iShrink) + { + assert(iSize >= iShrink); + // Shrink dereferences + if(fRef) { Copy(iSize - iShrink); return; } + if(!iShrink) return; + // Realloc + pMData = realloc(pMData, iSize -= iShrink); + } + // Clear buffer + void Clear() + { + if(!fRef) free(pMData); + pMData = NULL; fRef = true; iSize = 0; + } // Free buffer that had been grabbed static void DeletePointer(void *data) { free(data); } - // * Composed actions + // * Composed actions - // Set buffer size (dereferences) - void SetSize(size_t inSize) - { - if(inSize > iSize) - Grow(inSize - iSize); - else - Shrink(iSize - inSize); - } + // Set buffer size (dereferences) + void SetSize(size_t inSize) + { + if(inSize > iSize) + Grow(inSize - iSize); + else + Shrink(iSize - inSize); + } - // Write buffer contents into the buffer - void Write(const StdBuf &Buf2, size_t iAt = 0) - { + // Write buffer contents into the buffer + void Write(const StdBuf &Buf2, size_t iAt = 0) + { Write(Buf2.getData(), Buf2.getSize(), iAt); - } + } - // Compare (a part of) this buffer's contents to another's - int Compare(const StdBuf &Buf2, size_t iAt = 0) const - { + // Compare (a part of) this buffer's contents to another's + int Compare(const StdBuf &Buf2, size_t iAt = 0) const + { return Compare(Buf2.getData(), Buf2.getSize(), iAt); - } + } - // Create a copy of the data (dereferences, obviously) - void Copy(size_t inSize) - { - if(isNull() && !inSize) return; - const void *pOldData = getData(); + // Create a copy of the data (dereferences, obviously) + void Copy(size_t inSize) + { + if(isNull() && !inSize) return; + const void *pOldData = getData(); size_t iOldSize = iSize; - New(inSize); - Write(pOldData, Min(iOldSize, inSize)); - } - void Copy() - { - Copy(iSize); - } - // Copy data from address - void Copy(const void *pnData, size_t inSize) - { + New(inSize); + Write(pOldData, Min(iOldSize, inSize)); + } + void Copy() + { + Copy(iSize); + } + // Copy data from address + void Copy(const void *pnData, size_t inSize) + { Ref(pnData, inSize); Copy(); - } - // Copy from another buffer - void Copy(const StdBuf &Buf2) - { - Copy(Buf2.getData(), Buf2.getSize()); - } + } + // Copy from another buffer + void Copy(const StdBuf &Buf2) + { + Copy(Buf2.getData(), Buf2.getSize()); + } // Create a copy and return it StdBuf Duplicate() const { StdBuf Buf; Buf.Copy(*this); return Buf; } - // Append data from address - void Append(const void *pnData, int inSize) - { - Grow(inSize); - Write(pnData, inSize, iSize - inSize); - } - // Append data from another buffer - void Append(const StdBuf &Buf2) - { - Append(Buf2.getData(), Buf2.getSize()); - } + // Append data from address + void Append(const void *pnData, int inSize) + { + Grow(inSize); + Write(pnData, inSize, iSize - inSize); + } + // Append data from another buffer + void Append(const StdBuf &Buf2) + { + Append(Buf2.getData(), Buf2.getSize()); + } // Reference another buffer's contents - void Ref(const StdBuf &Buf2) + void Ref(const StdBuf &Buf2) { Ref(Buf2.getData(), Buf2.getSize()); } @@ -278,101 +278,101 @@ public: { return StdBuf(getData(), getSize()); } - // take over another buffer's contents - void Take(StdBuf RREF Buf2) + // take over another buffer's contents + void Take(StdBuf RREF Buf2) { - Take(Buf2.GrabPointer(), Buf2.getSize()); - } + Take(Buf2.GrabPointer(), Buf2.getSize()); + } - // * File support - bool LoadFromFile(const char *szFile); - bool SaveToFile(const char *szFile) const; + // * File support + bool LoadFromFile(const char *szFile); + bool SaveToFile(const char *szFile) const; - // *** Operators + // *** Operators - // Null check - bool operator ! () const { return isNull(); } + // Null check + bool operator ! () const { return isNull(); } - // Appending - StdBuf operator += (const StdBuf &Buf2) { - Append(Buf2); - return *this; - } - StdBuf operator + (const StdBuf &Buf2) const - { - StdBuf Buf(getRef()); - Buf.Append(Buf2); - return Buf; - } + // Appending + StdBuf operator += (const StdBuf &Buf2) { + Append(Buf2); + return *this; + } + StdBuf operator + (const StdBuf &Buf2) const + { + StdBuf Buf(getRef()); + Buf.Append(Buf2); + return Buf; + } - // Compare - bool operator == (const StdBuf &Buf2) const - { - return getSize() == Buf2.getSize() && !Compare(Buf2); - } - bool operator != (const StdBuf &Buf2) const { return ! operator == (Buf2); } + // Compare + bool operator == (const StdBuf &Buf2) const + { + return getSize() == Buf2.getSize() && !Compare(Buf2); + } + bool operator != (const StdBuf &Buf2) const { return ! operator == (Buf2); } - // Set (as constructor: take if possible) - StdBuf &operator = (StdBuf RREF Buf2) + // Set (as constructor: take if possible) + StdBuf &operator = (StdBuf RREF Buf2) { if(Buf2.isRef()) Ref(Buf2); else Take(std::move(Buf2)); - return *this; - } + return *this; + } - // build a simple hash - int GetHash() const - { - if(isNull()) return 0; - return crc32(0, reinterpret_cast(getData()), getSize()); - } + // build a simple hash + int GetHash() const + { + if(isNull()) return 0; + return crc32(0, reinterpret_cast(getData()), getSize()); + } - // *** Compiling + // *** Compiling - void CompileFunc(class StdCompiler *pComp, int iType = 0); + void CompileFunc(class StdCompiler *pComp, int iType = 0); }; // Cast Hide Helpers - MSVC doesn't allow this as member template template - const elem_t *getBufPtr(const StdBuf &Buf, size_t iPos = 0) - { - // assert(iPos + sizeof(elem_t) <= Buf.getSize()); - const void *pPos = reinterpret_cast(Buf.getData()) + iPos; - return reinterpret_cast(pPos); - } + const elem_t *getBufPtr(const StdBuf &Buf, size_t iPos = 0) + { + // assert(iPos + sizeof(elem_t) <= Buf.getSize()); + const void *pPos = reinterpret_cast(Buf.getData()) + iPos; + return reinterpret_cast(pPos); + } template - elem_t *getMBufPtr(StdBuf &Buf, size_t iPos = 0) - { - // assert(iPos + sizeof(elem_t) <= Buf.getSize()); - void *pPos = reinterpret_cast(Buf.getMData()) + iPos; - return reinterpret_cast(pPos); - } + elem_t *getMBufPtr(StdBuf &Buf, size_t iPos = 0) + { + // assert(iPos + sizeof(elem_t) <= Buf.getSize()); + void *pPos = reinterpret_cast(Buf.getMData()) + iPos; + return reinterpret_cast(pPos); + } // Copy-Buffer - Just copies data in the copy constructor. class StdCopyBuf : public StdBuf { public: - StdCopyBuf() - { } + StdCopyBuf() + { } - // Set by buffer. Copies data by default. - StdCopyBuf(const StdBuf &Buf2, bool fCopy = true) - : StdBuf(Buf2.getRef(), fCopy) - { } + // Set by buffer. Copies data by default. + StdCopyBuf(const StdBuf &Buf2, bool fCopy = true) + : StdBuf(Buf2.getRef(), fCopy) + { } - // Set by buffer. Copies data by default. - StdCopyBuf(const StdCopyBuf &Buf2, bool fCopy = true) - : StdBuf(Buf2.getRef(), fCopy) - { } + // Set by buffer. Copies data by default. + StdCopyBuf(const StdCopyBuf &Buf2, bool fCopy = true) + : StdBuf(Buf2.getRef(), fCopy) + { } - // Set by constant data. Copies data by default. - StdCopyBuf(const void *pData, size_t iSize, bool fCopy = true) - : StdBuf(pData, iSize, fCopy) - { } + // Set by constant data. Copies data by default. + StdCopyBuf(const void *pData, size_t iSize, bool fCopy = true) + : StdBuf(pData, iSize, fCopy) + { } - StdCopyBuf &operator = (const StdBuf &Buf2) { Copy(Buf2); return *this; } - StdCopyBuf &operator = (const StdCopyBuf &Buf2) { Copy(Buf2); return *this; } + StdCopyBuf &operator = (const StdBuf &Buf2) { Copy(Buf2); return *this; } + StdCopyBuf &operator = (const StdCopyBuf &Buf2) { Copy(Buf2); return *this; } }; @@ -381,7 +381,7 @@ class StdStrBuf : protected StdBuf { public: - // *** Construction + // *** Construction StdStrBuf() : StdBuf() @@ -393,150 +393,150 @@ public: // StdBuf constructor will be used, which will ref the contents // instead of moving them. StdStrBuf(StdStrBuf RREF Buf2, bool fCopy = false) - : StdBuf(static_cast(Buf2), fCopy) - { } + : StdBuf(static_cast(Buf2), fCopy) + { } #ifdef HAVE_RVALUE_REF StdStrBuf(const StdStrBuf & Buf2, bool fCopy = true) - : StdBuf(Buf2, fCopy) - { } + : StdBuf(Buf2, fCopy) + { } #endif - // Set by constant data. References data by default, copies if specified. - explicit StdStrBuf(const char *pData, bool fCopy = false) - : StdBuf(pData, pData ? strlen(pData) + 1 : 0, fCopy) - { } + // Set by constant data. References data by default, copies if specified. + explicit StdStrBuf(const char *pData, bool fCopy = false) + : StdBuf(pData, pData ? strlen(pData) + 1 : 0, fCopy) + { } - // As previous constructor, but set length manually. - StdStrBuf(const char *pData, long int iLength) - : StdBuf(pData, pData ? iLength + 1 : 0, false) - { } - StdStrBuf(const char *pData, size_t iLength, bool fCopy = false) - : StdBuf(pData, pData ? iLength + 1 : 0, fCopy) - { } + // As previous constructor, but set length manually. + StdStrBuf(const char *pData, long int iLength) + : StdBuf(pData, pData ? iLength + 1 : 0, false) + { } + StdStrBuf(const char *pData, size_t iLength, bool fCopy = false) + : StdBuf(pData, pData ? iLength + 1 : 0, fCopy) + { } ALLOW_TEMP_TO_REF(StdStrBuf) public: - // *** Getters + // *** Getters bool isNull() const { return StdBuf::isNull(); } - const char *getData() const { return getBufPtr(*this); } - char *getMData() { return getMBufPtr(*this); } - size_t getSize() const { return StdBuf::getSize(); } - size_t getLength() const { return getSize() ? getSize() - 1 : 0; } - bool isRef() const { return StdBuf::isRef(); } + const char *getData() const { return getBufPtr(*this); } + char *getMData() { return getMBufPtr(*this); } + size_t getSize() const { return StdBuf::getSize(); } + size_t getLength() const { return getSize() ? getSize() - 1 : 0; } + bool isRef() const { return StdBuf::isRef(); } - const char *getPtr(size_t i) const { return getBufPtr(*this, i); } - char *getMPtr(size_t i) { return getMBufPtr(*this, i); } + const char *getPtr(size_t i) const { return getBufPtr(*this, i); } + char *getMPtr(size_t i) { return getMBufPtr(*this, i); } - // For convenience. Note that writing can't be allowed. - char operator [] (size_t i) const { return *getPtr(i); } + // For convenience. Note that writing can't be allowed. + char operator [] (size_t i) const { return *getPtr(i); } - // Analogous to StdBuf - void Ref(const char *pnData) { StdBuf::Ref(pnData, pnData ? strlen(pnData) + 1 : 0); } - void Ref(const char *pnData, size_t iLength) { assert((!pnData && !iLength) || strlen(pnData) == iLength); StdBuf::Ref(pnData, iLength + 1); } - void Take(char *pnData) { StdBuf::Take(pnData, pnData ? strlen(pnData) + 1 : 0); } - void Take(char *pnData, size_t iLength) { assert((!pnData && !iLength) || strlen(pnData) == iLength); StdBuf::Take(pnData, iLength + 1); } + // Analogous to StdBuf + void Ref(const char *pnData) { StdBuf::Ref(pnData, pnData ? strlen(pnData) + 1 : 0); } + void Ref(const char *pnData, size_t iLength) { assert((!pnData && !iLength) || strlen(pnData) == iLength); StdBuf::Ref(pnData, iLength + 1); } + void Take(char *pnData) { StdBuf::Take(pnData, pnData ? strlen(pnData) + 1 : 0); } + void Take(char *pnData, size_t iLength) { assert((!pnData && !iLength) || strlen(pnData) == iLength); StdBuf::Take(pnData, iLength + 1); } char *GrabPointer() { return reinterpret_cast(StdBuf::GrabPointer()); } - void Ref(const StdStrBuf &Buf2) { StdBuf::Ref(Buf2.getData(), Buf2.getSize()); } + void Ref(const StdStrBuf &Buf2) { StdBuf::Ref(Buf2.getData(), Buf2.getSize()); } StdStrBuf getRef() const { return StdStrBuf(getData(), getLength()); } void Take(StdStrBuf RREF Buf2) { StdBuf::Take(std::move(Buf2)); } - void Clear() { StdBuf::Clear(); } - void Copy() { StdBuf::Copy(); } - void Copy(const char *pnData) { StdBuf::Copy(pnData, pnData ? strlen(pnData) + 1 : 0); } - void Copy(const StdStrBuf &Buf2) { StdBuf::Copy(Buf2); } + void Clear() { StdBuf::Clear(); } + void Copy() { StdBuf::Copy(); } + void Copy(const char *pnData) { StdBuf::Copy(pnData, pnData ? strlen(pnData) + 1 : 0); } + void Copy(const StdStrBuf &Buf2) { StdBuf::Copy(Buf2); } StdStrBuf Duplicate() const { StdStrBuf Buf; Buf.Copy(*this); return Buf; } void Move(size_t iFrom, size_t inSize, size_t iTo = 0) { StdBuf::Move(iFrom, inSize, iTo); } - // Byte-wise compare (will compare characters up to the length of the second string) - int Compare(const StdStrBuf &Buf2, size_t iAt = 0) const - { - assert(iAt <= getLength()); - return StdBuf::Compare(Buf2.getData(), Buf2.getLength(), iAt); - } - int Compare_(const char *pCData, size_t iAt = 0) const - { - StdStrBuf str(pCData); // GCC needs this, for some obscure reason - return Compare(str, iAt); - } - - // Grows the string to contain the specified number more/less characters. - // Note: Will set the terminator, but won't initialize - use Append* instead. - void Grow(size_t iGrow) - { - StdBuf::Grow(getSize() ? iGrow : iGrow + 1); - *getMPtr(getLength()) = '\0'; - } - void Shrink(size_t iShrink) - { - assert(iShrink <= getLength()); - StdBuf::Shrink(iShrink); - *getMPtr(getLength()) = '\0'; - } - void SetLength(size_t iLength) - { - if(iLength == getLength() && !isNull()) return; - if(iLength >= getLength()) - Grow(iLength - getLength()); - else - Shrink(getLength() - iLength); - } - - // Append string - void Append(const char *pnData, size_t iChars) - { - //assert(iChars <= strlen(pnData)); - Grow(iChars); - Write(pnData, iChars, iSize - iChars - 1); + // Byte-wise compare (will compare characters up to the length of the second string) + int Compare(const StdStrBuf &Buf2, size_t iAt = 0) const + { + assert(iAt <= getLength()); + return StdBuf::Compare(Buf2.getData(), Buf2.getLength(), iAt); + } + int Compare_(const char *pCData, size_t iAt = 0) const + { + StdStrBuf str(pCData); // GCC needs this, for some obscure reason + return Compare(str, iAt); } - void Append(const char *pnData) - { - Append(pnData, strlen(pnData)); - } - void Append(const StdStrBuf &Buf2) - { - Append(Buf2.getData(), Buf2.getLength()); - } - // Copy string - void Copy(const char *pnData, size_t iChars) - { - Clear(); - Append(pnData, iChars); - } + // Grows the string to contain the specified number more/less characters. + // Note: Will set the terminator, but won't initialize - use Append* instead. + void Grow(size_t iGrow) + { + StdBuf::Grow(getSize() ? iGrow : iGrow + 1); + *getMPtr(getLength()) = '\0'; + } + void Shrink(size_t iShrink) + { + assert(iShrink <= getLength()); + StdBuf::Shrink(iShrink); + *getMPtr(getLength()) = '\0'; + } + void SetLength(size_t iLength) + { + if(iLength == getLength() && !isNull()) return; + if(iLength >= getLength()) + Grow(iLength - getLength()); + else + Shrink(getLength() - iLength); + } - // * File support - bool LoadFromFile(const char *szFile); - bool SaveToFile(const char *szFile) const; + // Append string + void Append(const char *pnData, size_t iChars) + { + //assert(iChars <= strlen(pnData)); + Grow(iChars); + Write(pnData, iChars, iSize - iChars - 1); + } + void Append(const char *pnData) + { + Append(pnData, strlen(pnData)); + } + void Append(const StdStrBuf &Buf2) + { + Append(Buf2.getData(), Buf2.getLength()); + } - // * Operators + // Copy string + void Copy(const char *pnData, size_t iChars) + { + Clear(); + Append(pnData, iChars); + } - bool operator ! () const { return isNull(); } + // * File support + bool LoadFromFile(const char *szFile); + bool SaveToFile(const char *szFile) const; - StdStrBuf &operator += (const StdStrBuf &Buf2) { Append(Buf2); return *this; } - StdStrBuf &operator += (const char *szString) { Append(szString); return *this; } - StdStrBuf operator + (const StdStrBuf &Buf2) const { StdStrBuf Buf = getRef(); Buf.Append(Buf2); return Buf; } - StdStrBuf operator + (const char *szString) const { StdStrBuf Buf = getRef(); Buf.Append(szString); return Buf; } + // * Operators - bool operator == (const StdStrBuf &Buf2) const - { - return getLength() == Buf2.getLength() && !Compare(Buf2); - } - bool operator != (const StdStrBuf &Buf2) const { return !operator == (Buf2); } + bool operator ! () const { return isNull(); } - bool operator == (const char *szString) const { return StdStrBuf(szString) == *this; } - bool operator != (const char *szString) const { return ! operator == (szString); } + StdStrBuf &operator += (const StdStrBuf &Buf2) { Append(Buf2); return *this; } + StdStrBuf &operator += (const char *szString) { Append(szString); return *this; } + StdStrBuf operator + (const StdStrBuf &Buf2) const { StdStrBuf Buf = getRef(); Buf.Append(Buf2); return Buf; } + StdStrBuf operator + (const char *szString) const { StdStrBuf Buf = getRef(); Buf.Append(szString); return Buf; } - // Note this references the data. - StdStrBuf &operator = (const StdStrBuf &Buf2) { Ref(Buf2); return *this; } - StdStrBuf &operator = (const char *szString) { Ref(szString); return *this; } + bool operator == (const StdStrBuf &Buf2) const + { + return getLength() == Buf2.getLength() && !Compare(Buf2); + } + bool operator != (const StdStrBuf &Buf2) const { return !operator == (Buf2); } - // conversion to "bool" - operator const void *() const { return getData(); } + bool operator == (const char *szString) const { return StdStrBuf(szString) == *this; } + bool operator != (const char *szString) const { return ! operator == (szString); } + + // Note this references the data. + StdStrBuf &operator = (const StdStrBuf &Buf2) { Ref(Buf2); return *this; } + StdStrBuf &operator = (const char *szString) { Ref(szString); return *this; } + + // conversion to "bool" + operator const void *() const { return getData(); } // less-than operation for map inline bool operator <(const StdStrBuf &v2) const @@ -548,42 +548,42 @@ public: return iLen < iLen2; } - // * String specific + // * String specific - void AppendChars(char cChar, size_t iCnt) - { - Grow(iCnt); - for(size_t i = getLength() - iCnt; i < getLength(); i++) - *getMPtr(i) = cChar; - } - void AppendChar(char cChar) - { - AppendChars(cChar, 1); - } - void InsertChar(char cChar, size_t insert_before) - { + void AppendChars(char cChar, size_t iCnt) + { + Grow(iCnt); + for(size_t i = getLength() - iCnt; i < getLength(); i++) + *getMPtr(i) = cChar; + } + void AppendChar(char cChar) + { + AppendChars(cChar, 1); + } + void InsertChar(char cChar, size_t insert_before) + { assert(insert_before <= getLength()); - Grow(1); - for(size_t i = getLength()-1; i > insert_before; --i) - *getMPtr(i) = *getPtr(i-1); + Grow(1); + for(size_t i = getLength()-1; i > insert_before; --i) + *getMPtr(i) = *getPtr(i-1); *getMPtr(insert_before) = cChar; - } + } - // Append data until given character (or string end) occurs. - void AppendUntil(const char *szString, char cUntil) - { - const char *pPos = strchr(szString, cUntil); - if(pPos) - Append(szString, pPos - szString); - else - Append(szString); - } - // See above - void CopyUntil(const char *szString, char cUntil) - { - Clear(); - AppendUntil(szString, cUntil); - } + // Append data until given character (or string end) occurs. + void AppendUntil(const char *szString, char cUntil) + { + const char *pPos = strchr(szString, cUntil); + if(pPos) + Append(szString, pPos - szString); + else + Append(szString); + } + // See above + void CopyUntil(const char *szString, char cUntil) + { + Clear(); + AppendUntil(szString, cUntil); + } // cut end after given char into another string. Return whether char was found at all bool SplitAtChar(char cSplit, StdStrBuf *psSplit) { @@ -596,19 +596,19 @@ public: return true; } - void Format(const char *szFmt, ...) GNUC_FORMAT_ATTRIBUTE_O; - void FormatV(const char *szFmt, va_list args); - void AppendFormat(const char *szFmt, ...) GNUC_FORMAT_ATTRIBUTE_O; - void AppendFormatV(const char *szFmt, va_list args); + void Format(const char *szFmt, ...) GNUC_FORMAT_ATTRIBUTE_O; + void FormatV(const char *szFmt, va_list args); + void AppendFormat(const char *szFmt, ...) GNUC_FORMAT_ATTRIBUTE_O; + void AppendFormatV(const char *szFmt, va_list args); - StdStrBuf copyPart(size_t iStart, size_t inSize) const - { - assert(iStart + inSize <= iSize); + StdStrBuf copyPart(size_t iStart, size_t inSize) const + { + assert(iStart + inSize <= iSize); if (!inSize) return StdStrBuf(); StdStrBuf sResult; sResult.Copy(getPtr(iStart), inSize); return sResult; - } + } // replace all occurences of one string with another. Return number of replacements. int Replace(const char *szOld, const char *szNew, size_t iStartSearch=0); @@ -643,9 +643,9 @@ public: bool TrimSpaces(); // kill spaces at beginning and end. Return if changed. - // * Compiling + // * Compiling - void CompileFunc(class StdCompiler *pComp, int iRawType = 0); + void CompileFunc(class StdCompiler *pComp, int iRawType = 0); }; @@ -654,25 +654,25 @@ class StdCopyStrBuf : public StdStrBuf { public: - StdCopyStrBuf() - { } + StdCopyStrBuf() + { } - explicit StdCopyStrBuf(const StdStrBuf &Buf2, bool fCopy = true) - : StdStrBuf(Buf2.getRef(), fCopy) - { } + explicit StdCopyStrBuf(const StdStrBuf &Buf2, bool fCopy = true) + : StdStrBuf(Buf2.getRef(), fCopy) + { } - StdCopyStrBuf(const StdCopyStrBuf &Buf2, bool fCopy = true) - : StdStrBuf(Buf2.getRef(), fCopy) - { } + StdCopyStrBuf(const StdCopyStrBuf &Buf2, bool fCopy = true) + : StdStrBuf(Buf2.getRef(), fCopy) + { } - // Set by constant data. Copies data if desired. - explicit StdCopyStrBuf(const char *pData, bool fCopy = true) - : StdStrBuf(pData, fCopy) - { } + // Set by constant data. Copies data if desired. + explicit StdCopyStrBuf(const char *pData, bool fCopy = true) + : StdStrBuf(pData, fCopy) + { } - StdCopyStrBuf &operator = (const StdStrBuf &Buf2) { Copy(Buf2); return *this; } - StdCopyStrBuf &operator = (const StdCopyStrBuf &Buf2) { Copy(Buf2); return *this; } - StdCopyStrBuf &operator = (const char *szString) { Copy(szString); return *this; } + StdCopyStrBuf &operator = (const StdStrBuf &Buf2) { Copy(Buf2); return *this; } + StdCopyStrBuf &operator = (const StdCopyStrBuf &Buf2) { Copy(Buf2); return *this; } + StdCopyStrBuf &operator = (const char *szString) { Copy(szString); return *this; } }; @@ -680,9 +680,9 @@ public: // const char* + StdStrBuf inline StdStrBuf operator + (const char* szString, const StdStrBuf& Buf2) { - StdStrBuf Buf(szString); - Buf.Append(Buf2); - return Buf; + StdStrBuf Buf(szString); + Buf.Append(Buf2); + return Buf; } #endif diff --git a/src/lib/StdCompiler.cpp b/src/lib/StdCompiler.cpp index 047e964bb..08572f5af 100644 --- a/src/lib/StdCompiler.cpp +++ b/src/lib/StdCompiler.cpp @@ -30,32 +30,32 @@ void StdCompiler::Warn(const char *szWarning, ...) { - // Got warning callback? - if(!pWarnCB) return; - // Format message - va_list args; va_start(args, szWarning); - StdStrBuf Msg; Msg.FormatV(szWarning, args); - // do callback - (*pWarnCB)(pWarnData, getPosition().getData(), Msg.getData()); + // Got warning callback? + if(!pWarnCB) return; + // Format message + va_list args; va_start(args, szWarning); + StdStrBuf Msg; Msg.FormatV(szWarning, args); + // do callback + (*pWarnCB)(pWarnData, getPosition().getData(), Msg.getData()); } char StdCompiler::SeperatorToChar(Sep eSep) { switch(eSep) { - case SEP_SEP: return ','; - case SEP_SEP2: return ';'; - case SEP_SET: return '='; - case SEP_PART: return '.'; - case SEP_PART2: return ':'; + case SEP_SEP: return ','; + case SEP_SEP2: return ';'; + case SEP_SET: return '='; + case SEP_PART: return '.'; + case SEP_PART2: return ':'; case SEP_PLUS: return '+'; case SEP_START: return '('; case SEP_END: return ')'; case SEP_START2: return '['; case SEP_END2: return ']'; case SEP_VLINE: return '|'; - case SEP_DOLLAR: return '$'; - default: assert(!"Unhandled Seperator value"); + case SEP_DOLLAR: return '$'; + default: assert(!"Unhandled Seperator value"); } return ' '; } @@ -72,18 +72,18 @@ void StdCompilerBinWrite::Boolean(bool &rBool) { WriteValue(rBool); } void StdCompilerBinWrite::Character(char &rChar) { WriteValue(rChar); } void StdCompilerBinWrite::String(char *szString, size_t iMaxLength, RawCompileType eType) { - WriteData(szString, strlen(szString) + 1); + WriteData(szString, strlen(szString) + 1); } void StdCompilerBinWrite::String(char **pszString, RawCompileType eType) { - if(*pszString) - WriteData(*pszString, strlen(*pszString) + 1); - else - WriteValue('\0'); + if(*pszString) + WriteData(*pszString, strlen(*pszString) + 1); + else + WriteValue('\0'); } template - void StdCompilerBinWrite::WriteValue(const T &rValue) + void StdCompilerBinWrite::WriteValue(const T &rValue) { // Copy data if(fSecondPass) @@ -94,28 +94,28 @@ template void StdCompilerBinWrite::WriteData(const void *pData, size_t iSize) { // Copy data - if(fSecondPass) + if(fSecondPass) Buf.Write(pData, iSize, iPos); - iPos += iSize; + iPos += iSize; } void StdCompilerBinWrite::Raw(void *pData, size_t iSize, RawCompileType eType) { // Copy data - if(fSecondPass) + if(fSecondPass) Buf.Write(pData, iSize, iPos); - iPos += iSize; + iPos += iSize; } void StdCompilerBinWrite::Begin() { - fSecondPass = false; iPos = 0; + fSecondPass = false; iPos = 0; } void StdCompilerBinWrite::BeginSecond() { - Buf.New(iPos); - fSecondPass = true; iPos = 0; + Buf.New(iPos); + fSecondPass = true; iPos = 0; } // *** StdCompilerBinRead @@ -159,11 +159,11 @@ void StdCompilerBinRead::String(char **pszString, RawCompileType eType) void StdCompilerBinRead::Raw(void *pData, size_t iSize, RawCompileType eType) { - if(iPos + iSize > Buf.getSize()) + if(iPos + iSize > Buf.getSize()) { excEOF(); return; } - // Copy data - memcpy(pData, Buf.getPtr(iPos), iSize); - iPos += iSize; + // Copy data + memcpy(pData, Buf.getPtr(iPos), iSize); + iPos += iSize; } StdStrBuf StdCompilerBinRead::getPosition() const @@ -191,275 +191,275 @@ void StdCompilerBinRead::Begin() bool StdCompilerINIWrite::Name(const char *szName) { - // Sub-Namesections exist, so it's a section. Write name if not already done so. - if(fPutName) PutName(true); - // Push struct - Naming *pnNaming = new Naming; - pnNaming->Name.Copy(szName); - pnNaming->Parent = pNaming; - pNaming = pnNaming; - iDepth++; - // Done - fPutName = true; fInSection = false; - return true; + // Sub-Namesections exist, so it's a section. Write name if not already done so. + if(fPutName) PutName(true); + // Push struct + Naming *pnNaming = new Naming; + pnNaming->Name.Copy(szName); + pnNaming->Parent = pNaming; + pNaming = pnNaming; + iDepth++; + // Done + fPutName = true; fInSection = false; + return true; } void StdCompilerINIWrite::NameEnd(bool fBreak) { - // Nothing written? Do not put name. - //if(fPutName) PutName(false); + // Nothing written? Do not put name. + //if(fPutName) PutName(false); - // Append newline + // Append newline if(!fPutName && !fInSection) Buf.Append("\r\n"); fPutName = false; // Note this makes it impossible to distinguish an empty name section from // a non-existing name section. - // Pop - assert(iDepth); - Naming *poNaming = pNaming; - pNaming = poNaming->Parent; - delete poNaming; - iDepth--; - // We're inside a section now - fInSection = true; + // Pop + assert(iDepth); + Naming *poNaming = pNaming; + pNaming = poNaming->Parent; + delete poNaming; + iDepth--; + // We're inside a section now + fInSection = true; } bool StdCompilerINIWrite::Seperator(Sep eSep) { - if(fInSection) - { - // Re-put section name - PutName(true); - } - else + if(fInSection) + { + // Re-put section name + PutName(true); + } + else { PrepareForValue(); Buf.AppendChar(SeperatorToChar(eSep)); } - return true; + return true; } void StdCompilerINIWrite::DWord(int32_t &rInt) { - PrepareForValue(); - Buf.AppendFormat("%d", rInt); + PrepareForValue(); + Buf.AppendFormat("%d", rInt); } void StdCompilerINIWrite::DWord(uint32_t &rInt) { - PrepareForValue(); - Buf.AppendFormat("%u", rInt); + PrepareForValue(); + Buf.AppendFormat("%u", rInt); } void StdCompilerINIWrite::Word(int16_t &rInt) { - PrepareForValue(); - Buf.AppendFormat("%d", rInt); + PrepareForValue(); + Buf.AppendFormat("%d", rInt); } void StdCompilerINIWrite::Word(uint16_t &rInt) { - PrepareForValue(); - Buf.AppendFormat("%u", rInt); + PrepareForValue(); + Buf.AppendFormat("%u", rInt); } void StdCompilerINIWrite::Byte(int8_t &rByte) { - PrepareForValue(); - Buf.AppendFormat("%d", rByte); + PrepareForValue(); + Buf.AppendFormat("%d", rByte); } void StdCompilerINIWrite::Byte(uint8_t &rInt) { - PrepareForValue(); - Buf.AppendFormat("%u", rInt); + PrepareForValue(); + Buf.AppendFormat("%u", rInt); } void StdCompilerINIWrite::Boolean(bool &rBool) { - PrepareForValue(); - Buf.Append(rBool ? "true" : "false"); + PrepareForValue(); + Buf.Append(rBool ? "true" : "false"); } void StdCompilerINIWrite::Character(char &rChar) { - PrepareForValue(); - Buf.AppendFormat("%c", rChar); + PrepareForValue(); + Buf.AppendFormat("%c", rChar); } void StdCompilerINIWrite::String(char *szString, size_t iMaxLength, RawCompileType eType) { - PrepareForValue(); - switch(eType) - { - case RCT_Escaped: - WriteEscaped(szString, szString + strlen(szString)); - break; - case RCT_All: - case RCT_Idtf: + PrepareForValue(); + switch(eType) + { + case RCT_Escaped: + WriteEscaped(szString, szString + strlen(szString)); + break; + case RCT_All: + case RCT_Idtf: case RCT_IdtfAllowEmpty: - case RCT_ID: - Buf.Append(szString); - } + case RCT_ID: + Buf.Append(szString); + } } void StdCompilerINIWrite::String(char **pszString, RawCompileType eType) { - char cNull = '\0'; - String(*pszString ? *pszString : &cNull, 0, eType); + char cNull = '\0'; + String(*pszString ? *pszString : &cNull, 0, eType); } void StdCompilerINIWrite::Raw(void *pData, size_t iSize, RawCompileType eType) { - switch(eType) - { - case RCT_Escaped: - WriteEscaped(reinterpret_cast(pData), reinterpret_cast(pData) + iSize); - break; - case RCT_All: - case RCT_Idtf: + switch(eType) + { + case RCT_Escaped: + WriteEscaped(reinterpret_cast(pData), reinterpret_cast(pData) + iSize); + break; + case RCT_All: + case RCT_Idtf: case RCT_IdtfAllowEmpty: - case RCT_ID: - Buf.Append(reinterpret_cast(pData), iSize); - } + case RCT_ID: + Buf.Append(reinterpret_cast(pData), iSize); + } } void StdCompilerINIWrite::Begin() { - pNaming = NULL; - fPutName = false; - iDepth = 0; - fInSection = false; - Buf.Clear(); + pNaming = NULL; + fPutName = false; + iDepth = 0; + fInSection = false; + Buf.Clear(); } void StdCompilerINIWrite::End() { - // Ensure all namings were closed properly - assert(!iDepth); + // Ensure all namings were closed properly + assert(!iDepth); } void StdCompilerINIWrite::PrepareForValue() { - // Put name (value-type), if not already done so - if(fPutName) PutName(false); - // No data allowed inside of sections - assert(!fInSection); - // No values allowed on top-level - must be contained in at least one section - assert(iDepth > 1); + // Put name (value-type), if not already done so + if(fPutName) PutName(false); + // No data allowed inside of sections + assert(!fInSection); + // No values allowed on top-level - must be contained in at least one section + assert(iDepth > 1); } void StdCompilerINIWrite::WriteEscaped(const char *szString, const char *pEnd) { - Buf.AppendChar('"'); - // Try to write chunks as huge as possible of "normal" chars. - // Note this excludes '\0', so the standard Append() can be used. - const char *pStart, *pPos; pStart = pPos = szString; - bool fLastNumEscape = false; // catch "\1""1", which must become "\1\61" - for(; pPos < pEnd; pPos++) - if(!isprint((unsigned char)(unsigned char) *pPos) || *pPos == '\\' || *pPos == '"' || (fLastNumEscape && isdigit((unsigned char)*pPos))) - { - // Write everything up to this point - if(pPos - pStart) Buf.Append(pStart, pPos - pStart); - // Escape - fLastNumEscape = false; - switch(*pPos) - { - case '\a': Buf.Append("\\a"); break; - case '\b': Buf.Append("\\b"); break; - case '\f': Buf.Append("\\f"); break; - case '\n': Buf.Append("\\n"); break; - case '\r': Buf.Append("\\r"); break; - case '\t': Buf.Append("\\t"); break; - case '\v': Buf.Append("\\v"); break; - case '\"': Buf.Append("\\\""); break; - case '\\': Buf.Append("\\\\"); break; - default: - Buf.AppendFormat("\\%o", *reinterpret_cast(pPos)); - fLastNumEscape = true; - } - // Set pointer - pStart = pPos + 1; - } - else - fLastNumEscape = false; - // Write the rest - if(pEnd - pStart) Buf.Append(pStart, pEnd - pStart); - Buf.AppendChar('"'); + Buf.AppendChar('"'); + // Try to write chunks as huge as possible of "normal" chars. + // Note this excludes '\0', so the standard Append() can be used. + const char *pStart, *pPos; pStart = pPos = szString; + bool fLastNumEscape = false; // catch "\1""1", which must become "\1\61" + for(; pPos < pEnd; pPos++) + if(!isprint((unsigned char)(unsigned char) *pPos) || *pPos == '\\' || *pPos == '"' || (fLastNumEscape && isdigit((unsigned char)*pPos))) + { + // Write everything up to this point + if(pPos - pStart) Buf.Append(pStart, pPos - pStart); + // Escape + fLastNumEscape = false; + switch(*pPos) + { + case '\a': Buf.Append("\\a"); break; + case '\b': Buf.Append("\\b"); break; + case '\f': Buf.Append("\\f"); break; + case '\n': Buf.Append("\\n"); break; + case '\r': Buf.Append("\\r"); break; + case '\t': Buf.Append("\\t"); break; + case '\v': Buf.Append("\\v"); break; + case '\"': Buf.Append("\\\""); break; + case '\\': Buf.Append("\\\\"); break; + default: + Buf.AppendFormat("\\%o", *reinterpret_cast(pPos)); + fLastNumEscape = true; + } + // Set pointer + pStart = pPos + 1; + } + else + fLastNumEscape = false; + // Write the rest + if(pEnd - pStart) Buf.Append(pStart, pEnd - pStart); + Buf.AppendChar('"'); } void StdCompilerINIWrite::WriteIndent(bool fSection) { - // Do not indent level 1 (level 0 values aren't allowed - see above) - int iIndent = iDepth - 1; - // Sections are indented more, even though they belong to this level - if(!fSection) iIndent--; - // Do indention - if(iIndent <= 0) return; - Buf.AppendChars(' ', iIndent * 2); + // Do not indent level 1 (level 0 values aren't allowed - see above) + int iIndent = iDepth - 1; + // Sections are indented more, even though they belong to this level + if(!fSection) iIndent--; + // Do indention + if(iIndent <= 0) return; + Buf.AppendChars(' ', iIndent * 2); } void StdCompilerINIWrite::PutName(bool fSection) { - if(fSection && Buf.getLength()) + if(fSection && Buf.getLength()) Buf.Append("\r\n"); - WriteIndent(fSection); - // Put name - if(fSection) - Buf.AppendFormat("[%s]\r\n", pNaming->Name.getData()); - else - Buf.AppendFormat("%s=", pNaming->Name.getData()); - // Set flag - fPutName = false; + WriteIndent(fSection); + // Put name + if(fSection) + Buf.AppendFormat("[%s]\r\n", pNaming->Name.getData()); + else + Buf.AppendFormat("%s=", pNaming->Name.getData()); + // Set flag + fPutName = false; } // *** StdCompilerINIRead StdCompilerINIRead::StdCompilerINIRead() - : pNameRoot(NULL), iDepth(0), iRealDepth(0) + : pNameRoot(NULL), iDepth(0), iRealDepth(0) { } StdCompilerINIRead::~StdCompilerINIRead() { - FreeNameTree(); + FreeNameTree(); } // Naming bool StdCompilerINIRead::Name(const char *szName) { - // Increase depth - iDepth++; - // Parent category virtual? - if(iDepth - 1 > iRealDepth) - return false; - // Name must be alphanumerical and non-empty (force it) - if(!isalpha((unsigned char)*szName)) - { assert(false); return false; } - for(const char *p = szName + 1; *p; p++) - // C4Update needs Name**... - if(!isalnum((unsigned char)*p) && *p != ' ' && *p != '_' && *p != '*') - { assert(false); return false; } - // Search name - NameNode *pNode; - for(pNode = pName->FirstChild; pNode; pNode = pNode->NextChild) - if(pNode->Pos && pNode->Name == szName) - break; - // Not found? - if(!pNode) + // Increase depth + iDepth++; + // Parent category virtual? + if(iDepth - 1 > iRealDepth) + return false; + // Name must be alphanumerical and non-empty (force it) + if(!isalpha((unsigned char)*szName)) + { assert(false); return false; } + for(const char *p = szName + 1; *p; p++) + // C4Update needs Name**... + if(!isalnum((unsigned char)*p) && *p != ' ' && *p != '_' && *p != '*') + { assert(false); return false; } + // Search name + NameNode *pNode; + for(pNode = pName->FirstChild; pNode; pNode = pNode->NextChild) + if(pNode->Pos && pNode->Name == szName) + break; + // Not found? + if(!pNode) { NotFoundName = szName; return false; } - // Save tree position, indicate success - pName = pNode; - pPos = pName->Pos; + // Save tree position, indicate success + pName = pNode; + pPos = pName->Pos; pReenter = NULL; - iRealDepth++; - return true; + iRealDepth++; + return true; } void StdCompilerINIRead::NameEnd(bool fBreak) { - assert(iDepth > 0); - if(iRealDepth == iDepth) - { + assert(iDepth > 0); + if(iRealDepth == iDepth) + { // Remove childs for(NameNode *pNode = pName->FirstChild, *pNext; pNode; pNode = pNext) { @@ -470,26 +470,26 @@ void StdCompilerINIRead::NameEnd(bool fBreak) pNext = pNode->NextChild; delete pNode; } - // Remove name so it won't be found again + // Remove name so it won't be found again NameNode *pParent = pName->Parent; (pName->PrevChild ? pName->PrevChild->NextChild : pParent->FirstChild) = pName->NextChild; (pName->NextChild ? pName->NextChild->PrevChild : pParent->LastChild) = pName->PrevChild; delete pName; - // Go up - pName = pParent; - iRealDepth--; - } - // Decrease depth - iDepth--; - // This is the middle of nowhere - pPos = NULL; pReenter = NULL; + // Go up + pName = pParent; + iRealDepth--; + } + // Decrease depth + iDepth--; + // This is the middle of nowhere + pPos = NULL; pReenter = NULL; } bool StdCompilerINIRead::FollowName(const char *szName) { // Current naming virtual? - if(iDepth > iRealDepth) - return false; + if(iDepth > iRealDepth) + return false; // Next section must be the one if(!pName->NextChild || pName->NextChild->Name != szName) { @@ -510,32 +510,32 @@ bool StdCompilerINIRead::FollowName(const char *szName) // Seperators bool StdCompilerINIRead::Seperator(Sep eSep) { - if(iDepth > iRealDepth) return false; - // In section? - if(pName->Section) - { - // Store current name, search another section with the same name - StdStrBuf CurrName = pName->Name; - NameEnd(); - return Name(CurrName.getData()); - } + if(iDepth > iRealDepth) return false; + // In section? + if(pName->Section) + { + // Store current name, search another section with the same name + StdStrBuf CurrName = pName->Name; + NameEnd(); + return Name(CurrName.getData()); + } // Position saved back from seperator mismatch? - if(pReenter) { pPos = pReenter; pReenter = NULL; } + if(pReenter) { pPos = pReenter; pReenter = NULL; } // Nothing to read? if(!pPos) return false; - // Read (while skipping over whitespace) - SkipWhitespace(); + // Read (while skipping over whitespace) + SkipWhitespace(); // Seperator mismatch? Let all read attempts fail until the correct seperator is found or the naming ends. - if(*pPos != SeperatorToChar(eSep)) { pReenter = pPos; pPos = NULL; return false; } - // Go over seperator, success - pPos++; - return true; + if(*pPos != SeperatorToChar(eSep)) { pReenter = pPos; pPos = NULL; return false; } + // Go over seperator, success + pPos++; + return true; } void StdCompilerINIRead::NoSeperator() { // Position saved back from seperator mismatch? - if(pReenter) { pPos = pReenter; pReenter = NULL; } + if(pReenter) { pPos = pReenter; pReenter = NULL; } } int StdCompilerINIRead::NameCount(const char *szName) @@ -544,102 +544,102 @@ int StdCompilerINIRead::NameCount(const char *szName) if (iDepth > iRealDepth || !pName) return 0; // count within current name int iCount = 0; - NameNode *pNode; - for(pNode = pName->FirstChild; pNode; pNode = pNode->NextChild) + NameNode *pNode; + for(pNode = pName->FirstChild; pNode; pNode = pNode->NextChild) // if no name is given, all valid subsections are counted - if(pNode->Pos && (!szName || pNode->Name == szName)) - ++iCount; + if(pNode->Pos && (!szName || pNode->Name == szName)) + ++iCount; return iCount; } // Various data readers void StdCompilerINIRead::DWord(int32_t &rInt) { - rInt = ReadNum(); + rInt = ReadNum(); } void StdCompilerINIRead::DWord(uint32_t &rInt) { - rInt = ReadUNum(); + rInt = ReadUNum(); } void StdCompilerINIRead::Word(int16_t &rShort) { - const int MIN = -(1 << 15), MAX = (1 << 15) - 1; - int iNum = ReadNum(); - if(iNum < MIN || iNum > MAX) - Warn("number out of range (%d to %d): %d ", MIN, MAX, iNum); - rShort = BoundBy(iNum, MIN, MAX); + const int MIN = -(1 << 15), MAX = (1 << 15) - 1; + int iNum = ReadNum(); + if(iNum < MIN || iNum > MAX) + Warn("number out of range (%d to %d): %d ", MIN, MAX, iNum); + rShort = BoundBy(iNum, MIN, MAX); } void StdCompilerINIRead::Word(uint16_t &rShort) { - const unsigned int MIN = 0, MAX = (1 << 15) - 1; - unsigned int iNum = ReadUNum(); - if(iNum > MAX) - Warn("number out of range (%u to %u): %u ", MIN, MAX, iNum); - rShort = BoundBy(iNum, MIN, MAX); + const unsigned int MIN = 0, MAX = (1 << 15) - 1; + unsigned int iNum = ReadUNum(); + if(iNum > MAX) + Warn("number out of range (%u to %u): %u ", MIN, MAX, iNum); + rShort = BoundBy(iNum, MIN, MAX); } void StdCompilerINIRead::Byte(int8_t &rByte) { - const int MIN = -(1 << 7), MAX = (1 << 7) - 1; - int iNum = ReadNum(); - if(iNum < MIN || iNum > MAX) - Warn("number out of range (%d to %d): %d ", MIN, MAX, iNum); - rByte = BoundBy(iNum, MIN, MAX); + const int MIN = -(1 << 7), MAX = (1 << 7) - 1; + int iNum = ReadNum(); + if(iNum < MIN || iNum > MAX) + Warn("number out of range (%d to %d): %d ", MIN, MAX, iNum); + rByte = BoundBy(iNum, MIN, MAX); } void StdCompilerINIRead::Byte(uint8_t &rByte) { - const unsigned int MIN = 0, MAX = (1 << 8) - 1; - unsigned int iNum = ReadUNum(); - if(iNum > MAX) - Warn("number out of range (%u to %u): %u ", MIN, MAX, iNum); - rByte = BoundBy(iNum, MIN, MAX); + const unsigned int MIN = 0, MAX = (1 << 8) - 1; + unsigned int iNum = ReadUNum(); + if(iNum > MAX) + Warn("number out of range (%u to %u): %u ", MIN, MAX, iNum); + rByte = BoundBy(iNum, MIN, MAX); } void StdCompilerINIRead::Boolean(bool &rBool) { - if(!pPos) { notFound("Boolean"); return; } - if(*pPos == '1' && !isdigit((unsigned char)*(pPos+1))) - { rBool = true; pPos ++; } - else if(*pPos == '0' && !isdigit((unsigned char)*(pPos+1))) - { rBool = false; pPos ++; } - else if(SEqual2(pPos, "true")) - { rBool = true; pPos += 4; } - else if(SEqual2(pPos, "false")) - { rBool = false; pPos += 5; } - else + if(!pPos) { notFound("Boolean"); return; } + if(*pPos == '1' && !isdigit((unsigned char)*(pPos+1))) + { rBool = true; pPos ++; } + else if(*pPos == '0' && !isdigit((unsigned char)*(pPos+1))) + { rBool = false; pPos ++; } + else if(SEqual2(pPos, "true")) + { rBool = true; pPos += 4; } + else if(SEqual2(pPos, "false")) + { rBool = false; pPos += 5; } + else { notFound("Boolean"); return; } } void StdCompilerINIRead::Character(char &rChar) { - if(!pPos || !isalpha((unsigned char)*pPos)) + if(!pPos || !isalpha((unsigned char)*pPos)) { notFound("Character"); return; } - rChar = *pPos++; + rChar = *pPos++; } void StdCompilerINIRead::String(char *szString, size_t iMaxLength, RawCompileType eType) { - // Read data - StdBuf Buf = ReadString(iMaxLength, eType, true); - // Copy - SCopy(getBufPtr(Buf), szString, iMaxLength); + // Read data + StdBuf Buf = ReadString(iMaxLength, eType, true); + // Copy + SCopy(getBufPtr(Buf), szString, iMaxLength); } void StdCompilerINIRead::String(char **pszString, RawCompileType eType) { - // For Backwards compatibility: Escaped strings default to normal strings if no escaped string is given + // For Backwards compatibility: Escaped strings default to normal strings if no escaped string is given if (eType == RCT_Escaped && pPos && *pPos!='"') eType = RCT_All; - // Get length - size_t iLength = GetStringLength(eType); - // Read data - StdBuf Buf = ReadString(iLength, eType, true); - // Set - *pszString = reinterpret_cast(Buf.GrabPointer()); + // Get length + size_t iLength = GetStringLength(eType); + // Read data + StdBuf Buf = ReadString(iLength, eType, true); + // Set + *pszString = reinterpret_cast(Buf.GrabPointer()); } void StdCompilerINIRead::Raw(void *pData, size_t iSize, RawCompileType eType) { - // Read data - StdBuf Buf = ReadString(iSize, eType, false); - // Correct size? - if(Buf.getSize() != iSize) - Warn("got %u bytes raw data, but %u bytes expected!", Buf.getSize(), iSize); - // Copy - MemCopy(Buf.getData(), pData, iSize); + // Read data + StdBuf Buf = ReadString(iSize, eType, false); + // Correct size? + if(Buf.getSize() != iSize) + Warn("got %u bytes raw data, but %u bytes expected!", Buf.getSize(), iSize); + // Copy + MemCopy(Buf.getData(), pData, iSize); } StdStrBuf StdCompilerINIRead::getPosition() const @@ -656,305 +656,305 @@ StdStrBuf StdCompilerINIRead::getPosition() const void StdCompilerINIRead::Begin() { - // Already running? This may happen if someone confuses Compile with Value. - assert(!iDepth && !iRealDepth && !pNameRoot); - // Create tree - CreateNameTree(); - // Start must be inside a section - iDepth = iRealDepth = 0; - pPos = NULL; pReenter = NULL; + // Already running? This may happen if someone confuses Compile with Value. + assert(!iDepth && !iRealDepth && !pNameRoot); + // Create tree + CreateNameTree(); + // Start must be inside a section + iDepth = iRealDepth = 0; + pPos = NULL; pReenter = NULL; } void StdCompilerINIRead::End() { - assert(!iDepth && !iRealDepth); - FreeNameTree(); + assert(!iDepth && !iRealDepth); + FreeNameTree(); } void StdCompilerINIRead::CreateNameTree() { FreeNameTree(); - // Create root node - pName = pNameRoot = new NameNode(); + // Create root node + pName = pNameRoot = new NameNode(); // No input? Stop if(!Buf) return; - // Start scanning - pPos = Buf.getPtr(0); - while(*pPos) - { - // Go over whitespace - int iIndent = 0; - while(*pPos == ' ' || *pPos == '\t') - { pPos++; iIndent++; } - // Name/Section? - bool fSection = *pPos == '[' && isalpha((unsigned char)*(pPos+1)); - if(fSection || isalpha((unsigned char)*pPos)) - { - // Treat values as if they had more indention - // (so they become children of sections on the same level) - if(!fSection) iIndent++; else pPos++; - // Go up in tree structure if there is less indention - while(pName->Parent && pName->Indent >= iIndent) - pName = pName->Parent; - // Copy name - StdStrBuf Name; - while(isalnum((unsigned char)*pPos) || *pPos == ' ' || *pPos == '_') - Name.AppendChar(*pPos++); - while(*pPos == ' ' || *pPos == '\t') pPos++; - if( *pPos != (fSection ? ']' : '=') ) - // Warn, ignore - Warn(isprint((unsigned char)*pPos) ? "Unexpected character ('%c'): %s ignored" : "Unexpected character ('0x%02x'): %s ignored", unsigned(*pPos), fSection ? "section" : "value"); - else - { - pPos++; - // Create new node + // Start scanning + pPos = Buf.getPtr(0); + while(*pPos) + { + // Go over whitespace + int iIndent = 0; + while(*pPos == ' ' || *pPos == '\t') + { pPos++; iIndent++; } + // Name/Section? + bool fSection = *pPos == '[' && isalpha((unsigned char)*(pPos+1)); + if(fSection || isalpha((unsigned char)*pPos)) + { + // Treat values as if they had more indention + // (so they become children of sections on the same level) + if(!fSection) iIndent++; else pPos++; + // Go up in tree structure if there is less indention + while(pName->Parent && pName->Indent >= iIndent) + pName = pName->Parent; + // Copy name + StdStrBuf Name; + while(isalnum((unsigned char)*pPos) || *pPos == ' ' || *pPos == '_') + Name.AppendChar(*pPos++); + while(*pPos == ' ' || *pPos == '\t') pPos++; + if( *pPos != (fSection ? ']' : '=') ) + // Warn, ignore + Warn(isprint((unsigned char)*pPos) ? "Unexpected character ('%c'): %s ignored" : "Unexpected character ('0x%02x'): %s ignored", unsigned(*pPos), fSection ? "section" : "value"); + else + { + pPos++; + // Create new node NameNode *pPrev = pName->LastChild; - pName = - pName->LastChild = - (pName->LastChild ? pName->LastChild->NextChild : pName->FirstChild) = - new NameNode(pName); + pName = + pName->LastChild = + (pName->LastChild ? pName->LastChild->NextChild : pName->FirstChild) = + new NameNode(pName); pName->PrevChild = pPrev; pName->Name.Take(std::move(Name)); - pName->Pos = pPos; - pName->Indent = iIndent; - pName->Section = fSection; - // Values don't have children (even if the indention looks like it) - if(!fSection) - pName = pName->Parent; - } - } - // Skip line - while(*pPos && (*pPos != '\n' && *pPos != '\r')) - pPos++; - while(*pPos == '\n' || *pPos == '\r') - pPos++; - } - // Set pointer back - pName = pNameRoot; + pName->Pos = pPos; + pName->Indent = iIndent; + pName->Section = fSection; + // Values don't have children (even if the indention looks like it) + if(!fSection) + pName = pName->Parent; + } + } + // Skip line + while(*pPos && (*pPos != '\n' && *pPos != '\r')) + pPos++; + while(*pPos == '\n' || *pPos == '\r') + pPos++; + } + // Set pointer back + pName = pNameRoot; } void StdCompilerINIRead::FreeNameTree() { - // free all nodes + // free all nodes FreeNameNode(pNameRoot); - pName = pNameRoot = NULL; + pName = pNameRoot = NULL; } void StdCompilerINIRead::FreeNameNode(NameNode *pDelNode) { NameNode *pNode = pDelNode; - while(pNode) - { - if(pNode->FirstChild) - pNode = pNode->FirstChild; - else - { - NameNode *pDelete = pNode; + while(pNode) + { + if(pNode->FirstChild) + pNode = pNode->FirstChild; + else + { + NameNode *pDelete = pNode; if (pDelete == pDelNode) { delete pDelete; break; } - if(pNode->NextChild) + if(pNode->NextChild) pNode = pNode->NextChild; else { pNode = pNode->Parent; if(pNode) pNode->FirstChild = NULL; } - delete pDelete; - } - } + delete pDelete; + } + } } void StdCompilerINIRead::SkipWhitespace() { - while(*pPos == ' ' || *pPos == '\t') - pPos++; + while(*pPos == ' ' || *pPos == '\t') + pPos++; } void StdCompilerINIRead::SkipNum() { - while(*pPos == '+' || *pPos == '-' || isdigit((unsigned char)*pPos)) - pPos++; + while(*pPos == '+' || *pPos == '-' || isdigit((unsigned char)*pPos)) + pPos++; } long StdCompilerINIRead::ReadNum() { - if(!pPos) + if(!pPos) { notFound("Number"); return 0; } - // Skip whitespace - SkipWhitespace(); + // Skip whitespace + SkipWhitespace(); // Read number. If this breaks, Günther is to blame! const char *pnPos = pPos; long iNum = strtol(pPos, const_cast(&pnPos), 10); // Could not read? if(!iNum && pnPos == pPos) { notFound("Number"); return 0; } - // Get over it - pPos = pnPos; - return iNum; + // Get over it + pPos = pnPos; + return iNum; } unsigned long StdCompilerINIRead::ReadUNum() { - if(!pPos) + if(!pPos) { notFound("Number"); return 0; } - // Skip whitespace - SkipWhitespace(); + // Skip whitespace + SkipWhitespace(); // Read number. If this breaks, Günther is to blame! const char *pnPos = pPos; unsigned long iNum = strtoul(pPos, const_cast(&pnPos), 10); // Could not read? if(!iNum && pnPos == pPos) { notFound("Number"); return 0; } - // Get over it - pPos = pnPos; - return iNum; + // Get over it + pPos = pnPos; + return iNum; } size_t StdCompilerINIRead::GetStringLength(RawCompileType eRawType) { - // Excpect valid position - if(!pPos) + // Excpect valid position + if(!pPos) { notFound("String"); return 0; } - // Skip whitespace - SkipWhitespace(); - // Save position - const char *pStart = pPos; - // Escaped? Go over '"' - if(eRawType == RCT_Escaped && *pPos++ != '"') + // Skip whitespace + SkipWhitespace(); + // Save position + const char *pStart = pPos; + // Escaped? Go over '"' + if(eRawType == RCT_Escaped && *pPos++ != '"') { notFound("Escaped string"); return 0; } - // Search end of string - size_t iLength = 0; - while(!TestStringEnd(eRawType)) - { - // Read a character (we're just counting atm) - if(eRawType == RCT_Escaped) - ReadEscapedChar(); - else - pPos++; - // Count it - iLength++; - } - // Reset position, return the length - pPos = pStart; - return iLength; + // Search end of string + size_t iLength = 0; + while(!TestStringEnd(eRawType)) + { + // Read a character (we're just counting atm) + if(eRawType == RCT_Escaped) + ReadEscapedChar(); + else + pPos++; + // Count it + iLength++; + } + // Reset position, return the length + pPos = pStart; + return iLength; } StdBuf StdCompilerINIRead::ReadString(size_t iLength, RawCompileType eRawType, bool fAppendNull) { - // Excpect valid position - if(!pPos) + // Excpect valid position + if(!pPos) { notFound("String"); return StdBuf(); } - // Skip whitespace - SkipWhitespace(); - // Escaped? Go over '"' - if(eRawType == RCT_Escaped && *pPos++ != '"') + // Skip whitespace + SkipWhitespace(); + // Escaped? Go over '"' + if(eRawType == RCT_Escaped && *pPos++ != '"') { notFound("Escaped string"); return StdBuf(); } - // Create buffer - StdBuf OutBuf; OutBuf.New(iLength + (fAppendNull ? sizeof('\0') : 0)); - // Read - char *pOut = getMBufPtr(OutBuf); - while(iLength && !TestStringEnd(eRawType)) - { - // Read a character - if(eRawType == RCT_Escaped) - *pOut++ = ReadEscapedChar(); - else - *pOut++ = *pPos++; - // Count it - iLength--; - } - // Escaped: Go over '"' - if(eRawType == RCT_Escaped) - { - while(*pPos != '"') - { - if(!*pPos || *pPos == '\n' || *pPos == '\r') + // Create buffer + StdBuf OutBuf; OutBuf.New(iLength + (fAppendNull ? sizeof('\0') : 0)); + // Read + char *pOut = getMBufPtr(OutBuf); + while(iLength && !TestStringEnd(eRawType)) + { + // Read a character + if(eRawType == RCT_Escaped) + *pOut++ = ReadEscapedChar(); + else + *pOut++ = *pPos++; + // Count it + iLength--; + } + // Escaped: Go over '"' + if(eRawType == RCT_Escaped) + { + while(*pPos != '"') + { + if(!*pPos || *pPos == '\n' || *pPos == '\r') { Warn("string not terminated!"); pPos--; break; } - pPos++; - } - pPos++; - } + pPos++; + } + pPos++; + } // Nothing read? Identifiers need to be non-empty if(pOut == OutBuf.getData() && (eRawType == RCT_Idtf || eRawType == RCT_ID)) { notFound("String"); return StdBuf(); } - // Append null - if(fAppendNull) - *pOut = '\0'; - // Shrink, if less characters were read - OutBuf.Shrink(iLength); - // Done - return OutBuf; + // Append null + if(fAppendNull) + *pOut = '\0'; + // Shrink, if less characters were read + OutBuf.Shrink(iLength); + // Done + return OutBuf; } bool StdCompilerINIRead::TestStringEnd(RawCompileType eType) { - switch(eType) - { - case RCT_Escaped: return *pPos == '"' || !*pPos || *pPos == '\n' || *pPos == '\r'; - case RCT_All: return !*pPos || *pPos == '\n' || *pPos == '\r'; - // '-' is needed for Layers in Scenario.txt (C4NameList) and other Material-Texture combinations - case RCT_Idtf: case RCT_IdtfAllowEmpty: case RCT_ID: return !isalnum((unsigned char)*pPos) && *pPos != '_' && *pPos != '-'; - } - // unreachable - return true; + switch(eType) + { + case RCT_Escaped: return *pPos == '"' || !*pPos || *pPos == '\n' || *pPos == '\r'; + case RCT_All: return !*pPos || *pPos == '\n' || *pPos == '\r'; + // '-' is needed for Layers in Scenario.txt (C4NameList) and other Material-Texture combinations + case RCT_Idtf: case RCT_IdtfAllowEmpty: case RCT_ID: return !isalnum((unsigned char)*pPos) && *pPos != '_' && *pPos != '-'; + } + // unreachable + return true; } char StdCompilerINIRead::ReadEscapedChar() { - // Catch some no-noes like \0, \n etc. - if(*pPos >= 0 && iscntrl((unsigned char)*pPos)) + // Catch some no-noes like \0, \n etc. + if(*pPos >= 0 && iscntrl((unsigned char)*pPos)) { Warn("Nonprintable character found in string: %02x", static_cast(*pPos)); return *pPos; } - // Not escaped? Just return it - if(*pPos != '\\') return *pPos++; - // What type of escape? - switch(*++pPos) - { - case 'a': pPos++; return '\a'; - case 'b': pPos++; return '\b'; - case 'f': pPos++; return '\f'; - case 'n': pPos++; return '\n'; - case 'r': pPos++; return '\r'; - case 't': pPos++; return '\t'; - case 'v': pPos++; return '\v'; - case '\'': pPos++; return '\''; - case '"': pPos++; return '"'; - case '\\': pPos++; return '\\'; - case '?': pPos++; return '?'; - case 'x': - // Treat '\x' as 'x' - damn special cases - if(!isxdigit((unsigned char)*++pPos)) - return 'x'; - else - { - // Read everything that looks like it might be hexadecimal - MSVC does it this way, so do not sue me. - int iCode = 0; - do - { iCode = iCode * 16 + (isdigit((unsigned char)*pPos) ? *pPos - '0' : *pPos - 'a' + 10); pPos++; } - while(isxdigit((unsigned char)*pPos)); - // Done. Don't bother to check the range (we aren't doing anything mission-critical here, are we?) - return char(iCode); - } - default: - // Not octal? Let it pass through. - if(!isdigit((unsigned char)*pPos) || *pPos >= '8') - return *pPos++; - else - { - // Read it the octal way. - int iCode = 0; - do - { iCode = iCode * 8 + (*pPos - '0'); pPos++;} - while(isdigit((unsigned char)*pPos) && *pPos < '8'); - // Done. See above. - return char(iCode); - } - } - // unreachable + // Not escaped? Just return it + if(*pPos != '\\') return *pPos++; + // What type of escape? + switch(*++pPos) + { + case 'a': pPos++; return '\a'; + case 'b': pPos++; return '\b'; + case 'f': pPos++; return '\f'; + case 'n': pPos++; return '\n'; + case 'r': pPos++; return '\r'; + case 't': pPos++; return '\t'; + case 'v': pPos++; return '\v'; + case '\'': pPos++; return '\''; + case '"': pPos++; return '"'; + case '\\': pPos++; return '\\'; + case '?': pPos++; return '?'; + case 'x': + // Treat '\x' as 'x' - damn special cases + if(!isxdigit((unsigned char)*++pPos)) + return 'x'; + else + { + // Read everything that looks like it might be hexadecimal - MSVC does it this way, so do not sue me. + int iCode = 0; + do + { iCode = iCode * 16 + (isdigit((unsigned char)*pPos) ? *pPos - '0' : *pPos - 'a' + 10); pPos++; } + while(isxdigit((unsigned char)*pPos)); + // Done. Don't bother to check the range (we aren't doing anything mission-critical here, are we?) + return char(iCode); + } + default: + // Not octal? Let it pass through. + if(!isdigit((unsigned char)*pPos) || *pPos >= '8') + return *pPos++; + else + { + // Read it the octal way. + int iCode = 0; + do + { iCode = iCode * 8 + (*pPos - '0'); pPos++;} + while(isdigit((unsigned char)*pPos) && *pPos < '8'); + // Done. See above. + return char(iCode); + } + } + // unreachable assert (false); } diff --git a/src/lib/StdCompiler.h b/src/lib/StdCompiler.h index 0183b81fc..b015271ba 100644 --- a/src/lib/StdCompiler.h +++ b/src/lib/StdCompiler.h @@ -53,21 +53,21 @@ public: #endif {} - // *** Overridables (Interface) - virtual ~StdCompiler() {} + // *** Overridables (Interface) + virtual ~StdCompiler() {} - // * Properties + // * Properties - // Needs two passes? Binary compiler uses this for calculating the size. - virtual bool isDoublePass() { return false; } + // Needs two passes? Binary compiler uses this for calculating the size. + virtual bool isDoublePass() { return false; } - // Changes the target? - virtual bool isCompiler() { return false; } - inline bool isDecompiler() { return !isCompiler(); } + // Changes the target? + virtual bool isCompiler() { return false; } + inline bool isDecompiler() { return !isCompiler(); } - // Does the compiler support naming, so values can be omitted without harm to - // the data structure? Is seperation implemented? - virtual bool hasNaming() { return false; } + // Does the compiler support naming, so values can be omitted without harm to + // the data structure? Is seperation implemented? + virtual bool hasNaming() { return false; } // Does the compiler encourage verbosity (like producing more text instead of // just a numerical value)? @@ -77,19 +77,19 @@ public: virtual void setRuntimeWritesAllowed(int32_t iChange) { } // * Naming - // Provides extra data for the compiler so he can deal with reordered data. - // Note that sections stack and each section will get compiled only once. - // StartSection won't fail if the naming isn't found while compiling. Name and - // all value compiling functions will fail, though. + // Provides extra data for the compiler so he can deal with reordered data. + // Note that sections stack and each section will get compiled only once. + // StartSection won't fail if the naming isn't found while compiling. Name and + // all value compiling functions will fail, though. // Set the NameEnd parameter to true if you are stopping to parse the structure // for whatever reason (suppress warning messages). - virtual bool Name(const char *szName) { return true; } - virtual void NameEnd(bool fBreak = false) { } + virtual bool Name(const char *szName) { return true; } + virtual void NameEnd(bool fBreak = false) { } - // Special: A naming that follows to the currently active naming (on the same level). + // Special: A naming that follows to the currently active naming (on the same level). // Note this will end the current naming, so no additional NameEnd() is needed. - // Only used to maintain backwards compatibility, should not be used in new code. - virtual bool FollowName(const char *szName) { NameEnd(); return Name(szName); } + // Only used to maintain backwards compatibility, should not be used in new code. + virtual bool FollowName(const char *szName) { NameEnd(); return Name(szName); } // Called when a named value omitted because of defaulting (compiler only) // Returns whether the value has been handled @@ -99,23 +99,23 @@ public: virtual int NameCount(const char *szName = NULL) { assert(false); return 0; } - // * Seperation - // Some data types need seperation (note that naming makes this unnecessary). - // Compilers that implement naming must implement seperation. Others may just - // always return success. - // If a seperator wasn't found, some compilers might react by throwing a - // NotFound exception for all attempts to read a value. This behaviour will - // stop when NoSeperator() is called (which just resets this state) or - // Seperator() is called successfully. This behaviour will reset after - // ending the naming, too. - enum Sep - { - SEP_NONE=0, // No seperator ("") - SEP_SEP, // Array seperation (",") - SEP_SEP2, // Array seperation 2 (";") - SEP_SET, // Map pair seperation ("=") - SEP_PART, // Value part seperation (".") - SEP_PART2, // Value part seperation 2 (":") + // * Seperation + // Some data types need seperation (note that naming makes this unnecessary). + // Compilers that implement naming must implement seperation. Others may just + // always return success. + // If a seperator wasn't found, some compilers might react by throwing a + // NotFound exception for all attempts to read a value. This behaviour will + // stop when NoSeperator() is called (which just resets this state) or + // Seperator() is called successfully. This behaviour will reset after + // ending the naming, too. + enum Sep + { + SEP_NONE=0, // No seperator ("") + SEP_SEP, // Array seperation (",") + SEP_SEP2, // Array seperation 2 (";") + SEP_SET, // Map pair seperation ("=") + SEP_PART, // Value part seperation (".") + SEP_PART2, // Value part seperation 2 (":") SEP_PLUS, // Value seperation with a '+' char ("+") SEP_START, // Start some sort of list ('(') SEP_END, // End some sort of list ('(') @@ -123,103 +123,103 @@ public: SEP_END2, // End some sort of list (']') SEP_VLINE, // Vertical line seperator ('|') SEP_DOLLAR // Dollar sign ('$') - }; - virtual bool Seperator(Sep eSep = SEP_SEP) { return true; } - virtual void NoSeperator() { } + }; + virtual bool Seperator(Sep eSep = SEP_SEP) { return true; } + virtual void NoSeperator() { } - // * Data - // Compiling functions for different data types - virtual void DWord(int32_t &rInt) = 0; // Needs seperator! - virtual void DWord(uint32_t &rInt) = 0; // Needs seperator! - virtual void Word(int16_t &rShort) = 0; // Needs seperator! - virtual void Word(uint16_t &rShort) = 0; // Needs seperator! - virtual void Byte(int8_t &rByte) = 0; // Needs seperator! - virtual void Byte(uint8_t &rByte) = 0; // Needs seperator! - virtual void Boolean(bool &rBool) = 0; - virtual void Character(char &rChar) = 0; // Alphanumerical only! + // * Data + // Compiling functions for different data types + virtual void DWord(int32_t &rInt) = 0; // Needs seperator! + virtual void DWord(uint32_t &rInt) = 0; // Needs seperator! + virtual void Word(int16_t &rShort) = 0; // Needs seperator! + virtual void Word(uint16_t &rShort) = 0; // Needs seperator! + virtual void Byte(int8_t &rByte) = 0; // Needs seperator! + virtual void Byte(uint8_t &rByte) = 0; // Needs seperator! + virtual void Boolean(bool &rBool) = 0; + virtual void Character(char &rChar) = 0; // Alphanumerical only! - // Compile raw data (strings) - enum RawCompileType - { - RCT_Escaped=0,// Any data allowed, no seperator needed (default) - RCT_All, // Printable characters only, must be last element in naming. - RCT_Idtf, // Alphanumerical characters or '_', seperator needed. + // Compile raw data (strings) + enum RawCompileType + { + RCT_Escaped=0,// Any data allowed, no seperator needed (default) + RCT_All, // Printable characters only, must be last element in naming. + RCT_Idtf, // Alphanumerical characters or '_', seperator needed. RCT_IdtfAllowEmpty, // Like RCT_Idtf, but empty strings are also allowed - RCT_ID // Like RCT_Idtf (only used for special compilers that treat IDs differently) - }; - // Note that string won't allow '\0' inside the buffer, even with escaped compiling! - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped) = 0; - virtual void String(char **pszString, RawCompileType eType = RCT_Escaped) = 0; - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped) = 0; + RCT_ID // Like RCT_Idtf (only used for special compilers that treat IDs differently) + }; + // Note that string won't allow '\0' inside the buffer, even with escaped compiling! + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped) = 0; + virtual void String(char **pszString, RawCompileType eType = RCT_Escaped) = 0; + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped) = 0; // * Position // May return information about the current position of compilation (used for errors and warnings) virtual StdStrBuf getPosition() const { return StdStrBuf(); } - // * Passes - virtual void Begin() { } - virtual void BeginSecond() { } - virtual void End() { } + // * Passes + virtual void Begin() { } + virtual void BeginSecond() { } + virtual void End() { } - // *** Composed + // *** Composed - // Generic compiler function (plus specializations) - template void Value(const T &rStruct) { rStruct.CompileFunc(this); } - template void Value(T &rStruct) { CompileFunc(rStruct, this); } + // Generic compiler function (plus specializations) + template void Value(const T &rStruct) { rStruct.CompileFunc(this); } + template void Value(T &rStruct) { CompileFunc(rStruct, this); } - void Value(int32_t &rInt) { DWord(rInt); } - void Value(uint32_t &rInt) { DWord(rInt); } - void Value(int16_t &rInt) { Word(rInt); } - void Value(uint16_t &rInt) { Word(rInt); } - void Value(int8_t &rInt) { Byte(rInt); } - void Value(uint8_t &rInt) { Byte(rInt); } - void Value(bool &rBool) { Boolean(rBool); } + void Value(int32_t &rInt) { DWord(rInt); } + void Value(uint32_t &rInt) { DWord(rInt); } + void Value(int16_t &rInt) { Word(rInt); } + void Value(uint16_t &rInt) { Word(rInt); } + void Value(int8_t &rInt) { Byte(rInt); } + void Value(uint8_t &rInt) { Byte(rInt); } + void Value(bool &rBool) { Boolean(rBool); } - // Compiling/Decompiling (may throw a data format exception!) - template inline void Compile(T RREF rStruct) - { + // Compiling/Decompiling (may throw a data format exception!) + template inline void Compile(T RREF rStruct) + { assert(isCompiler()); DoCompilation(rStruct); - } - template inline void Decompile(const T &rStruct) - { + } + template inline void Decompile(const T &rStruct) + { assert(!isCompiler()); DoCompilation(const_cast(rStruct)); - } + } protected: - // Compilation process + // Compilation process template inline void DoCompilation(T &rStruct) { - // Start compilation, do first pass - Begin(); - Value(rStruct); - // Second pass needed? - if(isDoublePass()) - { - BeginSecond(); - Value(rStruct); - } - // Finish - End(); + // Start compilation, do first pass + Begin(); + Value(rStruct); + // Second pass needed? + if(isDoublePass()) + { + BeginSecond(); + Value(rStruct); + } + // Finish + End(); } public: - // Compiler exception - thrown when something is wrong with the data to compile - struct Exception - { - StdStrBuf Pos; - StdStrBuf Msg; + // Compiler exception - thrown when something is wrong with the data to compile + struct Exception + { + StdStrBuf Pos; + StdStrBuf Msg; protected: - Exception(StdStrBuf Pos, StdStrBuf Msg) : Pos(Pos), Msg(Msg) { } - private: - // do not copy - Exception(const Exception &Exc) { } - }; + Exception(StdStrBuf Pos, StdStrBuf Msg) : Pos(Pos), Msg(Msg) { } + private: + // do not copy + Exception(const Exception &Exc) { } + }; class NotFoundException : public Exception { friend class StdCompiler; @@ -270,29 +270,29 @@ protected: bool endFailSafe() { fFailSafe = false; return !fFail; } public: - template bool ValueSafe(const T &rStruct) { rStruct.CompileFunc(this); return true; } - template bool ValueSafe(T &rStruct) { CompileFunc(rStruct, this); return true; } + template bool ValueSafe(const T &rStruct) { rStruct.CompileFunc(this); return true; } + template bool ValueSafe(T &rStruct) { CompileFunc(rStruct, this); return true; } - bool ValueSafe(int32_t &rInt) { beginFailSafe(); DWord(rInt); return endFailSafe(); } - bool ValueSafe(uint32_t &rInt) { beginFailSafe(); DWord(rInt); return endFailSafe(); } - bool ValueSafe(int16_t &rInt) { beginFailSafe(); Word(rInt); return endFailSafe(); } - bool ValueSafe(uint16_t &rInt) { beginFailSafe(); Word(rInt); return endFailSafe(); } - bool ValueSafe(int8_t &rInt) { beginFailSafe(); Byte(rInt); return endFailSafe(); } - bool ValueSafe(uint8_t &rInt) { beginFailSafe(); Byte(rInt); return endFailSafe(); } - bool ValueSafe(bool &rBool) { beginFailSafe(); Boolean(rBool); return endFailSafe(); } + bool ValueSafe(int32_t &rInt) { beginFailSafe(); DWord(rInt); return endFailSafe(); } + bool ValueSafe(uint32_t &rInt) { beginFailSafe(); DWord(rInt); return endFailSafe(); } + bool ValueSafe(int16_t &rInt) { beginFailSafe(); Word(rInt); return endFailSafe(); } + bool ValueSafe(uint16_t &rInt) { beginFailSafe(); Word(rInt); return endFailSafe(); } + bool ValueSafe(int8_t &rInt) { beginFailSafe(); Byte(rInt); return endFailSafe(); } + bool ValueSafe(uint8_t &rInt) { beginFailSafe(); Byte(rInt); return endFailSafe(); } + bool ValueSafe(bool &rBool) { beginFailSafe(); Boolean(rBool); return endFailSafe(); } #endif public: - // * Warnings - typedef void (*WarnCBT)(void *, const char *, const char *); - void setWarnCallback(WarnCBT pnWarnCB, void *pData) { pWarnCB = pnWarnCB; pWarnData = pData; } - void Warn(const char *szWarning, ...); + // * Warnings + typedef void (*WarnCBT)(void *, const char *, const char *); + void setWarnCallback(WarnCBT pnWarnCB, void *pData) { pWarnCB = pnWarnCB; pWarnData = pData; } + void Warn(const char *szWarning, ...); private: - // Warnings - WarnCBT pWarnCB; + // Warnings + WarnCBT pWarnCB; void *pWarnData; protected: @@ -304,8 +304,8 @@ protected: // Standard compile funcs template - inline void CompileFunc(T &rStruct, StdCompiler *pComp) - { + inline void CompileFunc(T &rStruct, StdCompiler *pComp) + { // If the compiler doesn't like this line, you tried to compile // something the compiler doesn't know how to handle. // Possible reasons: @@ -340,33 +340,33 @@ template // Helpers for buffer-based compiling (may throw a data format exception!) template - void CompileFromBuf(StructT RREF TargetStruct, const typename CompT::InT &SrcBuf) - { - CompT Compiler; - Compiler.setInput(SrcBuf.getRef()); - Compiler.Compile(TargetStruct); - } + void CompileFromBuf(StructT RREF TargetStruct, const typename CompT::InT &SrcBuf) + { + CompT Compiler; + Compiler.setInput(SrcBuf.getRef()); + Compiler.Compile(TargetStruct); + } template - StructT * CompileFromBufToNew(const typename CompT::InT &SrcBuf) - { + StructT * CompileFromBufToNew(const typename CompT::InT &SrcBuf) + { StructT *pStruct = NULL; CompileFromBuf(mkPtrAdaptNoNull(pStruct), SrcBuf); return pStruct; - } + } template - StructT * CompileFromBufToNewNamed(const typename CompT::InT &SrcBuf, const char *szName) - { + StructT * CompileFromBufToNewNamed(const typename CompT::InT &SrcBuf, const char *szName) + { StructT *pStruct = NULL; CompileFromBuf(mkNamingAdapt(mkPtrAdaptNoNull(pStruct), szName), SrcBuf); - return pStruct; - } + return pStruct; + } template - typename CompT::OutT DecompileToBuf(const StructT &SrcStruct) - { - CompT Compiler; - Compiler.Decompile(SrcStruct); - return Compiler.getOutput(); - } + typename CompT::OutT DecompileToBuf(const StructT &SrcStruct) + { + CompT Compiler; + Compiler.Decompile(SrcStruct); + return Compiler.getOutput(); + } // *** Null compiler @@ -377,25 +377,25 @@ class StdCompilerNull : public StdCompiler public: // Properties - virtual bool isCompiler() { return true; } - virtual bool hasNaming() { return true; } + virtual bool isCompiler() { return true; } + virtual bool hasNaming() { return true; } // Naming - virtual bool Name(const char *szName) { return false; } + virtual bool Name(const char *szName) { return false; } virtual int NameCount(const char *szName = NULL) { return 0; } - // Data readers - virtual void DWord(int32_t &rInt) { } - virtual void DWord(uint32_t &rInt) { } - virtual void Word(int16_t &rShort) { } - virtual void Word(uint16_t &rShort) { } - virtual void Byte(int8_t &rByte) { } - virtual void Byte(uint8_t &rByte) { } - virtual void Boolean(bool &rBool) { } - virtual void Character(char &rChar) { } - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped) { } - virtual void String(char **pszString, RawCompileType eType = RCT_Escaped) { } - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped) { } + // Data readers + virtual void DWord(int32_t &rInt) { } + virtual void DWord(uint32_t &rInt) { } + virtual void Word(int16_t &rShort) { } + virtual void Word(uint16_t &rShort) { } + virtual void Byte(int8_t &rByte) { } + virtual void Byte(uint8_t &rByte) { } + virtual void Boolean(bool &rBool) { } + virtual void Character(char &rChar) { } + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped) { } + virtual void String(char **pszString, RawCompileType eType = RCT_Escaped) { } + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped) { } }; @@ -409,39 +409,39 @@ class StdCompilerBinWrite : public StdCompiler { public: - // Result - typedef StdBuf OutT; - inline OutT getOutput() { return Buf; } + // Result + typedef StdBuf OutT; + inline OutT getOutput() { return Buf; } - // Properties - virtual bool isDoublePass() { return true; } + // Properties + virtual bool isDoublePass() { return true; } - // Data writers - virtual void DWord(int32_t &rInt); - virtual void DWord(uint32_t &rInt); - virtual void Word(int16_t &rShort); - virtual void Word(uint16_t &rShort); - virtual void Byte(int8_t &rByte); - virtual void Byte(uint8_t &rByte); - virtual void Boolean(bool &rBool); - virtual void Character(char &rChar); - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); - virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); + // Data writers + virtual void DWord(int32_t &rInt); + virtual void DWord(uint32_t &rInt); + virtual void Word(int16_t &rShort); + virtual void Word(uint16_t &rShort); + virtual void Byte(int8_t &rByte); + virtual void Byte(uint8_t &rByte); + virtual void Boolean(bool &rBool); + virtual void Character(char &rChar); + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); + virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); - // Passes - virtual void Begin(); - virtual void BeginSecond(); + // Passes + virtual void Begin(); + virtual void BeginSecond(); protected: // Process data - bool fSecondPass; - int iPos; - StdBuf Buf; + bool fSecondPass; + int iPos; + StdBuf Buf; // Helpers - template void WriteValue(const T &rValue); - void WriteData(const void *pData, size_t iSize); + template void WriteValue(const T &rValue); + void WriteData(const void *pData, size_t iSize); }; // binary read @@ -449,43 +449,43 @@ class StdCompilerBinRead : public StdCompiler { public: - // Input - typedef StdBuf InT; - void setInput(InT RREF In) { Buf = In; } + // Input + typedef StdBuf InT; + void setInput(InT RREF In) { Buf = In; } // Properties - virtual bool isCompiler() { return true; } + virtual bool isCompiler() { return true; } - // Data readers - virtual void DWord(int32_t &rInt); - virtual void DWord(uint32_t &rInt); - virtual void Word(int16_t &rShort); - virtual void Word(uint16_t &rShort); - virtual void Byte(int8_t &rByte); - virtual void Byte(uint8_t &rByte); - virtual void Boolean(bool &rBool); - virtual void Character(char &rChar); - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); - virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); + // Data readers + virtual void DWord(int32_t &rInt); + virtual void DWord(uint32_t &rInt); + virtual void Word(int16_t &rShort); + virtual void Word(uint16_t &rShort); + virtual void Byte(int8_t &rByte); + virtual void Byte(uint8_t &rByte); + virtual void Boolean(bool &rBool); + virtual void Character(char &rChar); + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); + virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); // Position virtual StdStrBuf getPosition() const; - // Passes - virtual void Begin(); + // Passes + virtual void Begin(); // Data - int getPosition() { return iPos; } + int getPosition() { return iPos; } int getRemainingBytes() { return Buf.getSize() - iPos; } protected: // Process data size_t iPos; - StdBuf Buf; + StdBuf Buf; // Helper - template void ReadValue(T &rValue); + template void ReadValue(T &rValue); }; // *** INI compiler @@ -520,61 +520,61 @@ protected: class StdCompilerINIWrite : public StdCompiler { public: - // Input - typedef StdStrBuf OutT; - inline OutT getOutput() { return Buf; } + // Input + typedef StdStrBuf OutT; + inline OutT getOutput() { return Buf; } - // Properties - virtual bool hasNaming() { return true; } + // Properties + virtual bool hasNaming() { return true; } - // Naming - virtual bool Name(const char *szName); - virtual void NameEnd(bool fBreak = false); + // Naming + virtual bool Name(const char *szName); + virtual void NameEnd(bool fBreak = false); - // Seperators - virtual bool Seperator(Sep eSep); + // Seperators + virtual bool Seperator(Sep eSep); - // Data writers - virtual void DWord(int32_t &rInt); - virtual void DWord(uint32_t &rInt); - virtual void Word(int16_t &rShort); - virtual void Word(uint16_t &rShort); - virtual void Byte(int8_t &rByte); - virtual void Byte(uint8_t &rByte); - virtual void Boolean(bool &rBool); - virtual void Character(char &rChar); - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); - virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); + // Data writers + virtual void DWord(int32_t &rInt); + virtual void DWord(uint32_t &rInt); + virtual void Word(int16_t &rShort); + virtual void Word(uint16_t &rShort); + virtual void Byte(int8_t &rByte); + virtual void Byte(uint8_t &rByte); + virtual void Boolean(bool &rBool); + virtual void Character(char &rChar); + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); + virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); - // Passes - virtual void Begin(); - virtual void End(); + // Passes + virtual void Begin(); + virtual void End(); protected: - // Result - StdStrBuf Buf; + // Result + StdStrBuf Buf; - // Naming stack - struct Naming - { - StdStrBuf Name; - Naming *Parent; - }; - Naming *pNaming; - // Recursion depth - int iDepth; + // Naming stack + struct Naming + { + StdStrBuf Name; + Naming *Parent; + }; + Naming *pNaming; + // Recursion depth + int iDepth; - // Name not put yet (it's not clear wether it is a value or a section) - bool fPutName, - // Currently inside a section, so raw data can't be printed - fInSection; + // Name not put yet (it's not clear wether it is a value or a section) + bool fPutName, + // Currently inside a section, so raw data can't be printed + fInSection; - void PrepareForValue(); - void WriteEscaped(const char *szString, const char *pEnd); - void WriteIndent(bool fSectionName); - void PutName(bool fSection); + void PrepareForValue(); + void WriteEscaped(const char *szString, const char *pEnd); + void WriteIndent(bool fSectionName); + void PutName(bool fSection); }; // text reader @@ -582,83 +582,83 @@ class StdCompilerINIRead : public StdCompiler { public: - StdCompilerINIRead(); - ~StdCompilerINIRead(); + StdCompilerINIRead(); + ~StdCompilerINIRead(); - // Input - typedef StdStrBuf InT; - void setInput(const InT &In) { Buf.Ref(In); } + // Input + typedef StdStrBuf InT; + void setInput(const InT &In) { Buf.Ref(In); } - // Properties - virtual bool isCompiler() { return true; } - virtual bool hasNaming() { return true; } + // Properties + virtual bool isCompiler() { return true; } + virtual bool hasNaming() { return true; } - // Naming - virtual bool Name(const char *szName); - virtual void NameEnd(bool fBreak = false); - virtual bool FollowName(const char *szName); + // Naming + virtual bool Name(const char *szName); + virtual void NameEnd(bool fBreak = false); + virtual bool FollowName(const char *szName); - // Seperators - virtual bool Seperator(Sep eSep); - virtual void NoSeperator(); + // Seperators + virtual bool Seperator(Sep eSep); + virtual void NoSeperator(); // Counters virtual int NameCount(const char *szName = NULL); - // Data writers - virtual void DWord(int32_t &rInt); - virtual void DWord(uint32_t &rInt); - virtual void Word(int16_t &rShort); - virtual void Word(uint16_t &rShort); - virtual void Byte(int8_t &rByte); - virtual void Byte(uint8_t &rByte); - virtual void Boolean(bool &rBool); - virtual void Character(char &rChar); - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); - virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); + // Data writers + virtual void DWord(int32_t &rInt); + virtual void DWord(uint32_t &rInt); + virtual void Word(int16_t &rShort); + virtual void Word(uint16_t &rShort); + virtual void Byte(int8_t &rByte); + virtual void Byte(uint8_t &rByte); + virtual void Boolean(bool &rBool); + virtual void Character(char &rChar); + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); + virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); // Position virtual StdStrBuf getPosition() const; - // Passes - virtual void Begin(); - virtual void End(); + // Passes + virtual void Begin(); + virtual void End(); protected: - // * Data + // * Data - // Name tree - struct NameNode - { - // Name - StdStrBuf Name; - // Section? - bool Section; - // Tree structure - NameNode *Parent, - *FirstChild, *PrevChild, *NextChild, *LastChild; - // Indent level - int Indent; - // Name number in parent map - const char *Pos; - // Constructor - NameNode(NameNode *pParent = NULL) - : Parent(pParent), FirstChild(NULL), PrevChild(NULL), NextChild(NULL), LastChild(NULL), - Indent(-1) - { } - }; - NameNode *pNameRoot, *pName; - // Current depth - int iDepth; - // Real depth (depth of recursive Name()-calls - if iDepth != iRealDepth, we are in a nonexistant namespace) - int iRealDepth; + // Name tree + struct NameNode + { + // Name + StdStrBuf Name; + // Section? + bool Section; + // Tree structure + NameNode *Parent, + *FirstChild, *PrevChild, *NextChild, *LastChild; + // Indent level + int Indent; + // Name number in parent map + const char *Pos; + // Constructor + NameNode(NameNode *pParent = NULL) + : Parent(pParent), FirstChild(NULL), PrevChild(NULL), NextChild(NULL), LastChild(NULL), + Indent(-1) + { } + }; + NameNode *pNameRoot, *pName; + // Current depth + int iDepth; + // Real depth (depth of recursive Name()-calls - if iDepth != iRealDepth, we are in a nonexistant namespace) + int iRealDepth; - // Data - StdStrBuf Buf; - // Position - const char *pPos; + // Data + StdStrBuf Buf; + // Position + const char *pPos; // Reenter position (if an nonexistant seperator was specified) const char *pReenter; @@ -666,22 +666,22 @@ protected: // Uppermost name that wasn't found StdCopyStrBuf NotFoundName; - // * Implementation + // * Implementation - // Name tree - void CreateNameTree(); - void FreeNameTree(); + // Name tree + void CreateNameTree(); + void FreeNameTree(); void FreeNameNode(NameNode *pNode); - // Navigation - void SkipWhitespace(); - void SkipNum(); - long ReadNum(); - size_t GetStringLength(RawCompileType eTyped); - StdBuf ReadString(size_t iLength, RawCompileType eTyped, bool fAppendNull = true); - bool TestStringEnd(RawCompileType eType); - char ReadEscapedChar(); - unsigned long ReadUNum(); + // Navigation + void SkipWhitespace(); + void SkipNum(); + long ReadNum(); + size_t GetStringLength(RawCompileType eTyped); + StdBuf ReadString(size_t iLength, RawCompileType eTyped, bool fAppendNull = true); + bool TestStringEnd(RawCompileType eType); + char ReadEscapedChar(); + unsigned long ReadUNum(); void notFound(const char *szWhat); diff --git a/src/lib/texture/C4Facet.cpp b/src/lib/texture/C4Facet.cpp index 5304913cb..bb06f3982 100644 --- a/src/lib/texture/C4Facet.cpp +++ b/src/lib/texture/C4Facet.cpp @@ -38,7 +38,7 @@ void C4Facet::Default() } void C4Facet::Set(SURFACE nsfc, int32_t nx, int32_t ny, int32_t nwdt, int32_t nhgt) - { + { Surface=nsfc; X=nx; Y=ny; Wdt=nwdt; Hgt=nhgt; } @@ -265,7 +265,7 @@ void C4Facet::DrawSectionSelect(C4Facet &cgo, int32_t iSelection, int32_t iMaxSe if (iSelection==firstid+cnt) lpDDraw->DrawBox(cgo2.Surface,cgo2.X,cgo2.Y,cgo2.X+cgo2.Wdt-1,cgo2.Y+cgo2.Hgt-1,CRed); Draw(cgo2,true,firstid+cnt,0); - } + } } void C4Facet::DrawValue(C4Facet &cgo, int32_t iValue, int32_t iSectionX, int32_t iSectionY, int32_t iAlign) diff --git a/src/lib/texture/C4Facet.h b/src/lib/texture/C4Facet.h index a5a2f9bb3..ea6c3b4f2 100644 --- a/src/lib/texture/C4Facet.h +++ b/src/lib/texture/C4Facet.h @@ -118,18 +118,18 @@ class C4DrawTransform : public CBltTransform }; class C4Facet - { - public: - SURFACE Surface; - int32_t X,Y,Wdt,Hgt; + { + public: + SURFACE Surface; + int32_t X,Y,Wdt,Hgt; public: C4Facet(); C4Facet(SURFACE pSfc, int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt) : Surface(pSfc), X(iX), Y(iY), Wdt(iWdt), Hgt(iHgt) { } - public: + public: void Default(); void Set(CSurface &rSfc); - void Set(SURFACE nsfc, int32_t nx, int32_t ny, int32_t nwdt, int32_t nhgt); + void Set(SURFACE nsfc, int32_t nx, int32_t ny, int32_t nwdt, int32_t nhgt); void Set(const C4Facet &cpy) { *this=cpy; } void Wipe(); void Expand(int32_t iLeft=0, int32_t iRight=0, int32_t iTop=0, int32_t iBottom=0); @@ -165,6 +165,6 @@ class C4Facet #ifdef _WIN32 void Draw(HWND hWnd, int32_t iTx, int32_t iTy, int32_t iTWdt, int32_t iTHgt, bool fAspect=true, int32_t iPhaseX=0, int32_t iPhaseY=0); #endif - }; + }; #endif // INC_C4Facet diff --git a/src/lib/texture/C4GraphicsResource.cpp b/src/lib/texture/C4GraphicsResource.cpp index 56c3a81b8..80af08bea 100644 --- a/src/lib/texture/C4GraphicsResource.cpp +++ b/src/lib/texture/C4GraphicsResource.cpp @@ -180,11 +180,11 @@ void C4GraphicsResource::ClearFonts() } bool C4GraphicsResource::Init(bool fInitGUI) - { + { // Init fonts (double init will never if groups didnt change) if (!InitFonts()) return false; - // Game palette - could perhaps be eliminated... + // Game palette - could perhaps be eliminated... int32_t idNewPalGrp; C4Group *pPalGrp=Files.FindEntry("C4.pal", NULL, &idNewPalGrp); if (!pPalGrp) { LogF("%s: %s", LoadResStr("IDS_PRC_FILENOTFOUND"), "C4.pal"); return false; } @@ -207,7 +207,7 @@ bool C4GraphicsResource::Init(bool fInitGUI) idPalGrp = idNewPalGrp; } - // Control + // Control if (!LoadFile(sfcControl, "Control", Files, idSfcControl)) return false; fctKeyboard.Set(&sfcControl,0,0,80,36); fctCommand.Set(&sfcControl,0,36,32,32); @@ -215,7 +215,7 @@ bool C4GraphicsResource::Init(bool fInitGUI) fctOKCancel.Set(&sfcControl,128,100,32,32); fctMouse.Set(&sfcControl,198,100,32,32); - // Facet bitmap resources + // Facet bitmap resources if (!LoadFile(fctFire, "Fire", Files, C4FCT_Height)) return false; if (!LoadFile(fctBackground, "Background", Files)) return false; if (!LoadFile(fctFlag, "Flag", Files)) return false; // (new format) @@ -291,8 +291,8 @@ bool C4GraphicsResource::Init(bool fInitGUI) // mark initialized fInitialized = true; - return true; - } + return true; + } bool C4GraphicsResource::LoadCursorGfx() { @@ -325,14 +325,14 @@ bool C4GraphicsResource::LoadCursorGfx() } if (iCursorSize == 13) { - fctInsideSymbol.Set(fctMouseCursor.Surface, 468, 0, 13, 13); - fctDropTarget.Set(fctMouseCursor.Surface, 494, 0, 13, 13); - } - else - { - fctInsideSymbol.Set(fctMouseCursor.Surface, 36*iCursorSize, 0, iCursorSize, iCursorSize); - fctDropTarget.Set(fctMouseCursor.Surface, 38*iCursorSize, 0, iCursorSize, iCursorSize); - } + fctInsideSymbol.Set(fctMouseCursor.Surface, 468, 0, 13, 13); + fctDropTarget.Set(fctMouseCursor.Surface, 494, 0, 13, 13); + } + else + { + fctInsideSymbol.Set(fctMouseCursor.Surface, 36*iCursorSize, 0, iCursorSize, iCursorSize); + fctDropTarget.Set(fctMouseCursor.Surface, 38*iCursorSize, 0, iCursorSize, iCursorSize); + } // done return true; } diff --git a/src/lib/texture/StdPNG.cpp b/src/lib/texture/StdPNG.cpp index dfd71d5b4..5e8899d3d 100644 --- a/src/lib/texture/StdPNG.cpp +++ b/src/lib/texture/StdPNG.cpp @@ -187,7 +187,7 @@ DWORD CPNGFile::GetPix(int iX, int iY) case PNG_COLOR_TYPE_RGB: return 0xff << 24 | RGB(pPix[0], pPix[1], pPix[2]); case PNG_COLOR_TYPE_RGB_ALPHA: - return pPix[3] << 24 | RGB(pPix[0], pPix[1], pPix[2]); + return pPix[3] << 24 | RGB(pPix[0], pPix[1], pPix[2]); } return 0; } diff --git a/src/netio/TstC4NetIO.cpp b/src/netio/TstC4NetIO.cpp index 0b5d76f65..e3d0d66d6 100644 --- a/src/netio/TstC4NetIO.cpp +++ b/src/netio/TstC4NetIO.cpp @@ -31,18 +31,18 @@ char DummyData[1024 * 1024]; class MyCBClass : public C4NetIOMan { - unsigned int iTime, iPcks; + unsigned int iTime, iPcks; public: virtual bool OnConn(const C4NetIO::addr_t &addr, const C4NetIO::addr_t &addr2, C4NetIO *pNetIO) { cout << "got connection from " << inet_ntoa(addr.sin_addr) << endl; - iTime = timeGetTime(); iPcks = 0; + iTime = timeGetTime(); iPcks = 0; #ifdef ASYNC_CONNECT if(!fHost) { - DummyData[0] = 0; - if(!pNetIO->Send(C4NetIOPacket(DummyData, iSize, true, addr))) + DummyData[0] = 0; + if(!pNetIO->Send(C4NetIOPacket(DummyData, iSize, true, addr))) cout << " Fehler: " << (pNetIO->GetError() ? pNetIO->GetError() : "bla") << endl; } #endif @@ -50,23 +50,23 @@ public: } virtual void OnPacket(const class C4NetIOPacket &rPacket, C4NetIO *pNetIO) { - if(timeGetTime() > iTime + 1000) { - cout << iPcks << " packets in " << timeGetTime() - iTime << " ms (" << iPcks * 1000 / (timeGetTime() - iTime) << " per second, " << (iPcks ? (timeGetTime() - iTime) * 1000 / iPcks : -1u) << "us per packet)" << endl; - iTime = timeGetTime(); iPcks = 0; - } - if(!rPacket.getStatus()) - { - // dummys - DummyData[0] = 1; - C4NetIOPacket Dummy(DummyData, iSize, true, rPacket.getAddr()); - for(int i = 0; i < iCnt; i++) { - if(!pNetIO->Send(Dummy)) + if(timeGetTime() > iTime + 1000) { + cout << iPcks << " packets in " << timeGetTime() - iTime << " ms (" << iPcks * 1000 / (timeGetTime() - iTime) << " per second, " << (iPcks ? (timeGetTime() - iTime) * 1000 / iPcks : -1u) << "us per packet)" << endl; + iTime = timeGetTime(); iPcks = 0; + } + if(!rPacket.getStatus()) + { + // dummys + DummyData[0] = 1; + C4NetIOPacket Dummy(DummyData, iSize, true, rPacket.getAddr()); + for(int i = 0; i < iCnt; i++) { + if(!pNetIO->Send(Dummy)) cout << " Fehler: " << (pNetIO->GetError() ? pNetIO->GetError() : "bla") << endl; - } - // pong - pNetIO->Send(rPacket); - iPcks++; - } + } + // pong + pNetIO->Send(rPacket); + iPcks++; + } // cout << "got " << rPacket.GetSize() << " bytes of data (" << int(*rPacket.GetData()) << ")" << endl; } virtual void OnDisconn(const C4NetIO::addr_t &addr, C4NetIO *pNetIO, const char *szReason) diff --git a/src/network/C4Client.cpp b/src/network/C4Client.cpp index 9106d4cdc..879163693 100644 --- a/src/network/C4Client.cpp +++ b/src/network/C4Client.cpp @@ -37,7 +37,7 @@ C4ClientCore::C4ClientCore() : iID(-1), fActivated(false), - fObserver(false) + fObserver(false) { Name.Ref(""); CUID.Ref(""); Nick.Ref(""); } @@ -52,7 +52,7 @@ void C4ClientCore::SetLocal(int32_t inID, bool fnActivated, bool fnObserver) // status iID = inID; fActivated = fnActivated; - fObserver = fnObserver; + fObserver = fnObserver; // misc Name.CopyValidated(Config.Network.Nick); CUID.CopyValidated(Config.GetRegistrationData("Cuid")); @@ -93,13 +93,13 @@ int32_t C4ClientCore::getDiffLevel(const C4ClientCore &CCore2) const void C4ClientCore::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(iID, "ID", C4ClientIDUnknown)); - pComp->Value(mkNamingAdapt(fActivated, "Activated", false)); - pComp->Value(mkNamingAdapt(fObserver, "Observer", false)); - pComp->Value(mkNamingAdapt(Name, "Name", "")); - pComp->Value(mkNamingAdapt(CUID, "CUID", "")); - pComp->Value(mkNamingAdapt(Nick, "Nick", "")); - pComp->Value(mkNamingAdapt(Revision, "Revision", "")); + pComp->Value(mkNamingAdapt(iID, "ID", C4ClientIDUnknown)); + pComp->Value(mkNamingAdapt(fActivated, "Activated", false)); + pComp->Value(mkNamingAdapt(fObserver, "Observer", false)); + pComp->Value(mkNamingAdapt(Name, "Name", "")); + pComp->Value(mkNamingAdapt(CUID, "CUID", "")); + pComp->Value(mkNamingAdapt(Nick, "Nick", "")); + pComp->Value(mkNamingAdapt(Revision, "Revision", "")); } // *** C4Client diff --git a/src/network/C4GameControlNetwork.cpp b/src/network/C4GameControlNetwork.cpp index 55bd05bb8..021a54b42 100644 --- a/src/network/C4GameControlNetwork.cpp +++ b/src/network/C4GameControlNetwork.cpp @@ -44,7 +44,7 @@ C4GameControlNetwork::C4GameControlNetwork(C4GameControl *pnParent) C4GameControlNetwork::~C4GameControlNetwork() { - Clear(); + Clear(); } bool C4GameControlNetwork::Init(int32_t inClientID, bool fnHost, int32_t iStartTick, bool fnActivated, C4Network2 *pnNetwork) // by main thread @@ -61,7 +61,7 @@ bool C4GameControlNetwork::Init(int32_t inClientID, bool fnHost, int32_t iStartT // make sure no control has been lost pNetwork->Clients.BroadcastMsgToConnClients(MkC4NetIOPacket(PID_ControlReq, C4PacketControlReq(iControlReady + 1))); // ok - fEnabled = true; fRunning = false; + fEnabled = true; fRunning = false; iTargetFPS = 38; iNextControlReqeust = timeGetTime() + C4ControlRequestInterval; return true; } @@ -70,7 +70,7 @@ void C4GameControlNetwork::Clear() // by main thread { fEnabled = false; fRunning = false; iAvgControlSendTime = 0; - ClearCtrl(); ClearClients(); + ClearCtrl(); ClearClients(); // clear sync control SyncControl.Clear(); while(pSyncCtrlQueue) @@ -87,9 +87,9 @@ void C4GameControlNetwork::Execute() // by main thread if(Game.FrameCounter % ::Control.ControlRate) return; - // Save time the control tick was reached - if(iWaitStart == -1) - iWaitStart = timeGetTime(); + // Save time the control tick was reached + if(iWaitStart == -1) + iWaitStart = timeGetTime(); // Execute any queued sync control ExecQueuedSyncCtrl(); @@ -98,9 +98,9 @@ void C4GameControlNetwork::Execute() // by main thread bool C4GameControlNetwork::CtrlReady(int32_t iTick) // by main thread { // check for complete control and pack it - CheckCompleteCtrl(false); + CheckCompleteCtrl(false); // control ready? - return iControlReady >= iTick; + return iControlReady >= iTick; } bool C4GameControlNetwork::GetControl(C4Control *pCtrl, int32_t iTick) // by main thread @@ -113,9 +113,9 @@ bool C4GameControlNetwork::GetControl(C4Control *pCtrl, int32_t iTick) // by mai return false; // set pCtrl->Clear(); - pCtrl->Append(pPkt->getControl()); - // calc performance - CalcPerformance(iTick); + pCtrl->Append(pPkt->getControl()); + // calc performance + CalcPerformance(iTick); iWaitStart = -1; // ok return true; @@ -130,20 +130,20 @@ bool C4GameControlNetwork::ClientReady(int32_t iClientID, int32_t iTick) // by m int32_t C4GameControlNetwork::ClientPerfStat(int32_t iClientID) // by main thread { if(eMode == CNM_Central && !fHost) return true; - // get client - CStdLock ClientsLock(&ClientsCSec); - C4GameControlClient *pClient = getClient(iClientID); - // return performance - return pClient ? pClient->getPerfStat() : 0; + // get client + CStdLock ClientsLock(&ClientsCSec); + C4GameControlClient *pClient = getClient(iClientID); + // return performance + return pClient ? pClient->getPerfStat() : 0; } int32_t C4GameControlNetwork::ClientNextControl(int32_t iClientID) // by main thread { - // get client - CStdLock ClientsLock(&ClientsCSec); - C4GameControlClient *pClient = getClient(iClientID); - // return performance - return pClient ? pClient->getNextControl() : 0; + // get client + CStdLock ClientsLock(&ClientsCSec); + C4GameControlClient *pClient = getClient(iClientID); + // return performance + return pClient ? pClient->getNextControl() : 0; } bool C4GameControlNetwork::CtrlNeeded(int32_t iFrame) const // by main thread @@ -185,7 +185,7 @@ void C4GameControlNetwork::DoInput(const C4Control &Input) // by main thread void C4GameControlNetwork::DoInput(C4PacketType eCtrlType, C4ControlPacket *pCtrl, C4ControlDeliveryType eDelivery) // by main thread { - if(!fEnabled) return; + if(!fEnabled) return; // Create packet C4PacketControlPkt CtrlPkt(eDelivery, C4IDPacket(eCtrlType, pCtrl, false)); @@ -250,7 +250,7 @@ void C4GameControlNetwork::DoInput(C4PacketType eCtrlType, C4ControlPacket *pCtr C4ControlDeliveryType C4GameControlNetwork::DecideControlDelivery() const { // This doesn't make sense for clients - if(!fHost) + if(!fHost) return CDT_Queue; // Decide the fastest control delivery type atm. Note this is a guess. // Control sent with the returned delivery type may in theory be delayed infinitely. @@ -307,20 +307,20 @@ void C4GameControlNetwork::ExecSyncControl(int32_t iControlTick) // by main thre void C4GameControlNetwork::AddClient(int32_t iClientID, const char *szName) // by main thread { - // security - if(!fEnabled || getClient(iClientID)) return; - // create new - C4GameControlClient *pClient = new C4GameControlClient(); - pClient->Set(iClientID, szName); + // security + if(!fEnabled || getClient(iClientID)) return; + // create new + C4GameControlClient *pClient = new C4GameControlClient(); + pClient->Set(iClientID, szName); pClient->SetNextControl(::Control.ControlTick); - // add client - AddClient(pClient); + // add client + AddClient(pClient); } void C4GameControlNetwork::ClearClients() { - CStdLock ClientsLock(&ClientsCSec); - while(pClients) { C4GameControlClient *pClient = pClients; RemoveClient(pClient); delete pClient; } + CStdLock ClientsLock(&ClientsCSec); + while(pClients) { C4GameControlClient *pClient = pClients; RemoveClient(pClient); delete pClient; } } void C4GameControlNetwork::CopyClientList(const C4ClientList &rClients) @@ -336,7 +336,7 @@ void C4GameControlNetwork::CopyClientList(const C4ClientList &rClients) void C4GameControlNetwork::SetRunning(bool fnRunning, int32_t inTargetTick) // by main thread { - assert(fEnabled); + assert(fEnabled); // check for redundant update, stop if running (safety) if(fRunning == fnRunning && iTargetTick == inTargetTick) return; fRunning = false; @@ -355,7 +355,7 @@ void C4GameControlNetwork::SetRunning(bool fnRunning, int32_t inTargetTick) // b void C4GameControlNetwork::SetActivated(bool fnActivated) // by main thread { - assert(fEnabled); + assert(fEnabled); // no change? ignore if(fActivated == fnActivated) return; // set @@ -367,36 +367,36 @@ void C4GameControlNetwork::SetActivated(bool fnActivated) // by main thread void C4GameControlNetwork::SetCtrlMode(C4GameControlNetworkMode enMode) // by main thread { - assert(fEnabled); - // no change? - if(eMode == enMode) return; + assert(fEnabled); + // no change? + if(eMode == enMode) return; // set mode eMode = enMode; - // changed to decentral? rebroadcast all own control - if(enMode == CNM_Decentral) - { - CStdLock CtrlLock(&CtrlCSec); C4GameControlPacket *pPkt; - for(int32_t iCtrlTick = ::Control.ControlTick; (pPkt = getCtrl(iClientID, iCtrlTick)); iCtrlTick++) - ::Network.Clients.BroadcastMsgToClients(MkC4NetIOPacket(PID_Control, *pPkt)); - } + // changed to decentral? rebroadcast all own control + if(enMode == CNM_Decentral) + { + CStdLock CtrlLock(&CtrlCSec); C4GameControlPacket *pPkt; + for(int32_t iCtrlTick = ::Control.ControlTick; (pPkt = getCtrl(iClientID, iCtrlTick)); iCtrlTick++) + ::Network.Clients.BroadcastMsgToClients(MkC4NetIOPacket(PID_Control, *pPkt)); + } else if(enMode == CNM_Central && fHost) { - CStdLock CtrlLock(&CtrlCSec); C4GameControlPacket *pPkt; - for(int32_t iCtrlTick = ::Control.ControlTick; (pPkt = getCtrl(C4ClientIDAll, iCtrlTick)); iCtrlTick++) - ::Network.Clients.BroadcastMsgToClients(MkC4NetIOPacket(PID_Control, *pPkt)); + CStdLock CtrlLock(&CtrlCSec); C4GameControlPacket *pPkt; + for(int32_t iCtrlTick = ::Control.ControlTick; (pPkt = getCtrl(C4ClientIDAll, iCtrlTick)); iCtrlTick++) + ::Network.Clients.BroadcastMsgToClients(MkC4NetIOPacket(PID_Control, *pPkt)); } } void C4GameControlNetwork::CalcPerformance(int32_t iCtrlTick) { - CStdLock ControlLock(&CtrlCSec); - CStdLock ClientLock(&ClientsCSec); - // should only be called if ready - assert(CtrlReady(iCtrlTick)); - // calc perfomance for all clients + CStdLock ControlLock(&CtrlCSec); + CStdLock ClientLock(&ClientsCSec); + // should only be called if ready + assert(CtrlReady(iCtrlTick)); + // calc perfomance for all clients int32_t iClientsPing=0; int32_t iPingClientCount=0; int32_t iNumTunnels=0; int32_t iHostPing=0; - for(C4GameControlClient *pClient = pClients; pClient; pClient = pClient->pNext) - { + for(C4GameControlClient *pClient = pClients; pClient; pClient = pClient->pNext) + { // Some rudimentary PreSend-calculation // get associated connection - NULL for self C4Network2Client *pNetClt = ::Network.Clients.GetClientByID(pClient->getClientID()); @@ -417,12 +417,12 @@ void C4GameControlNetwork::CalcPerformance(int32_t iCtrlTick) } } // Performance statistics - // find control (may not be found, if we only got the complete ctrl) - C4GameControlPacket *pCtrl = getCtrl(pClient->getClientID(), iCtrlTick); - if(!pCtrl) continue; - // calc stats - pClient->AddPerf(pCtrl->getTime() - iWaitStart); - } + // find control (may not be found, if we only got the complete ctrl) + C4GameControlPacket *pCtrl = getCtrl(pClient->getClientID(), iCtrlTick); + if(!pCtrl) continue; + // calc stats + pClient->AddPerf(pCtrl->getTime() - iWaitStart); + } // Now do PreSend-calcs based on ping times int32_t iControlSendTime; if (eMode == CNM_Decentral) @@ -476,30 +476,30 @@ void C4GameControlNetwork::HandlePacket(char cStatus, const C4PacketBase *pPacke case PID_ControlReq: // control request { - if(!IsEnabled()) break; + if(!IsEnabled()) break; if(pConn->isClosed() || !pConn->isAccepted()) break; GETPKT(C4PacketControlReq, rPkt) HandleControlReq(rPkt, pConn); } break; - case PID_ControlPkt: // single control packet (main thread!) - { + case PID_ControlPkt: // single control packet (main thread!) + { GETPKT(C4PacketControlPkt, rPkt) - // security - if(!fEnabled) break; - if(rPkt.getCtrl().getPktType() < CID_First) break; - // create copy (HandleControlPkt will store or delete) - C4IDPacket Copy(rPkt.getCtrl()); + // security + if(!fEnabled) break; + if(rPkt.getCtrl().getPktType() < CID_First) break; + // create copy (HandleControlPkt will store or delete) + C4IDPacket Copy(rPkt.getCtrl()); // some sanity checks C4ControlPacket *pCtrlPkt = static_cast(Copy.getPkt()); if(!pConn->isHost() && pConn->getClientID() != pCtrlPkt->getByClient()) break; // handle HandleControlPkt(Copy.getPktType(), pCtrlPkt, rPkt.getDelivery()); - Copy.Default(); - } - break; + Copy.Default(); + } + break; case PID_ExecSyncCtrl: { @@ -602,55 +602,55 @@ void C4GameControlNetwork::HandleControlPkt(C4PacketType eCtrlType, C4ControlPac C4GameControlClient *C4GameControlNetwork::getClient(int32_t iID) // by both { - CStdLock ClientsLock(&ClientsCSec); - for(C4GameControlClient *pClient = pClients; pClient; pClient = pClient->pNext) - if(pClient->getClientID() == iID) - return pClient; - return NULL; + CStdLock ClientsLock(&ClientsCSec); + for(C4GameControlClient *pClient = pClients; pClient; pClient = pClient->pNext) + if(pClient->getClientID() == iID) + return pClient; + return NULL; } void C4GameControlNetwork::AddClient(C4GameControlClient *pClient) // by main thread { - if(!pClient) return; - // lock - CStdLock ClientsLock(&ClientsCSec); - // add (ordered) - C4GameControlClient *pPrev = NULL, *pPos = pClients; - for(; pPos; pPrev = pPos, pPos = pPos->pNext) - if(pPos->getClientID() > pClient->getClientID()) - break; - // insert - (pPrev ? pPrev->pNext : pClients) = pClient; - pClient->pNext = pPos; + if(!pClient) return; + // lock + CStdLock ClientsLock(&ClientsCSec); + // add (ordered) + C4GameControlClient *pPrev = NULL, *pPos = pClients; + for(; pPos; pPrev = pPos, pPos = pPos->pNext) + if(pPos->getClientID() > pClient->getClientID()) + break; + // insert + (pPrev ? pPrev->pNext : pClients) = pClient; + pClient->pNext = pPos; } void C4GameControlNetwork::RemoveClient(C4GameControlClient *pClient) // by main thread { - // obtain lock - CStdLock ClientsLock(&ClientsCSec); - // first client? - if(pClient == pClients) - pClients = pClient->pNext; - else - { - C4GameControlClient *pPrev; - for(pPrev = pClients; pPrev && pPrev->pNext; pPrev = pPrev->pNext) - if(pPrev->pNext == pClient) - break; - if(pPrev && pPrev->pNext == pClient) - pPrev->pNext = pClient->pNext; - } + // obtain lock + CStdLock ClientsLock(&ClientsCSec); + // first client? + if(pClient == pClients) + pClients = pClient->pNext; + else + { + C4GameControlClient *pPrev; + for(pPrev = pClients; pPrev && pPrev->pNext; pPrev = pPrev->pNext) + if(pPrev->pNext == pClient) + break; + if(pPrev && pPrev->pNext == pClient) + pPrev->pNext = pClient->pNext; + } } C4GameControlPacket *C4GameControlNetwork::getCtrl(int32_t iClientID, int32_t iCtrlTick) // by both { - // lock - CStdLock CtrlLock(&CtrlCSec); - // search - for(C4GameControlPacket *pCtrl = pCtrlStack; pCtrl; pCtrl = pCtrl->pNext) - if(pCtrl->getClientID() == iClientID && pCtrl->getCtrlTick() == iCtrlTick) - return pCtrl; - return NULL; + // lock + CStdLock CtrlLock(&CtrlCSec); + // search + for(C4GameControlPacket *pCtrl = pCtrlStack; pCtrl; pCtrl = pCtrl->pNext) + if(pCtrl->getClientID() == iClientID && pCtrl->getCtrlTick() == iCtrlTick) + return pCtrl; + return NULL; } void C4GameControlNetwork::AddCtrl(C4GameControlPacket *pCtrl) // by both @@ -720,9 +720,9 @@ void C4GameControlNetwork::CheckCompleteCtrl(bool fSetEvent) // by both if(!(pComplete = PackCompleteCtrl(iControlReady + 1))) break; } - // preexecute to check if it's ready for execute - if(!pComplete->getControl().PreExecute()) - break; + // preexecute to check if it's ready for execute + if(!pComplete->getControl().PreExecute()) + break; // ok, control for this tick is ready iControlReady++; // tell the main thread to move on @@ -851,7 +851,7 @@ void C4GameControlNetwork::ExecQueuedSyncCtrl() // by main thread C4GameControlPacket::C4GameControlPacket() : iClientID(C4ClientIDUnknown), iCtrlTick(-1), - iTime(timeGetTime()), + iTime(timeGetTime()), pNext(NULL) { @@ -860,7 +860,7 @@ C4GameControlPacket::C4GameControlPacket() C4GameControlPacket::C4GameControlPacket(const C4GameControlPacket &Pkt2) : C4PacketBase(Pkt2), iClientID(Pkt2.getClientID()), iCtrlTick(Pkt2.getCtrlTick()), - iTime(timeGetTime()), + iTime(timeGetTime()), pNext(NULL) { Ctrl.Copy(Pkt2.getControl()); @@ -887,14 +887,14 @@ void C4GameControlPacket::Set(int32_t inClientID, int32_t inCtrlTick, const C4Co void C4GameControlPacket::Add(const C4GameControlPacket &Ctrl2) { - Ctrl.Append(Ctrl2.getControl()); + Ctrl.Append(Ctrl2.getControl()); } void C4GameControlPacket::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iClientID), "ClientID", C4ClientIDUnknown)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iCtrlTick), "CtrlTick", -1)); - pComp->Value(mkNamingAdapt(Ctrl, "Ctrl")); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iClientID), "ClientID", C4ClientIDUnknown)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iCtrlTick), "CtrlTick", -1)); + pComp->Value(mkNamingAdapt(Ctrl, "Ctrl")); } // *** C4GameControlClient diff --git a/src/network/C4GameControlNetwork.h b/src/network/C4GameControlNetwork.h index 73b4c3673..771d4577b 100644 --- a/src/network/C4GameControlNetwork.h +++ b/src/network/C4GameControlNetwork.h @@ -64,7 +64,7 @@ protected: volatile int32_t iControlPreSend; // statistics - int32_t iWaitStart; + int32_t iWaitStart; int32_t iAvgControlSendTime; int32_t iTargetFPS; // used for PreSend-colculation @@ -75,12 +75,12 @@ protected: C4GameControlPacket *pCtrlStack; CStdCSec CtrlCSec; - // list of clients (activated only!) - C4GameControlClient *pClients; - CStdCSec ClientsCSec; + // list of clients (activated only!) + C4GameControlClient *pClients; + CStdCSec ClientsCSec; // holds control that needs to be executed synchronized (main thread only) - C4Control SyncControl; + C4Control SyncControl; C4GameControlPacket *pSyncCtrlQueue; // control request timing @@ -107,7 +107,7 @@ public: void Execute(); // by main thread bool CtrlReady(int32_t iTick); // by main thread bool CtrlOverflow(int32_t iTick) const { return fRunning && iControlReady >= iTick + C4ControlOverflowLimit; } // by main thread - int32_t GetBehind(int32_t iTick) const { return iControlReady - iTick + 1; } // by main thread + int32_t GetBehind(int32_t iTick) const { return iControlReady - iTick + 1; } // by main thread bool GetControl(C4Control *pCtrl, int32_t iTick); // by main thread bool ClientReady(int32_t iClientID, int32_t iTick); // by main thread int32_t ClientPerfStat(int32_t iClientID); // by main thread @@ -115,7 +115,7 @@ public: bool CtrlNeeded(int32_t iTick) const; // by main thread void DoInput(const C4Control &Input); // by main thread - void DoInput(C4PacketType eCtrlType, C4ControlPacket *pPkt, enum C4ControlDeliveryType eType); // by main thread + void DoInput(C4PacketType eCtrlType, C4ControlPacket *pPkt, enum C4ControlDeliveryType eType); // by main thread // sync control C4ControlDeliveryType DecideControlDelivery() const; // by main thread @@ -131,8 +131,8 @@ public: void SetCtrlMode(C4GameControlNetworkMode enMode); // by main thread C4GameControlNetworkMode GetCtrlMode() const { return eMode; } // by main thread - // performance - void CalcPerformance(int32_t iCtrlTick); // by main thread + // performance + void CalcPerformance(int32_t iCtrlTick); // by main thread // interfaces void HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Network2IOConnection *pConn); @@ -141,19 +141,19 @@ public: protected: // clients - void AddClient(int32_t iClientID, const char *szName); // by main thread - void RemoveClient(int32_t iClientID); // by main thread - void ClearClients(); // by main thread + void AddClient(int32_t iClientID, const char *szName); // by main thread + void RemoveClient(int32_t iClientID); // by main thread + void ClearClients(); // by main thread // packet handling void HandleControl(int32_t iByClientID, const C4GameControlPacket &rPkt); void HandleControlReq(const C4PacketControlReq &rPkt, C4Network2IOConnection *pConn); void HandleControlPkt(C4PacketType eCtrlType, C4ControlPacket *pPkt, enum C4ControlDeliveryType eType); - // client list - C4GameControlClient *getClient(int32_t iID); - void AddClient(C4GameControlClient *pClient); - void RemoveClient(C4GameControlClient *pClient); + // client list + C4GameControlClient *getClient(int32_t iID); + void AddClient(C4GameControlClient *pClient); + void RemoveClient(C4GameControlClient *pClient); // control stack C4GameControlPacket *getCtrl(int32_t iClientID, int32_t iCtrlTick); // by both @@ -181,7 +181,7 @@ public: protected: // header int32_t iClientID, iCtrlTick; - int32_t iTime; + int32_t iTime; // data C4Control Ctrl; @@ -192,7 +192,7 @@ protected: public: int32_t getClientID() const { return iClientID; } int32_t getCtrlTick() const { return iCtrlTick; } - int32_t getTime() const { return iTime; } + int32_t getTime() const { return iTime; } const C4Control &getControl() const { return Ctrl; } void Set(int32_t iClientID, int32_t iCtrlTick); @@ -216,8 +216,8 @@ protected: // next expected control for this client int32_t iNextControl; - // performance data - int32_t iPerformance; + // performance data + int32_t iPerformance; // list (C4GameControl) C4GameControlClient *pNext; @@ -226,11 +226,11 @@ public: int32_t getClientID() const { return iClientID; } const char *getName() const { return szName; } int32_t getNextControl() const { return iNextControl; } - int32_t getPerfStat() const; + int32_t getPerfStat() const; - void Set(int32_t iClientID, const char *szName); + void Set(int32_t iClientID, const char *szName); void SetNextControl(int32_t inNextControl) { iNextControl = inNextControl; } - void AddPerf(int32_t iTime); + void AddPerf(int32_t iTime); }; // * Packet classes * diff --git a/src/network/C4InteractiveThread.cpp b/src/network/C4InteractiveThread.cpp index e342f9059..c98ce77ad 100644 --- a/src/network/C4InteractiveThread.cpp +++ b/src/network/C4InteractiveThread.cpp @@ -26,56 +26,56 @@ // *** C4InteractiveThread C4InteractiveThread::C4InteractiveThread() - { + { // Add head-item pFirstEvent = pLastEvent = new Event(); pFirstEvent->Type = Ev_None; pFirstEvent->Next = NULL; - // reset event handlers - ZeroMem(&pCallbacks, sizeof(pCallbacks)); + // reset event handlers + ZeroMem(&pCallbacks, sizeof(pCallbacks)); // Set notify proc NotifyProc.SetNotify(this); Application.Add(&NotifyProc); - } + } C4InteractiveThread::~C4InteractiveThread() - { + { CStdLock PushLock(&EventPushCSec), PopLock(&EventPopCSec); // Remove all items. This may leak data, if pData was allocated on the heap. while(PopEvent(NULL, NULL)) {} - // Delete head-item + // Delete head-item delete pFirstEvent; pFirstEvent = pLastEvent = NULL; // Unregister notify Application.Remove(&NotifyProc); - } + } bool C4InteractiveThread::AddProc(StdSchedulerProc *pProc) - { - bool fFirst = !Scheduler.getProcCnt(); - // Add the proc - Scheduler.Add(pProc); - // Not started yet? - if(fFirst) - if(!Scheduler.Start()) - return false; - return true; - } + { + bool fFirst = !Scheduler.getProcCnt(); + // Add the proc + Scheduler.Add(pProc); + // Not started yet? + if(fFirst) + if(!Scheduler.Start()) + return false; + return true; + } void C4InteractiveThread::RemoveProc(StdSchedulerProc *pProc) - { + { // Process not in list? if(!Scheduler.hasProc(pProc)) return; - // Last proc to be removed? - if(Scheduler.getProcCnt() == 1) - Scheduler.Stop(); - // Remove - Scheduler.Remove(pProc); - } + // Last proc to be removed? + if(Scheduler.getProcCnt() == 1) + Scheduler.Stop(); + // Remove + Scheduler.Remove(pProc); + } bool C4InteractiveThread::PushEvent(C4InteractiveEventType eEvent, void *pData) - { + { CStdLock PushLock(&EventPushCSec); if(!pLastEvent) return false; // create event @@ -83,7 +83,7 @@ bool C4InteractiveThread::PushEvent(C4InteractiveEventType eEvent, void *pData) pEvent->Type = eEvent; pEvent->Data = pData; #ifdef _DEBUG - pEvent->Time = timeGetTime(); + pEvent->Time = timeGetTime(); #endif pEvent->Next = NULL; // add item (at end) @@ -93,14 +93,14 @@ bool C4InteractiveThread::PushEvent(C4InteractiveEventType eEvent, void *pData) // notify main thread NotifyProc.Notify(); return true; - } + } #ifdef _DEBUG double AvgNetEvDelay = 0; #endif bool C4InteractiveThread::PopEvent(C4InteractiveEventType *pEventType, void **ppData) // (by main thread) - { + { CStdLock PopLock(&EventPopCSec); if(!pFirstEvent) return false; // get event @@ -108,83 +108,83 @@ bool C4InteractiveThread::PopEvent(C4InteractiveEventType *pEventType, void **pp if(!pEvent) return false; // return if(pEventType) - *pEventType = pEvent->Type; + *pEventType = pEvent->Type; if(ppData) - *ppData = pEvent->Data; + *ppData = pEvent->Data; #ifdef _DEBUG - if(Game.IsRunning) - AvgNetEvDelay += ((timeGetTime() - pEvent->Time) - AvgNetEvDelay) / 100; + if(Game.IsRunning) + AvgNetEvDelay += ((timeGetTime() - pEvent->Time) - AvgNetEvDelay) / 100; #endif // remove delete pFirstEvent; pFirstEvent = pEvent; pFirstEvent->Type = Ev_None; return true; - } + } void C4InteractiveThread::ProcessEvents() // by main thread - { - C4InteractiveEventType eEventType; void *pEventData; - while(PopEvent(&eEventType, &pEventData)) - switch(eEventType) - { - // Logging - case Ev_Log: case Ev_LogSilent: case Ev_LogFatal: - { + { + C4InteractiveEventType eEventType; void *pEventData; + while(PopEvent(&eEventType, &pEventData)) + switch(eEventType) + { + // Logging + case Ev_Log: case Ev_LogSilent: case Ev_LogFatal: + { // Reconstruct the StdStrBuf which allocated the data. StdStrBuf pLog; pLog.Take(reinterpret_cast(pEventData)); switch (eEventType) - { + { case Ev_Log: - Log(pLog.getData()); break; + Log(pLog.getData()); break; case Ev_LogSilent: - LogSilent(pLog.getData()); break; + LogSilent(pLog.getData()); break; case Ev_LogFatal: - LogFatal(pLog.getData()); break; + LogFatal(pLog.getData()); break; default: assert(eEventType == Ev_Log || eEventType == Ev_LogSilent || eEventType == Ev_LogFatal); // obviously will not happen, but someone tell gcc } - } - break; + } + break; - // Other events: check for a registered handler - default: - if(eEventType >= Ev_None && eEventType <= Ev_Last) - if(pCallbacks[eEventType]) - pCallbacks[eEventType]->OnThreadEvent(eEventType, pEventData); - // Note that memory might leak if the event wasn't processed.... - } - } + // Other events: check for a registered handler + default: + if(eEventType >= Ev_None && eEventType <= Ev_Last) + if(pCallbacks[eEventType]) + pCallbacks[eEventType]->OnThreadEvent(eEventType, pEventData); + // Note that memory might leak if the event wasn't processed.... + } + } bool C4InteractiveThread::ThreadLog(const char *szMessage, ...) - { + { // format message - va_list lst; va_start(lst, szMessage); - StdStrBuf Msg = FormatStringV(szMessage, lst); + va_list lst; va_start(lst, szMessage); + StdStrBuf Msg = FormatStringV(szMessage, lst); // send to main thread - return PushEvent(Ev_Log, Msg.GrabPointer()); - } + return PushEvent(Ev_Log, Msg.GrabPointer()); + } bool C4InteractiveThread::ThreadLogFatal(const char *szMessage, ...) - { + { // format message - va_list lst; va_start(lst, szMessage); - StdStrBuf Msg = FormatStringV(szMessage, lst); + va_list lst; va_start(lst, szMessage); + StdStrBuf Msg = FormatStringV(szMessage, lst); // send to main thread - return PushEvent(Ev_LogFatal, Msg.GrabPointer()); - } + return PushEvent(Ev_LogFatal, Msg.GrabPointer()); + } bool C4InteractiveThread::ThreadLogS(const char *szMessage, ...) - { + { // format message - va_list lst; va_start(lst, szMessage); - StdStrBuf Msg = FormatStringV(szMessage, lst); + va_list lst; va_start(lst, szMessage); + StdStrBuf Msg = FormatStringV(szMessage, lst); // send to main thread - return PushEvent(Ev_LogSilent, Msg.GrabPointer()); - } + return PushEvent(Ev_LogSilent, Msg.GrabPointer()); + } bool C4InteractiveThreadNotifyProc::Execute(int, pollfd*) { diff --git a/src/network/C4InteractiveThread.h b/src/network/C4InteractiveThread.h index 2c1f82e12..9a430f4a0 100644 --- a/src/network/C4InteractiveThread.h +++ b/src/network/C4InteractiveThread.h @@ -27,21 +27,21 @@ enum C4InteractiveEventType { Ev_None = 0, - Ev_Log, - Ev_LogSilent, - Ev_LogFatal, + Ev_Log, + Ev_LogSilent, + Ev_LogFatal, - Ev_FileChange, + Ev_FileChange, - Ev_HTTP_Response, + Ev_HTTP_Response, - Ev_IRC_Message, + Ev_IRC_Message, Ev_Net_Conn, Ev_Net_Disconn, Ev_Net_Packet, - Ev_Last = Ev_Net_Packet + Ev_Last = Ev_Net_Packet }; class C4InteractiveThreadNotifyProc : public CStdNotifyProc @@ -56,23 +56,23 @@ class C4InteractiveThreadNotifyProc : public CStdNotifyProc // Collects StdSchedulerProc objects and executes them in a seperate thread // Provides an event queue for the procs to communicate with the main thread class C4InteractiveThread - { - public: - C4InteractiveThread(); - ~C4InteractiveThread(); + { + public: + C4InteractiveThread(); + ~C4InteractiveThread(); - // Event callback interface - class Callback - { - public: - virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData) = 0; - virtual ~Callback() { } - }; + // Event callback interface + class Callback + { + public: + virtual void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData) = 0; + virtual ~Callback() { } + }; - private: + private: - // the thread itself - StdSchedulerThread Scheduler; + // the thread itself + StdSchedulerThread Scheduler; // event queue (signals to main thread) struct Event @@ -80,43 +80,43 @@ class C4InteractiveThread C4InteractiveEventType Type; void *Data; #ifdef _DEBUG - int Time; + int Time; #endif Event *Next; }; Event *pFirstEvent, *pLastEvent; CStdCSec EventPushCSec, EventPopCSec; - // callback objects for events of special types - Callback *pCallbacks[Ev_Last + 1]; + // callback objects for events of special types + Callback *pCallbacks[Ev_Last + 1]; // proc that is added to the main thread to receive messages from our thread C4InteractiveThreadNotifyProc NotifyProc; - public: + public: - // process management + // process management bool AddProc(StdSchedulerProc *pProc); void RemoveProc(StdSchedulerProc *pProc); - // event queue + // event queue bool PushEvent(C4InteractiveEventType eEventType, void *pData = NULL); - void ProcessEvents(); // by main thread + void ProcessEvents(); // by main thread // special events bool ThreadLog(const char *szMessage, ...) GNUC_FORMAT_ATTRIBUTE_O; bool ThreadLogFatal(const char *szMessage, ...) GNUC_FORMAT_ATTRIBUTE_O; bool ThreadLogS(const char *szMessage, ...) GNUC_FORMAT_ATTRIBUTE_O; - // event handlers - void SetCallback(C4InteractiveEventType eEvent, Callback *pnNetworkCallback) - { pCallbacks[eEvent] = pnNetworkCallback; } - void ClearCallback(C4InteractiveEventType eEvent, Callback *pnNetworkCallback) - { if(pCallbacks[eEvent] == pnNetworkCallback) pCallbacks[eEvent] = NULL; } + // event handlers + void SetCallback(C4InteractiveEventType eEvent, Callback *pnNetworkCallback) + { pCallbacks[eEvent] = pnNetworkCallback; } + void ClearCallback(C4InteractiveEventType eEvent, Callback *pnNetworkCallback) + { if(pCallbacks[eEvent] == pnNetworkCallback) pCallbacks[eEvent] = NULL; } - private: + private: bool PopEvent(C4InteractiveEventType *pEventType, void **ppData); // by main thread - }; + }; #endif // C4INTERACTIVETHREAD_H diff --git a/src/network/C4League.cpp b/src/network/C4League.cpp index c998716fd..92e56a01c 100644 --- a/src/network/C4League.cpp +++ b/src/network/C4League.cpp @@ -30,32 +30,32 @@ // *** C4LeagueRequestHead void C4LeagueRequestHead::CompileFunc(StdCompiler *pComp) - { + { - StdEnumEntry Actions[] = - { - { "Start", C4LA_Start }, - { "Update", C4LA_Update }, - { "End", C4LA_End }, - { "Join", C4LA_PlrAuthCheck }, + StdEnumEntry Actions[] = + { + { "Start", C4LA_Start }, + { "Update", C4LA_Update }, + { "End", C4LA_End }, + { "Join", C4LA_PlrAuthCheck }, - { "", C4LA_RefQuery }, - { "Auth", C4LA_PlrAuth }, + { "", C4LA_RefQuery }, + { "Auth", C4LA_PlrAuth }, - { "ReportDisconnect", C4LA_ReportDisconnect }, - }; + { "ReportDisconnect", C4LA_ReportDisconnect }, + }; - pComp->Value(mkNamingAdapt(mkEnumAdaptT(eAction, Actions), "Action", C4LA_RefQuery)); - pComp->Value(mkNamingAdapt(mkParAdapt(CSID, StdCompiler::RCT_IdtfAllowEmpty), "CSID", "")); - pComp->Value(mkNamingAdapt(mkParAdapt(AUID, StdCompiler::RCT_IdtfAllowEmpty), "AUID", "")); + pComp->Value(mkNamingAdapt(mkEnumAdaptT(eAction, Actions), "Action", C4LA_RefQuery)); + pComp->Value(mkNamingAdapt(mkParAdapt(CSID, StdCompiler::RCT_IdtfAllowEmpty), "CSID", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(AUID, StdCompiler::RCT_IdtfAllowEmpty), "AUID", "")); // Auth - pComp->Value(mkNamingAdapt(mkParAdapt(Account, StdCompiler::RCT_All), "Account", "")); - pComp->Value(mkNamingAdapt(mkParAdapt(Password, StdCompiler::RCT_All), "Password", "")); - pComp->Value(mkNamingAdapt(mkParAdapt(NewAccount, StdCompiler::RCT_All), "NewAccount", "")); - pComp->Value(mkNamingAdapt(mkParAdapt(NewPassword, StdCompiler::RCT_All), "NewPassword", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(Account, StdCompiler::RCT_All), "Account", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(Password, StdCompiler::RCT_All), "Password", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(NewAccount, StdCompiler::RCT_All), "NewAccount", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(NewPassword, StdCompiler::RCT_All), "NewPassword", "")); - } + } void C4LeagueRequestHead::SetAuth(const char *szAccount, const char *szPassword) { @@ -76,18 +76,18 @@ void C4LeagueRequestHead::SetNewPassword(const char *szNewPassword) // *** C4LeagueReportDisconnectHead void C4LeagueReportDisconnectHead::CompileFunc(StdCompiler *pComp) - { - // inherited fields - C4LeagueRequestHead::CompileFunc(pComp); - // reason - StdEnumEntry Reasons[] = - { - { "", C4LDR_Unknown }, - { "ConnectionFailed", C4LDR_ConnectionFailed}, - { "Desync", C4LDR_Desync }, - }; - pComp->Value(mkNamingAdapt(mkEnumAdaptT(eReason, Reasons), "Reason", C4LDR_Unknown)); - } + { + // inherited fields + C4LeagueRequestHead::CompileFunc(pComp); + // reason + StdEnumEntry Reasons[] = + { + { "", C4LDR_Unknown }, + { "ConnectionFailed", C4LDR_ConnectionFailed}, + { "Desync", C4LDR_Desync }, + }; + pComp->Value(mkNamingAdapt(mkEnumAdaptT(eReason, Reasons), "Reason", C4LDR_Unknown)); + } // *** C4LeagueRequestHeadEnd @@ -102,16 +102,16 @@ void C4LeagueRequestHeadEnd::CompileFunc(StdCompiler *pComp) // *** C4LeagueResponseHead void C4LeagueResponseHead::CompileFunc(StdCompiler *pComp) - { - pComp->Value(mkNamingAdapt(mkParAdapt(Status, StdCompiler::RCT_IdtfAllowEmpty), "Status", "")); - pComp->Value(mkNamingAdapt(mkParAdapt(CSID, StdCompiler::RCT_IdtfAllowEmpty), "CSID", "")); - pComp->Value(mkNamingAdapt(mkParAdapt(Message, StdCompiler::RCT_All), "Message", "")); + { + pComp->Value(mkNamingAdapt(mkParAdapt(Status, StdCompiler::RCT_IdtfAllowEmpty), "Status", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(CSID, StdCompiler::RCT_IdtfAllowEmpty), "CSID", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(Message, StdCompiler::RCT_All), "Message", "")); // Auth - pComp->Value(mkNamingAdapt(mkParAdapt(Account, StdCompiler::RCT_All), "Account", "")); - pComp->Value(mkNamingAdapt(mkParAdapt(AUID, StdCompiler::RCT_All), "AUID", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(Account, StdCompiler::RCT_All), "Account", "")); + pComp->Value(mkNamingAdapt(mkParAdapt(AUID, StdCompiler::RCT_All), "AUID", "")); pComp->Value(mkNamingAdapt(mkParAdapt(FBID, StdCompiler::RCT_All), "FBID", "")); - } + } // *** C4LeagueResponseHeadStart @@ -139,8 +139,8 @@ void C4LeagueResponseHeadUpdate::CompileFunc(StdCompiler *pComp) // League name pComp->Value(mkNamingAdapt(League, "League", "")); - // player infos - pComp->Value(mkNamingAdapt(PlrInfos, "PlayerInfos")); + // player infos + pComp->Value(mkNamingAdapt(PlrInfos, "PlayerInfos")); } // *** C4LeagueRequestHeadAuthCheck @@ -290,29 +290,29 @@ class DisconnectData // *** C4LeagueClient bool C4LeagueClient::Start(const C4Network2Reference &Ref) - { - // Create query - eCurrAction = C4LA_Start; + { + // Create query + eCurrAction = C4LA_Start; C4LeagueRequestHead Head(eCurrAction); StdStrBuf QueryText = DecompileToBuf( - mkInsertAdapt( - mkNamingAdapt(Head, "Request"), - mkNamingAdapt(mkDecompileAdapt(Ref), "Reference"), - false)); - // Perform query + mkInsertAdapt( + mkNamingAdapt(Head, "Request"), + mkNamingAdapt(mkDecompileAdapt(Ref), "Reference"), + false)); + // Perform query return Query(QueryText.getData(), false); - } + } bool C4LeagueClient::GetStartReply(StdStrBuf *pMessage, StdStrBuf *pLeague, StdStrBuf *pStreamingAddr, int32_t *pSeed, int32_t *pMaxPlayers) - { - if(!isSuccess() || eCurrAction != C4LA_Start) return false; - // Parse response head - C4LeagueResponseHeadStart Head; + { + if(!isSuccess() || eCurrAction != C4LA_Start) return false; + // Parse response head + C4LeagueResponseHeadStart Head; if(!CompileFromBuf_LogWarn(mkNamingAdapt(Head, "Response"), ResultString, "Start Reply")) return false; - // Get message, league and seed - if(pMessage) - pMessage->Copy(Head.getMessage()); + // Get message, league and seed + if(pMessage) + pMessage->Copy(Head.getMessage()); if(pLeague) pLeague->Copy(Head.getLeague()); if(pStreamingAddr) @@ -321,9 +321,9 @@ bool C4LeagueClient::GetStartReply(StdStrBuf *pMessage, StdStrBuf *pLeague, StdS *pSeed = Head.getSeed(); if(pMaxPlayers) *pMaxPlayers = Head.getMaxPlayers(); - // No success? - if(!Head.isSuccess()) - return false; + // No success? + if(!Head.isSuccess()) + return false; // Got no CSID? if(!Head.getCSID() || !*Head.getCSID()) { @@ -331,99 +331,99 @@ bool C4LeagueClient::GetStartReply(StdStrBuf *pMessage, StdStrBuf *pLeague, StdS pMessage->Copy(LoadResStr("IDS_LGA_INVALIDRESPONSE3")); return false; } - // So save back CSID - CSID = Head.getCSID(); - return true; - } + // So save back CSID + CSID = Head.getCSID(); + return true; + } bool C4LeagueClient::Update(const C4Network2Reference &Ref) - { + { assert(CSID.getLength()); - // Create query - eCurrAction = C4LA_Update; + // Create query + eCurrAction = C4LA_Update; C4LeagueRequestHead Head(eCurrAction, CSID.getData()); StdStrBuf QueryText = DecompileToBuf( - mkInsertAdapt( - mkNamingAdapt(Head, "Request"), - mkNamingAdapt(mkDecompileAdapt(Ref), "Reference"), - false)); - // Perform query + mkInsertAdapt( + mkNamingAdapt(Head, "Request"), + mkNamingAdapt(mkDecompileAdapt(Ref), "Reference"), + false)); + // Perform query return Query(QueryText.getData(), false); - } + } bool C4LeagueClient::GetUpdateReply(StdStrBuf *pMessage, C4ClientPlayerInfos *pPlayerLeagueInfos) - { - C4LeagueResponseHeadUpdate Reply; - if(!CompileFromBuf_LogWarn(mkNamingAdapt(Reply, "Response"), ResultString, "Update Reply")) + { + C4LeagueResponseHeadUpdate Reply; + if(!CompileFromBuf_LogWarn(mkNamingAdapt(Reply, "Response"), ResultString, "Update Reply")) return false; - // Get message - if(pMessage) - pMessage->Copy(Reply.getMessage()); - // get plr infos - if (pPlayerLeagueInfos) - *pPlayerLeagueInfos = Reply.GetPlrInfos(); - // Success - return true; - } + // Get message + if(pMessage) + pMessage->Copy(Reply.getMessage()); + // get plr infos + if (pPlayerLeagueInfos) + *pPlayerLeagueInfos = Reply.GetPlrInfos(); + // Success + return true; + } bool C4LeagueClient::End(const C4Network2Reference &Ref, const char *szRecordName, const BYTE *pRecordSHA) - { + { assert(CSID.getLength()); - // Create query - eCurrAction = C4LA_End; + // Create query + eCurrAction = C4LA_End; C4LeagueRequestHeadEnd Head(eCurrAction, CSID.getData(), szRecordName, pRecordSHA); StdStrBuf QueryText = DecompileToBuf( - mkInsertAdapt( - mkNamingAdapt(Head, "Request"), - mkNamingAdapt(mkDecompileAdapt(Ref), "Reference"), - false)); - // Perform query + mkInsertAdapt( + mkNamingAdapt(Head, "Request"), + mkNamingAdapt(mkDecompileAdapt(Ref), "Reference"), + false)); + // Perform query return Query(QueryText.getData(), false); - } + } bool C4LeagueClient::GetEndReply(StdStrBuf *pMessage, C4RoundResultsPlayers *pRoundResults) - { - // Parse response head - C4LeagueResponseHead Head; + { + // Parse response head + C4LeagueResponseHead Head; if(!CompileFromBuf_LogWarn(mkNamingAdapt(Head, "Response"), ResultString, "End Reply")) return false; - // Get message - if(pMessage) - pMessage->Copy(Head.getMessage()); - if(pRoundResults) + // Get message + if(pMessage) + pMessage->Copy(Head.getMessage()); + if(pRoundResults) CompileFromBuf_LogWarn(mkNamingAdapt(mkNamingAdapt(*pRoundResults, "PlayerInfos"), "Response"), ResultString, "Round Results"); - // Done - return Head.isSuccess(); - } + // Done + return Head.isSuccess(); + } bool C4LeagueClient::Auth(const C4PlayerInfo &PlrInfo, const char *szAccount, const char *szPassword, const char *szNewAccount, const char *szNewPassword) { // Build header - eCurrAction = C4LA_PlrAuth; + eCurrAction = C4LA_PlrAuth; C4LeagueRequestHead Head(eCurrAction); Head.SetAuth(szAccount, szPassword); if(szNewAccount) Head.SetNewAccount(szNewAccount); if(szNewPassword) Head.SetNewPassword(szNewPassword); - // Create query + // Create query StdStrBuf QueryText = DecompileToBuf( - mkInsertAdapt( - mkNamingAdapt(Head, "Request"), - mkNamingAdapt(mkDecompileAdapt(PlrInfo), "PlrInfo"), - false)); - // Perform query + mkInsertAdapt( + mkNamingAdapt(Head, "Request"), + mkNamingAdapt(mkDecompileAdapt(PlrInfo), "PlrInfo"), + false)); + // Perform query return Query(QueryText.getData(), false); } bool C4LeagueClient::GetAuthReply(StdStrBuf *pMessage, StdStrBuf *pAUID, StdStrBuf *pAccount, bool *pRegister) { - C4LeagueResponseHead Head; + C4LeagueResponseHead Head; if(!CompileFromBuf_LogWarn(mkNamingAdapt(Head, "Response"), ResultString, "Auth Reply")) return false; - // Get message & account - if(pMessage) - pMessage->Copy(Head.getMessage()); + // Get message & account + if(pMessage) + pMessage->Copy(Head.getMessage()); if(pAccount) pAccount->Copy(Head.getAccount()); if(pRegister) @@ -431,7 +431,7 @@ bool C4LeagueClient::GetAuthReply(StdStrBuf *pMessage, StdStrBuf *pAUID, StdStrB // No success? if(!Head.isSuccess()) return false; - // Check AUID + // Check AUID if(!Head.getAUID() || !*Head.getAUID()) { pMessage->Ref(LoadResStr("IDS_MSG_LEAGUESERVERREPLYWITHOUTA")); @@ -441,29 +441,29 @@ bool C4LeagueClient::GetAuthReply(StdStrBuf *pMessage, StdStrBuf *pAUID, StdStrB if(pAUID) pAUID->Copy(Head.getAUID()); FBIDList.AddFBID(Head.getFBID(), Head.getAccount()); - return true; + return true; } bool C4LeagueClient::AuthCheck(const C4PlayerInfo &PlrInfo) { assert(CSID.getLength()); // Build header - eCurrAction = C4LA_PlrAuthCheck; + eCurrAction = C4LA_PlrAuthCheck; C4LeagueRequestHead Head(eCurrAction, CSID.getData(), PlrInfo.getAuthID()); - // Create query + // Create query StdStrBuf QueryText = DecompileToBuf( - mkInsertAdapt( - mkNamingAdapt(Head, "Request"), - mkNamingAdapt(mkDecompileAdapt(PlrInfo), "PlrInfo"), - false)); - // Perform query + mkInsertAdapt( + mkNamingAdapt(Head, "Request"), + mkNamingAdapt(mkDecompileAdapt(PlrInfo), "PlrInfo"), + false)); + // Perform query return Query(QueryText.getData(), false); } bool C4LeagueClient::GetAuthCheckReply(StdStrBuf *pMessage, const char *szLeague, C4PlayerInfo *pPlrInfo) { - // Parse response head - C4LeagueResponseHeadAuthCheck Head; + // Parse response head + C4LeagueResponseHeadAuthCheck Head; if(!CompileFromBuf_LogWarn(mkNamingAdapt(Head, "Response"), ResultString, "Auth Check Reply")) return false; // Get message and additional data diff --git a/src/network/C4League.h b/src/network/C4League.h index 49f74085d..e569f1a52 100644 --- a/src/network/C4League.h +++ b/src/network/C4League.h @@ -34,30 +34,30 @@ const int32_t C4NetMaxLeagues = 10; enum C4LeagueAction { - C4LA_None, // no action + C4LA_None, // no action - C4LA_Start, // [host] Game registration - C4LA_Update, // [host] Game status update (heartbeat) - C4LA_End, // [host] Final game status - C4LA_PlrAuthCheck,// [host] Player authentication check + C4LA_Start, // [host] Game registration + C4LA_Update, // [host] Game status update (heartbeat) + C4LA_End, // [host] Final game status + C4LA_PlrAuthCheck,// [host] Player authentication check - C4LA_RefQuery, // [client] Query reference list - C4LA_PlrAuth, // [client] Player authentication request + C4LA_RefQuery, // [client] Query reference list + C4LA_PlrAuth, // [client] Player authentication request - C4LA_ReportDisconnect // [both] Sent by host and client when a client is disconnected irregularly + C4LA_ReportDisconnect // [both] Sent by host and client when a client is disconnected irregularly }; class C4LeagueRequestHead - { - public: - C4LeagueRequestHead(C4LeagueAction eAction, const char *szCSID = "", const char *szAUID = "") - : eAction(eAction), CSID(szCSID), AUID(szAUID) - { } + { + public: + C4LeagueRequestHead(C4LeagueAction eAction, const char *szCSID = "", const char *szAUID = "") + : eAction(eAction), CSID(szCSID), AUID(szAUID) + { } - private: - C4LeagueAction eAction; - StdCopyStrBuf CSID; - StdCopyStrBuf AUID; + private: + C4LeagueAction eAction; + StdCopyStrBuf CSID; + StdCopyStrBuf AUID; // Auth StdCopyStrBuf Account; @@ -65,24 +65,24 @@ class C4LeagueRequestHead StdCopyStrBuf NewAccount; StdCopyStrBuf NewPassword; - public: + public: void SetAuth(const char *szAccount, const char *szPassword); void SetNewAccount(const char *szNewAccount); void SetNewPassword(const char *szNewPassword); - void CompileFunc(StdCompiler *pComp); - }; + void CompileFunc(StdCompiler *pComp); + }; class C4LeagueReportDisconnectHead : public C4LeagueRequestHead - { - private: - C4LeagueDisconnectReason eReason; - public: - C4LeagueReportDisconnectHead(const char *szCSID, C4LeagueDisconnectReason eReason) : C4LeagueRequestHead(C4LA_ReportDisconnect, szCSID, NULL), eReason(eReason) {} + { + private: + C4LeagueDisconnectReason eReason; + public: + C4LeagueReportDisconnectHead(const char *szCSID, C4LeagueDisconnectReason eReason) : C4LeagueRequestHead(C4LA_ReportDisconnect, szCSID, NULL), eReason(eReason) {} - public: - void CompileFunc(StdCompiler *pComp); - }; + public: + void CompileFunc(StdCompiler *pComp); + }; class C4LeagueRequestHeadEnd : public C4LeagueRequestHead { @@ -98,36 +98,36 @@ class C4LeagueRequestHeadEnd : public C4LeagueRequestHead StdCopyStrBuf RecordName; uint8_t RecordSHA[SHA_DIGEST_LENGTH]; - public: - void CompileFunc(StdCompiler *pComp); + public: + void CompileFunc(StdCompiler *pComp); }; class C4LeagueResponseHead - { - public: - C4LeagueResponseHead() { } + { + public: + C4LeagueResponseHead() { } - private: - StdCopyStrBuf Status; - StdCopyStrBuf CSID; - StdCopyStrBuf Message; + private: + StdCopyStrBuf Status; + StdCopyStrBuf CSID; + StdCopyStrBuf Message; // Auth StdCopyStrBuf Account; StdCopyStrBuf AUID; StdCopyStrBuf FBID; - public: - const char *getCSID() const { return CSID.getData(); } - const char *getMessage() const { return Message.getData(); } - bool isSuccess() const { return SEqualNoCase(Status.getData(), "Success"); } - bool isStatusRegister() const { return SEqualNoCase(Status.getData(), "Register"); } + public: + const char *getCSID() const { return CSID.getData(); } + const char *getMessage() const { return Message.getData(); } + bool isSuccess() const { return SEqualNoCase(Status.getData(), "Success"); } + bool isStatusRegister() const { return SEqualNoCase(Status.getData(), "Register"); } const char *getAccount() const { return Account.getData(); } const char *getAUID() const { return AUID.getData(); } const char *getFBID() const { return FBID.getData(); } - void CompileFunc(StdCompiler *pComp); - }; + void CompileFunc(StdCompiler *pComp); + }; class C4LeagueResponseHeadStart : public C4LeagueResponseHead { @@ -152,11 +152,11 @@ class C4LeagueResponseHeadUpdate : public C4LeagueResponseHead { private: StdCopyStrBuf League; - C4ClientPlayerInfos PlrInfos; + C4ClientPlayerInfos PlrInfos; public: const char *getLeague() const { return League.getData(); } - const C4ClientPlayerInfos &GetPlrInfos() const { return PlrInfos; } + const C4ClientPlayerInfos &GetPlrInfos() const { return PlrInfos; } void CompileFunc(StdCompiler *pComp); }; @@ -202,30 +202,30 @@ class C4LeagueFBIDList }; class C4LeagueClient : public C4Network2RefClient - { + { - private: - StdCopyStrBuf CSID; - C4LeagueAction eCurrAction; + private: + StdCopyStrBuf CSID; + C4LeagueAction eCurrAction; C4LeagueFBIDList FBIDList; - public: + public: C4LeagueClient() : C4Network2RefClient(), CSID(), eCurrAction(C4LA_None) { } - const char *getCSID() const { return CSID.getData(); } - C4LeagueAction getCurrentAction() const { return eCurrAction; } + const char *getCSID() const { return CSID.getData(); } + C4LeagueAction getCurrentAction() const { return eCurrAction; } void ResetCurrentAction() { eCurrAction = C4LA_None; } - // Action "Start" - bool Start(const C4Network2Reference &Ref); - bool GetStartReply(StdStrBuf *pMessage, StdStrBuf *pLeague, StdStrBuf *pStreamingAddr, int32_t *pSeed, int32_t *pMaxPlayers); + // Action "Start" + bool Start(const C4Network2Reference &Ref); + bool GetStartReply(StdStrBuf *pMessage, StdStrBuf *pLeague, StdStrBuf *pStreamingAddr, int32_t *pSeed, int32_t *pMaxPlayers); - // Action "Update" - bool Update(const C4Network2Reference &Ref); - bool GetUpdateReply(StdStrBuf *pMessage, C4ClientPlayerInfos *pPlayerLeagueInfos); + // Action "Update" + bool Update(const C4Network2Reference &Ref); + bool GetUpdateReply(StdStrBuf *pMessage, C4ClientPlayerInfos *pPlayerLeagueInfos); - // Action "End" - bool End(const C4Network2Reference &Ref, const char *szRecordName, const BYTE *pRecordSHA); - bool GetEndReply(StdStrBuf *pMessage, class C4RoundResultsPlayers *pRoundResults); + // Action "End" + bool End(const C4Network2Reference &Ref, const char *szRecordName, const BYTE *pRecordSHA); + bool GetEndReply(StdStrBuf *pMessage, class C4RoundResultsPlayers *pRoundResults); // Action "Auth" bool Auth(const C4PlayerInfo &PlrInfo, const char *szAccount, const char *szPassword, const char *szNewAccount = NULL, const char *szNewPassword = NULL); @@ -235,10 +235,10 @@ class C4LeagueClient : public C4Network2RefClient bool AuthCheck(const C4PlayerInfo &PlrInfo); bool GetAuthCheckReply(StdStrBuf *pMessage, const char *szLeague, class C4PlayerInfo *pPlrInfo); - // Action "Disconnect" - sent by host and client when one or more clients are disconnected irregularly - bool ReportDisconnect(const C4ClientPlayerInfos &rSendPlayerFBIDs, C4LeagueDisconnectReason eReason); - bool GetReportDisconnectReply(StdStrBuf *pMessage); - }; + // Action "Disconnect" - sent by host and client when one or more clients are disconnected irregularly + bool ReportDisconnect(const C4ClientPlayerInfos &rSendPlayerFBIDs, C4LeagueDisconnectReason eReason); + bool GetReportDisconnectReply(StdStrBuf *pMessage); + }; // dialog shown for each participating player to enter league authentication data class C4LeagueSignupDialog : public C4GUI::Dialog diff --git a/src/network/C4NetIO.cpp b/src/network/C4NetIO.cpp index 30e487aa7..f32f617af 100644 --- a/src/network/C4NetIO.cpp +++ b/src/network/C4NetIO.cpp @@ -134,47 +134,47 @@ const char *GetSocketErrorMsg() } bool HaveSocketError() { - return !! WSAGetLastError(); + return !! WSAGetLastError(); } bool HaveWouldBlockError() { - return WSAGetLastError() == WSAEWOULDBLOCK; + return WSAGetLastError() == WSAEWOULDBLOCK; } bool HaveConnResetError() { - return WSAGetLastError() == WSAECONNRESET; + return WSAGetLastError() == WSAECONNRESET; } void ResetSocketError() { - WSASetLastError(0); + WSASetLastError(0); } static int iWSockUseCounter = 0; bool AcquireWinSock() { - if(!iWSockUseCounter) - { - // initialize winsock - WSADATA data; - int res = WSAStartup(WINSOCK_VERSION, &data); - // success? count - if(!res) - iWSockUseCounter++; - // return result - return !res; - } - // winsock already initialized - iWSockUseCounter++; - return true; + if(!iWSockUseCounter) + { + // initialize winsock + WSADATA data; + int res = WSAStartup(WINSOCK_VERSION, &data); + // success? count + if(!res) + iWSockUseCounter++; + // return result + return !res; + } + // winsock already initialized + iWSockUseCounter++; + return true; } void ReleaseWinSock() { - iWSockUseCounter--; - // last use? - if(!iWSockUseCounter) - WSACleanup(); + iWSockUseCounter--; + // last use? + if(!iWSockUseCounter) + WSACleanup(); } #else @@ -185,24 +185,24 @@ const char *GetSocketErrorMsg(int iError) } const char *GetSocketErrorMsg() { - return GetSocketErrorMsg(errno); + return GetSocketErrorMsg(errno); } bool HaveSocketError() { - return !! errno; + return !! errno; } bool HaveWouldBlockError() { - return errno == EINPROGRESS || errno == EWOULDBLOCK; + return errno == EINPROGRESS || errno == EWOULDBLOCK; } bool HaveConnResetError() { - return errno == ECONNRESET; + return errno == ECONNRESET; } void ResetSocketError() { - errno = 0; + errno = 0; } #endif // HAVE_WINSOCK @@ -297,12 +297,12 @@ bool C4NetIOTCP::Init(uint16_t iPort) if(fInit) Close(); #ifdef HAVE_WINSOCK - // init winsock - if(!AcquireWinSock()) - { - SetError("could not start winsock"); - return false; - } + // init winsock + if(!AcquireWinSock()) + { + SetError("could not start winsock"); + return false; + } #endif #ifdef STDSCHEDULER_USE_EVENTS @@ -376,8 +376,8 @@ bool C4NetIOTCP::Close() #endif #ifdef HAVE_WINSOCK - // release winsock - ReleaseWinSock(); + // release winsock + ReleaseWinSock(); #endif // ok @@ -804,30 +804,30 @@ int C4NetIOTCP::GetNextTick(int Now) // (mt-safe) bool C4NetIOTCP::GetStatistic(int *pBroadcastRate) // (mt-safe) { - // no broadcast - if(pBroadcastRate) *pBroadcastRate = 0; - return true; + // no broadcast + if(pBroadcastRate) *pBroadcastRate = 0; + return true; } bool C4NetIOTCP::GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss) // (mt-safe) { CStdShareLock PeerListLock(&PeerListCSec); // find peer - Peer *pPeer = GetPeer(addr); - if(!pPeer || !pPeer->Open()) return false; - // return statistics - if(pIRate) *pIRate = pPeer->GetIRate(); - if(pORate) *pORate = pPeer->GetORate(); - if(pLoss) *pLoss = 0; - return true; + Peer *pPeer = GetPeer(addr); + if(!pPeer || !pPeer->Open()) return false; + // return statistics + if(pIRate) *pIRate = pPeer->GetIRate(); + if(pORate) *pORate = pPeer->GetORate(); + if(pLoss) *pLoss = 0; + return true; } void C4NetIOTCP::ClearStatistic() { CStdShareLock PeerListLock(&PeerListCSec); // clear all peer statistics - for(Peer *pPeer = pPeerList; pPeer; pPeer = pPeer->Next) - pPeer->ClearStatistics(); + for(Peer *pPeer = pPeerList; pPeer; pPeer = pPeer->Next) + pPeer->ClearStatistics(); } C4NetIOTCP::Peer *C4NetIOTCP::Accept(SOCKET nsock, const addr_t &ConnectAddr) // (mt-safe) @@ -877,9 +877,9 @@ C4NetIOTCP::Peer *C4NetIOTCP::Accept(SOCKET nsock, const addr_t &ConnectAddr) // return NULL; } - // disable nagle (yep, we know what we are doing here - I think) - int iNoDelay = 1; - ::setsockopt(nsock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&iNoDelay), sizeof(iNoDelay)); + // disable nagle (yep, we know what we are doing here - I think) + int iNoDelay = 1; + ::setsockopt(nsock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&iNoDelay), sizeof(iNoDelay)); #ifdef STDSCHEDULER_USE_EVENTS // set event @@ -1179,8 +1179,8 @@ bool C4NetIOTCP::Peer::Send() // (mt-safe) // nothin sent? if(iBytesSent == SOCKET_ERROR || !iBytesSent) return true; - // increase output rate - iORate += iBytesSent + iTCPHeaderSize; + // increase output rate + iORate += iBytesSent + iTCPHeaderSize; // data remaining? if(unsigned(iBytesSent) < OBuf.getSize()) @@ -1271,14 +1271,14 @@ void C4NetIOTCP::Peer::Close() // (mt-safe) // clear buffers IBuf.Clear(); OBuf.Clear(); iIBufUsage = 0; - // reset statistics - iIRate = iORate = 0; + // reset statistics + iIRate = iORate = 0; } void C4NetIOTCP::Peer::ClearStatistics() // (mt-safe) { CStdLock ILock(&ICSec); CStdLock OLock(&OCSec); - iIRate = iORate = 0; + iIRate = iORate = 0; } // *** C4NetIOSimpleUDP @@ -1306,12 +1306,12 @@ bool C4NetIOSimpleUDP::Init(uint16_t inPort) if(fInit) Close(); #ifdef HAVE_WINSOCK - // init winsock - if(!AcquireWinSock()) - { - SetError("could not start winsock"); - return false; - } + // init winsock + if(!AcquireWinSock()) + { + SetError("could not start winsock"); + return false; + } #endif // create socket @@ -1453,10 +1453,10 @@ bool C4NetIOSimpleUDP::Close() #ifdef STDSCHEDULER_USE_EVENTS // close event if(hEvent != NULL) - { + { WSACloseEvent(hEvent); - hEvent = NULL; - } + hEvent = NULL; + } #else // close pipes close(Pipe[0]); @@ -1464,12 +1464,12 @@ bool C4NetIOSimpleUDP::Close() #endif #ifdef HAVE_WINSOCK - // release winsock - ReleaseWinSock(); + // release winsock + ReleaseWinSock(); #endif // ok - fInit = false; + fInit = false; return false; } @@ -1730,7 +1730,7 @@ struct C4NetIOUDP::PacketHdr struct C4NetIOUDP::ConnPacket : public PacketHdr { - uint32_t ProtocolVer; + uint32_t ProtocolVer; C4NetIO::addr_t Addr; C4NetIO::addr_t MCAddr; }; @@ -1932,7 +1932,7 @@ bool C4NetIOUDP::InitBroadcast(addr_t *pBroadcastAddr) // set flags fMultiCast = true; iOPacketCounter = 0; - iBroadcastRate = 0; + iBroadcastRate = 0; // ok return true; @@ -1962,7 +1962,7 @@ bool C4NetIOUDP::Close() #endif // ok - fInit = false; + fInit = false; return fSuccess; } @@ -2098,33 +2098,33 @@ int C4NetIOUDP::GetNextTick(int Now) // (mt-safe) bool C4NetIOUDP::GetStatistic(int *pBroadcastRate) // (mt-safe) { - CStdLock StatLock(&StatCSec); - if(pBroadcastRate) *pBroadcastRate = iBroadcastRate; - return true; + CStdLock StatLock(&StatCSec); + if(pBroadcastRate) *pBroadcastRate = iBroadcastRate; + return true; } bool C4NetIOUDP::GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss) // (mt-safe) { CStdShareLock PeerListLock(&PeerListCSec); // find peer - Peer *pPeer = GetPeer(addr); - if(!pPeer || !pPeer->Open()) return false; - // return statistics - if(pIRate) *pIRate = pPeer->GetIRate(); - if(pORate) *pORate = pPeer->GetORate(); - if(pLoss) *pLoss = 0; - return true; + Peer *pPeer = GetPeer(addr); + if(!pPeer || !pPeer->Open()) return false; + // return statistics + if(pIRate) *pIRate = pPeer->GetIRate(); + if(pORate) *pORate = pPeer->GetORate(); + if(pLoss) *pLoss = 0; + return true; } void C4NetIOUDP::ClearStatistic() { CStdShareLock PeerListLock(&PeerListCSec); // clear all peer statistics - for(Peer *pPeer = pPeerList; pPeer; pPeer = pPeer->Next) - pPeer->ClearStatistics(); - // broadcast statistics - CStdLock StatLock(&StatCSec); - iBroadcastRate = 0; + for(Peer *pPeer = pPeerList; pPeer; pPeer = pPeer->Next) + pPeer->ClearStatistics(); + // broadcast statistics + CStdLock StatLock(&StatCSec); + iBroadcastRate = 0; } void C4NetIOUDP::OnPacket(const C4NetIOPacket &Packet, C4NetIO *pNetIO) @@ -2238,7 +2238,7 @@ C4NetIOUDP::Packet::Packet(C4NetIOPacket RREF rnData, nr_t inNr) C4NetIOUDP::Packet::~Packet() { - delete [] pFragmentGot; pFragmentGot = NULL; + delete [] pFragmentGot; pFragmentGot = NULL; } // implementation @@ -2442,9 +2442,9 @@ bool C4NetIOUDP::PacketList::DeletePacket(Packet *pPacket) void C4NetIOUDP::PacketList::ClearPackets(unsigned int iUntil) { - CStdLock ListLock(&ListCSec); - while(pFront && pFront->GetNr() < iUntil) - DeletePacket(pFront); + CStdLock ListLock(&ListCSec); + while(pFront && pFront->GetNr() < iUntil) + DeletePacket(pFront); } void C4NetIOUDP::PacketList::Clear() @@ -2473,7 +2473,7 @@ C4NetIOUDP::Peer::Peer(const sockaddr_in &naddr, C4NetIOUDP *pnParent) iIMCPacketCounter(0), iRIMCPacketCounter(0), iMCAckPacketCounter(0), iNextReCheck(0), - iIRate(0), iORate(0), iLoss(0) + iIRate(0), iORate(0), iLoss(0) { ZeroMem(&addr2, sizeof(addr2)); ZeroMem(&PeerAddr, sizeof(PeerAddr)); @@ -2543,8 +2543,8 @@ bool C4NetIOUDP::Peer::Check(bool fForceCheck) void C4NetIOUDP::Peer::OnRecv(const C4NetIOPacket &rPacket) // (mt-safe) { - // statistics - { CStdLock StatLock(&StatCSec); iIRate += rPacket.getSize() + iUDPHeaderSize; } + // statistics + { CStdLock StatLock(&StatCSec); iIRate += rPacket.getSize() + iUDPHeaderSize; } // get packet header if(rPacket.getSize() < sizeof(PacketHdr)) return; const PacketHdr *pHdr = getBufPtr(rPacket); @@ -2565,8 +2565,8 @@ void C4NetIOUDP::Peer::OnRecv(const C4NetIOPacket &rPacket) // (mt-safe) // check size if(rPacket.getSize() != sizeof(ConnPacket)) break; const ConnPacket *pPkt = getBufPtr(rPacket); - // right version? - if(pPkt->ProtocolVer != pParent->iVersion) break; + // right version? + if(pPkt->ProtocolVer != pParent->iVersion) break; if(!fBroadcasted) { // Second connection attempt using different address? @@ -2695,14 +2695,14 @@ void C4NetIOUDP::Peer::OnRecv(const C4NetIOPacket &rPacket) // (mt-safe) const CheckPacketHdr *pPkt = getBufPtr(rPacket); // check packet size if(rPacket.getSize() < sizeof(CheckPacketHdr) + (pPkt->AskCount + pPkt->MCAskCount) * sizeof(int)) break; - // clear all acknowledged packets + // clear all acknowledged packets CStdLock OutLock(&OutCSec); - OPackets.ClearPackets(pPkt->AckNr); - if(pPkt->MCAckNr > iMCAckPacketCounter) - { - iMCAckPacketCounter = pPkt->MCAckNr; - pParent->ClearMCPackets(); - } + OPackets.ClearPackets(pPkt->AckNr); + if(pPkt->MCAckNr > iMCAckPacketCounter) + { + iMCAckPacketCounter = pPkt->MCAckNr; + pParent->ClearMCPackets(); + } OutLock.Clear(); // read ask list const int *pAskList = getBufPtr(rPacket, sizeof(CheckPacketHdr)); @@ -2714,7 +2714,7 @@ void C4NetIOUDP::Peer::OnRecv(const C4NetIOPacket &rPacket) // (mt-safe) bool fMCPacket = i >= pPkt->AskCount; CStdLock OutLock(fMCPacket ? &pParent->OutCSec : &OutCSec); Packet *pPkt2Send = (fMCPacket ? pParent->OPackets : OPackets).GetPacketFrgm(pAskList[i]); - if(!pPkt2Send) { Close("starvation"); break; } + if(!pPkt2Send) { Close("starvation"); break; } // send the fragment if(fMCPacket) pParent->BroadcastDirect(*pPkt2Send, pAskList[i]); @@ -2766,9 +2766,9 @@ void C4NetIOUDP::Peer::CheckTimeout() void C4NetIOUDP::Peer::ClearStatistics() { - CStdLock StatLock(&StatCSec); - iIRate = iORate = 0; - iLoss = 0; + CStdLock StatLock(&StatCSec); + iIRate = iORate = 0; + iLoss = 0; } bool C4NetIOUDP::Peer::DoConn(bool fMC) // (mt-safe) @@ -2780,7 +2780,7 @@ bool C4NetIOUDP::Peer::DoConn(bool fMC) // (mt-safe) // send packet (include current outgoing packet counter and mc addr) ConnPacket Pkt; Pkt.StatusByte = uint8_t(IPID_Conn) | (fMC ? 0x80 : 0x00); - Pkt.ProtocolVer = pParent->iVersion; + Pkt.ProtocolVer = pParent->iVersion; Pkt.Nr = fMC ? pParent->iOPacketCounter : iOPacketCounter; Pkt.Addr = addr; if(pParent->fMultiCast) @@ -2794,8 +2794,8 @@ bool C4NetIOUDP::Peer::DoCheck(int iAskCnt, int iMCAskCnt, unsigned int *pAskLis { // security if(!pAskList) iAskCnt = iMCAskCnt = 0; - // statistics - { CStdLock StatLock(&StatCSec); iLoss += iAskCnt + iMCAskCnt; } + // statistics + { CStdLock StatLock(&StatCSec); iLoss += iAskCnt + iMCAskCnt; } // alloc data int iAskListSize = (iAskCnt + iMCAskCnt) * sizeof(*pAskList); StdBuf Packet; Packet.New(sizeof(CheckPacketHdr) + iAskListSize); @@ -2803,8 +2803,8 @@ bool C4NetIOUDP::Peer::DoCheck(int iAskCnt, int iMCAskCnt, unsigned int *pAskLis // set up header pChkPkt->StatusByte = IPID_Check; // (note: always du here, see C4NetIOUDP::DoCheck) pChkPkt->Nr = iOPacketCounter; - pChkPkt->AckNr = iIPacketCounter; - pChkPkt->MCAckNr = iIMCPacketCounter; + pChkPkt->AckNr = iIPacketCounter; + pChkPkt->MCAckNr = iIMCPacketCounter; // copy ask list pChkPkt->AskCount = iAskCnt; pChkPkt->MCAskCount = iMCAskCnt; @@ -2830,10 +2830,10 @@ bool C4NetIOUDP::Peer::SendDirect(C4NetIOPacket RREF rPacket) // (mt-safe) { // insert correct addr if(!(rPacket.getStatus() & 0x80)) rPacket.SetAddr(addr); - // count outgoing - { CStdLock StatLock(&StatCSec); iORate += rPacket.getSize() + iUDPHeaderSize; } + // count outgoing + { CStdLock StatLock(&StatCSec); iORate += rPacket.getSize() + iUDPHeaderSize; } // forward call - return pParent->SendDirect(std::move(rPacket)); + return pParent->SendDirect(std::move(rPacket)); } void C4NetIOUDP::Peer::OnConn() @@ -2878,8 +2878,8 @@ void C4NetIOUDP::Peer::CheckCompleteIPackets() Packet *pPkt; while((pPkt = IPackets.GetFirstPacketComplete())) { - // missing packet? - if(pPkt->GetNr() != iIPacketCounter) break; + // missing packet? + if(pPkt->GetNr() != iIPacketCounter) break; // do callback if(pParent->pCB) pParent->pCB->OnPacket(pPkt->GetData(), pParent); @@ -2892,8 +2892,8 @@ void C4NetIOUDP::Peer::CheckCompleteIPackets() } while((pPkt = IMCPackets.GetFirstPacketComplete())) { - // missing packet? - if(pPkt->GetNr() != iIMCPacketCounter) break; + // missing packet? + if(pPkt->GetNr() != iIMCPacketCounter) break; // do callback if(pParent->pCB) pParent->pCB->OnPacket(pPkt->GetData(), pParent); @@ -2956,13 +2956,13 @@ bool C4NetIOUDP::SendDirect(C4NetIOPacket RREF rPacket) // (mt-safe) addr_t toaddr = rPacket.getAddr(); // packet meant to be broadcasted? if(rPacket.getStatus() & 0x80) - { + { // set addr toaddr = C4NetIOSimpleUDP::getMCAddr(); - // statistics - CStdLock StatLock(&StatCSec); - iBroadcastRate += rPacket.getSize() + iUDPHeaderSize; - } + // statistics + CStdLock StatLock(&StatCSec); + iBroadcastRate += rPacket.getSize() + iUDPHeaderSize; + } // debug #ifdef C4NETIO_DEBUG @@ -2970,8 +2970,8 @@ bool C4NetIOUDP::SendDirect(C4NetIOPacket RREF rPacket) // (mt-safe) #endif #ifdef C4NETIO_SIMULATE_PACKETLOSS - if((rPacket.getStatus() & 0x7F) != IPID_Test) - if(SafeRandom(100) < C4NETIO_SIMULATE_PACKETLOSS) return true; + if((rPacket.getStatus() & 0x7F) != IPID_Test) + if(SafeRandom(100) < C4NETIO_SIMULATE_PACKETLOSS) return true; #endif // send it @@ -3019,20 +3019,20 @@ bool C4NetIOUDP::DoLoopbackTest() void C4NetIOUDP::ClearMCPackets() { - CStdShareLock PeerListLock(&PeerListCSec); - CStdLock OutLock(&OutCSec); - // clear packets if no client is present - if(!pPeerList) - OPackets.Clear(); - else - { - // find minimum acknowledged packet number - unsigned int iAckNr = pPeerList->GetMCAckPacketCounter(); - for(Peer *pPeer = pPeerList->Next; pPeer; pPeer = pPeer->Next) - iAckNr = Min(iAckNr, pPeerList->GetMCAckPacketCounter()); - // clear packets - OPackets.ClearPackets(iAckNr); - } + CStdShareLock PeerListLock(&PeerListCSec); + CStdLock OutLock(&OutCSec); + // clear packets if no client is present + if(!pPeerList) + OPackets.Clear(); + else + { + // find minimum acknowledged packet number + unsigned int iAckNr = pPeerList->GetMCAckPacketCounter(); + for(Peer *pPeer = pPeerList->Next; pPeer; pPeer = pPeer->Next) + iAckNr = Min(iAckNr, pPeerList->GetMCAckPacketCounter()); + // clear packets + OPackets.ClearPackets(iAckNr); + } } void C4NetIOUDP::AddPeer(Peer *pPeer) @@ -3084,17 +3084,17 @@ C4NetIOUDP::Peer *C4NetIOUDP::GetPeer(const addr_t &addr) C4NetIOUDP::Peer *C4NetIOUDP::ConnectPeer(const addr_t &PeerAddr, bool fFailCallback) // (mt-safe) { CStdShareLock PeerListLock(&PeerListCSec); - // lock so no new peer can be added after this point - CStdLock PeerListAddLock(&PeerListAddCSec); - // recheck: address already known? - Peer *pnPeer = GetPeer(PeerAddr); - if(pnPeer) return pnPeer; - // create new Peer class + // lock so no new peer can be added after this point + CStdLock PeerListAddLock(&PeerListAddCSec); + // recheck: address already known? + Peer *pnPeer = GetPeer(PeerAddr); + if(pnPeer) return pnPeer; + // create new Peer class pnPeer = new Peer(PeerAddr, this); if(!pnPeer) return NULL; // add peer to list AddPeer(pnPeer); - PeerListAddLock.Clear(); + PeerListAddLock.Clear(); // send connection request if(!pnPeer->Connect(fFailCallback)) { pnPeer->Close("connect failed"); return NULL; } // ok (do not wait for peer) @@ -3333,26 +3333,26 @@ bool ResolveAddress(const char *szAddress, C4NetIO::addr_t *paddr, uint16_t iPor raddr.sin_family = AF_INET; raddr.sin_port = htons(iPort); // no plain IP address? - if((raddr.sin_addr.s_addr = inet_addr(szAddress)) == INADDR_NONE) - { + if((raddr.sin_addr.s_addr = inet_addr(szAddress)) == INADDR_NONE) + { #ifdef HAVE_WINSOCK if(!AcquireWinSock()) return false; #endif - // resolve - hostent *pHost; - if(!(pHost = gethostbyname(szAddress))) + // resolve + hostent *pHost; + if(!(pHost = gethostbyname(szAddress))) #ifdef HAVE_WINSOCK { ReleaseWinSock(); return false; } ReleaseWinSock(); #else - return false; -#endif - // correct type? - if(pHost->h_addrtype != AF_INET || pHost->h_length != sizeof(in_addr)) return false; - // get address - raddr.sin_addr = *reinterpret_cast(pHost->h_addr_list[0]); - } +#endif + // correct type? + if(pHost->h_addrtype != AF_INET || pHost->h_length != sizeof(in_addr)) + return false; + // get address + raddr.sin_addr = *reinterpret_cast(pHost->h_addr_list[0]); + } // ok *paddr = raddr; return true; diff --git a/src/network/C4NetIO.h b/src/network/C4NetIO.h index b775d798f..0a7bbe36f 100644 --- a/src/network/C4NetIO.h +++ b/src/network/C4NetIO.h @@ -119,10 +119,10 @@ public: virtual bool SetBroadcast(const addr_t &addr, bool fSet = true) = 0; virtual bool Broadcast(const class C4NetIOPacket &rPacket) = 0; - // statistics - virtual bool GetStatistic(int *pBroadcastRate) = 0; - virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss) = 0; - virtual void ClearStatistic() = 0; + // statistics + virtual bool GetStatistic(int *pBroadcastRate) = 0; + virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss) = 0; + virtual void ClearStatistic() = 0; // *** errors protected: @@ -155,7 +155,7 @@ public: protected: - // address + // address C4NetIO::addr_t addr; public: @@ -165,12 +165,12 @@ public: uint8_t getStatus()const { return getSize() ? *getBufPtr(*this) : 0; } const char *getPData() const { return getSize() ? getBufPtr(*this, 1) : NULL; } size_t getPSize() const { return getSize() ? getSize() - 1 : 0; } - StdBuf getPBuf() const { return getSize() ? getPart(1, getSize() - 1) : getRef(); } + StdBuf getPBuf() const { return getSize() ? getPart(1, getSize() - 1) : getRef(); } // Some overloads C4NetIOPacket getRef() const { return C4NetIOPacket(StdBuf::getRef(), addr); } C4NetIOPacket Duplicate() const { return C4NetIOPacket(StdBuf::Duplicate(), addr); } - // change addr + // change addr void SetAddr(const C4NetIO::addr_t &naddr) { addr = naddr; } // delete contents @@ -213,10 +213,10 @@ public: #endif virtual int GetNextTick(int Now); - // statistics - virtual bool GetStatistic(int *pBroadcastRate); - virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss); - virtual void ClearStatistic(); + // statistics + virtual bool GetStatistic(int *pBroadcastRate); + virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss); + virtual void ClearStatistic(); protected: @@ -238,9 +238,9 @@ protected: Peer(const C4NetIO::addr_t &naddr, SOCKET nsock, C4NetIOTCP *pnParent); ~Peer(); protected: - // constants - static const unsigned int iTCPHeaderSize; // = 28 + 24; // (bytes) - static const unsigned int iMinIBufSize; // = 8192; // (bytes) + // constants + static const unsigned int iTCPHeaderSize; // = 28 + 24; // (bytes) + static const unsigned int iMinIBufSize; // = 8192; // (bytes) // parent C4NetIOTCP *const pParent; // addr @@ -250,8 +250,8 @@ protected: // incoming & outgoing buffer StdBuf IBuf, OBuf; int iIBufUsage; - // statistics - int iIRate, iORate; + // statistics + int iIRate, iORate; // status (1 = open, 0 = closed) bool fOpen; // selected for broadcast? @@ -262,8 +262,8 @@ protected: // data access const C4NetIO::addr_t &GetAddr() const { return addr; } SOCKET GetSocket() const { return sock; } - int GetIRate() const { return iIRate; } - int GetORate() const { return iORate; } + int GetIRate() const { return iIRate; } + int GetORate() const { return iORate; } // send a packet to this peer bool Send(const C4NetIOPacket &rPacket); // send as much data of the interal outgoing buffer as possible @@ -282,8 +282,8 @@ protected: bool hasWaitingData() const { return !OBuf.isNull(); } // select/unselect peer void SetBroadcast(bool fSet) { fDoBroadcast = fSet; } - // statistics - void ClearStatistics(); + // statistics + void ClearStatistics(); public: // next peer Peer *Next; @@ -375,9 +375,9 @@ public: virtual bool SetBroadcast(const addr_t &addr, bool fSet = true) { assert(false); return false; } virtual bool GetStatistic(int *pBroadcastRate) { assert(false); return false; } - virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss) + virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss) { assert(false); return false; } - virtual void ClearStatistic() { assert(false); } + virtual void ClearStatistic() { assert(false); } private: // status @@ -455,9 +455,9 @@ public: virtual int GetNextTick(int Now); - virtual bool GetStatistic(int *pBroadcastRate); - virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss); - virtual void ClearStatistic(); + virtual bool GetStatistic(int *pBroadcastRate); + virtual bool GetConnStatistic(const addr_t &addr, int *pIRate, int *pORate, int *pLoss); + virtual void ClearStatistic(); protected: @@ -483,12 +483,12 @@ protected: // constants static const unsigned int iVersion; // = 2; - static const unsigned int iStdTimeout, // = 1000, // (ms) + static const unsigned int iStdTimeout, // = 1000, // (ms) iCheckInterval; // = 1000 // (ms) static const unsigned int iMaxOPacketBacklog; // = 100; - static const unsigned int iUDPHeaderSize; // = 8 + 24; // (bytes) + static const unsigned int iUDPHeaderSize; // = 8 + 24; // (bytes) // packet class class PacketList; @@ -609,7 +609,7 @@ protected: unsigned int iIPacketCounter, iRIPacketCounter; unsigned int iIMCPacketCounter, iRIMCPacketCounter; - unsigned int iMCAckPacketCounter; + unsigned int iMCAckPacketCounter; // output critical section CStdCSec OutCSec; @@ -622,11 +622,11 @@ protected: unsigned int iTimeout; unsigned int iRetries; - // statistics - int iIRate, iORate, iLoss; + // statistics + int iIRate, iORate, iLoss; CStdCSec StatCSec; - public: + public: // data access const C4NetIO::addr_t &GetAddr() const { return addr; } const C4NetIO::addr_t &GetAltAddr() const { return addr2; } @@ -651,8 +651,8 @@ protected: // multicast support? bool MultiCast() const { return fMultiCast; } - // acknowledgment check - unsigned int GetMCAckPacketCounter() const { return iMCAckPacketCounter; } + // acknowledgment check + unsigned int GetMCAckPacketCounter() const { return iMCAckPacketCounter; } // timeout checking int GetTimeout() { return iTimeout; } @@ -666,11 +666,11 @@ protected: // alternate address void SetAltAddr(const C4NetIO::addr_t &naddr2) { addr2 = naddr2; } - // statistics - int GetIRate() const { return iIRate; } - int GetORate() const { return iORate; } - int GetLoss() const { return iLoss; } - void ClearStatistics(); + // statistics + int GetIRate() const { return iIRate; } + int GetORate() const { return iORate; } + int GetLoss() const { return iLoss; } + void ClearStatistics(); protected: @@ -727,9 +727,9 @@ protected: PacketList OPackets; unsigned int iOPacketCounter; - // statistics - int iBroadcastRate; - CStdCSec StatCSec; + // statistics + int iBroadcastRate; + CStdCSec StatCSec; // callback proxy NETIO_CREATE_CALLBACK_PROXY(C4NetIOUDP, CBProxy) @@ -742,7 +742,7 @@ protected: // multicast related bool DoLoopbackTest(); - void ClearMCPackets(); + void ClearMCPackets(); // peer list void AddPeer(Peer *pPeer); @@ -823,23 +823,23 @@ inline uint8_t &in_addr_b(in_addr &addr, int i) { inline void CompileFunc(in_addr &ip, StdCompiler *pComp) { - pComp->Value(in_addr_b(ip, 0)); pComp->Seperator(StdCompiler::SEP_PART); - pComp->Value(in_addr_b(ip, 1)); pComp->Seperator(StdCompiler::SEP_PART); - pComp->Value(in_addr_b(ip, 2)); pComp->Seperator(StdCompiler::SEP_PART); - pComp->Value(in_addr_b(ip, 3)); + pComp->Value(in_addr_b(ip, 0)); pComp->Seperator(StdCompiler::SEP_PART); + pComp->Value(in_addr_b(ip, 1)); pComp->Seperator(StdCompiler::SEP_PART); + pComp->Value(in_addr_b(ip, 2)); pComp->Seperator(StdCompiler::SEP_PART); + pComp->Value(in_addr_b(ip, 3)); } inline void CompileFunc(C4NetIO::addr_t &addr, StdCompiler *pComp) { pComp->Value(addr.sin_addr); pComp->Seperator(StdCompiler::SEP_PART2); - uint16_t iPort = htons(addr.sin_port); - pComp->Value(iPort); - addr.sin_port = htons(iPort); - if(pComp->isCompiler()) - { - addr.sin_family = AF_INET; - ZeroMem(addr.sin_zero, sizeof(addr.sin_zero)); - } + uint16_t iPort = htons(addr.sin_port); + pComp->Value(iPort); + addr.sin_port = htons(iPort); + if(pComp->isCompiler()) + { + addr.sin_family = AF_INET; + ZeroMem(addr.sin_zero, sizeof(addr.sin_zero)); + } } #ifdef HAVE_WINSOCK diff --git a/src/network/C4Network2.cpp b/src/network/C4Network2.cpp index 64e97abc5..670ce8ce7 100644 --- a/src/network/C4Network2.cpp +++ b/src/network/C4Network2.cpp @@ -126,8 +126,8 @@ void C4Network2Status::CompileFunc(StdCompiler *pComp, bool fReference) { "Paused", GS_Pause }, { "Running", GS_Go }, }; - pComp->Value(mkNamingAdapt(mkEnumAdaptT(eState, GameStates), "State", GS_None)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iCtrlMode), "CtrlMode", -1)); + pComp->Value(mkNamingAdapt(mkEnumAdaptT(eState, GameStates), "State", GS_None)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iCtrlMode), "CtrlMode", -1)); if(!fReference) pComp->Value(mkNamingAdapt(mkIntPackAdapt(iTargetCtrlTick), "TargetTick", -1)); @@ -190,9 +190,9 @@ bool C4Network2::InitHost(bool fLobby) // init network control pControl = &::Control.Network; pControl->Init(C4ClientIDHost, true, ::Control.getNextControlTick(), true, this); - // init league + // init league bool fCancel = true; - if(!InitLeague(&fCancel) || !LeagueStart(&fCancel)) + if(!InitLeague(&fCancel) || !LeagueStart(&fCancel)) { // deinit league DeinitLeague(); @@ -204,8 +204,8 @@ bool C4Network2::InitHost(bool fLobby) return false; #endif } - // allow connect - NetIO.SetAcceptMode(true); + // allow connect + NetIO.SetAcceptMode(true); // timer Application.Add(this); // ok @@ -265,15 +265,15 @@ C4Network2::InitResult C4Network2::InitClient(const C4Network2Reference &Ref, bo // initialize ressources if(!Game.Parameters.InitNetwork(&ResList)) return IR_Fatal; - // init league - if(!InitLeague(NULL)) + // init league + if(!InitLeague(NULL)) { // deinit league DeinitLeague(); return IR_Fatal; } - // allow connect - NetIO.SetAcceptMode(true); + // allow connect + NetIO.SetAcceptMode(true); // timer Application.Add(this); // ok, success @@ -356,8 +356,8 @@ bool C4Network2::DoLobby() // lobby runs fLobbyRunning = true; - fAllowJoin = true; - Log(LoadResStr("IDS_NET_LOBBYWAITING")); + fAllowJoin = true; + Log(LoadResStr("IDS_NET_LOBBYWAITING")); // client: lobby status reached, message to host if(!isHost()) @@ -412,7 +412,7 @@ bool C4Network2::DoLobby() // lobby end delete pLobbyCountdown; pLobbyCountdown = NULL; fLobbyRunning = false; - fAllowJoin = !Config.Network.NoRuntimeJoin; + fAllowJoin = !Config.Network.NoRuntimeJoin; // notify user that the lobby has ended (for people who tasked out) Application.NotifyUserIfInactive(); @@ -502,10 +502,10 @@ bool C4Network2::FinalInit() // log Log(LoadResStr("IDS_NET_START")); } - // synchronize - Game.SyncClearance(); - Game.Synchronize(false); - // finished + // synchronize + Game.SyncClearance(); + Game.Synchronize(false); + // finished return isEnabled(); } @@ -517,7 +517,7 @@ bool C4Network2::RetrieveScenario(char *szScenario) // wait for scenario C4Network2Res::Ref pScenario = RetrieveRes(*Game.Parameters.Scenario.getResCore(), - C4NetResRetrieveTimeout, LoadResStr("IDS_NET_RES_SCENARIO")); + C4NetResRetrieveTimeout, LoadResStr("IDS_NET_RES_SCENARIO")); if(!pScenario) return false; @@ -585,10 +585,10 @@ void C4Network2::Execute() RemoveDynamic(); // Set chase target UpdateChaseTarget(); - // check for inactive clients and deactivate them - DeactivateInactiveClients(); - // reference - if(!iLastReferenceUpdate || time(NULL) > (time_t) (iLastReferenceUpdate + C4NetReferenceUpdateInterval)) + // check for inactive clients and deactivate them + DeactivateInactiveClients(); + // reference + if(!iLastReferenceUpdate || time(NULL) > (time_t) (iLastReferenceUpdate + C4NetReferenceUpdateInterval)) if (NetIO.IsReferenceNeeded()) { // create @@ -598,15 +598,15 @@ void C4Network2::Execute() NetIO.SetReference(pRef); iLastReferenceUpdate = time(NULL); } - // league server reference - if(!iLastLeagueUpdate || time(NULL) > (time_t) (iLastLeagueUpdate + iLeagueUpdateDelay)) - { - LeagueUpdate(); - } + // league server reference + if(!iLastLeagueUpdate || time(NULL) > (time_t) (iLastLeagueUpdate + iLeagueUpdateDelay)) + { + LeagueUpdate(); + } // league update reply receive if(pLeagueClient && fHost && !pLeagueClient->isBusy() && pLeagueClient->getCurrentAction() == C4LA_Update) { - LeagueUpdateProcessReply(); + LeagueUpdateProcessReply(); } // voting timeout if(Votes.firstPkt() && time(NULL) > (time_t) (iVoteStartTime + C4NetVotingTimeout)) @@ -625,11 +625,11 @@ void C4Network2::Execute() StreamOut(); } } - else - { - // request activate, if neccessary - if(iLastActivateRequest) RequestActivate(); - } + else + { + // request activate, if neccessary + if(iLastActivateRequest) RequestActivate(); + } } void C4Network2::Clear() @@ -667,8 +667,8 @@ void C4Network2::Clear() sPassword.Clear(); // stuff fAllowJoin = false; - iDynamicTick = -1; fDynamicNeeded = false; - iLastActivateRequest = iLastChaseTargetUpdate = iLastReferenceUpdate = iLastLeagueUpdate = 0; + iDynamicTick = -1; fDynamicNeeded = false; + iLastActivateRequest = iLastChaseTargetUpdate = iLastReferenceUpdate = iLastLeagueUpdate = 0; fDelayedActivateReq = false; if(::pGUI) delete pVoteDialog; pVoteDialog = NULL; fPausedForVote = false; @@ -733,16 +733,16 @@ void C4Network2::AllowJoin(bool fAllow) void C4Network2::SetAllowObserve(bool fAllow) { if(!isHost()) return; - fAllowObserve = fAllow; + fAllowObserve = fAllow; } void C4Network2::SetCtrlMode(int32_t iCtrlMode) { if(!isHost()) return; - // no change? - if(iCtrlMode == Status.getCtrlMode()) return; - // change game status - ChangeGameStatus(Status.getState(), ::Control.ControlTick, iCtrlMode); + // no change? + if(iCtrlMode == Status.getCtrlMode()) return; + // change game status + ChangeGameStatus(Status.getState(), ::Control.ControlTick, iCtrlMode); } void C4Network2::OnConn(C4Network2IOConnection *pConn) @@ -755,7 +755,7 @@ void C4Network2::OnConn(C4Network2IOConnection *pConn) void C4Network2::OnDisconn(C4Network2IOConnection *pConn) { - // could not establish host connection? + // could not establish host connection? if(Status.getState() == GS_Init && !isHost()) { if(!NetIO.getConnectionCount()) @@ -826,16 +826,16 @@ void C4Network2::HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Netwo } break; - case PID_JoinData: - { - // host->client only - if(isHost() || !pClient || !pClient->isHost()) break; + case PID_JoinData: + { + // host->client only + if(isHost() || !pClient || !pClient->isHost()) break; if(!pConn->isOpen()) break; - // handle - GETPKT(C4PacketJoinData, rPkt) - HandleJoinData(rPkt); - } - break; + // handle + GETPKT(C4PacketJoinData, rPkt) + HandleJoinData(rPkt); + } + break; case PID_Status: // status change { @@ -863,17 +863,17 @@ void C4Network2::HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Netwo } break; - case PID_ClientActReq: // client activation request - { - // client->host only - if(!isHost() || !pClient || pClient->isHost()) break; + case PID_ClientActReq: // client activation request + { + // client->host only + if(!isHost() || !pClient || pClient->isHost()) break; // must be initialized if(Status.getState() == GS_Init) break; - // handle - GETPKT(C4PacketActivateReq, rPkt) - HandleActivateReq(rPkt.getTick(), pClient); - } - break; + // handle + GETPKT(C4PacketActivateReq, rPkt) + HandleActivateReq(rPkt.getTick(), pClient); + } + break; } @@ -917,7 +917,7 @@ void C4Network2::DrawStatus(C4TargetFacet &cgo) C4Network2Client *pLocal = Clients.GetLocal(); - StdStrBuf Stat; + StdStrBuf Stat; // local client status Stat.AppendFormat("Local: %s %s %s (ID %d)", @@ -933,8 +933,8 @@ void C4Network2::DrawStatus(C4TargetFacet &cgo) C4NetIO *pMsgIO = NetIO.MsgIO(), *pDataIO = NetIO.DataIO(); if(pMsgIO && pDataIO) { - C4Network2IOProtocol eMsgProt = NetIO.getNetIOProt(pMsgIO), - eDataProt = NetIO.getNetIOProt(pDataIO); + C4Network2IOProtocol eMsgProt = NetIO.getNetIOProt(pMsgIO), + eDataProt = NetIO.getNetIOProt(pDataIO); int32_t iMsgPort = 0, iDataPort = 0; switch(eMsgProt) { case P_TCP: iMsgPort = Config.Network.PortTCP; break; @@ -948,22 +948,22 @@ void C4Network2::DrawStatus(C4TargetFacet &cgo) case P_NONE: assert(eMsgProt != P_NONE); break; } Stat.AppendFormat( "|Protocols: %s: %s (%d i%d o%d bc%d)", - pMsgIO != pDataIO ? "Msg" : "Msg/Data", + pMsgIO != pDataIO ? "Msg" : "Msg/Data", NetIO.getNetIOName(pMsgIO), iMsgPort, - NetIO.getProtIRate(eMsgProt), NetIO.getProtORate(eMsgProt), NetIO.getProtBCRate(eMsgProt)); - if(pMsgIO != pDataIO) - Stat.AppendFormat( ", Data: %s (%d i%d o%d bc%d)", - NetIO.getNetIOName(pDataIO), iDataPort, - NetIO.getProtIRate(eDataProt), NetIO.getProtORate(eDataProt), NetIO.getProtBCRate(eDataProt)); + NetIO.getProtIRate(eMsgProt), NetIO.getProtORate(eMsgProt), NetIO.getProtBCRate(eMsgProt)); + if(pMsgIO != pDataIO) + Stat.AppendFormat( ", Data: %s (%d i%d o%d bc%d)", + NetIO.getNetIOName(pDataIO), iDataPort, + NetIO.getProtIRate(eDataProt), NetIO.getProtORate(eDataProt), NetIO.getProtBCRate(eDataProt)); } else Stat.Append("|Protocols: none"); // some control statistics Stat.AppendFormat( "|Control: %s, Tick %d, Behind %d, Rate %d, PreSend %d, ACT: %d", - Status.getCtrlMode() == CNM_Decentral ? "Decentral" : Status.getCtrlMode() == CNM_Central ? "Central" : "Async", + Status.getCtrlMode() == CNM_Decentral ? "Decentral" : Status.getCtrlMode() == CNM_Central ? "Central" : "Async", ::Control.ControlTick, pControl->GetBehind(::Control.ControlTick), - ::Control.ControlRate, pControl->getControlPreSend(), pControl->getAvgControlSendTime()); + ::Control.ControlRate, pControl->getControlPreSend(), pControl->getAvgControlSendTime()); // Streaming statistics if(fStreaming) @@ -993,9 +993,9 @@ void C4Network2::DrawStatus(C4TargetFacet &cgo) Stat.AppendFormat( "|- %s %s %s (ID %d) (wait %d ms, behind %d)%s%s", Core.isObserver() ? "Observing" : Core.isActivated() ? "Active" : "Inactive", Core.isHost() ? "host" : "client", Core.getName(), Core.getID(), - pControl->ClientPerfStat(pClient->getID()), - ::Control.ControlTick - pControl->ClientNextControl(pClient->getID()), - szClientStatus, + pControl->ClientPerfStat(pClient->getID()), + ::Control.ControlTick - pControl->ClientNextControl(pClient->getID()), + szClientStatus, pClient->isActivated() && !pControl->ClientReady(pClient->getID(), ::Control.ControlTick) ? " (!ctrl)" : ""); // connections if(pClient->isConnected()) @@ -1006,14 +1006,14 @@ void C4Network2::DrawStatus(C4TargetFacet &cgo) inet_ntoa(pClient->getMsgConn()->getPeerAddr().sin_addr), htons(pClient->getMsgConn()->getPeerAddr().sin_port), pClient->getMsgConn()->getPingTime(), - pClient->getMsgConn()->getPacketLoss()); + pClient->getMsgConn()->getPacketLoss()); if(pClient->getMsgConn() != pClient->getDataConn()) Stat.AppendFormat( ", Data: %s (%s:%d p%d l%d)", NetIO.getNetIOName(pClient->getDataConn()->getNetClass()), inet_ntoa(pClient->getDataConn()->getPeerAddr().sin_addr), htons(pClient->getDataConn()->getPeerAddr().sin_port), pClient->getDataConn()->getPingTime(), - pClient->getDataConn()->getPacketLoss()); + pClient->getDataConn()->getPacketLoss()); } else Stat.Append("| Not connected"); @@ -1084,7 +1084,7 @@ void C4Network2::HandleConn(const C4PacketConn &Pkt, C4Network2IOConnection *pCo if(pClient) if(CheckConn(NewCCore, pConn, pClient, reply.getData())) { - // accept + // accept if(!reply) reply = "connection accepted"; fOK = true; } @@ -1092,7 +1092,7 @@ void C4Network2::HandleConn(const C4PacketConn &Pkt, C4Network2IOConnection *pCo if(!fOK && !isHost() && Status.getState() == GS_Init && !Clients.GetHost()) if(HostConnect(NewCCore, pConn, reply.getData())) { - // accept + // accept if(!reply) reply = "host connection accepted"; fOK = true; } @@ -1113,9 +1113,9 @@ void C4Network2::HandleConn(const C4PacketConn &Pkt, C4Network2IOConnection *pCo // accept join else if(Join(NewCCore, pConn, reply.getData())) { - // save core + // save core pConn->SetCCore(NewCCore); - // accept + // accept if(!reply) reply = "join accepted"; fOK = true; } @@ -1129,9 +1129,9 @@ void C4Network2::HandleConn(const C4PacketConn &Pkt, C4Network2IOConnection *pCo if(fOK && pConn->isHalfAccepted()) return; - // send answer + // send answer C4PacketConnRe pcr(fOK, fWrongPassword, reply.getData()); - if(!pConn->Send(MkC4NetIOPacket(PID_ConnRe, pcr))) + if(!pConn->Send(MkC4NetIOPacket(PID_ConnRe, pcr))) return; // accepted? @@ -1187,10 +1187,10 @@ bool C4Network2::Join(C4ClientCore &CCore, C4Network2IOConnection *pConn, const if(CCore.getID() != C4ClientIDUnknown) { szReply = "join with set id not allowed"; return false; } // find free client id CCore.SetID(iNextClientID++); - // observer? - if(!fAllowJoin) CCore.SetObserver(true); - // deactivate - client will have to ask for activation. - CCore.SetActivated(false); + // observer? + if(!fAllowJoin) CCore.SetObserver(true); + // deactivate - client will have to ask for activation. + CCore.SetActivated(false); // Name already in use? Find unused one if(Clients.GetClient(CCore.getName())) { @@ -1329,20 +1329,20 @@ void C4Network2::HandleStatusAck(const C4Network2Status &nStatus, C4Network2Clie void C4Network2::HandleActivateReq(int32_t iTick, C4Network2Client *pByClient) { - if(!isHost()) return; - // not allowed or already activated? ignore - if(pByClient->isObserver() || pByClient->isActivated()) return; + if(!isHost()) return; + // not allowed or already activated? ignore + if(pByClient->isObserver() || pByClient->isActivated()) return; // not joined completely yet? ignore if(!pByClient->isWaitedFor()) return; - // check behind limit - if(isRunning()) - { - // make a guess how much the client lags. - int32_t iLagFrames = BoundBy(pByClient->getMsgConn()->getPingTime() * Game.FPS / 500, 0, 100); - if(iTick < Game.FrameCounter - iLagFrames - C4NetMaxBehind4Activation) - return; - } - // activate him + // check behind limit + if(isRunning()) + { + // make a guess how much the client lags. + int32_t iLagFrames = BoundBy(pByClient->getMsgConn()->getPingTime() * Game.FPS / 500, 0, 100); + if(iTick < Game.FrameCounter - iLagFrames - C4NetMaxBehind4Activation) + return; + } + // activate him ::Control.DoInput(CID_ClientUpdate, new C4ControlClientUpdate(pByClient->getID(), CUT_Activate, true), CDT_Sync); @@ -1565,7 +1565,7 @@ C4Network2Res::Ref C4Network2::RetrieveRes(const C4Network2ResCore &Core, int32_ { // create pDlg = new C4GUI::ProgressDialog(FormatString(LoadResStr("IDS_NET_WAITFORRES"), szResName).getData(), - LoadResStr("IDS_NET_CAPTION"), 100, 0, C4GUI::Ico_NetWait); + LoadResStr("IDS_NET_CAPTION"), 100, 0, C4GUI::Ico_NetWait); // show dialog if(!pDlg->Show(::pGUI, true)) { delete pDlg; return NULL; } } @@ -1633,11 +1633,11 @@ void C4Network2::RemoveDynamic() bool C4Network2::isFrozen() const { - // "frozen" means all clients are garantueed to be in the same tick. - // This is only the case if the game is not started yet (lobby) or the - // tick has been ensured (pause) and acknowledged by all joined clients. - // Note unjoined clients must be ignored here - they can't be faster than - // the host, anyway. + // "frozen" means all clients are garantueed to be in the same tick. + // This is only the case if the game is not started yet (lobby) or the + // tick has been ensured (pause) and acknowledged by all joined clients. + // Note unjoined clients must be ignored here - they can't be faster than + // the host, anyway. if(Status.getState() == GS_Lobby) return true; if(Status.getState() == GS_Pause && fStatusAck) return true; return false; @@ -1651,10 +1651,10 @@ bool C4Network2::ChangeGameStatus(C4NetGameState enState, int32_t iTargetCtrlTic Status.Set(enState, iTargetCtrlTick); // update reference InvalidateReference(); - // control mode change? - if(iCtrlMode >= 0) Status.SetCtrlMode(iCtrlMode); + // control mode change? + if(iCtrlMode >= 0) Status.SetCtrlMode(iCtrlMode); // log - LogSilentF("Network: going into status %s (tick %d)", Status.getStateName(), iTargetCtrlTick); + LogSilentF("Network: going into status %s (tick %d)", Status.getStateName(), iTargetCtrlTick); // set flags Clients.ResetReady(); fStatusReached = fStatusAck = false; @@ -1676,19 +1676,19 @@ void C4Network2::CheckStatusReached(bool fFromFinalInit) else if(Status.getState() == GS_Go || Status.getState() == GS_Pause) { if(Game.IsRunning || fFromFinalInit) - { + { // Make sure we have reached the tick and the control queue is empty (except for chasing) if(::Control.CtrlTickReached(Status.getTargetCtrlTick()) && (fChasing || !pControl->CtrlReady(::Control.ControlTick))) fStatusReached = true; else - { + { // run ctrl so the tick can be reached pControl->SetRunning(true, Status.getTargetCtrlTick()); Game.HaltCount = 0; - Console.UpdateHaltCtrls(!! Game.HaltCount); - } - } + Console.UpdateHaltCtrls(!! Game.HaltCount); + } + } } if(!fStatusReached) return; // call handler @@ -1733,24 +1733,24 @@ void C4Network2::CheckStatusAck() void C4Network2::OnStatusReached() { // stop ctrl, wait for ack - if(pControl->IsEnabled()) - { - Console.UpdateHaltCtrls(!!++Game.HaltCount); + if(pControl->IsEnabled()) + { + Console.UpdateHaltCtrls(!!++Game.HaltCount); pControl->SetRunning(false); - } + } } void C4Network2::OnStatusAck() { // log it LogSilentF("Network: status %s (tick %d) reached", Status.getStateName(), Status.getTargetCtrlTick()); - // pause? - if(Status.getState() == GS_Pause) - { - // set halt-flag (show hold message) - Console.UpdateHaltCtrls(!!++Game.HaltCount); - } - // go? + // pause? + if(Status.getState() == GS_Pause) + { + // set halt-flag (show hold message) + Console.UpdateHaltCtrls(!!++Game.HaltCount); + } + // go? if(Status.getState() == GS_Go) { // set mode @@ -1759,20 +1759,20 @@ void C4Network2::OnStatusAck() Players.OnStatusGoReached(); // start ctrl pControl->SetRunning(true); - // reset halt-flag + // reset halt-flag Game.HaltCount = 0; - Console.UpdateHaltCtrls(!!Game.HaltCount); + Console.UpdateHaltCtrls(!!Game.HaltCount); } } void C4Network2::RequestActivate() { - // neither observer nor activated? - if(Game.Clients.getLocal()->isObserver() || Game.Clients.getLocal()->isActivated()) - { - iLastActivateRequest = 0; - return; - } + // neither observer nor activated? + if(Game.Clients.getLocal()->isObserver() || Game.Clients.getLocal()->isActivated()) + { + iLastActivateRequest = 0; + return; + } // host? just do it if(fHost) { @@ -1782,29 +1782,29 @@ void C4Network2::RequestActivate() CDT_Sync); return; } - // ensure interval - if(iLastActivateRequest && timeGetTime() < iLastActivateRequest + C4NetActivationReqInterval) - return; + // ensure interval + if(iLastActivateRequest && timeGetTime() < iLastActivateRequest + C4NetActivationReqInterval) + return; // status not reached yet? May be chasing, let's delay this. if(!fStatusReached) { fDelayedActivateReq = true; return; } - // request - Clients.SendMsgToHost(MkC4NetIOPacket(PID_ClientActReq, C4PacketActivateReq(Game.FrameCounter))); - // store time - iLastActivateRequest = timeGetTime(); + // request + Clients.SendMsgToHost(MkC4NetIOPacket(PID_ClientActReq, C4PacketActivateReq(Game.FrameCounter))); + // store time + iLastActivateRequest = timeGetTime(); } void C4Network2::DeactivateInactiveClients() { - // host only - if(!isHost()) return; - // update activity - Clients.UpdateClientActivity(); - // find clients to deactivate - for(C4Network2Client *pClient = Clients.GetNextClient(NULL); pClient; pClient = Clients.GetNextClient(pClient)) + // host only + if(!isHost()) return; + // update activity + Clients.UpdateClientActivity(); + // find clients to deactivate + for(C4Network2Client *pClient = Clients.GetNextClient(NULL); pClient; pClient = Clients.GetNextClient(pClient)) if(!pClient->isLocal() && pClient->isActivated()) if(pClient->getLastActivity() + C4NetDeactivationDelay < Game.FrameCounter) ::Control.DoInput(CID_ClientUpdate, new C4ControlClientUpdate(pClient->getID(), CUT_Activate, false), CDT_Sync); @@ -1911,42 +1911,42 @@ bool C4Network2::InitLeague(bool *pCancel) } - // Init - pLeagueClient = new C4LeagueClient(); - if(!pLeagueClient->Init() || - !pLeagueClient->SetServer(MasterServerAddress.getData())) - { - // Log message - StdStrBuf Message = FormatString(LoadResStr("IDS_NET_ERR_LEAGUEINIT"), pLeagueClient->GetError()); - LogFatal(Message.getData()); - // Clear league - delete pLeagueClient; pLeagueClient = NULL; - if(fHost) - Game.Parameters.LeagueAddress.Clear(); - // Show message, allow abort + // Init + pLeagueClient = new C4LeagueClient(); + if(!pLeagueClient->Init() || + !pLeagueClient->SetServer(MasterServerAddress.getData())) + { + // Log message + StdStrBuf Message = FormatString(LoadResStr("IDS_NET_ERR_LEAGUEINIT"), pLeagueClient->GetError()); + LogFatal(Message.getData()); + // Clear league + delete pLeagueClient; pLeagueClient = NULL; + if(fHost) + Game.Parameters.LeagueAddress.Clear(); + // Show message, allow abort bool fResult = true; - if(::pGUI && !Console.Active) - fResult = ::pGUI->ShowMessageModal(Message.getData(), LoadResStr("IDS_NET_ERR_LEAGUE"), - (pCancel ? C4GUI::MessageDialog::btnOK : 0) | C4GUI::MessageDialog::btnAbort, - C4GUI::Ico_Error); - if (pCancel) *pCancel = fResult; - return false; - } + if(::pGUI && !Console.Active) + fResult = ::pGUI->ShowMessageModal(Message.getData(), LoadResStr("IDS_NET_ERR_LEAGUE"), + (pCancel ? C4GUI::MessageDialog::btnOK : 0) | C4GUI::MessageDialog::btnAbort, + C4GUI::Ico_Error); + if (pCancel) *pCancel = fResult; + return false; + } // Add to message loop Application.Add(pLeagueClient); - // OK - return true; + // OK + return true; } void C4Network2::DeinitLeague() { // league clear MasterServerAddress.Clear(); - Game.Parameters.League.Clear(); - Game.Parameters.LeagueAddress.Clear(); - if (pLeagueClient) + Game.Parameters.League.Clear(); + Game.Parameters.LeagueAddress.Clear(); + if (pLeagueClient) { Application.Remove(pLeagueClient); delete pLeagueClient; pLeagueClient = NULL; @@ -1955,23 +1955,23 @@ void C4Network2::DeinitLeague() bool C4Network2::LeagueStart(bool *pCancel) { - // Not needed? - if(!pLeagueClient || !fHost) - return true; + // Not needed? + if(!pLeagueClient || !fHost) + return true; // Default if(pCancel) *pCancel = true; - // Do update - C4Network2Reference Ref; - Ref.InitLocal(); - if(!pLeagueClient->Start(Ref)) - { - // Log message - StdStrBuf Message = FormatString(LoadResStr("IDS_NET_ERR_LEAGUE_STARTGAME"), pLeagueClient->GetError()); - LogFatal(Message.getData()); - // Show message - if(::pGUI && !Console.Active) + // Do update + C4Network2Reference Ref; + Ref.InitLocal(); + if(!pLeagueClient->Start(Ref)) + { + // Log message + StdStrBuf Message = FormatString(LoadResStr("IDS_NET_ERR_LEAGUE_STARTGAME"), pLeagueClient->GetError()); + LogFatal(Message.getData()); + // Show message + if(::pGUI && !Console.Active) { // Show option to cancel, if possible bool fResult = ::pGUI->ShowMessageModal( @@ -1983,18 +1983,18 @@ bool C4Network2::LeagueStart(bool *pCancel) *pCancel = !fResult; } // Failed - return false; - } + return false; + } // We have an internet connection, so let's punch the master server here in order to open an udp port C4NetIO::addr_t PuncherAddr; if(ResolveAddress(Config.Network.PuncherAddress, &PuncherAddr, C4NetStdPortPuncher)) NetIO.Punch(PuncherAddr); - // Let's wait for response - StdStrBuf Message = FormatString(LoadResStr("IDS_NET_LEAGUE_REGGAME"), pLeagueClient->getServerName()); - Log(Message.getData()); - // Set up a dialog + // Let's wait for response + StdStrBuf Message = FormatString(LoadResStr("IDS_NET_LEAGUE_REGGAME"), pLeagueClient->getServerName()); + Log(Message.getData()); + // Set up a dialog C4GUI::MessageDialog *pDlg = NULL; if(::pGUI && !Console.Active) { @@ -2005,21 +2005,21 @@ bool C4Network2::LeagueStart(bool *pCancel) } // Wait for response while(pLeagueClient->isBusy()) - { - // Execute GUI + { + // Execute GUI if(!Application.ScheduleProcs() || - (pDlg && pDlg->IsAborted())) - { + (pDlg && pDlg->IsAborted())) + { // Clear up - if(::pGUI && pDlg) delete pDlg; + if(::pGUI && pDlg) delete pDlg; return false; - } - // Check if league server has responded - if(!pLeagueClient->Execute(100)) - break; - } - // Close dialog - if(::pGUI && pDlg) + } + // Check if league server has responded + if(!pLeagueClient->Execute(100)) + break; + } + // Close dialog + if(::pGUI && pDlg) { pDlg->Close(true); delete pDlg; @@ -2028,16 +2028,16 @@ bool C4Network2::LeagueStart(bool *pCancel) StdStrBuf LeagueServerMessage, League, StreamingAddr; int32_t Seed = Game.RandomSeed, MaxPlayersLeague = 0; if(!pLeagueClient->isSuccess() || - !pLeagueClient->GetStartReply(&LeagueServerMessage, &League, &StreamingAddr, &Seed, &MaxPlayersLeague)) - { - const char *pError = pLeagueClient->GetError() ? pLeagueClient->GetError() : - LeagueServerMessage.getLength() ? LeagueServerMessage.getData() : - LoadResStr("IDS_NET_ERR_LEAGUE_EMPTYREPLY"); - StdStrBuf Message = FormatString(LoadResStr("IDS_NET_ERR_LEAGUE_REGGAME"), pError); - // Log message - Log(Message.getData()); - // Show message - if(::pGUI && !Console.Active) + !pLeagueClient->GetStartReply(&LeagueServerMessage, &League, &StreamingAddr, &Seed, &MaxPlayersLeague)) + { + const char *pError = pLeagueClient->GetError() ? pLeagueClient->GetError() : + LeagueServerMessage.getLength() ? LeagueServerMessage.getData() : + LoadResStr("IDS_NET_ERR_LEAGUE_EMPTYREPLY"); + StdStrBuf Message = FormatString(LoadResStr("IDS_NET_ERR_LEAGUE_REGGAME"), pError); + // Log message + Log(Message.getData()); + // Show message + if(::pGUI && !Console.Active) { // Show option to cancel, if possible bool fResult = ::pGUI->ShowMessageModal( @@ -2049,17 +2049,17 @@ bool C4Network2::LeagueStart(bool *pCancel) *pCancel = !fResult; } // Failed - return false; - } + return false; + } // Show message if(LeagueServerMessage.getLength()) { - StdStrBuf Message = FormatString(LoadResStr("IDS_MSG_LEAGUEGAMESIGNUP"), pLeagueClient->getServerName(), LeagueServerMessage.getData()); - // Log message - Log(Message.getData()); + StdStrBuf Message = FormatString(LoadResStr("IDS_MSG_LEAGUEGAMESIGNUP"), pLeagueClient->getServerName(), LeagueServerMessage.getData()); + // Log message + Log(Message.getData()); // Show message - if(::pGUI && !Console.Active) + if(::pGUI && !Console.Active) { // Show option to cancel, if possible bool fResult = ::pGUI->ShowMessageModal( @@ -2092,38 +2092,38 @@ bool C4Network2::LeagueStart(bool *pCancel) Game.Parameters.StreamAddress = StreamingAddr; } - // All ok + // All ok fLeagueEndSent = false; - return true; + return true; } bool C4Network2::LeagueUpdate() { - // Not needed? - if(!pLeagueClient || !fHost) - return true; + // Not needed? + if(!pLeagueClient || !fHost) + return true; // League client currently busy? if(pLeagueClient->isBusy()) return true; - // Create reference - C4Network2Reference Ref; - Ref.InitLocal(); + // Create reference + C4Network2Reference Ref; + Ref.InitLocal(); - // Do update - if(!pLeagueClient->Update(Ref)) - { - // Log - LogF(LoadResStr("IDS_NET_ERR_LEAGUE_UPDATEGAME"), pLeagueClient->GetError()); - return false; - } + // Do update + if(!pLeagueClient->Update(Ref)) + { + // Log + LogF(LoadResStr("IDS_NET_ERR_LEAGUE_UPDATEGAME"), pLeagueClient->GetError()); + return false; + } // Timing - iLastLeagueUpdate = time(NULL); + iLastLeagueUpdate = time(NULL); iLeagueUpdateDelay = Config.Network.MasterReferencePeriod; - return true; + return true; } bool C4Network2::LeagueUpdateProcessReply() @@ -2134,37 +2134,37 @@ bool C4Network2::LeagueUpdateProcessReply() assert(!pLeagueClient->isBusy()); assert(pLeagueClient->getCurrentAction() == C4LA_Update); // check reply success - C4ClientPlayerInfos PlayerLeagueInfos; - StdStrBuf LeagueServerMessage; - bool fSucc = pLeagueClient->isSuccess() && pLeagueClient->GetUpdateReply(&LeagueServerMessage, &PlayerLeagueInfos); - pLeagueClient->ResetCurrentAction(); + C4ClientPlayerInfos PlayerLeagueInfos; + StdStrBuf LeagueServerMessage; + bool fSucc = pLeagueClient->isSuccess() && pLeagueClient->GetUpdateReply(&LeagueServerMessage, &PlayerLeagueInfos); + pLeagueClient->ResetCurrentAction(); if(!fSucc) - { - const char *pError = pLeagueClient->GetError() ? pLeagueClient->GetError() : - LeagueServerMessage.getLength() ? LeagueServerMessage.getData() : - LoadResStr("IDS_NET_ERR_LEAGUE_EMPTYREPLY"); - StdStrBuf Message = FormatString(LoadResStr("IDS_NET_ERR_LEAGUE_UPDATEGAME"), pError); - // Show message - no dialog, because it's not really fatal and might happen in the running game - Log(Message.getData()); + { + const char *pError = pLeagueClient->GetError() ? pLeagueClient->GetError() : + LeagueServerMessage.getLength() ? LeagueServerMessage.getData() : + LoadResStr("IDS_NET_ERR_LEAGUE_EMPTYREPLY"); + StdStrBuf Message = FormatString(LoadResStr("IDS_NET_ERR_LEAGUE_UPDATEGAME"), pError); + // Show message - no dialog, because it's not really fatal and might happen in the running game + Log(Message.getData()); return false; - } + } // evaluate reply: Transfer data to players - // Take round results - C4PlayerInfoList &TargetList = Game.PlayerInfos; - C4ClientPlayerInfos *pInfos; C4PlayerInfo *pInfo, *pResultInfo; - for(int iClient = 0; (pInfos = TargetList.GetIndexedInfo(iClient)); iClient++) - for(int iInfo = 0; (pInfo = pInfos->GetPlayerInfo(iInfo)); iInfo++) - if((pResultInfo = PlayerLeagueInfos.GetPlayerInfoByID(pInfo->GetID()))) - { + // Take round results + C4PlayerInfoList &TargetList = Game.PlayerInfos; + C4ClientPlayerInfos *pInfos; C4PlayerInfo *pInfo, *pResultInfo; + for(int iClient = 0; (pInfos = TargetList.GetIndexedInfo(iClient)); iClient++) + for(int iInfo = 0; (pInfo = pInfos->GetPlayerInfo(iInfo)); iInfo++) + if((pResultInfo = PlayerLeagueInfos.GetPlayerInfoByID(pInfo->GetID()))) + { int32_t iLeagueProjectedGain = pResultInfo->GetLeagueProjectedGain(); if (iLeagueProjectedGain != pInfo->GetLeagueProjectedGain()) { pInfo->SetLeagueProjectedGain(iLeagueProjectedGain); pInfos->SetUpdated(); } - } + } // transfer info update to other clients - Players.SendUpdatedPlayers(); + Players.SendUpdatedPlayers(); // if lobby is open, notify lobby of updated players if (pLobby) pLobby->OnPlayersChange(); // OMFG SUCCESS! @@ -2258,9 +2258,9 @@ bool C4Network2::LeagueEnd(const char *szRecordName, const BYTE *pRecordSHA) bool C4Network2::LeaguePlrAuth(C4PlayerInfo *pInfo) { - // Not possible? - if(!pLeagueClient) - return false; + // Not possible? + if(!pLeagueClient) + return false; // Make sure league client is avilable LeagueWaitNotBusy(); @@ -2343,7 +2343,7 @@ bool C4Network2::LeaguePlrAuth(C4PlayerInfo *pInfo) (pDlg && pDlg->IsAborted())) { // Clear up - if(::pGUI && pDlg) delete pDlg; + if(::pGUI && pDlg) delete pDlg; return false; } // Check if league server has responded @@ -2425,9 +2425,9 @@ bool C4Network2::LeaguePlrAuth(C4PlayerInfo *pInfo) bool C4Network2::LeaguePlrAuthCheck(C4PlayerInfo *pInfo) { - // Not possible? - if(!pLeagueClient) - return false; + // Not possible? + if(!pLeagueClient) + return false; // Make sure league client is available LeagueWaitNotBusy(); @@ -2442,8 +2442,8 @@ bool C4Network2::LeaguePlrAuthCheck(C4PlayerInfo *pInfo) // Wait for response while(pLeagueClient->isBusy()) - if(!pLeagueClient->Execute(100)) - break; + if(!pLeagueClient->Execute(100)) + break; // Check response validity if (!pLeagueClient->isSuccess()) @@ -2500,8 +2500,8 @@ void C4Network2::LeagueWaitNotBusy() // wait for it Log(LoadResStr("IDS_LEAGUE_WAITINGFORLASTLEAGUESERVE")); while(pLeagueClient->isBusy()) - if(!pLeagueClient->Execute(100)) - break; + if(!pLeagueClient->Execute(100)) + break; // if last request was an update request, process it if (pLeagueClient->getCurrentAction() == C4LA_Update) LeagueUpdateProcessReply(); diff --git a/src/network/C4Network2.h b/src/network/C4Network2.h index 87a62dd4d..7b2c3f33f 100644 --- a/src/network/C4Network2.h +++ b/src/network/C4Network2.h @@ -39,15 +39,15 @@ const int16_t C4NetStdPortTCP = 11112, C4NetStdPortDiscovery = 11114, C4NetStdPortRefServer = 11111, C4NetStdPortPuncher = 11115, - C4NetStdPortHTTP = 80; + C4NetStdPortHTTP = 80; // ressource retrieve wait timeout const int C4NetResRetrieveTimeout = 100000; // (ms) // client (de)activation const int C4NetActivationReqInterval = 5000, // (ms) - C4NetMaxBehind4Activation = 20, // (ticks) - C4NetDeactivationDelay = 500; // (ticks) + C4NetMaxBehind4Activation = 20, // (ticks) + C4NetDeactivationDelay = 500; // (ticks) // client chase const unsigned int C4NetChaseTargetUpdateInterval = 5; // (s) @@ -89,7 +89,7 @@ public: int32_t getCtrlMode() const { return iCtrlMode; } int32_t getTargetCtrlTick() const { return iTargetCtrlTick; } const char *getStateName() const; - const char *getDescription() const; + const char *getDescription() const; bool isEnabled() const { return eState != GS_None; } bool isLobbyActive() const { return eState == GS_Lobby; } @@ -165,16 +165,16 @@ protected: // chase uint32_t iLastChaseTargetUpdate; - // activation - uint32_t iLastActivateRequest; + // activation + uint32_t iLastActivateRequest; - // reference - uint32_t iLastReferenceUpdate; + // reference + uint32_t iLastReferenceUpdate; uint32_t iLastLeagueUpdate, iLeagueUpdateDelay; bool fLeagueEndSent; - // league - class C4LeagueClient *pLeagueClient; + // league + class C4LeagueClient *pLeagueClient; // game password StdStrBuf sPassword; @@ -231,7 +231,7 @@ public: bool InitHost(bool fLobby); InitResult InitClient(const class C4Network2Reference &Ref, bool fObserver); InitResult InitClient(const class C4Network2Address *pAddrs, int iAddrCount, const class C4ClientCore &HostCore, const char *szPassword = NULL); - bool InitHostRessources(); + bool InitHostRessources(); bool DoLobby(); bool Start(); bool Pause(); @@ -253,7 +253,7 @@ public: bool ToggleClientListDlg(); void AllowJoin(bool fAllow); void SetAllowObserve(bool fAllow); - void SetCtrlMode(int32_t iCtrlMode); + void SetCtrlMode(int32_t iCtrlMode); void SetPassword(const char *szToPassword); StdStrBuf QueryClientPassword(); // ask client for a password; empty if user canceled @@ -269,17 +269,17 @@ public: // status void DrawStatus(C4TargetFacet &cgo); - // client activation - void RequestActivate(); - void DeactivateInactiveClients(); // host + // client activation + void RequestActivate(); + void DeactivateInactiveClients(); // host - // league - void LeagueGameEvaluate(const char *szRecordName = NULL, const BYTE *pRecordSHA = NULL); + // league + void LeagueGameEvaluate(const char *szRecordName = NULL, const BYTE *pRecordSHA = NULL); void LeagueSignupDisable(); // if "internet game" button is switched off in lobby: Remove from league server bool LeagueSignupEnable(); // if "internet game" button is switched on in lobby: (re)Add to league server void InvalidateReference(); // forces a recreation and re-send of the game reference in the next execution cycle - bool LeaguePlrAuth(C4PlayerInfo *pInfo); // client: get authentication for a player from the league server - bool LeaguePlrAuthCheck(C4PlayerInfo *pInfo); // host: check AUID of player info with league server + bool LeaguePlrAuth(C4PlayerInfo *pInfo); // client: get authentication for a player from the league server + bool LeaguePlrAuthCheck(C4PlayerInfo *pInfo); // host: check AUID of player info with league server void LeagueNotifyDisconnect(int32_t iClientID, enum C4LeagueDisconnectReason eReason); // void LeagueWaitNotBusy(); // block until league serveris no longer busy. Process update reply if last message was an update void LeagueSurrender(); // forfeit in league - just fake a disconnect @@ -427,13 +427,13 @@ public: class C4PacketActivateReq : public C4PacketBase { public: - C4PacketActivateReq(int32_t iTick = -1) : iTick(iTick) { } + C4PacketActivateReq(int32_t iTick = -1) : iTick(iTick) { } protected: - int32_t iTick; + int32_t iTick; public: - int32_t getTick() const { return iTick; } + int32_t getTick() const { return iTick; } virtual void CompileFunc(StdCompiler *pComp); }; diff --git a/src/network/C4Network2Client.cpp b/src/network/C4Network2Client.cpp index 3357df247..beb5c449d 100644 --- a/src/network/C4Network2Client.cpp +++ b/src/network/C4Network2Client.cpp @@ -62,9 +62,9 @@ void C4Network2Address::CompileFunc(StdCompiler *pComp) pComp->Seperator(StdCompiler::SEP_PART2); // ':' // Write port - uint16_t iPort = htons(addr.sin_port); - pComp->Value(iPort); - addr.sin_port = htons(iPort); + uint16_t iPort = htons(addr.sin_port); + pComp->Value(iPort); + addr.sin_port = htons(iPort); } StdStrBuf C4Network2Address::toString() const @@ -89,9 +89,9 @@ C4Network2Client::C4Network2Client(C4Client *pClient) : pClient(pClient), iAddrCnt(0), eStatus(NCS_Ready), - iLastActivity(0), + iLastActivity(0), pMsgConn(NULL), pDataConn(NULL), - iNextConnAttempt(0), + iNextConnAttempt(0), pNext(NULL), pParent(NULL), pstatPing(NULL) { } @@ -146,29 +146,29 @@ void C4Network2Client::RemoveConn(C4Network2IOConnection *pConn) void C4Network2Client::CloseConns(const char *szMsg) { - C4PacketConnRe Pkt(false, false, szMsg); - C4Network2IOConnection *pConn; - while((pConn = pMsgConn)) - { - // send packet, close - if(pConn->isOpen()) - { - pConn->Send(MkC4NetIOPacket(PID_ConnRe, Pkt)); - pConn->Close(); - } - // remove - RemoveConn(pConn); - } + C4PacketConnRe Pkt(false, false, szMsg); + C4Network2IOConnection *pConn; + while((pConn = pMsgConn)) + { + // send packet, close + if(pConn->isOpen()) + { + pConn->Send(MkC4NetIOPacket(PID_ConnRe, Pkt)); + pConn->Close(); + } + // remove + RemoveConn(pConn); + } } bool C4Network2Client::SendMsg(C4NetIOPacket rPkt) const { - return getMsgConn() && getMsgConn()->Send(rPkt); + return getMsgConn() && getMsgConn()->Send(rPkt); } bool C4Network2Client::SendData(C4NetIOPacket rPkt) const { - return getDataConn() && getDataConn()->Send(rPkt); + return getDataConn() && getDataConn()->Send(rPkt); } bool C4Network2Client::DoConnectAttempt(C4Network2IO *pIO) @@ -234,35 +234,35 @@ bool C4Network2Client::AddAddr(const C4Network2Address &addr, bool fAnnounce) void C4Network2Client::AddLocalAddrs(int16_t iPortTCP, int16_t iPortUDP) { - // set up address struct + // set up address struct sockaddr_in addr; ZeroMem(&addr, sizeof addr); addr.sin_family = AF_INET; - // get local address(es) - in_addr **ppAddr = NULL; + // get local address(es) + in_addr **ppAddr = NULL; #ifdef HAVE_WINSOCK bool fGotWinSock = AcquireWinSock(); - if(fGotWinSock) + if(fGotWinSock) #endif - { - // get local host name - char szLocalHostName[128+1]; *szLocalHostName = '\0'; - ::gethostname(szLocalHostName, 128); - // get hostent-struct - hostent *ph = ::gethostbyname(szLocalHostName); - // check type, get addr list - if(ph) - { - if(ph->h_addrtype != AF_INET) - ph = NULL; - else - ppAddr = reinterpret_cast(ph->h_addr_list); - } - } + { + // get local host name + char szLocalHostName[128+1]; *szLocalHostName = '\0'; + ::gethostname(szLocalHostName, 128); + // get hostent-struct + hostent *ph = ::gethostbyname(szLocalHostName); + // check type, get addr list + if(ph) + { + if(ph->h_addrtype != AF_INET) + ph = NULL; + else + ppAddr = reinterpret_cast(ph->h_addr_list); + } + } - // add address(es) - for(;;) - { + // add address(es) + for(;;) + { if(iPortTCP >= 0) { addr.sin_port = htons(iPortTCP); @@ -273,13 +273,13 @@ void C4Network2Client::AddLocalAddrs(int16_t iPortTCP, int16_t iPortUDP) addr.sin_port = htons(iPortUDP); AddAddr(C4Network2Address(addr, P_UDP), false); } - // get next - if(!ppAddr || !*ppAddr) break; - addr.sin_addr = **ppAddr++; - } + // get next + if(!ppAddr || !*ppAddr) break; + addr.sin_addr = **ppAddr++; + } #ifdef HAVE_WINSOCK - if(fGotWinSock) ReleaseWinSock(); + if(fGotWinSock) ReleaseWinSock(); #endif } @@ -387,7 +387,7 @@ C4Network2Client *C4Network2ClientList::GetHost() C4Network2Client *C4Network2ClientList::GetNextClient(C4Network2Client *pClient) { - return pClient ? pClient->pNext : pFirst; + return pClient ? pClient->pNext : pFirst; } void C4Network2ClientList::Init(C4ClientList *pnClientList, bool fnHost) @@ -409,7 +409,7 @@ C4Network2Client *C4Network2ClientList::RegClient(C4Client *pClient) for(;pPos; pLast = pPos, pPos = pPos->getNext()) if(pPos->getID() > pClient->getID()) break; - assert(!pLast || pLast->getID() != pClient->getID()); + assert(!pLast || pLast->getID() != pClient->getID()); // create new client C4Network2Client *pNetClient = new C4Network2Client(pClient); // add to list @@ -609,9 +609,9 @@ bool C4Network2ClientList::AllClientsReady() const void C4Network2ClientList::UpdateClientActivity() { for(C4Network2Client *pClient = pFirst; pClient; pClient = pClient->getNext()) - if(pClient->isActivated()) - if(::Players.GetAtClient(pClient->getID())) - pClient->SetLastActivity(Game.FrameCounter); + if(pClient->isActivated()) + if(::Players.GetAtClient(pClient->getID())) + pClient->SetLastActivity(Game.FrameCounter); } // *** C4PacketAddr diff --git a/src/network/C4Network2Client.h b/src/network/C4Network2Client.h index 5c061af4a..dcad61902 100644 --- a/src/network/C4Network2Client.h +++ b/src/network/C4Network2Client.h @@ -93,7 +93,7 @@ public: ~C4Network2Client(); protected: - // client data + // client data C4Client *pClient; // addresses @@ -101,17 +101,17 @@ protected: int32_t AddrAttempts[C4ClientMaxAddr]; int32_t iAddrCnt; - // status + // status C4Network2ClientStatus eStatus; - // frame of last activity - int32_t iLastActivity; + // frame of last activity + int32_t iLastActivity; - // connections + // connections C4Network2IOConnection *pMsgConn, *pDataConn; time_t iNextConnAttempt; - // part of client list + // part of client list C4Network2Client *pNext; class C4Network2ClientList *pParent; @@ -141,13 +141,13 @@ public: bool isConnected() const { return !! pMsgConn; } time_t getNextConnAttempt() const { return iNextConnAttempt; } - int32_t getLastActivity() const { return iLastActivity; } + int32_t getLastActivity() const { return iLastActivity; } class C4TableGraph *getStatPing() const { return pstatPing; } C4Network2Client *getNext() const { return pNext; } - void SetStatus(C4Network2ClientStatus enStatus) { eStatus = enStatus; } - void SetLastActivity(int32_t iTick) { iLastActivity = iTick; } + void SetStatus(C4Network2ClientStatus enStatus) { eStatus = enStatus; } + void SetLastActivity(int32_t iTick) { iLastActivity = iTick; } C4Network2IOConnection *getMsgConn() const { return pMsgConn; } C4Network2IOConnection *getDataConn() const { return pDataConn; } @@ -155,10 +155,10 @@ public: void SetMsgConn(C4Network2IOConnection *pConn); void SetDataConn(C4Network2IOConnection *pConn); void RemoveConn(C4Network2IOConnection *pConn); - void CloseConns(const char *szMsg); + void CloseConns(const char *szMsg); - bool SendMsg(C4NetIOPacket rPkt) const; - bool SendData(C4NetIOPacket rPkt) const; + bool SendMsg(C4NetIOPacket rPkt) const; + bool SendData(C4NetIOPacket rPkt) const; bool DoConnectAttempt(class C4Network2IO *pIO); @@ -222,8 +222,8 @@ public: void ResetReady(); bool AllClientsReady() const; - // activity - void UpdateClientActivity(); + // activity + void UpdateClientActivity(); }; // * Packets * diff --git a/src/network/C4Network2Dialogs.cpp b/src/network/C4Network2Dialogs.cpp index d312f29da..333ebce4f 100644 --- a/src/network/C4Network2Dialogs.cpp +++ b/src/network/C4Network2Dialogs.cpp @@ -65,9 +65,9 @@ void C4Network2ClientDlg::UpdateText() // get client (may be NULL for local info) C4Network2Client *pNetClient = pClient->getNetClient(); // show some info - StdCopyStrBuf strActivated(LoadResStr(pClient->isActivated() ? "IDS_MSG_ACTIVE" : "IDS_MSG_INACTIVE")); - StdCopyStrBuf strLocal(LoadResStr(pClient->isLocal() ? "IDS_MSG_LOCAL" : "IDS_MSG_REMOTE")); - StdCopyStrBuf strHost(LoadResStr(pClient->isHost() ? "IDS_MSG_HOST" : "IDS_MSG_CLIENT")); + StdCopyStrBuf strActivated(LoadResStr(pClient->isActivated() ? "IDS_MSG_ACTIVE" : "IDS_MSG_INACTIVE")); + StdCopyStrBuf strLocal(LoadResStr(pClient->isLocal() ? "IDS_MSG_LOCAL" : "IDS_MSG_REMOTE")); + StdCopyStrBuf strHost(LoadResStr(pClient->isHost() ? "IDS_MSG_HOST" : "IDS_MSG_CLIENT")); AddLineFmt(LoadResStr("IDS_NET_CLIENT_INFO_FORMAT"), strActivated.getData(), strLocal.getData(), strHost.getData(), pClient->getName(), iClientID, @@ -354,7 +354,7 @@ void C4Network2ClientListBox::ConnectionListItem::Update() ::Network.NetIO.getNetIOName(pConn->getNetClass()), inet_ntoa(pConn->getPeerAddr().sin_addr), htons(pConn->getPeerAddr().sin_port), - pConn->getPacketLoss()).getData()); + pConn->getPacketLoss()).getData()); } void C4Network2ClientListBox::ConnectionListItem::OnButtonDisconnect(C4GUI::Control *pButton) @@ -487,7 +487,7 @@ void C4Network2ClientListDlg::Update() StdStrBuf sStatusText; sStatusText.Format("Tick %d, Behind %d, Rate %d, PreSend %d, ACT: %d", (int)::Control.ControlTick, (int)::Control.Network.GetBehind(::Control.ControlTick), - (int)::Control.ControlRate, (int)::Control.Network.getControlPreSend(), + (int)::Control.ControlRate, (int)::Control.Network.getControlPreSend(), (int)::Control.Network.getAvgControlSendTime()); // Update status label pStatusLabel->SetText(sStatusText.getData()); @@ -499,7 +499,7 @@ bool C4Network2ClientListDlg::Toggle() if (!C4GUI::IsGUIValid()) return false; // toggle off? if (pInstance) { pInstance->Close(true); return true; } - // toggle on! + // toggle on! return ::pGUI->ShowRemoveDlg(pInstance = new C4Network2ClientListDlg()); } @@ -716,9 +716,9 @@ void C4GameOptionButtons::OnCommentSet(const StdStrBuf &rsNewComment) { // check for change; no reference invalidation if not changed if (rsNewComment == Config.Network.Comment) return; - // Set in configuration, update reference + // Set in configuration, update reference Config.Network.Comment.CopyValidated(rsNewComment.getData()); - ::Network.InvalidateReference(); + ::Network.InvalidateReference(); // message feedback Log(LoadResStr("IDS_NET_COMMENTCHANGED")); // acoustic feedback @@ -783,7 +783,7 @@ int GetAxisStepRange(int iRange, int iMaxSteps) while (iDec>=iNextStepDivider && iNextStepDivider*iRange/iDec <= iMaxSteps) { iDec/=iNextStepDivider; - iNextStepDivider = 7 - iNextStepDivider; + iNextStepDivider = 7 - iNextStepDivider; } return iDec; } diff --git a/src/network/C4Network2Discover.cpp b/src/network/C4Network2Discover.cpp index 0430ce645..b05734c40 100644 --- a/src/network/C4Network2Discover.cpp +++ b/src/network/C4Network2Discover.cpp @@ -30,7 +30,7 @@ void C4Network2IODiscover::OnPacket(const class C4NetIOPacket &rPacket, C4NetIO { // discovery? if(fEnabled && rPacket.getSize() == 1 && rPacket.getStatus() == 3) - Announce(); + Announce(); } bool C4Network2IODiscover::Init(uint16_t iPort) @@ -56,9 +56,9 @@ bool C4Network2IODiscover::Init(uint16_t iPort) bool C4Network2IODiscover::Announce() { - // Announce our presence - C4Network2IODiscoverReply Reply = { 4, htons(iRefServerPort) }; - return Send(C4NetIOPacket(&Reply, sizeof(Reply), false, DiscoveryAddr)); + // Announce our presence + C4Network2IODiscoverReply Reply = { 4, htons(iRefServerPort) }; + return Send(C4NetIOPacket(&Reply, sizeof(Reply), false, DiscoveryAddr)); } // *** C4Network2IODiscoverClient diff --git a/src/network/C4Network2Discover.h b/src/network/C4Network2Discover.h index 1db8e152d..c6eb41107 100644 --- a/src/network/C4Network2Discover.h +++ b/src/network/C4Network2Discover.h @@ -27,7 +27,7 @@ const unsigned long C4NetDiscoveryAddress = 0xef; // 239.0.0.0 class C4Network2IODiscover : public C4NetIOSimpleUDP, private C4NetIO::CBClass { public: - C4Network2IODiscover(int16_t iRefServerPort) : iRefServerPort(iRefServerPort), fEnabled(false) + C4Network2IODiscover(int16_t iRefServerPort) : iRefServerPort(iRefServerPort), fEnabled(false) { C4NetIOSimpleUDP::SetCallback(this); } protected: @@ -37,14 +37,14 @@ protected: public: bool Init(uint16_t iPort = P_NONE); - void SetDiscoverable(bool fnEnabled) { fEnabled = fnEnabled; } - bool Announce(); + void SetDiscoverable(bool fnEnabled) { fEnabled = fnEnabled; } + bool Announce(); private: sockaddr_in DiscoveryAddr; int16_t iRefServerPort; - bool fEnabled; + bool fEnabled; }; class C4Network2IODiscoverClient : public C4NetIOSimpleUDP, private C4NetIO::CBClass diff --git a/src/network/C4Network2IO.cpp b/src/network/C4Network2IO.cpp index e2c81084d..2b5470251 100644 --- a/src/network/C4Network2IO.cpp +++ b/src/network/C4Network2IO.cpp @@ -53,11 +53,11 @@ C4Network2IO::C4Network2IO() pConnList(NULL), iNextConnID(0), fAllowConnect(false), - pAutoAcceptList(NULL), + pAutoAcceptList(NULL), fExclusiveConn(false), iLastExecute(0), iLastPing(0), iLastStatistic(0), - iTCPIRate(0), iTCPORate(0), iTCPBCRate(0), - iUDPIRate(0), iUDPORate(0), iUDPBCRate(0) + iTCPIRate(0), iTCPORate(0), iTCPBCRate(0), + iUDPIRate(0), iUDPORate(0), iUDPBCRate(0) { ZeroMem(&PuncherAddr, sizeof(PuncherAddr)); } @@ -74,16 +74,16 @@ bool C4Network2IO::Init(int16_t iPortTCP, int16_t iPortUDP, int16_t iPortDiscove // init members iLastPing = iLastStatistic = timeGetTime(); - iTCPIRate = iTCPORate = iTCPBCRate = 0; - iUDPIRate = iUDPORate = iUDPBCRate = 0; + iTCPIRate = iTCPORate = iTCPBCRate = 0; + iUDPIRate = iUDPORate = iUDPBCRate = 0; // init event callback - C4InteractiveThread &Thread = Application.InteractiveThread; - Thread.SetCallback(Ev_Net_Conn, this); - Thread.SetCallback(Ev_Net_Disconn, this); - Thread.SetCallback(Ev_Net_Packet, this); + C4InteractiveThread &Thread = Application.InteractiveThread; + Thread.SetCallback(Ev_Net_Conn, this); + Thread.SetCallback(Ev_Net_Disconn, this); + Thread.SetCallback(Ev_Net_Packet, this); - // initialize net i/o classes: TCP first + // initialize net i/o classes: TCP first if(iPortTCP > 0) { // create @@ -94,15 +94,15 @@ bool C4Network2IO::Init(int16_t iPortTCP, int16_t iPortUDP, int16_t iPortDiscove LogF("Network: could not init TCP i/o (%s)", pNetIO_TCP->GetError() ? pNetIO_TCP->GetError() : ""); delete pNetIO_TCP; pNetIO_TCP = NULL; } - else - LogSilentF("Network: TCP initialized on port %d", iPortTCP); + else + LogSilentF("Network: TCP initialized on port %d", iPortTCP); // add to thread, set callback if(pNetIO_TCP) - { - Thread.AddProc(pNetIO_TCP); - pNetIO_TCP->SetCallback(this); - } + { + Thread.AddProc(pNetIO_TCP); + pNetIO_TCP->SetCallback(this); + } } // then UDP @@ -116,8 +116,8 @@ bool C4Network2IO::Init(int16_t iPortTCP, int16_t iPortUDP, int16_t iPortDiscove LogF("Network: could not init UDP i/o (%s)", pNetIO_UDP->GetError() ? pNetIO_UDP->GetError() : ""); delete pNetIO_UDP; pNetIO_UDP = NULL; } - else - LogSilentF("Network: UDP initialized on port %d", iPortUDP); + else + LogSilentF("Network: UDP initialized on port %d", iPortUDP); // broadcast deactivated for now, it will possibly cause problems with connection recovery #if 0 @@ -134,40 +134,40 @@ bool C4Network2IO::Init(int16_t iPortTCP, int16_t iPortUDP, int16_t iPortDiscove // add to thread, set callback if(pNetIO_UDP) - { - Thread.AddProc(pNetIO_UDP); - pNetIO_UDP->SetCallback(this); - } + { + Thread.AddProc(pNetIO_UDP); + pNetIO_UDP->SetCallback(this); + } } // no protocols? if(!pNetIO_TCP && !pNetIO_UDP) - { - LogFatal("Network: fatal - no protocols available!"); - Thread.ClearCallback(Ev_Net_Conn, this); - Thread.ClearCallback(Ev_Net_Disconn, this); - Thread.ClearCallback(Ev_Net_Packet, this); - return false; - } + { + LogFatal("Network: fatal - no protocols available!"); + Thread.ClearCallback(Ev_Net_Conn, this); + Thread.ClearCallback(Ev_Net_Disconn, this); + Thread.ClearCallback(Ev_Net_Packet, this); + return false; + } // discovery last if(iPortDiscover > 0) { // create pNetIODiscover = new C4Network2IODiscover(iPortRefServer); - pNetIODiscover->SetDiscoverable(false); + pNetIODiscover->SetDiscoverable(false); // init if(!pNetIODiscover->Init(iPortDiscover)) { LogF("Network: could not init discovery (%s)", pNetIODiscover->GetError() ? pNetIODiscover->GetError() : ""); delete pNetIODiscover; pNetIODiscover = NULL; } - else - LogSilentF("Network: discovery initialized on port %d", iPortDiscover); + else + LogSilentF("Network: discovery initialized on port %d", iPortDiscover); // add to thread if(pNetIODiscover) - Thread.AddProc(pNetIODiscover); + Thread.AddProc(pNetIODiscover); } // plus reference server @@ -181,11 +181,11 @@ bool C4Network2IO::Init(int16_t iPortTCP, int16_t iPortUDP, int16_t iPortDiscove LogF("Network: could not init reference server (%s)", pNetIO_UDP->GetError() ? pNetIO_UDP->GetError() : ""); delete pRefServer; pRefServer = NULL; } - else - LogSilentF("Network: reference server initialized on port %d", iPortRefServer); + else + LogSilentF("Network: reference server initialized on port %d", iPortRefServer); // add to thread if(pRefServer) - Thread.AddProc(pRefServer); + Thread.AddProc(pRefServer); } // own timer @@ -199,12 +199,12 @@ bool C4Network2IO::Init(int16_t iPortTCP, int16_t iPortUDP, int16_t iPortDiscove void C4Network2IO::Clear() // by main thread { // process remaining events - C4InteractiveThread &Thread = Application.InteractiveThread; - Thread.ProcessEvents(); + C4InteractiveThread &Thread = Application.InteractiveThread; + Thread.ProcessEvents(); // clear event callbacks - Thread.ClearCallback(Ev_Net_Conn, this); - Thread.ClearCallback(Ev_Net_Disconn, this); - Thread.ClearCallback(Ev_Net_Packet, this); + Thread.ClearCallback(Ev_Net_Conn, this); + Thread.ClearCallback(Ev_Net_Disconn, this); + Thread.ClearCallback(Ev_Net_Packet, this); // close all connections CStdLock ConnListLock(&ConnListCSec); for(C4Network2IOConnection *pConn = pConnList, *pNext; pConn; pConn = pNext) @@ -218,7 +218,7 @@ void C4Network2IO::Clear() // by main thread pConnList = NULL; ConnListLock.Clear(); // close net i/o classes - Thread.RemoveProc(this); + Thread.RemoveProc(this); if(pNetIODiscover) { Thread.RemoveProc(pNetIODiscover); delete pNetIODiscover; pNetIODiscover = NULL; } if(pNetIO_TCP) { Thread.RemoveProc(pNetIO_TCP); delete pNetIO_TCP; pNetIO_TCP = NULL; } if(pNetIO_UDP) { Thread.RemoveProc(pNetIO_UDP); delete pNetIO_UDP; pNetIO_UDP = NULL; } @@ -284,15 +284,15 @@ bool C4Network2IO::Connect(const C4NetIO::addr_t &addr, C4Network2IOProtocol ePr void C4Network2IO::SetAcceptMode(bool fnAllowConnect) // by main thread { fAllowConnect = fnAllowConnect; - // Allow connect? Allow discovery of this host - if(fAllowConnect) - { - if(pNetIODiscover) - { - pNetIODiscover->SetDiscoverable(true); - pNetIODiscover->Announce(); - } - } + // Allow connect? Allow discovery of this host + if(fAllowConnect) + { + if(pNetIODiscover) + { + pNetIODiscover->SetDiscoverable(true); + pNetIODiscover->Announce(); + } + } } void C4Network2IO::SetExclusiveConnMode(bool fnExclusiveConn) // by main thread @@ -531,7 +531,7 @@ bool C4Network2IO::OnConn(const C4NetIO::addr_t &PeerAddr, const C4NetIO::addr_t // log Application.InteractiveThread.ThreadLogS("Network: got %s connection from %s:%d", getNetIOName(pNetIO), inet_ntoa(PeerAddr.sin_addr), htons(PeerAddr.sin_port)); #endif - // do event (disabled - unused) + // do event (disabled - unused) // pConn->AddRef(); PushNetEv(NE_Conn, pConn); // ok return true; @@ -557,12 +557,12 @@ void C4Network2IO::OnDisconn(const C4NetIO::addr_t &addr, C4NetIO *pNetIO, const if(!pConn) pConn = GetConnectionByConnAddr(addr, pNetIO); if(!pConn) return; #if(C4NET2IO_DUMP_LEVEL > 0) - // log + // log Application.InteractiveThread.ThreadLogS("Network: %s connection to %s:%d %s (%s)", getNetIOName(pNetIO), inet_ntoa(addr.sin_addr), htons(addr.sin_port), pConn->isConnecting() ? "failed" : "closed" , szReason); #endif - // already closed? ignore - if(!pConn->isClosed()) + // already closed? ignore + if(!pConn->isClosed()) // not accepted yet? count as connection failure pConn->SetStatus(pConn->isHalfAccepted() ? CS_Closed : CS_ConnectFail); // keep connection for main thread message @@ -570,7 +570,7 @@ void C4Network2IO::OnDisconn(const C4NetIO::addr_t &addr, C4NetIO *pNetIO, const // check for pending welcome packets SendConnPackets(); // signal to main thread - Application.InteractiveThread.PushEvent(Ev_Net_Disconn, pConn); + Application.InteractiveThread.PushEvent(Ev_Net_Disconn, pConn); // don't remove connection from list - wait for postmortem or timeout } @@ -621,10 +621,10 @@ bool C4Network2IO::Execute(int iTimeout, pollfd *) iLastPing = iLastExecute; } - // do statistics + // do statistics if(!Inside(iLastStatistic, timeGetTime() - C4NetStatisticsFreq, timeGetTime())) { - GenerateStatistics(iLastExecute - iLastStatistic); + GenerateStatistics(iLastExecute - iLastStatistic); iLastStatistic = iLastExecute; } @@ -770,8 +770,8 @@ C4Network2IOConnection *C4Network2IO::GetConnectionByID(uint32_t iConnID) // by void C4Network2IO::SetReference(C4Network2Reference *pReference) { - if(pRefServer) - pRefServer->SetReference(pReference); + if(pRefServer) + pRefServer->SetReference(pReference); else delete pReference; } @@ -809,10 +809,10 @@ bool C4Network2IO::HandlePacket(const C4NetIOPacket &rPacket, C4Network2IOConnec // unpack packet (yet another no-idea-why-it's-needed-cast) C4IDPacket Pkt; C4PacketBase &PktB = Pkt; try - { - PktB.unpack(rPacket); - } - catch(StdCompiler::Exception *pExc) + { + PktB.unpack(rPacket); + } + catch(StdCompiler::Exception *pExc) { Application.InteractiveThread.ThreadLog("Network: error: Failed to unpack packet id %02x: %s", rPacket.getStatus(), pExc->Msg.getData()); delete pExc; @@ -832,9 +832,9 @@ bool C4Network2IO::HandlePacket(const C4NetIOPacket &rPacket, C4Network2IOConnec (iTime / 1000 / 60 / 60), (iTime / 1000 / 60) % 60, (iTime / 1000) % 60, iTime % 1000, inet_ntoa(pConn->getPeerAddr().sin_addr), htons(pConn->getPeerAddr().sin_port), static_cast(rPacket.getSize()), pConn->getInPacketCounter()); - StdStrBuf Dump = DecompileToBuf(mkNamingAdapt(Pkt, PacketHeader.getData())); - // Put it directly. The standard functions behind StdBuf.Format seem to choke when you pass them too much data. - Application.InteractiveThread.PushEvent(Ev_LogSilent, Dump.GrabPointer()); + StdStrBuf Dump = DecompileToBuf(mkNamingAdapt(Pkt, PacketHeader.getData())); + // Put it directly. The standard functions behind StdBuf.Format seem to choke when you pass them too much data. + Application.InteractiveThread.PushEvent(Ev_LogSilent, Dump.GrabPointer()); } #endif @@ -964,7 +964,7 @@ void C4Network2IO::HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Net if(doAutoAccept(rPkt.getCCore(), *pConn)) { // send answer back - C4PacketConnRe pcr(true, false, "auto accept"); + C4PacketConnRe pcr(true, false, "auto accept"); if(!pConn->Send(MkC4NetIOPacket(PID_ConnRe, pcr))) pConn->Close(); // accept @@ -990,10 +990,10 @@ void C4Network2IO::HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Net GETPKT(C4PacketConnRe, rPkt) // auto accept connection if(rPkt.isOK()) - { - if(pConn->isHalfAccepted() && pConn->isAutoAccepted()) + { + if(pConn->isHalfAccepted() && pConn->isAutoAccepted()) pConn->SetAccepted(); - } + } } break; @@ -1070,7 +1070,7 @@ void C4Network2IO::HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Net void C4Network2IO::HandleFwdReq(const C4PacketFwd &rFwd, C4Network2IOConnection *pBy) { CStdLock ConnListLock(&ConnListCSec); - // init packet + // init packet C4PacketFwd nFwd; nFwd.SetListType(false); // find all clients the message should be forwarded to @@ -1168,18 +1168,18 @@ void C4Network2IO::CheckTimeout() // status timeout if(!pConn->isClosed() && !pConn->isAccepted()) if(difftime(time(NULL), pConn->getTimestamp()) > C4NetAcceptTimeout) - { - Application.InteractiveThread.ThreadLogS("Network: connection accept timeout to %s:%d", inet_ntoa(pConn->getPeerAddr().sin_addr), htons(pConn->getPeerAddr().sin_port)); + { + Application.InteractiveThread.ThreadLogS("Network: connection accept timeout to %s:%d", inet_ntoa(pConn->getPeerAddr().sin_addr), htons(pConn->getPeerAddr().sin_port)); pConn->Close(); - } + } // ping timeout if(pConn->isAccepted()) if((pConn->getLag() != -1 ? pConn->getLag() : 1000 * (time(NULL) - pConn->getTimestamp())) > C4NetPingTimeout) - { - Application.InteractiveThread.ThreadLogS("Network: ping timeout to %s:%d", inet_ntoa(pConn->getPeerAddr().sin_addr), htons(pConn->getPeerAddr().sin_port)); + { + Application.InteractiveThread.ThreadLogS("Network: ping timeout to %s:%d", inet_ntoa(pConn->getPeerAddr().sin_addr), htons(pConn->getPeerAddr().sin_port)); pConn->Close(); - } + } // delayed connection removal if(pConn->isClosed()) if(difftime(time(NULL), pConn->getTimestamp()) > C4NetAcceptTimeout) @@ -1189,40 +1189,40 @@ void C4Network2IO::CheckTimeout() void C4Network2IO::GenerateStatistics(int iInterval) { - int iTCPIRateSum = 0, iTCPORateSum = 0, - iUDPIRateSum = 0, iUDPORateSum = 0; + int iTCPIRateSum = 0, iTCPORateSum = 0, + iUDPIRateSum = 0, iUDPORateSum = 0; - // acquire lock, get connection statistics + // acquire lock, get connection statistics CStdLock ConnListLock(&ConnListCSec); for(C4Network2IOConnection *pConn = pConnList; pConn; pConn = pConn->pNext) - if(pConn->isOpen()) - { - bool fTCP = pConn->getNetClass() == pNetIO_TCP; - pConn->DoStatistics(iInterval, fTCP ? &iTCPIRateSum : &iUDPIRateSum, - fTCP ? &iTCPORateSum : &iUDPORateSum); - } - ConnListLock.Clear(); + if(pConn->isOpen()) + { + bool fTCP = pConn->getNetClass() == pNetIO_TCP; + pConn->DoStatistics(iInterval, fTCP ? &iTCPIRateSum : &iUDPIRateSum, + fTCP ? &iTCPORateSum : &iUDPORateSum); + } + ConnListLock.Clear(); - // get broadcast statistics - int inTCPBCRate = 0, inUDPBCRate = 0; - if(pNetIO_TCP) pNetIO_TCP->GetStatistic(&inTCPBCRate); - if(pNetIO_UDP) pNetIO_UDP->GetStatistic(&inUDPBCRate); + // get broadcast statistics + int inTCPBCRate = 0, inUDPBCRate = 0; + if(pNetIO_TCP) pNetIO_TCP->GetStatistic(&inTCPBCRate); + if(pNetIO_UDP) pNetIO_UDP->GetStatistic(&inUDPBCRate); - // normalize everything - iTCPIRateSum = iTCPIRateSum * 1000 / iInterval; - iTCPORateSum = iTCPORateSum * 1000 / iInterval; - iUDPIRateSum = iUDPIRateSum * 1000 / iInterval; - iUDPORateSum = iUDPORateSum * 1000 / iInterval; - inTCPBCRate = inTCPBCRate * 1000 / iInterval; - inUDPBCRate = inUDPBCRate * 1000 / iInterval; + // normalize everything + iTCPIRateSum = iTCPIRateSum * 1000 / iInterval; + iTCPORateSum = iTCPORateSum * 1000 / iInterval; + iUDPIRateSum = iUDPIRateSum * 1000 / iInterval; + iUDPORateSum = iUDPORateSum * 1000 / iInterval; + inTCPBCRate = inTCPBCRate * 1000 / iInterval; + inUDPBCRate = inUDPBCRate * 1000 / iInterval; - // clear - if(pNetIO_TCP) pNetIO_TCP->ClearStatistic(); - if(pNetIO_UDP) pNetIO_UDP->ClearStatistic(); + // clear + if(pNetIO_TCP) pNetIO_TCP->ClearStatistic(); + if(pNetIO_UDP) pNetIO_UDP->ClearStatistic(); - // save back - iTCPIRate = iTCPIRateSum; iTCPORate = iTCPORateSum; iTCPBCRate = inTCPBCRate; - iUDPIRate = iUDPIRateSum; iUDPORate = iUDPORateSum; iUDPBCRate = inUDPBCRate; + // save back + iTCPIRate = iTCPIRateSum; iTCPORate = iTCPORateSum; iTCPBCRate = inTCPBCRate; + iUDPIRate = iUDPIRateSum; iUDPORate = iUDPORateSum; iUDPBCRate = inUDPBCRate; } void C4Network2IO::SendConnPackets() @@ -1490,21 +1490,21 @@ void C4Network2IOConnection::SetBroadcastTarget(bool fSet) void C4Network2IOConnection::DoStatistics(int iInterval, int *pIRateSum, int *pORateSum) { - // get C4NetIO statistics - int inIRate, inORate, inLoss; - if(!isOpen() || !pNetClass->GetConnStatistic(PeerAddr, &inIRate, &inORate, &inLoss)) - { - iIRate = iORate = iPacketLoss = 0; - return; - } - // normalize - inIRate = inIRate * 1000 / iInterval; - inORate = inORate * 1000 / iInterval; - // set - iIRate = inIRate; iORate = inORate; iPacketLoss = inLoss; - // sum up - if(pIRateSum) *pIRateSum += iIRate; - if(pORateSum) *pORateSum += iORate; + // get C4NetIO statistics + int inIRate, inORate, inLoss; + if(!isOpen() || !pNetClass->GetConnStatistic(PeerAddr, &inIRate, &inORate, &inLoss)) + { + iIRate = iORate = iPacketLoss = 0; + return; + } + // normalize + inIRate = inIRate * 1000 / iInterval; + inORate = inORate * 1000 / iInterval; + // set + iIRate = inIRate; iORate = inORate; iPacketLoss = inLoss; + // sum up + if(pIRateSum) *pIRateSum += iIRate; + if(pORateSum) *pORateSum += iORate; } void C4Network2IOConnection::AddRef() diff --git a/src/network/C4Network2IO.h b/src/network/C4Network2IO.h index d7247bb67..86a33aaf6 100644 --- a/src/network/C4Network2IO.h +++ b/src/network/C4Network2IO.h @@ -40,9 +40,9 @@ const int C4NetTimer = 500, // ms const int C4NetMaxClients = 256; class C4Network2IO - : protected C4InteractiveThread::Callback, - protected C4NetIO::CBClass, - protected StdSchedulerProc + : protected C4InteractiveThread::Callback, + protected C4NetIO::CBClass, + protected StdSchedulerProc { public: C4Network2IO(); @@ -88,18 +88,18 @@ protected: // timer & ping unsigned long iLastExecute, iLastPing; - // statistics - unsigned long iLastStatistic; - int iTCPIRate, iTCPORate, iTCPBCRate, - iUDPIRate, iUDPORate, iUDPBCRate; + // statistics + unsigned long iLastStatistic; + int iTCPIRate, iTCPORate, iTCPBCRate, + iUDPIRate, iUDPORate, iUDPBCRate; // punching C4NetIO::addr_t PuncherAddr; public: - bool hasTCP() const { return !! pNetIO_TCP; } - bool hasUDP() const { return !! pNetIO_UDP; } + bool hasTCP() const { return !! pNetIO_TCP; } + bool hasUDP() const { return !! pNetIO_UDP; } // initialization bool Init(int16_t iPortTCP, int16_t iPortUDP, int16_t iPortDiscovery = -1, int16_t iPortRefServer = -1, bool fBroadcast = false); // by main thread @@ -140,13 +140,13 @@ public: const char *getNetIOName(C4NetIO *pNetIO); C4Network2IOProtocol getNetIOProt(C4NetIO *pNetIO); - // statistics - int getProtIRate(C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPIRate : iUDPIRate; } - int getProtORate(C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPORate : iUDPORate; } - int getProtBCRate(C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPBCRate : iUDPBCRate; } + // statistics + int getProtIRate(C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPIRate : iUDPIRate; } + int getProtORate(C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPORate : iUDPORate; } + int getProtBCRate(C4Network2IOProtocol eProt) const { return eProt == P_TCP ? iTCPBCRate : iUDPBCRate; } - // reference - void SetReference(class C4Network2Reference *pReference); + // reference + void SetReference(class C4Network2Reference *pReference); bool IsReferenceNeeded(); protected: @@ -161,7 +161,7 @@ protected: virtual bool Execute(int iTimeout, pollfd *); virtual int GetNextTick(int Now); // Event callback by C4InteractiveThread - void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData); // by main thread + void OnThreadEvent(C4InteractiveEventType eEvent, void *pEventData); // by main thread // connections list void AddConnection(C4Network2IOConnection *pConn); // by both @@ -187,7 +187,7 @@ protected: // misc bool Ping(); void CheckTimeout(); - void GenerateStatistics(int iInterval); + void GenerateStatistics(int iInterval); void SendConnPackets(); // puncher @@ -230,8 +230,8 @@ protected: unsigned long iLastPong; // last pong received C4ClientCore CCore; // client core (>= CS_HalfAccepted) CStdCSec CCoreCSec; - int iIRate, iORate; // input/output rates (by C4NetIO, in b/s) - int iPacketLoss; // lost packets (in the last seconds) + int iIRate, iORate; // input/output rates (by C4NetIO, in b/s) + int iPacketLoss; // lost packets (in the last seconds) StdCopyStrBuf Password; // password to use for connect bool fConnSent; // initial connection packet send bool fPostMortemSent; // post mortem send @@ -267,9 +267,9 @@ public: bool isHost() const { return CCore.isHost(); } int getPingTime() const { return iPingTime; } int getLag() const; - int getIRate() const { return iIRate; } - int getORate() const { return iORate; } - int getPacketLoss() const { return iPacketLoss; } + int getIRate() const { return iIRate; } + int getORate() const { return iORate; } + int getPacketLoss() const { return iPacketLoss; } const char *getPassword() const { return Password.getData(); } bool isConnSent() const { return fConnSent; } @@ -311,8 +311,8 @@ public: bool Send(const C4NetIOPacket &rPkt); void SetBroadcastTarget(bool fSet); // (only call after C4Network2IO::BeginBroadcast!) - // statistics - void DoStatistics(int iInterval, int *pIRateSum, int *pORateSum); + // statistics + void DoStatistics(int iInterval, int *pIRateSum, int *pORateSum); // reference counting void AddRef(); void DelRef(); diff --git a/src/network/C4Network2IRC.cpp b/src/network/C4Network2IRC.cpp index 9bb3737a3..fc09bb189 100644 --- a/src/network/C4Network2IRC.cpp +++ b/src/network/C4Network2IRC.cpp @@ -266,8 +266,8 @@ bool C4Network2IRCClient::OnConn(const C4NetIO::addr_t &AddrPeer, const C4NetIO: void C4Network2IRCClient::OnDisconn(const C4NetIO::addr_t &AddrPeer, C4NetIO *pNetIO, const char *szReason) { fConnected = false; - // Show a message with the reason - PushMessage(MSG_Status, "", Nick.getData(), FormatString(LoadResStr("IDS_MSG_DISCONNECTEDFROMSERVER"), szReason).getData()); + // Show a message with the reason + PushMessage(MSG_Status, "", Nick.getData(), FormatString(LoadResStr("IDS_MSG_DISCONNECTEDFROMSERVER"), szReason).getData()); } void C4Network2IRCClient::OnPacket(const class C4NetIOPacket &rPacket, C4NetIO *pNetIO) @@ -397,36 +397,36 @@ bool C4Network2IRCClient::Part(const char *szChannel) bool C4Network2IRCClient::Message(const char *szTarget, const char *szText) { if(!Send("PRIVMSG", FormatString("%s :%s", szTarget, szText).getData())) - return false; - PushMessage(MSG_Message, Nick.getData(), szTarget, szText); - return true; + return false; + PushMessage(MSG_Message, Nick.getData(), szTarget, szText); + return true; } bool C4Network2IRCClient::Notice(const char *szTarget, const char *szText) { if(!Send("NOTICE", FormatString("%s :%s", szTarget, szText).getData())) - return false; - PushMessage(MSG_Notice, Nick.getData(), szTarget, szText); - return true; + return false; + PushMessage(MSG_Notice, Nick.getData(), szTarget, szText); + return true; } bool C4Network2IRCClient::Action(const char *szTarget, const char *szText) - { - if(!Send("PRIVMSG", FormatString("%s :\1ACTION %s\1", szTarget, szText).getData())) - return false; - PushMessage(MSG_Action, Nick.getData(), szTarget, szText); - return true; - } + { + if(!Send("PRIVMSG", FormatString("%s :\1ACTION %s\1", szTarget, szText).getData())) + return false; + PushMessage(MSG_Action, Nick.getData(), szTarget, szText); + return true; + } bool C4Network2IRCClient::ChangeNick(const char *szNewNick) - { - return Send("NICK", szNewNick); - } + { + return Send("NICK", szNewNick); + } bool C4Network2IRCClient::RegisterNick(const char *szPassword, const char *szMail) - { + { return Send("PRIVMSG", FormatString("NickServ :REGISTER %s %s", szPassword, szMail).getData()); - } + } void C4Network2IRCClient::OnCommand(const char *szSender, const char *szCommand, const char *szParameters) { @@ -513,14 +513,14 @@ void C4Network2IRCClient::OnCommand(const char *szSender, const char *szCommand, // Get comment StdStrBuf Comment = ircExtractPar(&szParameters); // Format status message - StdStrBuf Message = FormatString(LoadResStr("IDS_MSG_HASDISCONNECTED"), SenderNick.getData(), Comment.getData()); - // Remove him from all channels - for(C4Network2IRCChannel *pChan = pChannels; pChan; pChan = pChan->Next) - if(pChan->getUser(SenderNick.getData())) - { - pChan->OnPart(SenderNick.getData(), "Quit"); - PushMessage(MSG_Status, szSender, pChan->getName(), Message.getData()); - } + StdStrBuf Message = FormatString(LoadResStr("IDS_MSG_HASDISCONNECTED"), SenderNick.getData(), Comment.getData()); + // Remove him from all channels + for(C4Network2IRCChannel *pChan = pChannels; pChan; pChan = pChan->Next) + if(pChan->getUser(SenderNick.getData())) + { + pChan->OnPart(SenderNick.getData(), "Quit"); + PushMessage(MSG_Status, szSender, pChan->getName(), Message.getData()); + } } // Topic change? if(SEqualNoCase(szCommand, "TOPIC")) @@ -562,18 +562,18 @@ void C4Network2IRCClient::OnCommand(const char *szSender, const char *szCommand, // Get new nick StdStrBuf NewNick = ircExtractPar(&szParameters); // Format status message - StdStrBuf Message = FormatString(LoadResStr("IDS_MSG_ISNOWKNOWNAS"), SenderNick.getData(), NewNick.getData()); - // Rename on all channels - for(C4Network2IRCChannel *pChan = pChannels; pChan; pChan = pChan->Next) - if(pChan->getUser(SenderNick.getData())) - { - pChan->OnPart(SenderNick.getData(), "Nickchange"); - pChan->OnJoin(NewNick.getData()); - PushMessage(MSG_Status, szSender, pChan->getName(), Message.getData()); - } - // Self? - if(SenderNick == Nick) - Nick = NewNick; + StdStrBuf Message = FormatString(LoadResStr("IDS_MSG_ISNOWKNOWNAS"), SenderNick.getData(), NewNick.getData()); + // Rename on all channels + for(C4Network2IRCChannel *pChan = pChannels; pChan; pChan = pChan->Next) + if(pChan->getUser(SenderNick.getData())) + { + pChan->OnPart(SenderNick.getData(), "Nickchange"); + pChan->OnJoin(NewNick.getData()); + PushMessage(MSG_Status, szSender, pChan->getName(), Message.getData()); + } + // Self? + if(SenderNick == Nick) + Nick = NewNick; } } @@ -638,8 +638,8 @@ void C4Network2IRCClient::OnNumericCommand(const char *szSender, int iCommand, c // Finish AddChannel(Channel.getData())->OnUsersEnd(); fShowMessage = false; - // Notify - if(pNotify) pNotify->PushEvent(Ev_IRC_Message, this); + // Notify + if(pNotify) pNotify->PushEvent(Ev_IRC_Message, this); } break; @@ -785,9 +785,9 @@ void C4Network2IRCClient::PushMessage(C4Network2IRCMessageType eType, const char iUnreadLogLength++; while(iLogLength > C4NetIRCMaxLogLength) PopMessage(); - // Notify - if(pNotify) - pNotify->PushEvent(Ev_IRC_Message, this); + // Notify + if(pNotify) + pNotify->PushEvent(Ev_IRC_Message, this); } C4Network2IRCChannel *C4Network2IRCClient::AddChannel(const char *szName) diff --git a/src/network/C4Network2IRC.h b/src/network/C4Network2IRC.h index e781d60e7..41fc013a6 100644 --- a/src/network/C4Network2IRC.h +++ b/src/network/C4Network2IRC.h @@ -147,8 +147,8 @@ class C4Network2IRCClient : public C4NetIOTCP, private C4NetIO::CBClass C4Network2IRCMessage *pLog, *pLogLastRead, *pLogEnd; int32_t iLogLength, iUnreadLogLength; - // Event queue for notify - class C4InteractiveThread *pNotify; + // Event queue for notify + class C4InteractiveThread *pNotify; // Critical section for data CStdCSec CSec; @@ -186,8 +186,8 @@ class C4Network2IRCClient : public C4NetIOTCP, private C4NetIO::CBClass using C4NetIOTCP::Send; bool Send(const char *szCommand, const char *szParameters = NULL); - // Notfiy interface - void SetNotify(class C4InteractiveThread *pnNotify) { pNotify = pnNotify; } + // Notfiy interface + void SetNotify(class C4InteractiveThread *pnNotify) { pNotify = pnNotify; } // Special IRC commands bool Quit(const char *szReason); @@ -195,9 +195,9 @@ class C4Network2IRCClient : public C4NetIOTCP, private C4NetIO::CBClass bool Part(const char *szChannel); bool Message(const char *szTarget, const char *szText); bool Notice(const char *szTarget, const char *szText); - bool Action(const char *szTarget, const char *szText); - bool ChangeNick(const char *szNewNick); - bool RegisterNick(const char *szPassword, const char *szMail); + bool Action(const char *szTarget, const char *szText); + bool ChangeNick(const char *szNewNick); + bool RegisterNick(const char *szPassword, const char *szMail); // Status bool IsActive() const { return fConnecting || fConnected; } diff --git a/src/network/C4Network2Players.cpp b/src/network/C4Network2Players.cpp index ebee7449f..05e8e5350 100644 --- a/src/network/C4Network2Players.cpp +++ b/src/network/C4Network2Players.cpp @@ -66,8 +66,8 @@ bool C4Network2Players::JoinLocalPlayer(const char *szLocalPlayerFilename, bool // shouldn't even come here though assert(!Game.C4S.Head.Replay); if (Game.C4S.Head.Replay) return false; - // if observing: don't try - if (Game.Clients.getLocal()->isObserver()) return false; + // if observing: don't try + if (Game.Clients.getLocal()->isObserver()) return false; // network only assert(::Network.isEnabled()); // create join info packet @@ -101,9 +101,9 @@ bool C4Network2Players::JoinLocalPlayer(const char *szLocalPlayerFilename, bool // with infos of all other clients if (fAdd && !JoinRequest.Info.GetPlayerCount()) return false; ::Network.Clients.SendMsgToHost(MkC4NetIOPacket(PID_PlayerInfoUpdReq, JoinRequest)); - // request activation - if(JoinRequest.Info.GetPlayerCount() && !Game.Clients.getLocal()->isActivated()) - ::Network.RequestActivate(); + // request activation + if(JoinRequest.Info.GetPlayerCount() && !Game.Clients.getLocal()->isActivated()) + ::Network.RequestActivate(); } // done, success return true; @@ -177,11 +177,11 @@ void C4Network2Players::HandlePlayerInfoUpdRequest(const class C4ClientPlayerInf // this may only change colors and names of all unjoined players (which is all players in lobby mode) // any affected players will get an updated-flag rInfoList.UpdatePlayerAttributes(&OwnInfoPacket, true); - // league score gains may now be different - rInfoList.ResetLeagueProjectedGain(true); - int32_t iPlrInfo = 0; - C4PlayerInfo *pPlrInfo; - while ((pPlrInfo = OwnInfoPacket.GetPlayerInfo(iPlrInfo++))) pPlrInfo->ResetLeagueProjectedGain(); + // league score gains may now be different + rInfoList.ResetLeagueProjectedGain(true); + int32_t iPlrInfo = 0; + C4PlayerInfo *pPlrInfo; + while ((pPlrInfo = OwnInfoPacket.GetPlayerInfo(iPlrInfo++))) pPlrInfo->ResetLeagueProjectedGain(); if (Game.Parameters.isLeague()) { // lobby only @@ -210,7 +210,7 @@ void C4Network2Players::HandlePlayerInfoUpdRequest(const class C4ClientPlayerInf // so future player join request will take the other joined clients into consideration // when assigning player colors, etc.; it will also start resource loading // in running mode, this call will also put the actual player joins into the queue - ::Control.DoInput(CID_PlrInfo, new C4ControlPlayerInfo(OwnInfoPacket), CDT_Direct); + ::Control.DoInput(CID_PlrInfo, new C4ControlPlayerInfo(OwnInfoPacket), CDT_Direct); // notify lobby of updates C4GameLobby::MainDlg *pLobby = ::Network.GetLobby(); if (pLobby) pLobby->OnPlayersChange(); @@ -335,7 +335,7 @@ void C4Network2Players::JoinUnjoinedPlayersInControlQueue(C4ClientPlayerInfos *p pInfo->SetJoinIssued(); // do so! C4Network2Res *pPlrRes = pInfo->GetRes(); - C4Network2Client *pClient = ::Network.Clients.GetClientByID(pNewPacket->GetClientID()); + C4Network2Client *pClient = ::Network.Clients.GetClientByID(pNewPacket->GetClientID()); if (!pPlrRes || (!pClient && pNewPacket->GetClientID() != ::Control.ClientID())) if (pInfo->GetType() != C4PT_Script) { @@ -361,7 +361,7 @@ void C4Network2Players::JoinUnjoinedPlayersInControlQueue(C4ClientPlayerInfos *p void C4Network2Players::HandlePacket(char cStatus, const C4PacketBase *pPacket, C4Network2IOConnection *pConn) { - if(!pConn) return; + if(!pConn) return; // find associated client C4Network2Client *pClient = ::Network.Clients.GetClient(pConn); @@ -422,8 +422,8 @@ void C4Network2Players::OnClientPart(C4Client *pPartClient) rInfoList.UpdatePlayerAttributes(); // team distribution of remaining unjoined players may change Game.Teams.RecheckTeams(); - // league score gains may now be different - Game.PlayerInfos.ResetLeagueProjectedGain(true); + // league score gains may now be different + Game.PlayerInfos.ResetLeagueProjectedGain(true); // send changes to all clients and reset update flags SendUpdatedPlayers(); } diff --git a/src/network/C4Network2Reference.cpp b/src/network/C4Network2Reference.cpp index fef13e47f..8a110d9d3 100644 --- a/src/network/C4Network2Reference.cpp +++ b/src/network/C4Network2Reference.cpp @@ -85,18 +85,18 @@ void C4Network2Reference::InitLocal() void C4Network2Reference::SortNullIPsBack() { - // Sort all addresses with zero IP to back of list - int iSortAddrCnt = iAddrCnt; - for(int i = 0; i < iSortAddrCnt; i++) - if(Addrs[i].isIPNull()) - { - C4Network2Address Addr = Addrs[i]; - for(int j = i + 1; j < iAddrCnt; j++) - Addrs[j - 1] = Addrs[j]; - Addrs[iAddrCnt - 1] = Addr; - // Correct position - i--; iSortAddrCnt--; - } + // Sort all addresses with zero IP to back of list + int iSortAddrCnt = iAddrCnt; + for(int i = 0; i < iSortAddrCnt; i++) + if(Addrs[i].isIPNull()) + { + C4Network2Address Addr = Addrs[i]; + for(int j = i + 1; j < iAddrCnt; j++) + Addrs[j - 1] = Addrs[j]; + Addrs[iAddrCnt - 1] = Addr; + // Correct position + i--; iSortAddrCnt--; + } } void C4Network2Reference::CompileFunc(StdCompiler *pComp) @@ -152,19 +152,19 @@ C4Network2RefServer::C4Network2RefServer() C4Network2RefServer::~C4Network2RefServer() { - Clear(); + Clear(); } void C4Network2RefServer::Clear() { - C4NetIOTCP::Close(); - delete pReference; pReference = NULL; + C4NetIOTCP::Close(); + delete pReference; pReference = NULL; } void C4Network2RefServer::SetReference(C4Network2Reference *pNewReference) { - CStdLock RefLock(&RefCSec); - delete pReference; pReference = pNewReference; + CStdLock RefLock(&RefCSec); + delete pReference; pReference = pNewReference; } void C4Network2RefServer::PackPacket(const C4NetIOPacket &rPacket, StdBuf &rOutBuf) @@ -203,16 +203,16 @@ void C4Network2RefServer::RespondNotImplemented(const C4NetIO::addr_t &addr, con void C4Network2RefServer::RespondReference(const C4NetIO::addr_t &addr) { - CStdLock RefLock(&RefCSec); + CStdLock RefLock(&RefCSec); // Pack StdStrBuf PacketData = DecompileToBuf(mkNamingPtrAdapt(pReference, "Reference")); // Create header StdStrBuf Header = FormatString( "HTTP/1.1 200 Found\r\n" - "Content-Length: %lu\r\n" - "Content-Type: text/plain; charset=UTF-8\r\n" - "Server: " C4ENGINENAME "/" C4VERSION "\r\n" - "\r\n", + "Content-Length: %lu\r\n" + "Content-Type: text/plain; charset=UTF-8\r\n" + "Server: " C4ENGINENAME "/" C4VERSION "\r\n" + "\r\n", static_cast(PacketData.getLength())); // Send back Send(C4NetIOPacket(Header, Header.getLength(), false, addr)); @@ -225,7 +225,7 @@ void C4Network2RefServer::RespondReference(const C4NetIO::addr_t &addr) C4Network2HTTPClient::C4Network2HTTPClient() : fBinary(false), fBusy(false), fSuccess(false), fConnected(false), iDataOffset(0), iDownloadedSize(0), iTotalSize(0), - pNotify(NULL) + pNotify(NULL) { C4NetIOTCP::SetCallback(this); } @@ -242,8 +242,8 @@ void C4Network2HTTPClient::PackPacket(const C4NetIOPacket &rPacket, StdBuf &rOut size_t C4Network2HTTPClient::UnpackPacket(const StdBuf &rInBuf, const C4NetIO::addr_t &addr) { - // since new data arrived, increase timeout time - ResetRequestTimeout(); + // since new data arrived, increase timeout time + ResetRequestTimeout(); // Check for complete header if (!iDataOffset) { @@ -283,8 +283,8 @@ size_t C4Network2HTTPClient::UnpackPacket(const StdBuf &rInBuf, const C4NetIO::a else ResultString.Copy(getBufPtr(Data), Data.getSize()); fBusy = false; fSuccess = true; - // Callback - OnPacket(C4NetIOPacket(Data, addr), this); + // Callback + OnPacket(C4NetIOPacket(Data, addr), this); // Done Close(addr); return rInBuf.getSize(); @@ -404,16 +404,16 @@ void C4Network2HTTPClient::OnDisconn(const C4NetIO::addr_t &AddrPeer, C4NetIO *p Error.Format("Unexpected disconnect: %s", szReason); } fConnected = false; - // Notify - if(pNotify) - pNotify->PushEvent(Ev_HTTP_Response, this); + // Notify + if(pNotify) + pNotify->PushEvent(Ev_HTTP_Response, this); } void C4Network2HTTPClient::OnPacket(const class C4NetIOPacket &rPacket, C4NetIO *pNetIO) { // Everything worthwhile was already done in UnpackPacket. Only do notify callback - if(pNotify) - pNotify->PushEvent(Ev_HTTP_Response, this); + if(pNotify) + pNotify->PushEvent(Ev_HTTP_Response, this); } bool C4Network2HTTPClient::Execute(int iMaxTime) @@ -448,38 +448,38 @@ bool C4Network2HTTPClient::Query(const StdBuf &Data, bool fBinary) // Create request const char *szCharset = GetCharsetCodeName(LoadResStr("IDS_LANG_CHARSET")); StdStrBuf Header; - if(Data.getSize()) - Header.Format( - "POST %s HTTP/1.0\r\n" - "Host: %s\r\n" - "Connection: Close\r\n" - "Content-Length: %lu\r\n" - "Content-Type: text/plain; encoding=%s\r\n" - "Accept-Charset: %s\r\n" - "Accept-Encoding: gzip\r\n" - "Accept-Language: %s\r\n" - "User-Agent: " C4ENGINENAME "/" C4VERSION "\r\n" - "\r\n", - RequestPath.getData(), - Server.getData(), - static_cast(Data.getSize()), - szCharset, - szCharset, - Config.General.LanguageEx); - else - Header.Format( - "GET %s HTTP/1.0\r\n" - "Host: %s\r\n" - "Connection: Close\r\n" - "Accept-Charset: %s\r\n" - "Accept-Encoding: gzip\r\n" - "Accept-Language: %s\r\n" - "User-Agent: " C4ENGINENAME "/" C4VERSION "\r\n" - "\r\n", - RequestPath.getData(), - Server.getData(), - szCharset, - Config.General.LanguageEx); + if(Data.getSize()) + Header.Format( + "POST %s HTTP/1.0\r\n" + "Host: %s\r\n" + "Connection: Close\r\n" + "Content-Length: %lu\r\n" + "Content-Type: text/plain; encoding=%s\r\n" + "Accept-Charset: %s\r\n" + "Accept-Encoding: gzip\r\n" + "Accept-Language: %s\r\n" + "User-Agent: " C4ENGINENAME "/" C4VERSION "\r\n" + "\r\n", + RequestPath.getData(), + Server.getData(), + static_cast(Data.getSize()), + szCharset, + szCharset, + Config.General.LanguageEx); + else + Header.Format( + "GET %s HTTP/1.0\r\n" + "Host: %s\r\n" + "Connection: Close\r\n" + "Accept-Charset: %s\r\n" + "Accept-Encoding: gzip\r\n" + "Accept-Language: %s\r\n" + "User-Agent: " C4ENGINENAME "/" C4VERSION "\r\n" + "\r\n", + RequestPath.getData(), + Server.getData(), + szCharset, + Config.General.LanguageEx); // Compose query Request.Take(Header.GrabPointer(), Header.getLength()); Request.Append(Data); @@ -490,7 +490,7 @@ bool C4Network2HTTPClient::Query(const StdBuf &Data, bool fBinary) fBusy = true; iDataOffset = 0; ResetRequestTimeout(); - ResetError(); + ResetError(); return true; } @@ -539,12 +539,12 @@ bool C4Network2HTTPClient::SetServer(const char *szServerAddress) SetError(FormatString("Could not resolve server address %s!", Server.getData()).getData()); return false; } - // Remove port - const char *pColon = strchr(Server.getData(), ':'); - if(pColon) - Server.SetLength(pColon - Server.getData()); + // Remove port + const char *pColon = strchr(Server.getData(), ':'); + if(pColon) + Server.SetLength(pColon - Server.getData()); // Done - ResetError(); + ResetError(); return true; } @@ -555,8 +555,8 @@ bool C4Network2RefClient::QueryReferences() { // invalidate version fVerSet = false; - // Perform an Query query - return Query(NULL, false); + // Perform an Query query + return Query(NULL, false); } bool C4Network2RefClient::GetReferences(C4Network2Reference **&rpReferences, int32_t &rRefCount) @@ -602,7 +602,7 @@ bool C4Network2RefClient::GetReferences(C4Network2Reference **&rpReferences, int // validate version if (MasterVersion.iVer[0]) fVerSet = true; // Done - ResetError(); + ResetError(); return true; } diff --git a/src/network/C4Network2Reference.h b/src/network/C4Network2Reference.h index 56b363afc..c1f53ee28 100644 --- a/src/network/C4Network2Reference.h +++ b/src/network/C4Network2Reference.h @@ -81,7 +81,7 @@ public: void InitLocal(); - void SortNullIPsBack(); + void SortNullIPsBack(); void CompileFunc(StdCompiler *pComp); }; @@ -94,12 +94,12 @@ public: virtual ~C4Network2RefServer(); private: - CStdCSec RefCSec; - C4Network2Reference *pReference; + CStdCSec RefCSec; + C4Network2Reference *pReference; public: - void Clear(); - void SetReference(C4Network2Reference *pReference); + void Clear(); + void SetReference(C4Network2Reference *pReference); protected: // Overridden @@ -136,11 +136,11 @@ private: size_t iDownloadedSize, iTotalSize; bool fCompressed; - // Event queue to use for notify when something happens - class C4InteractiveThread *pNotify; + // Event queue to use for notify when something happens + class C4InteractiveThread *pNotify; protected: - StdCopyBuf ResultBin; // set if fBinary + StdCopyBuf ResultBin; // set if fBinary StdCopyStrBuf ResultString; // set if !fBinary protected: @@ -158,26 +158,26 @@ protected: virtual int32_t GetDefaultPort() { return 80; } public: - bool Query(const StdBuf &Data, bool fBinary); - bool Query(const char *szData, bool fBinary) { return Query(StdBuf(szData, SLen(szData)), fBinary); } + bool Query(const StdBuf &Data, bool fBinary); + bool Query(const char *szData, bool fBinary) { return Query(StdBuf(szData, SLen(szData)), fBinary); } - bool isBusy() const { return fBusy; } - bool isSuccess() const { return fSuccess; } + bool isBusy() const { return fBusy; } + bool isSuccess() const { return fSuccess; } bool isConnected() const { return fConnected; } size_t getTotalSize() const { return iTotalSize; } size_t getDownloadedSize() const { return iDownloadedSize; } - const StdBuf &getResultBin() const { assert(fBinary); return ResultBin; } + const StdBuf &getResultBin() const { assert(fBinary); return ResultBin; } const char *getResultString() const { assert(!fBinary); return ResultString.getData(); } const char *getServerName() const { return Server.getData(); } const char *getRequest() const { return RequestPath.getData(); } const C4NetIO::addr_t &getServerAddress() const { return ServerAddr; } void Cancel(const char *szReason); - void Clear(); + void Clear(); - bool SetServer(const char *szServerAddress); + bool SetServer(const char *szServerAddress); - void SetNotify(class C4InteractiveThread *pnNotify) { pNotify = pnNotify; } + void SetNotify(class C4InteractiveThread *pnNotify) { pNotify = pnNotify; } // Overridden virtual bool Execute(int iMaxTime, pollfd * readyfds) { return Execute(iMaxTime); } @@ -200,8 +200,8 @@ protected: public: C4Network2RefClient() : C4Network2HTTPClient(), fVerSet(false) {} - bool QueryReferences(); - bool GetReferences(C4Network2Reference **&rpReferences, int32_t &rRefCount); + bool QueryReferences(); + bool GetReferences(C4Network2Reference **&rpReferences, int32_t &rRefCount); bool GetMasterVersion(C4GameVersion *pSaveToVer); // call only after GetReferences }; diff --git a/src/network/C4Network2Res.cpp b/src/network/C4Network2Res.cpp index 45b03d719..c91cd2ca3 100644 --- a/src/network/C4Network2Res.cpp +++ b/src/network/C4Network2Res.cpp @@ -123,9 +123,9 @@ void C4Network2ResCore::Clear() void C4Network2ResCore::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkEnumAdaptT(eType, C4Network2ResType_EnumMap), "Type", NRT_Null)); - pComp->Value(mkNamingAdapt(iID, "ID", -1)); - pComp->Value(mkNamingAdapt(iDerID, "DerID", -1)); + pComp->Value(mkNamingAdapt(mkEnumAdaptT(eType, C4Network2ResType_EnumMap), "Type", NRT_Null)); + pComp->Value(mkNamingAdapt(iID, "ID", -1)); + pComp->Value(mkNamingAdapt(iDerID, "DerID", -1)); pComp->Value(mkNamingAdapt(fLoadable, "Loadable", true)); if(fLoadable) { @@ -134,12 +134,12 @@ void C4Network2ResCore::CompileFunc(StdCompiler *pComp) pComp->Value(mkNamingAdapt(iChunkSize, "ChunkSize", C4NetResChunkSize)); if(!iChunkSize) pComp->excCorrupt("zero chunk size"); } - pComp->Value(mkNamingAdapt(iContentsCRC, "ContentsCRC", 0U)); + pComp->Value(mkNamingAdapt(iContentsCRC, "ContentsCRC", 0U)); pComp->Value(mkNamingCountAdapt(fHasFileSHA, "FileSHA")); if(fHasFileSHA) pComp->Value(mkNamingAdapt(mkHexAdapt(FileSHA), "FileSHA")); - pComp->Value(mkNamingAdapt(mkNetFilenameAdapt(FileName), "Filename", "")); - pComp->Value(mkNamingAdapt(mkNetFilenameAdapt(Author), "Author", "")); + pComp->Value(mkNamingAdapt(mkNetFilenameAdapt(FileName), "Filename", "")); + pComp->Value(mkNamingAdapt(mkNetFilenameAdapt(Author), "Author", "")); } // *** C4Network2ResLoad @@ -329,33 +329,33 @@ int32_t C4Network2ResChunkData::getPresentChunk(int32_t iNr) const void C4Network2ResChunkData::CompileFunc(StdCompiler *pComp) { - bool fCompiler = pComp->isCompiler(); - if(fCompiler) Clear(); - // Data - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iChunkCnt), "ChunkCnt", 0)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iChunkRangeCnt), "ChunkRangeCnt", 0)); + bool fCompiler = pComp->isCompiler(); + if(fCompiler) Clear(); + // Data + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iChunkCnt), "ChunkCnt", 0)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iChunkRangeCnt), "ChunkRangeCnt", 0)); // Ranges - if(!pComp->Name("Ranges")) - pComp->excCorrupt("ResChunk ranges expected!"); - ChunkRange *pRange = NULL; + if(!pComp->Name("Ranges")) + pComp->excCorrupt("ResChunk ranges expected!"); + ChunkRange *pRange = NULL; for(int32_t i = 0; i < iChunkRangeCnt; i++) { - // Create new range / go to next range - if(fCompiler) - pRange = (pRange ? pRange->Next : pChunkRanges) = new ChunkRange; - else - pRange = pRange ? pRange->Next : pChunkRanges; - // Seperate - if(i) pComp->Seperator(); - // Compile range + // Create new range / go to next range + if(fCompiler) + pRange = (pRange ? pRange->Next : pChunkRanges) = new ChunkRange; + else + pRange = pRange ? pRange->Next : pChunkRanges; + // Seperate + if(i) pComp->Seperator(); + // Compile range pComp->Value(mkIntPackAdapt(pRange->Start)); - pComp->Seperator(StdCompiler::SEP_PART2); + pComp->Seperator(StdCompiler::SEP_PART2); pComp->Value(mkIntPackAdapt(pRange->Length)); } - // Terminate list - if(fCompiler) - (pRange ? pRange->Next : pChunkRanges) = NULL; - pComp->NameEnd(); + // Terminate list + if(fCompiler) + (pRange ? pRange->Next : pChunkRanges) = NULL; + pComp->NameEnd(); } // *** C4Network2Res @@ -375,13 +375,13 @@ C4Network2Res::C4Network2Res(C4Network2ResList *pnParent) C4Network2Res::~C4Network2Res() { - assert(!pNext); + assert(!pNext); Clear(); } bool C4Network2Res::SetByFile(const char *strFilePath, bool fTemp, C4Network2ResType eType, int32_t iResID, const char *szResName, bool fSilent) { - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); // default ressource name: relative path if(!szResName) szResName = Config.AtRelativePath(strFilePath); SCopy(strFilePath, szFile, sizeof(szFile)-1); @@ -415,7 +415,7 @@ bool C4Network2Res::SetByFile(const char *strFilePath, bool fTemp, C4Network2Res bool C4Network2Res::SetByGroup(C4Group *pGrp, bool fTemp, C4Network2ResType eType, int32_t iResID, const char *szResName, bool fSilent) // by main thread { Clear(); - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); // default ressource name: relative path StdStrBuf sResName; if (szResName) @@ -501,7 +501,7 @@ bool C4Network2Res::SetByCore(const C4Network2ResCore &nCore, bool fSilent, cons bool C4Network2Res::SetLoad(const C4Network2ResCore &nCore) // by main thread { Clear(); - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); // must be loadable if(!nCore.isLoadable()) return false; // save core, set chunks @@ -530,24 +530,24 @@ bool C4Network2Res::SetLoad(const C4Network2ResCore &nCore) // by main thread bool C4Network2Res::SetDerived(const char *strName, const char *strFilePath, bool fTemp, C4Network2ResType eType, int32_t iDResID) { - Clear(); - CStdLock FileLock(&FileCSec); - // set core - Core.Set(eType, C4NetResIDAnonymous, strName, ~0, ""); - Core.SetDerived(iDResID); - // save file path - SCopy(strFilePath, szFile, _MAX_PATH); - *szStandalone = '\0'; - // set flags - fDirty = false; - fTempFile = fTemp; - fStandaloneFailed = false; - fRemoved = false; + Clear(); + CStdLock FileLock(&FileCSec); + // set core + Core.Set(eType, C4NetResIDAnonymous, strName, ~0, ""); + Core.SetDerived(iDResID); + // save file path + SCopy(strFilePath, szFile, _MAX_PATH); + *szStandalone = '\0'; + // set flags + fDirty = false; + fTempFile = fTemp; + fStandaloneFailed = false; + fRemoved = false; iLastReqTime = time(NULL); fLoading = false; - // Do not set any chunk data - anonymous ressources are very likely to change. - // Wait for FinishDerived()-call. - return true; + // Do not set any chunk data - anonymous ressources are very likely to change. + // Wait for FinishDerived()-call. + return true; } void C4Network2Res::ChangeID(int32_t inID) @@ -560,7 +560,7 @@ bool C4Network2Res::IsBinaryCompatible() // returns wether the standalone of this ressource is binary compatible // to the official version (means: matches the file checksum) - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); // standalone set? ok then (see GetStandalone) if(szStandalone[0]) return true; // is a directory? @@ -587,10 +587,10 @@ bool C4Network2Res::GetStandalone(char *pTo, int32_t iMaxL, bool fSetOfficial, b if(!fSetOfficial && !Core.isLoadable()) return false; // set flag, so failure below will let future calls fail fStandaloneFailed = true; - // lock file - CStdLock FileLock(&FileCSec); + // lock file + CStdLock FileLock(&FileCSec); - // directory? + // directory? SCopy(szFile, szStandalone, sizeof(szStandalone)-1); if(DirectoryExists(szFile)) { @@ -697,105 +697,105 @@ bool C4Network2Res::CalculateSHA() C4Network2Res::Ref C4Network2Res::Derive() { - // Called before the file is changed. Rescues all files and creates a - // new ressource for the file. This ressource is flagged as "anonymous", as it - // has no official core (no res ID, to be exact). - // The resource gets its final core when FinishDerive() is called. + // Called before the file is changed. Rescues all files and creates a + // new ressource for the file. This ressource is flagged as "anonymous", as it + // has no official core (no res ID, to be exact). + // The resource gets its final core when FinishDerive() is called. - // For security: This doesn't make much sense if the resource is currently being - // loaded. So better assume the caller doesn't know what he's doing and check. - if(isLoading()) return NULL; + // For security: This doesn't make much sense if the resource is currently being + // loaded. So better assume the caller doesn't know what he's doing and check. + if(isLoading()) return NULL; - CStdLock FileLock(&FileCSec); - // Save back original file name - char szOrgFile[_MAX_PATH+1]; - SCopy(szFile, szOrgFile, _MAX_PATH); - bool fOrgTempFile = fTempFile; + CStdLock FileLock(&FileCSec); + // Save back original file name + char szOrgFile[_MAX_PATH+1]; + SCopy(szFile, szOrgFile, _MAX_PATH); + bool fOrgTempFile = fTempFile; - // Create a copy of the file, if neccessary - if(!*szStandalone || SEqual(szStandalone, szFile)) - { + // Create a copy of the file, if neccessary + if(!*szStandalone || SEqual(szStandalone, szFile)) + { if(!pParent->FindTempResFileName(szOrgFile, szFile)) { Log("Derive: could not find free name for temporary file!"); return NULL; } if(!C4Group_CopyItem(szOrgFile, szFile)) { Log("Derive: could not copy to temporary file!"); return NULL; } - // set standalone - if(*szStandalone) - SCopy(szFile, szStandalone, _MAX_PATH); - fTempFile = true; - } - else - { - // Standlone exists: Just set szFile to point on the standlone. It's - // assumed that the original file isn't of intrest after this point anyway. - SCopy(szStandalone, szFile, _MAX_PATH); - fTempFile = true; - } + // set standalone + if(*szStandalone) + SCopy(szFile, szStandalone, _MAX_PATH); + fTempFile = true; + } + else + { + // Standlone exists: Just set szFile to point on the standlone. It's + // assumed that the original file isn't of intrest after this point anyway. + SCopy(szStandalone, szFile, _MAX_PATH); + fTempFile = true; + } Application.InteractiveThread.ThreadLogS("Network: Ressource: deriving from %d:%s, original at %s", getResID(), Core.getFileName(), szFile); - // (note: should remove temp file if something fails after this point) + // (note: should remove temp file if something fails after this point) - // create new ressource + // create new ressource C4Network2Res::Ref pDRes = new C4Network2Res(pParent); - if(!pDRes) return NULL; + if(!pDRes) return NULL; - // initialize - if(!pDRes->SetDerived(Core.getFileName(), szOrgFile, fOrgTempFile, getType(), getResID())) - return NULL; + // initialize + if(!pDRes->SetDerived(Core.getFileName(), szOrgFile, fOrgTempFile, getType(), getResID())) + return NULL; - // add to list - pParent->Add(pDRes); + // add to list + pParent->Add(pDRes); - // return new ressource - return pDRes; + // return new ressource + return pDRes; } bool C4Network2Res::FinishDerive() // by main thread { - // All changes have been made. Register this ressource with a new ID. + // All changes have been made. Register this ressource with a new ID. - // security - if(!isAnonymous()) return false; + // security + if(!isAnonymous()) return false; - CStdLock FileLock(&FileCSec); - // Save back data - int32_t iDerID = Core.getDerID(); - char szName[_MAX_PATH+1]; SCopy(Core.getFileName(), szName, _MAX_PATH); - char szFileC[_MAX_PATH+1]; SCopy(szFile, szFileC, _MAX_PATH); - // Set by file - if(!SetByFile(szFileC, fTempFile, getType(), pParent->nextResID(), szName)) - return false; - // create standalone - if(!GetStandalone(NULL, 0, true)) - return false; - // Set ID - Core.SetDerived(iDerID); + CStdLock FileLock(&FileCSec); + // Save back data + int32_t iDerID = Core.getDerID(); + char szName[_MAX_PATH+1]; SCopy(Core.getFileName(), szName, _MAX_PATH); + char szFileC[_MAX_PATH+1]; SCopy(szFile, szFileC, _MAX_PATH); + // Set by file + if(!SetByFile(szFileC, fTempFile, getType(), pParent->nextResID(), szName)) + return false; + // create standalone + if(!GetStandalone(NULL, 0, true)) + return false; + // Set ID + Core.SetDerived(iDerID); // announce derive pParent->getIOClass()->BroadcastMsg(MkC4NetIOPacket(PID_NetResDerive, Core)); - // derivation is dirty bussines - fDirty = true; - // ok - return true; + // derivation is dirty bussines + fDirty = true; + // ok + return true; } bool C4Network2Res::FinishDerive(const C4Network2ResCore &nCore) { - // security - if(!isAnonymous()) return false; - // Set core - Core = nCore; - // Set chunks (assume the ressource is complete) - Chunks.SetComplete(Core.getChunkCnt()); + // security + if(!isAnonymous()) return false; + // Set core + Core = nCore; + // Set chunks (assume the ressource is complete) + Chunks.SetComplete(Core.getChunkCnt()); - // Note that the Contents-CRC is /not/ checked. Derivation needs to be - // synchronized outside of C4Network2Res. + // Note that the Contents-CRC is /not/ checked. Derivation needs to be + // synchronized outside of C4Network2Res. - // But note that the ressource /might/ be binary compatible (though very - // unlikely), so do not set fNotBinaryCompatible. + // But note that the ressource /might/ be binary compatible (though very + // unlikely), so do not set fNotBinaryCompatible. - // ok - return true; + // ok + return true; } C4Group *C4Network2Res::OpenAsGrp() const @@ -842,7 +842,7 @@ bool C4Network2Res::SendChunk(uint32_t iChunk, int32_t iToClient) // save last request time iLastReqTime = time(NULL); // create packet - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); C4Network2ResChunk ResChunk; ResChunk.Set(this, iChunk); // send @@ -903,8 +903,8 @@ void C4Network2Res::OnChunk(const C4Network2ResChunk &rChunk) if(!fLoading) return; // correct ressource? if(rChunk.getResID() != getResID()) return; - // add ressource data - CStdLock FileLock(&FileCSec); + // add ressource data + CStdLock FileLock(&FileCSec); bool fSuccess = rChunk.AddTo(this, pParent->getIOClass()); #ifdef C4NET2RES_DEBUG_LOG // log @@ -977,7 +977,7 @@ bool C4Network2Res::NeedsDiscover() void C4Network2Res::Clear() { - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); // delete files if(fTempFile) if(FileExists(szFile)) @@ -1000,14 +1000,14 @@ void C4Network2Res::Clear() int32_t C4Network2Res::OpenFileRead() { - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); if(!GetStandalone(NULL, 0, false, false, true)) return -1; return open(szStandalone, _O_BINARY | O_RDONLY); } int32_t C4Network2Res::OpenFileWrite() { - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); return open(szStandalone, _O_BINARY | O_CREAT | O_WRONLY, S_IREAD | S_IWRITE); } @@ -1154,7 +1154,7 @@ void C4Network2Res::RemoveCChunks(ClientChunks *pChunks) bool C4Network2Res::OptimizeStandalone(bool fSilent) { - CStdLock FileLock(&FileCSec); + CStdLock FileLock(&FileCSec); // for now: player files only if(Core.getType() == NRT_Player) { @@ -1285,9 +1285,9 @@ void C4Network2ResChunk::CompileFunc(StdCompiler *pComp) { // pack header pComp->Value(mkNamingAdapt(iResID, "ResID", -1)); - pComp->Value(mkNamingAdapt(iChunk, "Chunk", ~0U)); - // Data - pComp->Value(mkNamingAdapt(Data, "Data")); + pComp->Value(mkNamingAdapt(iChunk, "Chunk", ~0U)); + // Data + pComp->Value(mkNamingAdapt(Data, "Data")); } // *** C4Network2ResList @@ -1385,10 +1385,10 @@ C4Network2Res::Ref C4Network2ResList::getRefRes(const char *szFile, bool fLocalO C4Network2Res::Ref C4Network2ResList::getRefNextRes(int32_t iResID) { CStdShareLock ResListLock(&ResListCSec); - C4Network2Res *pRes = NULL; + C4Network2Res *pRes = NULL; for(C4Network2Res *pCur = pFirst; pCur; pCur = pCur->pNext) if(!pCur->isRemoved() && pCur->getResID() >= iResID) - if(!pRes || pRes->getResID() > pCur->getResID()) + if(!pRes || pRes->getResID() > pCur->getResID()) pRes = pCur; return pRes; } @@ -1470,7 +1470,7 @@ C4Network2Res::Ref C4Network2ResList::AddByCore(const C4Network2ResCore &Core, b // try set by core if(!pRes->SetByCore(Core, true)) { - pRes.Clear(); + pRes.Clear(); // try load (if specified) return fLoad ? AddLoad(Core) : NULL; } @@ -1651,7 +1651,7 @@ void C4Network2ResList::OnShareFree(CStdCSecEx *pCSec) // unlink (pPrev ? pPrev->pNext : pFirst) = pNext; // remove - pRes->pNext = NULL; + pRes->pNext = NULL; pRes->DelRef(); } else @@ -1721,23 +1721,23 @@ bool C4Network2ResList::CreateNetworkFolder() bool C4Network2ResList::FindTempResFileName(const char *szFilename, char *pTarget) { - char safeFilename[_MAX_PATH]; - char* safePos = safeFilename; - while (*szFilename) - { - if ((*szFilename >= 'a' && *szFilename <= 'z') || - (*szFilename >= 'A' && *szFilename <= 'Z') || - (*szFilename >= '0' && *szFilename <= '9') || - (*szFilename == '.') || (*szFilename == '/')) - *safePos = *szFilename; - else - *safePos = '_'; + char safeFilename[_MAX_PATH]; + char* safePos = safeFilename; + while (*szFilename) + { + if ((*szFilename >= 'a' && *szFilename <= 'z') || + (*szFilename >= 'A' && *szFilename <= 'Z') || + (*szFilename >= '0' && *szFilename <= '9') || + (*szFilename == '.') || (*szFilename == '/')) + *safePos = *szFilename; + else + *safePos = '_'; - ++safePos; - ++szFilename; - } - *safePos = 0; - szFilename = safeFilename; + ++safePos; + ++szFilename; + } + *safePos = 0; + szFilename = safeFilename; // create temporary file SCopy(Config.AtNetworkPath(GetFilename(szFilename)), pTarget, _MAX_PATH); diff --git a/src/network/C4Network2Res.h b/src/network/C4Network2Res.h index a62f11f97..36b6992ed 100644 --- a/src/network/C4Network2Res.h +++ b/src/network/C4Network2Res.h @@ -99,7 +99,7 @@ public: void Set(C4Network2ResType eType, int32_t iResID, const char *strFileName, uint32_t iContentsCRC, const char *szAutor); void SetID(int32_t inID) { iID = inID; } - void SetDerived(int32_t inDerID) { iDerID = inDerID; } + void SetDerived(int32_t inDerID) { iDerID = inDerID; } void SetLoadable(uint32_t iSize, uint32_t iCRC); void SetFileSHA(BYTE *pSHA) { memcpy(FileSHA, pSHA, SHA_DIGEST_LENGTH); fHasFileSHA = true; } void Clear(); @@ -213,7 +213,7 @@ protected: bool fDirty; // local file data - CStdCSec FileCSec; + CStdCSec FileCSec; char szFile[_MAX_PATH + 1], szStandalone[_MAX_PATH + 1]; bool fTempFile, fStandaloneFailed; @@ -244,19 +244,19 @@ public: int32_t getResID() const { return Core.getID(); } int32_t getResClient() const { return Core.getID() >> 16; } const char *getFile() const { return szFile; } - CStdCSec *getFileCSec() { return &FileCSec; } + CStdCSec *getFileCSec() { return &FileCSec; } int32_t getLastReqTime()const { return iLastReqTime; } bool isRemoved() const { return fRemoved; } bool isLoading() const { return fLoading; } bool isComplete() const { return !fLoading; } - int32_t getPresentPercent() const { return fLoading ? Chunks.getPresentPercent() : 100; } + int32_t getPresentPercent() const { return fLoading ? Chunks.getPresentPercent() : 100; } bool SetByFile(const char *strFilePath, bool fTemp, C4Network2ResType eType, int32_t iResID, const char *szResName = NULL, bool fSilent = false); bool SetByGroup(C4Group *pGrp, bool fTemp, C4Network2ResType eType, int32_t iResID, const char *szResName = NULL, bool fSilent = false); bool SetByCore(const C4Network2ResCore &nCore, bool fSilent = false, const char *szAsFilename = NULL, int32_t iRecursion=0); bool SetLoad(const C4Network2ResCore &nCore); - bool SetDerived(const char *strName, const char *strFilePath, bool fTemp, C4Network2ResType eType, int32_t iDResID); + bool SetDerived(const char *strName, const char *strFilePath, bool fTemp, C4Network2ResType eType, int32_t iDResID); void ChangeID(int32_t inID); @@ -264,10 +264,10 @@ public: bool GetStandalone(char *pTo, int32_t iMaxL, bool fSetOfficial, bool fAllowUnloadable = false, bool fSilent = false); bool CalculateSHA(); - bool SaveBackFile(); + bool SaveBackFile(); C4Network2Res::Ref Derive(); - bool FinishDerive(); - bool FinishDerive(const C4Network2ResCore &nCore); + bool FinishDerive(); + bool FinishDerive(const C4Network2ResCore &nCore); bool SendStatus(C4Network2IOConnection *pTo = NULL); bool SendChunk(uint32_t iChunk, int32_t iToClient); @@ -315,7 +315,7 @@ protected: StdBuf Data; public: - int32_t getResID() const { return iResID; } + int32_t getResID() const { return iResID; } uint32_t getChunkNr() const { return iChunk; } bool Set(C4Network2Res *pRes, uint32_t iChunk); diff --git a/src/network/C4Network2ResDlg.cpp b/src/network/C4Network2ResDlg.cpp index ea82b5350..ec5fcaa28 100644 --- a/src/network/C4Network2ResDlg.cpp +++ b/src/network/C4Network2ResDlg.cpp @@ -103,7 +103,7 @@ void C4Network2ResDlg::ListItem::LocalSaveResource(bool fDoOverwrite) C4Network2Res::Ref pRes = GetRefRes(); if (!pRes) return; const char *szResFile = pRes->getFile(); - StdCopyStrBuf strErrCopyFile(LoadResStr("IDS_NET_ERR_COPYFILE")); + StdCopyStrBuf strErrCopyFile(LoadResStr("IDS_NET_ERR_COPYFILE")); if (!SEqual2(szResFile, Config.Network.WorkPath)) { GetScreen()->ShowMessage(LoadResStr("IDS_NET_ERR_COPYFILE_LOCAL"), strErrCopyFile.getData(), C4GUI::Ico_Error); diff --git a/src/network/C4Network2Stats.cpp b/src/network/C4Network2Stats.cpp index a1588c774..998b119d6 100644 --- a/src/network/C4Network2Stats.cpp +++ b/src/network/C4Network2Stats.cpp @@ -385,8 +385,8 @@ C4Graph *C4Network2Stats::GetGraphByName(const StdStrBuf &rszName, bool &rfIsTem // compare against default graph names rfIsTemp = false; if (SEqualNoCase(rszName.getData(), "oc")) return &statObjCount; - if (SEqualNoCase(rszName.getData(), "fps")) return &statFPS; - if (SEqualNoCase(rszName.getData(), "netio")) return &graphNetIO; + if (SEqualNoCase(rszName.getData(), "fps")) return &statFPS; + if (SEqualNoCase(rszName.getData(), "netio")) return &graphNetIO; if (SEqualNoCase(rszName.getData(), "pings")) return &statPings; if (SEqualNoCase(rszName.getData(), "control")) return &statControls; if (SEqualNoCase(rszName.getData(), "apm")) return &statActions; diff --git a/src/network/C4Packet2.cpp b/src/network/C4Packet2.cpp index 380ab1700..19fedbd27 100644 --- a/src/network/C4Packet2.cpp +++ b/src/network/C4Packet2.cpp @@ -33,7 +33,7 @@ template struct unpack_class { static C4PacketBase *unpack(StdCompiler *pComp) { - assert(pComp->isCompiler()); + assert(pComp->isCompiler()); T *pPkt = new T(); try { @@ -163,8 +163,8 @@ C4NetIOPacket C4PacketBase::pack(uint8_t cStatus, const C4NetIO::addr_t &addr) c void C4PacketBase::unpack(const C4NetIOPacket &Pkt, char *pStatus) { - if(pStatus) *pStatus = Pkt.getStatus(); - CompileFromBuf(*this, pStatus ? Pkt.getPBuf() : Pkt.getRef()); + if(pStatus) *pStatus = Pkt.getStatus(); + CompileFromBuf(*this, pStatus ? Pkt.getPBuf() : Pkt.getRef()); } @@ -208,7 +208,7 @@ C4IDPacket::C4IDPacket(const C4IDPacket &Packet2) eID(PID_None), pPkt(NULL), fOwnPkt(true), pNext(NULL) { // kinda hacky (note this might throw an uncaught exception) - C4PacketBase::unpack(Packet2.C4PacketBase::pack()); + C4PacketBase::unpack(Packet2.C4PacketBase::pack()); } C4IDPacket::~C4IDPacket() @@ -218,16 +218,16 @@ C4IDPacket::~C4IDPacket() const char *C4IDPacket::getPktName() const { - // Use map - for(const C4PktHandlingData *pPData = PktHandlingData; pPData->ID != PID_None; pPData++) + // Use map + for(const C4PktHandlingData *pPData = PktHandlingData; pPData->ID != PID_None; pPData++) if(pPData->ID == eID && pPData->Name) - return pPData->Name; - return "Unknown Packet Type"; + return pPData->Name; + return "Unknown Packet Type"; } void C4IDPacket::Default() { - eID = PID_None; pPkt = NULL; + eID = PID_None; pPkt = NULL; } void C4IDPacket::Clear() @@ -239,29 +239,29 @@ void C4IDPacket::Clear() void C4IDPacket::CompileFunc(StdCompiler *pComp) { // Packet ID - pComp->Value(mkNamingAdapt(mkIntAdaptT(eID), "ID", PID_None)); + pComp->Value(mkNamingAdapt(mkIntAdaptT(eID), "ID", PID_None)); // Compiling or Decompiling? - if(pComp->isCompiler()) - { - if(!pComp->Name(getPktName())) + if(pComp->isCompiler()) + { + if(!pComp->Name(getPktName())) { pComp->excCorrupt("C4IDPacket: Data value needed! Packet data missing!"); return; } - // Delete old packet - if(fOwnPkt) delete pPkt; pPkt = NULL; - if(eID == PID_None) return; - // Search unpacking function + // Delete old packet + if(fOwnPkt) delete pPkt; pPkt = NULL; + if(eID == PID_None) return; + // Search unpacking function for(const C4PktHandlingData *pPData = PktHandlingData; pPData->ID != PID_None; pPData++) if(pPData->ID == eID && pPData->FnUnpack) - { - pPkt = pPData->FnUnpack(pComp); - break; - } - if(!pPkt) - pComp->excCorrupt("C4IDPacket: could not unpack packet id %02x!", eID); - pComp->NameEnd(); - } - else if(eID != PID_None) - // Just write - pComp->Value(mkNamingAdapt(*pPkt, getPktName())); + { + pPkt = pPData->FnUnpack(pComp); + break; + } + if(!pPkt) + pComp->excCorrupt("C4IDPacket: could not unpack packet id %02x!", eID); + pComp->NameEnd(); + } + else if(eID != PID_None) + // Just write + pComp->Value(mkNamingAdapt(*pPkt, getPktName())); } // *** C4PacketList @@ -319,9 +319,9 @@ void C4PacketList::AddHead(C4PacketType eType, C4PacketBase *pPkt) void C4PacketList::Take(C4PacketList &List) { - pFirst = List.pFirst; - pLast = List.pLast; - List.pFirst = List.pLast = NULL; + pFirst = List.pFirst; + pLast = List.pLast; + List.pFirst = List.pLast = NULL; } void C4PacketList::Append(const C4PacketList &List) @@ -366,13 +366,13 @@ void C4PacketList::Delete(C4IDPacket *pPkt) void C4PacketList::CompileFunc(StdCompiler *pComp) { // unpack packets - if(pComp->isCompiler()) - { - // Read until no further sections available - while(pComp->Name("IDPacket")) - { - // Read the packet - C4IDPacket *pPkt = new C4IDPacket(); + if(pComp->isCompiler()) + { + // Read until no further sections available + while(pComp->Name("IDPacket")) + { + // Read the packet + C4IDPacket *pPkt = new C4IDPacket(); try { pComp->Value(*pPkt); @@ -383,25 +383,25 @@ void C4PacketList::CompileFunc(StdCompiler *pComp) delete pPkt; throw; } - // Terminator? - if(!pPkt->getPkt()) { delete pPkt; break; } - // Add to list - Add(pPkt); - } - pComp->NameEnd(); - } - else - { - // Write all packets - for(C4IDPacket *pPkt = pFirst; pPkt; pPkt = pPkt->pNext) - pComp->Value(mkNamingAdapt(*pPkt, "IDPacket")); - // Terminate, if no naming is available - if(!pComp->hasNaming()) + // Terminator? + if(!pPkt->getPkt()) { delete pPkt; break; } + // Add to list + Add(pPkt); + } + pComp->NameEnd(); + } + else { - C4IDPacket Pkt; - pComp->Value(mkNamingAdapt(Pkt, "IDPacket")); - } - } + // Write all packets + for(C4IDPacket *pPkt = pFirst; pPkt; pPkt = pPkt->pNext) + pComp->Value(mkNamingAdapt(*pPkt, "IDPacket")); + // Terminate, if no naming is available + if(!pComp->hasNaming()) + { + C4IDPacket Pkt; + pComp->Value(mkNamingAdapt(Pkt, "IDPacket")); + } + } } // *** C4PacketConn @@ -442,9 +442,9 @@ C4PacketConnRe::C4PacketConnRe(bool fnOK, bool fWrongPassword, const char *sznMs void C4PacketConnRe::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(fOK, "OK", true)); - pComp->Value(mkNamingAdapt(szMsg, "Message", "")); - pComp->Value(mkNamingAdapt(fWrongPassword, "WrongPassword", false)); + pComp->Value(mkNamingAdapt(fOK, "OK", true)); + pComp->Value(mkNamingAdapt(szMsg, "Message", "")); + pComp->Value(mkNamingAdapt(fWrongPassword, "WrongPassword", false)); } // *** C4PacketFwd @@ -488,22 +488,22 @@ void C4PacketFwd::AddClient(int32_t iClient) void C4PacketFwd::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(fNegativeList, "Negative", false)); + pComp->Value(mkNamingAdapt(fNegativeList, "Negative", false)); pComp->Value(mkNamingAdapt(mkIntPackAdapt(iClientCnt), "ClientCnt", 0)); - pComp->Value(mkNamingAdapt(mkArrayAdaptMap(iClients, iClientCnt, mkIntPackAdapt), "Clients", -1)); - pComp->Value(mkNamingAdapt(Data, "Data")); + pComp->Value(mkNamingAdapt(mkArrayAdaptMap(iClients, iClientCnt, mkIntPackAdapt), "Clients", -1)); + pComp->Value(mkNamingAdapt(Data, "Data")); } // *** C4PacketJoinData void C4PacketJoinData::CompileFunc(StdCompiler *pComp) - { + { pComp->Value(mkNamingAdapt(mkIntPackAdapt(iClientID), "ClientID", C4ClientIDUnknown)); - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iStartCtrlTick), "CtrlTick", -1)); - pComp->Value(mkNamingAdapt(mkParAdapt(GameStatus, true), "GameStatus")); - pComp->Value(mkNamingAdapt(Dynamic, "Dynamic")); - pComp->Value(Parameters); - } + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iStartCtrlTick), "CtrlTick", -1)); + pComp->Value(mkNamingAdapt(mkParAdapt(GameStatus, true), "GameStatus")); + pComp->Value(mkNamingAdapt(Dynamic, "Dynamic")); + pComp->Value(Parameters); + } // *** C4PacketPing @@ -539,8 +539,8 @@ C4PacketResStatus::C4PacketResStatus(int32_t iResID, const C4Network2ResChunkDat void C4PacketResStatus::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(iResID, "ResID")); - pComp->Value(mkNamingAdapt(Chunks, "Chunks")); + pComp->Value(mkNamingAdapt(iResID, "ResID")); + pComp->Value(mkNamingAdapt(Chunks, "Chunks")); } // *** C4PacketResDiscover @@ -569,8 +569,8 @@ bool C4PacketResDiscover::AddDisID(int32_t iID) void C4PacketResDiscover::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iDisIDCnt), "DiscoverCnt", 0)); - pComp->Value(mkNamingAdapt(mkArrayAdapt(iDisIDs, iDisIDCnt), "Discovers", -1)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iDisIDCnt), "DiscoverCnt", 0)); + pComp->Value(mkNamingAdapt(mkArrayAdapt(iDisIDs, iDisIDCnt), "Discovers", -1)); } // *** C4PacketResRequest @@ -597,14 +597,14 @@ C4PacketControlReq::C4PacketControlReq(int32_t inCtrlTick) void C4PacketControlReq::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iCtrlTick), "CtrlTick", -1)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iCtrlTick), "CtrlTick", -1)); } // *** C4PacketActivateReq void C4PacketActivateReq::CompileFunc(StdCompiler *pComp) { - pComp->Value(mkNamingAdapt(mkIntPackAdapt(iTick), "Tick", -1)); + pComp->Value(mkNamingAdapt(mkIntPackAdapt(iTick), "Tick", -1)); } diff --git a/src/network/C4PacketBase.h b/src/network/C4PacketBase.h index 3fc315300..76bcac0e4 100644 --- a/src/network/C4PacketBase.h +++ b/src/network/C4PacketBase.h @@ -43,7 +43,7 @@ public: inline C4NetIOPacket MkC4NetIOPacket(char cStatus, const class C4PacketBase &Pkt, const C4NetIO::addr_t &addr = C4NetIO::addr_t()) { - return Pkt.pack(cStatus, addr); + return Pkt.pack(cStatus, addr); } // Filename Adaptor @@ -71,7 +71,7 @@ struct C4NetFilenameAdapt } #endif } - ALLOW_TEMP_TO_REF(C4NetFilenameAdapt) + ALLOW_TEMP_TO_REF(C4NetFilenameAdapt) template bool operator == (const T &rVal) { return FileName == rVal; } template C4NetFilenameAdapt &operator = (const T &rVal) { FileName = rVal; return *this; } }; @@ -166,7 +166,7 @@ enum C4PacketType CID_EMMoveObj = CID_First | 0x30, CID_EMDrawTool = CID_First | 0x31, - CID_DebugRec = CID_First | 0x40 + CID_DebugRec = CID_First | 0x40 }; // packet classes @@ -239,7 +239,7 @@ public: protected: C4PacketType eID; C4PacketBase *pPkt; - bool fOwnPkt; + bool fOwnPkt; // used by C4PacketList C4IDPacket *pNext; @@ -278,7 +278,7 @@ public: void Add(C4PacketType eType, C4PacketBase *pPkt); void AddHead(C4PacketType eType, C4PacketBase *pPkt); - void Take(C4PacketList &List); + void Take(C4PacketList &List); void Append(const C4PacketList &List); void Clear(); diff --git a/src/platform/Bitmap256.cpp b/src/platform/Bitmap256.cpp index 010b988c4..d336e8e4d 100644 --- a/src/platform/Bitmap256.cpp +++ b/src/platform/Bitmap256.cpp @@ -40,19 +40,19 @@ int CBitmapInfo::FileBitsOffset() void CBitmapInfo::Set(int iWdt, int iHgt, int iBitDepth) { Default(); - // Set header - Head.bfType=*((WORD*)"BM"); - Head.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+DWordAligned(iWdt)*iHgt; - Head.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER); - // Set bitmap info - Info.biSize=sizeof(BITMAPINFOHEADER); - Info.biWidth=iWdt; - Info.biHeight=iHgt; - Info.biPlanes=1; - Info.biBitCount=iBitDepth; - Info.biCompression=0; - Info.biSizeImage=iWdt*iHgt; - Info.biClrUsed=Info.biClrImportant=0; + // Set header + Head.bfType=*((WORD*)"BM"); + Head.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+DWordAligned(iWdt)*iHgt; + Head.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER); + // Set bitmap info + Info.biSize=sizeof(BITMAPINFOHEADER); + Info.biWidth=iWdt; + Info.biHeight=iHgt; + Info.biPlanes=1; + Info.biBitCount=iBitDepth; + Info.biCompression=0; + Info.biSizeImage=iWdt*iHgt; + Info.biClrUsed=Info.biClrImportant=0; } @@ -63,8 +63,8 @@ CBitmap256Info::CBitmap256Info() bool CBitmap256Info::Valid() { - if (Head.bfType != *((WORD*)"BM") ) return false; - if ((Info.biBitCount!=8) || (Info.biCompression!=0)) return false; + if (Head.bfType != *((WORD*)"BM") ) return false; + if ((Info.biBitCount!=8) || (Info.biCompression!=0)) return false; return true; } @@ -76,26 +76,26 @@ int CBitmap256Info::FileBitsOffset() void CBitmap256Info::Set(int iWdt, int iHgt, BYTE *bypPalette) { Default(); - // Set header - Head.bfType=*((WORD*)"BM"); - Head.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD)+DWordAligned(iWdt)*iHgt; - Head.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD); - // Set bitmap info - Info.biSize=sizeof(BITMAPINFOHEADER); - Info.biWidth=iWdt; - Info.biHeight=iHgt; - Info.biPlanes=1; - Info.biBitCount=8; - Info.biCompression=0; - Info.biSizeImage=iWdt*iHgt; - Info.biClrUsed=Info.biClrImportant=256; + // Set header + Head.bfType=*((WORD*)"BM"); + Head.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD)+DWordAligned(iWdt)*iHgt; + Head.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD); + // Set bitmap info + Info.biSize=sizeof(BITMAPINFOHEADER); + Info.biWidth=iWdt; + Info.biHeight=iHgt; + Info.biPlanes=1; + Info.biBitCount=8; + Info.biCompression=0; + Info.biSizeImage=iWdt*iHgt; + Info.biClrUsed=Info.biClrImportant=256; // Set palette - for (int cnt=0; cnt<256; cnt++) - { - Colors[cnt].rgbRed = bypPalette[cnt*3+0]; - Colors[cnt].rgbGreen = bypPalette[cnt*3+1]; - Colors[cnt].rgbBlue = bypPalette[cnt*3+2]; - } + for (int cnt=0; cnt<256; cnt++) + { + Colors[cnt].rgbRed = bypPalette[cnt*3+0]; + Colors[cnt].rgbGreen = bypPalette[cnt*3+1]; + Colors[cnt].rgbBlue = bypPalette[cnt*3+2]; + } } void CBitmap256Info::Default() diff --git a/src/platform/C4FileClasses.cpp b/src/platform/C4FileClasses.cpp index 09d593d0b..69b192799 100644 --- a/src/platform/C4FileClasses.cpp +++ b/src/platform/C4FileClasses.cpp @@ -45,20 +45,20 @@ bool SetProtocol(const char *szProtocol, const char *szCommand, const char *szMo } bool SetC4FileClasses(const char *szEnginePath) - { + { - if (!SetRegFileClass("Clonk4.Scenario", "c4s", "Clonk 4 Scenario", szEnginePath, 1, C4FileClassContentType)) return false; - if (!SetRegFileClass("Clonk4.Group", "c4g", "Clonk 4 Group", szEnginePath, 2, C4FileClassContentType)) return false; - if (!SetRegFileClass("Clonk4.Folder", "c4f", "Clonk 4 Folder", szEnginePath, 3, C4FileClassContentType)) return false; - if (!SetRegFileClass("Clonk4.Player", "c4p", "Clonk 4 Player", szEnginePath, 4, C4FileClassContentType)) return false; - if (!SetRegFileClass("Clonk4.Definition", "c4d", "Clonk 4 Object Definition", szEnginePath, 6, C4FileClassContentType)) return false; - if (!SetRegFileClass("Clonk4.Object", "c4i", "Clonk 4 Object Info", szEnginePath, 7, C4FileClassContentType)) return false; - if (!SetRegFileClass("Clonk4.Material", "c4m", "Clonk 4 Material", szEnginePath, 8, "text/plain")) return false; - if (!SetRegFileClass("Clonk4.Binary", "c4b", "Clonk 4 Binary", szEnginePath, 9, "application/octet-stream")) return false; - if (!SetRegFileClass("Clonk4.Video", "c4v", "Clonk 4 Video", szEnginePath, 10, "video/avi")) return false; - if (!SetRegFileClass("Clonk4.Weblink", "c4l", "Clonk 4 Weblink", szEnginePath, 11, C4FileClassContentType)) return false; - if (!SetRegFileClass("Clonk4.Key", "c4k", "Clonk 4 Key", szEnginePath, 12, "application/octet-stream")) return false; - if (!SetRegFileClass("Clonk4.Update", "c4u", "Clonk 4 Update", szEnginePath, 13, C4FileClassContentType)) return false; + if (!SetRegFileClass("Clonk4.Scenario", "c4s", "Clonk 4 Scenario", szEnginePath, 1, C4FileClassContentType)) return false; + if (!SetRegFileClass("Clonk4.Group", "c4g", "Clonk 4 Group", szEnginePath, 2, C4FileClassContentType)) return false; + if (!SetRegFileClass("Clonk4.Folder", "c4f", "Clonk 4 Folder", szEnginePath, 3, C4FileClassContentType)) return false; + if (!SetRegFileClass("Clonk4.Player", "c4p", "Clonk 4 Player", szEnginePath, 4, C4FileClassContentType)) return false; + if (!SetRegFileClass("Clonk4.Definition", "c4d", "Clonk 4 Object Definition", szEnginePath, 6, C4FileClassContentType)) return false; + if (!SetRegFileClass("Clonk4.Object", "c4i", "Clonk 4 Object Info", szEnginePath, 7, C4FileClassContentType)) return false; + if (!SetRegFileClass("Clonk4.Material", "c4m", "Clonk 4 Material", szEnginePath, 8, "text/plain")) return false; + if (!SetRegFileClass("Clonk4.Binary", "c4b", "Clonk 4 Binary", szEnginePath, 9, "application/octet-stream")) return false; + if (!SetRegFileClass("Clonk4.Video", "c4v", "Clonk 4 Video", szEnginePath, 10, "video/avi")) return false; + if (!SetRegFileClass("Clonk4.Weblink", "c4l", "Clonk 4 Weblink", szEnginePath, 11, C4FileClassContentType)) return false; + if (!SetRegFileClass("Clonk4.Key", "c4k", "Clonk 4 Key", szEnginePath, 12, "application/octet-stream")) return false; + if (!SetRegFileClass("Clonk4.Update", "c4u", "Clonk 4 Update", szEnginePath, 13, C4FileClassContentType)) return false; if (!SetProtocol("clonk", "%s %%1 /Fullscreen", szEnginePath)) return false; @@ -74,4 +74,4 @@ bool SetC4FileClasses(const char *szEnginePath) DeleteRegistryKey(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Clonk.exe"); return true; - } + } diff --git a/src/platform/C4FileMonitor.cpp b/src/platform/C4FileMonitor.cpp index 675088e82..96a585bf7 100644 --- a/src/platform/C4FileMonitor.cpp +++ b/src/platform/C4FileMonitor.cpp @@ -39,11 +39,11 @@ /* Structure describing an inotify event. */ struct inotify_event { - int wd; /* Watch descriptor. */ - uint32_t mask; /* Watch mask. */ - uint32_t cookie; /* Cookie to synchronize two events. */ - uint32_t len; /* Length (including NULs) of name. */ - char name __flexarr; /* Name. */ + int wd; /* Watch descriptor. */ + uint32_t mask; /* Watch mask. */ + uint32_t cookie; /* Cookie to synchronize two events. */ + uint32_t len; /* Length (including NULs) of name. */ + char name __flexarr; /* Name. */ }; diff --git a/src/platform/C4GamePadCon.cpp b/src/platform/C4GamePadCon.cpp index fc81bb24d..b76d80071 100644 --- a/src/platform/C4GamePadCon.cpp +++ b/src/platform/C4GamePadCon.cpp @@ -104,7 +104,7 @@ int C4GamePadControl::GetGamePadCount() ZeroMem(&joy, sizeof(JOYINFOEX)); joy.dwSize = sizeof(JOYINFOEX); joy.dwFlags = JOY_RETURNALL; int iCnt=0; while (iCnt 0) - return deadZone + 1; - return 0; - } + int amplify(int i) { + if (i < 0) + return -(deadZone + 1); + if (i > 0) + return deadZone + 1; + return 0; + } } void C4GamePadControl::FeedEvent(SDL_Event& event) { switch(event.type) { - case SDL_JOYHATMOTION: - { - SDL_Event fakeX; - fakeX.jaxis.type = SDL_JOYAXISMOTION; - fakeX.jaxis.which = event.jhat.which; - fakeX.jaxis.axis = event.jhat.hat * 2 + 6; /* *magic*number* */ - fakeX.jaxis.value = 0; - SDL_Event fakeY = fakeX; - fakeY.jaxis.axis += 1; - switch (event.jhat.value) { - case SDL_HAT_LEFTUP: fakeX.jaxis.value = amplify(-1); fakeY.jaxis.value = amplify(-1); break; - case SDL_HAT_LEFT: fakeX.jaxis.value = amplify(-1); break; - case SDL_HAT_LEFTDOWN: fakeX.jaxis.value = amplify(-1); fakeY.jaxis.value = amplify(+1); break; - case SDL_HAT_UP: fakeY.jaxis.value = amplify(-1); break; - case SDL_HAT_DOWN: fakeY.jaxis.value = amplify(+1); break; - case SDL_HAT_RIGHTUP: fakeX.jaxis.value = amplify(+1); fakeY.jaxis.value = amplify(-1); break; - case SDL_HAT_RIGHT: fakeX.jaxis.value = amplify(+1); break; - case SDL_HAT_RIGHTDOWN: fakeX.jaxis.value = amplify(+1); fakeY.jaxis.value = amplify(+1); break; - } - FeedEvent(fakeX); - FeedEvent(fakeY); - return; - } - case SDL_JOYBALLMOTION: - { - SDL_Event fake; - fake.jaxis.type = SDL_JOYAXISMOTION; - fake.jaxis.which = event.jball.which; - fake.jaxis.axis = event.jball.ball * 2 + 12; /* *magic*number* */ - fake.jaxis.value = amplify(event.jball.xrel); - FeedEvent(event); - fake.jaxis.axis += 1; - fake.jaxis.value = amplify(event.jball.yrel); - FeedEvent(event); - return; - } + case SDL_JOYHATMOTION: + { + SDL_Event fakeX; + fakeX.jaxis.type = SDL_JOYAXISMOTION; + fakeX.jaxis.which = event.jhat.which; + fakeX.jaxis.axis = event.jhat.hat * 2 + 6; /* *magic*number* */ + fakeX.jaxis.value = 0; + SDL_Event fakeY = fakeX; + fakeY.jaxis.axis += 1; + switch (event.jhat.value) { + case SDL_HAT_LEFTUP: fakeX.jaxis.value = amplify(-1); fakeY.jaxis.value = amplify(-1); break; + case SDL_HAT_LEFT: fakeX.jaxis.value = amplify(-1); break; + case SDL_HAT_LEFTDOWN: fakeX.jaxis.value = amplify(-1); fakeY.jaxis.value = amplify(+1); break; + case SDL_HAT_UP: fakeY.jaxis.value = amplify(-1); break; + case SDL_HAT_DOWN: fakeY.jaxis.value = amplify(+1); break; + case SDL_HAT_RIGHTUP: fakeX.jaxis.value = amplify(+1); fakeY.jaxis.value = amplify(-1); break; + case SDL_HAT_RIGHT: fakeX.jaxis.value = amplify(+1); break; + case SDL_HAT_RIGHTDOWN: fakeX.jaxis.value = amplify(+1); fakeY.jaxis.value = amplify(+1); break; + } + FeedEvent(fakeX); + FeedEvent(fakeY); + return; + } + case SDL_JOYBALLMOTION: + { + SDL_Event fake; + fake.jaxis.type = SDL_JOYAXISMOTION; + fake.jaxis.which = event.jball.which; + fake.jaxis.axis = event.jball.ball * 2 + 12; /* *magic*number* */ + fake.jaxis.value = amplify(event.jball.xrel); + FeedEvent(event); + fake.jaxis.axis += 1; + fake.jaxis.value = amplify(event.jball.yrel); + FeedEvent(event); + return; + } case SDL_JOYAXISMOTION: { C4KeyCode minCode = KEY_Gamepad(event.jaxis.which, KEY_JOY_Axis(event.jaxis.axis, false)); diff --git a/src/platform/C4MusicFile.cpp b/src/platform/C4MusicFile.cpp index 329b035bf..9d219c007 100644 --- a/src/platform/C4MusicFile.cpp +++ b/src/platform/C4MusicFile.cpp @@ -195,11 +195,11 @@ bool C4MusicFileMP3::Play(bool loop) // Play Song Channel = FSOUND_Stream_Play(FSOUND_FREE, stream); - if(Channel == -1) return false; + if(Channel == -1) return false; - // Set highest priority - if(!FSOUND_SetPriority(Channel, 255)) - return false; + // Set highest priority + if(!FSOUND_SetPriority(Channel, 255)) + return false; return true; } @@ -253,15 +253,15 @@ bool C4MusicFileOgg::Play(bool loop) // Play Song Channel = FSOUND_Stream_Play(FSOUND_FREE, stream); - if(Channel == -1) return false; + if(Channel == -1) return false; - // Set highest priority - if(!FSOUND_SetPriority(Channel, 255)) - return false; + // Set highest priority + if(!FSOUND_SetPriority(Channel, 255)) + return false; - Playing = true; + Playing = true; - FSOUND_Stream_SetEndCallback(stream, &C4MusicFileOgg::OnEnd, this); + FSOUND_Stream_SetEndCallback(stream, &C4MusicFileOgg::OnEnd, this); return true; } @@ -269,9 +269,9 @@ bool C4MusicFileOgg::Play(bool loop) // End Callback signed char __stdcall C4MusicFileOgg::OnEnd(FSOUND_STREAM* stream, void* buff, int length, void *param) { - C4MusicFileOgg* pFile = static_cast(param); - pFile->Playing = false; - return 0; + C4MusicFileOgg* pFile = static_cast(param); + pFile->Playing = false; + return 0; } void C4MusicFileOgg::Stop(int fadeout_ms) @@ -282,13 +282,13 @@ void C4MusicFileOgg::Stop(int fadeout_ms) stream = NULL; } if(Data) { delete[] Data; Data = NULL; } - Playing = false; + Playing = false; } void C4MusicFileOgg::CheckIfPlaying() - { + { - if(!Playing) + if(!Playing) //if(FSOUND_Stream_GetPosition(stream) >= (unsigned) FSOUND_Stream_GetLength(stream)) Application.MusicSystem.NotifySuccess(); } diff --git a/src/platform/C4MusicFile.h b/src/platform/C4MusicFile.h index c52ca4634..906a0e662 100644 --- a/src/platform/C4MusicFile.h +++ b/src/platform/C4MusicFile.h @@ -81,7 +81,7 @@ class C4MusicFileMOD : public C4MusicFile public: C4MusicFileMOD(); ~C4MusicFileMOD(); - bool Play(bool loop = false); + bool Play(bool loop = false); void Stop(int fadeout_ms = 0); void CheckIfPlaying(); void SetVolume(int); @@ -97,7 +97,7 @@ class C4MusicFileMP3 : public C4MusicFile public: C4MusicFileMP3(); ~C4MusicFileMP3(); - bool Play(bool loop = false); + bool Play(bool loop = false); void Stop(int fadeout_ms = 0); void CheckIfPlaying(); void SetVolume(int); @@ -114,18 +114,18 @@ class C4MusicFileOgg : public C4MusicFile public: C4MusicFileOgg(); ~C4MusicFileOgg(); - bool Play(bool loop = false); + bool Play(bool loop = false); void Stop(int fadeout_ms = 0); void CheckIfPlaying(); void SetVolume(int); - static signed char __stdcall OnEnd(FSOUND_STREAM* stream, void* buff, int length, void* param); + static signed char __stdcall OnEnd(FSOUND_STREAM* stream, void* buff, int length, void* param); protected: FSOUND_STREAM *stream; char *Data; int Channel; - bool Playing; + bool Playing; }; #elif defined HAVE_LIBSDL_MIXER @@ -135,7 +135,7 @@ class C4MusicFileSDL : public C4MusicFile public: C4MusicFileSDL(); ~C4MusicFileSDL(); - bool Play(bool loop = false); + bool Play(bool loop = false); void Stop(int fadeout_ms = 0); void CheckIfPlaying(); void SetVolume(int); diff --git a/src/platform/C4MusicSystem.cpp b/src/platform/C4MusicSystem.cpp index e1c72bbc2..93fa01670 100644 --- a/src/platform/C4MusicSystem.cpp +++ b/src/platform/C4MusicSystem.cpp @@ -223,7 +223,7 @@ void C4MusicSystem::Load(const char *szFile) case MUSICTYPE_MID: if (MODInitialized) - NewSong = new C4MusicFileMID; + NewSong = new C4MusicFileMID; break; } #elif defined HAVE_LIBSDL_MIXER diff --git a/src/platform/C4SoundSystem.cpp b/src/platform/C4SoundSystem.cpp index 18bd08ae7..6f373e2f8 100644 --- a/src/platform/C4SoundSystem.cpp +++ b/src/platform/C4SoundSystem.cpp @@ -45,9 +45,9 @@ C4SoundEffect::C4SoundEffect(): } C4SoundEffect::~C4SoundEffect() - { - Clear(); - } + { + Clear(); + } void C4SoundEffect::Clear() { @@ -64,37 +64,37 @@ void C4SoundEffect::Clear() } bool C4SoundEffect::Load(const char *szFileName, C4Group &hGroup, bool fStatic) - { - // Sound check - if (!Config.Sound.RXSound) return false; - // Locate sound in file - StdBuf WaveBuffer; - if (!hGroup.LoadEntry(szFileName, WaveBuffer)) return false; + { + // Sound check + if (!Config.Sound.RXSound) return false; + // Locate sound in file + StdBuf WaveBuffer; + if (!hGroup.LoadEntry(szFileName, WaveBuffer)) return false; // load it from mem if (!Load((BYTE*)WaveBuffer.getData(), WaveBuffer.getSize(), fStatic)) return false; - // Set name - SCopy(szFileName,Name,C4MaxSoundName); + // Set name + SCopy(szFileName,Name,C4MaxSoundName); return true; - } + } bool C4SoundEffect::Load(BYTE *pData, size_t iDataLen, bool fStatic, bool fRaw) { - // Sound check - if (!Config.Sound.RXSound) return false; + // Sound check + if (!Config.Sound.RXSound) return false; // load directly from memory #ifdef HAVE_FMOD int32_t iOptions = FSOUND_NORMAL | FSOUND_2D | FSOUND_LOADMEMORY; if (fRaw) iOptions |= FSOUND_LOADRAW; if(!(pSample = FSOUND_Sample_Load(FSOUND_UNMANAGED, (const char *)pData, iOptions, 0, iDataLen))) - { Clear(); return false; } - // get length - int32_t iSamples = FSOUND_Sample_GetLength(pSample); + { Clear(); return false; } + // get length + int32_t iSamples = FSOUND_Sample_GetLength(pSample); int iSampleRate = SampleRate; - if(!iSamples || !FSOUND_Sample_GetDefaults(pSample, &iSampleRate, 0, 0, 0)) - return false; + if(!iSamples || !FSOUND_Sample_GetDefaults(pSample, &iSampleRate, 0, 0, 0)) + return false; SampleRate = iSampleRate; - Length = iSamples * 10 / (SampleRate / 100); + Length = iSamples * 10 / (SampleRate / 100); #endif #ifdef HAVE_LIBSDL_MIXER // Be paranoid about SDL_Mixer initialisation @@ -108,89 +108,89 @@ bool C4SoundEffect::Load(BYTE *pData, size_t iDataLen, bool fStatic, bool fRaw) #endif *Name = '\0'; // Set usage time - UsageTime=Game.Time; - Static=fStatic; - return true; + UsageTime=Game.Time; + Static=fStatic; + return true; } void C4SoundEffect::Execute() { - // check for instances that have stopped and volume changes - for(C4SoundInstance *pInst = FirstInst; pInst; ) - { - C4SoundInstance *pNext = pInst->pNext; - if(!pInst->Playing()) - RemoveInst(pInst); - else - pInst->Execute(); - pInst = pNext; - } + // check for instances that have stopped and volume changes + for(C4SoundInstance *pInst = FirstInst; pInst; ) + { + C4SoundInstance *pNext = pInst->pNext; + if(!pInst->Playing()) + RemoveInst(pInst); + else + pInst->Execute(); + pInst = pNext; + } } C4SoundInstance *C4SoundEffect::New(bool fLoop, int32_t iVolume, C4Object *pObj, int32_t iCustomFalloffDistance) { - // check: too many instances? - if(!fLoop && Instances >= C4MaxSoundInstances) return NULL; - // create & init sound instance - C4SoundInstance *pInst = new C4SoundInstance(); - if(!pInst->Create(this, fLoop, iVolume, pObj, 0, iCustomFalloffDistance)) { delete pInst; return NULL; } - // add to list - AddInst(pInst); - // return - return pInst; + // check: too many instances? + if(!fLoop && Instances >= C4MaxSoundInstances) return NULL; + // create & init sound instance + C4SoundInstance *pInst = new C4SoundInstance(); + if(!pInst->Create(this, fLoop, iVolume, pObj, 0, iCustomFalloffDistance)) { delete pInst; return NULL; } + // add to list + AddInst(pInst); + // return + return pInst; } C4SoundInstance *C4SoundEffect::GetInstance(C4Object *pObj) { - for(C4SoundInstance *pInst = FirstInst; pInst; pInst = pInst->pNext) - if(pInst->getObj() == pObj) - return pInst; - return NULL; + for(C4SoundInstance *pInst = FirstInst; pInst; pInst = pInst->pNext) + if(pInst->getObj() == pObj) + return pInst; + return NULL; } void C4SoundEffect::ClearPointers(C4Object *pObj) { - for(C4SoundInstance *pInst = FirstInst; pInst; pInst = pInst->pNext) - pInst->ClearPointers(pObj); + for(C4SoundInstance *pInst = FirstInst; pInst; pInst = pInst->pNext) + pInst->ClearPointers(pObj); } int32_t C4SoundEffect::GetStartedInstanceCount(int32_t iX, int32_t iY, int32_t iRad) { - int32_t cnt = 0; - for(C4SoundInstance *pInst = FirstInst; pInst; pInst = pInst->pNext) - if(pInst->isStarted() && pInst->getObj() && pInst->Inside(iX, iY, iRad)) - cnt++; - return cnt; + int32_t cnt = 0; + for(C4SoundInstance *pInst = FirstInst; pInst; pInst = pInst->pNext) + if(pInst->isStarted() && pInst->getObj() && pInst->Inside(iX, iY, iRad)) + cnt++; + return cnt; } int32_t C4SoundEffect::GetStartedInstanceCount() { - int32_t cnt = 0; - for(C4SoundInstance *pInst = FirstInst; pInst; pInst = pInst->pNext) - if(pInst->isStarted() && pInst->Playing() && !pInst->getObj()) - cnt++; - return cnt; + int32_t cnt = 0; + for(C4SoundInstance *pInst = FirstInst; pInst; pInst = pInst->pNext) + if(pInst->isStarted() && pInst->Playing() && !pInst->getObj()) + cnt++; + return cnt; } void C4SoundEffect::AddInst(C4SoundInstance *pInst) { - pInst->pNext = FirstInst; - FirstInst = pInst; - Instances++; + pInst->pNext = FirstInst; + FirstInst = pInst; + Instances++; } void C4SoundEffect::RemoveInst(C4SoundInstance *pInst) { - if(pInst == FirstInst) - FirstInst = pInst->pNext; - else - { - C4SoundInstance *pPos = FirstInst; + if(pInst == FirstInst) + FirstInst = pInst->pNext; + else + { + C4SoundInstance *pPos = FirstInst; while (pPos && pPos->pNext != pInst) pPos = pPos->pNext; - if(pPos) - pPos->pNext = pInst->pNext; - } - delete pInst; - Instances--; + if(pPos) + pPos->pNext = pInst->pNext; + } + delete pInst; + Instances--; } @@ -204,67 +204,67 @@ C4SoundInstance::C4SoundInstance(): C4SoundInstance::~C4SoundInstance() { - Clear(); + Clear(); } void C4SoundInstance::Clear() { - Stop(); - iChannel = -1; + Stop(); + iChannel = -1; } bool C4SoundInstance::Create(C4SoundEffect *pnEffect, bool fLoop, int32_t inVolume, C4Object *pnObj, int32_t inNearInstanceMax, int32_t iFalloffDistance) { - // Sound check - if (!Config.Sound.RXSound || !pnEffect) return false; + // Sound check + if (!Config.Sound.RXSound || !pnEffect) return false; // Already playing? Stop - if(Playing()) { Stop(); return false; } - // Set effect - pEffect = pnEffect; - // Set - iStarted = timeGetTime(); - iVolume = inVolume; iPan = 0; iChannel = -1; - iNearInstanceMax = inNearInstanceMax; + if(Playing()) { Stop(); return false; } + // Set effect + pEffect = pnEffect; + // Set + iStarted = timeGetTime(); + iVolume = inVolume; iPan = 0; iChannel = -1; + iNearInstanceMax = inNearInstanceMax; this->iFalloffDistance = iFalloffDistance; - pObj = pnObj; - fLooping = fLoop; - // Start - Execute(); - // Safe usage - pEffect->UsageTime = Game.Time; - return true; + pObj = pnObj; + fLooping = fLoop; + // Start + Execute(); + // Safe usage + pEffect->UsageTime = Game.Time; + return true; } bool C4SoundInstance::CheckStart() { - // already started? - if(isStarted()) return true; - // don't bother if half the time is up and the sound is not looping - if(timeGetTime() > iStarted + pEffect->Length / 2 && !fLooping) - return false; - // do near-instances check - int32_t iNearInstances = pObj ? pEffect->GetStartedInstanceCount(pObj->GetX(), pObj->GetY(), C4NearSoundRadius) - : pEffect->GetStartedInstanceCount(); - // over maximum? - if(iNearInstances > iNearInstanceMax) return false; - // Start - return Start(); + // already started? + if(isStarted()) return true; + // don't bother if half the time is up and the sound is not looping + if(timeGetTime() > iStarted + pEffect->Length / 2 && !fLooping) + return false; + // do near-instances check + int32_t iNearInstances = pObj ? pEffect->GetStartedInstanceCount(pObj->GetX(), pObj->GetY(), C4NearSoundRadius) + : pEffect->GetStartedInstanceCount(); + // over maximum? + if(iNearInstances > iNearInstanceMax) return false; + // Start + return Start(); } bool C4SoundInstance::Start() { #ifdef HAVE_FMOD - // Start + // Start if((iChannel = FSOUND_PlaySound(FSOUND_FREE, pEffect->pSample)) == -1) - return false; - if(!FSOUND_SetLoopMode(iChannel, fLooping ? FSOUND_LOOP_NORMAL : FSOUND_LOOP_OFF)) - { Stop(); return false; } - // set position - if(timeGetTime() > iStarted + 20) - { - int32_t iTime = (timeGetTime() - iStarted) % pEffect->Length; - FSOUND_SetCurrentPosition(iChannel, iTime / 10 * pEffect->SampleRate / 100); - } + return false; + if(!FSOUND_SetLoopMode(iChannel, fLooping ? FSOUND_LOOP_NORMAL : FSOUND_LOOP_OFF)) + { Stop(); return false; } + // set position + if(timeGetTime() > iStarted + 20) + { + int32_t iTime = (timeGetTime() - iStarted) % pEffect->Length; + FSOUND_SetCurrentPosition(iChannel, iTime / 10 * pEffect->SampleRate / 100); + } #elif defined HAVE_LIBSDL_MIXER // Be paranoid about SDL_Mixer initialisation if(!Application.MusicSystem.MODInitialized) return false; @@ -273,9 +273,9 @@ bool C4SoundInstance::Start() #else return false; #endif - // Update volume - Execute(); - return true; + // Update volume + Execute(); + return true; } bool C4SoundInstance::Stop() @@ -299,18 +299,18 @@ bool C4SoundInstance::Stop() } bool C4SoundInstance::Playing() - { - if(!pEffect) return false; + { + if(!pEffect) return false; #ifdef HAVE_FMOD - if(fLooping) return true; - return isStarted() ? FSOUND_GetCurrentSample(iChannel) == pEffect->pSample - : timeGetTime() < iStarted + pEffect->Length; + if(fLooping) return true; + return isStarted() ? FSOUND_GetCurrentSample(iChannel) == pEffect->pSample + : timeGetTime() < iStarted + pEffect->Length; #endif #ifdef HAVE_LIBSDL_MIXER return Application.MusicSystem.MODInitialized && (iChannel != -1) && Mix_Playing(iChannel); #endif return false; - } + } void C4SoundInstance::Execute() { @@ -365,30 +365,30 @@ void C4SoundInstance::Execute() } void C4SoundInstance::SetVolumeByPos(int32_t x, int32_t y) - { - iVolume = ::GraphicsSystem.GetAudibility(x, y, &iPan); - } + { + iVolume = ::GraphicsSystem.GetAudibility(x, y, &iPan); + } void C4SoundInstance::ClearPointers(C4Object *pDelete) - { - if(!Playing()) { Stop(); return; } - if(pObj == pDelete) - { - // stop if looping (would most likely loop forever) - if(fLooping) - Stop(); - // otherwise: set volume by last position - else - SetVolumeByPos(pObj->GetX(), pObj->GetY()); - pObj = NULL; - } - } + { + if(!Playing()) { Stop(); return; } + if(pObj == pDelete) + { + // stop if looping (would most likely loop forever) + if(fLooping) + Stop(); + // otherwise: set volume by last position + else + SetVolumeByPos(pObj->GetX(), pObj->GetY()); + pObj = NULL; + } + } bool C4SoundInstance::Inside(int32_t iX, int32_t iY, int32_t iRad) - { - return pObj && - (pObj->GetX() - iX) * (pObj->GetX() - iX) + (pObj->GetY() - iY) * (pObj->GetY() - iY) <= iRad * iRad; - } + { + return pObj && + (pObj->GetX() - iX) * (pObj->GetX() - iX) + (pObj->GetY() - iY) * (pObj->GetY() - iY) <= iRad * iRad; + } C4SoundSystem::C4SoundSystem(): @@ -440,68 +440,68 @@ void C4SoundSystem::ClearEffects() void C4SoundSystem::Execute() { // Sound effect statistics & unload check - C4SoundEffect *csfx,*next=NULL,*prev=NULL; - for (csfx=FirstSound; csfx; csfx=next) - { - next=csfx->Next; - // Instance removal check - csfx->Execute(); - // Unload check - if (!csfx->Static && Game.Time-csfx->UsageTime > SoundUnloadTime && !csfx->FirstInst) - { - if (prev) prev->Next=next; - else FirstSound=next; - delete csfx; - } - else - prev=csfx; - } + C4SoundEffect *csfx,*next=NULL,*prev=NULL; + for (csfx=FirstSound; csfx; csfx=next) + { + next=csfx->Next; + // Instance removal check + csfx->Execute(); + // Unload check + if (!csfx->Static && Game.Time-csfx->UsageTime > SoundUnloadTime && !csfx->FirstInst) + { + if (prev) prev->Next=next; + else FirstSound=next; + delete csfx; + } + else + prev=csfx; + } } int32_t C4SoundSystem::EffectInBank(const char *szSound) { int32_t iResult = 0; - C4SoundEffect *pSfx; - char szName[C4MaxSoundName+4+1]; + C4SoundEffect *pSfx; + char szName[C4MaxSoundName+4+1]; // Compose name (with extension) - SCopy(szSound,szName,C4MaxSoundName); + SCopy(szSound,szName,C4MaxSoundName); DefaultExtension(szName,"wav"); // Count all matching sounds in bank - for (pSfx=FirstSound; pSfx; pSfx=pSfx->Next) - if (WildcardMatch(szName,pSfx->Name)) - iResult++; - return iResult; + for (pSfx=FirstSound; pSfx; pSfx=pSfx->Next) + if (WildcardMatch(szName,pSfx->Name)) + iResult++; + return iResult; } C4SoundEffect* C4SoundSystem::AddEffect(const char *szSoundName) { - C4SoundEffect *nsfx; - // Allocate new bank entry - if (!( nsfx=new C4SoundEffect )) return NULL; - // Load sound to entry + C4SoundEffect *nsfx; + // Allocate new bank entry + if (!( nsfx=new C4SoundEffect )) return NULL; + // Load sound to entry C4GRP_DISABLE_REWINDWARN // dynamic load; must rewind here :( - if (!nsfx->Load(szSoundName,SoundFile,false)) + if (!nsfx->Load(szSoundName,SoundFile,false)) if (!nsfx->Load(szSoundName,Game.ScenarioFile,false)) { C4GRP_ENABLE_REWINDWARN delete nsfx; return NULL; } C4GRP_ENABLE_REWINDWARN - // Add sound to bank - nsfx->Next=FirstSound; - FirstSound=nsfx; - return nsfx; + // Add sound to bank + nsfx->Next=FirstSound; + FirstSound=nsfx; + return nsfx; } C4SoundEffect* C4SoundSystem::GetEffect(const char *szSndName) { - C4SoundEffect *pSfx; - char szName[C4MaxSoundName+4+1]; - int32_t iNumber; - // Evaluate sound name - SCopy(szSndName,szName,C4MaxSoundName); + C4SoundEffect *pSfx; + char szName[C4MaxSoundName+4+1]; + int32_t iNumber; + // Evaluate sound name + SCopy(szSndName,szName,C4MaxSoundName); // Default extension DefaultExtension(szName,"wav"); // Convert old style '*' wildcard to correct '?' wildcard // For sound effects, '*' is supposed to match single digits only - SReplaceChar(szName, '*', '?'); + SReplaceChar(szName, '*', '?'); // Sound with a wildcard: determine number of available matches if (SCharCount('?',szName)) { @@ -514,47 +514,47 @@ C4SoundEffect* C4SoundSystem::GetEffect(const char *szSndName) // None found: failure return NULL; // Insert index to name - iNumber=BoundBy(1+SafeRandom(iNumber),1,9); - SReplaceChar(szName,'?','0'+iNumber); + iNumber=BoundBy(1+SafeRandom(iNumber),1,9); + SReplaceChar(szName,'?','0'+iNumber); } - // Find requested sound effect in bank - for (pSfx=FirstSound; pSfx; pSfx=pSfx->Next) - if (SEqualNoCase(szName,pSfx->Name)) - break; - // Sound not in bank, try add - if (!pSfx) - if (!(pSfx = AddEffect(szName))) - return NULL; - return pSfx; + // Find requested sound effect in bank + for (pSfx=FirstSound; pSfx; pSfx=pSfx->Next) + if (SEqualNoCase(szName,pSfx->Name)) + break; + // Sound not in bank, try add + if (!pSfx) + if (!(pSfx = AddEffect(szName))) + return NULL; + return pSfx; } C4SoundInstance *C4SoundSystem::NewEffect(const char *szSndName, bool fLoop, int32_t iVolume, C4Object *pObj, int32_t iCustomFalloffDistance) { // Sound not active - if (!Config.Sound.RXSound) return false; + if (!Config.Sound.RXSound) return false; // Get sound - C4SoundEffect *csfx; - if (!(csfx=GetEffect(szSndName))) return false; + C4SoundEffect *csfx; + if (!(csfx=GetEffect(szSndName))) return false; // Play - return csfx->New(fLoop, iVolume, pObj, iCustomFalloffDistance); + return csfx->New(fLoop, iVolume, pObj, iCustomFalloffDistance); } C4SoundInstance *C4SoundSystem::FindInstance(const char *szSndName, C4Object *pObj) - { - char szName[C4MaxSoundName+4+1]; - // Evaluate sound name (see GetEffect) - SCopy(szSndName,szName,C4MaxSoundName); + { + char szName[C4MaxSoundName+4+1]; + // Evaluate sound name (see GetEffect) + SCopy(szSndName,szName,C4MaxSoundName); DefaultExtension(szName,"wav"); - SReplaceChar(szName, '*', '?'); - // Find an effect with a matching instance - for(C4SoundEffect *csfx = FirstSound; csfx; csfx = csfx->Next) - if(WildcardMatch(szName, csfx->Name)) - { - C4SoundInstance *pInst = csfx->GetInstance(pObj); - if(pInst) return pInst; - } - return NULL; - } + SReplaceChar(szName, '*', '?'); + // Find an effect with a matching instance + for(C4SoundEffect *csfx = FirstSound; csfx; csfx = csfx->Next) + if(WildcardMatch(szName, csfx->Name)) + { + C4SoundInstance *pInst = csfx->GetInstance(pObj); + if(pInst) return pInst; + } + return NULL; + } // LoadEffects will load all sound effects of all known sound types (i.e. *.wav and *.ogg) // To play an ogg effect, however, you will have to specify the extension in the sound @@ -613,62 +613,62 @@ int32_t C4SoundSystem::RemoveEffect(const char *szFilename) } void C4SoundSystem::ClearPointers(C4Object *pObj) - { + { for (C4SoundEffect *pEff=FirstSound; pEff; pEff=pEff->Next) - pEff->ClearPointers(pObj); - } + pEff->ClearPointers(pObj); + } C4SoundInstance *StartSoundEffect(const char *szSndName, bool fLoop, int32_t iVolume, C4Object *pObj, int32_t iCustomFalloffDistance) - { - // Sound check - if (!Config.Sound.RXSound) return false; - // Start new - return Application.SoundSystem.NewEffect(szSndName, fLoop, iVolume, pObj, iCustomFalloffDistance); - } + { + // Sound check + if (!Config.Sound.RXSound) return false; + // Start new + return Application.SoundSystem.NewEffect(szSndName, fLoop, iVolume, pObj, iCustomFalloffDistance); + } C4SoundInstance *StartSoundEffectAt(const char *szSndName, int32_t iX, int32_t iY, bool fLoop, int32_t iVolume) - { - // Sound check - if (!Config.Sound.RXSound) return false; - // Create - C4SoundInstance *pInst = StartSoundEffect(szSndName, fLoop, iVolume); - // Set volume by position - if(pInst) pInst->SetVolumeByPos(iX, iY); - // Return - return pInst; - } + { + // Sound check + if (!Config.Sound.RXSound) return false; + // Create + C4SoundInstance *pInst = StartSoundEffect(szSndName, fLoop, iVolume); + // Set volume by position + if(pInst) pInst->SetVolumeByPos(iX, iY); + // Return + return pInst; + } C4SoundInstance *GetSoundInstance(const char *szSndName, C4Object *pObj) - { - return Application.SoundSystem.FindInstance(szSndName, pObj); - } + { + return Application.SoundSystem.FindInstance(szSndName, pObj); + } void StopSoundEffect(const char *szSndName, C4Object *pObj) - { - // Find instance - C4SoundInstance *pInst = Application.SoundSystem.FindInstance(szSndName, pObj); - if(!pInst) return; - // Stop - pInst->Stop(); - } + { + // Find instance + C4SoundInstance *pInst = Application.SoundSystem.FindInstance(szSndName, pObj); + if(!pInst) return; + // Stop + pInst->Stop(); + } void SoundLevel(const char *szSndName, C4Object *pObj, int32_t iLevel) - { - // Sound level zero? Stop - if(!iLevel) { StopSoundEffect(szSndName, pObj); return; } - // Find or create instance - C4SoundInstance *pInst = Application.SoundSystem.FindInstance(szSndName, pObj); - if(!pInst) pInst = StartSoundEffect(szSndName, true, iLevel, pObj); - if(!pInst) return; - // Set volume - pInst->SetVolume(iLevel); - pInst->Execute(); - } + { + // Sound level zero? Stop + if(!iLevel) { StopSoundEffect(szSndName, pObj); return; } + // Find or create instance + C4SoundInstance *pInst = Application.SoundSystem.FindInstance(szSndName, pObj); + if(!pInst) pInst = StartSoundEffect(szSndName, true, iLevel, pObj); + if(!pInst) return; + // Set volume + pInst->SetVolume(iLevel); + pInst->Execute(); + } void SoundPan(const char *szSndName, C4Object *pObj, int32_t iPan) - { - // Find instance - C4SoundInstance *pInst = Application.SoundSystem.FindInstance(szSndName, pObj); - if(!pInst) return; - // Set pan - pInst->SetPan(iPan); - pInst->Execute(); - } + { + // Find instance + C4SoundInstance *pInst = Application.SoundSystem.FindInstance(szSndName, pObj); + if(!pInst) return; + // Set pan + pInst->SetPan(iPan); + pInst->Execute(); + } diff --git a/src/platform/C4SoundSystem.h b/src/platform/C4SoundSystem.h index bb00de1cd..3d921cc5b 100644 --- a/src/platform/C4SoundSystem.h +++ b/src/platform/C4SoundSystem.h @@ -36,8 +36,8 @@ #endif const int32_t C4MaxSoundName=100, - C4MaxSoundInstances=20, - C4NearSoundRadius=50, + C4MaxSoundInstances=20, + C4NearSoundRadius=50, C4AudibilityRadius=700; class C4Object; @@ -45,14 +45,14 @@ class C4SoundInstance; class C4SoundEffect { - friend class C4SoundInstance; + friend class C4SoundInstance; public: - C4SoundEffect(); - ~C4SoundEffect(); + C4SoundEffect(); + ~C4SoundEffect(); public: - char Name[C4MaxSoundName+1]; - int32_t UsageTime, Instances; - int32_t SampleRate, Length; + char Name[C4MaxSoundName+1]; + int32_t UsageTime, Instances; + int32_t SampleRate, Length; bool Static; #ifdef HAVE_FMOD FSOUND_SAMPLE *pSample; @@ -60,55 +60,55 @@ public: #ifdef HAVE_LIBSDL_MIXER Mix_Chunk * pSample; #endif - C4SoundInstance *FirstInst; - C4SoundEffect *Next; + C4SoundInstance *FirstInst; + C4SoundEffect *Next; public: - void Clear(); - bool Load(const char *szFileName, C4Group &hGroup, bool fStatic); + void Clear(); + bool Load(const char *szFileName, C4Group &hGroup, bool fStatic); bool Load(BYTE *pData, size_t iDataLen, bool fStatic, bool fRaw=false); // load directly from memory - void Execute(); - C4SoundInstance *New(bool fLoop = false, int32_t iVolume = 100, C4Object *pObj = NULL, int32_t iCustomFalloffDistance = 0); - C4SoundInstance *GetInstance(C4Object *pObj); - void ClearPointers(C4Object *pObj); - int32_t GetStartedInstanceCount(int32_t iX, int32_t iY, int32_t iRad); // local - int32_t GetStartedInstanceCount(); // global + void Execute(); + C4SoundInstance *New(bool fLoop = false, int32_t iVolume = 100, C4Object *pObj = NULL, int32_t iCustomFalloffDistance = 0); + C4SoundInstance *GetInstance(C4Object *pObj); + void ClearPointers(C4Object *pObj); + int32_t GetStartedInstanceCount(int32_t iX, int32_t iY, int32_t iRad); // local + int32_t GetStartedInstanceCount(); // global protected: - void AddInst(C4SoundInstance *pInst); - void RemoveInst(C4SoundInstance *pInst); + void AddInst(C4SoundInstance *pInst); + void RemoveInst(C4SoundInstance *pInst); }; class C4SoundInstance { - friend class C4SoundEffect; + friend class C4SoundEffect; protected: - C4SoundInstance(); + C4SoundInstance(); public: - ~C4SoundInstance(); + ~C4SoundInstance(); protected: - C4SoundEffect *pEffect; - int32_t iVolume, iPan, iChannel; - unsigned long iStarted; - int32_t iNearInstanceMax; - bool fLooping; - C4Object *pObj; + C4SoundEffect *pEffect; + int32_t iVolume, iPan, iChannel; + unsigned long iStarted; + int32_t iNearInstanceMax; + bool fLooping; + C4Object *pObj; int32_t iFalloffDistance; - C4SoundInstance *pNext; + C4SoundInstance *pNext; public: - C4Object *getObj() const { return pObj; } - bool isStarted() const { return iChannel != -1; } - void Clear(); - bool Create(C4SoundEffect *pEffect, bool fLoop = false, int32_t iVolume = 100, C4Object *pObj = NULL, int32_t iNearInstanceMax = 0, int32_t iFalloffDistance = 0); - bool CheckStart(); - bool Start(); - bool Stop(); - bool Playing(); - void Execute(); - void SetVolume(int32_t inVolume) { iVolume = inVolume; } - void SetPan(int32_t inPan) { iPan = inPan; } - void SetVolumeByPos(int32_t x, int32_t y); - void SetObj(C4Object *pnObj) { pObj = pnObj; } - void ClearPointers(C4Object *pObj); - bool Inside(int32_t iX, int32_t iY, int32_t iRad); + C4Object *getObj() const { return pObj; } + bool isStarted() const { return iChannel != -1; } + void Clear(); + bool Create(C4SoundEffect *pEffect, bool fLoop = false, int32_t iVolume = 100, C4Object *pObj = NULL, int32_t iNearInstanceMax = 0, int32_t iFalloffDistance = 0); + bool CheckStart(); + bool Start(); + bool Stop(); + bool Playing(); + void Execute(); + void SetVolume(int32_t inVolume) { iVolume = inVolume; } + void SetPan(int32_t inPan) { iPan = inPan; } + void SetVolumeByPos(int32_t x, int32_t y); + void SetObj(C4Object *pnObj) { pObj = pnObj; } + void ClearPointers(C4Object *pObj); + bool Inside(int32_t iX, int32_t iY, int32_t iRad); }; const int32_t SoundUnloadTime=60, SoundMaxUnloadSize=100000; @@ -124,7 +124,7 @@ class C4SoundSystem C4SoundInstance *NewEffect(const char *szSound, bool fLoop = false, int32_t iVolume = 100, C4Object *pObj = NULL, int32_t iCustomFalloffDistance = 0); C4SoundInstance *FindInstance(const char *szSound, C4Object *pObj); bool Init(); - void ClearPointers(C4Object *pObj); + void ClearPointers(C4Object *pObj); protected: C4Group SoundFile; C4SoundEffect *FirstSound; diff --git a/src/platform/C4Video.cpp b/src/platform/C4Video.cpp index 726369489..4618ed3d8 100644 --- a/src/platform/C4Video.cpp +++ b/src/platform/C4Video.cpp @@ -159,7 +159,7 @@ bool C4Video::Start(const char *szFilename) BufferSize = InfoSize + DWordAligned(Width)*Height * Config.Graphics.BitDepth/8; Buffer = new BYTE[BufferSize]; // Set bitmap info - BITMAPINFO *pInfo = (BITMAPINFO*) Buffer; + BITMAPINFO *pInfo = (BITMAPINFO*) Buffer; ZeroMem((BYTE*)pInfo,sizeof(BITMAPINFOHEADER)); pInfo->bmiHeader.biSize=sizeof(BITMAPINFOHEADER); pInfo->bmiHeader.biPlanes=1; @@ -230,21 +230,21 @@ bool C4Video::AdjustPosition() #ifdef _WIN32 static void StdBlit(uint8_t *bypSource, int iSourcePitch, int iSrcBufHgt, - int iSrcX, int iSrcY, int iSrcWdt, int iSrcHgt, - uint8_t *bypTarget, int iTargetPitch, int iTrgBufHgt, - int iTrgX, int iTrgY, int iTrgWdt, int iTrgHgt, + int iSrcX, int iSrcY, int iSrcWdt, int iSrcHgt, + uint8_t *bypTarget, int iTargetPitch, int iTrgBufHgt, + int iTrgX, int iTrgY, int iTrgWdt, int iTrgHgt, int iBytesPerPixel=1, bool fFlip=false) - { - if (!bypSource || !bypTarget) return; - if (!iTrgWdt || !iTrgHgt) return; - int xcnt,ycnt,zcnt,sline,tline,fy; - for (ycnt=0; ycnt0) sline = ( iSrcBufHgt - 1 - iSrcY - fy ) * iSourcePitch; - else sline = ( iSrcY + fy ) * iSourcePitch; - if (iTrgBufHgt>0) tline = ( iTrgBufHgt - 1 - iTrgY - ycnt ) * iTargetPitch; - else tline = ( iTrgY + ycnt ) * iTargetPitch; + { + if (!bypSource || !bypTarget) return; + if (!iTrgWdt || !iTrgHgt) return; + int xcnt,ycnt,zcnt,sline,tline,fy; + for (ycnt=0; ycnt0) sline = ( iSrcBufHgt - 1 - iSrcY - fy ) * iSourcePitch; + else sline = ( iSrcY + fy ) * iSourcePitch; + if (iTrgBufHgt>0) tline = ( iTrgBufHgt - 1 - iTrgY - ycnt ) * iTargetPitch; + else tline = ( iTrgY + ycnt ) * iTargetPitch; if (!fFlip) { for (xcnt=0; xcntRelease(); lpDevice=NULL; } - lpD3D->Release(); lpD3D=NULL; - } + lpD3D->Release(); lpD3D=NULL; + } SceneOpen=false; CStdDDraw::Clear(); } @@ -93,14 +93,14 @@ bool CStdD3D::PageFlip(RECT *pSrcRt, RECT *pDstRt, CStdWindow * pWindow) // safety if (!lpDevice) return false; // end the scene and present it - EndScene(); + EndScene(); if (lpDevice->Present(pSrcRt, pDstRt, pWindow ? pWindow->hWindow : 0, NULL) == D3DERR_DEVICELOST) { if (lpDevice->TestCooperativeLevel() == D3DERR_DEVICELOST) return false; if (!RestoreDeviceObjects()) return false; lpDevice->Present(NULL, NULL, NULL, NULL); } - return true; + return true; } @@ -490,8 +490,8 @@ bool CStdD3D::CreatePrimarySurfaces(bool Fullscreen, unsigned int iXRes, unsigne d3dpp.SwapEffect = D3DSWAPEFFECT_FLIP; d3dpp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; hr = lpD3D->CreateDevice(iMonitor, fSoftware ? D3DDEVTYPE_REF : D3DDEVTYPE_HAL, hWindow, - D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE, - &d3dpp, &lpDevice); + D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE, + &d3dpp, &lpDevice); } else { @@ -509,13 +509,13 @@ bool CStdD3D::CreatePrimarySurfaces(bool Fullscreen, unsigned int iXRes, unsigne d3dpp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; // create primary surface hr = lpD3D->CreateDevice(iMonitor, fSoftware ? D3DDEVTYPE_REF : D3DDEVTYPE_HAL, hWindow, - D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE, - &d3dpp, &lpDevice); + D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE, + &d3dpp, &lpDevice); // windowed mode: Try dfault adapter as well if (hr != D3D_OK && iMonitor != D3DADAPTER_DEFAULT) hr = lpD3D->CreateDevice(D3DADAPTER_DEFAULT, fSoftware ? D3DDEVTYPE_REF : D3DDEVTYPE_HAL, hWindow, - D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE, - &d3dpp, &lpDevice); + D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE, + &d3dpp, &lpDevice); } switch (hr) { diff --git a/src/platform/StdD3D.h b/src/platform/StdD3D.h index 4bceb5c8c..1a7a02660 100644 --- a/src/platform/StdD3D.h +++ b/src/platform/StdD3D.h @@ -48,24 +48,24 @@ // default Clonk vertex format struct C4VERTEX - { - FLOAT x, y, z, rhw; // transformed vertex pos - FLOAT tu, tv; // texture offsets + { + FLOAT x, y, z, rhw; // transformed vertex pos + FLOAT tu, tv; // texture offsets }; // vertex format for solid blits struct C4CLRVERTEX - { - FLOAT x, y, z, rhw; // transformed vertex pos - DWORD color; // blit color + { + FLOAT x, y, z, rhw; // transformed vertex pos + DWORD color; // blit color }; // vertex format for ColorByOwner-blits struct C4CTVERTEX - { - FLOAT x, y, z, rhw; // transformed vertex pos - DWORD color; // overlay color - FLOAT tu, tv; // texture offsets + { + FLOAT x, y, z, rhw; // transformed vertex pos + DWORD color; // overlay color + FLOAT tu, tv; // texture offsets }; #define D3DFVF_C4VERTEX (D3DFVF_XYZRHW|D3DFVF_TEX1) @@ -80,29 +80,29 @@ class CStdD3DShader; // direct draw encapsulation class CStdD3D : public CStdDDraw - { - public: - CStdD3D(bool fSoftware); - ~CStdD3D(); - protected: - IDirect3D9 *lpD3D; - IDirect3DDevice9 *lpDevice; - IDirect3DVertexBuffer9 *pVB; // prepared vertex buffer for blitting - IDirect3DVertexBuffer9 *pVBClr; // prepared vertex buffer for drawing in solid color - IDirect3DVertexBuffer9 *pVBClrTex;// prepared vertex buffer for blitting iwth color/tex-modulation - C4VERTEX bltVertices[8]; // prepared vertex data; need to insert x/y and u/v - C4CLRVERTEX clrVertices[8]; // prepared vertex data; need to insert x/y and color - C4CTVERTEX bltClrVertices[8]; // prepared vertex data; need to insert x/y, color and u/v - IDirect3DStateBlock9 *bltState[3]; // saved state block for blitting (0: copy; 1: blit; 2: blit additive) - IDirect3DStateBlock9 *bltBaseState[4]; // saved state block for blitting with a base face (0: normal; 1: additive; 2: mod2; 3: mod2+additive) - IDirect3DStateBlock9 *drawSolidState[2]; // saved state block for drawing in solid color (0: normal; 1: additive) - IDirect3DStateBlock9 *pSavedState; // state block to backup current state - D3DVIEWPORT9 WindowClipper; - D3DDISPLAYMODE dspMode; - D3DPRESENT_PARAMETERS d3dpp; // device present parameters - D3DFORMAT dwSurfaceType;// surface format for new textures - D3DFORMAT PrimarySrfcFormat;// surace format of primary surface - bool fSoftware; // software rendering + { + public: + CStdD3D(bool fSoftware); + ~CStdD3D(); + protected: + IDirect3D9 *lpD3D; + IDirect3DDevice9 *lpDevice; + IDirect3DVertexBuffer9 *pVB; // prepared vertex buffer for blitting + IDirect3DVertexBuffer9 *pVBClr; // prepared vertex buffer for drawing in solid color + IDirect3DVertexBuffer9 *pVBClrTex;// prepared vertex buffer for blitting iwth color/tex-modulation + C4VERTEX bltVertices[8]; // prepared vertex data; need to insert x/y and u/v + C4CLRVERTEX clrVertices[8]; // prepared vertex data; need to insert x/y and color + C4CTVERTEX bltClrVertices[8]; // prepared vertex data; need to insert x/y, color and u/v + IDirect3DStateBlock9 *bltState[3]; // saved state block for blitting (0: copy; 1: blit; 2: blit additive) + IDirect3DStateBlock9 *bltBaseState[4]; // saved state block for blitting with a base face (0: normal; 1: additive; 2: mod2; 3: mod2+additive) + IDirect3DStateBlock9 *drawSolidState[2]; // saved state block for drawing in solid color (0: normal; 1: additive) + IDirect3DStateBlock9 *pSavedState; // state block to backup current state + D3DVIEWPORT9 WindowClipper; + D3DDISPLAYMODE dspMode; + D3DPRESENT_PARAMETERS d3dpp; // device present parameters + D3DFORMAT dwSurfaceType;// surface format for new textures + D3DFORMAT PrimarySrfcFormat;// surace format of primary surface + bool fSoftware; // software rendering enum ShaderIndex { SHIDX_Mod2 = 1, @@ -112,61 +112,61 @@ class CStdD3D : public CStdDDraw CStdD3DShader *pShaders[SHIDX_Size]; BITMAPINFO sfcBmpInfo; // surface bits as bitmap bits info bool SceneOpen; // set if a scene has begun - public: - // General - void Clear(); - void Default(); - bool PageFlip(RECT *pSrcRt=NULL, RECT *pDstRt=NULL, CStdWindow * pWindow = NULL); - bool BeginScene(); // prepare device for drawing - void EndScene(); // prepare device for surface locking, flipping etc. - virtual int GetEngine() { return fSoftware ? 2 : 0; } // get indexed engine - void TaskOut(); // user taskswitched the app away - void TaskIn(); // user tasked back - bool SetVideoMode(unsigned int iXRes, unsigned int iYRes, unsigned int iColorDepth, unsigned int iMonitor, bool fFullScreen); - virtual bool OnResolutionChanged(unsigned int iXRes, unsigned int iYRes); // reinit clipper for new resolution - // Clipper - bool UpdateClipper(); // set current clipper to render target - virtual bool PrepareMaterial(StdMeshMaterial &mat); - // Surface - bool PrepareRendering(SURFACE sfcToSurface); // check if/make rendering possible to given surface - // Blit + public: + // General + void Clear(); + void Default(); + bool PageFlip(RECT *pSrcRt=NULL, RECT *pDstRt=NULL, CStdWindow * pWindow = NULL); + bool BeginScene(); // prepare device for drawing + void EndScene(); // prepare device for surface locking, flipping etc. + virtual int GetEngine() { return fSoftware ? 2 : 0; } // get indexed engine + void TaskOut(); // user taskswitched the app away + void TaskIn(); // user tasked back + bool SetVideoMode(unsigned int iXRes, unsigned int iYRes, unsigned int iColorDepth, unsigned int iMonitor, bool fFullScreen); + virtual bool OnResolutionChanged(unsigned int iXRes, unsigned int iYRes); // reinit clipper for new resolution + // Clipper + bool UpdateClipper(); // set current clipper to render target + virtual bool PrepareMaterial(StdMeshMaterial &mat); + // Surface + bool PrepareRendering(SURFACE sfcToSurface); // check if/make rendering possible to given surface + // Blit virtual void PerformMesh(StdMeshInstance &instance, float tx, float ty, float twdt, float thgt, DWORD dwPlayerColor, CBltTransform* pTransform); - void PerformBlt(CBltData &rBltData, CTexRef *pTex, DWORD dwModClr, bool fMod2, bool fExact); - bool BlitTex2Window(CTexRef *pTexRef, HDC hdcTarget, RECT &rtFrom, RECT &rtTo); - bool BlitSurface2Window(SURFACE sfcSource, int fX, int fY, int fWdt, int fHgt, HWND hWnd, int tX, int tY, int tWdt, int tHgt); - void FillBG(DWORD dwClr=0); - // Drawing - void DrawQuadDw(SURFACE sfcTarget, float *ipVtx, DWORD dwClr1, DWORD dwClr2, DWORD dwClr3, DWORD dwClr4); - void PerformLine(SURFACE sfcTarget, float x1, float y1, float x2, float y2, DWORD dwClr); - void PerformPix(SURFACE sfcDest, float tx, float ty, DWORD dwCol); + void PerformBlt(CBltData &rBltData, CTexRef *pTex, DWORD dwModClr, bool fMod2, bool fExact); + bool BlitTex2Window(CTexRef *pTexRef, HDC hdcTarget, RECT &rtFrom, RECT &rtTo); + bool BlitSurface2Window(SURFACE sfcSource, int fX, int fY, int fWdt, int fHgt, HWND hWnd, int tX, int tY, int tWdt, int tHgt); + void FillBG(DWORD dwClr=0); + // Drawing + void DrawQuadDw(SURFACE sfcTarget, float *ipVtx, DWORD dwClr1, DWORD dwClr2, DWORD dwClr3, DWORD dwClr4); + void PerformLine(SURFACE sfcTarget, float x1, float y1, float x2, float y2, DWORD dwClr); + void PerformPix(SURFACE sfcDest, float tx, float ty, DWORD dwCol); void DrawPixPrimary(SURFACE sfcDest, int tx, int ty, DWORD dwCol); - // Gamma - virtual bool ApplyGammaRamp(D3DGAMMARAMP &ramp, bool fForce); - virtual bool SaveDefaultGammaRamp(CStdWindow * pWindow); - // device objects - bool InitDeviceObjects(); // init device dependent objects + // Gamma + virtual bool ApplyGammaRamp(D3DGAMMARAMP &ramp, bool fForce); + virtual bool SaveDefaultGammaRamp(CStdWindow * pWindow); + // device objects + bool InitDeviceObjects(); // init device dependent objects bool InitShaders(); // parse and set shaders - bool RestoreDeviceObjects(); // restore device dependent objects - bool InvalidateDeviceObjects(); // free device dependent objects - bool DeleteDeviceObjects(); // free device dependent objects - void SetTexture(); - void ResetTexture(); - bool DeviceReady() { return !!lpDevice; } + bool RestoreDeviceObjects(); // restore device dependent objects + bool InvalidateDeviceObjects(); // free device dependent objects + bool DeleteDeviceObjects(); // free device dependent objects + void SetTexture(); + void ResetTexture(); + bool DeviceReady() { return !!lpDevice; } bool CreateStateBlock(IDirect3DStateBlock9 **pBlock, bool fTransparent, bool fSolid, bool fBaseTex, bool fAdditive, bool fMod2); // capture state blocks for blitting - protected: - bool FindDisplayMode(unsigned int iXRes, unsigned int iYRes, unsigned int iColorDepth, unsigned int iMonitor); + protected: + bool FindDisplayMode(unsigned int iXRes, unsigned int iYRes, unsigned int iColorDepth, unsigned int iMonitor); bool FindDisplayMode(unsigned int iXRes, unsigned int iYRes, D3DFORMAT format, unsigned int iMonitor); virtual bool CreatePrimarySurfaces(bool Fullscreen, unsigned int iXRes, unsigned int iYRes, int iColorDepth, unsigned int iMonitor); - bool SetOutputAdapter(unsigned int iMonitor); + bool SetOutputAdapter(unsigned int iMonitor); inline bool HasShaders() const { return !!pShaders[0]; } - friend class CSurface; - friend class CTexRef; - friend class CPattern; - }; + friend class CSurface; + friend class CTexRef; + friend class CPattern; + }; // Global D3D access pointer extern CStdD3D *pD3D; diff --git a/src/platform/StdDDraw2.cpp b/src/platform/StdDDraw2.cpp index 65f803a01..ef3fc2ef6 100644 --- a/src/platform/StdDDraw2.cpp +++ b/src/platform/StdDDraw2.cpp @@ -42,9 +42,9 @@ CStdPalette *lpDDrawPal=NULL; int iGfxEngine=-1; inline void SetRect(RECT &rect, int left, int top, int right, int bottom) - { - rect.left=left; rect.top=top; rect.bottom=bottom; rect.right=right; - } + { + rect.left=left; rect.top=top; rect.bottom=bottom; rect.right=right; + } inline DWORD GetTextShadowClr(DWORD dwTxtClr) { @@ -481,7 +481,7 @@ bool CStdDDraw::NoPrimaryClipper() } void CStdDDraw::BlitLandscape(SURFACE sfcSource, float fx, float fy, - SURFACE sfcTarget, float tx, float ty, float wdt, float hgt, const SURFACE textures[]) + SURFACE sfcTarget, float tx, float ty, float wdt, float hgt, const SURFACE textures[]) { Blit(sfcSource, fx, fy, wdt, hgt, sfcTarget, tx, ty, wdt, hgt, false); } @@ -767,19 +767,19 @@ bool CStdDDraw::BlitRotate(SURFACE sfcSource, int fx, int fy, int fwdt, int fhgt rot.SetRotate(iAngle, (float) (tx+tx+twdt)/2, (float) (ty+ty+thgt)/2); return Blit(sfcSource, float(fx), float(fy), float(fwdt), float(fhgt), sfcTarget, float(tx), float(ty), float(twdt), float(thgt), true, &rot); } - // Object is first stretched to dest rect, then rotated at place. - int xcnt,ycnt,fcx,fcy,tcx,tcy,cpcx,cpcy; - int npcx,npcy; - double mtx[4],dang; - if (!fwdt || !fhgt || !twdt || !thgt) return false; - // Lock the surfaces - if (!sfcSource->Lock()) - return false; - if (!sfcTarget->Lock()) - { sfcSource->Unlock(); return false; } - // Rectangle centers - fcx=fwdt/2; fcy=fhgt/2; - tcx=twdt/2; tcy=thgt/2; + // Object is first stretched to dest rect, then rotated at place. + int xcnt,ycnt,fcx,fcy,tcx,tcy,cpcx,cpcy; + int npcx,npcy; + double mtx[4],dang; + if (!fwdt || !fhgt || !twdt || !thgt) return false; + // Lock the surfaces + if (!sfcSource->Lock()) + return false; + if (!sfcTarget->Lock()) + { sfcSource->Unlock(); return false; } + // Rectangle centers + fcx=fwdt/2; fcy=fhgt/2; + tcx=twdt/2; tcy=thgt/2; // Adjust angle range while (iAngle<0) iAngle+=36000; while (iAngle>35999) iAngle-=36000; // Exact/free rotation @@ -843,10 +843,10 @@ bool CStdDDraw::BlitRotate(SURFACE sfcSource, int fx, int fy, int fwdt, int fhgt break; } - // Unlock the surfaces + // Unlock the surfaces sfcSource->Unlock(); sfcTarget->Unlock(); - return true; + return true; } @@ -889,18 +889,18 @@ bool CStdDDraw::BlitSurface(SURFACE sfcSurface, SURFACE sfcTarget, int tx, int t sfcSurface->pMainSfc = pSfcBase; return true; } - } + } bool CStdDDraw::BlitSurfaceTile(SURFACE sfcSurface, SURFACE sfcTarget, int iToX, int iToY, int iToWdt, int iToHgt, int iOffsetX, int iOffsetY, bool fSrcColKey) - { - int iSourceWdt,iSourceHgt,iX,iY,iBlitX,iBlitY,iBlitWdt,iBlitHgt; + { + int iSourceWdt,iSourceHgt,iX,iY,iBlitX,iBlitY,iBlitWdt,iBlitHgt; // Get source surface size - if (!GetSurfaceSize(sfcSurface,iSourceWdt,iSourceHgt)) return false; + if (!GetSurfaceSize(sfcSurface,iSourceWdt,iSourceHgt)) return false; // reduce offset to needed size iOffsetX %= iSourceWdt; iOffsetY %= iSourceHgt; // Vertical blits - for (iY=iToY+iOffsetY; iYIsRenderTarget()) return Blit(sfcSurface, iOffsetX, iOffsetY, iToWdt, iToHgt, sfcTarget, iToX, iToY, iToWdt, iToHgt, false);*/ - int tx,ty,iBlitX,iBlitY,iBlitWdt,iBlitHgt; + int tx,ty,iBlitX,iBlitY,iBlitWdt,iBlitHgt; // get tile size int iTileWdt=sfcSurface->Wdt; int iTileHgt=sfcSurface->Hgt; @@ -1046,13 +1046,13 @@ void CStdDDraw::DrawBox(SURFACE sfcDest, int iX1, int iY1, int iX2, int iY2, BYT } // draw as primitives DrawBoxDw(sfcDest, iX1, iY1, iX2, iY2, dwClr); - } + } void CStdDDraw::DrawLineDw(SURFACE sfcTarget, float x1, float y1, float x2, float y2, DWORD dwClr) { ApplyZoom(x1, y1); ApplyZoom(x2, y2); - // manual clipping? + // manual clipping? if (DDrawCfg.ClipManuallyE) { float i; @@ -1152,53 +1152,53 @@ void CStdDDraw::DrawVerticalLine(SURFACE sfcDest, int x, int y1, int y2, BYTE co } void CStdDDraw::DrawFrame(SURFACE sfcDest, int x1, int y1, int x2, int y2, BYTE col) - { - DrawHorizontalLine(sfcDest,x1,x2,y1,col); - DrawHorizontalLine(sfcDest,x1,x2,y2,col); - DrawVerticalLine(sfcDest,x1,y1,y2,col); - DrawVerticalLine(sfcDest,x2,y1,y2,col); - } + { + DrawHorizontalLine(sfcDest,x1,x2,y1,col); + DrawHorizontalLine(sfcDest,x1,x2,y2,col); + DrawVerticalLine(sfcDest,x1,y1,y2,col); + DrawVerticalLine(sfcDest,x2,y1,y2,col); + } void CStdDDraw::DrawFrameDw(SURFACE sfcDest, int x1, int y1, int x2, int y2, DWORD dwClr) // make these parameters float...? - { + { DrawLineDw(sfcDest,(float)x1,(float)y1,(float)x2,(float)y1, dwClr); DrawLineDw(sfcDest,(float)x2,(float)y1,(float)x2,(float)y2, dwClr); DrawLineDw(sfcDest,(float)x2,(float)y2,(float)x1,(float)y2, dwClr); DrawLineDw(sfcDest,(float)x1,(float)y2,(float)x1,(float)y1, dwClr); - } + } // Globally locked surface variables - for DrawLine callback crap CSurface *GLSBuffer=NULL; bool LockSurfaceGlobal(SURFACE sfcTarget) - { - if (GLSBuffer) return false; - GLSBuffer=sfcTarget; + { + if (GLSBuffer) return false; + GLSBuffer=sfcTarget; return !!sfcTarget->Lock(); - } + } bool UnLockSurfaceGlobal(SURFACE sfcTarget) - { - if (!GLSBuffer) return false; + { + if (!GLSBuffer) return false; sfcTarget->Unlock(); - GLSBuffer=NULL; - return true; - } + GLSBuffer=NULL; + return true; + } bool DLineSPix(int32_t x, int32_t y, int32_t col) - { - if (!GLSBuffer) return false; - GLSBuffer->SetPix(x,y,col); - return true; - } + { + if (!GLSBuffer) return false; + GLSBuffer->SetPix(x,y,col); + return true; + } bool DLineSPixDw(int32_t x, int32_t y, int32_t dwClr) - { - if (!GLSBuffer) return false; - GLSBuffer->SetPixDw(x,y,(DWORD) dwClr); - return true; - } + { + if (!GLSBuffer) return false; + GLSBuffer->SetPixDw(x,y,(DWORD) dwClr); + return true; + } void CStdDDraw::DrawPatternedCircle(SURFACE sfcDest, int x, int y, int r, BYTE col, CPattern & Pattern, CStdPalette &rPal) { diff --git a/src/platform/StdDDraw2.h b/src/platform/StdDDraw2.h index a58d4e304..3c085d179 100644 --- a/src/platform/StdDDraw2.h +++ b/src/platform/StdDDraw2.h @@ -171,9 +171,9 @@ struct CBltData #ifndef USE_DIRECTX typedef struct _D3DGAMMARAMP { - WORD red [256]; - WORD green[256]; - WORD blue [256]; + WORD red [256]; + WORD green[256]; + WORD blue [256]; } D3DGAMMARAMP; #endif diff --git a/src/platform/StdFacet.h b/src/platform/StdFacet.h index e31610c63..975fd0c5e 100644 --- a/src/platform/StdFacet.h +++ b/src/platform/StdFacet.h @@ -29,14 +29,14 @@ class CFacet public: CFacet() : Surface(NULL), X(0), Y(0), Wdt(0), Hgt(0) { } ~CFacet() { } - public: - SURFACE Surface; - int X,Y,Wdt,Hgt; - public: + public: + SURFACE Surface; + int X,Y,Wdt,Hgt; + public: void Draw(SURFACE sfcSurface, int iX, int iY, int iPhaseX=0, int iPhaseY=0); void Default() { Surface=NULL; X=Y=Wdt=Hgt=0; } void Clear() { Surface=NULL; X=Y=Wdt=Hgt=0; } - void Set(SURFACE nsfc, int nx, int ny, int nwdt, int nhgt) + void Set(SURFACE nsfc, int nx, int ny, int nwdt, int nhgt) { Surface=nsfc; X=nx; Y=ny; Wdt=nwdt; Hgt=nhgt; } }; #endif // STD_FACET diff --git a/src/platform/StdFile.cpp b/src/platform/StdFile.cpp index 247198b10..3f7fe8446 100644 --- a/src/platform/StdFile.cpp +++ b/src/platform/StdFile.cpp @@ -55,19 +55,19 @@ static const char *DirectorySeparators = "/"; // Return pointer to position after last backslash. char *GetFilename(char *szPath) - { + { if (!szPath) return NULL; char *pPos,*pFilename=szPath; for (pPos=szPath; *pPos; pPos++) if (*pPos==DirectorySeparator || *pPos=='/') pFilename = pPos+1; return pFilename; - } + } const char *GetFilename(const char *szPath) - { + { if (!szPath) return NULL; const char *pPos,*pFilename=szPath; for (pPos=szPath; *pPos; pPos++) if (*pPos==DirectorySeparator || *pPos=='/') pFilename = pPos+1; return pFilename; - } + } const char* GetFilenameOnly(const char *strFilename) { @@ -131,23 +131,23 @@ const char *GetFilenameWeb(const char *szPath) // Return pointer to last file extension. char *GetExtension(char *szFilename) - { - int pos, end; - for (end=0; szFilename[end]; end++) {} - pos = end; - while ((pos > 0) && (szFilename[pos-1] != '.') && (szFilename[pos-1] != DirectorySeparator)) --pos; - if ((pos > 0) && szFilename[pos-1] == '.') return szFilename + pos; - return szFilename + end; - } + { + int pos, end; + for (end=0; szFilename[end]; end++) {} + pos = end; + while ((pos > 0) && (szFilename[pos-1] != '.') && (szFilename[pos-1] != DirectorySeparator)) --pos; + if ((pos > 0) && szFilename[pos-1] == '.') return szFilename + pos; + return szFilename + end; + } const char *GetExtension(const char *szFilename) - { - int pos, end; - for (end=0; szFilename[end]; end++) {} - pos = end; - while ((pos>0) && (szFilename[pos-1] != '.') && (szFilename[pos-1] != DirectorySeparator)) pos--; - if (szFilename[pos-1] == '.') return szFilename+pos; - return szFilename+end; - } + { + int pos, end; + for (end=0; szFilename[end]; end++) {} + pos = end; + while ((pos>0) && (szFilename[pos-1] != '.') && (szFilename[pos-1] != DirectorySeparator)) pos--; + if (szFilename[pos-1] == '.') return szFilename+pos; + return szFilename+end; + } void RealPath(const char *szFilename, char *pFullFilename) @@ -155,14 +155,14 @@ void RealPath(const char *szFilename, char *pFullFilename) #ifdef _WIN32 _fullpath(pFullFilename, szFilename, _MAX_PATH); #else - char *pSuffix = NULL; + char *pSuffix = NULL; char szCopy[_MAX_PATH + 1]; - for(;;) + for(;;) { // Try to convert to full filename. Note this might fail if the given file doesn't exist if(realpath(szFilename, pFullFilename)) break; - // ... which is undesired behaviour here. Try to reduce the filename until it works. + // ... which is undesired behaviour here. Try to reduce the filename until it works. if(!pSuffix) { SCopy(szFilename, szCopy, _MAX_PATH); @@ -271,59 +271,59 @@ bool TruncatePath(char *szPath) { // Append terminating backslash if not present. void AppendBackslash(char *szFilename) - { - int i=SLen(szFilename); - if (i>0) if ((szFilename[i-1]==DirectorySeparator)) return; - SAppendChar(DirectorySeparator,szFilename); - } + { + int i=SLen(szFilename); + if (i>0) if ((szFilename[i-1]==DirectorySeparator)) return; + SAppendChar(DirectorySeparator,szFilename); + } // Remove terminating backslash if present. void TruncateBackslash(char *szFilename) { - int i=SLen(szFilename); - if (i>0) if ((szFilename[i-1]==DirectorySeparator)) szFilename[i-1]=0; + int i=SLen(szFilename); + if (i>0) if ((szFilename[i-1]==DirectorySeparator)) szFilename[i-1]=0; } // Append extension if no extension. void DefaultExtension(char *szFilename, const char *szExtension) - { - if (!(*GetExtension(szFilename))) - { SAppend(".",szFilename); SAppend(szExtension,szFilename); } - } + { + if (!(*GetExtension(szFilename))) + { SAppend(".",szFilename); SAppend(szExtension,szFilename); } + } void DefaultExtension(StdStrBuf *sFilename, const char *szExtension) - { + { assert(sFilename); - if (!(*GetExtension(sFilename->getData()))) - { sFilename->AppendChar('.'); sFilename->Append(szExtension); } - } + if (!(*GetExtension(sFilename->getData()))) + { sFilename->AppendChar('.'); sFilename->Append(szExtension); } + } // Append or overwrite extension. void EnforceExtension(char *szFilename, const char *szExtension) - { + { char *ext = GetExtension(szFilename); - if (ext[0]) { SCopy(szExtension,ext); } + if (ext[0]) { SCopy(szExtension,ext); } else { SAppend(".",szFilename); SAppend(szExtension,szFilename); } - } + } void EnforceExtension(StdStrBuf *sFilename, const char *szExtension) - { + { assert(sFilename); const char *ext = GetExtension(sFilename->getData()); - if (ext[0]) { sFilename->ReplaceEnd(ext - sFilename->getData(), szExtension); } + if (ext[0]) { sFilename->ReplaceEnd(ext - sFilename->getData(), szExtension); } else { sFilename->AppendChar('.'); sFilename->Append(szExtension); } - } + } // remove extension void RemoveExtension(char *szFilename) - { + { char *ext = GetExtension(szFilename); - if (ext[0]) ext[-1]=0; - } + if (ext[0]) ext[-1]=0; + } void RemoveExtension(StdStrBuf *psFileName) { @@ -337,35 +337,35 @@ void RemoveExtension(StdStrBuf *psFileName) // Enforce indexed extension until item does not exist. void MakeTempFilename(char *szFilename) - { - DefaultExtension(szFilename,"tmp"); - char *fn_ext=GetExtension(szFilename); - int cnum=-1; - do - { - cnum++; - osprintf(fn_ext,"%03d",cnum); - } - while (FileExists(szFilename) && (cnum<999)); - } + { + DefaultExtension(szFilename,"tmp"); + char *fn_ext=GetExtension(szFilename); + int cnum=-1; + do + { + cnum++; + osprintf(fn_ext,"%03d",cnum); + } + while (FileExists(szFilename) && (cnum<999)); + } void MakeTempFilename(StdStrBuf *sFilename) { assert(sFilename); if (!sFilename->getLength()) sFilename->Copy("temp.tmp"); EnforceExtension(sFilename, "tmp"); - char *fn_ext=GetExtension(sFilename->getMData()); - int cnum=-1; - do - { - cnum++; - osprintf(fn_ext,"%03d",cnum); - } - while (FileExists(sFilename->getData()) && (cnum<999)); + char *fn_ext=GetExtension(sFilename->getMData()); + int cnum=-1; + do + { + cnum++; + osprintf(fn_ext,"%03d",cnum); + } + while (FileExists(sFilename->getData()) && (cnum<999)); } bool WildcardListMatch(const char *szWildcardList, const char *szString) - { + { // safety if(!szString || !szWildcardList) return false; // match any item in list @@ -377,7 +377,7 @@ bool WildcardListMatch(const char *szWildcardList, const char *szString) } // none matched return false; - } + } bool IsWildcardString(const char *szString) { @@ -388,31 +388,31 @@ bool IsWildcardString(const char *szString) } bool WildcardMatch(const char *szWildcard, const char *szString) - { + { // safety if(!szString || !szWildcard) return false; - // match char-wise - const char *pWild = szWildcard, *pPos = szString; - const char *pLWild = NULL, *pLPos = NULL; // backtracking - while(*pWild || pLWild) - // string wildcard? - if(*pWild == '*') - { pLWild = ++pWild; pLPos = pPos; } - // nothing left to match? - else if(!*pPos) - break; - // equal or one-character-wildcard? proceed - else if(*pWild == '?' || tolower(*pWild) == tolower(*pPos)) - { pWild++; pPos++; } - // backtrack possible? - else if(pLPos) - { pWild = pLWild; pPos = ++pLPos; } - // match failed - else - return false; - // match complete if both strings are fully matched - return !*pWild && !*pPos; - } + // match char-wise + const char *pWild = szWildcard, *pPos = szString; + const char *pLWild = NULL, *pLPos = NULL; // backtracking + while(*pWild || pLWild) + // string wildcard? + if(*pWild == '*') + { pLWild = ++pWild; pLPos = pPos; } + // nothing left to match? + else if(!*pPos) + break; + // equal or one-character-wildcard? proceed + else if(*pWild == '?' || tolower(*pWild) == tolower(*pPos)) + { pWild++; pPos++; } + // backtrack possible? + else if(pLPos) + { pWild = pLWild; pPos = ++pLPos; } + // match failed + else + return false; + // match complete if both strings are fully matched + return !*pWild && !*pPos; + } #define SStripChars "!\"§%&/=?+*#:;<>\\." // create a valid file name from some title @@ -473,7 +473,7 @@ int FileTime(const char *szFilename) } bool EraseFile(const char *szFilename) - { + { //chmod(szFilename,200); #ifdef _WIN32 SetFileAttributes(szFilename, FILE_ATTRIBUTE_NORMAL); @@ -565,19 +565,19 @@ bool MakeOriginalFilename(char *szFilename) /* Directories */ const char *GetWorkingDirectory() - { - static char buf[_MAX_PATH+1]; - return getcwd(buf,_MAX_PATH); - } + { + static char buf[_MAX_PATH+1]; + return getcwd(buf,_MAX_PATH); + } bool SetWorkingDirectory(const char *path) - { + { #ifdef _WIN32 - return SetCurrentDirectory(path) != 0; + return SetCurrentDirectory(path) != 0; #else - return (chdir(path)==0); + return (chdir(path)==0); #endif - } + } bool CreatePath(const std::string &path) { @@ -755,26 +755,26 @@ bool RenameItem(const char *szItemName, const char *szNewItemName) } bool EraseItem(const char *szItemName) - { - if (!EraseFile(szItemName)) return EraseDirectory(szItemName); - else return true; - } + { + if (!EraseFile(szItemName)) return EraseDirectory(szItemName); + else return true; + } bool CreateItem(const char *szItemname) - { + { // Overwrite any old item EraseItem(szItemname); // Create dummy item - FILE *fhnd; - if (!(fhnd=fopen(szItemname,"wb"))) return false; - fclose(fhnd); + FILE *fhnd; + if (!(fhnd=fopen(szItemname,"wb"))) return false; + fclose(fhnd); // Success return true; - } + } #ifdef _WIN32 bool EraseItems(const char *szItemPath) { - return ForEachFile(szItemPath,&EraseItem) > 0; + return ForEachFile(szItemPath,&EraseItem) > 0; } #endif bool CopyItem(const char *szSource, const char *szTarget, bool fResetAttributes) diff --git a/src/platform/StdFont.cpp b/src/platform/StdFont.cpp index 225a4f3b3..57784b3ae 100644 --- a/src/platform/StdFont.cpp +++ b/src/platform/StdFont.cpp @@ -493,9 +493,9 @@ void CStdFont::Init(CStdVectorFont & VectorFont, const char *font_face_name, DWO } const DWORD FontDelimeterColor = 0xff0000, - FontDelimiterColorLB = 0x00ff00, - FontDelimeterColorIndent1 = 0xffff00, - FontDelimeterColorIndent2 = 0xff00ff; + FontDelimiterColorLB = 0x00ff00, + FontDelimeterColorIndent1 = 0xffff00, + FontDelimeterColorIndent2 = 0xff00ff; // perform color matching in 16 bit inline bool ColorMatch(DWORD dwClr1, DWORD dwClr2) @@ -570,7 +570,7 @@ void CStdFont::Init(const char *szFontName, CSurface *psfcFontSfc, int iIndent) break; } } - } + } // release texture data sfcCurrent->Unlock(); // adjust line height @@ -741,7 +741,7 @@ int CStdFont::BreakMessage(const char *szMsg, int iWdt, char *szOut, int iMaxOut { // image renderer not hooked or ID not found, or surface not present: just ignore it // printing it out wouldn't look better... - iCharWdt = 0; + iCharWdt = 0; } // skip image tag szPos+=iImgLgt+3; @@ -750,11 +750,11 @@ int CStdFont::BreakMessage(const char *szMsg, int iWdt, char *szOut, int iMaxOut { // regular char // look up character width in texture coordinates table - if (c >= ' ') + if (c >= ' ') iCharWdt = int(fZoom * GetCharacterFacet(c).Wdt / iFontZoom) + iHSpace; else - iCharWdt = 0; // OMFG ctrl char - } + iCharWdt = 0; // OMFG ctrl char + } // add chars to output while (szLastPos != szPos) { @@ -897,7 +897,7 @@ int CStdFont::BreakMessage(const char *szMsg, int iWdt, StdStrBuf *pOut, bool fC { // image renderer not hooked or ID not found, or surface not present: just ignore it // printing it out wouldn't look better... - iCharWdt = 0; + iCharWdt = 0; } // skip image tag szPos+=iImgLgt+3; @@ -906,11 +906,11 @@ int CStdFont::BreakMessage(const char *szMsg, int iWdt, StdStrBuf *pOut, bool fC { // regular char // look up character width in texture coordinates table - if (c >= ' ') + if (c >= ' ') iCharWdt = int(fZoom * GetCharacterFacet(c).Wdt / iFontZoom) + iHSpace; else - iCharWdt = 0; // OMFG ctrl char - } + iCharWdt = 0; // OMFG ctrl char + } // add chars to output pOut->Append(szLastPos, szPos - szLastPos); // add to line; always add one char at minimum @@ -1067,8 +1067,8 @@ void CStdFont::DrawText(SURFACE sfcDest, float iX, float iY, DWORD dwColor, cons } // apply texture zoom fZoom /= iFontZoom; - // set start markup transformation - if (!Markup.Clean()) pbt=&bt; + // set start markup transformation + if (!Markup.Clean()) pbt=&bt; // output text uint32_t c; CFacet fctFromBlt; // source facet @@ -1152,7 +1152,7 @@ void CStdFont::DrawText(SURFACE sfcDest, float iX, float iY, DWORD dwColor, cons true, pbt); // advance pos and skip character indent iX+=w2+iHSpace; - } + } // reset blit modulation if (fWasModulated) lpDDraw->ActivateBlitModulation(dwOldModClr); diff --git a/src/platform/StdFont.h b/src/platform/StdFont.h index 874d43817..ba183c204 100644 --- a/src/platform/StdFont.h +++ b/src/platform/StdFont.h @@ -70,7 +70,7 @@ class CStdFont protected: DWORD dwDefFontHeight; // configured font size (in points) - char szFontName[80+1]; // used font name (or surface file name) + char szFontName[80+1]; // used font name (or surface file name) bool fPrerenderedFont; // true for fonts that came from a prerendered bitmap surface - no runtime adding of characters CSurface **psfcFontData; // font recource surfaces - additional surfaces created as needed @@ -119,8 +119,8 @@ class CStdFont public: int iLineHgt; // height of one line of font (in pixels) - // draw ine line of text - void DrawText(SURFACE sfcDest, float iX, float iY, DWORD dwColor, const char *szText, DWORD dwFlags, CMarkup &Markup, float fZoom); + // draw ine line of text + void DrawText(SURFACE sfcDest, float iX, float iY, DWORD dwColor, const char *szText, DWORD dwFlags, CMarkup &Markup, float fZoom); // get text size bool GetTextExtent(const char *szText, int32_t &rsx, int32_t &rsy, bool fCheckMarkup = true); diff --git a/src/platform/StdGL.cpp b/src/platform/StdGL.cpp index 1294befbb..77d867b02 100644 --- a/src/platform/StdGL.cpp +++ b/src/platform/StdGL.cpp @@ -1266,7 +1266,7 @@ void CStdGL::PerformMesh(StdMeshInstance &instance, float tx, float ty, float tw } void CStdGL::BlitLandscape(SURFACE sfcSource, float fx, float fy, - SURFACE sfcTarget, float tx, float ty, float wdt, float hgt, const SURFACE mattextures[]) + SURFACE sfcTarget, float tx, float ty, float wdt, float hgt, const SURFACE mattextures[]) { //Blit(sfcSource, fx, fy, wdt, hgt, sfcTarget, tx, ty, wdt, hgt);return; // safety @@ -1648,7 +1648,7 @@ void CStdGL::PerformLine(SURFACE sfcTarget, float x1, float y1, float x2, float } void CStdGL::PerformPix(SURFACE sfcTarget, float tx, float ty, DWORD dwClr) - { + { // render target? if (sfcTarget->IsRenderTarget()) { @@ -1667,7 +1667,7 @@ void CStdGL::PerformPix(SURFACE sfcTarget, float tx, float ty, DWORD dwClr) // emulate sfcTarget->SetPixDw((int)tx, (int)ty, dwClr); } - } + } static void DefineShaderARB(const char * p, GLuint & s) { diff --git a/src/platform/StdGLCtx.cpp b/src/platform/StdGLCtx.cpp index 89682f4db..c4528f0d2 100644 --- a/src/platform/StdGLCtx.cpp +++ b/src/platform/StdGLCtx.cpp @@ -347,10 +347,10 @@ bool CStdGLCtx::Select(bool verbose) void CStdGLCtx::Deselect() { if (pGL && pGL->pCurrCtx == this) - { + { pGL->pCurrCtx = 0; pGL->RenderTarget = 0; - } + } } bool CStdGLCtx::PageFlip() diff --git a/src/platform/StdGtkWindow.cpp b/src/platform/StdGtkWindow.cpp index b856e28ce..8885a20fc 100644 --- a/src/platform/StdGtkWindow.cpp +++ b/src/platform/StdGtkWindow.cpp @@ -47,12 +47,12 @@ CStdWindow* CStdGtkWindow::Init(CStdApp * pApp, const char * Title, CStdWindow * if(!FindInfo()) return 0; - assert(!window); + assert(!window); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // Override gtk's default to match name/class of the XLib windows - gtk_window_set_wmclass(GTK_WINDOW(window), C4ENGINENAME, C4ENGINENAME); + gtk_window_set_wmclass(GTK_WINDOW(window), C4ENGINENAME, C4ENGINENAME); handlerDestroy = g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(OnDestroyStatic), this); g_signal_connect(G_OBJECT(window), "key-press-event", G_CALLBACK(OnUpdateKeyMask), pApp); diff --git a/src/platform/StdMesh.cpp b/src/platform/StdMesh.cpp index f04449a58..d36291188 100644 --- a/src/platform/StdMesh.cpp +++ b/src/platform/StdMesh.cpp @@ -500,7 +500,7 @@ StdMeshQuaternion operator*(const StdMeshQuaternion& lhs, float rhs) StdMeshQuaternion operator*(float lhs, const StdMeshQuaternion& rhs) { - return rhs * lhs; + return rhs * lhs; } StdMeshQuaternion& operator+=(StdMeshQuaternion& lhs, const StdMeshQuaternion& rhs) @@ -890,7 +890,7 @@ bool StdMeshInstance::AnimationNode::GetBoneTransform(unsigned int bone, StdMesh } StdMeshInstance::AttachedMesh::AttachedMesh(unsigned int number, StdMeshInstance* parent, StdMeshInstance* child, bool own_child, - unsigned int parent_bone, unsigned int child_bone, const StdMeshMatrix& transform): + unsigned int parent_bone, unsigned int child_bone, const StdMeshMatrix& transform): Number(number), Parent(parent), Child(child), OwnChild(own_child), ParentBone(parent_bone), ChildBone(child_bone), AttachTrans(transform), FinalTransformDirty(true) diff --git a/src/platform/StdRegistry.cpp b/src/platform/StdRegistry.cpp index e06571be5..52dcf272c 100644 --- a/src/platform/StdRegistry.cpp +++ b/src/platform/StdRegistry.cpp @@ -34,21 +34,21 @@ bool DeleteRegistryValue(const char *szSubKey, const char *szValueName) bool DeleteRegistryValue(HKEY hKey, const char *szSubKey, const char *szValueName) { - long qerr; - HKEY ckey; - // Open the key - if ((qerr=RegOpenKeyEx(hKey, - szSubKey, - 0, - KEY_ALL_ACCESS, - &ckey - ))!=ERROR_SUCCESS) return false; + long qerr; + HKEY ckey; + // Open the key + if ((qerr=RegOpenKeyEx(hKey, + szSubKey, + 0, + KEY_ALL_ACCESS, + &ckey + ))!=ERROR_SUCCESS) return false; // Delete the key - if ((qerr=RegDeleteValue(ckey, + if ((qerr=RegDeleteValue(ckey, szValueName ))!=ERROR_SUCCESS) return false; - // Close the key - RegCloseKey(ckey); + // Close the key + RegCloseKey(ckey); // Success return true; } @@ -64,152 +64,152 @@ bool GetRegistryDWord(const char *szSubKey, const char *szValueName, DWORD *lpdw } bool GetRegistryDWord(HKEY hKey, const char *szSubKey, const char *szValueName, DWORD *lpdwValue) - { - long qerr; - HKEY ckey; - DWORD valtype; - DWORD valsize=sizeof(DWORD); + { + long qerr; + HKEY ckey; + DWORD valtype; + DWORD valsize=sizeof(DWORD); - // Open the key - if ((qerr=RegOpenKeyEx(hKey, - szSubKey, - 0, - KEY_READ, - &ckey - ))!=ERROR_SUCCESS) return false; + // Open the key + if ((qerr=RegOpenKeyEx(hKey, + szSubKey, + 0, + KEY_READ, + &ckey + ))!=ERROR_SUCCESS) return false; - // Get the value - if ((qerr=RegQueryValueEx(ckey, - szValueName, - NULL, - &valtype, - (BYTE*) lpdwValue, - &valsize - ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } + // Get the value + if ((qerr=RegQueryValueEx(ckey, + szValueName, + NULL, + &valtype, + (BYTE*) lpdwValue, + &valsize + ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } - // Close the key - RegCloseKey(ckey); + // Close the key + RegCloseKey(ckey); - if (valtype!=REG_DWORD) return false; + if (valtype!=REG_DWORD) return false; - return true; - } + return true; + } bool SetRegistryDWord(HKEY hKey, const char *szSubKey, const char *szValueName, DWORD dwValue) - { - long qerr; - HKEY ckey; - DWORD disposition; - // Open the key - if ((qerr=RegCreateKeyEx(hKey, - szSubKey, - 0, - "", - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, - NULL, - &ckey, - &disposition - ))!=ERROR_SUCCESS) return false; - // Set the value - if ((qerr=RegSetValueEx(ckey, - szValueName, - 0, - REG_DWORD, - (BYTE*) &dwValue, - sizeof(dwValue) - ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } + { + long qerr; + HKEY ckey; + DWORD disposition; + // Open the key + if ((qerr=RegCreateKeyEx(hKey, + szSubKey, + 0, + "", + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + NULL, + &ckey, + &disposition + ))!=ERROR_SUCCESS) return false; + // Set the value + if ((qerr=RegSetValueEx(ckey, + szValueName, + 0, + REG_DWORD, + (BYTE*) &dwValue, + sizeof(dwValue) + ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } - // Close the key - RegCloseKey(ckey); + // Close the key + RegCloseKey(ckey); // Success return true; - } + } bool GetRegistryString(const char *szSubKey, - const char *szValueName, - char *sValue, DWORD dwValSize) - { - long qerr; - HKEY ckey; - DWORD valtype; + const char *szValueName, + char *sValue, DWORD dwValSize) + { + long qerr; + HKEY ckey; + DWORD valtype; - // Open the key - if ((qerr=RegOpenKeyEx(HKEY_CURRENT_USER, - szSubKey, - 0, - KEY_READ, - &ckey - ))!=ERROR_SUCCESS) return false; + // Open the key + if ((qerr=RegOpenKeyEx(HKEY_CURRENT_USER, + szSubKey, + 0, + KEY_READ, + &ckey + ))!=ERROR_SUCCESS) return false; - // Get the value - if ((qerr=RegQueryValueEx(ckey, - szValueName, - NULL, - &valtype, - (BYTE*) sValue, - &dwValSize - ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } + // Get the value + if ((qerr=RegQueryValueEx(ckey, + szValueName, + NULL, + &valtype, + (BYTE*) sValue, + &dwValSize + ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } - // Close the key - RegCloseKey(ckey); + // Close the key + RegCloseKey(ckey); - if (valtype!=REG_SZ) return false; + if (valtype!=REG_SZ) return false; - return true; - } + return true; + } bool SetRegistryString(const char *szSubKey, - const char *szValueName, - const char *szValue) - { + const char *szValueName, + const char *szValue) + { - long qerr; - HKEY ckey; - DWORD disposition; + long qerr; + HKEY ckey; + DWORD disposition; - // Open the key - if ((qerr=RegCreateKeyEx(HKEY_CURRENT_USER, - szSubKey, - 0, - "", - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, - NULL, - &ckey, - &disposition - ))!=ERROR_SUCCESS) return false; + // Open the key + if ((qerr=RegCreateKeyEx(HKEY_CURRENT_USER, + szSubKey, + 0, + "", + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + NULL, + &ckey, + &disposition + ))!=ERROR_SUCCESS) return false; - // Set the value - if ((qerr=RegSetValueEx(ckey, - szValueName, - 0, - REG_SZ, - (BYTE*) szValue, - SLen(szValue)+1 - ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } + // Set the value + if ((qerr=RegSetValueEx(ckey, + szValueName, + 0, + REG_SZ, + (BYTE*) szValue, + SLen(szValue)+1 + ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } - // Close the key - RegCloseKey(ckey); + // Close the key + RegCloseKey(ckey); - return true; - } + return true; + } bool DeleteRegistryKey(HKEY hKey, const char *szSubKey) { - HKEY ckey; - // Open the key - if (RegOpenKeyEx(hKey, szSubKey, 0, KEY_ALL_ACCESS, &ckey) != ERROR_SUCCESS) return false; + HKEY ckey; + // Open the key + if (RegOpenKeyEx(hKey, szSubKey, 0, KEY_ALL_ACCESS, &ckey) != ERROR_SUCCESS) return false; // Delete all subkeys char strChild[1024 + 1]; while (RegEnumKey(ckey, 0, strChild, 1024) == ERROR_SUCCESS) if (!DeleteRegistryKey(ckey, strChild)) return false; - // Close the key - RegCloseKey(ckey); + // Close the key + RegCloseKey(ckey); // Delete the key - if (RegDeleteKey(hKey, szSubKey) != ERROR_SUCCESS) return false; + if (RegDeleteKey(hKey, szSubKey) != ERROR_SUCCESS) return false; // Success return true; } @@ -220,131 +220,131 @@ bool DeleteRegistryKey(const char *szSubKey) } bool SetRegClassesRoot(const char *szSubKey, - const char *szValueName, - const char *szStringValue) - { + const char *szValueName, + const char *szStringValue) + { - long qerr; - HKEY ckey; - DWORD disposition; + long qerr; + HKEY ckey; + DWORD disposition; - // Open the key - if ((qerr=RegCreateKeyEx(HKEY_CLASSES_ROOT, - szSubKey, - 0, - "", - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, - NULL, - &ckey, - &disposition - ))!=ERROR_SUCCESS) return false; + // Open the key + if ((qerr=RegCreateKeyEx(HKEY_CLASSES_ROOT, + szSubKey, + 0, + "", + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + NULL, + &ckey, + &disposition + ))!=ERROR_SUCCESS) return false; - // Set the value - if ((qerr=RegSetValueEx(ckey, - szValueName, - 0, - REG_SZ, - (BYTE*) szStringValue, - SLen(szStringValue)+1 - ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } + // Set the value + if ((qerr=RegSetValueEx(ckey, + szValueName, + 0, + REG_SZ, + (BYTE*) szStringValue, + SLen(szStringValue)+1 + ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } - // Close the key - RegCloseKey(ckey); + // Close the key + RegCloseKey(ckey); - return true; - } + return true; + } bool SetRegClassesRootString(const char *szSubKey, const char *szValueName, const char *szValue) - { + { - long qerr; - HKEY ckey; - DWORD disposition; + long qerr; + HKEY ckey; + DWORD disposition; - // Open the key - if ((qerr=RegCreateKeyEx(HKEY_CLASSES_ROOT, - szSubKey, - 0, - "", - REG_OPTION_NON_VOLATILE, - KEY_ALL_ACCESS, - NULL, - &ckey, - &disposition - ))!=ERROR_SUCCESS) return false; + // Open the key + if ((qerr=RegCreateKeyEx(HKEY_CLASSES_ROOT, + szSubKey, + 0, + "", + REG_OPTION_NON_VOLATILE, + KEY_ALL_ACCESS, + NULL, + &ckey, + &disposition + ))!=ERROR_SUCCESS) return false; - // Set the value - if ((qerr=RegSetValueEx(ckey, - szValueName, - 0, - REG_SZ, - (BYTE*) szValue, - SLen(szValue)+1 - ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } + // Set the value + if ((qerr=RegSetValueEx(ckey, + szValueName, + 0, + REG_SZ, + (BYTE*) szValue, + SLen(szValue)+1 + ))!=ERROR_SUCCESS) { RegCloseKey(ckey); return false; } - // Close the key - RegCloseKey(ckey); + // Close the key + RegCloseKey(ckey); - return true; - } + return true; + } bool SetRegShell(const char *szClassName, - const char *szShellName, - const char *szShellCaption, - const char *szCommand, + const char *szShellName, + const char *szShellCaption, + const char *szCommand, bool fMakeDefault) - { - char szKeyName[256+1]; - // Set shell caption - sprintf(szKeyName,"%s\\Shell\\%s",szClassName,szShellName); - if (!SetRegClassesRoot(szKeyName, NULL, szShellCaption)) return false; - // Set shell command - sprintf(szKeyName,"%s\\Shell\\%s\\Command",szClassName,szShellName); - if (!SetRegClassesRoot(szKeyName, NULL, szCommand)) return false; + { + char szKeyName[256+1]; + // Set shell caption + sprintf(szKeyName,"%s\\Shell\\%s",szClassName,szShellName); + if (!SetRegClassesRoot(szKeyName, NULL, szShellCaption)) return false; + // Set shell command + sprintf(szKeyName,"%s\\Shell\\%s\\Command",szClassName,szShellName); + if (!SetRegClassesRoot(szKeyName, NULL, szCommand)) return false; // Set as default command if (fMakeDefault) { sprintf(szKeyName, "%s\\Shell", szClassName); if (!SetRegClassesRoot(szKeyName, NULL, szShellName)) return false; } - return true; - } + return true; + } bool RemoveRegShell(const char *szClassName, const char *szShellName) - { - char strKey[256+1]; - sprintf(strKey, "%s\\Shell\\%s", szClassName, szShellName); - if (!DeleteRegistryKey(HKEY_CLASSES_ROOT, strKey)) return false; - return true; - } + { + char strKey[256+1]; + sprintf(strKey, "%s\\Shell\\%s", szClassName, szShellName); + if (!DeleteRegistryKey(HKEY_CLASSES_ROOT, strKey)) return false; + return true; + } bool SetRegFileClass(const char *szClassRoot, - const char *szExtension, - const char *szClassName, - const char *szIconPath, int iIconNum, + const char *szExtension, + const char *szClassName, + const char *szIconPath, int iIconNum, const char *szContentType) - { - char keyname[100]; - char iconpath[512]; + { + char keyname[100]; + char iconpath[512]; // Create root class entry - if (!SetRegClassesRoot(szClassRoot,NULL,szClassName)) return false; + if (!SetRegClassesRoot(szClassRoot,NULL,szClassName)) return false; // Set root class icon - sprintf(keyname,"%s\\DefaultIcon",szClassRoot); - sprintf(iconpath,"%s,%d",szIconPath,iIconNum); - if (!SetRegClassesRoot(keyname,NULL,iconpath)) return false; + sprintf(keyname,"%s\\DefaultIcon",szClassRoot); + sprintf(iconpath,"%s,%d",szIconPath,iIconNum); + if (!SetRegClassesRoot(keyname,NULL,iconpath)) return false; // Set extension map entry - sprintf(keyname,".%s",szExtension); - if (!SetRegClassesRoot(keyname,NULL,szClassRoot)) return false; + sprintf(keyname,".%s",szExtension); + if (!SetRegClassesRoot(keyname,NULL,szClassRoot)) return false; // Set extension content type - sprintf(keyname,".%s",szExtension); + sprintf(keyname,".%s",szExtension); if (!SetRegClassesRootString(keyname,"Content Type",szContentType)) return false; // Success - return true; - } + return true; + } //------------------------------ Window Position ------------------------------------------ @@ -532,18 +532,18 @@ void StdCompilerConfigWrite::CreateKey(HKEY hParent) if(pKey->Handle) return; // Open/Create registry key - if(RegCreateKeyEx(hParent ? hParent : pKey->Parent->Handle, + if(RegCreateKeyEx(hParent ? hParent : pKey->Parent->Handle, pKey->Name.getData(), 0, "", REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, - &pKey->Handle, NULL) != ERROR_SUCCESS) + &pKey->Handle, NULL) != ERROR_SUCCESS) excCorrupt(0, FormatString("Could not create key %s!", pKey->Name.getData())); } void StdCompilerConfigWrite::WriteDWord(uint32_t iVal) { - // Set the value - if(RegSetValueEx(pKey->Parent->Handle, pKey->Name.getData(), + // Set the value + if(RegSetValueEx(pKey->Parent->Handle, pKey->Name.getData(), 0, REG_DWORD, reinterpret_cast(&iVal), sizeof(iVal)) != ERROR_SUCCESS) excCorrupt(0, FormatString("Could not write key %s!", pKey->Name.getData())); @@ -551,8 +551,8 @@ void StdCompilerConfigWrite::WriteDWord(uint32_t iVal) void StdCompilerConfigWrite::WriteString(const char *szString) { - // Set the value - if(RegSetValueEx(pKey->Parent->Handle, pKey->Name.getData(), + // Set the value + if(RegSetValueEx(pKey->Parent->Handle, pKey->Name.getData(), 0, REG_SZ, reinterpret_cast(szString), strlen(szString) + 1) != ERROR_SUCCESS) excCorrupt(0, FormatString("Could not write key %s!", pKey->Name.getData())); @@ -566,7 +566,7 @@ StdCompilerConfigRead::StdCompilerConfigRead(HKEY hRoot, const char *szPath) pKey->Name = szPath; pKey->Virtual = false; // Open root - if(RegOpenKeyEx(hRoot, szPath, + if(RegOpenKeyEx(hRoot, szPath, 0, KEY_READ, &pKey->Handle) != ERROR_SUCCESS) pKey->Handle = 0; @@ -584,7 +584,7 @@ bool StdCompilerConfigRead::Name(const char *szName) bool fFound = true; // Try to open registry key HKEY hSubKey; DWORD dwType = 0; - if(RegOpenKeyEx(pKey->Handle, szName, + if(RegOpenKeyEx(pKey->Handle, szName, 0, KEY_READ, &hSubKey) != ERROR_SUCCESS) { @@ -717,9 +717,9 @@ uint32_t StdCompilerConfigRead::ReadDWord() // Wrong type? if(pKey->Type != REG_DWORD && pKey->Type != REG_DWORD_LITTLE_ENDIAN) { excNotFound("Wrong value type!"); return 0; } - // Read + // Read uint32_t iVal; DWORD iSize = sizeof(iVal); - if(RegQueryValueEx(pKey->Parent->Handle, pKey->Name.getData(), + if(RegQueryValueEx(pKey->Parent->Handle, pKey->Name.getData(), 0, NULL, reinterpret_cast(&iVal), &iSize) != ERROR_SUCCESS) @@ -739,17 +739,17 @@ StdStrBuf StdCompilerConfigRead::ReadString() // Wrong type? if(pKey->Type != REG_SZ) { excNotFound("Wrong value type!"); return StdStrBuf(); } - // Get size of string + // Get size of string DWORD iSize; - if(RegQueryValueEx(pKey->Parent->Handle, pKey->Name.getData(), + if(RegQueryValueEx(pKey->Parent->Handle, pKey->Name.getData(), 0, NULL, NULL, &iSize) != ERROR_SUCCESS) { excNotFound("Could not read value %s!", pKey->Name.getData()); return StdStrBuf(); } - // Allocate string + // Allocate string StdStrBuf Result; Result.SetLength(iSize - 1); // Read - if(RegQueryValueEx(pKey->Parent->Handle, pKey->Name.getData(), + if(RegQueryValueEx(pKey->Parent->Handle, pKey->Name.getData(), 0, NULL, reinterpret_cast(Result.getMData()), &iSize) != ERROR_SUCCESS) diff --git a/src/platform/StdRegistry.h b/src/platform/StdRegistry.h index 392c2a269..89173b22b 100644 --- a/src/platform/StdRegistry.h +++ b/src/platform/StdRegistry.h @@ -31,12 +31,12 @@ bool DeleteRegistryValue(HKEY hKey, const char *szSubKey, bool DeleteRegistryValue(const char *szSubKey, const char *szValueName); bool GetRegistryDWord(HKEY hKey, const char *szSubKey, - const char *szValueName, DWORD *lpdwValue); + const char *szValueName, DWORD *lpdwValue); bool GetRegistryDWord(const char *szSubKey, const char *szValueName, DWORD *lpdwValue); bool SetRegistryDWord(HKEY hKey, const char *szSubKey, - const char *szValueName, DWORD dwValue); + const char *szValueName, DWORD dwValue); bool SetRegistryDWord(const char *szSubKey, const char *szValueName, DWORD dwValue); @@ -47,22 +47,22 @@ bool DeleteRegistryKey(HKEY hKey, const char *szSubKey); bool DeleteRegistryKey(const char *szSubKey); bool SetRegClassesRoot(const char *szSubKey, - const char *szValueName, - const char *szStringValue); + const char *szValueName, + const char *szStringValue); bool SetRegShell(const char *szClassName, - const char *szShellName, - const char *szShellCaption, - const char *szCommand, + const char *szShellName, + const char *szShellCaption, + const char *szCommand, bool fMakeDefault = false); bool RemoveRegShell(const char *szClassName, const char *szShellName); bool SetRegFileClass(const char *szClassRoot, - const char *szExtension, - const char *szClassName, - const char *szIconPath, int iIconNum, + const char *szExtension, + const char *szClassName, + const char *szIconPath, int iIconNum, const char *szContentType); bool StoreWindowPosition(HWND hwnd, @@ -84,35 +84,35 @@ public: StdCompilerConfigWrite(HKEY hRoot, const char *szPath); ~StdCompilerConfigWrite(); - // Properties - virtual bool hasNaming() { return true; } + // Properties + virtual bool hasNaming() { return true; } virtual bool forceWrite() { return true; } - // Naming - virtual bool Name(const char *szName); - virtual void NameEnd(bool fBreak = false); - virtual bool FollowName(const char *szName); + // Naming + virtual bool Name(const char *szName); + virtual void NameEnd(bool fBreak = false); + virtual bool FollowName(const char *szName); virtual bool Default(const char *szName); - // Seperators - virtual bool Seperator(Sep eSep); + // Seperators + virtual bool Seperator(Sep eSep); - // Data writers - virtual void DWord(int32_t &rInt); - virtual void DWord(uint32_t &rInt); - virtual void Word(int16_t &rShort); - virtual void Word(uint16_t &rShort); - virtual void Byte(int8_t &rByte); - virtual void Byte(uint8_t &rByte); - virtual void Boolean(bool &rBool); - virtual void Character(char &rChar); - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); - virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); + // Data writers + virtual void DWord(int32_t &rInt); + virtual void DWord(uint32_t &rInt); + virtual void Word(int16_t &rShort); + virtual void Word(uint16_t &rShort); + virtual void Byte(int8_t &rByte); + virtual void Byte(uint8_t &rByte); + virtual void Boolean(bool &rBool); + virtual void Character(char &rChar); + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); + virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); - // Passes - virtual void Begin(); - virtual void End(); + // Passes + virtual void Begin(); + virtual void End(); private: @@ -140,34 +140,34 @@ public: StdCompilerConfigRead(HKEY hRoot, const char *szPath); ~StdCompilerConfigRead(); - // Properties + // Properties virtual bool isCompiler() { return true; } - virtual bool hasNaming() { return true; } + virtual bool hasNaming() { return true; } - // Naming - virtual bool Name(const char *szName); - virtual void NameEnd(bool fBreak = false); - virtual bool FollowName(const char *szName); + // Naming + virtual bool Name(const char *szName); + virtual void NameEnd(bool fBreak = false); + virtual bool FollowName(const char *szName); - // Seperators - virtual bool Seperator(Sep eSep); + // Seperators + virtual bool Seperator(Sep eSep); - // Data writers - virtual void DWord(int32_t &rInt); - virtual void DWord(uint32_t &rInt); - virtual void Word(int16_t &rShort); - virtual void Word(uint16_t &rShort); - virtual void Byte(int8_t &rByte); - virtual void Byte(uint8_t &rByte); - virtual void Boolean(bool &rBool); - virtual void Character(char &rChar); - virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); - virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); - virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); + // Data writers + virtual void DWord(int32_t &rInt); + virtual void DWord(uint32_t &rInt); + virtual void Word(int16_t &rShort); + virtual void Word(uint16_t &rShort); + virtual void Byte(int8_t &rByte); + virtual void Byte(uint8_t &rByte); + virtual void Boolean(bool &rBool); + virtual void Character(char &rChar); + virtual void String(char *szString, size_t iMaxLength, RawCompileType eType = RCT_Escaped); + virtual void String(char **pszString, RawCompileType eType = RCT_Escaped); + virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped); - // Passes - virtual void Begin(); - virtual void End(); + // Passes + virtual void Begin(); + virtual void End(); private: diff --git a/src/platform/StdSDLApp.cpp b/src/platform/StdSDLApp.cpp index 0505be301..cdc896bb7 100644 --- a/src/platform/StdSDLApp.cpp +++ b/src/platform/StdSDLApp.cpp @@ -67,7 +67,7 @@ bool CStdApp::Init(int argc, char * argv[]) { szCmdLine = s.c_str(); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) { - Log("Error initializing SDL."); + Log("Error initializing SDL."); return false; } @@ -105,7 +105,7 @@ bool CStdApp::FlushMessages() { } void CStdApp::HandleSDLEvent(SDL_Event& event) { - // Directly handle QUIT messages. + // Directly handle QUIT messages. switch (event.type) { case SDL_QUIT: Quit(); @@ -116,7 +116,7 @@ void CStdApp::HandleSDLEvent(SDL_Event& event) { MacUtility::ensureWindowInFront(); #endif - // Everything else goes to the window. + // Everything else goes to the window. if (pWindow) pWindow->HandleMessage(event); } diff --git a/src/platform/StdSDLWindow.cpp b/src/platform/StdSDLWindow.cpp index 9d2b7fb0b..2a6235e2a 100644 --- a/src/platform/StdSDLWindow.cpp +++ b/src/platform/StdSDLWindow.cpp @@ -49,7 +49,7 @@ CStdWindow * CStdWindow::Init(CStdApp * pApp) { CStdWindow * CStdWindow::Init(CStdApp * pApp, const char * Title, CStdWindow * pParent, bool HideCursor) { Active = true; - SetTitle(Title); + SetTitle(Title); return this; } diff --git a/src/platform/StdScheduler.cpp b/src/platform/StdScheduler.cpp index 476465d68..c8fac7b52 100644 --- a/src/platform/StdScheduler.cpp +++ b/src/platform/StdScheduler.cpp @@ -85,7 +85,7 @@ bool StdSchedulerProc::IsSignaled() return GetEvent() && WaitForSingleObject(GetEvent(), 0) == WAIT_OBJECT_0; #else // Initialize file descriptor sets - std::vector fds; + std::vector fds; // Get file descriptors GetFDs(fds); @@ -348,7 +348,7 @@ void StdSchedulerThread::Remove(StdSchedulerProc *pProc) bool fGotThread = fThread; if(fGotThread) Stop(); // Set - StdScheduler::Remove(pProc); + StdScheduler::Remove(pProc); // Restart if(fGotThread) Start(); } diff --git a/src/platform/StdSurface2.cpp b/src/platform/StdSurface2.cpp index 07db01f66..a4073d5d4 100644 --- a/src/platform/StdSurface2.cpp +++ b/src/platform/StdSurface2.cpp @@ -345,26 +345,26 @@ void CSurface::FreeTextures() bool ClrByOwner(DWORD &dwClr) // new style, based on Microsoft Knowledge Base Article - 29240 { - int H,L,S; - WORD R,G,B; - BYTE cMax,cMin; - WORD Rdelta,Gdelta,Bdelta; - // get RGB (from BGR...?) - R = GetBValue(dwClr); - G = GetGValue(dwClr); - B = GetRValue(dwClr); - // calculate lightness - cMax = Max(Max(R,G),B); - cMin = Min(Min(R,G),B); - L = ( ((cMax+cMin)*HLSMAX) + RGBMAX )/(2*RGBMAX); - // achromatic case - if (cMax == cMin) + int H,L,S; + WORD R,G,B; + BYTE cMax,cMin; + WORD Rdelta,Gdelta,Bdelta; + // get RGB (from BGR...?) + R = GetBValue(dwClr); + G = GetGValue(dwClr); + B = GetRValue(dwClr); + // calculate lightness + cMax = Max(Max(R,G),B); + cMin = Min(Min(R,G),B); + L = ( ((cMax+cMin)*HLSMAX) + RGBMAX )/(2*RGBMAX); + // achromatic case + if (cMax == cMin) { - S = 0; - H = (HLSMAX*2/3); - } + S = 0; + H = (HLSMAX*2/3); + } // chromatic case - else + else { // saturation if (L <= (HLSMAX/2)) @@ -386,7 +386,7 @@ bool ClrByOwner(DWORD &dwClr) // new style, based on Microsoft Knowledge Base Ar H += HLSMAX; if (H > HLSMAX) H -= HLSMAX; - } + } // Not blue if (!(Inside(H, 145, 175) && (S > 100))) return false; // It's blue: make it gray @@ -636,13 +636,13 @@ bool CSurface::ReadBMP(CStdStream &hGroup, bool fOwnPal) } // Close file - hFile.Close(); + hFile.Close(); // Unlock Unlock(); // Success - return true; + return true; } */ bool CSurface::SavePNG(const char *szFilename, bool fSaveAlpha, bool fApplyGamma, bool fSaveOverlayOnly) @@ -688,7 +688,7 @@ bool CSurface::SavePNG(const char *szFilename, bool fSaveAlpha, bool fApplyGamma Unlock(); // Success - return true; + return true; } diff --git a/src/platform/StdSurface2.h b/src/platform/StdSurface2.h index e50c8813d..8ce4f1a0c 100644 --- a/src/platform/StdSurface2.h +++ b/src/platform/StdSurface2.h @@ -208,8 +208,8 @@ typedef CSurface * SURFACE; #ifndef USE_DIRECTX typedef struct _D3DLOCKED_RECT { - int Pitch; - unsigned char * pBits; + int Pitch; + unsigned char * pBits; } D3DLOCKED_RECT; #endif diff --git a/src/platform/StdSurface8.cpp b/src/platform/StdSurface8.cpp index a217f67f2..e4faa33be 100644 --- a/src/platform/StdSurface8.cpp +++ b/src/platform/StdSurface8.cpp @@ -133,7 +133,7 @@ bool CSurface8::Read(CStdStream &hGroup, bool fOwnPal) // needs to be kept for some special surfaces //f8BitSfc=false; - // Create and lock surface + // Create and lock surface if (!Create(BitmapInfo.Info.biWidth,BitmapInfo.Info.biHeight, fOwnPal)) return false; if (BitmapInfo.Info.biBitCount == 8) @@ -156,12 +156,12 @@ bool CSurface8::Read(CStdStream &hGroup, bool fOwnPal) BYTE *pBuf = new BYTE[iBufSize]; // Read lines iLineRest = DWordAligned(BitmapInfo.Info.biWidth) - BitmapInfo.Info.biWidth; - for (lcnt=Hgt-1; lcnt>=0; lcnt--) - { - if (!hGroup.Read(pBuf, iBufSize)) - { Clear(); delete [] pBuf; return false; } + for (lcnt=Hgt-1; lcnt>=0; lcnt--) + { + if (!hGroup.Read(pBuf, iBufSize)) + { Clear(); delete [] pBuf; return false; } BYTE *pPix=pBuf; - for (int x=0; xy = i1[1]; - edge->bottom = i2[1] - 1; - edge->dx = ((i2[0] - i1[0]) << POLYGON_FIX_SHIFT) / (i2[1] - i1[1]); - edge->x = (i1[0] << POLYGON_FIX_SHIFT) + (1<<(POLYGON_FIX_SHIFT-1)) - 1; - edge->prev = NULL; - edge->next = NULL; - if (edge->dx < 0) - edge->x += Min(edge->dx+(1<w = Max(Abs(edge->dx)-(1<y = i1[1]; + edge->bottom = i2[1] - 1; + edge->dx = ((i2[0] - i1[0]) << POLYGON_FIX_SHIFT) / (i2[1] - i1[1]); + edge->x = (i1[0] << POLYGON_FIX_SHIFT) + (1<<(POLYGON_FIX_SHIFT-1)) - 1; + edge->prev = NULL; + edge->next = NULL; + if (edge->dx < 0) + edge->x += Min(edge->dx+(1<w = Max(Abs(edge->dx)-(1<x+pos->w/2 < edge->x+edge->w/2)) - { prev = pos; pos = pos->next; } - } - else - { - while ((pos) && (pos->y < edge->y)) - { prev = pos; pos = pos->next; } - } - edge->next = pos; - edge->prev = prev; - if (pos) pos->prev = edge; - if (prev) { prev->next = edge; return list; } - else return edge; - } + { + CPolyEdge *pos = list; + CPolyEdge *prev = NULL; + if (sort_by_x) + { + while ((pos) && (pos->x+pos->w/2 < edge->x+edge->w/2)) + { prev = pos; pos = pos->next; } + } + else + { + while ((pos) && (pos->y < edge->y)) + { prev = pos; pos = pos->next; } + } + edge->next = pos; + edge->prev = prev; + if (pos) pos->prev = edge; + if (prev) { prev->next = edge; return list; } + else return edge; + } static CPolyEdge *remove_edge(CPolyEdge *list, CPolyEdge *edge) - { - if (edge->next) edge->next->prev = edge->prev; - if (edge->prev) { edge->prev->next = edge->next; return list; } - else return edge->next; - } + { + if (edge->next) edge->next->prev = edge->prev; + if (edge->prev) { edge->prev->next = edge->next; return list; } + else return edge->next; + } // Global polygon quick buffer const int QuickPolyBufSize = 20; @@ -458,19 +458,19 @@ void CSurface8::AllowColor(BYTE iRngLo, BYTE iRngHi, bool fAllowZero) } void CSurface8::SetBuffer(BYTE *pbyToBuf, int Wdt, int Hgt, int Pitch) - { - // release old - Clear(); - // set new - this->Wdt=Wdt; - this->Hgt=Hgt; - this->Pitch=Pitch; - this->Bits = pbyToBuf; - NoClip(); - } + { + // release old + Clear(); + // set new + this->Wdt=Wdt; + this->Hgt=Hgt; + this->Pitch=Pitch; + this->Bits = pbyToBuf; + NoClip(); + } void CSurface8::ReleaseBuffer() - { - this->Bits = NULL; - Clear(); - } + { + this->Bits = NULL; + Clear(); + } diff --git a/src/platform/StdSurface8.h b/src/platform/StdSurface8.h index 95f70f313..7d38b93ab 100644 --- a/src/platform/StdSurface8.h +++ b/src/platform/StdSurface8.h @@ -66,8 +66,8 @@ class CSurface8 void GetSurfaceSize(int &irX, int &irY); // get surface size void EnforceC0Transparency() { pPal->EnforceC0Transparency(); } void AllowColor(BYTE iRngLo, BYTE iRngHi, bool fAllowZero=false); - void SetBuffer(BYTE *pbyToBuf, int Wdt, int Hgt, int Pitch); - void ReleaseBuffer(); + void SetBuffer(BYTE *pbyToBuf, int Wdt, int Hgt, int Pitch); + void ReleaseBuffer(); protected: void MapBytes(BYTE *bpMap); bool ReadBytes(BYTE **lpbpData, void *bpTarget, int iSize); diff --git a/src/platform/StdSync.h b/src/platform/StdSync.h index b660a4123..d0c00cef9 100644 --- a/src/platform/StdSync.h +++ b/src/platform/StdSync.h @@ -67,79 +67,79 @@ public: class CStdCSec { public: - CStdCSec() { + CStdCSec() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); } - virtual ~CStdCSec() { pthread_mutex_destroy(&mutex); } + virtual ~CStdCSec() { pthread_mutex_destroy(&mutex); } protected: - pthread_mutex_t mutex; + pthread_mutex_t mutex; public: - virtual void Enter() { pthread_mutex_lock(&mutex); } - virtual void Leave() { pthread_mutex_unlock(&mutex); } + virtual void Enter() { pthread_mutex_lock(&mutex); } + virtual void Leave() { pthread_mutex_unlock(&mutex); } }; class CStdEvent { public: - CStdEvent(bool fManualReset) : fManualReset(fManualReset), fSet(false) - { - pthread_cond_init(&cond, NULL); - pthread_mutex_init(&mutex, NULL); - } - ~CStdEvent() - { - pthread_cond_destroy(&cond); - pthread_mutex_destroy(&mutex); - } + CStdEvent(bool fManualReset) : fManualReset(fManualReset), fSet(false) + { + pthread_cond_init(&cond, NULL); + pthread_mutex_init(&mutex, NULL); + } + ~CStdEvent() + { + pthread_cond_destroy(&cond); + pthread_mutex_destroy(&mutex); + } protected: - pthread_cond_t cond; - pthread_mutex_t mutex; - bool fManualReset, fSet; + pthread_cond_t cond; + pthread_mutex_t mutex; + bool fManualReset, fSet; public: - void Set() - { - pthread_mutex_lock(&mutex); - fSet = true; - pthread_cond_broadcast(&cond); - pthread_mutex_unlock(&mutex); - } - void Pulse() - { - pthread_cond_broadcast(&cond); - } - void Reset() - { - pthread_mutex_lock(&mutex); - fSet = false; - pthread_mutex_unlock(&mutex); - } - bool WaitFor(unsigned int iMillis) - { - pthread_mutex_lock(&mutex); - // Already set? - while(!fSet) - { - // Use pthread_cond_wait or pthread_cond_timedwait depending on wait length. Check return value. - // Note this will temporarily unlock the mutex, so no deadlock should occur. - timespec ts = { iMillis / 1000, (iMillis % 1000) * 1000000 }; - if(0 != (iMillis != INFINITE ? pthread_cond_timedwait(&cond, &mutex, &ts) : pthread_cond_wait(&cond, &mutex))) - { - pthread_mutex_unlock(&mutex); - return false; - } - } - // Reset flag, release mutex, done. - if (!fManualReset) fSet = false; - pthread_mutex_unlock(&mutex); - return true; - } + void Set() + { + pthread_mutex_lock(&mutex); + fSet = true; + pthread_cond_broadcast(&cond); + pthread_mutex_unlock(&mutex); + } + void Pulse() + { + pthread_cond_broadcast(&cond); + } + void Reset() + { + pthread_mutex_lock(&mutex); + fSet = false; + pthread_mutex_unlock(&mutex); + } + bool WaitFor(unsigned int iMillis) + { + pthread_mutex_lock(&mutex); + // Already set? + while(!fSet) + { + // Use pthread_cond_wait or pthread_cond_timedwait depending on wait length. Check return value. + // Note this will temporarily unlock the mutex, so no deadlock should occur. + timespec ts = { iMillis / 1000, (iMillis % 1000) * 1000000 }; + if(0 != (iMillis != INFINITE ? pthread_cond_timedwait(&cond, &mutex, &ts) : pthread_cond_wait(&cond, &mutex))) + { + pthread_mutex_unlock(&mutex); + return false; + } + } + // Reset flag, release mutex, done. + if (!fManualReset) fSet = false; + pthread_mutex_unlock(&mutex); + return true; + } }; #if defined __GNUC__ && ((__GNUC__ >= 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ >= 5)) @@ -177,10 +177,10 @@ public: class CStdLock { public: - CStdLock(CStdCSec *pSec) : sec(pSec) - { sec->Enter(); } - ~CStdLock() - { Clear(); } + CStdLock(CStdCSec *pSec) : sec(pSec) + { sec->Enter(); } + ~CStdLock() + { Clear(); } protected: CStdCSec *sec; diff --git a/src/platform/StdVideo.cpp b/src/platform/StdVideo.cpp index 52d33eb31..e9deef9e1 100644 --- a/src/platform/StdVideo.cpp +++ b/src/platform/StdVideo.cpp @@ -128,7 +128,7 @@ bool AVIOpenGrab(const char *szFilename, { // Open avi stream - if ( AVIStreamOpenFromFile( + if ( AVIStreamOpenFromFile( ppAviStream, szFilename, streamtypeVIDEO, diff --git a/src/platform/StdWindow.cpp b/src/platform/StdWindow.cpp index 58188336f..4c5ea08b7 100644 --- a/src/platform/StdWindow.cpp +++ b/src/platform/StdWindow.cpp @@ -67,7 +67,7 @@ BOOL CStdWindow::RegisterWindowClass(HINSTANCE hInst) { WndClass.hbrBackground = (HBRUSH) COLOR_BACKGROUND; WndClass.lpszClassName = C4FullScreenClassName; WndClass.hIcon = LoadIcon (hInst, MAKEINTRESOURCE (IDI_00_C4X) ); - WndClass.hIconSm = LoadIcon (hInst, MAKEINTRESOURCE (IDI_00_C4X) ); + WndClass.hIconSm = LoadIcon (hInst, MAKEINTRESOURCE (IDI_00_C4X) ); return RegisterClassEx(&WndClass); } @@ -285,9 +285,9 @@ bool CStdApp::GetIndexedDisplayMode(int32_t iIndex, int32_t *piXRes, int32_t *pi // prepare search struct DEVMODE dmode; ZeroMemory(&dmode, sizeof(dmode)); dmode.dmSize = sizeof(dmode); - StdStrBuf Mon; + StdStrBuf Mon; if (iMonitor) - Mon.Format("\\\\.\\Display%d", iMonitor+1); + Mon.Format("\\\\.\\Display%d", iMonitor+1); // check if indexed mode exists if (!EnumDisplaySettings(Mon.getData(), iIndex, &dmode)) return false; // mode exists; return it diff --git a/src/platform/StdWindow.h b/src/platform/StdWindow.h index 9aeb32737..4d6cd3fe2 100644 --- a/src/platform/StdWindow.h +++ b/src/platform/StdWindow.h @@ -283,7 +283,7 @@ protected: void * Info; #elif defined(USE_SDL_MAINLOOP) private: - int width, height; + int width, height; protected: virtual void HandleMessage(SDL_Event&) {} #endif diff --git a/src/platform/StdXApp.cpp b/src/platform/StdXApp.cpp index e35adf38b..ff80e4b4d 100644 --- a/src/platform/StdXApp.cpp +++ b/src/platform/StdXApp.cpp @@ -583,7 +583,7 @@ bool CStdApp::ReadStdInCommand() { char c; if(read(0, &c, 1) != 1) return false; - if(c == '\n') { + if(c == '\n') { if(!CmdBuf.isNull()) { OnCommand(CmdBuf.getData()); CmdBuf.Clear(); } diff --git a/src/platform/StdXWindow.cpp b/src/platform/StdXWindow.cpp index 54fd235f3..08721ca05 100644 --- a/src/platform/StdXWindow.cpp +++ b/src/platform/StdXWindow.cpp @@ -236,7 +236,7 @@ bool CStdWindow::StorePosition(const char *, const char *, bool) { return true; bool CStdWindow::RestorePosition(const char *, const char *, bool) { // The Windowmanager is responsible for window placement. - return true; + return true; } bool CStdWindow::GetSize(RECT * pRect) { diff --git a/src/script/C4Aul.cpp b/src/script/C4Aul.cpp index f471dba85..6d09d1526 100644 --- a/src/script/C4Aul.cpp +++ b/src/script/C4Aul.cpp @@ -220,7 +220,7 @@ void C4AulScript::Clear() // delete script+code Script.Clear(); ClearCode(); - // reset flags + // reset flags State = ASS_NONE; } @@ -520,11 +520,11 @@ bool C4AulScriptEngine::DenumerateVariablePointers() } void C4AulScriptEngine::CompileFunc(StdCompiler *pComp) - { + { C4ValueMapData GlobalNamedDefault; GlobalNamedDefault.SetNameList(&GlobalNamedNames); pComp->Value(mkNamingAdapt(GlobalNamed, "GlobalNamed" , GlobalNamedDefault)); - } + } bool C4AulScriptEngine::InitDebug(uint16_t iPort, const char *szPassword, const char *szHost, bool fWait) { diff --git a/src/script/C4AulLink.cpp b/src/script/C4AulLink.cpp index fe7e25a24..d5d453d7d 100644 --- a/src/script/C4AulLink.cpp +++ b/src/script/C4AulLink.cpp @@ -211,13 +211,13 @@ void C4AulScript::AfterLink() } bool C4AulScript::ReloadScript(const char *szPath) - { - // call for childs + { + // call for childs for (C4AulScript *s = Child0; s; s = s->Next) - if(s->ReloadScript(szPath)) - return true; - return false; - } + if(s->ReloadScript(szPath)) + return true; + return false; + } void C4AulScriptEngine::Link(C4DefList *rDefs) { @@ -277,10 +277,10 @@ void C4AulScriptEngine::Link(C4DefList *rDefs) rDefs->CallEveryDefinition(); // display state LogF("C4AulScriptEngine linked - %d line%s, %d warning%s, %d error%s", - lineCnt, (lineCnt != 1 ? "s" : ""), warnCnt, (warnCnt != 1 ? "s" : ""), errCnt, (errCnt != 1 ? "s" : "")); + lineCnt, (lineCnt != 1 ? "s" : ""), warnCnt, (warnCnt != 1 ? "s" : ""), errCnt, (errCnt != 1 ? "s" : "")); - // reset counters - warnCnt = errCnt = nonStrictCnt = lineCnt = 0; + // reset counters + warnCnt = errCnt = nonStrictCnt = lineCnt = 0; } catch (C4AulError *err) { @@ -315,13 +315,13 @@ void C4AulScriptEngine::ReLink(C4DefList *rDefs) } bool C4AulScriptEngine::ReloadScript(const char *szScript, C4DefList *pDefs) - { - // reload - if(!C4AulScript::ReloadScript(szScript)) - return false; - // relink - ReLink(pDefs); - // ok - return true; - } + { + // reload + if(!C4AulScript::ReloadScript(szScript)) + return false; + // relink + ReLink(pDefs); + // ok + return true; + } diff --git a/src/script/C4PropList.cpp b/src/script/C4PropList.cpp index bf224ca04..60b7744c2 100644 --- a/src/script/C4PropList.cpp +++ b/src/script/C4PropList.cpp @@ -401,9 +401,9 @@ unsigned int C4Set::Hash(int e) { unsigned int hash = 4, tmp; hash += e >> 16; - tmp = ((e & 0xffff) << 11) ^ hash; - hash = (hash << 16) ^ tmp; - hash += hash >> 11; + tmp = ((e & 0xffff) << 11) ^ hash; + hash = (hash << 16) ^ tmp; + hash += hash >> 11; hash ^= hash << 3; hash += hash >> 5; hash ^= hash << 4; diff --git a/src/script/C4ScriptHost.cpp b/src/script/C4ScriptHost.cpp index 314bdaed0..c3e003e07 100644 --- a/src/script/C4ScriptHost.cpp +++ b/src/script/C4ScriptHost.cpp @@ -99,9 +99,9 @@ void C4ScriptHost::Close() } int32_t C4ScriptHost::GetControlMethod(int32_t com, int32_t first, int32_t second) - { + { return ((first >> com) & 0x01) | (((second >> com) & 0x01) << 1); - } + } void C4ScriptHost::GetControlMethodMask(const char *szFunctionFormat, int32_t& first, int32_t& second) { @@ -137,20 +137,20 @@ C4Value C4ScriptHost::Call(const char *szFunction, C4Object *pObj, C4AulParSet * } bool C4ScriptHost::ReloadScript(const char *szPath) - { - // this? - if(SEqualNoCase(szPath, FilePath) || (stringTable && SEqualNoCase(szPath, stringTable->GetFilePath()))) - { - // try reload - char szParentPath[_MAX_PATH + 1]; C4Group ParentGrp; - if(GetParentPath(szPath, szParentPath)) - if(ParentGrp.Open(szParentPath)) - if(Load(Name, ParentGrp, Filename, Config.General.Language, NULL, stringTable)) - return true; - } - // call for childs - return C4AulScript::ReloadScript(szPath); - } + { + // this? + if(SEqualNoCase(szPath, FilePath) || (stringTable && SEqualNoCase(szPath, stringTable->GetFilePath()))) + { + // try reload + char szParentPath[_MAX_PATH + 1]; C4Group ParentGrp; + if(GetParentPath(szPath, szParentPath)) + if(ParentGrp.Open(szParentPath)) + if(Load(Name, ParentGrp, Filename, Config.General.Language, NULL, stringTable)) + return true; + } + // call for childs + return C4AulScript::ReloadScript(szPath); + } void C4ScriptHost::SetError(const char *szMessage) { @@ -249,7 +249,7 @@ C4Value C4GameScriptHost::GRBroadcast(const char *szFunction, C4AulParSet *pPars } void C4GameScriptHost::CompileFunc(StdCompiler *pComp) - { + { pComp->Value(mkNamingAdapt(Go, "Go", false)); pComp->Value(mkNamingAdapt(Counter, "Counter", 0)); - } + } diff --git a/src/script/C4ScriptHost.h b/src/script/C4ScriptHost.h index df96f4485..20c64b32c 100644 --- a/src/script/C4ScriptHost.h +++ b/src/script/C4ScriptHost.h @@ -52,7 +52,7 @@ class C4ScriptHost : public C4AulScript, public C4ComponentHost protected: void SetError(const char *szMessage); void MakeScript(); - bool ReloadScript(const char *szPath); + bool ReloadScript(const char *szPath); }; @@ -88,12 +88,12 @@ class C4GameScriptHost : public C4ScriptHost // Global script data // FIXME: Move to C4AulScriptEngine - int32_t Counter; + int32_t Counter; bool Go; bool Execute(); - // Compile scenario script data - void CompileFunc(StdCompiler *pComp); + // Compile scenario script data + void CompileFunc(StdCompiler *pComp); }; diff --git a/src/script/C4ValueMap.cpp b/src/script/C4ValueMap.cpp index 7ddb3be82..611af71fc 100644 --- a/src/script/C4ValueMap.cpp +++ b/src/script/C4ValueMap.cpp @@ -262,21 +262,21 @@ void C4ValueMapData::DenumeratePointers() void C4ValueMapData::CompileFunc(StdCompiler *pComp) { - bool fCompiler = pComp->isCompiler(); - if(fCompiler) Reset(); - // Compile item count - int32_t iValueCnt; - if(!fCompiler) iValueCnt = pNames ? pNames->iSize : 0; - pComp->Value(mkDefaultAdapt(iValueCnt, 0)); + bool fCompiler = pComp->isCompiler(); + if(fCompiler) Reset(); + // Compile item count + int32_t iValueCnt; + if(!fCompiler) iValueCnt = pNames ? pNames->iSize : 0; + pComp->Value(mkDefaultAdapt(iValueCnt, 0)); // nuthing 2do for no items if (!iValueCnt) return; - // Seperator (';') - pComp->Seperator(StdCompiler::SEP_SEP2); - // Data - char **ppNames = !fCompiler ? pNames->pNames : new char * [iValueCnt]; + // Seperator (';') + pComp->Seperator(StdCompiler::SEP_SEP2); + // Data + char **ppNames = !fCompiler ? pNames->pNames : new char * [iValueCnt]; if (fCompiler) for(int32_t i = 0; i < iValueCnt; i++) ppNames[i] = 0; - C4Value *pValues = !fCompiler ? pData : new C4Value [iValueCnt]; - // Compile + C4Value *pValues = !fCompiler ? pData : new C4Value [iValueCnt]; + // Compile try { for(int32_t i = 0; i < iValueCnt; i++) @@ -305,19 +305,19 @@ void C4ValueMapData::CompileFunc(StdCompiler *pComp) } throw; } - // Set - if(fCompiler) - { - C4ValueMapNames *pOldNames = pNames; - // Set - CreateTempNameList(); - pNames->SetNameArray(const_cast(ppNames), iValueCnt); + // Set + if(fCompiler) + { + C4ValueMapNames *pOldNames = pNames; + // Set + CreateTempNameList(); + pNames->SetNameArray(const_cast(ppNames), iValueCnt); for(int32_t i = 0; i < iValueCnt; i++) delete ppNames[i]; - delete [] ppNames; delete [] pData; - pData = pValues; - // Assign old name list - if(pOldNames) SetNameList(pOldNames); - } + delete [] ppNames; delete [] pData; + pData = pValues; + // Assign old name list + if(pOldNames) SetNameList(pOldNames); + } } // *** C4ValueMapNames *** @@ -436,7 +436,7 @@ void C4ValueMapNames::SetNameArray(const char **pnNames, int32_t nSize) int32_t C4ValueMapNames::AddName(const char *pnName) { // name already existing? - int32_t iNr; + int32_t iNr; if((iNr=GetItemNr(pnName)) != -1) return iNr; diff --git a/src/script/C4ValueMap.h b/src/script/C4ValueMap.h index e16f34a22..afaf081ba 100644 --- a/src/script/C4ValueMap.h +++ b/src/script/C4ValueMap.h @@ -74,7 +74,7 @@ public: void DenumeratePointers(); - void CompileFunc(StdCompiler *pComp); + void CompileFunc(StdCompiler *pComp); private: