Automatic fixes using clang-tidy

See http://forum.openclonk.org/topic_show.pl?tid=3376 for discussion.

Close GH-41
alut-include-path
Tushar Maheshwari 2017-05-03 20:28:00 +02:00 committed by Lukas Werling
parent d750a57410
commit e58a7884e4
162 changed files with 1245 additions and 1403 deletions

View File

@ -23,21 +23,17 @@
#include "game/C4Game.h"
#include "lib/C4Log.h"
C4Extra::C4Extra()
{
}
C4Extra::C4Extra() = default;
C4Extra::~C4Extra()
{
}
C4Extra::~C4Extra() = default;
bool C4Extra::InitGroup()
{
// register extra root into game group set
for(C4Reloc::iterator iter = Reloc.begin(); iter != Reloc.end(); ++iter)
for(const auto & iter : Reloc)
{
std::unique_ptr<C4Group> pGroup(new C4Group);
if(pGroup->Open( ((*iter).strBuf + DirSep + C4CFN_Extra).getData()))
if(pGroup->Open( (iter.strBuf + DirSep + C4CFN_Extra).getData()))
ExtraGroups.emplace_back(std::move(pGroup));
}
@ -55,9 +51,9 @@ bool C4Extra::Init()
char szSegment[_MAX_PATH+1];
for (int cseg=0; SCopySegment(Game.DefinitionFilenames,cseg,szSegment,';',_MAX_PATH); cseg++)
{
for(unsigned int i = 0; i < ExtraGroups.size(); ++i)
for(auto & ExtraGroup : ExtraGroups)
{
if(LoadDef(*ExtraGroups[i], GetFilename(szSegment)))
if(LoadDef(*ExtraGroup, GetFilename(szSegment)))
{
break;
}

View File

@ -551,7 +551,7 @@ bool C4Group::Open(const char *szGroupName, bool fCreate)
char szRealGroup[_MAX_FNAME];
SCopy(szGroupNameN,szRealGroup,_MAX_FNAME);
do
{ if (!TruncatePath(szRealGroup)) return Error(FormatString("Open(\"%s\"): File not found", szGroupNameN).getData()); }
{ if (!TruncatePath(szRealGroup)) return Error(FormatString(R"(Open("%s"): File not found)", szGroupNameN).getData()); }
while (!FileExists(szRealGroup));
// Open mother and child in exclusive mode

View File

@ -569,7 +569,7 @@ int main(int argc, char *argv[])
break;
// Child process
case 0:
execl(strExecuteAtEnd, strExecuteAtEnd, static_cast<char *>(0)); // currently no parameters are passed to the executed program
execl(strExecuteAtEnd, strExecuteAtEnd, static_cast<char *>(nullptr)); // currently no parameters are passed to the executed program
exit(1);
// Parent process
default:

View File

@ -192,7 +192,7 @@ C4Group *C4GroupSet::FindEntry(const char *szWildcard, int32_t *pPriority, int32
C4Group *C4GroupSet::FindSuitableFile(const char *szName, const char * const extensions[], char *szFileName, int32_t *pID)
{
C4Group *pGrp = 0;
C4Group *pGrp = nullptr;
C4Group *pGrp2;
int iPrio = -1;
int32_t iPrio2;

View File

@ -68,7 +68,7 @@ void C4LangStringTable::PopulateStringTable() const
else if (*data == '\0' || *data == '\n' || *data == '\r')
{
if (!key.empty() && key[0]!='#')
LogF("%s: string table entry without a value: \"%s\"", GetFilePath() ? GetFilePath() : "<unknown>", key.c_str());
LogF(R"(%s: string table entry without a value: "%s")", GetFilePath() ? GetFilePath() : "<unknown>", key.c_str());
key.clear();
}
else
@ -134,7 +134,7 @@ void C4LangStringTable::ReplaceStrings(const StdStrBuf &rBuf, StdStrBuf &rTarget
}
catch (NoSuchTranslation &)
{
LogF("%s: string table entry not found: \"%s\"", GetFilePath() ? GetFilePath() : "<unknown>", szStringName);
LogF(R"(%s: string table entry not found: "%s")", GetFilePath() ? GetFilePath() : "<unknown>", szStringName);
}
}
// Alloc new Buffer

View File

@ -320,7 +320,7 @@ void C4Language::LoadInfos(C4Group &hGroup)
// of the same code - the system always loads the first string table found for a given code
if (!FindInfo(GetFilenameOnly(strEntry) + SLen(GetFilenameOnly(strEntry)) - 2))
// Load language string table
if (hGroup.LoadEntry(strEntry, &strTable, 0, 1))
if (hGroup.LoadEntry(strEntry, &strTable, nullptr, 1))
{
// New language info
C4LanguageInfo *pInfo = new C4LanguageInfo;

View File

@ -27,11 +27,11 @@
#include <zlib.h>
#include "zlib/gzio.h"
#include <stdio.h>
#include <cstdio>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <cassert>
CStdFile::CStdFile()
{

View File

@ -38,7 +38,7 @@
#include <sys/types.h>
#endif
#ifdef HAVE_LOCALE_H
#include <locale.h>
#include <clocale>
#endif
#ifdef USE_CONSOLE
@ -213,7 +213,7 @@ void C4ConfigSecurity::CompileFunc(StdCompiler *pComp)
{
pComp->Value(mkNamingAdapt(WasRegistered, "WasRegistered", 0 ));
#ifdef _WIN32
pComp->Value(mkNamingAdapt(s(KeyPath), "KeyPath", "%APPDATA%\\" C4ENGINENAME, false, true));
pComp->Value(mkNamingAdapt(s(KeyPath), "KeyPath", R"(%APPDATA%\)" C4ENGINENAME, false, true));
#elif defined(__linux__)
pComp->Value(mkNamingAdapt(s(KeyPath), "KeyPath", "$HOME/.clonk/" C4ENGINENICK, false, true));
#elif defined(__APPLE__)
@ -498,7 +498,7 @@ void C4ConfigGeneral::DeterminePaths()
SCopy(ConfigUserPath, UserDataPath);
else
#if defined(_WIN32)
SCopy("%APPDATA%\\" C4ENGINENAME, UserDataPath);
SCopy(R"(%APPDATA%\)" C4ENGINENAME, UserDataPath);
#elif defined(__APPLE__)
SCopy("$HOME/Library/Application Support/" C4ENGINENAME, UserDataPath);
#else
@ -718,7 +718,7 @@ const char* C4Config::GetSubkeyPath(const char *strSubkey)
{
static char key[1024 + 1];
#ifdef _WIN32
sprintf(key, "Software\\%s\\%s\\%s", C4CFG_Company, C4ENGINENAME, strSubkey);
sprintf(key, R"(Software\%s\%s\%s)", C4CFG_Company, C4ENGINENAME, strSubkey);
#else
sprintf(key, "%s", strSubkey);
#endif

View File

@ -52,7 +52,7 @@ bool C4Reloc::AddPath(const char* path, PathType pathType)
if(std::find(Paths.begin(), Paths.end(), path) != Paths.end())
return false;
Paths.push_back(PathInfo(StdCopyStrBuf(path), pathType));
Paths.emplace_back(StdCopyStrBuf(path), pathType);
return true;
}
@ -70,8 +70,8 @@ bool C4Reloc::Open(C4Group& hGroup, const char* filename) const
{
if(IsGlobalPath(filename)) return hGroup.Open(filename);
for(iterator iter = begin(); iter != end(); ++iter)
if(hGroup.Open(((*iter).strBuf + DirSep + filename).getData()))
for(const auto & iter : *this)
if(hGroup.Open((iter.strBuf + DirSep + filename).getData()))
return true;
return false;
@ -85,9 +85,9 @@ bool C4Reloc::LocateItem(const char* filename, StdStrBuf& str) const
return true;
}
for(iterator iter = begin(); iter != end(); ++iter)
for(const auto & iter : *this)
{
str.Copy((*iter).strBuf + DirSep + filename);
str.Copy(iter.strBuf + DirSep + filename);
if(ItemExists(str.getData()))
return true;
}

View File

@ -59,10 +59,7 @@ C4ControlPacket::C4ControlPacket()
}
C4ControlPacket::~C4ControlPacket()
{
}
C4ControlPacket::~C4ControlPacket() = default;
bool C4ControlPacket::LocalControl() const
{
@ -82,10 +79,7 @@ void C4ControlPacket::CompileFunc(StdCompiler *pComp)
// *** C4Control
C4Control::C4Control()
{
}
C4Control::C4Control() = default;
C4Control::~C4Control()
{
@ -540,7 +534,7 @@ void C4ControlMenuCommand::Execute() const
// menu was closed?
if (!menu) return;
C4Object *obj = target ? ::Objects.ObjectPointer(target) : 0;
C4Object *obj = target ? ::Objects.ObjectPointer(target) : nullptr;
// target has been removed in the meantime? abort now
if (target && !obj) return;
@ -751,9 +745,7 @@ void C4ControlPlayerAction::CompileFunc(StdCompiler *pComp)
// *** C4ControlSyncCheck
C4ControlSyncCheck::C4ControlSyncCheck()
{
}
C4ControlSyncCheck::C4ControlSyncCheck() = default;
void C4ControlSyncCheck::Set()
{
@ -1012,9 +1004,9 @@ void C4ControlClientRemove::CompileFunc(StdCompiler *pComp)
// *** C4ControlJoinPlayer
C4ControlJoinPlayer::C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo, const C4Network2ResCore &ResCore)
C4ControlJoinPlayer::C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo, C4Network2ResCore ResCore)
: Filename(szFilename, true), iAtClient(iAtClient),
idInfo(iIDInfo), fByRes(true), ResCore(ResCore)
idInfo(iIDInfo), fByRes(true), ResCore(std::move(ResCore))
{
}

View File

@ -428,7 +428,7 @@ struct C4ControlJoinPlayer : public C4ControlPacket // sync
{
public:
C4ControlJoinPlayer() : iAtClient(-1), idInfo(-1), fByRes(false) { }
C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo, const C4Network2ResCore &ResCore);
C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo, C4Network2ResCore ResCore);
C4ControlJoinPlayer(const char *szFilename, int32_t iAtClient, int32_t iIDInfo);
protected:
StdStrBuf Filename;

View File

@ -374,15 +374,9 @@ void C4GameResList::CompileFunc(StdCompiler *pComp)
// *** C4GameParameters
C4GameParameters::C4GameParameters()
{
C4GameParameters::C4GameParameters() = default;
}
C4GameParameters::~C4GameParameters()
{
}
C4GameParameters::~C4GameParameters() = default;
void C4GameParameters::Clear()
{

View File

@ -77,7 +77,7 @@ bool C4GameSave::SaveCore()
rC4S.Head.RandomSeed=Game.RandomSeed;
}
// reset some network flags
rC4S.Head.NetworkGame=0;
rC4S.Head.NetworkGame=false;
// Title in language game was started in (not: save scenarios and net references)
if (!GetKeepTitle())
{

View File

@ -135,9 +135,8 @@ void C4PlayerControlDefs::MergeFrom(const C4PlayerControlDefs &Src)
// Clear previous defs if specified in merge set
if (Src.clear_previous) Defs.clear();
// copy all defs from source file; overwrite defs of same name if found
for (DefVecImpl::const_iterator i = Src.Defs.begin(); i != Src.Defs.end(); ++i)
for (const auto & SrcDef : Src.Defs)
{
const C4PlayerControlDef &SrcDef = *i;
// overwrite if def of same name existed
int32_t iPrevIdx = GetControlIndexByIdentifier(SrcDef.GetIdentifier());
if (iPrevIdx != CON_None)
@ -285,9 +284,8 @@ bool C4PlayerControlAssignment::ResolveRefs(C4PlayerControlAssignmentSet *pParen
iControl = pControlDefs->GetControlIndexByIdentifier(sControlName.getData());
// resolve keys
KeyComboVec NewCombo;
for (KeyComboVec::iterator i = KeyCombo.begin(); i != KeyCombo.end(); ++i)
for (auto & rKeyComboItem : KeyCombo)
{
KeyComboItem &rKeyComboItem = *i;
const char *szKeyName = rKeyComboItem.sKeyName.getData();
// check if this is a key reference. A key reference must be preceded by CON_
// it may also be preceded by modifiers (Shift+), which are already set in rKeyComboItem.Key.dwShift
@ -316,9 +314,8 @@ bool C4PlayerControlAssignment::ResolveRefs(C4PlayerControlAssignmentSet *pParen
DWORD ref_shift = rKeyComboItem.Key.dwShift;
if (ref_shift)
{
for (KeyComboVec::iterator j = pRefAssignment->KeyCombo.begin(); j != pRefAssignment->KeyCombo.end(); ++j)
for (auto assignment_combo_item : pRefAssignment->KeyCombo)
{
KeyComboItem assignment_combo_item = *j;
assignment_combo_item.Key.dwShift |= ref_shift;
NewCombo.push_back(assignment_combo_item);
}
@ -340,7 +337,7 @@ bool C4PlayerControlAssignment::ResolveRefs(C4PlayerControlAssignmentSet *pParen
// non-reference: check if the assignment was valid
#ifndef USE_CONSOLE
if (rKeyComboItem.Key == KEY_Default)
LogF("WARNING: Control %s of set %s contains undefined key \"%s\".", GetControlName(), pParentSet->GetName(), szKeyName);
LogF(R"(WARNING: Control %s of set %s contains undefined key "%s".)", GetControlName(), pParentSet->GetName(), szKeyName);
#endif
// ...and just keep this item.
NewCombo.push_back(rKeyComboItem);
@ -352,16 +349,16 @@ bool C4PlayerControlAssignment::ResolveRefs(C4PlayerControlAssignmentSet *pParen
if (KeyCombo.size() > 1 && !fComboIsSequence)
{
int32_t shift = 0;
for (KeyComboVec::iterator i = KeyCombo.begin(); i != KeyCombo.end(); ++i)
for (auto & i : KeyCombo)
{
if (i->Key.Key == K_CONTROL_L || i->Key.Key == K_CONTROL_R) shift |= KEYS_Control;
if (i->Key.Key == K_SHIFT_L || i->Key.Key == K_SHIFT_R) shift |= KEYS_Shift;
shift |= i->Key.dwShift;
if (i.Key.Key == K_CONTROL_L || i.Key.Key == K_CONTROL_R) shift |= KEYS_Control;
if (i.Key.Key == K_SHIFT_L || i.Key.Key == K_SHIFT_R) shift |= KEYS_Shift;
shift |= i.Key.dwShift;
}
for (KeyComboVec::iterator i = KeyCombo.begin(); i != KeyCombo.end(); ++i) i->Key.dwShift |= shift;
for (auto & i : KeyCombo) i.Key.dwShift |= shift;
}
// remove control/shift duplications
for (KeyComboVec::iterator i = KeyCombo.begin(); i != KeyCombo.end(); ++i) i->Key.FixShiftKeys();
for (auto & i : KeyCombo) i.Key.FixShiftKeys();
// the trigger key is always last of the chain
if (KeyCombo.size()) TriggerKey = KeyCombo.back().Key; else TriggerKey = C4KeyCodeEx();
// done
@ -379,8 +376,8 @@ bool C4PlayerControlAssignment::IsComboMatched(const C4PlayerControlRecentKeyLis
C4TimeMilliseconds tKeyLast = C4TimeMilliseconds::Now();
// combo is a sequence: The last keys of RecentKeys must match the sequence
// the last ComboKey is the TriggerKey, which is omitted because it has already been matched and is not to be found in RecentKeys yet
KeyComboVec::const_reverse_iterator i = KeyCombo.rbegin()+1;
for (C4PlayerControlRecentKeyList::const_reverse_iterator ri = RecentKeys.rbegin(); i!=KeyCombo.rend(); ++ri)
auto i = KeyCombo.rbegin()+1;
for (auto ri = RecentKeys.rbegin(); i!=KeyCombo.rend(); ++ri)
{
// no more keys pressed but combo didn't end? -> no combo match
if (ri == RecentKeys.rend()) return false;
@ -403,13 +400,11 @@ bool C4PlayerControlAssignment::IsComboMatched(const C4PlayerControlRecentKeyLis
else
{
// combo requires keys to be down simultanuously: check that all keys of the combo are in the down-list
for (KeyComboVec::const_iterator i = KeyCombo.begin(); i!=KeyCombo.end(); ++i)
for (const auto & k : KeyCombo)
{
const KeyComboItem &k = *i;
bool fFound = false;
for (C4PlayerControlRecentKeyList::const_iterator di = DownKeys.begin(); di!=DownKeys.end(); ++di)
for (const auto & dk : DownKeys)
{
const C4PlayerControlRecentKey &dk = *di;
if (dk.matched_key == k.Key) { fFound = true; break; }
}
if (!fFound) return false;
@ -517,9 +512,8 @@ void C4PlayerControlAssignmentSet::CompileFunc(StdCompiler *pComp)
void C4PlayerControlAssignmentSet::MergeFrom(const C4PlayerControlAssignmentSet &Src, MergeMode merge_mode)
{
// take over all assignments defined in Src
for (C4PlayerControlAssignmentVec::const_iterator i = Src.Assignments.begin(); i != Src.Assignments.end(); ++i)
for (const auto & SrcAssignment : Src.Assignments)
{
const C4PlayerControlAssignment &SrcAssignment = *i;
bool fIsReleaseKey = !!(SrcAssignment.GetTriggerMode() & C4PlayerControlAssignment::CTM_Release);
// overwrite same def and release key state
if (merge_mode != MM_LowPrio && SrcAssignment.IsOverrideAssignments())
@ -546,18 +540,18 @@ void C4PlayerControlAssignmentSet::MergeFrom(const C4PlayerControlAssignmentSet
{
// if this is low priority, another override control kills this
bool any_override = false;
for (C4PlayerControlAssignmentVec::iterator j = Assignments.begin(); j != Assignments.end(); ++j)
if (SEqual((*j).GetControlName(), SrcAssignment.GetControlName()))
for (auto & Assignment : Assignments)
if (SEqual(Assignment.GetControlName(), SrcAssignment.GetControlName()))
{
bool fSelfIsReleaseKey = !!((*j).GetTriggerMode() & C4PlayerControlAssignment::CTM_Release);
bool fSelfIsReleaseKey = !!(Assignment.GetTriggerMode() & C4PlayerControlAssignment::CTM_Release);
if (fSelfIsReleaseKey == fIsReleaseKey)
{
any_override = true;
// config overloads just change the key of the inherited assignment
if (merge_mode == MM_ConfigOverload)
{
(*j).CopyKeyFrom(SrcAssignment);
(*j).SetInherited(false);
Assignment.CopyKeyFrom(SrcAssignment);
Assignment.SetInherited(false);
}
break;
}
@ -577,7 +571,7 @@ void C4PlayerControlAssignmentSet::MergeFrom(const C4PlayerControlAssignmentSet
C4PlayerControlAssignment *C4PlayerControlAssignmentSet::CreateAssignmentForControl(const char *control_name)
{
Assignments.push_back(C4PlayerControlAssignment());
Assignments.emplace_back();
Assignments.back().SetControlName(control_name);
return &Assignments.back();
}
@ -595,12 +589,12 @@ void C4PlayerControlAssignmentSet::RemoveAssignmentByControlName(const char *con
bool C4PlayerControlAssignmentSet::ResolveRefs(C4PlayerControlDefs *pDefs)
{
// reset all resolved flags to allow re-resolve after overloads
for (C4PlayerControlAssignmentVec::iterator i = Assignments.begin(); i != Assignments.end(); ++i)
(*i).ResetRefsResolved();
for (auto & Assignment : Assignments)
Assignment.ResetRefsResolved();
// resolve in order; ignore already resolved because they might have been resolved by cross reference
for (C4PlayerControlAssignmentVec::iterator i = Assignments.begin(); i != Assignments.end(); ++i)
if (!(*i).IsRefsResolved())
if (!(*i).ResolveRefs(this, pDefs))
for (auto & Assignment : Assignments)
if (!Assignment.IsRefsResolved())
if (!Assignment.ResolveRefs(this, pDefs))
return false;
return true;
}
@ -620,22 +614,22 @@ C4PlayerControlAssignment *C4PlayerControlAssignmentSet::GetAssignmentByIndex(in
C4PlayerControlAssignment *C4PlayerControlAssignmentSet::GetAssignmentByControlName(const char *szControlName)
{
for (C4PlayerControlAssignmentVec::iterator i = Assignments.begin(); i != Assignments.end(); ++i)
if (SEqual((*i).GetControlName(), szControlName))
for (auto & Assignment : Assignments)
if (SEqual(Assignment.GetControlName(), szControlName))
// We don't like release keys... (2do)
if (!((*i).GetTriggerMode() & C4PlayerControlAssignment::CTM_Release))
return &*i;
if (!(Assignment.GetTriggerMode() & C4PlayerControlAssignment::CTM_Release))
return &Assignment;
return nullptr;
}
C4PlayerControlAssignment *C4PlayerControlAssignmentSet::GetAssignmentByControl(int32_t control)
{
// TODO: Might want to stuff this into a vector indexed by control for faster lookup
for (C4PlayerControlAssignmentVec::iterator i = Assignments.begin(); i != Assignments.end(); ++i)
if ((*i).GetControl() == control)
for (auto & Assignment : Assignments)
if (Assignment.GetControl() == control)
// We don't like release keys... (2do)
if (!((*i).GetTriggerMode() & C4PlayerControlAssignment::CTM_Release))
return &*i;
if (!(Assignment.GetTriggerMode() & C4PlayerControlAssignment::CTM_Release))
return &Assignment;
return nullptr;
}
@ -649,9 +643,8 @@ void C4PlayerControlAssignmentSet::GetAssignmentsByKey(const C4PlayerControlDefs
{
assert(pOutVec);
// primary match by TriggerKey (todo: Might use a hash map here if matching speed becomes an issue due to large control sets)
for (C4PlayerControlAssignmentVec::const_iterator i = Assignments.begin(); i != Assignments.end(); ++i)
for (const auto & rAssignment : Assignments)
{
const C4PlayerControlAssignment &rAssignment = *i;
const C4KeyCodeEx &rAssignmentTriggerKey = rAssignment.GetTriggerKey();
if (!(rAssignmentTriggerKey.Key == key.Key)) continue;
// special: hold-keys-only ignore shift, because shift state might have been release during hold
@ -680,9 +673,8 @@ void C4PlayerControlAssignmentSet::GetTriggerKeys(const C4PlayerControlDefs &rDe
{
// put all trigger keys of keyset into output vectors
// first all hold keys
for (C4PlayerControlAssignmentVec::const_iterator i = Assignments.begin(); i != Assignments.end(); ++i)
for (const auto & rAssignment : Assignments)
{
const C4PlayerControlAssignment &rAssignment = *i;
const C4PlayerControlDef *pDef = rDefs.GetControlByIndex(rAssignment.GetControl());
if (pDef && pDef->IsHoldKey())
{
@ -691,9 +683,8 @@ void C4PlayerControlAssignmentSet::GetTriggerKeys(const C4PlayerControlDefs &rDe
}
}
// then all regular keys that aren't in the hold keys list yet
for (C4PlayerControlAssignmentVec::const_iterator i = Assignments.begin(); i != Assignments.end(); ++i)
for (const auto & rAssignment : Assignments)
{
const C4PlayerControlAssignment &rAssignment = *i;
const C4PlayerControlDef *pDef = rDefs.GetControlByIndex(rAssignment.GetControl());
if (pDef && !pDef->IsHoldKey())
{
@ -749,9 +740,8 @@ void C4PlayerControlAssignmentSets::MergeFrom(const C4PlayerControlAssignmentSet
// if source set is flagged to clear previous, do this!
if (Src.clear_previous) Sets.clear();
// take over all assignments in known sets and new sets defined in Src
for (AssignmentSetList::const_iterator i = Src.Sets.begin(); i != Src.Sets.end(); ++i)
for (const auto & SrcSet : Src.Sets)
{
const C4PlayerControlAssignmentSet &SrcSet = *i;
// overwrite if def of same name existed if it's not low priority anyway
bool fIsWildcardSet = SrcSet.IsWildcardName();
if (!fIsWildcardSet)
@ -775,9 +765,8 @@ void C4PlayerControlAssignmentSets::MergeFrom(const C4PlayerControlAssignmentSet
else
{
// source is a wildcard: Merge with all matching sets
for (AssignmentSetList::iterator j = Sets.begin(); j != Sets.end(); ++j)
for (auto & DstSet : Sets)
{
C4PlayerControlAssignmentSet &DstSet = *j;
if (WildcardMatch(SrcSet.GetName(), DstSet.GetName()))
{
DstSet.MergeFrom(SrcSet, merge_mode);
@ -789,22 +778,22 @@ void C4PlayerControlAssignmentSets::MergeFrom(const C4PlayerControlAssignmentSet
bool C4PlayerControlAssignmentSets::ResolveRefs(C4PlayerControlDefs *pDefs)
{
for (AssignmentSetList::iterator i = Sets.begin(); i != Sets.end(); ++i)
if (!(*i).ResolveRefs(pDefs)) return false;
for (auto & Set : Sets)
if (!Set.ResolveRefs(pDefs)) return false;
return true;
}
void C4PlayerControlAssignmentSets::SortAssignments()
{
for (AssignmentSetList::iterator i = Sets.begin(); i != Sets.end(); ++i)
(*i).SortAssignments();
for (auto & Set : Sets)
Set.SortAssignments();
}
C4PlayerControlAssignmentSet *C4PlayerControlAssignmentSets::GetSetByName(const char *szName)
{
for (AssignmentSetList::iterator i = Sets.begin(); i != Sets.end(); ++i)
if (WildcardMatch(szName, (*i).GetName()))
return &*i;
for (auto & Set : Sets)
if (WildcardMatch(szName, Set.GetName()))
return &Set;
return nullptr;
}
@ -837,7 +826,7 @@ C4PlayerControlAssignmentSet *C4PlayerControlAssignmentSets::GetSetByIndex(int32
C4PlayerControlAssignmentSet *C4PlayerControlAssignmentSets::CreateEmptySetByTemplate(const C4PlayerControlAssignmentSet &template_set)
{
Sets.push_back(C4PlayerControlAssignmentSet());
Sets.emplace_back();
Sets.back().InitEmptyFromTemplate(template_set);
return &Sets.back();
}
@ -1378,7 +1367,7 @@ void C4PlayerControl::Clear()
{
iPlr = NO_OWNER;
pControlSet = nullptr;
for (KeyBindingList::iterator i = KeyBindings.begin(); i != KeyBindings.end(); ++i) delete *i;
for (auto & KeyBinding : KeyBindings) delete KeyBinding;
KeyBindings.clear();
RecentKeys.clear();
DownKeys.clear();

View File

@ -106,9 +106,7 @@ C4Record::C4Record()
{
}
C4Record::~C4Record()
{
}
C4Record::~C4Record() = default;
bool C4Record::Start(bool fInitial)
{
@ -493,19 +491,19 @@ bool C4Playback::Open(C4Group &rGrp)
{
if (!DbgRecFile.Create(Config.General.DebugRecExternalFile))
{
LogFatal(FormatString("DbgRec: Creation of external file \"%s\" failed!", Config.General.DebugRecExternalFile).getData());
LogFatal(FormatString(R"(DbgRec: Creation of external file "%s" failed!)", Config.General.DebugRecExternalFile).getData());
return false;
}
else LogF("DbgRec: Writing to \"%s\"...", Config.General.DebugRecExternalFile);
else LogF(R"(DbgRec: Writing to "%s"...)", Config.General.DebugRecExternalFile);
}
else
{
if (!DbgRecFile.Open(Config.General.DebugRecExternalFile))
{
LogFatal(FormatString("DbgRec: Opening of external file \"%s\" failed!", Config.General.DebugRecExternalFile).getData());
LogFatal(FormatString(R"(DbgRec: Opening of external file "%s" failed!)", Config.General.DebugRecExternalFile).getData());
return false;
}
else LogF("DbgRec: Checking against \"%s\"...", Config.General.DebugRecExternalFile);
else LogF(R"(DbgRec: Checking against "%s"...)", Config.General.DebugRecExternalFile);
}
}
// ok
@ -625,7 +623,7 @@ void C4Playback::NextChunk()
// end of all chunks if not loading sequential here
if (!fLoadSequential) return;
// otherwise, get next few chunks
for (chunks_t::iterator i = chunks.begin(); i != chunks.end(); i++) i->Delete();
for (auto & chunk : chunks) chunk.Delete();
chunks.clear(); currChunk = chunks.end();
NextSequentialChunk();
}
@ -920,7 +918,7 @@ void C4Playback::Finish()
void C4Playback::Clear()
{
// free stuff
for (chunks_t::iterator i = chunks.begin(); i != chunks.end(); i++) i->Delete();
for (auto & chunk : chunks) chunk.Delete();
chunks.clear(); currChunk = chunks.end();
playbackFile.Close();
sequentialBuffer.Clear();

View File

@ -56,9 +56,7 @@ C4Console::C4Console(): C4ConsoleGUI()
#endif
}
C4Console::~C4Console()
{
}
C4Console::~C4Console() = default;
C4Window * C4Console::Init(C4AbstractApp * pApp)
{
@ -416,14 +414,14 @@ void C4Console::ClearPointers(C4Object *pObj)
void C4Console::Default()
{
EditCursor.Default();
PropertyDlgObject = 0;
PropertyDlgObject = nullptr;
ToolsDlg.Default();
}
void C4Console::Clear()
{
if (pSurface) delete pSurface;
pSurface = 0;
pSurface = nullptr;
C4Window::Clear();
C4ConsoleGUI::DeleteConsoleWindow();
@ -635,8 +633,8 @@ std::list<const char *> C4Console::GetScriptSuggestions(C4PropList *target, Rece
functions.insert(functions.begin(), nullptr);
// add pointers into string buffer list
// do not iterate with for (auto i : mru) because this would copy the buffer and add stack pointers
for (auto i = mru.begin(); i != mru.end(); ++i)
functions.insert(functions.begin(), i->getData());
for (const auto & i : mru)
functions.insert(functions.begin(), i.getData());
}
return functions;
}
@ -647,7 +645,7 @@ void C4Console::RegisterRecentInput(const char *input, RecentScriptInputLists se
// remove previous copy (i.e.: Same input just gets pushed to top)
mru.remove(StdCopyStrBuf(input));
// register to list
mru.push_back(StdCopyStrBuf(input));
mru.emplace_back(input);
// limit history length
if (static_cast<int32_t>(mru.size()) > ::Config.Developer.MaxScriptMRU)
mru.erase(mru.begin());
@ -669,7 +667,7 @@ void C4ConsoleGUI::AddMenuItemForPlayer(C4Player*, StdStrBuf&) {}
void C4ConsoleGUI::AddNetMenuItemForPlayer(int32_t, const char *, C4ConsoleGUI::ClientOperation) {}
void C4ConsoleGUI::AddNetMenu() {}
void C4ConsoleGUI::ToolsDlgClose() {}
bool C4ConsoleGUI::ClearLog() {return 0;}
bool C4ConsoleGUI::ClearLog() {return false;}
void C4ConsoleGUI::ClearNetMenu() {}
void C4ConsoleGUI::ClearPlayerMenu() {}
void C4ConsoleGUI::ClearViewportMenu() {}
@ -683,11 +681,11 @@ bool C4ConsoleGUI::CreateConsoleWindow(C4AbstractApp * pApp)
void C4ConsoleGUI::DeleteConsoleWindow() {}
void C4ConsoleGUI::DisplayInfoText(C4ConsoleGUI::InfoTextType, StdStrBuf&) {}
void C4ConsoleGUI::DoEnableControls(bool) {}
bool C4ConsoleGUI::DoUpdateHaltCtrls(bool) {return 0;}
bool C4ConsoleGUI::FileSelect(StdStrBuf *, char const*, DWORD, bool) {return 0;}
bool C4ConsoleGUI::Message(char const*, bool) {return 0;}
bool C4ConsoleGUI::DoUpdateHaltCtrls(bool) {return false;}
bool C4ConsoleGUI::FileSelect(StdStrBuf *, char const*, DWORD, bool) {return false;}
bool C4ConsoleGUI::Message(char const*, bool) {return false;}
void C4ConsoleGUI::Out(char const*) {}
bool C4ConsoleGUI::PropertyDlgOpen() {return 0;}
bool C4ConsoleGUI::PropertyDlgOpen() {return false;}
void C4ConsoleGUI::PropertyDlgClose() {}
void C4ConsoleGUI::PropertyDlgUpdate(class C4EditCursorSelection &, bool) {}
void C4ConsoleGUI::RecordingEnabled() {}
@ -696,22 +694,22 @@ void C4ConsoleGUI::SetCursor(C4ConsoleGUI::Cursor) {}
void C4ConsoleGUI::SetInputFunctions(std::list<const char*>&) {}
void C4ConsoleGUI::ShowAboutWithCopyright(StdStrBuf&) {}
void C4ConsoleGUI::ToolsDlgInitMaterialCtrls(C4ToolsDlg*) {}
bool C4ConsoleGUI::ToolsDlgOpen(C4ToolsDlg*) {return 0;}
bool C4ConsoleGUI::ToolsDlgOpen(C4ToolsDlg*) {return false;}
void C4ConsoleGUI::ToolsDlgSelectMaterial(C4ToolsDlg*, char const*) {}
void C4ConsoleGUI::ToolsDlgSelectTexture(C4ToolsDlg*, char const*) {}
void C4ConsoleGUI::ToolsDlgSelectBackMaterial(C4ToolsDlg*, char const*) {}
void C4ConsoleGUI::ToolsDlgSelectBackTexture(C4ToolsDlg*, char const*) {}
bool C4ConsoleGUI::UpdateModeCtrls(int) {return 0;}
bool C4ConsoleGUI::UpdateModeCtrls(int) {return false;}
void C4ToolsDlg::EnableControls() {}
void C4ToolsDlg::InitGradeCtrl() {}
void C4ToolsDlg::NeedPreviewUpdate() {}
bool C4ToolsDlg::PopMaterial() {return 0;}
bool C4ToolsDlg::PopTextures() {return 0;}
bool C4ToolsDlg::PopMaterial() {return false;}
bool C4ToolsDlg::PopTextures() {return false;}
void C4ToolsDlg::UpdateIFTControls() {}
void C4ToolsDlg::UpdateLandscapeModeCtrls() {}
void C4ToolsDlg::UpdateTextures() {}
void C4ToolsDlg::UpdateToolCtrls() {}
bool C4Viewport::ScrollBarsByViewPosition() {return 0;}
bool C4Viewport::TogglePlayerLock() {return 0;}
bool C4Viewport::ScrollBarsByViewPosition() {return false;}
bool C4Viewport::TogglePlayerLock() {return false;}
#include "editor/C4ConsoleGUICommon.h"
#endif

View File

@ -165,7 +165,7 @@ bool C4ConsoleGUI::FileSelect(StdStrBuf *sFilename, const char * szFilter, DWORD
}
#ifdef USE_WIN32_WINDOWS
// cwd backup
size_t l = GetCurrentDirectoryW(0, 0);
size_t l = GetCurrentDirectoryW(0, nullptr);
std::unique_ptr<wchar_t []> wd(new wchar_t[l]);
GetCurrentDirectoryW(l, wd.get());
#endif

View File

@ -51,9 +51,7 @@ C4ConsoleQtDefinitionListModel::C4ConsoleQtDefinitionListModel()
ReInit();
}
C4ConsoleQtDefinitionListModel::~C4ConsoleQtDefinitionListModel()
{
}
C4ConsoleQtDefinitionListModel::~C4ConsoleQtDefinitionListModel() = default;
void C4ConsoleQtDefinitionListModel::EnsureInit()
{
@ -67,9 +65,9 @@ void C4ConsoleQtDefinitionListModel::ReInit()
{
// Re-fill definition model with all loaded definitions matching condition
// (TODO: Add conditional lists)
root.reset(new DefListNode());
root = std::make_unique<C4ConsoleQtDefinitionListModel::DefListNode>();
int32_t index = 0; C4Def *def;
while (def = ::Definitions.GetDef(index++))
while ((def = ::Definitions.GetDef(index++)))
{
// Ignore hidden defs
if (def->HideInCreator) continue;

View File

@ -30,7 +30,7 @@ C4ConsoleQtDefinitionFileListModel::DefFileInfo::DefFileInfo(C4ConsoleQtDefiniti
// Delay opening of groups until information is actually requested
// Full names into child groups in C4S always delimeted with backslashes
if (parent->full_filename.getLength())
full_filename = parent->full_filename + "\\" + filename;
full_filename = parent->full_filename + R"(\)" + filename;
else
full_filename = filename;
}
@ -184,13 +184,9 @@ void C4ConsoleQtDefinitionFileListModel::DefFileInfo::AddExtraDef(const char *de
}
C4ConsoleQtDefinitionFileListModel::C4ConsoleQtDefinitionFileListModel()
{
}
C4ConsoleQtDefinitionFileListModel::C4ConsoleQtDefinitionFileListModel() = default;
C4ConsoleQtDefinitionFileListModel::~C4ConsoleQtDefinitionFileListModel()
{
}
C4ConsoleQtDefinitionFileListModel::~C4ConsoleQtDefinitionFileListModel() = default;
void C4ConsoleQtDefinitionFileListModel::AddExtraDef(const char *def)
{
@ -513,7 +509,7 @@ void C4ConsoleQtNewScenarioDlg::CreatePressed()
// (Also replace space, because spaces in filenames suk)
static char ReplaceSpecialFilenameChars(char c)
{
const char *special_chars = "\\/:<>|$?\" ";
const char *special_chars = R"(\/:<>|$?" )";
return strchr(special_chars, c) ? '_' : c;
}

View File

@ -67,12 +67,12 @@ C4PropertyPath::C4PropertyPath(C4Effect *fx, C4Object *target_obj) : get_path_ty
if (ofx == fx) break; else if (!strcmp(ofx->GetName(), name)) ++index;
if (target_obj)
{
get_path.Format("GetEffect(\"%s\", Object(%d), %d)", name, (int)target_obj->Number, (int)index);
get_path.Format(R"(GetEffect("%s", Object(%d), %d))", name, (int)target_obj->Number, (int)index);
root.Format("Object(%d)", (int)target_obj->Number);
}
else
{
get_path.Format("GetEffect(\"%s\", nil, %d)", name, (int)index);
get_path.Format(R"(GetEffect("%s", nil, %d))", name, (int)index);
root = ::Strings.P[P_Global].GetData();
}
}
@ -332,7 +332,7 @@ void C4PropertyDelegateString::SetModelData(QObject *editor, const C4PropertyPat
{
QString new_value = line_edit->text();
// TODO: Would be better to handle escaping in the C4Value-to-string code
new_value = new_value.replace("\\", "\\\\").replace("\"", "\\\"");
new_value = new_value.replace(R"(\)", R"(\\)").replace(R"(")", R"(\")");
property_path.SetProperty(C4VString(new_value.toUtf8()));
factory->GetPropertyModel()->DoOnUpdateCall(property_path, this);
line_edit->commit_pending = false;
@ -842,7 +842,7 @@ void C4StyledItemDelegateWithButton::paint(QPainter *painter, const QStyleOption
C4DeepQComboBox::C4DeepQComboBox(QWidget *parent, C4StyledItemDelegateWithButton::ButtonType button_type, bool editable)
: QComboBox(parent), last_popup_height(0), is_next_close_blocked(false), editable(editable), manual_text_edited(false)
{
item_delegate.reset(new C4StyledItemDelegateWithButton(button_type));
item_delegate = std::make_unique<C4StyledItemDelegateWithButton>(button_type);
QTreeView *view = new QTreeView(this);
view->setFrameShape(QFrame::NoFrame);
view->setSelectionBehavior(QTreeView::SelectRows);
@ -2215,10 +2215,10 @@ bool C4PropertyDelegateGraph::IsVertexPasteValid(const C4Value &val) const
const C4Value &pt = arr->GetItem(i_pt);
const C4PropList *ptp = pt.getPropList();
if (!ptp) return false;
for (int32_t i_prop = 0; i_prop < n_props; ++i_prop)
for (auto & property_name : property_names)
{
C4Value ptprop;
if (!ptp->GetProperty(property_names[i_prop], &ptprop)) return false;
if (!ptp->GetProperty(property_name, &ptprop)) return false;
if (ptprop.GetType() != C4V_Int) return false;
}
}
@ -2635,9 +2635,7 @@ C4ConsoleQtPropListModel::C4ConsoleQtPropListModel(C4PropertyDelegateFactory *de
layout_valid = false;
}
C4ConsoleQtPropListModel::~C4ConsoleQtPropListModel()
{
}
C4ConsoleQtPropListModel::~C4ConsoleQtPropListModel() = default;
bool C4ConsoleQtPropListModel::AddPropertyGroup(C4PropList *add_proplist, int32_t group_index, QString name, C4PropList *target_proplist, const C4PropertyPath &group_target_path, C4Object *base_object, C4String *default_selection, int32_t *default_selection_index)
{
@ -2835,7 +2833,7 @@ void C4ConsoleQtPropListModel::SetBasePropList(C4PropList *new_proplist)
void C4ConsoleQtPropListModel::DescendPath(const C4Value &new_value, C4PropList *new_info_proplist, const C4PropertyPath &new_path)
{
// Add previous proplist to stack
target_path_stack.push_back(TargetStackEntry(target_path, target_value, info_proplist));
target_path_stack.emplace_back(target_path, target_value, info_proplist);
// descend
target_value = new_value;
info_proplist.SetPropList(new_info_proplist);
@ -3132,7 +3130,7 @@ void C4ConsoleQtPropListModel::DoOnUpdateCall(const C4PropertyPath &updated_path
C4Value q;
if (base_proplist && base_proplist->GetProperty(P_EditorPropertyChanged, &q))
{
::Console.EditCursor.EMControl(CID_Script, new C4ControlScript(FormatString("%s->%s(\"%s\")", updated_path.GetRoot(), ::Strings.P[P_EditorPropertyChanged].GetCStr(), updated_path.GetGetPath()).getData(), 0, false));
::Console.EditCursor.EMControl(CID_Script, new C4ControlScript(FormatString(R"(%s->%s("%s"))", updated_path.GetRoot(), ::Strings.P[P_EditorPropertyChanged].GetCStr(), updated_path.GetGetPath()).getData(), 0, false));
}
}

View File

@ -594,9 +594,7 @@ C4ConsoleGUIState::C4ConsoleGUIState(C4ConsoleGUI *console) : viewport_area(null
{
}
C4ConsoleGUIState::~C4ConsoleGUIState()
{
}
C4ConsoleGUIState::~C4ConsoleGUIState() = default;
void C4ConsoleGUIState::AddToolbarSpacer(int space)
{
@ -631,9 +629,9 @@ bool C4ConsoleGUIState::CreateConsoleWindow(C4AbstractApp *app)
// stay valid over the lifetime of the application.
static int fake_argc = 1;
static const char *fake_argv[] = { "openclonk" };
application.reset(new QApplication(fake_argc, const_cast<char **>(fake_argv)));
application = std::make_unique<QApplication>(fake_argc, const_cast<char **>(fake_argv));
application->installTranslator(&qt_translator);
window.reset(new C4ConsoleQtMainWindow(app, this));
window = std::make_unique<C4ConsoleQtMainWindow>(app, this);
ui.setupUi(window.get());
// Setup some extra stuff that cannot be done easily in the designer
@ -692,29 +690,29 @@ bool C4ConsoleGUIState::CreateConsoleWindow(C4AbstractApp *app)
// (none right now)
// Property editor
property_delegate_factory.reset(new C4PropertyDelegateFactory());
property_delegate_factory = std::make_unique<C4PropertyDelegateFactory>();
ui.propertyTable->setItemDelegateForColumn(1, property_delegate_factory.get());
ui.propertyEditAscendPathButton->setMaximumWidth(ui.propertyEditAscendPathButton->fontMetrics().boundingRect(ui.propertyEditAscendPathButton->text()).width() + 10);
ui.propertyTable->setDropIndicatorShown(true);
ui.propertyTable->setAcceptDrops(true);
property_name_delegate.reset(new C4PropertyNameDelegate());
property_name_delegate = std::make_unique<C4PropertyNameDelegate>();
ui.propertyTable->setItemDelegateForColumn(0, property_name_delegate.get());
ui.propertyTable->setMouseTracking(true);
// View models
property_model.reset(new C4ConsoleQtPropListModel(property_delegate_factory.get()));
property_model = std::make_unique<C4ConsoleQtPropListModel>(property_delegate_factory.get());
property_delegate_factory->SetPropertyModel(property_model.get());
property_name_delegate->SetPropertyModel(property_model.get());
QItemSelectionModel *m = ui.propertyTable->selectionModel();
ui.propertyTable->setModel(property_model.get());
delete m;
property_model->SetSelectionModel(ui.propertyTable->selectionModel());
object_list_model.reset(new C4ConsoleQtObjectListModel());
object_list_model = std::make_unique<C4ConsoleQtObjectListModel>();
m = ui.objectListView->selectionModel();
ui.objectListView->setModel(object_list_model.get());
delete m;
window->connect(ui.objectListView->selectionModel(), &QItemSelectionModel::selectionChanged, window.get(), &C4ConsoleQtMainWindow::OnObjectListSelectionChanged);
definition_list_model.reset(new C4ConsoleQtDefinitionListModel());
definition_list_model = std::make_unique<C4ConsoleQtDefinitionListModel>();
property_delegate_factory->SetDefinitionListModel(definition_list_model.get());
m = ui.creatorTreeView->selectionModel();
ui.creatorTreeView->setModel(definition_list_model.get());
@ -852,12 +850,12 @@ static void SetComboItems(QComboBox *box, std::list<const char*> &items)
{
QString text = box->lineEdit()->text(); // remember and restore current text
box->clear();
for (std::list<const char*>::iterator it = items.begin(); it != items.end(); it++)
for (auto & item : items)
{
if (!*it)
if (!item)
box->addItem("----------");
else
box->addItem(*it);
box->addItem(item);
}
box->lineEdit()->setText(text);
}
@ -1147,15 +1145,14 @@ bool C4ConsoleGUIState::CreateNewScenario(StdStrBuf *out_filename, bool *out_hos
void C4ConsoleGUIState::InitWelcomeScreen()
{
// Init links
ui.welcomeNewLabel->setText(QString("<a href=\"new\">%1</a>").arg(ui.welcomeNewLabel->text()));
ui.welcomeOpenLabel->setText(QString("<a href=\"open\">%1</a>").arg(ui.welcomeOpenLabel->text()));
ui.welcomeExploreUserPathLabel->setText(QString("<a href=\"exploreuserpath\">%1</a>").arg(ui.welcomeExploreUserPathLabel->text()));
ui.welcomeNewLabel->setText(QString(R"(<a href="new">%1</a>)").arg(ui.welcomeNewLabel->text()));
ui.welcomeOpenLabel->setText(QString(R"(<a href="open">%1</a>)").arg(ui.welcomeOpenLabel->text()));
ui.welcomeExploreUserPathLabel->setText(QString(R"(<a href="exploreuserpath">%1</a>)").arg(ui.welcomeExploreUserPathLabel->text()));
// Recently opened scenarios
bool any_file = false;
int recent_idx = ui.welcomeScrollLayout->indexOf(ui.welcomeRecentLabel);
for (int32_t i = 0; i < CFG_MaxEditorMRU; ++i)
for (auto filename : ::Config.Developer.RecentlyEditedSzenarios)
{
const char *filename = ::Config.Developer.RecentlyEditedSzenarios[i];
if (*filename && ::ItemExists(filename))
{
StdStrBuf basename(GetFilename(filename), true);
@ -1174,7 +1171,7 @@ void C4ConsoleGUIState::InitWelcomeScreen()
ui.welcomeScrollLayout->insertWidget(++recent_idx, link);
link->setIndent(ui.welcomeOpenLabel->indent());
link->setTextInteractionFlags(ui.welcomeOpenLabel->textInteractionFlags());
link->setText(QString("<a href=\"open:%1\">%2</a>").arg(filename).arg(basename.getData())); // let's hope file names never contain "
link->setText(QString(R"(<a href="open:%1">%2</a>)").arg(filename).arg(basename.getData())); // let's hope file names never contain "
any_file = true;
window->connect(link, SIGNAL(linkActivated(QString)), window.get(), SLOT(WelcomeLinkActivated(QString)));
}

View File

@ -515,15 +515,15 @@ public:
HBITMAP hbmStatic;
HBITMAP hbmExact;
State(C4ToolsDlg *toolsDlg): C4ConsoleGUI::InternalState<class C4ToolsDlg>(toolsDlg), hDialog(0),
hbmBrush(0), hbmBrush2(0),
hbmLine(0), hbmLine2(0),
hbmRect(0), hbmRect2(0),
hbmFill(0), hbmFill2(0),
hbmPicker(0), hbmPicker2(0),
hbmDynamic(0),
hbmStatic(0),
hbmExact(0)
State(C4ToolsDlg *toolsDlg): C4ConsoleGUI::InternalState<class C4ToolsDlg>(toolsDlg), hDialog(nullptr),
hbmBrush(nullptr), hbmBrush2(nullptr),
hbmLine(nullptr), hbmLine2(nullptr),
hbmRect(nullptr), hbmRect2(nullptr),
hbmFill(nullptr), hbmFill2(nullptr),
hbmPicker(nullptr), hbmPicker2(nullptr),
hbmDynamic(nullptr),
hbmStatic(nullptr),
hbmExact(nullptr)
{
pPreviewWindow = nullptr;
}
@ -553,19 +553,19 @@ public:
void Clear()
{
// Unload bitmaps
if (hbmBrush) { DeleteObject(hbmBrush); hbmBrush = 0; }
if (hbmLine) { DeleteObject(hbmLine); hbmLine = 0; }
if (hbmRect) { DeleteObject(hbmRect); hbmRect = 0; }
if (hbmFill) { DeleteObject(hbmFill); hbmFill = 0; }
if (hbmPicker) { DeleteObject(hbmPicker); hbmPicker = 0; }
if (hbmBrush2) { DeleteObject(hbmBrush2); hbmBrush2 = 0; }
if (hbmLine2) { DeleteObject(hbmLine2); hbmLine2 = 0; }
if (hbmRect2) { DeleteObject(hbmRect2); hbmRect2 = 0; }
if (hbmFill2) { DeleteObject(hbmFill2); hbmFill2 = 0; }
if (hbmPicker2) { DeleteObject(hbmPicker2); hbmPicker2 = 0; }
if (hbmDynamic) { DeleteObject(hbmDynamic); hbmDynamic = 0; }
if (hbmStatic) { DeleteObject(hbmStatic); hbmStatic = 0; }
if (hbmExact) { DeleteObject(hbmExact); hbmExact = 0; }
if (hbmBrush) { DeleteObject(hbmBrush); hbmBrush = nullptr; }
if (hbmLine) { DeleteObject(hbmLine); hbmLine = nullptr; }
if (hbmRect) { DeleteObject(hbmRect); hbmRect = nullptr; }
if (hbmFill) { DeleteObject(hbmFill); hbmFill = nullptr; }
if (hbmPicker) { DeleteObject(hbmPicker); hbmPicker = nullptr; }
if (hbmBrush2) { DeleteObject(hbmBrush2); hbmBrush2 = nullptr; }
if (hbmLine2) { DeleteObject(hbmLine2); hbmLine2 = nullptr; }
if (hbmRect2) { DeleteObject(hbmRect2); hbmRect2 = nullptr; }
if (hbmFill2) { DeleteObject(hbmFill2); hbmFill2 = nullptr; }
if (hbmPicker2) { DeleteObject(hbmPicker2); hbmPicker2 = nullptr; }
if (hbmDynamic) { DeleteObject(hbmDynamic); hbmDynamic = nullptr; }
if (hbmStatic) { DeleteObject(hbmStatic); hbmStatic = nullptr; }
if (hbmExact) { DeleteObject(hbmExact); hbmExact = nullptr; }
if (pPreviewWindow)
{
delete pPreviewWindow;
@ -766,7 +766,7 @@ bool C4ConsoleGUI::Win32DialogMessageHandling(MSG *msg)
void C4ConsoleGUI::SetCursor(Cursor cursor)
{
::SetCursor(LoadCursor(0,IDC_WAIT));
::SetCursor(LoadCursor(nullptr,IDC_WAIT));
}
bool C4ConsoleGUI::UpdateModeCtrls(int iMode)
@ -980,8 +980,8 @@ bool C4ConsoleGUI::FileSelect(StdStrBuf *sFilename, const char * szFilter, DWORD
ofn.Flags=dwFlags;
bool fResult;
size_t l = GetCurrentDirectoryW(0,0);
wchar_t *wd = new wchar_t[l];
size_t l = GetCurrentDirectoryW(0,nullptr);
auto *wd = new wchar_t[l];
GetCurrentDirectoryW(l,wd);
if (fSave)
fResult = !!GetSaveFileNameW(&ofn);
@ -990,9 +990,9 @@ bool C4ConsoleGUI::FileSelect(StdStrBuf *sFilename, const char * szFilter, DWORD
// Reset working directory to exe path as Windows file dialog might have changed it
SetCurrentDirectoryW(wd);
delete[] wd;
len = WideCharToMultiByte(CP_UTF8, 0, buffer, ArbitraryMaximumLength, nullptr, 0, 0, 0);
len = WideCharToMultiByte(CP_UTF8, 0, buffer, ArbitraryMaximumLength, nullptr, 0, nullptr, nullptr);
sFilename->SetLength(len - 1);
WideCharToMultiByte(CP_UTF8, 0, buffer, ArbitraryMaximumLength, sFilename->getMData(), sFilename->getSize(), 0, 0);
WideCharToMultiByte(CP_UTF8, 0, buffer, ArbitraryMaximumLength, sFilename->getMData(), sFilename->getSize(), nullptr, nullptr);
return fResult;
}
@ -1071,12 +1071,12 @@ void C4ConsoleGUI::PropertyDlgClose()
static void SetComboItems(HWND hCombo, std::list<const char*> &items)
{
for (std::list<const char*>::iterator it = items.begin(); it != items.end(); it++)
for (auto & item : items)
{
if (!*it)
if (!item)
SendMessage(hCombo, CB_ADDSTRING, 0, (LPARAM)L"----------");
else
SendMessage(hCombo,CB_ADDSTRING,0,GetWideLPARAM(*it));
SendMessage(hCombo,CB_ADDSTRING,0,GetWideLPARAM(item));
}
}
@ -1139,12 +1139,12 @@ public:
pSurface = new C4Surface(&Application, this);
}
~C4ConsoleGUIPreviewWindow()
~C4ConsoleGUIPreviewWindow() override
{
delete pSurface;
}
virtual void Close() {}
void Close() override {}
};
bool C4ConsoleGUI::ToolsDlgOpen(C4ToolsDlg *dlg)

View File

@ -885,7 +885,7 @@ void C4EditCursor::Draw(C4TargetFacet &cgo)
creator_def->Shape.Wdt, creator_def->Shape.Hgt, 0, 0, cgo.Zoom, 0, 0);
if (!creator_overlay)
{
creator_overlay.reset(new C4GraphicsOverlay());
creator_overlay = std::make_unique<C4GraphicsOverlay>();
creator_overlay->SetAsBase(&creator_def->Graphics, C4GFXBLIT_ADDITIVE);
}
creator_overlay->Draw(cgo_creator, nullptr, NO_OWNER);

View File

@ -24,13 +24,9 @@
#include "script/C4Effect.h"
C4ObjectListDlg::C4ObjectListDlg()
{
}
C4ObjectListDlg::C4ObjectListDlg() = default;
C4ObjectListDlg::~C4ObjectListDlg()
{
}
C4ObjectListDlg::~C4ObjectListDlg() = default;
void C4ObjectListDlg::Execute()
{

View File

@ -130,7 +130,7 @@ void C4ToolsDlg::SetBackTexture(const char *szTexture)
bool C4ToolsDlg::SetIFT(bool fIFT)
{
ModeBack = false;
if (fIFT) ModeIFT = 1; else ModeIFT=0;
if (fIFT) ModeIFT = true; else ModeIFT=false;
// Keep sensible default values in BackMaterial / BackTexture
if (ModeIFT == 0)

View File

@ -105,9 +105,9 @@ bool C4Application::DoInit(int argc, char * argv[])
// Engine header message
Log(C4ENGINECAPTION);
LogF("Version: %s %s (%s - %s)", C4VERSION, C4_OS, GetRevision(), C4REVISION_TS);
LogF("ExePath: \"%s\"", Config.General.ExePath.getData());
LogF("SystemDataPath: \"%s\"", Config.General.SystemDataPath);
LogF("UserDataPath: \"%s\"", Config.General.UserDataPath);
LogF(R"(ExePath: "%s")", Config.General.ExePath.getData());
LogF(R"(SystemDataPath: "%s")", Config.General.SystemDataPath);
LogF(R"(UserDataPath: "%s")", Config.General.UserDataPath);
// Init C4Group
C4Group_SetProcessCallback(&ProcessCallback);
@ -214,7 +214,7 @@ void C4Application::ParseCommandLine(int argc, char * argv[])
Game.NetworkActive = false;
isEditor = 2;
int c;
while (1)
while (true)
{
static struct option long_options[] =
@ -231,36 +231,36 @@ void C4Application::ParseCommandLine(int argc, char * argv[])
{"nosignup", no_argument, &Config.Network.MasterServerSignUp, 0},
{"signup", no_argument, &Config.Network.MasterServerSignUp, 1},
{"debugrecread", required_argument, 0, 'K'},
{"debugrecwrite", required_argument, 0, 'w'},
{"debugrecread", required_argument, nullptr, 'K'},
{"debugrecwrite", required_argument, nullptr, 'w'},
{"client", required_argument, 0, 'c'},
{"host", no_argument, 0, 'h'},
{"debughost", required_argument, 0, 'H'},
{"debugpass", required_argument, 0, 'P'},
{"debug", required_argument, 0, 'D'},
{"data", required_argument, 0, 'd'},
{"startup", required_argument, 0, 's'},
{"stream", required_argument, 0, 'e'},
{"recdump", required_argument, 0, 'R'},
{"comment", required_argument, 0, 'm'},
{"pass", required_argument, 0, 'p'},
{"udpport", required_argument, 0, 'u'},
{"tcpport", required_argument, 0, 't'},
{"join", required_argument, 0, 'j'},
{"language", required_argument, 0, 'L'},
{"scenpar", required_argument, 0, 'S'},
{"client", required_argument, nullptr, 'c'},
{"host", no_argument, nullptr, 'h'},
{"debughost", required_argument, nullptr, 'H'},
{"debugpass", required_argument, nullptr, 'P'},
{"debug", required_argument, nullptr, 'D'},
{"data", required_argument, nullptr, 'd'},
{"startup", required_argument, nullptr, 's'},
{"stream", required_argument, nullptr, 'e'},
{"recdump", required_argument, nullptr, 'R'},
{"comment", required_argument, nullptr, 'm'},
{"pass", required_argument, nullptr, 'p'},
{"udpport", required_argument, nullptr, 'u'},
{"tcpport", required_argument, nullptr, 't'},
{"join", required_argument, nullptr, 'j'},
{"language", required_argument, nullptr, 'L'},
{"scenpar", required_argument, nullptr, 'S'},
{"observe", no_argument, 0, 'o'},
{"nonetwork", no_argument, 0, 'N'},
{"network", no_argument, 0, 'n'},
{"record", no_argument, 0, 'r'},
{"observe", no_argument, nullptr, 'o'},
{"nonetwork", no_argument, nullptr, 'N'},
{"network", no_argument, nullptr, 'n'},
{"record", no_argument, nullptr, 'r'},
{"lobby", optional_argument, 0, 'l'},
{"lobby", optional_argument, nullptr, 'l'},
{"debug-opengl", no_argument, &Config.Graphics.DebugOpenGL, 1},
{"config", required_argument, nullptr, 0},
{0, 0, 0, 0}
{nullptr, 0, nullptr, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "abc:d:f:",

View File

@ -64,7 +64,7 @@ void C4FullScreen::Close()
void C4FullScreen::Clear()
{
if (pSurface) delete pSurface;
pSurface = 0;
pSurface = nullptr;
C4Window::Clear();
}

View File

@ -86,8 +86,8 @@ class C4GameSec1Timer : public C4ApplicationSec1Timer
{
public:
C4GameSec1Timer() { Application.Add(this); }
~C4GameSec1Timer() { Application.Remove(this); }
void OnSec1Timer();
~C4GameSec1Timer() override { Application.Remove(this); }
void OnSec1Timer() override;
};
static C4GameParameters GameParameters;
@ -498,7 +498,7 @@ bool C4Game::Init()
FullScreen.CloseMenu();
// start statistics (always for now. Make this a config?)
pNetworkStatistics.reset(new C4Network2Stats);
pNetworkStatistics = std::make_unique<C4Network2Stats>();
// clear loader screen
if (GraphicsSystem.pLoaderScreen)
@ -2119,7 +2119,7 @@ bool C4Game::InitGame(C4Group &hGroup, InitMode init_mode, bool fLoadSky, C4Valu
// file monitor
if (Config.Developer.AutoFileReload && Application.isEditor && !pFileMonitor)
pFileMonitor.reset(new C4FileMonitor(FileMonitorCallback));
pFileMonitor = std::make_unique<C4FileMonitor>(FileMonitorCallback);
// system scripts
if (!InitScriptEngine())
@ -2193,7 +2193,7 @@ bool C4Game::InitGame(C4Group &hGroup, InitMode init_mode, bool fLoadSky, C4Valu
// prepare script menus
assert(!ScriptGuiRoot);
ScriptGuiRoot.reset(new C4ScriptGuiWindow);
ScriptGuiRoot = std::make_unique<C4ScriptGuiWindow>();
}
else if (fLoadSky)
{
@ -2961,33 +2961,33 @@ bool C4Game::InitKeyboard()
KeyboardInput.RegisterKey(new C4CustomKey(C4KeyCodeEx(K_SUBTRACT, KEYS_Shift), "GameSlowDown", KEYSCOPE_Generic, new C4KeyCB <C4Game> (*this, &C4Game::SlowDown)));
// fullscreen menu
Keys.clear(); Keys.push_back(C4KeyCodeEx(K_LEFT));
Keys.clear(); Keys.emplace_back(K_LEFT);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Left(Keys);
KeyboardInput.RegisterKey(new C4CustomKey(Keys, "FullscreenMenuLeft", KEYSCOPE_FullSMenu, new C4KeyCBEx<C4FullScreen, BYTE> (FullScreen, COM_MenuLeft, &C4FullScreen::MenuKeyControl)));
Keys.clear(); Keys.push_back(C4KeyCodeEx(K_RIGHT));
Keys.clear(); Keys.emplace_back(K_RIGHT);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Right(Keys);
KeyboardInput.RegisterKey(new C4CustomKey(Keys, "FullscreenMenuRight", KEYSCOPE_FullSMenu, new C4KeyCBEx<C4FullScreen, BYTE> (FullScreen, COM_MenuRight, &C4FullScreen::MenuKeyControl)));
Keys.clear(); Keys.push_back(C4KeyCodeEx(K_UP));
Keys.clear(); Keys.emplace_back(K_UP);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Up(Keys);
KeyboardInput.RegisterKey(new C4CustomKey(Keys, "FullscreenMenuUp", KEYSCOPE_FullSMenu, new C4KeyCBEx<C4FullScreen, BYTE> (FullScreen, COM_MenuUp, &C4FullScreen::MenuKeyControl)));
Keys.clear(); Keys.push_back(C4KeyCodeEx(K_DOWN));
Keys.clear(); Keys.emplace_back(K_DOWN);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Down(Keys);
KeyboardInput.RegisterKey(new C4CustomKey(Keys, "FullscreenMenuDown", KEYSCOPE_FullSMenu, new C4KeyCBEx<C4FullScreen, BYTE> (FullScreen, COM_MenuDown, &C4FullScreen::MenuKeyControl)));
Keys.clear(); Keys.push_back(C4KeyCodeEx(K_SPACE)); Keys.push_back(C4KeyCodeEx(K_RETURN));
Keys.clear(); Keys.emplace_back(K_SPACE); Keys.emplace_back(K_RETURN);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Ok(Keys);
KeyboardInput.RegisterKey(new C4CustomKey(Keys, "FullscreenMenuOK", KEYSCOPE_FullSMenu, new C4KeyCBEx<C4FullScreen, BYTE> (FullScreen, COM_MenuEnter, &C4FullScreen::MenuKeyControl))); // name used by PlrControlKeyName
Keys.clear(); Keys.push_back(C4KeyCodeEx(K_ESCAPE));
Keys.clear(); Keys.emplace_back(K_ESCAPE);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Cancel(Keys);
KeyboardInput.RegisterKey(new C4CustomKey(Keys, "FullscreenMenuCancel", KEYSCOPE_FullSMenu, new C4KeyCBEx<C4FullScreen, BYTE> (FullScreen, COM_MenuClose, &C4FullScreen::MenuKeyControl))); // name used by PlrControlKeyName
Keys.clear(); Keys.push_back(C4KeyCodeEx(K_SPACE));
Keys.clear(); Keys.emplace_back(K_SPACE);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Any(Keys);
KeyboardInput.RegisterKey(new C4CustomKey(Keys, "FullscreenMenuOpen", KEYSCOPE_FreeView, new C4KeyCB <C4FullScreen> (FullScreen, &C4FullScreen::ActivateMenuMain))); // name used by C4MainMenu!
KeyboardInput.RegisterKey(new C4CustomKey(C4KeyCodeEx(K_RIGHT ), "FilmNextPlayer", KEYSCOPE_FilmView, new C4KeyCB <C4ViewportList>(::Viewports, &C4ViewportList::ViewportNextPlayer)));
// chat
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_RETURN));
Keys.push_back(C4KeyCodeEx(K_F2)); // alternate chat key, if RETURN is blocked by player control
Keys.emplace_back(K_RETURN);
Keys.emplace_back(K_F2); // alternate chat key, if RETURN is blocked by player control
KeyboardInput.RegisterKey(new C4CustomKey(Keys, "ChatOpen", KEYSCOPE_Generic, new C4KeyCBEx<C4MessageInput, bool>(MessageInput, false, &C4MessageInput::KeyStartTypeIn)));
KeyboardInput.RegisterKey(new C4CustomKey(C4KeyCodeEx(K_RETURN, KEYS_Shift), "ChatOpen2Allies", KEYSCOPE_Generic, new C4KeyCBEx<C4MessageInput, bool>(MessageInput, true, &C4MessageInput::KeyStartTypeIn)));
@ -3303,8 +3303,8 @@ bool C4Game::CheckObjectEnumeration()
struct Check
{
int32_t maxNumber;
Check() : maxNumber(0) {}
int32_t maxNumber{0};
Check() = default;
// Check valid & maximum number & duplicate numbers
bool that(C4Object* cObj)
{

View File

@ -226,8 +226,8 @@ static C4ValueArray *FnFindConstructionSite(C4PropList * _this, C4PropList * Pro
return nullptr;
// Search for real
bool result = !!FindConSiteSpot(v1, v2, pDef->Shape.Wdt,pDef->Shape.Hgt, 20);
if(!result) return 0;
C4ValueArray *pArray = new C4ValueArray(2);
if(!result) return nullptr;
auto *pArray = new C4ValueArray(2);
pArray->SetItem(0, C4VInt(v1));
pArray->SetItem(1, C4VInt(v2));
return pArray;
@ -1299,7 +1299,7 @@ static C4ValueArray* FnPathFree2(C4PropList * _this, int32_t x1, int32_t y1, int
pArray->SetItem(1, C4VInt(y));
return pArray;
}
return 0;
return nullptr;
}
C4Object* FnObject(C4PropList * _this, long iNumber)
@ -1443,11 +1443,11 @@ public:
: pszNames(pszNames), iNameCnt(iNameCnt), iEntryNr(iEntryNr)
{ }
virtual bool isDeserializer() override { return false; }
virtual bool hasNaming() override { return true; }
virtual bool isVerbose() override { return false; }
bool isDeserializer() override { return false; }
bool hasNaming() override { return true; }
bool isVerbose() override { return false; }
virtual bool Name(const char *szName) override
bool Name(const char *szName) override
{
// match possible? (no match yet / continued match)
if (!iMatchStart || haveCurrentMatch())
@ -1464,13 +1464,13 @@ public:
return true;
}
virtual bool Default(const char *szName) override
bool Default(const char *szName) override
{
// Always process values even if they are default!
return false;
}
virtual void NameEnd(bool fBreak = false) override
void NameEnd(bool fBreak = false) override
{
// end of matched name section?
if (haveCurrentMatch())
@ -1481,7 +1481,7 @@ public:
iDepth--;
}
virtual void Begin() override
void Begin() override
{
// set up
iDepth = iMatchStart = iMatchCount = 0;
@ -1509,23 +1509,23 @@ private:
}
}
public:
virtual void DWord(int32_t &rInt) override { MaybeProcessInt(rInt); }
virtual void DWord(uint32_t &rInt) override { MaybeProcessInt(rInt); }
virtual void Word(int16_t &rShort) override { MaybeProcessInt(rShort); }
virtual void Word(uint16_t &rShort) override { MaybeProcessInt(rShort); }
virtual void Byte(int8_t &rByte) override { MaybeProcessInt(rByte); }
virtual void Byte(uint8_t &rByte) override { MaybeProcessInt(rByte); }
virtual void Boolean(bool &rBool) override { if (haveCompleteMatch()) if (!iEntryNr--) ProcessBool(rBool); }
virtual void Character(char &rChar) override { if (haveCompleteMatch()) if (!iEntryNr--) ProcessChar(rChar); }
void DWord(int32_t &rInt) override { MaybeProcessInt(rInt); }
void DWord(uint32_t &rInt) override { MaybeProcessInt(rInt); }
void Word(int16_t &rShort) override { MaybeProcessInt(rShort); }
void Word(uint16_t &rShort) override { MaybeProcessInt(rShort); }
void Byte(int8_t &rByte) override { MaybeProcessInt(rByte); }
void Byte(uint8_t &rByte) override { MaybeProcessInt(rByte); }
void Boolean(bool &rBool) override { if (haveCompleteMatch()) if (!iEntryNr--) ProcessBool(rBool); }
void Character(char &rChar) override { 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) override
void String(char *szString, size_t iMaxLength, RawCompileType eType) override
{ if (haveCompleteMatch()) if (!iEntryNr--) ProcessString(szString, iMaxLength, eType == StdCompiler::RCT_ID); }
virtual void String(char **pszString, RawCompileType eType) override
void String(char **pszString, RawCompileType eType) override
{ if (haveCompleteMatch()) if (!iEntryNr--) ProcessString(pszString, eType == StdCompiler::RCT_ID); }
virtual void String(std::string &str, RawCompileType type) override
void String(std::string &str, RawCompileType type) override
{ if (haveCompleteMatch()) if (!iEntryNr--) ProcessString(str, type == StdCompiler::RCT_ID); }
virtual void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped)
void Raw(void *pData, size_t iSize, RawCompileType eType = RCT_Escaped) override
{ /* C4Script can't handle this */ }
private:
@ -1564,15 +1564,15 @@ public:
protected:
// get values as C4Value
virtual void ProcessInt(int32_t &rInt) override { Res = C4VInt(rInt); }
virtual void ProcessBool(bool &rBool) override { Res = C4VBool(rBool); }
virtual void ProcessChar(char &rChar) override { Res = C4VString(FormatString("%c", rChar)); }
void ProcessInt(int32_t &rInt) override { Res = C4VInt(rInt); }
void ProcessBool(bool &rBool) override { Res = C4VBool(rBool); }
void ProcessChar(char &rChar) override { Res = C4VString(FormatString("%c", rChar)); }
virtual void ProcessString(char *szString, size_t iMaxLength, bool fIsID) override
void ProcessString(char *szString, size_t iMaxLength, bool fIsID) override
{ Res = (fIsID ? C4VPropList(C4Id2Def(C4ID(szString))) : C4VString(szString)); }
virtual void ProcessString(char **pszString, bool fIsID) override
void ProcessString(char **pszString, bool fIsID) override
{ Res = (fIsID ? C4VPropList(C4Id2Def(C4ID(*pszString))) : C4VString(*pszString)); }
virtual void ProcessString(std::string &str, bool fIsID) override
void ProcessString(std::string &str, bool fIsID) override
{ Res = (fIsID ? C4VPropList(C4Id2Def(C4ID(str.c_str()))) : C4VString(str.c_str())); }
};
@ -2212,7 +2212,7 @@ static bool FnSetViewOffset(C4PropList * _this, long iPlayer, long iX, long iY)
if (!ValidPlr(iPlayer)) return false;
// get player viewport
C4Viewport *pView = ::Viewports.GetViewport(iPlayer);
if (!pView) return 1; // sync safety
if (!pView) return true; // sync safety
// set
pView->SetViewOffset(iX, iY);
// ok
@ -3095,14 +3095,14 @@ C4ScriptConstDef C4ScriptGameConstMap[]=
C4ScriptFnDef C4ScriptGameFnMap[]=
{
{ "FindObject", 1, C4V_Object, { C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, 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}, 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}, FnObjectCount },
{ "GameCallEx", 1, C4V_Any, { C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnGameCallEx },
{ "PlayerMessage", 1, C4V_Int, { C4V_Int ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnPlayerMessage },
{ "Message", 1, C4V_Bool, { C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnMessage },
{ "AddMessage", 1, C4V_Bool, { C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnAddMessage },
{ "PV_KeyFrames", 1, C4V_Array, { C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnPV_KeyFrames },
{ "FindObject", true, C4V_Object, { C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnFindObject },
{ "FindObjects", true, C4V_Array, { C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnFindObjects },
{ "ObjectCount", true, C4V_Int, { C4V_Array ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnObjectCount },
{ "GameCallEx", true, C4V_Any, { C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnGameCallEx },
{ "PlayerMessage", true, C4V_Int, { C4V_Int ,C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnPlayerMessage },
{ "Message", true, C4V_Bool, { C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnMessage },
{ "AddMessage", true, C4V_Bool, { C4V_String ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnAddMessage },
{ "PV_KeyFrames", true, C4V_Array, { C4V_Int ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any ,C4V_Any}, FnPV_KeyFrames },
{ nullptr, 0, C4V_Nil, { C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil}, 0 }
{ nullptr, false, C4V_Nil, { C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil ,C4V_Nil}, nullptr }
};

View File

@ -154,7 +154,7 @@ void C4GraphicsSystem::Execute()
void C4GraphicsSystem::Default()
{
MessageBoard.reset(new C4MessageBoard);
MessageBoard = std::make_unique<C4MessageBoard>();
InvalidateBg();
ShowVertices=false;
ShowAction=false;

View File

@ -667,7 +667,7 @@ bool C4Viewport::Init(int32_t iPlayer, bool fSetTempOnly)
{
// Console viewport initialization
// Create window
pWindow.reset(new C4ViewportWindow(this));
pWindow = std::make_unique<C4ViewportWindow>(this);
if (!pWindow->Init(Player))
return false;
UpdateOutputSize();
@ -696,7 +696,7 @@ void C4Viewport::EnableFoW()
{
if (::Landscape.HasFoW() && Player != NO_OWNER)
{
pFoW.reset(new C4FoWRegion(::Landscape.GetFoW(), ::Players.Get(Player)));
pFoW = std::make_unique<C4FoWRegion>(::Landscape.GetFoW(), ::Players.Get(Player));
}
else
{
@ -845,9 +845,7 @@ C4ViewportList::C4ViewportList():
{
ViewportArea.Default();
}
C4ViewportList::~C4ViewportList()
{
}
C4ViewportList::~C4ViewportList() = default;
void C4ViewportList::Clear()
{
C4Viewport *next;

View File

@ -76,9 +76,9 @@ int WINAPI WinMain (HINSTANCE hInst,
LPWSTR *curwarg = wargv;
while(argc--)
{
int arglen = WideCharToMultiByte(CP_UTF8, 0, *curwarg, -1, nullptr, 0, 0, 0);
char *utf8arg = new char[arglen ? arglen : 1];
WideCharToMultiByte(CP_UTF8, 0, *curwarg, -1, utf8arg, arglen, 0, 0);
int arglen = WideCharToMultiByte(CP_UTF8, 0, *curwarg, -1, nullptr, 0, nullptr, nullptr);
auto *utf8arg = new char[arglen ? arglen : 1];
WideCharToMultiByte(CP_UTF8, 0, *curwarg, -1, utf8arg, arglen, nullptr, nullptr);
argv.push_back(utf8arg);
++curwarg;
}
@ -107,7 +107,7 @@ int WINAPI WinMain (HINSTANCE hInst,
int main()
{
return WinMain(GetModuleHandle(nullptr), 0, 0, 0);
return WinMain(GetModuleHandle(nullptr), nullptr, nullptr, 0);
}
#else // _WIN32
@ -203,7 +203,7 @@ static void restart(char * argv[])
for (int fd = 4; fd < open_max; fd++)
fcntl (fd, F_SETFD, FD_CLOEXEC);
// Execute the new engine
execlp(argv[0], argv[0], static_cast<char *>(0));
execlp(argv[0], argv[0], static_cast<char *>(nullptr));
}
int main (int argc, char * argv[])

View File

@ -32,7 +32,7 @@
#include "graphics/CSurface8.h"
#include "lib/StdColors.h"
#include <stdio.h>
#include <cstdio>
// Instruct Optimus laptops to use nVidia GPU instead of integrated GPU
#if defined(_WIN32) && !defined(USE_CONSOLE)
@ -106,7 +106,7 @@ C4Pattern& C4Pattern::operator=(const C4Pattern& nPattern)
}
else
{
CachedPattern = 0;
CachedPattern = nullptr;
}
Wdt = nPattern.Wdt;
Hgt = nPattern.Hgt;
@ -142,7 +142,7 @@ C4Pattern::C4Pattern()
{
// disable
sfcPattern32=nullptr;
CachedPattern = 0;
CachedPattern = nullptr;
Zoom=0;
}
@ -156,7 +156,7 @@ void C4Pattern::Clear()
// clear field
sfcPattern32=nullptr;
}
delete[] CachedPattern; CachedPattern = 0;
delete[] CachedPattern; CachedPattern = nullptr;
}
DWORD C4Pattern::PatternClr(unsigned int iX, unsigned int iY) const
@ -443,8 +443,8 @@ bool C4Draw::Blit8(C4Surface * sfcSource, int fx, int fy, int fwdt, int fhgt,
Transform *=* pTransform;
C4BltTransform TransformBack;
TransformBack.SetAsInv(Transform);
float ttx0=(float)tx, tty0=(float)ty, ttx1=(float)(tx+twdt), tty1=(float)(ty+thgt);
float ttx2=(float)ttx0, tty2=(float)tty1, ttx3=(float)ttx1, tty3=(float)tty0;
auto ttx0=(float)tx, tty0=(float)ty, ttx1=(float)(tx+twdt), tty1=(float)(ty+thgt);
auto ttx2=(float)ttx0, tty2=(float)tty1, ttx3=(float)ttx1, tty3=(float)tty0;
pTransform->TransformPoint(ttx0, tty0);
pTransform->TransformPoint(ttx1, tty1);
pTransform->TransformPoint(ttx2, tty2);
@ -653,8 +653,8 @@ void C4Draw::DrawFrameDw(C4Surface * sfcDest, int x1, int y1, int x2, int y2, DW
vertices[6] = vertices[5];
vertices[7] = vertices[0];
for(int i = 0; i < 8; ++i)
DwTo4UB(dwClr, vertices[i].color);
for(auto & vertex : vertices)
DwTo4UB(dwClr, vertex.color);
PerformMultiLines(sfcDest, vertices, 8, width, nullptr);
}
@ -753,19 +753,19 @@ void C4Draw::SetGamma(float r, float g, float b, int32_t iRampIndex)
// Recalculate resulting gamma. Note that we flip gamma direction here,
// because higher gammaOut means darker.
gammaOut[0] = gammaOut[1] = gammaOut[2] = 1.0f;
for (int i = 0; i < C4MaxGammaRamps; i++) {
gammaOut[0] /= gamma[i][0];
gammaOut[1] /= gamma[i][1];
gammaOut[2] /= gamma[i][2];
for (auto & i : gamma) {
gammaOut[0] /= i[0];
gammaOut[1] /= i[1];
gammaOut[2] /= i[2];
}
}
void C4Draw::ResetGamma()
{
for (int i = 0; i < C4MaxGammaRamps; i++) {
gamma[i][0] = 1.0f;
gamma[i][1] = 1.0f;
gamma[i][2] = 1.0f;
for (auto & i : gamma) {
i[0] = 1.0f;
i[1] = 1.0f;
i[2] = 1.0f;
}
gammaOut[0] = 1.0f;
gammaOut[1] = 1.0f;

View File

@ -35,8 +35,8 @@
#define _USE_MATH_DEFINES
#endif /* _MSC_VER */
#include <stdio.h>
#include <math.h>
#include <cstdio>
#include <cmath>
namespace
{
@ -105,7 +105,7 @@ namespace
#undef USERPARAM_CONST
CStdGL::CStdGL():
pMainCtx(0), CurrentVBO(0), NextVAOID(VAOIDs.end())
pMainCtx(nullptr), CurrentVBO(0), NextVAOID(VAOIDs.end())
{
GenericVBOs[0] = 0;
Default();
@ -146,7 +146,7 @@ void CStdGL::Clear()
SpriteShaderLightBaseNormalOverlayMod2.Clear();
// clear context
if (pCurrCtx) pCurrCtx->Deselect();
pMainCtx=0;
pMainCtx=nullptr;
C4Draw::Clear();
}
@ -323,9 +323,9 @@ CStdGLCtx *CStdGL::CreateContext(C4Window * pWindow, C4AbstractApp *pApp)
// Must log after context creation to get valid results
if (first_ctx)
{
const char *gl_vendor = reinterpret_cast<const char *>(glGetString(GL_VENDOR));
const char *gl_renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
const char *gl_version = reinterpret_cast<const char *>(glGetString(GL_VERSION));
const auto *gl_vendor = reinterpret_cast<const char *>(glGetString(GL_VENDOR));
const auto *gl_renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
const auto *gl_version = reinterpret_cast<const char *>(glGetString(GL_VERSION));
LogF("GL %s on %s (%s)", gl_version ? gl_version : "", gl_renderer ? gl_renderer : "", gl_vendor ? gl_vendor : "");
if (Config.Graphics.DebugOpenGL)
@ -831,8 +831,8 @@ bool CStdGL::InvalidateDeviceObjects()
glDeleteBuffers(N_GENERIC_VBOS, GenericVBOs);
GenericVBOs[0] = 0;
CurrentVBO = 0;
for (unsigned int i = 0; i < N_GENERIC_VBOS * 2; ++i)
FreeVAOID(GenericVAOs[i]);
for (unsigned int GenericVAO : GenericVAOs)
FreeVAOID(GenericVAO);
}
// invalidate shaders
@ -991,9 +991,8 @@ void CStdGL::FreeVAOID(unsigned int vaoid)
// For all other contexts, mark it to be deleted as soon as we select
// that context. Otherwise we would need to do a lot of context
// switching at this point.
for (std::list<CStdGLCtx*>::iterator iter = CStdGLCtx::contexts.begin(); iter != CStdGLCtx::contexts.end(); ++iter)
for (auto ctx : CStdGLCtx::contexts)
{
CStdGLCtx* ctx = *iter;
if (ctx != pCurrCtx && vaoid < ctx->hVAOs.size() && ctx->hVAOs[vaoid] != 0)
if (std::find(ctx->VAOsToBeDeleted.begin(), ctx->VAOsToBeDeleted.end(), vaoid) == ctx->VAOsToBeDeleted.end())
ctx->VAOsToBeDeleted.push_back(vaoid);

View File

@ -42,12 +42,12 @@ void CStdGLCtx::SelectCommon()
std::vector<GLuint> toBeDeleted;
if (!VAOsToBeDeleted.empty())
{
for (unsigned int i = 0; i < VAOsToBeDeleted.size(); ++i)
for (unsigned int i : VAOsToBeDeleted)
{
if (VAOsToBeDeleted[i] < hVAOs.size() && hVAOs[VAOsToBeDeleted[i]] != 0)
if (i < hVAOs.size() && hVAOs[i] != 0)
{
toBeDeleted.push_back(hVAOs[VAOsToBeDeleted[i]]);
hVAOs[VAOsToBeDeleted[i]] = 0;
toBeDeleted.push_back(hVAOs[i]);
hVAOs[i] = 0;
}
}
@ -61,7 +61,7 @@ void CStdGLCtx::SelectCommon()
#include <GL/wglew.h>
static PIXELFORMATDESCRIPTOR pfd; // desired pixel format
static HGLRC hrc = 0;
static HGLRC hrc = nullptr;
// Enumerate available pixel formats. Choose the best pixel format in
// terms of color and depth buffer bits and then return all formats with
@ -143,17 +143,17 @@ static std::vector<int> EnumeratePixelFormats(HDC hdc)
static int GetPixelFormatForMS(HDC hDC, int samples)
{
std::vector<int> vec = EnumeratePixelFormats(hDC);
for(unsigned int i = 0; i < vec.size(); ++i)
for(int i : vec)
{
int attributes[] = { WGL_SAMPLE_BUFFERS_ARB, WGL_SAMPLES_ARB };
const unsigned int n_attributes = 2;
int results[2];
if(!wglGetPixelFormatAttribivARB(hDC, vec[i], 0, n_attributes, attributes, results)) continue;
if(!wglGetPixelFormatAttribivARB(hDC, i, 0, n_attributes, attributes, results)) continue;
if( (samples == 0 && results[0] == 0) ||
(samples > 0 && results[0] == 1 && results[1] == samples))
{
return vec[i];
return i;
}
}
@ -171,9 +171,9 @@ public:
private:
static std::string format_error(error_code err)
{
LPWSTR buffer = 0;
LPWSTR buffer = nullptr;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
0, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&buffer), 0, 0);
nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&buffer), 0, nullptr);
StdStrBuf str(buffer);
LocalFree(buffer);
return std::string(str.getData(), str.getLength());
@ -188,7 +188,7 @@ class GLTempContext
public:
GLTempContext()
{
wnd = CreateWindowExW(0, L"STATIC", 0, WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, 0, 0, GetModuleHandle(0), 0);
wnd = CreateWindowExW(0, L"STATIC", nullptr, WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
if (!wnd)
throw WinAPIError();
dc = GetDC(wnd);
@ -201,7 +201,7 @@ public:
int format = ChoosePixelFormat(dc, &pfd);
if (!format ||
!SetPixelFormat(dc, format, &pfd) ||
(glrc = wglCreateContext(dc)) == 0)
(glrc = wglCreateContext(dc)) == nullptr)
{
DWORD err = GetLastError();
ReleaseDC(wnd, dc);
@ -220,22 +220,22 @@ public:
~GLTempContext()
{
if (glrc == wglGetCurrentContext())
wglMakeCurrent(dc, 0);
wglMakeCurrent(dc, nullptr);
wglDeleteContext(glrc);
ReleaseDC(wnd, dc);
DestroyWindow(wnd);
}
};
CStdGLCtx::CStdGLCtx(): pWindow(0), hDC(0), this_context(contexts.end()) { }
CStdGLCtx::CStdGLCtx(): pWindow(nullptr), hDC(nullptr), this_context(contexts.end()) { }
void CStdGLCtx::Clear(bool multisample_change)
{
Deselect();
if (hDC && pWindow)
ReleaseDC(pWindow->renderwnd, hDC);
hDC = 0;
pWindow = 0;
hDC = nullptr;
pWindow = nullptr;
if (this_context != contexts.end())
{
@ -247,7 +247,7 @@ void CStdGLCtx::Clear(bool multisample_change)
assert(!pGL->pCurrCtx);
if (hrc)
wglDeleteContext(hrc);
hrc = 0;
hrc = nullptr;
}
}
@ -257,12 +257,12 @@ bool CStdGLCtx::Init(C4Window * pWindow, C4AbstractApp *pApp)
if (!pGL || !pWindow) return false;
std::unique_ptr<GLTempContext> tempContext;
if (hrc == 0)
if (hrc == nullptr)
{
// Create a temporary context to be able to fetch GL extension pointers
try
{
tempContext.reset(new GLTempContext);
tempContext = std::make_unique<GLTempContext>();
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if(err != GLEW_OK)
@ -330,7 +330,7 @@ bool CStdGLCtx::Init(C4Window * pWindow, C4AbstractApp *pApp)
0
};
hrc = wglCreateContextAttribsARB(hDC, 0, attribs);
hrc = wglCreateContextAttribsARB(hDC, nullptr, attribs);
}
if (!hrc)
@ -345,7 +345,7 @@ bool CStdGLCtx::Init(C4Window * pWindow, C4AbstractApp *pApp)
0
};
pGL->Workarounds.ForceSoftwareTransform = true;
hrc = wglCreateContextAttribsARB(hDC, 0, attribs);
hrc = wglCreateContextAttribsARB(hDC, nullptr, attribs);
}
}
else
@ -390,12 +390,12 @@ std::vector<int> CStdGLCtx::EnumerateMultiSamples() const
{
std::vector<int> result;
std::vector<int> vec = EnumeratePixelFormats(hDC);
for(unsigned int i = 0; i < vec.size(); ++i)
for(int i : vec)
{
int attributes[] = { WGL_SAMPLE_BUFFERS_ARB, WGL_SAMPLES_ARB };
const unsigned int n_attributes = 2;
int results[2];
if(!wglGetPixelFormatAttribivARB(hDC, vec[i], 0, n_attributes, attributes, results)) continue;
if(!wglGetPixelFormatAttribivARB(hDC, i, 0, n_attributes, attributes, results)) continue;
if(results[0] == 1) result.push_back(results[1]);
}

View File

@ -26,7 +26,7 @@
#include "lib/StdMesh.h"
#include "graphics/C4GraphicsResource.h"
#include <locale.h>
#include <clocale>
#include <stdexcept>
#ifndef USE_CONSOLE
@ -215,9 +215,8 @@ namespace
// units that actually use a texture.
unsigned int texIndex = 0;
StdStrBuf textureUnitCode(""), textureUnitDeclCode("");
for(unsigned int i = 0; i < pass.TextureUnits.size(); ++i)
for(const auto & texunit : pass.TextureUnits)
{
const StdMeshMaterialTextureUnit& texunit = pass.TextureUnits[i];
textureUnitCode.Append(TextureUnitToCode(texIndex, texunit));
if(texunit.HasTexture())
@ -294,16 +293,15 @@ bool CStdGL::PrepareMaterial(StdMeshMatManager& mat_manager, StdMeshMaterialLoad
max_texture_units = std::min<GLint>(max_texture_units, 16);
unsigned int active_texture_units = 0;
for(unsigned int k = 0; k < pass.TextureUnits.size(); ++k)
if(pass.TextureUnits[k].HasTexture())
for(auto & TextureUnit : pass.TextureUnits)
if(TextureUnit.HasTexture())
++active_texture_units;
if (active_texture_units > static_cast<unsigned int>(max_texture_units))
technique.Available = false;
for (unsigned int k = 0; k < pass.TextureUnits.size(); ++k)
for (auto & texunit : pass.TextureUnits)
{
StdMeshMaterialTextureUnit& texunit = pass.TextureUnits[k];
for (unsigned int l = 0; l < texunit.GetNumTextures(); ++l)
{
const C4TexRef& texture = texunit.GetTexture(l);
@ -566,9 +564,8 @@ namespace
StdProjectionMatrix matrix = StdProjectionMatrix::Identity();
const double Position = instance.GetTexturePosition(passIndex, texUnitIndex);
for (unsigned int k = 0; k < texunit.Transformations.size(); ++k)
for (const auto & trans : texunit.Transformations)
{
const StdMeshMaterialTextureUnit::Transformation& trans = texunit.Transformations[k];
StdProjectionMatrix temp_matrix;
switch (trans.TransformType)
{
@ -913,12 +910,12 @@ namespace
// Set uniforms and instance parameters
SetStandardUniforms(call, dwModClr, dwPlayerColor, dwBlitMode, pass.CullHardware != StdMeshMaterialPass::CH_None, pFoW, clipRect, outRect);
for(unsigned int j = 0; j < pass.Program->Parameters.size(); ++j)
for(auto & Parameter : pass.Program->Parameters)
{
const int uniform = pass.Program->Parameters[j].UniformIndex;
const int uniform = Parameter.UniformIndex;
if(!shader->HaveUniform(uniform)) continue; // optimized out
const StdMeshMaterialShaderParameter* parameter = pass.Program->Parameters[j].Parameter;
const StdMeshMaterialShaderParameter* parameter = Parameter.Parameter;
StdMeshMaterialShaderParameter auto_resolved;
if(parameter->GetType() == StdMeshMaterialShaderParameter::AUTO)

View File

@ -52,7 +52,7 @@ bool C4FontLoader::InitFont(CStdFont * rFont, const char *szFontName, FontType e
assert(szFontName);
if (!szFontName || !*szFontName)
{
LogFatal(FormatString("%s (\"%s\")", LoadResStr("IDS_ERR_INITFONTS"), szFontName ? szFontName : "(null)").getData());
LogFatal(FormatString(R"(%s ("%s"))", LoadResStr("IDS_ERR_INITFONTS"), szFontName ? szFontName : "(null)").getData());
return false;
}
// if def has not been found, use the def as font name

View File

@ -337,8 +337,8 @@ bool C4GraphicsResource::RegisterGlobalGraphics()
// then be kept.
// The cleanest alternative would be to reinit all the fonts whenever a scenario is reloaded
// FIXME: Test whether vector fonts from a scenario are correctly reloaded
C4Group *pMainGfxGrp = new C4Group();
if (!Reloc.Open(*pMainGfxGrp, C4CFN_Graphics) || !Files.RegisterGroup(*pMainGfxGrp, true, C4GSPrio_Base, C4GSCnt_Graphics, 1))
auto *pMainGfxGrp = new C4Group();
if (!Reloc.Open(*pMainGfxGrp, C4CFN_Graphics) || !Files.RegisterGroup(*pMainGfxGrp, true, C4GSPrio_Base, C4GSCnt_Graphics, true))
{
// error
LogFatal(FormatString(LoadResStr("IDS_PRC_NOGFXFILE"),C4CFN_Graphics,pMainGfxGrp->GetError()).getData());

View File

@ -145,7 +145,7 @@ void C4Shader::AddSlice(ShaderSliceList& slices, int iPos, const char *szText, c
void C4Shader::AddSlices(ShaderSliceList& slices, const char *szWhat, const char *szText, const char *szSource, int iSourceTime)
{
if (std::find(SourceFiles.cbegin(), SourceFiles.cend(), szSource) == SourceFiles.cend())
SourceFiles.push_back(szSource);
SourceFiles.emplace_back(szSource);
const char *pStart = szText, *pPos = szText;
int iDepth = -1;
@ -265,9 +265,9 @@ int C4Shader::ParsePosition(const char *szWhat, const char **ppPos)
// Lookup name
int iPosition = -1;
for (unsigned int i = 0; i < sizeof(C4SH_PosNames) / sizeof(*C4SH_PosNames); i++) {
if (SEqual(Name.getData(), C4SH_PosNames[i].Name)) {
iPosition = C4SH_PosNames[i].Position;
for (auto & PosName : C4SH_PosNames) {
if (SEqual(Name.getData(), PosName.Name)) {
iPosition = PosName.Position;
break;
}
}
@ -540,8 +540,8 @@ bool C4Shader::Refresh()
&UniformNames[0],
&AttributeNames[0]
#else
0,
0
nullptr,
nullptr
#endif
))
return false;
@ -574,26 +574,26 @@ StdStrBuf C4Shader::Build(const ShaderSliceList &Slices, bool fDebug)
// 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++)
for (const auto & Slice : Slices)
{
if (pSlice->Position < iPos) continue;
if (pSlice->Position > iPos)
if (Slice.Position < iPos) continue;
if (Slice.Position > iPos)
{
iNextPos = std::min(iNextPos, pSlice->Position);
iNextPos = std::min(iNextPos, Slice.Position);
continue;
}
// Same position - add slice!
if (fDebug)
{
if (pSlice->Source.getLength())
if (Slice.Source.getLength())
{
// GLSL below 3.30 consider the line after a #line N directive to be N + 1; 3.30 and higher consider it N
Buf.AppendFormat("\t// Slice from %s:\n#line %d %d\n", pSlice->Source.getData(), pSlice->SourceLine - (C4Shader_Version < 330), GetSourceFileId(pSlice->Source.getData()) + 1);
Buf.AppendFormat("\t// Slice from %s:\n#line %d %d\n", Slice.Source.getData(), Slice.SourceLine - (C4Shader_Version < 330), GetSourceFileId(Slice.Source.getData()) + 1);
}
else
Buf.Append("\t// Built-in slice:\n#line 1 0\n");
}
Buf.Append(pSlice->Text);
Buf.Append(Slice.Text);
if (Buf[Buf.getLength()-1] != '\n')
Buf.AppendChar('\n');
}
@ -621,7 +621,7 @@ GLuint C4Shader::Create(GLenum iShaderType, const char *szWhat, const char *szSh
pGL->ObjectLabel(GL_SHADER, hShader, -1, szWhat);
// Compile
glShaderSource(hShader, 1, &szShader, 0);
glShaderSource(hShader, 1, &szShader, nullptr);
glCompileShader(hShader);
// Dump any information to log

View File

@ -37,11 +37,11 @@
#include <io.h>
#endif
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <list>
C4Surface::C4Surface() : fIsBackground(false)
@ -142,7 +142,7 @@ void C4Surface::Clear()
if (pCtx)
{
delete pCtx;
pCtx = 0;
pCtx = nullptr;
}
#endif
texture.reset();
@ -485,7 +485,7 @@ bool C4Surface::Unlock()
{
// emulated primary locks in OpenGL
delete[] PrimarySurfaceLockBits;
PrimarySurfaceLockBits = 0;
PrimarySurfaceLockBits = nullptr;
return true;
}
else
@ -683,7 +683,7 @@ C4TexRef::~C4TexRef()
#ifndef USE_CONSOLE
if (pGL && pGL->pCurrCtx) glDeleteTextures(1, &texName);
#endif
if (pDraw) delete [] static_cast<unsigned char*>(texLock.pBits); texLock.pBits = 0;
if (pDraw) delete [] static_cast<unsigned char*>(texLock.pBits); texLock.pBits = nullptr;
// remove from texture manager
pTexMgr->UnregTex(this);
}

View File

@ -235,7 +235,7 @@ extern "C"
#undef FAR
#include <jpeglib.h>
}
#include <setjmp.h>
#include <csetjmp>
// Straight from the libjpeg example
struct my_error_mgr

View File

@ -309,13 +309,13 @@ private:
static std::list<CPNGSaveThread *> threads;
public:
CPNGSaveThread(CPNGFile *png, const char *filename);
virtual ~CPNGSaveThread();
~CPNGSaveThread() override;
static bool HasPendingThreads();
protected:
virtual void Execute();
virtual bool IsSelfDestruct() { return true; }
void Execute() override;
bool IsSelfDestruct() override { return true; }
};
CStdCSec CPNGSaveThread::threads_sec;

View File

@ -76,8 +76,8 @@ void C4ChatControl::ChatSheet::NickItem::Update(class C4Network2IRCUser *pByUser
int32_t C4ChatControl::ChatSheet::NickItem::SortFunc(const C4GUI::Element *pEl1, const C4GUI::Element *pEl2, void *)
{
const NickItem *pNickItem1 = static_cast<const NickItem *>(pEl1);
const NickItem *pNickItem2 = static_cast<const NickItem *>(pEl2);
const auto *pNickItem1 = static_cast<const NickItem *>(pEl1);
const auto *pNickItem2 = static_cast<const NickItem *>(pEl2);
int32_t s1 = pNickItem1->GetStatus(), s2 = pNickItem2->GetStatus();
if (s1 != s2) return s1 - s2;
return stricmp(pNickItem2->GetNick(), pNickItem1->GetNick());
@ -92,7 +92,7 @@ C4ChatControl::ChatSheet::ChatSheet(C4ChatControl *pChatControl, const char *szT
if (szIdent) sIdent.Copy(szIdent);
// create elements - positioned later
C4Rect rcDefault(0,0,10,10);
pChatBox = new C4GUI::TextWindow(rcDefault,0,0,0,100,4096," ",false,0,0,true);
pChatBox = new C4GUI::TextWindow(rcDefault,0,0,0,100,4096," ",false,nullptr,0,true);
pChatBox->SetDecoration(false, false, nullptr, false);
AddElement(pChatBox);
if (eType == CS_Channel)
@ -961,9 +961,7 @@ C4ChatDlg::C4ChatDlg() : C4GUI::Dialog(100, 100, "IRC", false)
SetFocus(GetDefaultControl(), false);
}
C4ChatDlg::~C4ChatDlg()
{
}
C4ChatDlg::~C4ChatDlg() = default;
C4ChatDlg *C4ChatDlg::ShowChat()
{

View File

@ -47,9 +47,7 @@ C4FileSelDlg::ListItem::ListItem(const char *szFilename) : C4GUI::Control(C4Rect
if (szFilename) sFilename.Copy(szFilename); else sFilename.Clear();
}
C4FileSelDlg::ListItem::~ListItem()
{
}
C4FileSelDlg::ListItem::~ListItem() = default;
// ---------------------------------------------------
// C4FileSelDlg::DefaultListItem

View File

@ -459,9 +459,7 @@ namespace C4GUI
// LDownX/Y initialized upon need
}
CMouse::~CMouse()
{
}
CMouse::~CMouse() = default;
void CMouse::Input(int32_t iButton, int32_t iX, int32_t iY, DWORD dwKeyParam)
{

View File

@ -36,8 +36,8 @@ namespace C4GUI
{
// key callbacks
C4CustomKey::CodeList keys;
keys.push_back(C4KeyCodeEx(K_SPACE));
keys.push_back(C4KeyCodeEx(K_RETURN));
keys.emplace_back(K_SPACE);
keys.emplace_back(K_RETURN);
if (Config.Controls.GamepadGuiControl)
ControllerKeys::Ok(keys);
pKeyButton = new C4KeyBinding(keys, "GUIButtonPress", KEYSCOPE_Gui,

View File

@ -43,7 +43,7 @@ namespace C4GUI
}
// key callbacks: Check/Uncheck on space and primary joy button
C4CustomKey::CodeList Keys;
Keys.push_back(C4KeyCodeEx(K_SPACE));
Keys.emplace_back(K_SPACE);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Ok(Keys);

View File

@ -71,10 +71,10 @@ namespace C4GUI
*Text=0;
// key callbacks - lots of possibilities to get the dropdown
C4CustomKey::CodeList cbKeys;
cbKeys.push_back(C4KeyCodeEx(K_DOWN));
cbKeys.push_back(C4KeyCodeEx(K_SPACE));
cbKeys.push_back(C4KeyCodeEx(K_DOWN, KEYS_Alt));
cbKeys.push_back(C4KeyCodeEx(K_SPACE, KEYS_Alt));
cbKeys.emplace_back(K_DOWN);
cbKeys.emplace_back(K_SPACE);
cbKeys.emplace_back(K_DOWN, KEYS_Alt);
cbKeys.emplace_back(K_SPACE, KEYS_Alt);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Ok(cbKeys);
@ -83,7 +83,7 @@ namespace C4GUI
pKeyOpenCombo = new C4KeyBinding(cbKeys, "GUIComboOpen", KEYSCOPE_Gui,
new ControlKeyCB<ComboBox>(*this, &ComboBox::KeyDropDown), C4CustomKey::PRIO_Ctrl);
cbKeys.clear();
cbKeys.push_back(C4KeyCodeEx(K_ESCAPE));
cbKeys.emplace_back(K_ESCAPE);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Cancel(cbKeys);

View File

@ -285,7 +285,7 @@ namespace C4GUI
SetBounds(C4Rect(0,0,iWdt,iHgt));
// create key callbacks
C4CustomKey::CodeList Keys;
Keys.push_back(C4KeyCodeEx(K_TAB));
Keys.emplace_back(K_TAB);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Right(Keys);
@ -293,7 +293,7 @@ namespace C4GUI
pKeyAdvanceControl = new C4KeyBinding(Keys, "GUIAdvanceFocus", KEYSCOPE_Gui,
new DlgKeyCBEx<Dialog, bool>(*this, false, &Dialog::KeyAdvanceFocus), C4CustomKey::PRIO_Dlg);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_TAB, KEYS_Shift));
Keys.emplace_back(K_TAB, KEYS_Shift);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Left(Keys);
@ -301,12 +301,12 @@ namespace C4GUI
pKeyAdvanceControlB = new C4KeyBinding(Keys, "GUIAdvanceFocusBack", KEYSCOPE_Gui,
new DlgKeyCBEx<Dialog, bool>(*this, true, &Dialog::KeyAdvanceFocus), C4CustomKey::PRIO_Dlg);
Keys.clear();
Keys.push_back(C4KeyCodeEx(KEY_Any, KEYS_Alt));
Keys.push_back(C4KeyCodeEx(KEY_Any, C4KeyShiftState(KEYS_Alt | KEYS_Shift)));
Keys.emplace_back(KEY_Any, KEYS_Alt);
Keys.emplace_back(KEY_Any, C4KeyShiftState(KEYS_Alt | KEYS_Shift));
pKeyHotkey = new C4KeyBinding(Keys, "GUIHotkey", KEYSCOPE_Gui,
new DlgKeyCBPassKey<Dialog>(*this, &Dialog::KeyHotkey), C4CustomKey::PRIO_Ctrl);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_RETURN));
Keys.emplace_back(K_RETURN);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Ok(Keys);
@ -314,7 +314,7 @@ namespace C4GUI
pKeyEnter = new C4KeyBinding(Keys, "GUIDialogOkay", KEYSCOPE_Gui,
new DlgKeyCB<Dialog>(*this, &Dialog::KeyEnter), C4CustomKey::PRIO_Dlg);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_ESCAPE));
Keys.emplace_back(K_ESCAPE);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Cancel(Keys);
@ -322,8 +322,8 @@ namespace C4GUI
pKeyEscape = new C4KeyBinding(Keys, "GUIDialogAbort", KEYSCOPE_Gui,
new DlgKeyCB<Dialog>(*this, &Dialog::KeyEscape), C4CustomKey::PRIO_Dlg);
Keys.clear();
Keys.push_back(C4KeyCodeEx(KEY_Any));
Keys.push_back(C4KeyCodeEx(KEY_Any, KEYS_Shift));
Keys.emplace_back(KEY_Any);
Keys.emplace_back(KEY_Any, KEYS_Shift);
pKeyFocusDefControl = new C4KeyBinding(Keys, "GUIFocusDefault", KEYSCOPE_Gui,
new DlgKeyCB<Dialog>(*this, &Dialog::KeyFocusDefault), C4CustomKey::PRIO_Dlg);
}
@ -997,7 +997,7 @@ bool MessageDialog::KeyCopy()
// ProgressDialog
ProgressDialog::ProgressDialog(const char *szMessage, const char *szCaption, int32_t iMaxProgress, int32_t iInitialProgress, Icons icoIcon)
: Dialog(C4GUI_ProgressDlgWdt, std::max(::GraphicsResource.TextFont.BreakMessage(szMessage, C4GUI_ProgressDlgWdt-3*C4GUI_DefDlgIndent-C4GUI_IconWdt, 0, 0, true), C4GUI_IconHgt) + C4GUI_ProgressDlgVRoom, szCaption, false)
: Dialog(C4GUI_ProgressDlgWdt, std::max(::GraphicsResource.TextFont.BreakMessage(szMessage, C4GUI_ProgressDlgWdt-3*C4GUI_DefDlgIndent-C4GUI_IconWdt, nullptr, 0, true), C4GUI_IconHgt) + C4GUI_ProgressDlgVRoom, szCaption, false)
{
// get positions
ComponentAligner caMain(GetClientRect(), C4GUI_DefDlgIndent, C4GUI_DefDlgIndent, true);
@ -1101,7 +1101,7 @@ bool MessageDialog::KeyCopy()
InputDialog::InputDialog(const char *szMessage, const char *szCaption, Icons icoIcon, BaseInputCallback *pCB, bool fChatLayout)
: Dialog(fChatLayout ? C4GUI::GetScreenWdt()*4/5 : C4GUI_InputDlgWdt,
fChatLayout ? C4GUI::Edit::GetDefaultEditHeight() + 2 :
std::max(::GraphicsResource.TextFont.BreakMessage(szMessage, C4GUI_InputDlgWdt - 3 * C4GUI_DefDlgIndent - C4GUI_IconWdt, 0, 0, true),
std::max(::GraphicsResource.TextFont.BreakMessage(szMessage, C4GUI_InputDlgWdt - 3 * C4GUI_DefDlgIndent - C4GUI_IconWdt, nullptr, 0, true),
C4GUI_IconHgt) + C4GUI_InputDlgVRoom, szCaption, false),
pEdit(nullptr), pCB(pCB), fChatLayout(fChatLayout), pChatLbl(nullptr)
{

View File

@ -103,10 +103,10 @@ namespace C4GUI
{
// register same op for all shift states; distinction will be done in handling proc
C4CustomKey::CodeList KeyList;
KeyList.push_back(C4KeyCodeEx(key));
KeyList.push_back(C4KeyCodeEx(key, KEYS_Shift));
KeyList.push_back(C4KeyCodeEx(key, KEYS_Control));
KeyList.push_back(C4KeyCodeEx(key, C4KeyShiftState(KEYS_Shift | KEYS_Control)));
KeyList.emplace_back(key);
KeyList.emplace_back(key, KEYS_Shift);
KeyList.emplace_back(key, KEYS_Control);
KeyList.emplace_back(key, C4KeyShiftState(KEYS_Shift | KEYS_Control));
return new C4KeyBinding(KeyList, szName, KEYSCOPE_Gui, new ControlKeyCBExPassKey<Edit, CursorOperation>(*this, op, &Edit::KeyCursorOp), eKeyPrio);
}
@ -707,7 +707,7 @@ namespace C4GUI
else pPrevFocusCtrl=nullptr;
// key binding for rename abort
C4CustomKey::CodeList keys;
keys.push_back(C4KeyCodeEx(K_ESCAPE));
keys.emplace_back(K_ESCAPE);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Cancel(keys);

View File

@ -467,9 +467,7 @@ namespace C4GUI
fctPaint.Create(iSfcWdt, iSfcHgt);
}
PaintBox::~PaintBox()
{
}
PaintBox::~PaintBox() = default;
// --------------------------------------------------

View File

@ -43,22 +43,22 @@ namespace C4GUI
pKeyContext = new C4KeyBinding(C4KeyCodeEx(K_MENU), "GUIListBoxContext", KEYSCOPE_Gui,
new ControlKeyCB<ListBox>(*this, &ListBox::KeyContext), C4CustomKey::PRIO_Ctrl);
C4CustomKey::CodeList keys;
keys.push_back(C4KeyCodeEx(K_UP));
keys.emplace_back(K_UP);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Up(keys);
pKeyUp = new C4KeyBinding(keys, "GUIListBoxUp", KEYSCOPE_Gui,
new ControlKeyCB<ListBox>(*this, &ListBox::KeyUp), C4CustomKey::PRIO_Ctrl);
keys.clear();
keys.push_back(C4KeyCodeEx(K_DOWN));
keys.emplace_back(K_DOWN);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Down(keys);
pKeyDown = new C4KeyBinding(keys, "GUIListBoxDown", KEYSCOPE_Gui,
new ControlKeyCB<ListBox>(*this, &ListBox::KeyDown), C4CustomKey::PRIO_Ctrl);
keys.clear();
keys.push_back(C4KeyCodeEx(K_LEFT));
keys.emplace_back(K_LEFT);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Left(keys);
pKeyLeft = new C4KeyBinding(keys, "GUIListBoxLeft", KEYSCOPE_Gui,
new ControlKeyCB<ListBox>(*this, &ListBox::KeyLeft), C4CustomKey::PRIO_Ctrl);
keys.clear();
keys.push_back(C4KeyCodeEx(K_RIGHT));
keys.emplace_back(K_RIGHT);
if (Config.Controls.GamepadGuiControl) ControllerKeys::Right(keys);
pKeyRight = new C4KeyBinding(keys, "GUIListBoxRight", KEYSCOPE_Gui,
new ControlKeyCB<ListBox>(*this, &ListBox::KeyRight), C4CustomKey::PRIO_Ctrl);
@ -72,8 +72,8 @@ namespace C4GUI
new ControlKeyCB<ListBox>(*this, &ListBox::KeyEnd), C4CustomKey::PRIO_Ctrl);
// "activate" current item
keys.clear();
keys.push_back(C4KeyCodeEx(K_RETURN));
keys.push_back(C4KeyCodeEx(K_RETURN, KEYS_Alt));
keys.emplace_back(K_RETURN);
keys.emplace_back(K_RETURN, KEYS_Alt);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Ok(keys);

View File

@ -92,7 +92,7 @@ namespace C4GUI
rcBounds.Wdt=40; rcBounds.Hgt=7;
// key bindings
C4CustomKey::CodeList Keys;
Keys.push_back(C4KeyCodeEx(K_UP));
Keys.emplace_back(K_UP);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Up(Keys);
@ -101,7 +101,7 @@ namespace C4GUI
new C4KeyCB<ContextMenu>(*this, &ContextMenu::KeySelUp), C4CustomKey::PRIO_Context);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_DOWN));
Keys.emplace_back(K_DOWN);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Down(Keys);
@ -110,7 +110,7 @@ namespace C4GUI
new C4KeyCB<ContextMenu>(*this, &ContextMenu::KeySelDown), C4CustomKey::PRIO_Context);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_RIGHT));
Keys.emplace_back(K_RIGHT);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Right(Keys);
@ -119,7 +119,7 @@ namespace C4GUI
new C4KeyCB<ContextMenu>(*this, &ContextMenu::KeySubmenu), C4CustomKey::PRIO_Context);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_LEFT));
Keys.emplace_back(K_LEFT);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Left(Keys);
@ -128,7 +128,7 @@ namespace C4GUI
new C4KeyCB<ContextMenu>(*this, &ContextMenu::KeyBack), C4CustomKey::PRIO_Context);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_ESCAPE));
Keys.emplace_back(K_ESCAPE);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Cancel(Keys);
@ -137,7 +137,7 @@ namespace C4GUI
new C4KeyCB<ContextMenu>(*this, &ContextMenu::KeyAbort), C4CustomKey::PRIO_Context);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_RETURN));
Keys.emplace_back(K_RETURN);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Ok(Keys);
@ -589,12 +589,12 @@ namespace C4GUI
{
// reg keys for pressing the context button
C4CustomKey::CodeList ContextKeys;
ContextKeys.push_back(C4KeyCodeEx(K_RIGHT));
ContextKeys.push_back(C4KeyCodeEx(K_DOWN));
ContextKeys.push_back(C4KeyCodeEx(K_SPACE));
ContextKeys.push_back(C4KeyCodeEx(K_RIGHT, KEYS_Alt));
ContextKeys.push_back(C4KeyCodeEx(K_DOWN, KEYS_Alt));
ContextKeys.push_back(C4KeyCodeEx(K_SPACE, KEYS_Alt));
ContextKeys.emplace_back(K_RIGHT);
ContextKeys.emplace_back(K_DOWN);
ContextKeys.emplace_back(K_SPACE);
ContextKeys.emplace_back(K_RIGHT, KEYS_Alt);
ContextKeys.emplace_back(K_DOWN, KEYS_Alt);
ContextKeys.emplace_back(K_SPACE, KEYS_Alt);
pKeyContext = new C4KeyBinding(ContextKeys, "GUIContextButtonPress", KEYSCOPE_Gui,
new ControlKeyCB<ContextButton>(*this, &ContextButton::KeyContext), C4CustomKey::PRIO_Ctrl);
}

View File

@ -179,7 +179,7 @@ namespace C4GUI
// Ctrl+(Shift-)Tab works with dialog focus only (assumes max one tabular per dialog)
// Arrow keys work if control is focused only
C4CustomKey::CodeList Keys;
Keys.push_back(C4KeyCodeEx(K_UP));
Keys.emplace_back(K_UP);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Up(Keys);
@ -188,7 +188,7 @@ namespace C4GUI
new ControlKeyCB<Tabular>(*this, &Tabular::KeySelUp), C4CustomKey::PRIO_Ctrl);
Keys.clear();
Keys.push_back(C4KeyCodeEx(K_DOWN));
Keys.emplace_back(K_DOWN);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Down(Keys);

View File

@ -124,7 +124,7 @@ const C4KeyCodeMapEntry KeyCodeMap[] = {
{K_APOSTROPHE, "Apostrophe", "'"},
{K_GRAVE_ACCENT, "GraveAccent", "`"},
{K_SHIFT_L, "LeftShift", "LShift"},
{K_BACKSLASH, "Backslash", "\\"},
{K_BACKSLASH, "Backslash", R"(\)"},
{K_Z, "Z", nullptr},
{K_X, "X", nullptr},
{K_C, "C", nullptr},
@ -247,7 +247,7 @@ C4KeyCode C4KeyCodeEx::String2KeyCode(const StdStrBuf &sName)
if (sName.getLength() > 2)
{
unsigned int dwRVal;
if (sscanf(sName.getData(), "\\x%x", &dwRVal) == 1) return dwRVal;
if (sscanf(sName.getData(), R"(\x%x)", &dwRVal) == 1) return dwRVal;
// scan code
if (*sName.getData() == '$') return GetKeyByScanCode(sName.getData());
// direct gamepad code
@ -583,8 +583,8 @@ C4CustomKey::C4CustomKey(const C4KeyCodeEx &DefCode, const char *szName, C4KeySc
}
}
C4CustomKey::C4CustomKey(const CodeList &rDefCodes, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority)
: DefaultCodes(rDefCodes), Scope(Scope), Name(), uiPriority(uiPriority), iRef(0), is_down(false)
C4CustomKey::C4CustomKey(CodeList rDefCodes, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority)
: DefaultCodes(std::move(rDefCodes)), Scope(Scope), Name(), uiPriority(uiPriority), iRef(0), is_down(false)
{
// ctor for default key
Name.Copy(szName);
@ -602,10 +602,10 @@ C4CustomKey::C4CustomKey(const C4CustomKey &rCpy, bool fCopyCallbacks)
Name.Copy(rCpy.GetName());
if (fCopyCallbacks)
{
for (CBVec::const_iterator i = rCpy.vecCallbacks.begin(); i != rCpy.vecCallbacks.end(); ++i)
for (auto callback : rCpy.vecCallbacks)
{
(*i)->Ref();
vecCallbacks.push_back(*i);
callback->Ref();
vecCallbacks.push_back(callback);
}
}
}
@ -635,10 +635,10 @@ void C4CustomKey::Update(const C4CustomKey *pByKey)
if (pByKey->Codes.size()) Codes = pByKey->Codes;
if (pByKey->Scope != KEYSCOPE_None) Scope = pByKey->Scope;
if (pByKey->uiPriority != PRIO_None) uiPriority = pByKey->uiPriority;
for (CBVec::const_iterator i = pByKey->vecCallbacks.begin(); i != pByKey->vecCallbacks.end(); ++i)
for (auto callback : pByKey->vecCallbacks)
{
(*i)->Ref();
vecCallbacks.push_back(*i);
callback->Ref();
vecCallbacks.push_back(callback);
}
}
@ -669,8 +669,8 @@ bool C4CustomKey::Execute(C4KeyEventType eEv, C4KeyCodeEx key)
// remember down-state
is_down = (eEv == KEYEV_Down);
// execute all callbacks
for (CBVec::iterator i = vecCallbacks.begin(); i != vecCallbacks.end(); ++i)
if ((*i)->OnKeyEvent(key, eEv))
for (auto & callback : vecCallbacks)
if (callback->OnKeyEvent(key, eEv))
return true;
// no event processed it
return false;

View File

@ -451,7 +451,7 @@ public:
protected:
int iRef;
C4CustomKey(const C4KeyCodeEx &DefCode, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority = PRIO_Base); // ctor for default key
C4CustomKey(const CodeList &rDefCodes, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority = PRIO_Base); // ctor for default key with multiple possible keys assigned
C4CustomKey(CodeList rDefCodes, const char *szName, C4KeyScope Scope, C4KeyboardCallbackInterface *pCallback, unsigned int uiPriority = PRIO_Base); // ctor for default key with multiple possible keys assigned
friend class C4Game;
public:

View File

@ -124,8 +124,8 @@ void C4MessageBoard::Init(C4Facet &cgo, bool fStartup)
}
// messageboard
ScrollUpBinding.reset(new C4KeyBinding(C4KeyCodeEx(K_UP, KEYS_Shift), "MsgBoardScrollUp", KEYSCOPE_Fullscreen, new C4KeyCB <C4MessageBoard>(*GraphicsSystem.MessageBoard, &C4MessageBoard::ControlScrollUp)));
ScrollDownBinding.reset(new C4KeyBinding(C4KeyCodeEx(K_DOWN, KEYS_Shift), "MsgBoardScrollDown", KEYSCOPE_Fullscreen, new C4KeyCB <C4MessageBoard>(*GraphicsSystem.MessageBoard, &C4MessageBoard::ControlScrollDown)));
ScrollUpBinding = std::make_unique<C4KeyBinding>(C4KeyCodeEx(K_UP, KEYS_Shift), "MsgBoardScrollUp", KEYSCOPE_Fullscreen, new C4KeyCB <C4MessageBoard>(*GraphicsSystem.MessageBoard, &C4MessageBoard::ControlScrollUp));
ScrollDownBinding = std::make_unique<C4KeyBinding>(C4KeyCodeEx(K_DOWN, KEYS_Shift), "MsgBoardScrollDown", KEYSCOPE_Fullscreen, new C4KeyCB <C4MessageBoard>(*GraphicsSystem.MessageBoard, &C4MessageBoard::ControlScrollDown));
}
void C4MessageBoard::Draw(C4Facet &cgo)

View File

@ -116,8 +116,8 @@ C4GUI::Edit::InputResult C4ChatInputDialog::OnChatInput(C4GUI::Edit *edt, bool f
// no double processing
if (fProcessed) return C4GUI::Edit::IR_CloseDlg;
// get edit text
C4GUI::Edit *pEdt = reinterpret_cast<C4GUI::Edit *>(edt);
char *szInputText = const_cast<char *>(pEdt->GetText());
auto *pEdt = reinterpret_cast<C4GUI::Edit *>(edt);
auto *szInputText = const_cast<char *>(pEdt->GetText());
// Store to back buffer
::MessageInput.StoreBackBuffer(szInputText);
// script queried input?
@ -249,7 +249,7 @@ bool C4MessageInput::Init()
void C4MessageInput::Default()
{
// clear backlog
for (int32_t cnt=0; cnt<C4MSGB_BackBufferMax; cnt++) BackBuffer[cnt][0]=0;
for (auto & cnt : BackBuffer) cnt[0]=0;
}
void C4MessageInput::Clear()
@ -779,9 +779,9 @@ bool C4MessageInput::ProcessCommand(const char *szCommand)
// try writing main file (usually {SCENARIO}/TODO.txt); if access is not possible, e.g. because scenario is packed, write to alternate file
const char *todo_filenames[] = { ::Config.Developer.TodoFilename, ::Config.Developer.AltTodoFilename };
bool success = false;
for (int i = 0; i < static_cast<int>(std::extent<decltype(todo_filenames)>::value); ++i)
for (auto & i : todo_filenames)
{
StdCopyStrBuf todo_filename(todo_filenames[i]);
StdCopyStrBuf todo_filename(i);
todo_filename.Replace("{USERPATH}", Config.General.UserDataPath);
int replacements = todo_filename.Replace("{SCENARIO}", Game.ScenarioFile.GetFullName().getData());
// sanity checks for writing scenario TODO file

View File

@ -432,7 +432,7 @@ void C4MouseControl::Draw(C4TargetFacet &cgo, const ZoomData &GameZoom)
{
uint32_t ColorMod = DragImageObject->ColorMod;
uint32_t BlitMode = DragImageObject->BlitMode;
DragImageObject->ColorMod = (Drag == C4MC_Drag_Script) ? 0x7fffffff : (/*DragImagePhase*/0 ? 0x8f7f0000 : 0x1f007f00);
DragImageObject->ColorMod = (Drag == C4MC_Drag_Script) ? 0x7fffffff : (/*DragImagePhase*/false ? 0x8f7f0000 : 0x1f007f00);
DragImageObject->BlitMode = C4GFXBLIT_MOD2;
DragImageObject->DrawPicture(ccgo, false, nullptr);
@ -445,7 +445,7 @@ void C4MouseControl::Draw(C4TargetFacet &cgo, const ZoomData &GameZoom)
// draw in special modulation mode
pDraw->SetBlitMode(C4GFXBLIT_MOD2);
// draw DragImage in red or green, according to the phase to be used
pDraw->ActivateBlitModulation((Drag == C4MC_Drag_Script) ? 0x7fffffff : (/*DragImagePhase*/0 ? 0x8f7f0000 : 0x1f007f00));
pDraw->ActivateBlitModulation((Drag == C4MC_Drag_Script) ? 0x7fffffff : (/*DragImagePhase*/false ? 0x8f7f0000 : 0x1f007f00));
DragImageDef->Draw(ccgo, false, pPlayer ? pPlayer->ColorDw : 0xff0000ff, nullptr, 0, 0, nullptr);

View File

@ -34,19 +34,19 @@ private:
public:
C4ScoreboardDlg(C4Scoreboard *pForScoreboard);
~C4ScoreboardDlg();
~C4ScoreboardDlg() override;
protected:
void InvalidateRows() { delete [] piColWidths; piColWidths = nullptr; }
void Update(); // update row widths and own size and caption
virtual bool DoPlacement(C4GUI::Screen *pOnScreen, const C4Rect &rPreferredDlgRect);
virtual void Draw(C4TargetFacet &cgo);
virtual void DrawElement(C4TargetFacet &cgo);
bool DoPlacement(C4GUI::Screen *pOnScreen, const C4Rect &rPreferredDlgRect) override;
void Draw(C4TargetFacet &cgo) override;
void DrawElement(C4TargetFacet &cgo) override;
virtual const char *GetID() { return "Scoreboard"; }
const char *GetID() override { return "Scoreboard"; }
virtual bool IsMouseControlled() { return false; }
bool IsMouseControlled() override { return false; }
friend class C4Scoreboard;
};

View File

@ -129,13 +129,13 @@ const C4Value C4ScriptGuiWindowAction::ToC4Value(bool first)
void C4ScriptGuiWindowAction::ClearPointers(C4Object *pObj)
{
C4Object *targetObj = target ? target->GetObject() : 0;
C4Object *targetObj = target ? target->GetObject() : nullptr;
if (targetObj == pObj)
{
// not only forget object, but completely invalidate action
action = 0;
target = 0;
target = nullptr;
}
if (nextAction)
nextAction->ClearPointers(pObj);
@ -309,7 +309,7 @@ void C4ScriptGuiWindowProperty::SetNull(C4String *tag)
if (!tag) tag = &Strings.P[P_Std];
taggedProperties[tag] = Prop();
current = &taggedProperties[tag];
current->data = 0;
current->data = nullptr;
}
void C4ScriptGuiWindowProperty::CleanUp(Prop &prop)
@ -337,11 +337,11 @@ void C4ScriptGuiWindowProperty::CleanUp(Prop &prop)
void C4ScriptGuiWindowProperty::CleanUpAll()
{
for (std::map<C4String*, Prop>::iterator iter = taggedProperties.begin(); iter != taggedProperties.end(); ++iter)
for (auto & taggedProperty : taggedProperties)
{
CleanUp(iter->second);
if (iter->first != &Strings.P[P_Std])
iter->first->DecRef();
CleanUp(taggedProperty.second);
if (taggedProperty.first != &Strings.P[P_Std])
taggedProperty.first->DecRef();
}
}
@ -355,10 +355,10 @@ const C4Value C4ScriptGuiWindowProperty::ToC4Value()
// go through all of the tagged properties and add a property to the proplist containing both the tag name
// and the serialzed C4Value of the properties' value
for(std::map<C4String*, Prop>::iterator iter = taggedProperties.begin(); iter != taggedProperties.end(); ++iter)
for(auto & taggedProperty : taggedProperties)
{
C4String *tagString = iter->first;
const Prop &prop = iter->second;
C4String *tagString = taggedProperty.first;
const Prop &prop = taggedProperty.second;
C4Value val;
@ -517,7 +517,7 @@ void C4ScriptGuiWindowProperty::Set(const C4Value &value, C4String *tag)
C4PropList *symbol = value.getPropList();
if (symbol)
current->obj = symbol->GetObject();
else current->obj = 0;
else current->obj = nullptr;
break;
}
case C4ScriptGuiWindowPropertyName::symbolDef:
@ -525,7 +525,7 @@ void C4ScriptGuiWindowProperty::Set(const C4Value &value, C4String *tag)
C4PropList *symbol = value.getPropList();
if (symbol)
current->def = symbol->GetDef();
else current->def = 0;
else current->def = nullptr;
break;
}
case C4ScriptGuiWindowPropertyName::frameDecoration:
@ -538,7 +538,7 @@ void C4ScriptGuiWindowProperty::Set(const C4Value &value, C4String *tag)
if (!current->deco->SetByDef(def))
{
delete current->deco;
current->deco = 0;
current->deco = nullptr;
}
}
break;
@ -580,21 +580,21 @@ void C4ScriptGuiWindowProperty::ClearPointers(C4Object *pObj)
{
// assume that we actually contain an object
// go through all the tags and, in case the tag has anything to do with objects, check and clear it
for (std::map<C4String*, Prop>::iterator iter = taggedProperties.begin(); iter != taggedProperties.end(); ++iter)
for (auto & taggedProperty : taggedProperties)
{
switch (type)
{
case C4ScriptGuiWindowPropertyName::symbolObject:
if (iter->second.obj == pObj)
iter->second.obj = 0;
if (taggedProperty.second.obj == pObj)
taggedProperty.second.obj = nullptr;
break;
case C4ScriptGuiWindowPropertyName::onClickAction:
case C4ScriptGuiWindowPropertyName::onMouseInAction:
case C4ScriptGuiWindowPropertyName::onMouseOutAction:
case C4ScriptGuiWindowPropertyName::onCloseAction:
if (iter->second.action)
iter->second.action->ClearPointers(pObj);
if (taggedProperty.second.action)
taggedProperty.second.action->ClearPointers(pObj);
break;
default:
return;
@ -614,9 +614,9 @@ bool C4ScriptGuiWindowProperty::SwitchTag(C4String *tag)
std::list<C4ScriptGuiWindowAction*> C4ScriptGuiWindowProperty::GetAllActions()
{
std::list<C4ScriptGuiWindowAction*> allActions;
for (std::map<C4String*, Prop>::iterator iter = taggedProperties.begin(); iter != taggedProperties.end(); ++iter)
for (auto & taggedProperty : taggedProperties)
{
Prop &p = iter->second;
Prop &p = taggedProperty.second;
if (p.action)
allActions.push_back(p.action);
}
@ -681,7 +681,7 @@ void C4ScriptGuiWindow::Init()
wasRemoved = false;
closeActionWasExecuted = false;
currentMouseState = MouseState::None;
target = 0;
target = nullptr;
pScrollBar->fAutoHide = true;
rcBounds.x = rcBounds.y = 0;
@ -693,8 +693,8 @@ C4ScriptGuiWindow::~C4ScriptGuiWindow()
ClearChildren(false);
// delete certain properties that contain allocated elements or referenced strings
for (int32_t i = 0; i < C4ScriptGuiWindowPropertyName::_lastProp; ++i)
props[i].CleanUpAll();
for (auto & prop : props)
prop.CleanUpAll();
if (pScrollBar)
delete pScrollBar;
@ -828,7 +828,7 @@ void C4ScriptGuiWindow::SetPositionStringProperties(const C4Value &property, C4S
}
else // error, abort! (readere is not in a clean state anyway)
{
LogF("Warning: Could not parse menu format string \"%s\"!", property.getStr()->GetCStr());
LogF(R"(Warning: Could not parse menu format string "%s"!)", property.getStr()->GetCStr());
return;
}
@ -848,11 +848,11 @@ C4Value C4ScriptGuiWindow::PositionToC4Value(C4ScriptGuiWindowPropertyName relat
C4PropList *proplist = nullptr;
const bool onlyStdTag = relative.taggedProperties.size() == 1;
for (std::map<C4String*, C4ScriptGuiWindowProperty::Prop>::iterator iter = relative.taggedProperties.begin(); iter != relative.taggedProperties.end(); ++iter)
for (auto & taggedProperty : relative.taggedProperties)
{
C4String *tag = iter->first;
C4String *tag = taggedProperty.first;
StdStrBuf buf;
buf.Format("%f%%%+fem", 100.0f * iter->second.f, absolute.taggedProperties[tag].f);
buf.Format("%f%%%+fem", 100.0f * taggedProperty.second.f, absolute.taggedProperties[tag].f);
C4String *propString = Strings.RegString(buf);
if (onlyStdTag)
@ -918,9 +918,8 @@ const C4Value C4ScriptGuiWindow::ToC4Value()
const int32_t entryCount = sizeof(toSave) / sizeof(int32_t);
for (size_t i = 0; i < entryCount; ++i)
for (int prop : toSave)
{
int32_t prop = toSave[i];
C4Value val;
switch (prop)
@ -1289,7 +1288,7 @@ C4ScriptGuiWindow *C4ScriptGuiWindow::GetSubWindow(int32_t childID, C4Object *ch
if (subwindow->GetTarget() != childTarget) continue;
return subwindow;
}
return 0;
return nullptr;
}
void C4ScriptGuiWindow::RemoveChild(C4ScriptGuiWindow *child, bool close, bool all)
@ -1327,7 +1326,7 @@ void C4ScriptGuiWindow::RemoveChild(C4ScriptGuiWindow *child, bool close, bool a
void C4ScriptGuiWindow::ClearChildren(bool close)
{
RemoveChild(0, close, true);
RemoveChild(nullptr, close, true);
}
void C4ScriptGuiWindow::Close()
@ -1422,8 +1421,8 @@ void C4ScriptGuiWindow::UpdateLayoutGrid()
};
// do all the rounding after the calculations
const int32_t childWdt = (int32_t)(childWdtF + 0.5f);
const int32_t childHgt = (int32_t)(childHgtF + 0.5f);
const auto childWdt = (int32_t)(childWdtF + 0.5f);
const auto childHgt = (int32_t)(childHgtF + 0.5f);
// Check if the child even fits in the remainder of the row
const bool fitsInRow = (width - currentX) >= childWdt;
@ -1469,8 +1468,8 @@ void C4ScriptGuiWindow::UpdateLayoutTightGrid()
const float childHgtF = float(child->rcBounds.Hgt) + childTopMargin + childBottomMargin;
// do all the rounding after the calculations
const int32_t childWdt = (int32_t)(childWdtF + 0.5f);
const int32_t childHgt = (int32_t)(childHgtF + 0.5f);
const auto childWdt = (int32_t)(childWdtF + 0.5f);
const auto childHgt = (int32_t)(childHgtF + 0.5f);
// Look for a free spot.
int32_t currentX = borderX;
@ -1606,9 +1605,8 @@ bool C4ScriptGuiWindow::DrawChildren(C4TargetFacet &cgo, int32_t player, int32_t
// note that withMultipleFlag only plays a roll for the root-menu
bool oneDrawn = false; // was at least one child drawn?
//for (auto iter = rbegin(); iter != rend(); ++iter)
for (auto iter = begin(); iter != end(); ++iter)
for (auto element : *this)
{
C4GUI::Element *element = *iter;
C4ScriptGuiWindow *child = static_cast<C4ScriptGuiWindow*>(element);
if (withMultipleFlag != -1)
@ -2310,9 +2308,8 @@ bool C4ScriptGuiWindow::ExecuteCommand(int32_t actionID, int32_t player, int32_t
MenuDebugLogF("children:\t%d", GetElementCount());
MenuDebugLogF("all actions:\t%d", props[actionType].GetAllActions().size());
std::list<C4ScriptGuiWindowAction*> allActions = props[actionType].GetAllActions();
for (std::list<C4ScriptGuiWindowAction*>::iterator iter = allActions.begin(); iter != allActions.end(); ++iter)
for (auto action : allActions)
{
C4ScriptGuiWindowAction *action = *iter;
assert(action && "C4ScriptGuiWindowProperty::GetAllActions returned list with null-pointer");
if (action->ExecuteCommand(actionID, this, player))

View File

@ -49,9 +49,7 @@ C4StartupAboutDlg::C4StartupAboutDlg() : C4StartupDlg(LoadResStr("IDS_DLG_ABOUT"
caButtons.GetFromBottom(rUseFont.GetLineHeight())));
}
C4StartupAboutDlg::~C4StartupAboutDlg()
{
}
C4StartupAboutDlg::~C4StartupAboutDlg() = default;
void C4StartupAboutDlg::DoBack()
{

View File

@ -86,21 +86,21 @@ C4StartupMainDlg::C4StartupMainDlg() : C4StartupDlg(nullptr) // create w/o title
pParticipantsLbl->SetContextHandler(new C4GUI::CBContextHandler<C4StartupMainDlg>(this, &C4StartupMainDlg::OnPlayerSelContext));
// key bindings
C4CustomKey::CodeList keys;
keys.push_back(C4KeyCodeEx(K_DOWN)); keys.push_back(C4KeyCodeEx(K_RIGHT));
keys.emplace_back(K_DOWN); keys.emplace_back(K_RIGHT);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Down(keys); // right will be done by Dialog already
}
pKeyDown = new C4KeyBinding(keys, "StartupMainCtrlNext", KEYSCOPE_Gui,
new C4GUI::DlgKeyCBEx<C4StartupMainDlg, bool>(*this, false, &C4StartupMainDlg::KeyAdvanceFocus), C4CustomKey::PRIO_CtrlOverride);
keys.clear(); keys.push_back(C4KeyCodeEx(K_UP)); keys.push_back(C4KeyCodeEx(K_LEFT));
keys.clear(); keys.emplace_back(K_UP); keys.emplace_back(K_LEFT);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Up(keys); // left will be done by Dialog already
}
pKeyUp = new C4KeyBinding(keys, "StartupMainCtrlPrev", KEYSCOPE_Gui,
new C4GUI::DlgKeyCBEx<C4StartupMainDlg, bool>(*this, true, &C4StartupMainDlg::KeyAdvanceFocus), C4CustomKey::PRIO_CtrlOverride);
keys.clear(); keys.push_back(C4KeyCodeEx(K_RETURN));
keys.clear(); keys.emplace_back(K_RETURN);
pKeyEnter = new C4KeyBinding(keys, "StartupMainOK", KEYSCOPE_Gui,
new C4GUI::DlgKeyCB<C4StartupMainDlg>(*this, &C4StartupMainDlg::KeyEnterDown, &C4StartupMainDlg::KeyEnterUp), C4CustomKey::PRIO_CtrlOverride);
}

View File

@ -49,9 +49,9 @@ C4StartupNetListEntry::C4StartupNetListEntry(C4GUI::ListBox *pForListBox, C4GUI:
int32_t iThisWdt = rcIconRect.Wdt;
rcIconRect.x = iThisWdt - iIconSize * (iInfoIconCount + 1);
rcIconRect.Wdt = rcIconRect.Hgt = iIconSize;
for (int32_t iIcon = 0; iIcon<MaxInfoIconCount; ++iIcon)
for (auto & pInfoIcon : pInfoIcons)
{
AddElement(pInfoIcons[iIcon] = new C4GUI::Icon(rcIconRect, C4GUI::Ico_None));
AddElement(pInfoIcon = new C4GUI::Icon(rcIconRect, C4GUI::Ico_None));
rcIconRect.x -= rcIconRect.Wdt;
}
C4Rect rcLabelBounds;
@ -597,7 +597,7 @@ C4StartupNetDlg::C4StartupNetDlg() : C4StartupDlg(LoadResStr("IDS_DLG_NETSTART")
// ctor
// key bindings
C4CustomKey::CodeList keys;
keys.push_back(C4KeyCodeEx(K_BACK)); keys.push_back(C4KeyCodeEx(K_LEFT));
keys.emplace_back(K_BACK); keys.emplace_back(K_LEFT);
pKeyBack = new C4KeyBinding(keys, "StartupNetBack", KEYSCOPE_Gui,
new C4GUI::DlgKeyCB<C4StartupNetDlg>(*this, &C4StartupNetDlg::KeyBack), C4CustomKey::PRIO_Dlg);
pKeyRefresh = new C4KeyBinding(C4KeyCodeEx(K_F5), "StartupNetReload", KEYSCOPE_Gui,
@ -771,7 +771,7 @@ void C4StartupNetDlg::OnShown()
UpdateUpdateButton(); // in case update check was finished before callback registration
UpdateMasterserver();
OnSec1Timer();
tLastRefresh = time(0);
tLastRefresh = time(nullptr);
// also update chat
if (pChatCtrl) pChatCtrl->OnShown();
}
@ -1172,7 +1172,7 @@ bool C4StartupNetDlg::DoBack()
void C4StartupNetDlg::DoRefresh()
{
// check min refresh timer
time_t tNow = time(0);
time_t tNow = time(nullptr);
if (tLastRefresh && tNow < tLastRefresh + C4NetMinRefreshInterval)
{
// avoid hammering on refresh key

View File

@ -318,9 +318,9 @@ void C4StartupOptionsDlg::ControlConfigListBox::SetAssignmentSet(class C4PlayerC
std::stable_sort(grouped_assignments.begin(),grouped_assignments.end(),&C4StartupOptionsDlg::ControlConfigListBox::sort_by_group);
int32_t current_group = 0;
for (std::vector<C4PlayerControlAssignment *>::iterator i = grouped_assignments.begin(); i != grouped_assignments.end(); ++i)
for (auto & grouped_assignment : grouped_assignments)
{
assignment = *i;
assignment = grouped_assignment;
bool first_element_of_group = assignment->GetGUIGroup() > current_group;
current_group = assignment->GetGUIGroup();
// only show assignments of GUI-named controls
@ -662,11 +662,11 @@ C4StartupOptionsDlg::C4StartupOptionsDlg() : C4StartupDlg(LoadResStrNoAmp("IDS_D
// key bindings
C4CustomKey::CodeList keys;
keys.push_back(C4KeyCodeEx(K_BACK)); keys.push_back(C4KeyCodeEx(K_LEFT));
keys.emplace_back(K_BACK); keys.emplace_back(K_LEFT);
pKeyBack = new C4KeyBinding(keys, "StartupOptionsBack", KEYSCOPE_Gui,
new C4GUI::DlgKeyCB<C4StartupOptionsDlg>(*this, &C4StartupOptionsDlg::KeyBack), C4CustomKey::PRIO_Dlg);
keys.clear();
keys.push_back(C4KeyCodeEx(K_F3)); // overloading global toggle with higher priority here, so a new name is required
keys.emplace_back(K_F3); // overloading global toggle with higher priority here, so a new name is required
pKeyToggleMusic = new C4KeyBinding(keys, "OptionsMusicToggle", KEYSCOPE_Gui,
new C4GUI::DlgKeyCB<C4StartupOptionsDlg>(*this, &C4StartupOptionsDlg::KeyMusicToggle), C4CustomKey::PRIO_Dlg);
@ -918,8 +918,8 @@ C4StartupOptionsDlg::C4StartupOptionsDlg() : C4StartupDlg(LoadResStrNoAmp("IDS_D
sLabelTxt.Copy(LoadResStr("IDS_CTL_LOUD"));
pUseFont->GetTextExtent(sLabelTxt.getData(), w,q, true);
pGroupVolume->AddElement(new C4GUI::Label(sLabelTxt.getData(), caVolumeSlider.GetFromRight(w,q), ACenter, C4StartupFontClr, pUseFont, false, false));
C4GUI::ParCallbackHandler<C4StartupOptionsDlg, int32_t> *pCB = new C4GUI::ParCallbackHandler<C4StartupOptionsDlg, int32_t>(this, i ? &C4StartupOptionsDlg::OnSoundVolumeSliderChange : &C4StartupOptionsDlg::OnMusicVolumeSliderChange);
C4GUI::ScrollBar *pSlider = new C4GUI::ScrollBar(caVolumeSlider.GetCentered(caVolumeSlider.GetInnerWidth(), C4GUI_ScrollBarHgt), true, pCB, 101);
auto *pCB = new C4GUI::ParCallbackHandler<C4StartupOptionsDlg, int32_t>(this, i ? &C4StartupOptionsDlg::OnSoundVolumeSliderChange : &C4StartupOptionsDlg::OnMusicVolumeSliderChange);
auto *pSlider = new C4GUI::ScrollBar(caVolumeSlider.GetCentered(caVolumeSlider.GetInnerWidth(), C4GUI_ScrollBarHgt), true, pCB, 101);
pSlider->SetDecoration(&C4Startup::Get()->Graphics.sfctBookScroll, false);
pSlider->SetToolTip(i ? LoadResStr("IDS_DESC_VOLUMESOUND") : LoadResStr("IDS_DESC_VOLUMEMUSIC"));
pSlider->SetScrollPos(i ? Config.Sound.SoundVolume : Config.Sound.MusicVolume);
@ -1022,11 +1022,11 @@ void C4StartupOptionsDlg::OnGfxMSComboFill(C4GUI::ComboBox_FillCB *pFiller)
Application.pWindow->EnumerateMultiSamples(multisamples);
std::sort(multisamples.begin(), multisamples.end());
for(unsigned int i = 0; i < multisamples.size(); ++i)
for(int multisample : multisamples)
{
StdStrBuf text;
text.Format("%dx", multisamples[i]);
pFiller->AddEntry(text.getData(), multisamples[i]);
text.Format("%dx", multisample);
pFiller->AddEntry(text.getData(), multisample);
}
}

View File

@ -523,9 +523,9 @@ C4StartupPlrSelDlg::C4StartupPlrSelDlg() : C4StartupDlg("W"), eMode(PSDM_Player)
// key bindings
C4CustomKey::CodeList keys;
keys.push_back(C4KeyCodeEx(K_BACK));
keys.push_back(C4KeyCodeEx(K_LEFT));
keys.push_back(C4KeyCodeEx(K_ESCAPE));
keys.emplace_back(K_BACK);
keys.emplace_back(K_LEFT);
keys.emplace_back(K_ESCAPE);
if (Config.Controls.GamepadGuiControl)
{
ControllerKeys::Cancel(keys);
@ -998,8 +998,8 @@ typedef std::vector<C4StartupPlrSelDlg_CrewSortDataEntry> C4StartupPlrSelDlg_Cre
int32_t C4StartupPlrSelDlg::CrewSortFunc(const C4GUI::Element *pEl1, const C4GUI::Element *pEl2, void *par)
{
const CrewListItem *pItem1 = static_cast<const CrewListItem *>(pEl1);
const CrewListItem *pItem2 = static_cast<const CrewListItem *>(pEl2);
const auto *pItem1 = static_cast<const CrewListItem *>(pEl1);
const auto *pItem2 = static_cast<const CrewListItem *>(pEl2);
C4StartupPlrSelDlg_CrewSortData &rSortData = *static_cast<C4StartupPlrSelDlg_CrewSortData *>(par);
C4StartupPlrSelDlg_CrewSortData::iterator i = std::find_if(rSortData.begin(), rSortData.end(), C4StartupPlrSelDlg_CrewSortDataMatchType(pItem1->GetCore().id)),
j = std::find_if(rSortData.begin(), rSortData.end(), C4StartupPlrSelDlg_CrewSortDataMatchType(pItem2->GetCore().id));
@ -1022,7 +1022,7 @@ void C4StartupPlrSelDlg::ResortCrew()
{
C4StartupPlrSelDlg_CrewSortData::iterator i = std::find_if(SortData.begin(), SortData.end(), C4StartupPlrSelDlg_CrewSortDataMatchType(pCrewItem->GetCore().id));
if (i == SortData.end())
SortData.push_back(C4StartupPlrSelDlg_CrewSortDataEntry(pCrewItem->GetCore().Experience, pCrewItem->GetCore().id));
SortData.emplace_back(pCrewItem->GetCore().Experience, pCrewItem->GetCore().id);
else
(*i).iMaxExp = std::max<int32_t>((*i).iMaxExp, pCrewItem->GetCore().Experience);
}
@ -1038,7 +1038,7 @@ public:
protected:
// Event handler
virtual void OnClosed(bool commit);
void OnClosed(bool commit) override;
private:
class Picker : public C4GUI::Control
@ -1052,9 +1052,9 @@ private:
protected:
// Event handlers, overridden from C4GUI::Control
virtual void DrawElement(C4TargetFacet &cgo);
virtual void MouseInput(C4GUI::CMouse &rMouse, int32_t iButton, int32_t iX, int32_t iY, DWORD dwKeyParam);
virtual void DoDragging(C4GUI::CMouse &rMouse, int32_t iX, int32_t iY, DWORD dwKeyParam);
void DrawElement(C4TargetFacet &cgo) override;
void MouseInput(C4GUI::CMouse &rMouse, int32_t iButton, int32_t iX, int32_t iY, DWORD dwKeyParam) override;
void DoDragging(C4GUI::CMouse &rMouse, int32_t iX, int32_t iY, DWORD dwKeyParam) override;
private:
static const unsigned int HSPickerCursorSize = 5;

View File

@ -130,7 +130,7 @@ bool C4MapFolderData::Load(C4Group &hGroup, C4ScenarioListLoader::Folder *pScenL
// load images
if (!fctBackgroundPicture.Load(hGroup, C4CFN_MapFolderBG, C4FCT_Full, C4FCT_Full, false, 0))
{
DebugLogF("C4MapFolderData::Load(%s): Could not load background graphic \"%s\"", hGroup.GetName(), C4CFN_MapFolderBG);
DebugLogF(R"(C4MapFolderData::Load(%s): Could not load background graphic "%s")", hGroup.GetName(), C4CFN_MapFolderBG);
return false;
}
int i;
@ -156,18 +156,18 @@ bool C4MapFolderData::Load(C4Group &hGroup, C4ScenarioListLoader::Folder *pScenL
fSuccess = fctDump.Surface->SavePNG(pScen->sBaseImage.getData(), true, false, false);
}
if (!fSuccess)
DebugLogF("C4MapFolderData::Load(%s): Could not dump graphic \"%s\"", hGroup.GetName(), pScen->sBaseImage.getData());
DebugLogF(R"(C4MapFolderData::Load(%s): Could not dump graphic "%s")", hGroup.GetName(), pScen->sBaseImage.getData());
continue;
}
// load images
if (pScen->sBaseImage.getLength()>0) if (!pScen->fctBase.Load(hGroup, pScen->sBaseImage.getData(), C4FCT_Full, C4FCT_Full, false, 0))
{
DebugLogF("C4MapFolderData::Load(%s): Could not load base graphic \"%s\"", hGroup.GetName(), pScen->sBaseImage.getData());
DebugLogF(R"(C4MapFolderData::Load(%s): Could not load base graphic "%s")", hGroup.GetName(), pScen->sBaseImage.getData());
return false;
}
if (pScen->sOverlayImage.getLength()>0) if (!pScen->fctOverlay.Load(hGroup, pScen->sOverlayImage.getData(), C4FCT_Full, C4FCT_Full, false, 0))
{
DebugLogF("C4MapFolderData::Load(%s): Could not load graphic \"%s\"", hGroup.GetName(), pScen->sOverlayImage.getData());
DebugLogF(R"(C4MapFolderData::Load(%s): Could not load graphic "%s")", hGroup.GetName(), pScen->sOverlayImage.getData());
return false;
}
}
@ -176,7 +176,7 @@ bool C4MapFolderData::Load(C4Group &hGroup, C4ScenarioListLoader::Folder *pScenL
AccessGfx *pGfx= ppAccessGfxList[i];
if (pGfx->sOverlayImage.getLength()>0) if (!pGfx->fctOverlay.Load(hGroup, pGfx->sOverlayImage.getData(), C4FCT_Full, C4FCT_Full, false, 0))
{
DebugLogF("C4MapFolderData::Load(%s): Could not load graphic \"%s\"", hGroup.GetName(), pGfx->sOverlayImage.getData());
DebugLogF(R"(C4MapFolderData::Load(%s): Could not load graphic "%s")", hGroup.GetName(), pGfx->sOverlayImage.getData());
return false;
}
}
@ -680,9 +680,8 @@ bool C4ScenarioListLoader::Scenario::LoadCustomPre(C4Group &rGrp)
// achievement images: Loaded from this entry and parent folder
nAchievements = 0;
const C4ScenarioParameterDefs *deflists[] = { pParent ? pParent->GetAchievementDefs() : nullptr, &ParameterDefs };
for (size_t def_list_idx=0; def_list_idx<2; ++def_list_idx)
for (auto deflist : deflists)
{
const C4ScenarioParameterDefs *deflist = deflists[def_list_idx];
if (!deflist) continue;
const C4ScenarioParameterDef *def; size_t idx=0;
while ((def = deflist->GetParameterDefByIndex(idx++)))
@ -1046,7 +1045,7 @@ bool C4ScenarioListLoader::SubFolder::DoLoadContents(C4ScenarioListLoader *pLoad
// ...and load it
if (!pNewEntry->Load(&Group, &sChildFilename, fLoadEx))
{
DebugLogF("Error loading entry \"%s\" in SubFolder \"%s\"!", sChildFilename.getData(), Group.GetFullName().getData());
DebugLogF(R"(Error loading entry "%s" in SubFolder "%s"!)", sChildFilename.getData(), Group.GetFullName().getData());
delete pNewEntry;
}
}
@ -1079,8 +1078,7 @@ bool C4ScenarioListLoader::SubFolder::DoLoadContents(C4ScenarioListLoader *pLoad
// ------------------------------------
// RegularFolder
C4ScenarioListLoader::RegularFolder::~RegularFolder()
{}
C4ScenarioListLoader::RegularFolder::~RegularFolder() = default;
bool C4ScenarioListLoader::RegularFolder::LoadCustom(C4Group &rGrp, bool fNameLoaded, bool fIconLoaded)
{
@ -1139,7 +1137,7 @@ bool C4ScenarioListLoader::RegularFolder::DoLoadContents(C4ScenarioListLoader *p
// ...and load it
if (!pNewEntry->Load(nullptr, &sChildFilename, fLoadEx))
{
DebugLogF("Error loading entry \"%s\" in Folder \"%s\"!", szChildFilename, it->c_str());
DebugLogF(R"(Error loading entry "%s" in Folder "%s"!)", szChildFilename, it->c_str());
delete pNewEntry;
}
}
@ -1154,7 +1152,7 @@ bool C4ScenarioListLoader::RegularFolder::DoLoadContents(C4ScenarioListLoader *p
void C4ScenarioListLoader::RegularFolder::Merge(const char *szPath)
{
contents.push_back(szPath);
contents.emplace_back(szPath);
}
// ------------------------------------
@ -1223,8 +1221,8 @@ bool C4ScenarioListLoader::Load(const StdStrBuf &sRootFolder)
pCurrFolder = pRootFolder = new RegularFolder(this, nullptr);
// Load regular game data if no explicit path specified
if(!sRootFolder.getData())
for(C4Reloc::iterator iter = Reloc.begin(); iter != Reloc.end(); ++iter)
pRootFolder->Merge(iter->strBuf.getData());
for(const auto & iter : Reloc)
pRootFolder->Merge(iter.strBuf.getData());
bool fSuccess = pRootFolder->LoadContents(this, nullptr, &sRootFolder, false, false);
EndActivity();
return fSuccess;
@ -1319,7 +1317,7 @@ C4StartupScenSelDlg::ScenListItem::ScenListItem(C4GUI::ListBox *pForListBox, C4S
SetBounds(pIcon->GetBounds());
// add components
AddElement(pIcon); AddElement(pNameLabel);
for (int32_t i=0; i<C4StartupScenSel_MaxAchievements; ++i) if (ppAchievements[i]) AddElement(ppAchievements[i]);
for (auto & ppAchievement : ppAchievements) if (ppAchievement) AddElement(ppAchievement);
// tooltip by name, so long names can be read via tooltip
SetToolTip(pScenListEntry->GetName().getData());
// add to listbox (will get resized horizontally and moved) - zero indent; no tree structure in this dialog
@ -1338,9 +1336,9 @@ void C4StartupScenSelDlg::ScenListItem::UpdateOwnPos()
ParentClass::UpdateOwnPos();
// reposition achievement items
C4GUI::ComponentAligner caBounds(GetContainedClientRect(), IconLabelSpacing, IconLabelSpacing);
for (int32_t i=0; i<C4StartupScenSel_MaxAchievements; ++i) if (ppAchievements[i])
for (auto & ppAchievement : ppAchievements) if (ppAchievement)
{
ppAchievements[i]->SetBounds(caBounds.GetFromRight(caBounds.GetHeight()));
ppAchievement->SetBounds(caBounds.GetFromRight(caBounds.GetHeight()));
}
}
@ -1483,7 +1481,7 @@ C4StartupScenSelDlg::C4StartupScenSelDlg(bool fNetwork) : C4StartupDlg(LoadResSt
// key bindings
C4CustomKey::CodeList keys;
keys.push_back(C4KeyCodeEx(K_BACK)); keys.push_back(C4KeyCodeEx(K_LEFT));
keys.emplace_back(K_BACK); keys.emplace_back(K_LEFT);
pKeyBack = new C4KeyBinding(keys, "StartupScenSelFolderUp", KEYSCOPE_Gui,
new C4GUI::DlgKeyCB<C4StartupScenSelDlg>(*this, &C4StartupScenSelDlg::KeyBack), C4CustomKey::PRIO_CtrlOverride);
pKeyRefresh = new C4KeyBinding(C4KeyCodeEx(K_F5), "StartupScenSelReload", KEYSCOPE_Gui,

View File

@ -21,20 +21,16 @@
#include "graphics/C4GraphicsResource.h"
#include "graphics/C4Draw.h"
C4UpperBoard::C4UpperBoard()
{
}
C4UpperBoard::C4UpperBoard() = default;
C4UpperBoard::~C4UpperBoard()
{
}
C4UpperBoard::~C4UpperBoard() = default;
void C4UpperBoard::Execute()
{
if (!Config.Graphics.UpperBoard) return;
// Make the time strings
sprintf(cTimeString,"%02d:%02d:%02d", Game.Time/3600,(Game.Time%3600)/60,Game.Time%60);
time_t t = time(0); strftime(cTimeString2, sizeof(cTimeString2), "[%H:%M:%S]", localtime(&t));
time_t t = time(nullptr); strftime(cTimeString2, sizeof(cTimeString2), "[%H:%M:%S]", localtime(&t));
Draw(Output);
}

View File

@ -131,7 +131,7 @@ namespace
{
bool ForLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2,
std::function<bool(int32_t, int32_t)> fnCallback,
int32_t *lastx = 0, int32_t *lasty = 0)
int32_t *lastx = nullptr, int32_t *lasty = nullptr)
{
int d, dx, dy, aincr, bincr, xincr, yincr, x, y;
if (Abs(x2 - x1) < Abs(y2 - y1))
@ -1649,12 +1649,12 @@ bool C4Landscape::Init(C4Group &hGroup, bool fOverloadCurrent, bool fLoadSky, bo
// Create FoW
assert(p->pFoW == nullptr);
if (Game.C4S.Game.FoWEnabled)
p->pFoW.reset(new C4FoW);
p->pFoW = std::make_unique<C4FoW>();
// Create renderer
#ifndef USE_CONSOLE
if (!p->pLandscapeRender)
p->pLandscapeRender.reset(new C4LandscapeRenderGL);
p->pLandscapeRender = std::make_unique<C4LandscapeRenderGL>();
#endif
if (p->pLandscapeRender)

View File

@ -119,10 +119,10 @@ bool C4LandscapeRenderGL::ReInit(int32_t iWidth, int32_t iHeight)
this->iHeight = iHeight;
// Clear old landscape textures
for (int i = 0; i < C4LR_SurfaceCount; i++)
for (auto & Surface : Surfaces)
{
delete Surfaces[i];
Surfaces[i] = nullptr;
delete Surface;
Surface = nullptr;
}
// Allocate new landscape textures
@ -182,10 +182,10 @@ bool C4LandscapeRenderGL::InitLandscapeTexture()
int iSfcHgt = iHeight;
// Create our surfaces
for(int i = 0; i < C4LR_SurfaceCount; i++)
for(auto & Surface : Surfaces)
{
Surfaces[i] = new C4Surface();
if(!Surfaces[i]->Create(iSfcWdt, iSfcHgt))
Surface = new C4Surface();
if(!Surface->Create(iSfcWdt, iSfcHgt))
return false;
}
@ -196,7 +196,7 @@ bool C4LandscapeRenderGL::InitMaterialTexture(C4TextureMap *pTexs)
{
// Populate our map with all needed textures
MaterialTextureMap.push_back(StdCopyStrBuf(""));
MaterialTextureMap.emplace_back("");
AddTexturesFromMap(pTexs);
// Determine depth to use
@ -366,10 +366,10 @@ void C4LandscapeRenderGL::Update(C4Rect To, C4Landscape *pSource)
// main memory buffer for the box, so that only that box needs to be
// sent to the gpu, and not the whole texture, or every pixel
// separately. It's an important optimization.
for (int i = 0; i < C4LR_SurfaceCount; i++)
for (auto & Surface : Surfaces)
{
if (!Surfaces[i]->Lock()) return;
Surfaces[i]->ClearBoxDw(To.x, To.y, To.Wdt, To.Hgt);
if (!Surface->Lock()) return;
Surface->ClearBoxDw(To.x, To.y, To.Wdt, To.Hgt);
}
// Initialize up & down placement arrays. These arrays are always updated
@ -509,8 +509,8 @@ void C4LandscapeRenderGL::Update(C4Rect To, C4Landscape *pSource)
// done
delete[] placementSumsUp;
for (int i = 0; i < C4LR_SurfaceCount; i++)
Surfaces[i]->Unlock();
for (auto & Surface : Surfaces)
Surface->Unlock();
}
/** Returns the data used for the scaler shader for the given pixel. It is a 8-bit bitmask. The bits stand for the 8
@ -549,12 +549,12 @@ int C4LandscapeRenderGL::CalculateScalerBitmask(int x, int y, C4Rect To, C4Lands
// Look for highest-placement material in our surroundings
int maxPixel = pixel, maxPlacement = placement;
for(int i = 0; i < 8; i++)
for(int neighbour : neighbours)
{
int tempPlacement = MatPlacement(PixCol2Mat(neighbours[i]));
if(tempPlacement > maxPlacement || (tempPlacement == maxPlacement && neighbours[i] > maxPixel) )
int tempPlacement = MatPlacement(PixCol2Mat(neighbour));
if(tempPlacement > maxPlacement || (tempPlacement == maxPlacement && neighbour > maxPixel) )
{
maxPixel = neighbours[i];
maxPixel = neighbour;
maxPlacement = tempPlacement;
}
}
@ -801,17 +801,17 @@ void C4LandscapeRenderGL::AddTextureTransition(const char *szFrom, const char *s
if (LookupTextureTransition(szTo, szFrom) >= 0) return;
// Single texture? Add it as single
if (SEqual(szTo, szFrom))
MaterialTextureMap.push_back(StdCopyStrBuf(szFrom));
MaterialTextureMap.emplace_back(szFrom);
// Have one of the textures at the end of the list?
else if(SEqual(MaterialTextureMap.back().getData(), szFrom))
MaterialTextureMap.push_back(StdCopyStrBuf(szTo));
MaterialTextureMap.emplace_back(szTo);
else if(SEqual(MaterialTextureMap.back().getData(), szTo))
MaterialTextureMap.push_back(StdCopyStrBuf(szFrom));
MaterialTextureMap.emplace_back(szFrom);
else
{
// Otherwise add both
MaterialTextureMap.push_back(StdCopyStrBuf(szFrom));
MaterialTextureMap.push_back(StdCopyStrBuf(szTo));
MaterialTextureMap.emplace_back(szFrom);
MaterialTextureMap.emplace_back(szTo);
}
}
@ -1118,7 +1118,7 @@ void C4LandscapeRenderGL::Draw(const C4TargetFacet &cgo, const C4FoWRegion *Ligh
if (Light)
glEnableVertexAttribArray(shader->GetAttribute(C4LRA_LightTexCoord));
glVertexAttribPointer(shader->GetAttribute(C4LRA_Position), 2, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribPointer(shader->GetAttribute(C4LRA_Position), 2, GL_FLOAT, GL_FALSE, 0, nullptr);
glVertexAttribPointer(shader->GetAttribute(C4LRA_LandscapeTexCoord), 2, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<const uint8_t*>(8 * sizeof(float)));
if (Light)
glVertexAttribPointer(shader->GetAttribute(C4LRA_LightTexCoord), 2, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<const uint8_t*>(16 * sizeof(float)));

View File

@ -96,9 +96,9 @@ void C4MapCreator::Create(CSurface8 *sfcMap,
// Surface
ccol=rTexMap.GetIndexMatTex(rLScape.Material.c_str());
float amplitude= (float) rLScape.Amplitude.Evaluate();
float phase= (float) rLScape.Phase.Evaluate();
float period= (float) rLScape.Period.Evaluate();
auto amplitude= (float) rLScape.Amplitude.Evaluate();
auto phase= (float) rLScape.Phase.Evaluate();
auto period= (float) rLScape.Period.Evaluate();
if (rLScape.MapPlayerExtend) period *= std::min(iPlayerNum, C4S_MaxMapPlayerExtend);
float natural= (float) rLScape.Random.Evaluate();
int32_t level0= std::min(MapWdt,MapHgt)/2;

View File

@ -623,7 +623,7 @@ bool C4MCOverlay::PeekPix(int32_t iX, int32_t iY)
// start with this one
C4MCOverlay *pOvrl=this; bool fLastSetC=false; C4MCTokenType eLastOp=MCT_NONE; BYTE Crap;
// loop through op chain
while (1)
while (true)
{
fLastSetC=pOvrl->RenderPix(iX, iY, Crap, Crap, eLastOp, fLastSetC, false);
eLastOp=pOvrl->Op;
@ -1472,7 +1472,7 @@ void C4MCParser::ParseFile(const char *szFilename, C4Group *pGrp)
BPos=Code;
CPos=Code;
ParseTo(MapCreator);
if (0) PrintNodeTree(MapCreator, 0);
if (false) PrintNodeTree(MapCreator, 0);
// free code
// on errors, this will be done be destructor
Clear();
@ -1486,7 +1486,7 @@ void C4MCParser::Parse(const char *szScript)
BPos=szScript;
CPos=szScript;
ParseTo(MapCreator);
if (0) PrintNodeTree(MapCreator, 0);
if (false) PrintNodeTree(MapCreator, 0);
// free code
// on errors, this will be done be destructor
Clear();
@ -1759,7 +1759,7 @@ C4MCAlgorithm C4MCAlgoMap[] =
{ "script", &AlgoScript },
{ "rndall", &AlgoRndAll },
{ "poly", &AlgoPolygon },
{ "", 0 }
{ "", nullptr }
};
#define offsC4MCOvrl(x) reinterpret_cast<C4MCOverlayOffsetType>(&C4MCOverlay::x)
@ -1791,6 +1791,6 @@ namespace {
{ "mask", C4MCV_Boolean, offsC4MCOvrl(Mask) },
{ "evalFn", C4MCV_ScriptFunc, offsC4MCOvrl(pEvaluateFunc) },
{ "drawFn", C4MCV_ScriptFunc, offsC4MCOvrl(pDrawFunc) },
{ "", C4MCV_None, 0 }
{ "", C4MCV_None, nullptr }
};
}

View File

@ -617,7 +617,7 @@ bool C4MapScriptLayer::FindPos(const C4Rect &search_rect, const C4MapScriptMatTe
void C4MapScriptMap::Clear()
{
// Layers are owned by map. Free them.
for (std::list<C4MapScriptLayer *>::iterator i=layers.begin(); i!=layers.end(); ++i) delete *i;
for (auto & layer : layers) delete layer;
layers.clear();
}

View File

@ -38,7 +38,7 @@ bool C4MapScriptAlgo::GetXYProps(const C4PropList *props, C4PropertyName k, int3
if ((arr = val.getArray()))
{
if (arr->GetSize() != 2)
throw C4AulExecError(FormatString("C4MapScriptAlgo: Expected either integer or array with two integer elements in property \"%s\".", Strings.P[k].GetCStr()).getData());
throw C4AulExecError(FormatString(R"(C4MapScriptAlgo: Expected either integer or array with two integer elements in property "%s".)", Strings.P[k].GetCStr()).getData());
out_xy[0] = arr->GetItem(0).getInt();
out_xy[1] = arr->GetItem(1).getInt();
}
@ -54,7 +54,7 @@ C4MapScriptAlgoLayer::C4MapScriptAlgoLayer(const C4PropList *props)
// Get MAPALGO_Layer properties
C4PropList *layer_pl = props->GetPropertyPropList(P_Layer);
if (!layer_pl || !(layer = layer_pl->GetMapScriptLayer()))
throw C4AulExecError("C4MapScriptAlgoLayer: Expected layer in \"Layer\" property.");
throw C4AulExecError(R"(C4MapScriptAlgoLayer: Expected layer in "Layer" property.)");
}
bool C4MapScriptAlgoLayer::operator () (int32_t x, int32_t y, uint8_t& fg, uint8_t& bg) const
@ -143,7 +143,7 @@ C4MapScriptAlgoPolygon::C4MapScriptAlgoPolygon(const C4PropList *props)
props->GetProperty(P_X, &vptx); props->GetProperty(P_Y, &vpty);
C4ValueArray *ptx = vptx.getArray(), *pty = vpty.getArray();
if (!ptx || !pty || ptx->GetSize() != pty->GetSize())
throw C4AulExecError("C4MapScriptAlgoPolygon: Expected two equally sized int arrays in properties \"X\" and \"Y\".");
throw C4AulExecError(R"(C4MapScriptAlgoPolygon: Expected two equally sized int arrays in properties "X" and "Y".)");
poly.resize(ptx->GetSize());
for (int32_t i=0; i<ptx->GetSize(); ++i)
{
@ -195,7 +195,7 @@ C4MapScriptAlgoLines::C4MapScriptAlgoLines(const C4PropList *props)
// Get MAPALGO_Lines properties
lx = props->GetPropertyInt(P_X);
ly = props->GetPropertyInt(P_Y);
if (!lx && !ly) throw C4AulExecError("C4MapScriptAlgoLines: Invalid direction vector. Either \"X\" or \"Y\" must be nonzero!");
if (!lx && !ly) throw C4AulExecError(R"(C4MapScriptAlgoLines: Invalid direction vector. Either "X" or "Y" must be nonzero!)");
ox = props->GetPropertyInt(P_OffX);
oy = props->GetPropertyInt(P_OffY);
// use sync-safe distance function to calculate line width
@ -240,7 +240,7 @@ C4MapScriptAlgoModifier::C4MapScriptAlgoModifier(const C4PropList *props, int32_
n = ops->GetSize();
}
if (!ops || n<min_ops || (max_ops && n>max_ops))
throw C4AulExecError(FormatString("C4MapScriptAlgo: Expected between %d and %d operands in property \"Op\".", (int)min_ops, (int)max_ops).getData());
throw C4AulExecError(FormatString(R"(C4MapScriptAlgo: Expected between %d and %d operands in property "Op".)", (int)min_ops, (int)max_ops).getData());
operands.resize(n);
try
{
@ -249,7 +249,7 @@ C4MapScriptAlgoModifier::C4MapScriptAlgoModifier(const C4PropList *props, int32_
for (int32_t i=0; i<n; ++i)
{
C4MapScriptAlgo *new_algo = FnParAlgo(ops->GetItem(i).getPropList());
if (!new_algo) throw C4AulExecError(FormatString("C4MapScriptAlgo: Operand %d in property \"Op\" not valid.", (int)i).getData());
if (!new_algo) throw C4AulExecError(FormatString(R"(C4MapScriptAlgo: Operand %d in property "Op" not valid.)", (int)i).getData());
operands[i] = new_algo;
}
}
@ -263,7 +263,7 @@ C4MapScriptAlgoModifier::C4MapScriptAlgoModifier(const C4PropList *props, int32_
void C4MapScriptAlgoModifier::Clear()
{
// Child algos are owned by this algo, so delete them
for (std::vector<C4MapScriptAlgo *>::iterator i=operands.begin(); i != operands.end(); ++i) delete *i;
for (auto & operand : operands) delete operand;
operands.clear();
}
@ -271,9 +271,9 @@ bool C4MapScriptAlgoAnd::operator () (int32_t x, int32_t y, uint8_t& fg, uint8_t
{
// Evaluate MAPALGO_And at x,y:
// Return 0 if any of the operands is 0. Otherwise, returns value of last operand.
bool val=0;
for (std::vector<C4MapScriptAlgo *>::const_iterator i=operands.begin(); i != operands.end(); ++i)
if (!(val=(**i)(x, y, fg, bg)))
bool val=false;
for (auto operand : operands)
if (!(val=(*operand)(x, y, fg, bg)))
return false;
return val;
}
@ -283,8 +283,8 @@ bool C4MapScriptAlgoOr::operator () (int32_t x, int32_t y, uint8_t& fg, uint8_t&
// Evaluate MAPALGO_Or at x,y:
// Return first nonzero operand
bool val;
for (std::vector<C4MapScriptAlgo *>::const_iterator i=operands.begin(); i != operands.end(); ++i)
if ((val=(**i)(x, y, fg, bg)))
for (auto operand : operands)
if ((val=(*operand)(x, y, fg, bg)))
return val;
// If all operands are zero, return zero.
return false;

View File

@ -83,7 +83,7 @@ void C4MaterialReaction::ResolveScriptFuncs(const char *szMatName)
{
pScriptFunc = ::ScriptEngine.GetPropList()->GetFunc(this->ScriptFunc.getData());
if (!pScriptFunc)
DebugLogF("Error getting function \"%s\" for Material reaction of \"%s\"", this->ScriptFunc.getData(), szMatName);
DebugLogF(R"(Error getting function "%s" for Material reaction of "%s")", this->ScriptFunc.getData(), szMatName);
}
else
pScriptFunc = nullptr;
@ -292,8 +292,8 @@ C4Material::C4Material()
void C4Material::UpdateScriptPointers()
{
for (uint32_t i = 0; i < CustomReactionList.size(); ++i)
CustomReactionList[i].ResolveScriptFuncs(Name);
for (auto & i : CustomReactionList)
i.ResolveScriptFuncs(Name);
}
@ -449,9 +449,9 @@ bool C4MaterialMap::CrossMapMaterials(const char* szEarthMaterial) // Called aft
if ((sfcTexture=Texture->Surface32))
Map[cnt].PXSFace.Set(sfcTexture, Map[cnt].PXSGfxRt.x, Map[cnt].PXSGfxRt.y, Map[cnt].PXSGfxRt.Wdt, Map[cnt].PXSGfxRt.Hgt);
// evaluate reactions for that material
for (unsigned int iRCnt = 0; iRCnt < pMat->CustomReactionList.size(); ++iRCnt)
for (auto & iRCnt : pMat->CustomReactionList)
{
C4MaterialReaction *pReact = &(pMat->CustomReactionList[iRCnt]);
C4MaterialReaction *pReact = &iRCnt;
if (pReact->sConvertMat.getLength()) pReact->iConvertMat = Get(pReact->sConvertMat.getData()); else pReact->iConvertMat = -1;
// evaluate target spec
int32_t tmat;
@ -545,7 +545,7 @@ bool C4MaterialMap::CrossMapMaterials(const char* szEarthMaterial) // Called aft
// Get hardcoded system material indices
const C4TexMapEntry* earth_entry = ::TextureMap.GetEntry(::TextureMap.GetIndexMatTex(szEarthMaterial));
if(!earth_entry)
{ LogFatal(FormatString("Earth material \"%s\" not found!", szEarthMaterial).getData()); return false; }
{ LogFatal(FormatString(R"(Earth material "%s" not found!)", szEarthMaterial).getData()); return false; }
MVehic = Get("Vehicle"); MCVehic = Mat2PixColDefault(MVehic);
MHalfVehic = Get("HalfVehicle"); MCHalfVehic = Mat2PixColDefault(MHalfVehic);

View File

@ -42,8 +42,8 @@ void C4MaterialList::Clear()
void C4MaterialList::Reset()
{
for (int cnt=0; cnt<C4MaxMaterial; cnt++)
Amount[cnt]=0;
for (int & cnt : Amount)
cnt=0;
}
void C4MaterialList::Set(int32_t iMaterial, int32_t iAmount)

View File

@ -285,9 +285,9 @@ void C4SLandscape::Default()
{
BottomOpen=0; TopOpen=1;
LeftOpen=0; RightOpen=0;
AutoScanSideOpen=1;
AutoScanSideOpen=true;
SkyDef[0]=0;
for (int32_t cnt=0; cnt<6; cnt++) SkyDefFade[cnt]=0;
for (int & cnt : SkyDefFade) cnt=0;
VegLevel.Set(50,30,0,100);
Vegetation.Default();
InEarthLevel.Set(50,0,0,100);
@ -304,10 +304,10 @@ void C4SLandscape::Default()
Layers.Clear();
Material = "Earth";
Liquid = "Water";
ExactLandscape=0;
ExactLandscape=false;
Gravity.Set(100,0,10,200);
NoScan=0;
KeepMapCreator=0;
NoScan=false;
KeepMapCreator=false;
SkyScrollMode=0;
MaterialZoom=4;
FlatChunkShapes=false;
@ -364,7 +364,7 @@ void C4SWeather::Default()
StartSeason.Set(50,50);
YearSpeed.Set(50);
Wind.Set(0,70,-100,+100);
NoGamma=1;
NoGamma=true;
}
void C4SWeather::CompileFunc(StdCompiler *pComp)
@ -400,8 +400,8 @@ void C4SEnvironment::CompileFunc(StdCompiler *pComp)
void C4SRealism::Default()
{
LandscapePushPull=0;
LandscapeInsertThrust=0;
LandscapePushPull=false;
LandscapeInsertThrust=false;
ValueOverloads.Default();
}
@ -414,7 +414,7 @@ void C4Scenario::SetExactLandscape()
{
if (Landscape.ExactLandscape) return;
// Set landscape
Landscape.ExactLandscape = 1;
Landscape.ExactLandscape = true;
}
bool C4SDefinitions::GetModules(StdStrBuf *psOutModules) const

View File

@ -112,7 +112,7 @@ bool C4Sky::Init(bool fSavegame, std::string names)
{
SetFadePalette(Game.C4S.Landscape.SkyDefFade);
delete Surface;
Surface = 0;
Surface = nullptr;
}
// Load sky shaders: regular sprite shaders with OC_SKY define

View File

@ -417,7 +417,7 @@ C4SolidMask::C4SolidMask(C4Object *pForObject) : pForObject(pForObject)
iAttachingObjectsCount=iAttachingObjectsCapacity=0;
MaskMaterial=MCVehic;
// Update linked list
Next = 0;
Next = nullptr;
Prev = Last;
Last = this;
if (Prev) Prev->Next = this;
@ -462,8 +462,8 @@ void C4SolidMask::PutSolidMasks()
}
}
C4SolidMask * C4SolidMask::First = 0;
C4SolidMask * C4SolidMask::Last = 0;
C4SolidMask * C4SolidMask::First = nullptr;
C4SolidMask * C4SolidMask::Last = nullptr;
bool C4SolidMask::CheckConsistency()

View File

@ -31,7 +31,7 @@
#include "lib/C4Random.h"
#include "lib/StdColors.h"
#include <ctype.h>
#include <cctype>
#include <algorithm>
C4Texture::C4Texture()
@ -279,7 +279,7 @@ int32_t C4TextureMap::LoadMap(C4Group &hGroup, const char *szEntryName, bool *pO
std::string::const_iterator separator = std::find(value.cbegin(), value.cend(), '-');
if (separator == value.cend())
{
DebugLogF("TexMap line %u: Texture name \"%s\" is invalid (missing \"-\")", static_cast<unsigned>(line), value.c_str());
DebugLogF(R"(TexMap line %u: Texture name "%s" is invalid (missing "-"))", static_cast<unsigned>(line), value.c_str());
continue;
}
@ -326,9 +326,8 @@ bool C4TextureMap::SaveMap(C4Group &hGroup, const char *szEntryName)
if (fOverloadTextures) sTexMapFile.Append("# Import textures from global file as well" LineFeed "OverloadTextures" LineFeed);
sTexMapFile.Append(LineFeed);
// add entries
for (auto iter = Order.begin(); iter != Order.end(); ++iter)
for (auto i : Order)
{
int32_t i = *iter;
if (!Entry[i].isNull())
{
// compose line

View File

@ -34,9 +34,7 @@ C4TransferZone::C4TransferZone()
Used = false;
}
C4TransferZone::~C4TransferZone()
{
}
C4TransferZone::~C4TransferZone() = default;
C4TransferZones::C4TransferZones()
{

View File

@ -18,7 +18,7 @@
#include "landscape/fow/C4FoW.h"
#include "graphics/C4Draw.h"
#include <float.h>
#include <cfloat>
C4FoW::C4FoW()

View File

@ -60,7 +60,7 @@ double AmbientForPix(int x0, int y0, double R, const LightMap& light_map)
// Everything is illuminated, independent of the landscape
// This is used to obtain the normalization factor
struct LightMapFull {
LightMapFull() {}
LightMapFull() = default;
bool operator()(int x, int y) const { return true; }
};

View File

@ -205,7 +205,7 @@ void C4FoWDrawLightTextureStrategy::End(C4ShaderCall& call)
glBlendEquationSeparate(GL_FUNC_ADD, GL_MAX);
// Render 1st pass
glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, 0);
glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, nullptr);
// Prepare state for 2nd pass
//glBlendFunc(GL_ONE, GL_ONE);
@ -224,7 +224,7 @@ void C4FoWDrawLightTextureStrategy::End(C4ShaderCall& call)
}
// Render 2nd pass
glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, 0);
glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, nullptr);
// Prepare state for 3rd pass (color pass)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
@ -246,7 +246,7 @@ void C4FoWDrawLightTextureStrategy::End(C4ShaderCall& call)
}
// Render 3rd pass
glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, 0);
glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, nullptr);
// Reset GL state
glBindVertexArray(0);
@ -413,7 +413,7 @@ void C4FoWDrawWireframeStrategy::End(C4ShaderCall& call)
const float y_offset[] = { 0.0f, 0.0f };
call.SetUniform2fv(C4FoWRSU_VertexOffset, 1, y_offset);
glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, 0);
glDrawElements(GL_TRIANGLES, triangulator.GetNIndices(), GL_UNSIGNED_INT, nullptr);
// Reset GL state
glBindVertexArray(0);

View File

@ -47,14 +47,14 @@ C4FoWLight::C4FoWLight(C4Object *pObj)
C4FoWLight::~C4FoWLight()
{
for(size_t i = 0; i < sections.size(); ++i )
delete sections[i];
for(auto & section : sections)
delete section;
}
void C4FoWLight::Invalidate(C4Rect r)
{
for(size_t i = 0; i < sections.size(); ++i )
sections[i]->Invalidate(r);
for(auto & section : sections)
section->Invalidate(r);
}
void C4FoWLight::SetReach(int32_t iReach2, int32_t iFadeout2)
@ -68,15 +68,15 @@ void C4FoWLight::SetReach(int32_t iReach2, int32_t iFadeout2)
{
// Reach decreased? Prune beams
iReach = iReach2;
for(size_t i = 0; i < sections.size(); ++i )
sections[i]->Prune(iReach);
for(auto & section : sections)
section->Prune(iReach);
} else {
// Reach increased? Dirty beams that might get longer now
iReach = iReach2;
for(size_t i = 0; i < sections.size(); ++i )
sections[i]->Dirty(iReach);
for(auto & section : sections)
section->Dirty(iReach);
}
}
@ -110,13 +110,13 @@ void C4FoWLight::Update(C4Rect Rec)
// Clear if we moved in any way
if (iNX != iX || iNY != iY)
{
for(size_t i = 0; i < sections.size(); ++i )
sections[i]->Prune(0);
for(auto & section : sections)
section->Prune(0);
iX = iNX; iY = iNY;
}
for(size_t i = 0; i < sections.size(); ++i )
sections[i]->Update(Rec);
for(auto & section : sections)
section->Update(Rec);
}
void C4FoWLight::Render(C4FoWRegion *region, const C4TargetFacet *onScreen, C4ShaderCall& call)
@ -125,9 +125,9 @@ void C4FoWLight::Render(C4FoWRegion *region, const C4TargetFacet *onScreen, C4Sh
bool clip = false;
for(size_t i = 0; i < sections.size(); ++i )
for(auto & section : sections)
{
TriangleList sectionTriangles = sections[i]->CalculateTriangles(region);
TriangleList sectionTriangles = section->CalculateTriangles(region);
// if the triangles of one section are clipped completely, the neighbouring triangles
// must be marked as clipped
@ -145,9 +145,9 @@ void C4FoWLight::Render(C4FoWRegion *region, const C4TargetFacet *onScreen, C4Sh
if (!strategy.get())
{
if (onScreen)
strategy.reset(new C4FoWDrawWireframeStrategy(this, onScreen));
strategy = std::make_unique<C4FoWDrawWireframeStrategy>(this, onScreen);
else
strategy.reset(new C4FoWDrawLightTextureStrategy(this));
strategy = std::make_unique<C4FoWDrawLightTextureStrategy>(this);
}
strategy->Begin(region);
@ -162,10 +162,8 @@ void C4FoWLight::Render(C4FoWRegion *region, const C4TargetFacet *onScreen, C4Sh
void C4FoWLight::CalculateFanMaxed(TriangleList &triangles) const
{
for (TriangleList::iterator it = triangles.begin(); it != triangles.end(); ++it)
for (auto & tri : triangles)
{
C4FoWBeamTriangle &tri = *it;
// Is the left point close enough that normals don't max out?
float dist = sqrt(GetSquaredDistanceTo(tri.fanLX, tri.fanLY));
if (dist <= getNormalSize()) {
@ -305,10 +303,8 @@ void C4FoWLight::DrawFade(C4FoWDrawStrategy* pen, TriangleList &triangles) const
{
pen->BeginFade();
for (TriangleList::iterator it = triangles.begin(); it != triangles.end(); ++it)
for (auto & tri : triangles)
{
C4FoWBeamTriangle &tri = *it; // just for convenience
// The quad will be empty if fan points match
if (tri.fanLX == tri.fanRX && tri.fanLY == tri.fanRY) continue;

View File

@ -25,7 +25,7 @@
#include "landscape/fow/C4FoWRegion.h"
#include "landscape/C4Landscape.h"
#include "float.h"
#include <cfloat>
#include <iterator>
@ -752,10 +752,8 @@ std::list<C4FoWBeamTriangle> C4FoWLightSection::CalculateTriangles(C4FoWRegion *
#endif
// Phase 2: Calculate fade points
for (std::list<C4FoWBeamTriangle>::iterator it = result.begin(); it != result.end(); ++it)
for (auto & tri : result)
{
C4FoWBeamTriangle &tri = *it;
// Calculate light bounds. Note that the way light size is calculated
// and we are using it below, we need to consider an "asymetrical" light.
float lightLX, lightLY, lightRX, lightRY;
@ -797,9 +795,8 @@ std::list<C4FoWBeamTriangle> C4FoWLightSection::CalculateTriangles(C4FoWRegion *
void C4FoWLightSection::transTriangles(std::list<C4FoWBeamTriangle> &triangles) const
{
for (std::list<C4FoWBeamTriangle>::iterator it = triangles.begin(); it != triangles.end(); ++it)
for (auto & tri : triangles)
{
C4FoWBeamTriangle &tri = *it;
float x,y;
x = tri.fanRX, y = tri.fanRY;

View File

@ -161,7 +161,7 @@ namespace C4InVal
assert(!"not yet implemented");
}
// issue warning for invalid adjustments
if (0) if (!fValid)
if (false) if (!fValid)
{
const char *szOption = "unknown";
switch (eOption)
@ -178,7 +178,7 @@ namespace C4InVal
case VAL_IRCChannel: szOption = "IRC channel"; break;
case VAL_Comment: szOption = "Comment"; break;
}
LogF("WARNING: Adjusted invalid user input for \"%s\" to \"%s\"", szOption, rsString.getData());
LogF(R"(WARNING: Adjusted invalid user input for "%s" to "%s")", szOption, rsString.getData());
}
return !fValid;
}

View File

@ -33,12 +33,12 @@ void C4MarkupTagColor::Apply(C4BltTransform &rBltTrf, bool fDoClr, DWORD &dwClr)
bool C4Markup::Read(const char **ppText, bool fSkip)
{
char Tag[50]; C4MarkupTag *pNewTag=0; int iTagLen,iParLen;
char Tag[50]; C4MarkupTag *pNewTag=nullptr; int iTagLen,iParLen;
// get tag
if (!SCopyEnclosed(*ppText, '<', '>', Tag, 49)) return false;
iTagLen=SLen(Tag);
// split tag to name and pars
char *szPars=0; int iSPos;
char *szPars=nullptr; int iSPos;
if ((iSPos=SCharPos(' ', Tag))>-1)
{
Tag[iSPos]=0;

View File

@ -63,8 +63,8 @@ bool C4NameList::Add(const char *szName, int32_t iCount)
bool C4NameList::IsEmpty()
{
for (int32_t cnt=0; cnt<C4MaxNameList; cnt++)
if (Name[cnt][0])
for (auto & cnt : Name)
if (cnt[0])
return false;
return true;
}

View File

@ -21,13 +21,11 @@
// ** implemetation of C4MainStat
C4MainStat::C4MainStat()
: pFirst(0)
: pFirst(nullptr)
{
}
C4MainStat::~C4MainStat()
{
}
C4MainStat::~C4MainStat() = default;
void C4MainStat::RegisterStat(C4Stat* pStat)
{
@ -35,14 +33,14 @@ void C4MainStat::RegisterStat(C4Stat* pStat)
if (!pFirst)
{
pFirst = pStat;
pStat->pNext = 0;
pStat->pPrev = 0;
pStat->pNext = nullptr;
pStat->pPrev = nullptr;
}
else
{
pStat->pNext = pFirst;
pFirst->pPrev = pStat;
pStat->pPrev = 0;
pStat->pPrev = nullptr;
pFirst = pStat;
}
}
@ -53,20 +51,20 @@ void C4MainStat::UnRegStat(C4Stat* pStat)
if (!pStat->pPrev)
{
pFirst = pStat->pNext;
pStat->pNext = 0;
pStat->pNext = nullptr;
}
// last item?
else if (!pStat->pNext)
{
pStat->pPrev->pNext = 0;
pStat->pPrev = 0;
pStat->pPrev->pNext = nullptr;
pStat->pPrev = nullptr;
}
else
{
pStat->pNext->pPrev = pStat->pPrev;
pStat->pPrev->pNext = pStat->pNext;
pStat->pNext = 0;
pStat->pPrev = 0;
pStat->pNext = nullptr;
pStat->pPrev = nullptr;
}
}
@ -93,8 +91,8 @@ void C4MainStat::Show()
iCnt++;
// create array
C4Stat** StatArray = new C4Stat*[iCnt];
bool* bHS = new bool[iCnt];
auto** StatArray = new C4Stat*[iCnt];
auto* bHS = new bool[iCnt];
// sort it
unsigned int i,ii;

View File

@ -121,7 +121,7 @@ int32_t StrToI32(const char *str, int base, const char **scan_end)
result *= base;
result += value;
}
if (scan_end != 0L) *scan_end = s;
if (scan_end != nullptr) *scan_end = s;
result *= sign;
return result;
}

View File

@ -19,8 +19,8 @@
#include "lib/StdAdaptors.h"
#include "platform/StdFile.h"
#include <stdarg.h>
#include <stdio.h>
#include <cstdarg>
#include <cstdio>
#ifdef _WIN32
#include <io.h>
#include "platform/C4windowswrapper.h"
@ -30,7 +30,7 @@
#include <unistd.h>
#include <stdlib.h>
#endif
#include <ctype.h>
#include <cctype>
#include <fcntl.h>
#include <sys/stat.h>
@ -140,9 +140,9 @@ void StdBuf::CompileFunc(StdCompiler *pComp, int iType)
#ifdef _WIN32
StdStrBuf::StdStrBuf(const wchar_t * utf16)
{
int len = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, nullptr, 0, 0, 0);
int len = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, nullptr, 0, nullptr, nullptr);
SetSize(len);
WideCharToMultiByte(CP_UTF8, 0, utf16, -1, getMData(), getSize(), 0, 0);
WideCharToMultiByte(CP_UTF8, 0, utf16, -1, getMData(), getSize(), nullptr, nullptr);
}
StdStrBuf::wchar_t_holder StdStrBuf::GetWideChar() const
{
@ -461,8 +461,8 @@ bool StdStrBuf::EnsureUnicode()
{
//"€", 0, "", "ƒ", "„", "…", "†", "‡", "ˆ", "‰", "Š", "", "Œ", 0, "Ž", 0,
// 0, "", "", "“", "”", "•", "", "—", "˜", "™", "š", "", "œ", 0, "ž", "Ÿ" };
"\xe2\x82\xac", 0, "\xe2\x80\x9a", "\xc6\x92", "\xe2\x80\x9e", "\xe2\x80\xa6", "\xe2\x80\xa0", "\xe2\x80\xa1", "\xcb\x86", "\xe2\x80\xb0", "\xc5\xa0", "\xe2\x80\xb9", "\xc5\x92", 0, "\xc5\xbd", 0,
0, "\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\xa2", "\xe2\x80\x93", "\xe2\x80\x94", "\xcb\x9c", "\xe2\x84\xa2", "\xc5\xa1", "\xe2\x80\xba", "\xc5\x93", 0, "\xc5\xbe", "\xc5\xb8"
"\xe2\x82\xac", nullptr, "\xe2\x80\x9a", "\xc6\x92", "\xe2\x80\x9e", "\xe2\x80\xa6", "\xe2\x80\xa0", "\xe2\x80\xa1", "\xcb\x86", "\xe2\x80\xb0", "\xc5\xa0", "\xe2\x80\xb9", "\xc5\x92", nullptr, "\xc5\xbd", nullptr,
nullptr, "\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\xa2", "\xe2\x80\x93", "\xe2\x80\x94", "\xcb\x9c", "\xe2\x84\xa2", "\xc5\xa1", "\xe2\x80\xba", "\xc5\x93", nullptr, "\xc5\xbe", "\xc5\xb8"
};
buf.Append(extra_chars[c - 0x80]);
j += strlen(extra_chars[c - 0x80]);
@ -511,12 +511,12 @@ bool StdStrBuf::TrimSpaces()
#ifdef _WIN32
std::string WStrToString(wchar_t *ws)
{
int len = WideCharToMultiByte(CP_UTF8, 0, ws, -1, nullptr, 0, 0, 0);
int len = WideCharToMultiByte(CP_UTF8, 0, ws, -1, nullptr, 0, nullptr, nullptr);
assert(len >= 0);
if (len <= 0) return std::string{};
std::string s(static_cast<size_t>(len), '\0');
s.resize(WideCharToMultiByte(CP_UTF8, 0, ws, -1, &s[0], s.size(), 0, 0) - 1);
s.resize(WideCharToMultiByte(CP_UTF8, 0, ws, -1, &s[0], s.size(), nullptr, nullptr) - 1);
return s;
}
#endif

View File

@ -16,9 +16,9 @@
#include "C4Include.h"
#include "lib/StdCompiler.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include "lib/C4Log.h"
// *** StdCompiler
@ -393,17 +393,17 @@ void StdCompilerINIWrite::WriteEscaped(const char *szString, const char *pEnd)
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;
case '\a': Buf.Append(R"(\a)"); break;
case '\b': Buf.Append(R"(\b)"); break;
case '\f': Buf.Append(R"(\f)"); break;
case '\n': Buf.Append(R"(\n)"); break;
case '\r': Buf.Append(R"(\r)"); break;
case '\t': Buf.Append(R"(\t)"); break;
case '\v': Buf.Append(R"(\v)"); break;
case '\"': Buf.Append(R"(\")"); break;
case '\\': Buf.Append(R"(\\)"); break;
default:
Buf.AppendFormat("\\%o", *reinterpret_cast<const unsigned char *>(pPos));
Buf.AppendFormat(R"(\%o)", *reinterpret_cast<const unsigned char *>(pPos));
fLastNumEscape = true;
}
// Set pointer
@ -497,7 +497,7 @@ void StdCompilerINIRead::NameEnd(bool fBreak)
{
// Report unused entries
if (pNode->Pos && !fBreak)
Warn("Unexpected %s \"%s\"!", pNode->Section ? "section" : "value", pNode->Name.getData());
Warn(R"(Unexpected %s "%s"!)", pNode->Section ? "section" : "value", pNode->Name.getData());
// delete node
pNext = pNode->NextChild;
delete pNode;
@ -587,7 +587,7 @@ int StdCompilerINIRead::NameCount(const char *szName)
const char *StdCompilerINIRead::GetNameByIndex(size_t idx) const
{
// not in virtual naming
if (iDepth > iRealDepth || !pName) return 0;
if (iDepth > iRealDepth || !pName) return nullptr;
// count within current name
NameNode *pNode;
for (pNode = pName->FirstChild; pNode; pNode = pNode->NextChild)
@ -732,11 +732,11 @@ StdStrBuf StdCompilerINIRead::getPosition() const
if (pPos)
return FormatString("line %d", getLineNumberOfPos(pPos));
else if (iDepth == iRealDepth)
return FormatString(pName->Section ? "section \"%s\", after line %d" : "value \"%s\", line %d", pName->Name.getData(), getLineNumberOfPos(pName->Pos));
return FormatString(pName->Section ? R"(section "%s", after line %d)" : R"(value "%s", line %d)", pName->Name.getData(), getLineNumberOfPos(pName->Pos));
else if (iRealDepth)
return FormatString("missing value/section \"%s\" inside section \"%s\" (line %d)", NotFoundName.getData(), pName->Name.getData(), getLineNumberOfPos(pName->Pos));
return FormatString(R"(missing value/section "%s" inside section "%s" (line %d))", NotFoundName.getData(), pName->Name.getData(), getLineNumberOfPos(pName->Pos));
else
return FormatString("missing value/section \"%s\"", NotFoundName.getData());
return FormatString(R"(missing value/section "%s")", NotFoundName.getData());
}
void StdCompilerINIRead::Begin()

View File

@ -158,7 +158,7 @@ namespace
pComp->Value(mkParAdapt(id_str, StdCompiler::RCT_Idtf));
id = StdMeshInstance::SerializableValueProvider::Lookup(id_str.getData());
if(!id) pComp->excCorrupt("No value provider for ID \"%s\"", id_str.getData());
if(!id) pComp->excCorrupt(R"(No value provider for ID "%s")", id_str.getData());
}
else
{
@ -344,8 +344,8 @@ StdMeshAnimation::StdMeshAnimation(const StdMeshAnimation& other):
StdMeshAnimation::~StdMeshAnimation()
{
for (unsigned int i = 0; i < Tracks.size(); ++i)
delete Tracks[i];
for (auto & Track : Tracks)
delete Track;
}
StdMeshAnimation& StdMeshAnimation::operator=(const StdMeshAnimation& other)
@ -355,8 +355,8 @@ StdMeshAnimation& StdMeshAnimation::operator=(const StdMeshAnimation& other)
Name = other.Name;
Length = other.Length;
for (unsigned int i = 0; i < Tracks.size(); ++i)
delete Tracks[i];
for (auto & Track : Tracks)
delete Track;
Tracks.resize(other.Tracks.size());
@ -367,30 +367,28 @@ StdMeshAnimation& StdMeshAnimation::operator=(const StdMeshAnimation& other)
return *this;
}
StdMeshSkeleton::StdMeshSkeleton()
{
}
StdMeshSkeleton::StdMeshSkeleton() = default;
StdMeshSkeleton::~StdMeshSkeleton()
{
for (unsigned int i = 0; i < Bones.size(); ++i)
delete Bones[i];
for (auto & Bone : Bones)
delete Bone;
}
void StdMeshSkeleton::AddMasterBone(StdMeshBone *bone)
{
bone->Index = Bones.size(); // Remember index in master bone table
Bones.push_back(bone);
for (unsigned int i = 0; i < bone->Children.size(); ++i)
AddMasterBone(bone->Children[i]);
for (auto & i : bone->Children)
AddMasterBone(i);
}
const StdMeshBone* StdMeshSkeleton::GetBoneByName(const StdStrBuf& name) const
{
// Lookup parent bone
for (unsigned int i = 0; i < Bones.size(); ++i)
if (Bones[i]->Name == name)
return Bones[i];
for (auto Bone : Bones)
if (Bone->Name == name)
return Bone;
return nullptr;
}
@ -407,8 +405,8 @@ std::vector<const StdMeshAnimation*> StdMeshSkeleton::GetAnimations() const
{
std::vector<const StdMeshAnimation*> result;
result.reserve(Animations.size());
for (std::map<StdCopyStrBuf, StdMeshAnimation>::const_iterator iter = Animations.begin(); iter != Animations.end(); ++iter)
result.push_back(&iter->second);
for (const auto & Animation : Animations)
result.push_back(&Animation.second);
return result;
}
@ -448,12 +446,12 @@ void StdMeshSkeleton::MirrorAnimation(const StdMeshAnimation& animation)
// Mirror all the keyframes of both tracks
if (new_anim.Tracks[i] != nullptr)
for (std::map<float, StdMeshKeyFrame>::iterator iter = new_anim.Tracks[i]->Frames.begin(); iter != new_anim.Tracks[i]->Frames.end(); ++iter)
MirrorKeyFrame(iter->second, own_trans, StdMeshTransformation::Inverse(other_own_trans));
for (auto & Frame : new_anim.Tracks[i]->Frames)
MirrorKeyFrame(Frame.second, own_trans, StdMeshTransformation::Inverse(other_own_trans));
if (new_anim.Tracks[other_bone->Index] != nullptr)
for (std::map<float, StdMeshKeyFrame>::iterator iter = new_anim.Tracks[other_bone->Index]->Frames.begin(); iter != new_anim.Tracks[other_bone->Index]->Frames.end(); ++iter)
MirrorKeyFrame(iter->second, other_own_trans, StdMeshTransformation::Inverse(own_trans));
for (auto & Frame : new_anim.Tracks[other_bone->Index]->Frames)
MirrorKeyFrame(Frame.second, other_own_trans, StdMeshTransformation::Inverse(own_trans));
}
}
else if (bone.Name.Compare_(".N", bone.Name.getLength() - 2) != 0)
@ -463,8 +461,8 @@ void StdMeshSkeleton::MirrorAnimation(const StdMeshAnimation& animation)
StdMeshTransformation own_trans = bone.Transformation;
if (bone.GetParent()) own_trans = bone.GetParent()->InverseTransformation * bone.Transformation;
for (std::map<float, StdMeshKeyFrame>::iterator iter = new_anim.Tracks[i]->Frames.begin(); iter != new_anim.Tracks[i]->Frames.end(); ++iter)
MirrorKeyFrame(iter->second, own_trans, StdMeshTransformation::Inverse(own_trans));
for (auto & Frame : new_anim.Tracks[i]->Frames)
MirrorKeyFrame(Frame.second, own_trans, StdMeshTransformation::Inverse(own_trans));
}
}
}
@ -507,14 +505,14 @@ void StdMeshSkeleton::InsertAnimation(const StdMeshSkeleton& source, const StdMe
void StdMeshSkeleton::PostInit()
{
// Mirror .R and .L animations without counterpart
for (std::map<StdCopyStrBuf, StdMeshAnimation>::iterator iter = Animations.begin(); iter != Animations.end(); ++iter)
for (auto & Animation : Animations)
{
// For debugging purposes:
// if(iter->second.Name == "Jump")
// MirrorAnimation(StdCopyStrBuf("Jump.Mirror"), iter->second);
// mirrors only if necessary
MirrorAnimation(iter->second);
MirrorAnimation(Animation.second);
}
}
@ -773,7 +771,7 @@ void StdSubMeshInstance::CompileFunc(StdCompiler* pComp)
if(!material)
{
StdStrBuf buf;
buf.Format("There is no such material with name \"%s\"", material_name.getData());
buf.Format(R"(There is no such material with name "%s")", material_name.getData());
pComp->excCorrupt(buf.getData());
}
@ -894,7 +892,7 @@ void StdMeshInstanceAnimationNode::CompileFunc(StdCompiler* pComp, const StdMesh
StdCopyStrBuf anim_name;
pComp->Value(mkNamingAdapt(toC4CStrBuf(anim_name), "Animation"));
Leaf.Animation = Mesh->GetSkeleton().GetAnimationByName(anim_name);
if(!Leaf.Animation) pComp->excCorrupt("No such animation: \"%s\"", anim_name.getData());
if(!Leaf.Animation) pComp->excCorrupt(R"(No such animation: "%s")", anim_name.getData());
}
else
{
@ -909,7 +907,7 @@ void StdMeshInstanceAnimationNode::CompileFunc(StdCompiler* pComp, const StdMesh
StdCopyStrBuf bone_name;
pComp->Value(mkNamingAdapt(toC4CStrBuf(bone_name), "Bone"));
const StdMeshBone* bone = Mesh->GetSkeleton().GetBoneByName(bone_name);
if(!bone) pComp->excCorrupt("No such bone: \"%s\"", bone_name.getData());
if(!bone) pComp->excCorrupt(R"(No such bone: "%s")", bone_name.getData());
Custom.BoneIndex = bone->Index;
Custom.Transformation = new StdMeshTransformation;
}
@ -1122,9 +1120,9 @@ StdMeshInstance::~StdMeshInstance()
assert(AnimationNodes.empty());
// Delete submeshes
for (unsigned int i = 0; i < SubMeshInstances.size(); ++i)
for (auto & SubMeshInstance : SubMeshInstances)
{
delete SubMeshInstances[i];
delete SubMeshInstance;
}
}
@ -1307,9 +1305,9 @@ void StdMeshInstance::ExecuteAnimation(float dt)
#ifndef USE_CONSOLE
// Update animated textures
for (unsigned int i = 0; i < SubMeshInstances.size(); ++i)
for (auto & SubMeshInstance : SubMeshInstances)
{
StdSubMeshInstance& submesh = *SubMeshInstances[i];
StdSubMeshInstance& submesh = *SubMeshInstance;
const StdMeshMaterial& material = submesh.GetMaterial();
const StdMeshMaterialTechnique& technique = material.Techniques[material.BestTechniqueIndex];
for (unsigned int j = 0; j < submesh.PassData.size(); ++j)
@ -1339,8 +1337,8 @@ void StdMeshInstance::ExecuteAnimation(float dt)
#endif
// Update animation for attached meshes
for (AttachedMeshList::iterator iter = AttachChildren.begin(); iter != AttachChildren.end(); ++iter)
(*iter)->Child->ExecuteAnimation(dt);
for (auto & iter : AttachChildren)
iter->Child->ExecuteAnimation(dt);
}
StdMeshInstance::AttachedMesh* StdMeshInstance::AttachMesh(const StdMesh& mesh, AttachedMesh::Denumerator* denumerator, const StdStrBuf& parent_bone, const StdStrBuf& child_bone, const StdMeshMatrix& transformation, uint32_t flags, unsigned int attach_number)
@ -1498,17 +1496,17 @@ bool StdMeshInstance::UpdateBoneTransforms()
assert(!parent || parent->Index < i);
bool have_transform = false;
for (unsigned int j = 0; j < AnimationStack.size(); ++j)
for (auto & j : AnimationStack)
{
if (have_transform)
{
StdMeshTransformation other;
if (AnimationStack[j]->GetBoneTransform(i, other))
if (j->GetBoneTransform(i, other))
Transformation = StdMeshTransformation::Nlerp(Transformation, other, 1.0f); // TODO: Allow custom weighing for slot combination
}
else
{
have_transform = AnimationStack[j]->GetBoneTransform(i, Transformation);
have_transform = j->GetBoneTransform(i, Transformation);
}
}
@ -1528,9 +1526,8 @@ bool StdMeshInstance::UpdateBoneTransforms()
}
// Update attachment's attach transformations. Note this is done recursively.
for (AttachedMeshList::iterator iter = AttachChildren.begin(); iter != AttachChildren.end(); ++iter)
for (auto attach : AttachChildren)
{
AttachedMesh* attach = *iter;
const bool ChildBoneTransformsDirty = attach->Child->BoneTransformsDirty;
attach->Child->UpdateBoneTransforms();
@ -1566,9 +1563,9 @@ bool StdMeshInstance::UpdateBoneTransforms()
void StdMeshInstance::ReorderFaces(StdMeshMatrix* global_trans)
{
#ifndef USE_CONSOLE
for (unsigned int i = 0; i < SubMeshInstances.size(); ++i)
for (auto & SubMeshInstance : SubMeshInstances)
{
StdSubMeshInstance& inst = *SubMeshInstances[i];
StdSubMeshInstance& inst = *SubMeshInstance;
assert((inst.Faces.size() > 0) && "StdMeshInstance sub-mesh instance has zero faces");
if(inst.Faces.size() > 0 && inst.CurrentFaceOrdering != StdSubMeshInstance::FO_Fixed)
@ -1671,42 +1668,42 @@ void StdMeshInstance::CompileFunc(StdCompiler* pComp, AttachedMesh::DenumeratorF
int32_t iAnimCnt = AnimationStack.size();
pComp->Value(mkNamingCountAdapt(iAnimCnt, "AnimationNode"));
for(AnimationNodeList::iterator iter = AnimationStack.begin(); iter != AnimationStack.end(); ++iter)
pComp->Value(mkParAdapt(mkNamingPtrAdapt(*iter, "AnimationNode"), Mesh));
for(auto & iter : AnimationStack)
pComp->Value(mkParAdapt(mkNamingPtrAdapt(iter, "AnimationNode"), Mesh));
int32_t iAttachedCnt = AttachChildren.size();
pComp->Value(mkNamingCountAdapt(iAttachedCnt, "Attached"));
for(unsigned int i = 0; i < AttachChildren.size(); ++i)
pComp->Value(mkNamingAdapt(mkParAdapt(*AttachChildren[i], Factory), "Attached"));
for(auto & i : AttachChildren)
pComp->Value(mkNamingAdapt(mkParAdapt(*i, Factory), "Attached"));
}
}
void StdMeshInstance::DenumeratePointers()
{
for(unsigned int i = 0; i < AnimationNodes.size(); ++i)
if(AnimationNodes[i])
AnimationNodes[i]->DenumeratePointers();
for(auto & AnimationNode : AnimationNodes)
if(AnimationNode)
AnimationNode->DenumeratePointers();
for(unsigned int i = 0; i < AttachChildren.size(); ++i)
for(auto & i : AttachChildren)
{
AttachChildren[i]->DenumeratePointers();
i->DenumeratePointers();
}
}
void StdMeshInstance::ClearPointers(class C4Object* pObj)
{
for(unsigned int i = 0; i < AnimationNodes.size(); ++i)
if(AnimationNodes[i])
AnimationNodes[i]->ClearPointers(pObj);
for(auto & AnimationNode : AnimationNodes)
if(AnimationNode)
AnimationNode->ClearPointers(pObj);
std::vector<unsigned int> Removal;
for(unsigned int i = 0; i < AttachChildren.size(); ++i)
if(!AttachChildren[i]->ClearPointers(pObj))
Removal.push_back(AttachChildren[i]->Number);
for(auto & i : AttachChildren)
if(!i->ClearPointers(pObj))
Removal.push_back(i->Number);
for(unsigned int i = 0; i < Removal.size(); ++i)
DetachMesh(Removal[i]);
for(unsigned int i : Removal)
DetachMesh(i);
}
template<typename IteratorType, typename FuncObj>
@ -1909,10 +1906,8 @@ void StdMeshInstance::SetBoneTransformsDirty(bool value)
if (value)
{
// Update attachment's attach transformations. Note this is done recursively.
for (AttachedMeshList::iterator iter = AttachChildren.begin(); iter != AttachChildren.end(); ++iter)
for (auto attach : AttachChildren)
{
AttachedMesh* attach = *iter;
if (attach->GetFlags() & AM_MatchSkeleton)
{
attach->Child->SetBoneTransformsDirty(value);

View File

@ -247,9 +247,9 @@ void StdMeshSkeletonLoader::RemoveSkeletonsInGroup(const char* groupname)
}
}
for (unsigned i = 0; i < delete_skeletons.size(); i++)
for (const auto & delete_skeleton : delete_skeletons)
{
RemoveSkeleton(delete_skeletons[i]);
RemoveSkeleton(delete_skeleton);
}
}
@ -560,10 +560,8 @@ StdMesh *StdMeshLoader::LoadMeshBinary(const char *sourcefile, size_t length, co
else
vertices = &mesh->SharedVertices;
for (unsigned int j = 0; j < vertices->size(); ++j)
for (const auto & vertex : *vertices)
{
const StdMeshVertex& vertex = (*vertices)[j];
const float d = std::sqrt(vertex.x*vertex.x
+ vertex.y*vertex.y
+ vertex.z*vertex.z);

View File

@ -63,26 +63,26 @@ namespace Ogre
std::unique_ptr<Chunk> chunk;
switch (id)
{
case CID_Header: chunk.reset(new ChunkFileHeader()); break;
case CID_Mesh: chunk.reset(new ChunkMesh()); break;
case CID_Header: chunk = std::make_unique<Ogre::Mesh::ChunkFileHeader>(); break;
case CID_Mesh: chunk = std::make_unique<Ogre::Mesh::ChunkMesh>(); break;
case CID_Mesh_Bone_Assignment:
case CID_Submesh_Bone_Assignment:
chunk.reset(new ChunkMeshBoneAssignments()); break;
case CID_Mesh_Skeleton_Link: chunk.reset(new ChunkMeshSkeletonLink()); break;
case CID_Mesh_Bounds: chunk.reset(new ChunkMeshBounds()); break;
case CID_Submesh: chunk.reset(new ChunkSubmesh()); break;
case CID_Submesh_Op: chunk.reset(new ChunkSubmeshOp()); break;
case CID_Geometry: chunk.reset(new ChunkGeometry()); break;
case CID_Geometry_Vertex_Buffer: chunk.reset(new ChunkGeometryVertexBuffer()); break;
case CID_Geometry_Vertex_Data: chunk.reset(new ChunkGeometryVertexData()); break;
case CID_Geometry_Vertex_Decl: chunk.reset(new ChunkGeometryVertexDecl()); break;
case CID_Geometry_Vertex_Decl_Element: chunk.reset(new ChunkGeometryVertexDeclElement()); break;
chunk = std::make_unique<Ogre::Mesh::ChunkMeshBoneAssignments>(); break;
case CID_Mesh_Skeleton_Link: chunk = std::make_unique<Ogre::Mesh::ChunkMeshSkeletonLink>(); break;
case CID_Mesh_Bounds: chunk = std::make_unique<Ogre::Mesh::ChunkMeshBounds>(); break;
case CID_Submesh: chunk = std::make_unique<Ogre::Mesh::ChunkSubmesh>(); break;
case CID_Submesh_Op: chunk = std::make_unique<Ogre::Mesh::ChunkSubmeshOp>(); break;
case CID_Geometry: chunk = std::make_unique<Ogre::Mesh::ChunkGeometry>(); break;
case CID_Geometry_Vertex_Buffer: chunk = std::make_unique<Ogre::Mesh::ChunkGeometryVertexBuffer>(); break;
case CID_Geometry_Vertex_Data: chunk = std::make_unique<Ogre::Mesh::ChunkGeometryVertexData>(); break;
case CID_Geometry_Vertex_Decl: chunk = std::make_unique<Ogre::Mesh::ChunkGeometryVertexDecl>(); break;
case CID_Geometry_Vertex_Decl_Element: chunk = std::make_unique<Ogre::Mesh::ChunkGeometryVertexDeclElement>(); break;
default:
LogF("StdMeshLoader: I don't know what to do with a chunk of type 0x%xu", id);
// Fall through
case CID_Edge_List: case CID_Submesh_Name_Table:
// We don't care about these
chunk.reset(new ChunkUnknown()); break;
chunk = std::make_unique<Ogre::Mesh::ChunkUnknown>(); break;
};
chunk->type = id;
chunk->size = size;
@ -343,18 +343,18 @@ namespace Ogre
std::unique_ptr<Chunk> chunk;
switch (id)
{
case CID_Header: chunk.reset(new ChunkFileHeader()); break;
case CID_BlendMode: chunk.reset(new ChunkBlendMode()); break;
case CID_Bone: chunk.reset(new ChunkBone()); break;
case CID_Bone_Parent: chunk.reset(new ChunkBoneParent()); break;
case CID_Animation: chunk.reset(new ChunkAnimation()); break;
case CID_Animation_BaseInfo: chunk.reset(new ChunkAnimationBaseInfo()); break;
case CID_Animation_Track: chunk.reset(new ChunkAnimationTrack()); break;
case CID_Animation_Track_KF: chunk.reset(new ChunkAnimationTrackKF()); break;
case CID_Animation_Link: chunk.reset(new ChunkAnimationLink()); break;
case CID_Header: chunk = std::make_unique<Ogre::Skeleton::ChunkFileHeader>(); break;
case CID_BlendMode: chunk = std::make_unique<Ogre::Skeleton::ChunkBlendMode>(); break;
case CID_Bone: chunk = std::make_unique<Ogre::Skeleton::ChunkBone>(); break;
case CID_Bone_Parent: chunk = std::make_unique<Ogre::Skeleton::ChunkBoneParent>(); break;
case CID_Animation: chunk = std::make_unique<Ogre::Skeleton::ChunkAnimation>(); break;
case CID_Animation_BaseInfo: chunk = std::make_unique<Ogre::Skeleton::ChunkAnimationBaseInfo>(); break;
case CID_Animation_Track: chunk = std::make_unique<Ogre::Skeleton::ChunkAnimationTrack>(); break;
case CID_Animation_Track_KF: chunk = std::make_unique<Ogre::Skeleton::ChunkAnimationTrackKF>(); break;
case CID_Animation_Link: chunk = std::make_unique<Ogre::Skeleton::ChunkAnimationLink>(); break;
default:
LogF("StdMeshLoader: I don't know what to do with a chunk of type 0x%xu", id);
chunk.reset(new ChunkUnknown()); break;
chunk = std::make_unique<Ogre::Skeleton::ChunkUnknown>(); break;
};
chunk->type = id;
chunk->size = size;

View File

@ -111,8 +111,8 @@ void StdMeshLoader::StdMeshXML::LoadGeometry(StdMesh& mesh, std::vector<StdSubMe
// initialization of bounding box and bounding sphere.
bool hasVertices = false;
if(!mesh.SharedVertices.empty()) hasVertices = true;
for(unsigned int i = 0; i < mesh.SubMeshes.size(); ++i)
if(!mesh.SubMeshes[i].Vertices.empty())
for(auto & SubMesh : mesh.SubMeshes)
if(!SubMesh.Vertices.empty())
hasVertices = true;
int VertexCount = RequireIntAttribute(geometry_elem, "vertexcount");
@ -245,9 +245,8 @@ void StdMeshLoader::StdMeshXML::LoadBoneAssignments(StdMesh& mesh, std::vector<S
// Normalize vertex bone assignment weights (this is not guaranteed in the
// Ogre file format).
for (unsigned int i = 0; i < vertices.size(); ++i)
for (auto & vertex : vertices)
{
StdSubMesh::Vertex& vertex = vertices[i];
float sum = 0.0;
for (float weight : vertex.bone_weight)
sum += weight;
@ -456,9 +455,9 @@ void StdMeshSkeletonLoader::LoadSkeletonXml(const char* groupname, const char* f
std::shared_ptr<StdMeshSkeleton> Skeleton(new StdMeshSkeleton);
// Fill master bone table in hierarchical order:
for (unsigned int i = 0; i < bones.size(); ++i)
if (bones[i]->Parent == nullptr)
Skeleton->AddMasterBone(bones[i]);
for (auto & bone : bones)
if (bone->Parent == nullptr)
Skeleton->AddMasterBone(bone);
// Load Animations
TiXmlElement* animations_elem = skeleton_elem->FirstChildElement("animations");

View File

@ -27,7 +27,7 @@
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif /* _MSC_VER */
#include <math.h>
#include <cmath>
#ifdef WITH_GLIB
#include <glib.h>
@ -246,7 +246,7 @@ public:
template<typename SubT> void Load(StdMeshMaterialParserCtx& ctx, std::vector<SubT>& vec);
private:
unsigned int CurIndex;
unsigned int CurIndex{0u};
};
StdMeshMaterialParserCtx::StdMeshMaterialParserCtx(StdMeshMatManager& manager, const char* mat_script, const char* filename, StdMeshMaterialLoader& loader):
@ -522,13 +522,10 @@ void StdMeshMaterialParserCtx::ErrorUnexpectedIdentifier(const StdStrBuf& identi
void StdMeshMaterialParserCtx::WarningNotSupported(const char* identifier)
{
DebugLogF("%s:%d: Warning: \"%s\" is not supported!", FileName.getData(), Line, identifier);
DebugLogF(R"(%s:%d: Warning: "%s" is not supported!)", FileName.getData(), Line, identifier);
}
StdMeshMaterialSubLoader::StdMeshMaterialSubLoader()
: CurIndex(0)
{
}
StdMeshMaterialSubLoader::StdMeshMaterialSubLoader() = default;
template<typename SubT>
void StdMeshMaterialSubLoader::Load(StdMeshMaterialParserCtx& ctx, std::vector<SubT>& vec)
@ -734,9 +731,7 @@ void StdMeshMaterialShaderParameter::Move(StdMeshMaterialShaderParameter &&other
other.type = FLOAT;
}
StdMeshMaterialShaderParameters::StdMeshMaterialShaderParameters()
{
}
StdMeshMaterialShaderParameters::StdMeshMaterialShaderParameters() = default;
StdMeshMaterialShaderParameter StdMeshMaterialShaderParameters::LoadConstParameter(StdMeshMaterialParserCtx& ctx)
{
@ -780,7 +775,7 @@ StdMeshMaterialShaderParameter StdMeshMaterialShaderParameters::LoadConstParamet
}
else
{
ctx.Error(FormatString("Invalid type: \"%s\"", type_name.getData()));
ctx.Error(FormatString(R"(Invalid type: "%s")", type_name.getData()));
return StdMeshMaterialShaderParameter();
}
}
@ -840,12 +835,12 @@ bool StdMeshMaterialProgram::AddParameterNames(const StdMeshMaterialShaderParame
{
// TODO: This is O(n^2) -- not optimal!
bool added = false;
for (unsigned int i = 0; i < parameters.NamedParameters.size(); ++i)
for (const auto & NamedParameter : parameters.NamedParameters)
{
const std::vector<StdCopyStrBuf>::const_iterator iter = std::find(ParameterNames.begin(), ParameterNames.end(), parameters.NamedParameters[i].first);
const std::vector<StdCopyStrBuf>::const_iterator iter = std::find(ParameterNames.begin(), ParameterNames.end(), NamedParameter.first);
if (iter == ParameterNames.end())
{
ParameterNames.push_back(parameters.NamedParameters[i].first);
ParameterNames.push_back(NamedParameter.first);
added = true;
}
}
@ -1031,7 +1026,7 @@ void StdMeshMaterialTextureUnit::LoadTexture(StdMeshMaterialParserCtx& ctx, cons
if (surface->Wdt != surface->Hgt)
ctx.Error(StdCopyStrBuf("Texture '") + texname + "' is not quadratic");
Textures.push_back(TexPtr(surface.release()));
Textures.emplace_back(surface.release());
}
void StdMeshMaterialTextureUnit::Load(StdMeshMaterialParserCtx& ctx)
@ -1179,8 +1174,8 @@ void StdMeshMaterialTextureUnit::Load(StdMeshMaterialParserCtx& ctx)
{
Transformation trans;
trans.TransformType = Transformation::T_TRANSFORM;
for (int i = 0; i < 16; ++i)
trans.Transform.M[i] = ctx.AdvanceFloat();
for (float & i : trans.Transform.M)
i = ctx.AdvanceFloat();
Transformations.push_back(trans);
}
else if (token_name == "wave_xform")
@ -1219,9 +1214,9 @@ StdMeshMaterialPass::ProgramInstance::ProgramInstance(const StdMeshMaterialProgr
void StdMeshMaterialPass::ProgramInstance::LoadParameterRefs(const ShaderInstance* instance)
{
for(unsigned int i = 0; i < instance->Parameters.NamedParameters.size(); ++i)
for(const auto & NamedParameter : instance->Parameters.NamedParameters)
{
const int index = Program->GetParameterIndex(instance->Parameters.NamedParameters[i].first.getData());
const int index = Program->GetParameterIndex(NamedParameter.first.getData());
assert(index != -1);
const std::vector<ParameterRef>::const_iterator parameter_iter =
@ -1234,7 +1229,7 @@ void StdMeshMaterialPass::ProgramInstance::LoadParameterRefs(const ShaderInstanc
else
{
ParameterRef ref;
ref.Parameter = &instance->Parameters.NamedParameters[i].second;
ref.Parameter = &NamedParameter.second;
ref.UniformIndex = index;
Parameters.push_back(ref);
}
@ -1472,8 +1467,8 @@ bool StdMeshMaterialTechnique::IsOpaque() const
// non-opaque passes will just depend on the opaque value drawn in
// the previous pass; total result will not depend on original
// frame buffer value).
for(unsigned int i = 0; i < Passes.size(); ++i)
if(Passes[i].IsOpaque())
for(const auto & Pass : Passes)
if(Pass.IsOpaque())
return true;
return false;
}

View File

@ -18,7 +18,7 @@
#ifdef _MSC_VER
# define _USE_MATH_DEFINES
# include <math.h>
# include <cmath>
#endif
#include "lib/StdMeshMath.h"

View File

@ -26,16 +26,16 @@ StdMeshMaterialUpdate::StdMeshMaterialUpdate(StdMeshMatManager& manager):
void StdMeshMaterialUpdate::Update(StdMesh* mesh) const
{
for(std::vector<StdSubMesh>::iterator iter = mesh->SubMeshes.begin(); iter != mesh->SubMeshes.end(); ++iter)
for(auto & SubMesh : mesh->SubMeshes)
{
std::map<const StdMeshMaterial*, StdMeshMaterial>::const_iterator mat_iter = Materials.find(iter->Material);
auto mat_iter = Materials.find(SubMesh.Material);
if(mat_iter != Materials.end())
{
const StdMeshMaterial* new_material = MaterialManager.GetMaterial(mat_iter->second.Name.getData());
if(new_material)
{
iter->Material = new_material;
SubMesh.Material = new_material;
}
else
{
@ -44,7 +44,7 @@ void StdMeshMaterialUpdate::Update(StdMesh* mesh) const
// going - next time the scenario will be started the mesh will fail
// to load because the material cannot be found.
MaterialManager.Materials[mat_iter->second.Name] = mat_iter->second; // TODO: could be moved
iter->Material = MaterialManager.GetMaterial(mat_iter->second.Name.getData());
SubMesh.Material = MaterialManager.GetMaterial(mat_iter->second.Name.getData());
}
}
}
@ -70,8 +70,8 @@ void StdMeshMaterialUpdate::Update(StdMeshInstance* instance) const
void StdMeshMaterialUpdate::Cancel() const
{
// Reset all materials in manager
for(std::map<const StdMeshMaterial*, StdMeshMaterial>::const_iterator iter = Materials.begin(); iter != Materials.end(); ++iter)
MaterialManager.Materials[iter->second.Name] = iter->second; // TODO: could be moved
for(const auto & Material : Materials)
MaterialManager.Materials[Material.second.Name] = Material.second; // TODO: could be moved
}
void StdMeshMaterialUpdate::Add(const StdMeshMaterial* material)
@ -96,8 +96,8 @@ void StdMeshUpdate::Update(StdMeshInstance* instance, const StdMesh& new_mesh) c
instance->BoneTransforms = std::vector<StdMeshMatrix>(new_mesh.GetSkeleton().GetNumBones(), StdMeshMatrix::Identity());
instance->BoneTransformsDirty = true;
for (unsigned int i = 0; i < instance->SubMeshInstances.size(); ++i)
delete instance->SubMeshInstances[i];
for (auto & SubMeshInstance : instance->SubMeshInstances)
delete SubMeshInstance;
instance->SubMeshInstances.resize(new_mesh.GetNumSubMeshes());
for (unsigned int i = 0; i < instance->SubMeshInstances.size(); ++i)
{
@ -139,8 +139,8 @@ void StdMeshUpdate::Update(StdMeshInstance* instance, const StdMesh& new_mesh) c
}
}
for(unsigned int i = 0; i < Removal.size(); ++i)
instance->DetachMesh(Removal[i]);
for(unsigned int i : Removal)
instance->DetachMesh(i);
// Update custom nodes in the animation tree. Leaf nodes which refer to an animation that
// does not exist anymore are removed.
@ -197,9 +197,9 @@ StdMeshAnimationUpdate::StdMeshAnimationUpdate(const StdMeshSkeletonLoader& skel
for(StdMeshSkeletonLoader::skeleton_iterator iter = skeleton_loader.skeletons_begin(); iter != skeleton_loader.skeletons_end(); ++iter)
{
const StdMeshSkeleton& skeleton = *iter->second;
for (std::map<StdCopyStrBuf, StdMeshAnimation>::const_iterator iter = skeleton.Animations.begin(); iter != skeleton.Animations.end(); ++iter)
for (const auto & Animation : skeleton.Animations)
{
AnimationNames[&iter->second] = iter->first;
AnimationNames[&Animation.second] = Animation.first;
}
}
}

Some files were not shown because too many files have changed in this diff Show More