From 55ccee5b571c7218a41b0b39bd44750347bada86 Mon Sep 17 00:00:00 2001 From: Geoffray Levasseur Date: Wed, 28 Oct 2026 17:59:02 +0100 Subject: [PATCH] add back and splitted database --- game/Back.cpp | 90 + game/Back.h | 65 + game/CMakeLists.txt | 12 + game/src/Database.City.cpp | 179 ++ game/src/Database.Diplomacy.cpp | 481 ++++ game/src/Database.GameInitialization.cpp | 310 +++ game/src/Database.LocationNavigation.cpp | 137 ++ game/src/Database.MapCreation.cpp | 73 + game/src/Database.MapEditor.cpp | 110 + game/src/Database.MapProcessing.cpp | 398 +++ game/src/Database.MapRevealing.cpp | 663 +++++ game/src/Database.TechRelated.cpp | 222 ++ game/src/Database.TerritoryCalculation.cpp | 299 +++ game/src/Database.TestFlags.cpp | 93 + game/src/Database.cpp | 2548 +------------------- game/src/DatabaseInternal.h | 69 + 16 files changed, 3215 insertions(+), 2534 deletions(-) create mode 100644 game/Back.cpp create mode 100644 game/Back.h create mode 100644 game/src/Database.City.cpp create mode 100644 game/src/Database.Diplomacy.cpp create mode 100644 game/src/Database.GameInitialization.cpp create mode 100644 game/src/Database.LocationNavigation.cpp create mode 100644 game/src/Database.MapCreation.cpp create mode 100644 game/src/Database.MapEditor.cpp create mode 100644 game/src/Database.MapProcessing.cpp create mode 100644 game/src/Database.MapRevealing.cpp create mode 100644 game/src/Database.TechRelated.cpp create mode 100644 game/src/Database.TerritoryCalculation.cpp create mode 100644 game/src/Database.TestFlags.cpp create mode 100644 game/src/DatabaseInternal.h diff --git a/game/Back.cpp b/game/Back.cpp new file mode 100644 index 0000000..f147785 --- /dev/null +++ b/game/Back.cpp @@ -0,0 +1,90 @@ +// This file is part of cevo-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 "Back.h" + +#include "Global.h" + +#include +#include +#include + +namespace Cevo { + +Background::Background(QWidget *parent) : QWidget(parent) +{ + setWindowTitle(QStringLiteral("C-evo-evo")); + setWindowFlag(Qt::FramelessWindowHint); + QPalette pal = palette(); + pal.setColor(QPalette::Window, Qt::black); + setPalette(pal); + setAutoFillBackground(true); +} + +void Background::showEvent(QShowEvent *event) +{ + QWidget::showEvent(event); + updateInterface(); +} + +void Background::updateInterface() +{ + if (fullScreen) { + if (QScreen *primaryScreen = screen()) + setGeometry(primaryScreen->geometry()); + showFullScreen(); + if (!m_img) { + const QString fileName = getGraphicsDir() + QLatin1Char('/') + QStringLiteral("Background") + PngExt; + if (QFileInfo::exists(fileName)) { + m_img = std::make_unique(); + m_img->loadFromFile(fileName); + update(); + } + } + } else { + // Dropped the original's wsNormal/wsFullScreen/wsNormal toggle - an + // LCL-specific refresh workaround, not needed with Qt. + showNormal(); + if (m_anchor) { + setGeometry(m_anchor->x() - 8, m_anchor->y() - 8, m_anchor->width() + 16, m_anchor->height() + 16); + } + } +} + +void Background::paintEvent(QPaintEvent *event) +{ + QWidget::paintEvent(event); + if (m_img && fullScreen) { + QPainter painter(this); + const int x = width() - m_img->width() - (width() - 800) * 3 / 8; + const int y = (height() - 600) / 3; + painter.drawImage(x, y, m_img->image()); + } +} + +} // namespace Cevo diff --git a/game/Back.h b/game/Back.h new file mode 100644 index 0000000..c2a0aba --- /dev/null +++ b/game/Back.h @@ -0,0 +1,65 @@ +// This file is part of cevo-evo. +// +// This software is governed by the CeCILL license under French law and +// abiding by the rules of distribution of free software. You can use, +// modify and/or redistribute the software under the terms of the CeCILL +// license as circulated by CEA, CNRS and INRIA at the following URL +// "http://www.cecill.info". +// +// As a counterpart to the access to the source code and rights to copy, +// modify and redistribute granted by the license, users are provided only +// with a limited warranty and the software's author, the holder of the +// economic rights, and the successive licensors have only limited +// liability. +// +// In this respect, the user's attention is drawn to the risks associated +// with loading, using, modifying and/or developing or reproducing the +// software by the user in light of its specific status of free software, +// that may mean that it is complicated to manipulate, and that also +// therefore means that it is reserved for developers and experienced +// professionals having in-depth computer knowledge. Users are therefore +// encouraged to load and test the software's suitability as regards their +// requirements in conditions enabling the security of their systems and/or +// data to be ensured and, more generally, to use and operate it in the +// same conditions as regards security. +// +// The fact that you are presently reading this means that you have had +// knowledge of the CeCILL license and that you accept its terms. + +#pragma once + +#include "Dpi/DpiGraphics.h" + +#include + +#include + +namespace Cevo { + +// Equivalent of Back.pas's TBackground: a borderless, black window shown +// either fullscreen (with a Graphics/Background.png image) or sized/ +// positioned as a frame around another window (the start dialog). The +// original reaches directly into the global StartDlg for the latter case; +// since Start.pas isn't ported yet, this instead takes the anchor window +// explicitly (setAnchor()) - a disclosed decoupling, not a behavior change. +class Background : public QWidget { + Q_OBJECT +public: + explicit Background(QWidget *parent = nullptr); + + // Window to size/position around when not fullscreen (replaces the + // original's hardcoded StartDlg reference). + void setAnchor(QWidget *anchor) { m_anchor = anchor; } + + void updateInterface(); + +protected: + void paintEvent(QPaintEvent *event) override; + void showEvent(QShowEvent *event) override; + +private: + QWidget *m_anchor = nullptr; + std::unique_ptr m_img; +}; + +} // namespace Cevo diff --git a/game/CMakeLists.txt b/game/CMakeLists.txt index 935b807..92b1ee8 100644 --- a/game/CMakeLists.txt +++ b/game/CMakeLists.txt @@ -55,12 +55,24 @@ set(CEVO_GAME_HEADERS include/Cevo/Music.h include/Cevo/Platform.h include/Cevo/UnitProcessing.h + src/DatabaseInternal.h ) set(CEVO_GAME_SOURCES src/CityProcessing.cpp src/CmdList.cpp src/Database.cpp + src/Database.City.cpp + src/Database.Diplomacy.cpp + src/Database.GameInitialization.cpp + src/Database.LocationNavigation.cpp + src/Database.MapCreation.cpp + src/Database.MapEditor.cpp + src/Database.MapProcessing.cpp + src/Database.MapRevealing.cpp + src/Database.TechRelated.cpp + src/Database.TerritoryCalculation.cpp + src/Database.TestFlags.cpp src/FileList.cpp src/IPQ.cpp src/Map.cpp diff --git a/game/src/Database.City.cpp b/game/src/Database.City.cpp new file mode 100644 index 0000000..0f00f99 --- /dev/null +++ b/game/src/Database.City.cpp @@ -0,0 +1,179 @@ +// This file is part of cevo-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. + +// --- City --- (see Cevo/Database.h) + +#include "Cevo/Database.h" +#include "DatabaseInternal.h" + +#include + +namespace Cevo { +namespace Database { + +namespace { + +void stealCity(int p, int cix, bool saveUnits) +{ + TCity &city = (*rw[p].City)[cix]; + for (int i = 0; i < nWonder; ++i) { + if (city.Built[i] == 1) { + gWonder[i].EffectiveOwner = -1; + if (i == woPyramids) + freeSlaves(); + if (i == woEiffel) // deactivate expired wonders + for (int j = 0; j < nWonder; ++j) + if (gWonder[j].EffectiveOwner == p) + checkExpiration(j); + } + } + for (int i = nWonder; i < nImp; ++i) { + if (Imp[i].Kind != ikCommon && city.Built[i] > 0) { // destroy national projects + rw[p].NatBuilt[i] = 0; + if (i == imGrWall) + grWallContinent[p] = -1; + } + } + + TUn *un = *rw[p].Un; + for (int uix1 = 0; uix1 < rw[p].nUn; ++uix1) { + if (un[uix1].Loc >= 0 && un[uix1].Home == cix) { + if (saveUnits) { // support units by nearest other city + int nearest = -1; + for (int cix1 = 0; cix1 < rw[p].nCity; ++cix1) { + const TCity &c1 = (*rw[p].City)[cix1]; + if (cix1 != cix && c1.Loc >= 0 && + (nearest < 0 || distance(c1.Loc, un[uix1].Loc) < + distance((*rw[p].City)[nearest].Loc, un[uix1].Loc))) + nearest = cix1; + } + un[uix1].Home = nearest; + } else { + removeUnit(p, uix1); // destroy supported units + } + } + } +} + +} // namespace + +void destroyCity(int p, int cix, bool saveUnits) +{ + stealCity(p, cix, saveUnits); + TCity &city = (*rw[p].City)[cix]; + for (int i = 0; i < nWonder; ++i) + if (city.Built[i] > 0) + gWonder[i].CityID = WonderDestroyed; + Vicinity21Loc radius; + v21ToLoc(city.Loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) + if ((1u << v21) & city.Tiles) + usedByCity[static_cast(radius[static_cast(v21)])] = -1; + realMap[city.Loc] &= ~static_cast(fCity); + city.Loc = -1; +} + +void changeCityOwner(int pOld, int cixOld, int pNew) +{ + ++rw[pNew].nCity; + (*rw[pNew].City)[rw[pNew].nCity - 1] = (*rw[pOld].City)[cixOld]; + stealCity(pOld, cixOld, false); + (*rw[pOld].City)[cixOld].Loc = -1; + + TCity &city = (*rw[pNew].City)[rw[pNew].nCity - 1]; + city.Food = 0; + city.Project = cpImp + imTrGoods; + city.Prod = 0; + city.Project0 = city.Project; + city.Prod0 = 0; + city.Status = 0; + city.SavedStatus = 0; + city.N1 = 0; + + // check for siege + Vicinity21Loc radius; + v21ToLoc(city.Loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + if ((city.Tiles & (1u << v21) & ~(1u << CityOwnTile)) != 0) { + const int loc1 = radius[static_cast(v21)]; + assert(loc1 >= 0 && loc1 < mapSize && usedByCity[static_cast(loc1)] == city.Loc); + if (zocMap[loc1] > 0 && occupant[loc1] != pNew && rw[pNew].Treaty[occupant[loc1]] < trAlliance) { + // tile can't remain exploited + city.Tiles &= ~(1u << v21); + usedByCity[static_cast(loc1)] = -1; + } + // don't check for siege by peace territory here, because territory + // might not be up to date -- done in turn beginning anyway + } + } + city.Built[imTownHall] = 0; + city.Built[imCourt] = 0; + for (int i = nWonder; i < nImp; ++i) + if (Imp[i].Kind != ikCommon) + city.Built[i] = 0; // destroy national projects + for (int i = 0; i < nWonder; ++i) { + if (city.Built[i] == 1) { // new wonder owner! + gWonder[i].EffectiveOwner = pNew; + if (i == woEiffel) { // reactivate expired wonders + for (int j = 0; j < nWonder; ++j) + if (Imp[j].Expiration >= 0) + for (int cix1 = 0; cix1 < rw[pNew].nCity; ++cix1) + if ((*rw[pNew].City)[cix1].Built[j] == 1) + gWonder[j].EffectiveOwner = pNew; + } else { + checkExpiration(i); + } + switch (i) { + case woLighthouse: + checkSpecialModels(pNew, preLighthouse); + break; + case woLeo: + checkSpecialModels(pNew, preLeo); + break; + case woPyramids: + checkSpecialModels(pNew, preBuilder); + break; + default: + break; + } + } + } + + // remove city from enemy cities - not done by Discover, because fCity still set! + int cix1 = rw[pNew].nEnemyCity - 1; + TCityInfo *enemyCity = *rw[pNew].EnemyCity; + while (cix1 >= 0 && enemyCity[cix1].Loc != city.Loc) + --cix1; + assert(cix1 >= 0); + enemyCity[cix1].Loc = -1; + + changeTerritory(city.Loc, pNew); +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.Diplomacy.cpp b/game/src/Database.Diplomacy.cpp new file mode 100644 index 0000000..b95db87 --- /dev/null +++ b/game/src/Database.Diplomacy.cpp @@ -0,0 +1,481 @@ +// This file is part of cevo-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. + +// --- Diplomacy --- (see Cevo/Database.h) + +#include "Cevo/Database.h" + +#include +#include + +namespace Cevo { +namespace Database { + +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]; +} + +bool copyCivilReport(int pSender, int pTarget, int pAbout) +{ + bool result = false; + if (rw[pTarget].Treaty[pAbout] == trNoContact) + introduceEnemy(pTarget, pAbout); + TEnemyReport &rSender = *rw[pSender].EnemyReport[pAbout]; + TEnemyReport &rTarget = *rw[pTarget].EnemyReport[pAbout]; + if (rSender.TurnOfCivilReport > rTarget.TurnOfCivilReport) { // only if newer than current information + rTarget.TurnOfCivilReport = rSender.TurnOfCivilReport; + std::memcpy(rTarget.Treaty, rSender.Treaty, sizeof(rTarget.Treaty)); + rTarget.Government = rSender.Government; + rTarget.Money = rSender.Money; + rTarget.ResearchTech = rSender.ResearchTech; + rTarget.ResearchDone = rSender.ResearchDone; + result = true; + } + for (int i = 0; i < nAdv; ++i) + if (rTarget.Tech[i] < rSender.Tech[i]) { + rTarget.Tech[i] = rSender.Tech[i]; + result = true; + } + return result; +} + +bool copyMilReport(int pSender, int pTarget, int pAbout) +{ + bool result = false; + if (rw[pTarget].Treaty[pAbout] == trNoContact) + introduceEnemy(pTarget, pAbout); + TEnemyReport &rSender = *rw[pSender].EnemyReport[pAbout]; + TEnemyReport &rTarget = *rw[pTarget].EnemyReport[pAbout]; + if (rSender.TurnOfMilReport > rTarget.TurnOfMilReport) { // only if newer than current information + rTarget.TurnOfMilReport = rSender.TurnOfMilReport; + rTarget.nModelCounted = rSender.nModelCounted; + std::memcpy(rTarget.UnCount, rSender.UnCount, + sizeof(std::uint16_t) * static_cast(rSender.nModelCounted)); + for (int mix = 0; mix < rTarget.nModelCounted; ++mix) + tellAboutModel(pTarget, pAbout, mix); + result = true; + } + return result; +} + +void copyModel(int pSender, int pTarget, int mix) +{ + // only if target doesn't already have a model like this + bool ok = rw[pTarget].nModel < nMmax; + TModelInfo miSender{}; + MakeModelInfo(pSender, mix, (*rw[pSender].Model)[mix], miSender); + for (int i = 0; i < rw[pTarget].nModel && ok; ++i) { + TModelInfo miTarget{}; + MakeModelInfo(pTarget, i, (*rw[pTarget].Model)[i], miTarget); + if (IsSameModel(miSender, miTarget)) + ok = false; + } + if (ok) { + TModel &newModel = (*rw[pTarget].Model)[rw[pTarget].nModel]; + newModel = (*rw[pSender].Model)[mix]; + newModel.IntroTurn = static_cast(gTurn); + if (newModel.Kind == mkSelfDeveloped) + newModel.Kind = mkEnemyDeveloped; + newModel.Status = 0; + newModel.SavedStatus = 0; + newModel.Built = 0; + newModel.Lost = 0; + ++rw[pTarget].nModel; + ++researched[pTarget]; + tellAboutModel(pSender, pTarget, rw[pTarget].nModel - 1); + } +} + +void copyMap(int pSender, int pTarget) +{ + TPlayerContext &sender = rw[pSender]; + TPlayerContext &target = rw[pTarget]; + const std::int16_t *senderObserved = *sender.MapObservedLast; + std::int16_t *targetObserved = *target.MapObservedLast; + const std::uint32_t *senderMap = *sender.Map; + std::uint32_t *targetMap = *target.Map; + const std::int8_t *senderTerritory = *sender.Territory; + std::int8_t *targetTerritory = *target.Territory; + TCityInfo *senderEnemyCity = *sender.EnemyCity; + TCityInfo *targetEnemyCity = *target.EnemyCity; + const TCity *senderCity = *sender.City; + + for (int loc = 0; loc < mapSize; ++loc) { + if (senderObserved[loc] <= targetObserved[loc]) + continue; + std::uint32_t tile = senderMap[loc]; + if (tile & fCity) { + int i = 0; + while (i < target.nEnemyCity && targetEnemyCity[i].Loc != loc) + ++i; + if (i == target.nEnemyCity) { + ++target.nEnemyCity; + assert(target.nEnemyCity < necmax); + targetEnemyCity[i].Status = 0; + targetEnemyCity[i].SavedStatus = 0; + } + if (tile & fOwned) { // city owned by sender -- create new info + int cix = sender.nCity - 1; + while (cix >= 0 && senderCity[cix].Loc != loc) + --cix; + makeCityInfo(pSender, cix, targetEnemyCity[i]); + } else { // city not owned by sender -- copy old info + int cix = sender.nEnemyCity - 1; + while (cix >= 0 && senderEnemyCity[cix].Loc != loc) + --cix; + targetEnemyCity[i] = senderEnemyCity[cix]; + } + } else if (targetMap[loc] & fCity) { // remove enemycity + for (int cix = 0; cix < target.nEnemyCity; ++cix) + if (targetEnemyCity[cix].Loc == loc) + targetEnemyCity[cix].Loc = -1; + } + + tile &= (~static_cast(fSpecial | fModern) | resourceMask[pTarget]); + tile |= (targetMap[loc] & fModern); + if ((tile & fTerrain) == (targetMap[loc] & fTerrain)) + tile |= (targetMap[loc] & fSpecial); + + if ((targetMap[loc] & fTerrain) == static_cast(fUNKNOWN)) + ++discovered[pTarget]; + targetMap[loc] = (targetMap[loc] & fInEnemyZoC) // always preserve this flag! + | (tile & ~static_cast(fUnit | fHiddenUnit | fStealthUnit | fObserved | + fSpiedOut | fOwned | fInEnemyZoC | fOwnZoCUnit | + fPeace | fGrWall)); + // (the original re-assigns Territory unconditionally right after an + // equivalent if-guarded assignment - the guard was a no-op once its + // only other effect, a BorderHelper update, had been commented out) + targetTerritory[loc] = senderTerritory[loc]; + targetObserved[loc] = senderObserved[loc]; + } +} + +std::uint32_t doSpyMission(int p, int pCity, int cix, int mission) +{ + std::uint32_t result = 0; + switch (mission) { + case smSabotageProd: + (*rw[pCity].City)[cix].Flags |= chProductionSabotaged; + break; + case smStealMap: + copyMap(pCity, p); + recalcPeaceMap(p); + break; + case smStealCivilReport: + if (rw[p].Treaty[pCity] == trNoContact) + introduceEnemy(p, pCity); + giveCivilReport(p, pCity); + break; + case smStealMilReport: + if (rw[p].Treaty[pCity] == trNoContact) + introduceEnemy(p, pCity); + giveMilReport(p, pCity); + break; + case smStealForeignReports: + for (int p1 = 0; p1 < nPl; ++p1) { + if (p1 != p && p1 != pCity && rw[pCity].EnemyReport[p1]) { + if (rw[pCity].EnemyReport[p1]->TurnOfCivilReport >= 0 && copyCivilReport(pCity, p, p1)) + result |= (1u << (2 * p1)); + if (rw[pCity].EnemyReport[p1]->TurnOfMilReport >= 0 && copyMilReport(pCity, p, p1)) + result |= (2u << (2 * p1)); + } + } + break; + default: + break; + } + return result; +} + +void showPrice(int pSender, int pTarget, std::uint32_t price) +{ + switch (price & opMask) { + case opTech: // + advance + if (rw[pTarget].EnemyReport[pSender]->Tech[price - opTech] < tsApplicable) + rw[pTarget].EnemyReport[pSender]->Tech[price - opTech] = tsApplicable; + break; + case opModel: // + model index + tellAboutModel(pTarget, pSender, static_cast(price - opModel)); + break; + default: + break; + } +} + +bool payPrice(int pSender, int pTarget, std::uint32_t price, bool execute) +{ + bool result = true; + switch (price & opMask) { + case opCivilReport: { // + turn + concerned player shl 16 + const int pSubject = static_cast((price >> 16) & 0xF); + if (pTarget == pSubject) + result = false; + else if (pSender == pSubject) { + if (execute) + giveCivilReport(pTarget, pSender); + } else if (rw[pSender].EnemyReport[pSubject]->TurnOfCivilReport < 0) + result = false; + else if (execute) + copyCivilReport(pSender, pTarget, pSubject); + break; + } + case opMilReport: { // + turn + concerned player shl 16 + const int pSubject = static_cast((price >> 16) & 0xF); + if (pTarget == pSubject) + result = false; + else if (pSender == pSubject) { + if (execute) + giveMilReport(pTarget, pSender); + } else if (rw[pSender].EnemyReport[pSubject]->TurnOfMilReport < 0) + result = false; + else if (execute) + copyMilReport(pSender, pTarget, pSubject); + break; + } + case opMap: + if (execute) { + copyMap(pSender, pTarget); + recalcPeaceMap(pTarget); + } + break; + case opTreaty: { // + nation treaty (opMask only keeps the top byte, so + // this single case covers the original's whole + // opTreaty..opTreaty+trAlliance range) + if (static_cast(price - opTreaty) == rw[pSender].Treaty[pTarget] - 1) { // agreed treaty end + if (execute) + cancelTreaty(pSender, pTarget, false); + } else { + int newTreaty = -1; + if (static_cast(price - opTreaty) == rw[pSender].Treaty[pTarget] + 1) + newTreaty = static_cast(price - opTreaty); + else if (rw[pSender].Treaty[pTarget] == trNone && static_cast(price - opTreaty) == trPeace) + newTreaty = trPeace; + if (newTreaty < 0) + result = false; + else if (execute) { + assert(newTreaty > rw[pSender].Treaty[pTarget]); + rw[pSender].Treaty[pTarget] = newTreaty; + rw[pTarget].Treaty[pSender] = newTreaty; + if (newTreaty >= trFriendlyContact) { + giveCivilReport(pTarget, pSender); + giveCivilReport(pSender, pTarget); + } + if (newTreaty == trAlliance) { + giveMilReport(pTarget, pSender); + giveMilReport(pSender, pTarget); + copyMap(pSender, pTarget); + copyMap(pTarget, pSender); + recalcMapZoC(pSender); + recalcMapZoC(pTarget); + } + if (newTreaty != trPeace && newTreaty != trFriendlyContact) { + rw[pSender].EvaStart[pTarget] = -PeaceEvaTurns - 1; + rw[pTarget].EvaStart[pSender] = -PeaceEvaTurns - 1; + } + recalcPeaceMap(pSender); + recalcPeaceMap(pTarget); + } + } + break; + } + case opShipParts: { // + number + part type shl 16 + const int n = static_cast(price & 0xFFFF); // number + const int i = static_cast((price >> 16) & 0xF); // type + if (i < nShipPart && gShip[pSender].Parts[i] >= n) { + if (execute) { + gShip[pSender].Parts[i] -= n; + rw[pSender].Ship[pSender].Parts[i] = gShip[pSender].Parts[i]; + rw[pTarget].Ship[pSender].Parts[i] = gShip[pSender].Parts[i]; + if (rw[pTarget].NatBuilt[imSpacePort] > 0) { // space ship control requires space port + gShip[pTarget].Parts[i] += n; + rw[pSender].Ship[pTarget].Parts[i] = gShip[pTarget].Parts[i]; + rw[pTarget].Ship[pTarget].Parts[i] = gShip[pTarget].Parts[i]; + } + } + } else { + result = false; + } + break; + } + case opMoney: // + value + if (price - opMoney <= MaxMoneyPrice && rw[pSender].Money >= static_cast(price - opMoney)) { + if (execute) { + rw[pSender].Money -= static_cast(price - opMoney); + rw[pTarget].Money += static_cast(price - opMoney); + } + } else { + result = false; + } + break; + case opTribute: // + value + // tribute no longer in use - execute branch intentionally empty + break; + case opTech: // + advance + if (rw[pSender].Tech[price - opTech] >= tsApplicable) { + if (execute && rw[pTarget].Tech[price - opTech] == tsNA) { + seeTech(pTarget, static_cast(price - opTech)); + rw[pSender].EnemyReport[pTarget]->Tech[price - opTech] = tsSeen; + } + } else { + result = false; + } + break; + case opAllTech: + if (execute) { + for (int i = 0; i < nAdv; ++i) { + if (rw[pSender].Tech[i] >= tsApplicable && rw[pTarget].Tech[i] == tsNA) { + seeTech(pTarget, i); + rw[pSender].EnemyReport[pTarget]->Tech[i] = tsSeen; + rw[pTarget].EnemyReport[pSender]->Tech[i] = tsApplicable; + } + } + } + break; + case opModel: // + model index + if (static_cast(price - opModel) < rw[pSender].nModel) { + if (execute) + copyModel(pSender, pTarget, static_cast(price - opModel)); + } else { + result = false; + } + break; + case opAllModel: + if (execute) + for (int i = 0; i < rw[pSender].nModel; ++i) { + tellAboutModel(pTarget, pSender, i); + copyModel(pSender, pTarget, i); + } + break; + default: + break; + } + return result; +} + +void cancelTreaty(int p, int pWith, bool decreaseCredibility) +{ + TPlayerContext &player = rw[p]; + TPlayerContext &withPlayer = rw[pWith]; + const int oldTreaty = player.Treaty[pWith]; + peaceEnded = 0; + if (oldTreaty >= trPeace) + player.LastCancelTreaty[pWith] = gTurn; + if (decreaseCredibility) { + if (oldTreaty == trPeace) { + player.Credibility >>= 1; + if (player.MaxCredibility > 0) + player.MaxCredibility -= 10; + if (player.Credibility > player.MaxCredibility) + player.Credibility = player.MaxCredibility; + } else if (oldTreaty == trAlliance) { + player.Credibility = player.Credibility * 3 / 4; + } + withPlayer.EnemyReport[p]->Credibility = player.Credibility; + } + + if (oldTreaty == trPeace) { + for (int p1 = 0; p1 < nPl; ++p1) { + if (p1 == pWith || (decreaseCredibility && p1 != p && withPlayer.Treaty[p1] == trAlliance && + player.Treaty[p1] >= trPeace)) { + player.Treaty[p1] = trNone; + rw[p1].Treaty[p] = trNone; + player.EvaStart[p1] = -PeaceEvaTurns - 1; + rw[p1].EvaStart[p] = -PeaceEvaTurns - 1; + peaceEnded += (1 << p1); + } + } + checkBorders(-1); + if (mode > moLoading_Fast && peaceEnded > 0) + recalcMapZoC(p); + } else { + player.Treaty[pWith] = oldTreaty - 1; + withPlayer.Treaty[p] = oldTreaty - 1; + if (oldTreaty == trFriendlyContact) { // necessary for loading + giveCivilReport(p, pWith); + giveCivilReport(pWith, p); + } else if (oldTreaty == trAlliance) { // necessary for loading + giveMilReport(p, pWith); + giveMilReport(pWith, p); + } + if (mode > moLoading_Fast && oldTreaty == trAlliance) { + recalcMapZoC(p); + recalcMapZoC(pWith); + } + } + if (oldTreaty == trPeace || oldTreaty == trAlliance) { + recalcPeaceMap(p); + recalcPeaceMap(pWith); + } +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.GameInitialization.cpp b/game/src/Database.GameInitialization.cpp new file mode 100644 index 0000000..5065da2 --- /dev/null +++ b/game/src/Database.GameInitialization.cpp @@ -0,0 +1,310 @@ +// This file is part of cevo-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. + +// --- Game Initialization --- (see Cevo/Database.h) + +#include "Cevo/Database.h" +#include "DatabaseInternal.h" + +#include +#include +#include +#include +#include + +namespace Cevo { +namespace Database { + +// Delphi/Borland-compatible LCG (see Database.h) - only used by +// predefinedStartPositions() so far. +int delphiRandom(int max) +{ + const std::int64_t temp = static_cast(134775813) * static_cast(delphiRandSeed) + 1; + delphiRandSeed = static_cast(temp); + return static_cast((static_cast(static_cast(max)) * + static_cast(static_cast(delphiRandSeed))) >> + 32); +} + +void findContinents() +{ + auto replaceCont = [](int a, int b, int stop) { + if (a < b) + std::swap(a, b); + if (a > b) + for (int i = a; i <= stop; ++i) + if (continent[i] == a) + continent[i] = b; + }; + + for (int y = 1; y <= ly - 2; ++y) { + for (int x = 0; x < lx; ++x) { + const int loc = x + lx * y; + continent[loc] = -1; + if ((realMap[loc] & fTerrain) >= static_cast(fGrass)) { + if (y - 2 >= 1 && (realMap[loc - 2 * lx] & fTerrain) >= static_cast(fGrass)) + continent[loc] = continent[loc - 2 * lx]; + if ((x - 1 + (y & 1)) >= 0 && y - 1 >= 1 && + (realMap[loc - 1 + (y & 1) - lx] & fTerrain) >= static_cast(fGrass)) + continent[loc] = continent[loc - 1 + (y & 1) - lx]; + if ((x + (y & 1)) < lx && y - 1 >= 1 && + (realMap[loc + (y & 1) - lx] & fTerrain) >= static_cast(fGrass)) + continent[loc] = continent[loc + (y & 1) - lx]; + if (x - 1 >= 0 && (realMap[loc - 1] & fTerrain) >= static_cast(fGrass)) { + if (continent[loc] == -1) + continent[loc] = continent[loc - 1]; + else + replaceCont(continent[loc - 1], continent[loc], loc); + } + if (continent[loc] == -1) + continent[loc] = loc; + } + } + } + + // connect continents due to round earth + for (int y = 1; y <= ly - 2; ++y) { + if ((realMap[lx * y] & fTerrain) >= static_cast(fGrass)) { + int wrong = -1; + if ((realMap[lx - 1 + lx * y] & fTerrain) >= static_cast(fGrass)) + wrong = continent[lx - 1 + lx * y]; + if ((y & 1) == 0 && y - 1 >= 1 && + (realMap[lx - 1 + lx * (y - 1)] & fTerrain) >= static_cast(fGrass)) + wrong = continent[lx - 1 + lx * (y - 1)]; + if ((y & 1) == 0 && y + 1 < ly - 1 && + (realMap[lx - 1 + lx * (y + 1)] & fTerrain) >= static_cast(fGrass)) + wrong = continent[lx - 1 + lx * (y + 1)]; + if (wrong >= 0) + replaceCont(wrong, continent[lx * y], mapSize - 1); + } + } +} + +void predefinedStartPositions(int human) +{ + int nAlive = 0; + for (int p1 = 0; p1 < nPl; ++p1) + if ((1 << p1) & gAlive) + ++nAlive; + if (nAlive == 0) + return; + + std::vector startLoc0(static_cast(lxmax) * lymax, 0); + + int nStartLoc0 = 0; + int nPrefStartLoc0 = 0; + for (int loc1 = 0; loc1 < mapSize; ++loc1) { + if (realMap[loc1] & fPrefStartPos) { + startLoc0[static_cast(nStartLoc0)] = startLoc0[static_cast(nPrefStartLoc0)]; + startLoc0[static_cast(nPrefStartLoc0)] = loc1; + ++nPrefStartLoc0; + ++nStartLoc0; + realMap[loc1] &= ~static_cast(fPrefStartPos); + } else if (realMap[loc1] & fStartPos) { + startLoc0[static_cast(nStartLoc0)] = loc1; + ++nStartLoc0; + realMap[loc1] &= ~static_cast(fStartPos); + } + } + assert(nStartLoc0 >= nAlive); + + startLoc[0] = 0; + for (bool isHuman : { true, false }) { + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & gAlive) && ((((1 << p1) & human) != 0) == isHuman)) { + --nStartLoc0; + int imax = nStartLoc0; + if (nPrefStartLoc0 > 0) { + --nPrefStartLoc0; + imax = nPrefStartLoc0; + } + const int i = delphiRandom(imax + 1); + startLoc[p1] = startLoc0[static_cast(i)]; + startLoc2[p1] = startLoc0[static_cast(i)]; + startLoc0[static_cast(i)] = startLoc0[static_cast(imax)]; + startLoc0[static_cast(imax)] = startLoc0[static_cast(nStartLoc0)]; + } + } + } + saveMapCenterLoc = startLoc[0]; +} + +void initGame() +{ + occupant.fill(-1); + zocMap.fill(0); + observeLevel.fill(0); + usedByCity.fill(-1); + gTestFlags = 0; + gInitialized = gAlive | gWatching; + + for (int p = 0; p < nPl; ++p) { + if (((1 << p) & gInitialized) == 0) + continue; + TPlayerContext &player = rw[p]; + researched[p] = 0; + discovered[p] = 0; + territoryCount[p] = 0; + nTech[p] = 0; + resourceMask[p] = (difficulty[p] == 0) ? 0xFFFFFFFFu : (0xFFFFFFFFu & ~static_cast(fSpecial2 | fModern)); + grWallContinent[p] = -1; + + player.Map = reinterpret_cast(new std::uint32_t[static_cast(mapSize)]()); + player.MapObservedLast = reinterpret_cast(new std::int16_t[static_cast(mapSize)]); + std::memset(*player.MapObservedLast, 0xFF, static_cast(mapSize) * 2); + player.Territory = reinterpret_cast(new std::int8_t[static_cast(mapSize)]); + std::memset(*player.Territory, 0xFF, static_cast(mapSize)); + player.Un = reinterpret_cast(new TUn[nUmax]()); + player.Model = reinterpret_cast(new TModel[nMmax + 1]()); + player.City = reinterpret_cast(new TCity[nCmax]()); + player.EnemyUn = reinterpret_cast(new TUnitInfo[neumax]()); + player.EnemyCity = reinterpret_cast(new TCityInfo[necmax]()); + player.EnemyModel = reinterpret_cast(new TModelInfo[nemmax]()); + + for (int p1 = 0; p1 < nPl; ++p1) { + if ((1 << p1) & gInitialized) { + std::memset(rwemix[p][p1].data(), 0xFF, rwemix[p][p1].size() * sizeof(std::int16_t)); + std::memset(destroyed[p][p1].data(), 0, destroyed[p][p1].size() * sizeof(std::int16_t)); + } + player.Attitude[p1] = atNeutral; + player.Treaty[p1] = trNoContact; + player.LastCancelTreaty[p1] = -CancelTreatyTurns - 1; + player.EvaStart[p1] = -PeaceEvaTurns - 1; + player.Tribute[p1] = 0; + player.TributePaid[p1] = 0; + if (p1 != p && ((1 << p1) & gAlive)) { + // Truncated allocation (matches the original's own GetMem + // size: TEnemyReport's UnCount[] field is oversized via the + // same "open array via overlarge static type" trick used + // throughout this port - only nMmax slots are real). + player.EnemyReport[p1] = static_cast( + ::operator new(sizeof(TEnemyReport) - sizeof(std::uint16_t) * (INFIN + 1 - nMmax))); + std::memset(player.EnemyReport[p1]->Tech, tsNA, nAdv); + player.EnemyReport[p1]->TurnOfContact = -1; + player.EnemyReport[p1]->TurnOfCivilReport = -1; + player.EnemyReport[p1]->TurnOfMilReport = -1; + player.EnemyReport[p1]->Attitude = atNeutral; + player.EnemyReport[p1]->Government = gDespotism; + if (((1 << p) & gAlive) == 0) + player.Treaty[p1] = trNone; // supervisor + } else { + player.EnemyReport[p1] = nullptr; + } + } + player.TestFlags = gTestFlags; + player.Credibility = InitialCredibility; + player.MaxCredibility = 100; + player.nUn = 0; + player.nModel = 0; + player.nCity = 0; + player.nEnemyUn = 0; + player.nEnemyCity = 0; + player.nEnemyModel = 0; + std::uint32_t *map = *player.Map; + for (int loc1 = 0; loc1 < mapSize; ++loc1) + map[loc1] = fUNKNOWN; + std::memset(player.Tech, tsNA, nAdv); + std::memset(player.NatBuilt, 0, sizeof(player.NatBuilt)); + } + + // create initial models and units + for (int p = 0; p < nPl; ++p) { + if (((1 << p) & gAlive) == 0) + continue; + TPlayerContext &player = rw[p]; + TModel *model = *player.Model; + player.nModel = 0; + for (int i = 0; i < nSpecialModel; ++i) { + if (SpecialModelPreq[i] == preNone) { + model[player.nModel] = SpecialModel[i]; + model[player.nModel].Status = 0; + model[player.nModel].IntroTurn = 0; + model[player.nModel].Built = 0; + model[player.nModel].Lost = 0; + model[player.nModel].ID = static_cast((p << 12) + player.nModel); + setModelFlags(model[player.nModel]); + ++player.nModel; + } + } + player.nUn = 0; + unBuilt[p] = 0; + TUn *un = *player.Un; + for (int uix = 0; uix < nStartUn; ++uix) { + createUnit(p, StartUn[uix]); + --model[StartUn[uix]].Built; + un[uix].Loc = startLoc2[p]; + placeUnit(p, uix); + } + foundCity(p, startLoc[p]); + founded[p] = 1; + TCity &city = (*player.City)[0]; + city.ID = static_cast(p << 12); + city.Flags = chFounded; + } + + territoryCount[nPl] = mapSize; +} + +void initMapGame(int human) +{ + delphiRandSeed = rnd; + findContinents(); + predefinedStartPositions(human); + initGame(); +} + +void initRandomGame() +{ + throw std::runtime_error( + "Random map generation is not supported yet (CreateElevation/CreateMap/StartPositions not ported)."); +} + +void releaseGame() +{ + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & gInitialized) == 0) + continue; + TPlayerContext &player = rw[p1]; + for (int p2 = 0; p2 < nPl; ++p2) + if (player.EnemyReport[p2]) + ::operator delete(player.EnemyReport[p2]); + delete[] reinterpret_cast(player.EnemyUn); + delete[] reinterpret_cast(player.EnemyCity); + delete[] reinterpret_cast(player.EnemyModel); + delete[] reinterpret_cast(player.Un); + delete[] reinterpret_cast(player.City); + delete[] reinterpret_cast(player.Model); + delete[] reinterpret_cast(player.Territory); + delete[] reinterpret_cast(player.MapObservedLast); + delete[] reinterpret_cast(player.Map); + } + gInitialized = 0; +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.LocationNavigation.cpp b/game/src/Database.LocationNavigation.cpp new file mode 100644 index 0000000..600a3d1 --- /dev/null +++ b/game/src/Database.LocationNavigation.cpp @@ -0,0 +1,137 @@ +// This file is part of cevo-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. + +// --- Location Navigation --- (see Cevo/Database.h) + +#include "Cevo/Database.h" + +#include +#include +#include + +namespace Cevo { +namespace Database { + +int dLoc(int loc, int dx, int dy) +{ + // Faithful port of a likely upstream operator-precedence slip: Pascal's + // `not` binds tighter than `and`, so this only negates the first clause + // instead of the whole precondition. The very next line's assert + // re-checks the FULL intended condition correctly, and this isn't a + // memory-safety issue, so it's preserved as-is rather than silently + // "fixed" (see established policy in repo memory). + if (!(loc >= 0) && (loc < mapSize) && (dx + lx >= 0)) + throw std::runtime_error("Relative location error"); + assert((loc >= 0) && (loc < mapSize) && (dx + lx >= 0)); + + const int y0 = loc / lx; + int result = (loc + ((dx + (y0 & 1) + lx + lx) >> 1)) % lx + lx * (y0 + dy); + if (result < 0 || result >= mapSize) + result = -1; + return result; +} + +void dxdy(int loc0, int loc1, int &dx, int &dy) +{ + dx = (((loc1 % lx) * 2 + ((loc1 / lx) & 1)) - ((loc0 % lx) * 2 + ((loc0 / lx) & 1)) + 3 * lx) % (2 * lx) - lx; + dy = loc1 / lx - loc0 / lx; +} + +int distance(int loc0, int loc1) +{ + int dx, dy; + dxdy(loc0, loc1, dx, dy); + dx = std::abs(dx); + dy = std::abs(dy); + return dx + dy + (std::abs(dx - dy) >> 1); +} + +void v8ToLoc(int loc0, Vicinity8Loc &vicinityLoc) +{ + const int lx0 = lx; + int y0 = loc0 / lx0; + const int x0 = loc0 - y0 * lx0; + y0 &= 1; + vicinityLoc[1] = loc0 + lx0 * 2; + vicinityLoc[3] = loc0 - 1; + vicinityLoc[5] = loc0 - lx0 * 2; + vicinityLoc[7] = loc0 + 1; + loc0 += y0; + vicinityLoc[0] = loc0 + lx0; + vicinityLoc[2] = loc0 + lx0 - 1; + vicinityLoc[4] = loc0 - lx0 - 1; + vicinityLoc[6] = loc0 - lx0; + + // world is round! + if (x0 < lx0 - 1) { + if (x0 == 0) { + vicinityLoc[3] += lx0; + if (y0 == 0) { + vicinityLoc[2] += lx0; + vicinityLoc[4] += lx0; + } + } + } else { + vicinityLoc[7] -= lx0; + if (y0 == 1) { + vicinityLoc[0] -= lx0; + vicinityLoc[6] -= lx0; + } + } +} + +void v21ToLoc(int loc0, Vicinity21Loc &vicinityLoc) +{ + const int y0 = loc0 / lx; + int xComp0 = loc0 - y0 * lx - 1; // loc0 % lx - 1 + int xCompSwitch = xComp0 - 1 + (y0 & 1); + if (xComp0 < 0) + xComp0 += lx; + if (xCompSwitch < 0) + xCompSwitch += lx; + xCompSwitch ^= xComp0; + int yComp = lx * (y0 - 3); + int *dst = vicinityLoc.data(); + int bit = 1; + for (int dy = 0; dy < 7; ++dy) { + xComp0 ^= xCompSwitch; + int xComp = xComp0; + for (int dx = 0; dx < 4; ++dx) { + *dst = (bit & 0x67F7F76) != 0 ? xComp + yComp : -1; + ++xComp; + if (xComp >= lx) + xComp -= lx; + ++dst; + bit <<= 1; + } + yComp += lx; + } +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.MapCreation.cpp b/game/src/Database.MapCreation.cpp new file mode 100644 index 0000000..096e9b3 --- /dev/null +++ b/game/src/Database.MapCreation.cpp @@ -0,0 +1,73 @@ +// This file is part of cevo-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. + +// --- Map Creation --- (see Cevo/Database.h) + +#include "Cevo/Database.h" + +namespace Cevo { +namespace Database { + +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; +} // namespace + +void calculatePrimitive() +{ + primitive = 1; + int i = 2; + while (i * i <= mapSize + 1) { // test whether prime + if ((mapSize + 1) % i == 0) + primitive = 0; + ++i; + } + + if (primitive > 0) { + int j = 0; + do { + ++primitive; + i = 1; + j = 0; + do { + ++j; + i = i * primitive % (mapSize + 1); + } while (!(i == 1 || j == mapSize + 1)); + } while (!(j == mapSize)); + } +} + +bool mapGeneratorAvailable() +{ + return primitive > 0 && lx >= 20 && ly >= 40; +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.MapEditor.cpp b/game/src/Database.MapEditor.cpp new file mode 100644 index 0000000..e2de365 --- /dev/null +++ b/game/src/Database.MapEditor.cpp @@ -0,0 +1,110 @@ +// This file is part of cevo-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. + +// --- Map Editor --- (see Cevo/Database.h) + +#include "Cevo/Database.h" + +namespace Cevo { +namespace Database { + +bool checkShore(int loc) +{ + const std::uint32_t oldTile = realMap[loc]; + if ((oldTile & fTerrain) >= static_cast(fGrass)) + return false; + realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(fOcean); + Vicinity21Loc radius; + v21ToLoc(loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + const int loc1 = radius[static_cast(v21)]; + if (loc1 >= 0 && loc1 < mapSize && (realMap[loc1] & fTerrain) >= static_cast(fGrass) && + (realMap[loc1] & fTerrain) != static_cast(fArctic)) + realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(fShore); + } + return ((realMap[loc] ^ oldTile) & fTerrain) != 0; +} + +void editTile(int loc, std::uint32_t newTile) +{ + if (newTile & fDeadLands) + newTile = (newTile & (fDeadLands | fModern | fRiver)) | fDesert; + switch (newTile & fTerrain) { + case fOcean: + case fShore: + newTile &= (fTerrain | fSpecial); + break; + case fMountains: + case fArctic: + newTile &= ~static_cast(fRiver); + break; + default: + break; + } + const TerrainInfo &terrain = Terrain[newTile & fTerrain]; + if (terrain.ClearTerrain >= 0 || terrain.AfforestTerrain >= 0 || terrain.TransTerrain >= 0) + newTile |= fSpecial; // only automatic special resources for transformable tiles + if (newTile & fRR) + newTile &= ~static_cast(fRoad); + if (((terrTypeCanalableMask >> (newTile & fTerrain)) & 1) == 0) + newTile &= ~static_cast(fCanal); + if (Terrain[newTile & fTerrain].IrrEff == 0) { + newTile &= ~static_cast(fPrefStartPos | fStartPos); + if ((newTile & fTerImp) == tiIrrigation || (newTile & fTerImp) == tiFarm) + newTile &= ~static_cast(fTerImp); + } + if (Terrain[newTile & fTerrain].MineEff == 0 && (newTile & fTerImp) == tiMine) + newTile &= ~static_cast(fTerImp); + + realMap[loc] = newTile; + if ((newTile & fSpecial) == fSpecial) // standard special resource distribution + realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); + + // automatic shore tiles + Vicinity21Loc radius; + v21ToLoc(loc, radius); + for (int v21 = 1; v21 <= 26; ++v21) { + const int loc1 = radius[static_cast(v21)]; + if (loc1 >= 0 && loc1 < mapSize) { + if (checkShore(loc1)) + realMap[loc1] = (realMap[loc1] & ~static_cast(fSpecial)) | (actualSpecialTile(loc1) << 5); + realMap[loc1] |= (0xFu << 27); + (*rw[0].Map)[loc1] = (realMap[loc1] & 0x07FFFFFFu) | fObserved; + } + } +} + +void releaseMapEditor() +{ + delete[] reinterpret_cast(rw[0].Territory); + delete[] reinterpret_cast(rw[0].MapObservedLast); + delete[] reinterpret_cast(rw[0].Map); +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.MapProcessing.cpp b/game/src/Database.MapProcessing.cpp new file mode 100644 index 0000000..9152c9e --- /dev/null +++ b/game/src/Database.MapProcessing.cpp @@ -0,0 +1,398 @@ +// This file is part of cevo-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. + +// --- Map Processing --- (see Cevo/Database.h) + +#include "Cevo/Database.h" +#include "DatabaseInternal.h" + +#include +#include + +namespace Cevo { +namespace Database { + +// Equivalent of Database.pas's private `UnBuilt` global (see +// DatabaseInternal.h) - defined here since createUnit() is its primary +// user; also reset by Database.GameInitialization.cpp's initGame(). +std::array unBuilt{}; + +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; + } +} + +namespace { +// Equivalent of Database.pas's private CountLost() - only used here. +void countLost(int p, int mix, int enemy) +{ + ++(*rw[p].Model)[mix].Lost; + tellAboutModel(enemy, p, mix); + ++destroyed[enemy][p][mix]; +} +} // namespace + +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 removeDomainUnits(int d, int p, int loc) +{ + TPlayerContext &player = rw[p]; + TUn *un = *player.Un; + const TModel *model = *player.Model; + for (int uix = 0; uix < player.nUn; ++uix) + if (model[un[uix].mix].Domain == d && un[uix].Loc == loc) + removeUnit(p, uix); +} + +void removeAllUnits(int p, int loc, int enemy) +{ + TPlayerContext &player = rw[p]; + TUn *un = *player.Un; + for (int uix = 0; uix < player.nUn; ++uix) { + if (un[uix].Loc == loc) { + if (enemy >= 0) + countLost(p, un[uix].mix, enemy); + un[uix].Loc = -1; + } + } + occupant[loc] = -1; + zocMap[loc] = 0; +} + +void compactLists(int p) +{ + TPlayerContext &player = rw[p]; + TUn *un = *player.Un; + TCity *city = *player.City; + TCityInfo *enemyCity = *player.EnemyCity; + + // compact unit list + int uix = 0; + while (uix < player.nUn) { + if (un[uix].Loc < 0) { + --player.nUn; + un[uix] = un[player.nUn]; // replace removed unit by last + if (un[uix].TroopLoad > 0 || un[uix].AirLoad > 0) + for (int uix1 = 0; uix1 < player.nUn; ++uix1) + if (un[uix1].Master == player.nUn) // index of last unit changes + un[uix1].Master = uix; + } else { + ++uix; + } + } + + // compact city list + int cix = 0; + while (cix < player.nCity) { + if (city[cix].Loc < 0) { + --player.nCity; + city[cix] = city[player.nCity]; // replace city by last + for (int uix1 = 0; uix1 < player.nUn; ++uix1) + if (un[uix1].Home == player.nCity) // index of last city changes + un[uix1].Home = cix; + } else { + ++cix; + } + } + + // compact enemy city list + cix = 0; + while (cix < player.nEnemyCity) { + if (enemyCity[cix].Loc < 0) { + --player.nEnemyCity; + enemyCity[cix] = enemyCity[player.nEnemyCity]; // replace city by last + } else { + ++cix; + } + } +} + +int specialTile(int loc, int terrType, int lx) +{ + if (terrType == fOcean) + return 0; + const int y = loc / lx; + const int x = loc - y * lx; + if (terrType == fGrass) { // formula for productive grassland + const int v1 = lymax + x - (y >> 1); + return (((v1 >> 1) + x + ((y + 1) >> 1)) & 1) ? 1 : 0; + } + // formula for special resources + const int a = 4 * x - y + 9980; + const int qx = a / 10; + if (qx * 10 != a || (qx & 3) == 0) + return 0; + const int qy = (y + x) / 5; + if ((qy & 3) == ((qx >> 2) & 1) * 2) + return 0; + if (terrType == fArctic || terrType == fSwamp) + return 1; + if (terrType == fShore) { + if (((qx + qy) & 1) == 0) + return (qx & 3) == 2 ? 2 : 1; + return 0; + } + return ((qx + qy) & 1) + 1; +} + +std::uint32_t actualSpecialTile(int loc) +{ + return static_cast(specialTile(loc, static_cast(realMap[loc] & fTerrain), lx)); +} + +void foundCity(int p, int foundLoc) +{ + TPlayerContext &player = rw[p]; + if (player.nCity == nCmax) + return; + ++player.nCity; + TCity &city = (*player.City)[player.nCity - 1]; + city.Size = 2; + city.Status = 0; + city.SavedStatus = 0; + std::fill(std::begin(city.Built), std::end(city.Built), 0); + city.Food = 0; + city.Project = cpImp + imTrGoods; + city.Prod = 0; + city.Project0 = city.Project; + city.Prod0 = 0; + city.Pollution = 0; + city.N1 = 0; + city.Loc = foundLoc; + if (usedByCity[foundLoc] >= 0) { // central tile is exploited - toggle in exploiting city + int p1 = p; + int cix1; + searchCity(usedByCity[foundLoc], p1, cix1); + int dx, dy; + dxdy(usedByCity[foundLoc], foundLoc, dx, dy); + const int v21 = ((dy + 3) << 2) + ((dx + 3) >> 1); + (*rw[p1].City)[cix1].Tiles &= ~(1u << v21); + } + city.Tiles = 1u << 13; // exploit central tile + usedByCity[foundLoc] = foundLoc; + realMap[foundLoc] = + (realMap[foundLoc] & (fTerrain | fSpecial | fRiver | (static_cast(nPl) << 27))) | fCity; + + changeTerritory(city.Loc, p); +} + +void completeJob(int p, int loc, int job) +{ + assert(job != jCity); + int changedTerrain = -1; + switch (job) { + case jRoad: + realMap[loc] |= fRoad; + break; + case jRR: + realMap[loc] = (realMap[loc] & ~static_cast(fRoad)) | fRR; + break; + case jClear: + changedTerrain = Terrain[realMap[loc] & fTerrain].ClearTerrain; + realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); + realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); + break; + case jIrr: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiIrrigation; + break; + case jFarm: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiFarm; + break; + case jAfforest: + changedTerrain = Terrain[realMap[loc] & fTerrain].AfforestTerrain; + realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); + realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); + break; + case jMine: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiMine; + break; + case jFort: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiFort; + break; + case jCanal: + realMap[loc] |= fCanal; + break; + case jTrans: + changedTerrain = Terrain[realMap[loc] & fTerrain].TransTerrain; + realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); + realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); + if (((terrTypeCanalableMask >> (realMap[loc] & fTerrain)) & 1) == 0) { + removeDomainUnits(dSea, p, loc); + realMap[loc] &= ~static_cast(fCanal); + } + break; + case jPoll: + realMap[loc] &= ~static_cast(fPoll); + break; + case jBase: + realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiBase; + break; + case jPillage: + if (realMap[loc] & fTerImp) { + if ((realMap[loc] & fTerImp) == tiBase) + removeDomainUnits(dAir, p, loc); + realMap[loc] &= ~static_cast(fTerImp); + } else if (realMap[loc] & fCanal) { + removeDomainUnits(dSea, p, loc); + realMap[loc] &= ~static_cast(fCanal); + } else if (realMap[loc] & fRR) { + realMap[loc] = (realMap[loc] & ~static_cast(fRR)) | fRoad; + } else if (realMap[loc] & fRoad) { + realMap[loc] &= ~static_cast(fRoad); + } + break; + default: + break; + } + + if (changedTerrain >= 0) { // remove terrain improvements if not possible on new terrain + if (((realMap[loc] & fTerImp) == tiIrrigation || (realMap[loc] & fTerImp) == tiFarm) && + (Terrain[changedTerrain].IrrClearWork == 0 || Terrain[changedTerrain].ClearTerrain >= 0)) + realMap[loc] &= ~static_cast(fTerImp); + if ((realMap[loc] & fTerImp) == tiMine && + (Terrain[changedTerrain].MineAfforestWork == 0 || Terrain[changedTerrain].AfforestTerrain >= 0)) + realMap[loc] &= ~static_cast(fTerImp); + } + + // update map of all observing players + if (mode > moLoading_Fast) { + constexpr std::uint32_t mask = fTerrain | fSpecial | fTerImp | fRoad | fRR | fCanal | fPoll; + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & (gAlive | gWatching)) && (((observeLevel[loc] >> (2 * p1)) & 3) > lNoObserve)) { + std::uint32_t &tile = (*rw[p1].Map)[loc]; + tile = (tile & ~mask) | (realMap[loc] & mask); + } + } + } +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.MapRevealing.cpp b/game/src/Database.MapRevealing.cpp new file mode 100644 index 0000000..61ceeae --- /dev/null +++ b/game/src/Database.MapRevealing.cpp @@ -0,0 +1,663 @@ +// This file is part of cevo-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. + +// --- Map Revealing --- (see Cevo/Database.h) + +#include "Cevo/Database.h" + +#include + +namespace Cevo { +namespace Database { + +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; +} + +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 diff --git a/game/src/Database.TechRelated.cpp b/game/src/Database.TechRelated.cpp new file mode 100644 index 0000000..18ed7fc --- /dev/null +++ b/game/src/Database.TechRelated.cpp @@ -0,0 +1,222 @@ +// This file is part of cevo-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. + +// --- Tech Related Functions --- (see Cevo/Database.h) + +#include "Cevo/Database.h" +#include "DatabaseInternal.h" + +#include + +namespace Cevo { +namespace Database { + +// 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; + } + } +} + +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 calculateModel(TModel &m) +{ + m.Attack = static_cast((m.Cap[mcOffense] + m.Cap[mcOver]) * m.MStrength); + m.Defense = static_cast((m.Cap[mcDefense] + m.Cap[mcOver]) * m.MStrength); + switch (m.Domain) { + case dGround: + m.Speed = static_cast(150 + m.Cap[mcMob] * 50); + break; + case dSea: + m.Speed = static_cast(350 + 200 * m.Cap[mcNP] + 200 * m.Cap[mcTurbines]); + if (m.Cap[mcNP] == 0) + m.Speed = static_cast(m.Speed + 100 * m.Cap[mcSE]); + break; + case dAir: + m.Speed = static_cast(850 + 400 * m.Cap[mcJet]); + break; + default: + break; + } + int cost = 0; + for (int i = 0; i < nFeature; ++i) + if ((1 << m.Domain) & Feature[i].Domains) + cost += m.Cap[i] * Feature[i].Cost; + m.Cost = static_cast(cost * m.MCost); + int weight = 0; + for (int i = 0; i < nFeature; ++i) + if ((1 << m.Domain) & Feature[i].Domains) + weight += (m.Domain == dGround && i == mcDefense) ? m.Cap[i] * 2 : m.Cap[i] * Feature[i].Weight; + m.Weight = static_cast(weight); + setModelFlags(m); +} + +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 seeTech(int p, int ad) +{ + rw[p].Tech[ad] = tsSeen; + ++researched[p]; +} + +namespace { +void tellAboutKeyTech(int p, int source, int ad) +{ + for (int i = 1; i <= 3; ++i) + if (ad == AgePreq[i]) + for (int p1 = 0; p1 < nPl; ++p1) + if (p1 != p && ((gAlive | gWatching) & (1 << p1))) + rw[p1].EnemyReport[p]->Tech[ad] = static_cast(source); +} +} // namespace + +void discoverTech(int p, int ad) +{ + TPlayerContext &player = rw[p]; + if (IsFutureTech(ad)) { + if (player.Tech[ad] < tsApplicable) + player.Tech[ad] = 1; + else + ++player.Tech[ad]; + if (ad != futResearchTechnology) + nTech[p] += 2; + researched[p] += 8; + return; + } + + if (player.Tech[ad] == tsSeen) { + ++nTech[p]; + ++researched[p]; + } else { + nTech[p] += 2; + researched[p] += 2; + } + player.Tech[ad] = tsResearched; + tellAboutKeyTech(p, tsResearched, ad); + checkSpecialModels(p, ad); + if (ad == adScience) + resourceMask[p] |= fSpecial2; + if (ad == adMassProduction) + resourceMask[p] |= fModern; + + for (int i = 0; i < nWonder; ++i) { // check whether wonders expired + if (gWonder[i].EffectiveOwner != gWonder[woEiffel].EffectiveOwner && Imp[i].Expiration == ad) { + gWonder[i].EffectiveOwner = -1; + if (i == woPyramids) + freeSlaves(); + } + } +} + +void enableDevModel(int p) +{ + TPlayerContext &player = rw[p]; + if (player.nModel >= nMmax) + return; + TModel *model = *player.Model; + model[player.nModel] = player.DevModel; + 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); + ++player.nModel; + ++researched[p]; +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.TerritoryCalculation.cpp b/game/src/Database.TerritoryCalculation.cpp new file mode 100644 index 0000000..d70c8d7 --- /dev/null +++ b/game/src/Database.TerritoryCalculation.cpp @@ -0,0 +1,299 @@ +// This file is part of cevo-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. + +// --- Territory Calculation --- (see Cevo/Database.h) + +#include "Cevo/Database.h" +#include "DatabaseInternal.h" + +#include +#include +#include + +namespace Cevo { +namespace Database { + +void changeTerritory(int loc, int p) +{ + assert(p >= 0); // no player's territory indicated by p == nPl + --territoryCount[realMap[loc] >> 27]; + ++territoryCount[p]; + realMap[loc] = (realMap[loc] & ~(0xFu << 27)) | (static_cast(p) << 27); + if (p == 0xF) + p = -1; + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & (gAlive | gWatching)) == 0) + continue; + TPlayerContext &player = rw[p1]; + if (((*player.Map)[loc] & fTerrain) == fUNKNOWN) + continue; + (*player.Territory)[loc] = static_cast(p); + // Faithful port of the original relying on x86 SHL masking the shift + // count to 5 bits when p==-1 (so `1 shl p` becomes `1 shl 31`, never + // matching gAlive, rather than C++'s real UB for negative shifts) - + // see repo memory's policy on preserving known upstream quirks. + if (p < nPl && p != p1 && ((1u << (p & 31)) & static_cast(gAlive)) && + (player.Treaty[p] == trPeace || player.Treaty[p] == trFriendlyContact)) + (*player.Map)[loc] |= fPeace; + else + (*player.Map)[loc] &= ~static_cast(fPeace); + } +} + +void expandTerritory(int originLoc) +{ + if (originLoc == -1) + throw std::runtime_error("Location error"); + int i = 0; + int dyMax = 0; + while ((dyMax + 1) + ((dyMax + 1) >> 1) <= CountryRadius) + ++dyMax; + for (int dy = -dyMax; dy <= dyMax; ++dy) { + int dxMax = dy & 1; + while (std::abs(dy) + (dxMax + 2) + (std::abs(std::abs(dy) - (dxMax + 2)) >> 1) <= CountryRadius) + dxMax += 2; + for (int dx = -dxMax; dx <= dxMax; ++dx) { + if (((dy + dx) & 1) == 0) { + const std::uint32_t newOwner = (borderChanges[i / 8] >> ((i % 8) * 4)) & 0xF; + const int loc = dLoc(originLoc, dx, dy); + if (loc >= 0 && newOwner != (realMap[loc] >> 27)) + changeTerritory(loc, static_cast(newOwner)); + ++i; + } + } + } +} + +void checkBorders(int originLoc, int playerLosingCity) +{ + std::array country{}; + std::array formerCountry{}; + std::array dist{}; + std::array formerDist{}; + std::array stolenDist{}; + std::array, nPl + 1> atPeace{}; + Vicinity8Loc adjacent; + + constexpr std::uint32_t noZocTerrainMask = (1u << fShore) | (1u << fMountains) | (1u << fArctic); + + if (playerLosingCity >= 0) { + for (int loc = 0; loc < mapSize; ++loc) + stolenDist[loc] = static_cast(CountryRadius + 1); + for (int cix = 0; cix < rw[playerLosingCity].nCity; ++cix) { + const int loc = (*rw[playerLosingCity].City)[cix].Loc; + if (loc >= 0) + stolenDist[loc] = 0; + } + + for (int r = 1; r <= (CountryRadius >> 1); ++r) { + formerDist = stolenDist; + for (int loc = 0; loc < mapSize; ++loc) { + if (formerDist[loc] <= CountryRadius - 2 && + ((1u << (realMap[loc] & fTerrain)) & noZocTerrainMask) == 0) { + v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[v8]; + const int newDist = formerDist[loc] + 2 + (v8 & 1); + if (loc1 >= 0 && loc1 < mapSize && newDist < stolenDist[loc1]) + stolenDist[loc1] = static_cast(newDist); + } + } + } + } + } + + country.fill(-1); + for (int loc = 0; loc < mapSize; ++loc) + dist[loc] = static_cast(CountryRadius + 1); + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & gAlive) == 0) + continue; + for (int cix = 0; cix < rw[p1].nCity; ++cix) { + const int loc = (*rw[p1].City)[cix].Loc; + if (loc >= 0) { + country[loc] = static_cast(p1); + dist[loc] = 0; + } + } + } + + for (int r = 1; r <= (CountryRadius >> 1); ++r) { + formerCountry = country; + formerDist = dist; + for (int loc = 0; loc < mapSize; ++loc) { + if (formerDist[loc] <= CountryRadius - 2 && + ((1u << (realMap[loc] & fTerrain)) & noZocTerrainMask) == 0) { + assert(formerCountry[loc] >= 0); + v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[v8]; + const int newDist = formerDist[loc] + 2 + (v8 & 1); + if (loc1 >= 0 && loc1 < mapSize && newDist < dist[loc1]) { + country[loc1] = formerCountry[loc]; + dist[loc1] = static_cast(newDist); + } + } + } + } + } + + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & gAlive) == 0) + continue; + for (int p2 = 0; p2 < nPl; ++p2) + if (p2 != p1 && ((1 << p2) & gAlive) && rw[p1].Treaty[p2] >= trPeace) + atPeace[p1][p2] = true; + } + + if (originLoc >= 0) { + int i = 0; + borderChanges.fill(0); + int dyMax = 0; + while ((dyMax + 1) + ((dyMax + 1) >> 1) <= CountryRadius) + ++dyMax; + for (int dy = -dyMax; dy <= dyMax; ++dy) { + int dxMax = dy & 1; + while (std::abs(dy) + (dxMax + 2) + (std::abs(std::abs(dy) - (dxMax + 2)) >> 1) <= CountryRadius) + dxMax += 2; + for (int dx = -dxMax; dx <= dxMax; ++dx) { + if (((dy + dx) & 1) == 0) { + const int loc = dLoc(originLoc, dx, dy); + if (loc >= 0) { + const int oldOwner = static_cast(realMap[loc] >> 27); + int newOwner = country[loc] & 0xF; + if (newOwner != oldOwner) { + if (atPeace[newOwner][oldOwner] && + !(oldOwner == playerLosingCity && stolenDist[loc] > CountryRadius)) + newOwner = oldOwner; // peace fixes borders + else + changeTerritory(loc, newOwner); + } + borderChanges[i >> 3] |= static_cast(newOwner) << ((i & 7) * 4); + } + ++i; + } + } + } + } else { + for (int loc = 0; loc < mapSize; ++loc) { + const int oldOwner = static_cast(realMap[loc] >> 27); + const int newOwner = country[loc] & 0xF; + if (newOwner != oldOwner && + (!atPeace[newOwner][oldOwner] || (oldOwner == playerLosingCity && stolenDist[loc] > CountryRadius))) { + assert(originLoc != -2); // test if border saving works + changeTerritory(loc, newOwner); + } + } + } + +#ifndef NDEBUG + if (originLoc != -2) + checkBorders(-2); // check: single pass should do! +#endif +} + +void logCheckBorders(int p, int cix, int playerLosingCity) +{ + checkBorders((*rw[p].City)[cix].Loc, playerLosingCity); + intServer(sIntExpandTerritory, p, cix, borderChanges.data()); +} + +void recalcPeaceMap(int p) +{ + if (mode != moPlaying) + return; + TPlayerContext &player = rw[p]; + maskD(*player.Map, mapSize, ~static_cast(fPeace)); + std::array peacePlayer{}; // index p1+1, covers p1 in -1..nPl-1 + for (int p1 = 0; p1 < nPl; ++p1) + peacePlayer[p1 + 1] = p1 != p && ((1 << p1) & gAlive) && + (player.Treaty[p1] == trPeace || player.Treaty[p1] == trFriendlyContact); + std::uint32_t *map = *player.Map; + const TOwnerList &territory = *player.Territory; + for (int loc = 0; loc < mapSize; ++loc) + if (peacePlayer[territory[loc] + 1]) + map[loc] |= fPeace; +} + +void recalcMapZoC(int p) +{ + if (mode == moLoading_Fast) + return; + maskD(*rw[p].Map, mapSize, ~static_cast(fInEnemyZoC)); + const int observeMask = 3 << (2 * p); + std::uint32_t *map = *rw[p].Map; + for (int loc = 0; loc < mapSize; ++loc) { + if (zocMap[loc] > 0 && (observeLevel[loc] & observeMask)) { + const int p1 = occupant[loc]; + assert(p1 != nPl); + if (p1 != p && rw[p].Treaty[p1] < trAlliance) { + // this non-allied enemy ZoC unit is known to this player -- set flags! + Vicinity8Loc adjacent; + v8ToLoc(loc, adjacent); + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[static_cast(v8)]; + if (loc1 >= 0 && loc1 < mapSize) + map[loc1] |= fInEnemyZoC; + } + } + } + } +} + +void recalcV8ZoC(int p, int loc) +{ + if (mode == moLoading_Fast) + return; + const int observeMask = 3 << (2 * p); + Vicinity8Loc adjacent; + v8ToLoc(loc, adjacent); + std::uint32_t *map = *rw[p].Map; + for (int v8 = 0; v8 < 8; ++v8) { + const int loc1 = adjacent[static_cast(v8)]; + if (loc1 < 0 || loc1 >= mapSize) + continue; + std::uint32_t &tile1 = map[loc1]; + tile1 &= ~static_cast(fInEnemyZoC); + Vicinity8Loc adjacentAdjacent; + v8ToLoc(loc1, adjacentAdjacent); + for (int v8v8 = 0; v8v8 < 8; ++v8v8) { + const int loc2 = adjacentAdjacent[static_cast(v8v8)]; + if (loc2 >= 0 && loc2 < mapSize && zocMap[loc2] > 0 && (observeLevel[loc2] & observeMask)) { + const int p1 = occupant[loc2]; + assert(p1 != nPl); + if (p1 != p && rw[p].Treaty[p1] < trAlliance) { + tile1 |= fInEnemyZoC; + break; + } + } + } + } +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.TestFlags.cpp b/game/src/Database.TestFlags.cpp new file mode 100644 index 0000000..70eab5f --- /dev/null +++ b/game/src/Database.TestFlags.cpp @@ -0,0 +1,93 @@ +// This file is part of cevo-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. + +// --- Test Flags --- (see Cevo/Database.h) + +#include "Cevo/Database.h" + +namespace Cevo { +namespace Database { + +void clearTestFlags(int clearFlags) +{ + gTestFlags &= (~clearFlags | tfTested | tfAllTechs | tfAllContact); + for (int p1 = 0; p1 < nPl; ++p1) + if ((1 << p1) & (gAlive | gWatching)) + rw[p1].TestFlags = gTestFlags; +} + +void setTestFlags(int p, int setFlags) +{ + const int moreFlags = setFlags & ~gTestFlags; + gTestFlags |= (setFlags & 0x7FF); + for (int p1 = 0; p1 < nPl; ++p1) + if ((1 << p1) & (gAlive | gWatching)) + rw[p1].TestFlags = gTestFlags; + + if (moreFlags & (tfUncover | tfAllContact)) { + for (int p1 = 0; p1 < nPl - 1; ++p1) + if ((1 << p1) & gAlive) + for (int p2 = p1 + 1; p2 < nPl; ++p2) + if (((1 << p2) & gAlive) && rw[p1].Treaty[p2] == trNoContact) // make p1 and p2 know each other + introduceEnemy(p1, p2); + } + + if (moreFlags & tfAllTechs) { + for (int p1 = 0; p1 < nPl; ++p1) { + resourceMask[p1] = 0xFFFFFFFFu; + if ((1 << p1) & gAlive) { + for (int i = 0; i < nAdv; ++i) // give all techs to player p1 + if (!IsFutureTech(i) && rw[p1].Tech[i] < tsApplicable) { + rw[p1].Tech[i] = tsCheat; + checkSpecialModels(p1, i); + } + for (int p2 = 0; p2 < nPl; ++p2) + if (p2 != p1 && ((gAlive | gWatching) & (1 << p2))) + for (int i = 1; i <= 3; ++i) + if (rw[p2].EnemyReport[p1]->Tech[AgePreq[i]] < tsApplicable) + rw[p2].EnemyReport[p1]->Tech[AgePreq[i]] = tsCheat; + } + } + } + + if (moreFlags & tfUncover) { + discoverAll(p, lObserveSuper); + for (int p1 = 0; p1 < nPl; ++p1) { + if ((1 << p1) & gAlive) { + resourceMask[p1] = 0xFFFFFFFFu; + if (p1 != p) { + giveCivilReport(p, p1); + giveMilReport(p, p1); + } + } + } + } +} + +} // namespace Database +} // namespace Cevo diff --git a/game/src/Database.cpp b/game/src/Database.cpp index fa942a5..a314344 100644 --- a/game/src/Database.cpp +++ b/game/src/Database.cpp @@ -26,14 +26,23 @@ // The fact that you are presently reading this means that you have had // knowledge of the CeCILL license and that you accept its terms. +// Database.pas's global `var` state, MaskD(), and IntServer() - the parts +// declared in Cevo/Database.h before any `// --- Section ---` marker. Every +// other function now lives in one Database.
.cpp per header +// section (Database.LocationNavigation.cpp, Database.MapCreation.cpp, ..., +// Database.City.cpp) - split out of what used to be one large Database.cpp, +// since (unlike the original Pascal unit) C++ has no trouble spreading a +// single namespace's definitions across several translation units. Private +// (Pascal implementation-section-only) helpers/globals needed by more than +// one of those section files now live in DatabaseInternal.h instead of an +// anonymous namespace (anonymous-namespace internal linkage can't be shared +// across translation units). + #include "Cevo/Database.h" +#include "DatabaseInternal.h" #include -#include -#include #include -#include -#include namespace Cevo { namespace Database { @@ -85,1494 +94,17 @@ std::array observeLevel{}; // GameServer::generateStat() needs read access (index nPl means "no owner"). std::array territoryCount{}; -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 `BorderChanges` (sIntExpandTerritory // and $F == 8 packed Cardinal words, 4 bits per tile in the CountryRadius -// area around a city). +// area around a city). See DatabaseInternal.h. std::array borderChanges{}; -// 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]; -} - -// Forward declarations: defined further below (Territory Calculation -// section), needed earlier by intServer()'s sIntExpandTerritory case. -void changeTerritory(int loc, int p); -void expandTerritory(int originLoc); -} // namespace - void maskD(std::uint32_t *x, int count, std::uint32_t mask) { for (int i = 0; i < count; ++i) x[i] &= mask; } -int dLoc(int loc, int dx, int dy) -{ - // Faithful port of a likely upstream operator-precedence slip: Pascal's - // `not` binds tighter than `and`, so this only negates the first clause - // instead of the whole precondition. The very next line's assert - // re-checks the FULL intended condition correctly, and this isn't a - // memory-safety issue, so it's preserved as-is rather than silently - // "fixed" (see established policy in repo memory). - if (!(loc >= 0) && (loc < mapSize) && (dx + lx >= 0)) - throw std::runtime_error("Relative location error"); - assert((loc >= 0) && (loc < mapSize) && (dx + lx >= 0)); - - const int y0 = loc / lx; - int result = (loc + ((dx + (y0 & 1) + lx + lx) >> 1)) % lx + lx * (y0 + dy); - if (result < 0 || result >= mapSize) - result = -1; - return result; -} - -void dxdy(int loc0, int loc1, int &dx, int &dy) -{ - dx = (((loc1 % lx) * 2 + ((loc1 / lx) & 1)) - ((loc0 % lx) * 2 + ((loc0 / lx) & 1)) + 3 * lx) % (2 * lx) - lx; - dy = loc1 / lx - loc0 / lx; -} - -int distance(int loc0, int loc1) -{ - int dx, dy; - dxdy(loc0, loc1, dx, dy); - dx = std::abs(dx); - dy = std::abs(dy); - return dx + dy + (std::abs(dx - dy) >> 1); -} - -void v8ToLoc(int loc0, Vicinity8Loc &vicinityLoc) -{ - const int lx0 = lx; - int y0 = loc0 / lx0; - const int x0 = loc0 - y0 * lx0; - y0 &= 1; - vicinityLoc[1] = loc0 + lx0 * 2; - vicinityLoc[3] = loc0 - 1; - vicinityLoc[5] = loc0 - lx0 * 2; - vicinityLoc[7] = loc0 + 1; - loc0 += y0; - vicinityLoc[0] = loc0 + lx0; - vicinityLoc[2] = loc0 + lx0 - 1; - vicinityLoc[4] = loc0 - lx0 - 1; - vicinityLoc[6] = loc0 - lx0; - - // world is round! - if (x0 < lx0 - 1) { - if (x0 == 0) { - vicinityLoc[3] += lx0; - if (y0 == 0) { - vicinityLoc[2] += lx0; - vicinityLoc[4] += lx0; - } - } - } else { - vicinityLoc[7] -= lx0; - if (y0 == 1) { - vicinityLoc[0] -= lx0; - vicinityLoc[6] -= lx0; - } - } -} - -void v21ToLoc(int loc0, Vicinity21Loc &vicinityLoc) -{ - const int y0 = loc0 / lx; - int xComp0 = loc0 - y0 * lx - 1; // loc0 % lx - 1 - int xCompSwitch = xComp0 - 1 + (y0 & 1); - if (xComp0 < 0) - xComp0 += lx; - if (xCompSwitch < 0) - xCompSwitch += lx; - xCompSwitch ^= xComp0; - int yComp = lx * (y0 - 3); - int *dst = vicinityLoc.data(); - int bit = 1; - for (int dy = 0; dy < 7; ++dy) { - xComp0 ^= xCompSwitch; - int xComp = xComp0; - for (int dx = 0; dx < 4; ++dx) { - *dst = (bit & 0x67F7F76) != 0 ? xComp + yComp : -1; - ++xComp; - if (xComp >= lx) - xComp -= lx; - ++dst; - bit <<= 1; - } - yComp += lx; - } -} - -void calculatePrimitive() -{ - primitive = 1; - int i = 2; - while (i * i <= mapSize + 1) { // test whether prime - if ((mapSize + 1) % i == 0) - primitive = 0; - ++i; - } - - if (primitive > 0) { - int j = 0; - do { - ++primitive; - i = 1; - j = 0; - do { - ++j; - i = i * primitive % (mapSize + 1); - } while (!(i == 1 || j == mapSize + 1)); - } while (!(j == mapSize)); - } -} - -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 calculateModel(TModel &m) -{ - m.Attack = static_cast((m.Cap[mcOffense] + m.Cap[mcOver]) * m.MStrength); - m.Defense = static_cast((m.Cap[mcDefense] + m.Cap[mcOver]) * m.MStrength); - switch (m.Domain) { - case dGround: - m.Speed = static_cast(150 + m.Cap[mcMob] * 50); - break; - case dSea: - m.Speed = static_cast(350 + 200 * m.Cap[mcNP] + 200 * m.Cap[mcTurbines]); - if (m.Cap[mcNP] == 0) - m.Speed = static_cast(m.Speed + 100 * m.Cap[mcSE]); - break; - case dAir: - m.Speed = static_cast(850 + 400 * m.Cap[mcJet]); - break; - default: - break; - } - int cost = 0; - for (int i = 0; i < nFeature; ++i) - if ((1 << m.Domain) & Feature[i].Domains) - cost += m.Cap[i] * Feature[i].Cost; - m.Cost = static_cast(cost * m.MCost); - int weight = 0; - for (int i = 0; i < nFeature; ++i) - if ((1 << m.Domain) & Feature[i].Domains) - weight += (m.Domain == dGround && i == mcDefense) ? m.Cap[i] * 2 : m.Cap[i] * Feature[i].Weight; - m.Weight = static_cast(weight); - setModelFlags(m); -} - -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 seeTech(int p, int ad) -{ - rw[p].Tech[ad] = tsSeen; - ++researched[p]; -} - -namespace { -void tellAboutKeyTech(int p, int source, int ad) -{ - for (int i = 1; i <= 3; ++i) - if (ad == AgePreq[i]) - for (int p1 = 0; p1 < nPl; ++p1) - if (p1 != p && ((gAlive | gWatching) & (1 << p1))) - rw[p1].EnemyReport[p]->Tech[ad] = static_cast(source); -} -} // namespace - -void discoverTech(int p, int ad) -{ - TPlayerContext &player = rw[p]; - if (IsFutureTech(ad)) { - if (player.Tech[ad] < tsApplicable) - player.Tech[ad] = 1; - else - ++player.Tech[ad]; - if (ad != futResearchTechnology) - nTech[p] += 2; - researched[p] += 8; - return; - } - - if (player.Tech[ad] == tsSeen) { - ++nTech[p]; - ++researched[p]; - } else { - nTech[p] += 2; - researched[p] += 2; - } - player.Tech[ad] = tsResearched; - tellAboutKeyTech(p, tsResearched, ad); - checkSpecialModels(p, ad); - if (ad == adScience) - resourceMask[p] |= fSpecial2; - if (ad == adMassProduction) - resourceMask[p] |= fModern; - - for (int i = 0; i < nWonder; ++i) { // check whether wonders expired - if (gWonder[i].EffectiveOwner != gWonder[woEiffel].EffectiveOwner && Imp[i].Expiration == ad) { - gWonder[i].EffectiveOwner = -1; - if (i == woPyramids) - freeSlaves(); - } - } -} - -void enableDevModel(int p) -{ - TPlayerContext &player = rw[p]; - if (player.nModel >= nMmax) - return; - TModel *model = *player.Model; - model[player.nModel] = player.DevModel; - 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); - ++player.nModel; - ++researched[p]; -} - -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 removeDomainUnits(int d, int p, int loc) -{ - TPlayerContext &player = rw[p]; - TUn *un = *player.Un; - const TModel *model = *player.Model; - for (int uix = 0; uix < player.nUn; ++uix) - if (model[un[uix].mix].Domain == d && un[uix].Loc == loc) - removeUnit(p, uix); -} - -void removeAllUnits(int p, int loc, int enemy) -{ - TPlayerContext &player = rw[p]; - TUn *un = *player.Un; - for (int uix = 0; uix < player.nUn; ++uix) { - if (un[uix].Loc == loc) { - if (enemy >= 0) - countLost(p, un[uix].mix, enemy); - un[uix].Loc = -1; - } - } - occupant[loc] = -1; - zocMap[loc] = 0; -} - -void compactLists(int p) -{ - TPlayerContext &player = rw[p]; - TUn *un = *player.Un; - TCity *city = *player.City; - TCityInfo *enemyCity = *player.EnemyCity; - - // compact unit list - int uix = 0; - while (uix < player.nUn) { - if (un[uix].Loc < 0) { - --player.nUn; - un[uix] = un[player.nUn]; // replace removed unit by last - if (un[uix].TroopLoad > 0 || un[uix].AirLoad > 0) - for (int uix1 = 0; uix1 < player.nUn; ++uix1) - if (un[uix1].Master == player.nUn) // index of last unit changes - un[uix1].Master = uix; - } else { - ++uix; - } - } - - // compact city list - int cix = 0; - while (cix < player.nCity) { - if (city[cix].Loc < 0) { - --player.nCity; - city[cix] = city[player.nCity]; // replace city by last - for (int uix1 = 0; uix1 < player.nUn; ++uix1) - if (un[uix1].Home == player.nCity) // index of last city changes - un[uix1].Home = cix; - } else { - ++cix; - } - } - - // compact enemy city list - cix = 0; - while (cix < player.nEnemyCity) { - if (enemyCity[cix].Loc < 0) { - --player.nEnemyCity; - enemyCity[cix] = enemyCity[player.nEnemyCity]; // replace city by last - } else { - ++cix; - } - } -} - -int specialTile(int loc, int terrType, int lx) -{ - if (terrType == fOcean) - return 0; - const int y = loc / lx; - const int x = loc - y * lx; - if (terrType == fGrass) { // formula for productive grassland - const int v1 = lymax + x - (y >> 1); - return (((v1 >> 1) + x + ((y + 1) >> 1)) & 1) ? 1 : 0; - } - // formula for special resources - const int a = 4 * x - y + 9980; - const int qx = a / 10; - if (qx * 10 != a || (qx & 3) == 0) - return 0; - const int qy = (y + x) / 5; - if ((qy & 3) == ((qx >> 2) & 1) * 2) - return 0; - if (terrType == fArctic || terrType == fSwamp) - return 1; - if (terrType == fShore) { - if (((qx + qy) & 1) == 0) - return (qx & 3) == 2 ? 2 : 1; - return 0; - } - return ((qx + qy) & 1) + 1; -} - -std::uint32_t actualSpecialTile(int loc) -{ - return static_cast(specialTile(loc, static_cast(realMap[loc] & fTerrain), lx)); -} - -void foundCity(int p, int foundLoc) -{ - TPlayerContext &player = rw[p]; - if (player.nCity == nCmax) - return; - ++player.nCity; - TCity &city = (*player.City)[player.nCity - 1]; - city.Size = 2; - city.Status = 0; - city.SavedStatus = 0; - std::fill(std::begin(city.Built), std::end(city.Built), 0); - city.Food = 0; - city.Project = cpImp + imTrGoods; - city.Prod = 0; - city.Project0 = city.Project; - city.Prod0 = 0; - city.Pollution = 0; - city.N1 = 0; - city.Loc = foundLoc; - if (usedByCity[foundLoc] >= 0) { // central tile is exploited - toggle in exploiting city - int p1 = p; - int cix1; - searchCity(usedByCity[foundLoc], p1, cix1); - int dx, dy; - dxdy(usedByCity[foundLoc], foundLoc, dx, dy); - const int v21 = ((dy + 3) << 2) + ((dx + 3) >> 1); - (*rw[p1].City)[cix1].Tiles &= ~(1u << v21); - } - city.Tiles = 1u << 13; // exploit central tile - usedByCity[foundLoc] = foundLoc; - realMap[foundLoc] = - (realMap[foundLoc] & (fTerrain | fSpecial | fRiver | (static_cast(nPl) << 27))) | fCity; - - changeTerritory(city.Loc, p); -} - -void completeJob(int p, int loc, int job) -{ - assert(job != jCity); - int changedTerrain = -1; - switch (job) { - case jRoad: - realMap[loc] |= fRoad; - break; - case jRR: - realMap[loc] = (realMap[loc] & ~static_cast(fRoad)) | fRR; - break; - case jClear: - changedTerrain = Terrain[realMap[loc] & fTerrain].ClearTerrain; - realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); - realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); - break; - case jIrr: - realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiIrrigation; - break; - case jFarm: - realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiFarm; - break; - case jAfforest: - changedTerrain = Terrain[realMap[loc] & fTerrain].AfforestTerrain; - realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); - realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); - break; - case jMine: - realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiMine; - break; - case jFort: - realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiFort; - break; - case jCanal: - realMap[loc] |= fCanal; - break; - case jTrans: - changedTerrain = Terrain[realMap[loc] & fTerrain].TransTerrain; - realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(changedTerrain); - realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); - if (((terrTypeCanalableMask >> (realMap[loc] & fTerrain)) & 1) == 0) { - removeDomainUnits(dSea, p, loc); - realMap[loc] &= ~static_cast(fCanal); - } - break; - case jPoll: - realMap[loc] &= ~static_cast(fPoll); - break; - case jBase: - realMap[loc] = (realMap[loc] & ~static_cast(fTerImp)) | tiBase; - break; - case jPillage: - if (realMap[loc] & fTerImp) { - if ((realMap[loc] & fTerImp) == tiBase) - removeDomainUnits(dAir, p, loc); - realMap[loc] &= ~static_cast(fTerImp); - } else if (realMap[loc] & fCanal) { - removeDomainUnits(dSea, p, loc); - realMap[loc] &= ~static_cast(fCanal); - } else if (realMap[loc] & fRR) { - realMap[loc] = (realMap[loc] & ~static_cast(fRR)) | fRoad; - } else if (realMap[loc] & fRoad) { - realMap[loc] &= ~static_cast(fRoad); - } - break; - default: - break; - } - - if (changedTerrain >= 0) { // remove terrain improvements if not possible on new terrain - if (((realMap[loc] & fTerImp) == tiIrrigation || (realMap[loc] & fTerImp) == tiFarm) && - (Terrain[changedTerrain].IrrClearWork == 0 || Terrain[changedTerrain].ClearTerrain >= 0)) - realMap[loc] &= ~static_cast(fTerImp); - if ((realMap[loc] & fTerImp) == tiMine && - (Terrain[changedTerrain].MineAfforestWork == 0 || Terrain[changedTerrain].AfforestTerrain >= 0)) - realMap[loc] &= ~static_cast(fTerImp); - } - - // update map of all observing players - if (mode > moLoading_Fast) { - constexpr std::uint32_t mask = fTerrain | fSpecial | fTerImp | fRoad | fRR | fCanal | fPoll; - for (int p1 = 0; p1 < nPl; ++p1) { - if (((1 << p1) & (gAlive | gWatching)) && (((observeLevel[loc] >> (2 * p1)) & 3) > lNoObserve)) { - std::uint32_t &tile = (*rw[p1].Map)[loc]; - tile = (tile & ~mask) | (realMap[loc] & mask); - } - } - } -} - -bool checkShore(int loc) -{ - const std::uint32_t oldTile = realMap[loc]; - if ((oldTile & fTerrain) >= static_cast(fGrass)) - return false; - realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(fOcean); - Vicinity21Loc radius; - v21ToLoc(loc, radius); - for (int v21 = 1; v21 <= 26; ++v21) { - const int loc1 = radius[static_cast(v21)]; - if (loc1 >= 0 && loc1 < mapSize && (realMap[loc1] & fTerrain) >= static_cast(fGrass) && - (realMap[loc1] & fTerrain) != static_cast(fArctic)) - realMap[loc] = (realMap[loc] & ~static_cast(fTerrain)) | static_cast(fShore); - } - return ((realMap[loc] ^ oldTile) & fTerrain) != 0; -} - -void editTile(int loc, std::uint32_t newTile) -{ - if (newTile & fDeadLands) - newTile = (newTile & (fDeadLands | fModern | fRiver)) | fDesert; - switch (newTile & fTerrain) { - case fOcean: - case fShore: - newTile &= (fTerrain | fSpecial); - break; - case fMountains: - case fArctic: - newTile &= ~static_cast(fRiver); - break; - default: - break; - } - const TerrainInfo &terrain = Terrain[newTile & fTerrain]; - if (terrain.ClearTerrain >= 0 || terrain.AfforestTerrain >= 0 || terrain.TransTerrain >= 0) - newTile |= fSpecial; // only automatic special resources for transformable tiles - if (newTile & fRR) - newTile &= ~static_cast(fRoad); - if (((terrTypeCanalableMask >> (newTile & fTerrain)) & 1) == 0) - newTile &= ~static_cast(fCanal); - if (Terrain[newTile & fTerrain].IrrEff == 0) { - newTile &= ~static_cast(fPrefStartPos | fStartPos); - if ((newTile & fTerImp) == tiIrrigation || (newTile & fTerImp) == tiFarm) - newTile &= ~static_cast(fTerImp); - } - if (Terrain[newTile & fTerrain].MineEff == 0 && (newTile & fTerImp) == tiMine) - newTile &= ~static_cast(fTerImp); - - realMap[loc] = newTile; - if ((newTile & fSpecial) == fSpecial) // standard special resource distribution - realMap[loc] = (realMap[loc] & ~static_cast(fSpecial)) | (actualSpecialTile(loc) << 5); - - // automatic shore tiles - Vicinity21Loc radius; - v21ToLoc(loc, radius); - for (int v21 = 1; v21 <= 26; ++v21) { - const int loc1 = radius[static_cast(v21)]; - if (loc1 >= 0 && loc1 < mapSize) { - if (checkShore(loc1)) - realMap[loc1] = (realMap[loc1] & ~static_cast(fSpecial)) | (actualSpecialTile(loc1) << 5); - realMap[loc1] |= (0xFu << 27); - (*rw[0].Map)[loc1] = (realMap[loc1] & 0x07FFFFFFu) | fObserved; - } - } -} - -void releaseMapEditor() -{ - delete[] reinterpret_cast(rw[0].Territory); - delete[] reinterpret_cast(rw[0].MapObservedLast); - delete[] reinterpret_cast(rw[0].Map); -} - -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]; -} - -bool copyCivilReport(int pSender, int pTarget, int pAbout) -{ - bool result = false; - if (rw[pTarget].Treaty[pAbout] == trNoContact) - introduceEnemy(pTarget, pAbout); - TEnemyReport &rSender = *rw[pSender].EnemyReport[pAbout]; - TEnemyReport &rTarget = *rw[pTarget].EnemyReport[pAbout]; - if (rSender.TurnOfCivilReport > rTarget.TurnOfCivilReport) { // only if newer than current information - rTarget.TurnOfCivilReport = rSender.TurnOfCivilReport; - std::memcpy(rTarget.Treaty, rSender.Treaty, sizeof(rTarget.Treaty)); - rTarget.Government = rSender.Government; - rTarget.Money = rSender.Money; - rTarget.ResearchTech = rSender.ResearchTech; - rTarget.ResearchDone = rSender.ResearchDone; - result = true; - } - for (int i = 0; i < nAdv; ++i) - if (rTarget.Tech[i] < rSender.Tech[i]) { - rTarget.Tech[i] = rSender.Tech[i]; - result = true; - } - return result; -} - -bool copyMilReport(int pSender, int pTarget, int pAbout) -{ - bool result = false; - if (rw[pTarget].Treaty[pAbout] == trNoContact) - introduceEnemy(pTarget, pAbout); - TEnemyReport &rSender = *rw[pSender].EnemyReport[pAbout]; - TEnemyReport &rTarget = *rw[pTarget].EnemyReport[pAbout]; - if (rSender.TurnOfMilReport > rTarget.TurnOfMilReport) { // only if newer than current information - rTarget.TurnOfMilReport = rSender.TurnOfMilReport; - rTarget.nModelCounted = rSender.nModelCounted; - std::memcpy(rTarget.UnCount, rSender.UnCount, - sizeof(std::uint16_t) * static_cast(rSender.nModelCounted)); - for (int mix = 0; mix < rTarget.nModelCounted; ++mix) - tellAboutModel(pTarget, pAbout, mix); - result = true; - } - return result; -} - -void copyModel(int pSender, int pTarget, int mix) -{ - // only if target doesn't already have a model like this - bool ok = rw[pTarget].nModel < nMmax; - TModelInfo miSender{}; - MakeModelInfo(pSender, mix, (*rw[pSender].Model)[mix], miSender); - for (int i = 0; i < rw[pTarget].nModel && ok; ++i) { - TModelInfo miTarget{}; - MakeModelInfo(pTarget, i, (*rw[pTarget].Model)[i], miTarget); - if (IsSameModel(miSender, miTarget)) - ok = false; - } - if (ok) { - TModel &newModel = (*rw[pTarget].Model)[rw[pTarget].nModel]; - newModel = (*rw[pSender].Model)[mix]; - newModel.IntroTurn = static_cast(gTurn); - if (newModel.Kind == mkSelfDeveloped) - newModel.Kind = mkEnemyDeveloped; - newModel.Status = 0; - newModel.SavedStatus = 0; - newModel.Built = 0; - newModel.Lost = 0; - ++rw[pTarget].nModel; - ++researched[pTarget]; - tellAboutModel(pSender, pTarget, rw[pTarget].nModel - 1); - } -} - -void copyMap(int pSender, int pTarget) -{ - TPlayerContext &sender = rw[pSender]; - TPlayerContext &target = rw[pTarget]; - const std::int16_t *senderObserved = *sender.MapObservedLast; - std::int16_t *targetObserved = *target.MapObservedLast; - const std::uint32_t *senderMap = *sender.Map; - std::uint32_t *targetMap = *target.Map; - const std::int8_t *senderTerritory = *sender.Territory; - std::int8_t *targetTerritory = *target.Territory; - TCityInfo *senderEnemyCity = *sender.EnemyCity; - TCityInfo *targetEnemyCity = *target.EnemyCity; - const TCity *senderCity = *sender.City; - - for (int loc = 0; loc < mapSize; ++loc) { - if (senderObserved[loc] <= targetObserved[loc]) - continue; - std::uint32_t tile = senderMap[loc]; - if (tile & fCity) { - int i = 0; - while (i < target.nEnemyCity && targetEnemyCity[i].Loc != loc) - ++i; - if (i == target.nEnemyCity) { - ++target.nEnemyCity; - assert(target.nEnemyCity < necmax); - targetEnemyCity[i].Status = 0; - targetEnemyCity[i].SavedStatus = 0; - } - if (tile & fOwned) { // city owned by sender -- create new info - int cix = sender.nCity - 1; - while (cix >= 0 && senderCity[cix].Loc != loc) - --cix; - makeCityInfo(pSender, cix, targetEnemyCity[i]); - } else { // city not owned by sender -- copy old info - int cix = sender.nEnemyCity - 1; - while (cix >= 0 && senderEnemyCity[cix].Loc != loc) - --cix; - targetEnemyCity[i] = senderEnemyCity[cix]; - } - } else if (targetMap[loc] & fCity) { // remove enemycity - for (int cix = 0; cix < target.nEnemyCity; ++cix) - if (targetEnemyCity[cix].Loc == loc) - targetEnemyCity[cix].Loc = -1; - } - - tile &= (~static_cast(fSpecial | fModern) | resourceMask[pTarget]); - tile |= (targetMap[loc] & fModern); - if ((tile & fTerrain) == (targetMap[loc] & fTerrain)) - tile |= (targetMap[loc] & fSpecial); - - if ((targetMap[loc] & fTerrain) == static_cast(fUNKNOWN)) - ++discovered[pTarget]; - targetMap[loc] = (targetMap[loc] & fInEnemyZoC) // always preserve this flag! - | (tile & ~static_cast(fUnit | fHiddenUnit | fStealthUnit | fObserved | - fSpiedOut | fOwned | fInEnemyZoC | fOwnZoCUnit | - fPeace | fGrWall)); - // (the original re-assigns Territory unconditionally right after an - // equivalent if-guarded assignment - the guard was a no-op once its - // only other effect, a BorderHelper update, had been commented out) - targetTerritory[loc] = senderTerritory[loc]; - targetObserved[loc] = senderObserved[loc]; - } -} - -std::uint32_t doSpyMission(int p, int pCity, int cix, int mission) -{ - std::uint32_t result = 0; - switch (mission) { - case smSabotageProd: - (*rw[pCity].City)[cix].Flags |= chProductionSabotaged; - break; - case smStealMap: - copyMap(pCity, p); - recalcPeaceMap(p); - break; - case smStealCivilReport: - if (rw[p].Treaty[pCity] == trNoContact) - introduceEnemy(p, pCity); - giveCivilReport(p, pCity); - break; - case smStealMilReport: - if (rw[p].Treaty[pCity] == trNoContact) - introduceEnemy(p, pCity); - giveMilReport(p, pCity); - break; - case smStealForeignReports: - for (int p1 = 0; p1 < nPl; ++p1) { - if (p1 != p && p1 != pCity && rw[pCity].EnemyReport[p1]) { - if (rw[pCity].EnemyReport[p1]->TurnOfCivilReport >= 0 && copyCivilReport(pCity, p, p1)) - result |= (1u << (2 * p1)); - if (rw[pCity].EnemyReport[p1]->TurnOfMilReport >= 0 && copyMilReport(pCity, p, p1)) - result |= (2u << (2 * p1)); - } - } - break; - default: - break; - } - return result; -} - -void cancelTreaty(int p, int pWith, bool decreaseCredibility) -{ - TPlayerContext &player = rw[p]; - TPlayerContext &withPlayer = rw[pWith]; - const int oldTreaty = player.Treaty[pWith]; - peaceEnded = 0; - if (oldTreaty >= trPeace) - player.LastCancelTreaty[pWith] = gTurn; - if (decreaseCredibility) { - if (oldTreaty == trPeace) { - player.Credibility >>= 1; - if (player.MaxCredibility > 0) - player.MaxCredibility -= 10; - if (player.Credibility > player.MaxCredibility) - player.Credibility = player.MaxCredibility; - } else if (oldTreaty == trAlliance) { - player.Credibility = player.Credibility * 3 / 4; - } - withPlayer.EnemyReport[p]->Credibility = player.Credibility; - } - - if (oldTreaty == trPeace) { - for (int p1 = 0; p1 < nPl; ++p1) { - if (p1 == pWith || (decreaseCredibility && p1 != p && withPlayer.Treaty[p1] == trAlliance && - player.Treaty[p1] >= trPeace)) { - player.Treaty[p1] = trNone; - rw[p1].Treaty[p] = trNone; - player.EvaStart[p1] = -PeaceEvaTurns - 1; - rw[p1].EvaStart[p] = -PeaceEvaTurns - 1; - peaceEnded += (1 << p1); - } - } - checkBorders(-1); - if (mode > moLoading_Fast && peaceEnded > 0) - recalcMapZoC(p); - } else { - player.Treaty[pWith] = oldTreaty - 1; - withPlayer.Treaty[p] = oldTreaty - 1; - if (oldTreaty == trFriendlyContact) { // necessary for loading - giveCivilReport(p, pWith); - giveCivilReport(pWith, p); - } else if (oldTreaty == trAlliance) { // necessary for loading - giveMilReport(p, pWith); - giveMilReport(pWith, p); - } - if (mode > moLoading_Fast && oldTreaty == trAlliance) { - recalcMapZoC(p); - recalcMapZoC(pWith); - } - } - if (oldTreaty == trPeace || oldTreaty == trAlliance) { - recalcPeaceMap(p); - recalcPeaceMap(pWith); - } -} - -void showPrice(int pSender, int pTarget, std::uint32_t price) -{ - switch (price & opMask) { - case opTech: // + advance - if (rw[pTarget].EnemyReport[pSender]->Tech[price - opTech] < tsApplicable) - rw[pTarget].EnemyReport[pSender]->Tech[price - opTech] = tsApplicable; - break; - case opModel: // + model index - tellAboutModel(pTarget, pSender, static_cast(price - opModel)); - break; - default: - break; - } -} - -bool payPrice(int pSender, int pTarget, std::uint32_t price, bool execute) -{ - bool result = true; - switch (price & opMask) { - case opCivilReport: { // + turn + concerned player shl 16 - const int pSubject = static_cast((price >> 16) & 0xF); - if (pTarget == pSubject) - result = false; - else if (pSender == pSubject) { - if (execute) - giveCivilReport(pTarget, pSender); - } else if (rw[pSender].EnemyReport[pSubject]->TurnOfCivilReport < 0) - result = false; - else if (execute) - copyCivilReport(pSender, pTarget, pSubject); - break; - } - case opMilReport: { // + turn + concerned player shl 16 - const int pSubject = static_cast((price >> 16) & 0xF); - if (pTarget == pSubject) - result = false; - else if (pSender == pSubject) { - if (execute) - giveMilReport(pTarget, pSender); - } else if (rw[pSender].EnemyReport[pSubject]->TurnOfMilReport < 0) - result = false; - else if (execute) - copyMilReport(pSender, pTarget, pSubject); - break; - } - case opMap: - if (execute) { - copyMap(pSender, pTarget); - recalcPeaceMap(pTarget); - } - break; - case opTreaty: { // + nation treaty (opMask only keeps the top byte, so - // this single case covers the original's whole - // opTreaty..opTreaty+trAlliance range) - if (static_cast(price - opTreaty) == rw[pSender].Treaty[pTarget] - 1) { // agreed treaty end - if (execute) - cancelTreaty(pSender, pTarget, false); - } else { - int newTreaty = -1; - if (static_cast(price - opTreaty) == rw[pSender].Treaty[pTarget] + 1) - newTreaty = static_cast(price - opTreaty); - else if (rw[pSender].Treaty[pTarget] == trNone && static_cast(price - opTreaty) == trPeace) - newTreaty = trPeace; - if (newTreaty < 0) - result = false; - else if (execute) { - assert(newTreaty > rw[pSender].Treaty[pTarget]); - rw[pSender].Treaty[pTarget] = newTreaty; - rw[pTarget].Treaty[pSender] = newTreaty; - if (newTreaty >= trFriendlyContact) { - giveCivilReport(pTarget, pSender); - giveCivilReport(pSender, pTarget); - } - if (newTreaty == trAlliance) { - giveMilReport(pTarget, pSender); - giveMilReport(pSender, pTarget); - copyMap(pSender, pTarget); - copyMap(pTarget, pSender); - recalcMapZoC(pSender); - recalcMapZoC(pTarget); - } - if (newTreaty != trPeace && newTreaty != trFriendlyContact) { - rw[pSender].EvaStart[pTarget] = -PeaceEvaTurns - 1; - rw[pTarget].EvaStart[pSender] = -PeaceEvaTurns - 1; - } - recalcPeaceMap(pSender); - recalcPeaceMap(pTarget); - } - } - break; - } - case opShipParts: { // + number + part type shl 16 - const int n = static_cast(price & 0xFFFF); // number - const int i = static_cast((price >> 16) & 0xF); // type - if (i < nShipPart && gShip[pSender].Parts[i] >= n) { - if (execute) { - gShip[pSender].Parts[i] -= n; - rw[pSender].Ship[pSender].Parts[i] = gShip[pSender].Parts[i]; - rw[pTarget].Ship[pSender].Parts[i] = gShip[pSender].Parts[i]; - if (rw[pTarget].NatBuilt[imSpacePort] > 0) { // space ship control requires space port - gShip[pTarget].Parts[i] += n; - rw[pSender].Ship[pTarget].Parts[i] = gShip[pTarget].Parts[i]; - rw[pTarget].Ship[pTarget].Parts[i] = gShip[pTarget].Parts[i]; - } - } - } else { - result = false; - } - break; - } - case opMoney: // + value - if (price - opMoney <= MaxMoneyPrice && rw[pSender].Money >= static_cast(price - opMoney)) { - if (execute) { - rw[pSender].Money -= static_cast(price - opMoney); - rw[pTarget].Money += static_cast(price - opMoney); - } - } else { - result = false; - } - break; - case opTribute: // + value - // tribute no longer in use - execute branch intentionally empty - break; - case opTech: // + advance - if (rw[pSender].Tech[price - opTech] >= tsApplicable) { - if (execute && rw[pTarget].Tech[price - opTech] == tsNA) { - seeTech(pTarget, static_cast(price - opTech)); - rw[pSender].EnemyReport[pTarget]->Tech[price - opTech] = tsSeen; - } - } else { - result = false; - } - break; - case opAllTech: - if (execute) { - for (int i = 0; i < nAdv; ++i) { - if (rw[pSender].Tech[i] >= tsApplicable && rw[pTarget].Tech[i] == tsNA) { - seeTech(pTarget, i); - rw[pSender].EnemyReport[pTarget]->Tech[i] = tsSeen; - rw[pTarget].EnemyReport[pSender]->Tech[i] = tsApplicable; - } - } - } - break; - case opModel: // + model index - if (static_cast(price - opModel) < rw[pSender].nModel) { - if (execute) - copyModel(pSender, pTarget, static_cast(price - opModel)); - } else { - result = false; - } - break; - case opAllModel: - if (execute) - for (int i = 0; i < rw[pSender].nModel; ++i) { - tellAboutModel(pTarget, pSender, i); - copyModel(pSender, pTarget, i); - } - break; - default: - break; - } - return result; -} - -void clearTestFlags(int clearFlags) -{ - gTestFlags &= (~clearFlags | tfTested | tfAllTechs | tfAllContact); - for (int p1 = 0; p1 < nPl; ++p1) - if ((1 << p1) & (gAlive | gWatching)) - rw[p1].TestFlags = gTestFlags; -} - -void setTestFlags(int p, int setFlags) -{ - const int moreFlags = setFlags & ~gTestFlags; - gTestFlags |= (setFlags & 0x7FF); - for (int p1 = 0; p1 < nPl; ++p1) - if ((1 << p1) & (gAlive | gWatching)) - rw[p1].TestFlags = gTestFlags; - - if (moreFlags & (tfUncover | tfAllContact)) { - for (int p1 = 0; p1 < nPl - 1; ++p1) - if ((1 << p1) & gAlive) - for (int p2 = p1 + 1; p2 < nPl; ++p2) - if (((1 << p2) & gAlive) && rw[p1].Treaty[p2] == trNoContact) // make p1 and p2 know each other - introduceEnemy(p1, p2); - } - - if (moreFlags & tfAllTechs) { - for (int p1 = 0; p1 < nPl; ++p1) { - resourceMask[p1] = 0xFFFFFFFFu; - if ((1 << p1) & gAlive) { - for (int i = 0; i < nAdv; ++i) // give all techs to player p1 - if (!IsFutureTech(i) && rw[p1].Tech[i] < tsApplicable) { - rw[p1].Tech[i] = tsCheat; - checkSpecialModels(p1, i); - } - for (int p2 = 0; p2 < nPl; ++p2) - if (p2 != p1 && ((gAlive | gWatching) & (1 << p2))) - for (int i = 1; i <= 3; ++i) - if (rw[p2].EnemyReport[p1]->Tech[AgePreq[i]] < tsApplicable) - rw[p2].EnemyReport[p1]->Tech[AgePreq[i]] = tsCheat; - } - } - } - - if (moreFlags & tfUncover) { - discoverAll(p, lObserveSuper); - for (int p1 = 0; p1 < nPl; ++p1) { - if ((1 << p1) & gAlive) { - resourceMask[p1] = 0xFFFFFFFFu; - if (p1 != p) { - giveCivilReport(p, p1); - giveMilReport(p, p1); - } - } - } - } -} - void intServer(int command, int player, int subject, const void *data) { if (mode == moPlaying) @@ -1634,1057 +166,5 @@ void intServer(int command, int player, int subject, const void *data) // command dispatch - lower priority than the above. See repo memory. } -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; - } - } -} - -void recalcV8ZoC(int p, int loc) -{ - if (mode == moLoading_Fast) - return; - const int observeMask = 3 << (2 * p); - Vicinity8Loc adjacent; - v8ToLoc(loc, adjacent); - std::uint32_t *map = *rw[p].Map; - for (int v8 = 0; v8 < 8; ++v8) { - const int loc1 = adjacent[static_cast(v8)]; - if (loc1 < 0 || loc1 >= mapSize) - continue; - std::uint32_t &tile1 = map[loc1]; - tile1 &= ~static_cast(fInEnemyZoC); - Vicinity8Loc adjacentAdjacent; - v8ToLoc(loc1, adjacentAdjacent); - for (int v8v8 = 0; v8v8 < 8; ++v8v8) { - const int loc2 = adjacentAdjacent[static_cast(v8v8)]; - if (loc2 >= 0 && loc2 < mapSize && zocMap[loc2] > 0 && (observeLevel[loc2] & observeMask)) { - const int p1 = occupant[loc2]; - assert(p1 != nPl); - if (p1 != p && rw[p].Treaty[p1] < trAlliance) { - tile1 |= fInEnemyZoC; - break; - } - } - } - } -} - -void recalcMapZoC(int p) -{ - if (mode == moLoading_Fast) - return; - maskD(*rw[p].Map, mapSize, ~static_cast(fInEnemyZoC)); - const int observeMask = 3 << (2 * p); - std::uint32_t *map = *rw[p].Map; - for (int loc = 0; loc < mapSize; ++loc) { - if (zocMap[loc] > 0 && (observeLevel[loc] & observeMask)) { - const int p1 = occupant[loc]; - assert(p1 != nPl); - if (p1 != p && rw[p].Treaty[p1] < trAlliance) { - // this non-allied enemy ZoC unit is known to this player -- set flags! - Vicinity8Loc adjacent; - v8ToLoc(loc, adjacent); - for (int v8 = 0; v8 < 8; ++v8) { - const int loc1 = adjacent[static_cast(v8)]; - if (loc1 >= 0 && loc1 < mapSize) - map[loc1] |= fInEnemyZoC; - } - } - } - } -} - -void recalcPeaceMap(int p) -{ - if (mode != moPlaying) - return; - TPlayerContext &player = rw[p]; - maskD(*player.Map, mapSize, ~static_cast(fPeace)); - std::array peacePlayer{}; // index p1+1, covers p1 in -1..nPl-1 - for (int p1 = 0; p1 < nPl; ++p1) - peacePlayer[p1 + 1] = p1 != p && ((1 << p1) & gAlive) && - (player.Treaty[p1] == trPeace || player.Treaty[p1] == trFriendlyContact); - std::uint32_t *map = *player.Map; - const TOwnerList &territory = *player.Territory; - for (int loc = 0; loc < mapSize; ++loc) - if (peacePlayer[territory[loc] + 1]) - map[loc] |= fPeace; -} - -namespace { -void changeTerritory(int loc, int p) -{ - assert(p >= 0); // no player's territory indicated by p == nPl - --territoryCount[realMap[loc] >> 27]; - ++territoryCount[p]; - realMap[loc] = (realMap[loc] & ~(0xFu << 27)) | (static_cast(p) << 27); - if (p == 0xF) - p = -1; - for (int p1 = 0; p1 < nPl; ++p1) { - if (((1 << p1) & (gAlive | gWatching)) == 0) - continue; - TPlayerContext &player = rw[p1]; - if (((*player.Map)[loc] & fTerrain) == fUNKNOWN) - continue; - (*player.Territory)[loc] = static_cast(p); - // Faithful port of the original relying on x86 SHL masking the shift - // count to 5 bits when p==-1 (so `1 shl p` becomes `1 shl 31`, never - // matching gAlive, rather than C++'s real UB for negative shifts) - - // see repo memory's policy on preserving known upstream quirks. - if (p < nPl && p != p1 && ((1u << (p & 31)) & static_cast(gAlive)) && - (player.Treaty[p] == trPeace || player.Treaty[p] == trFriendlyContact)) - (*player.Map)[loc] |= fPeace; - else - (*player.Map)[loc] &= ~static_cast(fPeace); - } -} - -void expandTerritory(int originLoc) -{ - if (originLoc == -1) - throw std::runtime_error("Location error"); - int i = 0; - int dyMax = 0; - while ((dyMax + 1) + ((dyMax + 1) >> 1) <= CountryRadius) - ++dyMax; - for (int dy = -dyMax; dy <= dyMax; ++dy) { - int dxMax = dy & 1; - while (std::abs(dy) + (dxMax + 2) + (std::abs(std::abs(dy) - (dxMax + 2)) >> 1) <= CountryRadius) - dxMax += 2; - for (int dx = -dxMax; dx <= dxMax; ++dx) { - if (((dy + dx) & 1) == 0) { - const std::uint32_t newOwner = (borderChanges[i / 8] >> ((i % 8) * 4)) & 0xF; - const int loc = dLoc(originLoc, dx, dy); - if (loc >= 0 && newOwner != (realMap[loc] >> 27)) - changeTerritory(loc, static_cast(newOwner)); - ++i; - } - } - } -} -} // namespace - -void checkBorders(int originLoc, int playerLosingCity) -{ - std::array country{}; - std::array formerCountry{}; - std::array dist{}; - std::array formerDist{}; - std::array stolenDist{}; - std::array, nPl + 1> atPeace{}; - Vicinity8Loc adjacent; - - constexpr std::uint32_t noZocTerrainMask = (1u << fShore) | (1u << fMountains) | (1u << fArctic); - - if (playerLosingCity >= 0) { - for (int loc = 0; loc < mapSize; ++loc) - stolenDist[loc] = static_cast(CountryRadius + 1); - for (int cix = 0; cix < rw[playerLosingCity].nCity; ++cix) { - const int loc = (*rw[playerLosingCity].City)[cix].Loc; - if (loc >= 0) - stolenDist[loc] = 0; - } - - for (int r = 1; r <= (CountryRadius >> 1); ++r) { - formerDist = stolenDist; - for (int loc = 0; loc < mapSize; ++loc) { - if (formerDist[loc] <= CountryRadius - 2 && - ((1u << (realMap[loc] & fTerrain)) & noZocTerrainMask) == 0) { - v8ToLoc(loc, adjacent); - for (int v8 = 0; v8 < 8; ++v8) { - const int loc1 = adjacent[v8]; - const int newDist = formerDist[loc] + 2 + (v8 & 1); - if (loc1 >= 0 && loc1 < mapSize && newDist < stolenDist[loc1]) - stolenDist[loc1] = static_cast(newDist); - } - } - } - } - } - - country.fill(-1); - for (int loc = 0; loc < mapSize; ++loc) - dist[loc] = static_cast(CountryRadius + 1); - for (int p1 = 0; p1 < nPl; ++p1) { - if (((1 << p1) & gAlive) == 0) - continue; - for (int cix = 0; cix < rw[p1].nCity; ++cix) { - const int loc = (*rw[p1].City)[cix].Loc; - if (loc >= 0) { - country[loc] = static_cast(p1); - dist[loc] = 0; - } - } - } - - for (int r = 1; r <= (CountryRadius >> 1); ++r) { - formerCountry = country; - formerDist = dist; - for (int loc = 0; loc < mapSize; ++loc) { - if (formerDist[loc] <= CountryRadius - 2 && - ((1u << (realMap[loc] & fTerrain)) & noZocTerrainMask) == 0) { - assert(formerCountry[loc] >= 0); - v8ToLoc(loc, adjacent); - for (int v8 = 0; v8 < 8; ++v8) { - const int loc1 = adjacent[v8]; - const int newDist = formerDist[loc] + 2 + (v8 & 1); - if (loc1 >= 0 && loc1 < mapSize && newDist < dist[loc1]) { - country[loc1] = formerCountry[loc]; - dist[loc1] = static_cast(newDist); - } - } - } - } - } - - for (int p1 = 0; p1 < nPl; ++p1) { - if (((1 << p1) & gAlive) == 0) - continue; - for (int p2 = 0; p2 < nPl; ++p2) - if (p2 != p1 && ((1 << p2) & gAlive) && rw[p1].Treaty[p2] >= trPeace) - atPeace[p1][p2] = true; - } - - if (originLoc >= 0) { - int i = 0; - borderChanges.fill(0); - int dyMax = 0; - while ((dyMax + 1) + ((dyMax + 1) >> 1) <= CountryRadius) - ++dyMax; - for (int dy = -dyMax; dy <= dyMax; ++dy) { - int dxMax = dy & 1; - while (std::abs(dy) + (dxMax + 2) + (std::abs(std::abs(dy) - (dxMax + 2)) >> 1) <= CountryRadius) - dxMax += 2; - for (int dx = -dxMax; dx <= dxMax; ++dx) { - if (((dy + dx) & 1) == 0) { - const int loc = dLoc(originLoc, dx, dy); - if (loc >= 0) { - const int oldOwner = static_cast(realMap[loc] >> 27); - int newOwner = country[loc] & 0xF; - if (newOwner != oldOwner) { - if (atPeace[newOwner][oldOwner] && - !(oldOwner == playerLosingCity && stolenDist[loc] > CountryRadius)) - newOwner = oldOwner; // peace fixes borders - else - changeTerritory(loc, newOwner); - } - borderChanges[i >> 3] |= static_cast(newOwner) << ((i & 7) * 4); - } - ++i; - } - } - } - } else { - for (int loc = 0; loc < mapSize; ++loc) { - const int oldOwner = static_cast(realMap[loc] >> 27); - const int newOwner = country[loc] & 0xF; - if (newOwner != oldOwner && - (!atPeace[newOwner][oldOwner] || (oldOwner == playerLosingCity && stolenDist[loc] > CountryRadius))) { - assert(originLoc != -2); // test if border saving works - changeTerritory(loc, newOwner); - } - } - } - -#ifndef NDEBUG - if (originLoc != -2) - checkBorders(-2); // check: single pass should do! -#endif -} - -void logCheckBorders(int p, int cix, int playerLosingCity) -{ - checkBorders((*rw[p].City)[cix].Loc, playerLosingCity); - intServer(sIntExpandTerritory, p, cix, borderChanges.data()); -} - -int delphiRandom(int max) -{ - const std::int64_t temp = static_cast(134775813) * static_cast(delphiRandSeed) + 1; - delphiRandSeed = static_cast(temp); - return static_cast((static_cast(static_cast(max)) * - static_cast(static_cast(delphiRandSeed))) >> - 32); -} - -void findContinents() -{ - auto replaceCont = [](int a, int b, int stop) { - if (a < b) - std::swap(a, b); - if (a > b) - for (int i = a; i <= stop; ++i) - if (continent[i] == a) - continent[i] = b; - }; - - for (int y = 1; y <= ly - 2; ++y) { - for (int x = 0; x < lx; ++x) { - const int loc = x + lx * y; - continent[loc] = -1; - if ((realMap[loc] & fTerrain) >= static_cast(fGrass)) { - if (y - 2 >= 1 && (realMap[loc - 2 * lx] & fTerrain) >= static_cast(fGrass)) - continent[loc] = continent[loc - 2 * lx]; - if ((x - 1 + (y & 1)) >= 0 && y - 1 >= 1 && - (realMap[loc - 1 + (y & 1) - lx] & fTerrain) >= static_cast(fGrass)) - continent[loc] = continent[loc - 1 + (y & 1) - lx]; - if ((x + (y & 1)) < lx && y - 1 >= 1 && - (realMap[loc + (y & 1) - lx] & fTerrain) >= static_cast(fGrass)) - continent[loc] = continent[loc + (y & 1) - lx]; - if (x - 1 >= 0 && (realMap[loc - 1] & fTerrain) >= static_cast(fGrass)) { - if (continent[loc] == -1) - continent[loc] = continent[loc - 1]; - else - replaceCont(continent[loc - 1], continent[loc], loc); - } - if (continent[loc] == -1) - continent[loc] = loc; - } - } - } - - // connect continents due to round earth - for (int y = 1; y <= ly - 2; ++y) { - if ((realMap[lx * y] & fTerrain) >= static_cast(fGrass)) { - int wrong = -1; - if ((realMap[lx - 1 + lx * y] & fTerrain) >= static_cast(fGrass)) - wrong = continent[lx - 1 + lx * y]; - if ((y & 1) == 0 && y - 1 >= 1 && - (realMap[lx - 1 + lx * (y - 1)] & fTerrain) >= static_cast(fGrass)) - wrong = continent[lx - 1 + lx * (y - 1)]; - if ((y & 1) == 0 && y + 1 < ly - 1 && - (realMap[lx - 1 + lx * (y + 1)] & fTerrain) >= static_cast(fGrass)) - wrong = continent[lx - 1 + lx * (y + 1)]; - if (wrong >= 0) - replaceCont(wrong, continent[lx * y], mapSize - 1); - } - } -} - -void predefinedStartPositions(int human) -{ - int nAlive = 0; - for (int p1 = 0; p1 < nPl; ++p1) - if ((1 << p1) & gAlive) - ++nAlive; - if (nAlive == 0) - return; - - std::vector startLoc0(static_cast(lxmax) * lymax, 0); - - int nStartLoc0 = 0; - int nPrefStartLoc0 = 0; - for (int loc1 = 0; loc1 < mapSize; ++loc1) { - if (realMap[loc1] & fPrefStartPos) { - startLoc0[static_cast(nStartLoc0)] = startLoc0[static_cast(nPrefStartLoc0)]; - startLoc0[static_cast(nPrefStartLoc0)] = loc1; - ++nPrefStartLoc0; - ++nStartLoc0; - realMap[loc1] &= ~static_cast(fPrefStartPos); - } else if (realMap[loc1] & fStartPos) { - startLoc0[static_cast(nStartLoc0)] = loc1; - ++nStartLoc0; - realMap[loc1] &= ~static_cast(fStartPos); - } - } - assert(nStartLoc0 >= nAlive); - - startLoc[0] = 0; - for (bool isHuman : { true, false }) { - for (int p1 = 0; p1 < nPl; ++p1) { - if (((1 << p1) & gAlive) && ((((1 << p1) & human) != 0) == isHuman)) { - --nStartLoc0; - int imax = nStartLoc0; - if (nPrefStartLoc0 > 0) { - --nPrefStartLoc0; - imax = nPrefStartLoc0; - } - const int i = delphiRandom(imax + 1); - startLoc[p1] = startLoc0[static_cast(i)]; - startLoc2[p1] = startLoc0[static_cast(i)]; - startLoc0[static_cast(i)] = startLoc0[static_cast(imax)]; - startLoc0[static_cast(imax)] = startLoc0[static_cast(nStartLoc0)]; - } - } - } - saveMapCenterLoc = startLoc[0]; -} - -void initGame() -{ - occupant.fill(-1); - zocMap.fill(0); - observeLevel.fill(0); - usedByCity.fill(-1); - gTestFlags = 0; - gInitialized = gAlive | gWatching; - - for (int p = 0; p < nPl; ++p) { - if (((1 << p) & gInitialized) == 0) - continue; - TPlayerContext &player = rw[p]; - researched[p] = 0; - discovered[p] = 0; - territoryCount[p] = 0; - nTech[p] = 0; - resourceMask[p] = (difficulty[p] == 0) ? 0xFFFFFFFFu : (0xFFFFFFFFu & ~static_cast(fSpecial2 | fModern)); - grWallContinent[p] = -1; - - player.Map = reinterpret_cast(new std::uint32_t[static_cast(mapSize)]()); - player.MapObservedLast = reinterpret_cast(new std::int16_t[static_cast(mapSize)]); - std::memset(*player.MapObservedLast, 0xFF, static_cast(mapSize) * 2); - player.Territory = reinterpret_cast(new std::int8_t[static_cast(mapSize)]); - std::memset(*player.Territory, 0xFF, static_cast(mapSize)); - player.Un = reinterpret_cast(new TUn[nUmax]()); - player.Model = reinterpret_cast(new TModel[nMmax + 1]()); - player.City = reinterpret_cast(new TCity[nCmax]()); - player.EnemyUn = reinterpret_cast(new TUnitInfo[neumax]()); - player.EnemyCity = reinterpret_cast(new TCityInfo[necmax]()); - player.EnemyModel = reinterpret_cast(new TModelInfo[nemmax]()); - - for (int p1 = 0; p1 < nPl; ++p1) { - if ((1 << p1) & gInitialized) { - std::memset(rwemix[p][p1].data(), 0xFF, rwemix[p][p1].size() * sizeof(std::int16_t)); - std::memset(destroyed[p][p1].data(), 0, destroyed[p][p1].size() * sizeof(std::int16_t)); - } - player.Attitude[p1] = atNeutral; - player.Treaty[p1] = trNoContact; - player.LastCancelTreaty[p1] = -CancelTreatyTurns - 1; - player.EvaStart[p1] = -PeaceEvaTurns - 1; - player.Tribute[p1] = 0; - player.TributePaid[p1] = 0; - if (p1 != p && ((1 << p1) & gAlive)) { - // Truncated allocation (matches the original's own GetMem - // size: TEnemyReport's UnCount[] field is oversized via the - // same "open array via overlarge static type" trick used - // throughout this port - only nMmax slots are real). - player.EnemyReport[p1] = static_cast( - ::operator new(sizeof(TEnemyReport) - sizeof(std::uint16_t) * (INFIN + 1 - nMmax))); - std::memset(player.EnemyReport[p1]->Tech, tsNA, nAdv); - player.EnemyReport[p1]->TurnOfContact = -1; - player.EnemyReport[p1]->TurnOfCivilReport = -1; - player.EnemyReport[p1]->TurnOfMilReport = -1; - player.EnemyReport[p1]->Attitude = atNeutral; - player.EnemyReport[p1]->Government = gDespotism; - if (((1 << p) & gAlive) == 0) - player.Treaty[p1] = trNone; // supervisor - } else { - player.EnemyReport[p1] = nullptr; - } - } - player.TestFlags = gTestFlags; - player.Credibility = InitialCredibility; - player.MaxCredibility = 100; - player.nUn = 0; - player.nModel = 0; - player.nCity = 0; - player.nEnemyUn = 0; - player.nEnemyCity = 0; - player.nEnemyModel = 0; - std::uint32_t *map = *player.Map; - for (int loc1 = 0; loc1 < mapSize; ++loc1) - map[loc1] = fUNKNOWN; - std::memset(player.Tech, tsNA, nAdv); - std::memset(player.NatBuilt, 0, sizeof(player.NatBuilt)); - } - - // create initial models and units - for (int p = 0; p < nPl; ++p) { - if (((1 << p) & gAlive) == 0) - continue; - TPlayerContext &player = rw[p]; - TModel *model = *player.Model; - player.nModel = 0; - for (int i = 0; i < nSpecialModel; ++i) { - if (SpecialModelPreq[i] == preNone) { - model[player.nModel] = SpecialModel[i]; - model[player.nModel].Status = 0; - model[player.nModel].IntroTurn = 0; - model[player.nModel].Built = 0; - model[player.nModel].Lost = 0; - model[player.nModel].ID = static_cast((p << 12) + player.nModel); - setModelFlags(model[player.nModel]); - ++player.nModel; - } - } - player.nUn = 0; - unBuilt[p] = 0; - TUn *un = *player.Un; - for (int uix = 0; uix < nStartUn; ++uix) { - createUnit(p, StartUn[uix]); - --model[StartUn[uix]].Built; - un[uix].Loc = startLoc2[p]; - placeUnit(p, uix); - } - foundCity(p, startLoc[p]); - founded[p] = 1; - TCity &city = (*player.City)[0]; - city.ID = static_cast(p << 12); - city.Flags = chFounded; - } - - territoryCount[nPl] = mapSize; -} - -void initMapGame(int human) -{ - delphiRandSeed = rnd; - findContinents(); - predefinedStartPositions(human); - initGame(); -} - -void initRandomGame() -{ - throw std::runtime_error( - "Random map generation is not supported yet (CreateElevation/CreateMap/StartPositions not ported)."); -} - -void releaseGame() -{ - for (int p1 = 0; p1 < nPl; ++p1) { - if (((1 << p1) & gInitialized) == 0) - continue; - TPlayerContext &player = rw[p1]; - for (int p2 = 0; p2 < nPl; ++p2) - if (player.EnemyReport[p2]) - ::operator delete(player.EnemyReport[p2]); - delete[] reinterpret_cast(player.EnemyUn); - delete[] reinterpret_cast(player.EnemyCity); - delete[] reinterpret_cast(player.EnemyModel); - delete[] reinterpret_cast(player.Un); - delete[] reinterpret_cast(player.City); - delete[] reinterpret_cast(player.Model); - delete[] reinterpret_cast(player.Territory); - delete[] reinterpret_cast(player.MapObservedLast); - delete[] reinterpret_cast(player.Map); - } - gInitialized = 0; -} - -namespace { - -void stealCity(int p, int cix, bool saveUnits) -{ - TCity &city = (*rw[p].City)[cix]; - for (int i = 0; i < nWonder; ++i) { - if (city.Built[i] == 1) { - gWonder[i].EffectiveOwner = -1; - if (i == woPyramids) - freeSlaves(); - if (i == woEiffel) // deactivate expired wonders - for (int j = 0; j < nWonder; ++j) - if (gWonder[j].EffectiveOwner == p) - checkExpiration(j); - } - } - for (int i = nWonder; i < nImp; ++i) { - if (Imp[i].Kind != ikCommon && city.Built[i] > 0) { // destroy national projects - rw[p].NatBuilt[i] = 0; - if (i == imGrWall) - grWallContinent[p] = -1; - } - } - - TUn *un = *rw[p].Un; - for (int uix1 = 0; uix1 < rw[p].nUn; ++uix1) { - if (un[uix1].Loc >= 0 && un[uix1].Home == cix) { - if (saveUnits) { // support units by nearest other city - int nearest = -1; - for (int cix1 = 0; cix1 < rw[p].nCity; ++cix1) { - const TCity &c1 = (*rw[p].City)[cix1]; - if (cix1 != cix && c1.Loc >= 0 && - (nearest < 0 || distance(c1.Loc, un[uix1].Loc) < - distance((*rw[p].City)[nearest].Loc, un[uix1].Loc))) - nearest = cix1; - } - un[uix1].Home = nearest; - } else { - removeUnit(p, uix1); // destroy supported units - } - } - } -} - -} // namespace - -void destroyCity(int p, int cix, bool saveUnits) -{ - stealCity(p, cix, saveUnits); - TCity &city = (*rw[p].City)[cix]; - for (int i = 0; i < nWonder; ++i) - if (city.Built[i] > 0) - gWonder[i].CityID = WonderDestroyed; - Vicinity21Loc radius; - v21ToLoc(city.Loc, radius); - for (int v21 = 1; v21 <= 26; ++v21) - if ((1u << v21) & city.Tiles) - usedByCity[static_cast(radius[static_cast(v21)])] = -1; - realMap[city.Loc] &= ~static_cast(fCity); - city.Loc = -1; -} - -void changeCityOwner(int pOld, int cixOld, int pNew) -{ - ++rw[pNew].nCity; - (*rw[pNew].City)[rw[pNew].nCity - 1] = (*rw[pOld].City)[cixOld]; - stealCity(pOld, cixOld, false); - (*rw[pOld].City)[cixOld].Loc = -1; - - TCity &city = (*rw[pNew].City)[rw[pNew].nCity - 1]; - city.Food = 0; - city.Project = cpImp + imTrGoods; - city.Prod = 0; - city.Project0 = city.Project; - city.Prod0 = 0; - city.Status = 0; - city.SavedStatus = 0; - city.N1 = 0; - - // check for siege - Vicinity21Loc radius; - v21ToLoc(city.Loc, radius); - for (int v21 = 1; v21 <= 26; ++v21) { - if ((city.Tiles & (1u << v21) & ~(1u << CityOwnTile)) != 0) { - const int loc1 = radius[static_cast(v21)]; - assert(loc1 >= 0 && loc1 < mapSize && usedByCity[static_cast(loc1)] == city.Loc); - if (zocMap[loc1] > 0 && occupant[loc1] != pNew && rw[pNew].Treaty[occupant[loc1]] < trAlliance) { - // tile can't remain exploited - city.Tiles &= ~(1u << v21); - usedByCity[static_cast(loc1)] = -1; - } - // don't check for siege by peace territory here, because territory - // might not be up to date -- done in turn beginning anyway - } - } - city.Built[imTownHall] = 0; - city.Built[imCourt] = 0; - for (int i = nWonder; i < nImp; ++i) - if (Imp[i].Kind != ikCommon) - city.Built[i] = 0; // destroy national projects - for (int i = 0; i < nWonder; ++i) { - if (city.Built[i] == 1) { // new wonder owner! - gWonder[i].EffectiveOwner = pNew; - if (i == woEiffel) { // reactivate expired wonders - for (int j = 0; j < nWonder; ++j) - if (Imp[j].Expiration >= 0) - for (int cix1 = 0; cix1 < rw[pNew].nCity; ++cix1) - if ((*rw[pNew].City)[cix1].Built[j] == 1) - gWonder[j].EffectiveOwner = pNew; - } else { - checkExpiration(i); - } - switch (i) { - case woLighthouse: - checkSpecialModels(pNew, preLighthouse); - break; - case woLeo: - checkSpecialModels(pNew, preLeo); - break; - case woPyramids: - checkSpecialModels(pNew, preBuilder); - break; - default: - break; - } - } - } - - // remove city from enemy cities - not done by Discover, because fCity still set! - int cix1 = rw[pNew].nEnemyCity - 1; - TCityInfo *enemyCity = *rw[pNew].EnemyCity; - while (cix1 >= 0 && enemyCity[cix1].Loc != city.Loc) - --cix1; - assert(cix1 >= 0); - enemyCity[cix1].Loc = -1; - - changeTerritory(city.Loc, pNew); -} - } // namespace Database } // namespace Cevo diff --git a/game/src/DatabaseInternal.h b/game/src/DatabaseInternal.h new file mode 100644 index 0000000..8a7f738 --- /dev/null +++ b/game/src/DatabaseInternal.h @@ -0,0 +1,69 @@ +// This file is part of cevo-evo. +// +// This software is governed by the CeCILL license under French law and +// abiding by the rules of distribution of free software. You can use, +// modify and/or redistribute the software under the terms of the CeCILL +// license as circulated by CEA, CNRS and INRIA at the following URL +// "http://www.cecill.info". +// +// As a counterpart to the access to the source code and rights to copy, +// modify and redistribute granted by the license, users are provided only +// with a limited warranty and the software's author, the holder of the +// economic rights, and the successive licensors have only limited +// liability. +// +// In this respect, the user's attention is drawn to the risks associated +// with loading, using, modifying and/or developing or reproducing the +// software by the user in light of its specific status of free software, +// that may mean that it is complicated to manipulate, and that also +// therefore means that it is reserved for developers and experienced +// professionals having in-depth computer knowledge. Users are therefore +// encouraged to load and test the software's suitability as regards their +// requirements in conditions enabling the security of their systems and/or +// data to be ensured and, more generally, to use and operate it in the +// same conditions as regards security. +// +// The fact that you are presently reading this means that you have had +// knowledge of the CeCILL license and that you accept its terms. + +#pragma once + +// Database.pas's own implementation-section-private (`unit`-local) globals +// and helpers, shared across the Database.
.cpp translation units +// that Database.cpp is now split into. Not part of the public Cevo/Database.h +// API - include this only from Database*.cpp files in this library. Before +// the split these lived in a single anonymous namespace inside one .cpp +// (true C++ internal linkage, matching Pascal's interface/implementation +// visibility split); now that they're needed from several translation +// units, they're plain (externally linked) Database:: symbols instead - +// still private by convention, just no longer enforced by the compiler. + +#include "Cevo/Database.h" + +namespace Cevo { +namespace Database { + +// 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). +// Defined in Database.cpp; used by Database.MapProcessing.cpp (createUnit) +// and Database.GameInitialization.cpp (initGame). +extern std::array unBuilt; + +// Equivalent of Database.pas's private `BorderChanges` (sIntExpandTerritory +// and $F == 8 packed Cardinal words, 4 bits per tile in the CountryRadius +// area around a city). Defined in Database.cpp; used by Database.cpp's own +// intServer() and by Database.TerritoryCalculation.cpp. +extern std::array borderChanges; + +// Equivalent of Database.pas's private FreeSlaves(). Defined in +// Database.TechRelated.cpp; used there and by Database.City.cpp. +void freeSlaves(); + +// Defined in Database.TerritoryCalculation.cpp; used there, by +// Database.MapProcessing.cpp (foundCity), by Database.City.cpp +// (changeCityOwner), and by Database.cpp's own intServer(). +void changeTerritory(int loc, int p); +void expandTerritory(int originLoc); + +} // namespace Database +} // namespace Cevo