splited gameserver

This commit is contained in:
Geoffray Levasseur committed 2026-10-29 11:18:07 +01:00
1 parent 701a2fe4c7
commit 28a7acc6ac
9 files changed
+4263 -3709

No files matched your search

+6
View File
@@ -96,6 +96,12 @@ set(PROJECT_SOURCES
game/Brain.h
game/GameServer.cpp
game/GameServer.h
game/GameServerInternal.h
game/GameServer.ClientCallPlumbing.cpp
game/GameServer.Lifecycle.cpp
game/GameServer.MoveAndCombat.cpp
game/GameServer.Server.cpp
game/GameServer.TurnProcessing.cpp
game/Global.cpp
game/Global.h
game/Inp.cpp
+353
View File
@@ -0,0 +1,353 @@
// 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 "GameServer.h"
#include "GameServerInternal.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
// Equivalent of Directories.pas's GetAiDir() - see Brain.cpp's own copy of
// this (not shared via a header since Directories.pas itself isn't ported).
QString getAiDir()
{
#ifdef CEVO_AI_DIR
return QStringLiteral(CEVO_AI_DIR);
#else
return QString();
#endif
}
// Convenience wrapper matching Pascal's `Notify(Id)` (Index defaults to 0).
void notifyEvent(NotifyId id, int index)
{
if (notify)
notify(id, index);
}
// Re-applies previously-recorded sIntExpandTerritory diffs for the current
// player's turn (used after loading/replaying a game - during live play
// CheckBorders computes and applies territory changes directly instead).
void insertTerritoryUpdateCommands()
{
while (Database::cl.progress() < 1000) {
const CmdListState formerState = Database::cl.state();
int command = 0;
int p1 = 0;
int subject = 0;
const void *data = nullptr;
Database::cl.get(command, p1, subject, data);
if (command == sIntExpandTerritory && p1 == pTurn) {
Database::intServer(command, p1, subject, data);
} else {
Database::cl.setState(formerState);
break;
}
}
Database::invalidTreatyMap = 0;
}
void callPlayer(int command, int p, void *data)
{
if (Database::mode != Database::moMovie || p == 0) {
try {
playerBrain[p]->module.call(command, p, data);
} catch (...) {
// Fixes an apparent typo in the original (`Notify(ntException +
// bix[P])` doesn't even type-check as written - enum + object -
// matching the correct 2-arg Notify(Id, Index) calls used
// everywhere else in this same file, e.g. InitBrain below).
if (notify)
notify(NotifyId::Exception, brains.indexOf(playerBrain[p]));
}
}
}
void callAllPlayers(int command, void *data)
{
for (int i = 0; i < nPl; ++i)
if (playerBrain[i])
callPlayer(command, i, data);
}
void callClient(int brainIndex, int command, void *data)
{
if (Database::mode != Database::moMovie || brainIndex == brains.indexOf(playerBrain[0])) {
try {
brains[brainIndex].module.call(command, -1, data);
} catch (...) {
if (notify)
notify(NotifyId::Exception, brainIndex);
}
}
}
void putMessage(int level, const QString &text)
{
const QByteArray bytes = text.toUtf8();
playerBrain[0]->module.call(cDebugMessage, level, const_cast<char *>(bytes.constData()));
}
void changeClientWhenDone(int command, int player, const void *data, int dataSize)
{
ccCommand = command;
ccPlayer = player;
if (dataSize > 0)
std::memcpy(ccData.data(), data, static_cast<std::size_t>(dataSize));
notifyEvent(NotifyId::ChangeClient);
}
void forceClientDeactivation()
{
if (pDipActive < 0) {
server(sTurn, pTurn, 0, nullptr); // no nego mode
} else {
switch (lastEndClientCommand) { // nego mode
case scContact:
server(scReject, pDipActive, 0, nullptr);
break;
case scDipCancelTreaty:
case scDipBreak:
server(scDipNotice, pDipActive, 0, nullptr);
break;
default: {
TOffer nullOffer{};
nullOffer.nDeliver = 0;
nullOffer.nCost = 0;
server(scDipOffer, pDipActive, 0, &nullOffer);
break;
}
}
}
}
void inform(int p)
{
TPlayerContext &player = Database::rw[p];
player.Turn = Database::gTurn;
if (Database::gTurn == maxTurn && p == pTurn && p == 0)
player.Happened |= phTimeUp;
if (gWinner > 0 && p == pTurn && p == 0)
player.Happened |= phShipComplete;
player.Alive = Database::gAlive;
std::memcpy(player.Wonder, Database::gWonder.data(), sizeof(player.Wonder));
std::memcpy(player.Ship, Database::gShip.data(), sizeof(player.Ship));
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != p && playerBrain[p1] && Database::difficulty[p1] > 0)
player.EnemyReport[p1]->Credibility = Database::rw[p1].Credibility;
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != p && ((1 << p1) & Database::gAlive)) {
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p] == 0 ||
player.Treaty[p1] >= trFriendlyContact)
Database::giveCivilReport(p, p1);
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p] == 0 || player.Treaty[p1] == trAlliance)
Database::giveMilReport(p, p1);
}
}
TModelInfo *enemyModel = *player.EnemyModel;
for (int i = 0; i < player.nEnemyModel; ++i)
enemyModel[i].Lost = Database::destroyed[p][enemyModel[i].Owner][enemyModel[i].mix];
}
void logChanges()
{
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & Database::gWatching) && Database::processClientData[p]) {
TPlayerContext &player = Database::rw[p];
TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
if (un[ix].Loc >= 0 && un[ix].SavedStatus != un[ix].Status) {
Database::cl.put(sIntSetUnitStatus, p, ix, &un[ix].Status);
un[ix].SavedStatus = un[ix].Status;
}
TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
if (city[ix].Loc >= 0 && city[ix].SavedStatus != city[ix].Status) {
Database::cl.put(sIntSetCityStatus, p, ix, &city[ix].Status);
city[ix].SavedStatus = city[ix].Status;
}
TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
if (model[ix].SavedStatus != model[ix].Status) {
Database::cl.put(sIntSetModelStatus, p, ix, &model[ix].Status);
model[ix].SavedStatus = model[ix].Status;
}
TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
if (enemyCity[ix].Loc >= 0 && enemyCity[ix].SavedStatus != enemyCity[ix].Status) {
Database::cl.put(sIntSetECityStatus, p, ix, &enemyCity[ix].Status);
enemyCity[ix].SavedStatus = enemyCity[ix].Status;
}
if (playerBrain[p]->dataSize > 0) {
Database::cl.putDataChanges(sIntDataChange, p, static_cast<std::uint32_t *>(savedData[p]),
static_cast<std::uint32_t *>(player.Data), playerBrain[p]->dataSize);
std::memcpy(savedData[p], player.Data, static_cast<std::size_t>(playerBrain[p]->dataSize) * 4);
}
}
}
}
void noLogChanges()
{
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & Database::gWatching) && Database::processClientData[p]) {
TPlayerContext &player = Database::rw[p];
TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
un[ix].SavedStatus = un[ix].Status;
TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
city[ix].SavedStatus = city[ix].Status;
TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
model[ix].SavedStatus = model[ix].Status;
TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
enemyCity[ix].SavedStatus = enemyCity[ix].Status;
if (playerBrain[p]->dataSize > 0)
std::memcpy(savedData[p], player.Data, static_cast<std::size_t>(playerBrain[p]->dataSize) * 4);
}
}
}
bool hasChanges(int p)
{
TPlayerContext &player = Database::rw[p];
const TUn *un = *player.Un;
for (int ix = 0; ix < player.nUn; ++ix)
if (un[ix].Loc >= 0 && un[ix].SavedStatus != un[ix].Status)
return true;
const TCity *city = *player.City;
for (int ix = 0; ix < player.nCity; ++ix)
if (city[ix].Loc >= 0 && city[ix].SavedStatus != city[ix].Status)
return true;
const TModel *model = *player.Model;
for (int ix = 0; ix < player.nModel; ++ix)
if (model[ix].SavedStatus != model[ix].Status)
return true;
const TCityInfo *enemyCity = *player.EnemyCity;
for (int ix = 0; ix < player.nEnemyCity; ++ix)
if (enemyCity[ix].Loc >= 0 && enemyCity[ix].SavedStatus != enemyCity[ix].Status)
return true;
if (player.Data) {
const auto *savedWords = static_cast<const std::uint32_t *>(savedData[p]);
const auto *currentWords = static_cast<const std::uint32_t *>(player.Data);
for (int ix = 0; ix < playerBrain[p]->dataSize; ++ix)
if (savedWords[ix] != currentWords[ix])
return true;
}
return false;
}
void initBrain(Brain &brain)
{
assert(brain.kind != BrainType::SuperVirtual);
if (brain.initialized)
return;
if (brain.kind == BrainType::AI) { // get client function
if (notify)
notify(NotifyId::InitModule, brains.indexOf(&brain));
if (!brain.module.load(brain.dllName.toStdString()))
notify(NotifyId::DllError, brains.indexOf(&brain));
}
if (brain.module.isLoaded()) {
brain.initialized = true;
TInitModuleData initModuleData{};
initModuleData.Server = &server;
initModuleData.DataVersion = 0;
initModuleData.DataSize = 0;
initModuleData.Flags = 0;
callClient(brains.indexOf(&brain), cInitModule, &initModuleData);
brain.dataVersion = initModuleData.DataVersion;
brain.dataSize = (initModuleData.DataSize + 3) / 4;
if (brain.dataSize > MaxDataSize)
brain.dataSize = 0;
brain.flags |= initModuleData.Flags;
}
}
void changeClient()
{
const double t = nowPrecise();
putMessage((1 << 16) + 2, QStringLiteral("CLIENT: took %1 ms").arg((t - lastClientTime) * 1000.0, 0, 'f', 1));
lastClientTime = t;
putMessage((1 << 16) + 2,
QStringLiteral("CLIENT: calling %1 (%2)").arg(ccPlayer).arg(playerBrain[ccPlayer]->name()));
if (ccCommand == cTurn)
for (int p = 0; p < nPl; ++p)
if (p != ccPlayer && ((1 << p) & Database::gWatching))
callPlayer(cShowTurnChange, p, &ccPlayer);
const int p = ccPlayer;
ccPlayer = -1;
callPlayer(ccCommand, p, ccData.data());
if (Database::mode == Database::moPlaying && (playerBrain[p]->flags & aiThreaded) == 0 && ccPlayer < 0) {
notifyEvent(NotifyId::DeactivationMissing, p);
forceClientDeactivation();
}
}
} // namespace GameServer
} // namespace Cevo
+844
View File
@@ -0,0 +1,844 @@
// 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 "GameServer.h"
#include "GameServerInternal.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
void saveGame(const QString &fileName, bool autoSave)
{
int nLocal = 0;
for (int i = 0; i < nPl; ++i)
if (playerBrain[i] && playerBrain[i]->kind == BrainType::Term)
++nLocal;
if (Database::difficulty[0] == 0)
nLocal = 0;
std::vector<std::uint8_t> saveMap(static_cast<std::size_t>(lxmax) * lymax, 0);
if (nLocal <= 1) {
for (int y = 0; y < Database::ly; ++y) {
for (int x = 0; x < Database::lx; ++x) {
const std::uint32_t tile =
(*Database::rw[0].Map)[(x + Database::saveMapCenterLoc + (Database::lx >> 1)) % Database::lx +
Database::lx * y];
saveMap[static_cast<std::size_t>(x + Database::lx * y)] =
static_cast<std::uint8_t>((tile & fTerrain) + ((tile & (fCity | fUnit | fOwned)) >> 16));
}
}
}
QDir().mkpath(QFileInfo(fileName).path());
QFile file(fileName);
const bool append = autoSave && autoSaveExists;
if (!file.open(append ? QIODevice::ReadWrite : (QIODevice::WriteOnly | QIODevice::Truncate)))
throw std::runtime_error(("Cannot open " + fileName + " for writing").toStdString());
file.seek(0);
auto writeInt32 = [&file](std::int32_t value) { file.write(reinterpret_cast<const char *>(&value), 4); };
file.write("cEvoBook", 8);
writeInt32(CevoVersion);
const qint64 exeTime = QFileInfo(QCoreApplication::applicationFilePath()).lastModified().toSecsSinceEpoch();
writeInt32(static_cast<std::int32_t>(exeTime));
writeInt32(Database::lx);
writeInt32(Database::ly);
writeInt32(Database::landMass);
if (Database::landMass == 0)
file.write(reinterpret_cast<const char *>(Database::realMap.data()), Database::mapSize * 4);
writeInt32(maxTurn);
writeInt32(Database::rnd);
writeInt32(Database::gTurn);
if (nLocal > 1) { // multiplayer game -- no quick view
writeInt32(0x80);
} else {
file.write(reinterpret_cast<const char *>(saveMap.data()), ((Database::mapSize - 1) / 4 + 1) * 4);
}
for (int i = 0; i < nPl; ++i) {
if (!playerBrain[i]) {
writeInt32(0);
continue;
}
assert(playersBrain[i]); // bix[i] can only be set if playersBrain[i] was
const QByteArray name = ((playersBrain[i]->kind == BrainType::Random || playersBrain[i]->kind == BrainType::AI)
? playerBrain[i]->fileName
: playersBrain[i]->fileName)
.toLatin1();
// Pascal shortstring-style encoding: 1 length byte + chars, zero-
// padded up to a total of (length div 4 + 1) * 4 bytes.
const int len = name.size();
QByteArray buffer((len / 4 + 1) * 4, '\0');
buffer[0] = static_cast<char>(len);
std::memcpy(buffer.data() + 1, name.constData(), static_cast<std::size_t>(len));
file.write(buffer);
writeInt32(originalDataVersion[i]);
file.write(QByteArray(4, '\0')); // "behavior" string - always empty, kept for on-disk compatibility
writeInt32(Database::difficulty[i]);
}
if (append)
Database::cl.appendToFile(file, autoSaveState);
else
Database::cl.saveToFile(file);
file.close();
if (autoSave) {
autoSaveState = Database::cl.state();
autoSaveExists = true;
}
}
void startGame()
{
for (int p1 = 0; p1 < nPl; ++p1) {
if (playersBrain[p1] && playersBrain[p1]->kind == BrainType::SuperVirtual) {
playerBrain[p1] = brainTerm; // supervisor and local human use same module
} else if (playersBrain[p1] && playersBrain[p1]->kind == BrainType::Random) {
if (brains.kindCount(BrainType::AI) == 0) {
playerBrain[p1] = nullptr;
} else {
const std::vector<Brain *> aiBrains = brains.getByKind(BrainType::AI);
playerBrain[p1] = aiBrains[static_cast<std::size_t>(Database::delphiRandom(static_cast<int>(aiBrains.size())))];
}
} else {
playerBrain[p1] = playersBrain[p1];
}
if (!playersBrain[p1])
Database::difficulty[p1] = -1;
}
if (playerBrain[0]->kind != BrainType::NoTerm)
notifyEvent(NotifyId::InitLocalHuman);
std::array<bool, maxBrain> brainUsed{};
for (int p = 0; p < nPl; ++p) {
if (playerBrain[p] && (Database::mode != Database::moMovie || p == 0)) {
aiInfo[p] = playerBrain[p]->name();
initBrain(*playerBrain[p]);
if (Database::mode == Database::moPlaying) {
originalDataVersion[p] = playerBrain[p]->dataVersion;
Database::processClientData[p] = true;
} else {
Database::processClientData[p] =
Database::processClientData[p] && (originalDataVersion[p] == playerBrain[p]->dataVersion);
}
// NOTE: Term/Random/NetworkXxx brain kinds have no backing
// AiModule (no dylib to load) - until this port grows a real
// UI-side terminal-client bridge (StdIntf.pas equivalent,
// outside GameServer.pas's own scope), isLoaded() is always
// false for them, same as a failed-to-resolve Client in the
// original.
if (!playerBrain[p]->module.isLoaded()) {
if (playerBrain[0]->kind == BrainType::NoTerm) {
playerBrain[p] = nullptr;
} else {
playerBrain[p] = brainTerm;
originalDataVersion[p] = -1;
Database::processClientData[p] = false;
}
}
if (playerBrain[p])
brainUsed[static_cast<std::size_t>(brains.indexOf(playerBrain[p]))] = true;
}
}
notifyEvent(NotifyId::CreateWorld);
int nAlive = 0;
Database::gAlive = 0;
Database::gWatching = (Database::mode == Database::moMovie) ? 1 : 0;
Database::gAI = 0;
for (int p1 = 0; p1 < nPl; ++p1) {
if (playerBrain[p1]) {
if (Database::mode != Database::moMovie)
Database::gWatching |= (1 << p1);
if (playerBrain[p1]->kind == BrainType::AI)
Database::gAI |= (1 << p1);
if (Database::difficulty[p1] > 0) {
Database::gAlive |= (1 << p1);
++nAlive;
}
Database::serverVersion[p1] = playerBrain[p1]->serverVersion;
}
}
winOnAlone = playerBrain[0]->kind == BrainType::NoTerm && nAlive > 1;
gWinner = 0;
gColdWarStart = -ColdWarTurns - 1;
uixSelectedTransport = -1;
spyMission = smSabotageProd;
debugMap.fill(nullptr);
Database::gTurn = 0;
for (TWonderInfo &wonder : Database::gWonder) {
wonder.CityID = -1;
wonder.EffectiveOwner = -1;
}
Database::gShip.fill(TShipInfo{});
for (int p = 0; p < nPl; ++p) {
if (((1 << p) & (Database::gAlive | Database::gWatching)) == 0)
continue;
TPlayerContext &player = Database::rw[p];
player.Government = gDespotism;
player.Money = StartMoney;
player.TaxRate = 30;
player.LuxRate = 0;
player.Research = 0;
player.ResearchTech = -2;
player.AnarchyStart = -AnarchyTurns - 1;
player.Happened = 0;
Database::lastValidStat[p] = -1;
UnitProcessing::worked[p] = 0;
Database::founded[p] = 0;
devModelTurn[p] = -1;
player.OracleIncome = 0;
if (playerBrain[p]->dataSize > 0) {
savedData[p] = new std::uint32_t[static_cast<std::size_t>(playerBrain[p]->dataSize)]();
player.Data = new std::uint32_t[static_cast<std::size_t>(playerBrain[p]->dataSize)]();
} else {
player.Data = nullptr;
savedData[p] = nullptr;
}
player.nBattleHistory = 0;
player.BattleHistory = nullptr;
player.BorderHelper = nullptr;
for (int i = 0; i < nStat; ++i)
stat[static_cast<std::size_t>(i)][p].assign(static_cast<std::size_t>(maxTurn + 1), 0);
if (playerBrain[p]->flags & fDotNet) {
// fDotNet brains are filtered out in init() - unreachable, kept
// only for structural fidelity with the original.
player.DefaultDebugMap =
reinterpret_cast<TIntList *>(new std::int32_t[static_cast<std::size_t>(Database::mapSize)]());
debugMap[p] = player.DefaultDebugMap;
} else {
player.DefaultDebugMap = nullptr;
}
}
if (Database::landMass > 0) { // random map
Database::initRandomGame();
previewElevation = false;
mapField.clear();
} else { // predefined map
if (Database::mode == Database::moPlaying) {
Map map;
map.loadFromFile(mapFileName);
Database::mapSize = map.mapSize();
Database::lx = map.size().x();
Database::ly = map.size().y();
std::copy(map.tiles.begin(), map.tiles.begin() + Database::mapSize, Database::realMap.begin());
}
mapField.assign(Database::realMap.begin(), Database::realMap.begin() + Database::mapSize);
int human = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::Term)
human |= (1 << p1);
Database::initMapGame(human);
}
CityProcessing::initGame();
UnitProcessing::initGame();
for (int p = 0; p < nPl; ++p)
if ((1 << p) & (Database::gAlive | Database::gWatching))
inform(p);
pTurn = -1;
if (playerBrain[0]->kind != BrainType::NoTerm)
notifyEvent(NotifyId::InitLocalHuman);
TNewGameData game{};
game.lx = Database::lx;
game.ly = Database::ly;
game.LandMass = Database::landMass;
game.MaxTurn = maxTurn;
std::memcpy(game.Difficulty, Database::difficulty.data(), sizeof(game.Difficulty));
aiCredits.clear();
for (int i = 0; i < brains.count(); ++i) {
Brain &brain = brains[i];
if (!brain.initialized)
continue;
if (brainUsed[static_cast<std::size_t>(i)]) {
if (brain.kind == BrainType::AI)
notifyEvent(NotifyId::InitPlayers);
for (int p = 0; p < nPl; ++p) {
game.RO[p] = (brains.indexOf(playerBrain[p]) == i) ? &Database::rw[p] : nullptr;
game.SuperVisorRO[p] = (brain.kind == BrainType::Term && Database::difficulty[0] == 0 && playerBrain[p])
? &Database::rw[p]
: nullptr;
}
// DotNet AssemblyPath is unsupported by this port - always empty.
game.AssemblyPath[0] = '\0';
switch (Database::mode) {
case Database::moLoading:
case Database::moLoading_Fast:
callClient(i, cLoadGame, &game);
break;
case Database::moMovie:
callClient(i, cMovie, &game);
break;
case Database::moPlaying:
callClient(i, cNewGame, &game);
break;
}
if (brain.kind == BrainType::AI && !brain.credits.isEmpty()) {
if (aiCredits.isEmpty())
aiCredits = brain.credits;
else
aiCredits += QLatin1Char('\\') + brain.credits;
}
} else { // module no longer used -- unload
callClient(i, cReleaseModule, nullptr);
if (brain.kind == BrainType::AI && (brain.flags & fDotNet) == 0)
brain.module.unload();
brain.initialized = false;
}
}
if (playerBrain[0]->kind != BrainType::NoTerm) {
int brainUni = -1;
for (int p1 = 0; p1 < nPl; ++p1)
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::AI) {
if (brainUni == -1)
brainUni = brains.indexOf(playerBrain[p1]);
else if (brainUni != brains.indexOf(playerBrain[p1]))
brainUni = -2;
}
for (int p1 = 0; p1 < nPl; ++p1) {
if (playerBrain[p1] && playerBrain[p1]->kind == BrainType::AI) {
notifyMessage = (brainUni == -2) ? playerBrain[p1]->fileName : QString();
notifyEvent(NotifyId::SetAiName, p1);
}
}
}
Database::checkBorders(-1);
Database::invalidTreatyMap = 0;
autoSaveExists = false;
pDipActive = -1;
pTurn = 0;
if (Database::mode >= Database::moMovie)
notifyEvent(NotifyId::EndInfo);
}
void endGame()
{
mapField.clear(); // only populated for predefined maps in this port
for (int p1 = 0; p1 < nPl; ++p1) {
if (!playerBrain[p1])
continue;
for (int i = 0; i < nStat; ++i)
stat[static_cast<std::size_t>(i)][p1].clear();
TPlayerContext &player = Database::rw[p1];
delete[] reinterpret_cast<TBattle *>(player.BattleHistory);
player.BattleHistory = nullptr;
delete[] static_cast<std::uint32_t *>(player.Data);
player.Data = nullptr;
delete[] static_cast<std::uint32_t *>(savedData[p1]);
savedData[p1] = nullptr;
delete[] reinterpret_cast<std::int32_t *>(player.DefaultDebugMap);
player.DefaultDebugMap = nullptr;
}
UnitProcessing::releaseGame();
CityProcessing::releaseGame();
Database::releaseGame();
Database::cl = CmdList();
}
void generateStat(int p)
{
if (Database::difficulty[p] <= 0)
return;
TPlayerContext &player = Database::rw[p];
const int turn = Database::gTurn;
int statPop = 0;
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0)
statPop += city[cix].Size;
int statScience = Database::researched[p] * 50;
if (player.ResearchTech >= 0 && player.ResearchTech != adMilitary)
statScience += player.Research * 100 / Database::techBaseCost(Database::nTech[p], Database::difficulty[p]);
int statMil = 0;
const TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) {
if (un[uix].Loc < 0)
continue;
const TModel &m = model[un[uix].mix];
if (m.Kind <= mkEnemyDeveloped && un[uix].mix != 1)
statMil += m.Weight * m.MStrength * un[uix].Health / 100;
else if (m.Domain == dGround)
statMil += (m.Attack + 2 * m.Defense) * un[uix].Health / 100;
else
statMil += (m.Attack + m.Defense) * un[uix].Health / 100;
if (m.Kind == mkSlaves)
++statPop;
else if (m.Kind == mkSettler)
statPop += 2;
}
statMil /= 16;
stat[stPop][p][static_cast<std::size_t>(turn)] = statPop;
stat[stScience][p][static_cast<std::size_t>(turn)] = statScience;
stat[stMil][p][static_cast<std::size_t>(turn)] = statMil;
stat[stExplore][p][static_cast<std::size_t>(turn)] = Database::discovered[p];
stat[stTerritory][p][static_cast<std::size_t>(turn)] = Database::territoryCount[p];
stat[stWork][p][static_cast<std::size_t>(turn)] = UnitProcessing::worked[p];
Database::lastValidStat[p] = turn;
}
void logCityTileChanges()
{
TPlayerContext &player = Database::rw[pTurn];
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) {
if (city[cix].Loc < 0)
continue;
if (savedTiles[static_cast<std::size_t>(cix)] != city[cix].Tiles) {
Database::cl.put(sSetCityTiles, pTurn, cix, &city[cix].Tiles);
savedTiles[static_cast<std::size_t>(cix)] = city[cix].Tiles;
}
}
}
void noLogCityTileChanges()
{
TPlayerContext &player = Database::rw[pTurn];
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0)
savedTiles[static_cast<std::size_t>(cix)] = city[cix].Tiles;
}
bool hasCityTileChanges()
{
const TPlayerContext &player = Database::rw[pTurn];
const TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0 && savedTiles[static_cast<std::size_t>(cix)] != city[cix].Tiles)
return true;
return false;
}
const std::uint32_t *previewMap(int landMass)
{
Database::lx = lxmax;
Database::ly = lymax;
Database::mapSize = Database::lx * Database::ly;
// TODO: needs LandMass/DelphiRandSeed/CreateElevation/CreateMap, which
// live in Database.pas's Map Editor section (not ported yet).
Q_UNUSED(landMass);
Q_UNUSED(previewElevation);
return Database::realMap.data();
}
QString getLogFileName()
{
return logFileName;
}
namespace {
constexpr QLatin1Char AutoSavePrefix('~');
QString fromAutoSaveFileName(const QString &fileName)
{
const QFileInfo info(fileName);
if (!info.fileName().isEmpty() && info.fileName().at(0) == AutoSavePrefix)
return info.path() + QLatin1Char('/') + info.fileName().mid(1);
return fileName;
}
}
QString toAutoSaveFileName(const QString &fileName)
{
const QFileInfo info(fileName);
if (info.fileName().isEmpty() || info.fileName().at(0) != AutoSavePrefix)
return info.path() + QLatin1Char('/') + AutoSavePrefix + info.fileName();
return fileName;
}
bool isAutoSaveFileName(const QString &fileName)
{
const QString name = QFileInfo(fileName).fileName();
return !name.isEmpty() && name.at(0) == AutoSavePrefix;
}
void fillMap(std::uint32_t terrainType, bool specialResources)
{
if (specialResources) {
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
Database::editTile(loc1, terrainType | (0xFu << 27));
} else {
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
Database::realMap[loc1] = terrainType | (0xFu << 27);
}
}
void editMap(const QString &mapFileNameArg, const QString &writeMapFileName, int newlx, int newly, int newLandMass)
{
notifyEvent(NotifyId::StartDone);
notifyEvent(NotifyId::InitLocalHuman);
mapFileName = writeMapFileName;
Database::lx = newlx;
Database::ly = newly;
Database::mapSize = Database::lx * Database::ly;
Database::landMass = newLandMass;
playerBrain[0] = brainTerm;
Database::difficulty[0] = 0;
initBrain(*brainTerm);
Database::delphiRandSeed = static_cast<std::int32_t>(QDateTime::currentMSecsSinceEpoch());
Database::gAlive = 0;
Database::gWatching = 1;
if (QFileInfo::exists(mapFileNameArg)) {
Map map;
map.loadFromFile(mapFileNameArg);
Database::mapSize = map.mapSize();
Database::lx = map.size().x();
Database::ly = map.size().y();
std::copy(map.tiles.begin(), map.tiles.begin() + Database::mapSize, Database::realMap.begin());
} else {
fillMap(fOcean, false);
}
Database::cl = CmdList();
Database::initMapEditor();
Database::rw[0].Data = nullptr;
Database::rw[0].BorderHelper = nullptr;
Database::rw[0].Alive = 0;
TNewGameData game{};
game.lx = Database::lx;
game.ly = Database::ly;
game.RO[0] = &Database::rw[0];
game.Difficulty[0] = 0;
for (int p1 = 1; p1 < nPl; ++p1) {
game.RO[p1] = nullptr;
game.Difficulty[p1] = -1;
}
brainTerm->module.call(cNewMap, -1, &game);
Database::discoverAll(0, Database::lObserveSuper);
notifyEvent(NotifyId::EndInfo);
playerBrain[0]->module.call(cShowGame, 0, nullptr);
notifyEvent(NotifyId::BackOff);
changeClientWhenDone(cEditMap, 0, nullptr, 0);
}
void directHelp(int command)
{
initBrain(*brainTerm);
brainTerm->module.call(command, -1, nullptr);
aiCredits = QString(QChar(0));
}
void startNewGame(const QString &fileName, const QString &mapFileNameArg, int newlx, int newly, int newLandMass,
int newMaxTurn)
{
notifyEvent(NotifyId::StartDone);
savePath = QFileInfo(fileName).path();
logFileName = fileName;
mapFileName = mapFileNameArg;
Database::lx = newlx;
Database::ly = newly;
Database::mapSize = Database::lx * Database::ly;
Database::landMass = mapFileName.isEmpty() ? newLandMass : 0;
maxTurn = newMaxTurn;
Database::delphiRandSeed = static_cast<std::int32_t>(QDateTime::currentMSecsSinceEpoch());
Database::rnd = Database::delphiRandSeed;
Database::mode = Database::moPlaying;
Database::cl = CmdList();
startGame();
noLogChanges();
callAllPlayers(cGetReady, nullptr);
logChanges();
Database::cl.put(sTurn, 0, 0, nullptr);
beforeTurn0();
noLogCityTileChanges();
generateStat(pTurn);
nLogOpened = -1;
lastEndClientCommand = -1;
callPlayer(cShowGame, 0, nullptr);
for (int i = 0; i < nPl; ++i)
if (playerBrain[i] && playerBrain[i]->kind == BrainType::NetworkServer)
callPlayer(cShowGame, i, nullptr);
notifyEvent(NotifyId::BackOff);
inform(pTurn);
changeClientWhenDone(cTurn, 0, nullptr, 0);
}
bool loadGame(const QString &fileName, const QString &writeFileName, int turn, bool movieMode)
{
savePath = QFileInfo(writeFileName).path();
logFileName = writeFileName;
loadTurn = turn;
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
throw std::runtime_error(("Cannot open " + fileName).toStdString());
auto readInt32 = [&file]() {
std::int32_t value = 0;
file.read(reinterpret_cast<char *>(&value), 4);
return value;
};
char id[8];
file.read(id, 8); // file id, unused
const std::int32_t version = readInt32();
readInt32(); // exe time, unused
bool result = version >= FirstBookCompatibleVersion && version <= CevoVersion;
if (result) {
Database::lx = readInt32();
Database::ly = readInt32();
Database::mapSize = Database::lx * Database::ly;
Database::landMass = readInt32();
if (Database::landMass == 0) // use predefined map
file.read(reinterpret_cast<char *>(Database::realMap.data()), Database::mapSize * 4);
maxTurn = readInt32();
Database::rnd = readInt32();
Database::gTurn = readInt32();
std::vector<std::uint8_t> saveMap(static_cast<std::size_t>(((Database::mapSize - 1) / 4 + 1) * 4), 0);
file.read(reinterpret_cast<char *>(saveMap.data()), 4);
if (saveMap[0] != 0x80)
file.read(reinterpret_cast<char *>(saveMap.data() + 4), static_cast<qint64>(saveMap.size()) - 4);
for (int p1 = 0; p1 < nPl; ++p1) {
unsigned char header[4];
file.read(reinterpret_cast<char *>(header), 4);
if (header[0] == 0) {
playersBrain[p1] = nullptr;
continue;
}
const int len = header[0];
// Pascal shortstring-style decoding: matches SaveGame's (len div
// 4 + 1) * 4 total byte count, split here into the 4-byte
// header already read plus (len div 4) * 4 more bytes.
std::vector<char> buffer(static_cast<std::size_t>(4 + (len / 4) * 4), '\0');
std::memcpy(buffer.data(), header, 4);
if (len / 4 * 4 > 0)
file.read(buffer.data() + 4, len / 4 * 4);
const QString name = QString::fromLatin1(buffer.data() + 1, len);
originalDataVersion[p1] = readInt32();
readInt32(); // "behavior" string, always empty, kept for on-disk compatibility
Database::difficulty[p1] = readInt32();
Brain *found = nullptr;
for (int k = brains.count() - 1; k >= 0; --k) {
if (brains[k].fileName.compare(name, Qt::CaseInsensitive) == 0) {
found = &brains[k];
break;
}
}
if (!found) { // ai not found -- replace by local player
Database::processClientData[p1] = false;
notifyMessage = name;
notifyEvent(NotifyId::AiError);
found = brainTerm;
} else {
Database::processClientData[p1] = true;
}
if (found->kind == BrainType::NoTerm) // crashed tournament -- load as supervisor
found = brainSuperVirtual;
playersBrain[p1] = found;
}
}
if (result)
Database::cl.loadFromFile(file);
file.close();
if (!result)
return false;
notifyEvent(NotifyId::StartDone);
if (loadTurn < 0)
loadTurn = Database::gTurn;
if (movieMode)
Database::mode = Database::moMovie;
else if (loadTurn == 0)
Database::mode = Database::moLoading;
else
Database::mode = Database::moLoading_Fast;
loadOK = true;
startGame();
if (movieMode) {
playerBrain[0]->module.call(cShowGame, 0, nullptr);
notifyEvent(NotifyId::BackOff);
} else {
notifyEvent(NotifyId::LoadBegin);
}
bool started = false;
bool statRequest = false;
movieStopped = false;
while (!movieStopped && Database::cl.progress() < 1000) {
const CmdListState formerClState = Database::cl.state();
int command = 0;
int p1 = 0;
int subject = 0;
const void *data = nullptr;
Database::cl.get(command, p1, subject, data);
if (p1 < 0)
p1 = pTurn;
if (statRequest && (command & (sctMask | sExecute)) != (sctInternal | sExecute)) {
generateStat(pTurn);
statRequest = false;
}
// complete all internal commands following an sTurn before generating statistics
if (command == sTurn && !started) {
for (int p2 = 0; p2 < nPl; ++p2)
if (playerBrain[p2] && (Database::mode != Database::moMovie || p2 == 0))
callPlayer(cReplay, p2, nullptr);
beforeTurn0();
if (movieMode) {
inform(pTurn);
callPlayer(cMovieTurn, 0, nullptr);
}
statRequest = true;
started = true;
} else if (command == sTurn && pTurn == 0 && Database::gTurn == loadTurn) {
assert(Database::cl.state().loadPos == formerClState.loadPos + 4); // size of sTurn
Database::cl.setState(formerClState);
Database::cl.cut();
break;
} else if (command == sIntDataChange) {
if (Database::processClientData[p1])
Database::cl.getDataChanges(static_cast<std::uint32_t *>(Database::rw[p1].Data),
playerBrain[p1]->dataSize);
else
Database::cl.getDataChanges(nullptr, 0);
} else {
if ((command & (sctMask | sExecute)) == (sctInternal | sExecute))
Database::intServer(command, p1, subject, data);
else {
statRequest = command == sTurn;
server(command, p1, subject, const_cast<void *>(data));
}
}
if (!movieMode)
notifyEvent(NotifyId::LoadState, Database::cl.progress() * 128 / 1000);
}
if (movieMode) {
notifyEvent(NotifyId::BackOn);
playerBrain[0]->module.call(cBreakGame, -1, nullptr);
endGame();
notifyEvent(NotifyId::StartGo);
return false;
}
if (statRequest)
generateStat(pTurn);
assert(started);
noLogChanges();
noLogCityTileChanges();
if (isAutoSaveFileName(logFileName)) {
logFileName = fromAutoSaveFileName(logFileName);
nLogOpened = -1;
} else {
nLogOpened = Database::cl.state().nLog;
}
Database::mode = Database::moPlaying;
lastEndClientCommand = -1;
if ((Database::gTestFlags & tfUncover) || Database::difficulty[pTurn] == 0)
Database::discoverAll(pTurn, Database::lObserveSuper); // supervisor - all tiles visible
else
Database::discoverViewAreas(pTurn);
for (int p1 = 0; p1 < nPl; ++p1) {
if ((1 << p1) & (Database::gAlive | Database::gWatching)) {
Database::recalcPeaceMap(p1);
TUnitInfo *enemyUn = *Database::rw[p1].EnemyUn;
for (int ix = 0; ix < Database::rw[p1].nEnemyUn; ++ix)
enemyUn[ix].emix = static_cast<std::uint16_t>(Database::rwemix[p1][enemyUn[ix].Owner][enemyUn[ix].mix]);
inform(p1);
}
}
notifyEvent(NotifyId::EndInfo);
if (!loadOK) {
notifyMessage = logFileName;
notifyEvent(NotifyId::LoadError);
}
playerBrain[0]->module.call(cShowGame, 0, nullptr);
notifyEvent(NotifyId::BackOff);
inform(pTurn);
changeClientWhenDone(cResume, 0, nullptr, 0);
return true;
}
} // namespace GameServer
} // namespace Cevo
+576
View File
@@ -0,0 +1,576 @@
// 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 "GameServer.h"
#include "GameServerInternal.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
int executeMove(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove)
{
int result = 0;
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const TModel &model = (*player.Model)[un.mix];
int fromLoc = un.Loc;
if (un.Master < 0)
Database::freeUnit(p, uix);
if ((moveInfo.MoveType == UnitProcessing::mtMove || moveInfo.MoveType == UnitProcessing::mtCapture) &&
moveInfo.MountainDelay)
un.Flags |= unMountainDelay;
un.Loc = -2;
if (un.TroopLoad + un.AirLoad > 0) {
TUn *allUn = *player.Un;
for (int i = 0; i < player.nUn; ++i)
if (allUn[i].Loc >= 0 && allUn[i].Master == uix)
allUn[i].Loc = -2;
}
Database::updateUnitMap(fromLoc);
if (Database::mode >= Database::moMovie) { // show move in interface modules
showMove.EndHealth = moveInfo.EndHealth;
showMove.EndHealthDef = -1;
if (un.Master >= 0) {
if ((*player.Model)[(*player.Un)[un.Master].mix].Domain == dAir)
showMove.Flags |= umPlaneUnloading;
else
showMove.Flags |= umShipUnloading;
}
if (moveInfo.ToMaster >= 0) {
if ((*player.Model)[(*player.Un)[moveInfo.ToMaster].mix].Domain == dAir)
showMove.Flags |= umPlaneLoading;
else
showMove.Flags |= umShipLoading;
}
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
std::uint32_t minLevel;
if (model.Cap[mcStealth] > 0)
minLevel = Database::lObserveSuper;
else if (model.Cap[mcSub] > 0)
minLevel = Database::lObserveAll;
else
minLevel = Database::lObserveUnhidden;
const bool seeFrom =
p1 == p || ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= minLevel;
const bool seeTo = p1 == p || ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= minLevel;
if (seeFrom && seeTo) {
Database::tellAboutModel(p1, p, un.mix);
showMove.emix = (p1 == p) ? -1 : Database::emixSafe(p1, p, un.mix);
callPlayer(moveInfo.MoveType == UnitProcessing::mtCapture ? cShowCapturing : cShowMoving, p1,
&showMove);
} else if (seeFrom) {
callPlayer(cShowUnitChanged, p1, &fromLoc);
}
}
}
}
if (moveInfo.MoveType != UnitProcessing::mtSpyMission)
un.Loc = toLoc;
if (un.TroopLoad + un.AirLoad > 0) {
TUn *allUn = *player.Un;
for (int i = 0; i < player.nUn; ++i)
if (allUn[i].Loc == -2)
allUn[i].Loc = toLoc;
}
bool extDiscover = false;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
if (moveInfo.MoveType == UnitProcessing::mtCapture) {
assert(Database::occupant[toLoc] < 0);
TPlayerContext &defender = Database::rw[moveInfo.Defender];
TUn *defUn = *defender.Un;
for (int uix1 = 0; uix1 < defender.nUn; ++uix1) {
if (defUn[uix1].Loc >= 0 && defUn[uix1].Home == moveInfo.Dcix) {
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUn[uix1].Loc;
++nUpdateLoc;
}
}
// unit will be removed -- remember position and update for all players
if ((*defender.City)[moveInfo.Dcix].Size > 2 && player.nCity < nCmax) { // city captured
changeCityOwnerTellPlayers(moveInfo.Defender, moveInfo.Dcix, p);
TCity &newCity = (*player.City)[player.nCity - 1];
newCity.Flags = static_cast<decltype(newCity.Flags)>(CaptureTurns << 16);
CityProcessing::cityShrink(p, player.nCity - 1);
if (Database::mode == Database::moPlaying)
savedTiles[static_cast<std::size_t>(player.nCity - 1)] = newCity.Tiles;
extDiscover = true;
// Temple of Zeus effect
if (Database::gWonder[woZeus].EffectiveOwner == p) {
Database::giveCivilReport(p, moveInfo.Defender);
for (int i = 0; i < nAdv; ++i) {
if (!IsFutureTech(i) && player.Tech[i] < tsSeen && defender.Tech[i] >= tsApplicable) {
player.Happened |= phStealTech;
gStealFrom = moveInfo.Defender;
break;
}
}
}
if (Database::mode == Database::moPlaying)
Database::logCheckBorders(p, player.nCity - 1, moveInfo.Defender);
// territory should not be considered for the rest of the command
// execution, because during loading a game it's incorrect before
// subsequent sIntExpandTerritory is processed
} else { // city destroyed
destroyCityTellPlayers(moveInfo.Defender, moveInfo.Dcix, false);
Database::checkBorders(toLoc, moveInfo.Defender);
}
Database::recalcPeaceMap(p);
if (Database::mode >= Database::moMovie)
std::memcpy(player.Wonder, Database::gWonder.data(), sizeof(player.Wonder));
} // if MoveInfo.MoveType = mtCapture
if (moveInfo.MoveType == UnitProcessing::mtSpyMission) {
std::uint32_t missionResult = Database::doSpyMission(p, moveInfo.Defender, moveInfo.Dcix, spyMission);
if (Database::mode == Database::moPlaying && spyMission == smStealForeignReports)
callPlayer(cShowMissionResult, p, &missionResult);
}
un.Health = static_cast<decltype(un.Health)>(moveInfo.EndHealth);
un.Movement = static_cast<decltype(un.Movement)>(un.Movement - moveInfo.Cost);
// transport unload
if (un.Master >= 0) {
if (model.Domain == dAir)
--(*player.Un)[un.Master].AirLoad;
else {
--(*player.Un)[un.Master].TroopLoad;
assert(un.Movement <= 0);
}
un.Master = -1;
}
if (un.Health <= 0 || moveInfo.MoveType == UnitProcessing::mtSpyMission) {
Database::removeUnit(p, uix); // spy mission or victim of HostileDamage
} else { // transport load
un.Master = moveInfo.ToMaster;
if (moveInfo.ToMaster >= 0) {
if (model.Domain == dAir)
++(*player.Un)[moveInfo.ToMaster].AirLoad;
else
++(*player.Un)[moveInfo.ToMaster].TroopLoad;
} else {
Database::placeUnit(p, uix);
}
}
if (moveInfo.MoveType == UnitProcessing::mtCapture && nUpdateLoc > 0)
Database::recalcMapZoC(p);
Database::updateUnitMap(toLoc, moveInfo.MoveType == UnitProcessing::mtCapture);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)]);
// tell about lost units of defender
if (moveInfo.MoveType != UnitProcessing::mtSpyMission && un.Master < 0) {
if (model.Kind == mkDiplomat || model.Domain == dAir ||
model.Cap[mcRadar] + model.Cap[mcCarrier] + model.Cap[mcAcademy] > 0 ||
(Database::realMap[toLoc] & fTerrain) == static_cast<std::uint32_t>(fMountains) ||
(Database::realMap[toLoc] & fTerImp) == tiFort || (Database::realMap[toLoc] & fTerImp) == tiBase)
extDiscover = true;
std::uint32_t level;
if (model.Kind == mkDiplomat || model.Cap[mcSpy] > 0)
level = Database::lObserveSuper;
else if (model.Domain == dAir || model.Cap[mcRadar] + model.Cap[mcCarrier] > 0)
level = Database::lObserveAll;
else
level = Database::lObserveUnhidden;
if (extDiscover) {
if (Database::discover21(toLoc, p, static_cast<int>(level), true, model.Domain == dGround))
result |= rEnemySpotted;
} else {
if (Database::discover9(toLoc, p, static_cast<int>(level), true, model.Domain == dGround))
result |= rEnemySpotted;
}
}
if (Database::mode >= Database::moMovie) { // show after-move in interface modules
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
std::uint32_t minLevel;
if (model.Cap[mcStealth] > 0)
minLevel = Database::lObserveSuper;
else if (model.Cap[mcSub] > 0)
minLevel = Database::lObserveAll;
else
minLevel = Database::lObserveUnhidden;
const bool seeFrom =
p1 == p || ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= minLevel;
const bool seeTo = p1 == p || ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= minLevel;
if (seeTo && moveInfo.MoveType == UnitProcessing::mtCapture)
callPlayer(cShowCityChanged, p1, &toLoc);
if (seeFrom && seeTo)
callPlayer(cShowAfterMove, p1, &toLoc);
else if (moveInfo.MoveType != UnitProcessing::mtSpyMission && seeTo)
callPlayer(cShowUnitChanged, p1, &toLoc);
for (int i = 0; i < nUpdateLoc; ++i)
if (((Database::observeLevel[updateLoc[static_cast<std::size_t>(i)]] >> (2 * p1)) & 3) >=
Database::lObserveUnhidden)
callPlayer(cShowUnitChanged, p1, &updateLoc[static_cast<std::size_t>(i)]);
}
}
}
return result;
}
void ensureBattleHistoryCapacity(TPlayerContext &player)
{
if (player.nBattleHistory == 0) {
player.BattleHistory = reinterpret_cast<TBattleList *>(new TBattle[16]());
} else if (player.nBattleHistory >= 16 && (player.nBattleHistory & (player.nBattleHistory - 1)) == 0) {
TBattle *oldArr = reinterpret_cast<TBattle *>(player.BattleHistory);
auto *newArr = new TBattle[static_cast<std::size_t>(player.nBattleHistory) * 2]();
std::copy(oldArr, oldArr + player.nBattleHistory, newArr);
delete[] oldArr;
player.BattleHistory = reinterpret_cast<TBattleList *>(newArr);
}
}
void writeBattleHistory(int toLoc, int fromLoc, int attacker, int defender, int mixAttacker, int mixDefender,
bool attackerLost, bool defenderLost)
{
TPlayerContext &attackerPlayer = Database::rw[attacker];
ensureBattleHistoryCapacity(attackerPlayer);
TBattle &attackerBattle = (*attackerPlayer.BattleHistory)[attackerPlayer.nBattleHistory];
++attackerPlayer.nBattleHistory;
TPlayerContext &defenderPlayer = Database::rw[defender];
ensureBattleHistoryCapacity(defenderPlayer);
TBattle &defenderBattle = (*defenderPlayer.BattleHistory)[defenderPlayer.nBattleHistory];
++defenderPlayer.nBattleHistory;
attackerBattle.Enemy = static_cast<std::uint8_t>(defender);
attackerBattle.Flags = 0;
attackerBattle.Turn = static_cast<std::uint16_t>(Database::gTurn);
attackerBattle.mix = static_cast<std::uint16_t>(mixAttacker);
attackerBattle.mixEnemy = static_cast<std::uint16_t>(mixDefender);
attackerBattle.ToLoc = toLoc;
attackerBattle.FromLoc = fromLoc;
defenderBattle.Enemy = static_cast<std::uint8_t>(attacker);
defenderBattle.Flags = bhEnemyAttack;
defenderBattle.Turn = static_cast<std::uint16_t>(Database::gTurn);
defenderBattle.mix = static_cast<std::uint16_t>(mixDefender);
defenderBattle.mixEnemy = static_cast<std::uint16_t>(mixAttacker);
defenderBattle.ToLoc = toLoc;
defenderBattle.FromLoc = fromLoc;
if (attackerLost) {
attackerBattle.Flags |= bhMyUnitLost;
defenderBattle.Flags |= bhEnemyUnitLost;
}
if (defenderLost) {
attackerBattle.Flags |= bhEnemyUnitLost;
defenderBattle.Flags |= bhMyUnitLost;
}
}
int executeAttack(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove)
{
int result = 0;
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const TModel &model = (*player.Model)[un.mix];
int fromLoc = un.Loc;
showMove.EndHealth = moveInfo.EndHealth;
showMove.EndHealthDef = moveInfo.EndHealthDef;
if (moveInfo.MoveType == UnitProcessing::mtAttack)
writeBattleHistory(toLoc, fromLoc, p, moveInfo.Defender, un.mix, (*Database::rw[moveInfo.Defender].Un)[moveInfo.Duix].mix,
moveInfo.EndHealth <= 0, moveInfo.EndHealthDef <= 0);
if (Database::mode >= Database::moMovie) { // show attack in interface modules
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
const bool seeFrom = ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
const bool seeTo = ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
if (seeFrom && seeTo) {
Database::tellAboutModel(p1, p, un.mix);
showMove.emix = (p1 == p) ? -1 : Database::emixSafe(p1, p, un.mix);
callPlayer(cShowAttacking, p1, &showMove);
}
}
}
}
bool loseCityPop = false;
TPlayerContext *defenderPlayer = (moveInfo.Defender >= 0) ? &Database::rw[moveInfo.Defender] : nullptr;
TCity *defenderCity = defenderPlayer ? &(*defenderPlayer->City)[moveInfo.Dcix] : nullptr;
if ((Database::realMap[toLoc] & fCity) &&
((moveInfo.MoveType == UnitProcessing::mtAttack && moveInfo.EndHealthDef <= 0) ||
(moveInfo.MoveType == UnitProcessing::mtBombard &&
(BombardmentDestroysCity || defenderCity->Size > 2)))) {
switch (model.Domain) {
case dGround:
loseCityPop = model.Cap[mcArtillery] > 0 ||
(defenderCity->Built[imWalls] == 0 &&
Database::continent[toLoc] != Database::grWallContinent[moveInfo.Defender]);
break;
case dSea:
loseCityPop = defenderCity->Built[imCoastalFort] == 0;
break;
case dAir:
loseCityPop = defenderCity->Built[imMissileBat] == 0;
break;
default:
break;
}
}
const bool cityDestroyed = loseCityPop && defenderCity && defenderCity->Size <= 2;
if (moveInfo.MoveType == UnitProcessing::mtBombard) {
assert(un.Movement >= 100);
if (model.Attack == 0)
un.Flags &= ~static_cast<decltype(un.Flags)>(unBombsLoaded);
un.Movement -= 100;
} else if (moveInfo.MoveType == UnitProcessing::mtExpel) {
assert(un.Movement >= 100);
un.Job = jNone;
un.Flags &= ~static_cast<decltype(un.Flags)>(unFortified);
un.Movement -= 100;
} else {
assert(moveInfo.MoveType == UnitProcessing::mtAttack);
if (moveInfo.EndHealth == 0) {
Database::removeUnit(p, uix, moveInfo.Defender); // destroy attacker
} else { // update attacker
const int expGain = (un.Health - moveInfo.EndHealth + 1) >> 1;
if (un.Exp + expGain > (nExp - 1) * ExpCost)
un.Exp = static_cast<decltype(un.Exp)>((nExp - 1) * ExpCost);
else
un.Exp = static_cast<decltype(un.Exp)>(un.Exp + expGain);
un.Health = static_cast<decltype(un.Health)>(moveInfo.EndHealth);
un.Job = jNone;
if ((*defenderPlayer->Model)[(*defenderPlayer->Un)[moveInfo.Duix].mix].Domain < dAir)
un.Flags &= ~static_cast<decltype(un.Flags)>(unBombsLoaded);
un.Flags &= ~static_cast<decltype(un.Flags)>(unFortified);
if (un.Movement > 100)
un.Movement -= 100;
else
un.Movement = 0;
}
}
bool zocDefenderDestroyed = false;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
int expelToLoc = -1;
if (moveInfo.MoveType == UnitProcessing::mtExpel) { // expel friendly unit
TUn &defUn = (*defenderPlayer->Un)[moveInfo.Duix];
TCity *defCity = *defenderPlayer->City;
if (defUn.Home >= 0) {
expelToLoc = defCity[defUn.Home].Loc;
} else {
expelToLoc = defCity[0].Loc; // search destination for homeless units
for (int cix1 = 1; cix1 < defenderPlayer->nCity; ++cix1)
if (defCity[cix1].Loc >= 0 && (expelToLoc < 0 || defCity[cix1].Built[imPalace] > 0))
expelToLoc = defCity[cix1].Loc;
}
if (expelToLoc >= 0) {
Database::freeUnit(moveInfo.Defender, moveInfo.Duix);
defUn.Loc = expelToLoc;
Database::placeUnit(moveInfo.Defender, moveInfo.Duix);
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUn.Loc;
++nUpdateLoc;
defUn.Flags |= unWithdrawn;
}
} else if (moveInfo.MoveType == UnitProcessing::mtAttack && moveInfo.EndHealthDef > 0) { // update defender
TUn &defUn = (*defenderPlayer->Un)[moveInfo.Duix];
const int expGain = (defUn.Health - moveInfo.EndHealthDef + 1) >> 1;
if (defUn.Exp + expGain > (nExp - 1) * ExpCost)
defUn.Exp = static_cast<decltype(defUn.Exp)>((nExp - 1) * ExpCost);
else
defUn.Exp = static_cast<decltype(defUn.Exp)>(defUn.Exp + expGain);
defUn.Health = static_cast<decltype(defUn.Health)>(moveInfo.EndHealthDef);
} else { // destroy defenders
if (moveInfo.MoveType != UnitProcessing::mtBombard) {
zocDefenderDestroyed =
((*defenderPlayer->Model)[(*defenderPlayer->Un)[moveInfo.Duix].mix].Flags & mdZOC) != 0;
if ((((Database::realMap[toLoc] & fCity) == 0) && ((Database::realMap[toLoc] & fTerImp) != tiBase) &&
((Database::realMap[toLoc] & fTerImp) != tiFort)) ||
(loseCityPop && defenderCity->Size == 2)) // no city, base or fortress
Database::removeAllUnits(moveInfo.Defender, toLoc, p);
else
Database::removeUnit(moveInfo.Defender, moveInfo.Duix, p);
}
if (loseCityPop) { // city defender defeated -- shrink city
if (!cityDestroyed) {
CityProcessing::cityShrink(moveInfo.Defender, moveInfo.Dcix);
} else {
TUn *defUnits = *defenderPlayer->Un;
for (int uix1 = 0; uix1 < defenderPlayer->nUn; ++uix1) {
if (defUnits[uix1].Loc >= 0 && defUnits[uix1].Home == moveInfo.Dcix) {
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = defUnits[uix1].Loc;
++nUpdateLoc;
}
}
// unit will be removed -- remember position and update for all players
destroyCityTellPlayers(moveInfo.Defender, moveInfo.Dcix, false);
Database::checkBorders(toLoc, moveInfo.Defender);
Database::recalcPeaceMap(p);
}
}
}
if (cityDestroyed && nUpdateLoc > 0)
Database::recalcMapZoC(p);
else if (zocDefenderDestroyed)
Database::recalcV8ZoC(p, toLoc);
Database::updateUnitMap(fromLoc);
Database::updateUnitMap(toLoc, loseCityPop);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)]);
// tell about lost units of defender
if (Database::mode >= Database::moMovie) {
TModelInfo *enemyModel = *player.EnemyModel;
for (int i = 0; i < player.nEnemyModel; ++i)
enemyModel[i].Lost = Database::destroyed[p][enemyModel[i].Owner][enemyModel[i].mix];
for (int p1 = 0; p1 < nPl; ++p1) { // show after-attack in interface modules
if (((1 << p1) & Database::gWatching) && (p1 != p || playerBrain[p1]->kind == BrainType::Term)) {
const bool seeFrom = ((Database::observeLevel[fromLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
const bool seeTo = ((Database::observeLevel[toLoc] >> (2 * p1)) & 3) >= Database::lObserveUnhidden;
if (seeTo && cityDestroyed)
callPlayer(cShowCityChanged, p1, &toLoc); // city was destroyed
if (seeFrom && seeTo) {
callPlayer(cShowAfterAttack, p1, &toLoc);
callPlayer(cShowAfterAttack, p1, &fromLoc);
} else {
if (seeTo)
callPlayer(cShowUnitChanged, p1, &toLoc);
if (seeFrom)
callPlayer(cShowUnitChanged, p1, &fromLoc);
}
if (seeTo && moveInfo.MoveType == UnitProcessing::mtExpel && expelToLoc >= 0)
callPlayer(cShowUnitChanged, p1, &expelToLoc);
}
}
}
return result;
}
int moveUnit(int p, int uix, int dx, int dy, bool testOnly)
{
assert(((1 << p) & Database::invalidTreatyMap) == 0);
TPlayerContext &player = Database::rw[p];
TUn &un = (*player.Un)[uix];
const int toLoc = Database::dLoc(un.Loc, dx, dy);
if (toLoc < 0 || toLoc >= Database::mapSize)
return eInvalid;
UnitProcessing::TMoveInfo moveInfo;
int result = UnitProcessing::calculateMove(p, uix, toLoc, 3 - (dy & 1), testOnly, moveInfo);
if (result == eZOC_EnemySpotted)
zocTile = toLoc;
if (result >= rExecuted && !testOnly) {
TShowMove showMove{};
showMove.dx = dx;
showMove.dy = dy;
showMove.FromLoc = un.Loc;
showMove.mix = un.mix;
showMove.Health = un.Health;
showMove.Fuel = un.Fuel;
showMove.Exp = un.Exp;
showMove.Load = un.TroopLoad + un.AirLoad;
showMove.Owner = p;
showMove.Flags = (un.TroopLoad > 0 || un.AirLoad > 0) ? unMulti : 0;
switch (moveInfo.MoveType) {
case UnitProcessing::mtCapture:
showMove.Flags |= umCapturing;
break;
case UnitProcessing::mtSpyMission:
showMove.Flags |= umSpyMission;
break;
case UnitProcessing::mtBombard:
showMove.Flags |= umBombarding;
break;
case UnitProcessing::mtExpel:
showMove.Flags |= umExpelling;
break;
default:
break;
}
switch (moveInfo.MoveType) {
case UnitProcessing::mtMove:
case UnitProcessing::mtCapture:
case UnitProcessing::mtSpyMission:
result = executeMove(p, uix, toLoc, moveInfo, showMove) | result;
break;
case UnitProcessing::mtAttack:
case UnitProcessing::mtBombard:
case UnitProcessing::mtExpel:
result = executeAttack(p, uix, toLoc, moveInfo, showMove) | result;
break;
default:
break;
}
}
return result;
}
int countPrice(const TOffer &offer, std::uint32_t priceType)
{
int result = 0;
for (int i = 0; i < offer.nDeliver + offer.nCost; ++i)
if ((static_cast<std::uint32_t>(offer.Price[i]) & 0xFFFF0000u) == priceType)
++result;
return result;
}
} // namespace GameServer
} // namespace Cevo
File diff suppressed because it is too large. Load diff
+628
View File
@@ -0,0 +1,628 @@
// 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 "GameServer.h"
#include "GameServerInternal.h"
#include "Global.h"
#include "Cevo/CityProcessing.h"
#include "Cevo/CmdList.h"
#include "Cevo/Database.h"
#include "Cevo/Map.h"
#include "Cevo/Platform.h"
#include "Cevo/UnitProcessing.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPoint>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <vector>
namespace Cevo {
namespace GameServer {
void beforeTurn0()
{
TPlayerContext &player = Database::rw[pTurn];
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) // init movement points for first turn
un[uix].Movement = model[un[uix].mix].Speed;
if (Database::difficulty[pTurn] > 0) {
Database::discoverViewAreas(pTurn);
} else { // supervisor
Database::discoverAll(pTurn, Database::lObserveSuper);
for (int p1 = 1; p1 < nPl; ++p1) {
if ((1 << p1) & Database::gAlive) {
Database::giveCivilReport(pTurn, p1);
Database::giveMilReport(pTurn, p1);
}
}
}
}
void destroySpacePortTellPlayers(int p, int pCapturer)
{
// stop ship part production
TCity *city = *Database::rw[p].City;
for (int cix = 0; cix < Database::rw[p].nCity; ++cix) {
TCity &c = city[cix];
if (c.Loc >= 0 && (c.Project & cpImp) &&
((c.Project & cpIndex) == woMir || Imp[c.Project & cpIndex].Kind == ikShipPart)) {
Database::rw[p].Money += c.Prod0;
c.Prod = 0;
c.Prod0 = 0;
c.Project = cpImp + imTrGoods;
c.Project0 = cpImp + imTrGoods;
}
}
// destroy ship
TShipInfo &ship = Database::gShip[p];
if (ship.Parts[0] + ship.Parts[1] + ship.Parts[2] > 0) {
TShowShipChange showShipChange{};
for (int i = 0; i < nShipPart; ++i) {
showShipChange.Ship1Change[i] = -ship.Parts[i];
if (pCapturer >= 0) {
showShipChange.Ship2Change[i] = ship.Parts[i];
Database::gShip[pCapturer].Parts[i] += ship.Parts[i];
}
ship.Parts[i] = 0;
}
if (Database::mode >= Database::moMovie) {
showShipChange.Reason = pCapturer >= 0 ? scrCapture : scrDestruction;
showShipChange.Ship1Owner = p;
showShipChange.Ship2Owner = pCapturer;
for (int p1 = 0; p1 < nPl; ++p1) {
if ((1 << p1) & (Database::gAlive | Database::gWatching)) {
std::memcpy(Database::rw[p1].Ship, Database::gShip.data(), sizeof(Database::rw[p1].Ship));
if ((1 << p1) & Database::gWatching)
callPlayer(cShowShipChange, p1, &showShipChange);
}
}
}
}
}
void destroyCityTellPlayers(int p, int cix, bool saveUnits)
{
if ((*Database::rw[p].City)[cix].Built[imSpacePort] > 0)
destroySpacePortTellPlayers(p, -1);
Database::destroyCity(p, cix, saveUnits);
}
void changeCityOwnerTellPlayers(int pOld, int cixOld, int pNew)
{
if ((*Database::rw[pOld].City)[cixOld].Built[imSpacePort] > 0) {
if (Database::rw[pNew].NatBuilt[imSpacePort] > 0)
destroySpacePortTellPlayers(pOld, pNew);
else
destroySpacePortTellPlayers(pOld, -1);
}
Database::changeCityOwner(pOld, cixOld, pNew);
}
void checkWin(int p)
{
bool shipComplete = true;
for (int i = 0; i < nShipPart; ++i)
if (Database::gShip[p].Parts[i] < ShipNeed[i]) {
shipComplete = false;
break;
}
if (shipComplete)
gWinner |= (1 << p); // game won!
}
void beforeTurn()
{
assert((1 << pTurn) & (Database::gAlive | Database::gWatching));
if (((1 << pTurn) & Database::gAlive) == 0 && Database::difficulty[pTurn] > 0)
return;
TPlayerContext &player = Database::rw[pTurn];
if (Database::gWonder[woGrLibrary].EffectiveOwner == pTurn && gWinner == 0) { // check great library effect
int nAlive = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if ((1 << p1) & Database::gAlive)
++nAlive;
for (int ad = 0; ad <= nAdv - 5; ++ad) {
if (player.Tech[ad] < tsSeen) {
int nAppliers = 0;
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != pTurn && ((1 << p1) & Database::gAlive) && Database::rw[p1].Tech[ad] >= tsApplicable)
++nAppliers;
if (nAppliers * 2 > nAlive) {
Database::seeTech(pTurn, ad);
++Database::nTech[pTurn];
if (Database::mode >= Database::moMovie)
callPlayer(cShowGreatLibTech, pTurn, &ad);
// do not call CallPlayer(pTurn) while map is invalid
}
}
}
}
Database::maskD(Database::observeLevel.data(), Database::mapSize, ~static_cast<std::uint32_t>(3 << (2 * pTurn)));
if (Database::mode > Database::moLoading_Fast)
Database::maskD(*player.Map, Database::mapSize,
~static_cast<std::uint32_t>(fUnit | fHiddenUnit | fStealthUnit | fObserved | fSpiedOut |
fOwned | fOwnZoCUnit | fInEnemyZoC));
player.nEnemyUn = 0;
bool mirBuilt = false;
if (Database::difficulty[pTurn] > 0 && gWinner == 0) {
if (player.nCity > 0) {
TCity *city0 = *player.City;
TUn *un0 = *player.Un;
const TModel *model0 = *player.Model;
for (int p1 = 0; p1 < nPl; ++p1) {
if (Database::gTurn != player.EvaStart[p1] + PeaceEvaTurns)
continue;
// peace contract -- remove all units from p1's territory
int loc1 = city0[0].Loc; // search destination for homeless units
for (int cix = 1; cix < player.nCity; ++cix)
if (city0[cix].Loc >= 0 && (loc1 < 0 || city0[cix].Built[imPalace] > 0))
loc1 = city0[cix].Loc;
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &un = un0[uix];
if (un.Loc >= 0 && model0[un.mix].Kind != mkDiplomat && (un.Home >= 0 || loc1 >= 0) &&
(Database::realMap[un.Loc] >> 27) == static_cast<std::uint32_t>(p1)) {
const int oldLoc = un.Loc;
if (un.Master >= 0) { // transport unload
if (model0[un.mix].Domain == dAir)
--un0[un.Master].AirLoad;
else
--un0[un.Master].TroopLoad;
un.Master = -1;
} else {
Database::freeUnit(pTurn, uix);
}
un.Loc = un.Home >= 0 ? city0[un.Home].Loc : loc1;
Database::placeUnit(pTurn, uix);
Database::updateUnitMap(oldLoc);
Database::updateUnitMap(un.Loc);
un.Flags |= unWithdrawn;
player.Happened |= phPeaceEvacuation;
}
}
}
}
TShowShipChange showShipChange{};
bool tribeExtinct = true;
int nUpdateLoc = 0;
std::array<int, nUmax> updateLoc{};
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) { // city loop 1
TCity &c = city[cix];
if (c.Loc < 0)
continue;
// check for siege
int siegedTiles = 0;
Database::Vicinity21Loc radius;
Database::v21ToLoc(c.Loc, radius);
for (int v21 = 1; v21 <= 26; ++v21) {
if ((c.Tiles & (1u << v21) & ~(1u << Database::CityOwnTile)) == 0)
continue;
const int loc1 = radius[static_cast<std::size_t>(v21)];
assert(loc1 >= 0 && loc1 < Database::mapSize && Database::usedByCity[loc1] == c.Loc);
const auto p1 = static_cast<int>(Database::realMap[loc1] >> 27);
if ((Database::realMap[loc1] & fCity) ||
(p1 < nPl && p1 != pTurn && player.Treaty[p1] >= trPeace) ||
(Database::zocMap[loc1] > 0 && Database::occupant[loc1] != pTurn &&
player.Treaty[Database::occupant[loc1]] < trPeace)) {
c.Tiles &= ~(1u << v21);
Database::usedByCity[loc1] = -1;
c.Flags |= chSiege;
++siegedTiles;
}
}
while (siegedTiles > 0) { // replace sieged tiles
if (!CityProcessing::addBestCityTile(pTurn, cix))
break;
--siegedTiles;
}
if ((c.Flags & chFounded) == 0) {
if (CityProcessing::cityTurn(pTurn, cix)) {
tribeExtinct = false;
} else { // city is erased
Database::removeDomainUnits(dSea, pTurn, c.Loc);
Database::removeDomainUnits(dAir, pTurn, c.Loc);
(*player.Map)[c.Loc] &= ~static_cast<std::uint32_t>(fCity); // !!! do this in inner core
updateLoc[static_cast<std::size_t>(nUpdateLoc)] = c.Loc;
++nUpdateLoc;
destroyCityTellPlayers(pTurn, cix, true);
}
if ((c.Flags & chProduction) && (c.Project0 & cpImp)) {
if ((c.Project0 & cpIndex) == woMir)
mirBuilt = true;
else if ((c.Project0 & cpIndex) == woManhattan)
gColdWarStart = Database::gTurn;
else if (Imp[c.Project0 & cpIndex].Kind == ikShipPart) // ship parts produced
++showShipChange.Ship1Change[(c.Project0 & cpIndex) - imShipComp];
}
}
} // city loop 1
if (nUpdateLoc > 0) {
Database::checkBorders(-1, pTurn);
for (int i = 0; i < nUpdateLoc; ++i)
Database::updateUnitMap(updateLoc[static_cast<std::size_t>(i)], true);
if (Database::mode >= Database::moMovie)
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn)
for (int i = 0; i < nUpdateLoc; ++i)
if (((Database::observeLevel[updateLoc[static_cast<std::size_t>(i)]] >> (2 * p1)) & 3) >=
Database::lObserveUnhidden)
callPlayer(cShowCityChanged, p1, &updateLoc[static_cast<std::size_t>(i)]);
}
{
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) { // unit loop 2
TUn &u = un[uix];
if (u.Loc < 0)
continue;
if (u.Health < 100)
UnitProcessing::recover(pTurn, uix);
if (u.Flags & unMountainDelay) {
u.Movement = 0;
u.Flags &= ~static_cast<decltype(u.Flags)>(unMountainDelay);
} else {
u.Movement = Database::unitSpeed(pTurn, u.mix, u.Health); // refresh movement
}
assert(u.Loc >= 0);
if (model[u.mix].Kind != mkDiplomat) { // check treaty violation
const auto p1 = static_cast<int>(Database::realMap[u.Loc] >> 27);
if (p1 < nPl && p1 != pTurn && player.Treaty[p1] >= trPeace) {
if ((u.Job == jCity || u.Job == jPillage || u.Job == jClear || u.Job == jAfforest ||
u.Job == jTrans) ||
((u.Job == jIrr || u.Job == jMine || u.Job == jFort || u.Job == jBase) &&
(Database::realMap[u.Loc] & fTerImp)))
u.Job = jNone;
if (Database::gTurn > player.EvaStart[p1] + PeaceEvaTurns && player.Treaty[p1] != trAlliance) {
player.EvaStart[p1] = Database::gTurn;
player.Happened |= phPeaceViolation;
if (Database::mode >= Database::moMovie)
callPlayer(cShowPeaceViolation, p1, &pTurn);
}
}
}
if (Database::serverVersion[pTurn] >= 0x000EF0) {
if (u.Health <= 0 || tribeExtinct)
Database::removeUnitUpdateMap(pTurn, uix);
}
}
}
if (Database::serverVersion[pTurn] < 0x000EF0) {
TUn *un = *player.Un;
bool jobDone = false; // intentionally not reset per-iteration, matches the original's stale read
for (int uix = 0; uix < player.nUn; ++uix) { // unit loop 3
TUn &u = un[uix];
if (u.Loc < 0)
continue;
int loc1 = u.Loc;
const int job0 = u.Job;
if (u.Job != jNone)
jobDone = UnitProcessing::work(pTurn, uix);
// settlers do terrain improvement jobs
if (u.Health <= 0 || tribeExtinct)
Database::removeUnitUpdateMap(pTurn, uix);
if (job0 == jCity && jobDone) { // new city
CityProcessing::addBestCityTile(pTurn, player.nCity - 1);
Database::updateUnitMap(loc1, true);
if (Database::mode >= Database::moMovie) // tell enemies
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn &&
(Database::observeLevel[loc1] & (3 << (2 * p1))))
callPlayer(cShowCityChanged, p1, &loc1);
}
}
}
{ // pollution - city loop 3
TCity *cityList = *player.City;
for (int cix = 0; cix < player.nCity; ++cix)
if (cityList[cix].Loc >= 0 && cityList[cix].Pollution >= MaxPollution)
CityProcessing::pollute(pTurn, cix);
}
Database::compactLists(pTurn);
if (player.nUn == 0 && player.nCity == 0) { // nation made extinct
player.Happened |= phExtinct;
Database::gAlive &= ~(1 << pTurn);
stat[stPop][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stMil][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stScience][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stExplore][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stTerritory][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
stat[stWork][pTurn][static_cast<std::size_t>(Database::gTurn)] = 0;
for (int p1 = 0; p1 < nPl; ++p1) {
if (((1 << p1) & (Database::gAlive | Database::gWatching)) == 0)
continue;
if (p1 != pTurn) {
Database::giveCivilReport(p1, pTurn);
if ((Database::gTestFlags & tfUncover) || Database::difficulty[p1] == 0 ||
Database::rw[p1].Treaty[pTurn] == trAlliance)
Database::giveMilReport(p1, pTurn);
}
TPlayerContext &other = Database::rw[p1];
other.Alive = Database::gAlive;
for (int loc1 = 0; loc1 < Database::mapSize; ++loc1)
// remove territory of extinct nation from player maps
if ((*other.Territory)[loc1] == pTurn) {
(*other.Territory)[loc1] = -1;
(*other.Map)[loc1] &= ~static_cast<std::uint32_t>(fPeace);
}
}
return;
}
// check research
const int cost = Database::techCost(pTurn);
if (Database::gTestFlags & tfImmAdvance)
player.Research = cost;
if ((player.Happened & phTech) == 0 && player.Research >= cost) {
if (player.ResearchTech == adMilitary)
Database::enableDevModel(pTurn); // new Unit class initiated
else if (player.ResearchTech >= 0)
Database::discoverTech(pTurn, player.ResearchTech);
player.Research -= cost;
player.Happened |= phTech;
player.ResearchTech = -1;
} else if (player.ResearchTech == -2 && player.nCity > 0) {
player.Happened |= phTech;
player.ResearchTech = -1;
}
if (player.Credibility < player.MaxCredibility) {
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != pTurn && ((1 << p1) & Database::gAlive) && player.Treaty[p1] >= trPeace) {
++player.Credibility;
break;
}
}
}
if (gWinner == 0)
checkWin(pTurn);
if (Database::mode >= Database::moMovie && gWinner == 0 &&
(showShipChange.Ship1Change[0] > 0 || showShipChange.Ship1Change[1] > 0 ||
showShipChange.Ship1Change[2] > 0)) {
showShipChange.Reason = scrProduction;
showShipChange.Ship1Owner = pTurn;
showShipChange.Ship2Owner = -1;
for (int p1 = 0; p1 < nPl; ++p1) {
if (p1 != pTurn && ((1 << p1) & (Database::gAlive | Database::gWatching))) {
std::memcpy(Database::rw[p1].Ship, Database::gShip.data(), sizeof(Database::rw[p1].Ship));
if ((1 << p1) & Database::gWatching)
callPlayer(cShowShipChange, p1, &showShipChange);
}
}
}
if (winOnAlone && (Database::gAlive & ~((1 << pTurn) | 1)) == 0)
gWinner = 1 << pTurn; // break if only one nation left
if (Database::gTurn == player.AnarchyStart + AnarchyTurns) {
player.AnarchyStart = -AnarchyTurns - 1;
player.Government = gDespotism;
for (int p1 = 0; p1 < nPl; ++p1)
if (p1 != pTurn && ((Database::gAlive | Database::gWatching) & (1 << p1)))
Database::rw[p1].EnemyReport[pTurn]->Government = gDespotism;
player.Happened += phChangeGov;
}
} // if Difficulty[pTurn] > 0
if (pTurn == 0 && gWinner > 0) { // game over, give world map and all reports to player 0
Database::discoverAll(pTurn, Database::lObserveSuper);
for (int p1 = 1; p1 < nPl; ++p1) {
if ((1 << p1) & Database::gAlive) {
if (player.Treaty[p1] < trNone) {
player.Treaty[p1] = trNone;
Database::rw[p1].Treaty[pTurn] = trNone;
}
Database::giveCivilReport(pTurn, p1);
Database::giveMilReport(pTurn, p1);
}
}
} else {
// show observed areas
if ((Database::gTestFlags & tfUncover) || Database::difficulty[pTurn] == 0) { // supervisor - all tiles visible
if (playerBrain[pTurn]->kind != BrainType::NoTerm &&
(Database::difficulty[pTurn] > 0 || Database::mode > Database::moLoading_Fast))
Database::discoverAll(pTurn, Database::lObserveSuper);
} else {
Database::discoverViewAreas(pTurn);
if (mirBuilt)
Database::discoverAll(pTurn, Database::lObserveUnhidden);
}
}
}
void afterTurn()
{
TPlayerContext &player = Database::rw[pTurn];
TCity *city = *player.City;
for (int cix = 0; cix < player.nCity; ++cix) {
if (city[cix].Loc >= 0) {
city[cix].Flags &= (chCaptured | chDisorder);
CityProcessing::collectCityResources(pTurn, cix); // new style
}
}
player.Money += player.OracleIncome;
player.OracleIncome = 0;
if (Database::gWonder[woOracle].EffectiveOwner == pTurn) {
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gAlive) && (p1 == pTurn || player.Treaty[p1] > trNoContact)) {
const TCity *otherCity = *Database::rw[p1].City;
for (int cix = 0; cix < Database::rw[p1].nCity; ++cix)
if (otherCity[cix].Loc >= 0 && otherCity[cix].Built[imTemple] > 0)
++player.OracleIncome;
}
}
if ((Database::gTestFlags & tfImmImprove) == 0 && player.Government != gAnarchy)
for (int cix = 0; cix < player.nCity; ++cix)
if (city[cix].Loc >= 0 && (city[cix].Flags & chCaptured) == 0)
CityProcessing::payCityMaintenance(pTurn, cix);
if (Database::serverVersion[pTurn] >= 0x000EF0) { // let settlers work
for (int cix = 0; cix < player.nCity; ++cix)
city[cix].Flags &= ~static_cast<decltype(city[cix].Flags)>(chFounded);
TUn *un = *player.Un;
bool jobDone = false; // intentionally not reset per-iteration, matches the original's stale read
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
if (u.Loc < 0)
continue;
int loc1 = u.Loc;
const int job0 = u.Job;
if (u.Job != jNone)
jobDone = UnitProcessing::work(pTurn, uix);
// settlers do terrain improvement jobs
if (u.Health <= 0)
Database::removeUnitUpdateMap(pTurn, uix);
if (job0 == jCity && jobDone) { // new city
CityProcessing::addBestCityTile(pTurn, player.nCity - 1);
Database::updateUnitMap(loc1, true);
if (Database::mode >= Database::moMovie) // tell enemies
for (int p1 = 0; p1 < nPl; ++p1)
if (((1 << p1) & Database::gWatching) && p1 != pTurn &&
(Database::observeLevel[loc1] & (3 << (2 * p1))))
callPlayer(cShowCityChanged, p1, &loc1);
}
}
}
{ // next turn for all units
TUn *un = *player.Un;
const TModel *model = *player.Model;
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
if (u.Loc < 0)
continue;
if (model[u.mix].Domain == dAir) {
if (u.Master >= 0 || (Database::realMap[u.Loc] & fCity) ||
(Database::realMap[u.Loc] & fTerImp) == tiBase) {
u.Fuel = static_cast<decltype(u.Fuel)>(model[u.mix].Cap[mcFuel]);
u.Flags |= unBombsLoaded;
} else if (model[u.mix].Kind == mkSpecial_Glider) { // glider
if ((Database::realMap[u.Loc] & fTerrain) < static_cast<std::uint32_t>(fGrass)) {
Database::removeUnitUpdateMap(pTurn, uix); // unit lost
player.Happened |= phGliderLost;
}
} else {
--u.Fuel;
if (u.Fuel < 0) {
Database::removeUnitUpdateMap(pTurn, uix); // unit lost
player.Happened |= phPlaneLost;
}
}
} else if (u.Master < 0 && u.Movement > 0) { // check HostileDamage
u.Health = static_cast<decltype(u.Health)>(
u.Health - UnitProcessing::hostileDamage(pTurn, u.mix, u.Loc, u.Movement));
if (u.Health < 0)
Database::removeUnitUpdateMap(pTurn, uix);
}
} // unit loop 1
for (int uix = 0; uix < player.nUn; ++uix) {
TUn &u = un[uix];
u.Flags &= ~static_cast<decltype(u.Flags)>(unWithdrawn);
if (u.Loc >= 0 && model[u.mix].Domain == dGround && u.Master < 0 &&
(static_cast<int>(u.Movement) == model[u.mix].Speed ||
(model[u.mix].Cap[mcAcademy] > 0 && u.Movement * 2 >= model[u.mix].Speed)))
u.Flags |= unFortified; // fortify unmoved units
}
}
if ((Database::gTestFlags & tfUncover) == 0 && Database::difficulty[pTurn] > 0) {
// restrict view area to current positions
Database::maskD(Database::observeLevel.data(), Database::mapSize, ~static_cast<std::uint32_t>(3 << (2 * pTurn)));
if (Database::mode > Database::moLoading_Fast)
Database::maskD(*player.Map, Database::mapSize,
~static_cast<std::uint32_t>(fUnit | fHiddenUnit | fStealthUnit | fObserved | fSpiedOut |
fOwned | fOwnZoCUnit | fInEnemyZoC));
player.nEnemyUn = 0;
Database::discoverViewAreas(pTurn);
}
if (gWinner == 0)
for (int p1 = 0; p1 < nPl; ++p1)
if ((1 << p1) & Database::gAlive)
checkWin(p1);
}
void nextPlayerImpl()
{
if (Database::gTurn == 0)
beforeTurn0();
else
beforeTurn();
noLogCityTileChanges();
generateStat(pTurn);
inform(pTurn);
changeClient();
}
void nextPlayer()
{
nextPlayerImpl();
}
} // namespace GameServer
} // namespace Cevo
+2 -3707
View File
File diff suppressed because it is too large. Load diff
-2
View File
@@ -107,8 +107,6 @@ void done();
void startNewGame(const QString &fileName, const QString &mapFileName, int newlx, int newly, int newLandMass,
int newMaxTurn);
bool loadGame(const QString &fileName, const QString &writeFileName, int turn, bool movieMode);
// NOT YET IMPLEMENTED: needs the procedural map generator (see banner
// comment above) for the random-map (LandMass > 0) path.
void editMap(const QString &mapFileName, const QString &writeMapFileName, int newlx, int newly, int newLandMass);
void fillMap(std::uint32_t terrainType, bool specialResources);
void directHelp(int command);
+178
View File
@@ -0,0 +1,178 @@
// 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
// GameServer.pas's own implementation-section-private (`unit`-local)
// globals and helpers, shared across the GameServer.<Section>.cpp
// translation units that GameServer.cpp is now split into. Not part of the
// public GameServer.h API - include this only from GameServer*.cpp files.
// Before the split these lived in (two) anonymous namespaces 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) GameServer::
// symbols instead - still private by convention, just no longer enforced
// by the compiler. Every global below is defined in GameServer.cpp.
#include "GameServer.h"
#include "Cevo/CmdList.h"
#include "Cevo/UnitProcessing.h"
#include <QByteArray>
#include <QString>
#include <array>
#include <cstdint>
#include <vector>
namespace Cevo {
namespace GameServer {
extern NotifyFunction notify;
// Equivalent of Pascal's unit-level private `bix: TBrains` ("brain of the
// players") - renamed to avoid colliding with the pervasive `bix`
// parameter/loop-variable name used for brain *indices* elsewhere in the
// original (e.g. InitBrain(bix: TBrain), CallClient(bix, Command, ...)).
extern std::array<Brain *, nPl> playerBrain;
extern bool previewElevation;
// Remaining unit-level private state (GameServer.pas's own big private
// `var` block).
extern int maxTurn;
extern int pTurn;
extern int gWinner;
extern int gColdWarStart;
extern int pDipActive;
extern int pContacted;
extern TOffer lastOffer;
extern int uixSelectedTransport;
extern int spyMission;
extern bool winOnAlone;
extern bool autoSaveExists;
extern CmdListState autoSaveState;
extern std::array<void *, nPl> savedData;
extern std::array<void *, nPl> debugMap;
extern std::array<int, nPl> originalDataVersion;
extern std::array<int, nPl> devModelTurn; // turn of last sCreateDevModel call (comment name is stale in the original too)
extern std::array<QString, nPl> aiInfo;
extern QString aiCredits;
// Persistent byte-buffer caches for sGetAIInfo/sGetAICredits, which hand
// out a raw const char* into AIInfo[]/AICredits (valid until the next such
// call - same "valid until next mutating call" convention already used
// for CmdList::get's data pointer).
extern QByteArray aiInfoUtf8Cache;
extern QByteArray aiCreditsUtf8Cache;
extern QString mapFileName; // name of map to use, empty for random
extern QString logFileName;
extern QString savePath; // directory of the file for saving the current game
extern int lastEndClientCommand;
extern int ccCommand;
extern int ccPlayer;
extern std::array<int, 15> ccData;
extern double lastClientTime;
extern int gStealFrom;
extern int zocTile;
// GameServer.pas's own local ProjectType() result constants (Server()'s
// sSetCityProject handling only - not a shared Protocol.h concept).
constexpr int ptSelect = 0;
constexpr int ptTrGoods = 1;
constexpr int ptUn = 2;
constexpr int ptCaravan = 3;
constexpr int ptImp = 4;
constexpr int ptWonder = 6;
constexpr int ptShip = 7;
constexpr int ptInvalid = 8;
extern int loadTurn; // turn where to stop loading
extern int nLogOpened; // nLog of opened book
extern bool movieStopped;
extern bool loadOK;
// SavedTiles[cix] - a single shared scratch array (not per-player): only
// RW[pTurn]'s cities are ever "in focus" at a time, matching the original.
extern std::array<std::uint32_t, nCmax> savedTiles;
// Predefined map snapshot (only non-empty when Database::landMass == 0) -
// a disclosed std::vector-based simplification of the original's
// GetMem/FreeMem(MapField) raw pointer.
extern std::vector<std::uint32_t> mapField;
// Stat[st][p][turn] equivalent - std::vector instead of GetMem/FreeMem.
extern std::array<std::array<std::vector<std::int32_t>, nPl>, nStat> stat;
// Server() is the ~1600-line client-to-server command dispatcher, defined
// in GameServer.Server.cpp - the single biggest piece of GameServer.pas.
int CEVO_ABI_CALL server(int command, int player, int subject, void *data);
// --- GameServer.ClientCallPlumbing.cpp ---
QString getAiDir();
void notifyEvent(NotifyId id, int index = 0);
void insertTerritoryUpdateCommands();
void callPlayer(int command, int p, void *data);
void callAllPlayers(int command, void *data);
void callClient(int brainIndex, int command, void *data);
void putMessage(int level, const QString &text);
void changeClientWhenDone(int command, int player, const void *data, int dataSize);
void forceClientDeactivation();
void inform(int p);
void logChanges();
void noLogChanges();
bool hasChanges(int p);
void initBrain(Brain &brain);
// --- GameServer.Lifecycle.cpp ---
void saveGame(const QString &fileName, bool autoSave);
void startGame();
void endGame();
void generateStat(int p);
void logCityTileChanges();
void noLogCityTileChanges();
bool hasCityTileChanges();
// --- GameServer.TurnProcessing.cpp ---
void beforeTurn0();
void destroySpacePortTellPlayers(int p, int pCapturer);
void destroyCityTellPlayers(int p, int cix, bool saveUnits);
void changeCityOwnerTellPlayers(int pOld, int cixOld, int pNew);
void checkWin(int p);
void beforeTurn();
void afterTurn();
void nextPlayerImpl();
// --- GameServer.MoveAndCombat.cpp ---
int executeMove(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove);
void ensureBattleHistoryCapacity(TPlayerContext &player);
void writeBattleHistory(int toLoc, int fromLoc, int attacker, int defender, int mixAttacker, int mixDefender,
bool attackerLost, bool defenderLost);
int executeAttack(int p, int uix, int toLoc, UnitProcessing::TMoveInfo &moveInfo, TShowMove showMove);
int moveUnit(int p, int uix, int dx, int dy, bool testOnly);
int countPrice(const TOffer &offer, std::uint32_t priceType);
} // namespace GameServer
} // namespace Cevo