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

554 lines
19 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 "Term.MainScreen.h"
#include "Cevo/Database.h"
#include "ClientTools.h"
#include "Global.h"
#include "Tribes.h"
#include <QApplication>
#include <QDir>
#include <algorithm>
#include <cstdlib>
namespace Cevo {
namespace Term {
MainScreen::MainScreen(QWidget *parent) : DrawDlg(parent)
{
IsoEngine::init([](int emix) { return initEnemyModel(emix); });
mainScreenZoomToCity = [this](int loc, bool nextUnitOnClose, int showEvent) {
Q_UNUSED(nextUnitOnClose);
Q_UNUSED(showEvent);
// TODO: needs the real main map (not ported yet) to actually
// scroll/focus the view - just opens the city dialog for now.
cityDlg().showNewContent(WindowMode::Persistent, loc, 0);
return true;
};
mainScreenCityClosed = [](int, bool, bool) {};
mainScreenUpdateViews = [this](bool updateCityScreen) { updateViews(updateCityScreen); };
mainScreenRepaintAll = [this] { repaintAll(); };
mainScreenDipCall = [this](int command) { return dipCall(command); };
mainScreenContactRefused = [this](int p, const QString &item) { return contactRefused(p, item); };
modalSelectDlgShowCityProject = [this](int cix) {
modalSelectDlg().showNewContentCityProject(WindowMode::Modal, cix);
return modalSelectDlg().result;
};
listDlgRenameCity = [this](int cix) { return listDlg().renameCity(cix); };
mainScreenMessgExDlg = [this] { return &messgExDlg(); };
mainScreenModalSelectDlg = [this] { return &modalSelectDlg(); };
mainScreenNatStatDlg = [this] { return &natStatDlg(); };
mainScreenOfferCall = [this](const TOffer &offer) {
TOffer mutableOffer = offer;
return offerCall(mutableOffer);
};
}
MainScreen::~MainScreen() = default;
Wonders::WondersDlg &MainScreen::wondersDlg()
{
if (!m_wondersDlg)
m_wondersDlg = std::make_unique<Wonders::WondersDlg>();
return *m_wondersDlg;
}
TechTree::TechTreeDlg &MainScreen::techTreeDlg()
{
if (!m_techTreeDlg)
m_techTreeDlg = std::make_unique<TechTree::TechTreeDlg>();
return *m_techTreeDlg;
}
Enhance::EnhanceDlg &MainScreen::enhanceDlg()
{
if (!m_enhanceDlg)
m_enhanceDlg = std::make_unique<Enhance::EnhanceDlg>();
return *m_enhanceDlg;
}
Nego::NegoDlg &MainScreen::negoDlg()
{
if (!m_negoDlg)
m_negoDlg = std::make_unique<Nego::NegoDlg>();
return *m_negoDlg;
}
CityType::CityTypeDlg &MainScreen::cityTypeDlg()
{
if (!m_cityTypeDlg)
m_cityTypeDlg = std::make_unique<CityType::CityTypeDlg>();
return *m_cityTypeDlg;
}
Diagram::DiaDlg &MainScreen::diaDlg()
{
if (!m_diaDlg) {
m_diaDlg = std::make_unique<Diagram::DiaDlg>();
arrangeDialog(m_diaDlg.get());
}
return *m_diaDlg;
}
CityScreen::CityDlg &MainScreen::cityDlg()
{
if (!m_cityDlg) {
m_cityDlg = std::make_unique<CityScreen::CityDlg>();
m_cityDlg->checkAge();
}
return *m_cityDlg;
}
Rates::RatesDlg &MainScreen::ratesDlg()
{
if (!m_ratesDlg)
m_ratesDlg = std::make_unique<Rates::RatesDlg>();
return *m_ratesDlg;
}
Battle::BattleDlg &MainScreen::battleDlg()
{
if (!m_battleDlg)
m_battleDlg = std::make_unique<Battle::BattleDlg>();
return *m_battleDlg;
}
NatStat::NatStatDlg &MainScreen::natStatDlg()
{
if (!m_natStatDlg) {
m_natStatDlg = std::make_unique<NatStat::NatStatDlg>();
arrangeDialog(m_natStatDlg.get());
m_natStatDlg->checkAge();
}
return *m_natStatDlg;
}
UnitStat::UnitStatDlg &MainScreen::unitStatDlg()
{
if (!m_unitStatDlg) {
m_unitStatDlg = std::make_unique<UnitStat::UnitStatDlg>();
arrangeDialog(m_unitStatDlg.get());
m_unitStatDlg->checkAge();
}
return *m_unitStatDlg;
}
Draft::DraftDlg &MainScreen::draftDlg()
{
if (!m_draftDlg)
m_draftDlg = std::make_unique<Draft::DraftDlg>();
return *m_draftDlg;
}
Select::ModalSelectDlg &MainScreen::modalSelectDlg()
{
if (!m_modalSelectDlg)
m_modalSelectDlg = std::make_unique<Select::ModalSelectDlg>();
return *m_modalSelectDlg;
}
Select::ListDlg &MainScreen::listDlg()
{
if (!m_listDlg) {
m_listDlg = std::make_unique<Select::ListDlg>();
arrangeDialog(m_listDlg.get());
}
return *m_listDlg;
}
MessgEx::MessgExDlg &MainScreen::messgExDlg()
{
if (!m_messgExDlg)
m_messgExDlg = std::make_unique<MessgEx::MessgExDlg>();
return *m_messgExDlg;
}
Help::HelpDlg &MainScreen::helpDlg()
{
if (!m_helpDlg) {
m_helpDlg = std::make_unique<Help::HelpDlg>();
arrangeDialog(m_helpDlg.get());
// TODO: Help::HelpDlg has no difficulty field in this port yet
// (StringTables-dependent content was simplified away, see
// Help.pas's own repo-memory entry).
}
return *m_helpDlg;
}
Cevo::LogDlg &MainScreen::logDlg()
{
if (!m_logDlg)
m_logDlg = std::make_unique<Cevo::LogDlg>();
return *m_logDlg;
}
void MainScreen::arrangeDialog(BufferedDrawDlg *form)
{
if (!form)
return;
const Dpi::Monitor monitor = Dpi::Screen::primaryMonitor();
if (form == m_listDlg.get()) {
m_listDlg->userLeft = monitor.left() + 8;
m_listDlg->userTop = monitor.top() + TopBarHeight + 8;
}
if (form == m_helpDlg.get()) {
m_helpDlg->userLeft = monitor.left() + monitor.width() - m_helpDlg->width() - 8;
m_helpDlg->userTop = monitor.top() + TopBarHeight + 8;
}
if (form == m_unitStatDlg.get()) {
m_unitStatDlg->userLeft = monitor.left() + 397;
m_unitStatDlg->userTop = monitor.top() + TopBarHeight + 64;
}
if (form == m_diaDlg.get()) {
m_diaDlg->userLeft = monitor.left() + (monitor.width() - m_diaDlg->width()) / 2;
m_diaDlg->userTop = monitor.top() + (monitor.height() - m_diaDlg->height()) / 2;
}
if (form == m_natStatDlg.get()) {
m_natStatDlg->userLeft = monitor.left() + monitor.width() - m_natStatDlg->width() - 8;
m_natStatDlg->userTop = monitor.top() + monitor.height() - PanelHeight - m_natStatDlg->height() - 8;
if (m_natStatDlg->userTop < 8)
m_natStatDlg->userTop = 8;
}
}
void MainScreen::arrangeDialogs()
{
arrangeDialog(m_listDlg.get());
arrangeDialog(m_helpDlg.get());
arrangeDialog(m_unitStatDlg.get());
arrangeDialog(m_diaDlg.get());
arrangeDialog(m_natStatDlg.get());
}
namespace {
// Original: `if G.RO[DipMem[Me].pContact] <> nil then ApplyToVisibleForms
// (faClose) else begin if CityDlg.Visible ... end;` - the ApplyToVisibleForms
// branch is multiplayer/hotseat-only (closes every dialog so the next
// player's turn starts clean) and isn't reachable without the full
// GRO[]/hotseat machinery; simplified to always take the single-player
// "close CityDlg/UnitStatDlg if open" path, disclosed.
void closeDialogsForNextPlayer(MainScreen &mainScreen)
{
if (mainScreen.cityDlg().isVisible())
mainScreen.cityDlg().close();
if (mainScreen.unitStatDlg().isVisible())
mainScreen.unitStatDlg().close();
}
} // namespace
bool chooseResearch()
{
MainScreen &screen = *mainScreen;
Select::ModalSelectDlg &select = screen.modalSelectDlg();
const int me = ClientTools::me;
const TPlayerContext &ro = *ClientTools::myRO;
if (myData->farTech != adNone && ro.Tech[myData->farTech] >= tsApplicable)
myData->farTech = adNone;
int chosenResearch;
do {
// research complete -- select new
do {
select.showNewContent(WindowMode::Modal, Select::ListKind::Advance);
if (select.result < 0)
return false;
chosenResearch = select.result;
if (chosenResearch == adMilitary) {
screen.draftDlg().showNewContent(WindowMode::Modal);
if (screen.draftDlg().modalResult() != Dpi::ModalResult::Ok)
Tribes::tribe[static_cast<std::size_t>(me)]->modelPictureAt(ro.nModel).hGr = nullptr;
}
} while (chosenResearch == adMilitary && screen.draftDlg().modalResult() != Dpi::ModalResult::Ok);
if (chosenResearch == adMilitary) {
initMyModel(ro.nModel, true);
} else if (chosenResearch == adFar) {
select.showNewContent(WindowMode::Modal, Select::ListKind::FarAdvance);
if (select.result >= 0) {
if (select.result == adNone ||
ClientTools::server(sSetResearch - sExecute, me, select.result, nullptr) < rExecuted) {
myData->farTech = select.result;
} else {
chosenResearch = select.result;
// can be researched immediately
myData->farTech = adNone;
}
}
}
} while (chosenResearch == adFar);
if (chosenResearch == adNexus)
myData->farTech = adNexus;
else
ClientTools::server(sSetResearch, me, chosenResearch, nullptr);
screen.listDlg().techChange();
return true;
}
void applyToVisibleForms(FormAction formAction)
{
const QList<QWidget *> widgets = QApplication::topLevelWidgets();
for (QWidget *widget : widgets) {
auto *form = qobject_cast<BufferedDrawDlg *>(widget);
if (!form || !form->isVisible())
continue;
switch (formAction) {
case FormAction::Close:
form->close();
break;
case FormAction::Enable:
form->setEnabled(true);
break;
case FormAction::Disable:
form->setEnabled(false);
break;
case FormAction::Update:
// The original re-runs OnShow (private showEvent here); a repaint is what's reachable.
form->update();
form->repaint();
break;
case FormAction::SmartUpdateContent:
form->smartUpdateContent(false);
break;
}
}
}
int MainScreen::dipCall(int command)
{
const int result = ClientTools::server(command, ClientTools::me, 0, nullptr);
if (result >= rExecuted) {
DipMemEntry &mem = dipMem[static_cast<std::size_t>(ClientTools::me)];
if ((command & 0xFF0F) == scContact) {
mem.pContact = (command >> 4) & 0xF;
negoDlg().initiate();
mem.deliveredPrices.reset();
mem.receivedPrices.reset();
}
mem.sentCommand = command;
mem.formerTreaty = ClientTools::myRO->Treaty[mem.pContact];
if (command == scDipCancelTreaty) {
// TODO: Sound.pas not ported.
} else if (command == scDipAccept) {
for (int i = 0; i < receivedOffer.nDeliver; ++i)
mem.receivedPrices.set(static_cast<std::size_t>(receivedOffer.Price[i] >> 24));
for (int i = 0; i < receivedOffer.nCost; ++i)
mem.deliveredPrices.set(
static_cast<std::size_t>(receivedOffer.Price[receivedOffer.nDeliver + i] >> 24));
// TODO: Sound.pas not ported (NEWTREATY/ACCEPTOFFER distinction).
}
cityDlg().closeAction = CityScreen::CityCloseAction::None;
closeDialogsForNextPlayer(*this);
}
return result;
}
int MainScreen::offerCall(TOffer &offer)
{
const int result = ClientTools::server(scDipOffer, ClientTools::me, 0, &offer);
if (result >= rExecuted) {
DipMemEntry &mem = dipMem[static_cast<std::size_t>(ClientTools::me)];
mem.sentCommand = scDipOffer;
mem.formerTreaty = ClientTools::myRO->Treaty[mem.pContact];
mem.sentOffer = offer;
cityDlg().closeAction = CityScreen::CityCloseAction::None;
closeDialogsForNextPlayer(*this);
}
return result;
}
void MainScreen::updateViews(bool updateCityScreen)
{
ClientTools::sumCities(taxSum, scienceSum);
// TODO: needs PanelPaint/the real main map (not ported yet).
listDlg().ecoChange();
natStatDlg().ecoChange();
if (updateCityScreen)
cityDlg().smartUpdateContent();
}
void MainScreen::setAIName(int, const QString &)
{
// TODO: AILogo[]/GetAppSharePath() (per-player AI logo bitmap) - not
// ported, no consumer reads it yet either (main window/panel not
// ported); no-op for now.
}
bool MainScreen::contactRefused(int p, const QString &item)
{
Q_ASSERT(ClientTools::myRO->Treaty[p] >= trPeace);
const QString s = Tribes::tribe[static_cast<std::size_t>(p)]->tPhrase(item);
if (ClientTools::myRO->Turn < ClientTools::myRO->LastCancelTreaty[p] + CancelTreatyTurns) {
// TODO: Phrases/SimpleMessage dialog not shown - needs Messg.pas's
// simpleMessage() wired through an injection point if ever needed
// from here; the important part (refusing the cancel) still works.
return false;
}
const Dpi::ModalResult result =
MessgEx::simpleQuery(MessageKind::YesNo, s, QStringLiteral("NEGO_REJECTED"));
if (result == Dpi::ModalResult::Ok) {
// TODO: Sound.pas not ported.
int dummy = 0;
ClientTools::server(sCancelTreaty, ClientTools::me, 0, &dummy);
if (ClientTools::myRO->Treaty[p] == trNone)
ClientTools::cityOptimizer_BeginOfTurn();
// TODO: needs the real main map (not ported yet) to repaint.
return true;
}
return false;
}
void MainScreen::getTribeList()
{
unusedTribeFiles.clear();
const QDir dir(localizedFilePath(QStringLiteral("Tribes")));
const QString ext = QLatin1String(CevoTribeExt);
const QStringList files = dir.entryList({QLatin1Char('*') + ext}, QDir::Files, QDir::Name);
for (const QString &file : files) {
const QString baseName = file.left(file.length() - ext.length());
QString name;
QColor color;
if (Tribes::getTribeInfo(baseName, name, color))
unusedTribeFiles.push_back({baseName, color});
}
}
int MainScreen::chooseUnusedTribe()
{
Q_ASSERT(!unusedTribeFiles.empty());
int result = -1;
int bestColorDistance = -1;
int countBest = 0;
for (int j = 0; j < static_cast<int>(unusedTribeFiles.size()); ++j) {
const QColor candidate = unusedTribeFiles[static_cast<std::size_t>(j)].color;
int colorDistance = 250; // consider differences more than this infinite
for (const auto &tribe : Tribes::tribe) {
if (!tribe)
continue;
const int testColorDistance = std::abs(candidate.blue() - tribe->color.blue()) +
std::abs(candidate.green() - tribe->color.green()) * 3 +
std::abs(candidate.red() - tribe->color.red()) * 2;
colorDistance = std::min(colorDistance, testColorDistance);
}
if (colorDistance > bestColorDistance) {
countBest = 0;
bestColorDistance = colorDistance;
}
if (colorDistance == bestColorDistance) {
++countBest;
if (Database::delphiRandom(countBest) == 0)
result = j;
}
}
return result;
}
void MainScreen::showEnemyShipChange(const TShowShipChange &change)
{
MessgEx::MessgExDlg &dlg = messgExDlg();
const auto &owner1 = *Tribes::tribe[static_cast<std::size_t>(change.Ship1Owner)];
const auto &owner2 = *Tribes::tribe[static_cast<std::size_t>(change.Ship2Owner)];
switch (change.Reason) {
case scrProduction:
dlg.openSound = QStringLiteral("SHIP_BUILT");
dlg.messageText = owner1.tPhrase(QStringLiteral("SHIPBUILT"));
dlg.iconKind = MessgEx::MessageIconKind::Ship;
dlg.iconIndex = change.Ship1Owner;
break;
case scrDestruction:
dlg.openSound = QStringLiteral("SHIP_DESTROYED");
dlg.messageText = owner1.tPhrase(QStringLiteral("SHIPDESTROYED"));
dlg.iconKind = MessgEx::MessageIconKind::Imp;
break;
case scrTrade: {
dlg.openSound = QStringLiteral("SHIP_TRADED");
bool ship1Plus = false;
bool ship2Plus = false;
for (int i = 0; i < nShipPart; ++i) {
ship1Plus = ship1Plus || change.Ship1Change[i] > 0;
ship2Plus = ship2Plus || change.Ship2Change[i] > 0;
}
if (ship1Plus && ship2Plus) {
dlg.messageText = owner1.tPhrase(QStringLiteral("SHIPBITRADE1")) + QLatin1Char(' ') +
owner2.tPhrase(QStringLiteral("SHIPBITRADE2"));
} else if (ship1Plus) {
dlg.messageText = owner1.tPhrase(QStringLiteral("SHIPUNITRADE1")) + QLatin1Char(' ') +
owner2.tPhrase(QStringLiteral("SHIPUNITRADE2"));
} else {
dlg.messageText = owner2.tPhrase(QStringLiteral("SHIPUNITRADE1")) + QLatin1Char(' ') +
owner1.tPhrase(QStringLiteral("SHIPUNITRADE2"));
}
dlg.iconKind = MessgEx::MessageIconKind::Imp;
break;
}
case scrCapture:
dlg.openSound = QStringLiteral("SHIP_CAPTURED");
dlg.messageText = owner2.tPhrase(QStringLiteral("SHIPCAPTURE1")) + QLatin1Char(' ') +
owner1.tPhrase(QStringLiteral("SHIPCAPTURE2"));
dlg.iconKind = MessgEx::MessageIconKind::Ship;
dlg.iconIndex = change.Ship2Owner;
break;
}
if (dlg.iconKind == MessgEx::MessageIconKind::Imp) {
int mostCost = 0;
for (int i = 0; i < nShipPart; ++i) {
const int testCost = std::abs(change.Ship1Change[i]) * Imp[imShipComp + i].Cost;
if (testCost > mostCost) {
mostCost = testCost;
dlg.iconIndex = imShipComp + i;
}
}
}
dlg.kind = MessageKind::Ok;
dlg.showModal();
}
void MainScreen::rememberPeaceViolation()
{
myData->peaceEvaHappened = 0;
for (int uix = 0; uix < ClientTools::myRO->nUn; ++uix) {
const TUn &un = ClientTools::myUn[uix];
if (un.Loc >= 0) {
const int p1 = (*ClientTools::myRO->Territory)[un.Loc];
if (p1 != ClientTools::me && p1 >= 0 &&
ClientTools::myRO->Turn == ClientTools::myRO->EvaStart[p1] + (PeaceEvaTurns - 1))
myData->peaceEvaHappened |= (1 << p1);
}
}
}
} // namespace Term
} // namespace Cevo