diff --git a/CMakeLists.txt b/CMakeLists.txt index cec356f..4c014ed 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -153,8 +153,11 @@ set(PROJECT_SOURCES game/localplayer/Term.h game/localplayer/Term.MainScreen.cpp game/localplayer/Term.MainScreen.Client.cpp + game/localplayer/Term.MainScreen.Input.cpp game/localplayer/Term.MainScreen.Move.cpp + game/localplayer/Term.MainScreen.Menus.cpp game/localplayer/Term.MainScreen.Panel.cpp + game/localplayer/Term.MainScreen.Show.cpp game/localplayer/Term.MainScreen.Turn.cpp game/localplayer/Term.MainScreen.Window.cpp game/localplayer/Term.MainScreen.h diff --git a/game/GameServer.Server.cpp b/game/GameServer.Server.cpp index 64a9b4f..ce15868 100644 --- a/game/GameServer.Server.cpp +++ b/game/GameServer.Server.cpp @@ -98,8 +98,8 @@ int CEVO_ABI_CALL server(int command, int player, int subject, void *data) command == sGetEnemyCityAreaInfo || command == sGetCityReportNew || (command & 0xFF0F) == sGetChart || (command & 0xFF0F) == sSetAttitude) && // commands always allowed !(player == pTurn && command < 0x1000) && // info request always allowed for pTurn - !((pDipActive < 0 && player != pTurn) || (pDipActive >= 0 && player != pDipActive) || - (pDipActive >= 0 && (command & sctMask) != sctEndClient))) { // no nego command + ((pDipActive < 0 && player != pTurn) || (pDipActive >= 0 && player != pDipActive) || + (pDipActive >= 0 && (command & sctMask) != sctEndClient))) { // no nego command putMessage((1 << 16) + 1, QStringLiteral("No Turn: %1 calls %2").arg(player).arg(command >> 4, 0, 16)); return eNoTurn; } diff --git a/game/Messg.cpp b/game/Messg.cpp index 64b3b99..b287841 100644 --- a/game/Messg.cpp +++ b/game/Messg.cpp @@ -41,6 +41,7 @@ namespace Cevo { MessgDlg::MessgDlg(QWidget *parent) : BaseMessgDlg(parent), ui(new Ui::MessgDlg) { ui->setupUi(this); + initButtons(); ui->button1->onClick = [this] { setModalResult(Dpi::ModalResult::Ok); close(); diff --git a/game/localplayer/CityScreen.cpp b/game/localplayer/CityScreen.cpp index c2b1081..bf7a14d 100644 --- a/game/localplayer/CityScreen.cpp +++ b/game/localplayer/CityScreen.cpp @@ -171,6 +171,7 @@ void play(const QString &item) CityDlg::CityDlg(QWidget *parent) : BufferedDrawDlg(parent), ui(new Ui::CityDlg) { ui->setupUi(this); + initButtons(); redTex.image(); // ensure Texture's lazily-constructed image exists barTex.image(); noMap = std::make_unique(); diff --git a/game/localplayer/MessgEx.cpp b/game/localplayer/MessgEx.cpp index 9794f96..8c26403 100644 --- a/game/localplayer/MessgEx.cpp +++ b/game/localplayer/MessgEx.cpp @@ -35,6 +35,7 @@ #include "Cevo/Protocol.h" #include "ClientTools.h" #include "Diagram.h" +#include "Global.h" #include "Term.h" #include "Tribes.h" #include "UnitStat.h" @@ -61,6 +62,7 @@ MessgExDlg *instance = nullptr; MessgExDlg::MessgExDlg(QWidget *parent) : BaseMessgDlg(parent), ui(new Ui::MessgExDlg) { ui->setupUi(this); + initButtons(); iconKind = MessageIconKind::None; centerTo = 0; openSound.clear(); @@ -132,7 +134,14 @@ void MessgExDlg::keyPressEvent(QKeyEvent *event) void MessgExDlg::showEvent(QShowEvent *event) { BaseMessgDlg::showEvent(event); - setWindowTitle(tr("Message")); + prepareLayout(); +} + +// Sizes and arranges the dialog for its content; also called before show() because some window systems +// ignore geometry changes made once the window is mapped. +void MessgExDlg::prepareLayout() +{ + setWindowTitle(phrases.lookup(QStringLiteral("TITLE_MESSAGE"))); if (iconKind == MessageIconKind::EnemyArmy) Term::initAllEnemyModels(); @@ -155,26 +164,24 @@ void MessgExDlg::showEvent(QShowEvent *event) } ui->removeBtn->move(width() - 38, ui->removeBtn->y()); - // TODO: needs Phrases[] (StringTables.pas, not ported yet) - plain - // English literals until localization is ported. switch (kind) { case MessageKind::YesNo: case MessageKind::YesNoCancel: - ui->button1->setCaption(tr("Yes")); - ui->button2->setCaption(tr("No")); + ui->button1->setCaption(phrases.lookup(QStringLiteral("BTN_YES"))); + ui->button2->setCaption(phrases.lookup(QStringLiteral("BTN_NO"))); break; case MessageKind::OkCancel: case MessageKind::OkCancelRemove: - ui->button1->setCaption(tr("OK")); - ui->button2->setCaption(tr("Cancel")); + ui->button1->setCaption(phrases.lookup(QStringLiteral("BTN_OK"))); + ui->button2->setCaption(phrases.lookup(QStringLiteral("BTN_CANCEL"))); break; default: - ui->button1->setCaption(tr("OK")); - ui->button2->setCaption(tr("Info")); + ui->button1->setCaption(phrases.lookup(QStringLiteral("BTN_OK"))); + ui->button2->setCaption(phrases.lookup(QStringLiteral("BTN_INFO"))); break; } - ui->button3->setCaption(tr("Cancel")); - ui->removeBtn->setToolTip(tr("Delete saved game")); + ui->button3->setCaption(phrases.lookup(QStringLiteral("BTN_CANCEL"))); + ui->removeBtn->setToolTip(phrases.lookup(QStringLiteral("BTN_DELGAME"))); switch (iconKind) { case MessageIconKind::Imp: @@ -248,7 +255,7 @@ void MessgExDlg::showEvent(QShowEvent *event) Dpi::ModalResult MessgExDlg::showModal() { - setWindowTitle(tr("Message")); + prepareLayout(); if (Term::gameMode == cMovie) { movieCancelled = false; show(); @@ -514,49 +521,60 @@ void setInstance(MessgExDlg *dlg) instance = dlg; } +namespace { +MessgExDlg *current() +{ + return instance ? instance : Term::mainScreenMessgExDlg(); +} +} // namespace + void soundMessageEx(const QString &simpleText, const QString &soundItem) { - if (!instance) + MessgExDlg *dlg = current(); + if (!dlg) return; - instance->messageText = simpleText; - instance->openSound = soundItem; - instance->kind = MessageKind::Ok; - instance->showModal(); + dlg->messageText = simpleText; + dlg->openSound = soundItem; + dlg->kind = MessageKind::Ok; + dlg->showModal(); } void tribeMessage(int p, const QString &simpleText, const QString &soundItem) { - if (!instance) + MessgExDlg *dlg = current(); + if (!dlg) return; - instance->openSound = soundItem; - instance->messageText = simpleText; - instance->kind = MessageKind::Ok; - instance->iconKind = MessageIconKind::Tribe; - instance->iconIndex = p; - instance->showModal(); + dlg->openSound = soundItem; + dlg->messageText = simpleText; + dlg->kind = MessageKind::Ok; + dlg->iconKind = MessageIconKind::Tribe; + dlg->iconIndex = p; + dlg->showModal(); } Dpi::ModalResult simpleQuery(MessageKind queryKind, const QString &simpleText, const QString &soundItem) { - if (!instance) + MessgExDlg *dlg = current(); + if (!dlg) return Dpi::ModalResult::None; - instance->messageText = simpleText; - instance->openSound = soundItem; - instance->kind = queryKind; - return instance->showModal(); + dlg->messageText = simpleText; + dlg->openSound = soundItem; + dlg->kind = queryKind; + return dlg->showModal(); } void contextMessage(const QString &simpleText, const QString &soundItem, Help::LinkCategory contextKind, int contextNo) { - if (!instance) + MessgExDlg *dlg = current(); + if (!dlg) return; - instance->messageText = simpleText; - instance->openSound = soundItem; - instance->kind = MessageKind::OkHelp; - instance->helpKind = contextKind; - instance->helpNo = contextNo; - instance->showModal(); + dlg->messageText = simpleText; + dlg->openSound = soundItem; + dlg->kind = MessageKind::OkHelp; + dlg->helpKind = contextKind; + dlg->helpNo = contextNo; + dlg->showModal(); } } // namespace MessgEx diff --git a/game/localplayer/MessgEx.h b/game/localplayer/MessgEx.h index 8d9d12a..f54f38e 100644 --- a/game/localplayer/MessgEx.h +++ b/game/localplayer/MessgEx.h @@ -88,6 +88,7 @@ protected: void keyPressEvent(QKeyEvent *event) override; private: + void prepareLayout(); void paintBook(Dpi::Canvas &canvas, int x, int y, QColor clPage, QColor clCover); void paintMyArmy(Dpi::Canvas &canvas); void paintEnemyArmy(Dpi::Canvas &canvas); diff --git a/game/localplayer/Term.MainScreen.Client.cpp b/game/localplayer/Term.MainScreen.Client.cpp index 71aa78e..2edebb2 100644 --- a/game/localplayer/Term.MainScreen.Client.cpp +++ b/game/localplayer/Term.MainScreen.Client.cpp @@ -31,16 +31,14 @@ // // 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. +// cMovie/cNewMap, cGetReady/cReplay, cBreakGame, cShowGame, cShowTurnChange, +// cTurn/cResume/cContinue, cMovieTurn/cMovieEndTurn, cEditMap, scContact, +// scDipStart..scDipBreak, the pure message commands (cShowCancelTreaty*, +// cShowSupportAllianceAgainst, cShowPeaceViolation, cShowMissionResult, +// cShowShipChange, cShowGreatLibTech), cShowEndContact and the client +// exclusive commands. Still missing because they need MoveUnit/ShowMove +// (not ported): cShowUnitChanged/CityChanged/AfterMove/AfterAttack/Moving/ +// Capturing/Attacking, cRefreshDebugMap. #include "Term.MainScreen.h" @@ -50,6 +48,7 @@ #include "Cevo/CmdList.h" #include "Global.h" #include "Messg.h" +#include "Sound.h" #include "Tribes.h" #include @@ -137,7 +136,6 @@ void initPersistentData(PersistentData &data) void MainScreen::client(int command, int newPlayer, void *data) { - qWarning("TMPDEBUG client(%x, %d)", command, newPlayer); TNewGameData &g = ClientTools::g; const auto intData = [data] { return *static_cast(data); }; const auto isLocalSession = [] { return !ClientTools::isMultiPlayerGame(); }; @@ -302,7 +300,8 @@ void MainScreen::client(int command, int newPlayer, void *data) return; case cBreakGame: - // TODO: SaveSettings() needs the settings store (not ported). + saveSettings(); + saveConfig(); if (m_cityDlg) m_cityDlg->closeAction = CityScreen::CityCloseAction::None; applyToVisibleForms(FormAction::Close); @@ -339,7 +338,15 @@ void MainScreen::client(int command, int newPlayer, void *data) canvas.brush().setStyle(Qt::NoBrush); canvas.end(); } - show(); + if (fullScreen) { + m_restoredBounds = termBounds; + m_formFullScreen = true; + showFullScreen(); + } else { + m_formFullScreen = false; + setGeometry(termBounds); + show(); + } updateNow(); resizeControls(); m_repaintOnResize = true; @@ -449,7 +456,6 @@ void MainScreen::client(int command, int newPlayer, void *data) m_eot->setVisible(false); helpDlg().difficulty = 0; m_brushType = fGrass; - // TODO: UpdateInterface (mFillMap.Enabled) belongs to the menus, which are not ported. m_brushLoc = -1; m_edited = false; IsoEngine::unFocus = -1; @@ -502,13 +508,24 @@ void MainScreen::client(int command, int newPlayer, void *data) receivedOffer = *static_cast(data); initAllEnemyModels(); } - // TODO: the sounds played for scDipStart/scDipCancelTreaty/scDipAccept (sound is not ported). + if (command == scDipStart) + Sound::play(QStringLiteral("CONTACT_%1").arg(ClientTools::myRO->Attitude[dipMem[static_cast(newPlayer)].pContact])); + else if (command == scDipCancelTreaty) + Sound::play(QStringLiteral("CANCELTREATY")); if (command == scDipAccept) { // remember delivered and received prices DipMemEntry &mem = dipMem[static_cast(ClientTools::me)]; for (int i = 0; i < mem.sentOffer.nDeliver; ++i) mem.deliveredPrices.set(static_cast(mem.sentOffer.Price[i] >> 24)); for (int i = 0; i < mem.sentOffer.nCost; ++i) mem.receivedPrices.set(static_cast(mem.sentOffer.Price[mem.sentOffer.nDeliver + i] >> 24)); + bool isTreatyDeal = false; + for (int i = 0; i < receivedOffer.nDeliver + receivedOffer.nCost; ++i) { + if ((mem.sentOffer.Price[i] & opMask) == opTreaty) { + isTreatyDeal = true; + break; + } + } + Sound::play(isTreatyDeal ? QStringLiteral("NEWTREATY") : QStringLiteral("ACCEPTOFFER")); } negoDlg().start(); m_idle = true; @@ -561,6 +578,17 @@ void MainScreen::client(int command, int newPlayer, void *data) } return; + case cShowUnitChanged: + case cShowCityChanged: + case cShowAfterMove: + case cShowAfterAttack: + case cShowMoving: + case cShowCapturing: + case cShowAttacking: + case cRefreshDebugMap: + clientShow(command, newPlayer, data); + return; + case cShowEndContact: endNego(); return; diff --git a/game/localplayer/Term.MainScreen.Input.cpp b/game/localplayer/Term.MainScreen.Input.cpp new file mode 100644 index 0000000..d2f83e1 --- /dev/null +++ b/game/localplayer/Term.MainScreen.Input.cpp @@ -0,0 +1,725 @@ +// TMainScreen's mouse and keyboard handling (Term.pas): MapBoxMouseDown, +// PanelBoxMouse*, FormMouse*, FormKeyDown/FormKeyUp and the buttons. + +#include "Term.MainScreen.h" + +#include "Cevo/CevoScreenTools.h" +#include "Cevo/CevoTexture.h" +#include "Global.h" +#include "KeyBindings.h" +#include "Messg.h" +#include "Sound.h" + +#include +#include +#include +#include + +namespace Cevo { +namespace Term { + +namespace { + +QKeySequence keyOf(const QKeyEvent *event) +{ + return QKeySequence(event->modifiers() | event->key()); +} + +} // namespace + +bool MainScreen::isPanelPixel(int x, int y) const +{ + return y >= TopBarHeight + m_mapHeight || (y >= height() - PanelHeight && (x < m_xMidPanel || x >= m_xRightPanel)); +} + +void MainScreen::mousePressEvent(QMouseEvent *event) +{ + if (!m_idle) + return; + const QPoint pos = event->position().toPoint(); + const int x = pos.x(); + const int y = pos.y(); + if (x < 40 && y < 40) { + if (gameMode != cMovie) + showPopup(PopupKind::Game, mapToGlobal(QPoint(0, TopBarHeight - 1))); + } else if (isPanelPixel(x, y)) { + panelMouseDown(event->button(), event->modifiers(), QPoint(x, y - (height() - PanelHeight))); + } else if (y >= TopBarHeight && x >= m_mapOffset && x < m_mapOffset + m_mapWidth) { + mapMouseDown(event->button(), event->modifiers(), QPoint(x - m_mapOffset, y - TopBarHeight)); + } +} + +void MainScreen::mouseMoveEvent(QMouseEvent *event) +{ + if (!m_idle) + return; + const QPoint pos = event->position().toPoint(); + if (isPanelPixel(pos.x(), pos.y())) + panelMouseMove(event->buttons(), QPoint(pos.x(), pos.y() - (height() - PanelHeight))); + else if (pos.y() >= TopBarHeight && pos.x() >= m_mapOffset && pos.x() < m_mapOffset + m_mapWidth) + mapMouseMove(event->buttons(), event->modifiers(), QPoint(pos.x() - m_mapOffset, pos.y() - TopBarHeight)); +} + +void MainScreen::mouseReleaseEvent(QMouseEvent *) +{ + if (m_idle) + panelMouseUp(); +} + +void MainScreen::panelMouseMove(Qt::MouseButtons buttons, QPoint pos) +{ + const int lx = ClientTools::g.lx; + const int ly = ClientTools::g.ly; + const int xxt = m_mainMap->xxt; + const int yyt = m_mainMap->yyt; + if (!(m_tracking && (buttons & Qt::LeftButton))) { + m_tracking = false; + return; + } + const int x = pos.x(); + const int y = pos.y(); + if (x >= m_xMini + 2 && y >= m_yMini + 2 && x < m_xMini + 2 + 2 * lx && y < m_yMini + 2 + ly) { + const int xCentre = (m_xwMini + (x - m_xMini - 2) / 2 + lx / 2 + m_mapWidth / (xxt * 4)) % lx; + const int yCentre = y - m_yMini - 2; + m_xw = (xCentre - m_mapWidth / (xxt * 4) + lx) % lx; + if (m_ywmax <= 0) { + m_yw = m_ywcenter; + } else { + m_yw = (yCentre - m_mapHeight / (yyt * 2) + 1) & ~1; + if (m_yw < 0) + m_yw = 0; + else if (m_yw > m_ywmax) + m_yw = m_ywmax; + } + // the mini map with the frame around the view being dragged + bitBltBitmap(m_panel, m_xMini + 2, m_yMini + 2, lx * 2, ly, m_miniMap->bitmap, 0, 0); + Dpi::Canvas &canvas = m_panel.canvas(); + if (m_ywmax <= 0) + frame(canvas, x - m_mapWidth / (xxt * 2), m_yMini + 2, x + m_mapWidth / (xxt * 2) - 1, m_yMini + 2 + ly - 1, + MainTexture->colorMark, MainTexture->colorMark); + else + frame(canvas, x - m_mapWidth / (xxt * 2), m_yMini + 2 + m_yw, x + m_mapWidth / (xxt * 2) - 1, + m_yMini + 2 + m_yw + m_mapHeight / yyt - 2, MainTexture->colorMark, MainTexture->colorMark); + canvas.end(); + mainOffscreenPaint(); + invalidateMiniMap(); + updateNow(); + } +} + +void MainScreen::panelMouseUp() +{ + if (m_tracking) { + m_tracking = false; + m_xwMini = m_xw; + m_ywMini = m_yw; + miniMapPaint(); + panelPaint(); + } +} + +void MainScreen::mapMouseMove(Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, QPoint pos) +{ + m_mouseX = pos.x(); + m_mouseY = pos.y(); + if (clientMode == cEditMap && (buttons & Qt::LeftButton) && !m_tracking) { + const int mouseLoc = locationOfScreenPixel(pos.x(), pos.y()); + if (mouseLoc != m_brushLoc) + mapMouseDown(Qt::LeftButton, modifiers, pos); + } +} + +void MainScreen::panelMouseDown(Qt::MouseButton button, Qt::KeyboardModifiers modifiers, QPoint pos) +{ + using ClientTools::me; + using ClientTools::myMap; + using ClientTools::myRO; + using ClientTools::myUn; + const int lx = ClientTools::g.lx; + const int ly = ClientTools::g.ly; + const int x = pos.x(); + const int y = pos.y(); + if (gameMode == cMovie || button != Qt::LeftButton) + return; + const bool shift = modifiers & Qt::ShiftModifier; + + if (x >= m_xMini + 2 && y >= m_yMini + 2 && x < m_xMini + 2 + 2 * lx && y < m_yMini + 2 + ly) { + if (shift) { + const int xMouse = (m_xwMini + (x - (m_xMini + 2) + m_mapWidth / (m_mainMap->xxt * 2) + lx) / 2) % lx; + const int mouseLoc = xMouse + lx * (y - (m_yMini + 2)); + if ((myMap[mouseLoc] & fTerrain) != static_cast(fUNKNOWN)) { + const int p1 = (*myRO->Territory)[mouseLoc]; + if (p1 == me || (p1 >= 0 && myRO->Treaty[p1] >= trNone)) + natStatDlg().showNewContent(WindowMode::Persistent, p1); + } + } else { + if (m_cityDlg && m_cityDlg->isVisible()) + m_cityDlg->close(); + if (m_unitStatDlg && m_unitStatDlg->isVisible()) + m_unitStatDlg->close(); + m_tracking = true; + panelMouseMove(Qt::LeftButton, pos); + } + } else if (clientMode != cEditMap && x >= width() - XPalace && y >= YPalace && x < width() - XPalace + xSizeBig + && y < YPalace + ySizeBig) { + showPopup(PopupKind::Stat, + mapToGlobal(QPoint(width() - XPalace + 6, height() - PanelHeight + YPalace + ySizeBig + 3))); + } else if (x >= m_xTroop + 1 && y >= YTroop + 1 && x < m_xTroop + m_trRow * m_trPitch && y <= YTroop + 55) { + const int i = (x - m_xTroop - 1) / m_trPitch; + const int selected = m_trix[static_cast(i)]; + if (selected < 0) + return; + if (clientMode == cEditMap) { + m_brushType = static_cast(selected); + panelPaint(); + } else if (m_troopLoc >= 0) { + if ((myMap[m_troopLoc] & fOwned) != 0) { + if (shift) { + unitStatDlg().showNewContentOwnModel(WindowMode::Persistent, myUn[selected].mix); + } else if (!supervising && clientMode < scContact && x - m_xTroop - 1 - i * m_trPitch >= 60 - 20 + && y >= YTroop + 35 + && (myUn[selected].Job > jNone + || (myUn[selected].Status & (IsoEngine::usStay | IsoEngine::usRecover | IsoEngine::usGoto)) != 0)) { + // wake up + myUn[selected].Status = (myUn[selected].Status + & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto + - IsoEngine::usEnhance)) + | usWaiting; + if (myUn[selected].Job > jNone) + ClientTools::server(sStartJob + (jNone << 4), me, selected, nullptr); + if (IsoEngine::unFocus < 0 && !(m_cityDlg && m_cityDlg->isVisible())) { + setUnFocus(selected); + setTroopLoc(myUn[selected].Loc); + focusOnLoc(m_troopLoc, flRepaintPanel); + } else { + if (m_cityDlg && m_cityDlg->isVisible() && m_cityDlg->restoreUnFocus < 0) + m_cityDlg->restoreUnFocus = selected; + panelPaint(); + } + } else if (clientMode < scContact) { + if (supervising) { + unitStatDlg().showNewContentOwnUnit(WindowMode::Persistent, selected); + } else if (m_cityDlg && m_cityDlg->isVisible()) { + m_cityDlg->closeAction = CityScreen::CityCloseAction::None; + m_cityDlg->close(); + ClientTools::sumCities(taxSum, scienceSum); + setUnFocus(selected); + } else { + IsoEngine::destinationMarkOn = false; + paintDestination(); + IsoEngine::unFocus = selected; + unStartLoc = m_troopLoc; + m_blinkTime = 0; + IsoEngine::blinkOn = false; + paintLoc(m_troopLoc); + } + if (IsoEngine::unFocus >= 0) { + m_unitInfoBtn->setVisible(true); + m_unitBtn->setVisible(true); + m_turnComplete = false; + m_eot->setButtonIndex(eotGray); + } + checkTerrainBtnVisible(); + panelPaint(); + } + } else if (ClientTools::server(sGetUnits, me, m_troopLoc, &m_trCnt) >= rExecuted) { + if (shift) + unitStatDlg().showNewContentEnemyModel(WindowMode::Persistent, + (*myRO->EnemyUn)[myRO->nEnemyUn + selected].emix); // model info + else + unitStatDlg().showNewContentEnemyUnit(WindowMode::Persistent, myRO->nEnemyUn + selected); // unit info + } + } + } +} + +void MainScreen::mapMouseDown(Qt::MouseButton button, Qt::KeyboardModifiers modifiers, QPoint pos) +{ + using ClientTools::me; + using ClientTools::myMap; + using ClientTools::myModel; + using ClientTools::myRO; + using ClientTools::myUn; + using ClientTools::server; + const int lx = ClientTools::g.lx; + const int ly = ClientTools::g.ly; + const bool shift = modifiers & Qt::ShiftModifier; + const bool ctrl = modifiers & Qt::ControlModifier; + if (gameMode == cMovie) + return; + + if (m_cityDlg && m_cityDlg->isVisible()) + m_cityDlg->close(); + if (m_unitStatDlg && m_unitStatDlg->isVisible()) + m_unitStatDlg->close(); + const int mouseLoc = locationOfScreenPixel(pos.x(), pos.y()); + if (mouseLoc < 0 || mouseLoc >= lx * ly) + return; + + if (button == Qt::LeftButton && !shift) { + bool doCenter = true; + if (clientMode == cEditMap) { + doCenter = false; + TEditTileData editTileData; + editTileData.Loc = mouseLoc; + const std::uint32_t tile = myMap[mouseLoc]; + const std::uint32_t brush = m_brushType; + std::uint32_t newTile; + if (ctrl) { // toggle special resource + const std::uint32_t special = (((tile >> 5) & 3) + 1); + switch (tile & fTerrain) { + case fOcean: newTile = tile; break; + case fGrass: + case fArctic: newTile = (tile & ~static_cast(fSpecial)) | ((special % 2) << 5); break; + default: newTile = (tile & ~static_cast(fSpecial)) | ((special % 3) << 5); break; + } + } else if (brush <= static_cast(fTerrain)) { + newTile = (tile & ~static_cast(fTerrain)) | fSpecial | brush; + } else if ((brush & fDeadLands) != 0) { + if ((tile & (fDeadLands | fModern)) == (brush & (fDeadLands | fModern))) + newTile = tile & ~static_cast(fDeadLands | fModern); + else + newTile = (tile & ~static_cast(fDeadLands | fModern)) | brush; + } else if ((brush & fTerImp) != 0) { + if ((tile & fTerImp) == brush) + newTile = tile & ~static_cast(fTerImp); + else + newTile = (tile & ~static_cast(fTerImp)) | brush; + } else if ((brush & (fPrefStartPos | fStartPos)) != 0) { + if ((tile & (fPrefStartPos | fStartPos)) == (brush & (fPrefStartPos | fStartPos))) + newTile = tile & ~static_cast(fPrefStartPos | fStartPos); + else + newTile = (tile & ~static_cast(fPrefStartPos | fStartPos)) | brush; + } else { + newTile = tile ^ brush; + } + editTileData.NewTile = static_cast(newTile); + server(sEditTile, me, 0, &editTileData); + m_edited = true; + m_brushLoc = mouseLoc; + paintLoc(mouseLoc, 2); + miniMapPaint(); + copyMiniToPanel(); + m_panel.canvas().end(); + invalidateMiniMap(); + } else if ((myMap[mouseLoc] & fCity) != 0) { // city clicked + if ((myMap[mouseLoc] & (fOwned | fSpiedOut)) != 0) { + zoomToCity(mouseLoc); + doCenter = false; + } else { + unitStatDlg().showNewContentEnemyCity(WindowMode::Persistent, mouseLoc); + doCenter = false; + } + } else if ((myMap[mouseLoc] & fUnit) != 0) { // unit clicked + if ((myMap[mouseLoc] & fOwned) != 0) { + doCenter = false; + if (!supervising && clientMode < scContact) { // not in negotiation mode + int uix; + if (IsoEngine::unFocus >= 0 && myUn[IsoEngine::unFocus].Loc == mouseLoc) { // rotate + uix = (IsoEngine::unFocus + 1) % myRO->nUn; + int i = myRO->nUn - 1; + while (i > 0) { + if (myUn[uix].Loc == mouseLoc && myUn[uix].Job == jNone + && (myUn[uix].Status & (IsoEngine::usStay | IsoEngine::usRecover | IsoEngine::usEnhance | usWaiting)) + == usWaiting) + break; + --i; + uix = (uix + 1) % myRO->nUn; + } + if (i == 0) + uix = IsoEngine::unFocus; + } else { + server(sGetDefender, me, mouseLoc, &uix); + } + if (uix != IsoEngine::unFocus) + setUnFocus(uix); + m_turnComplete = false; + m_eot->setButtonIndex(eotGray); + } + setTroopLoc(mouseLoc); + panelPaint(); + } else if ((myMap[mouseLoc] & fSpiedOut) != 0 && !ctrl) { + doCenter = false; + setTroopLoc(mouseLoc); + panelPaint(); + } else { + doCenter = false; + unitStatDlg().showNewContentEnemyLoc(WindowMode::Persistent, mouseLoc); + } + } + if (doCenter) { + centre(mouseLoc); + paintAllMaps(); + } + } else if (clientMode != cEditMap && button == Qt::RightButton && !shift) { + if (supervising) { + m_editLoc = mouseLoc; + server(sGetModels, me, 0, nullptr); + QMenu *createUnit = createUnitMenu(); + int createLoc = mouseLoc; + for (int p1 = 0; p1 < nPl; ++p1) { + if (((1 << p1) & myRO->Alive) == 0) + continue; + QMenu *playerMenu = createUnit->addMenu(Tribes::tribe[static_cast(p1)]->tPhrase(QStringLiteral("SHORTNAME"))); + for (int emix = myRO->nEnemyModel - 1; emix >= 0; --emix) { + const TModelInfo &model = (*myRO->EnemyModel)[emix]; + if (model.Owner == p1 + && server(sCreateUnit - sExecute + (p1 << 4), me, model.mix, &createLoc) >= rExecuted) { + if (!Tribes::tribe[static_cast(p1)]->modelPictureAt(model.mix).hGr) + initEnemyModel(emix); + QAction *action = playerMenu->addAction( + Tribes::tribe[static_cast(p1)]->modelNameAt(model.mix)); + const int mix = model.mix; + connect(action, &QAction::triggered, this, [this, p1, mix] { + int loc = m_editLoc; + if (ClientTools::server(sCreateUnit + (p1 << 4), ClientTools::me, mix, &loc) >= rExecuted) + paintLoc(m_editLoc); + }); + } + } + playerMenu->menuAction()->setVisible(!playerMenu->isEmpty()); + } + showPopup(PopupKind::Edit, mapToGlobal(QPoint(pos.x() + m_mapOffset, pos.y() + TopBarHeight))); + } else if (IsoEngine::unFocus >= 0 && myUn[IsoEngine::unFocus].Loc != mouseLoc) { + TUn &un = myUn[IsoEngine::unFocus]; + const int dx = ((mouseLoc % lx * 2 + ((mouseLoc / lx) & 1)) - (un.Loc % lx * 2 + ((un.Loc / lx) & 1)) + 3 * lx) + % (2 * lx) + - lx; + const int dy = mouseLoc / lx - un.Loc / lx; + TMoveAdviceData moveAdviceData; + if (std::abs(dx) + std::abs(dy) < 3) { + IsoEngine::destinationMarkOn = false; + paintDestination(); + un.Status = (un.Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto - IsoEngine::usEnhance)) + | usWaiting; + moveUnit(dx, dy, muAutoNext); // simple move + } else if (ClientTools::getMoveAdvice(IsoEngine::unFocus, mouseLoc, moveAdviceData) >= rExecuted) { + if ((myMap[mouseLoc] & (fUnit | fOwned)) == static_cast(fUnit)) { + // check for suicide mission before movement + Battle::BattleDlg &battle = battleDlg(); + battle.forecast.pAtt = me; + battle.forecast.mixAtt = un.mix; + battle.forecast.HealthAtt = un.Health; + battle.forecast.ExpAtt = un.Exp; + battle.forecast.FlagsAtt = static_cast(un.Flags); + battle.forecast.Movement = un.Movement; + if (server(sGetBattleForecastEx, me, mouseLoc, &battle.forecast) >= rExecuted + && battle.forecast.EndHealthAtt <= 0) { + battle.uix = IsoEngine::unFocus; + battle.toLoc = mouseLoc; + battle.isSuicideQuery = true; + if (battle.showModal() != Dpi::ModalResult::Ok) + return; + } + } + IsoEngine::destinationMarkOn = false; + paintDestination(); + un.Status = (un.Status & ~(IsoEngine::usStay | IsoEngine::usRecover | IsoEngine::usEnhance)) | usWaiting; + moveToLoc(mouseLoc, false); // goto + } + } + } else if (button == Qt::MiddleButton && IsoEngine::unFocus >= 0 + && (myModel[myUn[IsoEngine::unFocus].mix].Kind == mkSettler + || myModel[myUn[IsoEngine::unFocus].mix].Kind == mkSlaves)) { + IsoEngine::destinationMarkOn = false; + paintDestination(); + myUn[IsoEngine::unFocus].Status = (myUn[IsoEngine::unFocus].Status + & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto)) + | IsoEngine::usEnhance; + const int uix = IsoEngine::unFocus; + if (mouseLoc != myUn[uix].Loc) + moveToLoc(mouseLoc, true); // goto + if (IsoEngine::unFocus == uix && myUn[uix].Loc == mouseLoc) + triggerMenu(MenuCommand::Enhance); + } else if (button == Qt::LeftButton && shift && (myMap[mouseLoc] & fTerrain) != static_cast(fUNKNOWN)) { + helpOnTerrain(mouseLoc, WindowMode::Persistent); + } else if (clientMode <= cContinue && button == Qt::RightButton && shift && IsoEngine::unFocus >= 0 + && (myMap[mouseLoc] & (fUnit | fOwned)) == static_cast(fUnit)) { // battle forecast + TUn &un = myUn[IsoEngine::unFocus]; + Battle::BattleDlg &battle = battleDlg(); + battle.forecast.pAtt = me; + battle.forecast.mixAtt = un.mix; + battle.forecast.HealthAtt = un.Health; + battle.forecast.ExpAtt = un.Exp; + battle.forecast.FlagsAtt = static_cast(un.Flags); + battle.forecast.Movement = un.Movement; + if (server(sGetBattleForecastEx, me, mouseLoc, &battle.forecast) >= rExecuted) { + battle.uix = IsoEngine::unFocus; + battle.toLoc = mouseLoc; + const QPoint global = mapToGlobal(QPoint(pos.x() + m_mapOffset, pos.y() + TopBarHeight)); + const QRect desktop = Dpi::Screen::primaryMonitor().boundsRect(); + int left = global.x() - battle.width() / 2; + left = std::clamp(left, desktop.left(), std::max(desktop.left(), desktop.right() - battle.width())); + int top = global.y() - battle.height() / 2; + top = std::clamp(top, desktop.top(), std::max(desktop.top(), desktop.bottom() - battle.height())); + battle.move(left, top); + battle.isSuicideQuery = false; + battle.show(); + } + } + Q_UNUSED(m_dragStartLoc); +} + +void MainScreen::mapButtonClicked(ButtonC *button) +{ + const int bit = button->property("tag").toInt() >> 8; + mapOptionChecked ^= 1u << bit; + setMapOptions(); + button->setButtonIndex(static_cast((mapOptionChecked >> bit) & 1) + 2); + if (button == m_mapBtn0) { // update mini map only + miniMapPaint(); + panelPaint(); + } else { // update main map + m_mapValid = false; + paintAllMaps(); + } +} + +void MainScreen::mapOptionButtonChanged(ButtonC *button, int option) +{ + if (button->down()) { + mapOptionChecked |= 1u << option; + button->setToolTip(QString()); + } else { + mapOptionChecked &= ~(1u << option); + button->setToolTip(phrases.lookup(QStringLiteral("CONTROLS"), (button->property("tag").toInt() & 0xFF) - 1)); + } + setMapOptions(); + m_mapValid = false; + paintAllMaps(); +} + +void MainScreen::panelButtonClicked(ButtonB *button) +{ + if (IsoEngine::unFocus < 0) + return; + showPopup(button == m_unitBtn ? PopupKind::Unit : PopupKind::Terrain, mapToGlobal(button->pos())); +} + +void MainScreen::wireControls() +{ + m_unitBtn->onClick = [this] { panelButtonClicked(m_unitBtn); }; + m_terrainBtn->onClick = [this] { panelButtonClicked(m_terrainBtn); }; + m_unitInfoBtn->onClick = [this] { + if (IsoEngine::unFocus >= 0) + unitStatDlg().showNewContentOwnModel(WindowMode::Persistent, ClientTools::myUn[IsoEngine::unFocus].mix); + }; + for (ButtonC *button : { m_mapBtn0, m_mapBtn1, m_mapBtn5 }) + button->onClick = [this, button] { mapButtonClicked(button); }; + m_mapBtn4->onDownChanged = [this] { mapOptionButtonChanged(m_mapBtn4, ClientTools::moGreatWall); }; + m_mapBtn6->onDownChanged = [this] { mapOptionButtonChanged(m_mapBtn6, ClientTools::moBareTerrain); }; + for (ButtonB *button : m_movieSpeedBtn) { + button->onClick = [this, button] { + m_movieSpeed = button->property("tag").toInt() >> 8; + checkMovieSpeedBtnState(); + }; + } + m_eot->onClick = [this] { + if (gameMode == cMovie) { + messgExDlg().cancelMovie(); + ClientTools::server(sBreak, ClientTools::me, 0, nullptr); + } else if (clientMode < 0) { + m_skipped = true; + } else if (clientMode >= scContact) { + negoDlg().showNewContent(WindowMode::Persistent); + } else if (m_jump[static_cast(m_pTurn)] > 0) { + m_jump[static_cast(m_pTurn)] = 0; + m_startRunning = false; + } else { + endTurn(); + } + }; +} + +void MainScreen::keyReleaseEvent(QKeyEvent *event) +{ + if (m_keyboardDisabled) + return; + if (m_idle && event->key() == Qt::Key_Menu) // the menu key calls the game menu + showPopup(PopupKind::Game, mapToGlobal(QPoint(0, TopBarHeight - 1))); +} + +void MainScreen::keyPressEvent(QKeyEvent *event) +{ + using namespace KeyBindings; + using ClientTools::myUn; + if (m_keyboardDisabled) + return; + const QKeySequence key = keyOf(event); + + if (bFullScreen->test(key)) + setFullScreen(!fullScreen); + + if (gameMode == cMovie) { + if (bScienceStat->test(key)) + menuClickChecked(PopupKind::Stat, MenuCommand::ScienceStat); + else if (bDiagram->test(key)) + menuClickChecked(PopupKind::Stat, MenuCommand::Diagram); + else if (bWonders->test(key)) + menuClickChecked(PopupKind::Stat, MenuCommand::Wonders); + else if (bShips->test(key)) + menuClickChecked(PopupKind::Stat, MenuCommand::Ships); + return; + } + if (!m_idle) + return; + + // map move + const auto moveMap = [this](int x, int y) { + const int speed = ClientTools::hasSaveOption(optionChecked, ClientTools::soScrollFast) ? 2 : 1; + if (x != 0 || y != 0) + scroll(x * speed, y * speed); + }; + if (bMapMoveLeftDown->test(key)) moveMap(-1, 1); + else if (bMapMoveDown->test(key)) moveMap(0, 2); + else if (bMapMoveRightDown->test(key)) moveMap(1, 1); + else if (bMapMoveLeft->test(key)) moveMap(-2, 0); + else if (bMapMoveRight->test(key)) moveMap(2, 0); + else if (bMapMoveLeftUp->test(key)) moveMap(-1, -1); + else if (bMapMoveUp->test(key)) moveMap(0, -2); + else if (bMapMoveRightUp->test(key)) moveMap(1, -1); + + if (clientMode == cEditMap) { + if (bResign->test(key)) triggerMenu(MenuCommand::Resign); + else if (bRandomMap->test(key)) triggerMenu(MenuCommand::RandomMap); + else if (bFillMap->test(key)) triggerMenu(MenuCommand::FillMap); + else if (bHelp->test(key)) triggerMenu(MenuCommand::Help); + return; + } + + if (bEndTurn->test(key)) endTurn(); + else if (bHelp->test(key)) triggerMenu(MenuCommand::Help); + else if (bUnitStat->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::UnitStat); + else if (bCityStat->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::CityStat); + else if (bScienceStat->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::ScienceStat); + else if (bEUnitStat->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::EUnitStat); + else if (bDiagram->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Diagram); + else if (bWonders->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Wonders); + else if (bShips->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Ships); + else if (bNations->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Nations); + else if (bEmpire->test(key)) menuClickChecked(PopupKind::Stat, MenuCommand::Empire); + else if (bSetDebugMap0->test(key)) setDebugMap(-1); + else if (bSetDebugMap1->test(key)) setDebugMap(1); + else if (bSetDebugMap2->test(key)) setDebugMap(2); + else if (bSetDebugMap3->test(key)) setDebugMap(3); + else if (bSetDebugMap4->test(key)) setDebugMap(4); + else if (bSetDebugMap5->test(key)) setDebugMap(5); + else if (bSetDebugMap6->test(key)) setDebugMap(6); + else if (bSetDebugMap7->test(key)) setDebugMap(7); + else if (bSetDebugMap8->test(key)) setDebugMap(8); + else if (bSetDebugMap9->test(key)) setDebugMap(9); + else if (bJump->test(key)) triggerMenu(MenuCommand::Jump); + else if (bLocCodes->test(key)) triggerMenu(MenuCommand::LocCodes); + else if (bLogDlg->test(key)) { + if (logDlg().isVisible()) + logDlg().close(); + else + logDlg().show(); + } else if (bNames->test(key)) triggerMenu(MenuCommand::Names); + else if (bResign->test(key)) menuClickChecked(PopupKind::Game, MenuCommand::Resign); + else if (bRun->test(key)) triggerMenu(MenuCommand::Run); + else if (bTestMapRepaint->test(key)) { // test map repaint time + QElapsedTimer timer; + timer.start(); + m_mapValid = false; + mainOffscreenPaint(); + simpleMessage(QStringLiteral("Map repaint time: %1 ms").arg(timer.nsecsElapsed() / 1e6, 0, 'f', 3)); + } else if (bSetViewpoint0->test(key)) setViewpoint(0); + else if (bSetViewpoint1->test(key)) setViewpoint(1); + else if (bSetViewpoint2->test(key)) setViewpoint(2); + else if (bSetViewpoint3->test(key)) setViewpoint(3); + else if (bSetViewpoint4->test(key)) setViewpoint(4); + else if (bSetViewpoint5->test(key)) setViewpoint(5); + else if (bSetViewpoint6->test(key)) setViewpoint(6); + else if (bSetViewpoint7->test(key)) setViewpoint(7); + else if (bSetViewpoint8->test(key)) setViewpoint(8); + else if (bSetViewpoint9->test(key)) setViewpoint(9); + else if (bMapBtn0->test(key)) mapButtonClicked(m_mapBtn0); + else if (bMapBtn1->test(key)) mapButtonClicked(m_mapBtn1); + else if (bMapBtn4->test(key)) mapButtonClicked(m_mapBtn4); + else if (bMapBtn5->test(key)) mapButtonClicked(m_mapBtn5); + else if (bMapBtn6->test(key)) mapButtonClicked(m_mapBtn6); + else if (bTechTree->test(key)) triggerMenu(MenuCommand::TechTree); + else if (bWait->test(key)) triggerMenu(MenuCommand::Wait); + + if (IsoEngine::unFocus >= 0) { + const auto doMoveUnit = [this](int x, int y) { + IsoEngine::destinationMarkOn = false; + paintDestination(); + TUn &un = ClientTools::myUn[IsoEngine::unFocus]; + un.Status = (un.Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto - IsoEngine::usEnhance)) + | usWaiting; + moveUnit(x, y, muAutoNext); + }; + using Cmd = MenuCommand; + const auto test = [](int job) { + return ClientTools::jobTest(IsoEngine::unFocus, job, 1ull << eTreaty); + }; + if (bDisbandUnit->test(key)) triggerMenu(Cmd::Disband); + else if (bFortify->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::Fort); + else if (bCenterUnit->test(key)) triggerMenu(Cmd::Centre); + else if (bStay->test(key)) triggerMenu(Cmd::Stay); + else if (bNoOrders->test(key)) triggerMenu(Cmd::NoOrders); + else if (bPrevUnit->test(key)) triggerMenu(Cmd::PrevUnit); + else if (bNextUnit->test(key)) triggerMenu(Cmd::NextUnit); + else if (bCancel->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Cancel); + else if (bPillage->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Pillage); + else if (bSelectTransport->test(key)) menuClickChecked(PopupKind::Unit, Cmd::SelectTransport); + else if (bAirBase->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::AirBase); + else if (bBuildCity->test(key)) menuClickChecked(PopupKind::Unit, Cmd::City); + else if (bEnhance->test(key)) { + initPopup(PopupKind::Terrain); + if (menuItemUsable(Cmd::Enhance)) + triggerMenu(Cmd::Enhance); + else + triggerMenu(Cmd::EnhanceDef); + } else if (bGoOn->test(key)) menuClickChecked(PopupKind::Unit, Cmd::GoOn); + else if (bHome->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Home); + else if (bFarmClearIrrigation->test(key)) { + if (test(jFarm)) triggerMenu(Cmd::Farm); + else if (test(jClear)) triggerMenu(Cmd::Clear); + else menuClickChecked(PopupKind::Terrain, Cmd::Irrigation); + } else if (bLoad->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Load); + else if (bAfforestMine->test(key)) { + if (test(jAfforest)) triggerMenu(Cmd::Afforest); + else menuClickChecked(PopupKind::Terrain, Cmd::Mine); + } else if (bCanal->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::Canal); + else if (bTrans->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::Trans); + else if (bPollution->test(key)) menuClickChecked(PopupKind::Terrain, Cmd::Pollution); + else if (bRailRoad->test(key)) { + if (test(jRR)) triggerMenu(Cmd::RailRoad); + else menuClickChecked(PopupKind::Terrain, Cmd::Road); + } else if (bUnload->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Unload); + else if (bRecover->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Recover); + else if (bUtilize->test(key)) menuClickChecked(PopupKind::Unit, Cmd::Utilize); + // unit move + else if (bUnitMoveLeftDown->test(key)) doMoveUnit(-1, 1); + else if (bUnitMoveDown->test(key)) doMoveUnit(0, 2); + else if (bUnitMoveRightDown->test(key)) doMoveUnit(1, 1); + else if (bUnitMoveLeft->test(key)) doMoveUnit(-2, 0); + else if (bUnitMoveRight->test(key)) doMoveUnit(2, 0); + else if (bUnitMoveLeftUp->test(key)) doMoveUnit(-1, -1); + else if (bUnitMoveUp->test(key)) doMoveUnit(0, -2); + else if (bUnitMoveRightUp->test(key)) doMoveUnit(1, -1); + } + Q_UNUSED(myUn); +} + +void MainScreen::setFullScreen(bool active) +{ + fullScreen = active; + if (active) { + if (!m_formFullScreen && !isFullScreen()) + m_restoredBounds = geometry(); + m_formFullScreen = true; + showFullScreen(); + } else { + m_formFullScreen = false; + showNormal(); + if (m_restoredBounds.isValid()) + setGeometry(m_restoredBounds); + } +} + +} // namespace Term +} // namespace Cevo diff --git a/game/localplayer/Term.MainScreen.Menus.cpp b/game/localplayer/Term.MainScreen.Menus.cpp new file mode 100644 index 0000000..5a9fb4b --- /dev/null +++ b/game/localplayer/Term.MainScreen.Menus.cpp @@ -0,0 +1,1183 @@ +// TMainScreen's menus (Term.pas): the game, unit, terrain and statistics +// popup menus with their click handlers, InitPopup, and the user settings. +// +// The popups are plain QMenus. Their check marks are not read back from the +// menu items like the original did: optionChecked/cityRepMask/mapOptionChecked +// are the single source of truth and the items update them when toggled. +// Shortcuts shown in the items come from the key bindings; the keys +// themselves are handled by keyPressEvent(). + +#include "Term.MainScreen.h" +#include "Term.MainScreen.Menus.h" + +#include "Cevo/CevoScreenTools.h" +#include "Cevo/CevoTexture.h" +#include "Cevo/Music.h" +#include "Global.h" +#include "KeyBindings.h" +#include "Messg.h" +#include "Sound.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace Cevo { +namespace Term { + +namespace { + +QString controlsPhrase(int tag) +{ + return phrases.lookup(QStringLiteral("CONTROLS"), (tag & 0xFF) - 1); +} + +QString shortcutSuffix(const KeyBindings::KeyBinding *binding) +{ + if (!binding || binding->shortCut.isEmpty()) + return QString(); + return QLatin1Char('\t') + KeyBindings::shortCutToText(binding->shortCut); +} + +bool hasOption(ClientTools::SaveOption so) +{ + return ClientTools::hasSaveOption(optionChecked, so); +} + +void setOption(ClientTools::SaveOption so, bool on) +{ + if (on) + optionChecked |= 1u << so; + else + optionChecked &= ~(1u << so); +} + +} // namespace + +void MainScreen::createMenus() +{ + using Cmd = MenuCommand; + m_menus = std::make_unique(); + Menus &m = *m_menus; + m.game = new QMenu(this); + m.unit = new QMenu(this); + m.stat = new QMenu(this); + m.terrain = new QMenu(this); + m.edit = new QMenu(this); + + const auto binding = [](Cmd command) -> const KeyBindings::KeyBinding * { + switch (command) { + case Cmd::Help: return KeyBindings::bHelp; + case Cmd::TechTree: return KeyBindings::bTechTree; + case Cmd::Jump: return KeyBindings::bJump; + case Cmd::Run: return KeyBindings::bRun; + case Cmd::Names: return KeyBindings::bNames; + case Cmd::LocCodes: return KeyBindings::bLocCodes; + case Cmd::Log: return KeyBindings::bLogDlg; + case Cmd::RandomMap: return KeyBindings::bRandomMap; + case Cmd::FillMap: return KeyBindings::bFillMap; + case Cmd::Resign: return KeyBindings::bResign; + case Cmd::Disband: return KeyBindings::bDisbandUnit; + case Cmd::Utilize: return KeyBindings::bUtilize; + case Cmd::City: return KeyBindings::bBuildCity; + case Cmd::Pillage: return KeyBindings::bPillage; + case Cmd::Home: return KeyBindings::bHome; + case Cmd::Load: return KeyBindings::bLoad; + case Cmd::Unload: return KeyBindings::bUnload; + case Cmd::SelectTransport: return KeyBindings::bSelectTransport; + case Cmd::GoOn: return KeyBindings::bGoOn; + case Cmd::Cancel: return KeyBindings::bCancel; + case Cmd::Recover: return KeyBindings::bRecover; + case Cmd::Wait: return KeyBindings::bWait; + case Cmd::NoOrders: return KeyBindings::bNoOrders; + case Cmd::Stay: return KeyBindings::bStay; + case Cmd::Centre: return KeyBindings::bCenterUnit; + case Cmd::PrevUnit: return KeyBindings::bPrevUnit; + case Cmd::NextUnit: return KeyBindings::bNextUnit; + case Cmd::UnitStat: return KeyBindings::bUnitStat; + case Cmd::CityStat: return KeyBindings::bCityStat; + case Cmd::ScienceStat: return KeyBindings::bScienceStat; + case Cmd::EUnitStat: return KeyBindings::bEUnitStat; + case Cmd::Diagram: return KeyBindings::bDiagram; + case Cmd::Wonders: return KeyBindings::bWonders; + case Cmd::Ships: return KeyBindings::bShips; + case Cmd::Nations: return KeyBindings::bNations; + case Cmd::Empire: return KeyBindings::bEmpire; + case Cmd::Trans: return KeyBindings::bTrans; + case Cmd::Afforest: case Cmd::Mine: return KeyBindings::bAfforestMine; + case Cmd::Clear: case Cmd::Farm: case Cmd::Irrigation: return KeyBindings::bFarmClearIrrigation; + case Cmd::Fort: return KeyBindings::bFortify; + case Cmd::AirBase: return KeyBindings::bAirBase; + case Cmd::Canal: return KeyBindings::bCanal; + case Cmd::RailRoad: case Cmd::Road: return KeyBindings::bRailRoad; + case Cmd::Pollution: return KeyBindings::bPollution; + case Cmd::Enhance: return KeyBindings::bEnhance; + default: return nullptr; + } + }; + + // Adds an item whose caption comes from CONTROLS[tag and $FF - 1] (or `caption` if given). + const auto item = [&](QMenu *menu, Cmd command, int tag, const QString &caption = QString()) { + QAction *action = menu->addAction((caption.isEmpty() ? controlsPhrase(tag) : caption) + + shortcutSuffix(binding(command))); + connect(action, &QAction::triggered, this, [this, command] { menuCommand(command); }); + m.action[command] = action; + return action; + }; + const auto submenu = [&](QMenu *parent, int tag, const QString &caption = QString()) { + QMenu *menu = parent->addMenu(caption.isEmpty() ? controlsPhrase(tag) : caption); + return menu; + }; + // A group of mutually exclusive items bound to option flags. + const auto optionRadio = [&](QMenu *menu, int tag, ClientTools::SaveOption so, QActionGroup *group) { + QAction *action = menu->addAction(controlsPhrase(tag)); + action->setCheckable(true); + group->addAction(action); + connect(action, &QAction::toggled, this, [so](bool on) { setOption(so, on); }); + m.optionItems.emplace_back(action, so); + return action; + }; + const auto optionToggle = [&](QMenu *menu, int tag, ClientTools::SaveOption so) { + QAction *action = menu->addAction(controlsPhrase(tag)); + action->setCheckable(true); + connect(action, &QAction::toggled, this, [so](bool on) { setOption(so, on); }); + m.optionItems.emplace_back(action, so); + return action; + }; + + // ---- game menu ---- + item(m.game, Cmd::Help, 7); + item(m.game, Cmd::TechTree, 0, phrases2[QStringLiteral("MENU_ADVTREE")]); + m.game->addSeparator(); + m.viewpoint = m.game->addMenu(phrases2[QStringLiteral("MENU_VIEWPOINT")]); + m.debugMap = m.game->addMenu(controlsPhrase(49)); + m.options = submenu(m.game, 29); + + m.ownMovement = submenu(m.options, 30); + auto *ownGroup = new QActionGroup(this); + optionRadio(m.ownMovement, 75, ClientTools::soSlowMoves, ownGroup); + optionRadio(m.ownMovement, 76, ClientTools::soFastMoves, ownGroup); + optionRadio(m.ownMovement, 77, ClientTools::soVeryFastMoves, ownGroup); + m.ownMovement->addSeparator(); + optionToggle(m.ownMovement, 95, ClientTools::soEffectiveMovesOnly); + + m.allyMovement = submenu(m.options, 90); + auto *allyGroup = new QActionGroup(this); + optionRadio(m.allyMovement, 91, ClientTools::soAlSlowMoves, allyGroup); + optionRadio(m.allyMovement, 92, ClientTools::soAlFastMoves, allyGroup); + optionRadio(m.allyMovement, 93, ClientTools::soAlNoMoves, allyGroup); + m.allyMovement->addSeparator(); + optionToggle(m.allyMovement, 94, ClientTools::soAlEffectiveMovesOnly); + + m.enemyMovement = submenu(m.options, 74); + auto *enemyGroup = new QActionGroup(this); + optionRadio(m.enemyMovement, 78, ClientTools::soEnMoves, enemyGroup); + optionRadio(m.enemyMovement, 79, ClientTools::soEnFastMoves, enemyGroup); + optionRadio(m.enemyMovement, 53, ClientTools::soEnNoMoves, enemyGroup); + m.enemyMovement->addSeparator(); + optionToggle(m.enemyMovement, 52, ClientTools::soEnAttacks); + + m.options->addSeparator(); + auto *repGroup = new QActionGroup(this); + m.repList = optionRadio(m.options, 65, ClientTools::soRepList, repGroup); + m.repScreens = optionRadio(m.options, 66, ClientTools::soRepScreens, repGroup); + m.rep = submenu(m.options, 34); + for (int i = 0; i < 16; ++i) { + QAction *action = m.rep->addAction(cityEventName(i)); + action->setCheckable(true); + connect(action, &QAction::triggered, this, [i](bool on) { + if (on) + cityRepMask |= 1u << i; + else + cityRepMask &= ~(1u << i); + }); + m.repItem[static_cast(i)] = action; + } + m.options->addSeparator(); + m.waitTurn = optionToggle(m.options, 32, ClientTools::soWaitTurn); + m.scrolling = submenu(m.options, 84); + auto *scrollGroup = new QActionGroup(this); + optionRadio(m.scrolling, 85, ClientTools::soScrollSlow, scrollGroup); + optionRadio(m.scrolling, 86, ClientTools::soScrollFast, scrollGroup); + optionRadio(m.scrolling, 87, ClientTools::soScrollOff, scrollGroup); + m.tileSize = submenu(m.options, 96); + m.tileGroup = new QActionGroup(this); + for (const auto &[command, tag] : { std::pair{ Cmd::TileSmall, 97 }, std::pair{ Cmd::TileNormal, 98 }, + std::pair{ Cmd::TileBig, 99 } }) { + QAction *action = item(m.tileSize, command, tag); + action->setCheckable(true); + m.tileGroup->addAction(action); + } + m.sound = submenu(m.options, 80); + m.soundGroup = new QActionGroup(this); + for (const auto &[command, tag] : { std::pair{ Cmd::SoundOn, 82 }, std::pair{ Cmd::SoundOnAlt, 83 }, + std::pair{ Cmd::SoundOff, 81 } }) { + QAction *action = item(m.sound, command, tag); + action->setCheckable(true); + m.soundGroup->addAction(action); + } + m.action[Cmd::SoundOnAlt]->setVisible(false); + m.music = submenu(m.options, 103); + m.musicGroup = new QActionGroup(this); + for (const auto &[command, tag] : { std::pair{ Cmd::MusicOn, 104 }, std::pair{ Cmd::MusicOff, 105 } }) { + QAction *action = item(m.music, command, tag); + action->setCheckable(true); + m.musicGroup->addAction(action); + } + m.options->addSeparator(); + m.test = submenu(m.options, 8); + item(m.test, Cmd::Jump, 54); + item(m.test, Cmd::Run, 63); + m.names = item(m.test, Cmd::Names, 67); + m.names->setCheckable(true); + m.locCodes = item(m.test, Cmd::LocCodes, 27); + m.locCodes->setCheckable(true); + item(m.test, Cmd::Log, 10); + + m.manip = submenu(m.game, 56); + for (int i = 0; i < nTestFlags; ++i) { + static const int tags[nTestFlags] = { 57, 314, 571, 828, 1085, 1342, 1604 }; + QAction *action = m.manip->addAction(controlsPhrase(tags[i])); + action->setCheckable(true); + const int flag = 1 << (tags[i] >> 8); + connect(action, &QAction::triggered, this, [this, flag] { + if ((ClientTools::myRO->TestFlags & flag) != 0) { + ClientTools::server(sClearTestFlag, 0, flag, nullptr); + } else { + ClientTools::server(sSetTestFlag, 0, flag, nullptr); + Sound::play(QStringLiteral("CHEAT")); + } + if (!supervising) { + if (flag == tfUncover) { + m_mapValid = false; + paintAllMaps(); + } else if (flag == tfAllTechs) { + tellNewModels(); + } + } + }); + m.manipItem[static_cast(i)] = action; + } + m.macro = submenu(m.game, 42); + item(m.macro, Cmd::EnhanceDef, 40); + item(m.macro, Cmd::CityTypes, 11); + item(m.game, Cmd::RandomMap, 71); + item(m.game, Cmd::FillMap, 102); + m.game->addSeparator(); + item(m.game, Cmd::Website, 88); + m.game->addSeparator(); + item(m.game, Cmd::Resign, 2); + + // ---- unit menu ---- + item(m.unit, Cmd::Disband, 72); + item(m.unit, Cmd::Utilize, 0, QStringLiteral("Utilize")); + m.unit->addSeparator(); + item(m.unit, Cmd::City, 0, QStringLiteral("City")); + item(m.unit, Cmd::Pillage, 19); + m.unit->addSeparator(); + item(m.unit, Cmd::Home, 0, QStringLiteral("Home")); + item(m.unit, Cmd::Load, 24); + item(m.unit, Cmd::Unload, 70); + item(m.unit, Cmd::SelectTransport, 73); + item(m.unit, Cmd::GoOn, 13); + item(m.unit, Cmd::Cancel, 1); + item(m.unit, Cmd::Recover, 69); + item(m.unit, Cmd::Wait, 25); + item(m.unit, Cmd::NoOrders, 26); + item(m.unit, Cmd::Stay, 22); + item(m.unit, Cmd::Centre, 12); + m.unit->addSeparator(); + item(m.unit, Cmd::PrevUnit, 100); + item(m.unit, Cmd::NextUnit, 101); + + // ---- statistics menu ---- + item(m.stat, Cmd::UnitStat, 9); + item(m.stat, Cmd::CityStat, 37); + item(m.stat, Cmd::ScienceStat, 38); + item(m.stat, Cmd::EUnitStat, 50); + item(m.stat, Cmd::Diagram, 21); + item(m.stat, Cmd::Wonders, 6); + item(m.stat, Cmd::Ships, 41); + m.stat->addSeparator(); + item(m.stat, Cmd::Nations, 55); + item(m.stat, Cmd::Empire, 3); + item(m.stat, Cmd::Revolution, 89); + + // ---- terrain menu ---- + item(m.terrain, Cmd::Trans, 273); + item(m.terrain, Cmd::Afforest, 301); + item(m.terrain, Cmd::Clear, 298); + item(m.terrain, Cmd::Fort, 276); + item(m.terrain, Cmd::AirBase, 272); + item(m.terrain, Cmd::Canal, 279); + item(m.terrain, Cmd::Mine, 302); + item(m.terrain, Cmd::Farm, 300); + item(m.terrain, Cmd::Irrigation, 299); + item(m.terrain, Cmd::RailRoad, 297); + item(m.terrain, Cmd::Road, 296); + item(m.terrain, Cmd::Pollution, 274); + item(m.terrain, Cmd::Enhance, 295); + + // ---- editor menu (units created on the fly) ---- + m.createUnit = m.edit->addMenu(controlsPhrase(47)); +} + +void MainScreen::menuClickChecked(PopupKind kind, MenuCommand command) +{ + initPopup(kind); + if (menuItemUsable(command)) + triggerMenu(command); +} + +void MainScreen::triggerMenu(MenuCommand command) +{ + m_menus->act(command)->trigger(); +} + +bool MainScreen::menuItemUsable(MenuCommand command) const +{ + const QAction *action = m_menus->act(command); + return action->isVisible() && action->isEnabled(); +} + +QMenu *MainScreen::createUnitMenu() +{ + m_menus->createUnit->clear(); + return m_menus->createUnit; +} + +void MainScreen::showPopup(PopupKind kind, const QPoint &globalPos) +{ + QMenu *menu = kind == PopupKind::Game ? m_menus->game + : kind == PopupKind::Unit ? m_menus->unit + : kind == PopupKind::Stat ? m_menus->stat + : kind == PopupKind::Edit ? m_menus->edit + : m_menus->terrain; + if (kind != PopupKind::Edit) + initPopup(kind); + menu->popup(globalPos); +} + +void MainScreen::initPopup(PopupKind kind) +{ + using ClientTools::me; + using ClientTools::myCity; + using ClientTools::myMap; + using ClientTools::myModel; + using ClientTools::myRO; + using ClientTools::myUn; + using ClientTools::server; + using Cmd = MenuCommand; + Menus &m = *m_menus; + TNewGameData &g = ClientTools::g; + const auto setItemVisible = [&](Cmd command, bool visible) { m.act(command)->setVisible(visible); }; + const auto enable = [&](Cmd command, bool enabled) { m.act(command)->setEnabled(enabled); }; + + const bool noSuper = !supervising && ((1 << me) & myRO->Alive) != 0; + bool haveCities = false; + for (int i = 0; i < myRO->nCity; ++i) { + if (myCity[i].Loc >= 0) { + haveCities = true; + break; + } + } + + if (kind == PopupKind::Game) { + setItemVisible(Cmd::TechTree, clientMode != cEditMap); + enable(Cmd::Resign, supervising || (me == 0 && clientMode < scContact)); + const bool mapGenerator = clientMode == cEditMap && server(sMapGeneratorRequest, me, 0, nullptr) == eOK; + setItemVisible(Cmd::RandomMap, mapGenerator); + setItemVisible(Cmd::FillMap, mapGenerator); + m.options->menuAction()->setVisible(clientMode != cEditMap); + m.manip->menuAction()->setVisible(clientMode != cEditMap); + if (clientMode != cEditMap) { + m.waitTurn->setVisible(noSuper); + m.rep->menuAction()->setVisible(noSuper); + m.repList->setVisible(noSuper); + m.repScreens->setVisible(noSuper); + m.ownMovement->menuAction()->setVisible(noSuper); + m.allyMovement->menuAction()->setVisible(noSuper); + // check marks come from the options + for (const auto &[action, so] : m.optionItems) + action->setChecked(hasOption(so)); + m.names->setChecked(mainScreenNamesChecked); + m.act(Cmd::SoundOn)->setChecked(Sound::mode == SoundMode::On); + m.act(Cmd::SoundOnAlt)->setChecked(Sound::mode == SoundMode::OnAlt); + m.act(Cmd::SoundOff)->setChecked(Sound::mode == SoundMode::Off); + m.act(Cmd::MusicOn)->setChecked(musicEnabled); + m.act(Cmd::MusicOff)->setChecked(!musicEnabled); + for (int i = 0; i < 16; ++i) + m.repItem[static_cast(i)]->setChecked((cityRepMask & (1u << i)) != 0); + for (int i = 0; i < nTestFlags; ++i) + m.manipItem[static_cast(i)]->setChecked((myRO->TestFlags & (1 << i)) != 0); + m.manip->setEnabled(supervising || me == 0); + bool multi = false; + for (int p1 = 1; p1 < nPl; ++p1) { + if (g.RO[p1]) { + multi = true; + break; + } + } + m.enemyMovement->menuAction()->setVisible(!multi); + } + m.macro->menuAction()->setVisible(noSuper && clientMode < scContact); + if (noSuper && clientMode < scContact) { + bool cityTypesUseful = false; + // check if city types already usefull: + if (myRO->nCity > 0) { + for (int i = nWonder; i < nImp; ++i) { + if (i != imTrGoods && Imp[i].Kind == ikCommon && Imp[i].Preq != preNA + && (Imp[i].Preq == preNone || myRO->Tech[Imp[i].Preq] >= tsApplicable)) { + cityTypesUseful = true; + break; + } + } + } + m.act(Cmd::CityTypes)->setEnabled(cityTypesUseful); + } + m.viewpoint->menuAction()->setVisible(clientMode != cEditMap && supervising); + m.viewpoint->menuAction()->setEnabled(g.RO[0]->Turn > 0); + m.debugMap->menuAction()->setVisible(clientMode != cEditMap && supervising); + if (supervising) { + m.viewpoint->clear(); + m.debugMap->clear(); + for (int p1 = 0; p1 < nPl; ++p1) { + if (p1 != 0 && ((1 << p1) & g.RO[0]->Alive) == 0) + continue; + const QString name = + p1 == 0 ? phrases[QStringLiteral("SUPER")] + : Tribes::tribe[static_cast(p1)]->tString( + phraseToQtFormat(phrases2[QStringLiteral("BELONG")])); + QAction *view = m.viewpoint->addAction(name); + view->setCheckable(true); + view->setChecked(p1 == me); + connect(view, &QAction::triggered, this, [this, p1] { setViewpoint(p1); }); + QAction *debug = m.debugMap->addAction(p1 == 0 ? phrases2[QStringLiteral("MENU_DEBUGMAPOFF")] : name); + debug->setCheckable(true); + debug->setChecked((p1 == 0 ? -1 : p1) == m_mainMap->pDebugMap); + connect(debug, &QAction::triggered, this, [this, p1] { setDebugMap(p1 == 0 ? -1 : p1); }); + } + } + m.locCodes->setChecked(m_locCodesChecked); + m.act(Cmd::TileSmall)->setChecked(m_mainMap->tileSize() == IsoEngine::TileSize::Small); + m.act(Cmd::TileNormal)->setChecked(m_mainMap->tileSize() == IsoEngine::TileSize::Medium); + m.act(Cmd::TileBig)->setChecked(m_mainMap->tileSize() == IsoEngine::TileSize::Big); + } else if (kind == PopupKind::Stat) { + setItemVisible(Cmd::Empire, noSuper); + enable(Cmd::Empire, myRO->Government != gAnarchy); + setItemVisible(Cmd::Revolution, noSuper); + enable(Cmd::Revolution, myRO->Government != gAnarchy && clientMode < scContact); + enable(Cmd::UnitStat, noSuper || myRO->Turn > 0); + setItemVisible(Cmd::CityStat, ((1 << me) & myRO->Alive) != 0); + enable(Cmd::CityStat, haveCities); + setItemVisible(Cmd::ScienceStat, true); + enable(Cmd::ScienceStat, !noSuper || myRO->ResearchTech >= 0 || (myRO->Happened & phTech) != 0 + || (myRO->Happened & phGameEnd) != 0 + || (myRO->TestFlags & (tfAllTechs | tfUncover | tfAllContact)) != 0); + // no researchtech in case just completed + enable(Cmd::EUnitStat, myRO->nEnemyModel > 0); + enable(Cmd::Diagram, myRO->Turn >= 2); + bool ships = false; + for (int p1 = 0; p1 < nPl; ++p1) { + if (myRO->Ship[p1].Parts[spComp] + myRO->Ship[p1].Parts[spPow] + myRO->Ship[p1].Parts[spHab] > 0) { + ships = true; + break; + } + } + enable(Cmd::Ships, ships); + } else if (kind == PopupKind::Unit) { + const TUn &un = myUn[IsoEngine::unFocus]; + const TModel &model = myModel[un.mix]; + const std::uint32_t tile = myMap[un.Loc]; + bool extended = (tile & fCity) == 0; + if (extended) { + m.act(Cmd::City)->setText(phrases[QStringLiteral("BTN_FOUND")] + shortcutSuffix(KeyBindings::bBuildCity)); + m.act(Cmd::Home)->setText(phrases[QStringLiteral("BTN_MOVEHOME")] + shortcutSuffix(KeyBindings::bHome)); + } else { + m.act(Cmd::City)->setText(phrases[QStringLiteral("BTN_ADD")] + shortcutSuffix(KeyBindings::bBuildCity)); + m.act(Cmd::Home)->setText(phrases[QStringLiteral("BTN_SETHOME")] + shortcutSuffix(KeyBindings::bHome)); + } + extended = extended + && (model.Kind == mkSettler + || (model.Kind == mkSlaves && myRO->Wonder[woPyramids].EffectiveOwner >= 0)) + && un.Master < 0 && (tile & fDeadLands) == 0; + if ((model.Kind == mkFreight && (tile & fCity) != 0 && !phrases2FallenBackToEnglish) + || server(sRemoveUnit - sExecute, me, IsoEngine::unFocus, nullptr) == eUtilized) { + setItemVisible(Cmd::Disband, false); + setItemVisible(Cmd::Utilize, true); + m.act(Cmd::Utilize)->setText( + (model.Kind == mkFreight ? phrases[QStringLiteral("UTILIZE")] : phrases[QStringLiteral("INTEGRATE")]) + + shortcutSuffix(KeyBindings::bUtilize)); + } else { + setItemVisible(Cmd::Disband, true); + setItemVisible(Cmd::Utilize, false); + } + setItemVisible(Cmd::GoOn, (un.Status & (IsoEngine::usGoto | usWaiting)) == (IsoEngine::usGoto | usWaiting)); + setItemVisible(Cmd::Home, haveCities); + const bool airOutside = !(model.Domain == dAir && (tile & fCity) == 0 + && (tile & fTerImp) != static_cast(tiBase)); + setItemVisible(Cmd::Recover, un.Health < 100 && (tile & fTerrain) >= static_cast(fGrass) + && (myRO->Wonder[woGardens].EffectiveOwner == me + || ((tile & fTerrain) != static_cast(fArctic) + && (tile & fTerrain) != static_cast(fDesert))) + && airOutside); + setItemVisible(Cmd::Stay, airOutside); + setItemVisible(Cmd::City, (extended && model.Kind == mkSettler) + || ((tile & fCity) != 0 + && (model.Kind == mkSettler || model.Kind == mkSlaves + || (un.Flags & unConscripts) != 0))); + setItemVisible(Cmd::Pillage, (tile & (fRoad | fRR | fCanal | fTerImp)) != 0 && un.Master < 0 && model.Domain == dGround); + setItemVisible(Cmd::Cancel, un.Job > jNone || (un.Status & (IsoEngine::usRecover | IsoEngine::usGoto)) != 0); + const int test = server(sLoadUnit - sExecute, me, IsoEngine::unFocus, nullptr); + setItemVisible(Cmd::Load, test >= rExecuted || test == eNoTime_Load); + setItemVisible(Cmd::Unload, un.Master >= 0 || un.TroopLoad + un.AirLoad > 0); + setItemVisible(Cmd::SelectTransport, server(sSelectTransport - sExecute, me, IsoEngine::unFocus, nullptr) >= rExecuted); + } else if (kind == PopupKind::Terrain) { + const TUn &un = myUn[IsoEngine::unFocus]; + const TModel &model = myModel[un.mix]; + const std::uint32_t tile = myMap[un.Loc]; + bool extended = (tile & fCity) == 0; + if ((tile & fRiver) != 0 && myRO->Tech[adBridgeBuilding] >= tsApplicable) { + m.act(Cmd::Road)->setText(phrases[QStringLiteral("BTN_BUILDBRIDGE")] + shortcutSuffix(KeyBindings::bRailRoad)); + m.act(Cmd::RailRoad)->setText(phrases[QStringLiteral("BTN_BUILDRRBRIDGE")] + shortcutSuffix(KeyBindings::bRailRoad)); + } else { + m.act(Cmd::Road)->setText(phrases[QStringLiteral("BTN_BUILDROAD")] + shortcutSuffix(KeyBindings::bRailRoad)); + m.act(Cmd::RailRoad)->setText(phrases[QStringLiteral("BTN_BUILDRR")] + shortcutSuffix(KeyBindings::bRailRoad)); + } + QString clearText; + if ((tile & fTerrain) == static_cast(fForest)) + clearText = phrases[QStringLiteral("BTN_CLEAR")]; + else if ((tile & fTerrain) == static_cast(fDesert)) + clearText = phrases[QStringLiteral("BTN_UNDESERT")]; + else + clearText = phrases[QStringLiteral("BTN_DRAIN")]; + m.act(Cmd::Clear)->setText(clearText + shortcutSuffix(KeyBindings::bFarmClearIrrigation)); + + extended = extended + && (model.Kind == mkSettler + || (model.Kind == mkSlaves && myRO->Wonder[woPyramids].EffectiveOwner >= 0)) + && un.Master < 0; + const std::initializer_list terrainCommands = { + Cmd::Road, Cmd::RailRoad, Cmd::Clear, Cmd::Irrigation, Cmd::Farm, Cmd::Afforest, Cmd::Mine, Cmd::Trans, + Cmd::Canal, Cmd::Fort, Cmd::AirBase, Cmd::Pollution, Cmd::Enhance + }; + if (extended) { + const ClientTools::JobResultSet treaty = 1ull << (eTreaty & 0x3F); + const ClientTools::JobResultSet bridgeTreaty = treaty | (1ull << (eNoBridgeBuilding & 0x3F)); + const auto test = [&](int job, ClientTools::JobResultSet ignore) { + return ClientTools::jobTest(IsoEngine::unFocus, job, ignore); + }; + setItemVisible(Cmd::Road, test(jRoad, bridgeTreaty)); + setItemVisible(Cmd::RailRoad, test(jRR, bridgeTreaty)); + setItemVisible(Cmd::Clear, test(jClear, treaty)); + setItemVisible(Cmd::Irrigation, test(jIrr, treaty)); + setItemVisible(Cmd::Farm, test(jFarm, treaty)); + setItemVisible(Cmd::Afforest, test(jAfforest, treaty)); + setItemVisible(Cmd::Mine, test(jMine, treaty)); + setItemVisible(Cmd::Trans, test(jTrans, treaty)); + setItemVisible(Cmd::Canal, test(jCanal, treaty)); + setItemVisible(Cmd::Fort, test(jFort, treaty)); + setItemVisible(Cmd::AirBase, test(jBase, treaty)); + setItemVisible(Cmd::Pollution, test(jPoll, treaty)); + setItemVisible(Cmd::Enhance, (tile & fDeadLands) == 0 + && myData->enhancementJobs[tile & fTerrain][0] != jNone); + } else { + for (const MenuCommand command : terrainCommands) + setItemVisible(command, false); + } + } +} + +void MainScreen::menuCommand(MenuCommand command) +{ + using ClientTools::me; + using ClientTools::myCity; + using ClientTools::myMap; + using ClientTools::myModel; + using ClientTools::myRO; + using ClientTools::myUn; + using ClientTools::server; + using Cmd = MenuCommand; + const bool focused = IsoEngine::unFocus >= 0; + + switch (command) { + case Cmd::Afforest: if (focused) doJob(jAfforest); break; + case Cmd::AirBase: if (focused) doJob(jBase); break; + case Cmd::Canal: if (focused) doJob(jCanal); break; + case Cmd::Clear: if (focused) doJob(jClear); break; + case Cmd::Fort: if (focused) doJob(jFort); break; + case Cmd::Farm: if (focused) doJob(jFarm); break; + case Cmd::Irrigation: if (focused) doJob(jIrr); break; + case Cmd::Mine: if (focused) doJob(jMine); break; + case Cmd::Trans: if (focused) doJob(jTrans); break; + case Cmd::Pollution: if (focused) doJob(jPoll); break; + case Cmd::RailRoad: if (focused) doJob(jRR); break; + case Cmd::Road: if (focused) doJob(jRoad); break; + case Cmd::Enhance: if (focused) doJob(-1); break; + case Cmd::Pillage: doJob(jPillage); break; + + case Cmd::Cancel: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + IsoEngine::destinationMarkOn = false; + paintDestination(); + un.Status &= 0xFFFF - IsoEngine::usRecover - IsoEngine::usGoto - IsoEngine::usEnhance; + if (un.Job > jNone) + server(sStartJob + (jNone << 4), me, IsoEngine::unFocus, nullptr); + } + break; + case Cmd::Centre: + if (focused) { + centre(myUn[IsoEngine::unFocus].Loc); + paintAllMaps(); + } + break; + case Cmd::City: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + const int loc0 = un.Loc; + if ((myMap[un.Loc] & fCity) == 0) { // build city + if (doJob(jCity) == eCity) { + m_mapValid = false; + paintAll(); + zoomToCity(loc0, true, chFounded); + } + } else { + ClientTools::cityOptimizer_BeforeRemoveUnit(IsoEngine::unFocus); + const int serverResult = server(sAddToCity, me, IsoEngine::unFocus, nullptr); + if (serverResult >= rExecuted) { + int cix = myRO->nCity - 1; + while (cix >= 0 && myCity[cix].Loc != loc0) + --cix; + Q_ASSERT(cix >= 0); + ClientTools::cityOptimizer_CityChange(cix); + ClientTools::cityOptimizer_AfterRemoveUnit(); // does nothing here + setTroopLoc(loc0); + updateViews(true); + IsoEngine::destinationMarkOn = false; + paintDestination(); + IsoEngine::unFocus = -1; + paintLoc(loc0); + nextUnit(unStartLoc, true); + } else if (serverResult == eMaxSize) { + simpleMessage(phrases[QStringLiteral("ADDTOMAXSIZE")]); + } + } + } + break; + case Cmd::CityStat: listDlg().showNewContent(WindowMode::Persistent, Select::ListKind::Cities); break; + case Cmd::CityTypes: cityTypeDlg().showNewContent(WindowMode::Modal); break; // modal: types are saved on close + case Cmd::Diagram: diaDlg().showNewContentCharts(WindowMode::Persistent); break; + case Cmd::Empire: ratesDlg().showNewContent(WindowMode::Persistent); break; + case Cmd::FillMap: + if (!m_edited + || MessgEx::simpleQuery(MessageKind::YesNo, phrases[QStringLiteral("MAP_FILL")], QString()) + == Dpi::ModalResult::Ok) { + TFillMapData fillMapData; + fillMapData.Tile = static_cast(m_brushType); + server(sFillMap, me, 0, &fillMapData); + m_edited = true; + m_mapValid = false; + paintAllMaps(); + } + break; + case Cmd::EnhanceDef: + if (focused) + enhanceDlg().showNewContent(WindowMode::Persistent, static_cast(myMap[myUn[IsoEngine::unFocus].Loc] & fTerrain)); + else + enhanceDlg().showNewContent(WindowMode::Persistent); + break; + case Cmd::EUnitStat: + if (myRO->nEnemyModel > 0) + listDlg().showNewContent(WindowMode::Persistent, Select::ListKind::AllEnemyModels); + break; + case Cmd::GoOn: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + const int destination = (un.Status >> 16) == 0x7FFF ? maNextCity : (un.Status >> 16); + un.Status = (un.Status & ~(IsoEngine::usStay | IsoEngine::usRecover)) | usWaiting; + moveToLoc(destination, true); + } + break; + case Cmd::Help: + if (clientMode == cEditMap) + helpDlg().showNewContent(WindowMode::Persistent, Help::LinkCategory::Text, + helpDlg().textIndex(QStringLiteral("MAPEDIT"))); + else + helpDlg().showNewContent(WindowMode::Persistent, Help::LinkCategory::Misc, + static_cast(Help::MiscLinkIndex::Main)); + break; + case Cmd::Home: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + if ((myMap[un.Loc] & fCity) != 0) { + const int cixOldHome = un.Home; + if (server(sSetUnitHome, me, IsoEngine::unFocus, nullptr) >= rExecuted) { + ClientTools::cityOptimizer_CityChange(cixOldHome); + ClientTools::cityOptimizer_CityChange(un.Home); + updateViews(true); + } else { + Sound::play(QStringLiteral("INVALID")); + } + } else { + un.Status &= ~(IsoEngine::usStay | IsoEngine::usRecover | IsoEngine::usEnhance); + moveToLoc(maNextCity, true); + } + } + break; + case Cmd::Jump: + m_jump[static_cast(supervising ? 0 : me)] = 20; + endTurn(true); + break; + case Cmd::Run: + m_jump[static_cast(supervising ? 0 : me)] = 999999; + endTurn(true); + break; + case Cmd::Load: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + const int result = server(sLoadUnit, me, IsoEngine::unFocus, nullptr); + if (result >= rExecuted) { + Sound::play(myModel[un.mix].Domain == dAir ? QStringLiteral("MOVE_PLANELANDING") + : QStringLiteral("MOVE_LOAD")); + IsoEngine::destinationMarkOn = false; + paintDestination(); + un.Status &= 0xFFFF - usWaiting - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto + - IsoEngine::usEnhance; + nextUnit(unStartLoc, true); + } else if (result == eNoTime_Load) { + if (myModel[un.mix].Domain == dAir) + soundMessage(phrases[QStringLiteral("NOTIMELOADAIR")], QStringLiteral("NOMOVE_TIME")); + else + soundMessage(formatPhrase(QStringLiteral("NOTIMELOADGROUND"), + { movementToString(myModel[un.mix].Speed) }), + QStringLiteral("NOMOVE_TIME")); + } + } + break; + case Cmd::Log: logDlg().show(); break; + case Cmd::LocCodes: + m_locCodesChecked = !m_locCodesChecked; + setMapOptions(); + m_mapValid = false; + paintAllMaps(); + break; + case Cmd::Names: { + mainScreenNamesChecked = !mainScreenNamesChecked; + generateNames = mainScreenNamesChecked; + for (int p1 = 0; p1 < nPl; ++p1) { + if (Tribes::tribe[static_cast(p1)]) + Tribes::tribe[static_cast(p1)]->numberName = generateNames ? -1 : p1; + } + m_mapValid = false; + paintAll(); + break; + } + case Cmd::MusicOn: + musicEnabled = true; + updateMusic(); + break; + case Cmd::MusicOff: + musicEnabled = false; + updateMusic(); + break; + case Cmd::Nations: natStatDlg().showNewContent(WindowMode::Persistent); break; + case Cmd::NextUnit: + if (focused) { + myUn[IsoEngine::unFocus].Status &= ~usWaiting; + focusNextUnit(1); + } + break; + case Cmd::PrevUnit: + if (focused) { + myUn[IsoEngine::unFocus].Status &= ~usWaiting; + focusNextUnit(-1); + } + break; + case Cmd::NoOrders: + if (focused) { + myUn[IsoEngine::unFocus].Status &= ~usWaiting; + nextUnit(unStartLoc, true); + } + break; + case Cmd::RandomMap: + if (!m_edited + || MessgEx::simpleQuery(MessageKind::YesNo, phrases[QStringLiteral("MAP_RANDOM")], QString()) + == Dpi::ModalResult::Ok) { + server(sRandomMap, me, 0, nullptr); + m_edited = true; + m_mapValid = false; + paintAllMaps(); + } + break; + case Cmd::Recover: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + IsoEngine::destinationMarkOn = false; + paintDestination(); + un.Status = (un.Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usGoto - IsoEngine::usEnhance)) + | IsoEngine::usRecover; + if (un.Job > jNone) + server(sStartJob + (jNone << 4), me, IsoEngine::unFocus, nullptr); + nextUnit(unStartLoc, true); + } + break; + case Cmd::Resign: + if (clientMode == cEditMap) { + if (m_edited) { + const Dpi::ModalResult r = + MessgEx::simpleQuery(MessageKind::YesNoCancel, phrases[QStringLiteral("MAP_CLOSE")], QString()); + if (r == Dpi::ModalResult::Ignore) + server(sAbandonMap, me, 0, nullptr); + else if (r == Dpi::ModalResult::Ok) + server(sSaveMap, me, 0, nullptr); + } else { + server(sAbandonMap, me, 0, nullptr); + } + } else if (server(sGetGameChanged, 0, 0, nullptr) == eOK) { + const Dpi::ModalResult r = + MessgEx::simpleQuery(MessageKind::YesNoCancel, phrases[QStringLiteral("RESIGN")], QString()); + if (r == Dpi::ModalResult::Ignore) + server(sResign, 0, 0, nullptr); + else if (r == Dpi::ModalResult::Ok) + server(sBreak, 0, 0, nullptr); + } else { + server(sResign, 0, 0, nullptr); + } + break; + case Cmd::Revolution: { + bool altGovs = false; + for (int i = 2; i < nGov; ++i) { + if (GovPreq[i] != preNA && (GovPreq[i] == preNone || myRO->Tech[GovPreq[i]] >= tsApplicable)) { + altGovs = true; + break; + } + } + if (!altGovs) { + soundMessage(phrases[QStringLiteral("NOALTGOVS")], QStringLiteral("MSG_DEFAULT")); + break; + } + bool revolutionChanged = false; + if ((myRO->Happened & phChangeGov) != 0) { + modalSelectDlg().showNewContent(WindowMode::Modal, Select::ListKind::Government); + if (modalSelectDlg().result >= 0) { + Sound::play(QStringLiteral("NEWGOV")); + server(sSetGovernment, me, modalSelectDlg().result, nullptr); + ClientTools::cityOptimizer_BeginOfTurn(); + revolutionChanged = true; + } + } else { // revolution! + MessgEx::MessgExDlg &dlg = messgExDlg(); + dlg.messageText = Tribes::tribe[static_cast(me)]->tPhrase(QStringLiteral("REVOLUTION")); + dlg.kind = MessageKind::YesNo; + dlg.iconKind = MessgEx::MessageIconKind::PureIcon; + dlg.iconIndex = 72; // anarchy palace + if (dlg.showModal() == Dpi::ModalResult::Ok) { + Sound::play(QStringLiteral("REVOLUTION")); + server(sRevolution, me, 0, nullptr); + revolutionChanged = true; + if (m_natStatDlg && m_natStatDlg->isVisible()) + m_natStatDlg->close(); + if (m_cityDlg && m_cityDlg->isVisible()) + m_cityDlg->close(); + } + } + if (revolutionChanged) + updateViews(true); + break; + } + case Cmd::ScienceStat: listDlg().showNewContent(WindowMode::Persistent, Select::ListKind::Science); break; + case Cmd::SelectTransport: + if (focused) + server(sSelectTransport, me, IsoEngine::unFocus, nullptr); + break; + case Cmd::Ships: diaDlg().showNewContentShip(WindowMode::Persistent); break; + case Cmd::Stay: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + IsoEngine::destinationMarkOn = false; + paintDestination(); + un.Status = (un.Status & (0xFFFF - IsoEngine::usRecover - IsoEngine::usGoto - IsoEngine::usEnhance)) + | IsoEngine::usStay; + if (un.Job > jNone) + server(sStartJob + (jNone << 4), me, IsoEngine::unFocus, nullptr); + nextUnit(unStartLoc, true); + } + break; + case Cmd::TechTree: techTreeDlg().showModal(); break; + case Cmd::UnitStat: + if (ClientTools::g.Difficulty[me] > 0) { + listDlg().showNewContentMilReport(WindowMode::Persistent, me); + } else { + int i = 1; + while (i < nPl && ((1 << i) & myRO->Alive) == 0) + ++i; + if (i < nPl) + listDlg().showNewContentMilReport(WindowMode::Persistent, i); + } + break; + case Cmd::Unload: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + if (un.Master >= 0) { + const int oldMaster = un.Master; + const int result = server(sUnloadUnit, me, IsoEngine::unFocus, nullptr); + if (result >= rExecuted) { + if (myModel[un.mix].Domain == dAir) + Sound::play(QStringLiteral("MOVE_PLANESTART")); + else if (myModel[myUn[oldMaster].mix].Domain == dAir && (myMap[un.Loc] & fCity) == 0 + && (myMap[un.Loc] & fTerImp) != static_cast(tiBase)) + Sound::play(QStringLiteral("MOVE_PARACHUTE")); + else + Sound::play(QStringLiteral("MOVE_UNLOAD")); + un.Status &= ~usWaiting; + if (myModel[un.mix].Domain != dAir) + nextUnit(un.Loc, true); + else + panelPaint(); + } else if (result == eNoTime_Load) { + if (myModel[un.mix].Domain == dAir) + soundMessage(phrases[QStringLiteral("NOTIMELOADAIR")], QStringLiteral("NOMOVE_TIME")); + else + soundMessage(formatPhrase(QStringLiteral("NOTIMELOADGROUND"), + { movementToString(myModel[un.mix].Speed) }), + QStringLiteral("NOMOVE_TIME")); + } + } else { + int newFocus = -1; + int uix = IsoEngine::unFocus; + for (int i = 1; i < myRO->nUn; ++i) { + uix = (uix + myRO->nUn - 1) % myRO->nUn; + if (myUn[uix].Master == IsoEngine::unFocus + && myUn[uix].Movement == static_cast(myModel[myUn[uix].mix].Speed)) { + myUn[uix].Status |= usWaiting; + newFocus = uix; + } + } + if (newFocus >= 0) { + setUnFocus(newFocus); + setTroopLoc(un.Loc); + panelPaint(); + } + } + } + break; + case Cmd::Wait: + if (focused) { + TUn &un = myUn[IsoEngine::unFocus]; + IsoEngine::destinationMarkOn = false; + paintDestination(); + un.Status = (un.Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto + - IsoEngine::usEnhance)) + | usWaiting; + } + nextUnit(-1, false); + break; + case Cmd::Website: QDesktopServices::openUrl(QUrl(QString::fromLatin1(CevoHomepage))); break; + case Cmd::Wonders: wondersDlg().showNewContent(WindowMode::Persistent); break; + case Cmd::Disband: disbandOrUtilize(false); break; + case Cmd::Utilize: disbandOrUtilize(true); break; + case Cmd::TileSmall: setTileSizeCenter(IsoEngine::TileSize::Small); break; + case Cmd::TileNormal: setTileSizeCenter(IsoEngine::TileSize::Medium); break; + case Cmd::TileBig: setTileSizeCenter(IsoEngine::TileSize::Big); break; + case Cmd::SoundOn: Sound::mode = SoundMode::On; setOption(ClientTools::soSoundOn, true); break; + case Cmd::SoundOnAlt: Sound::mode = SoundMode::OnAlt; setOption(ClientTools::soSoundOnAlt, true); break; + case Cmd::SoundOff: Sound::mode = SoundMode::Off; setOption(ClientTools::soSoundOff, true); break; + } +} + +void MainScreen::disbandOrUtilize(bool utilize) +{ + using ClientTools::me; + if (IsoEngine::unFocus < 0) + return; + TUn &un = ClientTools::myUn[IsoEngine::unFocus]; + if (utilize && ClientTools::server(sRemoveUnit - sExecute, me, IsoEngine::unFocus, nullptr) != eUtilized) { + simpleMessage(phrases2[QStringLiteral("SHIP_UTILIZE")]); + // freight for colony ship is the only case in which the command is + // available to player though not valid + return; + } + if (utilize && un.Health < 100 + && MessgEx::simpleQuery(MessageKind::YesNo, phrases[QStringLiteral("DAMAGED_UTILIZE")], QString()) + != Dpi::ModalResult::Ok) + return; + const int loc0 = un.Loc; + ClientTools::cityOptimizer_BeforeRemoveUnit(IsoEngine::unFocus); + if (ClientTools::server(sRemoveUnit, me, IsoEngine::unFocus, nullptr) == eUtilized) + Sound::play(QStringLiteral("CITY_UTILIZE")); + else + Sound::play(QStringLiteral("DISBAND")); + ClientTools::cityOptimizer_AfterRemoveUnit(); + setTroopLoc(loc0); + updateViews(true); + IsoEngine::destinationMarkOn = false; + paintDestination(); + IsoEngine::unFocus = -1; + paintLoc(loc0); + nextUnit(unStartLoc, true); +} + +int MainScreen::doJob(int j0) +{ + using ClientTools::me; + TUn &un = ClientTools::myUn[IsoEngine::unFocus]; + IsoEngine::destinationMarkOn = false; + paintDestination(); + const int loc0 = un.Loc; + const int movement0 = un.Movement; + int result; + if (j0 < 0) // terrain enhancement + result = ClientTools::processEnhancement(IsoEngine::unFocus, myData->enhancementJobs); + else + result = ClientTools::server(sStartJob + (j0 << 4), me, IsoEngine::unFocus, nullptr); + if (result >= rExecuted) { + if (result == eDied) + IsoEngine::unFocus = -1; + paintLoc(loc0); + if (IsoEngine::unFocus >= 0) { + if (j0 < 0 && result != eJobDone) // multi-turn terrain enhancement + un.Status = (un.Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto)) + | IsoEngine::usEnhance; + else + un.Status &= 0xFFFF - IsoEngine::usStay - IsoEngine::usRecover - IsoEngine::usGoto - IsoEngine::usEnhance; + if (un.Job != jNone || movement0 < 100) { + un.Status &= ~usWaiting; + nextUnit(unStartLoc, true); + } else { + panelPaint(); + } + } else { + nextUnit(unStartLoc, true); + } + } + switch (result) { + case eNoBridgeBuilding: + soundMessage(phrases[QStringLiteral("NOBB")], QStringLiteral("INVALID")); + break; + case eNoCityTerrain: + soundMessage(phrases[QStringLiteral("NOCITY")], QStringLiteral("INVALID")); + break; + case eTreaty: + soundMessage(Tribes::tribe[static_cast((*ClientTools::myRO->Territory)[loc0])]->tPhrase( + QStringLiteral("PEACE_NOWORK")), + QStringLiteral("NOMOVE_TREATY")); + break; + default: + if (result < rExecuted) + Sound::play(QStringLiteral("INVALID")); + break; + } + return result; +} + +void MainScreen::focusNextUnit(int dir) +{ + if (clientMode >= scContact) + return; + const TPlayerContext &ro = *ClientTools::myRO; + IsoEngine::destinationMarkOn = false; + paintDestination(); + int newFocus = -1; + for (int i = 1; i <= ro.nUn; ++i) { + const int uix = (IsoEngine::unFocus + i * dir + ro.nUn) % ro.nUn; + if (ClientTools::myUn[uix].Loc >= 0 && (ClientTools::myUn[uix].Status & IsoEngine::usStay) == 0) { + newFocus = uix; + break; + } + } + if (newFocus >= 0) { + setUnFocus(newFocus); + setTroopLoc(ClientTools::myUn[newFocus].Loc); + focusOnLoc(m_troopLoc, flRepaintPanel); + } +} + +void MainScreen::setDebugMap(int p) +{ + m_mainMap->pDebugMap = p; + IsoEngine::mapOptions &= ~(1u << ClientTools::moLocCodes); + m_locCodesChecked = false; + m_mapValid = false; + mainOffscreenPaint(); +} + +void MainScreen::setViewpoint(int p) +{ + if (!(supervising && ClientTools::g.RO[0]->Turn > 0 && (p == 0 || ((1 << p) & ClientTools::g.RO[0]->Alive) != 0))) + return; + applyToVisibleForms(FormAction::Close); + ClientTools::itsMeAgain(p); + ClientTools::sumCities(taxSum, scienceSum); + for (int i = 0; i < ClientTools::myRO->nModel; ++i) { + if (!Tribes::tribe[static_cast(ClientTools::me)]->modelPictureAt(i).hGr) + initMyModel(i, true); + } + setTroopLoc(-1); + panelPaint(); + m_mapValid = false; + paintAllMaps(); +} + +void MainScreen::updateMusic() +{ + if (musicEnabled) { + musicPlayer.setVolume(musicVolume); + if (!musicPlayer.playing()) { + musicPlayer.loadPlaylistFromDir(getMusicDir()); + musicPlayer.randomizePlaylist(); + if (!musicPlayer.playlist.isEmpty()) + musicPlayer.play(); + } + } else if (musicPlayer.playing()) { + musicPlayer.stop(); + } +} + +void MainScreen::loadSettings() +{ + QSettings settings; + const auto tileSize = static_cast( + std::clamp(settings.value(QStringLiteral("TileSize"), static_cast(IsoEngine::TileSize::Medium)).toInt(), 0, 2)); + m_mainMap->setTileSize(tileSize); + m_noMap->setTileSize(tileSize); + m_noMapPanel->setTileSize(tileSize); + const ClientTools::SaveOptions defaultOptions = (1u << ClientTools::soEnMoves) | (1u << ClientTools::soSlowMoves) + | (1u << ClientTools::soNames) | (1u << ClientTools::soRepScreens) + | (1u << ClientTools::soSoundOn) | (1u << ClientTools::soScrollSlow) + | (1u << ClientTools::soAlSlowMoves); + optionChecked = settings.value(QStringLiteral("OptionChecked"), defaultOptions).toUInt(); + mapOptionChecked = settings.value(QStringLiteral("MapOptionChecked"), 1u << ClientTools::moCityNames).toUInt(); + cityRepMask = settings.value(QStringLiteral("CityReport"), + ~static_cast(chPopIncrease) & ~static_cast(chNoGrowthWarning) + & ~static_cast(chCaptured)).toUInt(); + if (!hasOption(ClientTools::soScrollFast) && !hasOption(ClientTools::soScrollSlow) && !hasOption(ClientTools::soScrollOff)) + optionChecked |= 1u << ClientTools::soScrollSlow; // old settings with no scrolling + if (hasOption(ClientTools::soSoundOff)) + Sound::mode = SoundMode::Off; + else if (hasOption(ClientTools::soSoundOnAlt)) + Sound::mode = SoundMode::OnAlt; + else + Sound::mode = SoundMode::On; +} + +void MainScreen::saveSettings() +{ + QSettings settings; + settings.setValue(QStringLiteral("TileSize"), static_cast(m_mainMap->tileSize())); + settings.setValue(QStringLiteral("OptionChecked"), optionChecked); + settings.setValue(QStringLiteral("MapOptionChecked"), mapOptionChecked); + settings.setValue(QStringLiteral("CityReport"), cityRepMask); + settings.sync(); +} + +} // namespace Term +} // namespace Cevo diff --git a/game/localplayer/Term.MainScreen.Menus.h b/game/localplayer/Term.MainScreen.Menus.h new file mode 100644 index 0000000..03fe338 --- /dev/null +++ b/game/localplayer/Term.MainScreen.Menus.h @@ -0,0 +1,83 @@ +// 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. + +#pragma once + +// Private definition of TMainScreen's popup menus (see Term.MainScreen.Menus.cpp). + +#include "Term.MainScreen.h" + +#include +#include + +#include +#include +#include + +namespace Cevo { +namespace Term { + +struct MainScreen::Menus { + QMenu *game = nullptr; + QMenu *unit = nullptr; + QMenu *stat = nullptr; + QMenu *terrain = nullptr; + QMenu *edit = nullptr; + QMenu *options = nullptr; + QMenu *ownMovement = nullptr; + QMenu *allyMovement = nullptr; + QMenu *enemyMovement = nullptr; + QMenu *rep = nullptr; + QMenu *scrolling = nullptr; + QMenu *tileSize = nullptr; + QMenu *sound = nullptr; + QMenu *music = nullptr; + QMenu *test = nullptr; + QMenu *manip = nullptr; + QMenu *macro = nullptr; + QMenu *viewpoint = nullptr; + QMenu *debugMap = nullptr; + QMenu *createUnit = nullptr; + QAction *waitTurn = nullptr; + QAction *repList = nullptr; + QAction *repScreens = nullptr; + QAction *locCodes = nullptr; + std::map action; + std::array manipItem{}; + std::array repItem{}; + QActionGroup *tileGroup = nullptr; + QActionGroup *soundGroup = nullptr; + QActionGroup *musicGroup = nullptr; + QAction *names = nullptr; + std::vector> optionItems; + + QAction *act(MenuCommand command) const { return action.at(command); } +}; + +} // namespace Term +} // namespace Cevo diff --git a/game/localplayer/Term.MainScreen.Move.cpp b/game/localplayer/Term.MainScreen.Move.cpp new file mode 100644 index 0000000..5a6a6ae --- /dev/null +++ b/game/localplayer/Term.MainScreen.Move.cpp @@ -0,0 +1,670 @@ +// TMainScreen.MoveUnit, MoveToLoc and MoveOnScreen (Term.pas): moving the +// focused unit, path finding and the unit move animation. +// +// The animation draws the moving unit into m_moveTile (a copy of the map +// rectangle it travels through), which paintEvent() puts on top of the map +// layer; the original blitted the same buffer directly onto the screen. + +#include "Term.MainScreen.h" + +#include "Cevo/CevoScreenTools.h" +#include "Cevo/CevoTexture.h" +#include "Global.h" +#include "Messg.h" +#include "Sound.h" + +#include +#include +#include + +#include + +namespace Cevo { +namespace Term { + +namespace { + +constexpr int MoveTime = 300; // time for moving a unit, in ms + +QString movementPhrase(int movement) +{ + return movementToString(movement); +} + +} // namespace + +int MainScreen::moveUnit(int dx, int dy, int options) +{ + using ClientTools::me; + using ClientTools::myCity; + using ClientTools::myMap; + using ClientTools::myModel; + using ClientTools::myRO; + using ClientTools::myUn; + using ClientTools::server; + const int lx = ClientTools::g.lx; + const int ly = ClientTools::g.ly; + + int result = eInvalid; + const int unFocus0 = IsoEngine::unFocus; + const int fromLoc = myUn[IsoEngine::unFocus].Loc; + const int toLoc = ClientTools::dLoc(fromLoc, dx, dy); + if (toLoc < 0 || toLoc >= lx * ly) + return eInvalid; + if (myMap[toLoc] & fStealthUnit) { + soundMessage(phrases[QStringLiteral("ATTACKSTEALTH")], QString()); + return result; + } + if (myMap[toLoc] & fHiddenUnit) { + soundMessage(phrases[QStringLiteral("ATTACKSUB")], QString()); + return result; + } + + int euix = -1; + if ((myMap[toLoc] & (fUnit | fOwned)) == static_cast(fUnit)) { // attack -- search enemy unit + const TUn &un = myUn[IsoEngine::unFocus]; + if (myModel[un.mix].Attack == 0 && !(myModel[un.mix].Cap[mcBombs] > 0 && (un.Flags & unBombsLoaded) != 0)) { + soundMessage(phrases[QStringLiteral("NOATTACKER")], QString()); + return result; + } + euix = myRO->nEnemyUn - 1; + while (euix >= 0 && (*myRO->EnemyUn)[euix].Loc != toLoc) + --euix; + } + + const int dirCode = ((dx & 7) << 4) + ((dy & 7) << 7); + result = server(sMoveUnit - sExecute + dirCode, me, IsoEngine::unFocus, nullptr); + if (result < rExecuted && myUn[IsoEngine::unFocus].Job > jNone) + server(sStartJob + (jNone << 4), me, IsoEngine::unFocus, nullptr); + if (result < rExecuted && result != eNoTime_Move) { + const TUn &un = myUn[IsoEngine::unFocus]; + switch (result) { + case eNoTime_Load: + if (myModel[un.mix].Domain == dAir) + soundMessage(phrases[QStringLiteral("NOTIMELOADAIR")], QStringLiteral("NOMOVE_TIME")); + else + soundMessage(formatPhrase(QStringLiteral("NOTIMELOADGROUND"), { movementPhrase(myModel[un.mix].Speed) }), + QStringLiteral("NOMOVE_TIME")); + break; + case eNoTime_Bombard: + soundMessage(phrases[QStringLiteral("NOTIMEBOMBARD")], QStringLiteral("NOMOVE_TIME")); + break; + case eNoTime_Expel: + soundMessage(phrases[QStringLiteral("NOTIMEEXPEL")], QStringLiteral("NOMOVE_TIME")); + break; + case eNoRoad: + soundMessage(phrases[QStringLiteral("NOROAD")], QStringLiteral("NOMOVE_DEFAULT")); + break; + case eNoNav: + soundMessage(phrases[QStringLiteral("NONAV")], QStringLiteral("NOMOVE_DEFAULT")); + break; + case eNoCapturer: + soundMessage(phrases[QStringLiteral("NOCAPTURER")], QStringLiteral("NOMOVE_DEFAULT")); + break; + case eNoBombarder: + soundMessage(phrases[QStringLiteral("NOBOMBARDER")], QStringLiteral("NOMOVE_DEFAULT")); + break; + case eZOC: + MessgEx::contextMessage(phrases[QStringLiteral("ZOC")], QStringLiteral("NOMOVE_ZOC"), + Help::LinkCategory::Text, helpDlg().textIndex(QStringLiteral("MOVEMENT"))); + break; + case eTreaty: + if ((myMap[toLoc] & (fUnit | fOwned)) != static_cast(fUnit)) // no enemy unit -- move + soundMessage(Tribes::tribe[static_cast((*myRO->Territory)[toLoc])]->tPhrase( + QStringLiteral("PEACE_NOMOVE")), + QStringLiteral("NOMOVE_TREATY")); + else + soundMessage(Tribes::tribe[static_cast((*myRO->EnemyUn)[euix].Owner)]->tPhrase( + QStringLiteral("PEACE_NOATTACK")), + QStringLiteral("NOMOVE_TREATY")); + break; + case eDomainMismatch: + if (myModel[un.mix].Domain < dSea && (myMap[toLoc] & (fUnit | fOwned)) == static_cast(fUnit | fOwned)) { + // false load attempt + bool toShip = false; + bool toTransport = false; + for (int uix = 0; uix < myRO->nUn; ++uix) { + if (myUn[uix].Loc == toLoc && myModel[myUn[uix].mix].Domain == dSea) { + toShip = true; + if (myModel[myUn[uix].mix].Cap[mcSeaTrans] > 0) + toTransport = true; + } + } + if (toTransport) + soundMessage(phrases[QStringLiteral("FULLTRANSPORT")], QStringLiteral("NOMOVE_DEFAULT")); + else if (toShip) + soundMessage(phrases[QStringLiteral("NOTRANSPORT")], QStringLiteral("NOMOVE_DEFAULT")); + else + Sound::play(QStringLiteral("NOMOVE_DOMAIN")); + } else { + Sound::play(QStringLiteral("NOMOVE_DOMAIN")); + } + break; + default: + Sound::play(QStringLiteral("NOMOVE_DEFAULT")); + break; + } + return result; + } + + if ((result == eWon || result == eLost || result == eBloody) && myUn[IsoEngine::unFocus].Movement < 100 + && myModel[myUn[IsoEngine::unFocus].mix].Cap[mcWill] == 0) { + if (MessgEx::simpleQuery(MessageKind::YesNo, + formatPhrase(QStringLiteral("FASTATTACK"), + { QString::number(myUn[IsoEngine::unFocus].Movement) }), + QStringLiteral("NOMOVE_TIME")) + != Dpi::ModalResult::Ok) + return eInvalid; + updateNow(); // remove message box from screen + } + + bool oldUnrest = false; + bool newUnrest = false; + if (result >= rExecuted && (result & rUnitRemoved) == 0 + && (myMap[toLoc] & (fUnit | fOwned)) != static_cast(fUnit)) { + oldUnrest = ClientTools::unrestAtLoc(IsoEngine::unFocus, fromLoc); + newUnrest = ClientTools::unrestAtLoc(IsoEngine::unFocus, toLoc); + if (newUnrest > oldUnrest) { + QString queryItem; + int p1; + if (myRO->Government == gDemocracy) { + queryItem = QStringLiteral("UNREST_NOTOWN"); + p1 = me; + } else { + queryItem = QStringLiteral("UNREST_FOREIGN"); + p1 = (*myRO->Territory)[toLoc]; + } + MessgEx::MessgExDlg &dlg = messgExDlg(); + dlg.messageText = Tribes::tribe[static_cast(p1)]->tPhrase(queryItem).arg( + phrases.lookup(QStringLiteral("GOVERNMENT"), myRO->Government)); + dlg.kind = MessageKind::YesNo; + dlg.iconKind = MessgEx::MessageIconKind::Imp; + dlg.iconIndex = imPalace; + if (dlg.showModal() != Dpi::ModalResult::Ok) + return eInvalid; + updateNow(); // remove message box from screen + } + } + + if (result >= rExecuted && myModel[myUn[IsoEngine::unFocus].mix].Domain == dAir + && (myUn[IsoEngine::unFocus].Status & usToldNoReturn) == 0) { // can plane return? + TPlaneReturnData planeReturnData; + planeReturnData.Fuel = myUn[IsoEngine::unFocus].Fuel; + if ((myMap[toLoc] & (fUnit | fOwned)) == static_cast(fUnit) + || (myMap[toLoc] & (fCity | fOwned)) == static_cast(fCity)) { + // attack/expel/bombard -> 100MP + planeReturnData.Loc = fromLoc; + planeReturnData.Movement = std::max(0, myUn[IsoEngine::unFocus].Movement - 100); + } else { // move + planeReturnData.Loc = toLoc; + planeReturnData.Movement = myUn[IsoEngine::unFocus].Movement - ((dx & 1) != 0 ? 100 : 150); + } + if (server(sGetPlaneReturn, me, IsoEngine::unFocus, &planeReturnData) == eNoWay) { + const QString queryItem = myModel[myUn[IsoEngine::unFocus].mix].Kind == mkSpecial_Glider + ? QStringLiteral("LOWFUEL_GLIDER") + : QStringLiteral("LOWFUEL"); + if (MessgEx::simpleQuery(MessageKind::YesNo, phrases[queryItem], QStringLiteral("WARNING_LOWSUPPORT")) + != Dpi::ModalResult::Ok) + return eInvalid; + updateNow(); // remove message box from screen + myUn[IsoEngine::unFocus].Status |= usToldNoReturn; + } + } + + int mission = -1; + if (result == eMissionDone) { + modalSelectDlg().showNewContent(WindowMode::Modal, Select::ListKind::Mission); + updateNow(); // dialog still on screen + mission = modalSelectDlg().result; + if (mission < 0) + return result; + server(sSetSpyMission + (mission << 4), me, 0, nullptr); + } + + bool cityCaptured = false; + bool needEcoUpdate = false; + bool needRepaintPanel = false; + bool isAttack = false; + if (result == eNoTime_Move) { + Sound::play(QStringLiteral("NOMOVE_TIME")); + } else { + IsoEngine::destinationMarkOn = false; + paintDestination(); + if ((result & rUnitRemoved) != 0) + ClientTools::cityOptimizer_BeforeRemoveUnit(IsoEngine::unFocus); + isAttack = result == eBombarded + || (result != eMissionDone && (myMap[toLoc] & (fUnit | fOwned)) == static_cast(fUnit)); + if (!isAttack) { // move + int cix = myRO->nCity - 1; // look for own city at dest location + while (cix >= 0 && myCity[cix].Loc != toLoc) + --cix; + if (result != eMissionDone && (myMap[toLoc] & fCity) != 0 && cix < 0) + cityCaptured = true; + result = server(sMoveUnit + dirCode, me, IsoEngine::unFocus, nullptr); + if (result == eHiddenUnit) { + Sound::play(QStringLiteral("NOMOVE_SUBMARINE")); + paintLoc(toLoc); + } else if (result == eStealthUnit) { + Sound::play(QStringLiteral("NOMOVE_STEALTH")); + paintLoc(toLoc); + } else if (result == eZOC_EnemySpotted) { + Sound::play(QStringLiteral("NOMOVE_ZOC")); + paintLoc(toLoc, 1); + } else if (result >= rExecuted) { + if ((result & rUnitRemoved) != 0) { + IsoEngine::unFocus = -1; // unit died + } else { + Q_ASSERT(IsoEngine::unFocus >= 0); + TUn &un = myUn[IsoEngine::unFocus]; + un.Status &= ~(IsoEngine::usStay | IsoEngine::usRecover); + for (int uix = 0; uix < myRO->nUn; ++uix) { + if (myUn[uix].Master == IsoEngine::unFocus) + myUn[uix].Status &= ~usWaiting; + } + const bool democratic = + myRO->Government == gRepublic || myRO->Government == gDemocracy || myRO->Government == gFuture; + if (cityCaptured && democratic) { + // borders have moved, unrest might have changed in any city + ClientTools::cityOptimizer_BeginOfTurn(); + needEcoUpdate = true; + } else { + if (oldUnrest != newUnrest) { + ClientTools::cityOptimizer_CityChange(un.Home); + for (int uix = 0; uix < myRO->nUn; ++uix) { + if (myUn[uix].Master == IsoEngine::unFocus) + ClientTools::cityOptimizer_CityChange(myUn[uix].Home); + } + needEcoUpdate = true; + } + if (myRO->Government == gDespotism && myModel[un.mix].Kind == mkSpecial_TownGuard) { + const auto reoptimizeCityAt = [&](int loc) { + int cixChanged = myRO->nCity - 1; + while (cixChanged >= 0 && myCity[cixChanged].Loc != loc) + --cixChanged; + Q_ASSERT(cixChanged >= 0); + if (cixChanged >= 0) { + ClientTools::cityOptimizer_CityChange(cixChanged); + needEcoUpdate = true; + } + }; + // town guard moved out of / into a city in despotism -- reoptimize! + if ((myMap[fromLoc] & fCity) != 0) + reoptimizeCityAt(fromLoc); + if ((myMap[toLoc] & fCity) != 0 && !cityCaptured) + reoptimizeCityAt(toLoc); + } + } + } + } else { + Q_ASSERT(false); + } + setTroopLoc(toLoc); + } else { // enemy unit -- attack + int defender; + if (result == eBombarded) + defender = (*myRO->Territory)[toLoc]; + else + defender = (*myRO->EnemyUn)[euix].Owner; + if ((options & muNoSuicideCheck) == 0 && (result & rUnitRemoved) != 0 && result != eMissionDone) { + // suicide query + Battle::BattleDlg &battle = battleDlg(); + const TUn &un = myUn[IsoEngine::unFocus]; + battle.forecast.pAtt = me; + battle.forecast.mixAtt = un.mix; + battle.forecast.HealthAtt = un.Health; + battle.forecast.ExpAtt = un.Exp; + battle.forecast.FlagsAtt = static_cast(un.Flags); + battle.forecast.Movement = un.Movement; + server(sGetBattleForecastEx, me, toLoc, &battle.forecast); + battle.uix = IsoEngine::unFocus; + battle.toLoc = toLoc; + battle.isSuicideQuery = true; + if (battle.showModal() != Dpi::ModalResult::Ok) + return result; + } + + int cixChanged = -1; + if ((result & rUnitRemoved) != 0 && myRO->Government == gDespotism + && myModel[myUn[IsoEngine::unFocus].mix].Kind == mkSpecial_TownGuard && (myMap[fromLoc] & fCity) != 0) { + // town guard died in city in despotism -- reoptimize! + cixChanged = myRO->nCity - 1; + while (cixChanged >= 0 && myCity[cixChanged].Loc != fromLoc) + --cixChanged; + Q_ASSERT(cixChanged >= 0); + } + + for (int i = 0; i < myRO->nEnemyModel; ++i) + lostArmy[static_cast(i)] = (*myRO->EnemyModel)[i].Lost; + const std::uint32_t oldToTile = myMap[toLoc]; + result = server(sMoveUnit + dirCode, me, IsoEngine::unFocus, nullptr); + nLostArmy = 0; + for (int i = 0; i < myRO->nEnemyModel; ++i) { + lostArmy[static_cast(i)] = (*myRO->EnemyModel)[i].Lost - lostArmy[static_cast(i)]; + nLostArmy += lostArmy[static_cast(i)]; + } + if ((result & rUnitRemoved) != 0) { + IsoEngine::unFocus = -1; + setTroopLoc(fromLoc); + } + const bool democratic = + myRO->Government == gRepublic || myRO->Government == gDemocracy || myRO->Government == gFuture; + if ((oldToTile & ~myMap[toLoc] & fCity) != 0 && democratic) { + // city was destroyed, borders have moved, unrest might have changed in any city + ClientTools::cityOptimizer_BeginOfTurn(); + needEcoUpdate = true; + } else { + if (cixChanged >= 0) { + ClientTools::cityOptimizer_CityChange(cixChanged); + needEcoUpdate = true; + } + if (result == eWon || result == eBloody || result == eExpelled) { + ClientTools::cityOptimizer_TileBecomesAvailable(toLoc); + needEcoUpdate = true; + } + } + if (nLostArmy > 1) { + MessgEx::MessgExDlg &dlg = messgExDlg(); + dlg.kind = MessageKind::Ok; + dlg.iconKind = MessgEx::MessageIconKind::EnemyArmy; + dlg.messageText = Tribes::tribe[static_cast(defender)]->tString( + phraseToQtFormat(phrases.lookup(QStringLiteral("ARMYLOST"), + (*myRO->EnemyModel)[(*myRO->EnemyUn)[euix].emix].Domain))); + dlg.showModal(); + } + } + if ((result & rUnitRemoved) != 0) { + ClientTools::cityOptimizer_AfterRemoveUnit(); + listDlg().removeUnit(); + needEcoUpdate = true; + } + if (needEcoUpdate) { + updateViews(true); + updateNow(); + } + } + + if (result == eMissionDone) { + const int p1 = (*myRO->Territory)[toLoc]; + switch (mission) { + case smStealMap: + m_mapValid = false; + paintAllMaps(); + break; + case smStealCivilReport: + MessgEx::tribeMessage(p1, Tribes::tribe[static_cast(p1)]->tPhrase(QStringLiteral("DOSSIER_PREPARED")), + QString()); + break; + case smStealMilReport: + listDlg().showNewContentMilReport(WindowMode::Persistent, p1); + break; + default: + break; + } + } + + if (IsoEngine::unFocus >= 0) + checkToldNoReturn(IsoEngine::unFocus); + + if (result >= rExecuted) { + if (cityCaptured && (myMap[toLoc] & fCity) == 0) { // city destroyed + for (int i = 0; i < nWonder; ++i) { // tell about destroyed wonders + if (myRO->Wonder[i].CityID == WonderDestroyed && myData->toldWonders[static_cast(i)].CityID != WonderDestroyed) { + MessgEx::MessgExDlg &dlg = messgExDlg(); + if (m_wondersDlg && m_wondersDlg->isVisible()) + m_wondersDlg->smartUpdateContent(false); + dlg.openSound = QStringLiteral("WONDER_DESTROYED"); + dlg.messageText = formatPhrase(QStringLiteral("WONDERDEST"), + { phrases.lookup(QStringLiteral("IMPROVEMENTS"), i) }); + dlg.kind = MessageKind::OkHelp; + dlg.helpKind = Help::LinkCategory::Imp; + dlg.helpNo = i; + dlg.iconKind = MessgEx::MessageIconKind::Imp; + dlg.iconIndex = i; + dlg.showModal(); + std::memcpy(&myData->toldWonders[static_cast(i)], &myRO->Wonder[i], sizeof(myRO->Wonder[i])); + } + } + } + if (cityCaptured && (myMap[toLoc] & fCity) != 0) { // city captured + listDlg().addCity(); + for (int i = 0; i < nWonder; ++i) { // tell about capture of wonders + if (myCity[myRO->nCity - 1].Built[i] > 0) { + MessgEx::MessgExDlg &dlg = messgExDlg(); + if (m_wondersDlg && m_wondersDlg->isVisible()) + m_wondersDlg->smartUpdateContent(false); + dlg.openSound = QStringLiteral("WONDER_CAPTURED"); + dlg.messageText = Tribes::tribe[static_cast(me)]->tPhrase(QStringLiteral("WONDERCAPTOWN")) + .arg(phrases.lookup(QStringLiteral("IMPROVEMENTS"), i)); + dlg.kind = MessageKind::OkHelp; + dlg.helpKind = Help::LinkCategory::Imp; + dlg.helpNo = i; + dlg.iconKind = MessgEx::MessageIconKind::Imp; + dlg.iconIndex = i; + dlg.showModal(); + } + } + + if ((myRO->Happened & phStealTech) != 0) { // Temple of Zeus -- choose advance to steal + modalSelectDlg().showNewContent(WindowMode::Modal, Select::ListKind::StealTech); + server(sStealTech, me, modalSelectDlg().result, nullptr); + } + tellNewModels(); + + int cix = myRO->nCity - 1; + while (cix >= 0 && myCity[cix].Loc != toLoc) + --cix; + Q_ASSERT(cix >= 0); + myCity[cix].Status = (myCity[cix].Status & ~csResourceWeightsMask) | (3 << 4); + // captured city, set to maximum growth + int newTiles = 1 << 13; // exploit central tile only + server(sSetCityTiles, me, cix, &newTiles); + } else { + needRepaintPanel = true; + } + } + tellNewContacts(); + + if (IsoEngine::unFocus >= 0 && myUn[IsoEngine::unFocus].Master >= 0) { + TUn &master = myUn[myUn[IsoEngine::unFocus].Master]; + if ((master.Status & IsoEngine::usStay) != 0) { + master.Status &= ~IsoEngine::usStay; + if (master.Movement >= 100 && (master.Status & (IsoEngine::usRecover | IsoEngine::usGoto)) == 0) + master.Status |= usWaiting; + } + } + if ((options & (muAutoNoWait | muAutoNext)) != 0) { + if (IsoEngine::unFocus >= 0 + && (result == eNoTime_Move || ClientTools::unitExhausted(IsoEngine::unFocus) + || myUn[IsoEngine::unFocus].Master >= 0 + || (myModel[myUn[IsoEngine::unFocus].mix].Domain == dAir + && ((myMap[myUn[IsoEngine::unFocus].Loc] & fCity) != 0 + || (myMap[myUn[IsoEngine::unFocus].Loc] & fTerImp) == static_cast(tiBase))))) { + // aircrafts stop in cities + myUn[IsoEngine::unFocus].Status &= ~usWaiting; + if ((options & muAutoNext) != 0) { + if (cityCaptured && (myMap[toLoc] & fCity) != 0) { + IsoEngine::unFocus = -1; + paintLoc(toLoc); // don't show unit in city if not selected + } else { + nextUnit(unStartLoc, true); + } + } + } else if (IsoEngine::unFocus < 0 && (options & muAutoNext) != 0) { + nextUnit(unStartLoc, result != eMissionDone); + } + } + + if (needRepaintPanel && IsoEngine::unFocus == unFocus0) { + if (isAttack) { + panelPaint(); + } else { + Q_ASSERT(result != eMissionDone); + checkTerrainBtnVisible(); + focusOnLoc(toLoc, flRepaintPanel | flImmUpdate); + } + } + + if (result >= rExecuted && cityCaptured && (myMap[toLoc] & fCity) != 0) + zoomToCity(toLoc, IsoEngine::unFocus < 0, chCaptured); // show captured city + return result; +} + +void MainScreen::moveToLoc(int loc, bool checkSuicide) +{ + using ClientTools::myMap; + using ClientTools::myRO; + using ClientTools::myUn; + enum class StopReason { None, Arrived, Dead, NoTime, EnemySpotted, MoveError }; + + if (myUn[IsoEngine::unFocus].Job > jNone) + ClientTools::server(sStartJob + (jNone << 4), ClientTools::me, IsoEngine::unFocus, nullptr); + TMoveAdviceData moveAdviceData; + if (ClientTools::getMoveAdvice(IsoEngine::unFocus, loc, moveAdviceData) < rExecuted) + return; + const int uix = IsoEngine::unFocus; + StopReason stopReason = StopReason::None; + for (;;) { + for (int i = 0; i < moveAdviceData.nStep; ++i) { + int moveOptions = i == moveAdviceData.nStep - 1 ? muAutoNext : 0; + const int nextLoc = ClientTools::dLoc(myUn[uix].Loc, moveAdviceData.dx[i], moveAdviceData.dy[i]); + if (nextLoc == loc || (loc == maNextCity && (myMap[nextLoc] & fCity) != 0)) + stopReason = StopReason::Arrived; + if (!checkSuicide && nextLoc == loc) + moveOptions |= muNoSuicideCheck; + const int moveResult = moveUnit(moveAdviceData.dx[i], moveAdviceData.dy[i], moveOptions); + if (moveResult < rExecuted) + stopReason = StopReason::MoveError; + else if ((moveResult & rUnitRemoved) != 0) + stopReason = StopReason::Dead; + else if (stopReason == StopReason::None && (moveResult & rEnemySpotted) != 0) + stopReason = StopReason::EnemySpotted; + if (stopReason != StopReason::None) + break; + } + if (stopReason == StopReason::None && (moveAdviceData.nStep < 25 || myRO->Wonder[woShinkansen].EffectiveOwner != ClientTools::me)) + stopReason = StopReason::NoTime; + if (stopReason != StopReason::None) + break; + if (ClientTools::getMoveAdvice(IsoEngine::unFocus, loc, moveAdviceData) < rExecuted) { + Q_ASSERT(false); + break; + } + } + + switch (stopReason) { + case StopReason::None: + Q_ASSERT(false); + break; + case StopReason::Arrived: + myUn[uix].Status &= 0xFFFF - IsoEngine::usGoto; + break; + case StopReason::Dead: + if (IsoEngine::unFocus < 0) + nextUnit(unStartLoc, false); + break; + default: // multi-turn goto + myUn[uix].Status = (myUn[uix].Status & (0xFFFF - IsoEngine::usStay - IsoEngine::usRecover)) | IsoEngine::usGoto + | ((loc == maNextCity ? 0x7FFF : loc) << 16); + paintLoc(myUn[uix].Loc); + if (stopReason == StopReason::NoTime && IsoEngine::unFocus == uix) { + myUn[uix].Status &= ~usWaiting; + nextUnit(unStartLoc, true); + } + break; + } +} + +void MainScreen::moveOnScreen(const TShowMove &showMove, int step0, int step1, int nStep, bool restore) +{ + const int lx = ClientTools::g.lx; + const int xxt = m_mainMap->xxt; + const int yyt = m_mainMap->yyt; + m_timer->stop(); + + TUnitInfo unitInfo{}; + unitInfo.Owner = static_cast(showMove.Owner); + unitInfo.mix = static_cast(showMove.mix); + unitInfo.Health = static_cast(showMove.Health); + unitInfo.Job = jNone; + unitInfo.Flags = static_cast(showMove.Flags); + if (showMove.Owner != ClientTools::me) + unitInfo.emix = static_cast(showMove.emix); + + const int toLoc = ClientTools::dLoc(showMove.FromLoc, showMove.dx, showMove.dy); + int xToLoc = toLoc % lx; + const int yToLoc = toLoc / lx; + const int xFromLoc = showMove.FromLoc % lx; + const int yFromLoc = showMove.FromLoc / lx; + if (xToLoc > xFromLoc + 2) + xToLoc -= lx; + else if (xToLoc < xFromLoc - 2) + xToLoc += lx; + + int xw1 = m_xw + lx; + // ((xFromLoc-xw1)*2+yFromLoc and 1+1)*xxt+dx*xxt/2-MapWidth/2 -> min + while (std::abs(((xFromLoc - xw1 + lx) * 2 + (yFromLoc & 1) + 1) * xxt * 2 + showMove.dx * xxt - m_mapWidth) + < std::abs(((xFromLoc - xw1) * 2 + (yFromLoc & 1) + 1) * xxt * 2 + showMove.dx * xxt - m_mapWidth)) + xw1 -= lx; + + const int xTo = (xToLoc - xw1) * (xxt * 2) + (yToLoc & 1) * xxt + (xxt - IsoEngine::xxu); + const int yTo = (yToLoc - m_yw) * yyt + (yyt - IsoEngine::yyuAnchor); + const int xFrom = (xFromLoc - xw1) * (xxt * 2) + (yFromLoc & 1) * xxt + (xxt - IsoEngine::xxu); + const int yFrom = (yFromLoc - m_yw) * yyt + (yyt - IsoEngine::yyuAnchor); + const int xMin = std::min(xFrom, xTo); + const int yMin = std::min(yFrom, yTo); + const int xRange = std::abs(xTo - xFrom) + xxt * 2; + const int yRange = std::abs(yTo - yFrom) + yyt * 3; + + mainOffscreenPaint(); + if (m_moveTile.width() != xRange || m_moveTile.height() != yRange) + m_moveTile.setSize(xRange, yRange); + m_noMap->setOutput(&m_moveTile); + m_noMap->setPaintBounds(0, 0, xRange, yRange); + m_moveTilePos = QPoint(xMin, yMin); + const QRect area(xMin, yMin, xRange, yRange); + const int steps = std::abs(step1 - step0); + QElapsedTimer clock; + for (int step = 0; step <= steps; ++step) { + // the map rectangle the unit moves through, then the unit on top + m_moveTile.image() = m_offscreen.image().copy(area).convertToFormat(QImage::Format_ARGB32); + m_moveTile.canvas().setDevice(&m_moveTile.image()); + int xMoving = xFrom; + int yMoving = yFrom; + if (step1 != step0) { + const int pos = step0 + step * (step1 - step0) / std::abs(step1 - step0); + xMoving = xFrom + static_cast(std::lround(pos * static_cast(xTo - xFrom) / nStep)); + yMoving = yFrom + static_cast(std::lround(pos * static_cast(yTo - yFrom) / nStep)); + } + m_noMap->paintUnit(xMoving - xMin, yMoving - yMin, unitInfo, 0); + m_moveTile.canvas().end(); + m_moveTileValid = true; + invalidateRect(m_mapOffset + xMin, TopBarHeight + yMin, m_mapOffset + xMin + xRange, TopBarHeight + yMin + yRange); + updateNow(); + + // wait for MoveTime/12 ms per step, keeping the application responsive + clock.start(); + const qint64 stepTime = MoveTime / 12; + do { + if (!m_idle || gameMode == cMovie) + processEventsWithDisabledKeyboard(); + QThread::msleep(1); + } while (clock.elapsed() < stepTime); + } + if (restore) { + m_moveTileValid = false; + invalidateRect(m_mapOffset + xMin, TopBarHeight + yMin, m_mapOffset + xMin + xRange, TopBarHeight + yMin + yRange); + updateNow(); + } + m_blinkTime = -1; + m_timer->start(); +} + +void MainScreen::processEventsWithDisabledKeyboard() +{ + m_keyboardDisabled = true; + QCoreApplication::processEvents(); + m_keyboardDisabled = false; +} + +} // namespace Term +} // namespace Cevo diff --git a/game/localplayer/Term.MainScreen.Show.cpp b/game/localplayer/Term.MainScreen.Show.cpp new file mode 100644 index 0000000..b8641de --- /dev/null +++ b/game/localplayer/Term.MainScreen.Show.cpp @@ -0,0 +1,316 @@ +// TMainScreen.Client() branches that show what happens on the map +// (Term.pas): cShowUnitChanged/CityChanged/AfterMove/AfterAttack, +// cShowMoving/cShowCapturing, cShowAttacking and cRefreshDebugMap. + +#include "Term.MainScreen.h" + +#include "Cevo/CevoScreenTools.h" +#include "Cevo/CevoTexture.h" +#include "Global.h" +#include "Messg.h" +#include "Sound.h" + +#include + +namespace Cevo { +namespace Term { + +namespace { + +constexpr int MoveTime = 300; +constexpr int WaitAfterShowMove = 32; + +bool option(ClientTools::SaveOption so) +{ + return ClientTools::hasSaveOption(optionChecked, so); +} + +} // namespace + +void MainScreen::clientShow(int command, int newPlayer, void *data) +{ + using ClientTools::me; + using ClientTools::myCity; + using ClientTools::myMap; + using ClientTools::myModel; + using ClientTools::myRO; + const int lx = ClientTools::g.lx; + const bool movieFast = gameMode == cMovie && m_movieSpeed == 4; + const auto intData = [data] { return *static_cast(data); }; + CurrentMoveInfo &info = m_currentMoveInfo; + + if (command == cRefreshDebugMap) { + if (intData() == m_mainMap->pDebugMap) { + m_mapValid = false; + mainOffscreenPaint(); + updateNow(); + } + return; + } + + if (command == cShowUnitChanged || command == cShowCityChanged || command == cShowAfterMove + || command == cShowAfterAttack) { + if (!((m_idle && newPlayer == me) || (!m_idle && !m_skipped)) || movieFast) + return; + Q_ASSERT(newPlayer == me); + if (!m_idle || gameMode == cMovie) + QCoreApplication::processEvents(); + if (command == cShowCityChanged) { + if (m_idle) + info.doShow = true; + else if (info.isAlly) + info.doShow = !option(ClientTools::soAlNoMoves); + else + info.doShow = !option(ClientTools::soEnNoMoves); + } else if (command == cShowUnitChanged) { + if (m_idle) + info.doShow = !option(ClientTools::soEffectiveMovesOnly); + else if (info.isAlly) + info.doShow = !(option(ClientTools::soAlNoMoves) || option(ClientTools::soAlEffectiveMovesOnly)); + else + info.doShow = !(option(ClientTools::soEnNoMoves) || option(ClientTools::soEnAttacks)); + } // else keep doShow from cShowMove/cShowAttack + + if (info.doShow) { + if (command == cShowCityChanged) + m_mapValid = false; + focusOnLoc(intData(), flImmUpdate); + if (command == cShowAfterMove) + paintLoc(intData(), info.afterMovePaintRadius); // show discovered areas + else + paintLoc(intData(), 1); + if (command == cShowAfterAttack && info.afterAttackExpeller >= 0) { + MessgEx::soundMessageEx(Tribes::tribe[static_cast(info.afterAttackExpeller)]->tPhrase( + QStringLiteral("EXPEL")), + QString()); + info.afterAttackExpeller = -1; + updateNow(); // remove message box from screen + } else if (!m_idle) { + if (command == cShowCityChanged) + QThread::msleep(static_cast(MoveTime * WaitAfterShowMove / 16)); + else if (command == cShowUnitChanged && (myMap[intData()] & fUnit) != 0) + QThread::msleep(static_cast(MoveTime * WaitAfterShowMove / 32)); + } + } else { + m_mapValid = false; + } + return; + } + + auto &showMove = *static_cast(data); + if (command == cShowMoving || command == cShowCapturing) { + if (!((m_idle && newPlayer == me) || (!m_idle && !m_skipped && showMove.emix != 0xFFFF)) || movieFast) + return; + Q_ASSERT(newPlayer == me); + if (!m_idle || gameMode == cMovie) + QCoreApplication::processEvents(); + info.doShow = false; + if (!m_idle && !Tribes::tribe[static_cast(showMove.Owner)]->modelPictureAt(showMove.mix).hGr) + initEnemyModel(showMove.emix); + + const int toLoc = ClientTools::dLoc(showMove.FromLoc, showMove.dx, showMove.dy); + int animationSpeed = 16; + int showMoveDomain = dGround; + bool isAlpine = false; + const auto movieSpeedAnimation = [this]() { + if (m_movieSpeed == 3) + return 4; + if (m_movieSpeed == 2) + return 8; + return 16; + }; + if (m_idle) { // own unit -- make discovered land visible + Q_ASSERT(showMove.Owner == me); // no foreign moves during my turn! + info.doShow = !option(ClientTools::soEffectiveMovesOnly) || command == cShowCapturing; + if (info.doShow) { + if (gameMode == cMovie) + animationSpeed = movieSpeedAnimation(); + else if (option(ClientTools::soVeryFastMoves)) + animationSpeed = 4; + else if (option(ClientTools::soFastMoves)) + animationSpeed = 8; + else + animationSpeed = 16; + const TModel &model = myModel[showMove.mix]; + if (model.Kind == mkDiplomat || model.Domain == dAir + || model.Cap[mcRadar] + model.Cap[mcCarrier] + model.Cap[mcAcademy] > 0 + || (myMap[toLoc] & fTerrain) == static_cast(fMountains) + || (myMap[toLoc] & fTerImp) == static_cast(tiFort) + || (myMap[toLoc] & fTerImp) == static_cast(tiBase)) + info.afterMovePaintRadius = 2; + else + info.afterMovePaintRadius = 1; + if (myRO->Wonder[woShinkansen].EffectiveOwner == me && model.Domain == dGround + && (myMap[showMove.FromLoc] & (fRR | fCity)) != 0 && (myMap[toLoc] & (fRR | fCity)) != 0 + && (showMove.Flags & umPlaneUnloading) == 0) + animationSpeed = 4; + showMoveDomain = model.Domain; + isAlpine = model.Cap[mcAlpine] > 0; + } + } else { + info.isAlly = myRO->Treaty[showMove.Owner] == trAlliance; + if (gameMode == cMovie) + info.doShow = true; + else if (info.isAlly) + info.doShow = !option(ClientTools::soAlNoMoves) + && !(option(ClientTools::soAlEffectiveMovesOnly) && command != cShowCapturing); + else + info.doShow = !option(ClientTools::soEnNoMoves) + && !(option(ClientTools::soEnAttacks) && command != cShowCapturing); + if (info.doShow) { + const TModelInfo &emodel = (*myRO->EnemyModel)[showMove.emix]; + if (command == cShowCapturing) { // show capture message + QString cityName; + if ((myMap[toLoc] & fOwned) != 0) { // own city, search + int cix = myRO->nCity - 1; + while (cix >= 0 && myCity[cix].Loc != toLoc) + --cix; + cityName = Tribes::cityName(myCity[cix].ID); + } else { // foreign city, search + int ecix = myRO->nEnemyCity - 1; + while (ecix >= 0 && (*myRO->EnemyCity)[ecix].Loc != toLoc) + --ecix; + cityName = Tribes::cityName((*myRO->EnemyCity)[ecix].ID); + } + MessgEx::tribeMessage(showMove.Owner, + Tribes::tribe[static_cast(showMove.Owner)]->tPhrase( + QStringLiteral("CAPTURE")).arg(cityName), + QString()); + updateNow(); // remove message box from screen + } + + if (info.isAlly) { // allied unit -- make discovered land visible + animationSpeed = option(ClientTools::soAlFastMoves) ? 8 : 16; + if (emodel.Kind == mkDiplomat || emodel.Domain == dAir || emodel.ATrans_Fuel > 0 + || (emodel.Cap & ((1u << (mcRadar - mcFirstNonCap)) | (1u << (mcAcademy - mcFirstNonCap)))) != 0 + || (myMap[toLoc] & fTerrain) == static_cast(fMountains) + || (myMap[toLoc] & fTerImp) == static_cast(tiFort) + || (myMap[toLoc] & fTerImp) == static_cast(tiBase)) + info.afterMovePaintRadius = 2; + else + info.afterMovePaintRadius = 1; + } else { + animationSpeed = option(ClientTools::soEnFastMoves) ? 8 : 16; + info.afterMovePaintRadius = 0; // enemy unit, nothing discovered + } + if (gameMode == cMovie) + animationSpeed = movieSpeedAnimation(); + showMoveDomain = emodel.Domain; + isAlpine = (emodel.Cap & (1u << (mcAlpine - mcFirstNonCap))) != 0; + } + } + + if (info.doShow) { + using Sound::play; + const int flags = showMove.Flags; + if (command == cShowCapturing) + play(QStringLiteral("MOVE_CAPTURE")); + else if (showMove.EndHealth <= 0) + play(QStringLiteral("MOVE_DIE")); + else if (flags & umSpyMission) + play(QStringLiteral("MOVE_COVERT")); + else if (flags & umShipLoading) + play(showMoveDomain == dAir ? QStringLiteral("MOVE_PLANELANDING") : QStringLiteral("MOVE_LOAD")); + else if (flags & umPlaneLoading) + play(QStringLiteral("MOVE_LOAD")); + else if (flags & umShipUnloading) + play(showMoveDomain == dAir ? QStringLiteral("MOVE_PLANESTART") : QStringLiteral("MOVE_UNLOAD")); + else if (flags & umPlaneUnloading) + play((myMap[showMove.FromLoc] & fCity) == 0 + && (myMap[showMove.FromLoc] & fTerImp) != static_cast(tiBase) + ? QStringLiteral("MOVE_PARACHUTE") + : QStringLiteral("MOVE_UNLOAD")); + else if (showMoveDomain == dGround && !isAlpine + && (myMap[toLoc] & fTerrain) == static_cast(fMountains) + && ((myMap[showMove.FromLoc] & (fRoad | fRR | fCity)) == 0 + || (myMap[toLoc] & (fRoad | fRR | fCity)) == 0)) + play(QStringLiteral("MOVE_MOUNTAIN")); + + focusOnLoc(showMove.FromLoc, flImmUpdate); + paintLocBeforeMove(showMove.FromLoc); + if (command == cShowCapturing) + moveOnScreen(showMove, 1, 32, 32); + else + moveOnScreen(showMove, 1, animationSpeed, animationSpeed); + } else { + m_mapValid = false; + } + Q_UNUSED(lx); + return; + } + + if (command == cShowAttacking) { + if (!((m_idle && newPlayer == me) || (!m_idle && !m_skipped && showMove.emix != 0xFFFF)) || movieFast) + return; + Q_ASSERT(newPlayer == me); + if (!m_idle || gameMode == cMovie) + QCoreApplication::processEvents(); + info.afterAttackExpeller = -1; + info.doShow = false; + if (m_idle) { + info.doShow = true; // own unit -- always show attacks + } else { + info.isAlly = myRO->Treaty[showMove.Owner] == trAlliance; + info.doShow = info.isAlly ? !option(ClientTools::soAlNoMoves) : !option(ClientTools::soEnNoMoves); + } + if (!info.doShow) { + m_mapValid = false; + return; + } + const int toLoc = ClientTools::dLoc(showMove.FromLoc, showMove.dx, showMove.dy); + if (!Tribes::tribe[static_cast(showMove.Owner)]->modelPictureAt(showMove.mix).hGr) + initEnemyModel(showMove.emix); + + if ((myMap[toLoc] & (fCity | fUnit | fOwned)) == static_cast(fCity | fOwned)) { + // tell about bombardment + int cix = myRO->nCity - 1; + while (cix >= 0 && myCity[cix].Loc != toLoc) + --cix; + if ((myCity[cix].Status & csToldBombard) == 0) { + if (!supervising) + myCity[cix].Status |= csToldBombard; + MessgEx::soundMessageEx(Tribes::tribe[static_cast(showMove.Owner)]->tPhrase( + QStringLiteral("BOMBARD")).arg(Tribes::cityName(myCity[cix].ID)), + QString()); + updateNow(); // remove message box from screen + } + } else if (showMove.Flags & umExpelling) { + info.afterAttackExpeller = showMove.Owner; + } + + if (showMove.Flags & umExpelling) { + Sound::play(QStringLiteral("MOVE_EXPEL")); + } else if (showMove.Owner == me) { + TModelInfo mi{}; + MakeModelInfo(me, showMove.mix, myModel[showMove.mix], mi); + Sound::play(attackSound(Tribes::modelCode(mi))); + } else { + Sound::play(attackSound(Tribes::modelCode((*myRO->EnemyModel)[showMove.emix]))); + } + + focusOnLoc(showMove.FromLoc, flImmUpdate); + + // before combat + m_mainMap->attackBegin(showMove); + if ((myMap[toLoc] & fCity) != 0) + paintLoc(toLoc); + paintLoc(showMove.FromLoc); + moveOnScreen(showMove, 1, 9, 16); + moveOnScreen(showMove, 17, 12, 32); + moveOnScreen(showMove, 7, 11, 16); + + // after combat + m_mainMap->attackEffect(showMove); + paintLoc(toLoc); + if (showMove.EndHealth > 0) { + showMove.Health = showMove.EndHealth; + moveOnScreen(showMove, 10, 0, 16); + } else if (!m_idle) { + QThread::msleep(static_cast(MoveTime / 2)); + } + m_mainMap->attackEnd(); + } +} + +} // namespace Term +} // namespace Cevo diff --git a/game/localplayer/Term.MainScreen.Turn.cpp b/game/localplayer/Term.MainScreen.Turn.cpp index 63afd34..24ae55d 100644 --- a/game/localplayer/Term.MainScreen.Turn.cpp +++ b/game/localplayer/Term.MainScreen.Turn.cpp @@ -13,6 +13,7 @@ #include "Cevo/CevoTexture.h" #include "Global.h" #include "Messg.h" +#include "Sound.h" #include #include @@ -141,7 +142,7 @@ void MainScreen::initTurn(int newPlayer) MainTexture->setAge(-1); m_eot->setButtonIndex(clientMode == cMovieTurn ? eotCancel : eotBlinkOn); } - // TODO: InitCityMark(MainTexture) - the city mark sprite is not ported. + initCityMark(*MainTexture); if (m_cityDlg) m_cityDlg->checkAge(); if (m_natStatDlg) @@ -624,8 +625,63 @@ void MainScreen::initTurn(int newPlayer) else un.Status |= usWaiting; checkToldNoReturn(uix); - // TODO: continuing multi-turn goto (GetMoveAdvice + MoveUnit) and terrain enhancement - // (ProcessEnhancement) needs MoveUnit, which is not ported yet. + if ((un.Status & IsoEngine::usGoto) != 0) { // continue multi-turn goto + setUnFocus(uix); + setTroopLoc(un.Loc); + focusOnLoc(m_troopLoc, flRepaintPanel | flImmUpdate); + TMoveAdviceData moveAdviceData; + int moveResult; + if ((un.Status >> 16) == 0x7FFF) + moveResult = ClientTools::getMoveAdvice(IsoEngine::unFocus, maNextCity, moveAdviceData); + else + moveResult = ClientTools::getMoveAdvice(IsoEngine::unFocus, un.Status >> 16, moveAdviceData); + bool stop; + if (moveResult >= rExecuted) { // !!! Shinkansen + moveResult = eOK; + bool ok = true; + for (int i = 0; i < moveAdviceData.nStep; ++i) { + const int loc1 = ClientTools::dLoc(un.Loc, moveAdviceData.dx[i], moveAdviceData.dy[i]); + if ((ClientTools::myMap[loc1] & (fCity | fOwned)) == static_cast(fCity) + // don't capture cities during auto move + || (ClientTools::myMap[loc1] & (fUnit | fOwned)) == static_cast(fUnit)) { + // don't attack during auto move + ok = false; + break; + } + const int moveOptions = loc1 == moveAdviceData.ToLoc + || (moveAdviceData.ToLoc == maNextCity + && (ClientTools::myMap[loc1] & fCity) != 0) + ? muAutoNoWait + : 0; + moveResult = moveUnit(moveAdviceData.dx[i], moveAdviceData.dy[i], moveOptions); + if (moveResult < rExecuted || moveResult == eEnemySpotted) { + ok = false; + break; + } + } + stop = !ok || un.Loc == moveAdviceData.ToLoc + || (moveAdviceData.ToLoc == maNextCity && (ClientTools::myMap[un.Loc] & fCity) != 0); + } else { + moveResult = eOK; + stop = true; + } + if (moveResult != eDied) { + if (stop) + un.Status &= 0xFFFF - IsoEngine::usGoto; + else + un.Status &= ~usWaiting; + } + } + if ((un.Status & (IsoEngine::usEnhance | IsoEngine::usGoto)) == IsoEngine::usEnhance) { + // continue terrain enhancement + const int moveResult = ClientTools::processEnhancement(uix, myData->enhancementJobs); + if (moveResult != eDied) { + if (moveResult == eJobDone) + un.Status &= ~IsoEngine::usEnhance; + else + un.Status &= ~usWaiting; + } + } } } } @@ -701,7 +757,8 @@ void MainScreen::nextUnit(int nearLoc, bool autoTurn) setTroopLoc(-1); QTimer::singleShot(0, this, [this] { endTurn(); }); } else { - // TODO: Play('TURNEND') when the turn becomes complete (sound is not ported). + if (!m_turnComplete && m_eot->isVisible()) + Sound::play(QStringLiteral("TURNEND")); m_turnComplete = true; setUnFocus(-1); setTroopLoc(-1); diff --git a/game/localplayer/Term.MainScreen.Window.cpp b/game/localplayer/Term.MainScreen.Window.cpp index cd51855..668ae43 100644 --- a/game/localplayer/Term.MainScreen.Window.cpp +++ b/game/localplayer/Term.MainScreen.Window.cpp @@ -45,6 +45,7 @@ #include "Cevo/CevoGraphicSet.h" #include "Cevo/CevoScreenTools.h" #include "Cevo/CevoTexture.h" +#include "Cevo/Music.h" #include "Global.h" #include @@ -249,7 +250,10 @@ void MainScreen::closeEvent(QCloseEvent *event) DrawDlg::closeEvent(event); if (!event->isAccepted()) return; + termBounds = fullScreen ? m_restoredBounds : geometry(); m_timer->stop(); + if (musicPlayer.playing()) + musicPlayer.stop(); } // ---- painting ---- @@ -310,6 +314,8 @@ void MainScreen::paintEvent(QPaintEvent *) blit(m_mapOffset, TopBarHeight, m_offscreen, 0, 0, m_mapWidth, m_mapHeight); if (m_blinkTileValid) painter.drawImage(m_blinkTilePos + QPoint(m_mapOffset, TopBarHeight), m_blinkTile.image()); + if (m_moveTileValid) + painter.drawImage(m_moveTilePos + QPoint(m_mapOffset, TopBarHeight), m_moveTile.image()); painter.restore(); blit(0, 0, m_topBar, 0, 0, cw, TopBarHeight); @@ -390,7 +396,11 @@ void MainScreen::copyMiniToPanel() bitBltBitmap(m_panel, m_xMini + 2, m_yMini + 2, lx * 2, ly, m_miniMap->bitmap, 0, 0); Dpi::Canvas &canvas = m_panel.canvas(); if (m_markCityLoc >= 0) { - // TODO: the city mark sprite (InitCityMark/CityMark2) is not ported yet. + if (const GraphicSetItem *mark = HGrSystem->searchByName(QStringLiteral("CityMark2"))) + sprite(canvas, *HGrSystem, + m_xMini - 2 + (4 * lx + 2 * (m_markCityLoc % lx) + (lx - m_mapWidth / (xxt * 2)) - 2 * m_xwd) % (2 * lx) + + ((m_markCityLoc / lx) & 1), + m_yMini - 3 + m_markCityLoc / lx, mark->width, mark->height, mark->left, mark->top); } else if (m_ywmax <= 0) { frame(canvas, m_xMini + 2 + lx - m_mapWidth / (xxt * 2), m_yMini + 2, m_xMini + 1 + lx + m_mapWidth / (xxt * 2), m_yMini + 2 + ly - 1, MainTexture->colorMark, MainTexture->colorMark); diff --git a/game/localplayer/Term.MainScreen.cpp b/game/localplayer/Term.MainScreen.cpp index 1715269..4a33160 100644 --- a/game/localplayer/Term.MainScreen.cpp +++ b/game/localplayer/Term.MainScreen.cpp @@ -27,10 +27,12 @@ // knowledge of the CeCILL license and that you accept its terms. #include "Term.MainScreen.h" +#include "Term.MainScreen.Menus.h" #include "Cevo/Database.h" #include "ClientTools.h" #include "Global.h" +#include "Sound.h" #include "Tribes.h" #include @@ -54,7 +56,8 @@ MainScreen::MainScreen(QWidget *parent) : DrawDlg(parent) resize(800, 480); setAttribute(Qt::WA_OpaquePaintEvent); onCloseQuery = [this] { - // TODO: when not closable, idle and playing, the original resigns (mResign.Click). + if (!m_closable && m_idle && ClientTools::me == 0 && clientMode < scContact) + menuCommand(MenuCommand::Resign); return m_closable; }; @@ -66,7 +69,9 @@ MainScreen::MainScreen(QWidget *parent) : DrawDlg(parent) m_topBar.canvas().font().assign(UniFont[static_cast(FontType::Normal)]); m_offscreen.canvas().font().assign(UniFont[static_cast(FontType::Small)]); createControls(); - + loadSettings(); + createMenus(); + wireControls(); mainScreenZoomToCity = [this](int loc, bool nextUnitOnClose, int showEvent) { return zoomToCity(loc, nextUnitOnClose, showEvent); }; @@ -381,14 +386,21 @@ int MainScreen::dipCall(int command) mem.sentCommand = command; mem.formerTreaty = ClientTools::myRO->Treaty[mem.pContact]; if (command == scDipCancelTreaty) { - // TODO: Sound.pas not ported. + Sound::play(QStringLiteral("CANCELTREATY")); } else if (command == scDipAccept) { for (int i = 0; i < receivedOffer.nDeliver; ++i) mem.receivedPrices.set(static_cast(receivedOffer.Price[i] >> 24)); for (int i = 0; i < receivedOffer.nCost; ++i) mem.deliveredPrices.set( static_cast(receivedOffer.Price[receivedOffer.nDeliver + i] >> 24)); - // TODO: Sound.pas not ported (NEWTREATY/ACCEPTOFFER distinction). + bool isTreatyDeal = false; + for (int i = 0; i < receivedOffer.nDeliver + receivedOffer.nCost; ++i) { + if ((receivedOffer.Price[i] & opMask) == opTreaty) { + isTreatyDeal = true; + break; + } + } + Sound::play(isTreatyDeal ? QStringLiteral("NEWTREATY") : QStringLiteral("ACCEPTOFFER")); } cityDlg().closeAction = CityScreen::CityCloseAction::None; closeDialogsForNextPlayer(*this); @@ -440,25 +452,27 @@ void MainScreen::setAIName(int p, const QString &name) bool MainScreen::contactRefused(int p, const QString &item) { Q_ASSERT(ClientTools::myRO->Treaty[p] >= trPeace); - const QString s = Tribes::tribe[static_cast(p)]->tPhrase(item); + QString s = Tribes::tribe[static_cast(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. + simpleMessage(s); 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; + switch (ClientTools::myRO->Treaty[p]) { + case trPeace: s += QLatin1Char(' ') + phrases[QStringLiteral("FRCANCELQUERY_PEACE")]; break; + case trFriendlyContact: s += QLatin1Char(' ') + phrases[QStringLiteral("FRCANCELQUERY_FRIENDLY")]; break; + case trAlliance: s += QLatin1Char(' ') + phrases[QStringLiteral("FRCANCELQUERY_ALLIANCE")]; break; + default: break; } - return false; + if (MessgEx::simpleQuery(MessageKind::YesNo, s, QStringLiteral("NEGO_REJECTED")) != Dpi::ModalResult::Ok) + return false; + Sound::play(QStringLiteral("CANCELTREATY")); + ClientTools::server(sCancelTreaty, ClientTools::me, 0, nullptr); + if (ClientTools::myRO->Treaty[p] == trNone) + ClientTools::cityOptimizer_BeginOfTurn(); + // peace treaty was cancelled -- use formerly forbidden tiles + m_mapValid = false; + paintAllMaps(); + return true; } void MainScreen::getTribeList() diff --git a/game/localplayer/Term.MainScreen.h b/game/localplayer/Term.MainScreen.h index ce0f822..6979dcb 100644 --- a/game/localplayer/Term.MainScreen.h +++ b/game/localplayer/Term.MainScreen.h @@ -28,20 +28,14 @@ #pragma once -// TMainScreen equivalent - PARTIAL PORT (session 1 of what will be a many- -// session effort, see /memories/repo/cevo-evo-game.md for the full 183- -// method inventory + proposed 10-file split). This slice only covers: the -// 17 lazy dialog accessors, arrangeDialog()/arrangeDialogs(), and the -// handful of small cross-dialog methods (dipCall/offerCall/ -// contactRefused/updateViews/setAIName/rememberPeaceViolation) that every -// other LocalPlayer dialog already has a `Term::mainScreenXxx` -// std::function injection point standing in for - this class's -// constructor wires all of those through to real methods below. The full -// map/panel/menu system (MainOffscreenPaint/PanelPaint/Client() etc.) is -// NOT part of this slice and remains future work - this header is kept -// SEPARATE from the widely-included Term.h specifically so consumers that -// only need the `Term::mainScreen` pointer don't have to transitively -// include all 17 dialog headers below. +// TMainScreen equivalent - PARTIAL PORT. Ported so far: the window layer and +// paint pipeline (Term.MainScreen.Window.cpp), PanelPaint (…Panel.cpp), +// InitTurn/NextUnit/EndTurn/ZoomToCity (…Turn.cpp), most of Client() +// (…Client.cpp) and the 17 lazy dialog accessors with the small cross-dialog +// methods in Term.MainScreen.cpp. Still missing: the menus, mouse/keyboard +// input, MoveUnit/ShowMove and sound. This header is kept SEPARATE from the +// widely-included Term.h so consumers that only need the `Term::mainScreen` +// pointer don't have to transitively include all the dialog headers below. #include "Battle.h" #include "Cevo/CevoArea.h" @@ -157,6 +151,64 @@ public: void panelPaint(); void setUnFocus(int uix); void focusOnLoc(int loc, int options = 0); + // Moves the focused unit to an adjacent tile (Term.pas's MoveUnit). + int moveUnit(int dx, int dy, int options = 0); + // Path finder: moves the focused unit to loc, starts a multi-turn goto if too far. + void moveToLoc(int loc, bool checkSuicide); + // Animates a unit moving from step0 to step1 of nStep. + void moveOnScreen(const TShowMove &showMove, int step0, int step1, int nStep, bool restore = true); + void processEventsWithDisabledKeyboard(); + // Client() branches that animate what happens on the map. + void clientShow(int command, int newPlayer, void *data); + + // ---- Menus, settings and input (Term.MainScreen.Menus.cpp / Input.cpp) ---- + void loadSettings(); + void saveSettings(); + void updateMusic(); + void setDebugMap(int p); + void setViewpoint(int p); + void focusNextUnit(int dir = 1); + int doJob(int job); + void setFullScreen(bool active); + +protected: + void mousePressEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; + void keyReleaseEvent(QKeyEvent *event) override; + +private: + enum class MenuCommand { + Help, TechTree, Jump, Run, Names, LocCodes, Log, EnhanceDef, CityTypes, RandomMap, FillMap, Website, Resign, + Disband, Utilize, City, Pillage, Home, Load, Unload, SelectTransport, GoOn, Cancel, Recover, Wait, NoOrders, Stay, + Centre, PrevUnit, NextUnit, UnitStat, CityStat, ScienceStat, EUnitStat, Diagram, Wonders, Ships, Nations, Empire, + Revolution, Trans, Afforest, Clear, Fort, AirBase, Canal, Mine, Farm, Irrigation, RailRoad, Road, Pollution, + Enhance, TileSmall, TileNormal, TileBig, SoundOn, SoundOnAlt, SoundOff, MusicOn, MusicOff + }; + enum class PopupKind { Game, Unit, Stat, Terrain, Edit }; + struct Menus; + void createMenus(); + void initPopup(PopupKind kind); + void showPopup(PopupKind kind, const QPoint &globalPos); + void menuCommand(MenuCommand command); + // Triggers a menu item if it is visible and enabled (MenuClick_Check of FormKeyDown). + void menuClickChecked(PopupKind kind, MenuCommand command); + void mapMouseDown(Qt::MouseButton button, Qt::KeyboardModifiers modifiers, QPoint pos); + void mapMouseMove(Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, QPoint pos); + void panelMouseDown(Qt::MouseButton button, Qt::KeyboardModifiers modifiers, QPoint pos); + void panelMouseMove(Qt::MouseButtons buttons, QPoint pos); + void panelMouseUp(); + bool isPanelPixel(int x, int y) const; + void mapButtonClicked(ButtonC *button); + void mapOptionButtonChanged(ButtonC *button, int option); + void panelButtonClicked(ButtonB *button); + void disbandOrUtilize(bool utilize); + void setTroopLocAndPanel(int loc); + void wireControls(); + QMenu *createUnitMenu(); + void triggerMenu(MenuCommand command); + bool menuItemUsable(MenuCommand command) const; void setTileSize(IsoEngine::TileSize tileSize, int loc, QPoint mapPos); void setTileSizeCenter(IsoEngine::TileSize tileSize); void checkTerrainBtnVisible(); @@ -245,10 +297,28 @@ private: Dpi::Bitmap m_blinkTile; QPoint m_blinkTilePos; bool m_blinkTileValid = false; + // The map rectangle a moving unit travels through (see moveOnScreen). + Dpi::Bitmap m_moveTile; + QPoint m_moveTilePos; + bool m_moveTileValid = false; + bool m_keyboardDisabled = false; + struct CurrentMoveInfo { + int afterMovePaintRadius = 0; + int afterAttackExpeller = -1; + bool doShow = false; + bool isAlly = false; + } m_currentMoveInfo; std::unique_ptr m_mainMap; std::unique_ptr m_noMap; std::unique_ptr m_noMapPanel; std::unique_ptr m_miniMap; + std::unique_ptr m_menus; + int m_editLoc = -1; + int m_mouseX = 0; + int m_mouseY = 0; + int m_dragStartLoc = -1; + QRect m_restoredBounds; + bool m_formFullScreen = false; std::unique_ptr m_verticalScrollBar; ButtonB *m_unitBtn = nullptr; ButtonB *m_unitInfoBtn = nullptr; diff --git a/game/localplayer/Term.cpp b/game/localplayer/Term.cpp index e7cd209..dc4533b 100644 --- a/game/localplayer/Term.cpp +++ b/game/localplayer/Term.cpp @@ -382,10 +382,10 @@ bool createTribe(int p, QString fileName, bool original) tribeOriginal[player] = original; Tribes::tribe[player] = std::make_unique(fileName); if (gameMode == cNewGame || !original) { - chooseModelPicture(p, 0, 010, 1, 0, true, true); - chooseModelPicture(p, 1, 040, 1, 0, true, true); - chooseModelPicture(p, 2, 041, 1, 0, true, true); - chooseModelPicture(p, -1, 017, 1, 0, true, true); + chooseModelPicture(p, 0, 10, 1, 0, true, true); + chooseModelPicture(p, 1, 40, 1, 0, true, true); + chooseModelPicture(p, 2, 41, 1, 0, true, true); + chooseModelPicture(p, -1, 17, 1, 0, true, true); } dipMem[player].pContact = -1; return true; diff --git a/game/localplayer/Term.h b/game/localplayer/Term.h index 57aac0f..6cbe1ca 100644 --- a/game/localplayer/Term.h +++ b/game/localplayer/Term.h @@ -224,6 +224,11 @@ constexpr int prPaint = 0x0001; constexpr int prAutoBounds = 0x0002; constexpr int prInvalidate = 0x0004; +// MoveUnit options. +constexpr int muAutoNoWait = 0x0001; +constexpr int muAutoNext = 0x0002; +constexpr int muNoSuicideCheck = 0x0004; + enum class PaintLocTempStyle { Normal, Blink }; // Terrain brushes of the map editor.