From 9afe83e68e4a6881f6159ec6478b0d3bd0d7ef5b Mon Sep 17 00:00:00 2001 From: Geoffray Levasseur Date: Tue, 3 Nov 2026 11:25:49 +0100 Subject: [PATCH] added clienttools and diplomacy --- CMakeLists.txt | 4 + game/localplayer/ClientTools.cpp | 637 +++++++++++++++++++++++++++++++ game/localplayer/ClientTools.h | 106 +++++ game/localplayer/Diplomacy.cpp | 240 ++++++++++++ game/localplayer/Diplomacy.h | 46 +++ game/localplayer/Tribes.cpp | 38 +- 6 files changed, 1065 insertions(+), 6 deletions(-) create mode 100644 game/localplayer/ClientTools.cpp create mode 100644 game/localplayer/ClientTools.h create mode 100644 game/localplayer/Diplomacy.cpp create mode 100644 game/localplayer/Diplomacy.h diff --git a/CMakeLists.txt b/CMakeLists.txt index bcc10e5..46b779b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -117,6 +117,10 @@ set(PROJECT_SOURCES game/Messg.ui game/localplayer/KeyBindings.cpp game/localplayer/KeyBindings.h + game/localplayer/ClientTools.cpp + game/localplayer/ClientTools.h + game/localplayer/Diplomacy.cpp + game/localplayer/Diplomacy.h game/localplayer/Tribes.cpp game/localplayer/Tribes.h ${TS_FILES} diff --git a/game/localplayer/ClientTools.cpp b/game/localplayer/ClientTools.cpp new file mode 100644 index 0000000..db05182 --- /dev/null +++ b/game/localplayer/ClientTools.cpp @@ -0,0 +1,637 @@ +// This file is part of c-evo-evo. +// +// This software is governed by the CeCILL license under French law and +// abiding by the rules of distribution of free software. You can use, +// modify and/or redistribute the software under the terms of the CeCILL +// license as circulated by CEA, CNRS and INRIA at the following URL +// "http://www.cecill.info". +// +// As a counterpart to the access to the source code and rights to copy, +// modify and redistribute granted by the license, users are provided only +// with a limited warranty and the software's author, the holder of the +// economic rights, and the successive licensors have only limited +// liability. +// +// In this respect, the user's attention is drawn to the risks associated +// with loading, using, modifying and/or developing or reproducing the +// software by the user in light of its specific status of free software, +// that may mean that it is complicated to manipulate, and that also +// therefore means that it is reserved for developers and experienced +// professionals having in-depth computer knowledge. Users are therefore +// encouraged to load and test the software's suitability as regards their +// requirements in conditions enabling the security of their systems and/or +// data to be ensured and, more generally, to use and operate it in the +// same conditions as regards security. +// +// The fact that you are presently reading this means that you have had +// knowledge of the CeCILL license and that you accept its terms. + +#include "ClientTools.h" + +#include +#include + +namespace Cevo { +namespace ClientTools { + +TServerCall server = nullptr; +TNewGameData g{}; +int me = 0; +TPlayerContext *myRO = nullptr; +std::uint32_t *myMap = nullptr; +TUn *myUn = nullptr; +TCity *myCity = nullptr; +TModel *myModel = nullptr; +std::array advValue{}; + +namespace { + +std::array cityNeedsOptimize{}; + +void markPreqs(int i, std::array &known) +{ + if (known[static_cast(i)] == 0) { + known[static_cast(i)] = 1; + if (i != adScience && i != adMassProduction) { + if (AdvPreq[i][0] >= 0) + markPreqs(AdvPreq[i][0], known); + if (AdvPreq[i][1] >= 0) + markPreqs(AdvPreq[i][1], known); + } + } +} + +void calculateAdvValues() +{ + advValue.fill(0); + for (int i = 0; i < nAdv; ++i) { + std::array known{}; + markPreqs(i, known); + int sum = 0; + for (int j = 0; j < nAdv; ++j) + if (known[static_cast(j)] > 0) + ++sum; + advValue[static_cast(i)] = sum; + if (IsFutureTech(i)) + advValue[static_cast(i)] += 3000; + else if (known[static_cast(adMassProduction)] > 0) + advValue[static_cast(i)] += 2000; + else if (known[static_cast(adScience)] > 0) + advValue[static_cast(i)] += 1000; + } +} + +bool markCitiesAround(int loc, int cixExcept) +{ + bool result = false; + for (int cix = 0; cix < myRO->nCity; ++cix) { + if (cix != cixExcept && myCity[cix].Loc >= 0 && (myCity[cix].Flags & chCaptured) == 0 && + distance(myCity[cix].Loc, loc) <= 5) { + cityNeedsOptimize[static_cast(cix)] = true; + result = true; + } + } + return result; +} + +void optimizeCities(bool checkOnly) +{ + bool done; + do { + done = true; + for (int cix = 0; cix < myRO->nCity; ++cix) { + if (!cityNeedsOptimize[static_cast(cix)]) + continue; + const int optiType = (myCity[cix].Status >> 4) & 0x0F; + if (optiType != 0) { + TCityTileAdviceData advice{}; + // optiType should only ever be 0..nOfferedResourceWeights-1 + // in practice; guard against an out-of-bounds read if not. + advice.ResourceWeights = + optiType < nOfferedResourceWeights ? OfferedResourceWeights[optiType] : rwOff; + server(sGetCityTileAdvice, me, cix, &advice); + if (advice.Tiles != myCity[cix].Tiles && !checkOnly) { + for (int fix = 1; fix <= 26; ++fix) { + if ((myCity[cix].Tiles & ~advice.Tiles & (1u << fix)) != 0) { + const int dy = (fix >> 2) - 3; + const int dx = (((fix & 3) << 1) - 3) + ((dy + 3) & 1); + const int loc1 = dLoc(myCity[cix].Loc, dx, dy); + if (markCitiesAround(loc1, cix)) { + done = false; + break; + } + } + } + server(sSetCityTiles, me, cix, &advice.Tiles); + } + // else CheckOnly: original leaves this branch empty (its + // assert was already commented out upstream). + } + cityNeedsOptimize[static_cast(cix)] = false; + } + } while (!done); +} + +} // namespace + +void init() +{ + Q_ASSERT(nImp < 128); + calculateAdvValues(); +} + +int dLoc(int loc, int dx, int dy) +{ + const int y0 = (loc + g.lx * 1024) / g.lx - 1024; + return (loc + ((dx + (y0 & 1) + g.lx * 1024) >> 1)) % g.lx + g.lx * (y0 + dy); +} + +int distance(int loc0, int loc1) +{ + loc0 += g.lx * 1024; + loc1 += g.lx * 1024; + const int dx = std::abs(((loc1 % g.lx * 2 + (loc1 / g.lx & 1)) - (loc0 % g.lx * 2 + (loc0 / g.lx & 1)) + + 3 * g.lx) % + (2 * g.lx) - + g.lx); + const int dy = std::abs(loc1 / g.lx - loc0 / g.lx); + return dx + dy + (std::abs(dx - dy) >> 1); +} + +bool unrestAtLoc(int uix, int loc) +{ + bool result = false; + const TModel &model = myModel[myUn[uix].mix]; + if ((model.Flags & mdCivil) == 0) { + switch (myRO->Government) { + case gRepublic: + case gFuture: + result = (*myRO->Territory)[loc] >= 0 && (*myRO->Territory)[loc] != me && + myRO->Treaty[(*myRO->Territory)[loc]] < trAlliance; + break; + case gDemocracy: + result = (*myRO->Territory)[loc] < 0 || + ((*myRO->Territory)[loc] != me && myRO->Treaty[(*myRO->Territory)[loc]] < trAlliance); + break; + default: + break; + } + } + if (model.Cap[mcSeaTrans] + model.Cap[mcAirTrans] + model.Cap[mcCarrier] > 0) { + for (int uix1 = 0; uix1 < myRO->nUn; ++uix1) + if (myUn[uix1].Loc >= 0 && myUn[uix1].Master == uix) + result = result || unrestAtLoc(uix1, loc); + } + return result; +} + +int getMoveAdvice(int uix, int toLoc, TMoveAdviceData &moveAdviceData) +{ + int minEndHealth = myModel[myUn[uix].mix].Domain == dGround ? 100 : 1; + for (;;) { + if (myUn[uix].Health >= minEndHealth) { + moveAdviceData.ToLoc = toLoc; + moveAdviceData.MoreTurns = 999; + moveAdviceData.MaxHostile_MovementLeft = myUn[uix].Health - minEndHealth; + const int result = server(sGetMoveAdvice, me, uix, &moveAdviceData); + if (minEndHealth <= 1 || result != eNoWay) + return result; + } + switch (minEndHealth) { + case 100: minEndHealth = 50; break; + case 50: minEndHealth = 25; break; + case 25: minEndHealth = 12; break; + default: minEndHealth = 1; break; + } + } +} + +int colorOfHealth(int health) +{ + int green = 400 * health / 100; + if (green > 200) + green = 200; + int red = 510 * (100 - health) / 100; + if (red > 255) + red = 255; + return (green << 8) + red; +} + +bool isMultiPlayerGame() +{ + for (int p1 = 1; p1 < nPl; ++p1) + if (g.RO[p1]) + return true; + return false; +} + +void itsMeAgain(int p) +{ + if (g.RO[p]) + myRO = g.RO[p]; + else if (g.SuperVisorRO[p]) + myRO = g.SuperVisorRO[p]; + else + return; + me = p; + myMap = *myRO->Map; + myUn = *myRO->Un; + myCity = *myRO->City; + myModel = *myRO->Model; +} + +int getAge(int p) +{ + int result = 0; + if (p == me) { + for (int i = 1; i <= 3; ++i) + if (myRO->Tech[AgePreq[i]] >= tsApplicable) + result = i; + } else { + for (int i = 1; i <= 3; ++i) + if (myRO->EnemyReport[p]->Tech[AgePreq[i]] >= tsApplicable) + result = i; + } + return result; +} + +bool isCivilReportNew(int enemy) +{ + Q_ASSERT(enemy != me); + const int i = myRO->EnemyReport[enemy]->TurnOfCivilReport; + return i == myRO->Turn || (i == myRO->Turn - 1 && enemy > me); +} + +bool isMilReportNew(int enemy) +{ + Q_ASSERT(enemy != me); + const int i = myRO->EnemyReport[enemy]->TurnOfMilReport; + return i == myRO->Turn || (i == myRO->Turn - 1 && enemy > me); +} + +int cutCityFoodSurplus(int foodSurplus, bool isCityAlive, int gov, int size) +{ + int result = foodSurplus; + if (!isCityAlive || (result > 0 && (gov == gFuture || (size >= NeedAqueductSize && result < 2)))) + result = 0; // no growth + return result; +} + +int cityTaxBalance(int cix, const TCityReportNew &cityReport) +{ + int result = 0; + if (cityReport.HappinessBalance >= 0 && (myCity[cix].Flags & chCaptured) == 0) { + result += cityReport.Tax; + if ((myCity[cix].Project & (cpImp + cpIndex)) == cpImp + imTrGoods && cityReport.Production > 0) + result += cityReport.Production; + if (((myRO->Government == gFuture) || + (myCity[cix].Size >= NeedAqueductSize && cityReport.FoodSurplus < 2)) && + cityReport.FoodSurplus > 0) + result += cityReport.FoodSurplus; + } + for (int i = nWonder; i < nImp; ++i) + if (myCity[cix].Built[i] > 0) + result -= Imp[i].Maint; + return result; +} + +void sumCities(int &taxSum, int &scienceSum) +{ + taxSum = myRO->OracleIncome; + scienceSum = 0; + if (myRO->Government == gAnarchy) + return; + for (int cix = 0; cix < myRO->nCity; ++cix) { + if (myCity[cix].Loc >= 0) { + TCityReportNew cityReport{}; + cityReport.HypoTiles = -1; + cityReport.HypoTaxRate = -1; + cityReport.HypoLuxuryRate = -1; + server(sGetCityReportNew, me, cix, &cityReport); + if (cityReport.HappinessBalance >= 0 && (myCity[cix].Flags & chCaptured) == 0) + scienceSum += cityReport.Science; + taxSum += cityTaxBalance(cix, cityReport); + } + } +} + +bool jobTest(int uix, int job, JobResultSet ignoreResults) +{ + const int test = server(sStartJob + (job << 4) - sExecute, me, uix, nullptr); + if (test >= rExecuted) + return true; + return test >= 0 && test < 40 && (ignoreResults & (JobResultSet(1) << test)) != 0; +} + +void getUnitInfo(int loc, int &uix, TUnitInfo &unitInfo) +{ + if ((myMap[loc] & fOwned) != 0) { + server(sGetDefender, me, loc, &uix); + int cnt = 0; + for (int i = 0; i < myRO->nUn; ++i) + if (myUn[i].Loc == loc) + ++cnt; + MakeUnitInfo(me, myUn[uix], unitInfo); + if (cnt > 1) + unitInfo.Flags |= unMulti; + } else { + uix = myRO->nEnemyUn - 1; + while (uix >= 0 && (*myRO->EnemyUn)[uix].Loc != loc) + --uix; + unitInfo = (*myRO->EnemyUn)[uix]; + } +} + +void getCityInfo(int loc, int &cix, TCityInfo &cityInfo) +{ + if ((myMap[loc] & fOwned) != 0) { + cityInfo.Loc = loc; + cix = myRO->nCity - 1; + while (cix >= 0 && myCity[cix].Loc != loc) + --cix; + cityInfo.Owner = static_cast(me); + cityInfo.ID = myCity[cix].ID; + cityInfo.Size = myCity[cix].Size; + cityInfo.Flags = 0; + if (myCity[cix].Built[imPalace] > 0) + cityInfo.Flags |= ciCapital; + if (myCity[cix].Built[imWalls] > 0 || (myMap[myCity[cix].Loc] & fGrWall) != 0) + cityInfo.Flags |= ciWalled; + if (myCity[cix].Built[imCoastalFort] > 0) + cityInfo.Flags |= ciCoastalFort; + if (myCity[cix].Built[imMissileBat] > 0) + cityInfo.Flags |= ciMissileBat; + if (myCity[cix].Built[imBunker] > 0) + cityInfo.Flags |= ciBunker; + if (myCity[cix].Built[imSpacePort] > 0) + cityInfo.Flags |= ciSpacePort; + } else { + cix = myRO->nEnemyCity - 1; + while (cix >= 0 && (*myRO->EnemyCity)[cix].Loc != loc) + --cix; + cityInfo = (*myRO->EnemyCity)[cix]; + } +} + +bool unitExhausted(int uix) +{ + bool result = true; + if (myUn[uix].Movement > 0 || myRO->Wonder[woShinkansen].EffectiveOwner == me) { + if (myUn[uix].Movement >= 100 || + (myModel[myUn[uix].mix].Kind == mkCaravan && (myMap[myUn[uix].Loc] & fCity) != 0)) { + result = false; + } else { + for (int dx = -2; dx <= 2 && result; ++dx) { + for (int dy = -2; dy <= 2; ++dy) { + if (std::abs(dx) + std::abs(dy) == 2) { + const int cmd = sMoveUnit - sExecute + ((dx & 7) << 4) + ((dy & 7) << 7); + if (server(cmd, me, uix, nullptr) >= rExecuted) { + result = false; + break; + } + } + } + } + } + } + return result; +} + +int modelHash(const TModelInfo &modelInfo) +{ + if (modelInfo.Kind > mkEnemyDeveloped) + return static_cast(0xC0000000u + static_cast(modelInfo.Speed / 50) + + (static_cast(modelInfo.Kind) << 8)); + + std::uint32_t featureCode = 0; + for (int i = mcFirstNonCap; i < nFeature; ++i) { + if (((1u << modelInfo.Domain) & static_cast(Feature[i].Domains)) != 0) { + featureCode *= 2; + // Ported verbatim: "1 shl (i - mcFirstNonCap) <> 0" never + // actually consults ModelInfo.Cap and is always true here, so + // this unconditionally increments - kept as in the original. + if ((1u << (i - mcFirstNonCap)) != 0) + ++featureCode; + } + } + + std::uint32_t hash1 = 0; + std::uint32_t hash2 = 0; + switch (modelInfo.Domain) { + case dGround: + hash1 = static_cast((static_cast(modelInfo.Attack) * 2273 + modelInfo.Defense) * 9 + + (static_cast(modelInfo.Speed) - 150) / 50); + hash2 = featureCode * 1611 + modelInfo.Cost; + break; + case dSea: + hash1 = static_cast( + ((static_cast(modelInfo.Attack) * 6097 + modelInfo.Defense) * 5 + + (static_cast(modelInfo.Speed) - 350) / 100) * + 2); + if (modelInfo.Weight >= 6) + ++hash1; + hash2 = (((static_cast(modelInfo.TTrans) * 17 + modelInfo.ATrans_Fuel) << 9) + featureCode) * + 4381 + + modelInfo.Cost; + break; + case dAir: + hash1 = ((static_cast(modelInfo.Attack) * 1605 + modelInfo.Defense) << 5) + featureCode; + hash2 = ((static_cast(modelInfo.Bombs) * 7 + modelInfo.ATrans_Fuel) * 4 + modelInfo.TTrans) * + 2089 + + modelInfo.Cost; + break; + default: + break; + } + + std::uint32_t hash2r = 0; + for (int i = 0; i < 8; ++i) { + hash2r *= 13; + const std::uint32_t d = hash2 / 13; + hash2r += hash2 - d * 13; + hash2 = d; + } + const std::uint32_t combined = ((static_cast(modelInfo.Domain) << 30) + hash1) ^ hash2r; + return static_cast(combined); +} + +int processEnhancement(int uix, const TEnhancementJobs &jobs) +{ + std::uint32_t done = 0; + const int tile = static_cast(myMap[myUn[uix].Loc]); + if (tile & fRoad) done |= 1u << jRoad; + if (tile & fRR) done |= 1u << jRR; + if ((tile & fTerImp) == tiIrrigation || (tile & fTerImp) == tiFarm) done |= 1u << jIrr; + if ((tile & fTerImp) == tiFarm) done |= 1u << jFarm; + if ((tile & fTerImp) == tiMine) done |= 1u << jMine; + if ((tile & fPoll) == 0) done |= 1u << jPoll; + + int result = myUn[uix].Job == jNone ? eJobDone : eOK; + while (result != eOK && result != eDied) { + int stage = -1; + int nextJob; + do { + nextJob = stage == -1 ? jPoll : jobs[tile & fTerrain][stage]; + if (nextJob == jNone || (done & (1u << nextJob)) == 0) + break; + ++stage; + } while (stage != 5); + + if (stage == 5 || nextJob == jNone) { + result = eJobDone; + break; + } + result = server(sStartJob + (nextJob << 4), me, uix, nullptr); + done |= 1u << nextJob; + } + return result; +} + +bool autoBuild(int cix, const TImpOrder &impOrder) +{ + bool result = false; + if ((myCity[cix].Project & (cpImp + cpIndex)) == cpImp + imTrGoods || (myCity[cix].Flags & chProduction) != 0) { + int i = 0; + for (;;) { + while (impOrder[static_cast(i)] >= 0 && + myCity[cix].Built[impOrder[static_cast(i)]] > 0) + ++i; + if (impOrder[static_cast(i)] < 0) + break; + Q_ASSERT(i < nImp); + int newProject = cpImp + impOrder[static_cast(i)]; + if (server(sSetCityProject, me, cix, &newProject) >= rExecuted) { + result = true; + cityOptimizer_CityChange(cix); + break; + } + ++i; + } + } + return result; +} + +void debugMessage(int level, const QString &text) +{ + const QByteArray utf8 = text.toUtf8(); + server(sMessage, me, level, const_cast(utf8.constData())); +} + +void cityOptimizer_BeginOfTurn() +{ + // Ported verbatim: the original only clears nCity-1 of nCmax entries + // here (likely meant SizeOf(CityNeedsOptimize)); clamped below so a + // stray huge/negative nCity can't turn this into an OOB write. + const int clearCount = std::max(0, myRO->nCity - 1); + std::fill_n(cityNeedsOptimize.begin(), + std::min(static_cast(clearCount), cityNeedsOptimize.size()), false); + if (myRO->Government != gAnarchy) { + for (int cix = 0; cix < myRO->nCity; ++cix) + if (myCity[cix].Loc >= 0 && (myCity[cix].Flags & chCaptured) == 0) + cityNeedsOptimize[static_cast(cix)] = true; + optimizeCities(false); + } +} + +void cityOptimizer_CityChange(int cix) +{ + if (myRO->Government != gAnarchy && cix != -1 && (myCity[cix].Flags & chCaptured) == 0) { + cityNeedsOptimize[static_cast(cix)] = true; + optimizeCities(false); + } +} + +void cityOptimizer_TileBecomesAvailable(int loc) +{ + if (myRO->Government != gAnarchy && markCitiesAround(loc, -1)) + optimizeCities(false); +} + +void cityOptimizer_ReleaseCityTiles(int cix, int releasedTiles) +{ + if (myRO->Government != gAnarchy && releasedTiles != 0) { + bool done = true; + for (int fix = 1; fix <= 26; ++fix) { + if ((releasedTiles & (1 << fix)) != 0) { + const int dy = (fix >> 2) - 3; + const int dx = (((fix & 3) << 1) - 3) + ((dy + 3) & 1); + const int loc1 = dLoc(myCity[cix].Loc, dx, dy); + if (markCitiesAround(loc1, cix)) { + done = false; + break; + } + } + } + if (!done) + optimizeCities(false); + } +} + +void cityOptimizer_BeforeRemoveUnit(int uix) +{ + if (myRO->Government != gAnarchy) { + if (myUn[uix].Home >= 0) + cityNeedsOptimize[static_cast(myUn[uix].Home)] = true; + for (int uix1 = 0; uix1 < myRO->nUn; ++uix1) + if (myUn[uix1].Loc >= 0 && myUn[uix1].Master == uix && myUn[uix1].Home >= 0) + cityNeedsOptimize[static_cast(myUn[uix1].Home)] = true; + } +} + +void cityOptimizer_AfterRemoveUnit() +{ + if (myRO->Government != gAnarchy) + optimizeCities(false); +} + +void cityOptimizer_EndOfTurn() +{ +#ifndef NDEBUG + // Matches the original's {$IFOPT O-} (debug/non-optimized builds only): + // a consistency check, not functionally required. + if (myRO->Government != gAnarchy) { + const int clearCount = std::max(0, myRO->nCity - 1); + std::fill_n(cityNeedsOptimize.begin(), + std::min(static_cast(clearCount), cityNeedsOptimize.size()), false); + for (int cix = 0; cix < myRO->nCity; ++cix) + if (myCity[cix].Loc >= 0 && (myCity[cix].Flags & chCaptured) == 0) + cityNeedsOptimize[static_cast(cix)] = true; + optimizeCities(true); + } +#endif +} + +TCity *getMyCityByLoc(int loc) +{ + int i = myRO->nCity - 1; + while (i >= 0 && myCity[i].Loc != loc) + --i; + return i >= 0 ? &myCity[i] : nullptr; +} + +TCityInfo *getEnemyCityByLoc(int loc) +{ + int i = myRO->nEnemyCity - 1; + while (i >= 0 && (*myRO->EnemyCity)[i].Loc != loc) + --i; + return i >= 0 ? &(*myRO->EnemyCity)[i] : nullptr; +} + +TUn *getMyUnitByLoc(int loc) +{ + int i = myRO->nUn - 1; + while (i >= 0 && myUn[i].Loc != loc) + --i; + return i >= 0 ? &myUn[i] : nullptr; +} + +TUnitInfo *getEnemyUnitByLoc(int loc) +{ + int i = myRO->nEnemyUn - 1; + while (i >= 0 && (*myRO->EnemyUn)[i].Loc != loc) + --i; + return i >= 0 ? &(*myRO->EnemyUn)[i] : nullptr; +} + +} // namespace ClientTools +} // namespace Cevo diff --git a/game/localplayer/ClientTools.h b/game/localplayer/ClientTools.h new file mode 100644 index 0000000..df6115d --- /dev/null +++ b/game/localplayer/ClientTools.h @@ -0,0 +1,106 @@ +// This file is part of c-evo-evo. +// +// This software is governed by the CeCILL license under French law and +// abiding by the rules of distribution of free software. You can use, +// modify and/or redistribute the software under the terms of the CeCILL +// license as circulated by CEA, CNRS and INRIA at the following URL +// "http://www.cecill.info". +// +// As a counterpart to the access to the source code and rights to copy, +// modify and redistribute granted by the license, users are provided only +// with a limited warranty and the software's author, the holder of the +// economic rights, and the successive licensors have only limited +// liability. +// +// In this respect, the user's attention is drawn to the risks associated +// with loading, using, modifying and/or developing or reproducing the +// software by the user in light of its specific status of free software, +// that may mean that it is complicated to manipulate, and that also +// therefore means that it is reserved for developers and experienced +// professionals having in-depth computer knowledge. Users are therefore +// encouraged to load and test the software's suitability as regards their +// requirements in conditions enabling the security of their systems and/or +// data to be ensured and, more generally, to use and operate it in the +// same conditions as regards security. +// +// The fact that you are presently reading this means that you have had +// knowledge of the CeCILL license and that you accept its terms. + +#pragma once + +#include "Cevo/Protocol.h" + +#include + +#include +#include + +namespace Cevo { +namespace ClientTools { + +constexpr int nOfferedResourceWeights = 6; +constexpr std::uint32_t OfferedResourceWeights[nOfferedResourceWeights] = { + rwOff, rwMaxScience, rwForceScience, rwMaxGrowth, rwForceProd, rwMaxProd, +}; + +using TImpOrder = std::array; +using TEnhancementJobs = std::uint8_t[12][8]; +// Pascal's `set of 0..39`; bit i set means "treat Server() result code i as +// success too" (used only for the small 0..39 sub-codes a failed job-start +// call can return, never for the >=rExecuted big result codes). +using JobResultSet = std::uint64_t; + +// Module-level state (Pascal's unit-level `var` section). `server`/`g` are +// set up once by whatever (not yet ported) code starts a local-player game; +// itsMeAgain() then refreshes me/myRO/myMap/myUn/myCity/myModel from `g`. +extern TServerCall server; +extern TNewGameData g; +extern int me; +extern TPlayerContext *myRO; +extern std::uint32_t *myMap; // ro->Map, indexable as myMap[loc] +extern TUn *myUn; // ro->Un, indexable as myUn[uix] +extern TCity *myCity; // ro->City, indexable as myCity[cix] +extern TModel *myModel; // ro->Model, indexable as myModel[mix] +extern std::array advValue; + +// Computes advValue[] from the Advance prerequisite graph (Pascal's +// `initialization` section); call once at startup. +void init(); + +int dLoc(int loc, int dx, int dy); +int distance(int loc0, int loc1); +bool unrestAtLoc(int uix, int loc); +int getMoveAdvice(int uix, int toLoc, TMoveAdviceData &moveAdviceData); +int colorOfHealth(int health); +bool isMultiPlayerGame(); +void itsMeAgain(int p); +int getAge(int p); +bool isCivilReportNew(int enemy); +bool isMilReportNew(int enemy); +int cutCityFoodSurplus(int foodSurplus, bool isCityAlive, int gov, int size); +int cityTaxBalance(int cix, const TCityReportNew &cityReport); +void sumCities(int &taxSum, int &scienceSum); +bool jobTest(int uix, int job, JobResultSet ignoreResults = 0); +void getUnitInfo(int loc, int &uix, TUnitInfo &unitInfo); +void getCityInfo(int loc, int &cix, TCityInfo &cityInfo); +bool unitExhausted(int uix); +int modelHash(const TModelInfo &modelInfo); +int processEnhancement(int uix, const TEnhancementJobs &jobs); +bool autoBuild(int cix, const TImpOrder &impOrder); +void debugMessage(int level, const QString &text); + +void cityOptimizer_BeginOfTurn(); +void cityOptimizer_CityChange(int cix); +void cityOptimizer_TileBecomesAvailable(int loc); +void cityOptimizer_ReleaseCityTiles(int cix, int releasedTiles); +void cityOptimizer_BeforeRemoveUnit(int uix); +void cityOptimizer_AfterRemoveUnit(); +void cityOptimizer_EndOfTurn(); + +TCity *getMyCityByLoc(int loc); +TCityInfo *getEnemyCityByLoc(int loc); +TUn *getMyUnitByLoc(int loc); +TUnitInfo *getEnemyUnitByLoc(int loc); + +} // namespace ClientTools +} // namespace Cevo diff --git a/game/localplayer/Diplomacy.cpp b/game/localplayer/Diplomacy.cpp new file mode 100644 index 0000000..da789d6 --- /dev/null +++ b/game/localplayer/Diplomacy.cpp @@ -0,0 +1,240 @@ +// This file is part of c-evo-evo. +// +// This software is governed by the CeCILL license under French law and +// abiding by the rules of distribution of free software. You can use, +// modify and/or redistribute the software under the terms of the CeCILL +// license as circulated by CEA, CNRS and INRIA at the following URL +// "http://www.cecill.info". +// +// As a counterpart to the access to the source code and rights to copy, +// modify and redistribute granted by the license, users are provided only +// with a limited warranty and the software's author, the holder of the +// economic rights, and the successive licensors have only limited +// liability. +// +// In this respect, the user's attention is drawn to the risks associated +// with loading, using, modifying and/or developing or reproducing the +// software by the user in light of its specific status of free software, +// that may mean that it is complicated to manipulate, and that also +// therefore means that it is reserved for developers and experienced +// professionals having in-depth computer knowledge. Users are therefore +// encouraged to load and test the software's suitability as regards their +// requirements in conditions enabling the security of their systems and/or +// data to be ensured and, more generally, to use and operate it in the +// same conditions as regards security. +// +// The fact that you are presently reading this means that you have had +// knowledge of the CeCILL license and that you accept its terms. + +#include "Diplomacy.h" + +#include "Tribes.h" + +#include + +namespace Cevo { +namespace Diplomacy { + +namespace { + +// Phrases/Phrases2 (StringTables.pas) aren't ported; disclosed +// plain-English placeholders for the (non tribe-specific) keys this file +// looks up directly via Phrases[...]. +QString phrase(const QString &key) +{ + static const QHash table = { + {QStringLiteral("FRCANCELTREATY_PEACE"), QStringLiteral("I hereby cancel our peace treaty.")}, + {QStringLiteral("FRCANCELTREATY_FRIENDLY"), QStringLiteral("I hereby end our friendly relations.")}, + {QStringLiteral("FRCANCELTREATY_ALLIANCE"), QStringLiteral("I hereby cancel our alliance.")}, + {QStringLiteral("FRNOTICE"), QStringLiteral("I have a notice for you.")}, + {QStringLiteral("FRDONE"), QStringLiteral("That is all.")}, + {QStringLiteral("FRDELCHOICE"), QStringLiteral("in exchange for %1, you may choose what we deliver")}, + {QStringLiteral("FRCOSTCHOICE"), QStringLiteral("we offer %1, you may choose the price")}, + {QStringLiteral("FROFFER"), QStringLiteral("we offer %1 in exchange for %2")}, + {QStringLiteral("PRICE_CHOOSE"), QStringLiteral("something of our choosing")}, + {QStringLiteral("PRICE_SHIPCOMP"), QStringLiteral("%1 spaceship component(s)")}, + {QStringLiteral("PRICE_SHIPPOW"), QStringLiteral("%1 spaceship power module(s)")}, + {QStringLiteral("PRICE_SHIPHAB"), QStringLiteral("%1 spaceship habitation module(s)")}, + {QStringLiteral("PRICE_TRIBUTE"), QStringLiteral("a tribute of %1")}, + {QStringLiteral("PRICE_CONCAT"), QStringLiteral("%1, %2")}, + }; + const auto it = table.constFind(key); + return it != table.constEnd() ? it.value() : key; +} + +QString phraseTreaty(int treatyType) +{ + switch (treatyType) { + case trCeaseFire: return QStringLiteral("a cease-fire"); + case trPeace: return QStringLiteral("a peace treaty"); + case trFriendlyContact: return QStringLiteral("friendly relations"); + case trAlliance: return QStringLiteral("an alliance"); + default: return QStringLiteral("a treaty"); + } +} + +QString phraseAdvance(int advance) +{ + // Advance names (Rules.pas/StringTables.pas) aren't ported here. + return QStringLiteral("advance #%1").arg(advance); +} + +QString priceToString(int p, std::uint32_t price) +{ + Tribes::Tribe &tribe = *Tribes::tribe[static_cast(p)]; + switch (price & static_cast(opMask)) { + case opChoose: + return phrase(QStringLiteral("PRICE_CHOOSE")); + case opCivilReport: + return tribe.tPhrase(QStringLiteral("PRICE_CIVIL")); + case opMilReport: + return tribe.tPhrase(QStringLiteral("PRICE_MIL")); + case opMap: + return tribe.tPhrase(QStringLiteral("PRICE_MAP")); + case opTreaty: + return phraseTreaty(static_cast(price - opTreaty)); + case opShipParts: + switch ((price >> 16) & 0xFu) { + case 0: return phrase(QStringLiteral("PRICE_SHIPCOMP")).arg(price & 0xFFFFu); + case 1: return phrase(QStringLiteral("PRICE_SHIPPOW")).arg(price & 0xFFFFu); + case 2: return phrase(QStringLiteral("PRICE_SHIPHAB")).arg(price & 0xFFFFu); + default: return QString(); + } + case opMoney: + return QStringLiteral("%1%c").arg(price - opMoney); + case opTribute: + return phrase(QStringLiteral("PRICE_TRIBUTE")).arg(price - opTribute); + case opTech: + return phraseAdvance(static_cast(price - opTech)); + case opAllTech: + return tribe.tPhrase(QStringLiteral("PRICE_ALLTECH")); + case opModel: + return tribe.modelNameAt(static_cast(price - opModel)); + case opAllModel: + return tribe.tPhrase(QStringLiteral("PRICE_ALLMODEL")); + default: + return QString(); + } +} + +} // namespace + +QString dipCommandToString(int pSender, int pTarget, int treaty, int oppCommand, int command, const TOffer &oppOffer, + const TOffer &offer) +{ + Tribes::Tribe &sender = *Tribes::tribe[static_cast(pSender)]; + Tribes::Tribe &target = *Tribes::tribe[static_cast(pTarget)]; + + bool doIntro = oppCommand == scDipStart; + QString result; + + switch (command) { + case scDipCancelTreaty: + switch (treaty) { + case trPeace: result = phrase(QStringLiteral("FRCANCELTREATY_PEACE")); break; + case trFriendlyContact: result = phrase(QStringLiteral("FRCANCELTREATY_FRIENDLY")); break; + case trAlliance: result = phrase(QStringLiteral("FRCANCELTREATY_ALLIANCE")); break; + default: break; + } + doIntro = false; + break; + + case scDipNotice: + result = phrase(QStringLiteral("FRNOTICE")); + break; + + case scDipAccept: + if (oppOffer.nDeliver + oppOffer.nCost == 1 && (oppOffer.Price[0] & static_cast(opMask)) == opTreaty && + static_cast(oppOffer.Price[0] - opTreaty) > treaty) + result = target.tPhrase(QStringLiteral("FRACCEPTTREATY")); + else if (oppOffer.nDeliver == 0) + result = sender.tPhrase(QStringLiteral("FRACCEPTDEMAND_STRONG")); + else if (oppOffer.nCost == 0) + result = sender.tPhrase(QStringLiteral("FRACCEPTPRESENT")); + else + result = sender.tPhrase(QStringLiteral("FRACCEPTOFFER")); + break; + + case scDipBreak: + result = target.tPhrase(QStringLiteral("FRBREAK")); + doIntro = false; + break; + + case scDipOffer: { + if (oppCommand == scDipOffer && (oppOffer.nDeliver > 0 || oppOffer.nCost > 0) && + offer.nCost + offer.nDeliver <= 2) { + // Respond to the offer the other side just made before making our own. + if (oppOffer.nDeliver + oppOffer.nCost == 1 && + (oppOffer.Price[0] & static_cast(opMask)) == opTreaty && + static_cast(oppOffer.Price[0] - opTreaty) > treaty) + result = sender.tPhrase(QStringLiteral("FRNOTACCEPTTREATY")) + QLatin1Char('\\'); + else if (oppOffer.nDeliver == 0) + result = sender.tPhrase(QStringLiteral("FRNOTACCEPTDEMAND_STRONG")) + QLatin1Char('\\'); + else if (oppOffer.nCost == 0) + result = sender.tPhrase(QStringLiteral("FRNOTACCEPTPRESENT")) + QLatin1Char('\\'); + } + + QString sDeliver; + for (int i = 0; i < offer.nDeliver; ++i) { + const QString sAdd = priceToString(pSender, offer.Price[i]); + sDeliver = i == 0 ? sAdd : phrase(QStringLiteral("PRICE_CONCAT")).arg(sDeliver, sAdd); + } + QString sCost; + for (int i = 0; i < offer.nCost; ++i) { + const QString sAdd = priceToString(pTarget, offer.Price[offer.nDeliver + i]); + sCost = i == 0 ? sAdd : phrase(QStringLiteral("PRICE_CONCAT")).arg(sCost, sAdd); + } + + if (offer.nDeliver == 0 && offer.nCost == 0) { + if (oppCommand == scDipOffer && oppOffer.nDeliver == 0 && oppOffer.nCost == 0) { + result = target.tPhrase(QStringLiteral("FRBYE")); + } else { + if (result.isEmpty() && oppCommand == scDipOffer && (oppOffer.nDeliver > 0 || oppOffer.nCost > 0)) { + // The original also has two Phrases2-based "soft" variants + // here, unreachable without a StringTables.pas port. + result = sender.tPhrase(QStringLiteral("FRNOTACCEPTOFFER")) + QLatin1Char(' '); + } + result += phrase(QStringLiteral("FRDONE")); + doIntro = false; + } + } else if (offer.nDeliver + offer.nCost == 1 && + (offer.Price[0] & static_cast(opMask)) == opTreaty && + static_cast(offer.Price[0] - opTreaty) > treaty) { + switch (offer.Price[0] - opTreaty) { + case trPeace: result += target.tPhrase(QStringLiteral("FRPEACE")); break; + case trFriendlyContact: result += target.tPhrase(QStringLiteral("FRFRIENDLY")); break; + case trAlliance: result += target.tPhrase(QStringLiteral("FRALLIANCE")); break; + default: break; + } + } else if (offer.nDeliver == 0) { + // The original also has a Phrases2-based "soft" demand variant + // here, unreachable without a StringTables.pas port. + result += target.tPhrase(QStringLiteral("FRDEMAND_STRONG")).arg(sCost); + doIntro = false; + } else if (offer.nCost == 0) { + result += target.tPhrase(QStringLiteral("FRPRESENT")).arg(sDeliver); + } else if (offer.nDeliver == 1 && offer.Price[0] == opChoose) { + result += phrase(QStringLiteral("FRDELCHOICE")).arg(sCost); + } else if (offer.nCost == 1 && offer.Price[offer.nDeliver] == opChoose) { + result += phrase(QStringLiteral("FRCOSTCHOICE")).arg(sDeliver); + } else { + result += phrase(QStringLiteral("FROFFER")).arg(sDeliver, sCost); + } + break; + } + + default: + break; + } + + if (doIntro) { + if (treaty < trPeace) + result = sender.tPhrase(QStringLiteral("FRSTART_NOTREATY")) + QLatin1Char(' ') + result; + else + result = sender.tPhrase(QStringLiteral("FRSTART_PEACE")) + QLatin1Char(' ') + result; + } + return result; +} + +} // namespace Diplomacy +} // namespace Cevo diff --git a/game/localplayer/Diplomacy.h b/game/localplayer/Diplomacy.h new file mode 100644 index 0000000..dd797b9 --- /dev/null +++ b/game/localplayer/Diplomacy.h @@ -0,0 +1,46 @@ +// This file is part of c-evo-evo. +// +// This software is governed by the CeCILL license under French law and +// abiding by the rules of distribution of free software. You can use, +// modify and/or redistribute the software under the terms of the CeCILL +// license as circulated by CEA, CNRS and INRIA at the following URL +// "http://www.cecill.info". +// +// As a counterpart to the access to the source code and rights to copy, +// modify and redistribute granted by the license, users are provided only +// with a limited warranty and the software's author, the holder of the +// economic rights, and the successive licensors have only limited +// liability. +// +// In this respect, the user's attention is drawn to the risks associated +// with loading, using, modifying and/or developing or reproducing the +// software by the user in light of its specific status of free software, +// that may mean that it is complicated to manipulate, and that also +// therefore means that it is reserved for developers and experienced +// professionals having in-depth computer knowledge. Users are therefore +// encouraged to load and test the software's suitability as regards their +// requirements in conditions enabling the security of their systems and/or +// data to be ensured and, more generally, to use and operate it in the +// same conditions as regards security. +// +// The fact that you are presently reading this means that you have had +// knowledge of the CeCILL license and that you accept its terms. + +#pragma once + +#include "Cevo/Protocol.h" + +#include + +namespace Cevo { +namespace Diplomacy { + +// Builds the negotiation dialog line for a given Command (and, if any, the +// OppCommand the other side just sent). Phrases/Phrases2 (StringTables.pas) +// aren't ported, so the returned text uses disclosed plain-English +// placeholders instead of the real localized strings. +QString dipCommandToString(int pSender, int pTarget, int treaty, int oppCommand, int command, const TOffer &oppOffer, + const TOffer &offer); + +} // namespace Diplomacy +} // namespace Cevo diff --git a/game/localplayer/Tribes.cpp b/game/localplayer/Tribes.cpp index 5daef94..6fb4c99 100644 --- a/game/localplayer/Tribes.cpp +++ b/game/localplayer/Tribes.cpp @@ -33,6 +33,7 @@ #include #include +#include #include #include @@ -357,12 +358,37 @@ QString Tribe::tString(QString templateText) const QString Tribe::tPhrase(const QString &item) const { - // Phrases/Phrases2 (StringTables.pas) aren't ported. "GENCITY" is the - // only phrase this file ever looks up (a generated-city-name fallback - // once a tribe's scripted name list runs out) - fall back to a plain - // English template rather than failing on an unrecognized key. - Q_UNUSED(item); - return tString(QStringLiteral("City %1")); + // Phrases/Phrases2 (StringTables.pas) aren't ported; these are + // disclosed plain-English placeholders for the keys looked up via + // Tribe::TPhrase() across this file and Diplomacy.pas, run through + // TString() for the tribe's own #x name-template substitution. + static const QHash table = { + {QStringLiteral("GENCITY"), QStringLiteral("City %1")}, + {QStringLiteral("PRICE_CIVIL"), QStringLiteral("our civil report")}, + {QStringLiteral("PRICE_MIL"), QStringLiteral("our military report")}, + {QStringLiteral("PRICE_MAP"), QStringLiteral("our map")}, + {QStringLiteral("PRICE_ALLTECH"), QStringLiteral("all our advances")}, + {QStringLiteral("PRICE_ALLMODEL"), QStringLiteral("all our unit designs")}, + {QStringLiteral("FRACCEPTTREATY"), QStringLiteral("We accept your treaty proposal.")}, + {QStringLiteral("FRACCEPTDEMAND_STRONG"), QStringLiteral("As you wish.")}, + {QStringLiteral("FRACCEPTPRESENT"), QStringLiteral("We gladly accept your gift.")}, + {QStringLiteral("FRACCEPTOFFER"), QStringLiteral("We accept your offer.")}, + {QStringLiteral("FRBREAK"), QStringLiteral("We break off negotiations.")}, + {QStringLiteral("FRNOTACCEPTTREATY"), QStringLiteral("We do not accept this treaty.")}, + {QStringLiteral("FRNOTACCEPTDEMAND_STRONG"), QStringLiteral("We refuse your demand.")}, + {QStringLiteral("FRNOTACCEPTPRESENT"), QStringLiteral("We decline your gift.")}, + {QStringLiteral("FRBYE"), QStringLiteral("Farewell.")}, + {QStringLiteral("FRNOTACCEPTOFFER"), QStringLiteral("We do not accept this offer.")}, + {QStringLiteral("FRPEACE"), QStringLiteral("we propose a peace treaty")}, + {QStringLiteral("FRFRIENDLY"), QStringLiteral("we propose friendly relations")}, + {QStringLiteral("FRALLIANCE"), QStringLiteral("we propose an alliance")}, + {QStringLiteral("FRDEMAND_STRONG"), QStringLiteral("we demand %1")}, + {QStringLiteral("FRPRESENT"), QStringLiteral("we offer you %1 as a gift")}, + {QStringLiteral("FRSTART_NOTREATY"), QStringLiteral("Greetings.")}, + {QStringLiteral("FRSTART_PEACE"), QStringLiteral("Greetings, friend.")}, + }; + const auto it = table.constFind(item); + return tString(it != table.constEnd() ? it.value() : item); } void Tribe::initAge(int age)