diff --git a/CMakeLists.txt b/CMakeLists.txt index 14f2865..4b12a90 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -119,6 +119,11 @@ set(PROJECT_SOURCES game/NoTerm.cpp game/NoTerm.h game/NoTerm.ui + game/Start.cpp + game/Start.h + game/Start.Paint.cpp + game/Start.ui + game/StartLayout.h game/localplayer/KeyBindings.cpp game/localplayer/KeyBindings.h game/localplayer/ClientTools.cpp diff --git a/ai/stdai/CMakeLists.txt b/ai/stdai/CMakeLists.txt index 1d35cff..9928dbf 100644 --- a/ai/stdai/CMakeLists.txt +++ b/ai/stdai/CMakeLists.txt @@ -61,7 +61,11 @@ set_target_properties(stdai PROPERTIES ) include(GNUInstallDirs) +# Installed as an AI module directory (/StdAI/StdAI.ai.txt, StdAI.png and the library). install(TARGETS stdai - LIBRARY DESTINATION ${CMAKE_INSTALL_AIDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_AIDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_AIDIR}/StdAI + RUNTIME DESTINATION ${CMAKE_INSTALL_AIDIR}/StdAI +) +install(FILES StdAI.ai.txt StdAI.png + DESTINATION ${CMAKE_INSTALL_AIDIR}/StdAI ) diff --git a/ai/stdai/StdAI.ai.txt b/ai/stdai/StdAI.ai.txt new file mode 100644 index 0000000..dfcffe2 --- /dev/null +++ b/ai/stdai/StdAI.ai.txt @@ -0,0 +1,7 @@ +#NAME Standard AI +#GAMEVERSION 1.2.0 +#BEGINNER +#PATH stdai.so +#PATH_WIN32 stdai.dll +#PATH_WIN64 stdai.dll +#CREDITS Standard AI by Steffen Gerlach. diff --git a/ai/stdai/StdAI.png b/ai/stdai/StdAI.png new file mode 100644 index 0000000..a542638 Binary files /dev/null and b/ai/stdai/StdAI.png differ diff --git a/game/Brain.cpp b/game/Brain.cpp index 019838f..44d6be6 100644 --- a/game/Brain.cpp +++ b/game/Brain.cpp @@ -47,6 +47,10 @@ namespace { // resolve the install-time default set up by CMakeLists.txt. QString getAiDir() { + // The CEVO_AI_DIR environment variable overrides the install location (for running a build-tree binary). + const QByteArray fromEnvironment = qgetenv("CEVO_AI_DIR"); + if (!fromEnvironment.isEmpty()) + return QString::fromLocal8Bit(fromEnvironment); #ifdef CEVO_AI_DIR return QStringLiteral(CEVO_AI_DIR); #else diff --git a/game/Direct.cpp b/game/Direct.cpp index 10a03cd..ec314cd 100644 --- a/game/Direct.cpp +++ b/game/Direct.cpp @@ -31,6 +31,7 @@ #include "Global.h" #include "Messg.h" #include "NoTerm.h" +#include "Start.h" #include "localplayer/LocalPlayer.h" #include "Cevo/CevoScreenTools.h" @@ -82,6 +83,12 @@ DirectDlg::DirectDlg(QWidget *parent) : DrawDlg(parent) GameServer::brainRandom->lookupName = QStringLiteral("RANDOMAI"); } +void DirectDlg::setStartDlg(StartDlg *dlg) +{ + m_startDlg = dlg; + m_background = dlg ? dlg->background() : nullptr; +} + void DirectDlg::showEvent(QShowEvent *event) { DrawDlg::showEvent(event); @@ -240,10 +247,12 @@ void DirectDlg::dlgNotify(GameServer::NotifyId id, int index) case NotifyId::StartGoRefreshMaps: if (m_quick) { close(); - } else { - // TODO: StartDlg::updateFormerGames()/updateMaps() not ported. - if (m_startDlg) - m_startDlg->show(); + } else if (m_startDlg) { + if (id == NotifyId::StartGoRefresh) + m_startDlg->updateFormerGames(); + else if (id == NotifyId::StartGoRefreshMaps) + m_startDlg->updateMaps(false); + m_startDlg->show(); } break; case NotifyId::ChangeClient: diff --git a/game/Direct.h b/game/Direct.h index 3a90c7f..7d3b2e6 100644 --- a/game/Direct.h +++ b/game/Direct.h @@ -35,18 +35,17 @@ namespace Cevo { +class StartDlg; + // Equivalent of Direct.pas's TDirectDlg: the small "busy/progress" splash // dialog shown while the game engine starts up, loads a save/map file, or // hands control over between clients - and the application's actual entry // point (OnGo parses the command line and kicks everything off). Like // Back.pas, the .lfm has no child controls, so no .ui file is used here. // -// Start.pas/LocalPlayer.pas/NoTerm.pas/NetworkServer.pas/NetworkClient.pas -// are not ported - every place the original reaches into StartDlg or -// assigns a special brain's in-process Client function pointer is a -// disclosed, clearly-marked gap (see the .cpp). setStartDlg()/ -// setBackground() let the eventual Start.pas port plug itself in, the same -// decoupling already used by Back.pas's setAnchor(). +// NetworkServer.pas/NetworkClient.pas are not ported (their client entry +// points are a marked gap in the .cpp). The start screen plugs in through +// setStartDlg(), the same decoupling used by Back.pas's setAnchor(). class DirectDlg : public DrawDlg { Q_OBJECT public: @@ -56,9 +55,8 @@ public: // DlgNotify) - pass this to GameServer::init(). void dlgNotify(GameServer::NotifyId id, int index = 0); - // Not-yet-ported Start.pas decoupling (see class comment). - void setStartDlg(QWidget *dlg) { m_startDlg = dlg; } - void setBackground(QWidget *background) { m_background = background; } + // Start.pas decoupling: the start screen and, through it, the background window. + void setStartDlg(StartDlg *dlg); protected: void showEvent(QShowEvent *event) override; @@ -70,7 +68,7 @@ private: void setInfo(const QString &text); void setState(int value); - QWidget *m_startDlg = nullptr; + StartDlg *m_startDlg = nullptr; QWidget *m_background = nullptr; QString m_info; diff --git a/game/GameServer.ClientCallPlumbing.cpp b/game/GameServer.ClientCallPlumbing.cpp index e8c81ea..522428e 100644 --- a/game/GameServer.ClientCallPlumbing.cpp +++ b/game/GameServer.ClientCallPlumbing.cpp @@ -55,10 +55,13 @@ namespace Cevo { namespace GameServer { -// Equivalent of Directories.pas's GetAiDir() - see Brain.cpp's own copy of -// this (not shared via a header since Directories.pas itself isn't ported). +// Equivalent of Directories.pas's GetAiDir(). QString getAiDir() { + // The CEVO_AI_DIR environment variable overrides the install location (for running a build-tree binary). + const QByteArray fromEnvironment = qgetenv("CEVO_AI_DIR"); + if (!fromEnvironment.isEmpty()) + return QString::fromLocal8Bit(fromEnvironment); #ifdef CEVO_AI_DIR return QStringLiteral(CEVO_AI_DIR); #else diff --git a/game/GameServer.cpp b/game/GameServer.cpp index 65f9082..3529b95 100644 --- a/game/GameServer.cpp +++ b/game/GameServer.cpp @@ -210,8 +210,7 @@ void init(const NotifyFunction ¬ifyFunction) } } - if (brains.kindCount(BrainType::AI) == 0) - throw std::runtime_error(("No AI libraries found in directory " + getAiDir()).toStdString()); + // No AI at all is reported to the user by DirectDlg::go() (Brains.Count = 3 there), not fatal here. } diff --git a/game/Global.cpp b/game/Global.cpp index e90b5d3..5bc5611 100644 --- a/game/Global.cpp +++ b/game/Global.cpp @@ -35,11 +35,15 @@ #include #include #include +#include +#include #include namespace Cevo { bool fullScreen = false; +float musicVolume = 0.5f; +QRect termBounds(0, 0, 800, 480); bool musicEnabled = true; bool generateNames = true; @@ -160,6 +164,34 @@ QString formatPhrase(const QString &key, const QStringList &args) return result; } +void loadConfig() +{ + QSettings settings; + localeCode = settings.value(QStringLiteral("Locale")).toString(); + fullScreen = settings.value(QStringLiteral("ScreenMode"), 1).toInt() > 0; + musicEnabled = settings.value(QStringLiteral("MusicEnabled"), true).toBool(); + musicVolume = settings.value(QStringLiteral("MusicVolume"), 0.5).toFloat(); + termBounds = QRect(settings.value(QStringLiteral("TermLeft"), 0).toInt(), + settings.value(QStringLiteral("TermTop"), 0).toInt(), + settings.value(QStringLiteral("TermWidth"), 800).toInt(), + settings.value(QStringLiteral("TermHeight"), 480).toInt()); + gamma = settings.value(QStringLiteral("Gamma"), 100).toInt(); +} + +void saveConfig() +{ + QSettings settings; + settings.setValue(QStringLiteral("Locale"), localeCode); + settings.setValue(QStringLiteral("ScreenMode"), fullScreen ? 1 : 0); + settings.setValue(QStringLiteral("MusicEnabled"), musicEnabled); + settings.setValue(QStringLiteral("MusicVolume"), musicVolume); + settings.setValue(QStringLiteral("TermLeft"), termBounds.left()); + settings.setValue(QStringLiteral("TermTop"), termBounds.top()); + settings.setValue(QStringLiteral("TermWidth"), termBounds.width()); + settings.setValue(QStringLiteral("TermHeight"), termBounds.height()); + settings.setValue(QStringLiteral("Gamma"), gamma); +} + void loadAssets() { graphicsDir = getGraphicsDir(); diff --git a/game/Global.h b/game/Global.h index efefe94..0bd93f7 100644 --- a/game/Global.h +++ b/game/Global.h @@ -30,6 +30,7 @@ #include "Cevo/CevoStringTables.h" +#include #include #include @@ -42,6 +43,10 @@ constexpr const char *CevoTitle = "C-evo"; constexpr const char *CevoSubTitle = "New Horizons"; constexpr const char *CevoExt = ".cevo"; constexpr const char *CevoTribeExt = ".tribe.txt"; +constexpr const char *CevoHomepageShort = "app.zdechov.net/c-evo"; +constexpr const char *CevoHomepage = "https://app.zdechov.net/c-evo"; +constexpr const char *CevoContactBug = "https://app.zdechov.net/c-evo/report/1"; +constexpr const char *AITemplateFileName = "AI Template/AI development manual.html"; constexpr int CevoVersionMajor = 1; constexpr int CevoVersionMinor = 4; @@ -54,6 +59,17 @@ constexpr int CevoVersion = ((CevoVersionMajor & 0xFF) << 16) | ((CevoVersionMin // by Back.pas/Start.pas to decide fullscreen vs. windowed layout). extern bool fullScreen; +// Global.pas/ScreenTools.pas user settings: music volume (0..1) and the +// main game window's last position/size. +extern float musicVolume; +extern QRect termBounds; + +// The persisted user settings shared by the whole game (language, screen +// mode, music, main window bounds, gamma), stored with QSettings where the +// original used the registry. loadConfig() must run before loadAssets(). +void loadConfig(); +void saveConfig(); + // Equivalent of a user-settings `MusicEnabled` flag (Start.pas/Direct.pas - // neither ported in full - toggle background music playback on/off). extern bool musicEnabled; diff --git a/game/Start.Paint.cpp b/game/Start.Paint.cpp new file mode 100644 index 0000000..46f9ef3 --- /dev/null +++ b/game/Start.Paint.cpp @@ -0,0 +1,385 @@ +// 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. + +// Start.pas, the painting part: TStartDlg.OffscreenPaint and DrawAction. + +#include "Start.h" +#include "ui_Start.h" + +#include "Cevo/CevoButtonA.h" +#include "Cevo/CevoButtonB.h" +#include "Cevo/CevoButtonC.h" +#include "Cevo/CevoGraphicSet.h" +#include "Cevo/CevoListBoxEx.h" +#include "Cevo/CevoScreenTools.h" +#include "Cevo/CevoTexture.h" +#include "Cevo/Database.h" +#include "GameServer.h" +#include "Global.h" +#include "StartLayout.h" +#include "localplayer/Term.h" + +#include + +#include + +namespace Cevo { + +using namespace StartLayout; + +namespace { + +QString startControl(int index) +{ + return phrases.lookup(QStringLiteral("STARTCONTROLS"), index); +} + +bool isPlayableBrain(const Brain *brain) +{ + return brain && (brain->kind == BrainType::Term || brain->kind == BrainType::Random || + brain->kind == BrainType::AI); +} + +// Rectangular copy between two canvases (Pascal's BitBltCanvas). +void copyBlock(Dpi::Canvas &dst, int x, int y, int w, int h, Dpi::Canvas &src, int xSrc, int ySrc) +{ + dst.copyRect(QRect(x, y, w, h), src, QRect(xSrc, ySrc, w, h)); +} + +} // namespace + +void StartDlg::drawAction(int y, int iconIndex, const QString &headerItem, const QString &textItem) +{ + Dpi::Canvas &canvas = offscreen.canvas(); + canvas.font().assign(UniFont[static_cast(FontType::Caption)]); + canvas.font().setUnderline(true); + risedTextOut(canvas, xAction, y - 3, phrases2.lookup(headerItem)); + canvas.font().assign(UniFont[static_cast(FontType::Normal)]); + biColorTextOut(canvas, Colors->image().pixelColor(clkAge0 - 1, cliDimmedText), Qt::black, xAction, y + 21, + phrases2.lookup(textItem)); + + drawBufferEnsureSize(50, 50); + drawBuffer.canvas().begin(); + copyBlock(drawBuffer.canvas(), 0, 0, 50, 50, canvas, xActionIcon - 2, y - 2); + drawBuffer.canvas().end(); + glowFrame(drawBuffer, 8, 8, 34, 34, QColor(0x20, 0x20, 0x20)); + copyBlock(canvas, xActionIcon - 2, y - 2, 50, 50, drawBuffer.canvas(), 0, 0); + copyBlock(canvas, xActionIcon, y, 40, 40, bigImp->canvas(), (iconIndex % 7) * xSizeBig + 8, + (iconIndex / 7) * ySizeBig); + rframe(canvas, xActionIcon - 1, y - 1, xActionIcon + 40, y + 40, Qt::black, Qt::black); +} + +void StartDlg::offscreenPaint() +{ + static const int tabNames[4] = { 0, 11, 3, 4 }; + BufferedDrawDlg::offscreenPaint(); + clearOffscreen(offscreen); + if (!MainTexture || !HGrSystem || !Templates || !bigImp || !Colors) + return; + + Dpi::Canvas &canvas = offscreen.canvas(); + canvas.begin(); + const QColor shade = MainTexture->colorBevelShade; + const QColor light = MainTexture->colorBevelLight; + const int clientWidth = width(); + const int clientHeight = height(); + const int tabIndex = static_cast(m_tab); + canvas.font().assign(UniFont[static_cast(FontType::Normal)]); + canvas.brush().setStyle(Qt::NoBrush); + + paintBackground(canvas, 3, 3, TabOffset + 4 * TabSize - 4, TabHeight - 3, clientWidth, clientHeight); + paintBackground(canvas, 3, TabHeight + 3, clientWidth - 6, clientHeight - TabHeight - 6, clientWidth, + clientHeight); + canvas.brush().setStyle(Qt::SolidPattern); + canvas.brush().setColor(Qt::black); + canvas.fillRect(QRect(0, 1, clientWidth, 2)); + canvas.fillRect(QRect(TabOffset + 4 * TabSize + 2, 0, clientWidth - (TabOffset + 4 * TabSize + 2), TabHeight)); + canvas.brush().setStyle(Qt::NoBrush); + + if (m_page == Page::StartRandom || m_page == Page::StartMap) { + frame(canvas, 328, yMain + 112 - 15, clientWidth + 10, ui->up2Btn->y() + 38, shade, light); + if (m_autoDiff > 0) + frame(canvas, -1, yMain + 112 - 15, x0Brain + dxBrain + 64, ui->up2Btn->y() + 38, shade, light); + } else if (m_page != Page::Main) { + frame(canvas, 328, ui->up1Btn->y() - 15, clientWidth + 10, ui->up2Btn->y() + 38, shade, light); + } + frame(canvas, 0, 0, clientWidth - 1, clientHeight - 1, Qt::black, Qt::black); + + // draw tabs + const int lift0 = 2 * (m_tab != Tab::Main ? 1 : 0); + frame(canvas, 2, 2 + lift0, TabOffset + (0 + 1) * TabSize - 1, TabHeight, light, shade); + frame(canvas, 1, 1 + lift0, TabOffset + (0 + 1) * TabSize, TabHeight, light, shade); + canvas.setPixel(1, 1 + lift0, shade); + for (int tab2 = static_cast(Tab::Map); tab2 <= static_cast(Tab::PreviousGame); ++tab2) { + const int lift = 2 * (tabIndex != tab2 ? 1 : 0); + frame(canvas, TabOffset + tab2 * TabSize + 2, 2 + lift, TabOffset + (tab2 + 1) * TabSize - 1, TabHeight, light, + shade); + frame(canvas, TabOffset + tab2 * TabSize + 1, 1 + lift, TabOffset + (tab2 + 1) * TabSize, TabHeight, light, + shade); + canvas.setPixel(TabOffset + tab2 * TabSize + 1, 1 + lift, shade); + } + canvas.font().assign(UniFont[static_cast(FontType::Normal)]); + for (int tab2 = static_cast(Tab::Map); tab2 <= static_cast(Tab::PreviousGame); ++tab2) { + const QString s = startControl(tabNames[tab2]); + risedTextOut(canvas, TabOffset + tab2 * TabSize + 1 + (TabSize - biColorTextWidth(canvas, s)) / 2, + 10 + 2 * (tabIndex != tab2 ? 1 : 0), s); + } + frame(canvas, TabOffset + 4 * TabSize + 1, -1, clientWidth, TabHeight, Qt::black, Qt::black); + frame(canvas, 1, TabHeight + 1, clientWidth - 2, clientHeight - 2, light, shade); + frame(canvas, 2, TabHeight + 2, clientWidth - 3, clientHeight - 3, light, shade); + if (m_tab == Tab::Main) { + paintBackground(canvas, 3, TabHeight - 1, TabSize - 4 - 3 + TabOffset + 3, 4, clientWidth, clientHeight); + canvas.setPixel(2, TabHeight, light); + } else { + paintBackground(canvas, TabOffset + 3 + tabIndex * TabSize, TabHeight - 1, TabSize - 4, 4, clientWidth, + clientHeight); + canvas.setPixel(TabOffset + tabIndex * TabSize + 2, TabHeight, light); + } + canvas.setPixel(TabOffset + (tabIndex + 1) * TabSize - 1, TabHeight + 1, shade); + if (m_tab < Tab::PreviousGame) + frame(canvas, TabOffset + (tabIndex + 1) * TabSize + 1, 3, TabOffset + (tabIndex + 1) * TabSize + 2, + TabHeight, shade, shade); // tab shadow + + // Paint menu logo + if (GraphicSetItem *menuLogo = Templates->searchByName(QStringLiteral("MenuLogo"))) { + const int logoY = 3 + 2 * (m_tab != Tab::Main ? 1 : 0); + drawBufferEnsureSize(menuLogo->width, menuLogo->height); + drawBuffer.canvas().begin(); + copyBlock(drawBuffer.canvas(), 0, 0, menuLogo->width, menuLogo->height, canvas, 6, logoY); + drawBuffer.canvas().end(); + imageOpBCC(drawBuffer, Templates->data, 0, 0, menuLogo->left, menuLogo->top, menuLogo->width, + menuLogo->height - 9, 0xBFBF20, 0x4040DF); // logo part 1 + imageOpBCC(drawBuffer, Templates->data, 10, 27, menuLogo->left + 10, menuLogo->top + 27, menuLogo->width - 10, + 9, 0xBFBF20, 0x4040DF); // logo part 2 + copyBlock(canvas, 6, logoY, menuLogo->width, menuLogo->height, drawBuffer.canvas(), 0, 0); + } + + if (m_page == Page::Main) { + if (m_selectedAction != MainAction::None) { // mark selected action + const int row = static_cast(m_selectedAction); + const int w = clientWidth - 2 * ActionSideBorder; + int h = ActionPitch; + const int top = yAction + row * ActionPitch - 8; + if (top + h > clientHeight - ActionBottomBorder) + h = clientHeight - ActionBottomBorder - top; + drawBufferEnsureSize(w, h); + drawBuffer.canvas().begin(); + copyBlock(drawBuffer.canvas(), 0, 0, w, h, canvas, ActionSideBorder, top); + drawBuffer.canvas().end(); + makeBlue(drawBuffer, 0, 0, w, h); + copyBlock(canvas, ActionSideBorder, top, w, h, drawBuffer.canvas(), 0, 0); + } + int y = yAction; + for (int row = 0; row <= static_cast(MainAction::None); ++row, y += ActionPitch) { + const auto action = static_cast(row); + if (std::find(m_actionsOffered.begin(), m_actionsOffered.end(), action) == m_actionsOffered.end()) + continue; + switch (action) { + case MainAction::Config: drawAction(y, 25, QStringLiteral("ACTIONHEADER_CONFIG"), QStringLiteral("ACTION_CONFIG")); break; + case MainAction::Manual: drawAction(y, 19, QStringLiteral("ACTIONHEADER_MANUAL"), QStringLiteral("ACTION_MANUAL")); break; + case MainAction::Credits: drawAction(y, 22, QStringLiteral("ACTIONHEADER_CREDITS"), QStringLiteral("ACTION_CREDITS")); break; + case MainAction::AIDev: drawAction(y, 24, QStringLiteral("ACTIONHEADER_AIDEV"), QStringLiteral("ACTION_AIDEV")); break; + case MainAction::Web: { + canvas.font().assign(UniFont[static_cast(FontType::Caption)]); + risedTextOut(canvas, xActionIcon + 99, y, + phraseToQtFormat(phrases2.lookup(QStringLiteral("ACTIONHEADER_WEB"))) + .arg(QString::fromLatin1(CevoHomepageShort))); + canvas.font().assign(UniFont[static_cast(FontType::Normal)]); + if (GraphicSetItem *arrows = Templates->searchByName(QStringLiteral("LinkArrows"))) { + drawBufferEnsureSize(arrows->width, arrows->height); + drawBuffer.canvas().begin(); + copyBlock(drawBuffer.canvas(), 0, 0, arrows->width, arrows->height, canvas, xActionIcon, y + 2); + drawBuffer.canvas().end(); + imageOpBCC(drawBuffer, Templates->data, 0, 0, arrows->left, arrows->top, arrows->width, + arrows->height, 0, + colorToDelphi(Colors->image().pixelColor(clkAge0 - 1, cliDimmedText))); + copyBlock(canvas, xActionIcon, y + 2, arrows->width, arrows->height, drawBuffer.canvas(), 0, 0); + } + break; + } + case MainAction::None: break; + } + } + } else if (m_page == Page::StartRandom || m_page == Page::StartMap) { + underlinedTitleValue(canvas, startControl(10), Term::turnToString(m_maxTurn), 344, y0Mini + 61, 170); + + QString s = startControl(7); + loweredTextOut(canvas, -2, *MainTexture, x0Brain + 32 - canvas.textWidth(s) / 2, y0Brain + dyBrain + 69, s); + + initOrnament(); + GraphicSetItem *ornament = HGrSystem2 ? HGrSystem2->searchByName(QStringLiteral("Ornament")) : nullptr; + if (m_autoDiff < 0) { + if (ornament) { + for (int i = 12; i <= 19; ++i) { + if (i < 13 || i > 17) + sprite(canvas, 9 + i * 27, yLogo - 2, *ornament); + } + } + paintLogo(canvas, 69 + 11 * 27, yLogo, light, shade); + + for (int i = 0; i < nPlOffered; ++i) { + if (!((1 << i) & m_slotAvailable)) + continue; + Brain *brain = GameServer::playersBrain[static_cast(i)]; + if (brain) + frameImage(canvas, brain->picture, xBrain[i], yBrain[i], 64, 64, 0, 0, true); + else + frameImage(canvas, m_emptyPicture, xBrain[i], yBrain[i], 64, 64, 0, 0, true); + if (isPlayableBrain(brain)) { + const PlayerSlot &slot = m_playerSlots[static_cast(i)]; + copyBlock(canvas, xBrain[i] - 18, yBrain[i] + 19, 12, 14, HGrSystem->data.canvas(), + 134 + (Database::difficulty[static_cast(i)] - 1) * 13, 28); + frame(canvas, xBrain[i] - 19, yBrain[i] + 18, xBrain[i] - 18 + 12, yBrain[i] + (19 + 14), + Qt::black, Qt::black); + rframe(canvas, slot.diffUpBtn->x() - 1, slot.diffUpBtn->y() - 1, slot.diffUpBtn->x() + 12, + slot.diffUpBtn->y() + 24, shade, light); + canvas.brush().setStyle(Qt::SolidPattern); + canvas.brush().setColor(Qt::black); + canvas.fillRect(QRect(xBrain[i] - 5, yBrain[i] + 25, 3, 2)); + canvas.brush().setStyle(Qt::NoBrush); + if (slot.offerMultiple) { + rframe(canvas, slot.multiBtn->x() - 1, slot.multiBtn->y() - 1, slot.multiBtn->x() + 12, + slot.multiBtn->y() + 12, shade, light); + copyBlock(canvas, xBrain[i] - 31, yBrain[i], 13, 12, HGrSystem->data.canvas(), 88, 47); + } + } + if (brain) { + const PlayerSlot &slot = m_playerSlots[static_cast(i)]; + const QString hint = phraseToQtFormat(startControl(9)).arg(brain->name()); + slot.diffUpBtn->setToolTip(hint); + slot.diffDownBtn->setToolTip(hint); + } + } + } else { + dLine(canvas, 24, 198, yMain + 140 + 19, light, shade); + risedTextOut(canvas, 24, yMain + 140, startControl(15)); + if (m_page == Page::StartRandom) + s = QString::number(m_autoEnemies); + else if (m_mapStartPositions == 0) + s = QStringLiteral("0"); + else + s = QString::number(m_mapStartPositions - 1); + risedTextOut(canvas, 198 - biColorTextWidth(canvas, s), yMain + 140, s); + + dLine(canvas, 24, xDefault - 6, yMain + 164 + 19, light, shade); + risedTextOut(canvas, 24, yMain + 164, startControl(16)); + if (m_autoDiff == 1) { + if (Brain *beginner = GameServer::brains.beginner()) + frameImage(canvas, beginner->picture, xDefault, yDefault, 64, 64, 0, 0, false); + } else if (m_brainDefault) { + frameImage(canvas, m_brainDefault->picture, xDefault, yDefault, 64, 64, 0, 0, true); + } + dLine(canvas, 56, 272, y0Mini + 61 + 19, light, shade); + + risedTextOut(canvas, 56, y0Mini + 61, startControl(14)); + s = phrases.lookup(QStringLiteral("AUTODIFF"), m_autoDiff - 1); + risedTextOut(canvas, 272 - biColorTextWidth(canvas, s), y0Mini + 61, s); + if (ornament) { + for (int i = 0; i < 20; ++i) { + if (i < 2 || i > 6) + sprite(canvas, 9 + i * 27, yLogo - 2, *ornament); + } + } + paintLogo(canvas, 69, yLogo, light, shade); + } + } else if (m_page == Page::Load) { + if (m_lastTurn > 0) { + paintProgressBar(canvas, 6, xTurnSlider, yTurnSlider, 0, m_loadTurn * wTurnSlider / m_lastTurn, + wTurnSlider, *MainTexture); + frame(canvas, xTurnSlider - 2, yTurnSlider - 2, xTurnSlider + wTurnSlider + 1, yTurnSlider + 8, + QColor(0xB0, 0xB0, 0xB0), Qt::white); + rframe(canvas, xTurnSlider - 3, yTurnSlider - 3, xTurnSlider + wTurnSlider + 2, yTurnSlider + 9, + Qt::white, QColor(0xB0, 0xB0, 0xB0)); + } else { + dLine(canvas, 344, 514, y0Mini + 61 + 19, light, shade); + } + risedTextOut(canvas, 344, y0Mini + 61, startControl(8)); + const QString s = Term::turnToString(m_loadTurn); + risedTextOut(canvas, 514 - biColorTextWidth(canvas, s), y0Mini + 61, s); + } else if (m_page == Page::EditRandom) { + const QPoint world = WorldSizes[m_worldSize]; + underlinedTitleValue(canvas, startControl(5), + QString::number((world.x() * world.y() * 20 + DefaultWorldTiles / 2) / DefaultWorldTiles * 5) + + QLatin1Char('%'), + 344, y0Mini - 77, 170); + underlinedTitleValue(canvas, startControl(6), QString::number(m_startLandMass) + QLatin1Char('%'), 344, + y0Mini + 61, 170); + } else if (m_page == Page::EditMap) { + const QString s = phraseToQtFormat(phrases2.lookup(QStringLiteral("MAPPROP"))) + .arg((m_mapLandTiles * 100 + 556) / 1112) // 1112 is typical for a world with 100% size and default land mass + .arg(m_mapStartPositions); + risedTextOut(canvas, x0Mini - biColorTextWidth(canvas, s) / 2, y0Mini + 61, s); + } + + const auto frameButtonUp = [&](const QWidget *button, int height) { + if (button->isVisible()) + rframe(canvas, button->x() - 1, button->y() - 1, button->x() + 12, button->y() + height, shade, light); + }; + if (ui->startBtn->isVisible()) + btnFrame(canvas, ui->startBtn->geometry(), *MainTexture); + frameButtonUp(ui->up2Btn, 24); + frameButtonUp(ui->up1Btn, 24); + frameButtonUp(ui->autoDiffUpBtn, 24); + frameButtonUp(ui->autoEnemyUpBtn, 24); + frameButtonUp(ui->customizeBtn, 12); + if (ui->list->isVisible()) + editFrame(canvas, ui->list->geometry(), *MainTexture); + if (ui->renameBtn->isVisible()) + btnFrame(canvas, ui->renameBtn->geometry(), *MainTexture); + if (ui->deleteBtn->isVisible()) + btnFrame(canvas, ui->deleteBtn->geometry(), *MainTexture); + if (m_page == Page::Load) + btnFrame(canvas, ui->replayBtn->geometry(), *MainTexture); + + if (m_page != Page::Main && m_page != Page::NoLoad) { + const int xMini = x0Mini - m_miniMap.size.x(); + const int yMini = y0Mini - m_miniMap.size.y() / 2; + frame(canvas, xMini, yMini, xMini + 3 + m_miniMap.size.x() * 2, yMini + 3 + m_miniMap.size.y(), light, shade); + frame(canvas, xMini + 1, yMini + 1, xMini + 2 + m_miniMap.size.x() * 2, yMini + 2 + m_miniMap.size.y(), shade, + light); + + QString s; + if (m_miniMap.mode == MiniMap::Mode::Picture) { + canvas.draw(xMini + 2, yMini + 2, m_miniMap.bitmap.image()); + if (m_page == Page::StartRandom) + s = phrases.lookup(QStringLiteral("RANMAP")); + } else if (m_miniMap.mode == MiniMap::Mode::MultiPlayer) { + s = phrases.lookup(QStringLiteral("MPMAP")); + } else if (m_page == Page::StartMap) { + s = QFileInfo(m_mapFileName).completeBaseName(); + } else if (m_page == Page::EditMap) { + if (ui->list->currentItem()) + s = ui->list->currentItem()->text(); + } + if (!s.isEmpty()) + risedTextOut(canvas, x0Mini + 2 - biColorTextWidth(canvas, s) / 2, y0Mini - 8, s); + } + canvas.end(); +} + +} // namespace Cevo diff --git a/game/Start.cpp b/game/Start.cpp new file mode 100644 index 0000000..1526389 --- /dev/null +++ b/game/Start.cpp @@ -0,0 +1,1335 @@ +// 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. + +// Start.pas, the logic part (construction, settings, popups, buttons); +// the painting is in Start.Paint.cpp. + +#include "Start.h" +#include "ui_Start.h" + +#include "Cevo/CevoButtonA.h" +#include "Cevo/CevoButtonB.h" +#include "Cevo/CevoButtonC.h" +#include "Cevo/CevoGraphicSet.h" +#include "Cevo/CevoListBoxEx.h" +#include "Cevo/CevoScreenTools.h" +#include "Cevo/CevoTexture.h" +#include "Cevo/Database.h" +#include "Cevo/Map.h" +#include "Cevo/Music.h" +#include "Direct.h" +#include "GameServer.h" +#include "Global.h" +#include "Inp.h" +#include "Messg.h" +#include "StartLayout.h" +#include "localplayer/KeyBindings.h" +#include "localplayer/Term.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace Cevo { + +using namespace StartLayout; + +namespace { + +constexpr int AllPagesTag = 0x0FFFFF00; + +void setTag(QWidget *widget, quint32 tag) +{ + widget->setProperty("tag", tag); +} + +quint32 tagOf(const QWidget *widget) +{ + return widget->property("tag").toUInt(); +} + +bool isPlayableBrain(const Brain *brain) +{ + return brain && (brain->kind == BrainType::Term || brain->kind == BrainType::Random || + brain->kind == BrainType::AI); +} + +QString phraseN(const QString &key, int index) +{ + return phrases.lookup(key, index); +} + +// Pascal's AnsiCompareFileName ordering of captions (case-insensitive). +bool captionLess(const QString &a, const QString &b) +{ + return QString::compare(a, b, Qt::CaseInsensitive) < 0; +} + +QString incrementFileName(const QString &fileName) +{ + const int i = fileName.lastIndexOf(QLatin1Char(' ')); + if (i > 0) { + bool ok = false; + const int num = fileName.mid(i + 1).toInt(&ok); + if (ok) + return fileName.left(i).trimmed() + QLatin1Char(' ') + QString::number(num + 1); + } + return fileName + QStringLiteral(" 2"); +} + +} // namespace + +StartDlg::StartDlg(DirectDlg *direct, QWidget *parent) + : BufferedDrawDlg(parent), m_direct(direct), ui(new Ui::StartDlg) +{ + ui->setupUi(this); + setMouseTracking(true); + setWindowFlag(Qt::WindowStaysOnTopHint, true); + m_background = std::make_unique(); + m_background->setAnchor(this); + + titleHeight = 0; + loadConfig(); + loadAssets(); + loadLanguages(); + + m_actionsOffered = { MainAction::Config, MainAction::Manual, MainAction::Credits, MainAction::Web }; + if (QFileInfo::exists(getAppSharePath(QString::fromLatin1(AITemplateFileName)))) + m_actionsOffered.insert(m_actionsOffered.begin() + 3, MainAction::AIDev); + + m_brainDefault = nullptr; + for (int i = std::max(GameServer::brains.indexOf(GameServer::brainRandom), 0); i < GameServer::brains.count(); ++i) { + if (GameServer::brains[i].fileName == m_defaultAI) + m_brainDefault = &GameServer::brains[i]; + } + if (m_brainDefault == GameServer::brainRandom && GameServer::brains.kindCount(BrainType::AI) < 2) + m_brainDefault = nullptr; + if (!m_brainDefault && GameServer::brains.kindCount(BrainType::AI) > 0) // default AI not found, use any + m_brainDefault = GameServer::brains.getByKind(BrainType::AI).front(); + + m_direct->centerToScreen(); + updateInterface(); + + // Page visibility tags (Tag and (256 shl Page) <> 0). + setTag(ui->startBtn, 15104); + setTag(ui->down1Btn, 4096); + setTag(ui->up1Btn, 4096); + setTag(ui->renameBtn, 10240); + setTag(ui->deleteBtn, 10240); + setTag(ui->down2Btn, 6912); + setTag(ui->up2Btn, 6912); + setTag(ui->quitBtn, AllPagesTag); + setTag(ui->customizeBtn, 768); + setTag(ui->autoDiffUpBtn, 0); + setTag(ui->autoDiffDownBtn, 0); + setTag(ui->autoEnemyUpBtn, 0); + setTag(ui->autoEnemyDownBtn, 0); + setTag(ui->replayBtn, 2048); + setTag(ui->list, 15360); + + ui->down1Btn->setButtonIndex(0); + ui->up1Btn->setButtonIndex(1); + ui->down2Btn->setButtonIndex(0); + ui->up2Btn->setButtonIndex(1); + ui->autoDiffUpBtn->setButtonIndex(1); + ui->autoDiffDownBtn->setButtonIndex(0); + ui->autoEnemyUpBtn->setButtonIndex(1); + ui->autoEnemyDownBtn->setButtonIndex(0); + ui->renameBtn->setButtonIndex(31); + ui->deleteBtn->setButtonIndex(21); + ui->replayBtn->setButtonIndex(19); + ui->quitBtn->setButtonIndex(0); + + ui->quitBtn->setToolTip(phraseN(QStringLiteral("STARTCONTROLS"), 0)); + ui->replayBtn->setToolTip(phrases.lookup(QStringLiteral("BTN_REPLAY"))); + + for (int i = 0; i < nPlOffered; ++i) { + PlayerSlot &slot = m_playerSlots[static_cast(i)]; + slot.diffUpBtn = new ButtonC(this); + slot.diffUpBtn->setGeometry(xBrain[i] - 18, yBrain[i] + 39, 12, 12); + slot.diffUpBtn->setButtonIndex(1); + slot.diffUpBtn->onClick = [this, btn = slot.diffUpBtn] { diffClicked(btn); }; + slot.diffDownBtn = new ButtonC(this); + slot.diffDownBtn->setGeometry(xBrain[i] - 18, yBrain[i] + 51, 12, 12); + slot.diffDownBtn->setButtonIndex(0); + slot.diffDownBtn->onClick = [this, btn = slot.diffDownBtn] { diffClicked(btn); }; + setTag(slot.diffUpBtn, 0); + setTag(slot.diffDownBtn, 0); + } + for (int i = 6; i < 9; ++i) { + PlayerSlot &slot = m_playerSlots[static_cast(i)]; + slot.multiBtn = new ButtonC(this); + slot.multiBtn->setGeometry(xBrain[i] - 18, yBrain[i], 12, 12); + slot.multiBtn->onClick = [this, btn = slot.multiBtn] { multiClicked(btn); }; + setTag(slot.multiBtn, 0); + slot.offerMultiple = true; + } + + { + Dpi::Canvas measure; + measure.font().assign(UniFont[static_cast(FontType::Normal)]); + const int x = biColorTextWidth(measure, phraseN(QStringLiteral("STARTCONTROLS"), 7)) / 2; + ui->customizeBtn->move(x0Brain + 32 - 16 - x, ui->customizeBtn->y()); + } + ui->customizeBtn->setButtonIndex(m_autoDiff < 0 ? 3 : 2); + + const auto blitBrainPicture = [](Brain *brain, const QString &itemName) { + GraphicSetItem *item = HGrSystem2 ? HGrSystem2->searchByName(itemName) : nullptr; + if (brain && item) + bitBltBitmap(brain->picture, 0, 0, 64, 64, HGrSystem2->data, item->left, item->top); + }; + blitBrainPicture(GameServer::brainNoTerm, QStringLiteral("BrainNoTerm")); + blitBrainPicture(GameServer::brainSuperVirtual, QStringLiteral("BrainSuperVirtual")); + blitBrainPicture(GameServer::brainTerm, QStringLiteral("BrainTerm")); + blitBrainPicture(GameServer::brainRandom, QStringLiteral("BrainRandom")); + loadAiBrainsPictures(); + + m_emptyPicture.setSize(64, 64); + m_emptyPicture.image().fill(Qt::black); + + initButtons(); + + GameServer::playersBrain[0] = GameServer::brainTerm; + m_slotAvailable = -1; + m_tab = Tab::NewGame; + m_diff0 = 2; + m_turnValid = false; + m_tracking = false; + + m_formerGames.sharedDir = getSavedDir(true); + m_formerGames.userHomeDir = getSavedDir(); + m_formerGames.fileFilter = QLatin1Char('*') + QString::fromLatin1(CevoExt); + updateFormerGames(); + + m_mapFileName.clear(); + m_maps.sharedDir = getMapsDir(true); + m_maps.userHomeDir = getMapsDir(); + m_maps.fileFilter = QLatin1Char('*') + QString::fromLatin1(CevoMapExt); + m_maps.insertFirstItem = phrases.lookup(QStringLiteral("RANMAP")); + m_maps.sortByName = true; + updateMaps(true); + + ui->startBtn->onClick = [this] { startClicked(); }; + ui->down1Btn->onClick = [this] { down1Clicked(); }; + ui->up1Btn->onClick = [this] { up1Clicked(); }; + ui->down2Btn->onClick = [this] { down2Clicked(); }; + ui->up2Btn->onClick = [this] { up2Clicked(); }; + ui->renameBtn->onClick = [this] { renameClicked(); }; + ui->deleteBtn->onClick = [this] { deleteClicked(); }; + ui->quitBtn->onClick = [this] { close(); }; + ui->customizeBtn->onClick = [this] { customizeClicked(); }; + ui->autoDiffUpBtn->onClick = [this] { autoDiffUpClicked(); }; + ui->autoDiffDownBtn->onClick = [this] { autoDiffDownClicked(); }; + ui->autoEnemyUpBtn->onClick = [this] { autoEnemyUpClicked(); }; + ui->autoEnemyDownBtn->onClick = [this] { autoEnemyDownClicked(); }; + ui->replayBtn->onClick = [this] { replayClicked(); }; + + ui->list->installEventFilter(this); + connect(ui->list, &QListWidget::itemClicked, this, [this] { listClicked(); }); + connect(ui->list, &QListWidget::itemDoubleClicked, this, [this] { startClicked(); }); + connect(ui->list, &QListWidget::currentRowChanged, this, [this] { listSelectionChanged(); }); + + onShow = [this] { + MainTexture->setAge(-1); + m_emptyPicture.image().fill(Qt::black); + { + // Textured, darkened placeholder for empty player slots. + m_emptyPicture.canvas().begin(); + fill(m_emptyPicture.canvas(), QRect(0, 0, 64, 64), + QPoint((MainTexture->width() - 64) / 2, (MainTexture->height() - 64) / 2)); + m_emptyPicture.canvas().end(); + } + darkenImage(m_emptyPicture, 28); + + Database::difficulty[0] = m_diff0; + m_selectedAction = MainAction::None; + if (m_showTab == Tab::PreviousGame) + GameServer::previewMap(m_startLandMass); // avoid delay on first tab change + changeTab(m_showTab); + m_background->setEnabled(false); + updateMusic(); + }; + onHide = [this] { + m_diff0 = Database::difficulty[0]; + m_listIndex[static_cast(m_tab)] = ui->list->currentRow(); + m_showTab = m_tab; + m_background->setEnabled(true); + const int formerIndex = m_listIndex[static_cast(Tab::PreviousGame)]; + m_lastGame = formerIndex >= 0 && formerIndex < m_formerGames.count() ? m_formerGames[formerIndex].nameOnly() + : QString(); + const int mapIndex = m_listIndex[static_cast(Tab::Map)]; + m_lastMap = mapIndex >= 0 && mapIndex < m_maps.count() ? m_maps[mapIndex].nameOnly() : QString(); + }; + onActivate = [this] { + if (ui->list->count() > 0 && ui->list->currentItem()) + ui->list->scrollToItem(ui->list->currentItem()); + }; + onClose = [this] { m_direct->close(); }; +} + +StartDlg::~StartDlg() +{ + if (musicPlayer.playing()) + musicPlayer.stop(); + saveConfig(); + delete ui; +} + +void StartDlg::smartInvalidate(int x0, int y0, int x1, int y1, bool invalidateTab0) +{ + Q_UNUSED(invalidateTab0); // the whole offscreen is repainted anyway + update(QRect(x0, y0, x1 - x0, y1 - y0)); +} + +void StartDlg::loadConfig() +{ + QSettings settings; + settings.beginGroup(QStringLiteral("AI")); + for (int i = 0; i < nPlOffered; ++i) { + const QString controlKey = QStringLiteral("Control") + QString::number(i); + const QString diffKey = QStringLiteral("Diff") + QString::number(i); + if (!settings.contains(controlKey)) + settings.setValue(controlKey, i == 0 ? QStringLiteral(":StdIntf") : QStringLiteral("StdAI")); + if (!settings.contains(diffKey)) + settings.setValue(diffKey, 2); + } + settings.endGroup(); + + Cevo::loadConfig(); + m_worldSize = std::clamp(settings.value(QStringLiteral("WorldSize"), DefaultWorldSize).toInt(), 0, MaxWorldSize); + m_startLandMass = settings.value(QStringLiteral("LandMass"), DefaultLandMass).toInt(); + m_maxTurn = settings.value(QStringLiteral("MaxTurn"), 800).toInt(); + m_defaultAI = settings.value(QStringLiteral("DefaultAI"), QStringLiteral("StdAI")).toString(); + m_autoEnemies = settings.value(QStringLiteral("AutoEnemies"), 8).toInt(); + m_autoDiff = settings.value(QStringLiteral("AutoDiff"), 1).toInt(); + m_showTab = static_cast(std::clamp(settings.value(QStringLiteral("StartTab"), 2).toInt(), 0, 3)); + m_lastGame = settings.value(QStringLiteral("LastGame")).toString(); + m_lastMap = settings.value(QStringLiteral("LastMap")).toString(); + GameServer::networkEnabled = settings.value(QStringLiteral("NetworkEnabled"), false).toBool(); + m_multiControl = settings.value(QStringLiteral("MultiControl"), 0).toInt(); + + KeyBindings::keyBindings.loadFromSettings(settings, QStringLiteral("KeyBindings")); +} + +void StartDlg::saveConfig() +{ + Cevo::saveConfig(); + QSettings settings; + settings.setValue(QStringLiteral("WorldSize"), m_worldSize); + settings.setValue(QStringLiteral("LandMass"), m_startLandMass); + settings.setValue(QStringLiteral("MultiControl"), m_multiControl); + settings.setValue(QStringLiteral("StartTab"), static_cast(m_showTab)); + settings.setValue(QStringLiteral("LastGame"), m_lastGame); + settings.setValue(QStringLiteral("LastMap"), m_lastMap); + settings.setValue(QStringLiteral("NetworkEnabled"), GameServer::networkEnabled); + KeyBindings::keyBindings.saveToSettings(settings, QStringLiteral("KeyBindings")); +} + +void StartDlg::loadLanguages() +{ + m_languages.detectAvailable(); +} + +void StartDlg::loadAiBrainsPictures() +{ + for (Brain *brain : GameServer::brains.getByKind(BrainType::AI)) + brain->loadPicture(); +} + +void StartDlg::updateInterface() +{ + const QRect screen = Dpi::Screen::primaryMonitor().boundsRect(); + if (fullScreen) { + const QPoint shift((screen.width() - std::min(screen.width(), 800)) * 3 / 8, + (screen.height() - std::min(screen.height(), 600)) / 3); + move(screen.left() + shift.x(), screen.top() + screen.height() - height() - shift.y()); + // Only the quit button area above the tab strip stays visible, as in the original window region. + QRegion region(0, 0, width(), height()); + region -= QRegion(TabOffset + 4 * TabSize + 2, 0, width() - (TabOffset + 4 * TabSize + 2), TabHeight); + region += QRegion(ui->quitBtn->geometry()); + setMask(region); + } else { + clearMask(); + centerToScreen(); + } +} + +void StartDlg::showSettings() +{ + // TODO: Settings.pas (the configuration dialog) isn't ported yet. +} + +void StartDlg::updateMusic() +{ + if (musicEnabled) { + musicPlayer.setVolume(musicVolume); + if (!musicPlayer.playing()) { + musicPlayer.loadPlaylistFromDir(getMusicDir() + QStringLiteral("/Start")); + musicPlayer.randomizePlaylist(); + if (!musicPlayer.playlist.isEmpty()) + musicPlayer.play(); + } + } else if (musicPlayer.playing()) { + musicPlayer.stop(); + } +} + +FileList &StartDlg::currentFileList() +{ + return m_tab == Tab::Map ? m_maps : m_formerGames; +} + +FileItem *StartDlg::selectedFileItem() +{ + const int row = ui->list->currentRow(); + FileList &fileList = currentFileList(); + if (row < 0 || row >= fileList.count()) + return nullptr; + return &fileList[row]; +} + +void StartDlg::applyPageVisibility() +{ + const quint32 bit = 256u << static_cast(m_page); + const auto children = findChildren(QString(), Qt::FindDirectChildrenOnly); + for (QWidget *child : children) { + if (child->property("tag").isValid()) + child->setVisible((tagOf(child) & bit) != 0); + } +} + +void StartDlg::paintInfo() +{ + switch (m_page) { + case Page::StartRandom: + m_miniMap.mode = MiniMap::Mode::Picture; + m_miniMap.paintRandom(3, m_startLandMass, WorldSizes[m_worldSize]); + break; + case Page::NoLoad: + m_miniMap.mode = MiniMap::Mode::None; + m_miniMap.size = WorldSizes[DefaultWorldSize]; + break; + case Page::Load: { + const FileItem *item = selectedFileItem(); + if (!item) + break; + m_miniMap.loadFromLogFile(item->fileName, m_lastTurn, WorldSizes[DefaultWorldSize]); + if (!m_turnValid) { + m_loadTurn = m_lastTurn; + smartInvalidate(xTurnSlider - 2, y0Mini + 61, xTurnSlider + wTurnSlider + 2, yTurnSlider + 9); + } + m_turnValid = true; + break; + } + case Page::EditRandom: + m_mapFileName.clear(); + m_miniMap.mode = MiniMap::Mode::Picture; + m_miniMap.paintRandom(4, m_startLandMass, WorldSizes[m_worldSize]); + break; + case Page::StartMap: + case Page::EditMap: + if (m_page == Page::EditMap) { + const FileItem *item = selectedFileItem(); + if (!item) + return; + m_mapFileName = item->fileName; + } + m_miniMap.loadFromMapFile(m_mapFileName, m_mapLandTiles, m_mapStartPositions); + if (m_page == Page::EditMap) + smartInvalidate(x0Mini - 112, y0Mini + 61, x0Mini + 112, y0Mini + 91); + break; + case Page::Main: + break; + } + smartInvalidate(x0Mini - lxmax, y0Mini - lymax / 2, x0Mini - lxmax + 2 * lxmax + 4, y0Mini - lymax / 2 + lymax + 4); +} + +void StartDlg::updateFormerGames() +{ + m_formerGames.load(); + // Update last game with new saved game name + if (!GameServer::getLogFileName().isEmpty()) + m_lastGame = QFileInfo(GameServer::getLogFileName()).completeBaseName(); + + const int i = m_formerGames.indexOfNameOnly(m_lastGame); + m_listIndex[static_cast(Tab::PreviousGame)] = i >= 0 ? i : m_formerGames.count() - 1; + m_turnValid = false; +} + +void StartDlg::updateMaps(bool selectLastMap) +{ + m_maps.load(); + auto &mapIndex = m_listIndex[static_cast(Tab::Map)]; + const int i = m_maps.indexOfNameOnly(m_lastMap); + if (selectLastMap && i > 0) { // skip random map on index 0 + mapIndex = i; + m_mapFileName = m_maps[i].fileName; + } else { + mapIndex = m_maps.indexOfNameOnly(QFileInfo(m_mapFileName).completeBaseName()); + } + if (mapIndex < 0) + mapIndex = 0; + m_listIndex[static_cast(Tab::Main)] = mapIndex; +} + +void StartDlg::unlistBackupFile(QString fileName) +{ + if (!GameServer::isAutoSaveFileName(fileName)) + fileName = GameServer::toAutoSaveFileName(fileName); + const QString nameOnly = QFileInfo(fileName).completeBaseName(); + int i = m_formerGames.count() - 1; + while (i >= 0 && QString::compare(m_formerGames[i].nameOnly(), nameOnly, Qt::CaseInsensitive) != 0) + --i; + if (i >= 0) { + m_formerGames.removeAt(i); + if (m_listIndex[static_cast(Tab::NewGame)] == i) + m_listIndex[static_cast(Tab::NewGame)] = 0; + } +} + +void StartDlg::changePage(Page newPage) +{ + m_page = newPage; + switch (m_page) { + case Page::StartRandom: + case Page::StartMap: { + ui->startBtn->setCaption(phraseN(QStringLiteral("STARTCONTROLS"), 1)); + int count; + if (m_page == Page::StartRandom) { + count = nPlOffered; + } else { + count = m_mapStartPositions; + if (count == 0) { + GameServer::playersBrain[0] = GameServer::brainSuperVirtual; + Database::difficulty[0] = 0; + } + if (GameServer::playersBrain[0]->kind == BrainType::NoTerm || + GameServer::playersBrain[0]->kind == BrainType::SuperVirtual) + ++count; + if (count > nPl) + count = nPl; + m_multiControl = count <= nPlOffered ? 0 : InitMulti[count - nPlOffered - 1]; + } + if (InitAlive[count - 1] != m_slotAvailable) { + if (m_page == Page::StartRandom) { // restore AI assignment of last start + QSettings settings; + settings.beginGroup(QStringLiteral("AI")); + for (int p1 = 0; p1 < nPlOffered; ++p1) { + GameServer::playersBrain[static_cast(p1)] = nullptr; + const QString control = settings.value(QStringLiteral("Control") + QString::number(p1)).toString(); + Database::difficulty[static_cast(p1)] = + settings.value(QStringLiteral("Diff") + QString::number(p1), 2).toInt(); + if (!control.isEmpty()) { + for (int j = 0; j < GameServer::brains.count(); ++j) { + if (control == GameServer::brains[j].fileName) + GameServer::playersBrain[static_cast(p1)] = &GameServer::brains[j]; + } + } + } + } else { + for (int p1 = 1; p1 < nPl; ++p1) { + if ((1 << p1) & InitAlive[count - 1]) { + GameServer::playersBrain[static_cast(p1)] = m_brainDefault; + Database::difficulty[static_cast(p1)] = 2; + } else { + GameServer::playersBrain[static_cast(p1)] = nullptr; + } + } + } + } + m_slotAvailable = InitAlive[count - 1]; + for (int i = 0; i < nPlOffered; ++i) { + PlayerSlot &slot = m_playerSlots[static_cast(i)]; + const quint32 tag = + (m_autoDiff < 0 && isPlayableBrain(GameServer::playersBrain[static_cast(i)])) ? 768 : 0; + setTag(slot.diffUpBtn, tag); + setTag(slot.diffDownBtn, tag); + } + for (int i = 6; i < 9; ++i) { + PlayerSlot &slot = m_playerSlots[static_cast(i)]; + if (m_autoDiff < 0 && isPlayableBrain(GameServer::playersBrain[static_cast(i)])) { + setTag(slot.multiBtn, 768); + slot.multiBtn->setButtonIndex(2 + ((m_multiControl >> i) & 1)); + slot.multiBtn->setEnabled(m_page == Page::StartRandom); + } else { + setTag(slot.multiBtn, 0); + } + } + const quint32 enemyTag = (m_autoDiff > 0 && m_page != Page::StartMap) ? 768 : 0; + setTag(ui->autoEnemyUpBtn, enemyTag); + setTag(ui->autoEnemyDownBtn, enemyTag); + const quint32 diffTag = m_autoDiff > 0 ? 768 : 0; + setTag(ui->autoDiffUpBtn, diffTag); + setTag(ui->autoDiffDownBtn, diffTag); + break; + } + case Page::NoLoad: + case Page::Load: + ui->startBtn->setCaption(phraseN(QStringLiteral("STARTCONTROLS"), 2)); + ui->renameBtn->setToolTip(phrases.lookup(QStringLiteral("BTN_RENGAME"))); + ui->deleteBtn->setToolTip(phrases.lookup(QStringLiteral("BTN_DELGAME"))); + break; + case Page::EditRandom: + case Page::EditMap: + ui->startBtn->setCaption(phraseN(QStringLiteral("STARTCONTROLS"), 12)); + ui->renameBtn->setToolTip(phrases.lookup(QStringLiteral("BTN_RENMAP"))); + ui->deleteBtn->setToolTip(phrases.lookup(QStringLiteral("BTN_DELMAP"))); + break; + case Page::Main: + break; + } + + paintInfo(); + applyPageVisibility(); + if (m_page == Page::Load) + ui->replayBtn->setVisible(m_miniMap.mode != MiniMap::Mode::MultiPlayer); + update(); +} + +void StartDlg::changeTab(Tab newTab) +{ + m_tab = newTab; + if (m_tab == Tab::Map || m_tab == Tab::PreviousGame) { + ui->list->blockSignals(true); + ui->list->clear(); + ui->list->addItems(currentFileList().toStringList()); + ui->list->blockSignals(false); + } + if (m_tab != Tab::NewGame) { + if (ui->list->count() > 0) { + const int index = m_listIndex[static_cast(m_tab)]; + ui->list->setCurrentRow(index >= 0 && index < ui->list->count() ? index : 0); + } else { + ui->list->setCurrentRow(-1); + } + } + switch (m_tab) { + case Tab::Main: + changePage(Page::Main); + break; + case Tab::Map: + changePage(ui->list->currentRow() == 0 ? Page::EditRandom : Page::EditMap); + break; + case Tab::NewGame: + changePage(m_mapFileName.isEmpty() ? Page::StartRandom : Page::StartMap); + break; + case Tab::PreviousGame: + changePage(m_formerGames.count() == 0 ? Page::NoLoad : Page::Load); + break; + } + if (ui->list->isVisible()) + ui->list->setFocus(); +} + +void StartDlg::mousePressEvent(QMouseEvent *event) +{ + BufferedDrawDlg::mousePressEvent(event); + if (event->button() != Qt::LeftButton) + return; + const int x = event->pos().x(); + const int y = event->pos().y(); + if (y < TabHeight + 1 && x - TabOffset < TabSize * 4 && x - TabOffset >= 0 && + (x - TabOffset) / TabSize != static_cast(m_tab)) { + m_listIndex[static_cast(m_tab)] = ui->list->currentRow(); + changeTab(static_cast((x - TabOffset) / TabSize)); + } else if (m_page == Page::Main) { + switch (m_selectedAction) { + case MainAction::Config: showSettings(); break; + case MainAction::Manual: GameServer::directHelp(cStartHelp); break; + case MainAction::Credits: GameServer::directHelp(cStartCredits); break; + case MainAction::AIDev: + QDesktopServices::openUrl(QUrl::fromLocalFile(getAppSharePath(QString::fromLatin1(AITemplateFileName)))); + break; + case MainAction::Web: QDesktopServices::openUrl(QUrl(QString::fromLatin1(CevoHomepage))); break; + case MainAction::None: break; + } + } else if (m_autoDiff < 0 && (m_page == Page::StartRandom || (m_page == Page::StartMap && m_mapStartPositions > 0))) { + for (int i = 0; i < nPlOffered; ++i) { + if (((1 << i) & m_slotAvailable) && x >= xBrain[i] && y >= yBrain[i] && x < xBrain[i] + 64 && + y < yBrain[i] + 64) { + initPopup(i); + break; + } + } + } else if (m_autoDiff > 1 && (m_page == Page::StartRandom || m_page == Page::StartMap) && x >= xDefault && + y >= yDefault && x < xDefault + 64 && y < yDefault + 64) { + if (GameServer::brains.kindCount(BrainType::AI) < 2) + simpleMessage(phrases.lookup(QStringLiteral("NOMOD"))); + else + initPopup(-1); + } else if (m_page == Page::Load && m_lastTurn > 0 && y >= yTurnSlider && y < yTurnSlider + 7 && + x >= xTurnSlider && x <= xTurnSlider + wTurnSlider) { + m_loadTurn = m_lastTurn * (x - xTurnSlider) / wTurnSlider; + smartInvalidate(xTurnSlider - 2, y0Mini + 61, xTurnSlider + wTurnSlider + 2, yTurnSlider + 9); + m_tracking = true; + } +} + +void StartDlg::mouseReleaseEvent(QMouseEvent *event) +{ + BufferedDrawDlg::mouseReleaseEvent(event); + m_tracking = false; +} + +void StartDlg::mouseMoveEvent(QMouseEvent *event) +{ + BufferedDrawDlg::mouseMoveEvent(event); + int x = event->pos().x(); + const int y = event->pos().y(); + if (m_tracking) { + x = std::clamp(x - xTurnSlider, 0, wTurnSlider); + const int oldLoadTurn = m_loadTurn; + m_loadTurn = m_lastTurn * x / wTurnSlider; + if (m_loadTurn != oldLoadTurn) { + const int lo = std::min(m_loadTurn, oldLoadTurn); + const int hi = std::max(m_loadTurn, oldLoadTurn); + smartInvalidate(xTurnSlider + lo * wTurnSlider / m_lastTurn, yTurnSlider, + xTurnSlider + hi * wTurnSlider / m_lastTurn + 1, yTurnSlider + 7); + smartInvalidate(344, y0Mini + 61, 514, y0Mini + 82); + } + } else if (m_page == Page::Main) { + MainAction newAction = MainAction::None; + if (x >= ActionSideBorder && x < width() - ActionSideBorder && y >= yAction - 8 && + y < height() - ActionBottomBorder) { + const int index = (y - (yAction - 8)) / ActionPitch; + if (index >= 0 && index < static_cast(MainAction::None) && + std::find(m_actionsOffered.begin(), m_actionsOffered.end(), static_cast(index)) != + m_actionsOffered.end()) + newAction = static_cast(index); + } + if (newAction != m_selectedAction) { + const auto invalidateAction = [this](MainAction action) { + const int row = static_cast(action); + smartInvalidate(ActionSideBorder, yAction + row * ActionPitch - 8, width() - ActionSideBorder, + yAction + (row + 1) * ActionPitch - 8); + }; + if (m_selectedAction != MainAction::None) + invalidateAction(m_selectedAction); + m_selectedAction = newAction; + if (m_selectedAction != MainAction::None) + invalidateAction(m_selectedAction); + } + } +} + +void StartDlg::keyPressEvent(QKeyEvent *event) +{ + const QKeySequence shortcut(event->modifiers() | event->key()); + if (KeyBindings::bFullScreen && KeyBindings::bFullScreen->test(shortcut)) { + fullScreen = !fullScreen; + updateInterface(); + m_background->updateInterface(); + activateWindow(); + } else if (KeyBindings::bHelp && KeyBindings::bHelp->test(shortcut)) { + GameServer::directHelp(cStartHelp); + } else { + BufferedDrawDlg::keyPressEvent(event); + } +} + +bool StartDlg::eventFilter(QObject *watched, QEvent *event) +{ + if (watched == ui->list && event->type() == QEvent::KeyPress) { + auto *keyEvent = static_cast(event); + if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) { + startClicked(); + return true; + } + if (keyEvent->key() == Qt::Key_Delete) { + if (ui->deleteBtn->isVisible()) + deleteClicked(); + return true; + } + keyPressEvent(keyEvent); + } + return BufferedDrawDlg::eventFilter(watched, event); +} + +void StartDlg::offerBrain(QMenu &menu, Brain *brain, int fixedLines) +{ + const QString caption = brain ? brain->name() : phrases.lookup(QStringLiteral("NOMOD")); + int position = fixedLines; + const QList actions = menu.actions(); + while (position < actions.size() && !captionLess(caption, actions.at(position)->text()) && + QString::compare(caption, actions.at(position)->text(), Qt::CaseInsensitive) != 0) + ++position; + auto *action = new QAction(caption, &menu); + action->setCheckable(true); + const int brainIndex = GameServer::brains.indexOf(brain); + action->setChecked(m_playerPopupIndex < 0 ? m_brainDefault == brain + : GameServer::playersBrain[static_cast(m_playerPopupIndex)] == brain); + connect(action, &QAction::triggered, this, [this, brainIndex] { brainClicked(brainIndex); }); + if (position < actions.size()) + menu.insertAction(actions.at(position), action); + else + menu.addAction(action); +} + +void StartDlg::initPopup(int playerIndex) +{ + m_playerPopupIndex = playerIndex; + QMenu menu(this); + int fixedLines = 0; + const auto addSeparator = [&menu, &fixedLines] { + menu.addSeparator(); + ++fixedLines; + }; + const auto offerAIs = [&](bool onlyAvailable) { + for (Brain *ai : GameServer::brains.getByKind(BrainType::AI)) { + const bool offered = onlyAvailable + ? ((ai->flags & fMultiple) || !(ai->flags & fUsed) || + ai == GameServer::playersBrain[static_cast(m_playerPopupIndex)]) + : (ai->flags & fMultiple) != 0; + if (offered) + offerBrain(menu, ai, fixedLines); + } + }; + + if (playerIndex < 0) { // select default AI + if (GameServer::networkEnabled) { + offerBrain(menu, GameServer::brainNetworkClient, fixedLines); + ++fixedLines; + } + addSeparator(); + if (GameServer::brains.kindCount(BrainType::AI) >= 2) { + offerBrain(menu, GameServer::brainRandom, fixedLines); + ++fixedLines; + } + offerAIs(false); + } else { + if (playerIndex > 0) { + offerBrain(menu, nullptr, fixedLines); + ++fixedLines; + } + for (int i = GameServer::brains.indexOf(GameServer::brainTerm); i >= 0; --i) { // offer game interfaces + if (playerIndex == 0 || (GameServer::brains[i].kind == BrainType::Term && + GameServer::playersBrain[0]->kind != BrainType::NoTerm)) { + offerBrain(menu, &GameServer::brains[i], fixedLines); + ++fixedLines; + } + } + if (playerIndex > 0) { + if (GameServer::networkEnabled) { + offerBrain(menu, GameServer::brainNetworkServer, fixedLines); + ++fixedLines; + } + addSeparator(); + if (GameServer::brains.kindCount(BrainType::AI) >= 2) { + offerBrain(menu, GameServer::brainRandom, fixedLines); + ++fixedLines; + } + offerAIs(true); + } + } + + QPoint position; + if (playerIndex < 0) + position = QPoint(xDefault + 4, yDefault + 4); + else if (yBrain[playerIndex] > y0Brain) + position = QPoint(xBrain[playerIndex] + 4, yBrain[playerIndex] + 60); + else + position = QPoint(xBrain[playerIndex] + 4, yBrain[playerIndex] + 4); + menu.exec(mapToGlobal(position)); +} + +void StartDlg::brainClicked(int brainIndex) +{ + if (m_playerPopupIndex < 0) { // change default AI + m_brainDefault = brainIndex >= 0 ? &GameServer::brains[brainIndex] : nullptr; + smartInvalidate(xDefault, yDefault, xDefault + 64, yDefault + 64); + return; + } + const int slotIndex = m_playerPopupIndex; + const auto index = static_cast(slotIndex); + PlayerSlot &slot = m_playerSlots[index]; + Brain *&slotBrain = GameServer::playersBrain[index]; + if (slotBrain) + slotBrain->flags &= ~fUsed; + if (brainIndex < 0) { + slotBrain = nullptr; + slot.diffUpBtn->setVisible(false); + slot.diffDownBtn->setVisible(false); + if (slot.offerMultiple) { + slot.multiBtn->setVisible(false); + slot.multiBtn->setButtonIndex(2 + ((m_multiControl >> slotIndex) & 1)); + } + m_multiControl &= ~(1 << slotIndex); + } else { + slotBrain = &GameServer::brains[brainIndex]; + const bool playable = isPlayableBrain(slotBrain); + slot.diffUpBtn->setVisible(playable); + slot.diffDownBtn->setVisible(playable); + if (slot.offerMultiple) { + slot.multiBtn->setVisible(playable); + slot.multiBtn->setButtonIndex(2 + ((m_multiControl >> slotIndex) & 1)); + } + slotBrain->flags |= fUsed; + Database::difficulty[index] = + (slotBrain->kind == BrainType::NoTerm || slotBrain->kind == BrainType::SuperVirtual) ? 0 : 2; + if (slotIndex == 0 && !m_mapFileName.isEmpty()) + changePage(m_page); + if (slotBrain->kind == BrainType::NoTerm) { // turn all local players off + for (int i = 1; i < static_cast(m_playerSlots.size()); ++i) { + Brain *&other = GameServer::playersBrain[static_cast(i)]; + if (other && other->kind == BrainType::Term) { + PlayerSlot &otherSlot = m_playerSlots[static_cast(i)]; + other = nullptr; + otherSlot.diffUpBtn->setVisible(false); + setTag(otherSlot.diffUpBtn, 0); + otherSlot.diffDownBtn->setVisible(false); + setTag(otherSlot.diffDownBtn, 0); + if (otherSlot.offerMultiple) { + otherSlot.multiBtn->setVisible(false); + setTag(otherSlot.multiBtn, 0); + } + smartInvalidate(xBrain[i] - 31, yBrain[i] - 1, xBrain[i] + 64, otherSlot.diffUpBtn->y() + 25); + } + } + GameServer::brainTerm->flags &= ~fUsed; + } + } + smartInvalidate(xBrain[slotIndex] - 31, yBrain[slotIndex] - 1, xBrain[slotIndex] + 64, slot.diffUpBtn->y() + 25); +} + +void StartDlg::startClicked() +{ + switch (m_page) { + case Page::Load: { // load + const FileItem *item = selectedFileItem(); + if (!item) + return; + const QString fileName = item->fileName; + QString writeLogFileName; + FileList &fileList = *item->list; + if (fileName.startsWith(fileList.userHomeDir)) { + writeLogFileName = fileName; + } else { + const QString nameOnly = item->nameOnly(); + writeLogFileName = fileList.userHomeDir + QLatin1Char('/') + nameOnly + QString::fromLatin1(CevoExt); + while (fileList.indexOfNameOnly(QFileInfo(writeLogFileName).completeBaseName()) != -1) + writeLogFileName = QFileInfo(writeLogFileName).path() + QLatin1Char('/') + + incrementFileName(QFileInfo(writeLogFileName).completeBaseName()) + + QString::fromLatin1(CevoExt); + } + if (GameServer::loadGame(fileName, writeLogFileName, m_loadTurn, false)) + unlistBackupFile(fileName); + else + simpleMessage(phrases.lookup(QStringLiteral("LOADERR"))); + m_slotAvailable = -1; + break; + } + case Page::StartRandom: + case Page::StartMap: { + if (!GameServer::playersBrain[0]) + return; + if (m_page == Page::StartMap && m_mapStartPositions == 0 && m_autoDiff > 0) { + simpleMessage(phrases.lookup(QStringLiteral("NOSTARTPOS"))); + return; + } + QSettings settings; + int gameCount = settings.value(QStringLiteral("GameCount"), 0).toInt(); + QDir().mkpath(getSavedDir()); + QString fileName; + if (m_autoDiff < 0 && GameServer::playersBrain[0]->kind == BrainType::NoTerm) { + fileName = getSavedDir() + QStringLiteral("/Round") + QString::number(QCoreApplication::applicationPid()) + + QString::fromLatin1(CevoExt); + } else { + ++gameCount; + fileName = getSavedDir() + QLatin1Char('/') + + formatPhrase(QStringLiteral("GAME"), { QString::number(gameCount) }) + + QString::fromLatin1(CevoExt); + } + + // Save settings and AI assignment + if (m_page == Page::StartRandom) { + saveConfig(); + settings.beginGroup(QStringLiteral("AI")); + if (m_autoDiff < 0) { + for (int i = 0; i < nPlOffered; ++i) { + const Brain *brain = GameServer::playersBrain[static_cast(i)]; + settings.setValue(QStringLiteral("Control") + QString::number(i), + brain ? brain->fileName : QString()); + settings.setValue(QStringLiteral("Diff") + QString::number(i), + Database::difficulty[static_cast(i)]); + } + } + settings.endGroup(); + } + + if (m_brainDefault && m_brainDefault->kind != BrainType::NetworkClient) { + if (m_autoDiff > 0) { + settings.setValue(QStringLiteral("DefaultAI"), m_brainDefault->fileName); + m_slotAvailable = 0; // PlayerSlot will be invalid hereafter + GameServer::playersBrain[0] = GameServer::brainTerm; + Database::difficulty[0] = PlayerAutoDiff[m_autoDiff - 1]; + for (int i = 1; i < nPl; ++i) { + if ((m_page == Page::StartRandom && i <= m_autoEnemies) || + (m_page == Page::StartMap && i < m_mapStartPositions)) { + GameServer::playersBrain[static_cast(i)] = + m_autoDiff == 1 ? GameServer::brains.beginner() : m_brainDefault; + Database::difficulty[static_cast(i)] = EnemyAutoDiff[m_autoDiff - 1]; + } else { + GameServer::playersBrain[static_cast(i)] = nullptr; + } + } + } else { + for (int i = 6; i < 9; ++i) { + const auto index = static_cast(i); + if (GameServer::playersBrain[0]->kind != BrainType::NoTerm && (m_multiControl & (1 << i))) { + GameServer::playersBrain[index + 3] = GameServer::playersBrain[index]; + Database::difficulty[index + 3] = Database::difficulty[index]; + GameServer::playersBrain[index + 6] = GameServer::playersBrain[index]; + Database::difficulty[index + 6] = Database::difficulty[index]; + } else { + GameServer::playersBrain[index + 3] = nullptr; + GameServer::playersBrain[index + 6] = nullptr; + } + } + } + } + settings.setValue(QStringLiteral("AutoDiff"), m_autoDiff); + settings.setValue(QStringLiteral("AutoEnemies"), m_autoEnemies); + settings.setValue(QStringLiteral("MaxTurn"), m_maxTurn); + settings.setValue(QStringLiteral("GameCount"), gameCount); + settings.sync(); + + GameServer::startNewGame(fileName, m_mapFileName, WorldSizes[m_worldSize].x(), WorldSizes[m_worldSize].y(), + m_startLandMass, m_maxTurn); + unlistBackupFile(fileName); + break; + } + case Page::EditMap: { + const FileItem *item = selectedFileItem(); + if (!item) + return; + const QString fileName = item->fileName; + FileList &fileList = *item->list; + QString writeFileMap; + if (fileName.startsWith(fileList.userHomeDir)) { + writeFileMap = fileName; + } else { + writeFileMap = fileList.userHomeDir + QLatin1Char('/') + item->nameOnly() + QString::fromLatin1(CevoMapExt); + while (fileList.indexOfNameOnly(QFileInfo(writeFileMap).completeBaseName()) != -1) + writeFileMap = QFileInfo(writeFileMap).path() + QLatin1Char('/') + + incrementFileName(QFileInfo(writeFileMap).completeBaseName()) + + QString::fromLatin1(CevoMapExt); + } + GameServer::editMap(m_mapFileName, writeFileMap, lxmax, lymax, m_startLandMass); + break; + } + case Page::EditRandom: { // new map + QSettings settings; + const int mapCount = settings.value(QStringLiteral("MapCount"), 0).toInt() + 1; + settings.setValue(QStringLiteral("MapCount"), mapCount); + settings.sync(); + QDir().mkpath(getMapsDir()); + m_mapFileName = getMapsDir() + QLatin1Char('/') + + formatPhrase(QStringLiteral("MAP"), { QString::number(mapCount) }) + + QString::fromLatin1(CevoMapExt); + GameServer::editMap(m_mapFileName, m_mapFileName, WorldSizes[m_worldSize].x(), WorldSizes[m_worldSize].y(), + m_startLandMass); + break; + } + case Page::NoLoad: + case Page::Main: + break; + } +} + +void StartDlg::listClicked() +{ + if (m_tab == Tab::Map && (ui->list->currentRow() == 0) != (m_page == Page::EditRandom)) { + m_page = ui->list->currentRow() == 0 ? Page::EditRandom : Page::EditMap; + applyPageVisibility(); + smartInvalidate(328, ui->up1Btn->y() - 12, width(), ui->up2Btn->y() + 35); + } + if (m_page == Page::Load) + m_turnValid = false; + paintInfo(); + if (m_page == Page::Load) + ui->replayBtn->setVisible(m_miniMap.mode != MiniMap::Mode::MultiPlayer); +} + +void StartDlg::listSelectionChanged() +{ + const FileItem *item = selectedFileItem(); + if (!item) + return; + const bool inHome = item->fileName.startsWith(item->list->userHomeDir); + ui->deleteBtn->setVisible(inHome); + ui->renameBtn->setVisible(inHome); +} + +void StartDlg::renameClicked() +{ + FileItem *item = selectedFileItem(); + if (!item) + return; + InputDlg inputDlg; + inputDlg.setWindowTitle(phrases.lookup(m_page == Page::Load ? QStringLiteral("TITLE_BOOKNAME") + : QStringLiteral("TITLE_MAPNAME"))); + const int row = ui->list->currentRow(); + inputDlg.editInput()->setText(ui->list->item(row)->text()); + inputDlg.centerToRect(geometry()); + inputDlg.showModal(); + QString newName = inputDlg.editInput()->text(); + while (GameServer::isAutoSaveFileName(newName)) + newName.remove(0, 1); + if (inputDlg.modalResult() != Dpi::ModalResult::Ok || newName.isEmpty() || + newName == ui->list->item(row)->text()) + return; + static const QString forbidden = QStringLiteral("\\/:*?\"<>|"); + for (const QChar c : newName) { + if (forbidden.contains(c)) { + simpleMessage(formatPhrase(QStringLiteral("NOFILENAME"), { QString(c) })); + return; + } + } + FileList &fileList = *item->list; + if (fileList.indexOfNameOnly(newName) != -1) + return; + + const QString fileName = item->fileName; + const QFileInfo info(fileName); + const bool ok = QFile::rename(fileName, info.path() + QLatin1Char('/') + newName + QLatin1Char('.') + info.suffix()); + if (m_page != Page::Load) { // rename the map picture + const QString pictureFileName = info.path() + QLatin1Char('/') + info.completeBaseName() + + QString::fromLatin1(CevoMapPictureExt); + if (QFileInfo::exists(pictureFileName)) + QFile::rename(pictureFileName, info.path() + QLatin1Char('/') + newName + + QString::fromLatin1(CevoMapPictureExt)); + } + if (ok) { + item->setNameOnly(newName); + fileList.sortItems(); + ui->list->blockSignals(true); + ui->list->clear(); + ui->list->addItems(fileList.toStringList()); + ui->list->blockSignals(false); + ui->list->setCurrentRow(fileList.indexOfNameOnly(newName)); + if (m_page == Page::EditMap) + paintInfo(); + update(); + } +} + +void StartDlg::deleteClicked() +{ + const int row = ui->list->currentRow(); + FileItem *item = selectedFileItem(); + if (!item) + return; + MessgDlg dlg; + dlg.messageText = phrases.lookup(m_page == Page::Load ? QStringLiteral("DELETEQUERY") + : QStringLiteral("MAPDELETEQUERY")); + dlg.kind = MessageKind::OkCancel; + dlg.showModal(); + if (dlg.modalResult() != Dpi::ModalResult::Ok) + return; + QFile::remove(item->fileName); + FileList &fileList = *item->list; + fileList.removeAt(row); + ui->list->blockSignals(true); + delete ui->list->takeItem(row); + ui->list->blockSignals(false); + if (ui->list->count() == 0) { + changePage(Page::NoLoad); + } else { + ui->list->setCurrentRow(row == 0 ? 0 : row - 1); + if (m_page == Page::EditMap && ui->list->currentRow() == 0) { + changePage(Page::EditRandom); + } else { + update(); + if (m_page == Page::Load) + m_turnValid = false; + paintInfo(); + if (m_page == Page::Load) + ui->replayBtn->setVisible(m_miniMap.mode != MiniMap::Mode::MultiPlayer); + } + } +} + +void StartDlg::diffClicked(QWidget *sender) +{ + for (int i = 0; i < nPlOffered; ++i) { + const PlayerSlot &slot = m_playerSlots[static_cast(i)]; + int &difficulty = Database::difficulty[static_cast(i)]; + if ((sender == slot.diffUpBtn && difficulty < 3) || (sender == slot.diffDownBtn && difficulty > 1)) { + difficulty += sender == slot.diffUpBtn ? 1 : -1; + smartInvalidate(xBrain[i] - 18, yBrain[i] + 19, xBrain[i] - 18 + 12, yBrain[i] + (19 + 14)); + } + } +} + +void StartDlg::multiClicked(QWidget *sender) +{ + for (int i = 6; i < 9; ++i) { + PlayerSlot &slot = m_playerSlots[static_cast(i)]; + if (sender == slot.multiBtn) { + m_multiControl ^= 1 << i; + slot.multiBtn->setButtonIndex(2 + ((m_multiControl >> i) & 1)); + } + } +} + +void StartDlg::up1Clicked() +{ + if (m_worldSize < MaxWorldSize - 1) { + ++m_worldSize; + paintInfo(); + smartInvalidate(344, y0Mini - 77, 510, y0Mini - 77 + 21); + } +} + +void StartDlg::down1Clicked() +{ + if (m_worldSize > 0) { + --m_worldSize; + paintInfo(); + smartInvalidate(344, y0Mini - 77, 510, y0Mini - 77 + 21); + } +} + +void StartDlg::up2Clicked() +{ + switch (m_page) { + case Page::StartRandom: + case Page::StartMap: + if (m_maxTurn < 1400) { + m_maxTurn += 200; + smartInvalidate(344, y0Mini + 61, 514, y0Mini + 82); + } + break; + case Page::Load: + if (m_loadTurn < m_lastTurn) { + ++m_loadTurn; + smartInvalidate(xTurnSlider - 2, y0Mini + 61, xTurnSlider + wTurnSlider + 2, yTurnSlider + 9); + } + break; + case Page::EditRandom: + if (m_startLandMass < 96) { + m_startLandMass += 5; + paintInfo(); + smartInvalidate(344, y0Mini + 61, 514, y0Mini + 61 + 21); + } + break; + default: + break; + } +} + +void StartDlg::down2Clicked() +{ + switch (m_page) { + case Page::StartRandom: + case Page::StartMap: + if (m_maxTurn > 400) { + m_maxTurn -= 200; + smartInvalidate(344, y0Mini + 61, 514, y0Mini + 82); + } + break; + case Page::Load: + if (m_loadTurn > 0) { + --m_loadTurn; + smartInvalidate(xTurnSlider - 2, y0Mini + 61, xTurnSlider + wTurnSlider + 2, yTurnSlider + 9); + } + break; + case Page::EditRandom: + if (m_startLandMass > 10) { + m_startLandMass -= 5; + paintInfo(); + smartInvalidate(344, y0Mini + 61, 514, y0Mini + 61 + 21); + } + break; + default: + break; + } +} + +void StartDlg::customizeClicked() +{ + m_autoDiff = -m_autoDiff; + ui->customizeBtn->setButtonIndex(ui->customizeBtn->buttonIndex() ^ 1); + changePage(m_page); +} + +void StartDlg::autoDiffUpClicked() +{ + if (m_autoDiff < 5) { + ++m_autoDiff; + smartInvalidate(120, y0Mini + 61, 272, y0Mini + 61 + 21); + smartInvalidate(xDefault - 2, yDefault - 2, xDefault + 64 + 2, yDefault + 64 + 2); + } +} + +void StartDlg::autoDiffDownClicked() +{ + if (m_autoDiff > 1) { + --m_autoDiff; + smartInvalidate(120, y0Mini + 61, 272, y0Mini + 61 + 21); + smartInvalidate(xDefault - 2, yDefault - 2, xDefault + 64 + 2, yDefault + 64 + 2); + } +} + +void StartDlg::autoEnemyUpClicked() +{ + if (m_autoEnemies < nPl - 1) { + ++m_autoEnemies; + smartInvalidate(160, yMain + 140, 198, yMain + 140 + 21); + } +} + +void StartDlg::autoEnemyDownClicked() +{ + if (m_autoEnemies > 0) { + --m_autoEnemies; + smartInvalidate(160, yMain + 140, 198, yMain + 140 + 21); + } +} + +void StartDlg::replayClicked() +{ + const FileItem *item = selectedFileItem(); + if (!item) + return; + GameServer::loadGame(item->fileName, item->fileName, m_lastTurn, true); + m_slotAvailable = -1; +} + +} // namespace Cevo diff --git a/game/Start.h b/game/Start.h new file mode 100644 index 0000000..9db3d56 --- /dev/null +++ b/game/Start.h @@ -0,0 +1,173 @@ +// 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 + +#include "Back.h" +#include "Brain.h" +#include "Cevo/CevoBaseWin.h" +#include "Cevo/FileList.h" +#include "Languages.h" +#include "MiniMap.h" + +#include + +#include +#include +#include + +class QMenu; + +QT_BEGIN_NAMESPACE +namespace Ui { +class StartDlg; +} +QT_END_NAMESPACE + +namespace Cevo { + +class ButtonC; +class DirectDlg; + +// Equivalent of Start.pas's TStartDlg: the start screen - tabs for the main +// menu, the map editor, new games and earlier games, with the player slot +// setup, difficulty/world options, the map preview and the Start button. +class StartDlg : public BufferedDrawDlg { + Q_OBJECT +public: + enum class Page { StartRandom, StartMap, NoLoad, Load, EditRandom, EditMap, Main }; + enum class Tab { Main, Map, NewGame, PreviousGame }; + enum class MainAction { Config, Manual, Credits, AIDev, Web, None }; + + explicit StartDlg(DirectDlg *direct, QWidget *parent = nullptr); + ~StartDlg() override; + + Background *background() const { return m_background.get(); } + Languages &languages() { return m_languages; } + + // Called by DirectDlg when a game ends or a map was edited. + void updateFormerGames(); + void updateMaps(bool selectLastMap); + +protected: + void offscreenPaint() override; + void mousePressEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void mouseMoveEvent(QMouseEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; + bool eventFilter(QObject *watched, QEvent *event) override; + +private: + struct PlayerSlot { + ButtonC *diffUpBtn = nullptr; + ButtonC *diffDownBtn = nullptr; + ButtonC *multiBtn = nullptr; + bool offerMultiple = false; + }; + + // Persisted settings (Registry in the original, QSettings here). + void loadConfig(); + void saveConfig(); + void loadLanguages(); + void loadAiBrainsPictures(); + void updateInterface(); + void showSettings(); + void updateMusic(); + + void drawAction(int y, int iconIndex, const QString &headerItem, const QString &textItem); + void paintInfo(); + void changePage(Page newPage); + void changeTab(Tab newTab); + void smartInvalidate(int x0, int y0, int x1, int y1, bool invalidateTab0 = false); + void applyPageVisibility(); + void unlistBackupFile(QString fileName); + // The list shown on the current tab. + FileList ¤tFileList(); + FileItem *selectedFileItem(); + + void initPopup(int playerIndex); + void offerBrain(QMenu &menu, Brain *brain, int fixedLines); + void brainClicked(int brainIndex); + + void startClicked(); + void listClicked(); + void listSelectionChanged(); + void renameClicked(); + void deleteClicked(); + void diffClicked(QWidget *sender); + void multiClicked(QWidget *sender); + void up1Clicked(); + void down1Clicked(); + void up2Clicked(); + void down2Clicked(); + void customizeClicked(); + void autoDiffUpClicked(); + void autoDiffDownClicked(); + void autoEnemyUpClicked(); + void autoEnemyDownClicked(); + void replayClicked(); + + int m_worldSize = 0; + int m_startLandMass = 0; + int m_maxTurn = 800; + int m_autoEnemies = 8; + int m_autoDiff = 1; + int m_multiControl = 0; + Page m_page = Page::Main; + Tab m_showTab = Tab::NewGame; + Tab m_tab = Tab::NewGame; + int m_diff0 = 2; + Brain *m_brainDefault = nullptr; + int m_mapLandTiles = 0; + int m_mapStartPositions = 0; + int m_loadTurn = 0; + int m_lastTurn = 0; // last turn of the selected former game + int m_slotAvailable = -1; + int m_playerPopupIndex = -1; // slot concerned by the brain context menu + std::array m_listIndex{}; + QString m_mapFileName; + FileList m_formerGames; + FileList m_maps; + std::array m_playerSlots; + std::vector m_actionsOffered; + MainAction m_selectedAction = MainAction::None; + bool m_turnValid = false; + bool m_tracking = false; + QString m_defaultAI; + QString m_lastGame; + QString m_lastMap; + + DirectDlg *m_direct; + std::unique_ptr m_background; + Dpi::Bitmap m_emptyPicture; + MiniMap m_miniMap; + Languages m_languages; + Ui::StartDlg *ui; +}; + +} // namespace Cevo diff --git a/game/Start.ui b/game/Start.ui new file mode 100644 index 0000000..9813682 --- /dev/null +++ b/game/Start.ui @@ -0,0 +1,143 @@ + + + + StartDlg + + + + 0 + 0 + 556 + 326 + + + + C-evo + + + + 38928610025 + + + + + 5221111212 + + + + + 522991212 + + + + + 412982525 + + + + + 441982525 + + + + + 5222491212 + + + + + 5222371212 + + + + + 53072525 + + + + + 1203021212 + + + + + 2802371212 + + + + + 2802491212 + + + + + 2061521212 + + + + + 2061641212 + + + + + 3522862525 + + + + + 4564266238 + + + + + + Cevo::ButtonA + QWidget +
Cevo/CevoButtonA.h
+
+ + Cevo::ButtonB + QWidget +
Cevo/CevoButtonB.h
+
+ + Cevo::ButtonC + QWidget +
Cevo/CevoButtonC.h
+
+ + Cevo::ListBoxEx + QListWidget +
Cevo/CevoListBoxEx.h
+
+
+ +
diff --git a/game/StartLayout.h b/game/StartLayout.h new file mode 100644 index 0000000..8ff8c07 --- /dev/null +++ b/game/StartLayout.h @@ -0,0 +1,87 @@ +// 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 + +// Start.pas's implementation-section constants, shared by Start.cpp and +// Start.Paint.cpp. + +#include + +namespace Cevo { +namespace StartLayout { + +// predefined world sizes +// attention: lx * ly + 1 must be prime! +constexpr int MaxWorldSize = 6; +constexpr QPoint WorldSizes[MaxWorldSize] = { QPoint(30, 46), QPoint(40, 52), QPoint(50, 60), + QPoint(60, 70), QPoint(75, 82), QPoint(100, 96) }; +constexpr int DefaultWorldTiles = 4150; +constexpr int DefaultWorldSize = 3; +constexpr int DefaultLandMass = 30; + +constexpr int nPlOffered = 9; +constexpr int yMain = 14; +constexpr int xActionIcon = 55; +constexpr int xAction = 111; +constexpr int yAction = 60; +constexpr int ActionPitch = 56; +constexpr int ActionSideBorder = 24; +constexpr int ActionBottomBorder = 10; +constexpr int x0Mini = 437; +constexpr int y0Mini = 178; +constexpr int xTurnSlider = 346; +constexpr int yTurnSlider = 262; +constexpr int wTurnSlider = 168; +constexpr int yLogo = 74; +constexpr int xDefault = 234; +constexpr int yDefault = 148; +constexpr int x0Brain = 146; +constexpr int y0Brain = 148; +constexpr int dxBrain = 104; +constexpr int dyBrain = 80; +constexpr int xBrain[nPlOffered] = { x0Brain, x0Brain, x0Brain + dxBrain, x0Brain + dxBrain, x0Brain + dxBrain, + x0Brain, x0Brain - dxBrain, x0Brain - dxBrain, x0Brain - dxBrain }; +constexpr int yBrain[nPlOffered] = { y0Brain, y0Brain - dyBrain, y0Brain - dyBrain, y0Brain, y0Brain + dyBrain, + y0Brain + dyBrain, y0Brain + dyBrain, y0Brain, y0Brain - dyBrain }; +constexpr int TabOffset = -115; +constexpr int TabSize = 159; +constexpr int TabHeight = 40; + +// Bit set of the player slots offered for n (1-based) players. +constexpr int InitAlive[15] = { 1, 1 + 2, 1 + 2 + 32, 1 + 2 + 8 + 128, 1 + 2 + 8 + 32 + 128, + 1 + 2 + 8 + 16 + 64 + 128, 1 + 2 + 4 + 16 + 32 + 64 + 256, 511 - 32, 511, + 511 - 32, 511, 511 - 32, 511, 511 - 32, 511 }; +// Multi-controlled slots for n = 10..15 players. +constexpr int InitMulti[6] = { 256, 256, 256 + 128, 256 + 128, 256 + 128 + 64, 256 + 128 + 64 }; + +constexpr int PlayerAutoDiff[5] = { 1, 1, 2, 2, 3 }; +constexpr int EnemyAutoDiff[5] = { 4, 3, 2, 1, 1 }; + +} // namespace StartLayout +} // namespace Cevo diff --git a/main.cpp b/main.cpp index e286969..29f356f 100644 --- a/main.cpp +++ b/main.cpp @@ -26,9 +26,14 @@ // The fact that you are presently reading this means that you have had // knowledge of the CeCILL license and that you accept its terms. +#include "game/Direct.h" +#include "game/GameServer.h" +#include #include "game/Global.h" +#include "game/Start.h" #include +#include #include #include @@ -38,6 +43,7 @@ int main(int argc, char *argv[]) QCoreApplication::setOrganizationName(QStringLiteral("c-evo-evo")); QCoreApplication::setApplicationName(QStringLiteral("c-evo-evo")); Cevo::initDirectories(QCoreApplication::arguments()); + Cevo::loadConfig(); Cevo::loadAssets(); QTranslator translator; @@ -49,5 +55,15 @@ int main(int argc, char *argv[]) break; } } + + // DirectDlg (created first, as in the original) is the main window; it + // shows the start screen once the game engine is up. + Cevo::DirectDlg direct; + Cevo::StartDlg start(&direct); + direct.setStartDlg(&start); + direct.show(); + QTimer::singleShot(2000, [] { for (int i = 0; i < Cevo::GameServer::brains.count(); ++i) qWarning() << "BRAIN" << i << Cevo::GameServer::brains[i].fileName << Cevo::GameServer::brains[i].name() << int(Cevo::GameServer::brains[i].kind) << Cevo::GameServer::brains[i].beginner; }); // TEMP-GRAB + QTimer::singleShot(2500, [&start] { start.grab().save(QStringLiteral("/tmp/start-shot.png")); }); // TEMP-GRAB + QTimer::singleShot(3000, [] { QCoreApplication::quit(); }); // TEMP-GRAB return a.exec(); } diff --git a/widget/include/Cevo/CevoGraphicSet.h b/widget/include/Cevo/CevoGraphicSet.h index f3f4f45..3a7ba1e 100644 --- a/widget/include/Cevo/CevoGraphicSet.h +++ b/widget/include/Cevo/CevoGraphicSet.h @@ -58,9 +58,8 @@ public: }; // TGraphicSet equivalent: a sprite sheet (data) with its transparency mask -// (mask), plus a set of named item rectangles. Persisted as XML, though not -// in the same node layout as the original (custom WriteString/WriteInteger -// helper), so files are not binary-compatible with the original .grs format. +// (mask), plus a set of named item rectangles. Persisted as XML in the +// original .grs layout (each item field a child element). class GraphicSet { public: GraphicSet() = default; diff --git a/widget/include/Cevo/CevoScreenTools.h b/widget/include/Cevo/CevoScreenTools.h index d0afe8f..e7ea531 100644 --- a/widget/include/Cevo/CevoScreenTools.h +++ b/widget/include/Cevo/CevoScreenTools.h @@ -250,5 +250,7 @@ void paintLogo(Dpi::Canvas &canvas, int x, int y, QColor lightColor, QColor shad // ScreenTools.pas's InitOrnament(): recolours the ornament sprite to the // current texture's bevel colours (once). void initOrnament(); +// ScreenTools.pas's DarkenImage(): subtracts `change` from every colour channel (clamped at 0). +void darkenImage(Dpi::Bitmap &bitmap, int change); } // namespace Cevo diff --git a/widget/include/Dpi/DpiPixelPointer.h b/widget/include/Dpi/DpiPixelPointer.h index e049e93..0290949 100644 --- a/widget/include/Dpi/DpiPixelPointer.h +++ b/widget/include/Dpi/DpiPixelPointer.h @@ -59,7 +59,9 @@ public: private: QImage *m_image = nullptr; - int m_x = 0; + int m_baseX = 0; // position of the pointer's origin in the image + int m_baseY = 0; + int m_x = 0; // current position, relative to the origin int m_y = 0; int m_width = 0; int m_height = 0; diff --git a/widget/src/CevoGraphicSet.cpp b/widget/src/CevoGraphicSet.cpp index 6ff5115..7a4e1a2 100644 --- a/widget/src/CevoGraphicSet.cpp +++ b/widget/src/CevoGraphicSet.cpp @@ -86,14 +86,40 @@ void GraphicSet::loadFromFile(const QString &fileName) QXmlStreamReader xml(&file); while (!xml.atEnd()) { xml.readNext(); - if (xml.isStartElement() && xml.name() == QLatin1String("Item")) { - const QXmlStreamAttributes attrs = xml.attributes(); - GraphicSetItem *newItem = addNew(attrs.value("Name").toString()); - newItem->left = attrs.value("Left").toInt(); - newItem->top = attrs.value("Top").toInt(); - newItem->width = attrs.value("Width").toInt(); - newItem->height = attrs.value("Height").toInt(); + if (!xml.isStartElement() || xml.name() != QLatin1String("Item")) + continue; + // The original format stores each field as a child element (, , ...); + // attributes are accepted too. + const QXmlStreamAttributes attrs = xml.attributes(); + QString name = attrs.value("Name").toString(); + int left = attrs.value("Left").toInt(); + int top = attrs.value("Top").toInt(); + int width = attrs.value("Width").toInt(); + int height = attrs.value("Height").toInt(); + while (!xml.atEnd()) { + xml.readNext(); + if (xml.isEndElement() && xml.name() == QLatin1String("Item")) + break; + if (!xml.isStartElement()) + continue; + const QString field = xml.name().toString(); + const QString text = xml.readElementText(); + if (field == QLatin1String("Name")) + name = text; + else if (field == QLatin1String("Left")) + left = text.toInt(); + else if (field == QLatin1String("Top")) + top = text.toInt(); + else if (field == QLatin1String("Width")) + width = text.toInt(); + else if (field == QLatin1String("Height")) + height = text.toInt(); } + GraphicSetItem *newItem = addNew(name); + newItem->left = left; + newItem->top = top; + newItem->width = width; + newItem->height = height; } } @@ -110,11 +136,11 @@ void GraphicSet::saveToFile(const QString &fileName) const xml.writeStartElement(QLatin1String("Items")); for (GraphicSetItem *item : m_items) { xml.writeStartElement(QLatin1String("Item")); - xml.writeAttribute(QLatin1String("Name"), item->name); - xml.writeAttribute(QLatin1String("Left"), QString::number(item->left)); - xml.writeAttribute(QLatin1String("Top"), QString::number(item->top)); - xml.writeAttribute(QLatin1String("Width"), QString::number(item->width)); - xml.writeAttribute(QLatin1String("Height"), QString::number(item->height)); + xml.writeTextElement(QLatin1String("Name"), item->name); + xml.writeTextElement(QLatin1String("Left"), QString::number(item->left)); + xml.writeTextElement(QLatin1String("Top"), QString::number(item->top)); + xml.writeTextElement(QLatin1String("Width"), QString::number(item->width)); + xml.writeTextElement(QLatin1String("Height"), QString::number(item->height)); xml.writeEndElement(); } xml.writeEndElement(); diff --git a/widget/src/CevoScreenTools.cpp b/widget/src/CevoScreenTools.cpp index d590cef..bd6a512 100644 --- a/widget/src/CevoScreenTools.cpp +++ b/widget/src/CevoScreenTools.cpp @@ -956,6 +956,19 @@ void paintLogo(Dpi::Canvas &canvas, int x, int y, QColor lightColor, QColor shad canvas.copyRect(QRect(x, y, logo->width, logo->height), drawBuffer.canvas(), QRect(0, 0, logo->width, logo->height)); } +void darkenImage(Dpi::Bitmap &bitmap, int change) +{ + QImage &image = bitmap.image(); + for (int y = 0; y < image.height(); ++y) { + for (int x = 0; x < image.width(); ++x) { + const QRgb c = image.pixel(x, y); + image.setPixel(x, y, + qRgba(std::max(qRed(c) - change, 0), std::max(qGreen(c) - change, 0), + std::max(qBlue(c) - change, 0), qAlpha(c))); + } + } +} + namespace { bool ornamentInitialized = false; } diff --git a/widget/src/DpiPixelPointer.cpp b/widget/src/DpiPixelPointer.cpp index 7bf9714..5b9d4db 100644 --- a/widget/src/DpiPixelPointer.cpp +++ b/widget/src/DpiPixelPointer.cpp @@ -31,13 +31,12 @@ namespace Dpi { PixelPointer::PixelPointer(QImage *image, int baseX, int baseY) - : m_image(image) + : m_image(image), m_baseX(baseX), m_baseY(baseY) { if (m_image) { m_width = m_image->width(); m_height = m_image->height(); } - setXY(baseX, baseY); } void PixelPointer::setXY(int x, int y) @@ -64,30 +63,34 @@ void PixelPointer::previousPixel() void PixelPointer::nextLine() { ++m_y; + m_x = 0; } void PixelPointer::previousLine() { --m_y; + m_x = 0; } bool PixelPointer::posValid() const { - return m_image && m_x >= 0 && m_x < m_width && m_y >= 0 && m_y < m_height; + const int x = m_baseX + m_x; + const int y = m_baseY + m_y; + return m_image && x >= 0 && x < m_width && y >= 0 && y < m_height; } QRgb PixelPointer::pixelARGB() const { if (!posValid()) return 0; - return reinterpret_cast(m_image->constScanLine(m_y))[m_x]; + return reinterpret_cast(m_image->constScanLine(m_baseY + m_y))[m_baseX + m_x]; } void PixelPointer::setPixelARGB(QRgb value) { if (!posValid()) return; - reinterpret_cast(m_image->scanLine(m_y))[m_x] = value; + reinterpret_cast(m_image->scanLine(m_baseY + m_y))[m_baseX + m_x] = value; } QRgb PixelPointer::pixelRGB() const