// 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