Files
c-evo-evo/game/localplayer/Term.MainScreen.Client.cpp
T

459 lines
18 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.
// TMainScreen.Client() (Term.pas): the command dispatcher the server calls
// for the human player.
//
// PORT STATUS: served so far - cDebugMessage, cShowNego, cInitModule,
// cReleaseModule, cHelpOnly/cStartHelp/cStartCredits, cNewGame/cLoadGame/
// cMovie/cNewMap, cGetReady/cReplay, cBreakGame, the pure message commands
// (cShowCancelTreaty*, cShowSupportAllianceAgainst, cShowPeaceViolation,
// cShowMissionResult, cShowShipChange, cShowGreatLibTech), cShowEndContact
// and the client exclusive commands. Still missing because they need
// InitTurn()/the main map and panel (not ported): cShowGame, cTurn/
// cResume/cContinue/cMovieTurn/cMovieEndTurn, cEditMap, scContact and
// scDipStart..scDipBreak, cShowUnitChanged/CityChanged/AfterMove/
// AfterAttack/Moving/Capturing/Attacking, cRefreshDebugMap. Screen-only
// side effects inside the served commands (button visibility, panel
// repaint, sounds) are marked TODO.
#include "Term.MainScreen.h"
#include "Cevo/CevoGraphicSet.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include "Cevo/CmdList.h"
#include "Global.h"
#include "Messg.h"
#include "Tribes.h"
#include <QApplication>
#include <algorithm>
#include <cstring>
#include <type_traits>
namespace Cevo {
namespace Term {
static_assert(std::is_trivially_copyable_v<PersistentData>,
"PersistentData lives in server-allocated raw memory (and savegames)");
namespace {
QString negoOfferText(const TShowNegoData &nego)
{
const TOffer &offer = nego.Offer;
QString s = QStringLiteral("P%1 to P%2: ").arg(nego.pSender).arg(nego.pTarget);
if (nego.Action == scDipOffer && offer.nDeliver + offer.nCost > 0) {
s += QStringLiteral("Offer ");
for (int i = 0; i < offer.nDeliver + offer.nCost; ++i) {
if (i == offer.nDeliver)
s += QStringLiteral(" for ");
else if (i > 0)
s += QLatin1Char('+');
const int price = offer.Price[i];
const int value = price & 0xFFFFFF;
switch (price & opMask) {
case opChoose: s += QStringLiteral("Price of choice"); break;
case opCivilReport: s += QStringLiteral("State report"); break;
case opMilReport: s += QStringLiteral("Military report"); break;
case opMap: s += QStringLiteral("Map"); break;
case opTreaty: s += QStringLiteral("Treaty"); break;
case opShipParts: s += QStringLiteral("Ship part"); break;
case opMoney: s += QString::number(value) + QLatin1Char('o'); break;
case opTribute: s += QString::number(value) + QStringLiteral("o tribute"); break;
case opTech: s += phrases.lookup(QStringLiteral("ADVANCES"), value); break;
case opAllTech: s += QStringLiteral("All advances"); break;
case opModel:
s += Tribes::tribe[static_cast<std::size_t>(nego.pSender)]->modelNameAt(value);
break;
case opAllModel: s += QStringLiteral("All models"); break;
default: break;
}
}
} else if (nego.Action == scDipAccept) {
s += QStringLiteral("--- ACCEPTED! ---");
} else {
return QString();
}
return s;
}
// Initial per-player persistent data of a new game.
void initPersistentData(PersistentData &data)
{
const TNewGameData &g = ClientTools::g;
data.farTech = adNone;
for (auto &row : data.enhancementJobs)
std::fill(std::begin(row), std::end(row), static_cast<std::uint8_t>(jNone));
for (auto &order : data.impOrder)
order.fill(-1);
data.coldWarStart = -ColdWarTurns - 1;
data.toldAge = -1;
data.toldModels = 3;
data.toldAlive = 0;
data.toldContact = 0;
data.toldOwnCredibility = InitialCredibility;
for (int i = 0; i < nPl; ++i) {
if (g.Difficulty[i] > 0)
data.toldAlive += 1 << i;
}
data.peaceEvaHappened = 0;
for (auto &wonder : data.toldWonders) {
wonder.CityID = -1;
wonder.EffectiveOwner = -1;
}
data.toldTech.fill(static_cast<std::int8_t>(tsNA));
}
} // namespace
void MainScreen::endNego()
{
if (negoDlg().isVisible())
negoDlg().close();
// TODO: the end-of-turn button and panel repaint need the main window (not ported).
clientMode = -1;
m_idle = false;
}
void MainScreen::client(int command, int newPlayer, void *data)
{
TNewGameData &g = ClientTools::g;
const auto intData = [data] { return *static_cast<int *>(data); };
const auto isLocalSession = [] { return !ClientTools::isMultiPlayerGame(); };
if (command == cTurn || command == cResume || command == cContinue || command == cMovieTurn ||
command == scContact || (command >= scDipStart && command <= scDipBreak)) {
supervising = g.Difficulty[newPlayer] == 0;
// TODO: ArrangeMidPanel() needs the main window layout (not ported).
}
switch (command) {
case cDebugMessage:
logDlg().add(newPlayer, g.RO[0]->Turn, QString::fromLocal8Bit(static_cast<const char *>(data)));
return;
case cShowNego: {
const QString text = negoOfferText(*static_cast<TShowNegoData *>(data));
if (!text.isEmpty())
logDlg().add(newPlayer, g.RO[0]->Turn, text);
return;
}
case cInitModule: {
auto *initData = static_cast<TInitModuleData *>(data);
ClientTools::server = initData->Server;
initModule();
initData->DataSize = sizeof(PersistentData);
initData->Flags = aiThreaded;
return;
}
case cReleaseModule:
doneModule();
return;
case cHelpOnly:
case cStartHelp:
case cStartCredits: {
age = 0;
if (command == cHelpOnly)
MainTexture->setAge(-1);
Tribes::init();
const QRect screen = Dpi::Screen::primaryMonitor().boundsRect();
helpDlg().userLeft = screen.left() + (screen.width() - helpDlg().width()) / 2;
helpDlg().userTop = screen.top() + (screen.height() - helpDlg().height()) / 2;
helpDlg().difficulty = 0;
helpDlg().showNewContent(WindowMode::Modal, Help::LinkCategory::Misc,
static_cast<int>(command == cStartCredits ? Help::MiscLinkIndex::Credits
: Help::MiscLinkIndex::Main));
Tribes::done();
return;
}
case cNewGame:
case cLoadGame:
case cMovie:
case cNewMap:
// generateNames follows the "Names" menu item (mNames), which isn't ported: keep the current setting.
m_gameOK = true;
g = *static_cast<TNewGameData *>(data);
ClientTools::me = -1;
m_pLogo = -1;
clientMode = -1;
m_idle = false;
m_jump.fill(0);
if (m_startRunning)
m_jump[0] = 999999;
gameMode = command;
grExt.resetPixUsed();
// TODO: MainMap/NoMap.Reset and SetMapOptions need the main map (not ported).
Tribes::init();
getTribeList();
for (int p1 = 0; p1 < nPl; ++p1) {
if (g.RO[p1] && g.RO[p1]->Data)
initPersistentData(*static_cast<PersistentData *>(g.RO[p1]->Data));
}
arrangeDialogs();
age = 0;
m_movieSpeed = 1;
logDlg().setSlotItemVisible(true);
logDlg().host = this;
if (m_helpDlg)
m_helpDlg->clearHistory();
if (m_cityDlg)
m_cityDlg->reset();
// TODO: MiniMap sizing and the area buttons' visibility need the main window (not ported).
for (int i = 0; i < nPl; ++i) {
Tribes::tribe[static_cast<std::size_t>(i)].reset();
tribeOriginal[static_cast<std::size_t>(i)] = false;
}
toldSlavery = -1;
m_closable = false;
m_firstMovieTurn = true;
return;
case cGetReady:
case cReplay:
if (newPlayer == 0) {
int missing = 0;
for (int p1 = 0; p1 < nPl; ++p1) {
if (g.Difficulty[p1] > 0 && !Tribes::tribe[static_cast<std::size_t>(p1)])
++missing;
}
if (missing > static_cast<int>(unusedTribeFiles.size())) {
m_gameOK = false;
simpleMessage(phrases.lookup(QStringLiteral("TOOFEWTRIBES")));
} else {
const auto setTribe = [&](int trix, const QString &fileName) {
if (gameMode == cLoadGame) {
createTribe(trix, fileName, false);
} else {
TribeInfo info;
info.trix = trix;
info.fileName = fileName;
QByteArray packed = info.pack();
ClientTools::server(commandWithData(cSetTribe, info.commandDataSize()), 0, 0, packed.data());
}
};
for (int p1 = 0; p1 < nPl; ++p1) { // let player select own tribes
if (!(g.Difficulty[p1] > 0 && !Tribes::tribe[static_cast<std::size_t>(p1)] && g.RO[p1]))
continue;
tribeNames.clear();
for (const UnusedTribe &unused : unusedTribeFiles) {
QString name;
QColor color;
Tribes::getTribeInfo(unused.fileName, name, color);
tribeNames.push_back({name, color});
}
Q_ASSERT(!tribeNames.empty());
modalSelectDlg().showNewContent(WindowMode::Modal, Select::ListKind::Tribe);
QCoreApplication::processEvents();
const int chosen = modalSelectDlg().result;
const QString fileName = unusedTribeFiles[static_cast<std::size_t>(chosen)].fileName;
unusedTribeFiles.erase(unusedTribeFiles.begin() + chosen);
setTribe(p1, fileName);
}
for (int p1 = 0; p1 < nPl; ++p1) { // autoselect enemy tribes
if (!(g.Difficulty[p1] > 0 && !Tribes::tribe[static_cast<std::size_t>(p1)] && !g.RO[p1]))
continue;
const int chosen = chooseUnusedTribe();
const QString fileName = unusedTribeFiles[static_cast<std::size_t>(chosen)].fileName;
unusedTribeFiles.erase(unusedTribeFiles.begin() + chosen);
setTribe(p1, fileName);
}
}
if (!generateNames) {
for (int p1 = 0; p1 < nPl; ++p1) {
if (Tribes::tribe[static_cast<std::size_t>(p1)])
Tribes::tribe[static_cast<std::size_t>(p1)]->numberName = p1;
}
}
}
return;
case cBreakGame:
// TODO: SaveSettings() needs the settings store (not ported).
if (m_cityDlg)
m_cityDlg->closeAction = CityScreen::CityCloseAction::None;
applyToVisibleForms(FormAction::Close);
if (logDlg().isVisible())
logDlg().close();
logDlg().clear();
m_startRunning = !m_idle && m_jump[0] > 0; // AI called Reload
ClientTools::me = -1;
m_idle = false;
clientMode = -1;
// TODO: hiding the unit/terrain/EOT/movie buttons and the scrollbar reset need the main window.
for (auto &tribe : Tribes::tribe)
tribe.reset();
Tribes::done();
m_closable = true;
close();
return;
case cShowTurnChange:
if (intData() >= 0)
m_pLogo = intData();
// TODO: repainting the AI logo needs the main window (not ported).
return;
case cShowCancelTreaty:
if (isLocalSession()) {
const int other = intData();
QString key;
switch (g.RO[newPlayer]->Treaty[other]) {
case trPeace: key = QStringLiteral("FRCANCELBYREJECT_PEACE"); break;
case trFriendlyContact: key = QStringLiteral("FRCANCELBYREJECT_FRIENDLY"); break;
case trAlliance: key = QStringLiteral("FRCANCELBYREJECT_ALLIANCE"); break;
default: break;
}
MessgEx::tribeMessage(other, Tribes::tribe[static_cast<std::size_t>(other)]->tPhrase(key),
QStringLiteral("CANCELTREATY"));
}
return;
case cShowCancelTreatyByAlliance:
if (m_idle && newPlayer == ClientTools::me) {
MessgEx::tribeMessage(intData(),
Tribes::tribe[static_cast<std::size_t>(intData())]->tPhrase(
QStringLiteral("FRENEMYALLIANCE")),
QStringLiteral("CANCELTREATY"));
}
return;
case cShowSupportAllianceAgainst:
if (isLocalSession() && m_jump[0] == 0) {
const int ally = intData() & 0xF;
const int enemy = intData() >> 4;
MessgEx::tribeMessage(ally,
Tribes::tribe[static_cast<std::size_t>(ally)]->tPhrase(QStringLiteral("FRMYALLIANCE1")) +
QLatin1Char(' ') +
Tribes::tribe[static_cast<std::size_t>(enemy)]->tPhrase(
QStringLiteral("FRMYALLIANCE2")),
QStringLiteral("CANCELTREATY"));
}
return;
case cShowPeaceViolation:
if (isLocalSession() && m_jump[0] == 0) {
MessgEx::tribeMessage(
intData(),
Tribes::tribe[static_cast<std::size_t>(intData())]->tPhrase(QStringLiteral("EVIOLATION")).arg(
turnToString(ClientTools::myRO->Turn + PeaceEvaTurns - 1)),
QStringLiteral("MSG_WITHDRAW"));
}
return;
case cShowEndContact:
endNego();
return;
case cShowMissionResult: {
const auto info = *static_cast<std::uint32_t *>(data);
if (info == 0) {
MessgEx::soundMessageEx(phrases.lookup(QStringLiteral("NOFOREIGNINFO")), QString());
} else {
QString s = phrases.lookup(QStringLiteral("FOREIGNINFO"));
for (int p1 = 0; p1 < nPl; ++p1) {
if ((3u << (p1 * 2)) & info)
s += QLatin1Char('\\') + Tribes::tribe[static_cast<std::size_t>(p1)]->tPhrase(QStringLiteral("SHORTNAME"));
}
MessgEx::soundMessageEx(s, QString());
}
return;
}
case cShowShipChange:
if (isLocalSession() && m_jump[0] == 0)
showEnemyShipChange(*static_cast<TShowShipChange *>(data));
return;
case cShowGreatLibTech:
if (isLocalSession() && m_jump[0] == 0) {
MessgEx::MessgExDlg &dlg = messgExDlg();
dlg.messageText = formatPhrase(QStringLiteral("GRLIB_GENERAL"),
{ phrases.lookup(QStringLiteral("ADVANCES"), intData()) });
dlg.openSound = QStringLiteral("NEWADVANCE_GRLIB");
dlg.kind = MessageKind::Ok;
dlg.iconKind = MessgEx::MessageIconKind::Imp;
dlg.iconIndex = woGrLibrary;
dlg.showModal();
}
return;
default:
break;
}
if (command >= cClientEx) {
switch (command & ~static_cast<int>(CommandDataElementCountMask)) {
case cSetTribe: {
const TribeInfo info = unpackTribeInfo(data);
const auto it = std::find_if(unusedTribeFiles.begin(), unusedTribeFiles.end(),
[&](const UnusedTribe &unused) { return unused.fileName == info.fileName; });
if (it != unusedTribeFiles.end())
unusedTribeFiles.erase(it);
createTribe(info.trix, info.fileName, true);
return;
}
case cSetNewModelPicture:
case cSetModelPicture: {
const Tribes::ModelPictureInfo info = unpackModelPictureInfo(data);
if (tribeOriginal[static_cast<std::size_t>(info.trix)]) {
Tribes::tribe[static_cast<std::size_t>(info.trix)]->setModelPicture(
info, (command & ~static_cast<int>(CommandDataElementCountMask)) == cSetNewModelPicture);
}
return;
}
case cSetSlaveIndex:
Tribes::tribe[static_cast<std::size_t>(intData() >> 16)]->mixSlaves = intData() & 0xFFFF;
return;
case cSetCityName: {
const CityNameInfo info = unpackCityNameInfo(data);
if (tribeOriginal[static_cast<std::size_t>(info.id >> 12)])
Tribes::tribe[static_cast<std::size_t>(info.id >> 12)]->setCityName(info.id & 0xFFF, info.newName);
return;
}
case cSetModelName: {
const ModelNameInfo info = unpackModelNameInfo(data);
if (tribeOriginal[static_cast<std::size_t>(newPlayer)])
Tribes::tribe[static_cast<std::size_t>(newPlayer)]->modelNameAt(info.mix) = info.newName;
return;
}
default:
break;
}
}
}
} // namespace Term
} // namespace Cevo