From 18bf340deee2e32b880979666da25a15f8a66845 Mon Sep 17 00:00:00 2001 From: Geoffray Levasseur Date: Tue, 27 Oct 2026 11:57:29 +0100 Subject: [PATCH] city processing --- ai/include/Cevo/Protocol.h | 49 +- game/include/Cevo/CityProcessing.h | 52 +- game/include/Cevo/Database.h | 115 +++ game/src/CityProcessing.cpp | 1404 ++++++++++++++++++++++++++++ game/src/Database.cpp | 918 ++++++++++++++++++ 5 files changed, 2524 insertions(+), 14 deletions(-) diff --git a/ai/include/Cevo/Protocol.h b/ai/include/Cevo/Protocol.h index 6a593af..b8c82b4 100644 --- a/ai/include/Cevo/Protocol.h +++ b/ai/include/Cevo/Protocol.h @@ -43,12 +43,14 @@ // calling convention. // // NOT ported here (left as a follow-up, pure data with no ABI-shape impact): -// the large gameplay rule tables Imp[], Terrain[], Upgrade[], Feature[], -// AdvPreq[], GovPreq, AgePreq, JobPreq, SpecialModel[], ShipNeed/ShipImpIndex, -// SettlerFood/CorrLevel/SupportFree, ImpReplacement, AutoFeature, -// WeightPreq7/10. An AI module compiled against a slightly different copy of -// those tables still speaks the same wire protocol; it just has stale rule -// knowledge, which is a correctness/strength concern, not an ABI one. +// Terrain[], Upgrade[], Feature[], AdvPreq[], JobPreq, SpecialModel[], +// ImpReplacement, AutoFeature, WeightPreq7/10. An AI module compiled against +// a slightly different copy of those tables still speaks the same wire +// protocol; it just has stale rule knowledge, which is a correctness/ +// strength concern, not an ABI one. (Imp[]/GovPreq/AgePreq/SettlerFood/ +// CorrLevel/SupportFree/ShipNeed/ShipImpIndex WERE added later, once a +// consumer needed them - this comment previously listed them as unported, +// now corrected.) // // Field order/types mirror the Pascal records exactly; `{$PACKRECORDS C}` // (Free Pascal's C-compatible alignment) matches plain C++ struct layout on @@ -1649,6 +1651,41 @@ constexpr int GovPreq[nGov] = { preNA, preNone, adMonarchy, adTheRepublic, adThe constexpr int AgePreq[4] = { preNA, adScience, adMassProduction, adTransstellarColonization }; constexpr int SettlerFood[nGov] = { 1, 1, 1, 2, 1, 2, 2, 2 }; +constexpr int CorrLevel[nGov] = { 3, 3, 1, 2, 1, 0, 0, 0 }; +constexpr int SupportFree[nGov] = { 2, 2, 1, 0, 2, 1, 0, 0 }; + +constexpr int nSpecialModel = 9; + +// Pre-defined unit models every player has from the start (Settlers, +// Engineers, Militia, Town Guard, Special Commando, Freight, Longboat, +// Slaves, Glider) - field order matches struct TModel exactly (aggregate +// init, no designated initializers since this targets C++17). Trailing +// `{}`/short Cap[] initializers zero-fill the rest, same as the Pascal +// array literals' explicit zero lists. +constexpr TModel SpecialModel[nSpecialModel] = { + // Settlers + { 0, 0, 0, 0, 0, 0, mkSettler, dGround, 0, 10, 150, 40, 0, 0, 0, 0, 0, 0, 0, {} }, + // Engineers + { 0, 0, 0, 0, 0, 0, mkSettler, dGround, 0, 20, 300, 40, 0, 0, 0, 0, 0, 0, 0, {} }, + // Militia + { 0, 0, 0, 0, 0, 0, mkSelfDeveloped, dGround, 6, 6, 150, 10, 0, 0, 0, 0, 0, 0, 0, {} }, + // Town Guard + { 0, 0, 0, 0, 0, 0, mkSpecial_TownGuard, dGround, 4, 6, 150, 20, 0, 0, 0, 0, 0, 0, 0, {} }, + // Special Commando + { 0, 0, 0, 0, 0, 0, mkDiplomat, dGround, 12, 12, 250, 20, 0, 0, 0, 0, 0, 0, 0, {} }, + // Freight + { 0, 0, 0, 0, 0, 0, mkCaravan, dGround, 0, 6, 150, 60, 0, 0, 0, 0, 0, 0, 0, {} }, + // Longboat (Cap[3] = 2) + { 0, 0, 0, 0, 0, 0, mkSpecial_Boat, dSea, 0, 3, 250, 20, 0, 1, 0, 0, 0, 0, 0, { 0, 0, 0, 2 } }, + // Slaves + { 0, 0, 0, 0, 0, 0, mkSlaves, dGround, 0, 15, 150, 40, 0, 0, 0, 0, 0, 0, 0, {} }, + // Glider (Cap[17] = 1) + { 0, 0, 0, 0, 0, 0, mkSpecial_Glider, dAir, 6, 6, 450, 30, 0, 0, 0, 0, 0, 0, 0, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } }, +}; + +constexpr int SpecialModelPreq[nSpecialModel] = { preNone, adExplosives, preNone, preNone, adIntelligence, + adTrade, adMapMaking, preBuilder, preLeo }; struct TerrainInfo { int MoveCost; diff --git a/game/include/Cevo/CityProcessing.h b/game/include/Cevo/CityProcessing.h index 57c1d7d..2812ce1 100644 --- a/game/include/Cevo/CityProcessing.h +++ b/game/include/Cevo/CityProcessing.h @@ -33,14 +33,17 @@ namespace Cevo { namespace CityProcessing { -// Equivalent of CityProcessing.pas (~1743 lines). PORTED INCREMENTALLY: this -// is only its "Reporting" section's two simplest functions so far - every -// other function in the original (GetCityReport/GetCityReportNew and -// everything in "Internal Tile Picking"/"Turn Processing") additionally -// needs GetTileInfo/GetUnitReport/Strongest (Database.pas functions not -// ported yet) plus several more Database.pas globals (GWonder, Difficulty, -// ServerVersion, ...) and gameplay data tables (Imp[], CorrLevel[], -// SupportFree[], ...). Add more here only once those are ported too. +// Equivalent of CityProcessing.pas (~1743 lines). FULLY PORTED. Its +// private implementation-section helpers (DetermineCityProdProcessing/ +// DetermineCityTradeProcessing/BoostProd/SplitTrade/GetProjectCost/ +// GetSmallCityReport/NextBest/NextWorst/NextPoll, plus the ProdProcessing/ +// TradeProcessing/CityReportEx support structs) live in an anonymous +// namespace in CityProcessing.cpp, matching the original's own visibility +// (not part of its interface section either). +// CityTurn() needed a large prerequisite chain in Database.pas (Map +// Processing, most of Map Revealing, Tech Related Functions, a slice of +// Diplomacy, plus the SpecialModel[]/SpecialModelPreq[] tables) - see repo +// memory for the full list of what got ported to unblock it. // Equivalent of CityProcessing.pas's GetCityAreaInfo(). void getCityAreaInfo(int p, int loc, TCityAreaInfo &cityAreaInfo); @@ -48,5 +51,38 @@ void getCityAreaInfo(int p, int loc, TCityAreaInfo &cityAreaInfo); // Equivalent of CityProcessing.pas's CanCityGrow(). bool canCityGrow(int p, int cix); +// Equivalent of CityProcessing.pas's GetCityReport()/GetCityReportNew(). +int getCityReport(int p, int cix, TCityReport &cityReport); +int getCityReportNew(int p, int cix, TCityReportNew &cityReportNew); + +// Equivalent of CityProcessing.pas's AddBestCityTile(). +bool addBestCityTile(int p, int cix); + +// Equivalent of CityProcessing.pas's CityGrowth()/CityShrink()/Pollute(). +void cityGrowth(int p, int cix); +void cityShrink(int p, int cix); +void pollute(int p, int cix); + +// Equivalent of CityProcessing.pas's PayCityMaintenance()/CollectCityResources(). +void payCityMaintenance(int p, int cix); +void collectCityResources(int p, int cix); + +// Equivalent of CityProcessing.pas's CityTurn(). Return value: whether the +// city keeps existing. +bool cityTurn(int p, int cix); + +// Equivalent of CityProcessing.pas's SetCityTiles(). +int setCityTiles(int p, int cix, int newTiles, bool testOnly = false); + +// Equivalent of CityProcessing.pas's GetCityTileAdvice(): brute-force search +// over all "take N best tiles from each resource hierarchy" combinations to +// recommend the tile selection maximizing a weighted food/prod/tax/science +// value formula (weights packed into advice.ResourceWeights on input). +void getCityTileAdvice(int p, int cix, TCityTileAdviceData &advice); + +// Equivalent of CityProcessing.pas's InitGame()/ReleaseGame(). +void initGame(); +void releaseGame(); + } // namespace CityProcessing } // namespace Cevo diff --git a/game/include/Cevo/Database.h b/game/include/Cevo/Database.h index bc2687e..52e0686 100644 --- a/game/include/Cevo/Database.h +++ b/game/include/Cevo/Database.h @@ -28,6 +28,7 @@ #pragma once +#include "Cevo/CmdList.h" #include "Cevo/Protocol.h" #include @@ -58,6 +59,26 @@ namespace Database { // `TCity *city = *rw[p].City;` first if indexing repeatedly (same idiom // ai/src/CustomAI.cpp already uses for `myCity`). +// Observe levels (Database.pas's own constants, not Protocol.pas's). +constexpr int lNoObserve = 0; +constexpr int lObserveUnhidden = 1; +constexpr int lObserveAll = 2; +constexpr int lObserveSuper = 3; + +// Database.pas's own constant (not Protocol.pas's). +constexpr int CityOwnTile = 13; +constexpr int nemmax = 1024; +constexpr int necmax = 1024; +constexpr int neumax = 4096; + +// Equivalent of Database.pas's TGameMode - ordinal comparisons () match +// the original's enum declaration order. +enum GameMode { moLoading_Fast, moLoading, moMovie, moPlaying }; +extern GameMode mode; + +// Equivalent of Database.pas's `CL: TCmdList` - the live command log. +extern CmdList cl; + extern int lx; extern int ly; extern int mapSize; // = lx * ly @@ -67,16 +88,44 @@ using Vicinity21Loc = std::array; // player data extern std::array rw; +extern std::array difficulty; +extern std::array serverVersion; +extern std::array resourceMask; +extern std::array processClientData; +extern std::array discovered; // number of tiles discovered +extern std::array lastValidStat; +extern std::array nTech; // number of known techs +extern int gAlive; // players alive; bitset of 1 shl p +extern int gWatching; +extern int gAI; +extern int gTurn; // current turn +extern int gTestFlags; +extern std::array gWonder; +extern std::array grWallContinent; // continent id the Great Wall was built on, -1 if none +extern std::array gShip; +// [p1,p2,mix] -> index of p2's model mix in p1's enemy model list +extern std::array, nPl>, nPl> rwemix; +// [p1,p2,mix] -> number of p2's units with model mix that p1 has destroyed +extern std::array, nPl>, nPl> destroyed; // map data extern std::array realMap; +extern std::array continent; // continent id for each tile extern std::array occupant; // occupying player for each tile extern std::array zocMap; extern std::array usedByCity; // -1 if not exploited +extern std::array observeLevel; // observe level of player p in bits 2*p, 2*p+1 // Equivalent of Database.pas's MaskD(). void maskD(std::uint32_t *x, int count, std::uint32_t mask); +// Equivalent of Database.pas's IntServer(): dispatches internal server +// notifications (sIntXxx command codes) and records them to the command +// log. Declared here (used by several Map Revealing functions below) but +// only implemented once its own dependency chain (IntroduceEnemy, +// CancelTreaty, ...) exists - see Database.cpp for current coverage. +void intServer(int command, int player, int subject, const void *data); + // --- Location Navigation --- // Relative location, dx in hor and dy in ver direction from loc. Returns -1 @@ -92,5 +141,71 @@ void v21ToLoc(int loc0, Vicinity21Loc &vicinityLoc); void calculatePrimitive(); bool mapGeneratorAvailable(); +// --- Tech Related Functions --- + +int techBaseCost(int nTech, int diff); + +// Sets a model's Flags (ZOC/civil/double-support) from its other fields. +void setModelFlags(TModel &m); + +// Grants player p any SpecialModel[] not yet available that pre unlocks. +void checkSpecialModels(int p, int pre); + +// GWonder[wonder].EffectiveOwner must already be set before calling this. +void checkExpiration(int wonder); + +// --- Map Revealing --- + +// cix>=0: known city index of player p (internal use only). +// cix=-1: search city, player unknown, only if permission for p. +// cix=-2: don't search city, don't calculate city benefits, just government. +int getTileInfo(int p, int cix, int loc, TTileInfo &info); + +// Finds the strongest defender at loc. +void strongest(int loc, int &uix, int &strength, int &bonus, int &cnt); + +int unitSpeed(int p, int mix, int health); +void getUnitReport(int p, int uix, TUnitReport &unitReport); +void tellAboutModel(int p, int taOwner, int tamix); +int emixSafe(int p, int taOwner, int tamix); +int getUnitStack(int p, int loc); +void makeCityInfo(int p, int cix, TCityInfo &ci); + +// euix = -2: full discover. euix = -1: unit and city only, append to +// EnemyUn. euix >= 0: unit and city only, replace EnemyUn[euix]. +bool discoverTile(int loc, int p, int pTell, int level, bool enableContact, int euix = -2); + +bool discover9(int loc, int p, int level, bool tellAllied, bool enableContact); +bool discover21(int loc, int p, int adjacentLevel, bool tellAllied, bool enableContact); + +// Player p discovers the complete playground (for the supervisor). +void discoverAll(int p, int level); + +// Discovers unit and city view areas. +void discoverViewAreas(int p); + +// Updates maps and enemy units of all players after a unit change. +void updateUnitMap(int loc, bool cityChange = false); + +// Sets p to the supposed owner before the call. +void searchCity(int loc, int &p, int &cix); + +// --- Map Processing --- + +void createUnit(int p, int mix); +void placeUnit(int p, int uix); +void freeUnit(int p, int uix); +// loc or master should be set after call. Enemy >=0 counts the unit as lost +// to that player (use only from inside sMoveUnit if attack). +void removeUnit(int p, int uix, int enemy = -1); +void removeUnitUpdateMap(int p, int uix); + +// --- Diplomacy --- + +void introduceEnemy(int p1, int p2); +int techCost(int p); +void giveCivilReport(int p, int pAbout); +void giveMilReport(int p, int pAbout); + } // namespace Database } // namespace Cevo diff --git a/game/src/CityProcessing.cpp b/game/src/CityProcessing.cpp index 3e5a311..132929f 100644 --- a/game/src/CityProcessing.cpp +++ b/game/src/CityProcessing.cpp @@ -29,6 +29,11 @@ #include "Cevo/CityProcessing.h" #include "Cevo/Database.h" +#include +#include +#include +#include + namespace Cevo { namespace CityProcessing { @@ -66,5 +71,1404 @@ bool canCityGrow(int p, int cix) city.Built[imSewer] == 1); } +namespace { + +// Private (CityProcessing.pas implementation-section) support types/state/ +// helpers feeding getCityReport()/getCityReportNew() - not part of the +// original's interface section, so not exposed in CityProcessing.h either. + +struct ProdProcessing { + int ProdBonus; + int PollBonus; + int FutProdBonus; + int PollThreshold; +}; + +struct TradeProcessing { + int TaxBonus; + int LuxBonus; + int ScienceBonus; + int FutResBonus; + int ScienceDoubling; + int HappyBase; + double RelCorr; + bool FlexibleLuxury; +}; + +struct CityReportEx { + int BaseHappiness; + int BaseControl; + int Material; + ProdProcessing prodProcessing; + TradeProcessing tradeProcessing; +}; + +// Equivalent of CityProcessing.pas's private `MaxDist` - set by initGame(). +int maxDist = 0; + +void determineCityProdProcessing(int p, int cix, ProdProcessing &prodProcessing) +{ + const TCity &city = (*Database::rw[p].City)[cix]; + prodProcessing.ProdBonus = 0; + prodProcessing.PollBonus = 0; + if (city.Built[imFactory] == 1) + ++prodProcessing.ProdBonus; + if (city.Built[imMfgPlant] == 1) + ++prodProcessing.ProdBonus; + if (city.Built[imPower] == 1 || city.Built[imHydro] == 1 || city.Built[imNuclear] == 1 || + Database::gWonder[woHoover].EffectiveOwner == p) + prodProcessing.ProdBonus *= 2; + if (city.Built[imFactory] == 1) + ++prodProcessing.PollBonus; + if (city.Built[imMfgPlant] == 1) + ++prodProcessing.PollBonus; + if (city.Built[imFactory] + city.Built[imMfgPlant] > 0) { + if (city.Built[imHydro] > 0 || Database::gWonder[woHoover].EffectiveOwner == p) + --prodProcessing.PollBonus; + else if (city.Built[imNuclear] == 0 && city.Built[imPower] == 1) + ++prodProcessing.PollBonus; + } + if (Database::rw[p].Government <= gDespotism || city.Built[imRecycling] == 1) + prodProcessing.PollBonus = -2; // no pollution + prodProcessing.PollThreshold = city.Size; + prodProcessing.FutProdBonus = 0; + if (Database::rw[p].Tech[futProductionTechnology] > 0) { // future tech benefits + if (city.Built[imFactory] == 1) + prodProcessing.FutProdBonus += FactoryFutureBonus * Database::rw[p].Tech[futProductionTechnology]; + if (city.Built[imMfgPlant] == 1) + prodProcessing.FutProdBonus += MfgPlantFutureBonus * Database::rw[p].Tech[futProductionTechnology]; + } +} + +void boostProd(int baseProd, const ProdProcessing &prodProcessing, int &prod, int &poll) +{ + poll = (baseProd * (2 + prodProcessing.PollBonus)) >> 1; + if (poll <= prodProcessing.PollThreshold) + poll = 0; + else + poll -= prodProcessing.PollThreshold; + if (prodProcessing.FutProdBonus > 0) + prod = baseProd * (100 + prodProcessing.ProdBonus * 50 + prodProcessing.FutProdBonus) / 100; + else + prod = (baseProd * (2 + prodProcessing.ProdBonus)) >> 1; +} + +void determineCityTradeProcessing(int p, int cix, int happinessBeforeLux, TradeProcessing &tradeProcessing) +{ + const TCity &city = (*Database::rw[p].City)[cix]; + tradeProcessing.TaxBonus = 0; + tradeProcessing.ScienceBonus = 0; + if (city.Built[imMarket] == 1) + tradeProcessing.TaxBonus += 2; + if (city.Built[imBank] == 1) { + tradeProcessing.TaxBonus += 3; + if (Database::rw[p].NatBuilt[imStockEx - nWonder] == 1) + tradeProcessing.TaxBonus += 3; + } + tradeProcessing.LuxBonus = tradeProcessing.TaxBonus; + if (city.Built[imLibrary] == 1) + tradeProcessing.ScienceBonus += 2; + if (city.Built[imUniversity] == 1) + tradeProcessing.ScienceBonus += 3; + if (city.Built[imResLab] == 1) + tradeProcessing.ScienceBonus += 3; + tradeProcessing.ScienceDoubling = 0; + if (city.Built[imNatObs] > 0) + ++tradeProcessing.ScienceDoubling; + if (Database::rw[p].Government == gFundamentalism) + --tradeProcessing.ScienceDoubling; + else if (Database::gWonder[woNewton].EffectiveOwner == p && Database::rw[p].Government == gMonarchy) + ++tradeProcessing.ScienceDoubling; + + const bool newLiberty = Database::serverVersion[p] >= 0x0100F1 && Database::gWonder[woLiberty].EffectiveOwner == p; + const bool oldMich = Database::serverVersion[p] < 0x0100F1 && Database::gWonder[woMich].EffectiveOwner == p; + tradeProcessing.FlexibleLuxury = (newLiberty || oldMich) && Database::rw[p].Government != gAnarchy; + + tradeProcessing.FutResBonus = 0; + if (Database::rw[p].Tech[futResearchTechnology] > 0) { // future tech benefits + if (city.Built[imUniversity] == 1) + tradeProcessing.FutResBonus += UniversityFutureBonus * Database::rw[p].Tech[futResearchTechnology]; + if (city.Built[imResLab] == 1) + tradeProcessing.FutResBonus += ResLabFutureBonus * Database::rw[p].Tech[futResearchTechnology]; + } + + if (Database::rw[p].NatBuilt[imPalace - nWonder] > 0 || Database::serverVersion[p] < 0x010000) { + // calculate corruption + int dist = maxDist; + for (int i = 0; i < Database::rw[p].nCity; ++i) { + const TCity &otherCity = (*Database::rw[p].City)[i]; + if (otherCity.Loc >= 0 && otherCity.Built[imPalace] == 1) + dist = Database::distance(city.Loc, otherCity.Loc); + } + if (dist == 0 || CorrLevel[Database::rw[p].Government] == 0) { + tradeProcessing.RelCorr = 0.0; + } else { + tradeProcessing.RelCorr = static_cast(dist) / maxDist; + if (CorrLevel[Database::rw[p].Government] > 1) + tradeProcessing.RelCorr = std::exp(std::log(tradeProcessing.RelCorr) / CorrLevel[Database::rw[p].Government]); + if (city.Built[imCourt] == 1) + tradeProcessing.RelCorr /= 2; + } + } else if (city.Built[imCourt] == 1) { + tradeProcessing.RelCorr = 0.5; + } else { + tradeProcessing.RelCorr = 1.0; + } + tradeProcessing.HappyBase = city.Size + happinessBeforeLux; +} + +void splitTrade(int trade, int taxRate, int luxRate, int working, const TradeProcessing &tradeProcessing, + int &corruption, int &tax, int &lux, int &science) +{ + corruption = static_cast(trade * tradeProcessing.RelCorr); + tax = (taxRate * (trade - corruption) + 50) / 100; + if (tradeProcessing.FlexibleLuxury) { + const int plus = working * 2 - tradeProcessing.HappyBase; // required additional luxury + if (plus > 0) { + lux = (4 * plus + 3 + tradeProcessing.LuxBonus) / (4 + tradeProcessing.LuxBonus); + if (lux > trade - corruption) + lux = trade - corruption; + if (tax > trade - corruption - lux) + tax = trade - corruption - lux; + } else { + lux = 0; + } + } else if (luxRate == 0 || taxRate == 100) { + lux = 0; + } else { + lux = (luxRate * (trade - corruption) + 49) / 100; + } + science = trade - corruption - lux - tax; + tax = (tax * (4 + tradeProcessing.TaxBonus)) >> 2; + lux = (lux * (4 + tradeProcessing.LuxBonus)) >> 2; + if (tradeProcessing.FutResBonus > 0) + science = science * (100 + tradeProcessing.ScienceBonus * 25 + tradeProcessing.FutResBonus) / 100; + else + science = (science * (4 + tradeProcessing.ScienceBonus)) >> 2; + science = (science << 2) >> (2 - tradeProcessing.ScienceDoubling); +} + +int getProjectCost(int p, int cix) +{ + const TCity &city = (*Database::rw[p].City)[cix]; + int result; + if ((city.Project & cpImp) == 0) { + const TModel &model = (*Database::rw[p].Model)[city.Project & cpIndex]; + result = model.Cost; // unit project + if (city.Project & cpConscripts) { + const int mCost = model.MCost; + result -= 3 * mCost; + if (result <= 0) + result = mCost; + } else if (model.Cap[mcLine] > 0) { + if ((city.Project0 & (~cpAuto | cpRepeat)) == ((city.Project & ~cpAuto) | cpRepeat)) + result >>= 1; + else + result *= 2; + } + } else { // improvement project + result = Imp[city.Project & cpIndex].Cost; + if ((city.Project & cpIndex) < nWonder && Database::gWonder[woColossus].EffectiveOwner == p) + result = result * ColossusEffect / 100; + } + result = result * BuildCostMod[Database::difficulty[p]] / 12; + return result; +} + +int getSmallCityReport(int p, int cix, TCityReport &cityReport, CityReportEx *cityReportEx = nullptr) +{ + const TCity &city = (*Database::rw[p].City)[cix]; + + if (cityReport.HypoTiles <= 0) + cityReport.HypoTiles = static_cast(city.Tiles); + if (cityReport.HypoTax < 0) + cityReport.HypoTax = Database::rw[p].TaxRate; + if (cityReport.HypoLux < 0) + cityReport.HypoLux = Database::rw[p].LuxRate; + + int baseHappiness; + int control; + + if ((city.Flags & chCaptured) != 0 || Database::rw[p].Government == gAnarchy) { + cityReport.Working = 0; + for (int v21 = 1; v21 <= 26; ++v21) + if (cityReport.HypoTiles & (1 << v21)) + ++cityReport.Working; // for backward compatibility + + if (Database::rw[p].Government == gFundamentalism) { // !!! old bug, kept for compatibility + cityReport.Happy = city.Size; + control = city.Size; + } else { + cityReport.Happy = 0; + control = 0; + } + + baseHappiness = BasicHappy * 2; + cityReport.Support = 0; + cityReport.Deployed = 0; + cityReport.Eaten = city.Size * 2; + cityReport.FoodRep = city.Size * 2; + cityReport.ProdRep = 0; + cityReport.Trade = 0; + cityReport.PollRep = 0; + cityReport.Corruption = 0; + cityReport.Tax = 0; + cityReport.Lux = 0; + cityReport.Science = 0; + + if (cityReportEx) { + cityReportEx->Material = cityReport.ProdRep; + cityReportEx->BaseHappiness = baseHappiness; + cityReportEx->BaseControl = control; + } + } else { // not captured, no anarchy + control = 0; + baseHappiness = BasicHappy * 2; + cityReport.Happy = BasicHappy; + if (city.Built[imColosseum] > 0) { + if (cityReport.Happy < (city.Size + 1) >> 1) + cityReport.Happy = (city.Size + 1) >> 1; + if (city.Size > 4) + baseHappiness = city.Size; + } + for (int i = 0; i < nWonder; ++i) + if (city.Built[i] == 1) { + ++cityReport.Happy; + baseHappiness += 2; + } + if (city.Built[imTemple] == 1) { + ++cityReport.Happy; + baseHappiness += 2; + } + if (city.Built[imCathedral] == 1) { + cityReport.Happy += 2; + baseHappiness += 4; + if (Database::gWonder[woBach].EffectiveOwner == p) { + ++cityReport.Happy; + baseHappiness += 2; + } + } + if (city.Built[imTheater] > 0) { + cityReport.Happy += 2; + baseHappiness += 4; + } + + // calculate unit support + cityReport.Support = 0; + int forcedSupport = 0; + cityReport.Eaten = city.Size * 2; + cityReport.Deployed = 0; + const TUn *un = *Database::rw[p].Un; + for (int uix = 0; uix < Database::rw[p].nUn; ++uix) { + if (un[uix].Loc >= 0 && un[uix].Home == cix) { + TUnitReport unitReport; + Database::getUnitReport(p, uix, unitReport); + cityReport.Eaten += unitReport.FoodSupport; + if (unitReport.ReportFlags & urfAlwaysSupport) + forcedSupport += unitReport.ProdSupport; + else + cityReport.Support += unitReport.ProdSupport; + if (unitReport.ReportFlags & urfDeployed) + ++cityReport.Deployed; + } + } + if (cityReport.Deployed >= cityReport.Happy) + cityReport.Happy = 0; + else + cityReport.Happy -= cityReport.Deployed; + cityReport.Support -= (city.Size * SupportFree[Database::rw[p].Government]) >> 1; + if (cityReport.Support < 0) + cityReport.Support = 0; + cityReport.Support += forcedSupport; + + // control + switch (Database::rw[p].Government) { + case gDespotism: + for (int uix = 0; uix < Database::rw[p].nUn; ++uix) + if (un[uix].Loc == city.Loc && (*Database::rw[p].Model)[un[uix].mix].Kind == mkSpecial_TownGuard) { + ++cityReport.Happy; + control += 2; + } + break; + case gFundamentalism: + baseHappiness = 0; // done by control + cityReport.Happy = city.Size; + control = city.Size; + break; + } + + // collect processing parameters + ProdProcessing prodProcessing; + TradeProcessing tradeProcessing; + determineCityProdProcessing(p, cix, prodProcessing); + determineCityTradeProcessing(p, cix, baseHappiness + control - 2 * cityReport.Deployed, tradeProcessing); + + // collect resources + cityReport.Working = 0; + cityReport.FoodRep = 0; + cityReport.ProdRep = 0; + cityReport.Trade = 0; + int rareOK[4] = {0, 0, 0, 0}; + Database::Vicinity21Loc radius; + Database::v21ToLoc(city.Loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + if (cityReport.HypoTiles & (1 << v21)) { // sum resources of exploited tiles + const int loc1 = radius[v21]; + if (loc1 < 0 || loc1 >= Database::mapSize) // HypoTiles go beyond map border! + return eInvalid; + TTileInfo tileInfo; + Database::getTileInfo(p, cix, loc1, tileInfo); + cityReport.FoodRep += tileInfo.Food; + cityReport.ProdRep += tileInfo.Prod; + cityReport.Trade += tileInfo.Trade; + if ((Database::realMap[loc1] & fModern) != 0 && Database::rw[p].Tech[adMassProduction] >= tsApplicable) + ++rareOK[(Database::realMap[loc1] >> 25) & 3]; + ++cityReport.Working; + } + } + if (city.Built[imAlgae] == 1) + cityReport.FoodRep += 12; + + if (cityReportEx) { + cityReportEx->Material = cityReport.ProdRep; + cityReportEx->BaseHappiness = baseHappiness; + cityReportEx->BaseControl = control; + cityReportEx->prodProcessing = prodProcessing; + cityReportEx->tradeProcessing = tradeProcessing; + } + + boostProd(cityReport.ProdRep, prodProcessing, cityReport.ProdRep, cityReport.PollRep); + splitTrade(cityReport.Trade, cityReport.HypoTax, cityReport.HypoLux, cityReport.Working, tradeProcessing, + cityReport.Corruption, cityReport.Tax, cityReport.Lux, cityReport.Science); + // new style disorder requires 1 lux less for cities with odd size + cityReport.Happy += (cityReport.Lux + (city.Size & 1)) >> 1; + + // check if rare resource available + if ((Database::gTestFlags & tfNoRareNeed) == 0 && cityReport.ProdRep > cityReport.Support && + (city.Project & cpImp) != 0 && + (((city.Project & cpIndex) == imShipComp && rareOK[1] == 0) || + ((city.Project & cpIndex) == imShipPow && rareOK[2] == 0) || + ((city.Project & cpIndex) == imShipHab && rareOK[3] == 0))) + cityReport.ProdRep = cityReport.Support; + } + + return eOK; +} + +// Best tile unused but available by city cix. +void nextBest(int p, int cix, int &selectedLoc, int &selectedV21) +{ + int most = 0; + selectedLoc = -1; + selectedV21 = -1; + const TCity &city = (*Database::rw[p].City)[cix]; + Database::Vicinity21Loc radius; + Database::v21ToLoc(city.Loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + const int loc1 = radius[v21]; + if (loc1 < 0 || loc1 >= Database::mapSize || Database::usedByCity[loc1] != -1) + continue; + const int p1 = static_cast(Database::realMap[loc1] >> 27); + if ((p1 == nPl || p1 == p || Database::rw[p].Treaty[p1] < trPeace) && + (Database::zocMap[loc1] == 0 || Database::occupant[loc1] == p || + Database::rw[p].Treaty[Database::occupant[loc1]] == trAlliance)) { + TTileInfo tileInfo; + Database::getTileInfo(p, cix, loc1, tileInfo); + // priority: 1.food - 2.prod - 3.trade + const int resources = (tileInfo.Food << 16) + (tileInfo.Prod << 8) + tileInfo.Trade; + if (resources > most) { + selectedLoc = loc1; + selectedV21 = v21; + most = resources; + } + } + } +} + +// Worst tile used by city cix. +void nextWorst(int p, int cix, int &selectedLoc, int &selectedV21) +{ + int least = std::numeric_limits::max(); + selectedLoc = -1; + selectedV21 = -1; + const TCity &city = (*Database::rw[p].City)[cix]; + Database::Vicinity21Loc radius; + Database::v21ToLoc(city.Loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + if (v21 == Database::CityOwnTile) + continue; + const int loc1 = radius[v21]; + if (loc1 >= 0 && loc1 < Database::mapSize && (city.Tiles & (1u << v21)) != 0) { + TTileInfo tileInfo; + Database::getTileInfo(p, cix, loc1, tileInfo); + // priority: 1.food - 2.prod - 3.trade + const int resources = (tileInfo.Food << 16) + (tileInfo.Prod << 8) + tileInfo.Trade; + if (resources < least) { + selectedLoc = loc1; + selectedV21 = v21; + least = resources; + } + } + } +} + +int nextPoll(int p, int cix) +{ + int bestDist = std::numeric_limits::max(); + int best = 0; + int result = -1; + const TCity &city = (*Database::rw[p].City)[cix]; + Database::Vicinity21Loc radius; + Database::v21ToLoc(city.Loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + if (v21 == Database::CityOwnTile) + continue; + const int loc1 = radius[v21]; + if (loc1 >= 0 && loc1 < Database::mapSize && (Database::realMap[loc1] & fTerrain) >= fGrass && + (Database::realMap[loc1] & (fPoll | fDeadLands | fCity)) == 0) { + const int pTerr = static_cast(Database::realMap[loc1] >> 27); + if (pTerr == nPl || pTerr == p || Database::rw[p].Treaty[pTerr] < trPeace) { + TTileInfo tileInfo; + Database::getTileInfo(p, cix, loc1, tileInfo); + // priority: 1.prod - 2.trade - 3.food + const int resources = (tileInfo.Prod << 16) + (tileInfo.Trade << 8) + tileInfo.Food; + const int dy = (v21 >> 2) - 3; + const int dx = (((v21 & 3) << 1) - 3) + ((dy + 3) & 1); + const int dist = std::abs(dx) + std::abs(dy) + (std::abs(std::abs(dx) - std::abs(dy)) >> 1); + if (resources > best || (resources == best && dist < bestDist)) { + result = loc1; + best = resources; + bestDist = dist; + } + } + } + } + return result; +} + +} // namespace + +int getCityReport(int p, int cix, TCityReport &cityReport) +{ + const int result = getSmallCityReport(p, cix, cityReport); + cityReport.Storage = StorageSize[Database::difficulty[p]]; + cityReport.ProdCost = getProjectCost(p, cix); + return result; +} + +int getCityReportNew(int p, int cix, TCityReportNew &cityReportNew) +{ + TCityReport cityReport{}; + CityReportEx cityReportEx{}; + cityReport.HypoTiles = cityReportNew.HypoTiles; + cityReport.HypoTax = cityReportNew.HypoTaxRate; + cityReport.HypoLux = cityReportNew.HypoLuxuryRate; + const int result = getSmallCityReport(p, cix, cityReport, &cityReportEx); + + const TCity &city = (*Database::rw[p].City)[cix]; + cityReportNew.FoodSupport = cityReport.Eaten - 2 * city.Size; + cityReportNew.MaterialSupport = cityReport.Support; + cityReportNew.ProjectCost = getProjectCost(p, cix); + cityReportNew.Storage = StorageSize[Database::difficulty[p]]; + cityReportNew.Deployed = cityReport.Deployed; + cityReportNew.Morale = cityReportEx.BaseHappiness; + cityReportNew.CollectedControl = cityReportEx.BaseControl + (city.Size - cityReport.Working) * 2; + cityReportNew.CollectedFood = cityReport.FoodRep; + cityReportNew.CollectedMaterial = cityReportEx.Material; + cityReportNew.CollectedTrade = cityReport.Trade; + cityReportNew.Working = cityReport.Working; + cityReportNew.Production = cityReport.ProdRep - cityReport.Support; + cityReportNew.AddPollution = cityReport.PollRep; + cityReportNew.Corruption = cityReport.Corruption; + cityReportNew.Tax = cityReport.Tax; + cityReportNew.Science = cityReport.Science; + cityReportNew.Luxury = cityReport.Lux; + cityReportNew.FoodSurplus = cityReport.FoodRep - cityReport.Eaten; + cityReportNew.HappinessBalance = + cityReportNew.Morale + cityReportNew.Luxury + cityReportNew.CollectedControl - city.Size - 2 * cityReportNew.Deployed; + return result; +} + +bool addBestCityTile(int p, int cix) +{ + int tileLoc, v21; + nextBest(p, cix, tileLoc, v21); + const bool result = tileLoc >= 0; + if (result) { + TCity &city = (*Database::rw[p].City)[cix]; + assert((city.Tiles & (1u << v21)) == 0); + city.Tiles |= (1u << v21); + Database::usedByCity[tileLoc] = city.Loc; + } + return result; +} + +void cityGrowth(int p, int cix) +{ + TCity &city = (*Database::rw[p].City)[cix]; + ++city.Size; + int tileLoc, v21; + nextBest(p, cix, tileLoc, v21); + if (tileLoc >= 0) { // test whether exploitation of tile would lead to disorder + TCityReport altCityReport{}; + altCityReport.HypoTiles = static_cast(city.Tiles) + (1 << v21); + altCityReport.HypoTax = -1; + altCityReport.HypoLux = -1; + getSmallCityReport(p, cix, altCityReport); + if (altCityReport.Working - altCityReport.Happy <= city.Size >> 1) { + // !!! change to new style disorder + // no disorder -- exploit tile + assert((city.Tiles & (1u << v21)) == 0); + city.Tiles |= (1u << v21); + Database::usedByCity[tileLoc] = city.Loc; + } + } +} + +void cityShrink(int p, int cix) +{ + TCity &city = (*Database::rw[p].City)[cix]; + int working = 0; + for (int v21 = 1; v21 <= 26; ++v21) + if (city.Tiles & (1u << v21)) + ++working; + --city.Size; + if (city.Food > StorageSize[Database::difficulty[p]]) + city.Food = static_cast(StorageSize[Database::difficulty[p]]); + + int tileLoc, v21; + nextWorst(p, cix, tileLoc, v21); + if (working > city.Size) { // all citizens were working -- worst tile no longer exploited + assert((city.Tiles & (1u << v21)) != 0); + city.Tiles &= ~(1u << v21); + Database::usedByCity[tileLoc] = -1; + } else { // test whether exploitation of tile would lead to disorder + TCityReport altCityReport{}; + altCityReport.HypoTiles = -1; + altCityReport.HypoTax = -1; + altCityReport.HypoLux = -1; + getSmallCityReport(p, cix, altCityReport); + if (altCityReport.Working - altCityReport.Happy > city.Size >> 1) { + // !!! change to new style disorder + // disorder -- don't exploit tile + assert((city.Tiles & (1u << v21)) != 0); + city.Tiles &= ~(1u << v21); + Database::usedByCity[tileLoc] = -1; + } + } +} + +void pollute(int p, int cix) +{ + TCity &city = (*Database::rw[p].City)[cix]; + city.Pollution = static_cast(city.Pollution - MaxPollution); + const int pollutionLoc = nextPoll(p, cix); + if (pollutionLoc >= 0) { + city.Flags += chPollution; + Database::realMap[pollutionLoc] |= fPoll; + } +} + +void payCityMaintenance(int p, int cix) +{ + TPlayerContext &player = Database::rw[p]; + TCity &city = (*player.City)[cix]; + for (int i = nWonder; i < nImp; ++i) { + if (city.Built[i] > 0 && (city.Project0 & (cpImp | cpIndex)) != (cpImp | i)) { + // don't pay maintenance when just completed + player.Money -= Imp[i].Maint; + if (player.Money < 0) { // out of money - sell improvement + player.Money += Imp[i].Cost * BuildCostMod[Database::difficulty[p]] / 12; + city.Built[i] = 0; + if (Imp[i].Kind != ikCommon) { + assert(i != imSpacePort); // never sell automatically! (solution: no maintenance) + player.NatBuilt[i - nWonder] = 0; + if (i == imGrWall) + Database::grWallContinent[p] = -1; + } + city.Flags += chImprovementLost; + } + } + } +} + +void collectCityResources(int p, int cix) +{ + TPlayerContext &player = Database::rw[p]; + TCity &city = (*player.City)[cix]; + + if (city.Flags & chCaptured) { + city.Flags &= ~static_cast(chDisorder); + city.Flags -= 0x10000; + if ((city.Flags & chCaptured) == 0) + city.Flags |= chAfterCapture; + } else if (player.Government == gAnarchy) { + city.Flags &= ~static_cast(chDisorder); + } else { + TCityReportNew cityReport{}; + cityReport.HypoTiles = -1; + cityReport.HypoTaxRate = -1; + cityReport.HypoLuxuryRate = -1; + getCityReportNew(p, cix, cityReport); + const int cityStorage = StorageSize[Database::difficulty[p]]; + const int cityProjectCost = getProjectCost(p, cix); + + const bool disorder = cityReport.HappinessBalance < 0; + if (disorder && (city.Flags & chDisorder)) + cityReport.CollectedMaterial = 0; // second turn disorder + if (disorder) + city.Flags |= chDisorder; + else + city.Flags &= ~static_cast(chDisorder); + + if (!disorder && + ((player.Government == gFuture) || (city.Size >= NeedAqueductSize && cityReport.FoodSurplus < 2)) && + cityReport.FoodSurplus > 0) { + player.Money += cityReport.FoodSurplus; + } else if (!(disorder && cityReport.FoodSurplus > 0)) { // calculate new food storage + city.Food = static_cast(city.Food + cityReport.FoodSurplus); + if (((Database::gTestFlags & tfImmGrow) != 0 || + (city.Food >= cityStorage && city.Food - cityReport.FoodSurplus < cityStorage)) && // only warn once + city.Size < MaxCitySize && (city.Project & (cpImp + cpIndex)) != cpImp + imAqueduct && + (city.Project & (cpImp + cpIndex)) != cpImp + imSewer && !canCityGrow(p, cix)) + city.Flags += chNoGrowthWarning; + } + + if (city.Prod > cityProjectCost) { + player.Money += city.Prod - cityProjectCost; + city.Prod = static_cast(cityProjectCost); + } + if (cityReport.Production < 0) { + city.Flags |= chUnitLost; + } else if (!disorder && (city.Flags & chProductionSabotaged) == 0) { + if ((city.Project & (cpImp + cpIndex)) == cpImp + imTrGoods) + player.Money += cityReport.Production; + else + city.Prod = static_cast(city.Prod + cityReport.Production); + } + + if (!disorder) { // sum research points and taxes + player.Research += cityReport.Science; + player.Money += cityReport.Tax; + city.Pollution = static_cast(city.Pollution + cityReport.AddPollution); + } + } +} + +bool cityTurn(int p, int cix) +{ + // return value: whether city keeps existing + TPlayerContext &player = Database::rw[p]; + TCity &city = (*player.City)[cix]; + + int sizeMod = 0; + const int cityStorage = StorageSize[Database::difficulty[p]]; + const int cityProjectCost = getProjectCost(p, cix); + + const bool lackOfMaterial = (city.Flags & chUnitLost) != 0; + city.Flags &= ~static_cast(chUnitLost); + + const bool isActive = player.Government != gAnarchy && (city.Flags & chCaptured) == 0; + const bool checkGrow = (city.Flags & chDisorder) == 0 && isActive && player.Government != gFuture; + + TUn *un = *player.Un; + const TModel *model = *player.Model; + + if (checkGrow && (Database::gTestFlags & tfImmGrow) != 0) { // fast growth + if (canCityGrow(p, cix)) + ++sizeMod; + } else if (checkGrow && city.Food >= cityStorage) { // normal growth + if (canCityGrow(p, cix)) { + if (city.Built[imGranary] == 1) + city.Food = static_cast(city.Food - (cityStorage >> 1)); + else + city.Food = static_cast(city.Food - cityStorage); + ++sizeMod; + } + } else if (city.Food < 0) { // famine + city.Food = 0; + // check if settlers or conscripts there to disband + int uix = -1; + for (int i = 0; i < player.nUn; ++i) { + if (un[i].Loc >= 0 && un[i].Home == cix && + (model[un[i].mix].Kind == mkSettler || (un[i].Flags & unConscripts) != 0) && + (uix == -1 || model[un[i].mix].Cost < model[un[uix].mix].Cost || + (model[un[i].mix].Cost == model[un[uix].mix].Cost && un[i].Exp < un[uix].Exp))) + uix = i; + } + if (uix >= 0) { + Database::removeUnitUpdateMap(p, uix); + city.Flags += chUnitLost; + } else { + --sizeMod; + city.Flags += chPopDecrease; + } + } + if (city.Food > cityStorage) + city.Food = static_cast(cityStorage); + + if (lackOfMaterial && (city.Flags & chUnitLost) == 0) { // one unit lost + int uix = -1; + int det = std::numeric_limits::max(); + for (int i = 0; i < player.nUn; ++i) { + if (un[i].Loc >= 0 && un[i].Home == cix) { + const TModel &m = model[un[i].mix]; + int testDet; + if (m.Kind == mkSpecial_TownGuard) + testDet = un[i].Health + (un[i].Exp << 8); // disband townguards first + else { + testDet = un[i].Health + (un[i].Exp << 8) + (m.Cost << 16); // value of unit + if (m.Flags & mdDoubleSupport) + testDet >>= 1; // double support, tend to disband first + } + if (testDet < det) { + uix = i; + det = testDet; + } + } + } + if (uix >= 0) { + Database::removeUnitUpdateMap(p, uix); + city.Flags += chUnitLost; + } + } + + if (Database::gTestFlags & tfImmImprove) + city.Prod = static_cast(cityProjectCost); + bool doProd = (city.Project & (cpImp + cpIndex)) != cpImp + imTrGoods && city.Prod >= cityProjectCost; + + // check if wonder already built + if ((city.Project & cpImp) != 0 && (city.Project & cpIndex) < nWonder && + Database::gWonder[city.Project & cpIndex].CityID != WonderNotBuiltYet) { + city.Flags += chOldWonder; + doProd = false; + } + + // check if producing settlers would disband city + if (doProd && (city.Project & (cpImp | cpDisbandCity)) == 0 && + ((city.Size + sizeMod - 2 < 2 && model[city.Project & cpIndex].Kind == mkSettler) || + (city.Size + sizeMod - 1 < 2 && (model[city.Project & cpIndex].Kind == mkSlaves || + (city.Project & cpConscripts) != 0)))) { + city.Flags += chNoSettlerProd; + doProd = false; + } + + if (doProd) { // project complete + city.Prod = static_cast(city.Prod - cityProjectCost); + if ((city.Project & cpImp) == 0) { // produce unit + if (player.nUn < Database::neumax) { + Database::createUnit(p, city.Project & cpIndex); + un[player.nUn - 1].Loc = city.Loc; + TUn &newUn = un[player.nUn - 1]; + newUn.Home = static_cast(cix); + if (model[newUn.mix].Domain < dSea && city.Built[imElite] == 1) + newUn.Exp = static_cast(ExpCost * (nExp - 1)); // elite + else if ((model[newUn.mix].Domain < dSea && city.Built[imBarracks] == 1) || + (model[newUn.mix].Domain == dSea && city.Built[imDockyard] == 1) || + (model[newUn.mix].Domain == dAir && city.Built[imAirport] == 1)) + newUn.Exp = static_cast(ExpCost * 2); // vet + if (city.Project & cpConscripts) + newUn.Flags |= unConscripts; + Database::placeUnit(p, player.nUn - 1); + Database::updateUnitMap(city.Loc); + if (model[city.Project & cpIndex].Kind == mkSettler) + sizeMod -= 2; // settler produced - city shrink + else if (model[city.Project & cpIndex].Kind == mkSlaves || (city.Project & cpConscripts) != 0) + --sizeMod; // slaves/conscripts produced - city shrink + } + city.Project0 = static_cast(city.Project | cpRepeat | cpCompleted); + } else if (Imp[city.Project & cpIndex].Kind == ikShipPart) { // produce ship parts + ++Database::gShip[p].Parts[(city.Project & cpIndex) - imShipComp]; + city.Project0 = static_cast(city.Project | cpCompleted); + } else { // produce improvement + const int newImp = city.Project & cpIndex; + player.Money += city.Prod; // change rest to money + city.Project0 = static_cast(city.Project | cpCompleted); + city.Project = cpImp + imTrGoods; + city.Prod = 0; + + if (Imp[newImp].Kind == ikNatLocal || Imp[newImp].Kind == ikNatGlobal) { // nat. project + TCity *allCities = *player.City; + for (int i = 0; i < player.nCity; ++i) { + if (allCities[i].Loc >= 0 && allCities[i].Built[newImp] == 1) { // allowed only once + player.Money += Imp[newImp].Cost * BuildCostMod[Database::difficulty[p]] / 12; + allCities[i].Built[newImp] = 0; + } + } + player.NatBuilt[newImp - nWonder] = 1; + + // immediate nat. project effects + if (newImp == imGrWall) + Database::grWallContinent[p] = Database::continent[city.Loc]; + } + + if (newImp < nWonder) { // wonder + Database::gWonder[newImp].CityID = city.ID; + Database::gWonder[newImp].EffectiveOwner = p; + Database::checkExpiration(newImp); + + // immediate wonder effects + if (newImp == woEiffel) { // reactivate wonders + TCity *allCities = *player.City; + for (int i = 0; i < nWonder; ++i) + if (Imp[i].Expiration >= 0) + for (int cix2 = 0; cix2 < player.nCity; ++cix2) + if (allCities[cix2].Loc >= 0 && allCities[cix2].Built[i] == 1) + Database::gWonder[i].EffectiveOwner = p; + } else if (newImp == woLighthouse) { + Database::checkSpecialModels(p, preLighthouse); + } else if (newImp == woLeo) { + player.Research += Database::techBaseCost(Database::nTech[p], Database::difficulty[p]) + + Database::techBaseCost(Database::nTech[p] + 2, Database::difficulty[p]); + Database::checkSpecialModels(p, preLeo); + } else if (newImp == woPyramids) { + Database::checkSpecialModels(p, preBuilder); + } else if (newImp == woMir) { + for (int p1 = 0; p1 < nPl; ++p1) { + if (p1 != p && (Database::gAlive & (1 << p1))) { + if (player.Treaty[p1] == trNoContact) + Database::introduceEnemy(p, p1); + Database::giveCivilReport(p, p1); + Database::giveMilReport(p, p1); + } + } + } + } + + for (int i = 0; i < nImpReplacement; ++i) // sell obsolete buildings + if (ImpReplacement[i].NewImp == newImp && city.Built[ImpReplacement[i].OldImp] > 0) { + player.Money += Imp[ImpReplacement[i].OldImp].Cost * BuildCostMod[Database::difficulty[p]] / 12; + city.Built[ImpReplacement[i].OldImp] = 0; + } + + if (newImp == imPower || newImp == imHydro || newImp == imNuclear) { + for (int i = 0; i < nImp; ++i) { + if (i != newImp && (i == imPower || i == imHydro || i == imNuclear) && city.Built[i] > 0) { + // sell obsolete power plant + player.Money += Imp[i].Cost * BuildCostMod[Database::difficulty[p]] / 12; + city.Built[i] = 0; + } + } + } + + city.Built[newImp] = 1; + } + city.Prod0 = city.Prod; + city.Flags += chProduction; + } else { + city.Project0 = static_cast(city.Project0 & ~cpCompleted); + if ((city.Project0 & ~cpAuto) != (city.Project & ~cpAuto)) + city.Project0 = city.Project; + city.Prod0 = city.Prod; + } + + if (sizeMod > 0) { + cityGrowth(p, cix); + city.Flags += chPopIncrease; + } + const bool result = city.Size + sizeMod >= 2; + if (result) { + while (sizeMod < 0) { + cityShrink(p, cix); + ++sizeMod; + } + } + return result; +} + +int setCityTiles(int p, int cix, int newTiles, bool testOnly) +{ + TCity &city = (*Database::rw[p].City)[cix]; + const int changeTiles = newTiles ^ static_cast(city.Tiles); + const int addTiles = newTiles & ~static_cast(city.Tiles); + + if (Database::mode == Database::moPlaying) { // do all checks + if ((newTiles & ~0x67F7F76) != 0) + return eInvalid; // invalid tile index included + if ((newTiles & (1 << 13)) == 0) + return eViolation; // city tile must be exploited + if (changeTiles == 0) + return eNotChanged; + if (addTiles != 0) { + // check if new tiles possible + TCityAreaInfo cityAreaInfo; + getCityAreaInfo(p, city.Loc, cityAreaInfo); + for (int v21 = 1; v21 <= 26; ++v21) + if ((addTiles & (1 << v21)) != 0 && cityAreaInfo.Available[v21] != faAvailable) + return eTileNotAvailable; + // not more tiles than inhabitants + int working = 0; + for (int v21 = 1; v21 <= 26; ++v21) + if (newTiles & (1 << v21)) + ++working; + if (working > city.Size) + return eNoWorkerAvailable; + } + } + + if (!testOnly) { + Database::Vicinity21Loc radius; + Database::v21ToLoc(city.Loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + if (changeTiles & (1 << v21)) { + const int loc1 = radius[v21]; + assert(loc1 >= 0 && loc1 < Database::mapSize); + if (newTiles & (1 << v21)) { + Database::usedByCity[loc1] = city.Loc; // employ tile + } else if (Database::usedByCity[loc1] != city.Loc) { + // should only happen during loading, because of wrong + // sSetCityTiles command order + assert(Database::mode < Database::moPlaying); + } else { + Database::usedByCity[loc1] = -1; // unemploy tile + } + } + } + city.Tiles = static_cast(newTiles); + } + return eOK; +} + +namespace { +// Local to GetCityTileAdvice - equivalent of its nested TTileData record. +struct TileData { + int Food; + int Prod; + int Trade; + int SubValue; + int V21; +}; +} // namespace + +void getCityTileAdvice(int p, int cix, TCityTileAdviceData &advice) +{ + constexpr int oFood = 0, oProd = 1, oTax = 2, oScience = 3; + + TPlayerContext &player = Database::rw[p]; + TCity &city = (*player.City)[cix]; + + if (player.Government == gAnarchy || (city.Flags & chCaptured) != 0) { + advice.CityReport = TCityReport{}; + advice.Tiles = 1u << Database::CityOwnTile; + advice.CityReport.HypoTiles = 1 << Database::CityOwnTile; + return; + } + + // decode evaluation formula from weights parameter + double valueFormulaWeight[4]; + bool valueFormulaMultiply[4]; + for (int i = oFood; i <= oScience; ++i) { + const int formulaCode = static_cast((advice.ResourceWeights >> (24 - 8 * i)) & 0xFF); + valueFormulaMultiply[i] = (formulaCode & 0x80) != 0; + if (formulaCode & 0x40) + valueFormulaWeight[i] = (formulaCode & 0x0F) * (1 << ((formulaCode & 0x30) >> 4)) / 16.0; + else + valueFormulaWeight[i] = (formulaCode & 0x0F) * (1 << ((formulaCode & 0x30) >> 4)); + } + + TCityReport testReport{}; + testReport.HypoTiles = 1 << Database::CityOwnTile; + testReport.HypoTax = -1; + testReport.HypoLux = -1; + CityReportEx cityReportEx{}; + getSmallCityReport(p, cix, testReport, &cityReportEx); + + Database::Vicinity21Loc radius; + Database::v21ToLoc(city.Loc, radius); + const bool foodToTax = player.Government == gFuture; + const bool prodToTax = (city.Project & (cpImp + cpIndex)) == cpImp + imTrGoods; + const bool foodWasted = + !foodToTax && city.Food == StorageSize[Database::difficulty[p]] && !canCityGrow(p, cix); + + // sub criteria + std::array subCriterion{}; // index 0 unused, matches Pascal's 1..26 + for (int v21 = 1; v21 <= 26; ++v21) { + const int loc1 = radius[v21]; + if (loc1 >= 0) + subCriterion[v21] = (3360 - (Database::distance(city.Loc, loc1) - 1) * 32 - v21) ^ 0x15; + } + const TCity *allCities = *player.City; + for (int cix1 = 0; cix1 < player.nCity; ++cix1) { + if (cix1 == cix) + continue; + const int cityLoc1 = allCities[cix1].Loc; + if (cityLoc1 >= 0 && Database::distance(city.Loc, cityLoc1) <= 10) { + // cities overlap -- prefer tiles outside common range + Database::Vicinity21Loc radius1; + Database::v21ToLoc(cityLoc1, radius1); + for (int v21 = 1; v21 <= 26; ++v21) { + const int loc1 = radius1[v21]; + if (loc1 >= 0 && loc1 < Database::mapSize && Database::distance(city.Loc, loc1) <= 5) { + int dx, dy; + Database::dxdy(city.Loc, loc1, dx, dy); + subCriterion[((dy + 3) << 2) + ((dx + 3) >> 1)] -= 160; + } + } + } + } + + TCityAreaInfo cityAreaInfo; + getCityAreaInfo(p, city.Loc, cityAreaInfo); + int areaSize = 0; + for (int v21 = 1; v21 <= 26; ++v21) + if (cityAreaInfo.Available[v21] == faAvailable) + ++areaSize; + + int minWorking, maxWorking; + if (player.Government == gFundamentalism) { + minWorking = city.Size; + maxWorking = city.Size; + } else { + minWorking = cityReportEx.tradeProcessing.HappyBase >> 1; + if (minWorking > city.Size) + minWorking = city.Size; + if (player.LuxRate == 0 && !cityReportEx.tradeProcessing.FlexibleLuxury) + maxWorking = minWorking; + else + maxWorking = city.Size; + } + if (maxWorking > areaSize) { + maxWorking = areaSize; + if (minWorking > areaSize) + minWorking = areaSize; + } + int wantedProd; + if (testReport.Support == 0) + wantedProd = 0; + else + wantedProd = 1 + (testReport.Support * 100 - 1) / + (100 + cityReportEx.prodProcessing.ProdBonus * 50 + cityReportEx.prodProcessing.FutProdBonus); + + // consider resources for ship parts + int needRare = 0; + if ((Database::gTestFlags & tfNoRareNeed) == 0 && (city.Project & cpImp) != 0) { + const int projectIndex = city.Project & cpIndex; + if (projectIndex == imShipComp) + needRare = fCobalt; + else if (projectIndex == imShipPow) + needRare = fUranium; + else if (projectIndex == imShipHab) + needRare = fMercury; + } + int rareTiles = 0; + if (needRare > 0) { + for (int v21 = 1; v21 <= 26; ++v21) { + const int loc1 = radius[v21]; + if (loc1 >= 0 && loc1 < Database::mapSize && + (Database::realMap[loc1] & fModern) == static_cast(needRare)) + rareTiles |= (1 << v21); + } + } + + // step 1: sort tiles to hierarchies + int nHierarchy = 0; + TTileInfo baseTileInfo{}; + std::array nTile{}; + std::array, 21> hierarchy{}; + for (int v21 = 1; v21 <= 26; ++v21) { // non-rare tiles + if (cityAreaInfo.Available[v21] == faAvailable && (needRare == 0 || (rareTiles & (1 << v21)) == 0)) { + const int loc1 = radius[v21]; + assert(loc1 >= 0 && loc1 < Database::mapSize); + TTileInfo tileInfo; + Database::getTileInfo(p, cix, loc1, tileInfo); + if (v21 == Database::CityOwnTile) { + baseTileInfo = tileInfo; + } else { + int iH = 0; + int iT = 0; + while (iH < nHierarchy) { + iT = 0; + while (iT < nTile[iH] && tileInfo.Food <= hierarchy[iH][iT].Food && + tileInfo.Prod <= hierarchy[iH][iT].Prod && tileInfo.Trade <= hierarchy[iH][iT].Trade && + !(tileInfo.Food == hierarchy[iH][iT].Food && tileInfo.Prod == hierarchy[iH][iT].Prod && + tileInfo.Trade == hierarchy[iH][iT].Trade && + subCriterion[v21] >= subCriterion[hierarchy[iH][iT].V21])) + ++iT; + if (iT == nTile[iH] || (tileInfo.Food >= hierarchy[iH][iT].Food && + tileInfo.Prod >= hierarchy[iH][iT].Prod && + tileInfo.Trade >= hierarchy[iH][iT].Trade)) + break; // insert position found! + ++iH; + } + if (iH == nHierarchy) { // need to start new hierarchy + nTile[iH] = 0; + ++nHierarchy; + iT = 0; + } + for (int k = nTile[iH]; k > iT; --k) + hierarchy[iH][k] = hierarchy[iH][k - 1]; + ++nTile[iH]; + hierarchy[iH][iT].V21 = v21; + hierarchy[iH][iT].Food = tileInfo.Food; + hierarchy[iH][iT].Prod = tileInfo.Prod; + hierarchy[iH][iT].Trade = tileInfo.Trade; + hierarchy[iH][iT].SubValue = subCriterion[v21]; + } + } + } + if (needRare != 0) { // rare tiles need own hierarchy + int iH = nHierarchy; + for (int v21 = 1; v21 <= 26; ++v21) { + if (cityAreaInfo.Available[v21] == faAvailable && (rareTiles & (1 << v21)) != 0) { + const int loc1 = radius[v21]; + assert(v21 != Database::CityOwnTile && loc1 >= 0 && loc1 < Database::mapSize); + TTileInfo tileInfo; + Database::getTileInfo(p, cix, loc1, tileInfo); + int iT; + if (iH == nHierarchy) { // need to start new hierarchy + nTile[iH] = 0; + ++nHierarchy; + iT = 0; + } else { + iT = nTile[iH]; + } + ++nTile[iH]; + hierarchy[iH][iT].V21 = v21; + hierarchy[iH][iT].Food = tileInfo.Food; // = 0 + hierarchy[iH][iT].Prod = tileInfo.Prod; // = 1 + hierarchy[iH][iT].Trade = tileInfo.Trade; // = 0 + hierarchy[iH][iT].SubValue = subCriterion[v21]; + } + } + } + if (city.Built[imAlgae] > 0) + baseTileInfo.Food += 12; + + // step 2: summarize resources + for (int iH = 0; iH < nHierarchy; ++iH) { + for (int k = nTile[iH]; k >= 1; --k) + hierarchy[iH][k] = hierarchy[iH][k - 1]; + hierarchy[iH][0].Food = 0; + hierarchy[iH][0].Prod = 0; + hierarchy[iH][0].Trade = 0; + hierarchy[iH][0].SubValue = 0; + hierarchy[iH][0].V21 = 0; + for (int iT = 1; iT <= nTile[iH]; ++iT) { + hierarchy[iH][iT].Food += hierarchy[iH][iT - 1].Food; + hierarchy[iH][iT].Prod += hierarchy[iH][iT - 1].Prod; + hierarchy[iH][iT].Trade += hierarchy[iH][iT - 1].Trade; + hierarchy[iH][iT].SubValue += hierarchy[iH][iT - 1].SubValue; + hierarchy[iH][iT].V21 = (1 << hierarchy[iH][iT].V21) + hierarchy[iH][iT - 1].V21; + } + } + + // step 3: try all combinations + double bestValue = 0.0; + int bestSuperValue = 0; + int bestSubValue = 0; + int bestTiles = 0; + std::array nSelection{}; + testReport.FoodRep = baseTileInfo.Food; + int prodBeforeBoost = baseTileInfo.Prod; + testReport.Trade = baseTileInfo.Trade; + testReport.Working = 1; + int minFood = 0; + int minProd = 0; + int iH_Switch = nHierarchy; + do { + // ensure minima + int iH = 0; + while (testReport.Working < maxWorking && iH < iH_Switch && + (testReport.Working < minWorking || testReport.FoodRep < testReport.Eaten || + prodBeforeBoost < wantedProd)) { + assert(nSelection[iH] == 0); + int take = minWorking - testReport.Working; + if (take > nTile[iH]) { + take = nTile[iH]; + } else { + if (take < 0) + take = 0; + int maxTake = nTile[iH]; + if (testReport.Working + maxTake > maxWorking) + maxTake = maxWorking - testReport.Working; + while (take < maxTake && testReport.FoodRep + hierarchy[iH][take].Food < minFood) + ++take; + while (take < maxTake && prodBeforeBoost + hierarchy[iH][take].Prod < minProd) + ++take; + } + nSelection[iH] = take; + testReport.Working += take; + testReport.FoodRep += hierarchy[iH][take].Food; + prodBeforeBoost += hierarchy[iH][take].Prod; + testReport.Trade += hierarchy[iH][take].Trade; + ++iH; + } + + assert(testReport.Working >= minWorking && testReport.Working <= maxWorking); + if (testReport.FoodRep >= minFood && prodBeforeBoost >= minProd) { + splitTrade(testReport.Trade, player.TaxRate, player.LuxRate, testReport.Working, + cityReportEx.tradeProcessing, testReport.Corruption, testReport.Tax, testReport.Lux, + testReport.Science); + + if (cityReportEx.BaseHappiness + cityReportEx.BaseControl + testReport.Lux + + 2 * (static_cast(city.Size) - testReport.Working) - 2 * testReport.Deployed >= + city.Size) { + // city is not in disorder -- evaluate combination + if (minProd < wantedProd && prodBeforeBoost > minProd) { + // no combination reached wanted prod yet + minProd = prodBeforeBoost; + if (minProd > wantedProd) + minProd = wantedProd; + } + if (minProd == wantedProd) { + // do not care for food before prod is ensured + if (minFood < testReport.Eaten && testReport.FoodRep > minFood) { + // no combination reached wanted food yet + minFood = testReport.FoodRep; + if (minFood > testReport.Eaten) + minFood = testReport.Eaten; + } + } + boostProd(prodBeforeBoost, cityReportEx.prodProcessing, testReport.ProdRep, testReport.PollRep); + int superValue = 0; + + // super-criterion A: unit support granted? + if (testReport.ProdRep >= testReport.Support) + superValue |= (1 << 30); + + // super-criterion B: food demand granted? + if (testReport.FoodRep >= testReport.Eaten) + superValue |= (63 << 24); + else if (testReport.FoodRep > testReport.Eaten - 63) + superValue |= (63 - (testReport.Eaten - testReport.FoodRep)) << 24; + + const int superPlus = superValue - bestSuperValue; + if (superPlus >= 0) { + int output[4]; + output[oTax] = testReport.Tax; + output[oScience] = testReport.Science; + + if (testReport.FoodRep < testReport.Eaten) { + // appreciate what we have, combination will have bad supervalue anyway + output[oFood] = testReport.FoodRep; + } else if (foodWasted) { + output[oFood] = 0; + } else { + output[oFood] = testReport.FoodRep - testReport.Eaten; + if (foodToTax || (city.Size >= NeedAqueductSize && output[oFood] == 1)) { + output[oTax] += output[oFood]; + output[oFood] = 0; + } + } + + if (testReport.ProdRep < testReport.Support) { + // appreciate what we have, combination will have bad supervalue anyway + output[oProd] = testReport.ProdRep; + } else { + if (needRare > 0) { + bool rareOK = false; + for (int ih2 = 0; ih2 < nHierarchy; ++ih2) + if (hierarchy[ih2][nSelection[ih2]].V21 & rareTiles) { + rareOK = true; + break; + } + if (!rareOK) + testReport.ProdRep = testReport.Support; + } + output[oProd] = testReport.ProdRep - testReport.Support; + if (prodToTax) { + output[oTax] += output[oProd]; + output[oProd] = 0; + } + } + + bool needStep2 = false; + double value = 0; + for (int i = oFood; i <= oScience; ++i) { + if (valueFormulaMultiply[i]) + needStep2 = true; + else + value += valueFormulaWeight[i] * output[i]; + } + if (needStep2) { + if (value > 0) + value = std::log(value) + 123; + for (int i = oFood; i <= oScience; ++i) + if (valueFormulaMultiply[i] && output[i] > 0) + value += valueFormulaWeight[i] * (std::log(static_cast(output[i])) + 123); + } + + const double valuePlus = value - bestValue; + if (superPlus > 0 || valuePlus >= 0.0) { + int subValue = (testReport.FoodRep + prodBeforeBoost + testReport.Trade) << 18; + int testTiles = 1 << Database::CityOwnTile; + for (int ih2 = 0; ih2 < nHierarchy; ++ih2) { + testTiles += hierarchy[ih2][nSelection[ih2]].V21; + subValue += hierarchy[ih2][nSelection[ih2]].SubValue; + } + bool isBest = true; + if (superPlus == 0 && valuePlus == 0.0) { + const int subPlus = subValue - bestSubValue; + if (subPlus < 0) { + isBest = false; + } else if (subPlus == 0) { + assert(testTiles != bestTiles); + isBest = testTiles > bestTiles; + } + } + if (isBest) { + bestSuperValue = superValue; + bestValue = value; + bestSubValue = subValue; + bestTiles = testTiles; + testReport.Happy = (cityReportEx.tradeProcessing.HappyBase - city.Size) / 2 + + (testReport.Lux >> 1); + advice.CityReport = testReport; + } + } + } + } + } + + // calculate next combination + iH_Switch = 0; + do { + testReport.FoodRep -= hierarchy[iH_Switch][nSelection[iH_Switch]].Food; + prodBeforeBoost -= hierarchy[iH_Switch][nSelection[iH_Switch]].Prod; + testReport.Trade -= hierarchy[iH_Switch][nSelection[iH_Switch]].Trade; + ++nSelection[iH_Switch]; + ++testReport.Working; + if (nSelection[iH_Switch] <= nTile[iH_Switch] && testReport.Working <= maxWorking) { + testReport.FoodRep += hierarchy[iH_Switch][nSelection[iH_Switch]].Food; + prodBeforeBoost += hierarchy[iH_Switch][nSelection[iH_Switch]].Prod; + testReport.Trade += hierarchy[iH_Switch][nSelection[iH_Switch]].Trade; + break; + } + testReport.Working -= nSelection[iH_Switch]; + nSelection[iH_Switch] = 0; + ++iH_Switch; + } while (iH_Switch != nHierarchy); + } while (iH_Switch != nHierarchy); // everything tested -- done + + assert(bestSuperValue > 0); // advice should always be possible + advice.Tiles = static_cast(bestTiles); + advice.CityReport.HypoTiles = bestTiles; +} + +void initGame() +{ + maxDist = Database::distance(0, Database::mapSize - (Database::lx >> 1)); + for (int p = 0; p < nPl; ++p) { + if (((1 << p) & Database::gAlive) != 0) { + TPlayerContext &player = Database::rw[p]; + const TModel *model = *player.Model; + int mixTownGuard = 0; + while (model[mixTownGuard].Kind != mkSpecial_TownGuard) + ++mixTownGuard; + TCity &city = (*player.City)[0]; // initialize capital + city.Built[imPalace] = 1; + city.Size = 4; + for (int i = 2; i <= city.Size; ++i) + addBestCityTile(p, 0); + city.Project = mixTownGuard; + player.NatBuilt[imPalace - nWonder] = 1; + } + } +} + +void releaseGame() +{ +} + } // namespace CityProcessing } // namespace Cevo diff --git a/game/src/Database.cpp b/game/src/Database.cpp index a814f01..ba13ed4 100644 --- a/game/src/Database.cpp +++ b/game/src/Database.cpp @@ -30,6 +30,7 @@ #include #include +#include #include namespace Cevo { @@ -38,19 +39,66 @@ namespace Database { int lx = 0; int ly = 0; int mapSize = 0; +GameMode mode = moLoading_Fast; +CmdList cl; std::array rw{}; +std::array difficulty{}; +std::array serverVersion{}; +std::array resourceMask{}; +std::array processClientData{}; +std::array discovered{}; +std::array lastValidStat{}; +std::array nTech{}; +int gAlive = 0; +int gWatching = 0; +int gAI = 0; +int gTurn = 0; +int gTestFlags = 0; +std::array gWonder{}; +std::array grWallContinent{}; +std::array gShip{}; +std::array, nPl>, nPl> rwemix{}; +std::array, nPl>, nPl> destroyed{}; std::array realMap{}; +std::array continent{}; std::array occupant{}; std::array zocMap{}; std::array usedByCity{}; +std::array observeLevel{}; namespace { // Equivalent of Database.pas's private (implementation-section) `Primitive` // global - not exposed in the header, matching the original's own // interface/implementation visibility split. int primitive = 0; + +// Equivalent of Database.pas's private `UnBuilt: array[0..nPl-1] of Integer` +// (number of units built, used to assign unique per-player unit IDs). +std::array unBuilt{}; + +// Equivalent of Database.pas's private FreeSlaves(). +void freeSlaves() +{ + for (int p1 = 0; p1 < nPl; ++p1) { + if (gAlive & (1 << p1)) { + TUn *un = *rw[p1].Un; + const TModel *model = *rw[p1].Model; + for (int uix = 0; uix < rw[p1].nUn; ++uix) + if (model[un[uix].mix].Kind == mkSlaves) + un[uix].Job = jNone; + } + } +} + +// Equivalent of Database.pas's private CountLost(). +void countLost(int p, int mix, int enemy) +{ + ++(*rw[p].Model)[mix].Lost; + tellAboutModel(enemy, p, mix); + ++destroyed[enemy][p][mix]; +} } // namespace void maskD(std::uint32_t *x, int count, std::uint32_t mask) @@ -184,5 +232,875 @@ bool mapGeneratorAvailable() return primitive > 0 && lx >= 20 && ly >= 40; } +void searchCity(int loc, int &p, int &cix) +{ + if (realMap[loc] < static_cast(nPl) << 27) + p = static_cast(realMap[loc] >> 27); + for (int i = 0; i < nPl; ++i) { + if ((1 << p) & gAlive) { + TPlayerContext &player = rw[p]; + cix = player.nCity - 1; + while (cix >= 0 && (*player.City)[cix].Loc != loc) + --cix; + if (cix >= 0) + return; + } + assert(i < nPl - 1); + p = (p + 1) % nPl; + } +} + +int unitSpeed(int p, int mix, int health) +{ + const TModel &model = (*rw[p].Model)[mix]; + int result = model.Speed; + if (model.Domain == dSea) { + if (gWonder[woMagellan].EffectiveOwner == p) + result += 200; + if (health < 100) + result = ((result - 250) * health / 5000) * 50 + 250; + } + return result; +} + +void getUnitReport(int p, int uix, TUnitReport &unitReport) +{ + unitReport.FoodSupport = 0; + unitReport.ProdSupport = 0; + unitReport.ReportFlags = 0; + if (rw[p].Government == gAnarchy) + return; + + const TUn &un = (*rw[p].Un)[uix]; + const TModel &model = (*rw[p].Model)[un.mix]; + + if (model.Kind == mkSettler) + unitReport.FoodSupport = SettlerFood[rw[p].Government]; + else if (un.Flags & unConscripts) + unitReport.FoodSupport = 1; + + if (rw[p].Government == gFundamentalism) + return; + + if ((gTestFlags & tfImmImprove) == 0) { + unitReport.ProdSupport = (model.Flags & mdDoubleSupport) ? 2 : 1; + if (model.Kind == mkSpecial_TownGuard) + unitReport.ReportFlags |= urfAlwaysSupport; + } + if ((model.Flags & mdCivil) == 0) { + const int terrOwner = static_cast(realMap[un.Loc] >> 27); + switch (rw[p].Government) { + case gRepublic: + case gFuture: + if (terrOwner != p && terrOwner < nPl && rw[p].Treaty[terrOwner] < trAlliance) + unitReport.ReportFlags |= urfDeployed; + break; + case gDemocracy: + if (terrOwner >= nPl || (terrOwner != p && rw[p].Treaty[terrOwner] < trAlliance)) + unitReport.ReportFlags |= urfDeployed; + break; + } + } +} + +void strongest(int loc, int &uix, int &strength, int &bonus, int &cnt) +{ + const int defender = occupant[loc]; + int cost = 0; + cnt = 0; + int det = -1; + const TUn *defUn = *rw[defender].Un; + const TModel *defModel = *rw[defender].Model; + + for (int uix1 = 0; uix1 < rw[defender].nUn; ++uix1) { + const TUn &un = defUn[uix1]; + const TModel &model = defModel[un.mix]; + const int domain = (model.Kind == mkSpecial_Glider) ? dGround : model.Domain; + if (un.Loc != loc) + continue; + + ++cnt; + if (un.Master >= 0) + continue; + + int testBonus; + if (domain < dSea) { + testBonus = Terrain[realMap[loc] & fTerrain].Defense; + if ((realMap[loc] & fTerImp) == tiFort) + testBonus += 4; + if (un.Flags & unFortified) + testBonus += 2; + if (model.Kind == mkSpecial_TownGuard && (realMap[loc] & fCity)) + testBonus += 4; + } else { + testBonus = 4; + } + testBonus += un.Exp / ExpCost; + int testStrength = model.Defense * testBonus * un.Health; + if (domain == dAir && ((realMap[loc] & fCity) || (realMap[loc] & fTerImp) == tiBase)) + testStrength = 0; + if (domain == dSea && static_cast(realMap[loc] & fTerrain) >= fGrass) + testStrength >>= 1; + int testDet = testStrength; + if (model.Cap[mcStealth] > 0) { + // no detection bonus + } else if (model.Cap[mcSub] > 0) { + testDet += 1 << 28; + } else if (domain == dGround && model.Cap[mcFanatic] > 0 && + !(rw[defender].Government == gRepublic || rw[defender].Government == gDemocracy || + rw[defender].Government == gFuture)) { + testDet += 4 << 28; // fanatic ground units always defend + } else if (model.Flags & mdZOC) { + testDet += 3 << 28; + } else { + testDet += 2 << 28; + } + const int testCost = defModel[un.mix].Cost; + if (testDet > det || (testDet == det && testCost < cost)) { + uix = uix1; + strength = testStrength; + bonus = testBonus; + det = testDet; + cost = testCost; + } + } +} + +int getTileInfo(int p, int cix, int loc, TTileInfo &info) +{ + const int p0 = p; + std::uint32_t tile; + if (cix >= 0) { + tile = realMap[loc]; + } else { + tile = (*rw[p].Map)[loc]; + if ((tile & fTerrain) == fUNKNOWN) + return eNoPreq; + } + + if (cix == -1 && usedByCity[loc] >= 0) { // search exploiting player and city + searchCity(usedByCity[loc], p, cix); + if (!(p == p0 || ((observeLevel[usedByCity[loc]] >> (2 * p0)) & 3) == lObserveSuper)) + cix = -1; + } + if (cix == -1) + return eInvalid; // no city found here + + const std::uint32_t special = ((tile & fSpecial) & resourceMask[p]) >> 5; + const TerrainInfo &terrain = Terrain[tile & fTerrain]; + + info.Food = terrain.FoodRes[special]; + info.Prod = terrain.ProdRes[special]; + info.Trade = terrain.TradeRes[special]; + if (special > 0 && (tile & fTerrain) != fGrass && rw[p].NatBuilt[imSpacePort - nWonder] > 0) { + // GeoSat effect + info.Food = 2 * info.Food - terrain.FoodRes[0]; + info.Prod = 2 * info.Prod - terrain.ProdRes[0]; + info.Trade = 2 * info.Trade - terrain.TradeRes[0]; + } + + if ((tile & fTerImp) == tiIrrigation || (tile & fTerImp) == tiFarm || (tile & fCity) != 0) + info.Food += terrain.IrrEff; // irrigation effect + if ((tile & fTerImp) == tiMine) + info.Prod += terrain.MineEff; // mining effect + if ((tile & fRiver) != 0 && rw[p].Tech[adMapMaking] >= tsApplicable) + ++info.Trade; // river effect + if ((tile & (fRoad | fRR)) != 0 && terrain.MoveCost == 1 && rw[p].Tech[adWheel] >= tsApplicable) + ++info.Trade; // road effect + if ((tile & (fRR | fCity)) != 0 && rw[p].Tech[adRailroad] >= tsApplicable) + info.Prod += info.Prod >> 1; // railroad effect + + info.ExplCity = -1; + if (cix >= 0 && p == p0) + info.ExplCity = cix; + if (cix >= 0) { + const TCity &city = (*rw[p].City)[cix]; + if (static_cast(tile & fTerrain) >= fGrass) { + if (((tile & fTerImp) == tiFarm || (tile & fCity) != 0) && city.Built[imSupermarket] > 0) + info.Food += info.Food >> 1; // farmland effect + if ((tile & (fRoad | fRR)) != 0 && terrain.MoveCost == 1 && city.Built[imHighways] > 0) + info.Trade += 1; // superhighway effect + } else { + if (city.Built[imHarbor] > 0) + ++info.Food; // harbour effect + if (city.Built[imPlatform] > 0) + ++info.Prod; // oil platform effect + if (gWonder[woLighthouse].EffectiveOwner == p) + ++info.Prod; + } + } + + // good government influence + if ((rw[p].Government == gRepublic || rw[p].Government == gDemocracy || rw[p].Government == gFuture) && + info.Trade > 0) + ++info.Trade; + if (rw[p].Government == gCommunism && info.Prod > 1) + ++info.Prod; + + if (rw[p].Government == gAnarchy || rw[p].Government == gDespotism) { + // bad government influence + if (info.Food > 3) + info.Food = 3; + if (info.Prod > 2) + info.Prod = 2; + if (info.Trade > 2) + info.Trade = 2; + } + + if ((tile & (fTerrain | fPoll)) > fPoll) { + // pollution - decrease resources + info.Food -= info.Food >> 1; + info.Prod -= info.Prod >> 1; + info.Trade -= info.Trade >> 1; + } + + if ((tile & fCity) != 0) { + info.Trade = 0; + } else if (cix >= 0 && (*rw[p].City)[cix].Built[imCourt] + (*rw[p].City)[cix].Built[imPalace] == 0) { + if ((*rw[p].City)[cix].Built[imTownHall] == 0) + info.Trade = 0; + else if (info.Trade > 3) + info.Trade = 3; + } + + return eOK; +} + +int techBaseCost(int nTech, int diff) +{ + const double c0 = TechFormula_M[diff] * (nTech + 4) * std::exp((nTech + 4) / TechFormula_D[diff]); + if (c0 >= 0x10000000) + return 0x10000000; + return static_cast(c0); // truncates toward zero, matching Pascal's Trunc() +} + +void setModelFlags(TModel &m) +{ + m.Flags = 0; + if (m.Domain == dGround && m.Kind != mkDiplomat) + m.Flags |= mdZOC; + if (m.Kind == mkDiplomat || m.Attack + m.Cap[mcBombs] == 0) + m.Flags |= mdCivil; + if (m.Cap[mcOver] > 0 || (m.Domain == dSea && m.Weight >= 6)) + m.Flags |= mdDoubleSupport; +} + +void checkSpecialModels(int p, int pre) +{ + TPlayerContext &player = rw[p]; + TModel *model = *player.Model; + for (int i = 0; i < nSpecialModel; ++i) { + if (SpecialModelPreq[i] != pre || player.nModel >= nMmax) + continue; + bool hasAlready = false; + for (int mix1 = 0; mix1 < player.nModel; ++mix1) + if (model[mix1].Kind == SpecialModel[i].Kind && model[mix1].Attack == SpecialModel[i].Attack && + model[mix1].Speed == SpecialModel[i].Speed) + hasAlready = true; + if (!hasAlready) { + model[player.nModel] = SpecialModel[i]; + setModelFlags(model[player.nModel]); + TModel &newModel = model[player.nModel]; + newModel.Status = 0; + newModel.SavedStatus = 0; + newModel.IntroTurn = static_cast(gTurn); + newModel.Built = 0; + newModel.Lost = 0; + newModel.ID = static_cast((p << 12) + player.nModel); + if (newModel.Kind == mkSpecial_Boat && serverVersion[p] < 0x000EF0) + newModel.Speed = 350; // old longboat + ++player.nModel; + } + } +} + +void checkExpiration(int wonder) +{ + // GWonder[wonder].EffectiveOwner must be set before! + if (Imp[wonder].Expiration >= 0 && gWonder[woEiffel].EffectiveOwner != gWonder[wonder].EffectiveOwner) { + for (int p = 0; p < nPl; ++p) { + // check if already expired + if ((gAlive & (1 << p)) && rw[p].Tech[Imp[wonder].Expiration] >= tsApplicable) { + gWonder[wonder].EffectiveOwner = -1; + if (wonder == woPyramids) + freeSlaves(); + } + } + } +} + +void createUnit(int p, int mix) +{ + TPlayerContext &player = rw[p]; + TUn *un = *player.Un; + TModel *model = *player.Model; + + un[player.nUn].mix = static_cast(mix); + TUn &newUn = un[player.nUn]; + newUn.ID = static_cast(unBuilt[p]); + ++unBuilt[p]; + newUn.Status = 0; + newUn.SavedStatus = 0; + ++model[mix].Built; + newUn.Home = -1; + newUn.Health = 100; + newUn.Flags = 0; + newUn.Movement = 0; + if (model[mix].Domain == dAir) { + newUn.Fuel = static_cast(model[mix].Cap[mcFuel]); + newUn.Flags |= unBombsLoaded; + } + newUn.Job = jNone; + newUn.Exp = static_cast(ExpCost >> 1); + newUn.TroopLoad = 0; + newUn.AirLoad = 0; + newUn.Master = -1; + ++player.nUn; +} + +void placeUnit(int p, int uix) +{ + TPlayerContext &player = rw[p]; + TUn &un = (*player.Un)[uix]; + occupant[un.Loc] = static_cast(p); + if ((*player.Model)[un.mix].Flags & mdZOC) + zocMap[un.Loc] = 1; +} + +void freeUnit(int p, int uix) +{ + // loc or master should be set after call + // implementation is critical for loading performance, change carefully + TPlayerContext &player = rw[p]; + TUn &un = (*player.Un)[uix]; + un.Job = jNone; + un.Flags &= ~static_cast(unFortified | unMountainDelay); + const int loc0 = un.Loc; + + if (occupant[loc0] >= 0) { + assert(occupant[loc0] == p); + bool occ = false; + bool zoc = false; + const TUn *allUn = *player.Un; + const TModel *model = *player.Model; + for (int uix1 = 0; uix1 < player.nUn; ++uix1) { + if (allUn[uix1].Loc == loc0 && allUn[uix1].Master < 0 && uix1 != uix) { + occ = true; + if (model[allUn[uix1].mix].Flags & mdZOC) { + zoc = true; + break; + } + } + } + if (!occ) + occupant[loc0] = -1; + if (!zoc) + zocMap[loc0] = 0; + } +} + +void removeUnit(int p, int uix, int enemy) +{ + // use enemy only from inside sMoveUnit if attack + TPlayerContext &player = rw[p]; + TUn &un = (*player.Un)[uix]; + assert(un.Loc >= 0 || (*player.Model)[un.mix].Kind == mkDiplomat); + // already freed when spy mission + if (un.Loc >= 0) + freeUnit(p, uix); + if (un.Master >= 0) { + TUn &master = (*player.Un)[un.Master]; + if ((*player.Model)[un.mix].Domain == dAir) + --master.AirLoad; + else + --master.TroopLoad; + } + if (un.TroopLoad > 0 || un.AirLoad > 0) { + TUn *allUn = *player.Un; + for (int uix1 = 0; uix1 < player.nUn; ++uix1) { + // unit mastered by removed unit -- remove too + if (allUn[uix1].Loc >= 0 && allUn[uix1].Master == uix) { + allUn[uix1].Loc = -1; + if (enemy >= 0) + countLost(p, allUn[uix1].mix, enemy); + } + } + } + un.Loc = -1; + if (enemy >= 0) + countLost(p, un.mix, enemy); +} + +void removeUnitUpdateMap(int p, int uix) +{ + const int loc0 = (*rw[p].Un)[uix].Loc; + removeUnit(p, uix); + if (mode > moLoading_Fast) + updateUnitMap(loc0); +} + +void introduceEnemy(int p1, int p2) +{ + rw[p1].Treaty[p2] = trNone; + rw[p2].Treaty[p1] = trNone; +} + +int techCost(int p) +{ + TPlayerContext &player = rw[p]; + int result = techBaseCost(nTech[p], difficulty[p]); + if (player.ResearchTech >= 0) { + if (player.ResearchTech == adMilitary || player.Tech[player.ResearchTech] == tsSeen) + result >>= 1; + else if (IsFutureTech(player.ResearchTech)) + result *= (player.Government == gFuture) ? 2 : 4; + } + return result; +} + +void giveCivilReport(int p, int pAbout) +{ + TEnemyReport &report = *rw[p].EnemyReport[pAbout]; + report.TurnOfCivilReport = lastValidStat[pAbout]; + std::memcpy(report.Treaty, rw[pAbout].Treaty, sizeof(report.Treaty)); + report.Government = rw[pAbout].Government; + report.Money = rw[pAbout].Money; + report.ResearchTech = rw[pAbout].ResearchTech; + report.ResearchDone = rw[pAbout].Research * 100 / techCost(pAbout); + if (report.ResearchDone > 100) + report.ResearchDone = 100; + std::memcpy(report.Tech, rw[pAbout].Tech, nAdv); +} + +void giveMilReport(int p, int pAbout) +{ + TEnemyReport &report = *rw[p].EnemyReport[pAbout]; + report.TurnOfMilReport = lastValidStat[pAbout]; + report.nModelCounted = rw[pAbout].nModel; + for (int mix = 0; mix < rw[pAbout].nModel; ++mix) { + tellAboutModel(p, pAbout, mix); + report.UnCount[mix] = 0; + } + const TUn *un = *rw[pAbout].Un; + for (int uix = 0; uix < rw[pAbout].nUn; ++uix) + if (un[uix].Loc >= 0) + ++report.UnCount[un[uix].mix]; +} + +void intServer(int command, int player, int subject, const void *data) +{ + if (mode == moPlaying) + cl.put(command, player, subject, data); + + if (command == sIntTellAboutNation) { + introduceEnemy(player, subject); + } else if (command >= sIntTellAboutModel && command <= sIntTellAboutModel + ((nPl - 1) << 4)) { + const int p1 = (command - sIntTellAboutModel) >> 4; // told player + assert(player >= 0 && player < nPl); + assert(subject >= 0 && subject < rw[player].nModel); + TPlayerContext &toldPlayer = rw[p1]; + MakeModelInfo(player, subject, (*rw[player].Model)[subject], (*toldPlayer.EnemyModel)[toldPlayer.nEnemyModel]); + rwemix[p1][player][subject] = static_cast(toldPlayer.nEnemyModel); + ++toldPlayer.nEnemyModel; + assert(toldPlayer.nEnemyModel < nemmax); + } + // Other sIntXxx cases (sIntHaveContact/sIntCancelTreaty/sIntDiscoverZOC/ + // sIntExpandTerritory/sIntBuyMaterial/sIntPayPrices/sIntSetDevModel/ + // sIntSetXxxStatus) are NOT implemented yet - each needs its own + // not-yet-ported Database.pas function (CancelTreaty, Discover9, + // ExpandTerritory, PayPrice, DiscoverViewAreas, ...). Add them here once + // those exist - see repo memory for the current dependency-chain status. +} + +void tellAboutModel(int p, int taOwner, int tamix) +{ + if (p == taOwner || mode < moPlaying) + return; + TPlayerContext &player = rw[p]; + int i = 0; + const TModelInfo *enemyModel = *player.EnemyModel; + while (i < player.nEnemyModel && (enemyModel[i].Owner != taOwner || enemyModel[i].mix != tamix)) + ++i; + if (i == player.nEnemyModel) + intServer(sIntTellAboutModel + (p << 4), taOwner, tamix, nullptr); +} + +int emixSafe(int p, int taOwner, int tamix) +{ + int result = rwemix[p][taOwner][tamix]; + if (result < 0) { // sIntTellAboutModel comes too late + assert(mode == moMovie); + result = 0xFFFF; + } + return result; +} + +int getUnitStack(int p, int loc) +{ + int result = 0; + if (occupant[loc] < 0) + return result; + const int owner = occupant[loc]; + TPlayerContext &ownerPlayer = rw[owner]; + TPlayerContext &player = rw[p]; + TUnitInfo *enemyUn = *player.EnemyUn; + for (int uix = 0; uix < ownerPlayer.nUn; ++uix) { + const TUn &un = (*ownerPlayer.Un)[uix]; + if (un.Loc == loc) { + MakeUnitInfo(owner, un, enemyUn[player.nEnemyUn + result]); + tellAboutModel(p, owner, un.mix); + enemyUn[player.nEnemyUn + result].emix = static_cast(rwemix[p][owner][un.mix]); + ++result; + } + } + return result; +} + +void makeCityInfo(int p, int cix, TCityInfo &ci) +{ + assert(p >= 0 && p < nPl); + assert(cix >= 0 && cix < rw[p].nCity); + const TCity &city = (*rw[p].City)[cix]; + ci.Loc = city.Loc; + ci.ID = city.ID; + ci.Owner = static_cast(p); + ci.Size = city.Size; + ci.Flags = 0; + if (city.Built[imPalace] > 0) + ci.Flags += ciCapital; + if (city.Built[imWalls] > 0 || continent[city.Loc] == grWallContinent[p]) + ci.Flags += ciWalled; + if (city.Built[imCoastalFort] > 0) + ci.Flags += ciCoastalFort; + if (city.Built[imMissileBat] > 0) + ci.Flags += ciMissileBat; + if (city.Built[imBunker] > 0) + ci.Flags += ciBunker; + if (city.Built[imSpacePort] > 0) + ci.Flags += ciSpacePort; +} + +bool discoverTile(int loc, int p, int pTell, int level, bool enableContact, int euix) +{ + auto setContact = [&](int p1, int p2) { + if (mode < moPlaying || p1 == p2 || rw[p1].Treaty[p2] > trNoContact) + return; + intServer(sIntTellAboutNation, p1, p2, nullptr); + }; + + bool result = false; + TPlayerContext &player = rw[pTell]; + std::uint32_t *map = *player.Map; + TUnitInfo *enemyUn = *player.EnemyUn; + TCityInfo *enemyCity = *player.EnemyCity; + std::int8_t *territory = *player.Territory; + std::int16_t *mapObservedLast = *player.MapObservedLast; + + const std::uint32_t tile = realMap[loc] & resourceMask[pTell]; + std::uint32_t addFlags; + if (mode == moLoading_Fast) { + addFlags = 0; // don't discover units + } else { + addFlags = (map[loc] & fInEnemyZoC) | fObserved; // always preserve this flag! + if (level == lObserveSuper) + addFlags |= fSpiedOut; + if (grWallContinent[pTell] >= 0 && continent[loc] == grWallContinent[pTell]) + addFlags |= fGrWall; + if (mode == moPlaying && + (tile & (static_cast(nPl) << 27)) != (static_cast(nPl) << 27) && + pTell == p) { + // set fPeace flag? + const int terrOwner = static_cast(tile >> 27); + if (terrOwner != pTell) { + const int terrOwnerTreaty = player.Treaty[terrOwner]; + if ((1 << terrOwnerTreaty) & ((1 << trPeace) | (1 << trFriendlyContact))) + addFlags |= fPeace; + } + } + + if (occupant[loc] >= 0) { + if (occupant[loc] == pTell) { + addFlags |= (fOwned | fUnit); + if (zocMap[loc] > 0) + addFlags |= fOwnZoCUnit; + // level := lObserveSuper; // always see own units + } else if (map[loc] & fUnit) { + addFlags |= fUnit; + } else { + int uix, strength, bonus, cnt; + strongest(loc, uix, strength, bonus, cnt); + const TUn &unx = (*rw[occupant[loc]].Un)[uix]; + const TModel &mox = (*rw[occupant[loc]].Model)[unx.mix]; + assert((zocMap[loc] != 0) == ((mox.Flags & mdZOC) != 0)); + int minLevel; + if (mox.Cap[mcStealth] > 0 && (tile & fCity) == 0 && (tile & fTerImp) != tiBase) + minLevel = lObserveSuper; + else if (mox.Cap[mcSub] > 0 && static_cast(tile & fTerrain) < fGrass) + minLevel = lObserveAll; + else + minLevel = lObserveUnhidden; + if (level >= minLevel) { + addFlags |= fUnit; + int unitIndex; + if (euix >= 0) { + unitIndex = euix; + } else { + unitIndex = player.nEnemyUn; + ++player.nEnemyUn; + assert(player.nEnemyUn < neumax); + } + MakeUnitInfo(occupant[loc], unx, enemyUn[unitIndex]); + if (cnt > 1) + enemyUn[unitIndex].Flags |= unMulti; + if ((mox.Flags & mdZOC) && pTell == p && player.Treaty[occupant[loc]] < trAlliance) { + // set fInEnemyZoC flags of surrounding tiles + Vicinity8Loc adjacent; + v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[v8]; + if (loc1 >= 0 && loc1 < mapSize) + map[loc1] |= fInEnemyZoC; + } + } + if (enableContact && mox.Domain == dGround) + setContact(pTell, occupant[loc]); + if (mode >= moMovie) { + tellAboutModel(pTell, occupant[loc], unx.mix); + enemyUn[unitIndex].emix = static_cast(emixSafe(pTell, occupant[loc], unx.mix)); + } + // level := lObserveSuper; // don't discover unit twice + if (pTell == p && ((tile & fCity) == 0 || ((1 << pTell) & gAI))) + result = true; + } else { + addFlags |= map[loc] & (fStealthUnit | fHiddenUnit); + } + } + } + } // if mode > moLoading_Fast + + if (tile & fCity) { + if ((observeLevel[loc] >> (2 * pTell)) & 3) { + addFlags |= map[loc] & fOwned; + } else { + const int pFoundCity = static_cast(tile >> 27); + if (pFoundCity == pTell) { + addFlags |= fOwned; + } else { + if (enableContact) + setContact(pTell, pFoundCity); + int cixFoundCity = rw[pFoundCity].nCity - 1; + while (cixFoundCity >= 0 && (*rw[pFoundCity].City)[cixFoundCity].Loc != loc) + --cixFoundCity; + assert(cixFoundCity >= 0); + int i = 0; + while (i < player.nEnemyCity && enemyCity[i].Loc != loc) + ++i; + if (i == player.nEnemyCity) { + ++player.nEnemyCity; + assert(player.nEnemyCity < necmax); + enemyCity[i].Status = 0; + enemyCity[i].SavedStatus = 0; + if (pTell == p) + result = true; + } + makeCityInfo(pFoundCity, cixFoundCity, enemyCity[i]); + } + } + } else if (map[loc] & fCity) { // remove enemy city + for (int cix = 0; cix < player.nEnemyCity; ++cix) + if (enemyCity[cix].Loc == loc) + enemyCity[cix].Loc = -1; + } + + if ((map[loc] & fTerrain) == fUNKNOWN) + ++discovered[pTell]; + if (euix >= -1) { + map[loc] = (map[loc] & ~static_cast(fUnit | fCity | fOwned | fOwnZoCUnit)) | + ((tile & 0x07FFFFFFu | addFlags) & (fUnit | fCity | fOwned | fOwnZoCUnit)); + } else { + map[loc] = (tile & 0x07FFFFFFu) | addFlags; + if ((tile & 0x78000000u) == 0x78000000u) + territory[loc] = -1; + else + territory[loc] = static_cast(tile >> 27); + mapObservedLast[loc] = static_cast(gTurn); + } + observeLevel[loc] = (observeLevel[loc] & ~(3u << (2 * pTell))) | (static_cast(level) << (2 * pTell)); + + return result; +} + +bool discover9(int loc, int p, int level, bool tellAllied, bool enableContact) +{ + assert(mode > moLoading_Fast || rw[p].nEnemyUn == 0); + bool result = false; + Vicinity8Loc radius; + v8ToLoc(loc, radius); + for (int v9 = 0; v9 <= 8; ++v9) { + const int loc1 = (v9 == 8) ? loc : radius[v9]; + if (loc1 < 0 || loc1 >= mapSize) + continue; + if (tellAllied) { + for (int pTell = 0; pTell < nPl; ++pTell) { + if (pTell == p || (((1 << pTell) & gAlive) && rw[p].Treaty[pTell] == trAlliance)) { + const int oldLevel = (observeLevel[loc1] >> (2 * pTell)) & 3; + if (level > oldLevel) + result = discoverTile(loc1, p, pTell, level, enableContact) || result; + } + } + } else { + const int oldLevel = (observeLevel[loc1] >> (2 * p)) & 3; + if (level > oldLevel) + result = discoverTile(loc1, p, p, level, enableContact) || result; + } + } + return result; +} + +bool discover21(int loc, int p, int adjacentLevel, bool tellAllied, bool enableContact) +{ + assert(mode > moLoading_Fast || rw[p].nEnemyUn == 0); + bool result = false; + std::uint32_t adjacentFlags = 0x00267620u >> 1; + Vicinity21Loc radius; + v21ToLoc(loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + const int loc1 = radius[v21]; + if (loc1 >= 0 && loc1 < mapSize) { + const int level = (adjacentFlags & 1) ? adjacentLevel : lObserveUnhidden; + if (tellAllied) { + for (int pTell = 0; pTell < nPl; ++pTell) { + if (pTell == p || (((1 << pTell) & gAlive) && rw[p].Treaty[pTell] == trAlliance)) { + const int oldLevel = (observeLevel[loc1] >> (2 * pTell)) & 3; + if (level > oldLevel) + result = discoverTile(loc1, p, pTell, level, enableContact) || result; + } + } + } else { + const int oldLevel = (observeLevel[loc1] >> (2 * p)) & 3; + if (level > oldLevel) + result = discoverTile(loc1, p, p, level, enableContact) || result; + } + } + adjacentFlags >>= 1; + } + return result; +} + +void discoverAll(int p, int level) +{ + // player p discovers complete playground (for supervisor) + assert(mode > moLoading_Fast || rw[p].nEnemyUn == 0); + for (int loc = 0; loc < mapSize; ++loc) { + const int oldLevel = (observeLevel[loc] >> (2 * p)) & 3; + if (level > oldLevel) + discoverTile(loc, p, p, level, false); + } +} + +void discoverViewAreas(int p) +{ + // discover unit and city view areas + for (int pTell = 0; pTell < nPl; ++pTell) { + if (pTell != p && rw[p].Treaty[pTell] != trAlliance) + continue; + TPlayerContext &tellPlayer = rw[pTell]; + const TUn *un = *tellPlayer.Un; + for (int uix = 0; uix < tellPlayer.nUn; ++uix) { + if (un[uix].Loc >= 0 && un[uix].Master < 0 && (realMap[un[uix].Loc] & fCity) == 0) { + const TModel &model = (*tellPlayer.Model)[un[uix].mix]; + if (model.Kind == mkDiplomat || model.Cap[mcSpy] > 0) + discover21(un[uix].Loc, p, lObserveSuper, false, true); + else if (model.Cap[mcRadar] + model.Cap[mcCarrier] > 0 || model.Domain == dAir) + discover21(un[uix].Loc, p, lObserveAll, false, false); + else if (static_cast(realMap[un[uix].Loc] & fTerrain) == fMountains || + (realMap[un[uix].Loc] & fTerImp) == tiFort || (realMap[un[uix].Loc] & fTerImp) == tiBase || + model.Cap[mcAcademy] > 0) + discover21(un[uix].Loc, p, lObserveUnhidden, false, model.Domain == dGround); + else + discover9(un[uix].Loc, p, lObserveUnhidden, false, model.Domain == dGround); + } + } + const TCity *city = *tellPlayer.City; + for (int cix = 0; cix < tellPlayer.nCity; ++cix) + if (city[cix].Loc >= 0) + discover21(city[cix].Loc, p, lObserveUnhidden, false, true); + + TCityInfo *enemyCity = *tellPlayer.EnemyCity; + for (int ecix = 0; ecix < tellPlayer.nEnemyCity; ++ecix) { + // players know territory, so no use in hiding city owner + const int loc = enemyCity[ecix].Loc; + if (loc >= 0) { + const int realOwner = static_cast((realMap[loc] >> 27) & 0xF); + if (realOwner < nPl) { + enemyCity[ecix].Owner = static_cast(realOwner); + } else { + enemyCity[ecix].Loc = -1; + (*tellPlayer.Map)[loc] &= ~static_cast(fCity); + } + } + } + } +} + +void updateUnitMap(int loc, bool cityChange) +{ + // update maps and enemy units of all players after unit change + if (mode == moLoading_Fast && !cityChange) + return; + for (int p = 0; p < nPl; ++p) { + if (!((1 << p) & (gAlive | gWatching))) + continue; + const int oldLevel = (observeLevel[loc] >> (2 * p)) & 3; + if (oldLevel <= lNoObserve) + continue; + + TPlayerContext &player = rw[p]; + std::uint32_t *map = *player.Map; + TUnitInfo *enemyUn = *player.EnemyUn; + int euix; + + if ((map[loc] & (fUnit | fOwned)) == fUnit) { + // replace unit located here in EnemyUn + // do not just set loc:=-1 because total number would be unlimited + euix = player.nEnemyUn - 1; + while (euix >= 0) { + if (enemyUn[euix].Loc == loc) { + enemyUn[euix].Loc = -1; + break; + } + --euix; + } + map[loc] &= ~static_cast(fUnit); + } else { + // look for empty slot in EnemyUn + euix = player.nEnemyUn - 1; + while (euix >= 0 && enemyUn[euix].Loc >= 0) + --euix; + } + + if (occupant[loc] < 0 && !cityChange) { + // calling DiscoverTile not necessary, only clear map flags + std::uint32_t clearFlags = fUnit | fHiddenUnit | fStealthUnit | fOwnZoCUnit; + if ((realMap[loc] & fCity) == 0) + clearFlags |= fOwned; + map[loc] &= ~clearFlags; + } else if (occupant[loc] != p || cityChange) { + // city or enemy unit update necessary, call DiscoverTile + observeLevel[loc] &= ~(3u << (2 * p)); + discoverTile(loc, p, p, oldLevel, false, euix); + } else { + // calling DiscoverTile not necessary, only set map flags + std::uint32_t clearFlags = 0; + std::uint32_t addFlags = fUnit | fOwned; + if (zocMap[loc] > 0) + addFlags |= fOwnZoCUnit; + else + clearFlags |= fOwnZoCUnit; + map[loc] = (map[loc] & ~clearFlags) | addFlags; + } + } +} + } // namespace Database } // namespace Cevo