Files
c-evo-evo/game/GameServer.Lifecycle.cpp

849 lines
30 KiB
C++

// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "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)
{
constexpr std::int32_t PreviewRnd = 41601260; // randseed for preview map
Database::lx = lxmax;
Database::ly = lymax;
Database::mapSize = Database::lx * Database::ly;
Database::landMass = landMass;
Database::delphiRandSeed = PreviewRnd;
if (!previewElevation) {
Database::createElevation();
previewElevation = true;
}
Database::createMap(true);
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