void C4Console::UpdateNetMenu() { // Active & network hosting check if (!Active) return; if (!::Network.isHost() || !::Network.isEnabled()) return; // Clear old ClearNetMenu(); // Insert menu C4ConsoleGUI::AddNetMenu(); // Host StdStrBuf str; str.Format(LoadResStr("IDS_MNU_NETHOST"),Game.Clients.getLocalName(),Game.Clients.getLocalID()); AddNetMenuItemForPlayer(Game.Clients.getLocalID(), str.getData(), C4ConsoleGUI::CO_None); // Clients for (C4Network2Client *pClient=::Network.Clients.GetNextClient(nullptr); pClient; pClient=::Network.Clients.GetNextClient(pClient)) { if (pClient->isHost()) continue; str.Format(LoadResStr(pClient->isActivated() ? "IDS_MNU_NETCLIENT_DEACTIVATE" : "IDS_MNU_NETCLIENT_ACTIVATE"), pClient->getName(), pClient->getID()); AddNetMenuItemForPlayer(pClient->getID(), str.getData(), pClient->isActivated() ? C4ConsoleGUI::CO_Deactivate : C4ConsoleGUI::CO_Activate); str.Format(LoadResStr("IDS_NET_KICKCLIENTEX"), pClient->getName(), pClient->getID()); AddNetMenuItemForPlayer(pClient->getID(), str.getData(), C4ConsoleGUI::CO_Kick); } return; }
void C4StartupNetDlg::CheckVersionUpdate() { #ifdef WITH_AUTOMATIC_UPDATE StdStrBuf strVersion; strVersion.Format("%d.%d", C4XVER1, C4XVER2); StdStrBuf strQuery; strQuery.Format("%s?version=%s&platform=%s&action=version", Config.Network.UpdateServerAddress, strVersion.getData(), C4_OS); if (pUpdateClient.Init() && pUpdateClient.SetServer(strQuery.getData()) && pUpdateClient.QueryUpdateURL()) { pUpdateClient.SetNotify(&Application.InteractiveThread); Application.InteractiveThread.AddProc(&pUpdateClient); } fUpdateCheckPending = true; #endif }
bool C4Console::UpdatePlayerMenu() { if (!Active) return false; ClearPlayerMenu(); for (C4Player *pPlr=::Players.First; pPlr; pPlr=pPlr->Next) { StdStrBuf sText; if (::Network.isEnabled()) sText.Format(LoadResStr("IDS_CNS_PLRQUITNET"),pPlr->GetName(),pPlr->AtClientName); else sText.Format(LoadResStr("IDS_CNS_PLRQUIT"),pPlr->GetName()); AddKickPlayerMenuItem(pPlr, sText, (!::Network.isEnabled() || ::Network.isHost()) && Editing); } return true; }
bool C4GameSave::SaveDesc(C4Group &hToGroup) { // Unfortunately, there's no way to prealloc the buffer in an appropriate size StdStrBuf sBuffer; // Header sBuffer.AppendFormat("{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1031{\\fonttbl {\\f0\\fnil\\fcharset%d Times New Roman;}}", 0 /*FIXME: a number for UTF-8 here*/); sBuffer.Append(LineFeed); // Scenario title sBuffer.AppendFormat("\\uc1\\pard\\ulnone\\b\\f0\\fs20 %s\\par",Game.ScenarioTitle.getData()); sBuffer.Append(LineFeed "\\b0\\fs16\\par" LineFeed); // OK; each specializations has its own desc format WriteDesc(sBuffer); // End of file sBuffer.Append(LineFeed "}" LineFeed); // Generate Filename StdStrBuf sFilename; char szLang[3]; SCopyUntil(Config.General.Language, szLang, ',', 2); sFilename.Format(C4CFN_ScenarioDesc,szLang); // Save to file return !!hToGroup.Add(sFilename.getData(),sBuffer,false,true); }
bool OpenLog() { // open sLogFileName = C4CFN_Log; int iLog = 2; #ifdef _WIN32 while (!(C4LogFile = _fsopen(Config.AtUserDataPath(sLogFileName.getData()), "wt", _SH_DENYWR))) #elif defined(HAVE_SYS_FILE_H) int fd = 0; while (!(fd = open(Config.AtUserDataPath(sLogFileName.getData()), O_WRONLY | O_CREAT, 0644)) || flock(fd, LOCK_EX|LOCK_NB)) #else while (!(C4LogFile = fopen(Config.AtUserDataPath(sLogFileName.getData()), "wb"))) #endif { // Already locked by another instance? #if !defined(_WIN32) && defined(HAVE_SYS_FILE_H) if (fd) close(fd); #else if (C4LogFile) fclose(C4LogFile); #endif // If the file does not yet exist, the directory is r/o // don't go on then, or we have an infinite loop if (access(Config.AtUserDataPath(sLogFileName.getData()), 0)) return false; // try different name sLogFileName.Format(C4CFN_LogEx, iLog++); } #if !defined(_WIN32) && defined(HAVE_SYS_FILE_H) ftruncate(fd, 0); C4LogFile = fdopen(fd, "wb"); #endif // save start time time(&C4LogStartTime); return true; }
bool C4DownloadDlg::DownloadFile(const char *szDLType, C4GUI::Screen *pScreen, const char *szURL, const char *szSaveAsFilename, const char *szNotFoundMessage) { // log it LogF(LoadResStr("IDS_PRC_DOWNLOADINGFILE"), szURL); // show download dialog C4DownloadDlg *pDlg = new C4DownloadDlg(szDLType); if (!pDlg->ShowModal(pScreen, szURL, szSaveAsFilename)) { // show an appropriate error const char *szError = pDlg->GetError(); if (!szError || !*szError) szError = LoadResStr("IDS_PRC_UNKOWNERROR"); StdStrBuf sError; sError.Format(LoadResStr("IDS_PRC_DOWNLOADERROR"), GetFilename(szURL), szError); // it's a 404: display extended message if (SSearch(szError, "404") && szNotFoundMessage) { sError.Append("|"); sError.Append(szNotFoundMessage); } // display message pScreen->ShowMessageModal(sError.getData(), FormatString(LoadResStr("IDS_CTL_DL_TITLE"), szDLType).getData(), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error, NULL); delete pDlg; return false; } LogF(LoadResStr("IDS_PRC_DOWNLOADCOMPLETE"), szURL); delete pDlg; return true; }
void C4Network2ResDlg::ListItem::Update(const C4Network2Res *pByRes) { // update progress label iProgress = pByRes->getPresentPercent(); if (iProgress < 100) { StdStrBuf progress; progress.Format("%d%%", iProgress); if (pProgress) pProgress->SetText(progress.getData()); else { pProgress = new C4GUI::Label(progress.getData(), GetBounds().Wdt - IconLabelSpacing, 0, ARight); pProgress->SetToolTip(LoadResStr("IDS_NET_RESPROGRESS_DESC")); AddElement(pProgress); } } else if (pProgress) { delete pProgress; pProgress=NULL; } // update disk icon if (IsSavePossible()) { if (!pSaveBtn) { pSaveBtn = new C4GUI::CallbackButtonEx<C4Network2ResDlg::ListItem, C4GUI::IconButton>(C4GUI::Ico_Save, GetToprightCornerRect(16,16,2,1), 0, this, &ListItem::OnButtonSave); AddElement(pSaveBtn); } } else if (pSaveBtn) delete pSaveBtn; }
void C4StartupAboutDlg::OnRegisterBtn(C4GUI::Control *btn) { // open hardcoded registration URL // URL needs lowercase language code, two-character code only StdStrBuf sLangCode; sLangCode.Format("%.2s", Config.General.Language); sLangCode.ToLowerCase(); OpenURL(FormatString("http://www.clonk.de/register.php?lng=%s&product=cr", sLangCode.getData()).getData()); }
void C4StartupMainDlg::OnShown() { // Incoming update if (Application.IncomingUpdate) { C4UpdateDlg::ApplyUpdate(Application.IncomingUpdate.getData(), false, GetScreen()); Application.IncomingUpdate.Clear(); } // Manual update by command line or url if (Application.CheckForUpdates) { C4UpdateDlg::CheckForUpdates(GetScreen(), false); Application.CheckForUpdates = false; } // Automatic update else { if (Config.Network.AutomaticUpdate) C4UpdateDlg::CheckForUpdates(GetScreen(), true); } // first start evaluation if (Config.General.FirstStart) { Config.General.FirstStart = false; } // first thing that's needed is a new player, if there's none - independent of // first start bool fHasPlayer = false; StdStrBuf sSearchPath; const char *szFn; sSearchPath.Format("%s%s", (const char *)Config.General.ExePath, (const char *)Config.General.PlayerPath); for (DirectoryIterator i(sSearchPath.getData()); szFn = *i; i++) { szFn = Config.AtExeRelativePath(szFn); if (*GetFilename(szFn) == '.') continue; // ignore ".", ".." and private files (".*") if (!WildcardMatch(C4CFN_PlayerFiles, GetFilename(szFn))) continue; fHasPlayer = true; break; } if (!fHasPlayer) { // no player created yet: Create one C4GUI::Dialog *pDlg; GetScreen()->ShowModalDlg(pDlg = new C4StartupPlrPropertiesDlg(NULL, NULL), true); } // make sure participants are updated after switching back from player // selection UpdateParticipants(); // First show if (fFirstShown) { // Activate the application (trying to prevent flickering half-focus in // win32...) Application.Activate(); // Set the focus to the start button (we might still not have the focus // after the update-check sometimes... :/) SetFocus(pStartButton, false); } fFirstShown = false; }
C4PortraitSelDlg::C4PortraitSelDlg(C4FileSel_BaseCB *pSelCallback, bool fSetPicture, bool fSetBigIcon) : C4FileSelDlg(Config.General.ExePath, FormatString(LoadResStr("IDS_MSG_SELECT"), LoadResStr("IDS_TYPE_PORTRAIT")).getData(), pSelCallback, false), pCheckSetPicture(NULL), pCheckSetBigIcon(NULL), fDefSetPicture(fSetPicture), fDefSetBigIcon(fSetBigIcon) { char path[_MAX_PATH + 1]; // add common picture locations StdStrBuf strLocation; SCopy(Config.AtUserPath(""), path, _MAX_PATH); TruncateBackslash(path); strLocation.Format("%s %s", C4ENGINECAPTION, LoadResStr("IDS_TEXT_USERPATH")); AddLocation(strLocation.getData(), path); SCopy(Config.AtExePath(""), path, _MAX_PATH); TruncateBackslash(path); strLocation.Format("%s %s", C4ENGINECAPTION, LoadResStr("IDS_TEXT_PROGRAMDIRECTORY")); AddCheckedLocation(strLocation.getData(), Config.General.ExePath); #ifdef _WIN32 if (SHGetSpecialFolderPath(NULL, path, CSIDL_PERSONAL, FALSE)) AddCheckedLocation(LoadResStr("IDS_TEXT_MYDOCUMENTS"), path); if (SHGetSpecialFolderPath(NULL, path, CSIDL_MYPICTURES, FALSE)) AddCheckedLocation(LoadResStr("IDS_TEXT_MYPICTURES"), path); if (SHGetSpecialFolderPath(NULL, path, CSIDL_DESKTOPDIRECTORY, FALSE)) AddCheckedLocation(LoadResStr("IDS_TEXT_DESKTOP"), path); #endif #ifdef __APPLE__ AddCheckedLocation(LoadResStr("IDS_TEXT_HOME"), getenv("HOME")); #else AddCheckedLocation(LoadResStr("IDS_TEXT_HOMEFOLDER"), getenv("HOME")); #endif #ifndef _WIN32 sprintf(path, "%s%c%s", getenv("HOME"), (char)DirectorySeparator, (const char *)"Desktop"); AddCheckedLocation(LoadResStr("IDS_TEXT_DESKTOP"), path); #endif // build dialog InitElements(); // select last location SetCurrentLocation(Config.Startup.LastPortraitFolderIdx, false); }
StdStrBuf C4Shader::Build(const ShaderSliceList &Slices, bool fDebug) { // At the start of the shader set the #version and number of // available uniforms StdStrBuf Buf; #ifndef USE_CONSOLE GLint iMaxFrags = 0, iMaxVerts = 0; glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, &iMaxFrags); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, &iMaxVerts); #else int iMaxFrags = INT_MAX, iMaxVerts = INT_MAX; #endif Buf.Format("#version %d\n" "#define MAX_FRAGMENT_UNIFORM_COMPONENTS %d\n" "#define MAX_VERTEX_UNIFORM_COMPONENTS %d\n", C4Shader_Version, iMaxFrags, iMaxVerts); // Put slices int iPos = -1, iNextPos = -1; do { iPos = iNextPos; iNextPos = C4Shader_LastPosition+1; // Add all slices at the current level if (fDebug && iPos > 0) Buf.AppendFormat("\t// Position %d:\n", iPos); for (ShaderSliceList::const_iterator pSlice = Slices.begin(); pSlice != Slices.end(); pSlice++) { if (pSlice->Position < iPos) continue; if (pSlice->Position > iPos) { iNextPos = Min(iNextPos, pSlice->Position); continue; } // Same position - add slice! if (fDebug) { if (pSlice->Source.getLength()) Buf.AppendFormat("\t// Slice from %s:\n", pSlice->Source.getData()); else Buf.Append("\t// Built-in slice:\n"); } Buf.Append(pSlice->Text); if (Buf[Buf.getLength()-1] != '\n') Buf.AppendChar('\n'); } // Add seperator - only priority (-1) is top-level if (iPos == -1) { Buf.Append("void main() {\n"); } } while (iNextPos <= C4Shader_LastPosition); // Terminate Buf.Append("}\n"); return Buf; }
bool C4FullScreen::ViewportCheck() { int iPlrNum; C4Player *pPlr; // Not active if (!Active) return false; // Determine film mode bool fFilm = (Game.C4S.Head.Replay && Game.C4S.Head.Film); // Check viewports switch (::Viewports.GetViewportCount()) { // No viewports: create no-owner viewport case 0: iPlrNum = NO_OWNER; // Film mode: create viewport for first player (instead of no-owner) if (fFilm) if ((pPlr = ::Players.First)) iPlrNum = pPlr->Number; // Create viewport ::Viewports.CreateViewport(iPlrNum, iPlrNum==NO_OWNER); // Non-film (observer mode) if (!fFilm) { // Activate mouse control ::MouseControl.Init(iPlrNum); // Display message for how to open observer menu (this message will be cleared if any owned viewport opens) StdStrBuf sKey; sKey.Format("<c ffff00><%s></c>", Game.KeyboardInput.GetKeyCodeNameByKeyName("FullscreenMenuOpen", false).getData()); ::GraphicsSystem.FlashMessage(FormatString(LoadResStr("IDS_MSG_PRESSORPUSHANYGAMEPADBUTT"), sKey.getData()).getData()); } break; // One viewport: do nothing case 1: break; // More than one viewport: remove all no-owner viewports default: ::Viewports.CloseViewport(NO_OWNER, true); break; } // Look for no-owner viewport C4Viewport *pNoOwnerVp = ::Viewports.GetViewport(NO_OWNER); // No no-owner viewport found if (!pNoOwnerVp) { // Close any open fullscreen menu CloseMenu(); } // No-owner viewport present else { // movie mode: player present, and no valid viewport assigned? if (Game.C4S.Head.Replay && Game.C4S.Head.Film && (pPlr = ::Players.First)) // assign viewport to joined player pNoOwnerVp->Init(pPlr->Number, true); } // Done return true; }
void C4StartupMainDlg::OnSurveyBtn(C4GUI::Control *btn) { int32_t iPlrCount = SModuleCount(Config.General.Participants); int32_t plrCount = 1; StdStrBuf sError; if (iPlrCount == plrCount) { C4Startup::Get()->SwitchDialog(C4Startup::SDID_Survey); } else if (iPlrCount > plrCount) { sError.Format(LoadResStr("IDS_DLG_TOOMANY_QUESTIONNAIRE"), plrCount); GetScreen()->ShowMessage(sError.getData(), LoadResStr("IDS_MSG_CANNOTSTARTQUESTIONNAIRE"), C4GUI::Ico_Error); } else if (iPlrCount < plrCount) { sError.Format(LoadResStr("IDS_DLG_TOOFEW_QUESTIONNAIRE"), plrCount); GetScreen()->ShowMessage(sError.getData(), LoadResStr("IDS_MSG_CANNOTSTARTQUESTIONNAIRE"), C4GUI::Ico_Error); } }
C4Network2ClientListBox::ClientListItem::ClientListItem(class C4Network2ClientListBox *pForDlg, int iClientID) // ctor : ListItem(pForDlg, iClientID), pStatusIcon(nullptr), pName(nullptr), pPing(nullptr), pActivateBtn(nullptr), pKickBtn(nullptr), last_sound_time(0) { // get associated client const C4Client *pClient = GetClient(); // get size int iIconSize = ::GraphicsResource.TextFont.GetLineHeight(); if (pForDlg->IsStartup()) iIconSize *= 2; int iWidth = pForDlg->GetItemWidth(); int iVerticalIndent = 2; SetBounds(C4Rect(0, 0, iWidth, iIconSize+2*iVerticalIndent)); C4GUI::ComponentAligner ca(GetContainedClientRect(), 0,iVerticalIndent); // create subcomponents bool fIsHost = pClient && pClient->isHost(); pStatusIcon = new C4GUI::Icon(ca.GetFromLeft(iIconSize), fIsHost ? C4GUI::Ico_Host : C4GUI::Ico_Client); StdStrBuf sNameLabel; if (pClient) { if (pForDlg->IsStartup()) sNameLabel.Ref(pClient->getName()); else sNameLabel.Format("%s:%s", pClient->getName(), pClient->getNick()); } else { sNameLabel.Ref("???"); } pName = new C4GUI::Label(sNameLabel.getData(), iIconSize + IconLabelSpacing,iVerticalIndent, ALeft); int iPingRightPos = GetBounds().Wdt - IconLabelSpacing; if (::Network.isHost()) iPingRightPos -= 48; if (::Network.isHost() && pClient && !pClient->isHost()) { // activate/deactivate and kick btns for clients at host if (!pForDlg->IsStartup()) { pActivateBtn = new C4GUI::CallbackButtonEx<C4Network2ClientListBox::ClientListItem, C4GUI::IconButton>(C4GUI::Ico_Active, GetToprightCornerRect(std::max(iIconSize, 16),std::max(iIconSize, 16),2,1,1), 0, this, &ClientListItem::OnButtonActivate); fShownActive = true; } pKickBtn = new C4GUI::CallbackButtonEx<C4Network2ClientListBox::ClientListItem, C4GUI::IconButton>(C4GUI::Ico_Kick, GetToprightCornerRect(std::max(iIconSize, 16),std::max(iIconSize, 16),2,1,0), 0, this, &ClientListItem::OnButtonKick); pKickBtn->SetToolTip(LoadResStrNoAmp("IDS_NET_KICKCLIENT")); } if (!pForDlg->IsStartup()) if (pClient && !pClient->isLocal()) { // wait time pPing = new C4GUI::Label("???", iPingRightPos, iVerticalIndent, ARight); pPing->SetToolTip(LoadResStr("IDS_DESC_CONTROLWAITTIME")); } // add components AddElement(pStatusIcon); AddElement(pName); if (pPing) AddElement(pPing); if (pActivateBtn) AddElement(pActivateBtn); if (pKickBtn) AddElement(pKickBtn); // add to listbox (will eventually get moved) pForDlg->AddElement(this); // first-time update Update(); }
void C4StartupNetDlg::UpdateMasterserver() { // update button icon to current state btnInternet->SetIcon(Config.Network.MasterServerSignUp ? C4GUI::Ico_Ex_InternetOn : C4GUI::Ico_Ex_InternetOff); // creates masterserver object if masterserver is enabled; destroy otherwise if (!Config.Network.MasterServerSignUp == !pMasterserverClient) return; if (!Config.Network.MasterServerSignUp) { delete pMasterserverClient; pMasterserverClient = nullptr; } else { pMasterserverClient = new C4StartupNetListEntry(pGameSelList, nullptr, this); StdStrBuf strVersion; strVersion.Format("%d.%d", C4XVER1, C4XVER2); StdStrBuf strQuery; strQuery.Format("%s?version=%s&platform=%s", Config.Network.GetLeagueServerAddress(), strVersion.getData(), C4_OS); pMasterserverClient->SetRefQuery(strQuery.getData(), C4StartupNetListEntry::NRQT_Masterserver); } }
C4GoalDisplay::GoalPicture::GoalPicture(const C4Rect &rcBounds, C4ID idGoal, bool fFulfilled) : idGoal(idGoal), fFulfilled(fFulfilled), C4GUI::Window() { // bounds SetBounds(rcBounds); // can't get specialized desc from object at the moment because of potential script callbacks! StdStrBuf strGoalName, strGoalDesc; /*C4Object *pGoalObj = Game.Objects.FindInternal(idGoal); if (pGoalObj) { pGoalObj->GetInfoString().getData(); } else*/ { // just get desc from def C4Def *pGoalDef = Game.Defs.ID2Def(idGoal); if (pGoalDef) { strGoalName.Copy(pGoalDef->GetName()); strGoalDesc.Copy(pGoalDef->GetDesc()); } } // get tooltip StdStrBuf sToolTip; if (fFulfilled) sToolTip.Format(LoadResStr("IDS_DESC_GOALFULFILLED"), strGoalName.getData(), strGoalDesc.getData()); else sToolTip.Format(LoadResStr("IDS_DESC_GOALNOTFULFILLED"), strGoalName.getData(), strGoalDesc.getData()); SetToolTip(sToolTip.getData()); // create buffered picture of goal definition C4Def *pDrawDef = Game.Defs.ID2Def(idGoal); if (pDrawDef) { Picture.Create(C4PictureSize, C4PictureSize); // get an object instance to draw (optional; may be zero) C4Object *pGoalObj = Game.Objects.FindInternal(idGoal); // draw goal def! pDrawDef->Draw(Picture, false, 0, pGoalObj); } // unfulfilled goal: grey out picture if (!fFulfilled) Picture.Grayscale(30); }
bool C4Network2Res::SetByCore(const C4Network2ResCore &nCore, bool fSilent, const char *szAsFilename, int32_t iRecursion) // by main thread { StdStrBuf sFilename; // try open local file const char *szFilename = szAsFilename ? szAsFilename : GetC4Filename(nCore.getFileName()); if (SetByFile(szFilename, false, nCore.getType(), nCore.getID(), nCore.getFileName(), fSilent)) { // check contents checksum if (Core.getContentsCRC() == nCore.getContentsCRC()) { // set core fDirty = true; Core = nCore; // ok then return true; } } // get and search for filename without specified folder (e.g., Castle.ocs when the opened game is Easy.ocf\Castle.ocs) const char *szFilenameOnly = GetFilename(szFilename); const char *szFilenameC4 = GetC4Filename(szFilename); if (szFilenameOnly != szFilenameC4) { sFilename.Copy(szFilename, SLen(szFilename) - SLen(szFilenameC4)); sFilename.Append(szFilenameOnly); if (SetByCore(nCore, fSilent, szFilenameOnly, Config.Network.MaxResSearchRecursion)) return true; } // if it could still not be set, try within all folders of root (ignoring special folders), and try as file outside the folder // but do not recurse any deeper than set by config (default: One folder) if (iRecursion >= Config.Network.MaxResSearchRecursion) return false; StdStrBuf sSearchPath; const char *szSearchPath; if (!iRecursion) szSearchPath = Config.General.ExePath.getData(); else { sSearchPath.Copy(szFilename, SLen(szFilename) - SLen(szFilenameC4)); szSearchPath = sSearchPath.getData(); } StdStrBuf sNetPath; sNetPath.Copy(Config.Network.WorkPath); char *szNetPath = sNetPath.GrabPointer(); TruncateBackslash(szNetPath); sNetPath.Take(szNetPath); for (DirectoryIterator i(szSearchPath); *i; ++i) if (DirectoryExists(*i)) if (!*GetExtension(*i)) // directories without extension only if (!szNetPath || !*szNetPath || !ItemIdentical(*i, szNetPath)) // ignore network path { // search for complete name at subpath (e.g. MyFolder\Easy.ocf\Castle.ocs) sFilename.Format("%s%c%s", *i, DirectorySeparator, szFilenameC4); if (SetByCore(nCore, fSilent, sFilename.getData(), iRecursion + 1)) return true; } // file could not be found locally return false; }
void C4Network2ClientListDlg::Update() { // Compose status text 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.Network.getAvgControlSendTime()); // Update status label pStatusLabel->SetText(sStatusText.getData()); }
void C4Console::UpdateStatusBars() { if (!Active) return; // Frame counter if (Game.FrameCounter!=FrameCounter) { FrameCounter=Game.FrameCounter; StdStrBuf str; str.Format("Frame: %i",FrameCounter); C4ConsoleGUI::DisplayInfoText(CONSOLE_FrameCounter, str); } // Time & FPS if ((Game.Time!=Time) || (Game.FPS!=FPS)) { Time=Game.Time; FPS=Game.FPS; StdStrBuf str; str.Format("%02d:%02d:%02d (%i FPS)",Time/3600,(Time%3600)/60,Time%60,FPS); C4ConsoleGUI::DisplayInfoText(CONSOLE_TimeFPS, str); } }
bool C4VectorFont::Init(C4Group &hGrp, const char *szFilename, C4Config &rCfg) { // name by file Name.Copy(GetFilenameOnly(szFilename)); #if defined(_WIN32) && !defined(HAVE_FREETYPE) // check whether group is directory or packed if (!hGrp.IsPacked()) { // it's open: use the file directly SCopy(hGrp.GetFullName().getData(), FileName, _MAX_PATH); AppendBackslash(FileName); SAppend(szFilename, FileName); if (!FileExists(FileName)) { *FileName=0; return false; } fIsTempFile = false; } else { // it's packed: extract to temp path SCopy(rCfg.AtTempPath(szFilename), FileName, _MAX_PATH); // make sure the filename is not in use, in case multiple instances of the engine are run if (FileExists(FileName)) { RemoveExtension(FileName); StdStrBuf sNewFilename; for (int i=0; i<1000; ++i) { sNewFilename.Format("%s%x", FileName, (int)rand()); if (*GetExtension(szFilename)) { sNewFilename.AppendChar('.'); sNewFilename.Append(GetExtension(szFilename)); } if (!FileExists(sNewFilename.getData())) break; } SCopy(sNewFilename.getData(), FileName, _MAX_PATH); } if (!hGrp.ExtractEntry(szFilename, FileName)) { *FileName=0; return false; } fIsTempFile = true; } // add the font resource //if (!AddFontResourceEx(FileName, FR_PRIVATE, NULL)) requires win2k if (!AddFontResource(FileName)) { if (fIsTempFile) EraseFile(FileName); *FileName='\0'; return false; } #else if (!hGrp.LoadEntry(szFilename, Data)) return false; #endif // success return true; }
bool C4Console::UpdateViewportMenu() { if (!Active) return false; ClearViewportMenu(); for (C4Player *pPlr=::Players.First; pPlr; pPlr=pPlr->Next) { StdStrBuf sText; sText.Format(LoadResStr("IDS_CNS_NEWPLRVIEWPORT"),pPlr->GetName()); C4ConsoleGUI::AddMenuItemForPlayer(pPlr, sText); } return true; }
bool C4Network2IRCClient::Send(const char *szCommand, const char *szParameters) { if(!fConnected) { SetError("not connected"); return false; } // Create message StdStrBuf Msg; if(szParameters) Msg.Format("%s %s", szCommand, szParameters); else Msg.Ref(szCommand); // Send return C4NetIOTCP::Send(C4NetIOPacket(Msg.getData(), Msg.getLength(), false, PeerAddr)); }
void C4EditCursor::UpdateStatusBar() { int32_t X=this->X, Y=this->Y; StdStrBuf str; switch (Mode) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case C4CNS_ModePlay: if (::MouseControl.GetCaption()) str.CopyUntil(::MouseControl.GetCaption(),'|'); break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case C4CNS_ModeEdit: str.Format("%i/%i (%s)",X,Y,Target ? (Target->GetName()) : LoadResStr("IDS_CNS_NOTHING") ); break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - case C4CNS_ModeDraw: str.Format("%i/%i (%s)",X,Y,MatValid(GBackMat(X,Y)) ? ::MaterialMap.Map[GBackMat(X,Y)].Name : LoadResStr("IDS_CNS_NOTHING") ); break; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } Console.DisplayInfoText(C4ConsoleGUI::CONSOLE_Cursor, str); }
void C4StartupMainDlg::DrawElement(C4TargetFacet &cgo) { // inherited typedef C4GUI::FullscreenDialog Base; Base::DrawElement(cgo); // draw logo C4FacetID * fctStartupLogo = &C4Startup::Get()->Graphics.fctStartupLogo; float fLogoZoom = 1.0f; fctStartupLogo->DrawX(cgo.Surface, rcBounds.Wdt *1/21, rcBounds.Hgt/28, int32_t(fLogoZoom*fctStartupLogo->Wdt), int32_t(fLogoZoom*fctStartupLogo->Hgt)); // draw version info StdStrBuf sVer; sVer.Format(LoadResStr("IDS_DLG_VERSION"), C4VERSION); pDraw->TextOut(sVer.getData(), ::GraphicsResource.TextFont, 1.0f, cgo.Surface, rcBounds.Wdt*1/40, rcBounds.Hgt*38/40, 0xffffffff, ALeft, true); }
void C4Console::UpdateNetMenu() { // Active & network hosting check if (!Active) return; if (!::Network.isHost() || !::Network.isEnabled()) return; // Clear old ClearNetMenu(); // Insert menu C4ConsoleGUI::AddNetMenu(); // Host StdStrBuf str; str.Format(LoadResStr("IDS_MNU_NETHOST"),Game.Clients.getLocalName(),Game.Clients.getLocalID()); AddNetMenuItemForPlayer(IDM_NET_CLIENT1+Game.Clients.getLocalID(), str); // Clients for (C4Network2Client *pClient=::Network.Clients.GetNextClient(NULL); pClient; pClient=::Network.Clients.GetNextClient(pClient)) { str.Format(LoadResStr(pClient->isActivated() ? "IDS_MNU_NETCLIENT" : "IDS_MNU_NETCLIENTDE"), pClient->getName(), pClient->getID()); AddNetMenuItemForPlayer(IDM_NET_CLIENT1+pClient->getID(), str); } return; }
GLenum C4Shader::AddTexCoord(const char *szName) { // Make sure we have enough space assert(iTexCoords < C4Shader_MaxTexCoords); if(iTexCoords >= C4Shader_MaxTexCoords) return -1; // Add slices StdStrBuf Code = FormatString("gl_TexCoord[%d] = gl_MultiTexCoord%d;\n", iTexCoords, iTexCoords); AddVertexSlice(C4Shader_Vertex_TexCoordPos, Code.getData()); Code.Format("#define %s gl_TexCoord[%d]\n", szName, iTexCoords); AddFragmentSlice(-1, Code.getData()); return GL_TEXTURE0 + iTexCoords++; }
BOOL OpenLog() { // open sLogFileName = C4CFN_Log; int iLog = 2; #ifdef _WIN32 while (!(C4LogFile = _fsopen(sLogFileName.getData(), "wt", _SH_DENYWR))) #else while (!(C4LogFile = fopen(sLogFileName.getData(), "wb"))) #endif { // try different name sLogFileName.Format(C4CFN_LogEx, iLog++); } // save start time time(&C4LogStartTime); return true; }
bool C4MainMenu::ActivateGoals(int32_t iPlayer, bool fDoActivate) { C4FacetSurface fctSymbol; C4Facet fctGF; // goal fulfilled facet if (fDoActivate) { // Menu symbol/init InitRefSym(GfxR->fctMenu.GetPhase(4),LoadResStr("IDS_MENU_CPGOALS"),iPlayer); SetAlignment(C4MN_Align_Left | C4MN_Align_Bottom); SetPermanent(false); fctGF.Set(NULL, C4SymbolSize-::GraphicsResource.fctCaptain.Wdt-2, 2, ::GraphicsResource.fctCaptain.Wdt, ::GraphicsResource.fctCaptain.Hgt); } // determine if the goals are fulfilled - do the calls even if the menu is not to be opened to ensure synchronization C4IDList GoalList, FulfilledGoalList; C4RoundResults::EvaluateGoals(GoalList, FulfilledGoalList, iPlayer); // Add Items if (fDoActivate) { int32_t iNumGoals = GoalList.GetNumberOfIDs(), cnt; C4ID idGoal; C4Def *pDef; for (int32_t i=0; i<iNumGoals; ++i) if ((idGoal = GoalList.GetID(i, &cnt))) if ((pDef = C4Id2Def(idGoal))) { fctSymbol.Create(C4SymbolSize,C4SymbolSize); // 2do: If an object instance is known, draw the object instead? // this would allow us to do dynamic pictures and overlays; e.g. draw the actual, required settlement score // for settlement score goals // Same for pDef->GetName(), pDef->GetDesc() pDef->Draw(fctSymbol); if (FulfilledGoalList.GetIDCount(idGoal)) { fctGF.Surface=fctSymbol.Surface; ::GraphicsResource.fctCaptain.Draw(fctGF); } StdStrBuf Command; Command.Format("Player:Goal:%s", idGoal.ToString()); Add(pDef->GetName(),fctSymbol,Command.getData(),C4MN_Item_NoCount,NULL,""); } // Go back to options menu on close SetCloseCommand("ActivateMenu:Main"); } // Done return true; }
StdStrBuf C4RankSystem::GetRankName(int iRank, bool fReturnLastIfOver) { if (iRank<0) return StdStrBuf(); // if a new-style ranklist is loaded, seek there if (pszRankNames) { if (iRankNum<=0) return StdStrBuf(); // overflow check if (iRank>=iRankNum*(iRankExtNum+1)) { // rank undefined: Fallback to last rank if (!fReturnLastIfOver) return StdStrBuf(); iRank = iRankNum*(iRankExtNum+1)-1; } StdStrBuf sResult; if (iRank >= iRankNum) { // extended rank composed of two parts int iExtension = iRank / iRankNum - 1; iRank = iRank % iRankNum; sResult.Format(pszRankExtensions[iExtension], pszRankNames[iRank]); } else { // simple rank sResult.Ref(pszRankNames[iRank]); } return sResult; } #ifdef _WIN32 // old-style registry fallback while (iRank>=0) { char keyname[30]; StdCopyStrBuf rankname; sprintf(keyname,"Rank%03d",iRank+1); rankname = GetRegistryString(Register,keyname); if (!rankname.isNull()) return rankname; if (!fReturnLastIfOver) return StdStrBuf(); --iRank; } #endif return StdStrBuf(); }
bool C4MainMenu::ActivateNewPlayer(int32_t iPlayer) { // league or replay game if (Game.Parameters.isLeague() || Game.C4S.Head.Replay) return false; // Max player limit if (::Players.GetCount() >= Game.Parameters.MaxPlayers) return false; // Menu symbol/init if (GfxR->fctPlayerClr.Surface) GfxR->fctPlayerClr.Surface->SetClr(0xff); InitRefSym(GfxR->fctPlayerClr, LoadResStr("IDS_MENU_NOPLRFILES"), iPlayer); for (DirectoryIterator iter(Config.General.UserDataPath); *iter; ++iter) if (WildcardMatch("*.ocp", *iter)) { char szFilename[_MAX_PATH+1], szCommand[_MAX_PATH+30+1]; SCopy(*iter, szFilename, _MAX_PATH); if (DirectoryExists(szFilename)) continue; if (::Players.FileInUse(szFilename)) continue; // Open group C4Group hGroup; if (!hGroup.Open(szFilename)) continue; // Load player info C4PlayerInfoCore C4P; if (!C4P.Load(hGroup)) { hGroup.Close(); continue; } // Close group hGroup.Close(); // Add player item sprintf(szCommand, "JoinPlayer:%s", szFilename); StdStrBuf sItemText; sItemText.Format(LoadResStr("IDS_MENU_NEWPLAYER"), C4P.PrefName); C4FacetSurface fctSymbol; // Add menu item Add(sItemText.getData(), fctSymbol, szCommand); // Reset symbol facet (menu holds on to the surface) fctSymbol.Default(); } // Alignment SetAlignment(C4MN_Align_Left | C4MN_Align_Bottom); // Go back to options menu on close SetCloseCommand("ActivateMenu:Main"); return true; }