// 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 "Cevo/UnitProcessing.h" #include "Cevo/Database.h" #include "Cevo/IPQ.h" #include #include #include namespace Cevo { namespace UnitProcessing { int uixSelectedTransport = 0; // matches Pascal's zero-initialized global std::array worked{}; namespace { constexpr int eMountains = 0x6000FFFF; // additional return code for server internal use // tile control flags constexpr int coKnown = 0x02; constexpr int coTrue = 0x04; // ContraJobs[newJob]: bitset (1 << job) of jobs that get cancelled when // newJob is started on the same tile. constexpr std::array contraJobs = { static_cast(0), // jNone static_cast(1u << jCity), // jRoad static_cast(1u << jCity), // jRR static_cast((1u << jCity) | (1u << jTrans)), // jClear static_cast((1u << jCity) | (1u << jFarm) | (1u << jAfforest) | (1u << jMine) | (1u << jBase) | (1u << jFort)), // jIrr static_cast((1u << jCity) | (1u << jIrr) | (1u << jAfforest) | (1u << jMine) | (1u << jBase) | (1u << jFort)), // jFarm static_cast((1u << jCity) | (1u << jIrr) | (1u << jFarm) | (1u << jTrans)), // jAfforest static_cast((1u << jCity) | (1u << jTrans) | (1u << jIrr) | (1u << jFarm) | (1u << jBase) | (1u << jFort)), // jMine static_cast((1u << jCity) | (1u << jTrans)), // jCanal static_cast((1u << jCity) | (1u << jClear) | (1u << jAfforest) | (1u << jMine) | (1u << jCanal)), // jTrans static_cast((1u << jCity) | (1u << jIrr) | (1u << jFarm) | (1u << jMine) | (1u << jBase)), // jFort static_cast(1u << jCity), // jPoll static_cast((1u << jCity) | (1u << jIrr) | (1u << jFarm) | (1u << jMine) | (1u << jFort)), // jBase static_cast(1u << jCity), // jPillage static_cast(((1u << jPillage) << 1) - (1u << jRoad)), // jCity: jRoad..jPillage }; // Equivalent of the private `ToWork: ^TToWorkList` (work left for each tile // and job), sized to the map at initGame() instead of a GetMem block sized // to the theoretical TToWorkList bound. std::vector> toWork; // whether tile at loc is in control zone of enemy unit; returns a // combination of the tile control flags above. int controlled(int p, int loc, bool isDest) { if (isDest && Database::occupant[loc] == p && Database::zocMap[loc] > 0) return 0; int result = 0; if ((Database::realMap[loc] & fCity) == 0 || (static_cast(Database::realMap[loc] >> 27) != p && Database::serverVersion[p] >= 0x000EF0)) { Database::Vicinity8Loc adjacent; Database::v8ToLoc(loc, adjacent); for (int v8 = 0; v8 < 8; ++v8) { const int loc1 = adjacent[v8]; if (loc1 >= 0 && loc1 < Database::mapSize && Database::zocMap[loc1] > 0 && Database::occupant[loc1] >= 0 && Database::occupant[loc1] != p && Database::rw[p].Treaty[Database::occupant[loc1]] < trAlliance) { if ((Database::observeLevel[loc1] & (3u << (p * 2))) > 0) { return coKnown | coTrue; } else { result = coTrue; } } } } return result; } // MoveLength - 2 for short move, 3 for long move int getMoveCost(int p, int mix, int fromLoc, int toLoc, int moveLength, int &moveCost) { int result = eOK; const std::uint32_t fromTile = Database::realMap[fromLoc]; const std::uint32_t toTile = Database::realMap[toLoc]; const TModel &model = (*Database::rw[p].Model)[mix]; switch (model.Domain) { case dGround: if ((toTile & fTerrain) >= fGrass) { // domain ok, valid move if ((fromTile & (fRR | fCity)) != 0 && (toTile & (fRR | fCity)) != 0) { if (Database::gWonder[woShinkansen].EffectiveOwner == p) moveCost = 0; else moveCost = (model.Speed * (4 * 1311)) >> 17; // move along railroad } else if (((fromTile & (fRoad | fRR | fCity)) != 0 && (toTile & (fRoad | fRR | fCity)) != 0) || (fromTile & toTile & (fRiver | fCanal)) != 0 || model.Cap[mcAlpine] > 0) { // move along road, river or canal moveCost = (model.Cap[mcOver] > 0) ? 40 : 20; } else if (model.Cap[mcOver] > 0) { result = eNoRoad; } else { switch (Terrain[toTile & fTerrain].MoveCost) { case 1: moveCost = 50; // plain terrain break; case 2: assert(model.Speed - 150 <= 600); moveCost = 50 + (((model.Speed - 150) * 13) >> 7); // heavy terrain break; case 3: moveCost = model.Speed; return eMountains; } } moveCost *= moveLength; } else { result = eDomainMismatch; } break; case dSea: if ((toTile & (fCity | fCanal)) != 0 || (toTile & fTerrain) < fGrass) { // domain ok if ((toTile & fTerrain) != fOcean || model.Cap[mcNav] > 0) moveCost = 50 * moveLength; // valid move else result = eNoNav; // navigation required for open sea } else { result = eDomainMismatch; } break; case dAir: moveCost = 50 * moveLength; // always valid move break; } return result; } } // namespace // --- Moving/Combat --- int hostileDamage(int p, int mix, int loc, int mp) { const std::uint32_t tile = Database::realMap[loc]; const TModel &model = (*Database::rw[p].Model)[mix]; if (model.Domain >= dSea || (model.Kind == mkSettler && model.Speed >= 200) || (tile & (fCity | fRiver | fCanal)) != 0 || (tile & fTerImp) == tiBase || Database::gWonder[woGardens].EffectiveOwner == p) { return 0; } else if ((tile & fTerrain) == fDesert && (tile & fSpecial) != fSpecial1 /* Oasis */) { assert((tile & fTerImp) != tiIrrigation && (tile & fTerImp) != tiFarm); return ((DesertThurst * mp - 1) / model.Speed) + 1; } else if ((tile & fTerrain) == fArctic) { assert((tile & fTerImp) != tiIrrigation && (tile & fTerImp) != tiFarm); return ((ArcticThurst * mp - 1) / model.Speed) + 1; } return 0; } int calculateMove(int p, int uix, int toLoc, int moveLength, bool testOnly, TMoveInfo &moveInfo) { TPlayerContext &player = Database::rw[p]; TUn &un = (*player.Un)[uix]; const TModel &pModel = (*player.Model)[un.mix]; const int fromLoc = un.Loc; TBattleForecast battleForecast{}; battleForecast.pAtt = p; battleForecast.mixAtt = un.mix; battleForecast.HealthAtt = un.Health; battleForecast.ExpAtt = un.Exp; battleForecast.FlagsAtt = static_cast(un.Flags); battleForecast.Movement = un.Movement; int aStr = 0, dStr = 0, aBaseDamage = 0, dBaseDamage = 0; int result = getBattleForecast(toLoc, battleForecast, moveInfo.Duix, moveInfo.Dcix, aStr, dStr, aBaseDamage, dBaseDamage); if (result == eHiddenUnit) { if (testOnly) result = eOK; // behave just like unit was moving else if (Database::mode > Database::moLoading_Fast) (*player.Map)[toLoc] |= fHiddenUnit; } if (result == eStealthUnit) { if (testOnly) result = eOK; // behave just like unit was moving else if (Database::mode > Database::moLoading_Fast) (*player.Map)[toLoc] |= fStealthUnit; } if (result < rExecuted) return result; switch (result) { case eOK: moveInfo.MoveType = mtMove; break; case eExpelled: moveInfo.MoveType = mtExpel; break; default: moveInfo.MoveType = mtAttack; break; } if (moveInfo.MoveType == mtMove) { if (Database::mode == Database::moPlaying) { const int p1 = static_cast(Database::realMap[toLoc] >> 27); if (p1 < nPl && p1 != p && (((static_cast(Database::realMap[un.Loc] >> 27) != static_cast(p1)) && pModel.Kind != mkDiplomat && player.Treaty[p1] >= trPeace && player.Treaty[p1] < trAlliance) || ((Database::realMap[toLoc] & fCity) != 0 && player.Treaty[p1] >= trPeace))) { return eTreaty; // keep peace treaty! } } if ((Database::realMap[toLoc] & fCity) != 0 && static_cast(Database::realMap[toLoc] >> 27) != static_cast(p)) { // empty enemy city if (pModel.Kind == mkDiplomat) { moveInfo.MoveType = mtSpyMission; } else if (pModel.Domain == dGround) { if (pModel.Flags & mdCivil) return eNoCapturer; moveInfo.MoveType = mtCapture; } else { if (pModel.Domain == dSea && pModel.Cap[mcArtillery] == 0) return eDomainMismatch; if (pModel.Attack == 0 && !(pModel.Cap[mcBombs] > 0 && (un.Flags & unBombsLoaded) != 0)) return eNoBombarder; if (un.Movement < 100) return eNoTime_Bombard; moveInfo.MoveType = mtBombard; result = eBombarded; } } } moveInfo.MountainDelay = false; if (moveInfo.MoveType == mtAttack || moveInfo.MoveType == mtBombard || moveInfo.MoveType == mtExpel) { if (un.Master >= 0 || (pModel.Domain == dSea && (Database::realMap[fromLoc] & fTerrain) >= fGrass) || (pModel.Domain == dAir && ((Database::realMap[fromLoc] & fCity) != 0 || (Database::realMap[fromLoc] & fTerImp) == tiBase))) return eViolation; if (moveInfo.MoveType == mtBombard) { moveInfo.EndHealth = un.Health; moveInfo.EndHealthDef = -1; } else { moveInfo.EndHealth = battleForecast.EndHealthAtt; moveInfo.EndHealthDef = battleForecast.EndHealthDef; } } else { // mtMove / mtCapture / mtSpyMission if (un.Master >= 0 && pModel.Domain < dSea) { // transport unload moveInfo.Cost = pModel.Speed; if ((Database::realMap[toLoc] & fTerrain) < fGrass) result = eDomainMismatch; } else { result = getMoveCost(p, un.mix, fromLoc, toLoc, moveLength, moveInfo.Cost); if (result == eMountains) { result = eOK; moveInfo.MountainDelay = true; } } if (result >= rExecuted && moveInfo.MoveType == mtSpyMission) result = eMissionDone; moveInfo.ToMaster = -1; TUn *allUn = *player.Un; const TModel *allModel = *player.Model; if (result == eDomainMismatch && pModel.Domain < dSea && pModel.Cap[mcOver] == 0) { for (int uix1 = 0; uix1 < player.nUn; ++uix1) { // check load to transport TUn &un1 = allUn[uix1]; if (un1.Loc == toLoc && un1.TroopLoad < allModel[un1.mix].MTrans * allModel[un1.mix].Cap[mcSeaTrans]) { result = eLoaded; moveInfo.Cost = pModel.Speed; moveInfo.ToMaster = uix1; if (uixSelectedTransport >= 0 && uix1 == uixSelectedTransport) break; } } } else if (pModel.Domain == dAir && pModel.Cap[mcAirTrans] == 0 && (Database::realMap[toLoc] & fCity) == 0 && (Database::realMap[toLoc] & fTerImp) != tiBase) { for (int uix1 = 0; uix1 < player.nUn; ++uix1) { TUn &un1 = allUn[uix1]; if (un1.Loc == toLoc && un1.AirLoad < allModel[un1.mix].MTrans * allModel[un1.mix].Cap[mcCarrier]) { // load plane to ship result = eLoaded; moveInfo.ToMaster = uix1; if (uixSelectedTransport >= 0 && uix1 == uixSelectedTransport) break; } } } if (result < rExecuted) return result; if (un.Master < 0 && moveInfo.ToMaster < 0) moveInfo.EndHealth = un.Health - hostileDamage(p, un.mix, toLoc, moveInfo.Cost); else moveInfo.EndHealth = un.Health; if (Database::mode == Database::moPlaying && (pModel.Flags & mdZOC) != 0 && un.Master < 0 && moveInfo.ToMaster < 0 && controlled(p, fromLoc, false) >= coTrue) { const int destControlled = controlled(p, toLoc, true); if (destControlled >= coTrue + coKnown) return eZOC; else if (!testOnly && destControlled >= coTrue) return eZOC_EnemySpotted; } if ((un.Movement == 0 && Database::serverVersion[p] >= 0x0100F1) || moveInfo.Cost > un.Movement) { if (un.Master >= 0 || moveInfo.ToMaster >= 0) return eNoTime_Load; else return eNoTime_Move; } if (moveInfo.EndHealth <= 0 || moveInfo.MoveType == mtSpyMission) result |= rUnitRemoved; // spy mission or victim of HostileDamage } if (moveInfo.MoveType == mtAttack || moveInfo.MoveType == mtExpel) { moveInfo.Defender = Database::occupant[toLoc]; } else if (Database::realMap[toLoc] & fCity) { // moveInfo.Dcix not set yet moveInfo.Defender = static_cast(Database::realMap[toLoc] >> 27); Database::searchCity(toLoc, moveInfo.Defender, moveInfo.Dcix); } return result; } int getBattleForecast(int loc, TBattleForecast &battleForecast, int &duix, int &dcix, int &aStr, int &dStr, int &aBaseDamage, int &dBaseDamage) { int defender = Database::occupant[loc]; if (defender < 0 || defender == battleForecast.pAtt) return eOK; // no attack, simple move const TModel &pModel = (*Database::rw[battleForecast.pAtt].Model)[battleForecast.mixAtt]; int dBon = 0; { int dCnt = 0; Database::strongest(loc, duix, dStr, dBon, dCnt); // get defense strength and bonus } if (pModel.Kind == mkDiplomat && (Database::realMap[loc] & fCity) != 0) { // spy mission -- as if move was possible battleForecast.EndHealthAtt = battleForecast.HealthAtt; battleForecast.EndHealthDef = (*Database::rw[defender].Un)[duix].Health; return eOK; } const TModel &dModel = (*Database::rw[defender].Model)[(*Database::rw[defender].Un)[duix].mix]; if ((Database::realMap[loc] & fCity) == 0 && (Database::realMap[loc] & fTerImp) != tiBase) { if (dModel.Cap[mcSub] > 0 && (Database::realMap[loc] & fTerrain) < fGrass && ((Database::observeLevel[loc] >> (2 * battleForecast.pAtt)) & 3) < Database::lObserveAll) return eHiddenUnit; // attacking submarine not allowed if (dModel.Cap[mcStealth] > 0 && ((Database::observeLevel[loc] >> (2 * battleForecast.pAtt)) & 3) != Database::lObserveSuper) return eStealthUnit; // attacking stealth aircraft not allowed if (dModel.Domain == dAir && dModel.Kind != mkSpecial_Glider && pModel.Domain != dAir) return eDomainMismatch; // can't attack plane } if ((pModel.Cap[mcArtillery] == 0 || (Database::serverVersion[battleForecast.pAtt] >= 0x010200 && (Database::realMap[loc] & fTerrain) < fGrass && dModel.Cap[mcSub] > 0)) // ground units can't attack submarines && ((pModel.Domain == dGround && (Database::realMap[loc] & fTerrain) < fGrass) || (pModel.Domain == dSea && (Database::realMap[loc] & fTerrain) >= fGrass))) return eDomainMismatch; if (pModel.Attack == 0 && !(pModel.Cap[mcBombs] > 0 && (battleForecast.FlagsAtt & unBombsLoaded) != 0 && dModel.Domain < dAir)) return eInvalid; if (battleForecast.Movement == 0) return eNoTime_Attack; if (Database::rw[battleForecast.pAtt].Treaty[defender] >= trPeace) { if (pModel.Domain != dAir && pModel.Attack > 0 && static_cast(Database::realMap[loc] >> 27) == battleForecast.pAtt) { if (battleForecast.Movement >= 100) { // expel friendly unit battleForecast.EndHealthDef = (*Database::rw[defender].Un)[duix].Health; battleForecast.EndHealthAtt = battleForecast.HealthAtt; return eExpelled; } else { return eNoTime_Expel; } } else { return eTreaty; } } // calculate defender strength if (Database::realMap[loc] & fCity) { // consider city improvements Database::searchCity(loc, defender, dcix); if (pModel.Domain < dSea && pModel.Cap[mcArtillery] == 0 && ((*Database::rw[defender].City)[dcix].Built[imWalls] == 1 || Database::continent[(*Database::rw[defender].City)[dcix].Loc] == Database::grWallContinent[defender])) dBon += 8; else if (pModel.Domain == dSea && (*Database::rw[defender].City)[dcix].Built[imCoastalFort] == 1) dBon += 4; else if (pModel.Domain == dAir && (*Database::rw[defender].City)[dcix].Built[imMissileBat] == 1) dBon += 4; if ((*Database::rw[defender].City)[dcix].Built[imBunker] == 1) dBon += 4; } if (pModel.Domain == dAir && dModel.Cap[mcAirDef] > 0) dBon += 4; dStr = dModel.Defense * dBon * 100; if (dModel.Domain == dAir && ((Database::realMap[loc] & fCity) != 0 || (Database::realMap[loc] & fTerImp) == tiBase)) dStr = 0; if (dModel.Domain == dSea && (Database::realMap[loc] & fTerrain) >= fGrass) dStr >>= 1; // calculate attacker strength int time; if (pModel.Cap[mcWill] > 0) { time = 100; } else { time = battleForecast.Movement; if (time > 100) time = 100; } const int aBon = 4 + battleForecast.ExpAtt / ExpCost; aStr = pModel.Attack; if ((battleForecast.FlagsAtt & unBombsLoaded) != 0 && dModel.Domain < dAir) // use bombs aStr += pModel.Cap[mcBombs] * pModel.MStrength * 2; aStr = time * aStr * aBon; const TUn &defenderUn = (*Database::rw[defender].Un)[duix]; // base damage for defender if (dStr == 0) { dBaseDamage = defenderUn.Health; } else { dBaseDamage = battleForecast.HealthAtt * aStr / dStr; if (dBaseDamage == 0) dBaseDamage = 1; if (dBaseDamage > defenderUn.Health) dBaseDamage = defenderUn.Health; } // base damage for attacker if (aStr == 0) { aBaseDamage = battleForecast.HealthAtt; } else { aBaseDamage = defenderUn.Health * dStr / aStr; if (aBaseDamage == 0) aBaseDamage = 1; if (aBaseDamage > battleForecast.HealthAtt) aBaseDamage = battleForecast.HealthAtt; } // final damage for defender int multiDamage = 2; if (aBaseDamage == battleForecast.HealthAtt && pModel.Cap[mcFanatic] > 0 && !(Database::rw[battleForecast.pAtt].Government == gRepublic || Database::rw[battleForecast.pAtt].Government == gDemocracy || Database::rw[battleForecast.pAtt].Government == gFuture)) multiDamage *= 2; // fanatic attacker died battleForecast.EndHealthDef = defenderUn.Health - multiDamage * dBaseDamage / 2; if (battleForecast.EndHealthDef < 0) battleForecast.EndHealthDef = 0; // final damage for attacker multiDamage = 2; if (dBaseDamage == defenderUn.Health) { if (dModel.Cap[mcFanatic] > 0 && !(Database::rw[defender].Government == gRepublic || Database::rw[defender].Government == gDemocracy || Database::rw[defender].Government == gFuture)) multiDamage *= 2; // fanatic defender died if (pModel.Cap[mcFirst] > 0) multiDamage >>= 1; // first strike unit wins } time = battleForecast.Movement; if (time > 100) time = 100; battleForecast.EndHealthAtt = battleForecast.HealthAtt - multiDamage * aBaseDamage / 2 - hostileDamage(battleForecast.pAtt, battleForecast.mixAtt, loc, time); if (battleForecast.EndHealthAtt < 0) battleForecast.EndHealthAtt = 0; if (battleForecast.EndHealthDef > 0) return eLost; else if (battleForecast.EndHealthAtt > 0) return eWon; return eBloody; } int loadUnit(int p, int uix, bool testOnly) { int result = eOK; TPlayerContext &player = Database::rw[p]; TUn &un = (*player.Un)[uix]; const int d = (*player.Model)[un.mix].Domain; if (un.Master >= 0 || d == dSea || (*player.Model)[un.mix].Cap[mcAirTrans] + (*player.Model)[un.mix].Cap[mcOver] > 0) { result = eViolation; } else { int toMaster = -1; TUn *allUn = *player.Un; const TModel *allModel = *player.Model; for (int uix1 = 0; uix1 < player.nUn; ++uix1) { if (allUn[uix1].Loc == un.Loc) { TUn &un1 = allUn[uix1]; const TModel &model1 = allModel[un1.mix]; // candidate transport's own model (its own capacity) if ((d < dSea && un1.TroopLoad < model1.MTrans * (model1.Cap[mcSeaTrans] + model1.Cap[mcAirTrans])) || (d == dAir && un1.AirLoad < model1.MTrans * model1.Cap[mcCarrier])) { // load onto unit uix1 if (uixSelectedTransport < 0 || uix1 == uixSelectedTransport) { toMaster = uix1; break; } else if (toMaster < 0) { toMaster = uix1; } } } } if (toMaster < 0) { result = eNoLoadCapacity; } else { const int cost = (d == dAir) ? 100 : (*player.Model)[un.mix].Speed; if (un.Movement < cost) { result = eNoTime_Load; } else if (!testOnly) { Database::freeUnit(p, uix); un.Movement -= static_cast(cost); if (d == dAir) ++allUn[toMaster].AirLoad; else ++allUn[toMaster].TroopLoad; un.Master = static_cast(toMaster); Database::updateUnitMap(un.Loc); } } } return result; } int unloadUnit(int p, int uix, bool testOnly) { int result = eOK; TPlayerContext &player = Database::rw[p]; TUn &un = (*player.Un)[uix]; const TModel &model = (*player.Model)[un.mix]; if (un.Master < 0) { result = eNotChanged; } else if (model.Domain < dSea && (Database::realMap[un.Loc] & fTerrain) < fGrass) { result = eDomainMismatch; } else { const int cost = (model.Domain == dAir) ? 100 : model.Speed; if (un.Movement < cost) { result = eNoTime_Load; } else if (!testOnly) { un.Movement -= static_cast(cost); TUn &masterUn = (*player.Un)[un.Master]; if (model.Domain == dAir) --masterUn.AirLoad; else --masterUn.TroopLoad; // Movement:=0 // no more movement after unload (commented out upstream too) un.Master = -1; Database::placeUnit(p, uix); Database::updateUnitMap(un.Loc); } } return result; } void recover(int p, int uix) { TPlayerContext &player = Database::rw[p]; TUn &un = (*player.Un)[uix]; const TModel &model = (*player.Model)[un.mix]; int recovery; if (un.Master >= 0 && (*player.Model)[(*player.Un)[un.Master].mix].Cap[mcSupplyShip] > 0) { recovery = FastRecovery; // hospital ship } else if ((Database::realMap[un.Loc] & fTerImp) == tiBase) { recovery = CityRecovery; } else if (Database::realMap[un.Loc] & fCity) { // unit in city int cix = player.nCity - 1; const TCity *allCity = *player.City; while (cix >= 0 && allCity[cix].Loc != un.Loc) --cix; if (allCity[cix].Flags & chDisorder) { recovery = NoCityRecovery; } else if ((model.Domain == dGround && allCity[cix].Built[imBarracks] + allCity[cix].Built[imElite] > 0) || (model.Domain == dSea && allCity[cix].Built[imDockyard] == 1) || (model.Domain == dAir && allCity[cix].Built[imAirport] == 1)) { recovery = FastRecovery; // city has barracks/shipyard/airport } else { recovery = CityRecovery; } } else if ((Database::realMap[un.Loc] & fTerrain) >= fGrass && model.Domain != dAir) { recovery = NoCityRecovery; } else { recovery = 0; } recovery = recovery * un.Movement / model.Speed; // recovery depends on movement unused if (recovery > un.Health) // health max. doubled each turn recovery = un.Health; if (recovery > 100 - un.Health) recovery = 100 - un.Health; un.Health = static_cast(un.Health + recovery); } int getMoveAdvice(int p, int uix, TMoveAdviceData &a) { // domains constexpr int gmaAir = 0; constexpr int gmaSea = 1; constexpr int gmaGround_NoZoC = 2; constexpr int gmaGround_ZoC = 3; // flags constexpr int gmaNav = 4; constexpr int gmaOver = 4; constexpr int gmaAlpine = 8; TPlayerContext &player = Database::rw[p]; TUn &un = (*player.Un)[uix]; int maxDamage = un.Health - 1; if (maxDamage > a.MaxHostile_MovementLeft) maxDamage = (a.MaxHostile_MovementLeft >= 0) ? a.MaxHostile_MovementLeft : 0; const std::uint32_t *map = *player.Map; if (a.ToLoc != maNextCity && (a.ToLoc < 0 || a.ToLoc >= Database::mapSize)) return eInvalid; if (a.ToLoc != maNextCity && (map[a.ToLoc] & fTerrain) == fUNKNOWN) return eNoWay; const TModel &model = (*player.Model)[un.mix]; int moveInfo = 0; int heavyCost = 0; int railCost = 0; int maxMov = 0; int initMov = 0; bool resistant = false; switch (model.Domain) { case dGround: if (a.ToLoc != maNextCity && (map[a.ToLoc] & fTerrain) == fOcean) return eDomainMismatch; moveInfo = (model.Flags & mdZOC) ? gmaGround_ZoC : gmaGround_NoZoC; if (model.Cap[mcOver] > 0) moveInfo += gmaOver; if (model.Cap[mcAlpine] > 0) moveInfo += gmaAlpine; heavyCost = 50 + (((model.Speed - 150) * 13) >> 7); railCost = (Database::gWonder[woShinkansen].EffectiveOwner == p) ? 0 : (model.Speed * (4 * 1311)) >> 17; maxMov = model.Speed; initMov = 0; resistant = Database::gWonder[woGardens].EffectiveOwner == p || (model.Kind == mkSettler && model.Speed >= 200); break; case dSea: if (a.ToLoc != maNextCity && (map[a.ToLoc] & fTerrain) >= fGrass && (map[a.ToLoc] & (fCity | fUnit | fCanal)) == 0) return eDomainMismatch; moveInfo = gmaSea; if (model.Cap[mcNav] > 0) moveInfo += gmaNav; maxMov = Database::unitSpeed(p, un.mix, 100); initMov = maxMov - Database::unitSpeed(p, un.mix, un.Health); break; case dAir: moveInfo = gmaAir; maxMov = model.Speed; initMov = 0; break; } const int fromLoc = un.Loc; std::array from{}; std::array time{}; std::array damage{}; time.fill(-1); damage[fromLoc] = 0; Cevo::IPQ q(Database::mapSize); q.put(fromLoc, (maxMov - un.Movement) << 8); int loc = -1; int t = 0; while (q.get(loc, t)) { time[loc] = t; if (t >= (a.MoreTurns + 1) << 20) { loc = -1; break; } const std::uint32_t fromTile = map[loc]; if (loc == a.ToLoc || (a.ToLoc == maNextCity && (fromTile & fCity) != 0)) break; if ((t & 0xFFF00) == 0xFFF00) t += 0x100000; // indicates mountain delay Database::Vicinity8Loc adjacent; Database::v8ToLoc(loc, adjacent); for (int v8 = 0; v8 < 8; ++v8) { const int loc1 = adjacent[v8]; if (loc1 < 0 || loc1 >= Database::mapSize || time[loc1] >= 0) continue; const std::uint32_t toTile = map[loc1]; if (loc1 == a.ToLoc && (toTile & (fUnit | fOwned)) == fUnit && !((moveInfo & 3) == gmaSea && (fromTile & fTerrain) >= fGrass) && !((moveInfo & 3) == gmaAir && ((fromTile & fCity) != 0 || (fromTile & fTerImp) == tiBase))) { // attack position found if (q.put(loc1, t + 1)) from[loc1] = loc; } else if ((toTile & fTerrain) != fUNKNOWN && (loc1 == a.ToLoc || (toTile & (fCity | fOwned)) != fCity) && (loc1 == a.ToLoc || (toTile & (fUnit | fOwned)) != fUnit) && ((toTile & ~fromTile) & fPeace) == 0 && ((moveInfo & 3) < gmaGround_ZoC || (toTile & fromTile & fInEnemyZoC) == 0 || (toTile & fOwnZoCUnit) != 0 || (fromTile & fCity) != 0 || (toTile & (fCity | fOwned)) == (fCity | fOwned))) { int addDamage = 0; bool mountainDelay = false; int moveCost; switch (moveInfo) { case gmaAir: moveCost = 50; // always valid move break; case gmaSea: moveCost = ((toTile & (fCity | fCanal)) != 0 || (toTile & fTerrain) == fShore) ? 50 : -1; break; case gmaSea + gmaNav: moveCost = ((toTile & (fCity | fCanal)) != 0 || (toTile & fTerrain) < fGrass) ? 50 : -1; break; default: // ground unit if ((toTile & fTerrain) >= fGrass) { // domain ok, valid move if ((fromTile & (fRR | fCity)) != 0 && (toTile & (fRR | fCity)) != 0) { moveCost = railCost; // move along railroad } else if (((fromTile & (fRoad | fRR | fCity)) != 0 && (toTile & (fRoad | fRR | fCity)) != 0) || (fromTile & toTile & (fRiver | fCanal)) != 0 || (moveInfo & gmaAlpine) != 0) { // move along road, river or canal moveCost = (moveInfo & gmaOver) ? 40 : 20; } else if (moveInfo & gmaOver) { moveCost = -1; } else { switch (Terrain[toTile & fTerrain].MoveCost) { case 1: moveCost = 50; // plain terrain break; case 2: moveCost = heavyCost; // heavy terrain break; case 3: moveCost = maxMov; mountainDelay = true; break; default: moveCost = -1; break; } } // calculate HostileDamage if (!resistant && (toTile & fTerImp) != tiBase) { if ((toTile & (fTerrain | fCity | fRiver | fCanal | fSpecial1 /* Oasis */)) == static_cast(fDesert)) { addDamage = (v8 & 1) ? ((DesertThurst * 3 * moveCost - 1) / maxMov) + 1 : ((DesertThurst * 2 * moveCost - 1) / maxMov) + 1; } else if ((toTile & (fTerrain | fCity | fRiver | fCanal)) == static_cast(fArctic)) { addDamage = (v8 & 1) ? ((ArcticThurst * 3 * moveCost - 1) / maxMov) + 1 : ((ArcticThurst * 2 * moveCost - 1) / maxMov) + 1; } } } else { moveCost = -1; } break; } if (moveCost > 0 && !mountainDelay) moveCost = (v8 & 1) ? moveCost + moveCost * 2 : moveCost + moveCost; if ((moveInfo & 2) != 0 // ground unit, check transport load/unload && (((moveCost < 0) && (toTile & (fUnit | fOwned)) == (fUnit | fOwned)) // assume ship/plane is transport || (moveCost >= 0 && (fromTile & fTerrain) < fGrass))) moveCost = maxMov; // transport load or unload if (moveCost >= 0) { // valid move const int movementLeft = maxMov - ((t >> 8) & 0xFFF) - moveCost; int t1; if (movementLeft < 0 || (moveCost == 0 && movementLeft == 0)) { // must wait for next turn if ((moveInfo & 2) != 0 /* ground unit */ && !resistant && (fromTile & fTerImp) != tiBase) { if ((fromTile & (fTerrain | fCity | fRiver | fCanal | fSpecial1)) == static_cast(fDesert)) addDamage += ((DesertThurst * (maxMov - ((t >> 8) & 0xFFF)) - 1) / maxMov) + 1; else if ((fromTile & (fTerrain | fCity | fRiver | fCanal)) == static_cast(fArctic)) addDamage += ((ArcticThurst * (maxMov - ((t >> 8) & 0xFFF)) - 1) / maxMov) + 1; } t1 = (t & 0x7FF000FF) + 0x100000 + ((initMov + moveCost) << 8); } else { t1 = t + (moveCost << 8) + 1; } if (mountainDelay) t1 |= 0xFFF00; if (damage[loc] + addDamage <= maxDamage && (t1 & 0xFF) < 0xFF) { if (q.put(loc1, t1)) { from[loc1] = loc; damage[loc1] = damage[loc] + addDamage; } } } } } } int result; if (loc == a.ToLoc || (a.ToLoc == maNextCity && loc >= 0 && (map[loc] & fCity) != 0)) { a.MoreTurns = t >> 20; const int endLoc = loc; a.nStep = 0; while (loc != fromLoc) { if (time[loc] < 0x100000) ++a.nStep; loc = from[loc]; } loc = endLoc; int i = a.nStep; while (loc != fromLoc) { if (time[loc] < 0x100000) { --i; if (i < 25) { const int v1 = (loc % Database::lx) * 2 + ((loc / Database::lx) & 1); const int v2 = (from[loc] % Database::lx) * 2 + ((from[loc] / Database::lx) & 1); a.dx[i] = ((v1 - v2 + 3 * Database::lx) % (2 * Database::lx)) - Database::lx; a.dy[i] = loc / Database::lx - from[loc] / Database::lx; } } loc = from[loc]; } a.MaxHostile_MovementLeft = maxMov - ((time[endLoc] >> 8) & 0xFFF); if (a.nStep > 25) a.nStep = 25; result = eOK; } else { result = eNoWay; } return result; } bool canPlaneReturn(int p, int uix, const TPlaneReturnData &planeReturnData) { constexpr std::uint8_t mfEnd = 1; constexpr std::uint8_t mfReached = 2; TPlayerContext &player = Database::rw[p]; const std::uint32_t *map = *player.Map; std::array mapFlags{}; TUn &un = (*player.Un)[uix]; const TModel &model = (*player.Model)[un.mix]; if (model.Kind == mkSpecial_Glider) { for (int loc = 0; loc < Database::mapSize; ++loc) if ((map[loc] & fTerrain) >= fGrass) mapFlags[loc] |= mfEnd; } else { int loc = 0; for (loc = 0; loc < Database::mapSize; ++loc) if ((map[loc] & (fCity | fOwned)) == (fCity | fOwned) || ((map[loc] & fTerImp) == tiBase && (map[loc] & fObserved) != 0 && (map[loc] & (fUnit | fOwned)) != fUnit)) mapFlags[loc] |= mfEnd; if (model.Cap[mcAirTrans] == 0) { // plane can land on carriers TUn *allUn = *player.Un; const TModel *allModel = *player.Model; for (int uix1 = 0; uix1 < player.nUn; ++uix1) { TUn &un1 = allUn[uix1]; // Faithful port: the original reuses the preceding loop's // stale `Loc` (left at MapSize-1) here instead of un1.Loc - // looks like a dormant upstream bug, preserved as-is. if (un1.AirLoad < allModel[un1.mix].MTrans * allModel[un1.mix].Cap[mcCarrier]) mapFlags[loc] |= mfEnd; } } } if (un.Master >= 0) // can return to same carrier, even if full now mapFlags[un.Loc] |= mfEnd; const int maxMov = model.Speed; bool result = false; Cevo::IPQ q(Database::mapSize); q.put(planeReturnData.Loc, (maxMov - planeReturnData.Movement) << 8); int loc = 0; int t = 0; while (q.get(loc, t)) { mapFlags[loc] |= mfReached; if (t >= (planeReturnData.Fuel + 1) << 20) { result = false; break; } if (mapFlags[loc] & mfEnd) { result = true; break; } const std::uint32_t fromTile = map[loc]; Database::Vicinity8Loc adjacent; Database::v8ToLoc(loc, adjacent); for (int v8 = 0; v8 < 8; ++v8) { const int loc1 = adjacent[v8]; if (loc1 < 0 || loc1 >= Database::mapSize || (mapFlags[loc1] & mfReached)) continue; const std::uint32_t toTile = map[loc1]; if ((toTile & fTerrain) != fUNKNOWN && (toTile & (fCity | fOwned)) != fCity && (toTile & (fUnit | fOwned)) != fUnit && ((toTile & ~fromTile) & fPeace) == 0) { const int moveCost = (v8 & 1) ? 150 : 100; int t1; if (moveCost + ((t >> 8) & 0xFFF) > maxMov) // must wait for next turn t1 = (t & 0x7FF000FF) + 0x100000 + (moveCost << 8); else t1 = t + (moveCost << 8); q.put(loc1, t1); } } } return result; } // --- Terrain Improvement --- namespace { int calculateJobWork(int p, int loc, int job, int &jobWork) { int result = eOK; const int terrType = static_cast(Database::realMap[loc] & fTerrain); const TerrainInfo &terrain = Terrain[terrType]; switch (job) { case jCity: if (Database::realMap[loc] & fCity) result = eInvalid; else if (terrain.IrrEff == 0) result = eNoCityTerrain; else jobWork = CityWork; break; case jRoad: if ((Database::realMap[loc] & (fRoad | fRR)) == 0) { jobWork = terrain.MoveCost * RoadWork; if (Database::realMap[loc] & fRiver) { if (Database::rw[p].Tech[adBridgeBuilding] >= tsApplicable) jobWork += RoadBridgeWork; // across river else result = eNoBridgeBuilding; } } else { result = eInvalid; } break; case jRR: if ((Database::realMap[loc] & fRoad) == 0) result = eNoPreq; else if (Database::realMap[loc] & fRR) result = eInvalid; else { jobWork = terrain.MoveCost * RRWork; if (Database::realMap[loc] & fRiver) jobWork += RRBridgeWork; // across river } break; case jClear: if (terrType == fDesert && Database::gWonder[woGardens].EffectiveOwner != p) result = eInvalid; else if (terrain.ClearTerrain >= 0) jobWork = terrain.IrrClearWork; else result = eInvalid; break; case jIrr: jobWork = terrain.IrrClearWork; if (terrain.IrrEff == 0 || (Database::realMap[loc] & fTerImp) == tiIrrigation || (Database::realMap[loc] & fTerImp) == tiFarm) result = eInvalid; break; case jFarm: if ((Database::realMap[loc] & fTerImp) != tiIrrigation) { result = eNoPreq; } else { jobWork = terrain.IrrClearWork * FarmWork; if (jobWork <= 0 || (Database::realMap[loc] & fTerImp) == tiFarm) result = eInvalid; } break; case jAfforest: if (terrain.AfforestTerrain >= 0) jobWork = terrain.MineAfforestWork; else result = eInvalid; break; case jMine: jobWork = terrain.MineAfforestWork; if (terrain.MineEff == 0 || (Database::realMap[loc] & fTerImp) == tiMine) result = eInvalid; break; case jFort: if ((Database::realMap[loc] & fTerImp) != tiFort) jobWork = terrain.MoveCost * FortWork; else result = eInvalid; break; case jCanal: if ((Database::realMap[loc] & fCanal) == 0 && ((Database::terrTypeCanalableMask >> terrType) & 1)) jobWork = CanalWork; else result = eInvalid; break; case jTrans: jobWork = terrain.TransWork; if (jobWork <= 0) result = eInvalid; break; case jPoll: if (Database::realMap[loc] & fPoll) jobWork = PollWork; else result = eInvalid; break; case jBase: if ((Database::realMap[loc] & fTerImp) != tiBase) jobWork = terrain.MoveCost * BaseWork; else result = eInvalid; break; case jPillage: if (Database::realMap[loc] & (fRoad | fRR | fCanal | fTerImp)) jobWork = PillageWork; else result = eInvalid; break; default: break; } return result; } } // namespace int startJob(int p, int uix, int newJob, bool testOnly) { assert(((1 << p) & Database::invalidTreatyMap) == 0); int result = eOK; TPlayerContext &player = Database::rw[p]; TUn &un = (*player.Un)[uix]; if (newJob == un.Job) return eNotChanged; if (newJob == jNone) { if (!testOnly) un.Job = static_cast(jNone); return result; } const int loc0 = un.Loc; if ((Database::realMap[loc0] & fDeadLands) != 0 && newJob != jRoad && newJob != jRR) return eDeadLands; const int terrType = static_cast(Database::realMap[loc0] & fTerrain); const TModel &model = (*player.Model)[un.mix]; const bool allowed = ((newJob == jPillage) && model.Domain == dGround) || model.Kind == mkSettler || ((newJob != jCity) && model.Kind == mkSlaves && Database::gWonder[woPyramids].EffectiveOwner >= 0); if ((Database::realMap[loc0] & fCity) != 0 || terrType < fGrass || un.Master >= 0 || !allowed) return eInvalid; if (JobPreq[newJob] != preNone && player.Tech[JobPreq[newJob]] < tsApplicable) return eNoPreq; int jobWork = 0; result = calculateJobWork(p, loc0, newJob, jobWork); if (Database::mode == Database::moPlaying && result == eOK && newJob != jPoll) { // not in friendly territory const int p1 = static_cast(Database::realMap[loc0] >> 27); // owner of territory if (p1 < nPl && p1 != p && player.Treaty[p1] >= trPeace) result = eTreaty; // keep peace treaty! } if (testOnly || result < rExecuted) return result; if (toWork[loc0][newJob] == 0 || toWork[loc0][newJob] > jobWork) toWork[loc0][newJob] = static_cast(jobWork); un.Job = static_cast(newJob); un.Flags &= ~static_cast(unFortified); TUn *allUn = *player.Un; for (int uix1 = 0; uix1 < player.nUn; ++uix1) if (allUn[uix1].Loc == loc0 && (contraJobs[newJob] & (1u << allUn[uix1].Job))) allUn[uix1].Job = static_cast(jNone); // stop contradictive jobs if (Database::serverVersion[p] < 0x000EF0) if (work(p, uix)) result = eJobDone; if (newJob == jCity && result == eJobDone) { Database::removeUnitUpdateMap(p, uix); result = eCity; } else if (un.Health <= 0) { // victim of HostileDamage Database::removeUnitUpdateMap(p, uix); result |= rUnitRemoved; } if (Database::mode > Database::moLoading_Fast) { if (result == eCity) { Database::observeLevel[loc0] &= ~(3u << (2 * p)); Database::discover21(loc0, p, Database::lObserveUnhidden, true, true); } } return result; } bool work(int p, int uix) { bool result = false; TPlayerContext &player = Database::rw[p]; TUn &un = (*player.Un)[uix]; if (un.Movement >= 100) { assert(toWork[un.Loc][un.Job] < 0xFFFFu); // should have been set by startJob if (un.Job >= jRoad) { if (static_cast(un.Movement) >= static_cast(toWork[un.Loc][un.Job])) { // work complete result = true; if (un.Job != jIrr) un.Health = static_cast(un.Health - hostileDamage(p, un.mix, un.Loc, toWork[un.Loc][un.Job])); un.Movement -= static_cast(toWork[un.Loc][un.Job]); if (un.Job != jCity && un.Job != jPillage && un.Job != jPoll) worked[p] += toWork[un.Loc][un.Job]; if (un.Job == jCity) { // found new city Database::foundCity(p, un.Loc); ++Database::founded[p]; TCity &city = (*player.City)[player.nCity - 1]; city.ID = static_cast((p << 12) + Database::founded[p] - 1); city.Flags = chFounded; if (Database::mode == Database::moPlaying) { Database::logCheckBorders(p, player.nCity - 1); Database::recalcPeaceMap(p); } if (Database::mode < Database::moPlaying) Database::invalidTreatyMap = ~(1 << p); // territory should not be considered for the rest of the // command execution, because during loading a game it's // incorrect before subsequent sIntExpandTerritory is processed un.Health = 0; // causes unit to be removed later } else { Database::completeJob(p, un.Loc, un.Job); } toWork[un.Loc][un.Job] = 0; const int j0 = un.Job; TUn *allUn = *player.Un; for (int uix1 = 0; uix1 < player.nUn; ++uix1) if (allUn[uix1].Loc == un.Loc && allUn[uix1].Job == j0) allUn[uix1].Job = static_cast(jNone); } else { toWork[un.Loc][un.Job] = static_cast(toWork[un.Loc][un.Job] - un.Movement); if (un.Job != jCity && un.Job != jPillage && un.Job != jPoll) worked[p] += un.Movement; un.Health = static_cast(un.Health - hostileDamage(p, un.mix, un.Loc, un.Movement)); un.Movement = 0; } } } return result; } int getJobProgress(int p, int loc, TJobProgressData &jobProgressData) { TPlayerContext &player = Database::rw[p]; for (int job = 0; job < nJob; ++job) { const int jobResult = calculateJobWork(p, loc, job, jobProgressData[job].Required); if (jobResult == eOK) { if (toWork[loc][job] == 0xFFFFu) jobProgressData[job].Done = 0; else jobProgressData[job].Done = jobProgressData[job].Required - toWork[loc][job]; } else { jobProgressData[job].Required = 0; jobProgressData[job].Done = 0; } jobProgressData[job].NextTurnPlus = 0; } const TUn *un = *player.Un; for (int uix = 0; uix < player.nUn; ++uix) if (un[uix].Loc == loc && un[uix].Movement >= 100) jobProgressData[un[uix].Job].NextTurnPlus += un[uix].Movement; return eOK; } // --- Start/End Game --- void initGame() { toWork.assign(static_cast(Database::mapSize), {}); for (auto &row : toWork) row.fill(0xFFFFu); } void releaseGame() { toWork.clear(); toWork.shrink_to_fit(); } } // namespace UnitProcessing } // namespace Cevo