multiple intricate implementations

This commit is contained in:
Geoffray Levasseur committed 2026-11-04 11:41:01 +01:00
1 parent 7aa4ea4425
commit 77690cbd96
109 files changed
+2045 -56

No files matched your search

+10
View File
@@ -106,12 +106,19 @@ set(PROJECT_SOURCES
game/Inp.cpp game/Inp.cpp
game/Inp.h game/Inp.h
game/Inp.ui game/Inp.ui
game/Languages.cpp
game/Languages.h
game/Log.cpp game/Log.cpp
game/Log.h game/Log.h
game/Log.ui game/Log.ui
game/Messg.cpp game/Messg.cpp
game/Messg.h game/Messg.h
game/Messg.ui game/Messg.ui
game/MiniMap.cpp
game/MiniMap.h
game/NoTerm.cpp
game/NoTerm.h
game/NoTerm.ui
game/localplayer/KeyBindings.cpp game/localplayer/KeyBindings.cpp
game/localplayer/KeyBindings.h game/localplayer/KeyBindings.h
game/localplayer/ClientTools.cpp game/localplayer/ClientTools.cpp
@@ -135,7 +142,10 @@ set(PROJECT_SOURCES
game/localplayer/Term.cpp game/localplayer/Term.cpp
game/localplayer/Term.h game/localplayer/Term.h
game/localplayer/Term.MainScreen.cpp game/localplayer/Term.MainScreen.cpp
game/localplayer/Term.MainScreen.Client.cpp
game/localplayer/Term.MainScreen.h game/localplayer/Term.MainScreen.h
game/localplayer/LocalPlayer.cpp
game/localplayer/LocalPlayer.h
game/localplayer/Tribes.cpp game/localplayer/Tribes.cpp
game/localplayer/Tribes.h game/localplayer/Tribes.h
game/localplayer/Help.cpp game/localplayer/Help.cpp
+7
View File
@@ -56,6 +56,13 @@ public:
void unload(); void unload();
bool isLoaded() const { return m_client != nullptr; } bool isLoaded() const { return m_client != nullptr; }
const std::string &errorMessage() const { return m_error; } const std::string &errorMessage() const { return m_error; }
// Uses an in-process entry point (the game's own terminal/no-terminal
// clients) instead of one loaded from a library; nullptr clears it.
void setClient(TClientCall client)
{
unload();
m_client = client;
}
// Invokes the module's Client(Command, Player, Data) entry point. // Invokes the module's Client(Command, Player, Data) entry point.
void call(int command, int player, void *data) const; void call(int command, int player, void *data) const;
+2 -3
View File
@@ -28,6 +28,7 @@
#include "Brain.h" #include "Brain.h"
#include "Global.h"
#include "Cevo/CevoScreenTools.h" #include "Cevo/CevoScreenTools.h"
#include <QDir> #include <QDir>
@@ -82,9 +83,7 @@ QString Brain::name() const
{ {
if (!m_name.isEmpty()) if (!m_name.isEmpty())
return m_name; return m_name;
// TODO: needs Phrases[] (StringTables.pas, not ported yet) - fall back return phrases.lookup(lookupName);
// to the raw lookup key until localization is ported.
return lookupName;
} }
void Brain::loadPicture() void Brain::loadPicture()
+37 -19
View File
@@ -30,6 +30,8 @@
#include "Global.h" #include "Global.h"
#include "Messg.h" #include "Messg.h"
#include "NoTerm.h"
#include "localplayer/LocalPlayer.h"
#include "Cevo/CevoScreenTools.h" #include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h" #include "Cevo/CevoTexture.h"
@@ -47,19 +49,33 @@
namespace Cevo { namespace Cevo {
namespace {
// Shortens text until it fits into a dialog of the given width (with margins).
QString fitToWidth(QString text, int dialogWidth)
{
Dpi::Canvas canvas;
canvas.font().assign(UniFont[static_cast<std::size_t>(FontType::Normal)]);
while (!text.isEmpty() && biColorTextWidth(canvas, text) + 64 > dialogWidth)
text.chop(1);
return text;
}
} // namespace
DirectDlg::DirectDlg(QWidget *parent) : DrawDlg(parent) DirectDlg::DirectDlg(QWidget *parent) : DrawDlg(parent)
{ {
setWindowTitle(QStringLiteral("C-evo")); setWindowTitle(QStringLiteral("C-evo"));
GameServer::init([this](GameServer::NotifyId id, int index) { dlgNotify(id, index); }); GameServer::init([this](GameServer::NotifyId id, int index) { dlgNotify(id, index); });
// TODO: these special brains' in-process Client entry points need GameServer::brainNoTerm->module.setClient(NoTerm::client);
// Start.pas/LocalPlayer.pas/NoTerm.pas/NetworkServer.pas/
// NetworkClient.pas, none of which are ported yet - only the
// (purely cosmetic) lookup name is wired up for now.
GameServer::brainNoTerm->lookupName = QStringLiteral("AIT"); GameServer::brainNoTerm->lookupName = QStringLiteral("AIT");
GameServer::brainSuperVirtual->module.setClient(nullptr);
GameServer::brainSuperVirtual->lookupName = QStringLiteral("SUPER"); GameServer::brainSuperVirtual->lookupName = QStringLiteral("SUPER");
GameServer::brainTerm->module.setClient(LocalPlayer::client);
GameServer::brainTerm->lookupName = QStringLiteral("HUMAN"); GameServer::brainTerm->lookupName = QStringLiteral("HUMAN");
if (GameServer::networkEnabled) { if (GameServer::networkEnabled) {
// TODO: NetworkServer.pas/NetworkClient.pas (their Client entry points) aren't ported.
GameServer::brainNetworkServer->lookupName = QStringLiteral("NETWORK_SERVER"); GameServer::brainNetworkServer->lookupName = QStringLiteral("NETWORK_SERVER");
GameServer::brainNetworkClient->lookupName = QStringLiteral("NETWORK_CLIENT"); GameServer::brainNetworkClient->lookupName = QStringLiteral("NETWORK_CLIENT");
} }
@@ -86,7 +102,7 @@ void DirectDlg::go()
hide(); hide();
if (GameServer::brains.count() == 3) { if (GameServer::brains.count() == 3) {
QMessageBox::information(this, CevoTitle, tr("No AI libraries found.")); QMessageBox::information(this, CevoTitle, phrases.lookup(QStringLiteral("NOAI")));
close(); close();
return; return;
} }
@@ -124,14 +140,14 @@ void DirectDlg::go()
if (QFileInfo(fileName).suffix().prepend('.') == QString::fromLatin1(CevoExt)) { if (QFileInfo(fileName).suffix().prepend('.') == QString::fromLatin1(CevoExt)) {
m_quick = true; m_quick = true;
if (!GameServer::loadGame(fileName, fileName, -1, false)) { if (!GameServer::loadGame(fileName, fileName, -1, false)) {
simpleMessage(tr("Could not load the file.")); simpleMessage(phrases.lookup(QStringLiteral("LOADERR")));
close(); close();
} }
} else if (QFileInfo(fileName).suffix().prepend('.') == QString::fromLatin1(CevoMapExt)) { } else if (QFileInfo(fileName).suffix().prepend('.') == QString::fromLatin1(CevoMapExt)) {
m_quick = true; m_quick = true;
GameServer::editMap(fileName, fileName, lxmax, lymax, 30); GameServer::editMap(fileName, fileName, lxmax, lymax, 30);
} else { } else {
simpleMessage(tr("Could not load the file.")); simpleMessage(phrases.lookup(QStringLiteral("LOADERR")));
close(); close();
} }
} }
@@ -155,49 +171,49 @@ void DirectDlg::dlgNotify(GameServer::NotifyId id, int index)
case NotifyId::InitLocalHuman: case NotifyId::InitLocalHuman:
MainTexture->setAge(-1); MainTexture->setAge(-1);
m_state = -1; m_state = -1;
m_info = tr("Starting local human player..."); m_info = phrases.lookup(QStringLiteral("BUSY_MODLH"));
show(); show();
update(); update();
break; break;
case NotifyId::InitModule: case NotifyId::InitModule:
if (isVisible()) if (isVisible())
setInfo(tr("Starting %1...").arg(GameServer::brains[index].name())); setInfo(fitToWidth(formatPhrase(QStringLiteral("BUSY_MOD"), { GameServer::brains[index].name() }), width()));
break; break;
case NotifyId::CreateWorld: case NotifyId::CreateWorld:
if (isVisible()) if (isVisible())
setInfo(tr("Creating world...")); setInfo(phrases.lookup(QStringLiteral("BUSY_START")));
break; break;
case NotifyId::InitPlayers: case NotifyId::InitPlayers:
if (isVisible()) if (isVisible())
setInfo(tr("Initializing players...")); setInfo(phrases.lookup(QStringLiteral("BUSY_INIT")));
break; break;
case NotifyId::DeactivationMissing: case NotifyId::DeactivationMissing:
simpleMessage(tr("Player %1 did not hand over control.").arg(index)); simpleMessage(formatPhrase(QStringLiteral("MISSDEACT"), { QString::number(index) }));
break; break;
case NotifyId::SetAiName: case NotifyId::SetAiName:
// TODO: LocalPlayer.pas (SetAIName) isn't ported yet. LocalPlayer::setAIName(index, GameServer::notifyMessage);
break; break;
case NotifyId::Exception: case NotifyId::Exception:
QTimer::singleShot(0, this, [this, index]() { QTimer::singleShot(0, this, [this, index]() {
QMessageBox::warning(this, CevoTitle, QMessageBox::warning(this, CevoTitle,
tr("AI module %1 raised an exception.").arg(GameServer::brains[index].name())); formatPhrase(QStringLiteral("AIEXCEPTION"), { GameServer::brains[index].name() }));
}); });
break; break;
case NotifyId::LoadBegin: case NotifyId::LoadBegin:
m_info = tr("Loading..."); m_info = phrases.lookup(QStringLiteral("BUSY_LOAD"));
setState(0); setState(0);
break; break;
case NotifyId::LoadState: case NotifyId::LoadState:
setState(index); setState(index);
break; break;
case NotifyId::DllError: case NotifyId::DllError:
simpleMessage(tr("Could not load AI module %1.").arg(GameServer::brains[index].fileName)); simpleMessage(formatPhrase(QStringLiteral("DLLERROR"), { GameServer::brains[index].fileName }));
break; break;
case NotifyId::AiError: case NotifyId::AiError:
simpleMessage(tr("AI module error: %1").arg(GameServer::notifyMessage)); simpleMessage(formatPhrase(QStringLiteral("AIERROR"), { GameServer::notifyMessage }));
break; break;
case NotifyId::ClientError: case NotifyId::ClientError:
simpleMessage(tr("Client error in AI module %1.").arg(GameServer::brains[index].fileName)); simpleMessage(formatPhrase(QStringLiteral("CLIENTERROR"), { GameServer::brains[index].fileName }));
break; break;
case NotifyId::EndInfo: case NotifyId::EndInfo:
hide(); hide();
@@ -237,7 +253,9 @@ void DirectDlg::dlgNotify(GameServer::NotifyId id, int index)
QTimer::singleShot(0, this, []() { GameServer::nextPlayer(); }); QTimer::singleShot(0, this, []() { GameServer::nextPlayer(); });
break; break;
case NotifyId::DeinitModule: case NotifyId::DeinitModule:
m_info = tr("Unloading %1...").arg(GameServer::brains[index].name()); m_info = fitToWidth(
phraseToQtFormat(phrases2.lookup(QStringLiteral("BUSY_DEINIT"))).arg(GameServer::brains[index].name()),
width());
MainTexture->setAge(-1); MainTexture->setAge(-1);
m_state = -1; m_state = -1;
show(); show();
+79 -5
View File
@@ -32,6 +32,10 @@
#include "Cevo/CevoScreenTools.h" #include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h" #include "Cevo/CevoTexture.h"
#include <QDebug> #include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QLocale>
#include <QStandardPaths>
namespace Cevo { namespace Cevo {
@@ -67,12 +71,62 @@ QString getMusicDir()
return dir.isEmpty() ? QString() : dir + QStringLiteral("/Music"); return dir.isEmpty() ? QString() : dir + QStringLiteral("/Music");
} }
QString localizedFilePath(const QString &path) QString getAppSharePath(const QString &path)
{ {
const QString dir = resourceDir(); const QString dir = resourceDir();
return dir.isEmpty() ? path : dir + QLatin1Char('/') + path; return dir.isEmpty() ? path : dir + QLatin1Char('/') + path;
} }
QString localeCode;
QString localeCodeAuto()
{
const QLocale locale = QLocale::system();
if (locale.language() == QLocale::Chinese) {
return locale.script() == QLocale::TraditionalChineseScript ? QStringLiteral("zh-Hant")
: QStringLiteral("zh-Hans");
}
return locale.name().section(QLatin1Char('_'), 0, 0);
}
QString localizedFilePath(const QString &path)
{
if (localeCode != QLatin1String("en")) {
const QString code = localeCode.isEmpty() ? localeCodeAuto() : localeCode;
const QString localized = getAppSharePath(QStringLiteral("Localization/") + code + QLatin1Char('/') + path);
if (QFileInfo::exists(localized))
return localized;
}
return getAppSharePath(path);
}
namespace {
QString dataDirectory;
}
void initDirectories(const QStringList &args)
{
dataDirectory = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
if (dataDirectory.isEmpty())
dataDirectory = getAppSharePath(QString());
// Override by parameter
for (int i = 1; i < args.size() - 1; ++i) {
if (args.at(i) == QLatin1String("-d") || args.at(i) == QLatin1String("--data-dir"))
dataDirectory = args.at(i + 1);
}
QDir().mkpath(dataDirectory);
}
QString getSavedDir(bool share)
{
return share ? getAppSharePath(QStringLiteral("Saved")) : dataDirectory + QStringLiteral("/Saved");
}
QString getMapsDir(bool share)
{
return share ? getAppSharePath(QStringLiteral("Maps")) : dataDirectory + QStringLiteral("/Maps");
}
StringTable phrases; StringTable phrases;
StringTable phrases2; StringTable phrases2;
bool phrases2FallenBackToEnglish = false; bool phrases2FallenBackToEnglish = false;
@@ -80,10 +134,30 @@ bool phrases2FallenBackToEnglish = false;
void loadPhrases() void loadPhrases()
{ {
phrases2FallenBackToEnglish = false; phrases2FallenBackToEnglish = false;
if (!phrases.loadFromFile(localizedFilePath(QStringLiteral("Language.txt")))) const QString languageFile = localizedFilePath(QStringLiteral("Language.txt"));
qWarning("Language.txt not found in %s", qPrintable(localizedFilePath(QString()))); if (QFileInfo::exists(languageFile)) {
if (!phrases2.loadFromFile(localizedFilePath(QStringLiteral("Language2.txt")))) phrases.loadFromFile(languageFile);
qWarning("Language2.txt not found in %s", qPrintable(localizedFilePath(QString()))); const QString language2File = localizedFilePath(QStringLiteral("Language2.txt"));
if (QFileInfo::exists(language2File)) {
phrases2.loadFromFile(language2File);
} else {
phrases2.loadFromFile(getAppSharePath(QStringLiteral("Language2.txt")));
phrases2FallenBackToEnglish = true;
}
} else {
phrases.loadFromFile(getAppSharePath(QStringLiteral("Language.txt")));
phrases2.loadFromFile(getAppSharePath(QStringLiteral("Language2.txt")));
}
if (phrases.getHandle(QStringLiteral("BTN_OK")) < 0)
qWarning("Language.txt not found in %s", qPrintable(getAppSharePath(QString())));
}
QString formatPhrase(const QString &key, const QStringList &args)
{
QString result = phraseToQtFormat(phrases.lookup(key));
for (const QString &arg : args)
result = result.arg(arg);
return result;
} }
void loadAssets() void loadAssets()
+25 -10
View File
@@ -31,6 +31,7 @@
#include "Cevo/CevoStringTables.h" #include "Cevo/CevoStringTables.h"
#include <QString> #include <QString>
#include <QStringList>
namespace Cevo { namespace Cevo {
@@ -57,21 +58,33 @@ extern bool fullScreen;
// neither ported in full - toggle background music playback on/off). // neither ported in full - toggle background music playback on/off).
extern bool musicEnabled; extern bool musicEnabled;
// Minimal equivalent of Directories.pas's GetGraphicsDir() (that whole unit // Directories.pas's GetGraphicsDir()/GetMusicDir() (under the resource directory).
// isn't ported - this is just the one helper needed so far). Resolves to
// CEVO_RESOURCE_DIR/Graphics (see the top-level CMakeLists.txt).
QString getGraphicsDir(); QString getGraphicsDir();
// Same minimal-port rationale as getGraphicsDir(), for Directories.pas's
// GetMusicDir().
QString getMusicDir(); QString getMusicDir();
// Minimal equivalent of Directories.pas's LocalizedFilePath(): always // Directories.pas's GetAppSharePath(): a path inside the resource (shared,
// resolves to CEVO_RESOURCE_DIR/path, since localization (StringTables.pas // read-only) directory.
// and LocaleCode handling) isn't ported - this is the non-localized ("en") QString getAppSharePath(const QString &path);
// fallback branch the original always takes once no localized file exists.
// Directories.pas's `LocaleCode`: the interface language chosen by the
// user ("" for automatic, otherwise e.g. "fr", "zh-Hans").
extern QString localeCode;
// Language to use when localeCode is "" (from the system locale).
QString localeCodeAuto();
// Directories.pas's LocalizedFilePath(): the file under the localization
// directory of the current language if it exists there, else the shared one.
QString localizedFilePath(const QString &path); QString localizedFilePath(const QString &path);
// Directories.pas's UnitInit() part for the data directory: user data
// (saved games, maps) goes to the application data location unless
// overridden with -d/--data-dir in args.
void initDirectories(const QStringList &args);
// Directories.pas's GetSavedDir()/GetMapsDir(): the user's (or, with share,
// the shared read-only) directory of saved games / maps.
QString getSavedDir(bool share = false);
QString getMapsDir(bool share = false);
// ScreenTools.pas's `Phrases`/`Phrases2` string tables (Language.txt / // ScreenTools.pas's `Phrases`/`Phrases2` string tables (Language.txt /
// Language2.txt) and `Phrases2FallenBackToEnglish`; filled by loadPhrases(). // Language2.txt) and `Phrases2FallenBackToEnglish`; filled by loadPhrases().
extern StringTable phrases; extern StringTable phrases;
@@ -82,6 +95,8 @@ void loadPhrases();
// Converts a Language.txt Pascal Format() string (%d/%s/%%) to QString::arg() // Converts a Language.txt Pascal Format() string (%d/%s/%%) to QString::arg()
// style numbered placeholders (%1, %2, ...) in order of appearance. // style numbered placeholders (%1, %2, ...) in order of appearance.
QString phraseToQtFormat(const QString &text); QString phraseToQtFormat(const QString &text);
// Phrases[key] with its %d/%s placeholders filled in order from args.
QString formatPhrase(const QString &key, const QStringList &args = QStringList());
// ScreenTools.pas's UnitInit()/LoadAssets(): points the widget layer at the // ScreenTools.pas's UnitInit()/LoadAssets(): points the widget layer at the
// graphics directory and loads the phrases, fonts, system graphic sets, // graphics directory and loads the phrases, fonts, system graphic sets,
+2 -3
View File
@@ -29,6 +29,7 @@
#include "Inp.h" #include "Inp.h"
#include "ui_Inp.h" #include "ui_Inp.h"
#include "Global.h"
#include "Cevo/CevoButtonA.h" #include "Cevo/CevoButtonA.h"
#include "Cevo/CevoScreenTools.h" #include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h" #include "Cevo/CevoTexture.h"
@@ -77,9 +78,7 @@ void InputDlg::showEvent(QShowEvent *event)
{ {
DrawDlg::showEvent(event); DrawDlg::showEvent(event);
// TODO: needs Phrases[] (StringTables.pas, not ported yet) - plain ui->buttonOk->setCaption(phrases.lookup(QStringLiteral("BTN_OK")));
// English literal until localization is ported.
ui->buttonOk->setCaption(tr("OK"));
if (MainTexture) { if (MainTexture) {
QPalette pal = ui->editInput->palette(); QPalette pal = ui->editInput->palette();
pal.setColor(QPalette::Text, MainTexture->colorMark); pal.setColor(QPalette::Text, MainTexture->colorMark);
+75
View File
@@ -0,0 +1,75 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "Languages.h"
#include "Global.h"
#include <QDir>
namespace Cevo {
Languages::Languages()
{
addNew(QString(), QStringLiteral("Automatic"));
addNew(QStringLiteral("cs"), QStringLiteral("Czech"));
addNew(QStringLiteral("de"), QStringLiteral("German"));
addNew(QStringLiteral("en"), QStringLiteral("English"));
addNew(QStringLiteral("fr"), QStringLiteral("French"));
addNew(QStringLiteral("it"), QStringLiteral("Italian"));
addNew(QStringLiteral("ru"), QStringLiteral("Russian"));
addNew(QStringLiteral("zh-Hans"), QStringLiteral("Simplified Chinese"));
addNew(QStringLiteral("zh-Hant"), QStringLiteral("Traditional Chinese"));
}
void Languages::addNew(const QString &code, const QString &name)
{
auto language = std::make_unique<Language>();
language->code = code;
language->name = name;
m_items.push_back(std::move(language));
}
Language *Languages::searchByCode(const QString &code) const
{
for (const auto &item : m_items) {
if (item->code == code)
return item.get();
}
return nullptr;
}
void Languages::detectAvailable()
{
for (const auto &item : m_items) {
item->available = item->code.isEmpty() || item->code == QLatin1String("en") ||
QDir(getAppSharePath(QStringLiteral("Localization/") + item->code)).exists();
}
}
} // namespace Cevo
+69
View File
@@ -0,0 +1,69 @@
// 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 <QString>
#include <memory>
#include <vector>
namespace Cevo {
// Equivalent of Languages.pas's TLanguage/TLanguages: the languages the
// game interface can be offered in. Unlike the original's list of every
// ISO 639 code, this only knows the languages the game ships localized
// resources for (resources/Localization/<code>/), plus automatic and
// English.
struct Language {
QString code; // empty for "automatic"
QString name;
bool available = false;
};
class Languages {
public:
Languages();
int count() const { return static_cast<int>(m_items.size()); }
Language &at(int index) const { return *m_items[static_cast<std::size_t>(index)]; }
Language &operator[](int index) const { return at(index); }
// nullptr if there is no such language.
Language *searchByCode(const QString &code) const;
// Marks "automatic" and English as available, and every language whose
// Localization/<code> directory is installed.
void detectAvailable();
private:
void addNew(const QString &code, const QString &name);
std::vector<std::unique_ptr<Language>> m_items;
};
} // namespace Cevo
+47 -4
View File
@@ -29,6 +29,9 @@
#include "Log.h" #include "Log.h"
#include "ui_Log.h" #include "ui_Log.h"
#include "localplayer/ClientTools.h"
#include "localplayer/Tribes.h"
#include <QActionGroup> #include <QActionGroup>
#include <QKeyEvent> #include <QKeyEvent>
#include <QMenu> #include <QMenu>
@@ -64,10 +67,7 @@ LogDlg::LogDlg(QWidget *parent) : Dpi::Form(parent), ui(new Ui::LogDlg)
logPopup->addAction(ui->actionSlot); logPopup->addAction(ui->actionSlot);
logPopup->addAction(ui->actionClear); logPopup->addAction(ui->actionClear);
connect(ui->actionSlot, &QAction::triggered, this, [] { connect(ui->actionSlot, &QAction::triggered, this, [this] { listSlots(); });
// TODO: needs G.Difficulty[]/Tribe[].TPhrase("SHORTNAME") (Global.pas/
// Tribes.pas, not ported yet) - deferred until those units exist.
});
connect(ui->actionClear, &QAction::triggered, ui->list, &QPlainTextEdit::clear); connect(ui->actionClear, &QAction::triggered, ui->list, &QPlainTextEdit::clear);
} }
@@ -76,6 +76,49 @@ LogDlg::~LogDlg()
delete ui; delete ui;
} }
void LogDlg::clear()
{
ui->list->clear();
}
void LogDlg::setSlotItemVisible(bool visible)
{
ui->actionSlot->setVisible(visible);
}
void LogDlg::listSlots()
{
// Player slot numbers as laid out around the start screen's 3x3 grid.
static constexpr int SlotNo[3][3] = { { 8, 1, 2 }, { 7, 0, 3 }, { 6, 5, 4 } };
const auto shortName = [](int p) {
const auto &tribe = Tribes::tribe[static_cast<std::size_t>(p)];
return tribe ? tribe->tPhrase(QStringLiteral("SHORTNAME")) : QString();
};
for (int y = 0; y < 3; ++y) {
QString s = QStringLiteral("| ");
for (int x = 0; x < 3; ++x) {
const int slot = SlotNo[y][x];
const int difficulty = ClientTools::g.Difficulty[slot];
if (difficulty == 0) {
s += QStringLiteral("SUP |");
} else if (difficulty < 0) {
s += QStringLiteral("--- |");
} else {
if (slot >= 6 && slot <= 8) { // check multi control
if (ClientTools::g.Difficulty[slot + 3] >= 0)
s += shortName(slot + 3) + QLatin1Char('+');
if (ClientTools::g.Difficulty[slot + 6] >= 0)
s += shortName(slot + 6) + QLatin1Char('+');
}
s += shortName(slot) + QStringLiteral(" | ");
}
}
ui->list->appendPlainText(s);
}
QScrollBar *vBar = ui->list->verticalScrollBar();
vBar->setValue(vBar->maximum());
}
void LogDlg::setMaxLevel(int value, int checkedIndex) void LogDlg::setMaxLevel(int value, int checkedIndex)
{ {
maxLevel = value; maxLevel = value;
+4
View File
@@ -57,6 +57,9 @@ public:
Dpi::Form *host = nullptr; Dpi::Form *host = nullptr;
void add(int level, int turn, const QString &text); void add(int level, int turn, const QString &text);
void clear();
// Hides/shows the "slots" popup entry (the AI tournament window has no slots to list).
void setSlotItemVisible(bool visible);
protected: protected:
void keyPressEvent(QKeyEvent *event) override; void keyPressEvent(QKeyEvent *event) override;
@@ -72,6 +75,7 @@ private:
QMenu *logPopup; QMenu *logPopup;
void setMaxLevel(int value, int checkedIndex); void setMaxLevel(int value, int checkedIndex);
void listSlots();
}; };
} // namespace Cevo } // namespace Cevo
+5 -6
View File
@@ -29,6 +29,7 @@
#include "Messg.h" #include "Messg.h"
#include "ui_Messg.h" #include "ui_Messg.h"
#include "Global.h"
#include "Cevo/CevoButtonA.h" #include "Cevo/CevoButtonA.h"
#include <QKeyEvent> #include <QKeyEvent>
@@ -62,14 +63,12 @@ void MessgDlg::showEvent(QShowEvent *event)
ui->button2->setVisible(kind != MessageKind::Ok); ui->button2->setVisible(kind != MessageKind::Ok);
ui->button1->move(ui->button2->isVisible() ? 101 : 159, ui->button1->y()); ui->button1->move(ui->button2->isVisible() ? 101 : 159, ui->button1->y());
// TODO: needs Phrases[] (StringTables.pas, not ported yet) - plain
// English literals until localization is ported.
if (kind == MessageKind::YesNo) { if (kind == MessageKind::YesNo) {
ui->button1->setCaption(tr("Yes")); ui->button1->setCaption(phrases.lookup(QStringLiteral("BTN_YES")));
ui->button2->setCaption(tr("No")); ui->button2->setCaption(phrases.lookup(QStringLiteral("BTN_NO")));
} else { } else {
ui->button1->setCaption(tr("OK")); ui->button1->setCaption(phrases.lookup(QStringLiteral("BTN_OK")));
ui->button2->setCaption(tr("Cancel")); ui->button2->setCaption(phrases.lookup(QStringLiteral("BTN_CANCEL")));
} }
splitText(true); splitText(true);
+323
View File
@@ -0,0 +1,323 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "MiniMap.h"
#include "Cevo/CevoGraphicSet.h"
#include "Cevo/CevoScreenTools.h"
#include "Dpi/DpiCommon.h"
#include "GameServer.h"
#include "localplayer/Tribes.h"
#include <QFile>
#include <QFileInfo>
#include <algorithm>
#include <cstring>
namespace Cevo {
namespace {
// save map tile flags
constexpr int smOwned = 0x20;
constexpr int smUnit = 0x40;
constexpr int smCity = 0x80;
// Colour of a pixel of the system sprite sheet (black if it isn't loaded).
QColor systemPixel(int x, int y)
{
if (!HGrSystem || x >= HGrSystem->data.width() || y >= HGrSystem->data.height())
return Qt::black;
return HGrSystem->data.image().pixelColor(x, y);
}
// Each channel brightened to the upper half of its range.
QColor brighter(const QColor &color)
{
return QColor(0x80 | (color.red() >> 1), 0x80 | (color.green() >> 1), 0x80 | (color.blue() >> 1));
}
void putPixel(QImage &image, int x, int y, const QColor &color)
{
if (x >= 0 && y >= 0 && x < image.width() && y < image.height())
image.setPixelColor(x, y, color);
}
QColor tribeColor(int owner)
{
const auto &tribe = Tribes::tribe[static_cast<std::size_t>(owner)];
return tribe ? tribe->color : QColor(Qt::black);
}
} // namespace
MiniMap::MiniMap()
{
for (auto &row : colors)
row.fill(QColor(Qt::black));
for (int x = 0; x < 12; ++x) {
for (int y = 0; y < 2; ++y)
colors[static_cast<std::size_t>(x)][static_cast<std::size_t>(y)] = systemPixel(66 + x, 67 + y);
}
}
void MiniMap::resizeBitmap()
{
bitmap.setSize(Dpi::scaleToNative(size.x()) * 2, Dpi::scaleToNative(size.y()));
bitmap.image().fill(Qt::black);
}
void MiniMap::loadFromLogFile(const QString &fileName, int &lastTurn, QPoint defaultSize)
{
constexpr char FileId[] = "cEvoBook";
MapArray saveMap{};
bool ok = false;
QFile file(fileName);
if (file.open(QIODevice::ReadOnly)) {
const auto readInt = [&file]() {
std::int32_t value = 0;
file.read(reinterpret_cast<char *>(&value), sizeof value);
return value;
};
const QByteArray id = file.read(8);
ok = id == FileId;
if (ok) {
const std::uint32_t version = static_cast<std::uint32_t>(readInt()); // format id
if (version >= 0x000E01)
readInt(); // item stored since 0.14.1
size.setX(readInt());
size.setY(readInt());
const int fileLandMass = readInt();
if (fileLandMass == 0)
file.seek(file.pos() + static_cast<qint64>(size.y()) * size.x() * 4);
readInt(); // MaxTurn
readInt(); // RNG
lastTurn = readInt();
file.read(reinterpret_cast<char *>(saveMap.data()), 4);
mode = saveMap[0] == 0x80 ? Mode::MultiPlayer : Mode::Picture;
if (mode == Mode::Picture) {
if (size.x() > 0 && size.y() > 0 && static_cast<std::size_t>(size.x()) * size.y() <= saveMap.size())
file.read(reinterpret_cast<char *>(saveMap.data()) + 4, size.x() * size.y() - 4);
else
ok = false; // saved map data too big
}
}
}
if (!ok) {
lastTurn = 0;
size = defaultSize;
mode = Mode::None;
}
paintFile(saveMap);
}
void MiniMap::loadFromMapFile(const QString &fileName, int &mapLandTiles, int &mapStartPositions)
{
const QString imageFileName =
fileName.left(fileName.length() - static_cast<int>(std::strlen(CevoMapExt))) + QLatin1String(CevoMapPictureExt);
mode = Mode::Picture;
bool paintMapEnabled;
if (QFileInfo::exists(imageFileName) && bitmap.image().load(imageFileName)) {
bitmap.image() = bitmap.image().convertToFormat(QImage::Format_ARGB32);
if (bitmap.width() / 2 > MaxWidthMapLogo)
bitmap.image() = bitmap.image().copy(0, 0, MaxWidthMapLogo * 2, bitmap.height());
if (bitmap.height() > MaxHeightMapLogo)
bitmap.image() = bitmap.image().copy(0, 0, bitmap.width(), MaxHeightMapLogo);
size = QPoint(bitmap.width() / 2, bitmap.height());
paintMapEnabled = false;
} else {
size = QPoint(MaxWidthMapLogo, MaxHeightMapLogo);
paintMapEnabled = true;
}
Map map;
map.loadFromFile(fileName);
mapLandTiles = 0;
mapStartPositions = 0;
for (int y = 0; y < map.size().y(); ++y) {
for (int x = 0; x < map.size().x(); ++x) {
const std::uint32_t tile = map.tiles[static_cast<std::size_t>(y * map.size().x() + x)];
switch (tile & fTerrain) {
case fGrass:
case fPrairie:
case fTundra:
case fSwamp:
case fForest:
case fHills:
++mapLandTiles;
break;
default:
break;
}
if (tile & (fPrefStartPos | fStartPos))
++mapStartPositions;
}
}
if (mapStartPositions > nPl)
mapStartPositions = nPl;
if (paintMapEnabled) {
size = map.size();
paintMap(map);
}
}
void MiniMap::paintMap(const Map &map)
{
resizeBitmap();
if (mode != Mode::Picture)
return;
const int xx = Dpi::scaleToNative(size.x());
const int yy = Dpi::scaleToNative(size.y());
for (int y = 0; y < yy; ++y) {
for (int x = 0; x < xx; ++x) {
for (int i = 0; i < 2; ++i) {
const int xm = (x * 2 + i + (y & 1)) % (xx * 2);
const std::uint32_t tile =
map.tiles[static_cast<std::size_t>(Dpi::scaleFromNative(x) + size.x() * Dpi::scaleFromNative(y))];
const QColor color = (tile & fTerrain) == fUNKNOWN
? QColor(Qt::black)
: colors[tile & fTerrain][static_cast<std::size_t>(i)];
putPixel(bitmap.image(), xm, y, color);
}
}
}
}
void MiniMap::paintRandom(int brightness, int startLandMass, QPoint worldSize)
{
const std::uint32_t *map = GameServer::previewMap(startLandMass);
size = worldSize;
resizeBitmap();
const int xx = Dpi::scaleToNative(size.x());
const int yy = Dpi::scaleToNative(size.y());
for (int y = 0; y < yy; ++y) {
for (int x = 0; x < xx; ++x) {
for (int i = 0; i < 2; ++i) {
const int xm = (x * 2 + i + (y & 1)) % (xx * 2);
const int index = Dpi::scaleFromNative(x) * lxmax / size.x() +
lxmax * ((Dpi::scaleFromNative(y) * (lymax - 1) + size.y() / 2) / (size.y() - 1));
const QColor base = colors[map[index] & fTerrain][static_cast<std::size_t>(i)];
putPixel(bitmap.image(), xm, y,
QColor(base.red() * brightness / 3, base.green() * brightness / 3,
base.blue() * brightness / 3));
}
}
}
}
void MiniMap::paintFile(const MapArray &saveMap)
{
const QColor ownColor = systemPixel(95, 67);
const QColor enemyColor = systemPixel(96, 67);
resizeBitmap();
if (mode != Mode::Picture)
return;
const int xx = Dpi::scaleToNative(size.x());
const int yy = Dpi::scaleToNative(size.y());
for (int y = 0; y < yy; ++y) {
for (int x = 0; x < xx; ++x) {
for (int i = 0; i < 2; ++i) {
const int xm = (x * 2 + i + (y & 1)) % (xx * 2);
const int tile = saveMap[static_cast<std::size_t>(Dpi::scaleFromNative(x) + size.x() * Dpi::scaleFromNative(y))];
QColor color;
if ((tile & fTerrain) == fUNKNOWN) {
color = Qt::black;
} else if (tile & smCity) {
color = (tile & smOwned) ? ownColor : enemyColor;
if (y > 0) // 2x2 city dot covers two lines
putPixel(bitmap.image(), xm, y - 1, color);
} else if (i == 0 && (tile & smUnit)) {
color = (tile & smOwned) ? ownColor : enemyColor;
} else {
color = colors[static_cast<std::size_t>(tile & fTerrain)][static_cast<std::size_t>(i)];
}
putPixel(bitmap.image(), xm, y, color);
}
}
}
}
void MiniMap::paint(const std::uint32_t *myMap, int mapWidth, int clientMode, int xxt, int xwMini)
{
if (!myMap)
return;
const QColor polOcean = systemPixel(101, 67);
const QColor polNone = systemPixel(102, 67);
const int hw = mapWidth / (xxt * 2);
resizeBitmap();
const int xx = Dpi::scaleToNative(size.x());
const int yy = Dpi::scaleToNative(size.y());
for (int y = 0; y < yy; ++y) {
for (int x = 0; x < xx; ++x) {
const int loc = Dpi::scaleFromNative(x) + size.x() * Dpi::scaleFromNative(y);
if ((myMap[loc] & fTerrain) == fUNKNOWN)
continue;
for (int i = 0; i < 2; ++i) {
const int xm = ((x - Dpi::scaleToNative(xwMini)) * 2 + i + (y & 1) - Dpi::scaleToNative(hw) + xx * 5) %
(xx * 2);
std::uint32_t terrainTile = myMap[loc] & fTerrain;
if (terrainTile > 11)
terrainTile = 0;
QColor color = colors[terrainTile][static_cast<std::size_t>(i)];
if (clientMode == cEditMap) {
if (myMap[loc] & (fPrefStartPos | fStartPos))
color = Qt::white;
} else if (myMap[loc] & fCity) {
if (ClientTools::getMyCityByLoc(loc)) {
color = tribeColor(ClientTools::me);
} else if (const TCityInfo *enemyCity = ClientTools::getEnemyCityByLoc(loc)) {
color = tribeColor(enemyCity->Owner);
}
color = brighter(color);
if (y > 0) // 2x2 city dot covers two lines
putPixel(bitmap.image(), xm, y - 1, color);
} else if (i == 0 && (myMap[loc] & fUnit)) {
if (ClientTools::getMyUnitByLoc(loc)) {
color = tribeColor(ClientTools::me);
} else if (const TUnitInfo *enemyUnit = ClientTools::getEnemyUnitByLoc(loc)) {
color = tribeColor(enemyUnit->Owner);
}
color = brighter(color);
} else if (ClientTools::hasMapOption(mapOptions, ClientTools::moPolitical)) {
if ((myMap[loc] & fTerrain) < fGrass)
color = polOcean;
else if ((*ClientTools::myRO->Territory)[loc] < 0)
color = polNone;
else
color = tribeColor((*ClientTools::myRO->Territory)[loc]);
}
putPixel(bitmap.image(), xm, y, color);
}
}
}
}
} // namespace Cevo
+82
View File
@@ -0,0 +1,82 @@
// 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 "Cevo/Map.h"
#include "Cevo/Protocol.h"
#include "Dpi/DpiGraphics.h"
#include "localplayer/ClientTools.h"
#include <QColor>
#include <QPoint>
#include <QString>
#include <array>
#include <cstdint>
namespace Cevo {
// Equivalent of MiniMap.pas's TMiniMap: a small isometric-looking sample of
// the game world, used as the start screen's map preview and as the main
// screen's mini map.
class MiniMap {
public:
enum class Mode { None, Picture, MultiPlayer };
using MapArray = std::array<std::uint8_t, lxmax * lymax>;
static constexpr int MaxWidthMapLogo = 96;
static constexpr int MaxHeightMapLogo = 96;
MiniMap();
// Preview of a saved game ("book"); falls back to an empty preview of
// defaultSize if the file can't be read.
void loadFromLogFile(const QString &fileName, int &lastTurn, QPoint defaultSize);
// Preview of a map file (its picture if there is one, else painted
// from the tiles); also counts usable land tiles and start positions.
void loadFromMapFile(const QString &fileName, int &mapLandTiles, int &mapStartPositions);
void paintMap(const Map &map);
void paintRandom(int brightness, int startLandMass, QPoint worldSize);
void paintFile(const MapArray &saveMap);
// Paints the known part of the running game's map, centred on xwMini.
void paint(const std::uint32_t *myMap, int mapWidth, int clientMode, int xxt, int xwMini);
// Preview picture of the game world; sized in native pixels (twice the
// map width, since odd rows are shifted by one pixel).
Dpi::Bitmap bitmap;
QPoint size;
std::array<std::array<QColor, 2>, 32> colors;
Mode mode = Mode::None;
ClientTools::MapOptions mapOptions = 0;
private:
void resizeBitmap();
};
} // namespace Cevo
+382
View File
@@ -0,0 +1,382 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "NoTerm.h"
#include "ui_NoTerm.h"
#include "Cevo/CevoButtonB.h"
#include "Cevo/CevoGraphicSet.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include "GameServer.h"
#include "Global.h"
#include "Messg.h"
#include "localplayer/Term.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QKeyEvent>
#include <QPainter>
namespace Cevo {
namespace NoTerm {
namespace {
constexpr double UpdateInterval = 0.1; // seconds
constexpr double ShowActiveThreshold = 0.05; // seconds
constexpr int nPlOffered = 9;
constexpr int x0Brain = 109 + 48 + 23;
constexpr int y0Brain = 124 + 48 + 7 + 16;
constexpr int dxBrain = 128;
constexpr int dyBrain = 128;
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 xActive[nPlOffered] = { 0, 0, 36, 51, 36, 0, -36, -51, -36 };
constexpr int yActive[nPlOffered] = { 0, -51, -36, 0, 36, 51, 36, 0, -36 };
constexpr int yYear = 287 + 138;
double nowSeconds()
{
return static_cast<double>(QDateTime::currentMSecsSinceEpoch()) / 1000.0;
}
} // namespace
NoTermDlg::NoTermDlg(QWidget *parent) : DrawDlg(parent), ui(new Ui::NoTermDlg)
{
ui->setupUi(this);
const QRect screen = Dpi::Screen::primaryMonitor().boundsRect();
move(screen.left() + screen.width() - width() - 8, 8);
setWindowTitle(phrases.lookup(QStringLiteral("AIT")));
titleHeight = 36;
initButtons();
ui->goBtn->onClick = [this] { goClicked(); };
ui->quitBtn->onClick = [this] { quitClicked(); };
}
NoTermDlg::~NoTermDlg()
{
delete ui;
}
LogDlg &NoTermDlg::logDlg()
{
if (!m_logDlg)
m_logDlg = std::make_unique<LogDlg>();
return *m_logDlg;
}
void NoTermDlg::newStat()
{
m_round = 0;
m_winStat.fill(0);
m_extStat.fill(0);
m_aloneStat.fill(0);
m_timeStat.fill(0);
m_totalStatTime = 0;
m_mode = RunMode::Stop;
}
void NoTermDlg::endPlaying()
{
newStat();
int endCommand = sResign;
if (m_game.RO[m_me]->Turn > 0) {
MessgDlg dlg;
dlg.messageText = phrases.lookup(QStringLiteral("ENDTOUR"));
dlg.kind = MessageKind::YesNo;
dlg.showModal();
endCommand = dlg.modalResult() == Dpi::ModalResult::Ignore ? sResign : sBreak;
}
m_server(endCommand, m_me, 0, nullptr);
}
void NoTermDlg::showActive(int p, bool active)
{
if (p >= nPlOffered)
return;
m_shownActive[static_cast<std::size_t>(p)] = active;
update(x0Brain + 28 + xActive[p], y0Brain + 28 + yActive[p], 8, 8);
}
void NoTermDlg::paintActive(QPainter &painter, int p, bool active)
{
if (p >= nPlOffered)
return;
Dpi::Canvas canvas;
canvas.bind(&painter);
sprite(canvas, *HGrSystem, x0Brain + 28 + xActive[p], y0Brain + 28 + yActive[p], 8, 8, 81 + 9 * (active ? 1 : 0),
16);
canvas.unbind();
}
void NoTermDlg::showYear()
{
m_yearText = formatPhrase(QStringLiteral("AIT_ROUND"), { QString::number(m_round) }) + QLatin1Char(' ') +
Term::turnToString(m_game.RO[m_me]->Turn);
update(64, yYear, 192, 20);
}
void NoTermDlg::goClicked()
{
if (m_mode == RunMode::Running) {
m_mode = RunMode::Stop;
} else if (m_mode == RunMode::Stopped) {
m_mode = RunMode::Running;
ui->goBtn->setButtonIndex(23);
ui->goBtn->repaint();
m_server(sTurn, m_me, 0, nullptr);
}
}
void NoTermDlg::quitClicked()
{
if (m_mode == RunMode::Stopped)
endPlaying();
else
m_mode = RunMode::Quit;
}
void NoTermDlg::client(int command, int player, void *data)
{
switch (command) {
case cDebugMessage:
logDlg().add(player, m_game.RO[0] ? m_game.RO[0]->Turn : 0, QString::fromLocal8Bit(static_cast<const char *>(data)));
break;
case cInitModule: {
auto *initData = static_cast<TInitModuleData *>(data);
m_server = initData->Server;
initData->Flags = aiThreaded;
m_shade = QImage(64, 64, QImage::Format_ARGB32);
for (int x = 0; x < 64; ++x) {
for (int y = 0; y < 64; ++y)
m_shade.setPixel(x, y, ((x + y) & 1) ? qRgba(0, 0, 0, 255) : qRgba(0, 0, 0, 0));
}
newStat();
break;
}
case cReleaseModule:
m_shade = QImage();
break;
case cNewGame:
case cLoadGame:
++m_round;
m_game = *static_cast<TNewGameData *>(data);
m_shownActive.fill(false);
if (m_mode == RunMode::Running)
repaint();
else
show();
logDlg().setSlotItemVisible(false);
logDlg().host = nullptr;
m_toldAlive = m_game.RO[m_me]->Alive;
m_active = -1;
m_disallowShowActive.fill(false);
m_lastShowTurnChange = 0;
m_lastNewTurn = 0;
m_turnTime = 1.0;
break;
case cBreakGame:
logDlg().clear();
if (m_mode != RunMode::Running) {
if (logDlg().isVisible())
logDlg().close();
close();
}
break;
case cTurn:
case cResume:
case cContinue: {
m_me = player;
if (m_active >= 0) {
showActive(m_active, false);
m_active = -1;
} // should not happen
const double now = nowSeconds();
if (now - m_lastShowYearTime >= UpdateInterval) {
showYear();
m_lastShowYearTime = now;
}
m_turnTime = now - m_lastNewTurn;
m_lastNewTurn = now;
const TPlayerContext &ro = *m_game.RO[m_me];
if (ro.Alive != m_toldAlive) {
for (int p = 1; p < nPlOffered; ++p) {
if ((1 << p) & (ro.Alive ^ m_toldAlive))
update(xBrain[p], yBrain[p] - 16, 64, 64);
}
m_toldAlive = ro.Alive;
}
QCoreApplication::processEvents();
if (m_mode == RunMode::Quit) {
endPlaying();
} else if (ro.Happened & phGameEnd) { // game ended, update statistics
for (int p = 1; p < nPlOffered; ++p) {
if (!GameServer::playersBrain[static_cast<std::size_t>(p)])
continue;
if (!((1 << p) & ro.Alive)) {
++m_extStat[static_cast<std::size_t>(p)]; // extinct
} else if (ro.Alive == (1 << p)) {
++m_aloneStat[static_cast<std::size_t>(p)]; // only player alive
} else { // alive but not alone -- check colony ship
bool shipComplete = true;
for (int i = 0; i < nShipPart; ++i) {
if (ro.Ship[p].Parts[i] < ShipNeed[i]) {
shipComplete = false;
break;
}
}
if (shipComplete)
++m_winStat[static_cast<std::size_t>(p)];
}
}
if (m_mode == RunMode::Running)
m_server(sNextRound, m_me, 0, nullptr);
} else if (m_mode == RunMode::Running) {
m_server(sTurn, m_me, 0, nullptr);
}
if (m_mode == RunMode::Stop) {
ui->goBtn->setButtonIndex(22);
m_mode = RunMode::Stopped;
}
break;
}
case cShowTurnChange: {
const double now = nowSeconds();
if (m_active >= 0) {
const auto active = static_cast<std::size_t>(m_active);
const double activeDuration = now - m_lastShowTurnChange;
m_timeStat[active] += activeDuration;
m_totalStatTime += activeDuration;
if (!m_disallowShowActive[active])
showActive(m_active, false);
m_disallowShowActive[active] = activeDuration < m_turnTime * 0.25 && activeDuration < ShowActiveThreshold;
}
m_lastShowTurnChange = now;
m_active = *static_cast<int *>(data);
if (m_active >= 0 && !m_disallowShowActive[static_cast<std::size_t>(m_active)])
showActive(m_active, true);
break;
}
}
}
void NoTermDlg::paintEvent(QPaintEvent *)
{
QPainter painter(this);
Dpi::Canvas canvas;
canvas.bind(&painter);
canvas.brush().setStyle(Qt::NoBrush);
fill(canvas, 3, 3, width() - 6, height() - 6, 0, 0);
frame(canvas, 0, 0, width() - 1, height() - 1, Qt::black, Qt::black);
frame(canvas, 1, 1, width() - 2, height() - 2, MainTexture->colorBevelLight, MainTexture->colorBevelShade);
frame(canvas, 2, 2, width() - 3, height() - 3, MainTexture->colorBevelLight, MainTexture->colorBevelShade);
corner(canvas, 1, 1, 0, *MainTexture);
corner(canvas, width() - 9, 1, 1, *MainTexture);
corner(canvas, 1, height() - 9, 2, *MainTexture);
corner(canvas, width() - 9, height() - 9, 3, *MainTexture);
canvas.font().assign(UniFont[static_cast<std::size_t>(FontType::Caption)]);
risedTextOut(canvas, (width() - biColorTextWidth(canvas, windowTitle())) / 2, 7, windowTitle());
canvas.font().assign(UniFont[static_cast<std::size_t>(FontType::Small)]);
for (int i = 1; i < nPlOffered; ++i) {
Brain *brain = GameServer::playersBrain[static_cast<std::size_t>(i)];
if (!brain)
continue;
const int x = xBrain[i];
const int y = yBrain[i];
frame(canvas, x - 24, y - 8 - 16, x - 24 + 111, y - 8 - 16 + 111, MainTexture->colorBevelShade,
MainTexture->colorBevelShade);
frameImage(canvas, brain->picture, x, y - 16, 64, 64, 0, 0);
if (m_game.RO[m_me] && !((1 << i) & m_game.RO[m_me]->Alive))
painter.drawImage(x, y - 16, m_shade);
const auto stat = static_cast<std::size_t>(i);
sprite(canvas, *HGrSystem, x + 30 - 14, y + 53, 14, 14, 1, 316);
risedTextOut(canvas, x + 30 - 16 - biColorTextWidth(canvas, QString::number(m_winStat[stat])), y + 51,
QString::number(m_winStat[stat]));
sprite(canvas, *HGrSystem, x + 34, y + 53, 14, 14, 1 + 15, 316);
risedTextOut(canvas, x + 34 + 16, y + 51, QString::number(m_aloneStat[stat]));
sprite(canvas, *HGrSystem, x + 30 - 14, y + 53 + 16, 14, 14, 1 + 30, 316);
risedTextOut(canvas, x + 30 - 16 - biColorTextWidth(canvas, QString::number(m_extStat[stat])), y + 51 + 16,
QString::number(m_extStat[stat]));
sprite(canvas, *HGrSystem, x + 34, y + 53 + 16, 14, 14, 1 + 45, 316);
if (m_totalStatTime > 0) {
const int timeShare = static_cast<int>(m_timeStat[stat] / m_totalStatTime * 100 + 0.5);
risedTextOut(canvas, x + 34 + 16, y + 51 + 16, QString::number(timeShare) + QLatin1Char('%'));
}
paintActive(painter, i, m_shownActive[stat]);
}
sprite(canvas, *HGrSystem2, x0Brain + 32 - 20, y0Brain + 32 - 20, 40, 40, 115, 1);
Dpi::Bitmap state(192, 20);
state.canvas().begin();
fill(state.canvas(), 0, 0, 192, 20, 64, yYear);
state.canvas().font().assign(UniFont[static_cast<std::size_t>(FontType::Small)]);
state.canvas().brush().setStyle(Qt::NoBrush);
risedTextOut(state.canvas(), 0, 0, m_yearText);
state.canvas().end();
painter.drawImage(64, yYear, state.image());
btnFrame(canvas, ui->goBtn->geometry(), *MainTexture);
btnFrame(canvas, ui->quitBtn->geometry(), *MainTexture);
canvas.unbind();
}
void NoTermDlg::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_M && (event->modifiers() & Qt::ControlModifier)) {
if (logDlg().isVisible())
logDlg().close();
else
logDlg().show();
return;
}
DrawDlg::keyPressEvent(event);
}
void CEVO_ABI_CALL client(std::int32_t command, std::int32_t player, void *data)
{
static NoTermDlg *dlg = new NoTermDlg; // lives for the whole session, like Application.CreateForm
dlg->client(command, player, data);
}
} // namespace NoTerm
} // namespace Cevo
+108
View File
@@ -0,0 +1,108 @@
// 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 "Cevo/CevoDrawDlg.h"
#include "Cevo/Protocol.h"
#include "Log.h"
#include <QImage>
#include <array>
#include <memory>
QT_BEGIN_NAMESPACE
namespace Ui {
class NoTermDlg;
}
QT_END_NAMESPACE
namespace Cevo {
namespace NoTerm {
// Equivalent of NoTerm.pas's TNoTermDlg: the "AI tournament" window that
// stands in for a human terminal when only AI players take part. It shows
// each AI's picture with its win/extinction/colony-ship statistics, and
// drives the game round after round (Go/Stop/Quit).
class NoTermDlg : public DrawDlg {
Q_OBJECT
public:
explicit NoTermDlg(QWidget *parent = nullptr);
~NoTermDlg() override;
// The in-process Client(Command, Player, Data) entry point.
void client(int command, int player, void *data);
protected:
void paintEvent(QPaintEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
private:
enum class RunMode { Stop, Stopped, Running, Quit };
LogDlg &logDlg();
void goClicked();
void quitClicked();
void newStat();
void endPlaying();
void showActive(int p, bool active);
void showYear();
void paintActive(QPainter &painter, int p, bool active);
int m_me = 0;
int m_active = -1;
int m_toldAlive = 0;
int m_round = 0;
double m_lastShowYearTime = 0;
double m_lastShowTurnChange = 0;
double m_lastNewTurn = 0;
double m_turnTime = 1.0;
double m_totalStatTime = 0;
TNewGameData m_game{};
TServerCall m_server = nullptr;
QImage m_shade;
QString m_yearText;
std::array<int, nPl> m_winStat{};
std::array<int, nPl> m_extStat{};
std::array<int, nPl> m_aloneStat{};
std::array<bool, nPl> m_disallowShowActive{};
std::array<bool, nPl> m_shownActive{};
std::array<double, nPl> m_timeStat{};
RunMode m_mode = RunMode::Stop;
std::unique_ptr<LogDlg> m_logDlg;
Ui::NoTermDlg *ui;
};
// Pascal's unit-level Client(): creates the dialog on first use and
// forwards to it.
void CEVO_ABI_CALL client(std::int32_t command, std::int32_t player, void *data);
} // namespace NoTerm
} // namespace Cevo
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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
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.
-->
<ui version="4.0">
<class>NoTermDlg</class>
<widget class="QWidget" name="NoTermDlg">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>422</width>
<height>456</height>
</rect>
</property>
<property name="windowTitle">
<string>C-evo</string>
</property>
<widget class="Cevo::ButtonB" name="quitBtn">
<property name="geometry">
<rect>
<x>384</x>
<y>6</y>
<width>25</width>
<height>25</height>
</rect>
</property>
</widget>
<widget class="Cevo::ButtonB" name="goBtn">
<property name="geometry">
<rect>
<x>30</x>
<y>422</y>
<width>25</width>
<height>25</height>
</rect>
</property>
</widget>
</widget>
<customwidgets>
<customwidget>
<class>Cevo::ButtonB</class>
<extends>QWidget</extends>
<header>Cevo/CevoButtonB.h</header>
</customwidget>
</customwidgets>
<resources/>
</ui>
+2
View File
@@ -117,6 +117,8 @@ public:
~HelpDlg() override; ~HelpDlg() override;
void clearHistory() { histItems.clear(); } void clearHistory() { histItems.clear(); }
// Help.pas's `Difficulty` (the game's difficulty level, 0 for none).
int difficulty = 0;
void showNewContent(WindowMode newMode, LinkCategory category, int index); void showNewContent(WindowMode newMode, LinkCategory category, int index);
int textIndex(const QString &item) const { return helpText.getHandle(item); } int textIndex(const QString &item) const { return helpText.getHandle(item); }
+57
View File
@@ -0,0 +1,57 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
#include "LocalPlayer.h"
#include "Term.MainScreen.h"
namespace Cevo {
namespace LocalPlayer {
namespace {
Term::MainScreen *ensureMainScreen()
{
// Created on first use and kept for the whole session, like Application.CreateForm.
if (!Term::mainScreen)
new Term::MainScreen;
return Term::mainScreen;
}
} // namespace
void CEVO_ABI_CALL client(std::int32_t command, std::int32_t player, void *data)
{
ensureMainScreen()->client(command, player, data);
}
void setAIName(int p, const QString &name)
{
ensureMainScreen()->setAIName(p, name);
}
} // namespace LocalPlayer
} // namespace Cevo
+46
View File
@@ -0,0 +1,46 @@
// 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 "Cevo/Protocol.h"
#include <QString>
namespace Cevo {
namespace LocalPlayer {
// Equivalent of LocalPlayer.pas: the human terminal's client entry point.
// The main screen is created on the first call.
void CEVO_ABI_CALL client(std::int32_t command, std::int32_t player, void *data);
// Hands the display name of an AI player to the main screen.
void setAIName(int p, const QString &name);
} // namespace LocalPlayer
} // namespace Cevo
+2 -5
View File
@@ -658,10 +658,7 @@ void ListDlg::initLines()
break; break;
} }
case ListKind::Tribe: { case ListKind::Tribe: {
// Simplified: the original lists every predefined civilization for (int i = 0; i < static_cast<int>(Term::tribeNames.size()); ++i)
// name bundled with the game (TribeNames, a static resource list
// not ported); lists the nPl in-game nation slots instead.
for (int i = 0; i < nPl; ++i)
layers[static_cast<std::size_t>(LayerIndex::Improvements)].addLine(i); layers[static_cast<std::size_t>(LayerIndex::Improvements)].addLine(i);
break; break;
} }
@@ -1133,7 +1130,7 @@ void ListDlg::paintLine(Dpi::Canvas &ca, int l, bool nonText, bool lit, bool toW
break; break;
} }
case ListKind::Tribe: case ListKind::Tribe:
s = QStringLiteral("Nation #%1").arg(lix + 1); s = Term::tribeNames[static_cast<std::size_t>(lix)].name;
break; break;
case ListKind::ShipPart: case ListKind::ShipPart:
s = QStringLiteral("%1 (%2)") s = QStringLiteral("%1 (%2)")
+458
View File
@@ -0,0 +1,458 @@
// This file is part of c-evo-evo.
//
// This software is governed by the CeCILL license under French law and
// abiding by the rules of distribution of free software. You can use,
// modify and/or redistribute the software under the terms of the CeCILL
// license as circulated by CEA, CNRS and INRIA at the following URL
// "http://www.cecill.info".
//
// As a counterpart to the access to the source code and rights to copy,
// modify and redistribute granted by the license, users are provided only
// with a limited warranty and the software's author, the holder of the
// economic rights, and the successive licensors have only limited
// liability.
//
// In this respect, the user's attention is drawn to the risks associated
// with loading, using, modifying and/or developing or reproducing the
// software by the user in light of its specific status of free software,
// that may mean that it is complicated to manipulate, and that also
// therefore means that it is reserved for developers and experienced
// professionals having in-depth computer knowledge. Users are therefore
// encouraged to load and test the software's suitability as regards their
// requirements in conditions enabling the security of their systems and/or
// data to be ensured and, more generally, to use and operate it in the
// same conditions as regards security.
//
// The fact that you are presently reading this means that you have had
// knowledge of the CeCILL license and that you accept its terms.
// TMainScreen.Client() (Term.pas): the command dispatcher the server calls
// for the human player.
//
// PORT STATUS: served so far - cDebugMessage, cShowNego, cInitModule,
// cReleaseModule, cHelpOnly/cStartHelp/cStartCredits, cNewGame/cLoadGame/
// cMovie/cNewMap, cGetReady/cReplay, cBreakGame, the pure message commands
// (cShowCancelTreaty*, cShowSupportAllianceAgainst, cShowPeaceViolation,
// cShowMissionResult, cShowShipChange, cShowGreatLibTech), cShowEndContact
// and the client exclusive commands. Still missing because they need
// InitTurn()/the main map and panel (not ported): cShowGame, cTurn/
// cResume/cContinue/cMovieTurn/cMovieEndTurn, cEditMap, scContact and
// scDipStart..scDipBreak, cShowUnitChanged/CityChanged/AfterMove/
// AfterAttack/Moving/Capturing/Attacking, cRefreshDebugMap. Screen-only
// side effects inside the served commands (button visibility, panel
// repaint, sounds) are marked TODO.
#include "Term.MainScreen.h"
#include "Cevo/CevoGraphicSet.h"
#include "Cevo/CevoScreenTools.h"
#include "Cevo/CevoTexture.h"
#include "Cevo/CmdList.h"
#include "Global.h"
#include "Messg.h"
#include "Tribes.h"
#include <QApplication>
#include <algorithm>
#include <cstring>
#include <type_traits>
namespace Cevo {
namespace Term {
static_assert(std::is_trivially_copyable_v<PersistentData>,
"PersistentData lives in server-allocated raw memory (and savegames)");
namespace {
QString negoOfferText(const TShowNegoData &nego)
{
const TOffer &offer = nego.Offer;
QString s = QStringLiteral("P%1 to P%2: ").arg(nego.pSender).arg(nego.pTarget);
if (nego.Action == scDipOffer && offer.nDeliver + offer.nCost > 0) {
s += QStringLiteral("Offer ");
for (int i = 0; i < offer.nDeliver + offer.nCost; ++i) {
if (i == offer.nDeliver)
s += QStringLiteral(" for ");
else if (i > 0)
s += QLatin1Char('+');
const int price = offer.Price[i];
const int value = price & 0xFFFFFF;
switch (price & opMask) {
case opChoose: s += QStringLiteral("Price of choice"); break;
case opCivilReport: s += QStringLiteral("State report"); break;
case opMilReport: s += QStringLiteral("Military report"); break;
case opMap: s += QStringLiteral("Map"); break;
case opTreaty: s += QStringLiteral("Treaty"); break;
case opShipParts: s += QStringLiteral("Ship part"); break;
case opMoney: s += QString::number(value) + QLatin1Char('o'); break;
case opTribute: s += QString::number(value) + QStringLiteral("o tribute"); break;
case opTech: s += phrases.lookup(QStringLiteral("ADVANCES"), value); break;
case opAllTech: s += QStringLiteral("All advances"); break;
case opModel:
s += Tribes::tribe[static_cast<std::size_t>(nego.pSender)]->modelNameAt(value);
break;
case opAllModel: s += QStringLiteral("All models"); break;
default: break;
}
}
} else if (nego.Action == scDipAccept) {
s += QStringLiteral("--- ACCEPTED! ---");
} else {
return QString();
}
return s;
}
// Initial per-player persistent data of a new game.
void initPersistentData(PersistentData &data)
{
const TNewGameData &g = ClientTools::g;
data.farTech = adNone;
for (auto &row : data.enhancementJobs)
std::fill(std::begin(row), std::end(row), static_cast<std::uint8_t>(jNone));
for (auto &order : data.impOrder)
order.fill(-1);
data.coldWarStart = -ColdWarTurns - 1;
data.toldAge = -1;
data.toldModels = 3;
data.toldAlive = 0;
data.toldContact = 0;
data.toldOwnCredibility = InitialCredibility;
for (int i = 0; i < nPl; ++i) {
if (g.Difficulty[i] > 0)
data.toldAlive += 1 << i;
}
data.peaceEvaHappened = 0;
for (auto &wonder : data.toldWonders) {
wonder.CityID = -1;
wonder.EffectiveOwner = -1;
}
data.toldTech.fill(static_cast<std::int8_t>(tsNA));
}
} // namespace
void MainScreen::endNego()
{
if (negoDlg().isVisible())
negoDlg().close();
// TODO: the end-of-turn button and panel repaint need the main window (not ported).
clientMode = -1;
m_idle = false;
}
void MainScreen::client(int command, int newPlayer, void *data)
{
TNewGameData &g = ClientTools::g;
const auto intData = [data] { return *static_cast<int *>(data); };
const auto isLocalSession = [] { return !ClientTools::isMultiPlayerGame(); };
if (command == cTurn || command == cResume || command == cContinue || command == cMovieTurn ||
command == scContact || (command >= scDipStart && command <= scDipBreak)) {
supervising = g.Difficulty[newPlayer] == 0;
// TODO: ArrangeMidPanel() needs the main window layout (not ported).
}
switch (command) {
case cDebugMessage:
logDlg().add(newPlayer, g.RO[0]->Turn, QString::fromLocal8Bit(static_cast<const char *>(data)));
return;
case cShowNego: {
const QString text = negoOfferText(*static_cast<TShowNegoData *>(data));
if (!text.isEmpty())
logDlg().add(newPlayer, g.RO[0]->Turn, text);
return;
}
case cInitModule: {
auto *initData = static_cast<TInitModuleData *>(data);
ClientTools::server = initData->Server;
initModule();
initData->DataSize = sizeof(PersistentData);
initData->Flags = aiThreaded;
return;
}
case cReleaseModule:
doneModule();
return;
case cHelpOnly:
case cStartHelp:
case cStartCredits: {
age = 0;
if (command == cHelpOnly)
MainTexture->setAge(-1);
Tribes::init();
const QRect screen = Dpi::Screen::primaryMonitor().boundsRect();
helpDlg().userLeft = screen.left() + (screen.width() - helpDlg().width()) / 2;
helpDlg().userTop = screen.top() + (screen.height() - helpDlg().height()) / 2;
helpDlg().difficulty = 0;
helpDlg().showNewContent(WindowMode::Modal, Help::LinkCategory::Misc,
static_cast<int>(command == cStartCredits ? Help::MiscLinkIndex::Credits
: Help::MiscLinkIndex::Main));
Tribes::done();
return;
}
case cNewGame:
case cLoadGame:
case cMovie:
case cNewMap:
// generateNames follows the "Names" menu item (mNames), which isn't ported: keep the current setting.
m_gameOK = true;
g = *static_cast<TNewGameData *>(data);
ClientTools::me = -1;
m_pLogo = -1;
clientMode = -1;
m_idle = false;
m_jump.fill(0);
if (m_startRunning)
m_jump[0] = 999999;
gameMode = command;
grExt.resetPixUsed();
// TODO: MainMap/NoMap.Reset and SetMapOptions need the main map (not ported).
Tribes::init();
getTribeList();
for (int p1 = 0; p1 < nPl; ++p1) {
if (g.RO[p1] && g.RO[p1]->Data)
initPersistentData(*static_cast<PersistentData *>(g.RO[p1]->Data));
}
arrangeDialogs();
age = 0;
m_movieSpeed = 1;
logDlg().setSlotItemVisible(true);
logDlg().host = this;
if (m_helpDlg)
m_helpDlg->clearHistory();
if (m_cityDlg)
m_cityDlg->reset();
// TODO: MiniMap sizing and the area buttons' visibility need the main window (not ported).
for (int i = 0; i < nPl; ++i) {
Tribes::tribe[static_cast<std::size_t>(i)].reset();
tribeOriginal[static_cast<std::size_t>(i)] = false;
}
toldSlavery = -1;
m_closable = false;
m_firstMovieTurn = true;
return;
case cGetReady:
case cReplay:
if (newPlayer == 0) {
int missing = 0;
for (int p1 = 0; p1 < nPl; ++p1) {
if (g.Difficulty[p1] > 0 && !Tribes::tribe[static_cast<std::size_t>(p1)])
++missing;
}
if (missing > static_cast<int>(unusedTribeFiles.size())) {
m_gameOK = false;
simpleMessage(phrases.lookup(QStringLiteral("TOOFEWTRIBES")));
} else {
const auto setTribe = [&](int trix, const QString &fileName) {
if (gameMode == cLoadGame) {
createTribe(trix, fileName, false);
} else {
TribeInfo info;
info.trix = trix;
info.fileName = fileName;
QByteArray packed = info.pack();
ClientTools::server(commandWithData(cSetTribe, info.commandDataSize()), 0, 0, packed.data());
}
};
for (int p1 = 0; p1 < nPl; ++p1) { // let player select own tribes
if (!(g.Difficulty[p1] > 0 && !Tribes::tribe[static_cast<std::size_t>(p1)] && g.RO[p1]))
continue;
tribeNames.clear();
for (const UnusedTribe &unused : unusedTribeFiles) {
QString name;
QColor color;
Tribes::getTribeInfo(unused.fileName, name, color);
tribeNames.push_back({name, color});
}
Q_ASSERT(!tribeNames.empty());
modalSelectDlg().showNewContent(WindowMode::Modal, Select::ListKind::Tribe);
QCoreApplication::processEvents();
const int chosen = modalSelectDlg().result;
const QString fileName = unusedTribeFiles[static_cast<std::size_t>(chosen)].fileName;
unusedTribeFiles.erase(unusedTribeFiles.begin() + chosen);
setTribe(p1, fileName);
}
for (int p1 = 0; p1 < nPl; ++p1) { // autoselect enemy tribes
if (!(g.Difficulty[p1] > 0 && !Tribes::tribe[static_cast<std::size_t>(p1)] && !g.RO[p1]))
continue;
const int chosen = chooseUnusedTribe();
const QString fileName = unusedTribeFiles[static_cast<std::size_t>(chosen)].fileName;
unusedTribeFiles.erase(unusedTribeFiles.begin() + chosen);
setTribe(p1, fileName);
}
}
if (!generateNames) {
for (int p1 = 0; p1 < nPl; ++p1) {
if (Tribes::tribe[static_cast<std::size_t>(p1)])
Tribes::tribe[static_cast<std::size_t>(p1)]->numberName = p1;
}
}
}
return;
case cBreakGame:
// TODO: SaveSettings() needs the settings store (not ported).
if (m_cityDlg)
m_cityDlg->closeAction = CityScreen::CityCloseAction::None;
applyToVisibleForms(FormAction::Close);
if (logDlg().isVisible())
logDlg().close();
logDlg().clear();
m_startRunning = !m_idle && m_jump[0] > 0; // AI called Reload
ClientTools::me = -1;
m_idle = false;
clientMode = -1;
// TODO: hiding the unit/terrain/EOT/movie buttons and the scrollbar reset need the main window.
for (auto &tribe : Tribes::tribe)
tribe.reset();
Tribes::done();
m_closable = true;
close();
return;
case cShowTurnChange:
if (intData() >= 0)
m_pLogo = intData();
// TODO: repainting the AI logo needs the main window (not ported).
return;
case cShowCancelTreaty:
if (isLocalSession()) {
const int other = intData();
QString key;
switch (g.RO[newPlayer]->Treaty[other]) {
case trPeace: key = QStringLiteral("FRCANCELBYREJECT_PEACE"); break;
case trFriendlyContact: key = QStringLiteral("FRCANCELBYREJECT_FRIENDLY"); break;
case trAlliance: key = QStringLiteral("FRCANCELBYREJECT_ALLIANCE"); break;
default: break;
}
MessgEx::tribeMessage(other, Tribes::tribe[static_cast<std::size_t>(other)]->tPhrase(key),
QStringLiteral("CANCELTREATY"));
}
return;
case cShowCancelTreatyByAlliance:
if (m_idle && newPlayer == ClientTools::me) {
MessgEx::tribeMessage(intData(),
Tribes::tribe[static_cast<std::size_t>(intData())]->tPhrase(
QStringLiteral("FRENEMYALLIANCE")),
QStringLiteral("CANCELTREATY"));
}
return;
case cShowSupportAllianceAgainst:
if (isLocalSession() && m_jump[0] == 0) {
const int ally = intData() & 0xF;
const int enemy = intData() >> 4;
MessgEx::tribeMessage(ally,
Tribes::tribe[static_cast<std::size_t>(ally)]->tPhrase(QStringLiteral("FRMYALLIANCE1")) +
QLatin1Char(' ') +
Tribes::tribe[static_cast<std::size_t>(enemy)]->tPhrase(
QStringLiteral("FRMYALLIANCE2")),
QStringLiteral("CANCELTREATY"));
}
return;
case cShowPeaceViolation:
if (isLocalSession() && m_jump[0] == 0) {
MessgEx::tribeMessage(
intData(),
Tribes::tribe[static_cast<std::size_t>(intData())]->tPhrase(QStringLiteral("EVIOLATION")).arg(
turnToString(ClientTools::myRO->Turn + PeaceEvaTurns - 1)),
QStringLiteral("MSG_WITHDRAW"));
}
return;
case cShowEndContact:
endNego();
return;
case cShowMissionResult: {
const auto info = *static_cast<std::uint32_t *>(data);
if (info == 0) {
MessgEx::soundMessageEx(phrases.lookup(QStringLiteral("NOFOREIGNINFO")), QString());
} else {
QString s = phrases.lookup(QStringLiteral("FOREIGNINFO"));
for (int p1 = 0; p1 < nPl; ++p1) {
if ((3u << (p1 * 2)) & info)
s += QLatin1Char('\\') + Tribes::tribe[static_cast<std::size_t>(p1)]->tPhrase(QStringLiteral("SHORTNAME"));
}
MessgEx::soundMessageEx(s, QString());
}
return;
}
case cShowShipChange:
if (isLocalSession() && m_jump[0] == 0)
showEnemyShipChange(*static_cast<TShowShipChange *>(data));
return;
case cShowGreatLibTech:
if (isLocalSession() && m_jump[0] == 0) {
MessgEx::MessgExDlg &dlg = messgExDlg();
dlg.messageText = formatPhrase(QStringLiteral("GRLIB_GENERAL"),
{ phrases.lookup(QStringLiteral("ADVANCES"), intData()) });
dlg.openSound = QStringLiteral("NEWADVANCE_GRLIB");
dlg.kind = MessageKind::Ok;
dlg.iconKind = MessgEx::MessageIconKind::Imp;
dlg.iconIndex = woGrLibrary;
dlg.showModal();
}
return;
default:
break;
}
if (command >= cClientEx) {
switch (command & ~static_cast<int>(CommandDataElementCountMask)) {
case cSetTribe: {
const TribeInfo info = unpackTribeInfo(data);
const auto it = std::find_if(unusedTribeFiles.begin(), unusedTribeFiles.end(),
[&](const UnusedTribe &unused) { return unused.fileName == info.fileName; });
if (it != unusedTribeFiles.end())
unusedTribeFiles.erase(it);
createTribe(info.trix, info.fileName, true);
return;
}
case cSetNewModelPicture:
case cSetModelPicture: {
const Tribes::ModelPictureInfo info = unpackModelPictureInfo(data);
if (tribeOriginal[static_cast<std::size_t>(info.trix)]) {
Tribes::tribe[static_cast<std::size_t>(info.trix)]->setModelPicture(
info, (command & ~static_cast<int>(CommandDataElementCountMask)) == cSetNewModelPicture);
}
return;
}
case cSetSlaveIndex:
Tribes::tribe[static_cast<std::size_t>(intData() >> 16)]->mixSlaves = intData() & 0xFFFF;
return;
case cSetCityName: {
const CityNameInfo info = unpackCityNameInfo(data);
if (tribeOriginal[static_cast<std::size_t>(info.id >> 12)])
Tribes::tribe[static_cast<std::size_t>(info.id >> 12)]->setCityName(info.id & 0xFFF, info.newName);
return;
}
case cSetModelName: {
const ModelNameInfo info = unpackModelNameInfo(data);
if (tribeOriginal[static_cast<std::size_t>(newPlayer)])
Tribes::tribe[static_cast<std::size_t>(newPlayer)]->modelNameAt(info.mix) = info.newName;
return;
}
default:
break;
}
}
}
} // namespace Term
} // namespace Cevo
+15
View File
@@ -117,8 +117,23 @@ public:
// (advance icons, StdUnits graphics, smallImp). // (advance icons, StdUnits graphics, smallImp).
void initModule(); void initModule();
void doneModule(); void doneModule();
// Term.pas's TMainScreen.Client(): the in-process client entry point the
// server calls for the human player. See Term.MainScreen.Client.cpp for
// which commands are served so far.
void client(int command, int newPlayer, void *data);
// Term.pas's EndNego(): leaves the negotiation screen.
void endNego();
private: private:
// Term.pas's implementation-level state (Jump/pLogo/GameOK/Idle/...).
std::array<int, nPl> m_jump{};
int m_pLogo = -1;
bool m_gameOK = true;
bool m_idle = false;
bool m_startRunning = false;
bool m_firstMovieTurn = true;
bool m_closable = false;
int m_movieSpeed = 1;
std::unique_ptr<Wonders::WondersDlg> m_wondersDlg; std::unique_ptr<Wonders::WondersDlg> m_wondersDlg;
std::unique_ptr<TechTree::TechTreeDlg> m_techTreeDlg; std::unique_ptr<TechTree::TechTreeDlg> m_techTreeDlg;
std::unique_ptr<Enhance::EnhanceDlg> m_enhanceDlg; std::unique_ptr<Enhance::EnhanceDlg> m_enhanceDlg;
+36
View File
@@ -282,6 +282,42 @@ QByteArray packModelPictureInfo(const Tribes::ModelPictureInfo &info)
return data; return data;
} }
TribeInfo unpackTribeInfo(const void *data)
{
const auto *bytes = static_cast<const unsigned char *>(data);
TribeInfo info;
std::int32_t trix;
std::memcpy(&trix, bytes, sizeof trix);
info.trix = trix;
info.fileName = QString::fromUtf8(reinterpret_cast<const char *>(bytes + sizeof trix + 1), bytes[sizeof trix]);
return info;
}
CityNameInfo unpackCityNameInfo(const void *data)
{
const auto *bytes = static_cast<const unsigned char *>(data);
CityNameInfo info;
std::int32_t id;
std::memcpy(&id, bytes, sizeof id);
info.id = id;
info.newName = QString::fromUtf8(reinterpret_cast<const char *>(bytes + sizeof id + 1), bytes[sizeof id]);
return info;
}
ModelNameInfo unpackModelNameInfo(const void *data)
{
const auto *bytes = static_cast<const unsigned char *>(data);
ModelNameInfo info;
std::int32_t mix;
std::memcpy(&mix, bytes, sizeof mix);
info.mix = mix;
info.newName = QString::fromUtf8(reinterpret_cast<const char *>(bytes + sizeof mix + 1), bytes[sizeof mix]);
return info;
}
int clientMode = -1;
std::vector<TribeNameEntry> tribeNames;
Tribes::ModelPictureInfo unpackModelPictureInfo(const void *data) Tribes::ModelPictureInfo unpackModelPictureInfo(const void *data)
{ {
const auto *bytes = static_cast<const unsigned char *>(data); const auto *bytes = static_cast<const unsigned char *>(data);
+16
View File
@@ -297,6 +297,14 @@ struct ModelNameInfo {
// Wire layout of Tribes::ModelPictureInfo (4 int32 + ShortString). // Wire layout of Tribes::ModelPictureInfo (4 int32 + ShortString).
QByteArray packModelPictureInfo(const Tribes::ModelPictureInfo &info); QByteArray packModelPictureInfo(const Tribes::ModelPictureInfo &info);
Tribes::ModelPictureInfo unpackModelPictureInfo(const void *data); Tribes::ModelPictureInfo unpackModelPictureInfo(const void *data);
// Inverses of TribeInfo/CityNameInfo/ModelNameInfo::pack().
TribeInfo unpackTribeInfo(const void *data);
CityNameInfo unpackCityNameInfo(const void *data);
ModelNameInfo unpackModelNameInfo(const void *data);
// Term.pas's `ClientMode`: the command (cTurn, cResume, scContact, ...) the
// client is currently serving, -1 when idle.
extern int clientMode;
// Term.pas's `TribeOriginal`: whether tribe p comes from the original // Term.pas's `TribeOriginal`: whether tribe p comes from the original
// (non-network-relayed) game rather than being created for a movie/viewer. // (non-network-relayed) game rather than being created for a movie/viewer.
@@ -325,6 +333,14 @@ struct UnusedTribe {
}; };
extern std::vector<UnusedTribe> unusedTribeFiles; extern std::vector<UnusedTribe> unusedTribeFiles;
// Term.pas's `TribeNames` (display name + colour of the tribes a player can
// pick from, filled right before the tribe selection list is shown).
struct TribeNameEntry {
QString name;
QColor color;
};
extern std::vector<TribeNameEntry> tribeNames;
// Term.pas's `TaxSum`/`ScienceSum: Integer;` (aggregate tax/science totals // Term.pas's `TaxSum`/`ScienceSum: Integer;` (aggregate tax/science totals
// across all owned cities, refreshed by MainScreen::updateViews()). // across all owned cities, refreshed by MainScreen::updateViews()).
extern int taxSum; extern int taxSum;
+3
View File
@@ -35,6 +35,9 @@
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
QApplication a(argc, argv); QApplication a(argc, argv);
QCoreApplication::setOrganizationName(QStringLiteral("c-evo-evo"));
QCoreApplication::setApplicationName(QStringLiteral("c-evo-evo"));
Cevo::initDirectories(QCoreApplication::arguments());
Cevo::loadAssets(); Cevo::loadAssets();
QTranslator translator; QTranslator translator;
+1 -1
View File
@@ -33,7 +33,7 @@
# load it from CMAKE_INSTALL_RESOURCEDIR (see CEVO_RESOURCE_DIR, defined for # load it from CMAKE_INSTALL_RESOURCEDIR (see CEVO_RESOURCE_DIR, defined for
# the c-evo-evo target in the top-level CMakeLists.txt). # the c-evo-evo target in the top-level CMakeLists.txt).
install(DIRECTORY Graphics Music Sounds Localization Tribes install(DIRECTORY Graphics Music Sounds Localization Tribes Maps Saved
DESTINATION ${CMAKE_INSTALL_RESOURCEDIR} DESTINATION ${CMAKE_INSTALL_RESOURCEDIR}
) )
# English (default) texts; localized ones live in Localization/<locale>/. # English (default) texts; localized ones live in Localization/<locale>/.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 138 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 140 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 150 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 152 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 156 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 159 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 153 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 163 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 171 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 165 B

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
I've made a map of the world, with some concessions to playability.
Starting positions are within normal range for random maps, but are chosen to be unevenly distributed.
I used to test AI behavior in different conditions (room to expand, existence of neighbors).
The human player starts in Italy, which I think is the most interesting starting position (in a normal game).
Experienced players (interested in economy) should try the New Zealand starting position some time (by making it the favorite starting position)
To show that New Zealand is playable, and to show the potential power of my favorite Wonder (The Lighthouse) I included a game against SETI instances.
PS Sorry Argentineans, for cutting off a big chunk of the southern hemisphere
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more