id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,536,141
|
remotedesktopuniting.cpp
|
agafon0ff_SimpleRemoteDesktop/src/remotedesktopuniting.cpp
|
#include "remotedesktopuniting.h"
#include <QApplication>
#include <QCommonStyle>
#include <QMessageBox>
#include <QSettings>
#include <QHostInfo>
#include <QThread>
#include <QAction>
#include <QDebug>
#include <QUuid>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
RemoteDesktopUniting u;
return a.exec();
}
RemoteDesktopUniting::RemoteDesktopUniting(QObject *parent) : QObject(parent),
m_webSocketTransfer(Q_NULLPTR),
m_webSocketHandler(Q_NULLPTR),
m_serverHttp(new ServerHttp(this)),
m_graberClass(nullptr),
m_inputSimulator(new InputSimulator(this)),
m_trayMenu(new QMenu),
m_infoWidget(new InfoWidget),
m_trayIcon(new QSystemTrayIcon(this)),
m_title("SimpleRemoteDesktop v1.1"),
m_currentPort(8080),
m_isConnectedToProxy(false)
{
m_infoWidget->setWindowTitle(m_title);
m_trayMenu->addAction(QIcon(":/res/info.ico"), "Info", this, &RemoteDesktopUniting::showInfoWidget);
m_trayMenu->addAction(QIcon(":/res/close.ico"), "Exit", this, &RemoteDesktopUniting::closeSignal);
m_trayIcon->setContextMenu(m_trayMenu);
m_trayIcon->setIcon(QIcon(":/res/favicon.ico"));
m_trayIcon->setToolTip(m_title);
m_trayIcon->show();
startGraberClass();
startHttpServer(static_cast<quint16>(m_infoWidget->portHttp()), m_infoWidget->filesPath());
startWebSocketTransfer(static_cast<quint16>(m_infoWidget->portWeb()), m_infoWidget->login(),
m_infoWidget->pass(), m_infoWidget->name());
startWebSocketHandler(m_infoWidget->proxyHost(), m_infoWidget->name(), m_infoWidget->login(),
m_infoWidget->pass(), m_infoWidget->proxyLogin(), m_infoWidget->proxyPass());
}
void RemoteDesktopUniting::showInfoWidget()
{
m_infoWidget->showNormal();
m_infoWidget->raise();
}
void RemoteDesktopUniting::startHttpServer(quint16 port, const QString &filesPath)
{
m_serverHttp->setPort(static_cast<quint16>(port));
m_serverHttp->setPath(filesPath);
m_currentPort = port;
if(m_serverHttp->start())
{
showInfoWidget();
}
else
{
m_trayIcon->showMessage(m_title, "Failed to start on port: " +
QString::number(port) + "!", QSystemTrayIcon::Critical, 5000);
}
}
void RemoteDesktopUniting::startGraberClass()
{
QThread *thread = new QThread;
m_graberClass = new GraberClass;
connect(thread, &QThread::started, m_graberClass, &GraberClass::start);
connect(this, &RemoteDesktopUniting::closeSignal, m_graberClass, &GraberClass::stop);
connect(m_graberClass, &GraberClass::finished, this, &RemoteDesktopUniting::finishedWebSockeTransfer);
connect(m_graberClass, &GraberClass::finished, thread, &QThread::quit);
connect(thread, &QThread::finished, m_graberClass, &WebSocketTransfer::deleteLater);
connect(thread, &QThread::finished, thread, &QThread::deleteLater);
connect(this, &RemoteDesktopUniting::stopGrabing, m_graberClass, &GraberClass::stopSending);
m_graberClass->moveToThread(thread);
thread->start();
}
void RemoteDesktopUniting::startWebSocketTransfer(quint16 port, const QString &login, const QString &pass, const QString &name)
{
QThread *thread = new QThread;
m_webSocketTransfer = new WebSocketTransfer;
m_webSocketTransfer->setType(WebSocketTransfer::TransferWebClients);
m_webSocketTransfer->setPort(port);
m_webSocketTransfer->setName(name);
m_webSocketTransfer->setLoginPass(login, pass);
connect(thread, &QThread::started, m_webSocketTransfer, &WebSocketTransfer::start);
connect(this, &RemoteDesktopUniting::closeSignal, m_webSocketTransfer, &WebSocketTransfer::stop);
connect(m_webSocketTransfer, &WebSocketTransfer::finished, this, &RemoteDesktopUniting::finishedWebSockeTransfer);
connect(m_webSocketTransfer, &WebSocketTransfer::finished, thread, &QThread::quit);
connect(thread, &QThread::finished, m_webSocketTransfer, &WebSocketTransfer::deleteLater);
connect(thread, &QThread::finished, thread, &QThread::deleteLater);
connect(m_webSocketTransfer, &WebSocketTransfer::newSocketConnected, this, &RemoteDesktopUniting::createConnectionToHandler);
connect(m_webSocketTransfer, &WebSocketTransfer::connectedSocketUuid, this, &RemoteDesktopUniting::remoteClientConnected);
connect(m_webSocketTransfer, &WebSocketTransfer::disconnectedSocketUuid, this, &RemoteDesktopUniting::remoteClientDisconnected);
m_webSocketTransfer->moveToThread(thread);
thread->start();
}
void RemoteDesktopUniting::startWebSocketHandler(const QString &host, const QString &name, const QString &login,
const QString &pass, const QString &proxyLogin, const QString &proxyPass)
{
QThread *thread = new QThread;
m_webSocketHandler = new WebSocketHandler;
m_webSocketHandler->setType(WebSocketHandler::HandlerSingleClient);
m_webSocketHandler->setUrl(host);
m_webSocketHandler->setName(name);
m_webSocketHandler->setLoginPass(login, pass);
m_webSocketHandler->setProxyLoginPass(proxyLogin, proxyPass);
connect(thread, &QThread::started, m_webSocketHandler, &WebSocketHandler::createSocket);
connect(this, &RemoteDesktopUniting::closeSignal, m_webSocketHandler, &WebSocketHandler::removeSocket);
connect(m_webSocketHandler, &WebSocketHandler::finished, this, &RemoteDesktopUniting::finishedWebSockeHandler);
connect(m_webSocketHandler, &WebSocketHandler::finished, thread, &QThread::quit);
connect(thread, &QThread::finished, m_webSocketHandler, &WebSocketHandler::deleteLater);
connect(thread, &QThread::finished, thread, &QThread::deleteLater);
connect(m_webSocketHandler, &WebSocketHandler::connectedProxyClient, this, &RemoteDesktopUniting::remoteClientConnected);
connect(m_webSocketHandler, &WebSocketHandler::disconnectedProxyClient, this, &RemoteDesktopUniting::remoteClientDisconnected);
connect(m_webSocketHandler, &WebSocketHandler::authenticatedStatus, this, &RemoteDesktopUniting::connectedToProxyServer);
createConnectionToHandler(m_webSocketHandler);
m_webSocketHandler->moveToThread(thread);
thread->start();
}
void RemoteDesktopUniting::createConnectionToHandler(WebSocketHandler *webSocketHandler)
{
if(!webSocketHandler)
return;
connect(m_graberClass, &GraberClass::imageParameters, webSocketHandler, &WebSocketHandler::sendImageParameters);
connect(m_graberClass, &GraberClass::imageTile, webSocketHandler, &WebSocketHandler::sendImageTile);
connect(m_graberClass, &GraberClass::screenPositionChanged, m_inputSimulator, &InputSimulator::setScreenPosition);
connect(webSocketHandler, &WebSocketHandler::getDesktop, m_graberClass, &GraberClass::startSending);
connect(webSocketHandler, &WebSocketHandler::changeDisplayNum, m_graberClass, &GraberClass::changeScreenNum);
connect(webSocketHandler, &WebSocketHandler::receivedTileNum, m_graberClass, &GraberClass::setReceivedTileNum);
connect(webSocketHandler, &WebSocketHandler::setKeyPressed, m_inputSimulator, &InputSimulator::simulateKeyboard);
connect(webSocketHandler, &WebSocketHandler::setMousePressed, m_inputSimulator, &InputSimulator::simulateMouseKeys);
connect(webSocketHandler, &WebSocketHandler::setMouseMove, m_inputSimulator, &InputSimulator::simulateMouseMove);
connect(webSocketHandler, &WebSocketHandler::setWheelChanged, m_inputSimulator, &InputSimulator::simulateWheelEvent);
connect(webSocketHandler, &WebSocketHandler::setMouseDelta, m_inputSimulator, &InputSimulator::setMouseDelta);
}
void RemoteDesktopUniting::finishedWebSockeTransfer()
{
m_webSocketTransfer = Q_NULLPTR;
if(!m_webSocketHandler)
QApplication::quit();
}
void RemoteDesktopUniting::finishedWebSockeHandler()
{
m_webSocketHandler = Q_NULLPTR;
if(!m_webSocketTransfer)
QApplication::quit();
}
void RemoteDesktopUniting::remoteClientConnected(const QByteArray &uuid)
{
if(!m_remoteClientsList.contains(uuid))
m_remoteClientsList.append(uuid);
qDebug()<<"RemoteDesktopUniting remote client count:" << m_remoteClientsList.size();
}
void RemoteDesktopUniting::remoteClientDisconnected(const QByteArray &uuid)
{
if(m_remoteClientsList.contains(uuid))
{
m_remoteClientsList.removeOne(uuid);
if(m_remoteClientsList.size() == 0)
emit stopGrabing();
}
qDebug()<<"RemoteDesktopUniting remoteClientDisconnected, count:" << m_remoteClientsList.size();
}
void RemoteDesktopUniting::connectedToProxyServer(bool state)
{
if(m_isConnectedToProxy != state)
{
m_isConnectedToProxy = state;
if(state)
showInfoWidget();
}
}
| 8,728
|
C++
|
.cpp
| 173
| 45.364162
| 132
| 0.758042
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,142
|
infowidget.cpp
|
agafon0ff_SimpleRemoteDesktop/src/infowidget.cpp
|
#include <QNetworkInterface>
#include <QIntValidator>
#include <QCommonStyle>
#include <QApplication>
#include <QMessageBox>
#include <QGridLayout>
#include <QHostInfo>
#include <QSettings>
#include <QLineEdit>
#include <QMenuBar>
#include <QAction>
#include <QStyle>
#include <QLabel>
#include <QMenu>
#include "infowidget.h"
InfoWidget::InfoWidget(QWidget *parent)
: QMainWindow{parent}
{
setWindowIcon(QIcon(":/res/favicon.ico"));
setAttribute(Qt::WA_QuitOnClose, false);
setMinimumWidth(400);
QWidget *centralWidget = new QWidget(this);
QGridLayout *gridLayout = new QGridLayout(centralWidget);
gridLayout->setSpacing(0);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setContentsMargins(0, 0, 0, 0);
setCentralWidget(centralWidget);
loadSettings();
createInfoWidget();
createSettingsWidget();
QMenuBar *menuBar = new QMenuBar(this);
menuBar->addAction("Info", this, [=]{ m_settingsWidget->hide(); m_infoWidget->show(); });
menuBar->addAction("Settings", this, [=]{ m_infoWidget->hide(); m_settingsWidget->show(); });
QCommonStyle style;
QMenu *menuAbout = menuBar->addMenu("About");
menuAbout->addAction(QIcon(":/res/favicon.ico"), "About SRD", this, &InfoWidget::showAboutSRDMessage);
menuAbout->addAction(QIcon(style.standardPixmap(QStyle::SP_TitleBarMenuButton)),
"About Qt", this, &InfoWidget::showAboutQtMessage);
setMenuBar(menuBar);
}
void InfoWidget::loadSettings()
{
QSettings settings("config.ini",QSettings::IniFormat);
settings.beginGroup("REMOTE_DESKTOP");
int portHttp = settings.value("portHttp", 0).toInt();
if (portHttp != 0) m_portHttp = portHttp;
else settings.setValue("portHttp", m_portHttp);
QString filesPath(settings.value("filesPath").toString());
if (!filesPath.isEmpty()) m_filesPath = std::move(filesPath);
else settings.setValue("filesPath", m_filesPath);
int portWeb = settings.value("portWeb", 0).toInt();
if (portWeb != 0) m_portWeb = portWeb;
else settings.setValue("portWeb",portWeb);
QString login(settings.value("login").toString());
if (!login.isEmpty()) m_login = std::move(login);
else settings.setValue("login", m_login);
QString pass(settings.value("pass").toString());
if (!pass.isEmpty()) m_pass = std::move(pass);
else settings.setValue("pass", m_pass);
m_name = settings.value("name").toString();
if (m_name.isEmpty())
{
m_name = QHostInfo::localHostName();
settings.setValue("name", m_name);
}
QString proxyHost(settings.value("proxyHost").toString());
if (!proxyHost.isEmpty()) m_proxyHost = std::move(proxyHost);
else settings.setValue("proxyHost", m_proxyHost);
QString proxyLogin(settings.value("proxyLogin").toString());
if (!proxyLogin.isEmpty()) m_proxyLogin = std::move(proxyLogin);
else settings.setValue("proxyLogin", m_proxyLogin);
QString proxyPass(settings.value("proxyPass").toString());
if(!proxyPass.isEmpty()) m_proxyPass = std::move(proxyPass);
else settings.setValue("proxyPass",proxyPass);
settings.endGroup();
settings.sync();
}
void InfoWidget::showAboutSRDMessage()
{
QString text = tr("<h3>Simple Remote Desktop</h3>\n\n"
"<p>This software is distributed under the GPL-3.0 license.</p>"
"<p>Remote desktop management from a web browser, based on Qt5.</p>");
QString contacts = tr("<p>Contacts:</p><p>Email: agafon0ff@mail.ru</p>"
"<p>Github: <a href=\"https://%1/\">%1</a></p>"
"<p>Current version: <a href=\"https://%2/\">SimpleRemoteDesktop/releases</a></p>").
arg(QStringLiteral("github.com/agafon0ff"),
QStringLiteral("github.com/agafon0ff/SimpleRemoteDesktop/releases/"));
QMessageBox *msgBox = new QMessageBox(this);
msgBox->setWindowTitle(tr("About Simple Remote Desktop"));
msgBox->setText(text);
msgBox->setInformativeText(contacts);
msgBox->setAttribute(Qt::WA_QuitOnClose, false);
msgBox->setIconPixmap(QPixmap(":/res/favicon.ico"));
msgBox->exec();
delete msgBox;
}
void InfoWidget::showAboutQtMessage()
{
QMessageBox::aboutQt(this, "About Qt Libraries");
}
void InfoWidget::createInfoWidget()
{
if (m_infoWidget)
return;
m_infoWidget = new QWidget(centralWidget());
QGridLayout *gridLayout = new QGridLayout(m_infoWidget);
gridLayout->setSpacing(9);
gridLayout->setContentsMargins(9, 9, 9, 9);
QFont font = QApplication::font();
font.setPointSize(font.pointSize() * 1.5);
QLabel *labelFavicon = new QLabel(m_infoWidget);
labelFavicon->setPixmap(QPixmap(":/res/favicon.ico"));
labelFavicon->setScaledContents(true);
labelFavicon->setMaximumSize(50, 50);
gridLayout->addWidget(labelFavicon, 0, 0);
QLabel *infoLabel = new QLabel(m_infoWidget);
infoLabel->setText("To manage this computer\nfollow the link below:");
infoLabel->setAlignment(Qt::AlignCenter);
infoLabel->setWordWrap(true);
infoLabel->setFont(font);
gridLayout->addWidget(infoLabel, 0, 1);
QLabel *addrLabel = new QLabel(m_infoWidget);
addrLabel->setText(getLocalAddress());
addrLabel->setAlignment(Qt::AlignCenter);
addrLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
addrLabel->setFont(font);
gridLayout->addWidget(addrLabel, 1, 0, 1, 2);
centralWidget()->layout()->addWidget(m_infoWidget);
}
void InfoWidget::createSettingsWidget()
{
if (m_settingsWidget)
return;
m_settingsWidget = new QWidget(centralWidget());
QGridLayout *gridLayout = new QGridLayout(m_settingsWidget);
gridLayout->setSpacing(9);
gridLayout->setContentsMargins(9, 9, 9, 9);
int row = 0;
QLabel *labelMainSettings = new QLabel("Main settings:", m_settingsWidget);
labelMainSettings->setAlignment(Qt::AlignCenter);
gridLayout->addWidget(labelMainSettings, row, 0, 1, 2);
QLabel *labelName = new QLabel("Name:", m_settingsWidget);
gridLayout->addWidget(labelName, ++row, 0);
QLineEdit *lineEditName = new QLineEdit(m_name, m_settingsWidget);
gridLayout->addWidget(lineEditName, row, 1);
QLabel *labelPortHttp = new QLabel("Http port:", m_settingsWidget);
gridLayout->addWidget(labelPortHttp, ++row, 0);
QLineEdit *lineEditPortHttp = new QLineEdit(QString::number(m_portHttp), m_settingsWidget);
lineEditPortHttp->setValidator(new QIntValidator(0, 65535, this));
gridLayout->addWidget(lineEditPortHttp, row, 1);
QLabel *labelPortWeb = new QLabel("WebSocket port:", m_settingsWidget);
gridLayout->addWidget(labelPortWeb, ++row, 0);
QLineEdit *lineEditPortWeb = new QLineEdit(QString::number(m_portWeb), m_settingsWidget);
lineEditPortWeb->setValidator(lineEditPortHttp->validator());
gridLayout->addWidget(lineEditPortWeb, row, 1);
QLabel *labelLogin = new QLabel("Login:", m_settingsWidget);
gridLayout->addWidget(labelLogin, ++row, 0);
QLineEdit *lineEditLogin = new QLineEdit(m_login, m_settingsWidget);
gridLayout->addWidget(lineEditLogin, row, 1);
QLabel *labelPass = new QLabel("Password:", m_settingsWidget);
gridLayout->addWidget(labelPass, ++row, 0);
QLineEdit *lineEditPass = new QLineEdit(m_pass, m_settingsWidget);
lineEditPass->setEchoMode(QLineEdit::Password);
gridLayout->addWidget(lineEditPass, row, 1);
QLabel *labelSpacer = new QLabel(m_settingsWidget);
gridLayout->addWidget(labelSpacer, ++row, 0);
QLabel *labelProxySettings = new QLabel("Proxy settings:", m_settingsWidget);
labelProxySettings->setAlignment(Qt::AlignCenter);
gridLayout->addWidget(labelProxySettings, ++row, 0, 1, 2);
QLabel *labelProxyAddr = new QLabel("Proxy address:", m_settingsWidget);
gridLayout->addWidget(labelProxyAddr, ++row, 0);
QLineEdit *lineEditProxyAddr = new QLineEdit(m_proxyHost, m_settingsWidget);
gridLayout->addWidget(lineEditProxyAddr, row, 1);
QLabel *labelProxyLogin = new QLabel("Proxy login:", m_settingsWidget);
gridLayout->addWidget(labelProxyLogin, ++row, 0);
QLineEdit *lineEditProxyLogin = new QLineEdit(m_proxyLogin, m_settingsWidget);
gridLayout->addWidget(lineEditProxyLogin, row, 1);
QLabel *labelProxyPass = new QLabel("Proxy password:", m_settingsWidget);
gridLayout->addWidget(labelProxyPass, ++row, 0);
QLineEdit *lineEditProxyPass = new QLineEdit(m_proxyPass, m_settingsWidget);
lineEditProxyPass->setEchoMode(QLineEdit::Password);
gridLayout->addWidget(lineEditProxyPass, row, 1);
centralWidget()->layout()->addWidget(m_settingsWidget);
m_settingsWidget->hide();
}
QString InfoWidget::getLocalAddress()
{
QString result;
QList<QHostAddress> my_addr_list;
QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
for(int i=0;i<addresses.count();++i)
{
if(addresses.at(i).protocol() == QAbstractSocket::IPv4Protocol &&
!addresses.at(i).toString().contains("127") &&
!addresses.at(i).toString().contains("172"))
{
my_addr_list.append(addresses.at(i));
}
}
if(my_addr_list.count() == 0)
return result;
result.append("http://");
result.append(my_addr_list.at(0).toString());
result.append(":");
result.append(QString::number(portHttp()));
return result;
}
| 9,457
|
C++
|
.cpp
| 207
| 40.222222
| 107
| 0.702209
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,143
|
serverhttp.cpp
|
agafon0ff_SimpleRemoteDesktop/src/serverhttp.cpp
|
#include "serverhttp.h"
#include <QSettings>
#include <QDebug>
#include <QRegularExpression>
#include <QDir>
#include <QFile>
#include <QDateTime>
#include <QDirIterator>
ServerHttp::ServerHttp(QObject *parent) : QObject(parent),
m_tcpServer(Q_NULLPTR),
m_port(8080),
m_path(":/res/")
{
}
bool ServerHttp::start()
{
bool result = false;
if(!m_tcpServer)
{
m_tcpServer = new QTcpServer(this);
connect(m_tcpServer,SIGNAL(newConnection()),this,SLOT(newSocketConnected()));
if(!m_tcpServer->listen(QHostAddress::Any, m_port))
qDebug()<<"ERROR: HTTP-Server is not started on port:"<<m_port;
else
{
result = true;
qDebug()<<"OK: HTTP-Server is started on port:"<<m_port;
updateFilesList();
}
}
return result;
}
void ServerHttp::stop()
{
foreach(QTcpSocket* socket, m_tcpSockets)
{
socket->disconnectFromHost();
socket->deleteLater();
}
if(m_tcpServer)
{
if(m_tcpServer->isListening())
m_tcpServer->close();
m_tcpServer->deleteLater();
m_tcpServer = Q_NULLPTR;
}
emit finished();
}
void ServerHttp::setPort(quint16 port)
{
m_port = port;
}
void ServerHttp::setPath(const QString &path)
{
if(path.size() < 2)
return;
m_path = path;
if(m_path.at(m_path.size() - 1) != '/')
m_path.append("/");
}
void ServerHttp::sendResponse(QTcpSocket *socket, const QByteArray &data)
{
if(!socket)
return;
socket->write(data);
socket->waitForBytesWritten(1000);
socket->disconnectFromHost();
}
void ServerHttp::requestHandler(QTcpSocket *socket, const QString &method, const QString &path, const QMap<QString,QString> &cookies, const QByteArray &requestData)
{
Q_UNUSED(cookies);
Q_UNUSED(method);
Q_UNUSED(requestData);
QByteArray data = getData(path);
QByteArray response = createHeader(path,data.size(),QStringList());
response.append(data);
sendResponse(socket, response);
}
QByteArray ServerHttp::getData(const QString &name)
{
QByteArray result;
QString fileName;
if(name.size() < 3)
fileName = m_path+"index.html";
else
{
fileName = name;
if(fileName.at(0) == '/')
fileName.remove(0,1);
fileName.prepend(m_path);
}
if(!m_filesList.contains(fileName))
return result;
QFile file(fileName);
if(file.open(QIODevice::ReadOnly))
{
result = file.readAll();
file.close();
}
else
{
qDebug()<<"ERROR: File is not open: "+fileName+"!";
}
return result;
}
QByteArray ServerHttp::createHeader(const QString &path, int dataSize, const QStringList &cookies)
{
QByteArray code = "200 OK\r\n";
if(dataSize == 0)
code = "404 Not Found\r\n";
QByteArray type("Content-Type: ");
if(path.contains(".ico"))
type += "image/ico";
else if(path.contains(".css"))
type += "text/css";
else if(path.contains(".html"))
type += "text/html";
else if(path.contains(".js"))
type += "text/javascript";
else if(path.contains(".png"))
type += "image/png";
else if(path.contains(".svg"))
type += "image/svg+xml";
type += "; charset=utf-8\r\n";
QByteArray length = "Content-Length: ";
length.append(QByteArray::number(dataSize));
length.append("\r\n");
QByteArray date = "Date: ";
QDateTime dt = QDateTime::currentDateTime();
QLocale locale {QLocale(QLocale::English)};
date.append(locale.toString(dt, "ddd, dd MMM yyyy hh:mm:ss").toUtf8());
date.append(" GMT\r\n");
QByteArray cookie;
foreach(const QString &oneCookie, cookies)
cookie.append("Set-Cookie: " + oneCookie.toUtf8() + "\r\n");
QByteArray result;
result.append("HTTP/1.1 ");
result.append(code);
result.append(type);
result.append(length);
result.append("Vary: Accept-Encoding\r\n");
result.append("Connection: keep-alive\r\n");
result.append(cookie);
result.append(date);
result.append("\r\n");
return result;
}
void ServerHttp::newSocketConnected()
{
QTcpSocket* socket = m_tcpServer->nextPendingConnection();
QString address = QHostAddress(socket->peerAddress().toIPv4Address()).toString();
Q_UNUSED(address);
connect(socket,SIGNAL(disconnected()),this,SLOT(socketDisconneted()));
connect(socket,SIGNAL(readyRead()),this,SLOT(readDataFromSocket()));
m_tcpSockets.append(socket);
}
void ServerHttp::socketDisconneted()
{
QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
QString address = QHostAddress(socket->peerAddress().toIPv4Address()).toString();
Q_UNUSED(address);
m_tcpSockets.removeOne(socket);
socket->deleteLater();
}
void ServerHttp::readDataFromSocket()
{
QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
QByteArray buf = socket->readAll();
QStringList list = QString(buf).split("\r\n");
QString method;
QString path;
QByteArray requestData;
QMap<QString,QString> cookies;
QRegularExpression re;
if(list.last().size() > 0)
requestData.append(list.last().toUtf8());
foreach (QString line, list)
{
if(line.contains("HTTP"))
{
re = QRegularExpression("(\\S*)\\s*(\\S*)\\s*HTTP");
QRegularExpressionMatchIterator it = re.globalMatch(line);
while(it.hasNext())
{
QRegularExpressionMatch match = it.next();
method = match.captured(1);
path = match.captured(2);
}
}
else if(line.contains("Cookie:"))
{
re = QRegularExpression("\\s(.*?)=(.*?)($|;|:)");
QRegularExpressionMatchIterator it = re.globalMatch(line);
while(it.hasNext())
{
QRegularExpressionMatch match = it.next();
cookies.insert(match.captured(1),match.captured(2));
}
}
}
if(receivers(SIGNAL(request(QTcpSocket*,QString,QString,QMap<QString,QString>,QByteArray))) != 0)
emit request(socket,method,path,cookies,requestData);
else requestHandler(socket,method,path,cookies,requestData);
}
void ServerHttp::updateFilesList()
{
m_filesList.clear();
QDir dir(m_path);
if(!dir.exists())
{
qDebug()<<"ERROR: Dir is not exists:"<<m_path;
return;
}
qDebug()<<"OK: Dir with files:"<<m_path;
QDirIterator dirIterator(m_path, QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
QStringList fileList;
fileList = QDir(m_path).entryList(QDir::Files);
for(int i=0;i<fileList.count();++i)
m_filesList.append(m_path + fileList.at(i));
while(dirIterator.hasNext())
{
dirIterator.next();
QString filePath = dirIterator.filePath();
fileList = QDir(filePath).entryList(QDir::Files);
for(int i=0;i<fileList.count();++i)
m_filesList.append(filePath + "/" + fileList.at(i));
m_filesList.prepend(filePath);
if(m_filesList.size() > 3000)
return;
}
}
| 7,217
|
C++
|
.cpp
| 231
| 25.099567
| 164
| 0.629945
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,144
|
inputsimulator.cpp
|
agafon0ff_SimpleRemoteDesktop/src/inputsimulator.cpp
|
#include "inputsimulator.h"
#include <QDebug>
#include <QCursor>
#ifdef Q_OS_WIN
#include "windows.h"
#endif
#ifdef Q_OS_UNIX
//sudo apt install libxtst-dev
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>
#endif
InputSimulator::InputSimulator(QObject *parent) : QObject(parent),
m_screenPosition(QPoint(0,0))
{
#ifdef Q_OS_UNIX
createKeysMap();
#endif
}
void InputSimulator::simulateKeyboard(quint16 keyCode, bool state)
{
#ifdef Q_OS_UNIX
if(!m_keysMap.contains(keyCode))
{
qDebug()<<"InputSimulator::simulateKeyboard"<<keyCode<<state;
return;
}
Display *display;
display = XOpenDisplay(Q_NULLPTR);
unsigned int keycode = XKeysymToKeycode(display, m_keysMap.value(keyCode));
if(state)
XTestFakeKeyEvent(display, keycode, True, 0);
else XTestFakeKeyEvent(display, keycode, False, 0);
XFlush(display);
XCloseDisplay(display);
#endif
#ifdef Q_OS_WIN
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
ip.ki.wVk = static_cast<unsigned short>(keyCode);
if(state)
ip.ki.dwFlags = 0;
else ip.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &ip, sizeof(INPUT));
#endif
}
void InputSimulator::simulateMouseKeys(quint16 keyCode, bool state)
{
#ifdef Q_OS_UNIX
Display *display;
display = XOpenDisplay(Q_NULLPTR);
if(keyCode == 0)//left
XTestFakeButtonEvent(display,Button1,state,0);
else if(keyCode == 1)//middle
XTestFakeButtonEvent(display,Button2,state,0);
else if(keyCode == 2)//right
XTestFakeButtonEvent(display,Button3,state,0);
XFlush(display);
XCloseDisplay(display);
#endif
#ifdef Q_OS_WIN
INPUT ip;
ZeroMemory(&ip,sizeof(ip));
ip.type = INPUT_MOUSE;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
if(keyCode == 0)//left
{
if(state)ip.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
else ip.mi.dwFlags = MOUSEEVENTF_LEFTUP;
}
else if(keyCode == 1)//middle
{
if(state)ip.mi.dwFlags = MOUSEEVENTF_MIDDLEDOWN;
else ip.mi.dwFlags = MOUSEEVENTF_MIDDLEUP;
}
else if(keyCode == 2)//right
{
if(state)ip.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
else ip.mi.dwFlags = MOUSEEVENTF_RIGHTUP;
}
SendInput(1, &ip, sizeof(INPUT));
#endif
}
void InputSimulator::simulateMouseMove(quint16 posX, quint16 posY)
{
QCursor::setPos(m_screenPosition.x()+posX,m_screenPosition.y()+posY);
}
void InputSimulator::simulateWheelEvent(bool deltaPos)
{
#ifdef Q_OS_UNIX
Display *display;
display = XOpenDisplay(Q_NULLPTR);
quint32 btnNum = Button4;
if(deltaPos)btnNum = Button5;
XTestFakeButtonEvent(display,btnNum,true,0);
XTestFakeButtonEvent(display,btnNum,false,0);
XFlush(display);
XCloseDisplay(display);
#endif
#ifdef Q_OS_WIN
INPUT ip;
ZeroMemory(&ip,sizeof(ip));
ip.type = INPUT_MOUSE;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
ip.mi.dwFlags = MOUSEEVENTF_WHEEL;
if(deltaPos)ip.mi.mouseData = static_cast<DWORD>(-120);
else ip.mi.mouseData = 120;
SendInput(1, &ip, sizeof(INPUT));
#endif
}
void InputSimulator::setMouseDelta(qint16 deltaX, qint16 deltaY)
{
QPoint cursorPos = QCursor::pos();
quint16 posX = static_cast<quint16>(cursorPos.x() - deltaX);
quint16 posY = static_cast<quint16>(cursorPos.y() - deltaY);
QCursor::setPos(posX,posY);
}
void InputSimulator::createKeysMap()
{
#ifdef Q_OS_UNIX
m_keysMap.insert(8,XK_BackSpace);
m_keysMap.insert(9,XK_Tab);
m_keysMap.insert(13,XK_Return);
m_keysMap.insert(16,XK_Shift_L);
m_keysMap.insert(17,XK_Control_L);
m_keysMap.insert(18,XK_Alt_L);
m_keysMap.insert(44,XK_Pause);
m_keysMap.insert(20,XK_Caps_Lock);
m_keysMap.insert(27,XK_Escape);
m_keysMap.insert(32,XK_space);
m_keysMap.insert(35,XK_End);
m_keysMap.insert(36,XK_Home);
m_keysMap.insert(37,XK_Left);
m_keysMap.insert(38,XK_Up);
m_keysMap.insert(39,XK_Right);
m_keysMap.insert(40,XK_Down);
m_keysMap.insert(44,XK_Print);
m_keysMap.insert(45,XK_Insert);
m_keysMap.insert(46,XK_Delete);
m_keysMap.insert(48,XK_0);
m_keysMap.insert(49,XK_1);
m_keysMap.insert(50,XK_2);
m_keysMap.insert(51,XK_3);
m_keysMap.insert(52,XK_4);
m_keysMap.insert(53,XK_5);
m_keysMap.insert(54,XK_6);
m_keysMap.insert(55,XK_7);
m_keysMap.insert(56,XK_8);
m_keysMap.insert(57,XK_9);
m_keysMap.insert(65,XK_A);
m_keysMap.insert(66,XK_B);
m_keysMap.insert(67,XK_C);
m_keysMap.insert(68,XK_D);
m_keysMap.insert(69,XK_E);
m_keysMap.insert(70,XK_F);
m_keysMap.insert(71,XK_G);
m_keysMap.insert(72,XK_H);
m_keysMap.insert(73,XK_I);
m_keysMap.insert(74,XK_J);
m_keysMap.insert(75,XK_K);
m_keysMap.insert(76,XK_L);
m_keysMap.insert(77,XK_M);
m_keysMap.insert(78,XK_N);
m_keysMap.insert(79,XK_O);
m_keysMap.insert(80,XK_P);
m_keysMap.insert(81,XK_Q);
m_keysMap.insert(82,XK_R);
m_keysMap.insert(83,XK_S);
m_keysMap.insert(84,XK_T);
m_keysMap.insert(85,XK_U);
m_keysMap.insert(86,XK_V);
m_keysMap.insert(87,XK_W);
m_keysMap.insert(88,XK_X);
m_keysMap.insert(89,XK_Y);
m_keysMap.insert(90,XK_Z);
m_keysMap.insert(91,XK_Super_L);
m_keysMap.insert(93,XK_Menu);
m_keysMap.insert(96,XK_KP_0);
m_keysMap.insert(97,XK_KP_1);
m_keysMap.insert(98,XK_KP_2);
m_keysMap.insert(99,XK_KP_3);
m_keysMap.insert(100,XK_KP_4);
m_keysMap.insert(101,XK_KP_5);
m_keysMap.insert(102,XK_KP_6);
m_keysMap.insert(103,XK_KP_7);
m_keysMap.insert(104,XK_KP_8);
m_keysMap.insert(105,XK_KP_9);
m_keysMap.insert(112,XK_F1);
m_keysMap.insert(113,XK_F2);
m_keysMap.insert(114,XK_F3);
m_keysMap.insert(115,XK_F4);
m_keysMap.insert(116,XK_F5);
m_keysMap.insert(117,XK_F6);
m_keysMap.insert(118,XK_F7);
m_keysMap.insert(119,XK_F8);
m_keysMap.insert(120,XK_F9);
m_keysMap.insert(121,XK_F10);
m_keysMap.insert(122,XK_F11);
m_keysMap.insert(123,XK_F12);
m_keysMap.insert(144,XK_Num_Lock);
m_keysMap.insert(145,XK_Scroll_Lock);
m_keysMap.insert(179,179);//Play/pause
m_keysMap.insert(173,173);//Mute
m_keysMap.insert(174,174);//Volume-
m_keysMap.insert(175,175);//Volume+
m_keysMap.insert(186,XK_semicolon);
m_keysMap.insert(187,XK_equal);
m_keysMap.insert(188,XK_comma);
m_keysMap.insert(189,XK_minus);
m_keysMap.insert(190,XK_greater);
m_keysMap.insert(191,XK_question);
m_keysMap.insert(192,XK_asciitilde);
m_keysMap.insert(219,XK_bracketleft);
m_keysMap.insert(220,XK_backslash);
m_keysMap.insert(221,XK_bracketright);
m_keysMap.insert(222,XK_apostrophe);
m_keysMap.insert(226,XK_bar);
#endif
}
| 7,156
|
C++
|
.cpp
| 226
| 25.911504
| 80
| 0.654925
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,145
|
websockethandler.cpp
|
agafon0ff_SimpleRemoteDesktop/src/websockethandler.cpp
|
#include "websockethandler.h"
#include <QCryptographicHash>
#include <QDebug>
#include <QUuid>
static const char* KEY_GET_IMAGE = "GIMG";
static const char* KEY_IMAGE_PARAM = "IMGP";
static const char* KEY_IMAGE_TILE = "IMGT";
static const char* KEY_SET_KEY_STATE = "SKST";
static const char* KEY_SET_CURSOR_POS = "SCUP";
static const char* KEY_SET_CURSOR_DELTA = "SCUD";
static const char* KEY_SET_MOUSE_KEY = "SMKS";
static const char* KEY_SET_MOUSE_WHEEL = "SMWH";
static const char* KEY_CHANGE_DISPLAY = "CHDP";
static const char* KEY_TILE_RECEIVED = "TLRD";
static const char* KEY_SET_NONCE = "STNC";
static const char* KEY_SET_AUTH_REQUEST = "SARQ";
static const char* KEY_SET_AUTH_RESPONSE = "SARP";
static const char* KEY_CHECK_AUTH_REQUEST = "CARQ";
static const char* KEY_CHECK_AUTH_RESPONSE = "CARP";
static const char* KEY_SET_NAME = "STNM";
static const char* KEY_CONNECT_UUID = "CTUU";
static const char* KEY_CONNECTED_PROXY_CLIENT = "CNPC";
static const char* KEY_DISCONNECTED_PROXY_CLIENT = "DNPC";
static const char* KEY_PING_REQUEST = "PINQ";
static const char* KEY_PING_RESPONSE = "PINS";
const int COMMAD_SIZE = 4;
const int REQUEST_MIN_SIZE = 6;
const int SIZE_UUID = 16;
const int INTERVAL_RECONNECT = 5000;
const int PNG_HEADER_SIZE = 16;
WebSocketHandler::WebSocketHandler(QObject *parent) : QObject(parent),
m_webSocket(Q_NULLPTR),
m_timerReconnect(Q_NULLPTR),
m_timerWaitResponse(Q_NULLPTR),
m_type(HandlerWebClient),
m_waitType(WaitTypeUnknown),
m_pingCounter(0),
m_isAuthenticated(false)
{
m_command.resize(COMMAD_SIZE);
}
void WebSocketHandler::createSocket()
{
if (m_webSocket)
return;
if (!QUrl(m_url).isValid())
return;
m_webSocket = new QWebSocket("",QWebSocketProtocol::VersionLatest,this);
connect(m_webSocket, &QWebSocket::stateChanged, this, &WebSocketHandler::socketStateChanged);
connect(m_webSocket, &QWebSocket::textMessageReceived,this, &WebSocketHandler::textMessageReceived);
connect(m_webSocket, &QWebSocket::binaryMessageReceived,this, &WebSocketHandler::binaryMessageReceived);
if (!m_timerReconnect)
{
m_timerReconnect = new QTimer(this);
connect(m_timerReconnect, &QTimer::timeout, this, &WebSocketHandler::timerReconnectTick);
}
m_webSocket->open(QUrl(m_url));
}
void WebSocketHandler::removeSocket()
{
if (m_timerReconnect)
{
if (m_timerReconnect->isActive())
m_timerReconnect->stop();
m_timerReconnect->deleteLater();
m_timerReconnect = Q_NULLPTR;
}
if (m_timerWaitResponse)
{
if (m_timerWaitResponse->isActive())
m_timerWaitResponse->stop();
m_timerWaitResponse->deleteLater();
m_timerWaitResponse = Q_NULLPTR;
}
if (m_webSocket)
{
if (m_webSocket->state() != QAbstractSocket::UnconnectedState)
m_webSocket->close();
m_webSocket->disconnect();
m_webSocket->deleteLater();
m_webSocket = Q_NULLPTR;
}
emit finished();
}
void WebSocketHandler::setUrl(const QString &url)
{
m_url = url;
qDebug() << "WebSocketHandler::setUrl" << url << QUrl(url).isValid();
}
void WebSocketHandler::setType(int type)
{
m_type = type;
}
void WebSocketHandler::setName(const QString &name)
{
m_name = name;
}
QString WebSocketHandler::getName()
{
return m_name;
}
QByteArray WebSocketHandler::getUuid()
{
return m_uuid;
}
void WebSocketHandler::setLoginPass(const QString &login, const QString &pass)
{
m_login = login;
m_pass = pass;
}
void WebSocketHandler::setProxyLoginPass(const QString &login, const QString &pass)
{
m_proxyLogin = login;
m_proxyPass = pass;
}
void WebSocketHandler::setSocket(QWebSocket *webSocket)
{
if (!webSocket)
return;
m_webSocket = webSocket;
connect(m_webSocket, &QWebSocket::textMessageReceived,this, &WebSocketHandler::textMessageReceived);
connect(m_webSocket, &QWebSocket::binaryMessageReceived,this, &WebSocketHandler::binaryMessageReceived);
connect(m_webSocket, &QWebSocket::disconnected,this, &WebSocketHandler::socketDisconnected);
m_uuid = QUuid::createUuid().toRfc4122();
m_nonce = QUuid::createUuid().toRfc4122();
qDebug()<<"WebSocketHandler::setSocket"<<m_type<<m_uuid.toBase64();
m_dataToSend.clear();
m_dataToSend.append(KEY_SET_NONCE);
appendUint16(m_dataToSend, static_cast<quint16>(m_nonce.size()));
m_dataToSend.append(m_nonce);
sendBinaryMessage(m_dataToSend);
}
QWebSocket *WebSocketHandler::getSocket()
{
return m_webSocket;
}
void WebSocketHandler::sendImageParameters(const QSize &imageSize, int rectWidth)
{
if (!m_isAuthenticated)
return;
m_dataToSend.clear();
m_dataToSend.append(KEY_IMAGE_PARAM);
appendUint16(m_dataToSend, 6);
appendUint16(m_dataToSend, static_cast<quint16>(imageSize.width()));
appendUint16(m_dataToSend, static_cast<quint16>(imageSize.height()));
appendUint16(m_dataToSend, static_cast<quint16>(rectWidth));
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::sendImageTile(quint16 posX, quint16 posY, const QByteArray &imageData, quint16 tileNum)
{
if (!m_isAuthenticated)
return;
quint16 imageSize = static_cast<quint16>(imageData.size()) - PNG_HEADER_SIZE;
m_dataToSend.clear();
m_dataToSend.append(KEY_IMAGE_TILE);
appendUint16(m_dataToSend, imageSize + 6);
appendUint16(m_dataToSend, posX);
appendUint16(m_dataToSend, posY);
appendUint16(m_dataToSend, tileNum);
m_dataToSend.append(imageData.data() + PNG_HEADER_SIZE, imageSize);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::sendName(const QByteArray &name)
{
if (!m_isAuthenticated)
return;
m_dataToSend.clear();
m_dataToSend.append(KEY_SET_NAME);
appendUint16(m_dataToSend, static_cast<quint16>(name.size()));
m_dataToSend.append(name);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::sendPingRequest()
{
m_dataToSend.clear();
m_dataToSend.append(KEY_PING_REQUEST);
appendUint16(m_dataToSend, 0);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::sendPingResponse()
{
m_dataToSend.clear();
m_dataToSend.append(KEY_PING_RESPONSE);
appendUint16(m_dataToSend, 0);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::checkRemoteAuthentication(const QByteArray &uuid, const QByteArray &nonce, const QByteArray &request)
{
if (!m_isAuthenticated)
return;
qDebug()<<"WebSocketHandler::checkRemoteAuthentication"<<m_type<<uuid.toBase64();
if (uuid.size() != SIZE_UUID ||
nonce.size() != SIZE_UUID ||
request.size() != SIZE_UUID)
return;
m_dataToSend.clear();
m_dataToSend.append(KEY_CHECK_AUTH_REQUEST);
appendUint16(m_dataToSend, static_cast<quint16>(SIZE_UUID * 3));
m_dataToSend.append(uuid);
m_dataToSend.append(nonce);
m_dataToSend.append(request);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::setRemoteAuthenticationResponse(const QByteArray &uuid, const QByteArray &name)
{
qDebug() << "WebSocketHandler::setRemoteAuthenticationResponse" << m_type << uuid.toBase64() << name;
stopWaitResponseTimer();
m_dataToSend.clear();
m_dataToSend.append(KEY_CHECK_AUTH_RESPONSE);
appendUint16(m_dataToSend, static_cast<quint16>(SIZE_UUID + name.size()));
m_dataToSend.append(uuid);
m_dataToSend.append(name);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::createProxyConnection(WebSocketHandler *handler, const QByteArray &uuid)
{
disconnect(handler->getSocket(), &QWebSocket::binaryMessageReceived,handler, &WebSocketHandler::binaryMessageReceived);
connect(m_webSocket, &QWebSocket::binaryMessageReceived, handler->getSocket(), &QWebSocket::sendBinaryMessage);
connect(handler->getSocket(), &QWebSocket::binaryMessageReceived, m_webSocket, &QWebSocket::sendBinaryMessage);
connect(handler, &WebSocketHandler::disconnectedUuid, this, &WebSocketHandler::proxyHandlerDisconnected);
connect(this, &WebSocketHandler::proxyConnectionCreated, handler, &WebSocketHandler::sendAuthenticationResponse);
emit proxyConnectionCreated(true);
m_dataToSend.clear();
m_dataToSend.append(KEY_CONNECTED_PROXY_CLIENT);
appendUint16(m_dataToSend, static_cast<quint16>(uuid.size()));
m_dataToSend.append(uuid);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::proxyHandlerDisconnected(const QByteArray &uuid)
{
m_dataToSend.clear();
m_dataToSend.append(KEY_DISCONNECTED_PROXY_CLIENT);
appendUint16(m_dataToSend, static_cast<quint16>(uuid.size()));
m_dataToSend.append(uuid);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::newData(const QByteArray &command, const QByteArray &data)
{
// qDebug() << "DataParser::newData" << command << data;
if (!m_isAuthenticated)
{
if (command == KEY_SET_AUTH_REQUEST)
{
if (m_type == HandlerWebClient || m_type == HandlerDesktop)
{
m_isAuthenticated = data.toBase64() == getHashSum(m_nonce, m_login, m_pass);
sendAuthenticationResponse(m_isAuthenticated);
qDebug() << "Authentication attempt: " << m_isAuthenticated;
}
else if (m_type == HandlerProxyClient)
{
emit remoteAuthenticationRequest(m_uuid, m_nonce, data);
startWaitResponseTimer(5000, WaitTypeRemoteAuth);
}
return;
}
else if (command == KEY_SET_NONCE)
{
if (m_type == HandlerSingleClient)
{
m_nonce = data;
sendAuthenticationRequestToProxy();
}
return;
}
else if (command == KEY_SET_AUTH_RESPONSE)
{
bool authState = uint16FromArray(data.data());
if (m_type == HandlerSingleClient && authState)
{
m_isAuthenticated = true;
sendName(m_name.toUtf8());
}
else
{
m_isAuthenticated = false;
}
emit authenticatedStatus(m_isAuthenticated);
return;
}
else if (command == KEY_CONNECT_UUID)
{
emit newProxyConnection(this, m_uuid, data);
}
else
{
qDebug() << "WebSocketHandler::newData" << command << data;
debugHexData(data);
}
return;
}
if (command == KEY_IMAGE_TILE)
{
return;
}
else if (command == KEY_GET_IMAGE)
{
sendName(m_name.toUtf8());
emit getDesktop();
}
else if (command == KEY_TILE_RECEIVED)
{
quint16 tileNum = uint16FromArray(data.data());
emit receivedTileNum(tileNum);
}
else if (command == KEY_PING_REQUEST)
{
sendPingResponse();
}
else if (command == KEY_PING_RESPONSE)
{
m_pingCounter = 0;
}
else if (command == KEY_CHANGE_DISPLAY)
{
emit changeDisplayNum();
}
else if (command == KEY_SET_CURSOR_POS)
{
if (data.size() >= 4)
{
quint16 posX = uint16FromArray(data.data());
quint16 posY = uint16FromArray(data.data() + 2);
emit setMouseMove(posX, posY);
}
}
else if (command == KEY_SET_CURSOR_DELTA)
{
if (data.size() >= 4)
{
qint16 deltaX = static_cast<qint16>(uint16FromArray(data.data()));
qint16 deltaY = static_cast<qint16>(uint16FromArray(data.data() + 2));
emit setMouseDelta(deltaX, deltaY);
}
}
else if (command == KEY_SET_KEY_STATE)
{
if (data.size() >= 4)
{
quint16 keyCode = uint16FromArray(data.data());
quint16 keyState = uint16FromArray(data.data() + 2);
emit setKeyPressed(keyCode,static_cast<bool>(keyState));
}
}
else if (command == KEY_SET_MOUSE_KEY)
{
if (data.size() >= 4)
{
quint16 keyCode = uint16FromArray(data.data());
quint16 keyState = uint16FromArray(data.data() + 2);
emit setMousePressed(keyCode,static_cast<bool>(keyState));
}
}
else if (command == KEY_SET_MOUSE_WHEEL)
{
if (data.size() >= 4)
{
quint16 keyState = uint16FromArray(data.data() + 2);
emit setWheelChanged(static_cast<bool>(keyState));
}
}
else if (command == KEY_SET_NAME)
{
m_name = QString::fromUtf8(data);
qDebug() << this << "New desktop connected:" << m_name;
}
else if (command == KEY_CHECK_AUTH_REQUEST)
{
if (data.size() == SIZE_UUID * 3)
{
const QByteArray &uuid = data.mid(0, SIZE_UUID);
const QByteArray &nonce = data.mid(SIZE_UUID, SIZE_UUID);
const QByteArray &requset = data.mid(SIZE_UUID * 2, SIZE_UUID);
sendRemoteAuthenticationResponse(uuid, nonce, requset);
}
}
else if (command == KEY_CHECK_AUTH_RESPONSE)
{
if (data.size() == SIZE_UUID + 2)
{
const QByteArray &uuid = data.mid(0, SIZE_UUID);
quint16 authResponse = uint16FromArray(data.data() + SIZE_UUID);
emit remoteAuthenticationResponse(uuid, m_uuid, m_name.toUtf8(), static_cast<bool>(authResponse));
}
}
else if (command == KEY_CONNECTED_PROXY_CLIENT)
{
emit connectedProxyClient(data);
}
else if (command == KEY_DISCONNECTED_PROXY_CLIENT)
{
emit disconnectedProxyClient(data);
}
else
{
qDebug()<<"WebSocketHandler::newData"<<command<<data;
debugHexData(data);
}
}
void WebSocketHandler::sendAuthenticationRequestToProxy()
{
QByteArray hashSum = QByteArray::fromBase64(getHashSum(m_nonce, m_proxyLogin, m_proxyPass));
m_dataToSend.clear();
m_dataToSend.append(KEY_SET_AUTH_REQUEST);
appendUint16(m_dataToSend, static_cast<quint16>(hashSum.size()));
m_dataToSend.append(hashSum);
sendBinaryMessage(m_dataToSend);
}
void WebSocketHandler::sendAuthenticationResponse(bool state)
{
m_dataToSend.clear();
m_dataToSend.append(KEY_SET_AUTH_RESPONSE);
appendUint16(m_dataToSend, 2);
appendUint16(m_dataToSend, static_cast<quint16>(state));
sendBinaryMessage(m_dataToSend);
WebSocketHandler *handler = static_cast<WebSocketHandler*>(sender());
disconnect(handler, &WebSocketHandler::proxyConnectionCreated, this, &WebSocketHandler::sendAuthenticationResponse);
}
void WebSocketHandler::sendRemoteAuthenticationResponse(const QByteArray &uuid, const QByteArray &nonce, const QByteArray &request)
{
bool result = request.toBase64() == getHashSum(nonce, m_login, m_pass);
qDebug() << "WebSocketHandler::sendRemoteAuthenticationResponse" << m_type << uuid.toBase64();
if (!result)
return;
if (uuid.size() != SIZE_UUID ||
nonce.size() != SIZE_UUID ||
request.size() != SIZE_UUID)
return;
m_dataToSend.clear();
m_dataToSend.append(KEY_CHECK_AUTH_RESPONSE);
appendUint16(m_dataToSend, static_cast<quint16>(SIZE_UUID + 2));
m_dataToSend.append(uuid);
appendUint16(m_dataToSend, static_cast<quint16>(result));
sendBinaryMessage(m_dataToSend);
}
QByteArray WebSocketHandler::getHashSum(const QByteArray &nonce, const QString &login, const QString &pass)
{
QString sum = login + pass;
QByteArray concatFirst = QCryptographicHash::hash(sum.toUtf8(),QCryptographicHash::Md5).toBase64();
concatFirst.append(nonce.toBase64());
QByteArray result = QCryptographicHash::hash(concatFirst,QCryptographicHash::Md5).toBase64();
return result;
}
void WebSocketHandler::socketStateChanged(QAbstractSocket::SocketState state)
{
switch(state)
{
case QAbstractSocket::ConnectedState:
{
qDebug()<<"WebSocketHandler::socketStateChanged: Connected to server.";
emit connectedStatus(true);
break;
}
case QAbstractSocket::ClosingState:
{
qDebug()<<"WebSocketHandler::socketStateChanged: Disconnected from server.";
emit connectedStatus(false);
emit authenticatedStatus(false);
m_isAuthenticated = false;
break;
}
default: break;
}
if (m_timerReconnect)
if (!m_timerReconnect->isActive())
m_timerReconnect->start(INTERVAL_RECONNECT);
}
void WebSocketHandler::socketDisconnected()
{
emit disconnectedUuid(m_uuid);
emit disconnected(this);
}
void WebSocketHandler::sendBinaryMessage(const QByteArray &data)
{
if (m_webSocket)
if (m_webSocket->state() == QAbstractSocket::ConnectedState)
m_webSocket->sendBinaryMessage(data);
}
void WebSocketHandler::textMessageReceived(const QString &message)
{
qDebug() << "WebSocketHandler::textMessageReceived:" << message;
}
void WebSocketHandler::binaryMessageReceived(const QByteArray &data)
{
m_dataReceived = m_dataTmp;
m_dataReceived.append(data);
m_dataTmp.clear();
m_payload.clear();
int size = m_dataReceived.size();
if (size == COMMAD_SIZE)
{
newData(data, m_payload);
return;
}
if (size < REQUEST_MIN_SIZE)
return;
int dataStep = 0;
for(int i=0;i<size;++i)
{
m_command.setRawData(m_dataReceived.data(), COMMAD_SIZE);
quint16 dataSize = uint16FromArray(m_dataReceived.data() + COMMAD_SIZE);
if (size >= (dataStep + COMMAD_SIZE + dataSize))
{
m_payload.resize(dataSize);
m_payload.setRawData(m_dataReceived.data() + dataStep + COMMAD_SIZE + 2, dataSize);
dataStep += COMMAD_SIZE + 2 + dataSize;
newData(m_command, m_payload);
i = dataStep;
}
else
{
debugHexData(m_dataReceived);
if (size - dataStep < 2000) {
m_dataTmp.resize(size - dataStep);
m_dataTmp.setRawData(m_dataReceived.data() + dataStep, m_dataTmp.size());
}
break;
}
}
}
void WebSocketHandler::timerReconnectTick()
{
if (m_webSocket->state() == QAbstractSocket::ConnectedState)
{
if (m_type == HandlerSingleClient && m_isAuthenticated)
{
if (m_pingCounter > 2)
{
qDebug() << "WebSocketHandler connection error, reconnecting.";
m_webSocket->close();
m_pingCounter = 0;
}
else
{
++m_pingCounter;
sendPingRequest();
}
}
}
else
{
if (m_webSocket->state() == QAbstractSocket::ConnectingState)
m_webSocket->abort();
m_webSocket->open(QUrl(m_url));
}
}
void WebSocketHandler::startWaitResponseTimer(int msec, int type)
{
if (!m_timerWaitResponse)
{
m_timerWaitResponse = new QTimer(this);
connect(m_timerWaitResponse, &QTimer::timeout, this, &WebSocketHandler::timerWaitResponseTick);
}
m_timerWaitResponse->start(msec);
m_waitType = type;
}
void WebSocketHandler::stopWaitResponseTimer()
{
if (m_timerWaitResponse)
if (m_timerWaitResponse->isActive())
m_timerWaitResponse->stop();
m_waitType = WaitTypeUnknown;
}
void WebSocketHandler::timerWaitResponseTick()
{
m_timerWaitResponse->stop();
if (m_waitType == WaitTypeRemoteAuth)
sendAuthenticationResponse(false);
m_waitType = WaitTypeUnknown;
}
void WebSocketHandler::debugHexData(const QByteArray &data)
{
QString textHex;
int dataSize = data.size();
for(int i=0;i<dataSize;++i)
{
quint8 oneByte = static_cast<quint8>(data.at(i));
textHex.append(QString::number(oneByte,16));
if (i < dataSize-1)
textHex.append("|");
}
qDebug() << "WebSocketHandler::debugHexData:"<< textHex << data;
}
void WebSocketHandler::appendUint16(QByteArray &data, quint16 number)
{
int size = data.size();
data.resize(size + 2);
data[size] = static_cast<char>(number);
data[size + 1] = static_cast<char>(number >> 8);
}
quint16 WebSocketHandler::uint16FromArray(const char* buf)
{
quint16 m_number;
m_number = static_cast<quint16>(static_cast<quint8>(buf[0]) |
static_cast<quint8>(buf[1]) << 8);
return m_number;
}
| 20,562
|
C++
|
.cpp
| 597
| 28.154104
| 131
| 0.661229
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,146
|
websockettransfer.cpp
|
agafon0ff_SimpleRemoteDesktop/src/websockettransfer.cpp
|
#include "websockettransfer.h"
WebSocketTransfer::WebSocketTransfer(QObject *parent) : QObject(parent),
m_webSocketServer(Q_NULLPTR),
m_type(TransferWebClients),
m_port(8081)
{
}
void WebSocketTransfer::start()
{
if(m_webSocketServer)
return;
m_webSocketServer = new QWebSocketServer("Web Socket Server",QWebSocketServer::NonSecureMode,this);
if(m_webSocketServer->listen(QHostAddress::Any, m_port))
{
qDebug()<<"OK: Web-Server is started on port: "<<m_port;
connect(m_webSocketServer,&QWebSocketServer::newConnection,this,&WebSocketTransfer::setSocketConnected);
}
else qDebug()<<"ERROR: Web-Server is not started on port:"<<m_port;
}
void WebSocketTransfer::stop()
{
if(m_webSocketServer)
{
if(m_webSocketServer->isListening())
m_webSocketServer->close();
}
emit finished();
}
void WebSocketTransfer::setPort(quint16 port)
{
m_port = port;
}
void WebSocketTransfer::setLoginPass(const QString &login, const QString &pass)
{
m_login = login;
m_pass = pass;
}
void WebSocketTransfer::setName(const QString &name)
{
m_name = name;
}
void WebSocketTransfer::setType(int type)
{
m_type = type;
}
void WebSocketTransfer::checkRemoteAuthentication(const QByteArray &uuid, const QByteArray &nonce, const QByteArray &request)
{
foreach(WebSocketHandler *socketHandler, m_sockets)
socketHandler->checkRemoteAuthentication(uuid,nonce,request);
}
void WebSocketTransfer::setRemoteAuthenticationResponse(const QByteArray &uuidDst, const QByteArray &uuidSrc, const QByteArray &nameSrc)
{
qDebug()<<"WebSocketTransfer::setRemoteAuthenticationResponse:" << uuidDst.toBase64() << uuidSrc.toBase64() << nameSrc;
foreach(WebSocketHandler *socketHandler, m_sockets)
{
if(socketHandler->getUuid() == uuidDst)
{
socketHandler->setRemoteAuthenticationResponse(uuidSrc, nameSrc);
break;
}
}
}
void WebSocketTransfer::createProxyConnection(WebSocketHandler *handler, const QByteArray &uuidSrc, const QByteArray &uuidDst)
{
foreach(WebSocketHandler *socketHandler, m_sockets)
{
if(socketHandler->getUuid() == uuidDst)
{
socketHandler->createProxyConnection(handler, uuidSrc);
break;
}
}
}
void WebSocketTransfer::setSocketConnected()
{
QWebSocket *webSocket = m_webSocketServer->nextPendingConnection();
WebSocketHandler *socketHandler = new WebSocketHandler(this);
connect(socketHandler, &WebSocketHandler::disconnected, this, &WebSocketTransfer::socketDisconnected);
if(m_type == TransferDesktops)
socketHandler->setType(WebSocketHandler::HandlerDesktop);
else if(m_type == TransferWebClients)
socketHandler->setType(WebSocketHandler::HandlerWebClient);
else if(m_type == TransferProxyClients)
socketHandler->setType(WebSocketHandler::HandlerProxyClient);
socketHandler->setLoginPass(m_login, m_pass);
socketHandler->setName(m_name);
socketHandler->setSocket(webSocket);
m_sockets.append(socketHandler);
emit newSocketConnected(socketHandler);
emit connectedSocketUuid(socketHandler->getUuid());
}
void WebSocketTransfer::socketDisconnected(WebSocketHandler *pointer)
{
if(m_sockets.contains(pointer))
m_sockets.removeOne(pointer);
if(pointer)
{
qDebug()<<"Disconnected one:"<<pointer->getName();
emit disconnectedSocketUuid(pointer->getUuid());
QWebSocket *socket = pointer->getSocket();
socket->deleteLater();
pointer->disconnect();
pointer->deleteLater();
}
}
| 3,661
|
C++
|
.cpp
| 105
| 29.866667
| 136
| 0.725651
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,147
|
proxyunitingclass.cpp
|
agafon0ff_SimpleRemoteDesktop/src/proxyunitingclass.cpp
|
#include "proxyunitingclass.h"
#include <QCoreApplication>
#include <QSettings>
#include <QThread>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ProxyUnitingClass u;
return a.exec();
}
ProxyUnitingClass::ProxyUnitingClass(QObject *parent) : QObject(parent),
m_serverHttp(new ServerHttp(this)),
m_clientsSocketTransfer(Q_NULLPTR),
m_desktopSocketTransfer(Q_NULLPTR)
{
qDebug()<<"SimpleRemoteDesktop v1.1";
qDebug()<<"Create(ProxyUnitingClass)";
loadSettings();
}
void ProxyUnitingClass::loadSettings()
{
QSettings settings("config.ini",QSettings::IniFormat);
settings.beginGroup("REMOTE_DESKTOP_PROXY");
int portHttp = settings.value("portHttp",0).toInt();
if(portHttp == 0)
{
portHttp = 8080;
settings.setValue("portHttp",portHttp);
}
QString filesPath = settings.value("filesPath").toString();
if(filesPath.isEmpty())
{
filesPath = ":/res/";
settings.setValue("filesPath",filesPath);
}
int portWebClient = settings.value("portWebClient",0).toInt();
if(portWebClient == 0)
{
portWebClient = 8081;
settings.setValue("portWebClient",portWebClient);
}
int portWebDesktop = settings.value("portWebDesktop",0).toInt();
if(portWebDesktop == 0)
{
portWebDesktop = 8082;
settings.setValue("portWebDesktop",portWebDesktop);
}
QString login = settings.value("login").toString();
if(login.isEmpty())
{
login = "sysadmin";
settings.setValue("login",login);
}
QString pass = settings.value("pass").toString();
if(pass.isEmpty())
{
pass = "12345678";
settings.setValue("pass",pass);
}
settings.endGroup();
settings.sync();
startHttpServer(static_cast<quint16>(portHttp),filesPath);
startClientsWebSocketTransfer(static_cast<quint16>(portWebClient),login,pass);
startDesktopWebSocketTransfer(static_cast<quint16>(portWebDesktop),login,pass);
}
void ProxyUnitingClass::startHttpServer(quint16 port, const QString &filesPath)
{
m_serverHttp->setPort(static_cast<quint16>(port));
m_serverHttp->setPath(filesPath);
m_serverHttp->start();
}
void ProxyUnitingClass::startClientsWebSocketTransfer(quint16 port, const QString &login, const QString &pass)
{
m_clientsSocketTransfer = new WebSocketTransfer;
m_clientsSocketTransfer->setType(WebSocketTransfer::TransferProxyClients);
m_clientsSocketTransfer->setPort(port);
m_clientsSocketTransfer->setLoginPass(login, pass);
connect(m_clientsSocketTransfer, &WebSocketTransfer::newSocketConnected,
this, &ProxyUnitingClass::createClientWebSocketConnection);
moveWebSocketTransferToThread(m_clientsSocketTransfer);
}
void ProxyUnitingClass::startDesktopWebSocketTransfer(quint16 port, const QString &login, const QString &pass)
{
m_desktopSocketTransfer = new WebSocketTransfer;
m_desktopSocketTransfer->setType(WebSocketTransfer::TransferDesktops);
m_desktopSocketTransfer->setPort(port);
m_desktopSocketTransfer->setLoginPass(login, pass);
connect(m_desktopSocketTransfer, &WebSocketTransfer::newSocketConnected,
this, &ProxyUnitingClass::createDesktopWebSocketConnection);
moveWebSocketTransferToThread(m_desktopSocketTransfer);
}
void ProxyUnitingClass::moveWebSocketTransferToThread(WebSocketTransfer *webSocketTransfer)
{
QThread *thread = new QThread;
connect(thread, &QThread::started, webSocketTransfer, &WebSocketTransfer::start);
connect(webSocketTransfer, &WebSocketTransfer::finished, thread, &QThread::quit);
connect(thread, &QThread::finished, webSocketTransfer, &WebSocketTransfer::deleteLater);
connect(thread, &QThread::finished, thread, &QThread::deleteLater);
webSocketTransfer->moveToThread(thread);
thread->start();
}
void ProxyUnitingClass::createClientWebSocketConnection(WebSocketHandler *webSocket)
{
if(!webSocket)
return;
connect(webSocket, &WebSocketHandler::remoteAuthenticationRequest,
m_desktopSocketTransfer, &WebSocketTransfer::checkRemoteAuthentication);
connect(webSocket, &WebSocketHandler::newProxyConnection,
m_desktopSocketTransfer, &WebSocketTransfer::createProxyConnection);
}
void ProxyUnitingClass::createDesktopWebSocketConnection(WebSocketHandler *webSocket)
{
if(!webSocket)
return;
connect(webSocket, &WebSocketHandler::remoteAuthenticationResponse,
m_clientsSocketTransfer, &WebSocketTransfer::setRemoteAuthenticationResponse);
}
| 4,608
|
C++
|
.cpp
| 118
| 34.101695
| 110
| 0.748432
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,148
|
graberclass.cpp
|
agafon0ff_SimpleRemoteDesktop/src/graberclass.cpp
|
#include "graberclass.h"
#include <QPixmap>
#include <QScreen>
#include <QApplication>
#include <QWindow>
#include <QDesktopWidget>
#include <QDebug>
#include <QBuffer>
GraberClass::GraberClass(QObject *parent) : QObject(parent),
m_grabTimer(Q_NULLPTR),
m_grabInterval(40),
m_rectSize(60),
m_screenNumber(0),
m_currentTileNum(0),
m_receivedTileNum(0),
m_permitCounter(0),
m_tileCurrentImage(m_rectSize, m_rectSize, QImage::Format_RGB444)
{
}
void GraberClass::start()
{
if(!m_grabTimer)
{
m_grabTimer = new QTimer(this);
connect(m_grabTimer,SIGNAL(timeout()),this,SLOT(updateImage()));
}
}
void GraberClass::stop()
{
stopSending();
emit finished();
}
void GraberClass::changeScreenNum()
{
QList<QScreen *> screens = QApplication::screens();
if(screens.size() > m_screenNumber + 1)
++m_screenNumber;
else m_screenNumber = 0;
QScreen* screen = screens.at(m_screenNumber);
emit screenPositionChanged(QPoint(screen->geometry().x(),screen->geometry().y()));
startSending();
}
void GraberClass::startSending()
{
qDebug()<<"GraberClass::startSending";
if(m_grabTimer)
if(!m_grabTimer->isActive())
m_grabTimer->start(m_grabInterval);
m_permitCounter = 0;
m_receivedTileNum = 0;
m_currentTileNum = 0;
m_lastImage = QImage();
updateImage();
}
void GraberClass::stopSending()
{
qDebug()<<"GraberClass::stopSending";
if(m_grabTimer)
if(m_grabTimer->isActive())
m_grabTimer->stop();
}
void GraberClass::updateImage()
{
if(!isSendTilePermit())
return;
QScreen *screen = QApplication::screens().at(m_screenNumber);
m_currentImage = screen->grabWindow(0).toImage().convertToFormat(QImage::Format_RGB444);
int columnCount = m_currentImage.width() / m_rectSize;
int rowCount = m_currentImage.height() / m_rectSize;
if(m_currentImage.width() % m_rectSize > 0)
++columnCount;
if(m_currentImage.height() % m_rectSize > 0)
++rowCount;
bool sendWithoutCompare = false;
if(m_lastImage.isNull())
{
m_lastImage = QImage(m_currentImage.size(), m_currentImage.format());
m_lastImage.fill(QColor(Qt::black));
emit imageParameters(m_currentImage.size(), m_rectSize);
sendWithoutCompare = true;
}
QRect tileRect;
quint16 tileNum = 0;
m_currentTileNum = 0;
for (int j=0; j<rowCount; ++j)
{
for (int i=0; i<columnCount; ++i)
{
tileRect.setRect(i * m_rectSize, j * m_rectSize, m_rectSize, m_rectSize);
if(sendWithoutCompare || !compareImagesRects(m_currentImage, m_lastImage, tileRect))
{
sendImage(i, j, tileNum, m_currentImage.copy(tileRect));
m_currentTileNum = tileNum;
++tileNum;
sendWithoutCompare = tileNum > columnCount;
}
}
}
m_lastImage = m_currentImage;
}
void GraberClass::setReceivedTileNum(quint16 num)
{
m_permitCounter = 0;
m_receivedTileNum = num;
}
void GraberClass::sendImage(int posX, int posY, int tileNum, const QImage &image)
{
QBuffer buffer(&m_dataToSend);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");
emit imageTile(static_cast<quint16>(posX), static_cast<quint16>(posY), m_dataToSend, static_cast<quint16>(tileNum));
}
bool GraberClass::isSendTilePermit()
{
if (m_receivedTileNum >= m_currentTileNum)
return true;
if (++m_permitCounter > 20)
{
m_permitCounter = 0;
return true;
}
return false;
}
bool GraberClass::compareImagesRects(const QImage &img1, const QImage &img2, const QRect &r)
{
if (img1.depth() != img2.depth())
return false;
if (img1.width() != img2.width())
return false;
int depth = img1.depth() / 8;
int bytesPerLine = img1.width() * depth;
int lineBegin = r.x() * depth;
int size = r.width() * depth;
for (int i=r.y(); i<(r.y() + r.height()); ++i) {
int shift = bytesPerLine * i + lineBegin;
if (memcmp(img1.constBits() + shift, img2.constBits() + shift, size) != 0) {
return false;
}
}
return true;
}
| 4,263
|
C++
|
.cpp
| 141
| 24.751773
| 120
| 0.643417
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,149
|
proxyunitingclass.h
|
agafon0ff_SimpleRemoteDesktop/src/proxyunitingclass.h
|
#ifndef PROXYUNITINGCLASS_H
#define PROXYUNITINGCLASS_H
#include <QObject>
#include "serverhttp.h"
#include "websockettransfer.h"
class ProxyUnitingClass : public QObject
{
Q_OBJECT
public:
explicit ProxyUnitingClass(QObject *parent = Q_NULLPTR);
private:
ServerHttp *m_serverHttp;
WebSocketTransfer *m_clientsSocketTransfer;
WebSocketTransfer *m_desktopSocketTransfer;
private slots:
void loadSettings();
void startHttpServer(quint16 port, const QString &filesPath);
void startClientsWebSocketTransfer(quint16 port, const QString &login, const QString &pass);
void startDesktopWebSocketTransfer(quint16 port, const QString &login, const QString &pass);
void moveWebSocketTransferToThread(WebSocketTransfer *webSocketTransfer);
void createClientWebSocketConnection(WebSocketHandler *webSocket);
void createDesktopWebSocketConnection(WebSocketHandler *webSocket);
};
#endif // PROXYUNITINGCLASS_H
| 950
|
C++
|
.h
| 24
| 36.333333
| 96
| 0.81413
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,150
|
websockettransfer.h
|
agafon0ff_SimpleRemoteDesktop/src/websockettransfer.h
|
#pragma once
#include <QObject>
#include <QDebug>
#include <QtWebSockets/qwebsocketserver.h>
#include <QtWebSockets/qwebsocket.h>
#include "websockethandler.h"
class WebSocketTransfer : public QObject
{
Q_OBJECT
public:
explicit WebSocketTransfer(QObject *parent = Q_NULLPTR);
enum TransferType
{
TransferDesktops,
TransferWebClients,
TransferProxyClients
};
private:
QWebSocketServer *m_webSocketServer;
int m_type;
quint16 m_port;
QString m_login;
QString m_pass;
QString m_name;
QList<WebSocketHandler*> m_sockets;
signals:
void finished();
void newSocketConnected(WebSocketHandler *webSocket);
void connectedSocketUuid(const QByteArray &uuid);
void disconnectedSocketUuid(const QByteArray &uuid);
public slots:
void start();
void stop();
void setPort(quint16 port);
void setLoginPass(const QString &login, const QString &pass);
void setName(const QString &name);
void setType(int type);
void checkRemoteAuthentication(const QByteArray &uuid, const QByteArray &nonce, const QByteArray &request);
void setRemoteAuthenticationResponse(const QByteArray &uuidDst, const QByteArray &uuidSrc, const QByteArray &nameSrc);
void createProxyConnection(WebSocketHandler *handler, const QByteArray &uuidSrc, const QByteArray &uuidDst);
private slots:
void setSocketConnected();
void socketDisconnected(WebSocketHandler *pointer);
};
| 1,464
|
C++
|
.h
| 44
| 29.090909
| 122
| 0.761331
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,151
|
inputsimulator.h
|
agafon0ff_SimpleRemoteDesktop/src/inputsimulator.h
|
#pragma once
#include <QObject>
#include <QMap>
#include <QPoint>
class InputSimulator : public QObject
{
Q_OBJECT
public:
explicit InputSimulator(QObject *parent = nullptr);
private:
QMap<quint16,quint16> m_keysMap;
QPoint m_screenPosition;
signals:
public slots:
void simulateKeyboard(quint16 keyCode, bool state);
void simulateMouseKeys(quint16 keyCode, bool state);
void simulateMouseMove(quint16 posX, quint16 posY);
void simulateWheelEvent(bool deltaPos);
void setMouseDelta(qint16 deltaX, qint16 deltaY);
void setScreenPosition(const QPoint &pos){m_screenPosition = pos;}
private slots:
void createKeysMap();
};
| 700
|
C++
|
.h
| 23
| 25.913043
| 71
| 0.745098
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,152
|
graberclass.h
|
agafon0ff_SimpleRemoteDesktop/src/graberclass.h
|
#pragma once
#include <QObject>
#include <QTimer>
#include <QImage>
#include <QList>
class GraberClass : public QObject
{
Q_OBJECT
public:
explicit GraberClass(QObject *parent = Q_NULLPTR);
private:
struct TileStruct
{
int x;
int y;
QImage image;
TileStruct(int posX, int posY, const QImage &image) :
x(posX), y(posY), image(image){}
TileStruct(){}
};
QTimer *m_grabTimer;
int m_grabInterval;
int m_rectSize;
int m_screenNumber;
int m_currentTileNum;
int m_receivedTileNum;
int m_permitCounter;
QImage m_currentImage;
QImage m_lastImage;
QImage m_tileCurrentImage;
QByteArray m_dataToSend;
signals:
void finished();
void imageParameters(const QSize &imageSize, int rectWidth);
void imageTile(quint16 posX, quint16 posY, const QByteArray &imageData, quint16 tileNum);
void screenPositionChanged(const QPoint &pos);
public slots:
void start();
void stop();
void setInterval(int msec){m_grabInterval = msec;}
void setRectSize(int size){m_rectSize = size;}
void changeScreenNum();
void startSending();
void stopSending();
void updateImage();
void setReceivedTileNum(quint16 num);
private slots:
void sendImage(int posX, int posY, int tileNum, const QImage& image);
bool isSendTilePermit();
bool compareImagesRects(const QImage &img1, const QImage &img2, const QRect &r);
};
| 1,457
|
C++
|
.h
| 51
| 23.901961
| 93
| 0.700358
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,153
|
infowidget.h
|
agafon0ff_SimpleRemoteDesktop/src/infowidget.h
|
#pragma once
#include <QMainWindow>
class InfoWidget : public QMainWindow
{
Q_OBJECT
public:
explicit InfoWidget(QWidget *parent = nullptr);
signals:
public:
void loadSettings();
int portHttp() const { return m_portHttp; }
int portWeb() const { return m_portWeb; }
QString login() const { return m_login; }
QString pass() const { return m_pass; }
QString name() const { return m_name; }
QString filesPath() const { return m_filesPath; }
QString proxyHost() const { return m_proxyHost; }
QString proxyLogin() const { return m_proxyLogin; }
QString proxyPass() const { return m_proxyPass; }
private slots:
void showAboutSRDMessage();
void showAboutQtMessage();
void createInfoWidget();
void createSettingsWidget();
QString getLocalAddress();
private:
int m_portHttp = 8080;
int m_portWeb = 8081;
QString m_login = "login";
QString m_pass = "pass";
QString m_name = "DESK1";
QString m_filesPath = ":/res/";
QString m_proxyHost = "ws://<your.proxy.address>:8082";
QString m_proxyLogin = "sysadmin";
QString m_proxyPass = "12345678";
QWidget *m_infoWidget = nullptr;
QWidget *m_settingsWidget = nullptr;
};
| 1,221
|
C++
|
.h
| 38
| 28
| 59
| 0.687925
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,154
|
serverhttp.h
|
agafon0ff_SimpleRemoteDesktop/src/serverhttp.h
|
#pragma once
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
class ServerHttp : public QObject
{
Q_OBJECT
public:
explicit ServerHttp(QObject *parent = Q_NULLPTR);
private:
QTcpServer *m_tcpServer;
QList<QTcpSocket*> m_tcpSockets;
quint16 m_port;
QString m_path;
QStringList m_filesList;
signals:
void finished();
void request(QTcpSocket *socket, const QString &method, const QString &path,
const QMap<QString,QString> &cookies, const QByteArray &requestData);
public slots:
bool start();
void stop();
void setPort(quint16 port);
void setPath(const QString &path);
void sendResponse(QTcpSocket* socket, const QByteArray &data);
void requestHandler(QTcpSocket* socket, const QString &method, const QString &path, const QMap<QString,QString> &cookies, const QByteArray &requestData);
QByteArray getData(const QString &name);
QByteArray createHeader(const QString &path, int dataSize, const QStringList &cookies);
private slots:
void newSocketConnected();
void socketDisconneted();
void readDataFromSocket();
void updateFilesList();
};
| 1,157
|
C++
|
.h
| 34
| 29.823529
| 157
| 0.73991
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,155
|
remotedesktopuniting.h
|
agafon0ff_SimpleRemoteDesktop/src/remotedesktopuniting.h
|
#pragma once
#include <QSystemTrayIcon>
#include <QObject>
#include <QMenu>
#include "serverhttp.h"
#include "infowidget.h"
#include "websockettransfer.h"
#include "graberclass.h"
#include "inputsimulator.h"
class RemoteDesktopUniting : public QObject
{
Q_OBJECT
public:
explicit RemoteDesktopUniting(QObject *parent = Q_NULLPTR);
private:
WebSocketTransfer *m_webSocketTransfer;
WebSocketHandler *m_webSocketHandler;
ServerHttp *m_serverHttp;
GraberClass *m_graberClass;
InputSimulator *m_inputSimulator;
QMenu *m_trayMenu;
InfoWidget *m_infoWidget;
QSystemTrayIcon *m_trayIcon;
QString m_title;
int m_currentPort;
bool m_isConnectedToProxy;
QList<QByteArray> m_remoteClientsList;
signals:
void closeSignal();
void stopGrabing();
public slots:
private slots:
void showInfoWidget();
void startHttpServer(quint16 port, const QString &filesPath);
void startGraberClass();
void startWebSocketTransfer(quint16 port, const QString &login, const QString &pass, const QString &name);
void startWebSocketHandler(const QString &host, const QString &name, const QString &login,
const QString &pass, const QString &proxyLogin, const QString &proxyPass);
void createConnectionToHandler(WebSocketHandler *webSocketHandler);
void finishedWebSockeTransfer();
void finishedWebSockeHandler();
void remoteClientConnected(const QByteArray &uuid);
void remoteClientDisconnected(const QByteArray &uuid);
void connectedToProxyServer(bool state);
};
| 1,577
|
C++
|
.h
| 45
| 30.711111
| 110
| 0.763314
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,156
|
websockethandler.h
|
agafon0ff_SimpleRemoteDesktop/src/websockethandler.h
|
#pragma once
#include <QObject>
#include <QDebug>
#include <QTimer>
#include <QtWebSockets/qwebsocket.h>
#include <QSize>
#include <QMap>
class WebSocketHandler : public QObject
{
Q_OBJECT
public:
explicit WebSocketHandler(QObject *parent = Q_NULLPTR);
enum HandlerType
{
HandlerWebClient,
HandlerProxyClient,
HandlerDesktop,
HandlerSingleClient
};
enum WaitResponseType
{
WaitTypeUnknown,
WaitTypeRemoteAuth
};
private:
QWebSocket *m_webSocket;
QTimer *m_timerReconnect;
QTimer *m_timerWaitResponse;
int m_type;
int m_waitType;
int m_pingCounter;
bool m_isAuthenticated;
QString m_url;
QString m_name;
QString m_login;
QString m_pass;
QString m_proxyLogin;
QString m_proxyPass;
QByteArray m_dataTmp;
QByteArray m_uuid;
QByteArray m_nonce;
QByteArray m_command;
QByteArray m_payload;
QByteArray m_dataToSend;
QByteArray m_dataReceived;
signals:
void finished();
void getDesktop();
void connectedStatus(bool);
void authenticatedStatus(bool);
void receivedTileNum(quint16 num);
void changeDisplayNum();
void setKeyPressed(quint16 keyCode, bool state);
void setMousePressed(quint16 keyCode, bool state);
void setWheelChanged(bool deltaPos);
void setMouseMove(quint16 posX, quint16 posY);
void setMouseDelta(qint16 deltaX, qint16 deltaY);
void disconnected(WebSocketHandler *pointer);
void disconnectedUuid(const QByteArray &uuid);
void remoteAuthenticationRequest(const QByteArray &uuid, const QByteArray &nonce, const QByteArray &request);
void remoteAuthenticationResponse(const QByteArray &uuidDst, const QByteArray &uuidSrc,
const QByteArray &name, bool state);
void newProxyConnection(WebSocketHandler *handler, const QByteArray &uuidSrc, const QByteArray &uuidDst);
void proxyConnectionCreated(bool state);
void connectedProxyClient(const QByteArray &uuid);
void disconnectedProxyClient(const QByteArray &uuid);
public slots:
void createSocket();
void removeSocket();
void setUrl(const QString &url);
void setType(int type);
void setName(const QString &name);
QString getName();
QByteArray getUuid();
void setLoginPass(const QString &login, const QString &pass);
void setProxyLoginPass(const QString &login, const QString &pass);
void setSocket(QWebSocket *webSocket);
QWebSocket *getSocket();
void sendImageParameters(const QSize &imageSize, int rectWidth);
void sendImageTile(quint16 posX, quint16 posY,
const QByteArray &imageData, quint16 tileNum);
void sendName(const QByteArray &name);
void sendPingRequest();
void sendPingResponse();
void checkRemoteAuthentication(const QByteArray &uuid, const QByteArray &nonce, const QByteArray &request);
void setRemoteAuthenticationResponse(const QByteArray &uuid, const QByteArray &name);
void createProxyConnection(WebSocketHandler *handler, const QByteArray &uuid);
void proxyHandlerDisconnected(const QByteArray &uuid);
private slots:
void newData(const QByteArray &command, const QByteArray &data);
void sendAuthenticationRequestToProxy();
void sendAuthenticationResponse(bool state);
void sendRemoteAuthenticationResponse(const QByteArray &uuid, const QByteArray &nonce, const QByteArray &request);
QByteArray getHashSum(const QByteArray &nonce, const QString &login, const QString &pass);
void socketStateChanged(QAbstractSocket::SocketState state);
void socketDisconnected();
void sendBinaryMessage(const QByteArray &data);
void textMessageReceived(const QString &message);
void binaryMessageReceived(const QByteArray &data);
void timerReconnectTick();
void startWaitResponseTimer(int msec, int type);
void stopWaitResponseTimer();
void timerWaitResponseTick();
void debugHexData(const QByteArray &data);
public:
static void appendUint16(QByteArray &data, quint16 number);
static quint16 uint16FromArray(const char *buf);
};
| 4,146
|
C++
|
.h
| 108
| 33.083333
| 118
| 0.748631
|
agafon0ff/SimpleRemoteDesktop
| 38
| 11
| 2
|
LGPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,157
|
nxcontroller_cfw.cpp
|
wwwwwwzx_NXController/nxcontroller_cfw.cpp
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#include "nxcontroller_cfw.h"
#include <QString>
#include <QTcpSocket>
#include <QHostAddress>
nxcontroller_cfw::nxcontroller_cfw() {}
bool nxcontroller_cfw::connect(QString IP, short port) {
ts.connectToHost(QHostAddress(IP), port, QIODevice::ReadWrite);
ts.waitForConnected(2000);
return ts.state() == QAbstractSocket::ConnectedState;
}
void nxcontroller_cfw::send(QString msg) {
ts.write((msg + "\r\n").toUtf8());
ts.waitForBytesWritten();
}
void nxcontroller_cfw::click(QString button) {
send("click " + button);
}
void nxcontroller_cfw::press(QString button) {
send("press " + button);
}
void nxcontroller_cfw::release(QString button) {
send("release " + button);
}
void nxcontroller_cfw::detachController() {
send("detachController");
}
void nxcontroller_cfw::configuresleep(int mainLoopSleepTime, int buttonClickSleepTime) {
send("configure mainLoopSleepTime " + QString::number(mainLoopSleepTime));
send("configure buttonClickSleepTime " + QString::number(buttonClickSleepTime));
}
QString nxcontroller_cfw::tohex(short n) {
return QString(n < 0 ? "-" : "") + "0x" + QString::number(abs(n), 16);
}
void nxcontroller_cfw::LStick(short x, short y) {
LS_X = x;
LS_Y = y;
send("setStick LEFT " + tohex(x) + " " + tohex(y));
}
void nxcontroller_cfw::RStick(short x, short y) {
RS_X = x;
RS_Y = y;
send("setStick RIGHT " + tohex(x) + " " + tohex(y));
}
QString nxcontroller_cfw::peek(uint offset, uint size) {
send("peek 0x" + QString::number(offset, 16) + " " + QString::number(size));
ts.waitForReadyRead(10000);
return "0x" + ts.readLine();
}
QString nxcontroller_cfw::peek(QString offset, QString size) {
send("peek 0x" + offset + " " + size);
ts.waitForReadyRead(10000);
return "0x" + ts.readLine();
}
void nxcontroller_cfw::poke(uint offset, QByteArray data) {
send("poke 0x" + QString::number(offset, 16) + " 0x" + data.toHex(0));
}
void nxcontroller_cfw::poke(QString offset, QString data) {
send("poke 0x" + offset + " " + data);
}
void nxcontroller_cfw::close() {
ts.close();
}
| 2,788
|
C++
|
.cpp
| 79
| 33.189873
| 88
| 0.719911
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,158
|
nxcontroller.cpp
|
wwwwwwzx_NXController/nxcontroller.cpp
|
/*
* This file is part of nxcontroller
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#include "nxcontroller.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QString>
#include <QThread>
nxcontroller::nxcontroller() {}
bool nxcontroller::connect(QString port) {
if (port == "")
return false;
ser.setPortName(port);
return ser.open(QIODevice::WriteOnly);
}
void nxcontroller::write(QString msg) {
ser.write((msg + "\r\n").toUtf8());
ser.waitForBytesWritten();
}
void nxcontroller::release() {
ser.write("RELEASE\r\n");
ser.waitForBytesWritten();
}
void nxcontroller::send(QString msg, int duration) {
write(msg);
if (duration > 0) {
QThread::msleep(duration);
release();
QThread::msleep(buttondelay);
}
}
void nxcontroller::close() {
release();
QThread::msleep(500);
ser.close();
}
void nxcontroller::A(int duration) {
send("Button A", duration);
}
void nxcontroller::B(int duration) {
send("Button B", duration);
}
void nxcontroller::X(int duration) {
send("Button X", duration);
}
void nxcontroller::Y(int duration) {
send("Button Y", duration);
}
void nxcontroller::L(int duration) {
send("Button L", duration);
}
void nxcontroller::R(int duration) {
send("Button R", duration);
}
void nxcontroller::ZL(int duration) {
send("Button ZL", duration);
}
void nxcontroller::ZR(int duration) {
send("Button ZR", duration);
}
void nxcontroller::Plus(int duration) {
send("Button PLUS", duration);
}
void nxcontroller::Minus(int duration) {
send("Button MINUS", duration);
}
void nxcontroller::Home(int duration) {
send("Button HOME", duration);
}
void nxcontroller::Capture(int duration) {
send("Button CAPTURE", duration);
}
// Dpad
void nxcontroller::Up(int duration) {
send("HAT TOP", duration);
}
void nxcontroller::Down(int duration) {
send("HAT BOTTOM", duration);
}
void nxcontroller::Left(int duration) {
send("HAT LEFT", duration);
}
void nxcontroller::Right(int duration) {
send("HAT RIGHT", duration);
}
void nxcontroller::Dpad_Center() {
send("HAT CENTER", -1);
}
// Left stick
void nxcontroller::LS_Left(int duration) {
send("LX MIN", duration);
}
void nxcontroller::LS_Right(int duration) {
send("LX MAX", duration);
}
void nxcontroller::LS_Up(int duration) {
send("LY MIN", duration);
}
void nxcontroller::LS_Down(int duration) {
send("LY MAX", duration);
}
void nxcontroller::LS_XCenter() {
send("LX CENTER", -1);
}
void nxcontroller::LS_YCenter() {
send("LY CENTER", -1);
}
void nxcontroller::PressLeftStick(int duration) {
send("Button LCLICK", duration);
}
// Right stick
void nxcontroller::RS_Left(int duration) {
send("RX MIN", duration);
}
void nxcontroller::RS_Right(int duration) {
send("RX MAX", duration);
}
void nxcontroller::RS_Up(int duration) {
send("RY MIN", duration);
}
void nxcontroller::RS_Down(int duration) {
send("RY MAX", duration);
}
void nxcontroller::RS_XCenter() {
send("RX CENTER", -1);
}
void nxcontroller::RS_YCenter() {
send("RY CENTER", -1);
}
void nxcontroller::PressRightStick(int duration) {
send("Button RCLICK", duration);
}
| 3,742
|
C++
|
.cpp
| 146
| 23.732877
| 72
| 0.72357
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,159
|
inputtable.cpp
|
wwwwwwzx_NXController/UI/inputtable.cpp
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#include "inputtable.h"
QDataStream& operator<<(QDataStream& out, const inputtable& v) {
out << v.A << v.B << v.X << v.Y << v.L << v.R << v.ZL << v.ZR << v.LS << v.RS << v.Home << v.Capture << v.Plus << v.Minus;
out << v.D_Up << v.D_Down << v.D_Left << v.D_Right;
out << v.LS_Up << v.LS_Down << v.LS_Left << v.LS_Right;
out << v.RS_Up << v.RS_Down << v.RS_Left << v.RS_Right;
return out;
}
QDataStream& operator>>(QDataStream& in, inputtable& v) {
in >> v.A >> v.B >> v.X >> v.Y >> v.L >> v.R >> v.ZL >> v.ZR >> v.LS >> v.RS >> v.Home >> v.Capture >> v.Plus >> v.Minus;
in >> v.D_Up >> v.D_Down >> v.D_Left >> v.D_Right;
in >> v.LS_Up >> v.LS_Down >> v.LS_Left >> v.LS_Right;
in >> v.RS_Up >> v.RS_Down >> v.RS_Left >> v.RS_Right;
return in;
}
| 1,494
|
C++
|
.cpp
| 32
| 44.46875
| 124
| 0.641535
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,161
|
mainwindow.cpp
|
wwwwwwzx_NXController/UI/mainwindow.cpp
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "buttonconfig.h"
#include <QSettings>
#include <QMessageBox>
#include <QSerialPortInfo>
#include <QKeyEvent>
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
qRegisterMetaTypeStreamOperators<inputtable>("inputtable");
QSettings setting;
on_B_Refresh_clicked();
ui->B_Disconnect->setEnabled(false);
setMinimumHeight(135);
setMaximumHeight(135);
ui->ipaddress->setText(setting.value("settings/ip", "192.168.0.1").toString());
ui->ramaddress->setText(setting.value("settings/ramaddress", "0").toString());
ui->datasize->setText(setting.value("settings/datasize", "8").toString());
loadbuttonconfig();
on_B_Connect_clicked();
if (ui->B_Connect->isEnabled())
ui->RB_Socket->setChecked(true);
if (ui->ipaddress->text() != "192.168.0.1")
on_B_Connect_clicked(); // Try to connect sys-botbase
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::on_B_Refresh_clicked() {
QSettings setting;
QString last_device = setting.value("settings/serialport", "").toString();
ui->devicelist->clear();
Q_FOREACH (QSerialPortInfo port, QSerialPortInfo::availablePorts())
if (port.hasProductIdentifier()) {
ui->devicelist->addItem((port.portName()));
if (port.portName() == last_device)
ui->devicelist->setCurrentIndex(ui->devicelist->count() - 1);
}
}
void MainWindow::on_B_Connect_clicked() {
QSettings setting;
if (ui->RB_Serial->isChecked()) {
if (!c.connect(ui->devicelist->currentText()))
return;
setting.setValue("settings/serialport", ui->devicelist->currentText());
} else {
QStringList buffer = ui->ipaddress->text().split(":");
short port = 6000;
if (buffer.length() > 1)
port = buffer[1].toShort();
if (!b.connect(buffer[0],port)) {
QMessageBox MB;
MB.critical(0, "Error", "Connection failed");
MB.setFixedSize(500, 180);
return;
}
b.configuresleep(0, 50); // Default setting
setMaximumHeight(210);
setMinimumHeight(210);
setting.setValue("settings/ip", ui->ipaddress->text());
}
ui->B_Connect->setEnabled(false);
ui->B_Disconnect->setEnabled(true);
ui->devicelist->setEnabled(false);
ui->ipaddress->setEnabled(false);
ui->RB_Serial->setEnabled(false);
ui->RB_Socket->setEnabled(false);
}
void MainWindow::on_B_Disconnect_clicked() {
if (ui->RB_Serial->isChecked())
c.close();
else {
b.detachController();
b.close();
}
setMinimumHeight(135);
setMaximumHeight(135);
resize(380, 135);
ui->B_Connect->setEnabled(true);
ui->B_Disconnect->setEnabled(false);
ui->devicelist->setEnabled(true);
ui->ipaddress->setEnabled(true);
ui->RB_Serial->setEnabled(true);
ui->RB_Socket->setEnabled(true);
}
void MainWindow::on_B_Read_clicked() {
if (ui->B_Connect->isEnabled() || ui->RB_Serial->isChecked())
return;
QSettings setting;
QString datastring = b.peek(ui->ramaddress->text(), ui->datasize->text());
ui->data->setText(datastring);
setting.setValue("settings/ramaddress", ui->ramaddress->text());
setting.setValue("settings/datasize", ui->datasize->text());
if (QGuiApplication::keyboardModifiers() == Qt::ShiftModifier) {
int size = (datastring.count() - 2) / 2;
QByteArray ay(size, 0);
for (int i = 0; i < size; i++)
ay[i] = datastring.mid(i * 2 + 2, 2).toInt(nullptr, 16);
QFile file("dump_heap_0x" + ui->ramaddress->text() + "_" + ui->datasize->text() + ".bin");
file.open(QIODevice::WriteOnly);
file.write(ay);
file.close();
}
}
void MainWindow::on_B_Write_clicked() {
if (ui->B_Connect->isEnabled() || ui->RB_Serial->isChecked())
return;
QSettings setting;
b.poke(ui->ramaddress->text(), ui->data->text());
setting.setValue("settings/ramaddress", ui->ramaddress->text());
}
void MainWindow::keyPressEvent(QKeyEvent* event) {
if (ui->B_Connect->isEnabled())
return;
if (event->isAutoRepeat())
return;
int key = event->key();
if (ui->RB_Serial->isChecked()) {
if (key == keytable.A)
c.A(-1);
else if (key == keytable.B)
c.B(-1);
else if (key == keytable.X)
c.X(-1);
else if (key == keytable.Y)
c.Y(-1);
else if (key == keytable.LS_Up)
c.LS_Up(-1);
else if (key == keytable.LS_Down)
c.LS_Down(-1);
else if (key == keytable.LS_Left)
c.LS_Left(-1);
else if (key == keytable.LS_Right)
c.LS_Right(-1);
else if (key == keytable.RS_Up)
c.RS_Up(-1);
else if (key == keytable.RS_Down)
c.RS_Down(-1);
else if (key == keytable.RS_Left)
c.RS_Left(-1);
else if (key == keytable.RS_Right)
c.RS_Right(-1);
else if (key == keytable.D_Up)
c.Up(-1);
else if (key == keytable.D_Down)
c.Down(-1);
else if (key == keytable.D_Left)
c.Left(-1);
else if (key == keytable.D_Right)
c.Right(-1);
else if (key == keytable.Home)
c.Home();
else if (key == keytable.Capture)
c.Capture(-1);
else if (key == keytable.Plus)
c.Plus(-1);
else if (key == keytable.Minus)
c.Minus(-1);
else if (key == keytable.L)
c.L(-1);
else if (key == keytable.R)
c.R(-1);
else if (key == keytable.ZL)
c.ZL(-1);
else if (key == keytable.ZR)
c.ZR(-1);
else if (key == keytable.LS)
c.PressLeftStick(-1);
else if (key == keytable.RS)
c.PressRightStick(-1);
} else {
if (key == keytable.A)
b.press("A");
else if (key == keytable.B)
b.press("B");
else if (key == keytable.X)
b.press("X");
else if (key == keytable.Y)
b.press("Y");
else if (key == keytable.D_Up)
b.press("DUP");
else if (key == keytable.D_Down)
b.press("DDOWN");
else if (key == keytable.D_Left)
b.press("DLEFT");
else if (key == keytable.D_Right)
b.press("DRIGHT");
else if (key == keytable.Home)
b.press("HOME");
else if (key == keytable.Capture)
b.press("CAPTURE");
else if (key == keytable.Plus)
b.press("PLUS");
else if (key == keytable.Minus)
b.press("MINUS");
else if (key == keytable.L)
b.press("L");
else if (key == keytable.R)
b.press("R");
else if (key == keytable.ZL)
b.press("ZL");
else if (key == keytable.ZR)
b.press("ZR");
else if (key == keytable.LS)
b.press("LSTICK");
else if (key == keytable.RS)
b.press("RSTICK");
else if (key == keytable.LS_Up)
b.LStick(b.LS_X, 0x7FFF);
else if (key == keytable.LS_Down)
b.LStick(b.LS_X, -0x8000);
else if (key == keytable.LS_Left)
b.LStick(-0x8000, b.LS_Y);
else if (key == keytable.LS_Right)
b.LStick(0x7FFF, b.LS_Y);
else if (key == keytable.RS_Up)
b.RStick(b.RS_X, 0x7FFF);
else if (key == keytable.RS_Down)
b.RStick(b.RS_X, -0x8000);
else if (key == keytable.RS_Left)
b.RStick(-0x8000, b.RS_Y);
else if (key == keytable.RS_Right)
b.RStick(0x7FFF, b.RS_Y);
}
}
void MainWindow::keyReleaseEvent(QKeyEvent* event) {
if (ui->B_Connect->isEnabled())
return;
if (event->isAutoRepeat())
return;
int key = event->key();
if (ui->RB_Serial->isChecked()) {
if (key == keytable.A)
c.A(-1);
else if (key == keytable.B)
c.B(-1);
else if (key == keytable.X)
c.X(-1);
else if (key == keytable.Y)
c.Y(-1);
else if (key == keytable.LS_Left || key == keytable.LS_Right)
c.LS_XCenter();
else if (key == keytable.LS_Up || key == keytable.LS_Down)
c.LS_YCenter();
else if (key == keytable.RS_Left || key == keytable.RS_Right)
c.RS_XCenter();
else if (key == keytable.RS_Up || key == keytable.RS_Down)
c.RS_YCenter();
else if (key == keytable.D_Up || key == keytable.D_Down || key == keytable.D_Left || key == keytable.D_Right)
c.Dpad_Center();
else if (key == keytable.Capture)
c.Capture(-1);
else if (key == keytable.Plus)
c.Plus(-1);
else if (key == keytable.Minus)
c.Minus(-1);
else if (key == keytable.L)
c.L(-1);
else if (key == keytable.R)
c.R(-1);
else if (key == keytable.ZL)
c.ZL(-1);
else if (key == keytable.ZR)
c.ZR(-1);
else if (key == keytable.LS)
c.PressLeftStick(-1);
else if (key == keytable.RS)
c.PressRightStick(-1);
} else {
if (key == keytable.A)
b.release("A");
else if (key == keytable.B)
b.release("B");
else if (key == keytable.X)
b.release("X");
else if (key == keytable.Y)
b.release("Y");
else if (key == keytable.Home)
b.release("HOME");
else if (key == keytable.Capture)
b.release("CAPTURE");
else if (key == keytable.Plus)
b.release("PLUS");
else if (key == keytable.Minus)
b.release("MINUS");
else if (key == keytable.D_Up)
b.release("DUP");
else if (key == keytable.D_Down)
b.release("DDOWN");
else if (key == keytable.D_Left)
b.release("DLEFT");
else if (key == keytable.D_Right)
b.release("DRIGHT");
else if (key == keytable.L)
b.release("L");
else if (key == keytable.R)
b.release("R");
else if (key == keytable.ZL)
b.release("ZL");
else if (key == keytable.ZR)
b.release("ZR");
else if (key == keytable.LS)
b.release("LSTICK");
else if (key == keytable.RS)
b.release("RSTICK");
else if (key == keytable.LS_Left || key == keytable.LS_Right)
b.LStick(0, b.LS_Y);
else if (key == keytable.LS_Up || key == keytable.LS_Down)
b.LStick(b.LS_X, 0);
else if (key == keytable.RS_Left || key == keytable.RS_Right)
b.RStick(0, b.RS_Y);
else if (key == keytable.RS_Up || key == keytable.RS_Down)
b.RStick(b.RS_X, 0);
}
}
void MainWindow::on_B_Settings_clicked() {
auto* setting = new buttonconfig();
setting->show();
loadbuttonconfig();
}
void MainWindow::loadbuttonconfig() {
QSettings setting;
auto table = setting.value("settings/keyconfig", qVariantFromValue(keytable));
if (table.isValid())
keytable = table.value<inputtable>();
}
| 10,908
|
C++
|
.cpp
| 343
| 27.072886
| 113
| 0.618249
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,162
|
buttonconfig.cpp
|
wwwwwwzx_NXController/UI/buttonconfig.cpp
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#include "buttonconfig.h"
#include "ui_buttonconfig.h"
#include "inputtable.h"
#include <QSettings>
#include <QKeyEvent>
buttonconfig::buttonconfig(QWidget* parent) : QDialog(parent), ui(new Ui::buttonconfig) {
ui->setupUi(this);
QSettings setting;
auto table = setting.value("settings/keyconfig", qVariantFromValue(config));
if (table.isValid())
config = table.value<inputtable>();
loadsettings();
}
buttonconfig::~buttonconfig() {
delete ui;
}
void buttonconfig::on_buttonBox_accepted() {
QSettings setting;
setting.setValue("settings/keyconfig", qVariantFromValue(config));
}
void buttonconfig::on_B_Default_clicked() {
inputtable newconfig;
config = newconfig;
loadsettings();
}
void buttonconfig::loadsettings() {
ui->K_A->setText(QKeySequence(config.A).toString(QKeySequence::NativeText));
ui->K_B->setText(QKeySequence(config.B).toString(QKeySequence::NativeText));
ui->K_X->setText(QKeySequence(config.X).toString(QKeySequence::NativeText));
ui->K_Y->setText(QKeySequence(config.Y).toString(QKeySequence::NativeText));
ui->K_L->setText(QKeySequence(config.L).toString(QKeySequence::NativeText));
ui->K_R->setText(QKeySequence(config.R).toString(QKeySequence::NativeText));
ui->K_ZL->setText(QKeySequence(config.ZL).toString(QKeySequence::NativeText));
ui->K_ZR->setText(QKeySequence(config.ZR).toString(QKeySequence::NativeText));
ui->K_LS->setText(QKeySequence(config.LS).toString(QKeySequence::NativeText));
ui->K_RS->setText(QKeySequence(config.RS).toString(QKeySequence::NativeText));
ui->K_Home->setText(QKeySequence(config.Home).toString(QKeySequence::NativeText));
ui->K_Capture->setText(QKeySequence(config.Capture).toString(QKeySequence::NativeText));
ui->K_Plus->setText(QKeySequence(config.Plus).toString(QKeySequence::NativeText));
ui->K_Minus->setText(QKeySequence(config.Minus).toString(QKeySequence::NativeText));
ui->K_D_Up->setText(QKeySequence(config.D_Up).toString(QKeySequence::NativeText));
ui->K_D_Down->setText(QKeySequence(config.D_Down).toString(QKeySequence::NativeText));
ui->K_D_Left->setText(QKeySequence(config.D_Left).toString(QKeySequence::NativeText));
ui->K_D_Right->setText(QKeySequence(config.D_Right).toString(QKeySequence::NativeText));
ui->K_LS_Up->setText(QKeySequence(config.LS_Up).toString(QKeySequence::NativeText));
ui->K_LS_Down->setText(QKeySequence(config.LS_Down).toString(QKeySequence::NativeText));
ui->K_LS_Left->setText(QKeySequence(config.LS_Left).toString(QKeySequence::NativeText));
ui->K_LS_Right->setText(QKeySequence(config.LS_Right).toString(QKeySequence::NativeText));
ui->K_RS_Up->setText(QKeySequence(config.RS_Up).toString(QKeySequence::NativeText));
ui->K_RS_Down->setText(QKeySequence(config.RS_Down).toString(QKeySequence::NativeText));
ui->K_RS_Left->setText(QKeySequence(config.RS_Left).toString(QKeySequence::NativeText));
ui->K_RS_Right->setText(QKeySequence(config.RS_Right).toString(QKeySequence::NativeText));
}
void buttonconfig::on_K_A_textChanged(const QString& newtext) {
config.A = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_B_textChanged(const QString& newtext) {
config.B = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_X_textChanged(const QString& newtext) {
config.X = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_Y_textChanged(const QString& newtext) {
config.Y = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_L_textChanged(const QString& newtext) {
config.L = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_R_textChanged(const QString& newtext) {
config.R = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_ZL_textChanged(const QString& newtext) {
config.ZL = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_ZR_textChanged(const QString& newtext) {
config.ZR = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_LS_textChanged(const QString& newtext) {
config.LS = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_RS_textChanged(const QString& newtext) {
config.RS = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_Home_textChanged(const QString& newtext) {
config.Home = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_Capture_textChanged(const QString& newtext) {
config.Capture = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_Plus_textChanged(const QString& newtext) {
config.Plus = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_Minus_textChanged(const QString& newtext) {
config.Minus = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_D_Up_textChanged(const QString& newtext) {
config.D_Up = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_D_Down_textChanged(const QString& newtext) {
config.D_Down = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_D_Left_textChanged(const QString& newtext) {
config.D_Left = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_D_Right_textChanged(const QString& newtext) {
config.D_Right = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_LS_Up_textChanged(const QString& newtext) {
config.LS_Up = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_LS_Down_textChanged(const QString& newtext) {
config.LS_Down = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_LS_Left_textChanged(const QString& newtext) {
config.LS_Left = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_LS_Right_textChanged(const QString& newtext) {
config.LS_Right = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_RS_Up_textChanged(const QString& newtext) {
config.RS_Up = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_RS_Down_textChanged(const QString& newtext) {
config.RS_Down = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_RS_Left_textChanged(const QString& newtext) {
config.RS_Left = QKeySequence(newtext)[0];
}
void buttonconfig::on_K_RS_Right_textChanged(const QString& newtext) {
config.RS_Right = QKeySequence(newtext)[0];
}
| 6,607
|
C++
|
.cpp
| 148
| 42.594595
| 92
| 0.766047
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,163
|
qlineedithotkey.cpp
|
wwwwwwzx_NXController/UI/Control/qlineedithotkey.cpp
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#include "qlineedithotkey.h"
#include <QKeyEvent>
QLineEditHotKey::QLineEditHotKey(QWidget* pParent) : QLineEdit(pParent) {}
void QLineEditHotKey::keyPressEvent(QKeyEvent* event) {
int keyInt = event->key();
setText(QKeySequence(keyInt).toString(QKeySequence::NativeText));
}
| 1,010
|
C++
|
.cpp
| 24
| 40.125
| 74
| 0.769074
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,164
|
nxcontroller.h
|
wwwwwwzx_NXController/nxcontroller.h
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef NXCONTROLLER_H
#define NXCONTROLLER_H
#include <QString>
#include <QSerialPort>
class nxcontroller {
public:
nxcontroller();
bool connect(QString port);
void release();
void close();
void A(int duration = 100);
void B(int duration = 100);
void X(int duration = 100);
void Y(int duration = 100);
void L(int duration = 100);
void R(int duration = 100);
void ZL(int duration = 100);
void ZR(int duration = 100);
void Plus(int duration = 100);
void Minus(int duration = 100);
void Home(int duration = 100);
void Capture(int duration = 100);
// Dpad
void Up(int duration = 100);
void Down(int duration = 100);
void Left(int duration = 100);
void Right(int duration = 100);
void Dpad_Center();
// Left Stick
void LS_Left(int duration = 100);
void LS_Right(int duration = 100);
void LS_Up(int duration = 100);
void LS_Down(int duration = 100);
void LS_XCenter();
void LS_YCenter();
void PressLeftStick(int duration = 100);
// Right Stick
void RS_Left(int duration = 100);
void RS_Right(int duration = 100);
void RS_Up(int duration = 100);
void RS_Down(int duration = 100);
void RS_XCenter();
void RS_YCenter();
void PressRightStick(int duration = 100);
private:
QSerialPort ser;
int buttondelay = 100;
void write(QString msg);
void send(QString msg, int duration = 100);
};
#endif // NXCONTROLLER_H
| 2,122
|
C++
|
.h
| 68
| 28.588235
| 72
| 0.718475
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,165
|
nxcontroller_cfw.h
|
wwwwwwzx_NXController/nxcontroller_cfw.h
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef NXCONTROLLER_CFW_H
#define NXCONTROLLER_CFW_H
#include <QTcpSocket>
#include <QString>
class nxcontroller_cfw {
public:
nxcontroller_cfw();
bool connect(QString IP, short port = 6000);
void press(QString button);
void click(QString button);
void release(QString button);
void detachController();
void configuresleep(int mainLoopSleepTime, int buttonClickSleepTime);
void LStick(short x, short y);
void RStick(short x, short y);
QString peek(uint offset, uint size);
QString peek(QString offset, QString size);
void poke(uint offset, QByteArray data);
void poke(QString offset, QString data);
short LS_X = 0, LS_Y = 0, RS_X = 0, RS_Y = 0;
void close();
private:
QTcpSocket ts;
void send(QString msg);
QString tohex(short n);
};
#endif // NXCONTROLLER_CFW_H
| 1,534
|
C++
|
.h
| 44
| 32.545455
| 72
| 0.750336
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,166
|
inputtable.h
|
wwwwwwzx_NXController/UI/inputtable.h
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef INPUTTABLE_H
#define INPUTTABLE_H
#include <QKeyEvent>
struct inputtable {
int A = Qt::Key_A;
int B = Qt::Key_S;
int X = Qt::Key_Z;
int Y = Qt::Key_X;
int L = Qt::Key_Q;
int R = Qt::Key_W;
int ZL = Qt::Key_1;
int ZR = Qt::Key_2;
int LS = Qt::Key_3;
int RS = Qt::Key_4;
int Home = Qt::Key_B;
int Capture = Qt::Key_V;
int Plus = Qt::Key_N;
int Minus = Qt::Key_M;
int D_Left = Qt::Key_F;
int D_Right = Qt::Key_H;
int D_Up = Qt::Key_T;
int D_Down = Qt::Key_G;
int LS_Left = Qt::Key_Left;
int LS_Right = Qt::Key_Right;
int LS_Up = Qt::Key_Up;
int LS_Down = Qt::Key_Down;
int RS_Left = Qt::Key_J;
int RS_Right = Qt::Key_L;
int RS_Up = Qt::Key_I;
int RS_Down = Qt::Key_K;
};
Q_DECLARE_METATYPE(inputtable)
QDataStream& operator<<(QDataStream& out, const inputtable& v);
QDataStream& operator>>(QDataStream& in, inputtable& v);
#endif // INPUTTABLE_H
| 1,635
|
C++
|
.h
| 52
| 29.057692
| 72
| 0.685877
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,167
|
mainwindow.h
|
wwwwwwzx_NXController/UI/mainwindow.h
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "nxcontroller.h"
#include "nxcontroller_cfw.h"
#include "inputtable.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget* parent = nullptr);
~MainWindow();
void keyPressEvent(QKeyEvent* event);
void keyReleaseEvent(QKeyEvent* event);
nxcontroller c;
nxcontroller_cfw b;
inputtable keytable;
private slots:
void on_B_Refresh_clicked();
void on_B_Connect_clicked();
void on_B_Disconnect_clicked();
void on_B_Write_clicked();
void on_B_Read_clicked();
void on_B_Settings_clicked();
private:
void loadbuttonconfig();
Ui::MainWindow* ui;
};
#endif // MAINWINDOW_H
| 1,502
|
C++
|
.h
| 50
| 27.84
| 72
| 0.759862
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,168
|
buttonconfig.h
|
wwwwwwzx_NXController/UI/buttonconfig.h
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef BUTTONCONFIG_H
#define BUTTONCONFIG_H
#include <QDialog>
#include "inputtable.h"
namespace Ui {
class buttonconfig;
}
class buttonconfig : public QDialog {
Q_OBJECT
public:
explicit buttonconfig(QWidget* parent = nullptr);
~buttonconfig();
private slots:
void loadsettings();
void on_B_Default_clicked();
void on_buttonBox_accepted();
void on_K_A_textChanged(const QString& newtext);
void on_K_B_textChanged(const QString& newtext);
void on_K_X_textChanged(const QString& newtext);
void on_K_Y_textChanged(const QString& newtext);
void on_K_L_textChanged(const QString& newtext);
void on_K_R_textChanged(const QString& newtext);
void on_K_ZL_textChanged(const QString& newtext);
void on_K_ZR_textChanged(const QString& newtext);
void on_K_LS_textChanged(const QString& newtext);
void on_K_RS_textChanged(const QString& newtext);
void on_K_Home_textChanged(const QString& newtext);
void on_K_Capture_textChanged(const QString& newtext);
void on_K_Plus_textChanged(const QString& newtext);
void on_K_Minus_textChanged(const QString& newtext);
void on_K_D_Left_textChanged(const QString& newtext);
void on_K_D_Right_textChanged(const QString& newtext);
void on_K_D_Up_textChanged(const QString& newtext);
void on_K_D_Down_textChanged(const QString& newtext);
void on_K_LS_Left_textChanged(const QString& newtext);
void on_K_LS_Right_textChanged(const QString& newtext);
void on_K_LS_Up_textChanged(const QString& newtext);
void on_K_LS_Down_textChanged(const QString& newtext);
void on_K_RS_Left_textChanged(const QString& newtext);
void on_K_RS_Right_textChanged(const QString& newtext);
void on_K_RS_Up_textChanged(const QString& newtext);
void on_K_RS_Down_textChanged(const QString& newtext);
private:
Ui::buttonconfig* ui;
inputtable config;
};
#endif // BUTTONCONFIG_H
| 2,592
|
C++
|
.h
| 64
| 37.9375
| 72
| 0.763607
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,169
|
qlineedithotkey.h
|
wwwwwwzx_NXController/UI/Control/qlineedithotkey.h
|
/*
* This file is part of NXController
* Copyright (C) 2020 by wwwwwwzx
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef QLINEEDITHOTKEY_H
#define QLINEEDITHOTKEY_H
#include <QLineEdit>
class QLineEditHotKey : public QLineEdit {
public:
QLineEditHotKey(QWidget* pParent = NULL);
~QLineEditHotKey() {}
protected:
void keyPressEvent(QKeyEvent* event);
};
#endif // QLINEEDITHOTKEY_H
| 1,009
|
C++
|
.h
| 28
| 34
| 72
| 0.767418
|
wwwwwwzx/NXController
| 38
| 4
| 6
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,172
|
zAOG_ping.h
|
mtz8302_AOG_GPS_ESP32/AOG_GPS_ESP32/zAOG_ping.h
|
#ifndef PING_H
#define PING_H
#include <Arduino.h>
typedef void(*ping_recv_function)(void* arg, void *pdata);
typedef void(*ping_sent_function)(void* arg, void *pdata);
struct ping_option {
uint32_t count;
uint32_t ip;
uint32_t coarse_time;
ping_recv_function recv_function;
ping_sent_function sent_function;
void* reverse;
};
struct ping_resp {
uint32_t total_count;
float resp_time;
uint32_t seqno;
uint32_t timeout_count;
uint32_t bytes;
uint32_t total_bytes;
float total_time;
int8_t ping_err;
};
bool ping_start(struct ping_option *ping_opt);
void ping(const char *name, int count, int interval, int size, int timeout);
bool ping_start(IPAddress adr, int count, int interval, int size, int timeout, struct ping_option *ping_o = NULL);
#endif // PING_H
| 821
|
C++
|
.h
| 27
| 27.074074
| 114
| 0.715375
|
mtz8302/AOG_GPS_ESP32
| 36
| 18
| 1
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,174
|
bpf_endian.h
|
takehaya_Vinbero/include/bpf_endian.h
|
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef __BPF_ENDIAN__
#define __BPF_ENDIAN__
#include <linux/swab.h>
/* LLVM's BPF target selects the endianness of the CPU
* it compiles on, or the user specifies (bpfel/bpfeb),
* respectively. The used __BYTE_ORDER__ is defined by
* the compiler, we cannot rely on __BYTE_ORDER from
* libc headers, since it doesn't reflect the actual
* requested byte order.
*
* Note, LLVM's BPF target has different __builtin_bswapX()
* semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE
* in bpfel and bpfeb case, which means below, that we map
* to cpu_to_be16(). We could use it unconditionally in BPF
* case, but better not rely on it, so that this header here
* can be used from application and BPF program side, which
* use different targets.
*/
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define __bpf_ntohs(x) __builtin_bswap16(x)
# define __bpf_htons(x) __builtin_bswap16(x)
# define __bpf_constant_ntohs(x) ___constant_swab16(x)
# define __bpf_constant_htons(x) ___constant_swab16(x)
# define __bpf_ntohl(x) __builtin_bswap32(x)
# define __bpf_htonl(x) __builtin_bswap32(x)
# define __bpf_constant_ntohl(x) ___constant_swab32(x)
# define __bpf_constant_htonl(x) ___constant_swab32(x)
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
# define __bpf_ntohs(x) (x)
# define __bpf_htons(x) (x)
# define __bpf_constant_ntohs(x) (x)
# define __bpf_constant_htons(x) (x)
# define __bpf_ntohl(x) (x)
# define __bpf_htonl(x) (x)
# define __bpf_constant_ntohl(x) (x)
# define __bpf_constant_htonl(x) (x)
#else
# error "Fix your compiler's __BYTE_ORDER__?!"
#endif
#define bpf_htons(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_htons(x) : __bpf_htons(x))
#define bpf_ntohs(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_ntohs(x) : __bpf_ntohs(x))
#define bpf_htonl(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_htonl(x) : __bpf_htonl(x))
#define bpf_ntohl(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_ntohl(x) : __bpf_ntohl(x))
#endif /* __BPF_ENDIAN__ */
| 2,061
|
C++
|
.h
| 53
| 37.320755
| 60
| 0.668164
|
takehaya/Vinbero
| 36
| 4
| 6
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,175
|
bpf_helpers.h
|
takehaya_Vinbero/include/bpf_helpers.h
|
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
#ifndef __BPF_HELPERS__
#define __BPF_HELPERS__
#define __uint(name, val) int (*name)[val]
#define __type(name, val) typeof(val) *name
/* helper macro to print out debug messages */
#define bpf_printk(fmt, ...) \
({ \
char ____fmt[] = fmt; \
bpf_trace_printk(____fmt, sizeof(____fmt), \
##__VA_ARGS__); \
})
#ifdef __clang__
/* helper macro to place programs, maps, license in
* different sections in elf_bpf file. Section names
* are interpreted by elf_bpf loader
*/
#define SEC(NAME) __attribute__((section(NAME), used))
/* helper functions called from eBPF programs written in C */
static void *(*bpf_map_lookup_elem)(void *map, const void *key) =
(void *) BPF_FUNC_map_lookup_elem;
static int (*bpf_map_update_elem)(void *map, const void *key, const void *value,
unsigned long long flags) =
(void *) BPF_FUNC_map_update_elem;
static int (*bpf_map_delete_elem)(void *map, const void *key) =
(void *) BPF_FUNC_map_delete_elem;
static int (*bpf_map_push_elem)(void *map, const void *value,
unsigned long long flags) =
(void *) BPF_FUNC_map_push_elem;
static int (*bpf_map_pop_elem)(void *map, void *value) =
(void *) BPF_FUNC_map_pop_elem;
static int (*bpf_map_peek_elem)(void *map, void *value) =
(void *) BPF_FUNC_map_peek_elem;
static int (*bpf_probe_read)(void *dst, int size, const void *unsafe_ptr) =
(void *) BPF_FUNC_probe_read;
static unsigned long long (*bpf_ktime_get_ns)(void) =
(void *) BPF_FUNC_ktime_get_ns;
static int (*bpf_trace_printk)(const char *fmt, int fmt_size, ...) =
(void *) BPF_FUNC_trace_printk;
static void (*bpf_tail_call)(void *ctx, void *map, int index) =
(void *) BPF_FUNC_tail_call;
static unsigned long long (*bpf_get_smp_processor_id)(void) =
(void *) BPF_FUNC_get_smp_processor_id;
static unsigned long long (*bpf_get_current_pid_tgid)(void) =
(void *) BPF_FUNC_get_current_pid_tgid;
static unsigned long long (*bpf_get_current_uid_gid)(void) =
(void *) BPF_FUNC_get_current_uid_gid;
static int (*bpf_get_current_comm)(void *buf, int buf_size) =
(void *) BPF_FUNC_get_current_comm;
static unsigned long long (*bpf_perf_event_read)(void *map,
unsigned long long flags) =
(void *) BPF_FUNC_perf_event_read;
static int (*bpf_clone_redirect)(void *ctx, int ifindex, int flags) =
(void *) BPF_FUNC_clone_redirect;
static int (*bpf_redirect)(int ifindex, int flags) =
(void *) BPF_FUNC_redirect;
static int (*bpf_redirect_map)(void *map, int key, int flags) =
(void *) BPF_FUNC_redirect_map;
static int (*bpf_perf_event_output)(void *ctx, void *map,
unsigned long long flags, void *data,
int size) =
(void *) BPF_FUNC_perf_event_output;
static int (*bpf_get_stackid)(void *ctx, void *map, int flags) =
(void *) BPF_FUNC_get_stackid;
static int (*bpf_probe_write_user)(void *dst, const void *src, int size) =
(void *) BPF_FUNC_probe_write_user;
static int (*bpf_current_task_under_cgroup)(void *map, int index) =
(void *) BPF_FUNC_current_task_under_cgroup;
static int (*bpf_skb_get_tunnel_key)(void *ctx, void *key, int size, int flags) =
(void *) BPF_FUNC_skb_get_tunnel_key;
static int (*bpf_skb_set_tunnel_key)(void *ctx, void *key, int size, int flags) =
(void *) BPF_FUNC_skb_set_tunnel_key;
static int (*bpf_skb_get_tunnel_opt)(void *ctx, void *md, int size) =
(void *) BPF_FUNC_skb_get_tunnel_opt;
static int (*bpf_skb_set_tunnel_opt)(void *ctx, void *md, int size) =
(void *) BPF_FUNC_skb_set_tunnel_opt;
static unsigned long long (*bpf_get_prandom_u32)(void) =
(void *) BPF_FUNC_get_prandom_u32;
static int (*bpf_xdp_adjust_head)(void *ctx, int offset) =
(void *) BPF_FUNC_xdp_adjust_head;
static int (*bpf_xdp_adjust_meta)(void *ctx, int offset) =
(void *) BPF_FUNC_xdp_adjust_meta;
static int (*bpf_get_socket_cookie)(void *ctx) =
(void *) BPF_FUNC_get_socket_cookie;
static int (*bpf_setsockopt)(void *ctx, int level, int optname, void *optval,
int optlen) =
(void *) BPF_FUNC_setsockopt;
static int (*bpf_getsockopt)(void *ctx, int level, int optname, void *optval,
int optlen) =
(void *) BPF_FUNC_getsockopt;
static int (*bpf_sock_ops_cb_flags_set)(void *ctx, int flags) =
(void *) BPF_FUNC_sock_ops_cb_flags_set;
static int (*bpf_sk_redirect_map)(void *ctx, void *map, int key, int flags) =
(void *) BPF_FUNC_sk_redirect_map;
static int (*bpf_sk_redirect_hash)(void *ctx, void *map, void *key, int flags) =
(void *) BPF_FUNC_sk_redirect_hash;
static int (*bpf_sock_map_update)(void *map, void *key, void *value,
unsigned long long flags) =
(void *) BPF_FUNC_sock_map_update;
static int (*bpf_sock_hash_update)(void *map, void *key, void *value,
unsigned long long flags) =
(void *) BPF_FUNC_sock_hash_update;
static int (*bpf_perf_event_read_value)(void *map, unsigned long long flags,
void *buf, unsigned int buf_size) =
(void *) BPF_FUNC_perf_event_read_value;
static int (*bpf_perf_prog_read_value)(void *ctx, void *buf,
unsigned int buf_size) =
(void *) BPF_FUNC_perf_prog_read_value;
static int (*bpf_override_return)(void *ctx, unsigned long rc) =
(void *) BPF_FUNC_override_return;
static int (*bpf_msg_redirect_map)(void *ctx, void *map, int key, int flags) =
(void *) BPF_FUNC_msg_redirect_map;
static int (*bpf_msg_redirect_hash)(void *ctx,
void *map, void *key, int flags) =
(void *) BPF_FUNC_msg_redirect_hash;
static int (*bpf_msg_apply_bytes)(void *ctx, int len) =
(void *) BPF_FUNC_msg_apply_bytes;
static int (*bpf_msg_cork_bytes)(void *ctx, int len) =
(void *) BPF_FUNC_msg_cork_bytes;
static int (*bpf_msg_pull_data)(void *ctx, int start, int end, int flags) =
(void *) BPF_FUNC_msg_pull_data;
static int (*bpf_msg_push_data)(void *ctx, int start, int end, int flags) =
(void *) BPF_FUNC_msg_push_data;
static int (*bpf_msg_pop_data)(void *ctx, int start, int cut, int flags) =
(void *) BPF_FUNC_msg_pop_data;
static int (*bpf_bind)(void *ctx, void *addr, int addr_len) =
(void *) BPF_FUNC_bind;
static int (*bpf_xdp_adjust_tail)(void *ctx, int offset) =
(void *) BPF_FUNC_xdp_adjust_tail;
static int (*bpf_skb_get_xfrm_state)(void *ctx, int index, void *state,
int size, int flags) =
(void *) BPF_FUNC_skb_get_xfrm_state;
static int (*bpf_sk_select_reuseport)(void *ctx, void *map, void *key, __u32 flags) =
(void *) BPF_FUNC_sk_select_reuseport;
static int (*bpf_get_stack)(void *ctx, void *buf, int size, int flags) =
(void *) BPF_FUNC_get_stack;
static int (*bpf_fib_lookup)(void *ctx, struct bpf_fib_lookup *params,
int plen, __u32 flags) =
(void *) BPF_FUNC_fib_lookup;
static int (*bpf_lwt_push_encap)(void *ctx, unsigned int type, void *hdr,
unsigned int len) =
(void *) BPF_FUNC_lwt_push_encap;
static int (*bpf_lwt_seg6_store_bytes)(void *ctx, unsigned int offset,
void *from, unsigned int len) =
(void *) BPF_FUNC_lwt_seg6_store_bytes;
static int (*bpf_lwt_seg6_action)(void *ctx, unsigned int action, void *param,
unsigned int param_len) =
(void *) BPF_FUNC_lwt_seg6_action;
static int (*bpf_lwt_seg6_adjust_srh)(void *ctx, unsigned int offset,
unsigned int len) =
(void *) BPF_FUNC_lwt_seg6_adjust_srh;
static int (*bpf_rc_repeat)(void *ctx) =
(void *) BPF_FUNC_rc_repeat;
static int (*bpf_rc_keydown)(void *ctx, unsigned int protocol,
unsigned long long scancode, unsigned int toggle) =
(void *) BPF_FUNC_rc_keydown;
static unsigned long long (*bpf_get_current_cgroup_id)(void) =
(void *) BPF_FUNC_get_current_cgroup_id;
static void *(*bpf_get_local_storage)(void *map, unsigned long long flags) =
(void *) BPF_FUNC_get_local_storage;
static unsigned long long (*bpf_skb_cgroup_id)(void *ctx) =
(void *) BPF_FUNC_skb_cgroup_id;
static unsigned long long (*bpf_skb_ancestor_cgroup_id)(void *ctx, int level) =
(void *) BPF_FUNC_skb_ancestor_cgroup_id;
static struct bpf_sock *(*bpf_sk_lookup_tcp)(void *ctx,
struct bpf_sock_tuple *tuple,
int size, unsigned long long netns_id,
unsigned long long flags) =
(void *) BPF_FUNC_sk_lookup_tcp;
static struct bpf_sock *(*bpf_skc_lookup_tcp)(void *ctx,
struct bpf_sock_tuple *tuple,
int size, unsigned long long netns_id,
unsigned long long flags) =
(void *) BPF_FUNC_skc_lookup_tcp;
static struct bpf_sock *(*bpf_sk_lookup_udp)(void *ctx,
struct bpf_sock_tuple *tuple,
int size, unsigned long long netns_id,
unsigned long long flags) =
(void *) BPF_FUNC_sk_lookup_udp;
static int (*bpf_sk_release)(struct bpf_sock *sk) =
(void *) BPF_FUNC_sk_release;
static int (*bpf_skb_vlan_push)(void *ctx, __be16 vlan_proto, __u16 vlan_tci) =
(void *) BPF_FUNC_skb_vlan_push;
static int (*bpf_skb_vlan_pop)(void *ctx) =
(void *) BPF_FUNC_skb_vlan_pop;
static int (*bpf_rc_pointer_rel)(void *ctx, int rel_x, int rel_y) =
(void *) BPF_FUNC_rc_pointer_rel;
static void (*bpf_spin_lock)(struct bpf_spin_lock *lock) =
(void *) BPF_FUNC_spin_lock;
static void (*bpf_spin_unlock)(struct bpf_spin_lock *lock) =
(void *) BPF_FUNC_spin_unlock;
static struct bpf_sock *(*bpf_sk_fullsock)(struct bpf_sock *sk) =
(void *) BPF_FUNC_sk_fullsock;
static struct bpf_tcp_sock *(*bpf_tcp_sock)(struct bpf_sock *sk) =
(void *) BPF_FUNC_tcp_sock;
static struct bpf_sock *(*bpf_get_listener_sock)(struct bpf_sock *sk) =
(void *) BPF_FUNC_get_listener_sock;
static int (*bpf_skb_ecn_set_ce)(void *ctx) =
(void *) BPF_FUNC_skb_ecn_set_ce;
static int (*bpf_tcp_check_syncookie)(struct bpf_sock *sk,
void *ip, int ip_len, void *tcp, int tcp_len) =
(void *) BPF_FUNC_tcp_check_syncookie;
static int (*bpf_sysctl_get_name)(void *ctx, char *buf,
unsigned long long buf_len,
unsigned long long flags) =
(void *) BPF_FUNC_sysctl_get_name;
static int (*bpf_sysctl_get_current_value)(void *ctx, char *buf,
unsigned long long buf_len) =
(void *) BPF_FUNC_sysctl_get_current_value;
static int (*bpf_sysctl_get_new_value)(void *ctx, char *buf,
unsigned long long buf_len) =
(void *) BPF_FUNC_sysctl_get_new_value;
static int (*bpf_sysctl_set_new_value)(void *ctx, const char *buf,
unsigned long long buf_len) =
(void *) BPF_FUNC_sysctl_set_new_value;
static int (*bpf_strtol)(const char *buf, unsigned long long buf_len,
unsigned long long flags, long *res) =
(void *) BPF_FUNC_strtol;
static int (*bpf_strtoul)(const char *buf, unsigned long long buf_len,
unsigned long long flags, unsigned long *res) =
(void *) BPF_FUNC_strtoul;
static void *(*bpf_sk_storage_get)(void *map, struct bpf_sock *sk,
void *value, __u64 flags) =
(void *) BPF_FUNC_sk_storage_get;
static int (*bpf_sk_storage_delete)(void *map, struct bpf_sock *sk) =
(void *)BPF_FUNC_sk_storage_delete;
static int (*bpf_send_signal)(unsigned sig) = (void *)BPF_FUNC_send_signal;
static long long (*bpf_tcp_gen_syncookie)(struct bpf_sock *sk, void *ip,
int ip_len, void *tcp, int tcp_len) =
(void *) BPF_FUNC_tcp_gen_syncookie;
/* llvm builtin functions that eBPF C program may use to
* emit BPF_LD_ABS and BPF_LD_IND instructions
*/
struct sk_buff;
unsigned long long load_byte(void *skb,
unsigned long long off) asm("llvm.bpf.load.byte");
unsigned long long load_half(void *skb,
unsigned long long off) asm("llvm.bpf.load.half");
unsigned long long load_word(void *skb,
unsigned long long off) asm("llvm.bpf.load.word");
/* a helper structure used by eBPF C program
* to describe map attributes to elf_bpf loader
*/
struct bpf_map_def {
unsigned int type;
unsigned int key_size;
unsigned int value_size;
unsigned int max_entries;
unsigned int map_flags;
unsigned int inner_map_idx;
unsigned int numa_node;
};
#else
#include <bpf-helpers.h>
#endif
#define BPF_ANNOTATE_KV_PAIR(name, type_key, type_val) \
struct ____btf_map_##name { \
type_key key; \
type_val value; \
}; \
struct ____btf_map_##name \
__attribute__ ((section(".maps." #name), used)) \
____btf_map_##name = { }
static int (*bpf_skb_load_bytes)(void *ctx, int off, void *to, int len) =
(void *) BPF_FUNC_skb_load_bytes;
static int (*bpf_skb_load_bytes_relative)(void *ctx, int off, void *to, int len, __u32 start_header) =
(void *) BPF_FUNC_skb_load_bytes_relative;
static int (*bpf_skb_store_bytes)(void *ctx, int off, void *from, int len, int flags) =
(void *) BPF_FUNC_skb_store_bytes;
static int (*bpf_l3_csum_replace)(void *ctx, int off, int from, int to, int flags) =
(void *) BPF_FUNC_l3_csum_replace;
static int (*bpf_l4_csum_replace)(void *ctx, int off, int from, int to, int flags) =
(void *) BPF_FUNC_l4_csum_replace;
static int (*bpf_csum_diff)(void *from, int from_size, void *to, int to_size, int seed) =
(void *) BPF_FUNC_csum_diff;
static int (*bpf_skb_under_cgroup)(void *ctx, void *map, int index) =
(void *) BPF_FUNC_skb_under_cgroup;
static int (*bpf_skb_change_head)(void *, int len, int flags) =
(void *) BPF_FUNC_skb_change_head;
static int (*bpf_skb_pull_data)(void *, int len) =
(void *) BPF_FUNC_skb_pull_data;
static unsigned int (*bpf_get_cgroup_classid)(void *ctx) =
(void *) BPF_FUNC_get_cgroup_classid;
static unsigned int (*bpf_get_route_realm)(void *ctx) =
(void *) BPF_FUNC_get_route_realm;
static int (*bpf_skb_change_proto)(void *ctx, __be16 proto, __u64 flags) =
(void *) BPF_FUNC_skb_change_proto;
static int (*bpf_skb_change_type)(void *ctx, __u32 type) =
(void *) BPF_FUNC_skb_change_type;
static unsigned int (*bpf_get_hash_recalc)(void *ctx) =
(void *) BPF_FUNC_get_hash_recalc;
static unsigned long long (*bpf_get_current_task)(void) =
(void *) BPF_FUNC_get_current_task;
static int (*bpf_skb_change_tail)(void *ctx, __u32 len, __u64 flags) =
(void *) BPF_FUNC_skb_change_tail;
static long long (*bpf_csum_update)(void *ctx, __u32 csum) =
(void *) BPF_FUNC_csum_update;
static void (*bpf_set_hash_invalid)(void *ctx) =
(void *) BPF_FUNC_set_hash_invalid;
static int (*bpf_get_numa_node_id)(void) =
(void *) BPF_FUNC_get_numa_node_id;
static int (*bpf_probe_read_str)(void *ctx, __u32 size,
const void *unsafe_ptr) =
(void *) BPF_FUNC_probe_read_str;
static unsigned int (*bpf_get_socket_uid)(void *ctx) =
(void *) BPF_FUNC_get_socket_uid;
static unsigned int (*bpf_set_hash)(void *ctx, __u32 hash) =
(void *) BPF_FUNC_set_hash;
static int (*bpf_skb_adjust_room)(void *ctx, __s32 len_diff, __u32 mode,
unsigned long long flags) =
(void *) BPF_FUNC_skb_adjust_room;
/* Scan the ARCH passed in from ARCH env variable (see Makefile) */
#if defined(__TARGET_ARCH_x86)
#define bpf_target_x86
#define bpf_target_defined
#elif defined(__TARGET_ARCH_s390)
#define bpf_target_s390
#define bpf_target_defined
#elif defined(__TARGET_ARCH_arm)
#define bpf_target_arm
#define bpf_target_defined
#elif defined(__TARGET_ARCH_arm64)
#define bpf_target_arm64
#define bpf_target_defined
#elif defined(__TARGET_ARCH_mips)
#define bpf_target_mips
#define bpf_target_defined
#elif defined(__TARGET_ARCH_powerpc)
#define bpf_target_powerpc
#define bpf_target_defined
#elif defined(__TARGET_ARCH_sparc)
#define bpf_target_sparc
#define bpf_target_defined
#else
#undef bpf_target_defined
#endif
/* Fall back to what the compiler says */
#ifndef bpf_target_defined
#if defined(__x86_64__)
#define bpf_target_x86
#elif defined(__s390__)
#define bpf_target_s390
#elif defined(__arm__)
#define bpf_target_arm
#elif defined(__aarch64__)
#define bpf_target_arm64
#elif defined(__mips__)
#define bpf_target_mips
#elif defined(__powerpc__)
#define bpf_target_powerpc
#elif defined(__sparc__)
#define bpf_target_sparc
#endif
#endif
#if defined(bpf_target_x86)
#ifdef __KERNEL__
#define PT_REGS_PARM1(x) ((x)->di)
#define PT_REGS_PARM2(x) ((x)->si)
#define PT_REGS_PARM3(x) ((x)->dx)
#define PT_REGS_PARM4(x) ((x)->cx)
#define PT_REGS_PARM5(x) ((x)->r8)
#define PT_REGS_RET(x) ((x)->sp)
#define PT_REGS_FP(x) ((x)->bp)
#define PT_REGS_RC(x) ((x)->ax)
#define PT_REGS_SP(x) ((x)->sp)
#define PT_REGS_IP(x) ((x)->ip)
#else
#ifdef __i386__
/* i386 kernel is built with -mregparm=3 */
#define PT_REGS_PARM1(x) ((x)->eax)
#define PT_REGS_PARM2(x) ((x)->edx)
#define PT_REGS_PARM3(x) ((x)->ecx)
#define PT_REGS_PARM4(x) 0
#define PT_REGS_PARM5(x) 0
#define PT_REGS_RET(x) ((x)->esp)
#define PT_REGS_FP(x) ((x)->ebp)
#define PT_REGS_RC(x) ((x)->eax)
#define PT_REGS_SP(x) ((x)->esp)
#define PT_REGS_IP(x) ((x)->eip)
#else
#define PT_REGS_PARM1(x) ((x)->rdi)
#define PT_REGS_PARM2(x) ((x)->rsi)
#define PT_REGS_PARM3(x) ((x)->rdx)
#define PT_REGS_PARM4(x) ((x)->rcx)
#define PT_REGS_PARM5(x) ((x)->r8)
#define PT_REGS_RET(x) ((x)->rsp)
#define PT_REGS_FP(x) ((x)->rbp)
#define PT_REGS_RC(x) ((x)->rax)
#define PT_REGS_SP(x) ((x)->rsp)
#define PT_REGS_IP(x) ((x)->rip)
#endif
#endif
#elif defined(bpf_target_s390)
/* s390 provides user_pt_regs instead of struct pt_regs to userspace */
struct pt_regs;
#define PT_REGS_S390 const volatile user_pt_regs
#define PT_REGS_PARM1(x) (((PT_REGS_S390 *)(x))->gprs[2])
#define PT_REGS_PARM2(x) (((PT_REGS_S390 *)(x))->gprs[3])
#define PT_REGS_PARM3(x) (((PT_REGS_S390 *)(x))->gprs[4])
#define PT_REGS_PARM4(x) (((PT_REGS_S390 *)(x))->gprs[5])
#define PT_REGS_PARM5(x) (((PT_REGS_S390 *)(x))->gprs[6])
#define PT_REGS_RET(x) (((PT_REGS_S390 *)(x))->gprs[14])
/* Works only with CONFIG_FRAME_POINTER */
#define PT_REGS_FP(x) (((PT_REGS_S390 *)(x))->gprs[11])
#define PT_REGS_RC(x) (((PT_REGS_S390 *)(x))->gprs[2])
#define PT_REGS_SP(x) (((PT_REGS_S390 *)(x))->gprs[15])
#define PT_REGS_IP(x) (((PT_REGS_S390 *)(x))->psw.addr)
#elif defined(bpf_target_arm)
#define PT_REGS_PARM1(x) ((x)->uregs[0])
#define PT_REGS_PARM2(x) ((x)->uregs[1])
#define PT_REGS_PARM3(x) ((x)->uregs[2])
#define PT_REGS_PARM4(x) ((x)->uregs[3])
#define PT_REGS_PARM5(x) ((x)->uregs[4])
#define PT_REGS_RET(x) ((x)->uregs[14])
#define PT_REGS_FP(x) ((x)->uregs[11]) /* Works only with CONFIG_FRAME_POINTER */
#define PT_REGS_RC(x) ((x)->uregs[0])
#define PT_REGS_SP(x) ((x)->uregs[13])
#define PT_REGS_IP(x) ((x)->uregs[12])
#elif defined(bpf_target_arm64)
/* arm64 provides struct user_pt_regs instead of struct pt_regs to userspace */
struct pt_regs;
#define PT_REGS_ARM64 const volatile struct user_pt_regs
#define PT_REGS_PARM1(x) (((PT_REGS_ARM64 *)(x))->regs[0])
#define PT_REGS_PARM2(x) (((PT_REGS_ARM64 *)(x))->regs[1])
#define PT_REGS_PARM3(x) (((PT_REGS_ARM64 *)(x))->regs[2])
#define PT_REGS_PARM4(x) (((PT_REGS_ARM64 *)(x))->regs[3])
#define PT_REGS_PARM5(x) (((PT_REGS_ARM64 *)(x))->regs[4])
#define PT_REGS_RET(x) (((PT_REGS_ARM64 *)(x))->regs[30])
/* Works only with CONFIG_FRAME_POINTER */
#define PT_REGS_FP(x) (((PT_REGS_ARM64 *)(x))->regs[29])
#define PT_REGS_RC(x) (((PT_REGS_ARM64 *)(x))->regs[0])
#define PT_REGS_SP(x) (((PT_REGS_ARM64 *)(x))->sp)
#define PT_REGS_IP(x) (((PT_REGS_ARM64 *)(x))->pc)
#elif defined(bpf_target_mips)
#define PT_REGS_PARM1(x) ((x)->regs[4])
#define PT_REGS_PARM2(x) ((x)->regs[5])
#define PT_REGS_PARM3(x) ((x)->regs[6])
#define PT_REGS_PARM4(x) ((x)->regs[7])
#define PT_REGS_PARM5(x) ((x)->regs[8])
#define PT_REGS_RET(x) ((x)->regs[31])
#define PT_REGS_FP(x) ((x)->regs[30]) /* Works only with CONFIG_FRAME_POINTER */
#define PT_REGS_RC(x) ((x)->regs[1])
#define PT_REGS_SP(x) ((x)->regs[29])
#define PT_REGS_IP(x) ((x)->cp0_epc)
#elif defined(bpf_target_powerpc)
#define PT_REGS_PARM1(x) ((x)->gpr[3])
#define PT_REGS_PARM2(x) ((x)->gpr[4])
#define PT_REGS_PARM3(x) ((x)->gpr[5])
#define PT_REGS_PARM4(x) ((x)->gpr[6])
#define PT_REGS_PARM5(x) ((x)->gpr[7])
#define PT_REGS_RC(x) ((x)->gpr[3])
#define PT_REGS_SP(x) ((x)->sp)
#define PT_REGS_IP(x) ((x)->nip)
#elif defined(bpf_target_sparc)
#define PT_REGS_PARM1(x) ((x)->u_regs[UREG_I0])
#define PT_REGS_PARM2(x) ((x)->u_regs[UREG_I1])
#define PT_REGS_PARM3(x) ((x)->u_regs[UREG_I2])
#define PT_REGS_PARM4(x) ((x)->u_regs[UREG_I3])
#define PT_REGS_PARM5(x) ((x)->u_regs[UREG_I4])
#define PT_REGS_RET(x) ((x)->u_regs[UREG_I7])
#define PT_REGS_RC(x) ((x)->u_regs[UREG_I0])
#define PT_REGS_SP(x) ((x)->u_regs[UREG_FP])
/* Should this also be a bpf_target check for the sparc case? */
#if defined(__arch64__)
#define PT_REGS_IP(x) ((x)->tpc)
#else
#define PT_REGS_IP(x) ((x)->pc)
#endif
#endif
#if defined(bpf_target_powerpc)
#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = (ctx)->link; })
#define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP
#elif defined(bpf_target_sparc)
#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = PT_REGS_RET(ctx); })
#define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP
#else
#define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ \
bpf_probe_read(&(ip), sizeof(ip), (void *)PT_REGS_RET(ctx)); })
#define BPF_KRETPROBE_READ_RET_IP(ip, ctx) ({ \
bpf_probe_read(&(ip), sizeof(ip), \
(void *)(PT_REGS_FP(ctx) + sizeof(ip))); })
#endif
/*
* BPF_CORE_READ abstracts away bpf_probe_read() call and captures offset
* relocation for source address using __builtin_preserve_access_index()
* built-in, provided by Clang.
*
* __builtin_preserve_access_index() takes as an argument an expression of
* taking an address of a field within struct/union. It makes compiler emit
* a relocation, which records BTF type ID describing root struct/union and an
* accessor string which describes exact embedded field that was used to take
* an address. See detailed description of this relocation format and
* semantics in comments to struct bpf_offset_reloc in libbpf_internal.h.
*
* This relocation allows libbpf to adjust BPF instruction to use correct
* actual field offset, based on target kernel BTF type that matches original
* (local) BTF, used to record relocation.
*/
#define BPF_CORE_READ(dst, src) \
bpf_probe_read((dst), sizeof(*(src)), \
__builtin_preserve_access_index(src))
#endif
| 21,696
|
C++
|
.h
| 502
| 41.093625
| 102
| 0.682624
|
takehaya/Vinbero
| 36
| 4
| 6
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,176
|
bpf_helper_defs.h
|
takehaya_Vinbero/include/bpf_helper_defs.h
|
.. Copyright (C) All BPF authors and contributors from 2014 to present.
.. See git log include/uapi/linux/bpf.h in kernel tree for details.
..
.. %%%LICENSE_START(VERBATIM)
.. Permission is granted to make and distribute verbatim copies of this
.. manual provided the copyright notice and this permission notice are
.. preserved on all copies.
..
.. Permission is granted to copy and distribute modified versions of this
.. manual under the conditions for verbatim copying, provided that the
.. entire resulting derived work is distributed under the terms of a
.. permission notice identical to this one.
..
.. Since the Linux kernel and libraries are constantly changing, this
.. manual page may be incorrect or out-of-date. The author(s) assume no
.. responsibility for errors or omissions, or for damages resulting from
.. the use of the information contained herein. The author(s) may not
.. have taken the same level of care in the production of this manual,
.. which is licensed free of charge, as they might when working
.. professionally.
..
.. Formatted or processed versions of this manual, if unaccompanied by
.. the source, must acknowledge the copyright and authors of this work.
.. %%%LICENSE_END
..
.. Please do not edit this file. It was generated from the documentation
.. located in file include/uapi/linux/bpf.h of the Linux kernel sources
.. (helpers description), and from scripts/bpf_helpers_doc.py in the same
.. repository (header and footer).
===========
BPF-HELPERS
===========
-------------------------------------------------------------------------------
list of eBPF helper functions
-------------------------------------------------------------------------------
:Manual section: 7
DESCRIPTION
===========
The extended Berkeley Packet Filter (eBPF) subsystem consists in programs
written in a pseudo-assembly language, then attached to one of the several
kernel hooks and run in reaction of specific events. This framework differs
from the older, "classic" BPF (or "cBPF") in several aspects, one of them being
the ability to call special functions (or "helpers") from within a program.
These functions are restricted to a white-list of helpers defined in the
kernel.
These helpers are used by eBPF programs to interact with the system, or with
the context in which they work. For instance, they can be used to print
debugging messages, to get the time since the system was booted, to interact
with eBPF maps, or to manipulate network packets. Since there are several eBPF
program types, and that they do not run in the same context, each program type
can only call a subset of those helpers.
Due to eBPF conventions, a helper can not have more than five arguments.
Internally, eBPF programs call directly into the compiled helper functions
without requiring any foreign-function interface. As a result, calling helpers
introduces no overhead, thus offering excellent performance.
This document is an attempt to list and document the helpers available to eBPF
developers. They are sorted by chronological order (the oldest helpers in the
kernel at the top).
HELPERS
=======
**void \*bpf_map_lookup_elem(struct bpf_map \***\ *map*\ **, const void \***\ *key*\ **)**
Description
Perform a lookup in *map* for an entry associated to *key*.
Return
Map value associated to *key*, or **NULL** if no entry was
found.
**int bpf_map_update_elem(struct bpf_map \***\ *map*\ **, const void \***\ *key*\ **, const void \***\ *value*\ **, u64** *flags*\ **)**
Description
Add or update the value of the entry associated to *key* in
*map* with *value*. *flags* is one of:
**BPF_NOEXIST**
The entry for *key* must not exist in the map.
**BPF_EXIST**
The entry for *key* must already exist in the map.
**BPF_ANY**
No condition on the existence of the entry for *key*.
Flag value **BPF_NOEXIST** cannot be used for maps of types
**BPF_MAP_TYPE_ARRAY** or **BPF_MAP_TYPE_PERCPU_ARRAY** (all
elements always exist), the helper would return an error.
Return
0 on success, or a negative error in case of failure.
**int bpf_map_delete_elem(struct bpf_map \***\ *map*\ **, const void \***\ *key*\ **)**
Description
Delete entry with *key* from *map*.
Return
0 on success, or a negative error in case of failure.
**int bpf_probe_read(void \***\ *dst*\ **, u32** *size*\ **, const void \***\ *src*\ **)**
Description
For tracing programs, safely attempt to read *size* bytes from
address *src* and store the data in *dst*.
Return
0 on success, or a negative error in case of failure.
**u64 bpf_ktime_get_ns(void)**
Description
Return the time elapsed since system boot, in nanoseconds.
Return
Current *ktime*.
**int bpf_trace_printk(const char \***\ *fmt*\ **, u32** *fmt_size*\ **, ...)**
Description
This helper is a "printk()-like" facility for debugging. It
prints a message defined by format *fmt* (of size *fmt_size*)
to file *\/sys/kernel/debug/tracing/trace* from DebugFS, if
available. It can take up to three additional **u64**
arguments (as an eBPF helpers, the total number of arguments is
limited to five).
Each time the helper is called, it appends a line to the trace.
Lines are discarded while *\/sys/kernel/debug/tracing/trace* is
open, use *\/sys/kernel/debug/tracing/trace_pipe* to avoid this.
The format of the trace is customizable, and the exact output
one will get depends on the options set in
*\/sys/kernel/debug/tracing/trace_options* (see also the
*README* file under the same directory). However, it usually
defaults to something like:
::
telnet-470 [001] .N.. 419421.045894: 0x00000001: <formatted msg>
In the above:
* ``telnet`` is the name of the current task.
* ``470`` is the PID of the current task.
* ``001`` is the CPU number on which the task is
running.
* In ``.N..``, each character refers to a set of
options (whether irqs are enabled, scheduling
options, whether hard/softirqs are running, level of
preempt_disabled respectively). **N** means that
**TIF_NEED_RESCHED** and **PREEMPT_NEED_RESCHED**
are set.
* ``419421.045894`` is a timestamp.
* ``0x00000001`` is a fake value used by BPF for the
instruction pointer register.
* ``<formatted msg>`` is the message formatted with
*fmt*.
The conversion specifiers supported by *fmt* are similar, but
more limited than for printk(). They are **%d**, **%i**,
**%u**, **%x**, **%ld**, **%li**, **%lu**, **%lx**, **%lld**,
**%lli**, **%llu**, **%llx**, **%p**, **%s**. No modifier (size
of field, padding with zeroes, etc.) is available, and the
helper will return **-EINVAL** (but print nothing) if it
encounters an unknown specifier.
Also, note that **bpf_trace_printk**\ () is slow, and should
only be used for debugging purposes. For this reason, a notice
bloc (spanning several lines) is printed to kernel logs and
states that the helper should not be used "for production use"
the first time this helper is used (or more precisely, when
**trace_printk**\ () buffers are allocated). For passing values
to user space, perf events should be preferred.
Return
The number of bytes written to the buffer, or a negative error
in case of failure.
**u32 bpf_get_prandom_u32(void)**
Description
Get a pseudo-random number.
From a security point of view, this helper uses its own
pseudo-random internal state, and cannot be used to infer the
seed of other random functions in the kernel. However, it is
essential to note that the generator used by the helper is not
cryptographically secure.
Return
A random 32-bit unsigned value.
**u32 bpf_get_smp_processor_id(void)**
Description
Get the SMP (symmetric multiprocessing) processor id. Note that
all programs run with preemption disabled, which means that the
SMP processor id is stable during all the execution of the
program.
Return
The SMP id of the processor running the program.
**int bpf_skb_store_bytes(struct sk_buff \***\ *skb*\ **, u32** *offset*\ **, const void \***\ *from*\ **, u32** *len*\ **, u64** *flags*\ **)**
Description
Store *len* bytes from address *from* into the packet
associated to *skb*, at *offset*. *flags* are a combination of
**BPF_F_RECOMPUTE_CSUM** (automatically recompute the
checksum for the packet after storing the bytes) and
**BPF_F_INVALIDATE_HASH** (set *skb*\ **->hash**, *skb*\
**->swhash** and *skb*\ **->l4hash** to 0).
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_l3_csum_replace(struct sk_buff \***\ *skb*\ **, u32** *offset*\ **, u64** *from*\ **, u64** *to*\ **, u64** *size*\ **)**
Description
Recompute the layer 3 (e.g. IP) checksum for the packet
associated to *skb*. Computation is incremental, so the helper
must know the former value of the header field that was
modified (*from*), the new value of this field (*to*), and the
number of bytes (2 or 4) for this field, stored in *size*.
Alternatively, it is possible to store the difference between
the previous and the new values of the header field in *to*, by
setting *from* and *size* to 0. For both methods, *offset*
indicates the location of the IP checksum within the packet.
This helper works in combination with **bpf_csum_diff**\ (),
which does not update the checksum in-place, but offers more
flexibility and can handle sizes larger than 2 or 4 for the
checksum to update.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_l4_csum_replace(struct sk_buff \***\ *skb*\ **, u32** *offset*\ **, u64** *from*\ **, u64** *to*\ **, u64** *flags*\ **)**
Description
Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the
packet associated to *skb*. Computation is incremental, so the
helper must know the former value of the header field that was
modified (*from*), the new value of this field (*to*), and the
number of bytes (2 or 4) for this field, stored on the lowest
four bits of *flags*. Alternatively, it is possible to store
the difference between the previous and the new values of the
header field in *to*, by setting *from* and the four lowest
bits of *flags* to 0. For both methods, *offset* indicates the
location of the IP checksum within the packet. In addition to
the size of the field, *flags* can be added (bitwise OR) actual
flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is left
untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and
for updates resulting in a null checksum the value is set to
**CSUM_MANGLED_0** instead. Flag **BPF_F_PSEUDO_HDR** indicates
the checksum is to be computed against a pseudo-header.
This helper works in combination with **bpf_csum_diff**\ (),
which does not update the checksum in-place, but offers more
flexibility and can handle sizes larger than 2 or 4 for the
checksum to update.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_tail_call(void \***\ *ctx*\ **, struct bpf_map \***\ *prog_array_map*\ **, u32** *index*\ **)**
Description
This special helper is used to trigger a "tail call", or in
other words, to jump into another eBPF program. The same stack
frame is used (but values on stack and in registers for the
caller are not accessible to the callee). This mechanism allows
for program chaining, either for raising the maximum number of
available eBPF instructions, or to execute given programs in
conditional blocks. For security reasons, there is an upper
limit to the number of successive tail calls that can be
performed.
Upon call of this helper, the program attempts to jump into a
program referenced at index *index* in *prog_array_map*, a
special map of type **BPF_MAP_TYPE_PROG_ARRAY**, and passes
*ctx*, a pointer to the context.
If the call succeeds, the kernel immediately runs the first
instruction of the new program. This is not a function call,
and it never returns to the previous program. If the call
fails, then the helper has no effect, and the caller continues
to run its subsequent instructions. A call can fail if the
destination program for the jump does not exist (i.e. *index*
is superior to the number of entries in *prog_array_map*), or
if the maximum number of tail calls has been reached for this
chain of programs. This limit is defined in the kernel by the
macro **MAX_TAIL_CALL_CNT** (not accessible to user space),
which is currently set to 32.
Return
0 on success, or a negative error in case of failure.
**int bpf_clone_redirect(struct sk_buff \***\ *skb*\ **, u32** *ifindex*\ **, u64** *flags*\ **)**
Description
Clone and redirect the packet associated to *skb* to another
net device of index *ifindex*. Both ingress and egress
interfaces can be used for redirection. The **BPF_F_INGRESS**
value in *flags* is used to make the distinction (ingress path
is selected if the flag is present, egress path otherwise).
This is the only flag supported for now.
In comparison with **bpf_redirect**\ () helper,
**bpf_clone_redirect**\ () has the associated cost of
duplicating the packet buffer, but this can be executed out of
the eBPF program. Conversely, **bpf_redirect**\ () is more
efficient, but it is handled through an action code where the
redirection happens only after the eBPF program has returned.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**u64 bpf_get_current_pid_tgid(void)**
Return
A 64-bit integer containing the current tgid and pid, and
created as such:
*current_task*\ **->tgid << 32 \|**
*current_task*\ **->pid**.
**u64 bpf_get_current_uid_gid(void)**
Return
A 64-bit integer containing the current GID and UID, and
created as such: *current_gid* **<< 32 \|** *current_uid*.
**int bpf_get_current_comm(char \***\ *buf*\ **, u32** *size_of_buf*\ **)**
Description
Copy the **comm** attribute of the current task into *buf* of
*size_of_buf*. The **comm** attribute contains the name of
the executable (excluding the path) for the current task. The
*size_of_buf* must be strictly positive. On success, the
helper makes sure that the *buf* is NUL-terminated. On failure,
it is filled with zeroes.
Return
0 on success, or a negative error in case of failure.
**u32 bpf_get_cgroup_classid(struct sk_buff \***\ *skb*\ **)**
Description
Retrieve the classid for the current task, i.e. for the net_cls
cgroup to which *skb* belongs.
This helper can be used on TC egress path, but not on ingress.
The net_cls cgroup provides an interface to tag network packets
based on a user-provided identifier for all traffic coming from
the tasks belonging to the related cgroup. See also the related
kernel documentation, available from the Linux sources in file
*Documentation/admin-guide/cgroup-v1/net_cls.rst*.
The Linux kernel has two versions for cgroups: there are
cgroups v1 and cgroups v2. Both are available to users, who can
use a mixture of them, but note that the net_cls cgroup is for
cgroup v1 only. This makes it incompatible with BPF programs
run on cgroups, which is a cgroup-v2-only feature (a socket can
only hold data for one version of cgroups at a time).
This helper is only available is the kernel was compiled with
the **CONFIG_CGROUP_NET_CLASSID** configuration option set to
"**y**" or to "**m**".
Return
The classid, or 0 for the default unconfigured classid.
**int bpf_skb_vlan_push(struct sk_buff \***\ *skb*\ **, __be16** *vlan_proto*\ **, u16** *vlan_tci*\ **)**
Description
Push a *vlan_tci* (VLAN tag control information) of protocol
*vlan_proto* to the packet associated to *skb*, then update
the checksum. Note that if *vlan_proto* is different from
**ETH_P_8021Q** and **ETH_P_8021AD**, it is considered to
be **ETH_P_8021Q**.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_vlan_pop(struct sk_buff \***\ *skb*\ **)**
Description
Pop a VLAN header from the packet associated to *skb*.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_get_tunnel_key(struct sk_buff \***\ *skb*\ **, struct bpf_tunnel_key \***\ *key*\ **, u32** *size*\ **, u64** *flags*\ **)**
Description
Get tunnel metadata. This helper takes a pointer *key* to an
empty **struct bpf_tunnel_key** of **size**, that will be
filled with tunnel metadata for the packet associated to *skb*.
The *flags* can be set to **BPF_F_TUNINFO_IPV6**, which
indicates that the tunnel is based on IPv6 protocol instead of
IPv4.
The **struct bpf_tunnel_key** is an object that generalizes the
principal parameters used by various tunneling protocols into a
single struct. This way, it can be used to easily make a
decision based on the contents of the encapsulation header,
"summarized" in this struct. In particular, it holds the IP
address of the remote end (IPv4 or IPv6, depending on the case)
in *key*\ **->remote_ipv4** or *key*\ **->remote_ipv6**. Also,
this struct exposes the *key*\ **->tunnel_id**, which is
generally mapped to a VNI (Virtual Network Identifier), making
it programmable together with the **bpf_skb_set_tunnel_key**\
() helper.
Let's imagine that the following code is part of a program
attached to the TC ingress interface, on one end of a GRE
tunnel, and is supposed to filter out all messages coming from
remote ends with IPv4 address other than 10.0.0.1:
::
int ret;
struct bpf_tunnel_key key = {};
ret = bpf_skb_get_tunnel_key(skb, &key, sizeof(key), 0);
if (ret < 0)
return TC_ACT_SHOT; // drop packet
if (key.remote_ipv4 != 0x0a000001)
return TC_ACT_SHOT; // drop packet
return TC_ACT_OK; // accept packet
This interface can also be used with all encapsulation devices
that can operate in "collect metadata" mode: instead of having
one network device per specific configuration, the "collect
metadata" mode only requires a single device where the
configuration can be extracted from this helper.
This can be used together with various tunnels such as VXLan,
Geneve, GRE or IP in IP (IPIP).
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_set_tunnel_key(struct sk_buff \***\ *skb*\ **, struct bpf_tunnel_key \***\ *key*\ **, u32** *size*\ **, u64** *flags*\ **)**
Description
Populate tunnel metadata for packet associated to *skb.* The
tunnel metadata is set to the contents of *key*, of *size*. The
*flags* can be set to a combination of the following values:
**BPF_F_TUNINFO_IPV6**
Indicate that the tunnel is based on IPv6 protocol
instead of IPv4.
**BPF_F_ZERO_CSUM_TX**
For IPv4 packets, add a flag to tunnel metadata
indicating that checksum computation should be skipped
and checksum set to zeroes.
**BPF_F_DONT_FRAGMENT**
Add a flag to tunnel metadata indicating that the
packet should not be fragmented.
**BPF_F_SEQ_NUMBER**
Add a flag to tunnel metadata indicating that a
sequence number should be added to tunnel header before
sending the packet. This flag was added for GRE
encapsulation, but might be used with other protocols
as well in the future.
Here is a typical usage on the transmit path:
::
struct bpf_tunnel_key key;
populate key ...
bpf_skb_set_tunnel_key(skb, &key, sizeof(key), 0);
bpf_clone_redirect(skb, vxlan_dev_ifindex, 0);
See also the description of the **bpf_skb_get_tunnel_key**\ ()
helper for additional information.
Return
0 on success, or a negative error in case of failure.
**u64 bpf_perf_event_read(struct bpf_map \***\ *map*\ **, u64** *flags*\ **)**
Description
Read the value of a perf event counter. This helper relies on a
*map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of
the perf event counter is selected when *map* is updated with
perf event file descriptors. The *map* is an array whose size
is the number of available CPUs, and each cell contains a value
relative to one CPU. The value to retrieve is indicated by
*flags*, that contains the index of the CPU to look up, masked
with **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to
**BPF_F_CURRENT_CPU** to indicate that the value for the
current CPU should be retrieved.
Note that before Linux 4.13, only hardware perf event can be
retrieved.
Also, be aware that the newer helper
**bpf_perf_event_read_value**\ () is recommended over
**bpf_perf_event_read**\ () in general. The latter has some ABI
quirks where error and counter value are used as a return code
(which is wrong to do since ranges may overlap). This issue is
fixed with **bpf_perf_event_read_value**\ (), which at the same
time provides more features over the **bpf_perf_event_read**\
() interface. Please refer to the description of
**bpf_perf_event_read_value**\ () for details.
Return
The value of the perf event counter read from the map, or a
negative error code in case of failure.
**int bpf_redirect(u32** *ifindex*\ **, u64** *flags*\ **)**
Description
Redirect the packet to another net device of index *ifindex*.
This helper is somewhat similar to **bpf_clone_redirect**\
(), except that the packet is not cloned, which provides
increased performance.
Except for XDP, both ingress and egress interfaces can be used
for redirection. The **BPF_F_INGRESS** value in *flags* is used
to make the distinction (ingress path is selected if the flag
is present, egress path otherwise). Currently, XDP only
supports redirection to the egress interface, and accepts no
flag at all.
The same effect can be attained with the more generic
**bpf_redirect_map**\ (), which requires specific maps to be
used but offers better performance.
Return
For XDP, the helper returns **XDP_REDIRECT** on success or
**XDP_ABORTED** on error. For other program types, the values
are **TC_ACT_REDIRECT** on success or **TC_ACT_SHOT** on
error.
**u32 bpf_get_route_realm(struct sk_buff \***\ *skb*\ **)**
Description
Retrieve the realm or the route, that is to say the
**tclassid** field of the destination for the *skb*. The
indentifier retrieved is a user-provided tag, similar to the
one used with the net_cls cgroup (see description for
**bpf_get_cgroup_classid**\ () helper), but here this tag is
held by a route (a destination entry), not by a task.
Retrieving this identifier works with the clsact TC egress hook
(see also **tc-bpf(8)**), or alternatively on conventional
classful egress qdiscs, but not on TC ingress path. In case of
clsact TC egress hook, this has the advantage that, internally,
the destination entry has not been dropped yet in the transmit
path. Therefore, the destination entry does not need to be
artificially held via **netif_keep_dst**\ () for a classful
qdisc until the *skb* is freed.
This helper is available only if the kernel was compiled with
**CONFIG_IP_ROUTE_CLASSID** configuration option.
Return
The realm of the route for the packet associated to *skb*, or 0
if none was found.
**int bpf_perf_event_output(struct pt_regs \***\ *ctx*\ **, struct bpf_map \***\ *map*\ **, u64** *flags*\ **, void \***\ *data*\ **, u64** *size*\ **)**
Description
Write raw *data* blob into a special BPF perf event held by
*map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf
event must have the following attributes: **PERF_SAMPLE_RAW**
as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and
**PERF_COUNT_SW_BPF_OUTPUT** as **config**.
The *flags* are used to indicate the index in *map* for which
the value must be put, masked with **BPF_F_INDEX_MASK**.
Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU**
to indicate that the index of the current CPU core should be
used.
The value to write, of *size*, is passed through eBPF stack and
pointed by *data*.
The context of the program *ctx* needs also be passed to the
helper.
On user space, a program willing to read the values needs to
call **perf_event_open**\ () on the perf event (either for
one or for all CPUs) and to store the file descriptor into the
*map*. This must be done before the eBPF program can send data
into it. An example is available in file
*samples/bpf/trace_output_user.c* in the Linux kernel source
tree (the eBPF program counterpart is in
*samples/bpf/trace_output_kern.c*).
**bpf_perf_event_output**\ () achieves better performance
than **bpf_trace_printk**\ () for sharing data with user
space, and is much better suitable for streaming data from eBPF
programs.
Note that this helper is not restricted to tracing use cases
and can be used with programs attached to TC or XDP as well,
where it allows for passing data to user space listeners. Data
can be:
* Only custom structs,
* Only the packet payload, or
* A combination of both.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_load_bytes(const struct sk_buff \***\ *skb*\ **, u32** *offset*\ **, void \***\ *to*\ **, u32** *len*\ **)**
Description
This helper was provided as an easy way to load data from a
packet. It can be used to load *len* bytes from *offset* from
the packet associated to *skb*, into the buffer pointed by
*to*.
Since Linux 4.7, usage of this helper has mostly been replaced
by "direct packet access", enabling packet data to be
manipulated with *skb*\ **->data** and *skb*\ **->data_end**
pointing respectively to the first byte of packet data and to
the byte after the last byte of packet data. However, it
remains useful if one wishes to read large quantities of data
at once from a packet into the eBPF stack.
Return
0 on success, or a negative error in case of failure.
**int bpf_get_stackid(struct pt_regs \***\ *ctx*\ **, struct bpf_map \***\ *map*\ **, u64** *flags*\ **)**
Description
Walk a user or a kernel stack and return its id. To achieve
this, the helper needs *ctx*, which is a pointer to the context
on which the tracing program is executed, and a pointer to a
*map* of type **BPF_MAP_TYPE_STACK_TRACE**.
The last argument, *flags*, holds the number of stack frames to
skip (from 0 to 255), masked with
**BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set
a combination of the following flags:
**BPF_F_USER_STACK**
Collect a user space stack instead of a kernel stack.
**BPF_F_FAST_STACK_CMP**
Compare stacks by hash only.
**BPF_F_REUSE_STACKID**
If two different stacks hash into the same *stackid*,
discard the old one.
The stack id retrieved is a 32 bit long integer handle which
can be further combined with other data (including other stack
ids) and used as a key into maps. This can be useful for
generating a variety of graphs (such as flame graphs or off-cpu
graphs).
For walking a stack, this helper is an improvement over
**bpf_probe_read**\ (), which can be used with unrolled loops
but is not efficient and consumes a lot of eBPF instructions.
Instead, **bpf_get_stackid**\ () can collect up to
**PERF_MAX_STACK_DEPTH** both kernel and user frames. Note that
this limit can be controlled with the **sysctl** program, and
that it should be manually increased in order to profile long
user stacks (such as stacks for Java programs). To do so, use:
::
# sysctl kernel.perf_event_max_stack=<new value>
Return
The positive or null stack id on success, or a negative error
in case of failure.
**s64 bpf_csum_diff(__be32 \***\ *from*\ **, u32** *from_size*\ **, __be32 \***\ *to*\ **, u32** *to_size*\ **, __wsum** *seed*\ **)**
Description
Compute a checksum difference, from the raw buffer pointed by
*from*, of length *from_size* (that must be a multiple of 4),
towards the raw buffer pointed by *to*, of size *to_size*
(same remark). An optional *seed* can be added to the value
(this can be cascaded, the seed may come from a previous call
to the helper).
This is flexible enough to be used in several ways:
* With *from_size* == 0, *to_size* > 0 and *seed* set to
checksum, it can be used when pushing new data.
* With *from_size* > 0, *to_size* == 0 and *seed* set to
checksum, it can be used when removing data from a packet.
* With *from_size* > 0, *to_size* > 0 and *seed* set to 0, it
can be used to compute a diff. Note that *from_size* and
*to_size* do not need to be equal.
This helper can be used in combination with
**bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ (), to
which one can feed in the difference computed with
**bpf_csum_diff**\ ().
Return
The checksum result, or a negative error code in case of
failure.
**int bpf_skb_get_tunnel_opt(struct sk_buff \***\ *skb*\ **, u8 \***\ *opt*\ **, u32** *size*\ **)**
Description
Retrieve tunnel options metadata for the packet associated to
*skb*, and store the raw tunnel option data to the buffer *opt*
of *size*.
This helper can be used with encapsulation devices that can
operate in "collect metadata" mode (please refer to the related
note in the description of **bpf_skb_get_tunnel_key**\ () for
more details). A particular example where this can be used is
in combination with the Geneve encapsulation protocol, where it
allows for pushing (with **bpf_skb_get_tunnel_opt**\ () helper)
and retrieving arbitrary TLVs (Type-Length-Value headers) from
the eBPF program. This allows for full customization of these
headers.
Return
The size of the option data retrieved.
**int bpf_skb_set_tunnel_opt(struct sk_buff \***\ *skb*\ **, u8 \***\ *opt*\ **, u32** *size*\ **)**
Description
Set tunnel options metadata for the packet associated to *skb*
to the option data contained in the raw buffer *opt* of *size*.
See also the description of the **bpf_skb_get_tunnel_opt**\ ()
helper for additional information.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_change_proto(struct sk_buff \***\ *skb*\ **, __be16** *proto*\ **, u64** *flags*\ **)**
Description
Change the protocol of the *skb* to *proto*. Currently
supported are transition from IPv4 to IPv6, and from IPv6 to
IPv4. The helper takes care of the groundwork for the
transition, including resizing the socket buffer. The eBPF
program is expected to fill the new headers, if any, via
**skb_store_bytes**\ () and to recompute the checksums with
**bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\
(). The main case for this helper is to perform NAT64
operations out of an eBPF program.
Internally, the GSO type is marked as dodgy so that headers are
checked and segments are recalculated by the GSO/GRO engine.
The size for GSO target is adapted as well.
All values for *flags* are reserved for future usage, and must
be left at zero.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_change_type(struct sk_buff \***\ *skb*\ **, u32** *type*\ **)**
Description
Change the packet type for the packet associated to *skb*. This
comes down to setting *skb*\ **->pkt_type** to *type*, except
the eBPF program does not have a write access to *skb*\
**->pkt_type** beside this helper. Using a helper here allows
for graceful handling of errors.
The major use case is to change incoming *skb*s to
**PACKET_HOST** in a programmatic way instead of having to
recirculate via **redirect**\ (..., **BPF_F_INGRESS**), for
example.
Note that *type* only allows certain values. At this time, they
are:
**PACKET_HOST**
Packet is for us.
**PACKET_BROADCAST**
Send packet to all.
**PACKET_MULTICAST**
Send packet to group.
**PACKET_OTHERHOST**
Send packet to someone else.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_under_cgroup(struct sk_buff \***\ *skb*\ **, struct bpf_map \***\ *map*\ **, u32** *index*\ **)**
Description
Check whether *skb* is a descendant of the cgroup2 held by
*map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*.
Return
The return value depends on the result of the test, and can be:
* 0, if the *skb* failed the cgroup2 descendant test.
* 1, if the *skb* succeeded the cgroup2 descendant test.
* A negative error code, if an error occurred.
**u32 bpf_get_hash_recalc(struct sk_buff \***\ *skb*\ **)**
Description
Retrieve the hash of the packet, *skb*\ **->hash**. If it is
not set, in particular if the hash was cleared due to mangling,
recompute this hash. Later accesses to the hash can be done
directly with *skb*\ **->hash**.
Calling **bpf_set_hash_invalid**\ (), changing a packet
prototype with **bpf_skb_change_proto**\ (), or calling
**bpf_skb_store_bytes**\ () with the
**BPF_F_INVALIDATE_HASH** are actions susceptible to clear
the hash and to trigger a new computation for the next call to
**bpf_get_hash_recalc**\ ().
Return
The 32-bit hash.
**u64 bpf_get_current_task(void)**
Return
A pointer to the current task struct.
**int bpf_probe_write_user(void \***\ *dst*\ **, const void \***\ *src*\ **, u32** *len*\ **)**
Description
Attempt in a safe way to write *len* bytes from the buffer
*src* to *dst* in memory. It only works for threads that are in
user context, and *dst* must be a valid user space address.
This helper should not be used to implement any kind of
security mechanism because of TOC-TOU attacks, but rather to
debug, divert, and manipulate execution of semi-cooperative
processes.
Keep in mind that this feature is meant for experiments, and it
has a risk of crashing the system and running programs.
Therefore, when an eBPF program using this helper is attached,
a warning including PID and process name is printed to kernel
logs.
Return
0 on success, or a negative error in case of failure.
**int bpf_current_task_under_cgroup(struct bpf_map \***\ *map*\ **, u32** *index*\ **)**
Description
Check whether the probe is being run is the context of a given
subset of the cgroup2 hierarchy. The cgroup2 to test is held by
*map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*.
Return
The return value depends on the result of the test, and can be:
* 0, if the *skb* task belongs to the cgroup2.
* 1, if the *skb* task does not belong to the cgroup2.
* A negative error code, if an error occurred.
**int bpf_skb_change_tail(struct sk_buff \***\ *skb*\ **, u32** *len*\ **, u64** *flags*\ **)**
Description
Resize (trim or grow) the packet associated to *skb* to the
new *len*. The *flags* are reserved for future usage, and must
be left at zero.
The basic idea is that the helper performs the needed work to
change the size of the packet, then the eBPF program rewrites
the rest via helpers like **bpf_skb_store_bytes**\ (),
**bpf_l3_csum_replace**\ (), **bpf_l3_csum_replace**\ ()
and others. This helper is a slow path utility intended for
replies with control messages. And because it is targeted for
slow path, the helper itself can afford to be slow: it
implicitly linearizes, unclones and drops offloads from the
*skb*.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_pull_data(struct sk_buff \***\ *skb*\ **, u32** *len*\ **)**
Description
Pull in non-linear data in case the *skb* is non-linear and not
all of *len* are part of the linear section. Make *len* bytes
from *skb* readable and writable. If a zero value is passed for
*len*, then the whole length of the *skb* is pulled.
This helper is only needed for reading and writing with direct
packet access.
For direct packet access, testing that offsets to access
are within packet boundaries (test on *skb*\ **->data_end**) is
susceptible to fail if offsets are invalid, or if the requested
data is in non-linear parts of the *skb*. On failure the
program can just bail out, or in the case of a non-linear
buffer, use a helper to make the data available. The
**bpf_skb_load_bytes**\ () helper is a first solution to access
the data. Another one consists in using **bpf_skb_pull_data**
to pull in once the non-linear parts, then retesting and
eventually access the data.
At the same time, this also makes sure the *skb* is uncloned,
which is a necessary condition for direct write. As this needs
to be an invariant for the write part only, the verifier
detects writes and adds a prologue that is calling
**bpf_skb_pull_data()** to effectively unclone the *skb* from
the very beginning in case it is indeed cloned.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**s64 bpf_csum_update(struct sk_buff \***\ *skb*\ **, __wsum** *csum*\ **)**
Description
Add the checksum *csum* into *skb*\ **->csum** in case the
driver has supplied a checksum for the entire packet into that
field. Return an error otherwise. This helper is intended to be
used in combination with **bpf_csum_diff**\ (), in particular
when the checksum needs to be updated after data has been
written into the packet through direct packet access.
Return
The checksum on success, or a negative error code in case of
failure.
**void bpf_set_hash_invalid(struct sk_buff \***\ *skb*\ **)**
Description
Invalidate the current *skb*\ **->hash**. It can be used after
mangling on headers through direct packet access, in order to
indicate that the hash is outdated and to trigger a
recalculation the next time the kernel tries to access this
hash or when the **bpf_get_hash_recalc**\ () helper is called.
**int bpf_get_numa_node_id(void)**
Description
Return the id of the current NUMA node. The primary use case
for this helper is the selection of sockets for the local NUMA
node, when the program is attached to sockets using the
**SO_ATTACH_REUSEPORT_EBPF** option (see also **socket(7)**),
but the helper is also available to other eBPF program types,
similarly to **bpf_get_smp_processor_id**\ ().
Return
The id of current NUMA node.
**int bpf_skb_change_head(struct sk_buff \***\ *skb*\ **, u32** *len*\ **, u64** *flags*\ **)**
Description
Grows headroom of packet associated to *skb* and adjusts the
offset of the MAC header accordingly, adding *len* bytes of
space. It automatically extends and reallocates memory as
required.
This helper can be used on a layer 3 *skb* to push a MAC header
for redirection into a layer 2 device.
All values for *flags* are reserved for future usage, and must
be left at zero.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_xdp_adjust_head(struct xdp_buff \***\ *xdp_md*\ **, int** *delta*\ **)**
Description
Adjust (move) *xdp_md*\ **->data** by *delta* bytes. Note that
it is possible to use a negative value for *delta*. This helper
can be used to prepare the packet for pushing or popping
headers.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_probe_read_str(void \***\ *dst*\ **, int** *size*\ **, const void \***\ *unsafe_ptr*\ **)**
Description
Copy a NUL terminated string from an unsafe address
*unsafe_ptr* to *dst*. The *size* should include the
terminating NUL byte. In case the string length is smaller than
*size*, the target is not padded with further NUL bytes. If the
string length is larger than *size*, just *size*-1 bytes are
copied and the last byte is set to NUL.
On success, the length of the copied string is returned. This
makes this helper useful in tracing programs for reading
strings, and more importantly to get its length at runtime. See
the following snippet:
::
SEC("kprobe/sys_open")
void bpf_sys_open(struct pt_regs *ctx)
{
char buf[PATHLEN]; // PATHLEN is defined to 256
int res = bpf_probe_read_str(buf, sizeof(buf),
ctx->di);
// Consume buf, for example push it to
// userspace via bpf_perf_event_output(); we
// can use res (the string length) as event
// size, after checking its boundaries.
}
In comparison, using **bpf_probe_read()** helper here instead
to read the string would require to estimate the length at
compile time, and would often result in copying more memory
than necessary.
Another useful use case is when parsing individual process
arguments or individual environment variables navigating
*current*\ **->mm->arg_start** and *current*\
**->mm->env_start**: using this helper and the return value,
one can quickly iterate at the right offset of the memory area.
Return
On success, the strictly positive length of the string,
including the trailing NUL character. On error, a negative
value.
**u64 bpf_get_socket_cookie(struct sk_buff \***\ *skb*\ **)**
Description
If the **struct sk_buff** pointed by *skb* has a known socket,
retrieve the cookie (generated by the kernel) of this socket.
If no cookie has been set yet, generate a new cookie. Once
generated, the socket cookie remains stable for the life of the
socket. This helper can be useful for monitoring per socket
networking traffic statistics as it provides a global socket
identifier that can be assumed unique.
Return
A 8-byte long non-decreasing number on success, or 0 if the
socket field is missing inside *skb*.
**u64 bpf_get_socket_cookie(struct bpf_sock_addr \***\ *ctx*\ **)**
Description
Equivalent to bpf_get_socket_cookie() helper that accepts
*skb*, but gets socket from **struct bpf_sock_addr** context.
Return
A 8-byte long non-decreasing number.
**u64 bpf_get_socket_cookie(struct bpf_sock_ops \***\ *ctx*\ **)**
Description
Equivalent to bpf_get_socket_cookie() helper that accepts
*skb*, but gets socket from **struct bpf_sock_ops** context.
Return
A 8-byte long non-decreasing number.
**u32 bpf_get_socket_uid(struct sk_buff \***\ *skb*\ **)**
Return
The owner UID of the socket associated to *skb*. If the socket
is **NULL**, or if it is not a full socket (i.e. if it is a
time-wait or a request socket instead), **overflowuid** value
is returned (note that **overflowuid** might also be the actual
UID value for the socket).
**u32 bpf_set_hash(struct sk_buff \***\ *skb*\ **, u32** *hash*\ **)**
Description
Set the full hash for *skb* (set the field *skb*\ **->hash**)
to value *hash*.
Return
0
**int bpf_setsockopt(struct bpf_sock_ops \***\ *bpf_socket*\ **, int** *level*\ **, int** *optname*\ **, char \***\ *optval*\ **, int** *optlen*\ **)**
Description
Emulate a call to **setsockopt()** on the socket associated to
*bpf_socket*, which must be a full socket. The *level* at
which the option resides and the name *optname* of the option
must be specified, see **setsockopt(2)** for more information.
The option value of length *optlen* is pointed by *optval*.
This helper actually implements a subset of **setsockopt()**.
It supports the following *level*\ s:
* **SOL_SOCKET**, which supports the following *optname*\ s:
**SO_RCVBUF**, **SO_SNDBUF**, **SO_MAX_PACING_RATE**,
**SO_PRIORITY**, **SO_RCVLOWAT**, **SO_MARK**.
* **IPPROTO_TCP**, which supports the following *optname*\ s:
**TCP_CONGESTION**, **TCP_BPF_IW**,
**TCP_BPF_SNDCWND_CLAMP**.
* **IPPROTO_IP**, which supports *optname* **IP_TOS**.
* **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_adjust_room(struct sk_buff \***\ *skb*\ **, s32** *len_diff*\ **, u32** *mode*\ **, u64** *flags*\ **)**
Description
Grow or shrink the room for data in the packet associated to
*skb* by *len_diff*, and according to the selected *mode*.
There are two supported modes at this time:
* **BPF_ADJ_ROOM_MAC**: Adjust room at the mac layer
(room space is added or removed below the layer 2 header).
* **BPF_ADJ_ROOM_NET**: Adjust room at the network layer
(room space is added or removed below the layer 3 header).
The following flags are supported at this time:
* **BPF_F_ADJ_ROOM_FIXED_GSO**: Do not adjust gso_size.
Adjusting mss in this way is not allowed for datagrams.
* **BPF_F_ADJ_ROOM_ENCAP_L3_IPV4**,
**BPF_F_ADJ_ROOM_ENCAP_L3_IPV6**:
Any new space is reserved to hold a tunnel header.
Configure skb offsets and other fields accordingly.
* **BPF_F_ADJ_ROOM_ENCAP_L4_GRE**,
**BPF_F_ADJ_ROOM_ENCAP_L4_UDP**:
Use with ENCAP_L3 flags to further specify the tunnel type.
* **BPF_F_ADJ_ROOM_ENCAP_L2**\ (*len*):
Use with ENCAP_L3/L4 flags to further specify the tunnel
type; *len* is the length of the inner MAC header.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_redirect_map(struct bpf_map \***\ *map*\ **, u32** *key*\ **, u64** *flags*\ **)**
Description
Redirect the packet to the endpoint referenced by *map* at
index *key*. Depending on its type, this *map* can contain
references to net devices (for forwarding packets through other
ports), or to CPUs (for redirecting XDP frames to another CPU;
but this is only implemented for native XDP (with driver
support) as of this writing).
The lower two bits of *flags* are used as the return code if
the map lookup fails. This is so that the return value can be
one of the XDP program return codes up to XDP_TX, as chosen by
the caller. Any higher bits in the *flags* argument must be
unset.
When used to redirect packets to net devices, this helper
provides a high performance increase over **bpf_redirect**\ ().
This is due to various implementation details of the underlying
mechanisms, one of which is the fact that **bpf_redirect_map**\
() tries to send packet as a "bulk" to the device.
Return
**XDP_REDIRECT** on success, or **XDP_ABORTED** on error.
**int bpf_sk_redirect_map(struct bpf_map \***\ *map*\ **, u32** *key*\ **, u64** *flags*\ **)**
Description
Redirect the packet to the socket referenced by *map* (of type
**BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and
egress interfaces can be used for redirection. The
**BPF_F_INGRESS** value in *flags* is used to make the
distinction (ingress path is selected if the flag is present,
egress path otherwise). This is the only flag supported for now.
Return
**SK_PASS** on success, or **SK_DROP** on error.
**int bpf_sock_map_update(struct bpf_sock_ops \***\ *skops*\ **, struct bpf_map \***\ *map*\ **, void \***\ *key*\ **, u64** *flags*\ **)**
Description
Add an entry to, or update a *map* referencing sockets. The
*skops* is used as a new value for the entry associated to
*key*. *flags* is one of:
**BPF_NOEXIST**
The entry for *key* must not exist in the map.
**BPF_EXIST**
The entry for *key* must already exist in the map.
**BPF_ANY**
No condition on the existence of the entry for *key*.
If the *map* has eBPF programs (parser and verdict), those will
be inherited by the socket being added. If the socket is
already attached to eBPF programs, this results in an error.
Return
0 on success, or a negative error in case of failure.
**int bpf_xdp_adjust_meta(struct xdp_buff \***\ *xdp_md*\ **, int** *delta*\ **)**
Description
Adjust the address pointed by *xdp_md*\ **->data_meta** by
*delta* (which can be positive or negative). Note that this
operation modifies the address stored in *xdp_md*\ **->data**,
so the latter must be loaded only after the helper has been
called.
The use of *xdp_md*\ **->data_meta** is optional and programs
are not required to use it. The rationale is that when the
packet is processed with XDP (e.g. as DoS filter), it is
possible to push further meta data along with it before passing
to the stack, and to give the guarantee that an ingress eBPF
program attached as a TC classifier on the same device can pick
this up for further post-processing. Since TC works with socket
buffers, it remains possible to set from XDP the **mark** or
**priority** pointers, or other pointers for the socket buffer.
Having this scratch space generic and programmable allows for
more flexibility as the user is free to store whatever meta
data they need.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_perf_event_read_value(struct bpf_map \***\ *map*\ **, u64** *flags*\ **, struct bpf_perf_event_value \***\ *buf*\ **, u32** *buf_size*\ **)**
Description
Read the value of a perf event counter, and store it into *buf*
of size *buf_size*. This helper relies on a *map* of type
**BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of the perf event
counter is selected when *map* is updated with perf event file
descriptors. The *map* is an array whose size is the number of
available CPUs, and each cell contains a value relative to one
CPU. The value to retrieve is indicated by *flags*, that
contains the index of the CPU to look up, masked with
**BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to
**BPF_F_CURRENT_CPU** to indicate that the value for the
current CPU should be retrieved.
This helper behaves in a way close to
**bpf_perf_event_read**\ () helper, save that instead of
just returning the value observed, it fills the *buf*
structure. This allows for additional data to be retrieved: in
particular, the enabled and running times (in *buf*\
**->enabled** and *buf*\ **->running**, respectively) are
copied. In general, **bpf_perf_event_read_value**\ () is
recommended over **bpf_perf_event_read**\ (), which has some
ABI issues and provides fewer functionalities.
These values are interesting, because hardware PMU (Performance
Monitoring Unit) counters are limited resources. When there are
more PMU based perf events opened than available counters,
kernel will multiplex these events so each event gets certain
percentage (but not all) of the PMU time. In case that
multiplexing happens, the number of samples or counter value
will not reflect the case compared to when no multiplexing
occurs. This makes comparison between different runs difficult.
Typically, the counter value should be normalized before
comparing to other experiments. The usual normalization is done
as follows.
::
normalized_counter = counter * t_enabled / t_running
Where t_enabled is the time enabled for event and t_running is
the time running for event since last normalization. The
enabled and running times are accumulated since the perf event
open. To achieve scaling factor between two invocations of an
eBPF program, users can can use CPU id as the key (which is
typical for perf array usage model) to remember the previous
value and do the calculation inside the eBPF program.
Return
0 on success, or a negative error in case of failure.
**int bpf_perf_prog_read_value(struct bpf_perf_event_data \***\ *ctx*\ **, struct bpf_perf_event_value \***\ *buf*\ **, u32** *buf_size*\ **)**
Description
For en eBPF program attached to a perf event, retrieve the
value of the event counter associated to *ctx* and store it in
the structure pointed by *buf* and of size *buf_size*. Enabled
and running times are also stored in the structure (see
description of helper **bpf_perf_event_read_value**\ () for
more details).
Return
0 on success, or a negative error in case of failure.
**int bpf_getsockopt(struct bpf_sock_ops \***\ *bpf_socket*\ **, int** *level*\ **, int** *optname*\ **, char \***\ *optval*\ **, int** *optlen*\ **)**
Description
Emulate a call to **getsockopt()** on the socket associated to
*bpf_socket*, which must be a full socket. The *level* at
which the option resides and the name *optname* of the option
must be specified, see **getsockopt(2)** for more information.
The retrieved value is stored in the structure pointed by
*opval* and of length *optlen*.
This helper actually implements a subset of **getsockopt()**.
It supports the following *level*\ s:
* **IPPROTO_TCP**, which supports *optname*
**TCP_CONGESTION**.
* **IPPROTO_IP**, which supports *optname* **IP_TOS**.
* **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**.
Return
0 on success, or a negative error in case of failure.
**int bpf_override_return(struct pt_regs \***\ *regs*\ **, u64** *rc*\ **)**
Description
Used for error injection, this helper uses kprobes to override
the return value of the probed function, and to set it to *rc*.
The first argument is the context *regs* on which the kprobe
works.
This helper works by setting setting the PC (program counter)
to an override function which is run in place of the original
probed function. This means the probed function is not run at
all. The replacement function just returns with the required
value.
This helper has security implications, and thus is subject to
restrictions. It is only available if the kernel was compiled
with the **CONFIG_BPF_KPROBE_OVERRIDE** configuration
option, and in this case it only works on functions tagged with
**ALLOW_ERROR_INJECTION** in the kernel code.
Also, the helper is only available for the architectures having
the CONFIG_FUNCTION_ERROR_INJECTION option. As of this writing,
x86 architecture is the only one to support this feature.
Return
0
**int bpf_sock_ops_cb_flags_set(struct bpf_sock_ops \***\ *bpf_sock*\ **, int** *argval*\ **)**
Description
Attempt to set the value of the **bpf_sock_ops_cb_flags** field
for the full TCP socket associated to *bpf_sock_ops* to
*argval*.
The primary use of this field is to determine if there should
be calls to eBPF programs of type
**BPF_PROG_TYPE_SOCK_OPS** at various points in the TCP
code. A program of the same type can change its value, per
connection and as necessary, when the connection is
established. This field is directly accessible for reading, but
this helper must be used for updates in order to return an
error if an eBPF program tries to set a callback that is not
supported in the current kernel.
*argval* is a flag array which can combine these flags:
* **BPF_SOCK_OPS_RTO_CB_FLAG** (retransmission time out)
* **BPF_SOCK_OPS_RETRANS_CB_FLAG** (retransmission)
* **BPF_SOCK_OPS_STATE_CB_FLAG** (TCP state change)
* **BPF_SOCK_OPS_RTT_CB_FLAG** (every RTT)
Therefore, this function can be used to clear a callback flag by
setting the appropriate bit to zero. e.g. to disable the RTO
callback:
**bpf_sock_ops_cb_flags_set(bpf_sock,**
**bpf_sock->bpf_sock_ops_cb_flags & ~BPF_SOCK_OPS_RTO_CB_FLAG)**
Here are some examples of where one could call such eBPF
program:
* When RTO fires.
* When a packet is retransmitted.
* When the connection terminates.
* When a packet is sent.
* When a packet is received.
Return
Code **-EINVAL** if the socket is not a full TCP socket;
otherwise, a positive number containing the bits that could not
be set is returned (which comes down to 0 if all bits were set
as required).
**int bpf_msg_redirect_map(struct sk_msg_buff \***\ *msg*\ **, struct bpf_map \***\ *map*\ **, u32** *key*\ **, u64** *flags*\ **)**
Description
This helper is used in programs implementing policies at the
socket level. If the message *msg* is allowed to pass (i.e. if
the verdict eBPF program returns **SK_PASS**), redirect it to
the socket referenced by *map* (of type
**BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and
egress interfaces can be used for redirection. The
**BPF_F_INGRESS** value in *flags* is used to make the
distinction (ingress path is selected if the flag is present,
egress path otherwise). This is the only flag supported for now.
Return
**SK_PASS** on success, or **SK_DROP** on error.
**int bpf_msg_apply_bytes(struct sk_msg_buff \***\ *msg*\ **, u32** *bytes*\ **)**
Description
For socket policies, apply the verdict of the eBPF program to
the next *bytes* (number of bytes) of message *msg*.
For example, this helper can be used in the following cases:
* A single **sendmsg**\ () or **sendfile**\ () system call
contains multiple logical messages that the eBPF program is
supposed to read and for which it should apply a verdict.
* An eBPF program only cares to read the first *bytes* of a
*msg*. If the message has a large payload, then setting up
and calling the eBPF program repeatedly for all bytes, even
though the verdict is already known, would create unnecessary
overhead.
When called from within an eBPF program, the helper sets a
counter internal to the BPF infrastructure, that is used to
apply the last verdict to the next *bytes*. If *bytes* is
smaller than the current data being processed from a
**sendmsg**\ () or **sendfile**\ () system call, the first
*bytes* will be sent and the eBPF program will be re-run with
the pointer for start of data pointing to byte number *bytes*
**+ 1**. If *bytes* is larger than the current data being
processed, then the eBPF verdict will be applied to multiple
**sendmsg**\ () or **sendfile**\ () calls until *bytes* are
consumed.
Note that if a socket closes with the internal counter holding
a non-zero value, this is not a problem because data is not
being buffered for *bytes* and is sent as it is received.
Return
0
**int bpf_msg_cork_bytes(struct sk_msg_buff \***\ *msg*\ **, u32** *bytes*\ **)**
Description
For socket policies, prevent the execution of the verdict eBPF
program for message *msg* until *bytes* (byte number) have been
accumulated.
This can be used when one needs a specific number of bytes
before a verdict can be assigned, even if the data spans
multiple **sendmsg**\ () or **sendfile**\ () calls. The extreme
case would be a user calling **sendmsg**\ () repeatedly with
1-byte long message segments. Obviously, this is bad for
performance, but it is still valid. If the eBPF program needs
*bytes* bytes to validate a header, this helper can be used to
prevent the eBPF program to be called again until *bytes* have
been accumulated.
Return
0
**int bpf_msg_pull_data(struct sk_msg_buff \***\ *msg*\ **, u32** *start*\ **, u32** *end*\ **, u64** *flags*\ **)**
Description
For socket policies, pull in non-linear data from user space
for *msg* and set pointers *msg*\ **->data** and *msg*\
**->data_end** to *start* and *end* bytes offsets into *msg*,
respectively.
If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a
*msg* it can only parse data that the (**data**, **data_end**)
pointers have already consumed. For **sendmsg**\ () hooks this
is likely the first scatterlist element. But for calls relying
on the **sendpage** handler (e.g. **sendfile**\ ()) this will
be the range (**0**, **0**) because the data is shared with
user space and by default the objective is to avoid allowing
user space to modify data while (or after) eBPF verdict is
being decided. This helper can be used to pull in data and to
set the start and end pointer to given values. Data will be
copied if necessary (i.e. if data was not linear and if start
and end pointers do not point to the same chunk).
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
All values for *flags* are reserved for future usage, and must
be left at zero.
Return
0 on success, or a negative error in case of failure.
**int bpf_bind(struct bpf_sock_addr \***\ *ctx*\ **, struct sockaddr \***\ *addr*\ **, int** *addr_len*\ **)**
Description
Bind the socket associated to *ctx* to the address pointed by
*addr*, of length *addr_len*. This allows for making outgoing
connection from the desired IP address, which can be useful for
example when all processes inside a cgroup should use one
single IP address on a host that has multiple IP configured.
This helper works for IPv4 and IPv6, TCP and UDP sockets. The
domain (*addr*\ **->sa_family**) must be **AF_INET** (or
**AF_INET6**). Looking for a free port to bind to can be
expensive, therefore binding to port is not permitted by the
helper: *addr*\ **->sin_port** (or **sin6_port**, respectively)
must be set to zero.
Return
0 on success, or a negative error in case of failure.
**int bpf_xdp_adjust_tail(struct xdp_buff \***\ *xdp_md*\ **, int** *delta*\ **)**
Description
Adjust (move) *xdp_md*\ **->data_end** by *delta* bytes. It is
only possible to shrink the packet as of this writing,
therefore *delta* must be a negative integer.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_skb_get_xfrm_state(struct sk_buff \***\ *skb*\ **, u32** *index*\ **, struct bpf_xfrm_state \***\ *xfrm_state*\ **, u32** *size*\ **, u64** *flags*\ **)**
Description
Retrieve the XFRM state (IP transform framework, see also
**ip-xfrm(8)**) at *index* in XFRM "security path" for *skb*.
The retrieved value is stored in the **struct bpf_xfrm_state**
pointed by *xfrm_state* and of length *size*.
All values for *flags* are reserved for future usage, and must
be left at zero.
This helper is available only if the kernel was compiled with
**CONFIG_XFRM** configuration option.
Return
0 on success, or a negative error in case of failure.
**int bpf_get_stack(struct pt_regs \***\ *regs*\ **, void \***\ *buf*\ **, u32** *size*\ **, u64** *flags*\ **)**
Description
Return a user or a kernel stack in bpf program provided buffer.
To achieve this, the helper needs *ctx*, which is a pointer
to the context on which the tracing program is executed.
To store the stacktrace, the bpf program provides *buf* with
a nonnegative *size*.
The last argument, *flags*, holds the number of stack frames to
skip (from 0 to 255), masked with
**BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set
the following flags:
**BPF_F_USER_STACK**
Collect a user space stack instead of a kernel stack.
**BPF_F_USER_BUILD_ID**
Collect buildid+offset instead of ips for user stack,
only valid if **BPF_F_USER_STACK** is also specified.
**bpf_get_stack**\ () can collect up to
**PERF_MAX_STACK_DEPTH** both kernel and user frames, subject
to sufficient large buffer size. Note that
this limit can be controlled with the **sysctl** program, and
that it should be manually increased in order to profile long
user stacks (such as stacks for Java programs). To do so, use:
::
# sysctl kernel.perf_event_max_stack=<new value>
Return
A non-negative value equal to or less than *size* on success,
or a negative error in case of failure.
**int bpf_skb_load_bytes_relative(const struct sk_buff \***\ *skb*\ **, u32** *offset*\ **, void \***\ *to*\ **, u32** *len*\ **, u32** *start_header*\ **)**
Description
This helper is similar to **bpf_skb_load_bytes**\ () in that
it provides an easy way to load *len* bytes from *offset*
from the packet associated to *skb*, into the buffer pointed
by *to*. The difference to **bpf_skb_load_bytes**\ () is that
a fifth argument *start_header* exists in order to select a
base offset to start from. *start_header* can be one of:
**BPF_HDR_START_MAC**
Base offset to load data from is *skb*'s mac header.
**BPF_HDR_START_NET**
Base offset to load data from is *skb*'s network header.
In general, "direct packet access" is the preferred method to
access packet data, however, this helper is in particular useful
in socket filters where *skb*\ **->data** does not always point
to the start of the mac header and where "direct packet access"
is not available.
Return
0 on success, or a negative error in case of failure.
**int bpf_fib_lookup(void \***\ *ctx*\ **, struct bpf_fib_lookup \***\ *params*\ **, int** *plen*\ **, u32** *flags*\ **)**
Description
Do FIB lookup in kernel tables using parameters in *params*.
If lookup is successful and result shows packet is to be
forwarded, the neighbor tables are searched for the nexthop.
If successful (ie., FIB lookup shows forwarding and nexthop
is resolved), the nexthop address is returned in ipv4_dst
or ipv6_dst based on family, smac is set to mac address of
egress device, dmac is set to nexthop mac address, rt_metric
is set to metric from route (IPv4/IPv6 only), and ifindex
is set to the device index of the nexthop from the FIB lookup.
*plen* argument is the size of the passed in struct.
*flags* argument can be a combination of one or more of the
following values:
**BPF_FIB_LOOKUP_DIRECT**
Do a direct table lookup vs full lookup using FIB
rules.
**BPF_FIB_LOOKUP_OUTPUT**
Perform lookup from an egress perspective (default is
ingress).
*ctx* is either **struct xdp_md** for XDP programs or
**struct sk_buff** tc cls_act programs.
Return
* < 0 if any input argument is invalid
* 0 on success (packet is forwarded, nexthop neighbor exists)
* > 0 one of **BPF_FIB_LKUP_RET_** codes explaining why the
packet is not forwarded or needs assist from full stack
**int bpf_sock_hash_update(struct bpf_sock_ops_kern \***\ *skops*\ **, struct bpf_map \***\ *map*\ **, void \***\ *key*\ **, u64** *flags*\ **)**
Description
Add an entry to, or update a sockhash *map* referencing sockets.
The *skops* is used as a new value for the entry associated to
*key*. *flags* is one of:
**BPF_NOEXIST**
The entry for *key* must not exist in the map.
**BPF_EXIST**
The entry for *key* must already exist in the map.
**BPF_ANY**
No condition on the existence of the entry for *key*.
If the *map* has eBPF programs (parser and verdict), those will
be inherited by the socket being added. If the socket is
already attached to eBPF programs, this results in an error.
Return
0 on success, or a negative error in case of failure.
**int bpf_msg_redirect_hash(struct sk_msg_buff \***\ *msg*\ **, struct bpf_map \***\ *map*\ **, void \***\ *key*\ **, u64** *flags*\ **)**
Description
This helper is used in programs implementing policies at the
socket level. If the message *msg* is allowed to pass (i.e. if
the verdict eBPF program returns **SK_PASS**), redirect it to
the socket referenced by *map* (of type
**BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and
egress interfaces can be used for redirection. The
**BPF_F_INGRESS** value in *flags* is used to make the
distinction (ingress path is selected if the flag is present,
egress path otherwise). This is the only flag supported for now.
Return
**SK_PASS** on success, or **SK_DROP** on error.
**int bpf_sk_redirect_hash(struct sk_buff \***\ *skb*\ **, struct bpf_map \***\ *map*\ **, void \***\ *key*\ **, u64** *flags*\ **)**
Description
This helper is used in programs implementing policies at the
skb socket level. If the sk_buff *skb* is allowed to pass (i.e.
if the verdeict eBPF program returns **SK_PASS**), redirect it
to the socket referenced by *map* (of type
**BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and
egress interfaces can be used for redirection. The
**BPF_F_INGRESS** value in *flags* is used to make the
distinction (ingress path is selected if the flag is present,
egress otherwise). This is the only flag supported for now.
Return
**SK_PASS** on success, or **SK_DROP** on error.
**int bpf_lwt_push_encap(struct sk_buff \***\ *skb*\ **, u32** *type*\ **, void \***\ *hdr*\ **, u32** *len*\ **)**
Description
Encapsulate the packet associated to *skb* within a Layer 3
protocol header. This header is provided in the buffer at
address *hdr*, with *len* its size in bytes. *type* indicates
the protocol of the header and can be one of:
**BPF_LWT_ENCAP_SEG6**
IPv6 encapsulation with Segment Routing Header
(**struct ipv6_sr_hdr**). *hdr* only contains the SRH,
the IPv6 header is computed by the kernel.
**BPF_LWT_ENCAP_SEG6_INLINE**
Only works if *skb* contains an IPv6 packet. Insert a
Segment Routing Header (**struct ipv6_sr_hdr**) inside
the IPv6 header.
**BPF_LWT_ENCAP_IP**
IP encapsulation (GRE/GUE/IPIP/etc). The outer header
must be IPv4 or IPv6, followed by zero or more
additional headers, up to **LWT_BPF_MAX_HEADROOM**
total bytes in all prepended headers. Please note that
if **skb_is_gso**\ (*skb*) is true, no more than two
headers can be prepended, and the inner header, if
present, should be either GRE or UDP/GUE.
**BPF_LWT_ENCAP_SEG6**\ \* types can be called by BPF programs
of type **BPF_PROG_TYPE_LWT_IN**; **BPF_LWT_ENCAP_IP** type can
be called by bpf programs of types **BPF_PROG_TYPE_LWT_IN** and
**BPF_PROG_TYPE_LWT_XMIT**.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_lwt_seg6_store_bytes(struct sk_buff \***\ *skb*\ **, u32** *offset*\ **, const void \***\ *from*\ **, u32** *len*\ **)**
Description
Store *len* bytes from address *from* into the packet
associated to *skb*, at *offset*. Only the flags, tag and TLVs
inside the outermost IPv6 Segment Routing Header can be
modified through this helper.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_lwt_seg6_adjust_srh(struct sk_buff \***\ *skb*\ **, u32** *offset*\ **, s32** *delta*\ **)**
Description
Adjust the size allocated to TLVs in the outermost IPv6
Segment Routing Header contained in the packet associated to
*skb*, at position *offset* by *delta* bytes. Only offsets
after the segments are accepted. *delta* can be as well
positive (growing) as negative (shrinking).
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_lwt_seg6_action(struct sk_buff \***\ *skb*\ **, u32** *action*\ **, void \***\ *param*\ **, u32** *param_len*\ **)**
Description
Apply an IPv6 Segment Routing action of type *action* to the
packet associated to *skb*. Each action takes a parameter
contained at address *param*, and of length *param_len* bytes.
*action* can be one of:
**SEG6_LOCAL_ACTION_END_X**
End.X action: Endpoint with Layer-3 cross-connect.
Type of *param*: **struct in6_addr**.
**SEG6_LOCAL_ACTION_END_T**
End.T action: Endpoint with specific IPv6 table lookup.
Type of *param*: **int**.
**SEG6_LOCAL_ACTION_END_B6**
End.B6 action: Endpoint bound to an SRv6 policy.
Type of *param*: **struct ipv6_sr_hdr**.
**SEG6_LOCAL_ACTION_END_B6_ENCAP**
End.B6.Encap action: Endpoint bound to an SRv6
encapsulation policy.
Type of *param*: **struct ipv6_sr_hdr**.
A call to this helper is susceptible to change the underlying
packet buffer. Therefore, at load time, all checks on pointers
previously done by the verifier are invalidated and must be
performed again, if the helper is used in combination with
direct packet access.
Return
0 on success, or a negative error in case of failure.
**int bpf_rc_repeat(void \***\ *ctx*\ **)**
Description
This helper is used in programs implementing IR decoding, to
report a successfully decoded repeat key message. This delays
the generation of a key up event for previously generated
key down event.
Some IR protocols like NEC have a special IR message for
repeating last button, for when a button is held down.
The *ctx* should point to the lirc sample as passed into
the program.
This helper is only available is the kernel was compiled with
the **CONFIG_BPF_LIRC_MODE2** configuration option set to
"**y**".
Return
0
**int bpf_rc_keydown(void \***\ *ctx*\ **, u32** *protocol*\ **, u64** *scancode*\ **, u32** *toggle*\ **)**
Description
This helper is used in programs implementing IR decoding, to
report a successfully decoded key press with *scancode*,
*toggle* value in the given *protocol*. The scancode will be
translated to a keycode using the rc keymap, and reported as
an input key down event. After a period a key up event is
generated. This period can be extended by calling either
**bpf_rc_keydown**\ () again with the same values, or calling
**bpf_rc_repeat**\ ().
Some protocols include a toggle bit, in case the button was
released and pressed again between consecutive scancodes.
The *ctx* should point to the lirc sample as passed into
the program.
The *protocol* is the decoded protocol number (see
**enum rc_proto** for some predefined values).
This helper is only available is the kernel was compiled with
the **CONFIG_BPF_LIRC_MODE2** configuration option set to
"**y**".
Return
0
**u64 bpf_skb_cgroup_id(struct sk_buff \***\ *skb*\ **)**
Description
Return the cgroup v2 id of the socket associated with the *skb*.
This is roughly similar to the **bpf_get_cgroup_classid**\ ()
helper for cgroup v1 by providing a tag resp. identifier that
can be matched on or used for map lookups e.g. to implement
policy. The cgroup v2 id of a given path in the hierarchy is
exposed in user space through the f_handle API in order to get
to the same 64-bit id.
This helper can be used on TC egress path, but not on ingress,
and is available only if the kernel was compiled with the
**CONFIG_SOCK_CGROUP_DATA** configuration option.
Return
The id is returned or 0 in case the id could not be retrieved.
**u64 bpf_get_current_cgroup_id(void)**
Return
A 64-bit integer containing the current cgroup id based
on the cgroup within which the current task is running.
**void \*bpf_get_local_storage(void \***\ *map*\ **, u64** *flags*\ **)**
Description
Get the pointer to the local storage area.
The type and the size of the local storage is defined
by the *map* argument.
The *flags* meaning is specific for each map type,
and has to be 0 for cgroup local storage.
Depending on the BPF program type, a local storage area
can be shared between multiple instances of the BPF program,
running simultaneously.
A user should care about the synchronization by himself.
For example, by using the **BPF_STX_XADD** instruction to alter
the shared data.
Return
A pointer to the local storage area.
**int bpf_sk_select_reuseport(struct sk_reuseport_md \***\ *reuse*\ **, struct bpf_map \***\ *map*\ **, void \***\ *key*\ **, u64** *flags*\ **)**
Description
Select a **SO_REUSEPORT** socket from a
**BPF_MAP_TYPE_REUSEPORT_ARRAY** *map*.
It checks the selected socket is matching the incoming
request in the socket buffer.
Return
0 on success, or a negative error in case of failure.
**u64 bpf_skb_ancestor_cgroup_id(struct sk_buff \***\ *skb*\ **, int** *ancestor_level*\ **)**
Description
Return id of cgroup v2 that is ancestor of cgroup associated
with the *skb* at the *ancestor_level*. The root cgroup is at
*ancestor_level* zero and each step down the hierarchy
increments the level. If *ancestor_level* == level of cgroup
associated with *skb*, then return value will be same as that
of **bpf_skb_cgroup_id**\ ().
The helper is useful to implement policies based on cgroups
that are upper in hierarchy than immediate cgroup associated
with *skb*.
The format of returned id and helper limitations are same as in
**bpf_skb_cgroup_id**\ ().
Return
The id is returned or 0 in case the id could not be retrieved.
**struct bpf_sock \*bpf_sk_lookup_tcp(void \***\ *ctx*\ **, struct bpf_sock_tuple \***\ *tuple*\ **, u32** *tuple_size*\ **, u64** *netns*\ **, u64** *flags*\ **)**
Description
Look for TCP socket matching *tuple*, optionally in a child
network namespace *netns*. The return value must be checked,
and if non-**NULL**, released via **bpf_sk_release**\ ().
The *ctx* should point to the context of the program, such as
the skb or socket (depending on the hook in use). This is used
to determine the base network namespace for the lookup.
*tuple_size* must be one of:
**sizeof**\ (*tuple*\ **->ipv4**)
Look for an IPv4 socket.
**sizeof**\ (*tuple*\ **->ipv6**)
Look for an IPv6 socket.
If the *netns* is a negative signed 32-bit integer, then the
socket lookup table in the netns associated with the *ctx* will
will be used. For the TC hooks, this is the netns of the device
in the skb. For socket hooks, this is the netns of the socket.
If *netns* is any other signed 32-bit value greater than or
equal to zero then it specifies the ID of the netns relative to
the netns associated with the *ctx*. *netns* values beyond the
range of 32-bit integers are reserved for future use.
All values for *flags* are reserved for future usage, and must
be left at zero.
This helper is available only if the kernel was compiled with
**CONFIG_NET** configuration option.
Return
Pointer to **struct bpf_sock**, or **NULL** in case of failure.
For sockets with reuseport option, the **struct bpf_sock**
result is from *reuse*\ **->socks**\ [] using the hash of the
tuple.
**struct bpf_sock \*bpf_sk_lookup_udp(void \***\ *ctx*\ **, struct bpf_sock_tuple \***\ *tuple*\ **, u32** *tuple_size*\ **, u64** *netns*\ **, u64** *flags*\ **)**
Description
Look for UDP socket matching *tuple*, optionally in a child
network namespace *netns*. The return value must be checked,
and if non-**NULL**, released via **bpf_sk_release**\ ().
The *ctx* should point to the context of the program, such as
the skb or socket (depending on the hook in use). This is used
to determine the base network namespace for the lookup.
*tuple_size* must be one of:
**sizeof**\ (*tuple*\ **->ipv4**)
Look for an IPv4 socket.
**sizeof**\ (*tuple*\ **->ipv6**)
Look for an IPv6 socket.
If the *netns* is a negative signed 32-bit integer, then the
socket lookup table in the netns associated with the *ctx* will
will be used. For the TC hooks, this is the netns of the device
in the skb. For socket hooks, this is the netns of the socket.
If *netns* is any other signed 32-bit value greater than or
equal to zero then it specifies the ID of the netns relative to
the netns associated with the *ctx*. *netns* values beyond the
range of 32-bit integers are reserved for future use.
All values for *flags* are reserved for future usage, and must
be left at zero.
This helper is available only if the kernel was compiled with
**CONFIG_NET** configuration option.
Return
Pointer to **struct bpf_sock**, or **NULL** in case of failure.
For sockets with reuseport option, the **struct bpf_sock**
result is from *reuse*\ **->socks**\ [] using the hash of the
tuple.
**int bpf_sk_release(struct bpf_sock \***\ *sock*\ **)**
Description
Release the reference held by *sock*. *sock* must be a
non-**NULL** pointer that was returned from
**bpf_sk_lookup_xxx**\ ().
Return
0 on success, or a negative error in case of failure.
**int bpf_map_push_elem(struct bpf_map \***\ *map*\ **, const void \***\ *value*\ **, u64** *flags*\ **)**
Description
Push an element *value* in *map*. *flags* is one of:
**BPF_EXIST**
If the queue/stack is full, the oldest element is
removed to make room for this.
Return
0 on success, or a negative error in case of failure.
**int bpf_map_pop_elem(struct bpf_map \***\ *map*\ **, void \***\ *value*\ **)**
Description
Pop an element from *map*.
Return
0 on success, or a negative error in case of failure.
**int bpf_map_peek_elem(struct bpf_map \***\ *map*\ **, void \***\ *value*\ **)**
Description
Get an element from *map* without removing it.
Return
0 on success, or a negative error in case of failure.
**int bpf_msg_push_data(struct sk_buff \***\ *skb*\ **, u32** *start*\ **, u32** *len*\ **, u64** *flags*\ **)**
Description
For socket policies, insert *len* bytes into *msg* at offset
*start*.
If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a
*msg* it may want to insert metadata or options into the *msg*.
This can later be read and used by any of the lower layer BPF
hooks.
This helper may fail if under memory pressure (a malloc
fails) in these cases BPF programs will get an appropriate
error and BPF programs will need to handle them.
Return
0 on success, or a negative error in case of failure.
**int bpf_msg_pop_data(struct sk_msg_buff \***\ *msg*\ **, u32** *start*\ **, u32** *pop*\ **, u64** *flags*\ **)**
Description
Will remove *pop* bytes from a *msg* starting at byte *start*.
This may result in **ENOMEM** errors under certain situations if
an allocation and copy are required due to a full ring buffer.
However, the helper will try to avoid doing the allocation
if possible. Other errors can occur if input parameters are
invalid either due to *start* byte not being valid part of *msg*
payload and/or *pop* value being to large.
Return
0 on success, or a negative error in case of failure.
**int bpf_rc_pointer_rel(void \***\ *ctx*\ **, s32** *rel_x*\ **, s32** *rel_y*\ **)**
Description
This helper is used in programs implementing IR decoding, to
report a successfully decoded pointer movement.
The *ctx* should point to the lirc sample as passed into
the program.
This helper is only available is the kernel was compiled with
the **CONFIG_BPF_LIRC_MODE2** configuration option set to
"**y**".
Return
0
**int bpf_spin_lock(struct bpf_spin_lock \***\ *lock*\ **)**
Description
Acquire a spinlock represented by the pointer *lock*, which is
stored as part of a value of a map. Taking the lock allows to
safely update the rest of the fields in that value. The
spinlock can (and must) later be released with a call to
**bpf_spin_unlock**\ (\ *lock*\ ).
Spinlocks in BPF programs come with a number of restrictions
and constraints:
* **bpf_spin_lock** objects are only allowed inside maps of
types **BPF_MAP_TYPE_HASH** and **BPF_MAP_TYPE_ARRAY** (this
list could be extended in the future).
* BTF description of the map is mandatory.
* The BPF program can take ONE lock at a time, since taking two
or more could cause dead locks.
* Only one **struct bpf_spin_lock** is allowed per map element.
* When the lock is taken, calls (either BPF to BPF or helpers)
are not allowed.
* The **BPF_LD_ABS** and **BPF_LD_IND** instructions are not
allowed inside a spinlock-ed region.
* The BPF program MUST call **bpf_spin_unlock**\ () to release
the lock, on all execution paths, before it returns.
* The BPF program can access **struct bpf_spin_lock** only via
the **bpf_spin_lock**\ () and **bpf_spin_unlock**\ ()
helpers. Loading or storing data into the **struct
bpf_spin_lock** *lock*\ **;** field of a map is not allowed.
* To use the **bpf_spin_lock**\ () helper, the BTF description
of the map value must be a struct and have **struct
bpf_spin_lock** *anyname*\ **;** field at the top level.
Nested lock inside another struct is not allowed.
* The **struct bpf_spin_lock** *lock* field in a map value must
be aligned on a multiple of 4 bytes in that value.
* Syscall with command **BPF_MAP_LOOKUP_ELEM** does not copy
the **bpf_spin_lock** field to user space.
* Syscall with command **BPF_MAP_UPDATE_ELEM**, or update from
a BPF program, do not update the **bpf_spin_lock** field.
* **bpf_spin_lock** cannot be on the stack or inside a
networking packet (it can only be inside of a map values).
* **bpf_spin_lock** is available to root only.
* Tracing programs and socket filter programs cannot use
**bpf_spin_lock**\ () due to insufficient preemption checks
(but this may change in the future).
* **bpf_spin_lock** is not allowed in inner maps of map-in-map.
Return
0
**int bpf_spin_unlock(struct bpf_spin_lock \***\ *lock*\ **)**
Description
Release the *lock* previously locked by a call to
**bpf_spin_lock**\ (\ *lock*\ ).
Return
0
**struct bpf_sock \*bpf_sk_fullsock(struct bpf_sock \***\ *sk*\ **)**
Description
This helper gets a **struct bpf_sock** pointer such
that all the fields in this **bpf_sock** can be accessed.
Return
A **struct bpf_sock** pointer on success, or **NULL** in
case of failure.
**struct bpf_tcp_sock \*bpf_tcp_sock(struct bpf_sock \***\ *sk*\ **)**
Description
This helper gets a **struct bpf_tcp_sock** pointer from a
**struct bpf_sock** pointer.
Return
A **struct bpf_tcp_sock** pointer on success, or **NULL** in
case of failure.
**int bpf_skb_ecn_set_ce(struct sk_buf \***\ *skb*\ **)**
Description
Set ECN (Explicit Congestion Notification) field of IP header
to **CE** (Congestion Encountered) if current value is **ECT**
(ECN Capable Transport). Otherwise, do nothing. Works with IPv6
and IPv4.
Return
1 if the **CE** flag is set (either by the current helper call
or because it was already present), 0 if it is not set.
**struct bpf_sock \*bpf_get_listener_sock(struct bpf_sock \***\ *sk*\ **)**
Description
Return a **struct bpf_sock** pointer in **TCP_LISTEN** state.
**bpf_sk_release**\ () is unnecessary and not allowed.
Return
A **struct bpf_sock** pointer on success, or **NULL** in
case of failure.
**struct bpf_sock \*bpf_skc_lookup_tcp(void \***\ *ctx*\ **, struct bpf_sock_tuple \***\ *tuple*\ **, u32** *tuple_size*\ **, u64** *netns*\ **, u64** *flags*\ **)**
Description
Look for TCP socket matching *tuple*, optionally in a child
network namespace *netns*. The return value must be checked,
and if non-**NULL**, released via **bpf_sk_release**\ ().
This function is identical to **bpf_sk_lookup_tcp**\ (), except
that it also returns timewait or request sockets. Use
**bpf_sk_fullsock**\ () or **bpf_tcp_sock**\ () to access the
full structure.
This helper is available only if the kernel was compiled with
**CONFIG_NET** configuration option.
Return
Pointer to **struct bpf_sock**, or **NULL** in case of failure.
For sockets with reuseport option, the **struct bpf_sock**
result is from *reuse*\ **->socks**\ [] using the hash of the
tuple.
**int bpf_tcp_check_syncookie(struct bpf_sock \***\ *sk*\ **, void \***\ *iph*\ **, u32** *iph_len*\ **, struct tcphdr \***\ *th*\ **, u32** *th_len*\ **)**
Description
Check whether *iph* and *th* contain a valid SYN cookie ACK for
the listening socket in *sk*.
*iph* points to the start of the IPv4 or IPv6 header, while
*iph_len* contains **sizeof**\ (**struct iphdr**) or
**sizeof**\ (**struct ip6hdr**).
*th* points to the start of the TCP header, while *th_len*
contains **sizeof**\ (**struct tcphdr**).
Return
0 if *iph* and *th* are a valid SYN cookie ACK, or a negative
error otherwise.
**int bpf_sysctl_get_name(struct bpf_sysctl \***\ *ctx*\ **, char \***\ *buf*\ **, size_t** *buf_len*\ **, u64** *flags*\ **)**
Description
Get name of sysctl in /proc/sys/ and copy it into provided by
program buffer *buf* of size *buf_len*.
The buffer is always NUL terminated, unless it's zero-sized.
If *flags* is zero, full name (e.g. "net/ipv4/tcp_mem") is
copied. Use **BPF_F_SYSCTL_BASE_NAME** flag to copy base name
only (e.g. "tcp_mem").
Return
Number of character copied (not including the trailing NUL).
**-E2BIG** if the buffer wasn't big enough (*buf* will contain
truncated name in this case).
**int bpf_sysctl_get_current_value(struct bpf_sysctl \***\ *ctx*\ **, char \***\ *buf*\ **, size_t** *buf_len*\ **)**
Description
Get current value of sysctl as it is presented in /proc/sys
(incl. newline, etc), and copy it as a string into provided
by program buffer *buf* of size *buf_len*.
The whole value is copied, no matter what file position user
space issued e.g. sys_read at.
The buffer is always NUL terminated, unless it's zero-sized.
Return
Number of character copied (not including the trailing NUL).
**-E2BIG** if the buffer wasn't big enough (*buf* will contain
truncated name in this case).
**-EINVAL** if current value was unavailable, e.g. because
sysctl is uninitialized and read returns -EIO for it.
**int bpf_sysctl_get_new_value(struct bpf_sysctl \***\ *ctx*\ **, char \***\ *buf*\ **, size_t** *buf_len*\ **)**
Description
Get new value being written by user space to sysctl (before
the actual write happens) and copy it as a string into
provided by program buffer *buf* of size *buf_len*.
User space may write new value at file position > 0.
The buffer is always NUL terminated, unless it's zero-sized.
Return
Number of character copied (not including the trailing NUL).
**-E2BIG** if the buffer wasn't big enough (*buf* will contain
truncated name in this case).
**-EINVAL** if sysctl is being read.
**int bpf_sysctl_set_new_value(struct bpf_sysctl \***\ *ctx*\ **, const char \***\ *buf*\ **, size_t** *buf_len*\ **)**
Description
Override new value being written by user space to sysctl with
value provided by program in buffer *buf* of size *buf_len*.
*buf* should contain a string in same form as provided by user
space on sysctl write.
User space may write new value at file position > 0. To override
the whole sysctl value file position should be set to zero.
Return
0 on success.
**-E2BIG** if the *buf_len* is too big.
**-EINVAL** if sysctl is being read.
**int bpf_strtol(const char \***\ *buf*\ **, size_t** *buf_len*\ **, u64** *flags*\ **, long \***\ *res*\ **)**
Description
Convert the initial part of the string from buffer *buf* of
size *buf_len* to a long integer according to the given base
and save the result in *res*.
The string may begin with an arbitrary amount of white space
(as determined by **isspace**\ (3)) followed by a single
optional '**-**' sign.
Five least significant bits of *flags* encode base, other bits
are currently unused.
Base must be either 8, 10, 16 or 0 to detect it automatically
similar to user space **strtol**\ (3).
Return
Number of characters consumed on success. Must be positive but
no more than *buf_len*.
**-EINVAL** if no valid digits were found or unsupported base
was provided.
**-ERANGE** if resulting value was out of range.
**int bpf_strtoul(const char \***\ *buf*\ **, size_t** *buf_len*\ **, u64** *flags*\ **, unsigned long \***\ *res*\ **)**
Description
Convert the initial part of the string from buffer *buf* of
size *buf_len* to an unsigned long integer according to the
given base and save the result in *res*.
The string may begin with an arbitrary amount of white space
(as determined by **isspace**\ (3)).
Five least significant bits of *flags* encode base, other bits
are currently unused.
Base must be either 8, 10, 16 or 0 to detect it automatically
similar to user space **strtoul**\ (3).
Return
Number of characters consumed on success. Must be positive but
no more than *buf_len*.
**-EINVAL** if no valid digits were found or unsupported base
was provided.
**-ERANGE** if resulting value was out of range.
**void \*bpf_sk_storage_get(struct bpf_map \***\ *map*\ **, struct bpf_sock \***\ *sk*\ **, void \***\ *value*\ **, u64** *flags*\ **)**
Description
Get a bpf-local-storage from a *sk*.
Logically, it could be thought of getting the value from
a *map* with *sk* as the **key**. From this
perspective, the usage is not much different from
**bpf_map_lookup_elem**\ (*map*, **&**\ *sk*) except this
helper enforces the key must be a full socket and the map must
be a **BPF_MAP_TYPE_SK_STORAGE** also.
Underneath, the value is stored locally at *sk* instead of
the *map*. The *map* is used as the bpf-local-storage
"type". The bpf-local-storage "type" (i.e. the *map*) is
searched against all bpf-local-storages residing at *sk*.
An optional *flags* (**BPF_SK_STORAGE_GET_F_CREATE**) can be
used such that a new bpf-local-storage will be
created if one does not exist. *value* can be used
together with **BPF_SK_STORAGE_GET_F_CREATE** to specify
the initial value of a bpf-local-storage. If *value* is
**NULL**, the new bpf-local-storage will be zero initialized.
Return
A bpf-local-storage pointer is returned on success.
**NULL** if not found or there was an error in adding
a new bpf-local-storage.
**int bpf_sk_storage_delete(struct bpf_map \***\ *map*\ **, struct bpf_sock \***\ *sk*\ **)**
Description
Delete a bpf-local-storage from a *sk*.
Return
0 on success.
**-ENOENT** if the bpf-local-storage cannot be found.
**int bpf_send_signal(u32** *sig*\ **)**
Description
Send signal *sig* to the current task.
Return
0 on success or successfully queued.
**-EBUSY** if work queue under nmi is full.
**-EINVAL** if *sig* is invalid.
**-EPERM** if no permission to send the *sig*.
**-EAGAIN** if bpf program can try again.
**s64 bpf_tcp_gen_syncookie(struct bpf_sock \***\ *sk*\ **, void \***\ *iph*\ **, u32** *iph_len*\ **, struct tcphdr \***\ *th*\ **, u32** *th_len*\ **)**
Description
Try to issue a SYN cookie for the packet with corresponding
IP/TCP headers, *iph* and *th*, on the listening socket in *sk*.
*iph* points to the start of the IPv4 or IPv6 header, while
*iph_len* contains **sizeof**\ (**struct iphdr**) or
**sizeof**\ (**struct ip6hdr**).
*th* points to the start of the TCP header, while *th_len*
contains the length of the TCP header.
Return
On success, lower 32 bits hold the generated SYN cookie in
followed by 16 bits which hold the MSS value for that cookie,
and the top 16 bits are unused.
On failure, the returned value is one of the following:
**-EINVAL** SYN cookie cannot be issued due to error
**-ENOENT** SYN cookie should not be issued (no SYN flood)
**-EOPNOTSUPP** kernel configuration does not enable SYN cookies
**-EPROTONOSUPPORT** IP packet version is not 4 or 6
EXAMPLES
========
Example usage for most of the eBPF helpers listed in this manual page are
available within the Linux kernel sources, at the following locations:
* *samples/bpf/*
* *tools/testing/selftests/bpf/*
LICENSE
=======
eBPF programs can have an associated license, passed along with the bytecode
instructions to the kernel when the programs are loaded. The format for that
string is identical to the one in use for kernel modules (Dual licenses, such
as "Dual BSD/GPL", may be used). Some helper functions are only accessible to
programs that are compatible with the GNU Privacy License (GPL).
In order to use such helpers, the eBPF program must be loaded with the correct
license string passed (via **attr**) to the **bpf**\ () system call, and this
generally translates into the C source code of the program containing a line
similar to the following:
::
char ____license[] __attribute__((section("license"), used)) = "GPL";
IMPLEMENTATION
==============
This manual page is an effort to document the existing eBPF helper functions.
But as of this writing, the BPF sub-system is under heavy development. New eBPF
program or map types are added, along with new helper functions. Some helpers
are occasionally made available for additional program types. So in spite of
the efforts of the community, this page might not be up-to-date. If you want to
check by yourself what helper functions exist in your kernel, or what types of
programs they can support, here are some files among the kernel tree that you
may be interested in:
* *include/uapi/linux/bpf.h* is the main BPF header. It contains the full list
of all helper functions, as well as many other BPF definitions including most
of the flags, structs or constants used by the helpers.
* *net/core/filter.c* contains the definition of most network-related helper
functions, and the list of program types from which they can be used.
* *kernel/trace/bpf_trace.c* is the equivalent for most tracing program-related
helpers.
* *kernel/bpf/verifier.c* contains the functions used to check that valid types
of eBPF maps are used with a given helper function.
* *kernel/bpf/* directory contains other files in which additional helpers are
defined (for cgroups, sockmaps, etc.).
Compatibility between helper functions and program types can generally be found
in the files where helper functions are defined. Look for the **struct
bpf_func_proto** objects and for functions returning them: these functions
contain a list of helpers that a given program type can call. Note that the
**default:** label of the **switch ... case** used to filter helpers can call
other functions, themselves allowing access to additional helpers. The
requirement for GPL license is also in those **struct bpf_func_proto**.
Compatibility between helper functions and map types can be found in the
**check_map_func_compatibility**\ () function in file *kernel/bpf/verifier.c*.
Helper functions that invalidate the checks on **data** and **data_end**
pointers for network processing are listed in function
**bpf_helper_changes_pkt_data**\ () in file *net/core/filter.c*.
SEE ALSO
========
**bpf**\ (2),
**cgroups**\ (7),
**ip**\ (8),
**perf_event_open**\ (2),
**sendmsg**\ (2),
**socket**\ (7),
**tc-bpf**\ (8)
| 101,599
|
C++
|
.h
| 1,996
| 47.907816
| 165
| 0.718877
|
takehaya/Vinbero
| 36
| 4
| 6
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,177
|
srv6_structs.h
|
takehaya_Vinbero/src/srv6_structs.h
|
#ifndef __SRV6_STRUCTS_H
#define __SRV6_STRUCTS_H
#include "srv6_consts.h"
#include <linux/types.h>
#include <linux/in6.h> /* For struct in6_addr. */
struct v6addr_heep
{
struct in6_addr saddr;
struct in6_addr daddr;
};
struct transit_behavior
{
struct in6_addr saddr;
struct in6_addr daddr;
__u32 s_prefixlen;
__u32 d_prefixlen;
__u32 segment_length;
__u32 action;
struct in6_addr segments[MAX_SEGMENTS];
};
struct lpm_key_v4
{
__u32 prefixlen;
__u32 addr;
};
struct lpm_key_v6
{
__u32 prefixlen;
struct in6_addr addr;
};
struct end_function
{
__u32 saddr[4];
union
{
__u32 v6addr[4];
struct v4
{
__u32 addr;
__u32 padding[3];
} v4;
} nexthop;
// The reason why the "__u32 function" is not "__u8" is that it also serves as padding.
// The cilium/ebpf package assumes that the go structure takes 4 bytes each and does not pack.
__u32 function;
__u32 flaver;
__u32 v4_addr_spos;
__u32 v4_addr_dpos;
};
// Segment Routing Extension Header (SRH)
// https://datatracker.ietf.org/doc/draft-ietf-6man-segment-routing-header/
struct srhhdr
{
__u8 nextHdr;
__u8 hdrExtLen;
__u8 routingType;
__u8 segmentsLeft;
__u8 lastEntry;
__u8 flags;
__u16 tag;
// cf. 5.3. Encoding of Tags Field/ https://datatracker.ietf.org/doc/draft-murakami-dmm-user-plane-message-encoding
// __u8 gtpMessageType : 4; // least significant 4 bits of tag field
struct in6_addr segments[0];
};
/*
* struct vlan_hdr - vlan header
* @h_vlan_TCI: priority and VLAN ID
* @h_vlan_encapsulated_proto: packet type ID or len
*/
struct vlan_hdr
{
__u16 h_vlan_TCI;
__u16 h_vlan_encapsulated_proto;
};
// struct gtpu_exthdr
// {
// __u16 seq;
// __u8 npdu_num;
// __u8 nextexthdr;
// };
// struct gtp1_pdu_session_t
// {
// __u8 exthdrlen;
// __u8 type : 4;
// __u8 spare : 4;
// union
// {
// struct gtpu_qfi_bits
// {
// __u8 p : 1;
// __u8 r : 1;
// __u8 qfi : 6;
// } bits;
// __u8 val;
// } u;
// struct gtpu_exthdr paging[0];
// __u8 nextexthdr;
// };
/* According to 3GPP TS 29.060. */
struct gtp1hdr
{
// __u8 version : 3; // Version field: always 1 for GTPv1
// __u8 pt : 1; // Protocol Type (PT): GTP(1), GTP'(0)
// __u8 reserved : 1; // always zero (0)
// __u8 e : 1; // Extension Header flag (E)
// __u8 s : 1; // Sequence number flag (S): not present(0), present(1)
// __u8 pn : 1; // N-PDU Number flag (PN)
__u8 flags;
__u8 type;
__u16 length;
__u32 tid;
// options
// __u16 seq; // Sequence Number
// __u8 npdu; // N-PDU number
// __u8 nextExtHdr; // Next Extention Header Type
};
// https://tools.ietf.org/html/draft-ietf-dmm-srv6-mobile-uplane-09#section-6.1
// https://tools.ietf.org/html/draft-murakami-dmm-user-plane-message-encoding-02#section-5.2
struct args_mob_session
{
__u8 qfi : 6;
__u8 r : 1;
__u8 u : 1;
// __u8 qfi_r_u;
union
{
__u32 pdu_session_id;
struct seq
{
__u16 seq;
__u16 padding;
} seq;
} session;
} __attribute__((packed));
#endif
| 3,334
|
C++
|
.h
| 135
| 21.059259
| 119
| 0.574929
|
takehaya/Vinbero
| 36
| 4
| 6
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,178
|
srv6_consts.h
|
takehaya_Vinbero/src/srv6_consts.h
|
#ifndef __SRV6_CONSTS_H
#define __SRV6_CONSTS_H
#include "bpf_endian.h"
// user define fib ctl value
#define NextFIBCheck 10000
// max mtusize
#define LOOP_MAX_RANGE 4000
// linux/socket.h
#define AF_INET 2 /* Internet IP Protocol */
#define AF_INET6 10 /* IP version 6 */
#define ETH_P_8021Q 0x8100 /* 802.1Q VLAN Extended Header */
#define ETH_P_8021AD 0x88A8 /* 802.1ad Service VLAN */
#define ETH_P_ARP 0x0806
#define ETH_P_IPV4 0x0800
#define ETH_P_IPV6 0x86DD
// net/ipv6.h
#define NEXTHDR_ROUTING 43 /* Routing header. */
// Entry size
#define MAX_TXPORT_DEVICE 64
#define MAX_TRANSIT_ENTRIES 256
#define MAX_END_FUNCTION_ENTRIES 65536
#define MAX_SEGMENTS 5
#define MAX_GTP4_SRCADDR_PREFIX 96
#define MAX_GTP4_DSTADDR_PREFIX 56
// srh flag
#define SR6_FLAG1_PROTECTED (1 << 6)
#define SR6_FLAG1_OAM (1 << 5)
#define SR6_FLAG1_ALERT (1 << 4)
#define SR6_FLAG1_HMAC (1 << 3)
#define SR6_TLV_INGRESS 1
#define SR6_TLV_EGRESS 2
#define SR6_TLV_OPAQUE 3
#define SR6_TLV_PADDING 4
#define SR6_TLV_HMAC 5
#define sr_has_hmac(srh) ((srh)->flags & SR6_FLAG1_HMAC)
//Encap define
#define SEG6_IPTUN_MODE_INLINE 0
#define SEG6_IPTUN_MODE_ENCAP 1
#define SEG6_IPTUN_MODE_L2ENCAP 2
#define SEG6_IPTUN_MODE_ENCAP_T_M_GTP6_D 3
#define SEG6_IPTUN_MODE_ENCAP_T_M_GTP6_D_Di 4
#define SEG6_IPTUN_MODE_ENCAP_H_M_GTP4_D 5
// END($|X|T) case using
#define SEG6_LOCAL_FLAVER_NONE 1
#define SEG6_LOCAL_FLAVER_PSP 2
#define SEG6_LOCAL_FLAVER_USP 3
#define SEG6_LOCAL_FLAVER_USD 4
// Function define(e.g. Decap, segleft...)
#define SEG6_LOCAL_ACTION_END 1
#define SEG6_LOCAL_ACTION_END_X 2
#define SEG6_LOCAL_ACTION_END_T 3
#define SEG6_LOCAL_ACTION_END_DX2 4
#define SEG6_LOCAL_ACTION_END_DX6 5
#define SEG6_LOCAL_ACTION_END_DX4 6
#define SEG6_LOCAL_ACTION_END_DT6 7
#define SEG6_LOCAL_ACTION_END_DT4 8
#define SEG6_LOCAL_ACTION_END_B6 9
#define SEG6_LOCAL_ACTION_END_B6_ENCAPS 10
#define SEG6_LOCAL_ACTION_END_BM 11
#define SEG6_LOCAL_ACTION_END_S 12
#define SEG6_LOCAL_ACTION_END_AS 13
#define SEG6_LOCAL_ACTION_END_AM 14
#define SEG6_LOCAL_ACTION_END_M_GTP6_E 15
#define SEG6_LOCAL_ACTION_END_M_GTP4_E 16
#define IPV6_FLOWINFO_MASK __bpf_htonl(0x0FFFFFFF)
// GTP User Data Messages (GTPv1)
// 3GPP TS 29.060 "Table 1: Messages in GTP"
#define GTPV1_ECHO 1 // Echo Request
#define GTPV1_ECHORES 2 // Echo Response
#define GTPV1_ERROR 26 // Error Indication
#define GTPV1_END 254 // End Marker
#define GTPV1_GPDU 255 // G-PDU
#define GTP_V1 1
#define GTP1U_PORT 2152
/* from net/ip.h */
#define IP_DF 0x4000 /* Flag: "Don't Fragment" */
// from net/tcp.h
#define TCPOPT_EOL 0 /* End of options */
#define TCPOPT_NOP 1 /* Padding */
#define TCPOPT_MSS 2 /* Segment size negotiating */
#define DEFAULT_TTL 255
#endif
| 2,736
|
C++
|
.h
| 82
| 32.134146
| 62
| 0.752182
|
takehaya/Vinbero
| 36
| 4
| 6
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,179
|
srv6_maps.h
|
takehaya_Vinbero/src/srv6_maps.h
|
#ifndef __PGWU_MAPS_H
#define __PGWU_MAPS_H
#include <linux/bpf.h>
#include "bpf_helpers.h"
#include "srv6_consts.h"
#include "srv6_structs.h"
#include "hook.h"
struct
{
__uint(type, BPF_MAP_TYPE_DEVMAP);
__uint(key_size, sizeof(int));
__uint(value_size, sizeof(int));
__uint(max_entries, MAX_TXPORT_DEVICE);
} tx_port SEC(".maps");
struct
{
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__type(key, struct lpm_key_v6);
__type(value, struct end_function);
__uint(max_entries, MAX_END_FUNCTION_ENTRIES);
__uint(map_flags, BPF_F_NO_PREALLOC);
} function_table SEC(".maps");
struct
{
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__type(key, struct lpm_key_v4);
__type(value, struct transit_behavior);
__uint(max_entries, MAX_TRANSIT_ENTRIES);
__uint(map_flags, BPF_F_NO_PREALLOC);
} transit_table_v4 SEC(".maps");
struct
{
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__type(key, struct lpm_key_v6);
__type(value, struct transit_behavior);
__uint(max_entries, MAX_TRANSIT_ENTRIES);
__uint(map_flags, BPF_F_NO_PREALLOC);
} transit_table_v6 SEC(".maps");
struct
{
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
__type(key, int);
__type(value, struct v6addr_heep);
__uint(max_entries, 1);
} in_taple_v6_addr SEC(".maps");
// https://github.com/cloudflare/xdpcap
// struct bpf_map_def SEC("maps") xdpcap_hook = XDPCAP_HOOK();
struct xdpcap_hook
{
__uint(type, BPF_MAP_TYPE_PROG_ARRAY);
__uint(key_size, sizeof(int));
__uint(value_size, sizeof(int));
__uint(max_entries, 5);
} xdpcap_hook SEC(".maps");
#endif
| 1,587
|
C++
|
.h
| 55
| 25.745455
| 62
| 0.659449
|
takehaya/Vinbero
| 36
| 4
| 6
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,180
|
srv6_helpers.h
|
takehaya_Vinbero/src/srv6_helpers.h
|
#ifndef __SRV6_HELPERS_H
#define __SRV6_HELPERS_H
#include <stdbool.h>
#include <linux/types.h>
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/ipv6.h>
#include <linux/socket.h>
#include <linux/seg6.h>
#include <linux/seg6_local.h>
#include "bpf_helpers.h"
#include "bpf_endian.h"
#include "srv6_consts.h"
__attribute__((__always_inline__)) static inline void read_v6addr_in_pyload(
__u8 *payload, struct in6_addr *v6addr, __u16 payload_size, __u16 offset, __u16 shift)
{
offset = offset & 0xf;
payload_size = payload_size & 0xf;
if (sizeof(struct in6_addr) <= offset ||
sizeof(struct in6_addr) <= payload_size + offset ||
offset < 0)
return;
if (shift == 0)
{
#pragma clang loop unroll(disable)
for (__u16 index = 0; index < sizeof(struct in6_addr); index++)
{
index = index & 0xf;
if (payload_size <= index)
break;
__u8 *payval1 = (__u8 *)(void *)payload + index;
__u8 *v6val = (__u8 *)(void *)v6addr + offset + index;
if (offset + index + 1 >= sizeof(struct in6_addr))
break;
*payval1 = *v6val;
}
}
else
{
#pragma clang loop unroll(disable)
for (__u16 index = 0; index < sizeof(struct in6_addr); index++)
{
index = index & 0xf;
if (payload_size <= index || payload_size <= index + 1)
break;
__u8 *payval1 = (__u8 *)(void *)payload + index;
__u8 *payval2 = (__u8 *)(void *)payload + index + 1;
__u8 *v6val = (__u8 *)(void *)v6addr + offset + index;
if (offset + index + 1 >= sizeof(struct in6_addr))
break;
*payval1 |= *v6val >> shift;
*payval2 |= *v6val << (8 - shift);
}
}
}
__attribute__((__always_inline__)) static inline void read_v6addr_in_pkt_pyload(
__u8 *payload, struct in6_addr *v6addr, __u16 payload_size, __u16 offset, __u16 shift, const __u32 *data_end)
{
offset = offset & 0xffff;
payload_size = payload_size & 0xffff;
if (sizeof(struct in6_addr) <= offset ||
sizeof(struct in6_addr) <= payload_size + offset ||
offset < 0)
return;
if (shift == 0)
{
if ((void *)payload + payload_size > data_end)
return;
__builtin_memcpy(payload, &v6addr->in6_u.u6_addr8[offset], payload_size);
}
else
{
#pragma clang loop unroll(disable)
for (__u16 index = 0; index < sizeof(struct in6_addr); index++)
{
index = index & 0xf;
if (payload_size <= index)
break;
__u8 *payval1 = (__u8 *)(void *)payload + index;
__u8 *payval2 = (__u8 *)(void *)payload + index + 1;
__u8 *v6val = (__u8 *)(void *)v6addr + offset + index;
if ((void *)payval1 + 1 > data_end || payval2 + 1 > data_end || offset + index + 1 >= sizeof(struct in6_addr))
break;
*payval1 |= *v6val >> shift;
*payval2 |= *v6val << (8 - shift);
}
}
}
__attribute__((__always_inline__)) static inline void write_v6addr_in_pyload(
struct in6_addr *v6addr, __u8 *payload, __u16 payload_size, __u16 offset, __u16 shift, const __u32 *data_end)
{
offset = offset & 0xfff;
payload_size = payload_size & 0xffff;
if (sizeof(struct in6_addr) <= offset ||
sizeof(struct in6_addr) <= payload_size + offset ||
offset < 0)
return;
if (shift == 0)
{
if ((void *)v6addr + offset + payload_size > data_end)
return;
__builtin_memcpy(&v6addr->in6_u.u6_addr8[offset], payload, payload_size);
}
else
{
#pragma clang loop unroll(disable)
for (__u16 index = 0; index < sizeof(struct in6_addr); index++)
{
index = index & 0xf;
if (payload_size <= index)
break;
__u8 *v6val1 = (__u8 *)(void *)v6addr + offset + index;
__u8 *v6val2 = (__u8 *)(void *)v6addr + offset + index + 1;
if (v6val1 + 1 <= data_end && v6val2 + 1 <= data_end)
{
*v6val1 |= payload[index] >> shift;
*v6val2 |= payload[index] << (8 - shift);
}
else
break;
}
}
}
/* from include/net/ip.h */
__attribute__((__always_inline__)) static inline int ip_decrease_ttl(struct iphdr *iph)
{
__u32 check = (__u32)iph->check;
check += (__u32)bpf_htons(0x0100);
iph->check = (__sum16)(check + (check >= 0xFFFF));
return --iph->ttl;
};
__attribute__((__always_inline__)) static inline __u16 wrapsum(__u32 sum)
{
sum = ~sum & 0xFFFF;
return (sum);
}
// cf. https://github.com/iovisor/bcc/issues/2463#issuecomment-718800510
__attribute__((__always_inline__)) static inline void ipv4_udp_csum_build(struct udphdr *uh, struct iphdr *iph, __u32 *data_end)
{
uh->check = 0;
__u32 csum = 0;
csum = (iph->saddr >> 16) & 0xffff;
csum += (iph->saddr) & 0xffff;
csum += (iph->daddr >> 16) & 0xffff;
csum += (iph->daddr) & 0xffff;
csum += (iph->protocol) << 8;
csum += uh->len;
__u16 *buf = (__u16 *)uh;
// Compute checksum on udp header + payload
for (__u32 i = 0; i < LOOP_MAX_RANGE; i += 2)
{
if ((void *)(buf + 1) > data_end)
break;
csum += *buf;
buf++;
}
if ((void *)buf + 1 <= data_end)
// In case payload is not 2 bytes aligned
csum += *(__u8 *)buf;
csum = ~csum;
uh->check = csum;
// csum = (csum >> 16) + (csum & 0xffff);
// csum += csum >> 16;
// uh->check = wrapsum(csum);
}
__attribute__((__always_inline__)) static inline void csum_build(struct iphdr *iph)
{
__u16 *next_iph_u16;
__u32 csum = 0;
int i;
iph->check = 0;
next_iph_u16 = (__u16 *)iph;
#pragma clang loop unroll(disable)
for (i = 0; i < (sizeof(*iph) >> 1); i++)
csum += *next_iph_u16++;
iph->check = ~((csum & 0xffff) + (csum >> 16));
}
/* Function to set source and destination mac of the packet */
__attribute__((__always_inline__)) static inline void set_src_dst_mac(void *data, void *src, void *dst)
{
unsigned short *source = src;
unsigned short *dest = dst;
unsigned short *p = data;
__builtin_memcpy(p, dest, ETH_ALEN);
__builtin_memcpy(p + 3, source, ETH_ALEN);
}
__attribute__((__always_inline__)) static inline struct ethhdr *get_eth(struct xdp_md *xdp)
{
void *data = (void *)(long)xdp->data;
void *data_end = (void *)(long)xdp->data_end;
struct ethhdr *eth = data;
if (eth + 1 > data_end)
return NULL;
return eth;
}
__attribute__((__always_inline__)) static inline struct ipv6hdr *get_ipv6(struct xdp_md *xdp)
{
void *data = (void *)(long)xdp->data;
void *data_end = (void *)(long)xdp->data_end;
struct ipv6hdr *v6h = data + sizeof(struct ethhdr);
if (v6h + 1 > data_end)
return NULL;
return v6h;
};
__attribute__((__always_inline__)) static inline struct iphdr *get_ipv4(struct xdp_md *xdp)
{
void *data = (void *)(long)xdp->data;
void *data_end = (void *)(long)xdp->data_end;
struct iphdr *iph = data + sizeof(struct ethhdr);
if (iph + 1 > data_end)
return NULL;
return iph;
};
__attribute__((__always_inline__)) static inline struct srhhdr *get_srh(struct xdp_md *xdp)
{
void *data = (void *)(long)xdp->data;
void *data_end = (void *)(long)xdp->data_end;
struct srhhdr *srh;
int len, srhoff = 0;
srh = data + sizeof(struct ethhdr) + sizeof(struct ipv6hdr);
if (srh + 1 > data_end)
{
return NULL;
}
// len = (srh->hdrlen + 1) << 3;
return srh;
}
__attribute__((__always_inline__)) static inline struct udphdr *get_v4_udp(struct xdp_md *xdp)
{
void *data = (void *)(long)xdp->data;
void *data_end = (void *)(long)xdp->data_end;
struct udphdr *uh = data + sizeof(struct ethhdr) + sizeof(struct iphdr);
if ((void *)uh + sizeof(struct udphdr) > data_end)
return NULL;
return uh;
};
__attribute__((__always_inline__)) static inline struct gtp1hdr *get_v4_gtp1(struct xdp_md *xdp)
{
void *data = (void *)(long)xdp->data;
void *data_end = (void *)(long)xdp->data_end;
struct gtp1hdr *gtp1 = data + sizeof(struct ethhdr) + sizeof(struct iphdr) + sizeof(struct udphdr);
if ((void *)gtp1 + sizeof(struct gtp1hdr) > data_end)
return NULL;
return gtp1;
};
__attribute__((__always_inline__)) static inline struct srhhdr *get_and_validate_srh(struct xdp_md *xdp)
{
struct srhhdr *srh;
srh = get_srh(xdp);
if (!srh)
return NULL;
if (srh->segmentsLeft == 0)
return NULL;
// TODO
// #ifdef CONFIG_IPV6_SEG6_HMAC
// if (!seg6_hmac_validate_skb(skb))
// return NULL;
// #endif
return srh;
}
__attribute__((__always_inline__)) static inline bool advance_nextseg(struct srhhdr *srh, struct in6_addr *daddr, struct xdp_md *xdp)
{
struct in6_addr *addr;
void *data_end = (void *)(long)xdp->data_end;
srh->segmentsLeft--;
if ((void *)(long)srh + sizeof(struct srhhdr) + sizeof(struct in6_addr) * (srh->segmentsLeft + 1) > data_end)
return false;
addr = srh->segments + srh->segmentsLeft;
if (addr + 1 > data_end)
return false;
*daddr = *addr;
return true;
}
__attribute__((__always_inline__)) static inline bool lookup_nexthop(struct xdp_md *xdp, void *smac, void *dmac, __u32 *ifindex, __u32 flag)
{
void *data = (void *)(long)xdp->data;
void *data_end = (void *)(long)xdp->data_end;
struct ethhdr *eth = data;
struct iphdr *iph = get_ipv4(xdp);
struct ipv6hdr *v6h = get_ipv6(xdp);
struct bpf_fib_lookup fib_params = {};
__u16 h_proto;
//TODO:: impl dot1q proto
if (data + sizeof(struct ethhdr) > data_end)
return false;
h_proto = eth->h_proto;
__builtin_memset(&fib_params, 0, sizeof(fib_params));
switch (h_proto)
{
case bpf_htons(ETH_P_IP):
if (!iph)
return false;
fib_params.family = AF_INET;
fib_params.tos = iph->tos;
fib_params.l4_protocol = iph->protocol;
fib_params.sport = 0;
fib_params.dport = 0;
fib_params.tot_len = bpf_ntohs(iph->tot_len);
fib_params.ipv4_src = iph->saddr;
fib_params.ipv4_dst = iph->daddr;
break;
case bpf_htons(ETH_P_IPV6):
if (!v6h)
return false;
if (v6h->hop_limit <= 1)
return false;
struct in6_addr *src = (struct in6_addr *)fib_params.ipv6_src;
struct in6_addr *dst = (struct in6_addr *)fib_params.ipv6_dst;
fib_params.family = AF_INET6;
fib_params.tos = 0;
fib_params.flowinfo = *(__be32 *)v6h & IPV6_FLOWINFO_MASK;
fib_params.l4_protocol = v6h->nexthdr;
fib_params.sport = 0;
fib_params.dport = 0;
fib_params.tot_len = bpf_ntohs(v6h->payload_len);
*src = v6h->saddr;
*dst = v6h->daddr;
break;
default:
return false;
}
// bpf_fib_lookup
// flags: BPF_FIB_LOOKUP_DIRECT, BPF_FIB_LOOKUP_OUTPUT
// https://github.com/torvalds/linux/blob/v4.18/include/uapi/linux/bpf.h#L2611
fib_params.ifindex = xdp->ingress_ifindex;
// int rc = bpf_fib_lookup(xdp, &fib_params, sizeof(fib_params), BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT);
int rc = bpf_fib_lookup(xdp, &fib_params, sizeof(fib_params), flag);
switch (rc)
{
case BPF_FIB_LKUP_RET_SUCCESS: /* lookup successful */
if (h_proto == bpf_htons(ETH_P_IP))
ip_decrease_ttl(iph);
else if (h_proto == bpf_htons(ETH_P_IPV6))
v6h->hop_limit--;
*ifindex = fib_params.ifindex;
__u8 *source = smac;
__u8 *dest = dmac;
__builtin_memcpy(dest, fib_params.dmac, ETH_ALEN);
__builtin_memcpy(source, fib_params.smac, ETH_ALEN);
return true;
case BPF_FIB_LKUP_RET_BLACKHOLE: /* dest is blackholed; can be dropped */
// bpf_printk("BPF_FIB_LKUP_RET_BLACKHOLE");
break;
case BPF_FIB_LKUP_RET_UNREACHABLE: /* dest is unreachable; can be dropped */
// bpf_printk("BPF_FIB_LKUP_RET_UNREACHABLE");
break;
case BPF_FIB_LKUP_RET_PROHIBIT: /* dest not allowed; can be dropped */
// bpf_printk("BPF_FIB_LKUP_RET_PROHIBIT");
break;
// action = XDP_DROP;
// return false;
case BPF_FIB_LKUP_RET_NOT_FWDED: /* packet is not forwarded */
// bpf_printk("BPF_FIB_LKUP_RET_NOT_FWDED");
break;
case BPF_FIB_LKUP_RET_FWD_DISABLED: /* fwding is not enabled on ingress */
// bpf_printk("BPF_FIB_LKUP_RET_FWD_DISABLED");
break;
case BPF_FIB_LKUP_RET_UNSUPP_LWT: /* fwd requires encapsulation */
// bpf_printk("BPF_FIB_LKUP_RET_UNSUPP_LWT");
break;
case BPF_FIB_LKUP_RET_NO_NEIGH: /* no neighbor entry for nh */
// bpf_printk("BPF_FIB_LKUP_RET_NO_NEIGH");
break;
case BPF_FIB_LKUP_RET_FRAG_NEEDED: /* fragmentation required to fwd */
// bpf_printk("BPF_FIB_LKUP_RET_FRAG_NEEDED");
break;
/* PASS */
return false;
}
return false;
}
__attribute__((__always_inline__)) static inline int rewrite_nexthop(struct xdp_md *xdp, __u32 flag)
{
void *data = (void *)(long)xdp->data;
void *data_end = (void *)(long)xdp->data_end;
struct ethhdr *eth = data;
if (data + 1 > data_end)
return XDP_PASS;
// bpf_printk("rewrite_nexthop");
__u32 ifindex;
__u8 smac[6], dmac[6];
bool is_exist = lookup_nexthop(xdp, &smac, &dmac, &ifindex, flag);
if (is_exist)
{
set_src_dst_mac(data, &smac, &dmac);
// bpf_printk("lockup");
if (!bpf_map_lookup_elem(&tx_port, &ifindex))
return XDP_PASS;
if (xdp->ingress_ifindex == ifindex)
{
// bpf_printk("run tx");
return XDP_TX;
}
// bpf_printk("go to redirect");
return bpf_redirect_map(&tx_port, ifindex, 0);
}
// bpf_printk("failed rewrite nhop");
return XDP_PASS;
}
#endif
| 14,290
|
C++
|
.h
| 402
| 28.967662
| 140
| 0.575226
|
takehaya/Vinbero
| 36
| 4
| 6
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,187
|
Render.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Rendering/Render.cpp
|
/* Copyright (c) 2002-2012 Croteam Ltd.
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "stdh.h"
#include <Engine/Brushes/Brush.h>
#include <Engine/Brushes/BrushTransformed.h>
#include <Engine/Rendering/Render.h>
#include <Engine/Rendering/Render_internal.h>
#include <Engine/Base/Console.h>
#include <Engine/Templates/DynamicContainer.h>
#include <Engine/Templates/DynamicContainer.cpp>
#include <Engine/Light/LightSource.h>
#include <Engine/Light/Gradient.h>
#include <Engine/Base/ListIterator.inl>
#include <Engine/World/World.h>
#include <Engine/Entities/Entity.h>
#include <Engine/Templates/StaticArray.cpp>
#include <Engine/Math/Clipping.inl>
#include <Engine/Entities/EntityClass.h>
#include <Engine/World/WorldSettings.h>
#include <Engine/Entities/EntityProperties.h>
#include <Engine/Entities/FieldSettings.h>
#include <Engine/Entities/ShadingInfo.h>
#include <Engine/Light/LensFlares.h>
#include <Engine/Models/ModelObject.h>
#include <Engine/Models/RenderModel.h>
#include <Engine/Ska/Render.h>
#include <Engine/Terrain/Terrain.h>
#include <Engine/Templates/BSP.h>
#include <Engine/World/WorldEditingProfile.h>
#include <Engine/Brushes/BrushArchive.h>
#include <Engine/Math/Float.h>
#include <Engine/Math/OBBox.h>
#include <Engine/Math/Geometry.inl>
#include <Engine/Graphics/DrawPort.h>
#include <Engine/Graphics/GfxLibrary.h>
#include <Engine/Graphics/Fog_internal.h>
#include <Engine/Base/Statistics_internal.h>
#include <Engine/Rendering/RenderProfile.h>
#include <Engine/Templates/LinearAllocator.cpp>
#include <Engine/Templates/DynamicArray.cpp>
#include <Engine/Templates/StaticStackArray.cpp>
#include <Engine/Templates/DynamicStackArray.cpp>
extern BOOL _bSomeDarkExists;
extern INDEX d3d_bAlternateDepthReads;
// general coordinate stack referenced by the scene polygons
extern CStaticStackArray<GFXVertex3> _avtxScene;
//#pragma optimize ("gt", on)
#pragma inline_depth(255)
#pragma inline_recursion(on)
#ifndef NDEBUG
//#define ASER_EXTREME_CHECKING 1
#endif
// the renderer structures used in rendering
#define MAX_RENDERERS 2
static CRenderer _areRenderers[MAX_RENDERERS];
static BOOL _bMirrorDrawn = FALSE;
extern INDEX wld_bAlwaysAddAll;
extern INDEX wld_bRenderEmptyBrushes;
extern INDEX wld_bRenderDetailPolygons;
extern INDEX gfx_bRenderParticles;
extern INDEX gfx_bRenderModels;
extern INDEX gfx_bRenderFog;
extern INDEX gfx_bRenderPredicted;
extern INDEX gfx_iLensFlareQuality;
extern BOOL _bMultiPlayer;
// variables for selection on rendering
extern CBrushVertexSelection *_pselbvxtSelectOnRender = NULL;
extern CStaticStackArray<PIX2D> *_pavpixSelectLasso = NULL;
extern CEntitySelection *_pselenSelectOnRender = NULL;
extern PIX2D _vpixSelectNearPoint = PIX2D(0,0);
extern BOOL _bSelectAlternative = FALSE;
extern PIX _pixDeltaAroundVertex = 10;
// shading info for viewer of last rendered view
FLOAT3D _vViewerLightDirection;
COLOR _colViewerLight;
COLOR _colViewerAmbient;
// handy statistic helper routines
static enum CStatForm::StatTimerIndex _stiLastStatsMode = (enum CStatForm::StatTimerIndex)-1;
void StopStatsMode(void)
{
ASSERT( (INDEX)_stiLastStatsMode != -1);
if( _stiLastStatsMode>=0) _sfStats.StopTimer(_stiLastStatsMode);
_stiLastStatsMode = (enum CStatForm::StatTimerIndex)-1;
}
void StartStatsMode( enum CStatForm::StatTimerIndex sti)
{
ASSERT( (INDEX)sti != -1);
ASSERT( (INDEX)_stiLastStatsMode == -1);
if( sti>=0) _sfStats.StartTimer(sti);
_stiLastStatsMode = sti;
}
void ChangeStatsMode( enum CStatForm::StatTimerIndex sti)
{
StopStatsMode();
StartStatsMode(sti);
}
// screen edges, polygons and trapezoids used in rasterizing
CDynamicStackArray<CAddEdge> CRenderer::re_aadeAddEdges;
CDynamicStackArray<CScreenEdge> CRenderer::re_asedScreenEdges;
// spans for current scan line
CDynamicStackArray<CSpan> CRenderer::re_aspSpans;
// vertices clipped to current clip plane
CStaticStackArray<INDEX> CRenderer::re_aiClipBuffer;
// buffers for edges of polygons
CStaticStackArray<INDEX> CRenderer::re_aiEdgeVxClipSrc;
CStaticStackArray<INDEX> CRenderer::re_aiEdgeVxClipDst;
// add and remove lists for each scan line
CStaticArray<CListHead> CRenderer::re_alhAddLists;
CStaticArray<INDEX> CRenderer::re_actAddCounts; // count of edges in given add list
CStaticArray<CScreenEdge *> CRenderer::re_apsedRemoveFirst;
CStaticStackArray<CActiveEdge> CRenderer::re_aaceActiveEdgesTmp;
CStaticStackArray<CActiveEdge> CRenderer::re_aaceActiveEdges;
// container for sorting translucent polygons
CDynamicStackArray<CTranslucentPolygon> CRenderer::re_atcTranslucentPolygons;
// container for all light influencing current model
struct ModelLight {
CLightSource *ml_plsLight; // the light source
FLOAT3D ml_vDirection; // direction from light to the model position (normalized)
FLOAT ml_fShadowIntensity; // intensity at the model position (for shadow)
FLOAT ml_fR, ml_fG, ml_fB; // light components at light source (0..255)
inline void Clear(void) {};
};
static CDynamicStackArray<struct ModelLight> _amlLights;
static INDEX _ctMaxAddEdges=0;
static INDEX _ctMaxActiveEdges=0;
void RendererInfo(void)
{
CPrintF("Renderer information:\n");
SLONG slMem = 0;
slMem += CRenderer::re_aadeAddEdges.da_Count*sizeof(CAddEdge);
slMem += CRenderer::re_asedScreenEdges.da_Count*sizeof(CScreenEdge);
slMem += CRenderer::re_aspSpans.da_Count*sizeof(CSpan);
slMem += CRenderer::re_aiClipBuffer.sa_Count*sizeof(INDEX);
slMem += CRenderer::re_aiEdgeVxClipSrc.sa_Count*sizeof(INDEX);
slMem += CRenderer::re_aiEdgeVxClipDst.sa_Count*sizeof(INDEX);
slMem += CRenderer::re_alhAddLists.sa_Count*sizeof(CListHead);
slMem += CRenderer::re_actAddCounts.sa_Count*sizeof(INDEX);
slMem += CRenderer::re_apsedRemoveFirst.sa_Count*sizeof(CScreenEdge *);
slMem += CRenderer::re_atcTranslucentPolygons.da_Count*sizeof(CTranslucentPolygon);
slMem += CRenderer::re_aaceActiveEdges.sa_Count*sizeof(CActiveEdge);
slMem += CRenderer::re_aaceActiveEdgesTmp.sa_Count*sizeof(CActiveEdge);
for (INDEX ire = 0; ire<MAX_RENDERERS; ire++) {
CRenderer &re = _areRenderers[ire];
slMem += re.re_aspoScreenPolygons.da_Count*sizeof(CScreenPolygon);
slMem += re.re_admDelayedModels.da_Count*sizeof(CDelayedModel);
slMem += re.re_cenDrawn.sa_Count*sizeof(CEntity*);
slMem += re.re_alfiLensFlares.sa_Count*sizeof(CLensFlareInfo);
slMem += re.re_amiMirrors.da_Count*sizeof(CMirror);
slMem += re.re_avvxViewVertices.sa_Count*sizeof(CViewVertex);
slMem += re.re_aiEdgeVxMain.sa_Count*sizeof(INDEX);
}
CPrintF("Temporary memory used: %dk\n", slMem/1024);
}
void ClearRenderer(void)
{
CRenderer::re_aadeAddEdges.Clear();
CRenderer::re_asedScreenEdges.Clear();
CRenderer::re_aspSpans.Clear();
CRenderer::re_aiClipBuffer.Clear();
CRenderer::re_aiEdgeVxClipSrc.Clear();
CRenderer::re_aiEdgeVxClipDst.Clear();
CRenderer::re_alhAddLists.Clear();
CRenderer::re_actAddCounts.Clear();
CRenderer::re_apsedRemoveFirst.Clear();
CRenderer::re_atcTranslucentPolygons.Clear();
CRenderer::re_aaceActiveEdges.Clear();
CRenderer::re_aaceActiveEdgesTmp.Clear();
for (INDEX ire = 0; ire<MAX_RENDERERS; ire++) {
CRenderer &re = _areRenderers[ire];
re.re_aspoScreenPolygons.Clear();
re.re_admDelayedModels.Clear();
re.re_cenDrawn.Clear();
re.re_alfiLensFlares.Clear();
re.re_amiMirrors.Clear();
re.re_avvxViewVertices.Clear();
re.re_aiEdgeVxMain.Clear();
}
CPrintF("Renderer buffers cleared.\n");
}
/*
* How much to offset left, right, top and bottom clipping towards inside (in pixels).
* This can be used to test clipping or to add an epsilon value for it.
*/
//#define CLIPMARGIN 10.0f // used for debugging clipping
#define CLIPMARGIN 0.0f
#define CLIPEPSILON 0.5f
#define CLIPMARGADD (CLIPMARGIN-CLIPEPSILON)
#define CLIPMARGSUB (CLIPMARGIN+CLIPEPSILON)
#define SENTINELEDGE_EPSILON 0.4f
#include "RendMisc.cpp"
#include "RenCache.cpp"
#include "RendClip.cpp"
#include "RendASER.cpp"
#include "RenderModels.cpp"
#include "RenderBrushes.cpp"
#include "RenderAdding.cpp"
extern FLOAT wld_fEdgeOffsetI;
extern FLOAT wld_fEdgeAdjustK;
// initialize all rendering structures
void CRenderer::Initialize(void)
{
_pfRenderProfile.StartTimer(CRenderProfile::PTI_INITIALIZATION);
// used for fixing problems with extra trapezoids generated on t-junctions
if( !re_bRenderingShadows) {
re_fEdgeOffsetI = wld_fEdgeOffsetI; //0.125f;
re_fEdgeAdjustK = wld_fEdgeAdjustK; //1.0001f;
} else {
re_fEdgeOffsetI = 0.0f;
re_fEdgeAdjustK = 1.0f;
}
// prepare the raw projection (used for rendering target lines and getting object distances)
re_prProjection->ObjectPlacementL() = CPlacement3D(FLOAT3D(0.0f,0.0f,0.0f), ANGLE3D(0,0,0));
re_prProjection->ObjectFaceForwardL() = FALSE;
re_prProjection->ObjectStretchL() = FLOAT3D(1.0f, 1.0f, 1.0f);
re_prProjection->DepthBufferNearL() = 0.0f;
re_prProjection->DepthBufferFarL() = 0.9f;
re_prProjection->Prepare();
re_asedScreenEdges.PopAll();
re_aadeAddEdges.PopAll();
re_aspSpans.PopAll();
re_avvxViewVertices.PopAll();
re_aiEdgeVxMain.PopAll();
// if more scan lines are needed than last time
if (re_alhAddLists.Count()<re_ctScanLines) {
re_alhAddLists.Clear();
re_alhAddLists.New(re_ctScanLines);
re_actAddCounts.Clear();
re_actAddCounts.New(re_ctScanLines);
re_apsedRemoveFirst.Clear();
re_apsedRemoveFirst.New(re_ctScanLines);
}
// clear all add/remove lists
for(INDEX iScan=0; iScan<re_ctScanLines; iScan++) {
re_actAddCounts[iScan] = 0;
re_apsedRemoveFirst[iScan] = NULL;
}
// find selection color
re_colSelection = C_RED;
if (_wrpWorldRenderPrefs.GetSelectionType() == CWorldRenderPrefs::ST_POLYGONS) {
re_colSelection = C_YELLOW;
} else if (_wrpWorldRenderPrefs.GetSelectionType() == CWorldRenderPrefs::ST_SECTORS) {
re_colSelection = C_GREEN;
} else if (_wrpWorldRenderPrefs.GetSelectionType() == CWorldRenderPrefs::ST_ENTITIES) {
re_colSelection = C_BLUE;
}
// set up renderer for first scan line
re_iCurrentScan = 0;
re_pixCurrentScanJ = re_iCurrentScan + re_pixTopScanLineJ;
re_fCurrentScanJ = FLOAT(re_pixCurrentScanJ);
// no fog or haze initially
re_bCurrentSectorHasHaze = FALSE;
re_bCurrentSectorHasFog = FALSE;
_pfRenderProfile.StopTimer(CRenderProfile::PTI_INITIALIZATION);
}
// add initial sectors to active lists
void CRenderer::AddInitialSectors(void)
{
_pfRenderProfile.StartTimer(CRenderProfile::PTI_ADDINITIAL);
re_bViewerInHaze = FALSE;
re_ulVisExclude = 0;
re_ulVisInclude = 0;
// if showing vis tweaks
if (_wrpWorldRenderPrefs.wrp_bShowVisTweaksOn && _pselbscVisTweaks!=NULL) {
// add flags for selected flags
if (_pselbscVisTweaks->Count()>0) {
re_ulVisExclude = VISM_INCLUDEEXCLUDE;
}
FOREACHINDYNAMICCONTAINER(*_pselbscVisTweaks, CBrushSector, itbsc) {
if (itbsc->bsc_ulFlags2&BSCF2_VISIBILITYINCLUDE) {
re_ulVisInclude = itbsc->bsc_ulVisFlags&VISM_INCLUDEEXCLUDE;
} else {
re_ulVisExclude &= itbsc->bsc_ulVisFlags&VISM_INCLUDEEXCLUDE;
}
}
}
// check if the background is needed
re_bBackgroundEnabled = FALSE;
if (!re_bRenderingShadows && _wrpWorldRenderPrefs.wrp_bBackgroundTextureOn) {
CEntity *penBackgroundViewer = re_pwoWorld->GetBackgroundViewer();
if (penBackgroundViewer!=NULL) {
re_bBackgroundEnabled = TRUE;
re_penBackgroundViewer = penBackgroundViewer;
re_prBackgroundProjection = re_prProjection;
CPlacement3D plViewer = re_prProjection->ViewerPlacementR();
plViewer.pl_PositionVector = FLOAT3D(0,0,0);
CPlacement3D plBcgViewer = penBackgroundViewer->GetLerpedPlacement();
if (re_prProjection->pr_bMirror) {
ReflectPositionVectorByPlane(re_prProjection->pr_plMirror, plBcgViewer.pl_PositionVector);
}
plViewer.RelativeToAbsoluteSmooth(plBcgViewer);
re_prBackgroundProjection->ViewerPlacementL() = plViewer;
re_prBackgroundProjection->ObjectPlacementL() = CPlacement3D(FLOAT3D(0,0,0), ANGLE3D(0,0,0));
re_prBackgroundProjection->FarClipDistanceL() = -1.0f;
re_prBackgroundProjection->DepthBufferNearL() = 0.9f;
re_prBackgroundProjection->DepthBufferFarL() = 1.0f;
re_prBackgroundProjection->TurnOffWarpPlane(); // background never needs warp-plane clipping
re_prBackgroundProjection->Prepare();
}
}
// if a viewer entity is given
if (re_penViewer!=NULL) {
// add all zoning sectors near the entity
AddZoningSectorsAroundEntity(re_penViewer, re_prProjection->ViewerPlacementR().pl_PositionVector);
// make sure the viewer is always added (if model)
if(re_penViewer->en_RenderType==CEntity::RT_MODEL ||
re_penViewer->en_RenderType==CEntity::RT_EDITORMODEL) {
AddModelEntity(re_penViewer);
}
// if a viewer polygons are given
} else if (re_pcspoViewPolygons!=NULL) {
// for each polygon
FOREACHINDYNAMICCONTAINER(*re_pcspoViewPolygons, CScreenPolygon, itspo) {
CBrushPolygon *pbpo = itspo->spo_pbpoBrushPolygon;
// get the sector, sector's brush mip, brush and entity
CBrushSector *pbsc = pbpo->bpo_pbscSector;
CBrushMip *pbmBrushMip = pbsc->bsc_pbmBrushMip;
CBrush3D *pbrBrush = pbmBrushMip->bm_pbrBrush;
ASSERT(pbrBrush!=NULL);
CEntity *penBrush = pbrBrush->br_penEntity;
// if the brush is zoning
if (penBrush->en_ulFlags&ENF_ZONING) {
// add the sector that the polygon is in
AddGivenZoningSector(pbsc);
// if the brush is non-zoning
} else {
// add sectors around it
AddZoningSectorsAroundEntity(penBrush, penBrush->GetPlacement().pl_PositionVector);
}
}
// if there is no viewer entity/polygon
} else {
// set up viewer bounding box as box of minimum redraw range around viewer position
if (re_bRenderingShadows) {
// NOTE: when rendering shadows, this is set in ::RenderShadows()
//re_boxViewer = FLOATaabbox3D(re_prProjection->ViewerPlacementR().pl_PositionVector,
// 1.0f);
} else {
re_boxViewer = FLOATaabbox3D(re_prProjection->ViewerPlacementR().pl_PositionVector,
_wrpWorldRenderPrefs.wrp_fMinimumRenderRange);
}
// add all zoning sectors near viewer box
AddZoningSectorsAroundBox(re_boxViewer);
// NOTE: this is so entities outside of world can be edited in WEd
// if editor models should be rendered
if (_wrpWorldRenderPrefs.IsEditorModelsOn()) {
// add all nonzoning entities near viewer box
AddEntitiesInBox(re_boxViewer);
}
}
if( wld_bAlwaysAddAll) {
AddAllEntities(); // used for profiling
} else {
// NOTE: this is so that world can be viewed from the outside in game
// if no brush sectors have been added so far
if (!re_bRenderingShadows && re_lhActiveSectors.IsEmpty()) {
// add all entities in the world
AddAllEntities();
}
}
// add the background if needed
if (re_bBackgroundEnabled) {
AddZoningSectorsAroundEntity(re_penBackgroundViewer,
re_penBackgroundViewer->GetPlacement().pl_PositionVector);
}
_pfRenderProfile.StopTimer(CRenderProfile::PTI_ADDINITIAL);
}
// scan through portals for other sectors
void CRenderer::ScanForOtherSectors(void)
{
ChangeStatsMode(CStatForm::STI_WORLDVISIBILITY);
// if shadows or polygons should be drawn
if (re_bRenderingShadows
||_wrpWorldRenderPrefs.wrp_ftPolygons != CWorldRenderPrefs::FT_NONE) {
// rasterize edges into spans
ScanEdges();
}
// for each of models that were kept for delayed rendering
for(INDEX iModel=0; iModel<re_admDelayedModels.Count(); iModel++) {
// mark the entity as not active in rendering anymore
re_admDelayedModels[iModel].dm_penModel->en_ulFlags &= ~ENF_INRENDERING;
}
ChangeStatsMode(CStatForm::STI_WORLDTRANSFORM);
}
// cleanup after scanning
void CRenderer::CleanupScanning(void)
{
_pfRenderProfile.StartTimer(CRenderProfile::PTI_CLEANUP);
// for all active sectors
{FORDELETELIST(CBrushSector, bsc_lnInActiveSectors, re_lhActiveSectors, itbsc) {
// remove it from list
itbsc->bsc_lnInActiveSectors.Remove();
// for all polygons in sector
FOREACHINSTATICARRAY(itbsc->bsc_abpoPolygons, CBrushPolygon, itpo) {
CBrushPolygon &bpo = *itpo;
// clear screen polygon pointers
bpo.bpo_pspoScreenPolygon = NULL;
}
}}
ASSERT(re_lhActiveSectors.IsEmpty());
// for all active brushes
{FORDELETELIST(CBrush3D, br_lnInActiveBrushes, re_lhActiveBrushes, itbr) {
// remove it from list
itbr->br_lnInActiveBrushes.Remove();
}}
ASSERT(re_lhActiveBrushes.IsEmpty());
// for all active terrains
{FORDELETELIST(CTerrain, tr_lnInActiveTerrains, re_lhActiveTerrains, ittr) {
// remove it from list
ittr->tr_lnInActiveTerrains.Remove();
}}
ASSERT(re_lhActiveTerrains.IsEmpty());
_pfRenderProfile.StopTimer(CRenderProfile::PTI_CLEANUP);
}
// Render active terrains
void CRenderer::RenderTerrains(void)
{
CAnyProjection3D *papr;
papr = &re_prProjection;
// for all active terrains
{FORDELETELIST(CTerrain, tr_lnInActiveTerrains, re_lhActiveTerrains, ittr) {
// render terrain
ittr->Render(*papr, re_pdpDrawPort);
}}
}
// Render active terrains in wireframe mode
void CRenderer::RenderWireFrameTerrains(void)
{
CAnyProjection3D *papr;
papr = &re_prProjection;
BOOL bShowEdges = _wrpWorldRenderPrefs.wrp_ftEdges != CWorldRenderPrefs::FT_NONE;
BOOL bShowVertices = _wrpWorldRenderPrefs.wrp_ftVertices != CWorldRenderPrefs::FT_NONE;
// BOOL bForceRegenerate = _wrpWorldRenderPrefs.wrp_ftPolygons
COLOR colEdges = _wrpWorldRenderPrefs.wrp_colEdges;
COLOR colVertices = 0xFF0000FF;
// for all active terrains
{FORDELETELIST(CTerrain, tr_lnInActiveTerrains, re_lhActiveTerrains, ittr) {
// render terrain
if(bShowEdges) {
ittr->RenderWireFrame(*papr, re_pdpDrawPort,colEdges);
}
if(bShowVertices) {
//ittr->RenderVertices(*papr, re_pdpDrawPort,colVertices);
}
}}
}
// draw the prepared things to screen
void CRenderer::DrawToScreen(void)
{
ChangeStatsMode(CStatForm::STI_WORLDRENDERING);
//------------------------------------------------- first render background
// if polygons should be drawn
if (!re_bRenderingShadows &&
_wrpWorldRenderPrefs.wrp_ftPolygons != CWorldRenderPrefs::FT_NONE) {
_pfRenderProfile.StartTimer(CRenderProfile::PTI_RENDERSCENE);
if( re_bBackgroundEnabled) {
// render the polygons to screen
CPerspectiveProjection3D *pprPerspective =
(CPerspectiveProjection3D *)(CProjection3D *)(re_prBackgroundProjection);
pprPerspective->Prepare();
RenderScene( re_pdpDrawPort, re_pspoFirstBackground, re_prBackgroundProjection, re_colSelection, FALSE);
} else {
// this is just for far sentinel
RenderSceneBackground( re_pdpDrawPort, re_spoFarSentinel.spo_spoScenePolygon.spo_cColor);
}
_pfRenderProfile.StopTimer(CRenderProfile::PTI_RENDERSCENE);
}
if (re_bBackgroundEnabled) {
// render models that were kept for delayed rendering.
ChangeStatsMode(CStatForm::STI_MODELSETUP);
RenderModels(TRUE); // render background models
ChangeStatsMode(CStatForm::STI_WORLDRENDERING);
}
// if polygons should be drawn
if (!re_bRenderingShadows &&
re_bBackgroundEnabled
&&_wrpWorldRenderPrefs.wrp_ftPolygons != CWorldRenderPrefs::FT_NONE) {
// render translucent portals
_pfRenderProfile.StartTimer(CRenderProfile::PTI_RENDERSCENE);
CPerspectiveProjection3D *pprPerspective = (CPerspectiveProjection3D*)(CProjection3D*)(re_prBackgroundProjection);
RenderScene( re_pdpDrawPort, SortTranslucentPolygons(re_pspoFirstBackgroundTranslucent),
re_prBackgroundProjection, re_colSelection, TRUE);
_pfRenderProfile.StopTimer(CRenderProfile::PTI_RENDERSCENE);
}
if( re_bBackgroundEnabled) {
ChangeStatsMode(CStatForm::STI_PARTICLERENDERING);
RenderParticles(TRUE); // render background particless
ChangeStatsMode(CStatForm::STI_WORLDRENDERING);
}
//------------------------------------------------- second render non-background
// if polygons should be drawn
if( !re_bRenderingShadows
&& _wrpWorldRenderPrefs.wrp_ftPolygons != CWorldRenderPrefs::FT_NONE) {
// render the spans to screen
re_prProjection->Prepare();
_pfRenderProfile.StartTimer(CRenderProfile::PTI_RENDERSCENE);
CPerspectiveProjection3D *pprPerspective = (CPerspectiveProjection3D*)(CProjection3D*)re_prProjection;
RenderScene( re_pdpDrawPort, re_pspoFirst, re_prProjection, re_colSelection, FALSE);
_pfRenderProfile.StopTimer(CRenderProfile::PTI_RENDERSCENE);
}
// Render active terrains
if( !re_bRenderingShadows
&& _wrpWorldRenderPrefs.wrp_ftPolygons != CWorldRenderPrefs::FT_NONE) {
RenderTerrains();
}
// if wireframe should be drawn
if( !re_bRenderingShadows &&
( _wrpWorldRenderPrefs.wrp_ftEdges != CWorldRenderPrefs::FT_NONE
|| _wrpWorldRenderPrefs.wrp_ftVertices != CWorldRenderPrefs::FT_NONE
|| _wrpWorldRenderPrefs.wrp_stSelection == CWorldRenderPrefs::ST_VERTICES
|| _wrpWorldRenderPrefs.IsFieldBrushesOn())) {
// render in wireframe all brushes that were added (in orthographic projection!)
re_pdpDrawPort->SetOrtho();
RenderWireFrameBrushes();
RenderWireFrameTerrains();
}
// render models that were kept for delayed rendering
ChangeStatsMode(CStatForm::STI_MODELSETUP);
RenderModels(FALSE); // render non-background models
ChangeStatsMode(CStatForm::STI_PARTICLERENDERING);
RenderParticles(FALSE); // render non-background particles
ChangeStatsMode(CStatForm::STI_WORLDRENDERING);
// if polygons should be drawn
if (!re_bRenderingShadows
&&_wrpWorldRenderPrefs.wrp_ftPolygons != CWorldRenderPrefs::FT_NONE) {
// render translucent portals
_pfRenderProfile.StartTimer(CRenderProfile::PTI_RENDERSCENE);
CPerspectiveProjection3D *pprPerspective = (CPerspectiveProjection3D*)(CProjection3D*)re_prProjection;
pprPerspective->Prepare();
RenderScene( re_pdpDrawPort, SortTranslucentPolygons(re_pspoFirstTranslucent),
re_prProjection, re_colSelection, TRUE);
_pfRenderProfile.StopTimer(CRenderProfile::PTI_RENDERSCENE);
}
// render lens flares
if( !re_bRenderingShadows) {
ChangeStatsMode(CStatForm::STI_FLARESRENDERING);
RenderLensFlares(); // (this also sets orthographic projection!)
ChangeStatsMode(CStatForm::STI_WORLDRENDERING);
}
// if entity targets should be drawn
if( !re_bRenderingShadows && _wrpWorldRenderPrefs.wrp_bShowTargetsOn) {
// render entity targets
RenderEntityTargets();
}
// if entity targets should be drawn
if( !re_bRenderingShadows && _wrpWorldRenderPrefs.wrp_bShowEntityNames) {
RenderEntityNames();
}
// clean all buffers after rendering
re_aspoScreenPolygons.PopAll();
re_admDelayedModels.PopAll();
re_cenDrawn.PopAll();
re_avvxViewVertices.PopAll();
}
// draw mirror polygons to z-buffer to enable drawing of mirror
void CRenderer::FillMirrorDepth(CMirror &mi)
{
// create a list of scene polygons for mirror
ScenePolygon *pspoFirst = NULL;
// for each polygon
FOREACHINDYNAMICCONTAINER(mi.mi_cspoPolygons, CScreenPolygon, itspo) {
CScreenPolygon &spo = *itspo;
CBrushPolygon &bpo = *spo.spo_pbpoBrushPolygon;
// create a new screen polygon
CScreenPolygon &spoNew = re_aspoScreenPolygons.Push();
ScenePolygon &sppoNew = spoNew.spo_spoScenePolygon;
// add it to mirror list
sppoNew.spo_pspoSucc = pspoFirst;
pspoFirst = &sppoNew;
// use same triangles
sppoNew.spo_iVtx0 = spo.spo_spoScenePolygon.spo_iVtx0;
sppoNew.spo_ctVtx = spo.spo_spoScenePolygon.spo_ctVtx;
sppoNew.spo_piElements = spo.spo_spoScenePolygon.spo_piElements;
sppoNew.spo_ctElements = spo.spo_spoScenePolygon.spo_ctElements;
}
// render all those polygons just to clear z-buffer
RenderSceneZOnly( re_pdpDrawPort, pspoFirst, re_prProjection);
}
// do the rendering
void CRenderer::Render(void)
{
// if the world doesn't have all portal-sector links updated
if( !re_pwoWorld->wo_bPortalLinksUpToDate) {
// update the links
CSetFPUPrecision FPUPrecision(FPT_53BIT);
re_pwoWorld->wo_baBrushes.LinkPortalsAndSectors();
re_pwoWorld->wo_bPortalLinksUpToDate = TRUE;
}
StartStatsMode(CStatForm::STI_WORLDTRANSFORM);
_pfRenderProfile.IncrementAveragingCounter();
_pfRenderProfile.StartTimer(CRenderProfile::PTI_RENDERING);
// set FPU to single precision while rendering
CSetFPUPrecision FPUPrecision(FPT_24BIT);
// initialize all rendering structures
Initialize();
// init select-on-render functionality if not rendering shadows
extern void InitSelectOnRender( PIX pixSizeI, PIX pixSizeJ);
if( re_pdpDrawPort!=NULL) InitSelectOnRender( re_pdpDrawPort->GetWidth(), re_pdpDrawPort->GetHeight());
// add initial sectors to active lists
AddInitialSectors();
// scan through portals for other sectors
ScanForOtherSectors();
// force finishing of all OpenGL pending operations, if required
ChangeStatsMode(CStatForm::STI_SWAPBUFFERS);
extern INDEX ogl_iFinish; ogl_iFinish = Clamp( ogl_iFinish, 0L, 3L);
extern INDEX d3d_iFinish; d3d_iFinish = Clamp( d3d_iFinish, 0L, 3L);
if( (ogl_iFinish==1 && _pGfx->gl_eCurrentAPI==GAT_OGL)
#ifdef SE1_D3D
|| (d3d_iFinish==1 && _pGfx->gl_eCurrentAPI==GAT_D3D)
#endif // SE1_D3D
)
gfxFinish();
// check any eventual delayed depth points outside the mirror (if API and time allows)
if( !re_bRenderingShadows && re_iIndex==0) {
// OpenGL allows us to check z-buffer from previous frame - cool deal!
// Direct3D is, of course, totally different story. :(
if( _pGfx->gl_eCurrentAPI==GAT_OGL || _pGfx->gl_eCurrentAPI == GAT_VK || d3d_bAlternateDepthReads) {
ChangeStatsMode(CStatForm::STI_FLARESRENDERING);
extern void CheckDelayedDepthPoints( const CDrawPort *pdp, INDEX iMirrorLevel=0);
CheckDelayedDepthPoints(re_pdpDrawPort);
}
// in 1st pass - mirrors are not drawn
_bMirrorDrawn = FALSE;
}
// if may render one more mirror recursion
ChangeStatsMode(CStatForm::STI_WORLDTRANSFORM);
if( !re_bRenderingShadows
&& re_prProjection.IsPerspective()
&& re_iIndex<MAX_RENDERERS-1
&& re_amiMirrors.Count()>0
&& !re_pdpDrawPort->IsOverlappedRendering())
{
// cleanup after scanning
CleanupScanning();
// take next renderer
CRenderer &re = _areRenderers[re_iIndex+1];
// for each mirror
for( INDEX i=0; i<re_amiMirrors.Count(); i++)
{
// skip invalid mirrors
CMirror &mi = re_amiMirrors[i];
if( mi.mi_iMirrorType<0) continue;
// calculate all needed data for the mirror
mi.FinishAdding();
// skip mirror that has no significant area
if( mi.mi_fpixMaxPolygonArea<5) continue;
// expand mirror in each direction, but keep it inside drawport
PIX pixDPSizeI = re_pdpDrawPort->GetWidth();
PIX pixDPSizeJ = re_pdpDrawPort->GetHeight();
mi.mi_boxOnScreen.Expand(1);
mi.mi_boxOnScreen &= PIXaabbox2D( PIX2D(0,0), PIX2D(pixDPSizeI,pixDPSizeJ));
// get drawport and mirror coordinates
PIX pixMirrorMinI = mi.mi_boxOnScreen.Min()(1);
PIX pixMirrorMinJ = mi.mi_boxOnScreen.Min()(2);
PIX pixMirrorMaxI = mi.mi_boxOnScreen.Max()(1);
PIX pixMirrorMaxJ = mi.mi_boxOnScreen.Max()(2);
// calculate mirror size
PIX pixMirrorSizeI = pixMirrorMaxI-pixMirrorMinI;
PIX pixMirrorSizeJ = pixMirrorMaxJ-pixMirrorMinJ;
// clone drawport (must specify doubles here, to keep the precision)
re_pdpDrawPort->Unlock();
CDrawPort dpMirror( re_pdpDrawPort, pixMirrorMinI /(DOUBLE)pixDPSizeI, pixMirrorMinJ /(DOUBLE)pixDPSizeJ,
pixMirrorSizeI/(DOUBLE)pixDPSizeI, pixMirrorSizeJ/(DOUBLE)pixDPSizeJ);
// skip if cannot be locked
if( !dpMirror.Lock()) {
// lock back the original drawport
re_pdpDrawPort->Lock();
continue;
}
// recalculate mirror size to compensate for possible lost precision
pixMirrorMinI = dpMirror.dp_MinI - re_pdpDrawPort->dp_MinI;
pixMirrorMinJ = dpMirror.dp_MinJ - re_pdpDrawPort->dp_MinJ;
pixMirrorMaxI = dpMirror.dp_MaxI - re_pdpDrawPort->dp_MinI +1;
pixMirrorMaxJ = dpMirror.dp_MaxJ - re_pdpDrawPort->dp_MinJ +1;
pixMirrorSizeI = pixMirrorMaxI-pixMirrorMinI;
pixMirrorSizeJ = pixMirrorMaxJ-pixMirrorMinJ;
ASSERT( pixMirrorSizeI==dpMirror.dp_Width && pixMirrorSizeJ==dpMirror.dp_Height);
// set it up for rendering
re.re_pwoWorld = re_pwoWorld;
re.re_prProjection = re_prProjection;
re.re_pdpDrawPort = &dpMirror;
// initialize clipping rectangle around the mirror size
re.InitClippingRectangle( 0, 0, pixMirrorSizeI, pixMirrorSizeJ);
// setup projection to use the mirror drawport and keep same perspective as before
re.re_prProjection->ScreenBBoxL() = FLOATaabbox2D( FLOAT2D(0,0), FLOAT2D(pixDPSizeI, pixDPSizeJ));
((CPerspectiveProjection3D&)(*re.re_prProjection)).ppr_boxSubScreen =
FLOATaabbox2D( FLOAT2D(pixMirrorMinI, pixMirrorMinJ), FLOAT2D(pixMirrorMaxI, pixMirrorMaxJ));
// warp?
if( mi.mi_mp.mp_ulFlags&MPF_WARP) {
// warp clip plane is parallel to view plane and contains the closest point
re.re_penViewer = mi.mi_mp.mp_penWarpViewer;
re.re_pcspoViewPolygons = NULL;
re.re_prProjection->WarpPlaneL() = FLOATplane3D(FLOAT3D(0,0,-1), mi.mi_vClosest);
// create new viewer placement
CPlacement3D pl = re.re_prProjection->ViewerPlacementR();
FLOATmatrix3D m;
MakeRotationMatrixFast(m, pl.pl_OrientationAngle);
pl.AbsoluteToRelativeSmooth(mi.mi_mp.mp_plWarpIn);
pl.RelativeToAbsoluteSmooth(mi.mi_mp.mp_plWarpOut);
re.re_prProjection->ViewerPlacementL() = pl;
if (re.re_prProjection.IsPerspective() && mi.mi_mp.mp_fWarpFOV>=1 && mi.mi_mp.mp_fWarpFOV<=170) {
((CPerspectiveProjection3D&)*re.re_prProjection).FOVL() = mi.mi_mp.mp_fWarpFOV;
}
// mirror!
} else {
re.re_penViewer = NULL;
re.re_pcspoViewPolygons = &mi.mi_cspoPolygons;
re.re_prProjection->MirrorPlaneL() = mi.mi_plPlane;
re.re_prProjection->MirrorPlaneL().Offset(0.05f); // move projection towards mirror a bit, to avoid cracks
}
re.re_bRenderingShadows = FALSE;
re.re_ubLightIllumination = 0;
// just flat-fill if mirrors are disabled
extern INDEX wld_bRenderMirrors;
if( !wld_bRenderMirrors) dpMirror.Fill(C_GRAY|CT_OPAQUE);
else {
// render the view inside mirror
StopStatsMode();
_pfRenderProfile.StopTimer(CRenderProfile::PTI_RENDERING);
re.Render();
_pfRenderProfile.StartTimer(CRenderProfile::PTI_RENDERING);
StartStatsMode(CStatForm::STI_WORLDTRANSFORM);
}
// unlock mirror's and lock back the original drawport
dpMirror.Unlock();
re_pdpDrawPort->Lock();
// clear entire buffer to back value
re_pdpDrawPort->FillZBuffer(ZBUF_BACK);
// fill depth buffer of the mirror, so that scene cannot be drawn through it
FillMirrorDepth(mi);
_bMirrorDrawn = TRUE;
}
// flush all mirrors
re_amiMirrors.PopAll();
// fill z-buffer only if no mirrors have been drawn, not rendering second layer in world editor and not in wireframe mode
if( !_bMirrorDrawn
&& !re_pdpDrawPort->IsOverlappedRendering()
&& _wrpWorldRenderPrefs.wrp_ftPolygons != CWorldRenderPrefs::FT_NONE) {
re_pdpDrawPort->FillZBuffer(ZBUF_BACK);
}
// draw the prepared things to screen
DrawToScreen();
}
// no mirrors
else
{
// if rendering a mirror
// or not rendering second layer in world editor
// and not in wireframe mode
if( re_iIndex>0
|| !re_bRenderingShadows
&& !re_pdpDrawPort->IsOverlappedRendering()
&& _wrpWorldRenderPrefs.wrp_ftPolygons != CWorldRenderPrefs::FT_NONE) {
re_pdpDrawPort->FillZBuffer(ZBUF_BACK);
}
// draw the prepared things to screen and finish
DrawToScreen();
CleanupScanning();
}
// disable fog/haze
StopFog();
StopHaze();
// reset vertex arrays if this is the last renderer
if( re_iIndex==0) _avtxScene.PopAll();
// for D3D (or mirror) we have to check depth points now, because we need back (not depth!) buffer for it,
// and D3D can't guarantee that it won't be discarded upon swapbuffers (especially if multisampling is on!) :(
#ifdef SE1_D3D
if( !re_bRenderingShadows && ((_pGfx->gl_eCurrentAPI==GAT_D3D && !d3d_bAlternateDepthReads) || re_iIndex>0)) {
extern void CheckDelayedDepthPoints( const CDrawPort *pdp, INDEX iMirrorLevel=0);
CheckDelayedDepthPoints( re_pdpDrawPort, re_iIndex);
}
#endif // SE1_D3D
// end select-on-render functionality
extern void EndSelectOnRender(void);
EndSelectOnRender();
// assure that FPU precision was low all the rendering time
ASSERT( GetFPUPrecision()==FPT_24BIT);
StopStatsMode();
}
/*
* Constructor.
*/
CRenderer::CRenderer(void)
{
// setup self index
INDEX i = this-_areRenderers;
ASSERT(i>=0 && i<MAX_RENDERERS);
re_iIndex = i;
}
/*
* Destructor.
*/
CRenderer::~CRenderer(void)
{
}
// initialize clipping rectangle
void CRenderer::InitClippingRectangle(PIX pixMinI, PIX pixMinJ, PIX pixSizeI, PIX pixSizeJ)
{
re_pspoFirst = NULL;
re_pspoFirstTranslucent = NULL;
re_pspoFirstBackground = NULL;
re_pspoFirstBackgroundTranslucent = NULL;
re_fMinJ = (FLOAT) pixMinJ;
re_fMaxJ = (FLOAT) pixSizeJ+pixMinJ;
re_pixSizeI = pixSizeI;
re_fbbClipBox =
FLOATaabbox2D( FLOAT2D((FLOAT) pixMinI+CLIPMARGADD,
(FLOAT) pixMinJ+CLIPMARGADD),
FLOAT2D((FLOAT) pixMinI+pixSizeI-CLIPMARGSUB,
(FLOAT) pixMinJ+pixSizeJ-CLIPMARGSUB));
re_pixTopScanLineJ = PIXCoord(pixMinJ+CLIPMARGADD);
re_ctScanLines =
PIXCoord(pixSizeJ-CLIPMARGSUB) - PIXCoord(CLIPMARGADD)/* +1*/;
re_pixBottomScanLineJ = re_pixTopScanLineJ+re_ctScanLines;
}
// render a 3D view to a drawport
void RenderView(CWorld &woWorld, CEntity &enViewer,
CAnyProjection3D &prProjection, CDrawPort &dpDrawport)
{
// let the worldbase execute its render function
if (woWorld.wo_pecWorldBaseClass!=NULL
&&woWorld.wo_pecWorldBaseClass->ec_pdecDLLClass!=NULL
&&woWorld.wo_pecWorldBaseClass->ec_pdecDLLClass->dec_OnWorldRender!=NULL) {
woWorld.wo_pecWorldBaseClass->ec_pdecDLLClass->dec_OnWorldRender(&woWorld);
}
if(_wrpWorldRenderPrefs.GetShadowsType() == CWorldRenderPrefs::SHT_FULL)
{
// calculate all non directional shadows that are not up to date
woWorld.CalculateNonDirectionalShadows();
}
// take first renderer object
CRenderer &re = _areRenderers[0];
// set it up for rendering
re.re_penViewer = &enViewer;
re.re_pcspoViewPolygons = NULL;
re.re_pwoWorld = &woWorld;
re.re_prProjection = prProjection;
re.re_pdpDrawPort = &dpDrawport;
// initialize clipping rectangle around the drawport
re.InitClippingRectangle(0, 0, dpDrawport.GetWidth(), dpDrawport.GetHeight());
prProjection->ScreenBBoxL() = FLOATaabbox2D(
FLOAT2D(0.0f, 0.0f),
FLOAT2D((float)dpDrawport.GetWidth(), (float)dpDrawport.GetHeight())
);
re.re_bRenderingShadows = FALSE;
re.re_ubLightIllumination = 0;
// render the view (with eventuall t-buffer effect)
extern void SetTBufferEffect( BOOL bEnable);
SetTBufferEffect(TRUE);
re.Render();
SetTBufferEffect(FALSE);
}
// Render a world with some viewer, projection and drawport. (viewer may be NULL)
// internal version used for rendering shadows
ULONG RenderShadows(CWorld &woWorld, CEntity &enViewer,
CAnyProjection3D &prProjection, const FLOATaabbox3D &boxViewer,
UBYTE *pubShadowMask, SLONG slShadowWidth, SLONG slShadowHeight,
UBYTE ubIllumination)
{
_pfWorldEditingProfile.StartTimer(CWorldEditingProfile::PTI_RENDERSHADOWS);
// take a renderer object
CRenderer &re = _areRenderers[0];
// set it up for rendering
re.re_penViewer = &enViewer;
re.re_pcspoViewPolygons = NULL;
re.re_pwoWorld = &woWorld;
re.re_prProjection = prProjection;
re.re_pdpDrawPort = NULL;
re.re_boxViewer = boxViewer;
// initialize clipping rectangle around the drawport
const FLOATaabbox2D &box = prProjection->ScreenBBoxR();
//re.InitClippingRectangle(box.Min()(1), box.Min()(2), box.Size()(1), box.Size()(2));
re.InitClippingRectangle(0, 0, box.Size()(1), box.Size()(2));
re.re_bRenderingShadows = TRUE;
re.re_bDirectionalShadows = prProjection.IsParallel();
re.re_bSomeLightExists = FALSE;
re.re_bSomeDarkExists = FALSE;
_bSomeDarkExists = FALSE;
re.re_pubShadow = pubShadowMask;
re.re_slShadowWidth = slShadowWidth;
re.re_slShadowHeight = slShadowHeight;
re.re_ubLightIllumination = ubIllumination;
// render the view
re.Render();
ULONG ulFlags = 0;
if (!re.re_bSomeLightExists) {
ulFlags|=BSLF_ALLDARK;
}
if (!(re.re_bSomeDarkExists|_bSomeDarkExists)) {
ulFlags|=BSLF_ALLLIGHT;
}
_pfWorldEditingProfile.StopTimer(CWorldEditingProfile::PTI_RENDERSHADOWS);
return ulFlags;
}
| 37,901
|
C++
|
.cpp
| 902
| 37.906874
| 125
| 0.741045
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,536,188
|
CTString.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Base/CTString.cpp
|
/* Copyright (c) 2002-2012 Croteam Ltd.
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "stdh.h"
#include <Engine/Base/CTString.h>
#include <Engine/Base/Memory.h>
#include <Engine/Base/Stream.h>
#include <Engine/Base/Console.h>
/*
* Equality comparison.
*/
BOOL CTString::operator==(const CTString &strOther) const
{
ASSERT(IsValid() && strOther.IsValid());
return stricmp( str_String, strOther.str_String) == 0;
}
BOOL CTString::operator==(const char *strOther) const
{
ASSERT(IsValid() && strOther!=NULL);
return stricmp( str_String, strOther) == 0;
}
BOOL operator==(const char *strThis, const CTString &strOther)
{
ASSERT(strOther.IsValid() && strThis!=NULL);
return strOther == strThis;
}
/*
* Inequality comparison.
*/
BOOL CTString::operator!=(const CTString &strOther) const
{
ASSERT(IsValid() && strOther.IsValid());
return !( *this == strOther );
}
BOOL CTString::operator!=(const char *strOther) const
{
ASSERT(IsValid() && strOther!=NULL);
return !( *this == strOther );
}
BOOL operator!=(const char *strThis, const CTString &strOther)
{
ASSERT(strOther.IsValid() && strThis!=NULL);
return !( strOther == strThis);
}
/*
* String concatenation.
*/
CTString CTString::operator+(const CTString &strSecond) const
{
ASSERT(IsValid() && strSecond.IsValid());
return(CTString(*this)+=strSecond);
}
CTString operator+(const char *strFirst, const CTString &strSecond)
{
ASSERT(strFirst!=NULL && strSecond.IsValid());
return(CTString(strFirst)+=strSecond);
}
CTString &CTString::operator+=(const CTString &strSecond)
{
ASSERT(IsValid() && strSecond.IsValid());
GrowMemory( (void **)&str_String, strlen( str_String) + strlen( strSecond) + 1 );
strcat(str_String, strSecond.str_String);
return *this;
}
/*
* Remove given prefix string from this string
*/
BOOL CTString::RemovePrefix( const CTString &strPrefix)
{
INDEX lenPrefix = strlen( strPrefix);
INDEX lenDest = strlen( str_String) - lenPrefix;
if( strnicmp( str_String, strPrefix, lenPrefix) != 0)
return FALSE;
CTString strTemp = CTString( &str_String[ lenPrefix]);
ShrinkMemory( (void **)&str_String, lenDest+1);
strcpy( str_String, strTemp.str_String);
return TRUE;
}
/* Check if has given prefix */
BOOL CTString::HasPrefix( const CTString &strPrefix) const
{
INDEX lenPrefix = strlen( strPrefix);
if( strnicmp( str_String, strPrefix, lenPrefix) != 0)
return FALSE;
return TRUE;
}
/* Find index of a substring in a string (returns -1 if not found). */
INDEX CTString::FindSubstr(const CTString &strSub)
{
INDEX ct = Length();
INDEX ctSub = strSub.Length();
for (INDEX i=0; i<ct-ctSub+1; i++) {
for (INDEX iSub=0; iSub<ctSub; iSub++) {
if ((*this)[i+iSub]!=strSub[iSub]) {
goto wrong;
}
}
return i;
wrong:;
}
return -1;
}
/* Replace a substring in a string. */
BOOL CTString::ReplaceSubstr(const CTString &strSub, const CTString &strNewSub)
{
INDEX iPos = FindSubstr(strSub);
if (iPos<0) {
return FALSE;
}
CTString strPart1, strPart2;
Split(iPos, strPart1, strPart2);
strPart2.RemovePrefix(strSub);
*this = strPart1+strNewSub+strPart2;
return TRUE;
}
/* Trim the string from left to contain at most given number of characters. */
INDEX CTString::TrimLeft( INDEX ctCharacters)
{
// clamp negative values
if( ctCharacters<0) ctCharacters = 0;
// find how much characters to remove
INDEX lenOriginal = strlen(str_String);
INDEX lenPrefix = lenOriginal-ctCharacters;
// if nothing needs to be removed
if( lenPrefix<=0) return 0;
// crop
memmove( str_String, &str_String[ lenPrefix], ctCharacters+1);
ShrinkMemory( (void **)&str_String, ctCharacters+1);
return lenPrefix;
}
/* Trim the string from right to contain at most given number of characters. */
INDEX CTString::TrimRight( INDEX ctCharacters)
{
// clamp negative values
if( ctCharacters<0) ctCharacters = 0;
// find how much characters to remove
INDEX lenOriginal = strlen(str_String);
INDEX lenPrefix = lenOriginal-ctCharacters;
// if nothing needs to be removed
if( lenPrefix<=0) return 0;
// crop
str_String[ctCharacters] = '\0';
ShrinkMemory( (void**)&str_String, ctCharacters+1);
return lenPrefix;
}
// return naked length of the string (ignoring all decorate codes)
INDEX CTString::LengthNaked(void) const
{
return Undecorated().Length();
}
// strip decorations from the string
CTString CTString::Undecorated(void) const
{
// make a copy of the string to hold the result - we will rewrite it without the codes
CTString strResult = *this;
// start at the beginning of both strings
const char *pchSrc = str_String;
char *pchDst = strResult.str_String;
// while the source is not finished
while(pchSrc[0]!=0) {
// if the source char is not escape char
if (pchSrc[0]!='^') {
// copy it over
*pchDst++ = *pchSrc++;
// go to next char
continue;
}
// check the next char
switch(pchSrc[1]) {
// if one of the control codes, skip corresponding number of characters
case 'c': pchSrc += 2+FindZero((UBYTE*)pchSrc+2,6); break;
case 'a': pchSrc += 2+FindZero((UBYTE*)pchSrc+2,2); break;
case 'f': pchSrc += 2+FindZero((UBYTE*)pchSrc+2,2); break;
case 'b': case 'i': case 'r': case 'o':
case 'C': case 'A': case 'F': case 'B': case 'I': pchSrc+=2; break;
// if it is the escape char again, skip the first escape and copy the char
case '^': pchSrc++; *pchDst++ = *pchSrc++; break;
// if it is something else
default:
// just copy over the control char
*pchDst++ = *pchSrc++;
break;
}
}
*pchDst++ = 0;
ASSERT(strResult.Length()<=Length());
return strResult;
}
BOOL IsSpace(char c)
{
return c==' ' || c=='\t' || c=='\n' || c=='\r';
}
/* Trim the string from from spaces from left. */
INDEX CTString::TrimSpacesLeft(void)
{
// for each character in string
const char *chr;
for(chr = str_String; *chr!=0; chr++) {
// if the character is not space
if (!IsSpace(*chr)) {
// stop searching
break;
}
}
// trim to that character
return TrimLeft(str_String+strlen(str_String) - chr);
}
/* Trim the string from from spaces from right. */
INDEX CTString::TrimSpacesRight(void)
{
// for each character in string reversed
const char *chr;
for(chr = str_String+strlen(str_String)-1; chr>str_String; chr--) {
// if the character is not space
if (!IsSpace(*chr)) {
// stop searching
break;
}
}
// trim to that character
return TrimRight(chr-str_String+1);
}
// retain only first line of the string
void CTString::OnlyFirstLine(void)
{
// get position of first line end
const char *pchNL = strchr(str_String, '\n');
// if none
if (pchNL==NULL) {
// do nothing
return;
}
// trim everything after that char
TrimRight(pchNL-str_String);
}
/* Calculate hashing value for the string. */
ULONG CTString::GetHash(void) const
{
ULONG ulKey = 0;
INDEX len = strlen(str_String);
for(INDEX i=0; i<len; i++) {
ulKey = _rotl(ulKey,4)+toupper(str_String[i]);
}
return ulKey;
}
/*
* Throw exception
*/
void CTString::Throw_t(void)
{
throw(str_String);
}
/*
* Read from stream.
*/
CTStream &operator>>(CTStream &strmStream, CTString &strString)
{
ASSERT(strString.IsValid());
// read length
INDEX iLength;
strmStream>>iLength;
ASSERT(iLength>=0);
// allocate that much memory
FreeMemory(strString.str_String);
strString.str_String = (char *) AllocMemory(iLength+1); // take end-marker in account
// if the string is not empty
if (iLength>0) {
// read string
strmStream.Read_t( strString.str_String, iLength); // without end-marker
}
// set end-marker
strString.str_String[iLength] = 0;
return strmStream;
}
void CTString::ReadFromText_t(CTStream &strmStream,
const CTString &strKeyword="") // throw char *
{
ASSERT(IsValid());
// keyword must be present
strmStream.ExpectKeyword_t(strKeyword);
// read the string from the file
char str[1024];
strmStream.GetLine_t(str, sizeof(str));
// copy it here
(*this) = str;
}
/*
* Write to stream.
*/
CTStream &operator<<(CTStream &strmStream, const CTString &strString)
{
ASSERT(strString.IsValid());
// calculate size
INDEX iStringLen = strlen( strString);
// write size
strmStream<<iStringLen;
// if the string is not empty
if (iStringLen>0) {
// write string
strmStream.Write_t(strString.str_String, iStringLen); // without end-marker
}
return strmStream;
}
#ifndef NDEBUG
/*
* Check if string data is valid.
*/
BOOL CTString::IsValid(void) const
{
ASSERT(this!=NULL && str_String!=NULL);
return TRUE;
}
#endif // NDEBUG
/* Load an entire text file into a string. */
void CTString::ReadUntilEOF_t(CTStream &strmFile) // throw char *
{
// get the file size
SLONG slFileSize = strmFile.GetStreamSize()-strmFile.GetPos_t();
// allocate that much memory
FreeMemory(str_String);
str_String = (char *) AllocMemory(slFileSize+1); // take end-marker in account
// read the entire file there
if (slFileSize>0) {
strmFile.Read_t( str_String, slFileSize);
}
// add end marker
str_String[slFileSize] = 0;
// rewrite entire string
char *pchRead=str_String;
char *pchWrite=str_String;
while(*pchRead!=0) {
// skip the '\r' characters
if (*pchRead!='\r') {
*pchWrite++ = *pchRead++;
} else {
pchRead++;
}
}
*pchWrite = 0;
}
void CTString::Load_t(const class CTFileName &fnmFile) // throw char *
{
ASSERT(IsValid());
// open the file for reading
CTFileStream strmFile;
strmFile.Open_t(fnmFile);
// read string until end of file
ReadUntilEOF_t(strmFile);
}
void CTString::LoadKeepCRLF_t(const class CTFileName &fnmFile) // throw char *
{
ASSERT(IsValid());
// open the file for reading
CTFileStream strmFile;
strmFile.Open_t(fnmFile);
// get the file size
SLONG slFileSize = strmFile.GetStreamSize();
// allocate that much memory
FreeMemory(str_String);
str_String = (char *) AllocMemory(slFileSize+1); // take end-marker in account
// read the entire file there
if (slFileSize>0) {
strmFile.Read_t( str_String, slFileSize);
}
// add end marker
str_String[slFileSize] = 0;
}
/* Save an entire string into a text file. */
void CTString::Save_t(const class CTFileName &fnmFile) // throw char *
{
// open the file for writing
CTFileStream strmFile;
strmFile.Create_t(fnmFile);
// save the string to the file
strmFile.PutString_t(*this);
}
void CTString::SaveKeepCRLF_t(const class CTFileName &fnmFile) // throw char *
{
// open the file for writing
CTFileStream strmFile;
strmFile.Create_t(fnmFile);
// save the string to the file
if (strlen(str_String)>0) {
strmFile.Write_t(str_String, strlen(str_String));
}
}
// Print formatted to a string
INDEX CTString::PrintF(const char *strFormat, ...)
{
va_list arg;
va_start(arg, strFormat);
return VPrintF(strFormat, arg);
}
INDEX CTString::VPrintF(const char *strFormat, va_list arg)
{
static INDEX _ctBufferSize = 0;
static char *_pchBuffer = NULL;
// if buffer was not allocated yet
if (_ctBufferSize==0) {
// allocate it
_ctBufferSize = 256;
_pchBuffer = (char*)AllocMemory(_ctBufferSize);
}
// repeat
INDEX iLen;
FOREVER {
// print to the buffer
iLen = _vsnprintf(_pchBuffer, _ctBufferSize, strFormat, arg);
// if printed ok
if (iLen!=-1) {
// stop
break;
}
// increase the buffer size
_ctBufferSize += 256;
GrowMemory((void**)&_pchBuffer, _ctBufferSize);
}
(*this) = _pchBuffer;
return iLen;
}
static void *psscanf = &sscanf;
// Scan formatted from a string
__declspec(naked) INDEX CTString::ScanF(const char *strFormat, ...)
{
__asm {
push eax
mov eax,dword ptr [esp+8]
mov eax,dword ptr [eax]
mov dword ptr [esp+8], eax
pop eax
jmp dword ptr [psscanf]
}
}
// split string in two strings at specified position (char AT splitting position goes to str2)
void CTString::Split( INDEX iPos, CTString &str1, CTString &str2)
{
str1 = str_String;
str2 = str_String;
str1.TrimRight(iPos);
str2.TrimLeft(strlen(str2)-iPos);
}
// insert one character in string at specified pos
void CTString::InsertChar( INDEX iPos, char cChr)
{
// clamp position
INDEX ctChars = strlen(str_String);
if( iPos>ctChars) iPos=ctChars;
else if( iPos<0) iPos=0;
// grow memory used by string
GrowMemory( (void**)&str_String, ctChars+2);
// copy part of string to make room for char to insert
memmove( &str_String[iPos+1], &str_String[iPos], ctChars+1-iPos);
str_String[iPos] = cChr;
}
// delete one character from string at specified pos
void CTString::DeleteChar( INDEX iPos)
{
// clamp position
INDEX ctChars = strlen(str_String);
if (ctChars==0) {
return;
}
if( iPos>ctChars) iPos=ctChars;
else if( iPos<0) iPos=0;
// copy part of string
memmove( &str_String[iPos], &str_String[iPos+1], ctChars-iPos+1);
// shrink memory used by string over deleted char
ShrinkMemory( (void**)&str_String, ctChars);
}
// wild card comparison
BOOL CTString::Matches(const CTString &strOther) const
{
return Matches(strOther.str_String);
}
BOOL CTString::Matches(const char *strOther) const
{
// pattern matching code from sourceforge.net codesnippet archive
// adjusted a bit to match in/out parameters
#define MAX_CALLS 200
int calls=0, wild=0, q=0;
const char *mask=strOther, *name=str_String;
const char *m=mask, *n=name, *ma=mask, *na=name;
for(;;) {
if (++calls > MAX_CALLS) {
return FALSE;
}
if (*m == '*') {
while (*m == '*') ++m;
wild = 1;
ma = m;
na = n;
}
if (!*m) {
if (!*n) {
return TRUE;
}
for (--m; (m > mask) && (*m == '?'); --m) ;
if ((*m == '*') && (m > mask) &&
(m[-1] != '\\')) {
return TRUE;
}
if (!wild) {
return FALSE;
}
m = ma;
} else if (!*n) {
while(*m == '*') ++m;
if (*m != 0) {
return FALSE;
} else {
return TRUE;
}
}
if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?'))) {
++m;
q = 1;
} else {
q = 0;
}
if (((tolower(*m) != tolower(*n)) && ((*m!='\\') && (*n!='/')))
&& ((*m != '?') || q)) {
if (!wild) {
return FALSE;
}
m = ma;
n = ++na;
} else {
if (*m) ++m;
if (*n) ++n;
}
}
}
// variable management functions
void CTString::LoadVar(const class CTFileName &fnmFile)
{
try {
CTString str;
str.Load_t(fnmFile);
*this = str;
} catch (char *strError) {
CPrintF(TRANS("Cannot load variable from '%s':\n%s\n"), (CTString&)fnmFile, strError);
}
}
void CTString::SaveVar(const class CTFileName &fnmFile)
{
try {
Save_t(fnmFile);
} catch (char *strError) {
CPrintF(TRANS("Cannot save variable to '%s':\n%s\n"), (CTString&)fnmFile, strError);
}
}
// general variable functions
void LoadStringVar(const CTFileName &fnmVar, CTString &strVar)
{
strVar.LoadVar(fnmVar);
}
void SaveStringVar(const CTFileName &fnmVar, CTString &strVar)
{
strVar.SaveVar(fnmVar);
}
void LoadIntVar(const CTFileName &fnmVar, INDEX &iVar)
{
CTString strVar;
strVar.LoadVar(fnmVar);
if (strVar!="") {
CTString strHex = strVar;
if (strHex.RemovePrefix("0x")) {
strHex.ScanF("%x", &iVar);
} else {
strVar.ScanF("%d", &iVar);
}
}
}
void SaveIntVar(const CTFileName &fnmVar, INDEX &iVar)
{
CTString strVar;
strVar.PrintF("%d", iVar);
strVar.SaveVar(fnmVar);
}
// remove special codes from string
CTString RemoveSpecialCodes( const CTString &str)
{
CTString strRet=str;
char *pcSrc = (char*)(const char*)strRet;
char *pcDst = (char*)(const char*)strRet;
// copy char inside string skipping special codes
while( *pcSrc != 0)
{
if( *pcSrc != '^')
{ // advance to next char
*pcDst = *pcSrc;
pcSrc++;
pcDst++;
}
else
{ // skip some characters
pcSrc++;
switch( *pcSrc) {
case 'c': pcSrc+=FindZero((UBYTE*)pcSrc,7); continue;
case 'a': pcSrc+=FindZero((UBYTE*)pcSrc,3); continue;
case 'f': pcSrc+=FindZero((UBYTE*)pcSrc,2); continue;
case 'b': case 'i': case 'r': case 'o':
case 'C': case 'A': case 'F': case 'B': case 'I': pcSrc+=1; continue;
// if we get here this means that ^ or an unrecognized special code was specified
default: continue;
}
}
}
// terminate string
*pcDst = 0;
return strRet;
}
| 17,345
|
C++
|
.cpp
| 620
| 24.566129
| 96
| 0.665502
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,536,192
|
Gfx_Vulkan.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Gfx_Vulkan.cpp
|
/* Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "stdh.h"
#include <Engine/Base/Translation.h>
#include <Engine/Base/ErrorReporting.h>
#include <Engine/Base/Memory.h>
#include <Engine/Base/Console.h>
#include <Engine/Graphics/GfxLibrary.h>
#include <Engine/Graphics/Vulkan/SvkMain.h>
#include <Engine/Graphics/ViewPort.h>
#include <Engine/Templates/StaticStackArray.cpp>
#include <Engine/Templates/DynamicContainer.cpp>
#include <Engine/Templates/Stock_CTextureData.h>
FLOAT VkProjectionMatrix[16];
FLOAT VkViewMatrix[16];
#ifdef SE1_VULKAN
#ifndef NDEBUG
#define SVK_ENABLE_VALIDATION 1
#else
#define SVK_ENABLE_VALIDATION 0
#endif // !NDEBUG
// fog/haze textures
extern ULONG _fog_ulTexture;
extern ULONG _haze_ulTexture;
static uint32_t _no_ulTexture;
static uint64_t _no_ulTextureDescSet;
extern BOOL GFX_abTexture[GFX_MAXTEXUNITS];
extern BOOL GFX_bDepthTest;
extern BOOL GFX_bDepthWrite;
extern BOOL GFX_bAlphaTest;
extern BOOL GFX_bBlending;
extern BOOL GFX_bDithering;
extern BOOL GFX_bClipping;
extern BOOL GFX_bClipPlane;
extern BOOL GFX_bColorArray;
extern BOOL GFX_bFrontFace;
extern BOOL GFX_bTruform;
extern INDEX GFX_iActiveTexUnit;
extern FLOAT GFX_fMinDepthRange;
extern FLOAT GFX_fMaxDepthRange;
extern GfxBlend GFX_eBlendSrc;
extern GfxBlend GFX_eBlendDst;
extern GfxComp GFX_eDepthFunc;
extern GfxFace GFX_eCullFace;
extern INDEX GFX_iTexModulation[GFX_MAXTEXUNITS];
extern INDEX GFX_ctVertices;
extern BOOL GFX_bViewMatrix;
#pragma region Debug messenger
static VKAPI_ATTR VkBool32 VKAPI_CALL DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData)
{
// print debug message to console
CPrintF( "Vulkan Validation layer: %s\n", pCallbackData->pMessage);
return VK_FALSE;
}
void GetDebugMsgCreateInfo(VkDebugUtilsMessengerCreateInfoEXT &outInfo)
{
outInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
outInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
outInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
outInfo.pfnUserCallback = DebugCallback;
}
#pragma endregion
BOOL CGfxLibrary::InitDriver_Vulkan()
{
ASSERT(gl_SvkMain == nullptr);
gl_SvkMain = new SvkMain();
return gl_SvkMain->InitDriver_Vulkan();
}
void CGfxLibrary::EndDriver_Vulkan(void)
{
ASSERT(gl_SvkMain != nullptr);
gl_SvkMain->EndDriver_Vulkan();
delete gl_SvkMain;
gl_SvkMain = nullptr;
}
void CGfxLibrary::Reset_Vulkan()
{
gl_SvkMain->Reset_Vulkan();
}
void CGfxLibrary::InitContext_Vulkan()
{
gl_SvkMain->InitContext_Vulkan();
}
BOOL CGfxLibrary::SetCurrentViewport_Vulkan(CViewPort *pvp)
{
return gl_SvkMain->SetCurrentViewport_Vulkan(pvp);
}
void CGfxLibrary::SwapBuffers_Vulkan()
{
gl_SvkMain->SwapBuffers_Vulkan();
}
void CGfxLibrary::SetViewport_Vulkan(float leftUpperX, float leftUpperY, float width, float height, float minDepth, float maxDepth)
{
gl_SvkMain->SetViewport_Vulkan(leftUpperX, leftUpperY, width, height, minDepth, maxDepth);
}
SvkMain::SvkMain()
{
Reset_Vulkan();
}
// initialize Vulkan driver
BOOL SvkMain::InitDriver_Vulkan()
{
_pGfx->gl_hiDriver = NONE; // must be initialized?
ASSERT(gl_VkInstance == VK_NULL_HANDLE);
ASSERT(gl_VkDevice == VK_NULL_HANDLE);
HINSTANCE hInstance = GetModuleHandle(NULL);
// startup Vulkan
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Serious App";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Serious Engine 1";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo instanceInfo = {};
instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceInfo.pApplicationInfo = &appInfo;
// hard coded Windows extensions
const char* extensions[] = {
VK_KHR_SURFACE_EXTENSION_NAME,
VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
#if SVK_ENABLE_VALIDATION
VK_EXT_DEBUG_UTILS_EXTENSION_NAME
#endif
};
#if SVK_ENABLE_VALIDATION
VkDebugUtilsMessengerCreateInfoEXT debugMsgInfo = {};
GetDebugMsgCreateInfo(debugMsgInfo);
if (gl_VkLayers.Count() == 0)
{
gl_VkLayers.New(2);
gl_VkLayers[0] = "VK_LAYER_KHRONOS_validation";
gl_VkLayers[1] = "VK_LAYER_LUNARG_monitor";
}
instanceInfo.enabledExtensionCount = 3;
instanceInfo.ppEnabledExtensionNames = extensions;
instanceInfo.enabledLayerCount = (uint32_t)gl_VkLayers.Count();
instanceInfo.ppEnabledLayerNames = &gl_VkLayers[0];
instanceInfo.pNext = &debugMsgInfo;
#else
instanceInfo.enabledExtensionCount = 2;
instanceInfo.ppEnabledExtensionNames = extensions;
instanceInfo.enabledLayerCount = 0;
#endif
VkResult r = vkCreateInstance(&instanceInfo, nullptr, &gl_VkInstance);
if (r == VK_ERROR_INCOMPATIBLE_DRIVER)
{
CPrintF("Vulkan error: Can't find a compatible Vulkan ICD.\n");
return FALSE;
}
else if (r != VK_SUCCESS)
{
CPrintF("Vulkan error: Can't create instance.\n");
return FALSE;
}
#if SVK_ENABLE_VALIDATION
auto pfnCreateDUMsg = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(gl_VkInstance, "vkCreateDebugUtilsMessengerEXT");
if (pfnCreateDUMsg != nullptr)
{
pfnCreateDUMsg(gl_VkInstance, &debugMsgInfo, nullptr, &gl_VkDebugMessenger);
}
else
{
CPrintF("Vulkan error: Can't find vkCreateDebugUtilsMessengerEXT.\n");
return FALSE;
}
#endif
extern HWND _hwndMain;
if (!InitSurface_Win32(hInstance, _hwndMain))
{
CPrintF("Vulkan error: Can't create Win32 surface.\n");
return FALSE;
}
if (gl_VkPhysDeviceExtensions.Count() == 0)
{
gl_VkPhysDeviceExtensions.New(1);
gl_VkPhysDeviceExtensions[0] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
}
if (!PickPhysicalDevice())
{
CPrintF("Vulkan error: Can't find suitable physical device.\n");
return FALSE;
}
if (!CreateDevice())
{
CPrintF("Vulkan error: Can't create VkDevice.\n");
return FALSE;
}
InitSamplers();
CreateTexturesDataStructure();
CreateDescriptorPools();
CreateCmdBuffers();
CreateSyncPrimitives();
CreateVertexLayouts();
CreatePipelineCache();
CreateRenderPass();
CreateDescriptorSetLayouts();
CreateShaderModules();
InitDynamicBuffers();
InitOcclusionQuerying();
return TRUE;
}
void SvkMain::EndDriver_Vulkan(void)
{
if (gl_VkInstance == VK_NULL_HANDLE)
{
return;
}
vkDeviceWaitIdle(gl_VkDevice);
gl_VkVerts.Clear();
DestroyTexturesDataStructure();
DestroySwapchain();
DestroySyncPrimitives();
DestroyDynamicBuffers();
DestroyCmdBuffers();
DestroyDescriptorSetLayouts();
DestroyDescriptorPools();
DestroySamplers();
DestroyPipelines();
DestroyVertexLayouts();
DestroyShaderModules();
DestroyOcclusionQuerying();
vkDestroyPipelineCache(gl_VkDevice, gl_VkPipelineCache, nullptr);
vkDestroyRenderPass(gl_VkDevice, gl_VkRenderPass, nullptr);
vkDestroySurfaceKHR(gl_VkInstance, gl_VkSurface, nullptr);
vkDestroyDevice(gl_VkDevice, nullptr);
#if SVK_ENABLE_VALIDATION
auto pfnDestroyDUMsg = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(gl_VkInstance, "vkDestroyDebugUtilsMessengerEXT");
if (pfnDestroyDUMsg != nullptr)
{
pfnDestroyDUMsg(gl_VkInstance, gl_VkDebugMessenger, nullptr);
}
#endif
vkDestroyInstance(gl_VkInstance, nullptr);
Reset_Vulkan();
}
void SvkMain::Reset_Vulkan()
{
gl_VkInstance = VK_NULL_HANDLE;
gl_VkDevice = VK_NULL_HANDLE;
gl_VkSurface = VK_NULL_HANDLE;
gl_VkCurrentImageIndex = 0;
gl_VkCurrentViewport = {};
gl_VkCurrentScissor = {};
gl_VkSwapChainExtent = {};
gl_VkRenderPass = VK_NULL_HANDLE;
gl_VkSwapchain = VK_NULL_HANDLE;
gl_VkSurfColorFormat = VK_FORMAT_B8G8R8A8_UNORM;
gl_VkSurfColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
gl_VkSurfDepthFormat = VK_FORMAT_D24_UNORM_S8_UINT;
gl_VkSurfPresentMode = VK_PRESENT_MODE_FIFO_KHR;
gl_VkCmdBufferCurrent = 0;
gl_VkCmdIsRecording = false;
gl_VkUniformDescPool = VK_NULL_HANDLE;
gl_VkDescSetLayoutTexture = VK_NULL_HANDLE;
gl_VkDescriptorSetLayout = VK_NULL_HANDLE;
gl_VkPipelineLayout = VK_NULL_HANDLE;
gl_VkPipelineLayoutOcclusion = VK_NULL_HANDLE;
gl_VkPipelineCache = VK_NULL_HANDLE;
gl_VkDefaultVertexLayout = nullptr;
gl_VkShaderModuleVert = VK_NULL_HANDLE;
gl_VkShaderModuleFrag = VK_NULL_HANDLE;
gl_VkShaderModuleFragAlpha = VK_NULL_HANDLE;
gl_VkShaderModuleVertOcclusion = VK_NULL_HANDLE;
gl_VkShaderModuleFragOcclusion = VK_NULL_HANDLE;
gl_VkPreviousPipeline = nullptr;
// reset states to default
gl_VkGlobalState = SVK_PLS_DEFAULT_FLAGS;
gl_VkGlobalSamplerState = 0;
gl_VkLastTextureId = 1;
gl_VkImageMemPool = nullptr;
gl_VkPhysDevice = VK_NULL_HANDLE;
gl_VkPhMemoryProperties = {};
gl_VkPhProperties = {};
gl_VkPhFeatures = {};
gl_VkPhSurfCapabilities = {};
gl_VkQueueFamGraphics = VK_NULL_HANDLE;
gl_VkQueueFamTransfer = VK_NULL_HANDLE;
gl_VkQueueFamPresent = VK_NULL_HANDLE;
gl_VkQueueGraphics = VK_NULL_HANDLE;
gl_VkQueueTransfer = VK_NULL_HANDLE;
gl_VkQueuePresent = VK_NULL_HANDLE;
gl_VkPipelineOcclusion = VK_NULL_HANDLE;
gl_VkDebugMessenger = VK_NULL_HANDLE;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
gl_VkTextureDescPools[i] = VK_NULL_HANDLE;
gl_VkCmdPools[i] = VK_NULL_HANDLE;
gl_VkCmdBuffers[i] = VK_NULL_HANDLE;
gl_VkCmdBuffers[i + gl_VkMaxCmdBufferCount] = VK_NULL_HANDLE;
gl_VkImageAvailableSemaphores[i] = VK_NULL_HANDLE;
gl_VkRenderFinishedSemaphores[i] = VK_NULL_HANDLE;
gl_VkCmdFences[i] = VK_NULL_HANDLE;
gl_VkDynamicVB[i].sdb_Buffer = VK_NULL_HANDLE;
gl_VkDynamicIB[i].sdb_Buffer = VK_NULL_HANDLE;
gl_VkDynamicUB[i].sdb_Buffer = VK_NULL_HANDLE;
gl_VkDynamicVB[i].sdb_CurrentOffset = 0;
gl_VkDynamicIB[i].sdb_CurrentOffset = 0;
gl_VkDynamicUB[i].sdb_CurrentOffset = 0;
gl_VkDynamicVB[i].sdb_Data = nullptr;
gl_VkDynamicIB[i].sdb_Data = nullptr;
gl_VkDynamicUB[i].sdb_Data = nullptr;
gl_VkDynamicUB[i].sdu_DescriptorSet = VK_NULL_HANDLE;
gl_VkDynamicToDelete[i] = nullptr;
gl_VkTexturesToDelete[i] = nullptr;
gl_VkOcclusionQueryLast[i] = 0;
gl_VkOcclusionQueryPools[i] = VK_NULL_HANDLE;
}
gl_VkDynamicVBGlobal.sdg_DynamicBufferMemory = VK_NULL_HANDLE;
gl_VkDynamicIBGlobal.sdg_DynamicBufferMemory = VK_NULL_HANDLE;
gl_VkDynamicUBGlobal.sdg_DynamicBufferMemory = VK_NULL_HANDLE;
gl_VkDynamicVBGlobal.sdg_CurrentDynamicBufferSize = 0;
gl_VkDynamicIBGlobal.sdg_CurrentDynamicBufferSize = 0;
gl_VkDynamicUBGlobal.sdg_CurrentDynamicBufferSize = 0;
Svk_MatSetIdentity(VkProjectionMatrix);
Svk_MatSetIdentity(VkViewMatrix);
GFX_iActiveTexUnit = 0;
}
// prepares Vulkan drawing context, almost everything copied from OpenGL
void SvkMain::InitContext_Vulkan()
{
// must have context
ASSERT(_pGfx->gl_pvpActive != NULL);
// reset engine's internal state variables
for (INDEX iUnit = 0; iUnit < GFX_MAXTEXUNITS; iUnit++) {
GFX_abTexture[iUnit] = FALSE;
GFX_iTexModulation[iUnit] = 1;
}
// set default texture unit and modulation mode
GFX_iActiveTexUnit = 0;
_pGfx->gl_ctMaxStreams = 16;
extern FLOAT GFX_fLastL, GFX_fLastR, GFX_fLastT, GFX_fLastB, GFX_fLastN, GFX_fLastF;
GFX_fLastL = GFX_fLastR = GFX_fLastT = GFX_fLastB = GFX_fLastN = GFX_fLastF = 0;
GFX_bViewMatrix = TRUE;
GFX_bTruform = FALSE;
GFX_bClipping = TRUE;
// reset global state for pipeline
gl_VkGlobalState = SVK_PLS_DEFAULT_FLAGS;
GFX_abTexture[0] = TRUE;
GFX_bDithering = TRUE;
GFX_bBlending = FALSE;
GFX_bDepthTest = FALSE;
GFX_bAlphaTest = FALSE;
GFX_bClipPlane = FALSE;
GFX_eCullFace = GFX_NONE;
GFX_bFrontFace = TRUE;
GFX_bDepthWrite = FALSE;
GFX_eDepthFunc = GFX_LESS_EQUAL;
GFX_eBlendSrc = GFX_eBlendDst = GFX_ONE;
GFX_fMinDepthRange = 0.0f;
GFX_fMaxDepthRange = 1.0f;
// vertices array for Vulkan
gl_VkVerts.New(SVK_VERT_START_COUNT);
gl_VkVerts.SetAllocationStep(SVK_VERT_ALLOC_STEP);
// always true on Vulkan
GFX_bColorArray = TRUE;
// report header
CPrintF(TRANS("\n* Vulkan context created: *------------------------------------\n"));
CDisplayAdapter &da = _pGfx->gl_gaAPI[GAT_VK].ga_adaAdapter[_pGfx->gl_iCurrentAdapter];
CPrintF(" (%s, %s, %s)\n\n", da.da_strVendor, da.da_strRenderer, da.da_strVersion);
_pGfx->gl_ctTextureUnits = 4;
_pGfx->gl_ctRealTextureUnits = 4;
_pGfx->gl_fMaxTextureLODBias = gl_VkPhProperties.limits.maxSamplerLodBias;
_pGfx->gl_iMaxTextureAnisotropy = gl_VkPhProperties.limits.maxSamplerAnisotropy;
_pGfx->gl_iTessellationLevel = 0;
_pGfx->gl_iMaxTessellationLevel = 0;
GFX_bColorArray = TRUE;
_pGfx->gl_ulFlags |= GLF_HASACCELERATION;
_pGfx->gl_ulFlags |= GLF_32BITTEXTURES;
_pGfx->gl_ulFlags |= GLF_VSYNC;
_pGfx->gl_ulFlags &= ~GLF_TEXTURECOMPRESSION;
_pGfx->gl_ulFlags |= GLF_EXT_EDGECLAMP;
// setup fog and haze textures
extern PIX _fog_pixSizeH;
extern PIX _fog_pixSizeL;
extern PIX _haze_pixSize;
// create texture objects for Vulkan
_fog_ulTexture = CreateTexture();
_haze_ulTexture = CreateTexture();
_fog_pixSizeH = 0;
_fog_pixSizeL = 0;
_haze_pixSize = 0;
uint32_t noTexturePixels[] = { 0xFFFFFFFF, 0xFFFFFFFF };
VkExtent2D noTextureSize = { 1, 1 };
_no_ulTexture = CreateTexture();
InitTexture32Bit(_no_ulTexture, VK_FORMAT_R8G8B8A8_UNORM, noTexturePixels, &noTextureSize, 1, false);
// prepare pattern texture
extern CTexParams _tpPattern;
extern ULONG _ulPatternTexture;
extern ULONG _ulLastUploadedPattern;
_ulPatternTexture = CreateTexture();
_ulLastUploadedPattern = 0;
_tpPattern.Clear();
// reset texture filtering and array locking
_tpGlobal[0].Clear();
_tpGlobal[1].Clear();
_tpGlobal[2].Clear();
_tpGlobal[3].Clear();
GFX_ctVertices = 0;
_pGfx->gl_dwVertexShader = NONE;
extern INDEX gap_iTextureFiltering;
extern INDEX gap_iTextureAnisotropy;
//extern FLOAT gap_fTextureLODBias;
gfxSetTextureFiltering(gap_iTextureFiltering, gap_iTextureAnisotropy);
//gfxSetTextureBiasing(gap_fTextureLODBias);
// mark pretouching and probing
extern BOOL _bNeedPretouch;
_bNeedPretouch = TRUE;
_pGfx->gl_bAllowProbing = FALSE;
// update console system vars
extern void UpdateGfxSysCVars(void);
UpdateGfxSysCVars();
// reload all loaded textures and eventually shadows
extern INDEX shd_bCacheAll;
extern void ReloadTextures(void);
extern void CacheShadows(void);
ReloadTextures();
if (shd_bCacheAll) CacheShadows();
gl_VkReloadTexturesTimer = 3;
}
BOOL SvkMain::SetCurrentViewport_Vulkan(CViewPort* pvp)
{
// determine full screen mode
CDisplayMode dm;
RECT rectWindow;
_pGfx->GetCurrentDisplayMode(dm);
ASSERT((dm.dm_pixSizeI == 0 && dm.dm_pixSizeJ == 0) || (dm.dm_pixSizeI != 0 && dm.dm_pixSizeJ != 0));
GetClientRect(pvp->vp_hWnd, &rectWindow);
const PIX pixWinSizeI = rectWindow.right - rectWindow.left;
const PIX pixWinSizeJ = rectWindow.bottom - rectWindow.top;
// full screen allows only one window (main one, which has already been initialized)
if (dm.dm_pixSizeI == pixWinSizeI && dm.dm_pixSizeJ == pixWinSizeJ)
{
_pGfx->gl_pvpActive = pvp; // remember as current viewport (must do that BEFORE InitContext)
if (_pGfx->gl_ulFlags & GLF_INITONNEXTWINDOW) InitContext_Vulkan();
_pGfx->gl_ulFlags &= ~GLF_INITONNEXTWINDOW;
return TRUE;
}
// if must init entire Vulkan
if (_pGfx->gl_ulFlags & GLF_INITONNEXTWINDOW) {
_pGfx->gl_ulFlags &= ~GLF_INITONNEXTWINDOW;
// reopen window
pvp->CloseCanvas();
pvp->OpenCanvas();
_pGfx->gl_pvpActive = pvp;
InitContext_Vulkan();
pvp->vp_ctDisplayChanges = _pGfx->gl_ctDriverChanges;
return TRUE;
}
// if window was not set for this driver
if (pvp->vp_ctDisplayChanges < _pGfx->gl_ctDriverChanges) {
// reopen window
pvp->CloseCanvas();
pvp->OpenCanvas();
pvp->vp_ctDisplayChanges = _pGfx->gl_ctDriverChanges;
_pGfx->gl_pvpActive = pvp;
return TRUE;
}
// no need to set context if it is the same window as last time
if (_pGfx->gl_pvpActive != NULL && _pGfx->gl_pvpActive->vp_hWnd == pvp->vp_hWnd) return TRUE;
// set rendering target
//HRESULT hr;
//LPDIRECT3DSURFACE8 pColorSurface;
//hr = pvp->vp_pSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pColorSurface);
//if (hr != D3D_OK) return FALSE;
//hr = gl_pd3dDevice->SetRenderTarget(pColorSurface, pvp->vp_pSurfDepth);
//D3DRELEASE(pColorSurface, TRUE);
//if (hr != D3D_OK) return FALSE;
// remember as current window
_pGfx->gl_pvpActive = pvp;
return TRUE;
}
void SvkMain::SwapBuffers_Vulkan()
{
// TODO: remove this ugliest fix!
// without it textures are not fully reloaded
if (gl_VkReloadTexturesTimer > 0)
{
extern INDEX shd_bCacheAll;
extern void ReloadTextures(void);
extern void CacheShadows(void);
ReloadTextures();
if (shd_bCacheAll) CacheShadows();
gl_VkReloadTexturesTimer--;
}
VkResult r;
// wait until rendering is finished
VkSemaphore smpToWait = gl_VkRenderFinishedSemaphores[gl_VkCmdBufferCurrent];
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &smpToWait;
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &gl_VkSwapchain;
presentInfo.pImageIndices = &gl_VkCurrentImageIndex;
r = vkQueuePresentKHR(gl_VkQueuePresent, &presentInfo);
if (r == VK_ERROR_OUT_OF_DATE_KHR || r == VK_SUBOPTIMAL_KHR)
{
}
else if (r != VK_SUCCESS)
{
ASSERTALWAYS("Vulkan error: Can't present swap chain image.\n");
}
}
void SvkMain::SetViewport_Vulkan(float leftUpperX, float leftUpperY, float width, float height, float minDepth, float maxDepth)
{
gl_VkCurrentViewport.x = leftUpperX;
gl_VkCurrentViewport.y = leftUpperY;
gl_VkCurrentViewport.width = width;
gl_VkCurrentViewport.height = height;
gl_VkCurrentViewport.minDepth = minDepth;
gl_VkCurrentViewport.maxDepth = maxDepth;
gl_VkCurrentScissor.extent.width = width;
gl_VkCurrentScissor.extent.height = height;
gl_VkCurrentScissor.offset.x = leftUpperX;
gl_VkCurrentScissor.offset.y = leftUpperY;
ASSERT(gl_VkCmdIsRecording);
vkCmdSetViewport(GetCurrentCmdBuffer(), 0, 1, &gl_VkCurrentViewport);
vkCmdSetScissor(GetCurrentCmdBuffer(), 0, 1, &gl_VkCurrentScissor);
}
BOOL SvkMain::InitSurface_Win32(HINSTANCE hinstance, HWND hwnd)
{
VkWin32SurfaceCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
createInfo.pNext = nullptr;
createInfo.hinstance = hinstance;
createInfo.hwnd = hwnd;
VkResult r = vkCreateWin32SurfaceKHR(gl_VkInstance, &createInfo, nullptr, &gl_VkSurface);
return r == VK_SUCCESS;
// const BOOL bFullScreen = (pixSizeI > 0 && pixSizeJ > 0);
}
BOOL SvkMain::CreateDevice()
{
// temporary, graphics and transfer are the same family
ASSERT(gl_VkQueueFamGraphics == gl_VkQueueFamTransfer);
uint32_t uniqueFamilies[2] = { gl_VkQueueFamGraphics, gl_VkQueueFamPresent };
uint32_t uniqueFamilyCount = gl_VkQueueFamGraphics == gl_VkQueueFamPresent ? 1 : 2;
CStaticArray<VkDeviceQueueCreateInfo> queueInfos;
queueInfos.New(uniqueFamilyCount);
// only one queue
const uint32_t queueCount = 1;
float priorities[queueCount] = { 1.0f };
for (uint32_t i = 0; i < uniqueFamilyCount; i++)
{
VkDeviceQueueCreateInfo &qinfo = queueInfos[i];
qinfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
qinfo.pNext = nullptr;
qinfo.flags = 0;
qinfo.queueFamilyIndex = uniqueFamilies[i];
qinfo.queueCount = queueCount;
qinfo.pQueuePriorities = priorities;
}
VkPhysicalDeviceFeatures features = {};
features.samplerAnisotropy = VK_TRUE;
features.depthBounds = VK_TRUE;
VkDeviceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = (uint32_t)queueInfos.Count();
createInfo.pQueueCreateInfos = &queueInfos[0];
createInfo.pEnabledFeatures = &features;
createInfo.enabledExtensionCount = (uint32_t)gl_VkPhysDeviceExtensions.Count();
createInfo.ppEnabledExtensionNames = &gl_VkPhysDeviceExtensions[0];
#if SVK_ENABLE_VALIDATION
createInfo.enabledLayerCount = (uint32_t)gl_VkLayers.Count();
createInfo.ppEnabledLayerNames = &gl_VkLayers[0];
#endif
if (vkCreateDevice(gl_VkPhysDevice, &createInfo, nullptr, &gl_VkDevice) != VK_SUCCESS)
{
return FALSE;
}
vkGetDeviceQueue(gl_VkDevice, gl_VkQueueFamGraphics, 0, &gl_VkQueueGraphics);
gl_VkQueueTransfer = gl_VkQueueGraphics;
vkGetDeviceQueue(gl_VkDevice, gl_VkQueueFamPresent, 0, &gl_VkQueuePresent);
return TRUE;
}
void SvkMain::CreateRenderPass()
{
VkSampleCountFlagBits sampleCount = gl_VkMaxSampleCount;
bool useResolve = sampleCount != VK_SAMPLE_COUNT_1_BIT;
VkAttachmentDescription colorAttachment = {};
colorAttachment.format = gl_VkSurfColorFormat;
colorAttachment.samples = sampleCount;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = useResolve ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentDescription depthAttachment = {};
depthAttachment.format = gl_VkSurfDepthFormat;
depthAttachment.samples = sampleCount;
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentDescription colorAttachmentPresent = {};
colorAttachmentPresent.format = gl_VkSurfColorFormat;
colorAttachmentPresent.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachmentPresent.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachmentPresent.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachmentPresent.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachmentPresent.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachmentPresent.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachmentPresent.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentRef = {};
colorAttachmentRef.attachment = SVK_RENDERPASS_COLOR_ATTACHMENT_INDEX;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthAttachmentRef = {};
depthAttachmentRef.attachment = SVK_RENDERPASS_DEPTH_ATTACHMENT_INDEX;
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorAttachmentPresentRef = {};
colorAttachmentPresentRef.attachment = SVK_RENDERPASS_DEPTH_ATTACHMENT_INDEX + 1;
colorAttachmentPresentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
subpass.pDepthStencilAttachment = &depthAttachmentRef;
subpass.pResolveAttachments = useResolve ? &colorAttachmentPresentRef : nullptr;
VkSubpassDependency dependency = {};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkAttachmentDescription attachments[3] = { colorAttachment, depthAttachment, colorAttachmentPresent };
VkRenderPassCreateInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = useResolve ? 3 : 2;
renderPassInfo.pAttachments = attachments;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
if (vkCreateRenderPass(gl_VkDevice, &renderPassInfo, nullptr, &gl_VkRenderPass) != VK_SUCCESS)
{
ASSERTALWAYS("Vulkan error: Can't create render pass.\n");
}
}
void SvkMain::CreateCmdBuffers()
{
#ifndef NDEBUG
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount * 2; i++)
{
ASSERT(gl_VkCmdBuffers[i] == VK_NULL_HANDLE);
}
#endif // !NDEBUG
VkResult r;
VkCommandPoolCreateInfo cmdPoolInfo = {};
cmdPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
cmdPoolInfo.queueFamilyIndex = gl_VkQueueFamGraphics;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
r = vkCreateCommandPool(gl_VkDevice, &cmdPoolInfo, nullptr, &gl_VkCmdPools[i]);
VK_CHECKERROR(r);
}
// allocate cmd buffers
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
allocInfo.commandPool = gl_VkCmdPools[i];
r = vkAllocateCommandBuffers(gl_VkDevice, &allocInfo, &gl_VkCmdBuffers[i]);
VK_CHECKERROR(r);
r = vkAllocateCommandBuffers(gl_VkDevice, &allocInfo, &gl_VkCmdBuffers[i + gl_VkMaxCmdBufferCount]);
VK_CHECKERROR(r);
}
}
void SvkMain::DestroyCmdBuffers()
{
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
vkDestroyCommandPool(gl_VkDevice, gl_VkCmdPools[i], nullptr);
gl_VkCmdBuffers[i] = VK_NULL_HANDLE;
gl_VkCmdPools[i] = VK_NULL_HANDLE;
}
}
void SvkMain::AcquireNextImage()
{
VkResult r;
uint32_t nextImageIndex;
// get image index in swapchain
r = vkAcquireNextImageKHR(gl_VkDevice, gl_VkSwapchain, UINT64_MAX,
gl_VkImageAvailableSemaphores[gl_VkCmdBufferCurrent], VK_NULL_HANDLE, &nextImageIndex);
if (r == VK_ERROR_OUT_OF_DATE_KHR)
{
// TODO: Vulkan: recreate swapchain
}
else if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR)
{
ASSERTALWAYS("Vulkan error: Can't to acquire swap chain image.\n");
}
// set to next image index
gl_VkCurrentImageIndex = nextImageIndex;
}
void SvkMain::StartFrame()
{
VkResult r;
// set new index
gl_VkCmdBufferCurrent = (gl_VkCmdBufferCurrent + 1) % gl_VkMaxCmdBufferCount;
// wait when previous cmd with same index will be done
r = vkWaitForFences(gl_VkDevice, 1, &gl_VkCmdFences[gl_VkCmdBufferCurrent], VK_TRUE, UINT64_MAX);
VK_CHECKERROR(r);
// fences must be set to unsignaled state manually
vkResetFences(gl_VkDevice, 1, &gl_VkCmdFences[gl_VkCmdBufferCurrent]);
// get next image index
AcquireNextImage();
// previous cmd with same index completely finished,
// free dynamic buffers that have to be deleted
FreeUnusedDynamicBuffers(gl_VkCmdBufferCurrent);
// set 0 offsets to dynamic buffers for current cmd buffer
ClearCurrentDynamicOffsets(gl_VkCmdBufferCurrent);
FreeDeletedTextures(gl_VkCmdBufferCurrent);
// reset previous pipeline
gl_VkPreviousPipeline = nullptr;
PrepareDescriptorSets(gl_VkCmdBufferCurrent);
_no_ulTextureDescSet = GetTextureDescriptor(_no_ulTexture);
vkResetCommandPool(gl_VkDevice, gl_VkCmdPools[gl_VkCmdBufferCurrent], VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT);
VkCommandBuffer cmd = gl_VkCmdBuffers[gl_VkCmdBufferCurrent];
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
r = vkBeginCommandBuffer(cmd, &beginInfo);
VK_CHECKERROR(r);
gl_VkCmdIsRecording = true;
// reset occlusion query pool
ResetOcclusionQueries(cmd, gl_VkCmdBufferCurrent);
VkClearValue clearValues[2];
clearValues[0].color = { 0.25f, 0.25f, 0.25f, 1.0f };
clearValues[1].depthStencil = { 0.0f, 0 };
VkRenderPassBeginInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = gl_VkRenderPass;
renderPassInfo.framebuffer = gl_VkFramebuffers[gl_VkCurrentImageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = gl_VkSwapChainExtent;
renderPassInfo.clearValueCount = 2;
renderPassInfo.pClearValues = clearValues;
vkCmdBeginRenderPass(cmd, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
// it is guaranteed that viewport and scissor will be set dynamically
}
void SvkMain::UpdateViewportDepth(float minDepth, float maxDepth)
{
gl_VkCurrentViewport.minDepth = minDepth;
gl_VkCurrentViewport.maxDepth = maxDepth;
ASSERT(gl_VkCmdIsRecording);
vkCmdSetViewport(GetCurrentCmdBuffer(), 0, 1, &gl_VkCurrentViewport);
}
void SvkMain::EndFrame()
{
VkResult r;
VkCommandBuffer cmd = gl_VkCmdBuffers[gl_VkCmdBufferCurrent];
FlushDynamicBuffersMemory();
vkCmdEndRenderPass(cmd);
gl_VkCmdIsRecording = false;
r = vkEndCommandBuffer(cmd);
VK_CHECKERROR(r);
// wait until image will be avaialable
VkSemaphore smpToWait = gl_VkImageAvailableSemaphores[gl_VkCmdBufferCurrent];
// signal when it's finished
VkSemaphore smpToSignal = gl_VkRenderFinishedSemaphores[gl_VkCmdBufferCurrent];
VkPipelineStageFlags pipelineStageFlags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
VkSubmitInfo submitInfo[1] = {};
submitInfo[0].pNext = NULL;
submitInfo[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo[0].waitSemaphoreCount = 1;
submitInfo[0].pWaitSemaphores = &smpToWait;
submitInfo[0].pWaitDstStageMask = &pipelineStageFlags;
submitInfo[0].commandBufferCount = 1;
submitInfo[0].pCommandBuffers = &cmd;
submitInfo[0].signalSemaphoreCount = 1;
submitInfo[0].pSignalSemaphores = &smpToSignal;
// submit cmd buffer; fence will be in signaled state when cmd will be done
r = vkQueueSubmit(gl_VkQueueGraphics, 1, submitInfo, gl_VkCmdFences[gl_VkCmdBufferCurrent]);
VK_CHECKERROR(r);
}
VkCommandBuffer SvkMain::GetCurrentCmdBuffer()
{
return gl_VkCmdBuffers[gl_VkCmdBufferCurrent];
}
void SvkMain::DrawTriangles(uint32_t indexCount, const uint32_t *indices)
{
VkCommandBuffer cmd = gl_VkCmdBuffers[gl_VkCmdBufferCurrent];
// prepare data
CStaticStackArray<SvkVertex> &verts = gl_VkVerts;
ASSERT(verts.Count() > 0);
uint32_t vertsSize = verts.Count() * SVK_VERT_SIZE;
uint32_t indicesSize = indexCount * sizeof(UINT);
uint32_t uniformSize = 16 * sizeof(FLOAT);
FLOAT mvp[16];
if (GFX_bViewMatrix)
{
Svk_MatMultiply(mvp, VkViewMatrix, VkProjectionMatrix);
}
else
{
Svk_MatCopy(mvp, VkProjectionMatrix);
}
// get buffers
SvkDynamicBuffer vertexBuffer, indexBuffer;
SvkDynamicUniform uniformBuffer;
GetVertexBuffer(vertsSize, vertexBuffer);
GetIndexBuffer(indicesSize, indexBuffer);
GetUniformBuffer(uniformSize, uniformBuffer);
// copy data
memcpy(vertexBuffer.sdb_Data, &verts[0], vertsSize);
memcpy(indexBuffer.sdb_Data, indices, indicesSize);
memcpy(uniformBuffer.sdb_Data, mvp, uniformSize);
uint32_t descSetOffset = (uint32_t)uniformBuffer.sdb_CurrentOffset;
// if previously not bound or flags don't match then bind new pipeline
if (gl_VkPreviousPipeline == nullptr || (gl_VkPreviousPipeline != nullptr && gl_VkPreviousPipeline->sps_Flags != gl_VkGlobalState))
{
// bind pipeline
SvkPipelineState &ps = GetPipeline(gl_VkGlobalState);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, ps.sps_Pipeline);
// save as it's most likely that next will be same
gl_VkPreviousPipeline = &ps;
}
VkDescriptorSet sets[5] = { uniformBuffer.sdu_DescriptorSet };
float textureColorScale = 1.0f;
// bind texture descriptors
for (uint32_t i = 0; i < GFX_MAXTEXUNITS; i++)
{
if (GFX_abTexture[i])
{
VkDescriptorSet textureDescSet = GetTextureDescriptor(gl_VkActiveTextures[i]);
if (textureDescSet != VK_NULL_HANDLE)
{
sets[i + 1] = textureDescSet;
ASSERT(GFX_iTexModulation[i] == 1 || GFX_iTexModulation[i] == 2);
textureColorScale *= GFX_iTexModulation[i];
continue;
}
}
sets[i + 1] = _no_ulTextureDescSet;
}
// set uniform and textures
vkCmdBindDescriptorSets(
cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, gl_VkPipelineLayout,
0, 5, sets,
1, &descSetOffset);
// set texture color scales
vkCmdPushConstants(cmd, gl_VkPipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof(float), &textureColorScale);
// set mesh
vkCmdBindVertexBuffers(cmd, 0, 1, &vertexBuffer.sdb_Buffer, &vertexBuffer.sdb_CurrentOffset);
vkCmdBindIndexBuffer(cmd, indexBuffer.sdb_Buffer, indexBuffer.sdb_CurrentOffset, VK_INDEX_TYPE_UINT32);
// draw
vkCmdDrawIndexed(cmd, indexCount, 1, 0, 0, 0);
}
#endif // SE1_VULKAN
| 33,994
|
C++
|
.cpp
| 866
| 36.055427
| 229
| 0.763362
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,194
|
GfxLibrary.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/GfxLibrary.cpp
|
/* Copyright (c) 2002-2012 Croteam Ltd.
Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "stdh.h"
#include <Engine/Graphics/GfxLibrary.h>
#include <Engine/Base/Translation.h>
#include <Engine/Base/ErrorReporting.h>
#include <Engine/Base/Console.h>
#include <Engine/Base/Shell.h>
#include <Engine/Base/Statistics_internal.h>
#include <Engine/Base/ListIterator.inl>
#include <Engine/Math/Functions.h>
#include <Engine/Math/AABBox.h>
#include <Engine/Models/Normals.h>
#include <Engine/Sound/SoundLibrary.h>
#include <Engine/Templates/Stock_CModelData.h>
#include <Engine/Graphics/Adapter.h>
#include <Engine/Graphics/ShadowMap.h>
#include <Engine/Graphics/Texture.h>
#include <Engine/Graphics/GfxProfile.h>
#include <Engine/Graphics/Raster.h>
#include <Engine/Graphics/ViewPort.h>
#include <Engine/Graphics/DrawPort.h>
#include <Engine/Graphics/Color.h>
#include <Engine/Graphics/Font.h>
#include <Engine/Graphics/MultiMonitor.h>
#include <Engine/Templates/DynamicStackArray.h>
#include <Engine/Templates/DynamicStackArray.cpp>
#include <Engine/Templates/DynamicContainer.cpp>
#include <Engine/Templates/Stock_CTextureData.h>
#ifdef SE1_VULKAN
#include <Engine/Graphics/Vulkan/SvkMain.h>
#endif
// control for partial usage of compiled vertex arrays
extern BOOL CVA_b2D = FALSE;
extern BOOL CVA_bWorld = FALSE;
extern BOOL CVA_bModels = FALSE;
// common element arrays
CStaticStackArray<GFXVertex> _avtxCommon;
CStaticStackArray<GFXTexCoord> _atexCommon;
CStaticStackArray<GFXColor> _acolCommon;
CStaticStackArray<INDEX> _aiCommonElements;
CStaticStackArray<INDEX> _aiCommonQuads; // predefined array for rendering quads thru triangles in glDrawElements()
// global texture parameters
CTexParams _tpGlobal[GFX_MAXTEXUNITS];
// pointer to global graphics library object
CGfxLibrary *_pGfx = NULL;
// forced texture upload quality (0 = default, 16 = force 16-bit, 32 = force 32-bit)
INDEX _iTexForcedQuality = 0;
extern PIX _fog_pixSizeH;
extern PIX _fog_pixSizeL;
extern PIX _haze_pixSize;
// control for partial usage of compiled vertex arrays
extern BOOL CVA_b2D;
extern BOOL CVA_bWorld;
extern BOOL CVA_bModels;
// gamma control
static FLOAT _fLastBrightness, _fLastContrast, _fLastGamma;
static FLOAT _fLastBiasR, _fLastBiasG, _fLastBiasB;
static INDEX _iLastLevels;
static UWORD _auwGammaTable[256*3];
// table for clipping [-512..+1024] to [0..255]
static UBYTE aubClipByte[256*2+ 256 +256*3];
extern const UBYTE *pubClipByte = &aubClipByte[256*2];
// fast square root and 1/sqrt tables
UBYTE aubSqrt[SQRTTABLESIZE];
UWORD auw1oSqrt[SQRTTABLESIZE];
// table for conversion from compressed 16-bit gouraud normals to 8-bit
UBYTE aubGouraudConv[16384];
// flag for scene rendering in progress (i.e. between 1st lock in frame & swap-buffers)
static BOOL GFX_bRenderingScene = FALSE;
// ID of the last drawport that has been locked
static ULONG GFX_ulLastDrawPortID = 0;
// last size of vertex buffers
extern INDEX _iLastVertexBufferSize = 0;
// pretouch flag
extern BOOL _bNeedPretouch;
// flat texture
CTextureData *_ptdFlat = NULL;
static ULONG _ulWhite = 0xFFFFFFFF;
// fast sin/cos table
static FLOAT afSinTable[256+256+64];
extern const FLOAT *pfSinTable = afSinTable +256;
extern const FLOAT *pfCosTable = afSinTable +256+64;
// texture/shadow control
extern INDEX tex_iNormalQuality = 00; // 0=optimal, 1=16bit, 2=32bit, 3=compressed (1st num=opaque tex, 2nd=alpha tex)
extern INDEX tex_iAnimationQuality = 11; // 0=optimal, 1=16bit, 2=32bit, 3=compressed (1st num=opaque tex, 2nd=alpha tex)
extern INDEX tex_iNormalSize = 9; // log2 of texture area /2 for max texture size allowed
extern INDEX tex_iAnimationSize = 7;
extern INDEX tex_iEffectSize = 7;
extern INDEX tex_bDynamicMipmaps = FALSE; // how many mipmaps will be bilineary filtered (0-15)
extern INDEX tex_iDithering = 3; // 0=none, 1-3=low, 4-7=medium, 8-10=high
extern INDEX tex_bFineEffect = FALSE; // 32bit effect? (works only if base texture hasn't been dithered)
extern INDEX tex_bFineFog = TRUE; // should fog be 8/32bit? (or just plain 4/16bit)
extern INDEX tex_iFogSize = 7; // limit fog texture size
extern INDEX tex_iFiltering = 0; // -6 - +6; negative = sharpen, positive = blur, 0 = none
extern INDEX tex_iEffectFiltering = +4; // filtering of fire effect textures
extern INDEX tex_bProgressiveFilter = FALSE; // filter mipmaps in creation time (not afterwards)
extern INDEX tex_bColorizeMipmaps = FALSE; // DEBUG: colorize texture's mipmap levels in various colors
extern INDEX tex_bCompressAlphaChannel = FALSE; // for compressed textures, compress alpha channel too
extern INDEX tex_bAlternateCompression = FALSE; // basically, this is fix for GFs (compress opaque texture as translucent)
extern INDEX shd_iStaticSize = 8;
extern INDEX shd_iDynamicSize = 8;
extern INDEX shd_bFineQuality = FALSE;
extern INDEX shd_iFiltering = 3; // >0 = blurring, 0 = no filtering
extern INDEX shd_iDithering = 1; // 0=none, 1,2=low, 3,4=medium, 5=high
extern INDEX shd_iAllowDynamic = 1; // 0=disallow, 1=allow on polys w/o 'NoDynamicLights' flag, 2=allow unconditionally
extern INDEX shd_bDynamicMipmaps = TRUE;
extern FLOAT shd_tmFlushDelay = 30.0f; // in seconds
extern FLOAT shd_fCacheSize = 8.0f; // in megabytes
extern INDEX shd_bCacheAll = FALSE; // cache all shadowmap at the level loading time (careful - memory eater!)
extern INDEX shd_bAllowFlats = TRUE; // allow optimization of single-color shadowmaps
extern INDEX shd_iForceFlats = 0; // force all shadowmaps to be flat (internal!) - 0=don't, 1=w/o overbrighting, 2=w/ overbrighting
extern INDEX shd_bShowFlats = FALSE; // colorize flat shadows
extern INDEX shd_bColorize = FALSE; // colorize shadows by size (gradieng from red=big to green=little)
// OpenGL control
extern INDEX ogl_iTextureCompressionType = 1; // 0=none, 1=default (ARB), 2=S3TC, 3=FXT1, 4=old S3TC
extern INDEX ogl_bUseCompiledVertexArrays = 101; // =XYZ; X=2D, Y=world, Z=models
extern INDEX ogl_bAllowQuadArrays = FALSE;
extern INDEX ogl_bExclusive = TRUE;
extern INDEX ogl_bGrabDepthBuffer = FALSE;
extern INDEX ogl_iMaxBurstSize = 0; // unlimited
extern INDEX ogl_bTruformLinearNormals = TRUE;
extern INDEX ogl_bAlternateClipPlane = FALSE; // signal when user clip plane requires a texture unit
extern INDEX ogl_iTBufferEffect = 0; // 0=none, 1=partial FSAA, 2=Motion Blur
extern INDEX ogl_iTBufferSamples = 2; // 2, 4 or 8 (for now)
extern INDEX ogl_iFinish = 1; // 0=never, 1=before rendering of next frame, 2=at the end of this frame, 3=at projection change
// Direct3D control
extern INDEX d3d_bUseHardwareTnL = TRUE;
extern INDEX d3d_bAlternateDepthReads = FALSE; // should check delayed depth reads at the end of current frame (FALSE) or at begining of the next (TRUE)
extern INDEX d3d_iVertexBuffersSize = 1024; // KBs reserved for vertex buffers
extern INDEX d3d_iVertexRangeTreshold = 99; // minimum vertices in buffer that triggers range optimization
extern INDEX d3d_bFastUpload = TRUE; // use internal format conversion routines
extern INDEX d3d_iMaxBurstSize = 0; // 0=unlimited
extern INDEX d3d_iFinish = 0;
// Vulkan control
extern INDEX gfx_vk_iPresentMode = 0; // what present mode to use: 0=FIFO, 1=Mailbox, 2=Immediate
extern INDEX gfx_vk_iMSAA = 0; // MSAA: 0=1x, 1=2x, 2=4x, 3=8x
// API common controls
extern INDEX gap_iUseTextureUnits = 4;
extern INDEX gap_iTextureFiltering = 21; // bilinear by default
extern INDEX gap_iTextureAnisotropy = 1; // 1=isotropic, 2=min anisotropy
extern FLOAT gap_fTextureLODBias = 0.0f;
extern INDEX gap_bOptimizeStateChanges = TRUE;
extern INDEX gap_iOptimizeDepthReads = 1; // 0=imediately, 1=after frame, 2=every 0.1 seconds
extern INDEX gap_iOptimizeClipping = 2; // 0=no, 1=mirror plane only, 2=mirror and frustum
extern INDEX gap_bAllowGrayTextures = TRUE;
extern INDEX gap_bAllowSingleMipmap = TRUE;
extern INDEX gap_iSwapInterval = 0;
extern INDEX gap_iRefreshRate = 0;
extern INDEX gap_iDithering = 2; // 16-bit dithering: 0=none, 1=no alpha, 2=all
extern INDEX gap_bForceTruform = 0; // 0 = only for models that allow truform, 1=for every model
extern INDEX gap_iTruformLevel = 3; // 0 = no tesselation
extern INDEX gap_iDepthBits = 0; // 0 (as color depth), 16, 24 or 32
extern INDEX gap_iStencilBits = 0; // 0 (no stencil buffer), 4 or 8
// models control
extern INDEX mdl_bShowTriangles = FALSE;
extern INDEX mdl_bShowStrips = FALSE;
extern INDEX mdl_bTruformWeapons = FALSE;
extern INDEX mdl_bCreateStrips = TRUE;
extern INDEX mdl_bRenderDetail = TRUE;
extern INDEX mdl_bRenderSpecular = TRUE;
extern INDEX mdl_bRenderReflection = TRUE;
extern INDEX mdl_bRenderBump = TRUE;
extern INDEX mdl_bAllowOverbright = TRUE;
extern INDEX mdl_bFineQuality = TRUE;
extern INDEX mdl_iShadowQuality = 1;
extern FLOAT mdl_fLODMul = 1.0f;
extern FLOAT mdl_fLODAdd = 0.0f;
extern INDEX mdl_iLODDisappear = 1; // 0=never, 1=ignore bias, 2=with bias
// ska controls
extern INDEX ska_bShowSkeleton = FALSE;
extern INDEX ska_bShowColision = FALSE;
extern FLOAT ska_fLODMul = 1.0f;
extern FLOAT ska_fLODAdd = 0.0f;
// terrain controls
extern INDEX ter_bShowQuadTree = FALSE;
extern INDEX ter_bShowWireframe = FALSE;
extern INDEX ter_bLerpVertices = TRUE;
extern INDEX ter_bShowInfo = FALSE;
extern INDEX ter_bOptimizeRendering = TRUE;
extern INDEX ter_bTempFreezeCast = FALSE;
extern INDEX ter_bNoRegeneration = FALSE;
// rendering control
extern INDEX wld_bAlwaysAddAll = FALSE;
extern INDEX wld_bRenderMirrors = TRUE;
extern INDEX wld_bRenderEmptyBrushes = TRUE;
extern INDEX wld_bRenderShadowMaps = TRUE;
extern INDEX wld_bRenderTextures = TRUE;
extern INDEX wld_bRenderDetailPolygons = TRUE;
extern INDEX wld_bTextureLayers = 111;
extern INDEX wld_bShowTriangles = FALSE;
extern INDEX wld_bShowDetailTextures = FALSE;
extern INDEX wld_iDetailRemovingBias = 3;
extern FLOAT wld_fEdgeOffsetI = 0.0f; //0.125f;
extern FLOAT wld_fEdgeAdjustK = 1.0f; //1.0001f;
extern INDEX gfx_bRenderWorld = TRUE;
extern INDEX gfx_bRenderParticles = TRUE;
extern INDEX gfx_bRenderModels = TRUE;
extern INDEX gfx_bRenderPredicted = FALSE;
extern INDEX gfx_bRenderFog = TRUE;
extern INDEX gfx_iLensFlareQuality = 3; // 0=none, 1=corona only, 2=corona and reflections, 3=corona, reflections and glare
extern INDEX gfx_bDecoratedText = TRUE;
extern INDEX gfx_bClearScreen = FALSE;
extern FLOAT gfx_tmProbeDecay = 30.0f; // seconds
extern INDEX gfx_iProbeSize = 256; // in KBs
extern INDEX gfx_ctMonitors = 0;
extern INDEX gfx_bMultiMonDisabled = FALSE;
extern INDEX gfx_bDisableMultiMonSupport = TRUE;
extern INDEX gfx_bDisableWindowsKeys = TRUE;
extern INDEX wed_bIgnoreTJunctions = FALSE;
extern INDEX wed_bUseBaseForReplacement = FALSE;
// some nifty features
extern INDEX gfx_iHueShift = 0; // 0-359
extern FLOAT gfx_fSaturation = 1.0f; // 0.0f = min, 1.0f = default
// the following vars can be influenced by corresponding gfx_ vars
extern INDEX tex_iHueShift = 0; // added to gfx_
extern FLOAT tex_fSaturation = 1.0f; // multiplied by gfx_
extern INDEX shd_iHueShift = 0; // added to gfx_
extern FLOAT shd_fSaturation = 1.0f; // multiplied by gfx_
// gamma table control
extern FLOAT gfx_fBrightness = 0.0f; // -0.9 - 0.9
extern FLOAT gfx_fContrast = 1.0f; // 0.1 - 1.9
extern FLOAT gfx_fGamma = 1.0f; // 0.1 - 9.0
extern FLOAT gfx_fBiasR = 1.0f; // 0.0 - 1.0
extern FLOAT gfx_fBiasG = 1.0f; // 0.0 - 1.0
extern FLOAT gfx_fBiasB = 1.0f; // 0.0 - 1.0
extern INDEX gfx_iLevels = 256; // 2 - 256
// stereo rendering control
extern INDEX gfx_iStereo = 0; // 0=off, 1=red/cyan
extern INDEX gfx_bStereoInvert = FALSE; // is left eye RED or CYAN
extern INDEX gfx_iStereoOffset = 10; // view offset (or something:)
extern FLOAT gfx_fStereoSeparation = 0.25f; // distance between eyes
// cached integers for faster calculation
extern SLONG _slTexSaturation = 256; // 0 = min, 256 = default
extern SLONG _slTexHueShift = 0;
extern SLONG _slShdSaturation = 256;
extern SLONG _slShdHueShift = 0;
// 'supported' console variable flags
static INDEX sys_bHasTextureCompression = 0;
static INDEX sys_bHasTextureAnisotropy = 0;
static INDEX sys_bHasAdjustableGamma = 0;
static INDEX sys_bHasTextureLODBias = 0;
static INDEX sys_bHasMultitexturing = 0;
static INDEX sys_bHas32bitTextures = 0;
static INDEX sys_bHasSwapInterval = 0;
static INDEX sys_bHasHardwareTnL = 1;
static INDEX sys_bHasTruform = 0;
static INDEX sys_bHasCVAs = 0;
static INDEX sys_bUsingOpenGL = 0;
extern INDEX sys_bUsingDirect3D = 0;
extern INDEX sys_bUsingVulkan = 0;
/*
* Low level hook flags
*/
#define WH_KEYBOARD_LL 13
#pragma message(">> doublecheck me!!!")
// these are commented because they are already defined in winuser.h
//#define LLKHF_EXTENDED 0x00000001
//#define LLKHF_INJECTED 0x00000010
//#define LLKHF_ALTDOWN 0x00000020
//#define LLKHF_UP 0x00000080
//#define LLMHF_INJECTED 0x00000001
/*
* Structure used by WH_KEYBOARD_LL
*/
// this is commented because there's a variant for this struct in winuser.h
/*typedef struct tagKBDLLHOOKSTRUCT {
DWORD vkCode;
DWORD scanCode;
DWORD flags;
DWORD time;
DWORD dwExtraInfo;
} KBDLLHOOKSTRUCT, FAR *LPKBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT;*/
static HHOOK _hLLKeyHook = NULL;
LRESULT CALLBACK LowLevelKeyboardProc (INT nCode, WPARAM wParam, LPARAM lParam)
{
// By returning a non-zero value from the hook procedure, the
// message does not get passed to the target window
KBDLLHOOKSTRUCT *pkbhs = (KBDLLHOOKSTRUCT *) lParam;
BOOL bControlKeyDown = 0;
switch (nCode)
{
case HC_ACTION:
{
// Check to see if the CTRL key is pressed
bControlKeyDown = GetAsyncKeyState (VK_CONTROL) >> ((sizeof(SHORT) * 8) - 1);
// Disable CTRL+ESC
if (pkbhs->vkCode == VK_ESCAPE && bControlKeyDown)
return 1;
// Disable ALT+TAB
if (pkbhs->vkCode == VK_TAB && pkbhs->flags & LLKHF_ALTDOWN)
return 1;
// Disable ALT+ESC
if (pkbhs->vkCode == VK_ESCAPE && pkbhs->flags & LLKHF_ALTDOWN)
return 1;
break;
}
default:
break;
}
return CallNextHookEx (_hLLKeyHook, nCode, wParam, lParam);
}
void DisableWindowsKeys(void)
{
//if( _hLLKeyHook!=NULL) UnhookWindowsHookEx(_hLLKeyHook);
//_hLLKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, &LowLevelKeyboardProc, NULL, GetCurrentThreadId());
INDEX iDummy;
SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, TRUE, &iDummy, 0);
}
void EnableWindowsKeys(void)
{
INDEX iDummy;
SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, FALSE, &iDummy, 0);
// if( _hLLKeyHook!=NULL) UnhookWindowsHookEx(_hLLKeyHook);
}
// texture size reporting
static CTString ReportQuality( INDEX iQuality)
{
if( iQuality==0) return "optimal";
if( iQuality==1) return "16-bit";
if( iQuality==2) return "32-bit";
if( iQuality==3) return "compressed";
ASSERTALWAYS( "Invalid texture quality.");
return "?";
}
static void TexturesInfo(void)
{
UpdateTextureSettings();
INDEX ctNo04O=0, ctNo64O=0, ctNoMXO=0;
PIX pixK04O=0, pixK64O=0, pixKMXO=0;
SLONG slKB04O=0, slKB64O=0, slKBMXO=0;
INDEX ctNo04A=0, ctNo64A=0, ctNoMXA=0;
PIX pixK04A=0, pixK64A=0, pixKMXA=0;
SLONG slKB04A=0, slKB64A=0, slKBMXA=0;
// walk thru all textures on stock
{FOREACHINDYNAMICCONTAINER( _pTextureStock->st_ctObjects, CTextureData, ittd)
{ // get texture info
CTextureData &td = *ittd;
BOOL bAlpha = td.td_ulFlags&TEX_ALPHACHANNEL;
INDEX ctFrames = td.td_ctFrames;
SLONG slBytes = td.GetUsedMemory();
ASSERT( slBytes>=0);
// get texture size
PIX pixTextureSize = td.GetPixWidth() * td.GetPixHeight();
PIX pixMipmapSize = pixTextureSize;
if( !gap_bAllowSingleMipmap || td.td_ctFineMipLevels>1) pixMipmapSize = pixMipmapSize *4/3;
// increase corresponding counters
if( pixTextureSize<4096) {
if( bAlpha) { pixK04A+=pixMipmapSize; slKB04A+=slBytes; ctNo04A+=ctFrames; }
else { pixK04O+=pixMipmapSize; slKB04O+=slBytes; ctNo04O+=ctFrames; }
} else if( pixTextureSize<=65536) {
if( bAlpha) { pixK64A+=pixMipmapSize; slKB64A+=slBytes; ctNo64A+=ctFrames; }
else { pixK64O+=pixMipmapSize; slKB64O+=slBytes; ctNo64O+=ctFrames; }
} else {
if( bAlpha) { pixKMXA+=pixMipmapSize; slKBMXA+=slBytes; ctNoMXA+=ctFrames; }
else { pixKMXO+=pixMipmapSize; slKBMXO+=slBytes; ctNoMXO+=ctFrames; }
}
}}
// report
const PIX pixNormDim = sqrt((FLOAT)TS.ts_pixNormSize);
const PIX pixAnimDim = sqrt((FLOAT)TS.ts_pixAnimSize);
const PIX pixEffDim = 1L<<tex_iEffectSize;
CTString strTmp;
strTmp = tex_bFineEffect ? "32-bit" : "16-bit";
CPrintF( "\n");
CPrintF( "Normal-opaque textures quality: %s\n", ReportQuality(TS.ts_iNormQualityO));
CPrintF( "Normal-translucent textures quality: %s\n", ReportQuality(TS.ts_iNormQualityA));
CPrintF( "Animation-opaque textures quality: %s\n", ReportQuality(TS.ts_iAnimQualityO));
CPrintF( "Animation-translucent textures quality: %s\n", ReportQuality(TS.ts_iAnimQualityA));
CPrintF( "Effect textures quality: %s\n", strTmp);
CPrintF( "\n");
CPrintF( "Max allowed normal texture area size: %3dx%d\n", pixNormDim, pixNormDim);
CPrintF( "Max allowed animation texture area size: %3dx%d\n", pixAnimDim, pixAnimDim);
CPrintF( "Max allowed effect texture area size: %3dx%d\n", pixEffDim, pixEffDim);
CPrintF( "\n");
CPrintF( "Opaque textures memory usage:\n");
CPrintF( " <64 pix: %3d frames use %6.1f Kpix in %5d KB\n", ctNo04O, pixK04O/1024.0f, slKB04O/1024);
CPrintF( " 64-256 pix: %3d frames use %6.1f Kpix in %5d KB\n", ctNo64O, pixK64O/1024.0f, slKB64O/1024);
CPrintF( " >256 pix: %3d frames use %6.1f Kpix in %5d KB\n", ctNoMXO, pixKMXO/1024.0f, slKBMXO/1024);
CPrintF( "Translucent textures memory usage:\n");
CPrintF( " <64 pix: %3d frames use %6.1f Kpix in %5d KB\n", ctNo04A, pixK04A/1024.0f, slKB04A/1024);
CPrintF( " 64-256 pix: %3d frames use %6.1f Kpix in %5d KB\n", ctNo64A, pixK64A/1024.0f, slKB64A/1024);
CPrintF( " >256 pix: %3d frames use %6.1f Kpix in %5d KB\n", ctNoMXA, pixKMXA/1024.0f, slKBMXA/1024);
CPrintF("\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n");
}
// reformat an extensions string to cross multiple lines
extern CTString ReformatExtensionsString( CTString strUnformatted)
{
CTString strTmp, strDst = "\n";
char *pcSrc = (char*)(const char*)strUnformatted;
FOREVER {
char *pcSpace = strchr( pcSrc, ' ');
if( pcSpace==NULL) break;
*pcSpace = 0;
strTmp.PrintF( " %s\n", pcSrc);
strDst += strTmp;
*pcSpace = ' ';
pcSrc = pcSpace +1;
}
if(strDst=="\n") {
strDst = "none\n";
}
// done
return strDst;
}
// printout extensive OpenGL/Direct3D info to console
static void GAPInfo(void)
{
// check API
const GfxAPIType eAPI = _pGfx->gl_eCurrentAPI;
#ifdef SE1_D3D
ASSERT( eAPI==GAT_OGL || eAPI==GAT_D3D || eAPI==GAT_NONE);
#else // SE1_D3D
#ifdef SE1_VULKAN
ASSERT(eAPI == GAT_OGL || eAPI == GAT_VK || eAPI == GAT_NONE);
#else
ASSERT(eAPI == GAT_OGL || eAPI == GAT_NONE);
#endif // SE1_VULKAN
#endif // SE1_D3D
CPrintF( "\n");
// in case of driver hasn't been initialized yet
if( (_pGfx->go_hglRC==NULL
#ifdef SE1_D3D
&& _pGfx->gl_pd3dDevice==NULL
#endif // SE1_D3D
#ifdef SE1_VULKAN
&& _pGfx->gl_SvkMain->gl_VkInstance==VK_NULL_HANDLE
#endif // SE1_VULKAN
) || eAPI==GAT_NONE) {
// be brief, be quick
CPrintF( TRANS("Display driver hasn't been initialized.\n\n"));
return;
}
// report API
CPrintF( "- Graphics API: ");
if( eAPI==GAT_OGL) CPrintF( "OpenGL\n");
#ifdef SE1_D3D
else if (eAPI==GAT_D3D) CPrintF("Direct3D\n");
#endif // SE1_D3D
#ifdef SE1_VULKAN
else if (eAPI == GAT_VK) CPrintF("Vulkan\n");
#endif // SE1_VULKAN
// and number of adapters
CPrintF( "- Adapters found: %d\n", _pGfx->gl_gaAPI[eAPI].ga_ctAdapters);
CPrintF( "\n");
// report renderer
CDisplayAdapter &da = _pGfx->gl_gaAPI[eAPI].ga_adaAdapter[_pGfx->gl_iCurrentAdapter];
if( eAPI==GAT_OGL) CPrintF( "- Vendor: %s\n", da.da_strVendor);
CPrintF( "- Renderer: %s\n", da.da_strRenderer);
CPrintF( "- Version: %s\n", da.da_strVersion);
CPrintF( "\n");
// Z-buffer depth
CPrintF( "- Z-buffer precision: ");
if( _pGfx->gl_iCurrentDepth==0) CPrintF( "default\n");
else CPrintF( "%d bits\n", _pGfx->gl_iCurrentDepth);
// 32-bit textures
CPrintF( "- 32-bit textures: ");
if( _pGfx->gl_ulFlags & GLF_32BITTEXTURES) CPrintF( "supported\n");
else CPrintF( "not supported\n");
// grayscale textures
CPrintF( "- Grayscale textures: ");
if( gap_bAllowGrayTextures) CPrintF( "allowed\n");
else CPrintF( "not allowed\n");
// report maximum texture dimension
CPrintF( "- Max texture dimension: %d pixels\n", _pGfx->gl_pixMaxTextureDimension);
// report multitexturing capabilities
CPrintF( "- Multi-texturing: ");
if( _pGfx->gl_ctRealTextureUnits<2) CPrintF( "not supported\n");
else {
if( gap_iUseTextureUnits>1) CPrintF( "enabled (using %d texture units)\n", gap_iUseTextureUnits);
else CPrintF( "disabled\n");
CPrintF( "- Texture units: %d", _pGfx->gl_ctRealTextureUnits);
if( _pGfx->gl_ctTextureUnits < _pGfx->gl_ctRealTextureUnits) {
CPrintF(" (%d can be used)\n", _pGfx->gl_ctTextureUnits);
} else CPrintF("\n");
}
// report texture anisotropy degree
if( _pGfx->gl_iMaxTextureAnisotropy>=2) {
CPrintF( "- Texture anisotropy: %d of %d\n", _tpGlobal[0].tp_iAnisotropy, _pGfx->gl_iMaxTextureAnisotropy);
} else CPrintF( "- Anisotropic texture filtering: not supported\n");
// report texture LOD bias range
const FLOAT fMaxLODBias = _pGfx->gl_fMaxTextureLODBias;
if( fMaxLODBias>0) {
CPrintF( "- Texture LOD bias: %.1f of +/-%.1f\n", _pGfx->gl_fTextureLODBias, fMaxLODBias);
} else CPrintF( "- Texture LOD biasing: not supported\n");
// OpenGL only stuff ...
if( eAPI==GAT_OGL)
{
// report truform tessellation
CPrintF( "- Truform tessellation: ");
if( _pGfx->gl_iMaxTessellationLevel>0) {
if( _pGfx->gl_iTessellationLevel>0) {
CPrintF( "enabled ");
if( gap_bForceTruform) CPrintF( "(for all models)\n");
else CPrintF( "(only for Truform-ready models)\n");
CTString strNormalMode = ogl_bTruformLinearNormals ? "linear" : "quadratic";
CPrintF( "- Tesselation level: %d of %d (%s normals)\n", _pGfx->gl_iTessellationLevel, _pGfx->gl_iMaxTessellationLevel, strNormalMode);
} else CPrintF( "disabled\n");
} else CPrintF( "not supported\n");
// report current swap interval (only if fullscreen)
if( _pGfx->gl_ulFlags&GLF_FULLSCREEN) {
// report current swap interval
CPrintF( "- Swap interval: ");
if( _pGfx->gl_ulFlags&GLF_VSYNC) {
GLint gliWaits = pwglGetSwapIntervalEXT();
if( gliWaits>=0) {
ASSERT( gliWaits==_pGfx->gl_iSwapInterval);
CPrintF( "%d frame(s)\n", gliWaits);
} else CPrintF( "not readable\n");
} else CPrintF( "not adjustable\n");
}
// report T-Buffer support
if( _pGfx->gl_ulFlags & GLF_EXT_TBUFFER) {
CPrintF( "- T-Buffer effect: ");
if( _pGfx->go_ctSampleBuffers==0) CPrintF( "disabled\n");
else {
ogl_iTBufferEffect = Clamp( ogl_iTBufferEffect, 0L, 2L);
CTString strEffect = "Partial anti-aliasing";
if( ogl_iTBufferEffect<1) strEffect = "none";
if( ogl_iTBufferEffect>1) strEffect = "Motion blur";
CPrintF( "%s (%d buffers used)\n", strEffect, _pGfx->go_ctSampleBuffers);
}
}
// compiled vertex arrays support
CPrintF( "- Compiled Vertex Arrays: ");
if( _pGfx->gl_ulFlags & GLF_EXT_COMPILEDVERTEXARRAY) {
extern BOOL CVA_b2D;
extern BOOL CVA_bWorld;
extern BOOL CVA_bModels;
if( ogl_bUseCompiledVertexArrays) {
CTString strSep="";
CPrintF( "enabled (for ");
if( CVA_bWorld) { CPrintF( "world"); strSep="/"; }
if( CVA_bModels) { CPrintF( "%smodels", strSep); strSep="/"; }
if( CVA_b2D) { CPrintF( "%sparticles", strSep); }
CPrintF( ")\n");
} else CPrintF( "disabled\n");
} else CPrintF( "not supported\n");
// report texture compression type
CPrintF( "- Supported texture compression system(s): ");
if( !(_pGfx->gl_ulFlags&GLF_TEXTURECOMPRESSION)) CPrintF( "none\n");
else {
CTString strSep="";
if( _pGfx->gl_ulFlags & GLF_EXTC_ARB) { CPrintF( "ARB"); strSep=", "; }
if( _pGfx->gl_ulFlags & GLF_EXTC_S3TC) { CPrintF( "%sS3TC", strSep); strSep=", "; }
if( _pGfx->gl_ulFlags & GLF_EXTC_FXT1) { CPrintF( "%sFTX1", strSep); strSep=", "; }
if( _pGfx->gl_ulFlags & GLF_EXTC_LEGACY) { CPrintF( "%sold S3TC", strSep); }
CPrintF( "\n- Current texture compression system: ");
switch( ogl_iTextureCompressionType) {
case 0: CPrintF( "none\n"); break;
case 1: CPrintF( "ARB wrapper\n"); break;
case 2: CPrintF( "S3TC\n"); break;
case 3: CPrintF( "FXT1\n"); break;
default: CPrintF( "old S3TC\n"); break;
}
}
/* if exist, report vertex array range extension usage
if( ulExt & GOEXT_VERTEXARRAYRANGE) {
extern BOOL VB_bSetupFailed;
extern SLONG VB_slVertexBufferSize;
extern INDEX VB_iVertexBufferType;
extern INDEX ogl_iVertexBuffers;
if( VB_bSetupFailed) { // didn't manage to setup vertex buffers
CPrintF( "- Enhanced HW T&L: fail\n");
} else if( VB_iVertexBufferType==0) { // not used
CPrintF( "- Enhanced HW T&L: disabled\n");
} else { // works! :)
CTString strBufferType("AGP");
if( VB_iVertexBufferType==2) strBufferType = "video";
const SLONG slMemSize = VB_slVertexBufferSize/1024;
CPrintF( "- Enhanced hardware T&L: %d buffers in %d KB of %s memory",
ogl_iVertexBuffers, slMemSize, strBufferType);
}
} */
// report OpenGL externsions
CPrintF("\n");
CPrintF("- Published extensions: %s", ReformatExtensionsString(_pGfx->go_strExtensions));
if( _pGfx->go_strWinExtensions != "") CPrintF("%s", ReformatExtensionsString(_pGfx->go_strWinExtensions));
CPrintF("\n- Supported extensions: %s\n", ReformatExtensionsString(_pGfx->go_strSupportedExtensions));
}
// Direct3D only stuff
#ifdef SE1_D3D
if( eAPI==GAT_D3D)
{
// HW T&L
CPrintF( "- Hardware T&L: ");
if( _pGfx->gl_ulFlags&GLF_D3D_HASHWTNL) {
if( _pGfx->gl_ctMaxStreams<GFX_MINSTREAMS) CPrintF( "cannot be used\n");
else if( _pGfx->gl_ulFlags&GLF_D3D_USINGHWTNL) CPrintF( "enabled (%d streams)\n", _pGfx->gl_ctMaxStreams);
else CPrintF( "disabled\n");
} else CPrintF( "not present\n");
// report vtx/idx buffers size
extern SLONG SizeFromVertices_D3D( INDEX ctVertices);
const SLONG slMemoryUsed = SizeFromVertices_D3D(_pGfx->gl_ctVertices);
CPrintF( "- Vertex buffer size: %.1f KB (%d vertices)\n", slMemoryUsed/1024.0f, _pGfx->gl_ctVertices);
// N-Patches tessellation (Truform)
CPrintF( "- N-Patches: ");
if( _pGfx->gl_iMaxTessellationLevel>0) {
if( !(_pGfx->gl_ulFlags&GLF_D3D_USINGHWTNL)) CPrintF( "not possible with SW T&L\n");
else if( _pGfx->gl_iTessellationLevel>0) {
CPrintF( "enabled ");
if( gap_bForceTruform) CPrintF( "(for all models)\n");
else CPrintF( "(only for Truform-ready models)\n");
CPrintF( "- Tesselation level: %d of %d\n", _pGfx->gl_iTessellationLevel, _pGfx->gl_iMaxTessellationLevel);
} else CPrintF( "disabled\n");
} else CPrintF( "not supported\n");
// texture compression
CPrintF( "- Texture compression: ");
if( _pGfx->gl_ulFlags&GLF_TEXTURECOMPRESSION) CPrintF( "supported\n");
else CPrintF( "not supported\n");
// custom clip plane support
CPrintF( "- Custom clip plane: ");
if( _pGfx->gl_ulFlags&GLF_D3D_CLIPPLANE) CPrintF( "supported\n");
else CPrintF( "not supported\n");
// color buffer writes enable/disable support
CPrintF( "- Color masking: ");
if( _pGfx->gl_ulFlags&GLF_D3D_COLORWRITES) CPrintF( "supported\n");
else CPrintF( "not supported\n");
// depth (Z) bias support
CPrintF( "- Depth biasing: ");
if( _pGfx->gl_ulFlags&GLF_D3D_ZBIAS) CPrintF( "supported\n");
else CPrintF( "not supported\n");
// current swap interval (only if fullscreen)
if( _pGfx->gl_ulFlags&GLF_FULLSCREEN) {
CPrintF( "- Swap interval: ");
if( _pGfx->gl_ulFlags&GLF_VSYNC) {
CPrintF( "%d frame(s)\n", _pGfx->gl_iSwapInterval);
} else CPrintF( "not adjustable\n");
}
}
#endif // SE1_D3D
// Print info about Vulkan
#ifdef SE1_VULKAN
if (eAPI == GAT_VK)
{
CPrintF("Using Vulkan API.\n");
}
#endif // SE1_VULKAN
}
// update console system vars
extern void UpdateGfxSysCVars(void)
{
sys_bHasTextureCompression = 0;
sys_bHasTextureAnisotropy = 0;
sys_bHasAdjustableGamma = 0;
sys_bHasTextureLODBias = 0;
sys_bHasMultitexturing = 0;
sys_bHas32bitTextures = 0;
sys_bHasSwapInterval = 0;
sys_bHasHardwareTnL = 1;
sys_bHasTruform = 0;
sys_bHasCVAs = 1;
sys_bUsingOpenGL = 0;
sys_bUsingVulkan = 0;
sys_bUsingDirect3D = 0;
if( _pGfx->gl_iMaxTextureAnisotropy>1) sys_bHasTextureAnisotropy = 1;
if( _pGfx->gl_fMaxTextureLODBias>0) sys_bHasTextureLODBias = 1;
if( _pGfx->gl_ctTextureUnits>1) sys_bHasMultitexturing = 1;
if( _pGfx->gl_iMaxTessellationLevel>0) sys_bHasTruform = 1;
if( _pGfx->gl_ulFlags & GLF_TEXTURECOMPRESSION) sys_bHasTextureCompression = 1;
if( _pGfx->gl_ulFlags & GLF_ADJUSTABLEGAMMA) sys_bHasAdjustableGamma = 1;
if( _pGfx->gl_ulFlags & GLF_32BITTEXTURES) sys_bHas32bitTextures = 1;
if( _pGfx->gl_ulFlags & GLF_VSYNC) sys_bHasSwapInterval = 1;
if( _pGfx->gl_eCurrentAPI==GAT_OGL && !(_pGfx->gl_ulFlags&GLF_EXT_COMPILEDVERTEXARRAY)) sys_bHasCVAs = 0;
#ifdef SE1_D3D
if( _pGfx->gl_eCurrentAPI==GAT_D3D && !(_pGfx->gl_ulFlags&GLF_D3D_HASHWTNL)) sys_bHasHardwareTnL = 0;
#endif // SE1_D3D
if( _pGfx->gl_eCurrentAPI==GAT_OGL) sys_bUsingOpenGL = 1;
#ifdef SE1_D3D
if( _pGfx->gl_eCurrentAPI==GAT_D3D) sys_bUsingDirect3D = 1;
#endif // SE1_D3D
#ifdef SE1_VULKAN
if (_pGfx->gl_eCurrentAPI == GAT_VK) sys_bUsingVulkan = 1;
#endif // SE1_VULKAN
}
// determine whether texture or shadowmap needs probing
extern BOOL ProbeMode( CTimerValue tvLast)
{
// probing off ?
if( !_pGfx->gl_bAllowProbing) return FALSE;
if( gfx_tmProbeDecay<1) {
gfx_tmProbeDecay = 0;
return FALSE;
}
// clamp and determine probe mode
if( gfx_tmProbeDecay>999) gfx_tmProbeDecay = 999;
CTimerValue tvNow = _pTimer->GetHighPrecisionTimer();
const TIME tmDelta = (tvNow-tvLast).GetSeconds();
if( tmDelta>gfx_tmProbeDecay) return TRUE;
return FALSE;
}
// uncache all cached shadow maps
extern void UncacheShadows(void)
{
// mute all sounds
_pSound->Mute();
// prepare new saturation factors for shadowmaps
gfx_fSaturation = ClampDn( gfx_fSaturation, 0.0f);
shd_fSaturation = ClampDn( shd_fSaturation, 0.0f);
gfx_iHueShift = Clamp( gfx_iHueShift, 0L, 359L);
shd_iHueShift = Clamp( shd_iHueShift, 0L, 359L);
_slShdSaturation = (SLONG)( gfx_fSaturation*shd_fSaturation*256.0f);
_slShdHueShift = Clamp( (gfx_iHueShift+shd_iHueShift)*255L/359L, 0L, 255L);
CListHead &lhOriginal = _pGfx->gl_lhCachedShadows;
// while there is some shadow in main list
while( !lhOriginal.IsEmpty()) {
CShadowMap &sm = *LIST_HEAD( lhOriginal, CShadowMap, sm_lnInGfx);
sm.Uncache();
}
// mark that we need pretouching
_bNeedPretouch = TRUE;
}
// refresh (uncache and eventually cache) all cached shadow maps
extern void CacheShadows(void);
static void RecacheShadows(void)
{
// mute all sounds
_pSound->Mute();
UncacheShadows();
if( shd_bCacheAll) CacheShadows();
else CPrintF( TRANS("All shadows uncached.\n"));
}
// reload all textures that were loaded
extern void ReloadTextures(void)
{
// mute all sounds
_pSound->Mute();
// prepare new saturation factors for textures
gfx_fSaturation = ClampDn( gfx_fSaturation, 0.0f);
tex_fSaturation = ClampDn( tex_fSaturation, 0.0f);
gfx_iHueShift = Clamp( gfx_iHueShift, 0L, 359L);
tex_iHueShift = Clamp( tex_iHueShift, 0L, 359L);
_slTexSaturation = (SLONG)( gfx_fSaturation*tex_fSaturation*256.0f);
_slTexHueShift = Clamp( (gfx_iHueShift+tex_iHueShift)*255L/359L, 0L, 255L);
// update texture settings
UpdateTextureSettings();
// loop thru texture stock
{FOREACHINDYNAMICCONTAINER( _pTextureStock->st_ctObjects, CTextureData, ittd) {
CTextureData &td = *ittd;
td.Reload();
td.td_tpLocal.Clear();
}}
// reset fog/haze texture
_fog_pixSizeH = 0;
_fog_pixSizeL = 0;
_haze_pixSize = 0;
// reinit flat texture
ASSERT( _ptdFlat!=NULL);
_ptdFlat->td_tpLocal.Clear();
_ptdFlat->Unbind();
_ptdFlat->td_ulFlags = TEX_ALPHACHANNEL | TEX_32BIT | TEX_STATIC;
_ptdFlat->td_mexWidth = 1;
_ptdFlat->td_mexHeight = 1;
_ptdFlat->td_iFirstMipLevel = 0;
_ptdFlat->td_ctFineMipLevels = 1;
_ptdFlat->td_slFrameSize = 1*1* BYTES_PER_TEXEL;
_ptdFlat->td_ctFrames = 1;
_ptdFlat->td_ulInternalFormat = TS.ts_tfRGBA8;
_ptdFlat->td_pulFrames = &_ulWhite;
_ptdFlat->SetAsCurrent();
/*
// reset are renderable textures, too
CListHead &lhOriginal = _pGfx->gl_lhRenderTextures;
while( !lhOriginal.IsEmpty()) {
CRenderTexture &rt = *LIST_HEAD( lhOriginal, CRenderTexture, rt_lnInGfx);
rt.Reset();
}
*/
// mark that we need pretouching
_bNeedPretouch = TRUE;
CPrintF( TRANS("All textures reloaded.\n"));
}
// refreshes all textures and shadow maps
static void RefreshTextures(void)
{
// refresh
ReloadTextures();
RecacheShadows();
}
// reload all models that were loaded
static void ReloadModels(void)
{
// mute all sounds
_pSound->Mute();
// loop thru model stock
{FOREACHINDYNAMICCONTAINER( _pModelStock->st_ctObjects, CModelData, itmd) {
CModelData &md = *itmd;
md.Reload();
}}
// mark that we need pretouching
_bNeedPretouch = TRUE;
// all done
CPrintF( TRANS("All models reloaded.\n"));
}
// variable change post functions
static BOOL _bLastModelQuality = -1;
static void MdlPostFunc(void *pvVar)
{
mdl_bFineQuality = Clamp( mdl_bFineQuality, 0L, 1L);
if( _bLastModelQuality!=mdl_bFineQuality) {
_bLastModelQuality = mdl_bFineQuality;
ReloadModels();
}
}
/*
* GfxLibrary functions
*/
static void PrepareTables(void)
{
INDEX i;
// prepare array for fast clamping to 0..255
for( i=-256*2; i<256*4; i++) aubClipByte[i+256*2] = (UBYTE)Clamp( i, 0L, 255L);
// prepare fast sqrt tables
for( i=0; i<SQRTTABLESIZE; i++) aubSqrt[i] = (UBYTE)(sqrt((FLOAT)(i*65536/SQRTTABLESIZE)));
for( i=1; i<SQRTTABLESIZE; i++) auw1oSqrt[i] = (UWORD)(sqrt((FLOAT)(SQRTTABLESIZE-1)/i)*255.0f);
auw1oSqrt[0] = MAX_UWORD;
// prepare fast sin/cos table
for( i=-256; i<256+64; i++) afSinTable[i+256] = Sin((i-128)/256.0f*360.0f);
// prepare gouraud conversion table
for( INDEX h=0; h<128; h++) {
for( INDEX p=0; p<128; p++) {
const FLOAT fSinH = pfSinTable[h*2];
const FLOAT fSinP = pfSinTable[p*2];
const FLOAT fCosH = pfCosTable[h*2];
const FLOAT fCosP = pfCosTable[p*2];
const FLOAT3D v( -fSinH*fCosP, +fSinP, -fCosH*fCosP);
aubGouraudConv[h*128+p] = (UBYTE)GouraudNormal(v);
}
}
}
/*
* Construct uninitialized gfx library.
*/
CGfxLibrary::CGfxLibrary(void)
{
// reset some variables to default
gl_iFrameNumber = 0;
gl_slAllowedUploadBurst = 0;
gl_bAllowProbing = FALSE;
gl_iSwapInterval = 1234;
gl_pixMaxTextureDimension = 8192;
gl_ctTextureUnits = 0;
gl_ctRealTextureUnits = 0;
gl_fTextureLODBias = 0;
gl_fMaxTextureLODBias = 0;
gl_iMaxTextureAnisotropy = 0;
gl_iMaxTessellationLevel = 0;
gl_iTessellationLevel = 0;
gl_ulFlags = NONE;
// create some internal tables
PrepareTables();
// no driver loaded
gl_eCurrentAPI = GAT_NONE;
gl_hiDriver = NONE;
go_hglRC = NONE;
gl_ctDriverChanges = 0;
// DX8 not loaded either
#ifdef SE1_D3D
gl_pD3D = NONE;
gl_pd3dDevice = NULL;
gl_d3dColorFormat = (D3DFORMAT)NONE;
gl_d3dDepthFormat = (D3DFORMAT)NONE;
#endif // SE1_D3D
gl_pvpActive = NULL;
gl_ctMaxStreams = 0;
gl_dwVertexShader = 0;
#ifdef SE1_D3D
gl_pd3dIdx = NULL;
gl_pd3dVtx = NULL;
gl_pd3dNor = NULL;
for( INDEX i=0; i<GFX_MAXLAYERS; i++) gl_pd3dCol[i] = gl_pd3dTex[i] = NULL;
#endif // SE1_D3D
gl_ctVertices = 0;
gl_ctIndices = 0;
#ifdef SE1_VULKAN
gl_SvkMain = nullptr;
#endif // SE1_VULKAN
// reset profiling counters
gl_ctWorldTriangles = 0;
gl_ctModelTriangles = 0;
gl_ctParticleTriangles = 0;
gl_ctTotalTriangles = 0;
// init flat texture
_ptdFlat = new CTextureData;
_ptdFlat->td_ulFlags = TEX_ALPHACHANNEL | TEX_32BIT | TEX_STATIC;
// prepare some quad elements
extern void AddQuadElements( const INDEX ctQuads);
AddQuadElements(1024); // should be enough (at least for a start)
// reset GFX API function pointers
GFX_SetFunctionPointers( (INDEX)GAT_NONE);
}
/*
* Destruct (and clean up).
*/
CGfxLibrary::~CGfxLibrary()
{
extern void EnableWindowsKeys(void);
EnableWindowsKeys();
// free common arrays
_avtxCommon.Clear();
_atexCommon.Clear();
_acolCommon.Clear();
_aiCommonElements.Clear();
_aiCommonQuads.Clear();
// stop current display mode
StopDisplayMode();
// safe release of flat texture
ASSERT( _ptdFlat!=NULL);
_ptdFlat->td_pulFrames = NULL;
delete _ptdFlat;
_ptdFlat = NULL;
}
#define SM_CXVIRTUALSCREEN 78
#define SM_CYVIRTUALSCREEN 79
#define SM_CMONITORS 80
/* Initialize library for application main window. */
void CGfxLibrary::Init(void)
{
ASSERT( this!=NULL);
// report desktop settings
CPrintF(TRANS("Desktop settings...\n"));
HDC hdc = GetDC(NULL);
SLONG slBPP = GetDeviceCaps(hdc, PLANES) * GetDeviceCaps(hdc, BITSPIXEL);
ReleaseDC(NULL, hdc);
gfx_ctMonitors = GetSystemMetrics(SM_CMONITORS);
CPrintF(TRANS(" Color Depth: %dbit\n"), slBPP);
CPrintF(TRANS(" Screen: %dx%d\n"), GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
CPrintF(TRANS(" Virtual screen: %dx%d\n"), GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN));
CPrintF(TRANS(" Monitors directly reported: %d\n"), gfx_ctMonitors);
CPrintF("\n");
gfx_bMultiMonDisabled = FALSE;
_pfGfxProfile.Reset();
// we will never allow glide splash screen
putenv( "FX_GLIDE_NO_SPLASH=1");
// declare some console vars
_pShell->DeclareSymbol("user void MonitorsOn(void);", &MonitorsOn);
_pShell->DeclareSymbol("user void MonitorsOff(void);", &MonitorsOff);
_pShell->DeclareSymbol("user void GAPInfo(void);", &GAPInfo);
_pShell->DeclareSymbol("user void TexturesInfo(void);", &TexturesInfo);
_pShell->DeclareSymbol("user void UncacheShadows(void);", &UncacheShadows);
_pShell->DeclareSymbol("user void RecacheShadows(void);", &RecacheShadows);
_pShell->DeclareSymbol("user void RefreshTextures(void);", &RefreshTextures);
_pShell->DeclareSymbol("user void ReloadModels(void);", &ReloadModels);
_pShell->DeclareSymbol("persistent user INDEX ogl_bUseCompiledVertexArrays;", &ogl_bUseCompiledVertexArrays);
_pShell->DeclareSymbol("persistent user INDEX ogl_bExclusive;", &ogl_bExclusive);
_pShell->DeclareSymbol("persistent user INDEX ogl_bAllowQuadArrays;", &ogl_bAllowQuadArrays);
_pShell->DeclareSymbol("persistent user INDEX ogl_iTextureCompressionType;", &ogl_iTextureCompressionType);
_pShell->DeclareSymbol("persistent user INDEX ogl_iMaxBurstSize;", &ogl_iMaxBurstSize);
_pShell->DeclareSymbol("persistent user INDEX ogl_bGrabDepthBuffer;", &ogl_bGrabDepthBuffer);
_pShell->DeclareSymbol("persistent user INDEX ogl_iFinish;", &ogl_iFinish);
_pShell->DeclareSymbol("persistent user INDEX ogl_iTBufferEffect;", &ogl_iTBufferEffect);
_pShell->DeclareSymbol("persistent user INDEX ogl_iTBufferSamples;", &ogl_iTBufferSamples);
_pShell->DeclareSymbol("persistent user INDEX ogl_bTruformLinearNormals;", &ogl_bTruformLinearNormals);
_pShell->DeclareSymbol("persistent user INDEX ogl_bAlternateClipPlane;", &ogl_bAlternateClipPlane);
_pShell->DeclareSymbol("persistent user INDEX d3d_bUseHardwareTnL;", &d3d_bUseHardwareTnL);
_pShell->DeclareSymbol("persistent user INDEX d3d_iMaxBurstSize;", &d3d_iMaxBurstSize);
_pShell->DeclareSymbol("persistent user INDEX d3d_iVertexBuffersSize;", &d3d_iVertexBuffersSize);
_pShell->DeclareSymbol("persistent user INDEX d3d_iVertexRangeTreshold;", &d3d_iVertexRangeTreshold);
_pShell->DeclareSymbol("persistent user INDEX d3d_bAlternateDepthReads;", &d3d_bAlternateDepthReads);
_pShell->DeclareSymbol("persistent INDEX d3d_bFastUpload;", &d3d_bFastUpload);
_pShell->DeclareSymbol("persistent user INDEX d3d_iFinish;", &d3d_iFinish);
_pShell->DeclareSymbol("persistent user INDEX gfx_vk_iPresentMode;", &gfx_vk_iPresentMode);
_pShell->DeclareSymbol("persistent user INDEX gfx_vk_iMSAA;", &gfx_vk_iMSAA);
_pShell->DeclareSymbol("persistent user INDEX gap_iUseTextureUnits;", &gap_iUseTextureUnits);
_pShell->DeclareSymbol("persistent user INDEX gap_iTextureFiltering;", &gap_iTextureFiltering);
_pShell->DeclareSymbol("persistent user INDEX gap_iTextureAnisotropy;", &gap_iTextureAnisotropy);
_pShell->DeclareSymbol("persistent user FLOAT gap_fTextureLODBias;", &gap_fTextureLODBias);
_pShell->DeclareSymbol("persistent user INDEX gap_bAllowGrayTextures;", &gap_bAllowGrayTextures);
_pShell->DeclareSymbol("persistent user INDEX gap_bAllowSingleMipmap;", &gap_bAllowSingleMipmap);
_pShell->DeclareSymbol("persistent user INDEX gap_bOptimizeStateChanges;", &gap_bOptimizeStateChanges);
_pShell->DeclareSymbol("persistent user INDEX gap_iOptimizeDepthReads;", &gap_iOptimizeDepthReads);
_pShell->DeclareSymbol("persistent user INDEX gap_iOptimizeClipping;", &gap_iOptimizeClipping);
_pShell->DeclareSymbol("persistent user INDEX gap_iSwapInterval;", &gap_iSwapInterval);
_pShell->DeclareSymbol("persistent user INDEX gap_iRefreshRate;", &gap_iRefreshRate);
_pShell->DeclareSymbol("persistent user INDEX gap_iDithering;", &gap_iDithering);
_pShell->DeclareSymbol("persistent user INDEX gap_bForceTruform;", &gap_bForceTruform);
_pShell->DeclareSymbol("persistent user INDEX gap_iTruformLevel;", &gap_iTruformLevel);
_pShell->DeclareSymbol("persistent user INDEX gap_iDepthBits;", &gap_iDepthBits);
_pShell->DeclareSymbol("persistent user INDEX gap_iStencilBits;", &gap_iStencilBits);
_pShell->DeclareSymbol("void MdlPostFunc(INDEX);", &MdlPostFunc);
_pShell->DeclareSymbol(" user INDEX gfx_bRenderPredicted;", &gfx_bRenderPredicted);
_pShell->DeclareSymbol(" user INDEX gfx_bRenderModels;", &gfx_bRenderModels);
_pShell->DeclareSymbol(" user INDEX mdl_bShowTriangles;", &mdl_bShowTriangles);
_pShell->DeclareSymbol(" user INDEX mdl_bCreateStrips;", &mdl_bCreateStrips);
_pShell->DeclareSymbol(" user INDEX mdl_bShowStrips;", &mdl_bShowStrips);
_pShell->DeclareSymbol("persistent user FLOAT mdl_fLODMul;", &mdl_fLODMul);
_pShell->DeclareSymbol("persistent user FLOAT mdl_fLODAdd;", &mdl_fLODAdd);
_pShell->DeclareSymbol("persistent user INDEX mdl_iLODDisappear;", &mdl_iLODDisappear);
_pShell->DeclareSymbol("persistent user INDEX mdl_bRenderDetail;", &mdl_bRenderDetail);
_pShell->DeclareSymbol("persistent user INDEX mdl_bRenderSpecular;", &mdl_bRenderSpecular);
_pShell->DeclareSymbol("persistent user INDEX mdl_bRenderReflection;", &mdl_bRenderReflection);
_pShell->DeclareSymbol("persistent user INDEX mdl_bRenderBump;", &mdl_bRenderBump);
_pShell->DeclareSymbol("persistent user INDEX mdl_bAllowOverbright;", &mdl_bAllowOverbright);
_pShell->DeclareSymbol("persistent user INDEX mdl_bFineQuality post:MdlPostFunc;", &mdl_bFineQuality);
_pShell->DeclareSymbol("persistent user INDEX mdl_iShadowQuality;", &mdl_iShadowQuality);
_pShell->DeclareSymbol(" INDEX mdl_bTruformWeapons;", &mdl_bTruformWeapons);
_pShell->DeclareSymbol(" user INDEX ska_bShowSkeleton;", &ska_bShowSkeleton);
_pShell->DeclareSymbol(" user INDEX ska_bShowColision;", &ska_bShowColision);
_pShell->DeclareSymbol("persistent user FLOAT ska_fLODMul;", &ska_fLODMul);
_pShell->DeclareSymbol("persistent user FLOAT ska_fLODAdd;", &ska_fLODAdd);
_pShell->DeclareSymbol(" user INDEX ter_bShowQuadTree;", &ter_bShowQuadTree);
_pShell->DeclareSymbol(" user INDEX ter_bShowWireframe;", &ter_bShowWireframe);
_pShell->DeclareSymbol(" user INDEX ter_bLerpVertices;", &ter_bLerpVertices);
_pShell->DeclareSymbol(" user INDEX ter_bShowInfo;", &ter_bShowInfo);
_pShell->DeclareSymbol(" user INDEX ter_bOptimizeRendering;", &ter_bOptimizeRendering);
_pShell->DeclareSymbol(" user INDEX ter_bTempFreezeCast; ", &ter_bTempFreezeCast);
_pShell->DeclareSymbol(" user INDEX ter_bNoRegeneration; ", &ter_bNoRegeneration);
_pShell->DeclareSymbol("persistent user FLOAT gfx_tmProbeDecay;", &gfx_tmProbeDecay);
_pShell->DeclareSymbol("persistent user INDEX gfx_iProbeSize;", &gfx_iProbeSize);
_pShell->DeclareSymbol("persistent user INDEX gfx_bClearScreen;", &gfx_bClearScreen);
_pShell->DeclareSymbol("persistent user INDEX gfx_bDisableMultiMonSupport;", &gfx_bDisableMultiMonSupport);
_pShell->DeclareSymbol("persistent user INDEX gfx_bDisableWindowsKeys;", &gfx_bDisableWindowsKeys);
_pShell->DeclareSymbol("persistent user INDEX gfx_bDecoratedText;", &gfx_bDecoratedText);
_pShell->DeclareSymbol(" const user INDEX gfx_ctMonitors;", &gfx_ctMonitors);
_pShell->DeclareSymbol(" const user INDEX gfx_bMultiMonDisabled;", &gfx_bMultiMonDisabled);
_pShell->DeclareSymbol("persistent user INDEX tex_iNormalQuality;", &tex_iNormalQuality);
_pShell->DeclareSymbol("persistent user INDEX tex_iAnimationQuality;", &tex_iAnimationQuality);
_pShell->DeclareSymbol("persistent user INDEX tex_bFineEffect;", &tex_bFineEffect);
_pShell->DeclareSymbol("persistent user INDEX tex_bFineFog;", &tex_bFineFog);
_pShell->DeclareSymbol("persistent user INDEX tex_iNormalSize;", &tex_iNormalSize);
_pShell->DeclareSymbol("persistent user INDEX tex_iAnimationSize;", &tex_iAnimationSize);
_pShell->DeclareSymbol("persistent user INDEX tex_iEffectSize;", &tex_iEffectSize);
_pShell->DeclareSymbol("persistent user INDEX tex_iFogSize;", &tex_iFogSize);
_pShell->DeclareSymbol("persistent user INDEX tex_bCompressAlphaChannel;", &tex_bCompressAlphaChannel);
_pShell->DeclareSymbol("persistent user INDEX tex_bAlternateCompression;", &tex_bAlternateCompression);
_pShell->DeclareSymbol("persistent user INDEX tex_bDynamicMipmaps;", &tex_bDynamicMipmaps);
_pShell->DeclareSymbol("persistent user INDEX tex_iDithering;", &tex_iDithering);
_pShell->DeclareSymbol("persistent user INDEX tex_iFiltering;", &tex_iFiltering);
_pShell->DeclareSymbol("persistent user INDEX tex_iEffectFiltering;", &tex_iEffectFiltering);
_pShell->DeclareSymbol("persistent user INDEX tex_bProgressiveFilter;", &tex_bProgressiveFilter);
_pShell->DeclareSymbol(" user INDEX tex_bColorizeMipmaps;", &tex_bColorizeMipmaps);
_pShell->DeclareSymbol("persistent user INDEX shd_iStaticSize;", &shd_iStaticSize);
_pShell->DeclareSymbol("persistent user INDEX shd_iDynamicSize;", &shd_iDynamicSize);
_pShell->DeclareSymbol("persistent user INDEX shd_bFineQuality;", &shd_bFineQuality);
_pShell->DeclareSymbol("persistent user INDEX shd_iAllowDynamic;", &shd_iAllowDynamic);
_pShell->DeclareSymbol("persistent user INDEX shd_bDynamicMipmaps;", &shd_bDynamicMipmaps);
_pShell->DeclareSymbol("persistent user INDEX shd_iFiltering;", &shd_iFiltering);
_pShell->DeclareSymbol("persistent user INDEX shd_iDithering;", &shd_iDithering);
_pShell->DeclareSymbol("persistent user FLOAT shd_tmFlushDelay;", &shd_tmFlushDelay);
_pShell->DeclareSymbol("persistent user FLOAT shd_fCacheSize;", &shd_fCacheSize);
_pShell->DeclareSymbol("persistent user INDEX shd_bCacheAll;", &shd_bCacheAll);
_pShell->DeclareSymbol("persistent user INDEX shd_bAllowFlats;", &shd_bAllowFlats);
_pShell->DeclareSymbol("persistent INDEX shd_iForceFlats;", &shd_iForceFlats);
_pShell->DeclareSymbol(" user INDEX shd_bShowFlats;", &shd_bShowFlats);
_pShell->DeclareSymbol(" user INDEX shd_bColorize;", &shd_bColorize);
_pShell->DeclareSymbol(" user INDEX gfx_bRenderParticles;", &gfx_bRenderParticles);
_pShell->DeclareSymbol(" user INDEX gfx_bRenderFog;", &gfx_bRenderFog);
_pShell->DeclareSymbol(" user INDEX gfx_bRenderWorld;", &gfx_bRenderWorld);
_pShell->DeclareSymbol("persistent user INDEX gfx_iLensFlareQuality;", &gfx_iLensFlareQuality);
_pShell->DeclareSymbol("persistent user INDEX wld_bTextureLayers;", &wld_bTextureLayers);
_pShell->DeclareSymbol("persistent user INDEX wld_bRenderMirrors;", &wld_bRenderMirrors);
_pShell->DeclareSymbol("persistent user FLOAT wld_fEdgeOffsetI;", &wld_fEdgeOffsetI);
_pShell->DeclareSymbol("persistent user FLOAT wld_fEdgeAdjustK;", &wld_fEdgeAdjustK);
_pShell->DeclareSymbol("persistent user INDEX wld_iDetailRemovingBias;", &wld_iDetailRemovingBias);
_pShell->DeclareSymbol(" user INDEX wld_bRenderEmptyBrushes;", &wld_bRenderEmptyBrushes);
_pShell->DeclareSymbol(" user INDEX wld_bRenderShadowMaps;", &wld_bRenderShadowMaps);
_pShell->DeclareSymbol(" user INDEX wld_bRenderTextures;", &wld_bRenderTextures);
_pShell->DeclareSymbol(" user INDEX wld_bRenderDetailPolygons;", &wld_bRenderDetailPolygons);
_pShell->DeclareSymbol(" user INDEX wld_bShowTriangles;", &wld_bShowTriangles);
_pShell->DeclareSymbol(" user INDEX wld_bShowDetailTextures;", &wld_bShowDetailTextures);
_pShell->DeclareSymbol(" user INDEX wed_bIgnoreTJunctions;", &wed_bIgnoreTJunctions);
_pShell->DeclareSymbol("persistent user INDEX wed_bUseBaseForReplacement;", &wed_bUseBaseForReplacement);
_pShell->DeclareSymbol("persistent user INDEX tex_iHueShift;", &tex_iHueShift);
_pShell->DeclareSymbol("persistent user FLOAT tex_fSaturation;", &tex_fSaturation);
_pShell->DeclareSymbol("persistent user INDEX shd_iHueShift;", &shd_iHueShift);
_pShell->DeclareSymbol("persistent user FLOAT shd_fSaturation;", &shd_fSaturation);
_pShell->DeclareSymbol("persistent user INDEX gfx_iHueShift;", &gfx_iHueShift);
_pShell->DeclareSymbol("persistent user FLOAT gfx_fSaturation;", &gfx_fSaturation);
_pShell->DeclareSymbol("persistent user FLOAT gfx_fBrightness;", &gfx_fBrightness);
_pShell->DeclareSymbol("persistent user FLOAT gfx_fContrast;", &gfx_fContrast);
_pShell->DeclareSymbol("persistent user FLOAT gfx_fGamma;", &gfx_fGamma);
_pShell->DeclareSymbol("persistent user FLOAT gfx_fBiasR;", &gfx_fBiasR);
_pShell->DeclareSymbol("persistent user FLOAT gfx_fBiasG;", &gfx_fBiasG);
_pShell->DeclareSymbol("persistent user FLOAT gfx_fBiasB;", &gfx_fBiasB);
_pShell->DeclareSymbol("persistent user INDEX gfx_iLevels;", &gfx_iLevels);
_pShell->DeclareSymbol("persistent user INDEX gfx_iStereo;", &gfx_iStereo);
_pShell->DeclareSymbol("persistent user INDEX gfx_bStereoInvert;", &gfx_bStereoInvert);
_pShell->DeclareSymbol("persistent user INDEX gfx_iStereoOffset;", &gfx_iStereoOffset);
_pShell->DeclareSymbol("persistent user FLOAT gfx_fStereoSeparation;", &gfx_fStereoSeparation);
_pShell->DeclareSymbol( "INDEX sys_bHasTextureCompression;", &sys_bHasTextureCompression);
_pShell->DeclareSymbol( "INDEX sys_bHasTextureAnisotropy;", &sys_bHasTextureAnisotropy);
_pShell->DeclareSymbol( "INDEX sys_bHasAdjustableGamma;", &sys_bHasAdjustableGamma);
_pShell->DeclareSymbol( "INDEX sys_bHasTextureLODBias;", &sys_bHasTextureLODBias);
_pShell->DeclareSymbol( "INDEX sys_bHasMultitexturing;", &sys_bHasMultitexturing);
_pShell->DeclareSymbol( "INDEX sys_bHas32bitTextures;", &sys_bHas32bitTextures);
_pShell->DeclareSymbol( "INDEX sys_bHasSwapInterval;", &sys_bHasSwapInterval);
_pShell->DeclareSymbol( "INDEX sys_bHasHardwareTnL;", &sys_bHasHardwareTnL);
_pShell->DeclareSymbol( "INDEX sys_bHasTruform;", &sys_bHasTruform);
_pShell->DeclareSymbol( "INDEX sys_bHasCVAs;", &sys_bHasCVAs);
_pShell->DeclareSymbol( "INDEX sys_bUsingOpenGL;", &sys_bUsingOpenGL);
_pShell->DeclareSymbol( "INDEX sys_bUsingDirect3D;", &sys_bUsingDirect3D);
_pShell->DeclareSymbol( "INDEX sys_bUsingVulkan;", &sys_bUsingVulkan);
// initialize gfx APIs support
InitAPIs();
}
// set new display mode
BOOL CGfxLibrary::SetDisplayMode( enum GfxAPIType eAPI, INDEX iAdapter, PIX pixSizeI, PIX pixSizeJ,
enum DisplayDepth eColorDepth)
{
// some safeties
ASSERT( pixSizeI>0 && pixSizeJ>0);
// determine new API
GfxAPIType eNewAPI = eAPI;
if( eNewAPI==GAT_CURRENT) eNewAPI = gl_eCurrentAPI;
// shutdown old and startup new API, and mode and ... stuff, you know!
StopDisplayMode();
BOOL bRet = StartDisplayMode( eNewAPI, iAdapter, pixSizeI, pixSizeJ, eColorDepth);
if( !bRet) return FALSE; // didn't make it?
// update some info
gl_iCurrentAdapter = gl_gaAPI[gl_eCurrentAPI].ga_iCurrentAdapter = iAdapter;
gl_dmCurrentDisplayMode.dm_pixSizeI = pixSizeI;
gl_dmCurrentDisplayMode.dm_pixSizeJ = pixSizeJ;
gl_dmCurrentDisplayMode.dm_ddDepth = eColorDepth;
// prepare texture formats for this display mode
extern void DetermineSupportedTextureFormats( GfxAPIType eAPI);
DetermineSupportedTextureFormats(gl_eCurrentAPI);
// made it! (eventually disable windows system keys)
if( gfx_bDisableWindowsKeys) DisableWindowsKeys();
return TRUE;
}
// set display mode to original desktop display mode and default ICD driver
BOOL CGfxLibrary::ResetDisplayMode( enum GfxAPIType eAPI/*=GAT_CURRENT*/)
{
// determine new API
GfxAPIType eNewAPI = eAPI;
if( eNewAPI==GAT_CURRENT) eNewAPI = gl_eCurrentAPI;
// shutdown old and startup new API, and mode and ... stuff, you know!
StopDisplayMode();
BOOL bRet = StartDisplayMode( eNewAPI, 0, 0, 0, DD_DEFAULT);
if( !bRet) return FALSE; // didn't make it?
// update some info
gl_iCurrentAdapter = 0;
gl_dmCurrentDisplayMode.dm_pixSizeI = 0;
gl_dmCurrentDisplayMode.dm_pixSizeJ = 0;
gl_dmCurrentDisplayMode.dm_ddDepth = DD_DEFAULT;
// prepare texture formats for this display mode
extern void DetermineSupportedTextureFormats( GfxAPIType eAPI);
DetermineSupportedTextureFormats(gl_eCurrentAPI);
// made it!
EnableWindowsKeys();
return TRUE;
}
// startup gfx API and set given display mode
BOOL CGfxLibrary::StartDisplayMode( enum GfxAPIType eAPI, INDEX iAdapter, PIX pixSizeI, PIX pixSizeJ,
enum DisplayDepth eColorDepth)
{
// reinit gamma table
_fLastBrightness = 999;
_fLastContrast = 999;
_fLastGamma = 999;
_iLastLevels = 999;
_fLastBiasR = 999;
_fLastBiasG = 999;
_fLastBiasB = 999;
// prepare
BOOL bSuccess;
ASSERT( iAdapter>=0);
const BOOL bFullScreen = (pixSizeI>0 && pixSizeJ>0);
gl_ulFlags &= GLF_ADJUSTABLEGAMMA;
gl_ctDriverChanges++;
GFX_bRenderingScene = FALSE;
GFX_ulLastDrawPortID = 0;
gl_iTessellationLevel = 0;
gl_ctRealTextureUnits = 0;
_iLastVertexBufferSize = 0;
// prevent usage of Vulkan and DirectX at the same time
#ifdef SE1_VULKAN
#ifdef SE1_D3D
ASSERT(FALSE);
#endif // SE1_D3D
#endif // SE1_VULKAN
// OpenGL driver ?
if( eAPI==GAT_OGL)
{
// disable multimonitor support if it can interfere with OpenGL
MonitorsOff();
if( bFullScreen) {
// set windows mode to fit same size
bSuccess = CDS_SetMode( pixSizeI, pixSizeJ, eColorDepth);
if( !bSuccess) return FALSE;
} else {
// reset windows mode
CDS_ResetMode();
}
// startup OpenGL
bSuccess = InitDriver_OGL(iAdapter!=0);
// try to setup sub-driver
if( !bSuccess) {
// reset windows mode and fail
CDS_ResetMode();
return FALSE;
} // made it
gl_eCurrentAPI = GAT_OGL;
gl_iSwapInterval = 1234; // need to reset
}
// DirectX driver ?
#ifdef SE1_D3D
else if( eAPI==GAT_D3D)
{
// startup D3D
bSuccess = InitDriver_D3D();
if( !bSuccess) return FALSE; // what, didn't make it?
bSuccess = InitDisplay_D3D( iAdapter, pixSizeI, pixSizeJ, eColorDepth);
if( !bSuccess) return FALSE;
// made it
gl_eCurrentAPI = GAT_D3D;
}
#endif // SE1_D3D
#ifdef SE1_VULKAN
else if (eAPI == GAT_VK)
{
bSuccess = InitDriver_Vulkan();
if (!bSuccess) return FALSE;
gl_eCurrentAPI = GAT_VK;
}
#endif // SE1_VULKAN
// no driver
else
{
ASSERT( eAPI==GAT_NONE);
gl_eCurrentAPI = GAT_NONE;
}
// initialize on first child window
gl_iFrameNumber = 0;
gl_pvpActive = NULL;
gl_ulFlags |= GLF_INITONNEXTWINDOW;
bFullScreen ? gl_ulFlags|=GLF_FULLSCREEN : gl_ulFlags&=~GLF_FULLSCREEN;
// mark that some things needs to be reinitialized
gl_fTextureLODBias = 0.0f;
// set function pointers
GFX_SetFunctionPointers( (INDEX)gl_eCurrentAPI);
// all done
return TRUE;
}
// Stop display mode and shutdown API
void CGfxLibrary::StopDisplayMode(void)
{
// release all cached shadows and models' arrays
extern void Models_ClearVertexArrays(void);
extern void UncacheShadows(void);
Models_ClearVertexArrays();
UncacheShadows();
// shutdown API
if( gl_eCurrentAPI==GAT_OGL)
{ // OpenGL
EndDriver_OGL();
MonitorsOn(); // re-enable multimonitor support if disabled
CDS_ResetMode();
}
#ifdef SE1_D3D
else if( gl_eCurrentAPI==GAT_D3D)
{ // Direct3D
EndDriver_D3D();
MonitorsOn();
}
#endif // SE1_D3D
#ifdef SE1_VULKAN
else if (gl_eCurrentAPI == GAT_VK)
{ // Vulkan
EndDriver_Vulkan();
MonitorsOn();
}
#endif // SE1_VULKAN
else
{ // none
ASSERT( gl_eCurrentAPI==GAT_NONE);
}
// free driver DLL
if( gl_hiDriver!=NONE) FreeLibrary(gl_hiDriver);
gl_hiDriver = NONE;
// reset some vars
gl_ctRealTextureUnits = 0;
gl_eCurrentAPI = GAT_NONE;
gl_pvpActive = NULL;
gl_ulFlags &= GLF_ADJUSTABLEGAMMA;
// reset function pointers
GFX_SetFunctionPointers( (INDEX)GAT_NONE);
}
// prepare current viewport for rendering
BOOL CGfxLibrary::SetCurrentViewport(CViewPort *pvp)
{
if( gl_eCurrentAPI==GAT_OGL) return SetCurrentViewport_OGL(pvp);
#ifdef SE1_D3D
if( gl_eCurrentAPI==GAT_D3D) return SetCurrentViewport_D3D(pvp);
#endif // SE1_D3D
#ifdef SE1_VULKAN
if (gl_eCurrentAPI == GAT_VK) return SetCurrentViewport_Vulkan(pvp);
#endif // SE1_VULKAN
if( gl_eCurrentAPI==GAT_NONE) return TRUE;
ASSERTALWAYS( "SetCurrenViewport: Wrong API!");
return FALSE;
}
// Lock a drawport for drawing
BOOL CGfxLibrary::LockDrawPort( CDrawPort *pdpToLock)
{
// check API
#ifdef SE1_D3D
ASSERT( gl_eCurrentAPI==GAT_OGL || gl_eCurrentAPI==GAT_D3D || gl_eCurrentAPI==GAT_NONE);
#else // SE1_D3D
#ifdef SE1_VULKAN
ASSERT(gl_eCurrentAPI == GAT_OGL || gl_eCurrentAPI == GAT_VK || gl_eCurrentAPI == GAT_NONE);
#else
ASSERT(gl_eCurrentAPI == GAT_OGL || gl_eCurrentAPI == GAT_NONE);
#endif // SE1_VULKAN
#endif // SE1_D3D
// don't allow locking if drawport is too small
if( pdpToLock->dp_Width<1 || pdpToLock->dp_Height<1) return FALSE;
// don't set if same as last
const ULONG ulThisDrawPortID = pdpToLock->GetID();
if( GFX_ulLastDrawPortID==ulThisDrawPortID && gap_bOptimizeStateChanges) {
// just set projection
pdpToLock->SetOrtho();
return TRUE;
}
// OpenGL ...
if( gl_eCurrentAPI==GAT_OGL)
{
// pass drawport dimensions to OpenGL
const PIX pixMinSI = pdpToLock->dp_ScissorMinI;
const PIX pixMaxSI = pdpToLock->dp_ScissorMaxI;
const PIX pixMinSJ = pdpToLock->dp_Raster->ra_Height -1 - pdpToLock->dp_ScissorMaxJ;
const PIX pixMaxSJ = pdpToLock->dp_Raster->ra_Height -1 - pdpToLock->dp_ScissorMinJ;
pglViewport( pixMinSI, pixMinSJ, pixMaxSI-pixMinSI+1, pixMaxSJ-pixMinSJ+1);
pglScissor( pixMinSI, pixMinSJ, pixMaxSI-pixMinSI+1, pixMaxSJ-pixMinSJ+1);
OGL_CHECKERROR;
}
// Direct3D ...
#ifdef SE1_D3D
else if( gl_eCurrentAPI==GAT_D3D)
{
// set viewport
const PIX pixMinSI = pdpToLock->dp_ScissorMinI;
const PIX pixMaxSI = pdpToLock->dp_ScissorMaxI;
const PIX pixMinSJ = pdpToLock->dp_ScissorMinJ;
const PIX pixMaxSJ = pdpToLock->dp_ScissorMaxJ;
D3DVIEWPORT8 d3dViewPort = { pixMinSI, pixMinSJ, pixMaxSI-pixMinSI+1, pixMaxSJ-pixMinSJ+1, 0,1 };
HRESULT hr = gl_pd3dDevice->SetViewport( &d3dViewPort);
D3D_CHECKERROR(hr);
}
#endif // SE1_D3D
// Vulkan ...
#ifdef SE1_VULKAN
else if (gl_eCurrentAPI == GAT_VK)
{
const PIX pixMinSI = pdpToLock->dp_ScissorMinI;
const PIX pixMaxSI = pdpToLock->dp_ScissorMaxI;
const PIX pixMinSJ = pdpToLock->dp_ScissorMinJ;
const PIX pixMaxSJ = pdpToLock->dp_ScissorMaxJ;
SetViewport_Vulkan(pixMinSI, pixMinSJ, pixMaxSI - pixMinSI + 1, pixMaxSJ - pixMinSJ + 1, 0, 1);
}
#endif // SE1_VULKAN
// mark and set default projection
GFX_ulLastDrawPortID = ulThisDrawPortID;
pdpToLock->SetOrtho();
return TRUE;
}
// Unlock a drawport after drawing
void CGfxLibrary::UnlockDrawPort( CDrawPort *pdpToUnlock)
{
// check API
#ifdef SE1_D3D
ASSERT(gl_eCurrentAPI == GAT_OGL || gl_eCurrentAPI == GAT_D3D || gl_eCurrentAPI == GAT_NONE);
#else // SE1_D3D
#ifdef SE1_VULKAN
ASSERT(gl_eCurrentAPI == GAT_OGL || gl_eCurrentAPI == GAT_VK || gl_eCurrentAPI == GAT_NONE);
#else
ASSERT(gl_eCurrentAPI == GAT_OGL || gl_eCurrentAPI == GAT_NONE);
#endif // SE1_VULKAN
#endif // SE1_D3D
// eventually signalize that scene rendering has ended
}
/////////////////////////////////////////////////////////////////////
// Window canvas functions
/* Create a new window canvas. */
void CGfxLibrary::CreateWindowCanvas(void *hWnd, CViewPort **ppvpNew, CDrawPort **ppdpNew)
{
RECT rectWindow; // rectangle for the client area of the window
// get the dimensions from the window
GetClientRect( (HWND)hWnd, &rectWindow);
PIX pixWidth = rectWindow.right - rectWindow.left;
PIX pixHeight = rectWindow.bottom - rectWindow.top;
*ppvpNew = NULL;
*ppdpNew = NULL;
// create a new viewport
if (*ppvpNew = new CViewPort( pixWidth, pixHeight, (HWND)hWnd)) {
// and it's drawport
*ppdpNew = &(*ppvpNew)->vp_Raster.ra_MainDrawPort;
} else {
delete *ppvpNew;
*ppvpNew = NULL;
}
}
/* Destroy a window canvas. */
void CGfxLibrary::DestroyWindowCanvas(CViewPort *pvpOld) {
// delete the viewport
delete pvpOld;
}
/////////////////////////////////////////////////////////////////////
// Work canvas functions
#define WorkCanvasCLASS "WorkCanvas Window"
static BOOL _bClassRegistered = FALSE;
/* Create a work canvas. */
void CGfxLibrary::CreateWorkCanvas(PIX pixWidth, PIX pixHeight, CDrawPort **ppdpNew)
{
// must have dimensions
ASSERT (pixWidth>0 || pixHeight>0);
if (!_bClassRegistered) {
_bClassRegistered = TRUE;
WNDCLASSA wc;
// must have owndc for opengl and dblclks to give to parent
wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS;
wc.lpfnWndProc = DefWindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = NULL;
wc.hIcon = NULL;
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = WorkCanvasCLASS;
RegisterClassA(&wc);
}
// create a window
HWND hWnd = ::CreateWindowExA(
0,
WorkCanvasCLASS,
"", // title
WS_CLIPCHILDREN|WS_CLIPSIBLINGS|WS_POPUP,
0,0,
pixWidth, pixHeight, // window size
NULL,
NULL,
NULL, //hInstance,
NULL);
ASSERT(hWnd != NULL);
*ppdpNew = NULL;
CViewPort *pvp;
CreateWindowCanvas(hWnd, &pvp, ppdpNew);
}
/* Destroy a work canvas. */
void CGfxLibrary::DestroyWorkCanvas(CDrawPort *pdpOld)
{
CViewPort *pvp = pdpOld->dp_Raster->ra_pvpViewPort;
HWND hwnd = pvp->vp_hWndParent;
DestroyWindowCanvas(pvp);
::DestroyWindow(hwnd);
}
// optimize memory used by cached shadow maps
#define SHADOWMAXBYTES (256*256*4*4/3)
static SLONG slCachedShadowMemory=0, slDynamicShadowMemory=0;
static INDEX ctCachedShadows=0, ctFlatShadows=0, ctDynamicShadows=0;
extern BOOL _bShadowsUpdated = TRUE;
void CGfxLibrary::ReduceShadows(void)
{
_sfStats.StartTimer( CStatForm::STI_SHADOWUPDATE);
// clamp shadow caching variables
shd_fCacheSize = Clamp( shd_fCacheSize, 0.1f, 128.0f);
shd_tmFlushDelay = Clamp( shd_tmFlushDelay, 0.1f, 120.0f);
CTimerValue tvNow = _pTimer->GetHighPrecisionTimer(); // readout current time
const TIME tmAcientDelay = Clamp( shd_tmFlushDelay*3, 60.0f, 300.0f);
// determine cached shadowmaps stats (if needed)
if( _bShadowsUpdated)
{
_bShadowsUpdated = FALSE;
slCachedShadowMemory=0; slDynamicShadowMemory=0;
ctCachedShadows=0; ctFlatShadows=0; ctDynamicShadows=0;
{FORDELETELIST( CShadowMap, sm_lnInGfx, _pGfx->gl_lhCachedShadows, itsm) {
CShadowMap &sm = *itsm;
ASSERT( sm.sm_pulCachedShadowMap!=NULL); // must be cached
ASSERT( sm.sm_slMemoryUsed>0 && sm.sm_slMemoryUsed<=SHADOWMAXBYTES); // and have valid size
// remove acient shadowmaps from list (if allowed)
const TIME tmDelta = (tvNow-sm.sm_tvLastDrawn).GetSeconds();
if( tmDelta>tmAcientDelay && !(sm.sm_ulFlags&SMF_PROBED) && !shd_bCacheAll) {
sm.Uncache();
continue;
}
// determine type and occupied space
const BOOL bDynamic = sm.sm_pulDynamicShadowMap!=NULL;
const BOOL bFlat = sm.sm_pulCachedShadowMap==&sm.sm_colFlat;
if( bDynamic) { slDynamicShadowMemory += sm.sm_slMemoryUsed; ctDynamicShadows++; }
if( !bFlat) { slCachedShadowMemory += sm.sm_slMemoryUsed; ctCachedShadows++; }
else { slCachedShadowMemory += sizeof(sm.sm_colFlat); ctFlatShadows++; }
}}
}
// update statistics counters
_pfGfxProfile.IncrementCounter(CGfxProfile::PCI_CACHEDSHADOWBYTES, slCachedShadowMemory);
_pfGfxProfile.IncrementCounter(CGfxProfile::PCI_CACHEDSHADOWS, ctCachedShadows);
_pfGfxProfile.IncrementCounter(CGfxProfile::PCI_FLATSHADOWS, ctFlatShadows);
_pfGfxProfile.IncrementCounter(CGfxProfile::PCI_DYNAMICSHADOWBYTES, slDynamicShadowMemory);
_pfGfxProfile.IncrementCounter(CGfxProfile::PCI_DYNAMICSHADOWS, ctDynamicShadows);
_sfStats.IncrementCounter( CStatForm::SCI_CACHEDSHADOWBYTES, slCachedShadowMemory);
_sfStats.IncrementCounter( CStatForm::SCI_CACHEDSHADOWS, ctCachedShadows);
_sfStats.IncrementCounter( CStatForm::SCI_FLATSHADOWS, ctFlatShadows);
_sfStats.IncrementCounter( CStatForm::SCI_DYNAMICSHADOWBYTES, slDynamicShadowMemory);
_sfStats.IncrementCounter( CStatForm::SCI_DYNAMICSHADOWS, ctDynamicShadows);
// done if reducing is not allowed
if( shd_bCacheAll) {
_sfStats.StopTimer( CStatForm::STI_SHADOWUPDATE);
return;
}
// optimize only if low on memory
ULONG ulShadowCacheSize = (ULONG)(shd_fCacheSize*1024*1024); // in bytes
ULONG ulUsedShadowMemory = slCachedShadowMemory + slDynamicShadowMemory;
if( ulUsedShadowMemory <= ulShadowCacheSize) {
_sfStats.StopTimer( CStatForm::STI_SHADOWUPDATE);
return;
}
// reduce shadow delay if needed
// (lineary from specified value to 2sec for cachedsize>specsize to cachedsize>2*specsize)
TIME tmFlushDelay = shd_tmFlushDelay;
if( tmFlushDelay>2.0f) {
FLOAT fRatio = (FLOAT)ulUsedShadowMemory / ulShadowCacheSize;
ASSERT( fRatio>=1.0f);
fRatio = ClampUp( fRatio/2.0f, 1.0f);
tmFlushDelay = Lerp( tmFlushDelay, 2.0f, fRatio);
}
// loop thru cached shadowmaps list
{FORDELETELIST( CShadowMap, sm_lnInGfx, _pGfx->gl_lhCachedShadows, itsm)
{ // stop iteration if current shadow map it is not too old (list is sorted by time)
// or we have enough memory for cached shadows that remain
CShadowMap &sm = *itsm;
const TIME tmDelta = (tvNow-sm.sm_tvLastDrawn).GetSeconds();
if( tmDelta<tmFlushDelay || ulUsedShadowMemory<ulShadowCacheSize) break;
// uncache shadow (this returns ammount of memory that has been freed)
ulUsedShadowMemory -= sm.Uncache();
ASSERT( ulUsedShadowMemory>=0);
}}
// done
_sfStats.StopTimer( CStatForm::STI_SHADOWUPDATE);
}
// some vars for probing
extern INDEX _ctProbeTexs = 0;
extern INDEX _ctProbeShdU = 0;
extern INDEX _ctProbeShdB = 0;
extern INDEX _ctFullShdU = 0;
extern SLONG _slFullShdUBytes = 0;
static BOOL GenerateGammaTable(void);
/*
* Swap buffers in a viewport.
*/
void CGfxLibrary::SwapBuffers(CViewPort *pvp)
{
// check API
#ifdef SE1_D3D
ASSERT(gl_eCurrentAPI == GAT_OGL || gl_eCurrentAPI == GAT_D3D || gl_eCurrentAPI == GAT_NONE);
#else // SE1_D3D
#ifdef SE1_VULKAN
ASSERT(gl_eCurrentAPI == GAT_OGL || gl_eCurrentAPI == GAT_VK || gl_eCurrentAPI == GAT_NONE);
#else
ASSERT(gl_eCurrentAPI == GAT_OGL || gl_eCurrentAPI == GAT_NONE);
#endif // SE1_VULKAN
#endif // SE1_D3D
// safety check
ASSERT( gl_pvpActive!=NULL);
if( pvp!=gl_pvpActive) {
ASSERTALWAYS( "Swapping viewport that was not last drawn to!");
return;
}
// optimize memory used by cached shadow maps and update shadowmap counters
ReduceShadows();
// check and eventually adjust texture filtering and LOD biasing
gfxSetTextureFiltering( gap_iTextureFiltering, gap_iTextureAnisotropy);
gfxSetTextureBiasing( gap_fTextureLODBias);
// clamp some cvars
gap_iDithering = Clamp( gap_iDithering, 0L, 2L);
gap_iSwapInterval = Clamp( gap_iSwapInterval, 0L, 4L);
gap_iOptimizeClipping = Clamp( gap_iOptimizeClipping, 0L, 2L);
gap_iTruformLevel = Clamp( gap_iTruformLevel, 0L, _pGfx->gl_iMaxTessellationLevel);
ogl_iFinish = Clamp( ogl_iFinish, 0L, 3L);
d3d_iFinish = Clamp( d3d_iFinish, 0L, 3L);
// OpenGL
if( gl_eCurrentAPI==GAT_OGL)
{
// force finishing of all rendering operations (if required)
if( ogl_iFinish==2) gfxFinish();
// check state of swap interval extension usage
if( gl_ulFlags & GLF_VSYNC) {
if( gl_iSwapInterval != gap_iSwapInterval) {
gl_iSwapInterval = gap_iSwapInterval;
pwglSwapIntervalEXT( gl_iSwapInterval);
}
}
// swap buffers
CTempDC tdc(pvp->vp_hWnd);
pwglSwapBuffers(tdc.hdc);
// force finishing of all rendering operations (if required)
if( ogl_iFinish==3) gfxFinish();
// reset CVA usage if ext is not present
if( !(gl_ulFlags&GLF_EXT_COMPILEDVERTEXARRAY)) ogl_bUseCompiledVertexArrays = 0;
}
// Direct3D
#ifdef SE1_D3D
else if( gl_eCurrentAPI==GAT_D3D)
{
// force finishing of all rendering operations (if required)
if( d3d_iFinish==2) gfxFinish();
// end scene rendering
HRESULT hr;
if( GFX_bRenderingScene) {
hr = gl_pd3dDevice->EndScene();
D3D_CHECKERROR(hr);
}
CDisplayMode dm;
GetCurrentDisplayMode(dm);
ASSERT( (dm.dm_pixSizeI==0 && dm.dm_pixSizeJ==0) || (dm.dm_pixSizeI!=0 && dm.dm_pixSizeJ!=0));
if( dm.dm_pixSizeI==0 || dm.dm_pixSizeJ==0 ) {
// windowed mode
hr = pvp->vp_pSwapChain->Present( NULL, NULL, NULL, NULL);
} else {
// full screen mode
hr = gl_pd3dDevice->Present( NULL, NULL, NULL, NULL);
} // done swapping
D3D_CHECKERROR(hr);
// force finishing of all rendering operations (if required)
if( d3d_iFinish==3) gfxFinish();
// eventually reset vertex buffer if something got changed
if( _iLastVertexBufferSize!=d3d_iVertexBuffersSize
|| (gl_iTessellationLevel<1 && gap_iTruformLevel>0)
|| (gl_iTessellationLevel>0 && gap_iTruformLevel<1)) {
extern void SetupVertexArrays_D3D( INDEX ctVertices);
extern void SetupIndexArray_D3D( INDEX ctVertices);
extern DWORD SetupShader_D3D( ULONG ulStreamsMask);
SetupShader_D3D(NONE);
SetupVertexArrays_D3D(0);
SetupIndexArray_D3D(0);
extern INDEX VerticesFromSize_D3D( SLONG &slSize);
const INDEX ctVertices = VerticesFromSize_D3D(d3d_iVertexBuffersSize);
SetupVertexArrays_D3D(ctVertices);
SetupIndexArray_D3D(2*ctVertices);
_iLastVertexBufferSize = d3d_iVertexBuffersSize;
}
}
#endif // SE1_D3D
// Vulkan
#ifdef SE1_VULKAN
else if (gl_eCurrentAPI == GAT_VK)
{
// force finishing of all rendering operations (if required)
//if (vk_iFinish == 2) gfxFinish();
// end recording to cmd buffers
if (GFX_bRenderingScene)
{
gl_SvkMain->EndFrame();
}
SwapBuffers_Vulkan();
// force finishing of all rendering operations (if required)
//if (vk_iFinish == 3) gfxFinish();
}
#endif // SE1_VK
// update tessellation level
gl_iTessellationLevel = gap_iTruformLevel;
// must reset drawport and rendering status for subsequent locks
GFX_ulLastDrawPortID = 0;
GFX_bRenderingScene = FALSE;
// reset frustum/ortho matrix, too
extern BOOL GFX_bViewMatrix;
extern FLOAT GFX_fLastL, GFX_fLastR, GFX_fLastT, GFX_fLastB, GFX_fLastN, GFX_fLastF;
GFX_fLastL = GFX_fLastR = GFX_fLastT = GFX_fLastB = GFX_fLastN = GFX_fLastF = 0;
GFX_bViewMatrix = TRUE;
// set maximum allowed upload ammount
gfx_iProbeSize = Clamp( gfx_iProbeSize, 1L, 16384L);
gl_slAllowedUploadBurst = gfx_iProbeSize *1024;
_ctProbeTexs = 0;
_ctProbeShdU = 0;
_ctProbeShdB = 0;
_ctFullShdU = 0;
_slFullShdUBytes = 0;
// keep time when swap buffer occured and maintain counter of frames for temporal coherence checking
gl_tvFrameTime = _pTimer->GetHighPrecisionTimer();
gl_iFrameNumber++;
// reset profiling counters
gl_ctWorldTriangles = 0;
gl_ctModelTriangles = 0;
gl_ctParticleTriangles = 0;
gl_ctTotalTriangles = 0;
// re-adjust multi-texturing support
gap_iUseTextureUnits = Clamp( gap_iUseTextureUnits, 1L, _pGfx->gl_ctTextureUnits);
ASSERT( gap_iUseTextureUnits>=1 && gap_iUseTextureUnits<=GFX_MAXTEXUNITS);
// re-get usage of compiled vertex arrays
CVA_b2D = ogl_bUseCompiledVertexArrays /100;
CVA_bWorld = ogl_bUseCompiledVertexArrays /10 %10;
CVA_bModels = ogl_bUseCompiledVertexArrays %10;
ogl_bUseCompiledVertexArrays = 0;
if( CVA_b2D) ogl_bUseCompiledVertexArrays += 100;
if( CVA_bWorld) ogl_bUseCompiledVertexArrays += 10;
if( CVA_bModels) ogl_bUseCompiledVertexArrays += 1;
// eventually advance to next sample buffer
if( (gl_ulFlags&GLF_EXT_TBUFFER) && go_ctSampleBuffers>1) {
go_iCurrentWriteBuffer--;
if( go_iCurrentWriteBuffer<0) go_iCurrentWriteBuffer = go_ctSampleBuffers-1;
pglDisable( GL_MULTISAMPLE_3DFX);
}
// clear viewport if needed
if( gfx_bClearScreen) pvp->vp_Raster.ra_MainDrawPort.Fill( C_BLACK|CT_OPAQUE);
//pvp->vp_Raster.ra_MainDrawPort.FillZBuffer(ZBUF_BACK);
// adjust gamma table if supported ...
if( gl_ulFlags & GLF_ADJUSTABLEGAMMA) {
// ... and required
const BOOL bTableSet = GenerateGammaTable();
if( bTableSet) {
if( gl_eCurrentAPI==GAT_OGL) {
CTempDC tdc(pvp->vp_hWnd);
SetDeviceGammaRamp( tdc.hdc, &_auwGammaTable[0]);
}
#ifdef SE1_D3D
else if( gl_eCurrentAPI==GAT_D3D) {
gl_pd3dDevice->SetGammaRamp( D3DSGR_NO_CALIBRATION, (D3DGAMMARAMP*)&_auwGammaTable[0]);
}
#endif // SE1_D3D
#ifdef SE1_VULKAN
else if (gl_eCurrentAPI == GAT_VK)
{
CPrintF("Vulkan: Gamma adjustment is not available now.\n");
}
#endif // SE1_VULKAN
}
}
// if not supported
else {
// just reset settings to default
gfx_fBrightness = 0;
gfx_fContrast = 1;
gfx_fGamma = 1;
gfx_fBiasR = 1;
gfx_fBiasG = 1;
gfx_fBiasB = 1;
gfx_iLevels = 256;
}
}
// get array of all supported display modes
CDisplayMode *CGfxLibrary::EnumDisplayModes( INDEX &ctModes, enum GfxAPIType eAPI/*=GAT_CURRENT*/, INDEX iAdapter/*=0*/)
{
if( eAPI==GAT_CURRENT) eAPI = gl_eCurrentAPI;
if( iAdapter==0) iAdapter = gl_iCurrentAdapter;
CDisplayAdapter *pda = &gl_gaAPI[eAPI].ga_adaAdapter[iAdapter];
ctModes = pda->da_ctDisplayModes;
return &pda->da_admDisplayModes[0];
}
// Lock a raster for drawing.
BOOL CGfxLibrary::LockRaster( CRaster *praToLock)
{
// don't do this! it can break sync consistency in entities!
// SetFPUPrecision(FPT_24BIT);
ASSERT( praToLock->ra_pvpViewPort!=NULL);
BOOL bRes = SetCurrentViewport( praToLock->ra_pvpViewPort);
if( bRes) {
// must signal to picky Direct3D
#ifdef SE1_D3D
if( gl_eCurrentAPI==GAT_D3D && !GFX_bRenderingScene) {
HRESULT hr = gl_pd3dDevice->BeginScene();
D3D_CHECKERROR(hr);
bRes = (hr==D3D_OK);
} // mark it
#endif // SE1_D3D
#ifdef SE1_VULKAN
if (gl_eCurrentAPI == GAT_VK && !GFX_bRenderingScene)
{
gl_SvkMain->StartFrame();
}
#endif // SE1_VULKAN
GFX_bRenderingScene = TRUE;
} // done
return bRes;
}
// Unlock a raster after drawing.
void CGfxLibrary::UnlockRaster( CRaster *praToUnlock)
{
// don't do this! it can break sync consistency in entities!
// SetFPUPrecision(FPT_53BIT);
ASSERT( GFX_bRenderingScene);
}
// generates gamma table and returns true if gamma table has been changed
static BOOL GenerateGammaTable(void)
{
// only if needed
if( _fLastBrightness == gfx_fBrightness
&& _fLastContrast == gfx_fContrast
&& _fLastGamma == gfx_fGamma
&& _iLastLevels == gfx_iLevels
&& _fLastBiasR == gfx_fBiasR
&& _fLastBiasG == gfx_fBiasG
&& _fLastBiasB == gfx_fBiasB) return FALSE;
// guess it's needed
INDEX i;
gfx_fBrightness = Clamp( gfx_fBrightness, -0.8f, 0.8f);
gfx_fContrast = Clamp( gfx_fContrast, 0.2f, 4.0f);
gfx_fGamma = Clamp( gfx_fGamma, 0.2f, 4.0f);
gfx_iLevels = Clamp( gfx_iLevels, 2L, 256L);
gfx_fBiasR = Clamp( gfx_fBiasR, 0.0f, 2.0f);
gfx_fBiasG = Clamp( gfx_fBiasG, 0.0f, 2.0f);
gfx_fBiasB = Clamp( gfx_fBiasB, 0.0f, 2.0f);
_fLastBrightness = gfx_fBrightness;
_fLastContrast = gfx_fContrast;
_fLastGamma = gfx_fGamma;
_iLastLevels = gfx_iLevels;
_fLastBiasR = gfx_fBiasR;
_fLastBiasG = gfx_fBiasG;
_fLastBiasB = gfx_fBiasB;
// fill and adjust gamma
const FLOAT f1oGamma = 1.0f / gfx_fGamma;
for( i=0; i<256; i++) {
FLOAT fVal = i/255.0f;
fVal = Clamp( (FLOAT)pow(fVal,f1oGamma), 0.0f, 1.0f);
_auwGammaTable[i] = (UWORD)(fVal*65280);
}
// adjust contrast
for( i=0; i<256; i++) {
FLOAT fVal = _auwGammaTable[i]/65280.0f;
fVal = Clamp( (fVal-0.5f)*gfx_fContrast +0.5f, 0.0f, 1.0f);
_auwGammaTable[i] = (UWORD)(fVal*65280);
}
// adjust brightness
INDEX iAdd = 256* 256*gfx_fBrightness;
for( i=0; i<256; i++) {
_auwGammaTable[i] = Clamp( _auwGammaTable[i]+iAdd, 0L, 65280L);
}
// adjust levels (posterize)
if( gfx_iLevels<256) {
const FLOAT fLevels = 256 * 256.0f/gfx_iLevels;
for( i=0; i<256; i++) {
INDEX iVal = _auwGammaTable[i];
iVal = ((INDEX)(iVal/fLevels)) *fLevels;
_auwGammaTable[i] = ClampUp( iVal, 0xFF00L);
}
}
// copy R to G and B array
for( i=0; i<256; i++) {
FLOAT fR,fG,fB;
fR=fG=fB = _auwGammaTable[i]/65280.0f;
fR = Clamp( fR*gfx_fBiasR, 0.0f, 1.0f);
fG = Clamp( fG*gfx_fBiasG, 0.0f, 1.0f);
fB = Clamp( fB*gfx_fBiasB, 0.0f, 1.0f);
_auwGammaTable[i+0] = (UWORD)(fR*65280);
_auwGammaTable[i+256] = (UWORD)(fG*65280);
_auwGammaTable[i+512] = (UWORD)(fB*65280);
}
// done
return TRUE;
}
#if 0
DeclareSymbol( "[persistent] [hidden] [const] [type] name [minval] [maxval] [func()]", &shd_iStaticQuality, func()=NULL);
_pShell->DeclareSymbol( "INDEX GfxVarPreFunc(INDEX);", &GfxVarPreFunc);
_pShell->DeclareSymbol( "void GfxVarPostFunc(INDEX);", &GfxVarPostFunc);
static BOOL GfxVarPreFunc(void *pvVar)
{
if (pvVar==&gfx_fSaturation) {
CPrintF("cannot change saturation: just for test\n");
return FALSE;
} else {
CPrintF("gfx var about to be changed\n");
return TRUE;
}
}
static void GfxVarPostFunc(void *pvVar)
{
if (pvVar==&shd_bFineQuality) {
CPrintF("This requires RefreshTextures() to take effect!\n");
}
}
#endif
| 81,800
|
C++
|
.cpp
| 1,870
| 40.186096
| 153
| 0.707281
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,536,196
|
DrawPort_RenderScene.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/DrawPort_RenderScene.cpp
|
/* Copyright (c) 2002-2012 Croteam Ltd.
Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "stdh.h"
#include <Engine/Graphics/DrawPort.h>
#include <Engine/Base/Statistics_internal.h>
#include <Engine/Base/Console.h>
#include <Engine/Math/Projection.h>
#include <Engine/Graphics/RenderScene.h>
#include <Engine/Graphics/Texture.h>
#include <Engine/Graphics/GfxLibrary.h>
#include <Engine/Graphics/GfxProfile.h>
#include <Engine/Graphics/ShadowMap.h>
#include <Engine/Graphics/Fog_internal.h>
#include <Engine/Brushes/Brush.h>
#include <Engine/Brushes/BrushTransformed.h>
#include <Engine/Templates/StaticStackArray.cpp>
// asm shortcuts
#define O offset
#define Q qword ptr
#define D dword ptr
#define W word ptr
#define B byte ptr
#define ASMOPT 1
#define MAXTEXUNITS 4
#define SHADOWTEXTURE 3
extern INDEX wld_bShowTriangles;
extern INDEX wld_bShowDetailTextures;
extern INDEX wld_bRenderShadowMaps;
extern INDEX wld_bRenderTextures;
extern INDEX wld_bRenderDetailPolygons;
extern INDEX wld_iDetailRemovingBias;
extern INDEX wld_bAccurateColors;
extern INDEX gfx_bRenderWorld;
extern INDEX shd_iForceFlats;
extern INDEX shd_bShowFlats;
extern BOOL _bMultiPlayer;
extern BOOL CVA_bWorld;
static GfxAPIType eAPI;
// vertex coordinates and elements used by one pass of polygons
static CStaticStackArray<GFXVertex> _avtxPass;
static CStaticStackArray<GFXTexCoord> _atexPass[MAXTEXUNITS];
static CStaticStackArray<GFXColor> _acolPass;
static CStaticStackArray<INDEX> _aiElements;
// general coordinate stack referenced by the scene polygons
CStaticStackArray<GFXVertex3> _avtxScene;
// group flags (single-texturing)
#define GF_TX0 (1L<<0)
#define GF_TX1 (1L<<1)
#define GF_TX2 (1L<<2)
#define GF_SHD (1L<<3)
#define GF_FLAT (1L<<4) // flat fill instead of texture 1
#define GF_TA1 (1L<<5) // texture 2 after shade
#define GF_TA2 (1L<<6) // texture 3 after shade
#define GF_FOG (1L<<7)
#define GF_HAZE (1L<<8)
#define GF_SEL (1L<<9)
#define GF_KEY (1L<<10) // first layer requires alpha-keying
// texture combinations for max 4 texture units (fog, haze and selection not included)
#define GF_TX0_TX1 (1L<<11)
#define GF_TX0_TX2 (1L<<12)
#define GF_TX0_SHD (1L<<13)
#define GF_TX2_SHD (1L<<14) // second pass
#define GF_TX0_TX1_TX2 (1L<<15)
#define GF_TX0_TX1_SHD (1L<<16)
#define GF_TX0_TX2_SHD (1L<<17)
#define GF_TX0_TX1_TX2_SHD (1L<<18)
// total number of groups
#define GROUPS_MAXCOUNT (1L<<11) // max group +1 !
#define GROUPS_MINCOUNT (1L<<4)-1 // min group !
static ScenePolygon *_apspoGroups[GROUPS_MAXCOUNT];
static INDEX _ctGroupsCount=0;
// some static vars
static FLOAT _fHazeMul, _fHazeAdd;
static FLOAT _fFogMul;
static COLOR _colSelection;
static INDEX _ctUsableTexUnits;
static BOOL _bTranslucentPass; // rendering translucent polygons
static ULONG _ulLastFlags[MAXTEXUNITS];
static ULONG _ulLastBlends[MAXTEXUNITS];
static INDEX _iLastFrameNo[MAXTEXUNITS];
static CTextureData *_ptdLastTex[MAXTEXUNITS];
static CDrawPort *_pDP;
static CPerspectiveProjection3D *_ppr = NULL;
// draw batched elements
static void FlushElements(void)
{
// skip if empty
const INDEX ctElements = _aiElements.Count();
if( ctElements<3) return;
// draw
const INDEX ctTris = ctElements/3;
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_DRAWELEMENTS);
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESOPT, ctTris);
_sfStats.IncrementCounter( CStatForm::SCI_SCENE_TRIANGLEPASSES, ctTris);
_pGfx->gl_ctWorldTriangles += ctTris;
gfxDrawElements( ctElements, &_aiElements[0]);
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_DRAWELEMENTS);
// reset
_aiElements.PopAll();
}
// batch elements of one polygon
static __forceinline void AddElements( ScenePolygon *pspo)
{
const INDEX ctElems = pspo->spo_ctElements;
INDEX *piDst = _aiElements.Push(ctElems);
#if ASMOPT == 1
__asm {
mov eax,D [pspo]
mov ecx,D [ctElems]
mov edi,D [piDst]
mov esi,D [eax]ScenePolygon.spo_piElements
mov ebx,D [eax]ScenePolygon.spo_iVtx0Pass
movd mm1,ebx
movq mm0,mm1
psllq mm1,32
por mm1,mm0
shr ecx,1
jz elemRest
elemLoop:
movq mm0,Q [esi]
paddd mm0,mm1
movq Q [edi],mm0
add esi,8
add edi,8
dec ecx
jnz elemLoop
elemRest:
emms
test [ctElems],1
jz elemDone
mov eax,D [esi]
add eax,ebx
mov D [edi],eax
elemDone:
}
#else
const INDEX iVtx0Pass = pspo->spo_iVtx0Pass;
const INDEX *piSrc = pspo->spo_piElements;
for( INDEX iElem=0; iElem<ctElems; iElem++) {
// make an element in per-pass arrays
piDst[iElem] = piSrc[iElem]+iVtx0Pass;
}
#endif
}
// draw all elements of one pass
static __forceinline void DrawAllElements( ScenePolygon *pspoFirst)
{
ASSERT( _aiElements.Count()==0);
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_DRAWELEMENTS);
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc) {
const INDEX ctTris = pspo->spo_ctElements/3;
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESOPT, ctTris);
_sfStats.IncrementCounter( CStatForm::SCI_SCENE_TRIANGLEPASSES, ctTris);
_pGfx->gl_ctWorldTriangles += ctTris;
AddElements(pspo);
}
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_DRAWELEMENTS);
}
// calculate mip factor for a texture and adjust its mapping vectors
static BOOL RSMakeMipFactorAndAdjustMapping( ScenePolygon *pspo, INDEX iLayer)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_MAKEMIPFACTOR);
BOOL bRemoved = FALSE;
MEX mexTexSizeU, mexTexSizeV;
CMappingVectors &mv = pspo->spo_amvMapping[iLayer];
// texture map ?
if( iLayer<SHADOWTEXTURE)
{
const ULONG ulBlend = pspo->spo_aubTextureFlags[iLayer] & STXF_BLEND_MASK;
CTextureData *ptd = (CTextureData*)pspo->spo_aptoTextures[iLayer]->GetData();
mexTexSizeU = ptd->GetWidth();
mexTexSizeV = ptd->GetHeight();
// check whether detail can be rejected (but don't reject colorized textures)
if( ulBlend==STXF_BLEND_SHADE && (ptd->td_ulFlags&TEX_EQUALIZED)
&& (pspo->spo_acolColors[iLayer]&0xFFFFFF00)==0xFFFFFF00)
{ // get nearest vertex Z distance from viewer and u and v steps
const FLOAT fZ = pspo->spo_fNearestZ;
const FLOAT f1oPZ1 = fZ / _ppr->ppr_PerspectiveRatios(1);
const FLOAT f1oPZ2 = fZ / _ppr->ppr_PerspectiveRatios(2);
const FLOAT fDUoDI = Abs( mv.mv_vU(1) *f1oPZ1);
const FLOAT fDUoDJ = Abs( mv.mv_vU(2) *f1oPZ2);
const FLOAT fDVoDI = Abs( mv.mv_vV(1) *f1oPZ1);
const FLOAT fDVoDJ = Abs( mv.mv_vV(2) *f1oPZ2);
// find mip factor and adjust removing of texture layer
const FLOAT fMaxDoD = Max( Max(fDUoDI,fDUoDJ), Max(fDVoDI,fDVoDJ));
const INDEX iMipFactor = wld_iDetailRemovingBias + (((SLONG&)fMaxDoD)>>23) -127 +10;
const INDEX iLastMip = ptd->td_iFirstMipLevel + ptd->GetNoOfMips() -1; // determine last mipmap in texture
bRemoved = (iMipFactor>=iLastMip);
// check for detail texture showing
extern INDEX wld_bShowDetailTextures;
if( wld_bShowDetailTextures) {
if( iLayer==2) pspo->spo_acolColors[iLayer] = C_MAGENTA|255;
else pspo->spo_acolColors[iLayer] = C_CYAN |255;
}
}
// check if texture has been blended with low alpha
else bRemoved = (ulBlend==STXF_BLEND_ALPHA) && ((pspo->spo_acolColors[iLayer]&CT_AMASK)>>CT_ASHIFT)<3;
}
// shadow map
else
{
mexTexSizeU = pspo->spo_psmShadowMap->sm_mexWidth;
mexTexSizeV = pspo->spo_psmShadowMap->sm_mexHeight;
}
// adjust texture gradients
if( mexTexSizeU!=1024) {
const FLOAT fMul = 1024.0f /mexTexSizeU; // (no need to do shift-opt, because it won't speed up much!)
mv.mv_vU(1) *=fMul; mv.mv_vU(2) *=fMul; mv.mv_vU(3) *=fMul;
}
if( mexTexSizeV!=1024) {
const FLOAT fMul = 1024.0f /mexTexSizeV;
mv.mv_vV(1) *=fMul; mv.mv_vV(2) *=fMul; mv.mv_vV(3) *=fMul;
}
// all done
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_MAKEMIPFACTOR);
return bRemoved;
}
// Remove all polygons with no triangles from a list
static void RSRemoveDummyPolygons( ScenePolygon *pspoAll, ScenePolygon **ppspoNonDummy)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_REMOVEDUMMY);
*ppspoNonDummy = NULL;
// for all span polygons in list (remember one ahead to be able to reconnect them)
ScenePolygon *pspoNext;
for( ScenePolygon *pspoThis=pspoAll; pspoThis!=NULL; pspoThis=pspoNext) {
pspoNext = pspoThis->spo_pspoSucc;
// if the polygon has some triangles
if( pspoThis->spo_ctElements >0) {
// move it to the other list
pspoThis->spo_pspoSucc = *ppspoNonDummy;
*ppspoNonDummy = pspoThis;
}
}
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_REMOVEDUMMY);
}
// bin polygons into groups
static void RSBinToGroups( ScenePolygon *pspoFirst)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_BINTOGROUPS);
// clamp texture layers
extern INDEX wld_bTextureLayers;
BOOL bTextureLayer1 =(wld_bTextureLayers /100) || _bMultiPlayer; // must be enabled in multiplayer mode!
BOOL bTextureLayer2 = wld_bTextureLayers /10 %10;
BOOL bTextureLayer3 = wld_bTextureLayers %10;
wld_bTextureLayers = 0;
if( bTextureLayer1) wld_bTextureLayers += 100;
if( bTextureLayer2) wld_bTextureLayers += 10;
if( bTextureLayer3) wld_bTextureLayers += 1;
// cache rendering states
bTextureLayer1 = bTextureLayer1 && wld_bRenderTextures;
bTextureLayer2 = bTextureLayer2 && wld_bRenderTextures;
bTextureLayer3 = bTextureLayer3 && wld_bRenderTextures;
// clear all groups initially
memset( _apspoGroups, 0, sizeof(_apspoGroups));
_ctGroupsCount = GROUPS_MINCOUNT;
// for all span polygons in list (remember one ahead to be able to reconnect them)
for( ScenePolygon *pspoNext, *pspo=pspoFirst; pspo!=NULL; pspo=pspoNext)
{
pspoNext = pspo->spo_pspoSucc;
const INDEX ctTris = pspo->spo_ctElements/3;
ULONG ulBits = NONE;
// if it has texture 1 active
if( pspo->spo_aptoTextures[0]!=NULL && bTextureLayer1) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESORG, ctTris);
// prepare mapping for texture 0 and generate its mip factor
const BOOL bRemoved = RSMakeMipFactorAndAdjustMapping( pspo, 0);
if( !bRemoved) ulBits |= GF_TX0; // add if not removed
} else {
// flat fill is mutually exclusive with texture layer0
_ctGroupsCount |= GF_FLAT;
ulBits |= GF_FLAT;
}
// if it has texture 2 active
if( pspo->spo_aptoTextures[1]!=NULL && bTextureLayer2) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESORG, ctTris);
// prepare mapping for texture 1 and generate its mip factor
const BOOL bRemoved = RSMakeMipFactorAndAdjustMapping( pspo, 1);
if( !bRemoved) { // add if not removed
if( pspo->spo_aubTextureFlags[1] & STXF_AFTERSHADOW) {
_ctGroupsCount |= GF_TA1;
ulBits |= GF_TA1;
} else {
ulBits |= GF_TX1;
}
}
}
// if it has texture 3 active
if( pspo->spo_aptoTextures[2]!=NULL && bTextureLayer3) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESORG, ctTris);
// prepare mapping for texture 2 and generate its mip factor
const BOOL bRemoved = RSMakeMipFactorAndAdjustMapping( pspo, 2);
if( !bRemoved) { // add if not removed
if( pspo->spo_aubTextureFlags[2] & STXF_AFTERSHADOW) {
_ctGroupsCount |= GF_TA2;
ulBits |= GF_TA2;
} else {
ulBits |= GF_TX2;
}
}
}
// if it has shadowmap active
if( pspo->spo_psmShadowMap!=NULL && wld_bRenderShadowMaps) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESORG, ctTris);
// prepare shadow map
CShadowMap *psmShadow = pspo->spo_psmShadowMap;
psmShadow->Prepare();
const BOOL bFlat = psmShadow->IsFlat();
COLOR colFlat = psmShadow->sm_colFlat & 0xFFFFFF00;
const BOOL bOverbright = (colFlat & 0x80808000);
// only need to update poly color if shadowmap is flat
if( bFlat) {
if( !bOverbright || shd_iForceFlats==1) {
if( shd_bShowFlats) colFlat = C_mdMAGENTA; // show flat shadows?
else { // enhance light color to emulate overbrighting
if( !bOverbright) colFlat<<=1;
else {
UBYTE ubR,ubG,ubB;
ColorToRGB( colFlat, ubR,ubG,ubB);
ULONG ulR = ClampUp( ((ULONG)ubR)<<1, 255UL);
ULONG ulG = ClampUp( ((ULONG)ubG)<<1, 255UL);
ULONG ulB = ClampUp( ((ULONG)ubB)<<1, 255UL);
colFlat = RGBToColor(ulR,ulG,ulB);
}
} // mix color in the first texture layer
COLOR &colTotal = pspo->spo_acolColors[0];
COLOR colLayer = pspo->spo_acolColors[3];
if( colTotal==0xFFFFFFFF) colTotal = colLayer;
else if( colLayer!=0xFFFFFFFF) colTotal = MulColors( colTotal, colLayer);
if( colTotal==0xFFFFFFFF) colTotal = colFlat;
else colTotal = MulColors( colTotal, colFlat);
psmShadow->MarkDrawn();
}
else {
// need to update poly color if shadowmap is flat and overbrightened
COLOR &colTotal = pspo->spo_acolColors[3];
if( shd_bShowFlats) colFlat = C_mdBLUE; // overbrightened!
if( colTotal==0xFFFFFFFF) colTotal = colFlat;
else colTotal = MulColors( colTotal, colFlat);
ulBits |= GF_SHD; // mark the need for shadow layer
}
} else {
// prepare mapping for shadowmap and generate its mip factor
RSMakeMipFactorAndAdjustMapping( pspo, SHADOWTEXTURE);
ulBits |= GF_SHD;
}
}
// if it has fog active
if( pspo->spo_ulFlags&SPOF_RENDERFOG) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESORG, ctTris);
_ctGroupsCount |= GF_FOG;
ulBits |= GF_FOG;
}
// if it has haze active
if( pspo->spo_ulFlags&SPOF_RENDERHAZE) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESORG, ctTris);
_ctGroupsCount |= GF_HAZE;
ulBits |= GF_HAZE;
}
// if it is selected
if( pspo->spo_ulFlags&SPOF_SELECTED) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESORG, ctTris);
_ctGroupsCount |= GF_SEL;
ulBits |= GF_SEL;
}
// if it is transparent
if( pspo->spo_ulFlags&SPOF_TRANSPARENT) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLEPASSESORG, ctTris);
_ctGroupsCount |= GF_KEY;
ulBits |= GF_KEY;
}
// in case of at least one layer, add it to proper group
if( ulBits) {
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_TRIANGLES, ctTris);
pspo->spo_pspoSucc = _apspoGroups[ulBits];
_apspoGroups[ulBits] = pspo;
}
}
// determine maximum used groups
ASSERT( _ctGroupsCount);
__asm {
mov eax,2
bsr ecx,D [_ctGroupsCount]
shl eax,cl
mov D [_ctGroupsCount],eax
}
// done with bining
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_BINTOGROUPS);
}
// bin polygons that can use dual-texturing
static void RSBinByDualTexturing( ScenePolygon *pspoGroup, INDEX iLayer1, INDEX iLayer2,
ScenePolygon **ppspoST, ScenePolygon **ppspoMT)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_BINBYMULTITEXTURING);
*ppspoST = NULL;
*ppspoMT = NULL;
// for all span polygons in list (remember one ahead to be able to reconnect them)
for( ScenePolygon *pspoNext, *pspo=pspoGroup; pspo!=NULL; pspo=pspoNext)
{
pspoNext = pspo->spo_pspoSucc;
// if first texture is opaque or shade and second layer is shade
if( ((pspo->spo_aubTextureFlags[iLayer1]&STXF_BLEND_MASK)==STXF_BLEND_OPAQUE
|| (pspo->spo_aubTextureFlags[iLayer1]&STXF_BLEND_MASK)==STXF_BLEND_SHADE)
&& (pspo->spo_aubTextureFlags[iLayer2]&STXF_BLEND_MASK)==STXF_BLEND_SHADE) {
// can be merged, so put to multi-texture
pspo->spo_pspoSucc = *ppspoMT;
*ppspoMT = pspo;
} else {
// cannot be merged, so put to single-texture
pspo->spo_pspoSucc = *ppspoST;
*ppspoST = pspo;
}
}
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_BINBYMULTITEXTURING);
}
// bin polygons that can use triple-texturing
static void RSBinByTripleTexturing( ScenePolygon *pspoGroup, INDEX iLayer2, INDEX iLayer3,
ScenePolygon **ppspoST, ScenePolygon **ppspoMT)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_BINBYMULTITEXTURING);
*ppspoST = NULL;
*ppspoMT = NULL;
// for all span polygons in list (remember one ahead to be able to reconnect them)
for( ScenePolygon *pspoNext, *pspo=pspoGroup; pspo!=NULL; pspo=pspoNext)
{
pspoNext = pspo->spo_pspoSucc;
// if texture is shade and colors allow merging
if( (pspo->spo_aubTextureFlags[iLayer3]&STXF_BLEND_MASK)==STXF_BLEND_SHADE) {
// can be merged, so put to multi-texture
pspo->spo_pspoSucc = *ppspoMT;
*ppspoMT = pspo;
} else {
// cannot be merged, so put to single-texture
pspo->spo_pspoSucc = *ppspoST;
*ppspoST = pspo;
}
}
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_BINBYMULTITEXTURING);
}
// bin polygons that can use quad-texturing
static void RSBinByQuadTexturing( ScenePolygon *pspoGroup, ScenePolygon **ppspoST, ScenePolygon **ppspoMT)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_BINBYMULTITEXTURING);
*ppspoST = NULL;
*ppspoMT = pspoGroup;
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_BINBYMULTITEXTURING);
}
// check if all layers in all shadow maps are up to date
static void RSCheckLayersUpToDate( ScenePolygon *pspoFirst)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_CHECKLAYERSUPTODATE);
// for all span polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc) {
if( pspo->spo_psmShadowMap!=NULL) pspo->spo_psmShadowMap->CheckLayersUpToDate();
}
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_CHECKLAYERSUPTODATE);
}
// prepare parameters individual to a polygon texture
inline void RSSetTextureWrapping( ULONG ulFlags)
{
gfxSetTextureWrapping( (ulFlags&STXF_CLAMPU) ? GFX_CLAMP : GFX_REPEAT,
(ulFlags&STXF_CLAMPV) ? GFX_CLAMP : GFX_REPEAT);
}
// prepare parameters individual to a polygon texture
static void RSSetInitialTextureParameters(void)
{
_ulLastFlags[0] = STXF_BLEND_OPAQUE;
_ulLastBlends[0] = STXF_BLEND_OPAQUE;
_iLastFrameNo[0] = 0;
_ptdLastTex[0] = NULL;
gfxSetTextureModulation(1);
gfxDisableBlend();
}
static void RSSetTextureParameters( ULONG ulFlags)
{
// if blend flags have changed
ULONG ulBlendFlags = ulFlags&STXF_BLEND_MASK;
if( _ulLastBlends[0] != ulBlendFlags)
{ // determine new texturing mode
switch( ulBlendFlags) {
case STXF_BLEND_OPAQUE: // opaque texturing
gfxDisableBlend();
break;
case STXF_BLEND_ALPHA: // blend using texture alpha
gfxEnableBlend();
gfxBlendFunc( GFX_SRC_ALPHA, GFX_INV_SRC_ALPHA);
break;
case STXF_BLEND_ADD: // add to screen
gfxEnableBlend();
gfxBlendFunc( GFX_ONE, GFX_ONE);
break;
default: // screen*texture*2
ASSERT( ulBlendFlags==STXF_BLEND_SHADE);
gfxEnableBlend();
gfxBlendFunc( GFX_DST_COLOR, GFX_SRC_COLOR);
break;
}
// remember new flags
_ulLastBlends[0] = ulFlags;
}
}
// prepare initial parameters for polygon texture
static void RSSetInitialTextureParametersMT(void)
{
INDEX i;
// reset bleding modes
for( i=0; i<MAXTEXUNITS; i++) {
_ulLastFlags[i] = STXF_BLEND_OPAQUE;
_ulLastBlends[i] = STXF_BLEND_OPAQUE;
_iLastFrameNo[i] = 0;
_ptdLastTex[i] = NULL;
}
// reset for texture
gfxDisableBlend();
for( i=1; i<_ctUsableTexUnits; i++) {
gfxSetTextureUnit(i);
gfxSetTextureModulation(2);
}
gfxSetTextureUnit(0);
gfxSetTextureModulation(1);
}
// prepare parameters individual to a polygon texture
static void RSSetTextureParametersMT( ULONG ulFlags)
{
// skip if the same as last time
const ULONG ulBlendFlags = ulFlags&STXF_BLEND_MASK;
if( _ulLastBlends[0]==ulBlendFlags) return;
// update
if( ulBlendFlags==STXF_BLEND_OPAQUE) {
// opaque texturing
gfxDisableBlend();
} else {
// shade texturing
ASSERT( ulBlendFlags==STXF_BLEND_SHADE);
gfxEnableBlend();
gfxBlendFunc( GFX_DST_COLOR, GFX_SRC_COLOR);
} // keep
_ulLastBlends[0] = ulBlendFlags;
}
// make vertex coordinates for all polygons in the group
static void RSMakeVertexCoordinates( ScenePolygon *pspoGroup)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_MAKEVERTEXCOORDS);
_avtxPass.PopAll();
INDEX ctGroupVtx = 0;
// for all scene polygons in list
for( ScenePolygon *pspo=pspoGroup; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{
// create new vertices for that polygon in per-pass array
const INDEX ctVtx = pspo->spo_ctVtx;
pspo->spo_iVtx0Pass = _avtxPass.Count();
GFXVertex3 *pvtxScene = &_avtxScene[pspo->spo_iVtx0];
GFXVertex4 *pvtxPass = _avtxPass.Push(ctVtx);
// copy the vertex coordinates
for( INDEX iVtx=0; iVtx<ctVtx; iVtx++) {
pvtxPass[iVtx].x = pvtxScene[iVtx].x;
pvtxPass[iVtx].y = pvtxScene[iVtx].y;
pvtxPass[iVtx].z = pvtxScene[iVtx].z;
}
// add polygon vertices to total
ctGroupVtx += ctVtx;
}
// prepare texture and color arrays
_acolPass.PopAll();
_atexPass[0].PopAll();
_atexPass[1].PopAll();
_atexPass[2].PopAll();
_atexPass[3].PopAll();
_acolPass.Push(ctGroupVtx);
for( INDEX i=0; i<_ctUsableTexUnits; i++) _atexPass[i].Push(ctGroupVtx);
// done
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_MAKEVERTEXCOORDS);
}
static void RSSetPolygonColors( ScenePolygon *pspoGroup, UBYTE ubAlpha)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_SETCOLORS);
// for all scene polygons in list
COLOR col;
GFXColor *pcol;
for( ScenePolygon *pspo = pspoGroup; pspo != NULL; pspo = pspo->spo_pspoSucc) {
col = ByteSwap( AdjustColor( pspo->spo_cColor|ubAlpha, _slTexHueShift, _slTexSaturation));
pcol = &_acolPass[pspo->spo_iVtx0Pass];
for( INDEX i=0; i<pspo->spo_ctVtx; i++) pcol[i].abgr = col;
}
gfxSetColorArray( &_acolPass[0]);
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_SETCOLORS);
}
static void RSSetConstantColors( COLOR col)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_SETCOLORS);
col = ByteSwap( AdjustColor( col, _slTexHueShift, _slTexSaturation));
GFXColor *pcol = &_acolPass[0];
for( INDEX i=0; i<_acolPass.Count(); i++) pcol[i].abgr = col;
gfxSetColorArray( &_acolPass[0]);
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_SETCOLORS);
}
static void RSSetTextureColors( ScenePolygon *pspoGroup, ULONG ulLayerMask)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_SETCOLORS);
ASSERT( !(ulLayerMask & (GF_TA1|GF_TA2|GF_FOG|GF_HAZE|GF_SEL)));
// for all scene polygons in list
COLOR colLayer, colTotal;
for( ScenePolygon *pspo = pspoGroup; pspo != NULL; pspo = pspo->spo_pspoSucc)
{ // adjust hue/saturation and set colors
colTotal = C_WHITE|CT_OPAQUE;
if( ulLayerMask&GF_TX0) {
colLayer = AdjustColor( pspo->spo_acolColors[0], _slTexHueShift, _slTexSaturation);
if( colLayer!=0xFFFFFFFF) colTotal = MulColors( colTotal, colLayer);
}
if( ulLayerMask&GF_TX1) {
colLayer = AdjustColor( pspo->spo_acolColors[1], _slTexHueShift, _slTexSaturation);
if( colLayer!=0xFFFFFFFF) colTotal = MulColors( colTotal, colLayer);
}
if( ulLayerMask&GF_TX2) {
colLayer = AdjustColor( pspo->spo_acolColors[2], _slTexHueShift, _slTexSaturation);
if( colLayer!=0xFFFFFFFF) colTotal = MulColors( colTotal, colLayer);
}
if( ulLayerMask&GF_SHD) {
colLayer = AdjustColor( pspo->spo_acolColors[3], _slShdHueShift, _slShdSaturation);
if( colLayer!=0xFFFFFFFF) colTotal = MulColors( colTotal, colLayer);
}
// store
colTotal = ByteSwap(colTotal);
GFXColor *pcol= &_acolPass[pspo->spo_iVtx0Pass];
for( INDEX i=0; i<pspo->spo_ctVtx; i++) pcol[i].abgr = colTotal;
}
// set color array
gfxSetColorArray( &_acolPass[0]);
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_SETCOLORS);
}
// make texture coordinates for one texture in all polygons in group
static INDEX _iLastUnit = -1;
static void RSSetTextureCoords( ScenePolygon *pspoGroup, INDEX iLayer, INDEX iUnit)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_SETTEXCOORDS);
// eventualy switch texture unit
if( _iLastUnit != iUnit) {
gfxSetTextureUnit(iUnit);
gfxEnableTexture();
_iLastUnit = iUnit;
}
// generate tex coord for all scene polygons in list
const FLOATmatrix3D &mViewer = _ppr->pr_ViewerRotationMatrix;
const INDEX iMappingOffset = iLayer * sizeof(CMappingVectors);
for( ScenePolygon *pspo=pspoGroup; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{
ASSERT( pspo->spo_ctVtx>0);
const FLOAT3D &vN = ((CBrushPolygon*)pspo->spo_pvPolygon)->bpo_pbplPlane->bpl_pwplWorking->wpl_plView;
const GFXVertex *pvtx = &_avtxPass[pspo->spo_iVtx0Pass];
GFXTexCoord *ptex = &_atexPass[iUnit][pspo->spo_iVtx0Pass];
// reflective mapping?
if( pspo->spo_aubTextureFlags[iLayer] & STXF_REFLECTION) {
for( INDEX i=0; i<pspo->spo_ctVtx; i++) {
const FLOAT fNorm = 1.0f / sqrt(pvtx[i].x*pvtx[i].x + pvtx[i].y*pvtx[i].y + pvtx[i].z*pvtx[i].z);
const FLOAT fVx = pvtx[i].x *fNorm;
const FLOAT fVy = pvtx[i].y *fNorm;
const FLOAT fVz = pvtx[i].z *fNorm;
const FLOAT fNV = fVx*vN(1) + fVy*vN(2) + fVz*vN(3);
const FLOAT fRVx = fVx - 2*vN(1)*fNV;
const FLOAT fRVy = fVy - 2*vN(2)*fNV;
const FLOAT fRVz = fVz - 2*vN(3)*fNV;
const FLOAT fRVxT = fRVx*mViewer(1,1) + fRVy*mViewer(2,1) + fRVz*mViewer(3,1);
const FLOAT fRVzT = fRVx*mViewer(1,3) + fRVy*mViewer(2,3) + fRVz*mViewer(3,3);
ptex[i].s = fRVxT*0.5f +0.5f;
ptex[i].t = fRVzT*0.5f +0.5f;
}
// advance to next polygon
continue;
}
// diffuse mapping
const FLOAT3D &vO = pspo->spo_amvMapping[iLayer].mv_vO;
#if ASMOPT == 1
__asm {
mov esi,D [pspo]
mov edi,D [iMappingOffset]
lea eax,[esi].spo_amvMapping[edi].mv_vO
lea ebx,[esi].spo_amvMapping[edi].mv_vU
lea ecx,[esi].spo_amvMapping[edi].mv_vV
mov edx,D [esi].spo_ctVtx
mov esi,D [pvtx]
mov edi,D [ptex]
vtxLoop:
fld D [ebx+0]
fld D [esi]GFXVertex.x
fsub D [eax+0]
fmul st(1),st(0)
fmul D [ecx+0] // vV(1)*fDX, vU(1)*fDX
fld D [ebx+4]
fld D [esi]GFXVertex.y
fsub D [eax+4]
fmul st(1),st(0)
fmul D [ecx+4] // vV(2)*fDY, vU(2)*fDY, vV(1)*fDX, vU(1)*fDX
fld D [ebx+8]
fld D [esi]GFXVertex.z
fsub D [eax+8]
fmul st(1),st(0)
fmul D [ecx+8] // vV(3)*fDZ, vU(3)*fDZ, vV(2)*fDY, vU(2)*fDY, vV(1)*fDX, vU(1)*fDX
fxch st(5)
faddp st(3),st(0) // vU(3)*fDZ, vV(2)*fDY, vU(1)*fDX+vU(2)*fDY, vV(1)*fDX, vV(3)*fDZ
fxch st(1)
faddp st(3),st(0) // vU(3)*fDZ, vU(1)*fDX+vU(2)*fDY, vV(1)*fDX+vV(2)*fDY, vV(3)*fDZ
faddp st(1),st(0) // vU(1)*fDX+vU(2)*fDY+vU(3)*fDZ, vV(1)*fDX+vV(2)*fDY, vV(3)*fDZ
fxch st(1)
faddp st(2),st(0) // vU(1)*fDX+vU(2)*fDY+vU(3)*fDZ, vV(1)*fDX+vV(2)*fDY+vV(3)*fDZ
fstp D [edi]GFXTexCoord.s
fstp D [edi]GFXTexCoord.t
add esi,4*4
add edi,2*4
dec edx
jnz vtxLoop
}
#else
const FLOAT3D &vO = pspo->spo_amvMapping[iLayer].mv_vO;
const FLOAT3D &vU = pspo->spo_amvMapping[iLayer].mv_vU;
const FLOAT3D &vV = pspo->spo_amvMapping[iLayer].mv_vV;
for( INDEX i=0; i<pspo->spo_ctVtx; i++) {
const FLOAT fDX = pvtx[i].x -vO(1);
const FLOAT fDY = pvtx[i].y -vO(2);
const FLOAT fDZ = pvtx[i].z -vO(3);
ptex[i].s = vU(1)*fDX + vU(2)*fDY + vU(3)*fDZ;
ptex[i].t = vV(1)*fDX + vV(2)*fDY + vV(3)*fDZ;
}
#endif
}
// init array
gfxSetTexCoordArray( &_atexPass[iUnit][0], FALSE);
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_SETTEXCOORDS);
}
// make fog texture coordinates for all polygons in group
static void RSSetFogCoordinates( ScenePolygon *pspoGroup)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_SETTEXCOORDS);
// for all scene polygons in list
for( ScenePolygon *pspo=pspoGroup; pspo!=NULL; pspo=pspo->spo_pspoSucc) {
const GFXVertex *pvtx = &_avtxPass[pspo->spo_iVtx0Pass];
GFXTexCoord *ptex = &_atexPass[0][pspo->spo_iVtx0Pass];
for( INDEX i=0; i<pspo->spo_ctVtx; i++) {
ptex[i].s = pvtx[i].z *_fFogMul;
ptex[i].t = (_fog_vHDirView(1)*pvtx[i].x + _fog_vHDirView(2)*pvtx[i].y
+ _fog_vHDirView(3)*pvtx[i].z + _fog_fAddH) * _fog_fMulH;
}
}
gfxSetTexCoordArray( &_atexPass[0][0], FALSE);
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_SETTEXCOORDS);
}
// make haze texture coordinates for all polygons in group
static void RSSetHazeCoordinates( ScenePolygon *pspoGroup)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_SETTEXCOORDS);
// for all scene polygons in list
for( ScenePolygon *pspo=pspoGroup; pspo!=NULL; pspo=pspo->spo_pspoSucc) {
const GFXVertex *pvtx = &_avtxPass[pspo->spo_iVtx0Pass];
GFXTexCoord *ptex = &_atexPass[0][pspo->spo_iVtx0Pass];
for( INDEX i=0; i<pspo->spo_ctVtx; i++) {
ptex[i].s = (pvtx[i].z + _fHazeAdd) *_fHazeMul;
ptex[i].t = 0;
}
}
gfxSetTexCoordArray( &_atexPass[0][0], FALSE);
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_SETTEXCOORDS);
}
// render textures for all triangles in polygon list
static void RSRenderTEX( ScenePolygon *pspoFirst, INDEX iLayer)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERTEXTURES);
RSSetInitialTextureParameters();
// for all span polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{
ASSERT(pspo->spo_aptoTextures[iLayer]!=NULL);
CTextureData *ptdTextureData = (CTextureData*)pspo->spo_aptoTextures[iLayer]->GetData();
const INDEX iFrameNo = pspo->spo_aptoTextures[iLayer]->GetFrame();
if( _ptdLastTex[0] != ptdTextureData
|| _ulLastFlags[0] != pspo->spo_aubTextureFlags[iLayer]
|| _iLastFrameNo[0] != iFrameNo) {
// flush
FlushElements();
_ptdLastTex[0] = ptdTextureData;
_ulLastFlags[0] = pspo->spo_aubTextureFlags[iLayer];
_iLastFrameNo[0] = iFrameNo;
// set texture parameters if needed
RSSetTextureWrapping( pspo->spo_aubTextureFlags[iLayer]);
RSSetTextureParameters( pspo->spo_aubTextureFlags[iLayer]);
// prepare texture to be used by accelerator
ptdTextureData->SetAsCurrent(iFrameNo);
}
// render all triangles
AddElements(pspo);
}
// flush leftovers
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERTEXTURES);
}
// render shadows for all triangles in polygon list
static void RSRenderSHD( ScenePolygon *pspoFirst)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERSHADOWS);
RSSetInitialTextureParameters();
// for all span polygons in list
for( ScenePolygon *pspo = pspoFirst; pspo != NULL; pspo = pspo->spo_pspoSucc)
{
// get shadow map for the polygon
CShadowMap *psmShadow = pspo->spo_psmShadowMap;
ASSERT( psmShadow!=NULL); // shadows have been already sorted out
// set texture parameters if needed
RSSetTextureWrapping( pspo->spo_aubTextureFlags[SHADOWTEXTURE]);
RSSetTextureParameters( pspo->spo_aubTextureFlags[SHADOWTEXTURE]);
// upload the shadow to accelerator memory
psmShadow->SetAsCurrent();
// batch and render triangles
AddElements(pspo);
FlushElements();
}
// done
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERSHADOWS);
}
// render texture and shadow for all triangles in polygon list
static void RSRenderTEX_SHD( ScenePolygon *pspoFirst, INDEX iLayer)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERMT);
RSSetInitialTextureParametersMT();
// for all span polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{
// render batched triangles
FlushElements();
ASSERT( pspo->spo_aptoTextures[iLayer]!=NULL && pspo->spo_psmShadowMap!=NULL);
// upload the shadow to accelerator memory
gfxSetTextureUnit(1);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[SHADOWTEXTURE]);
pspo->spo_psmShadowMap->SetAsCurrent();
// prepare texture to be used by accelerator
CTextureData *ptd = (CTextureData*)pspo->spo_aptoTextures[iLayer]->GetData();
const INDEX iFrameNo = pspo->spo_aptoTextures[iLayer]->GetFrame();
gfxSetTextureUnit(0);
if( _ptdLastTex[0]!=ptd || _iLastFrameNo[0]!=iFrameNo || _ulLastFlags[0]!=pspo->spo_aubTextureFlags[iLayer]) {
_ptdLastTex[0]=ptd; _iLastFrameNo[0]=iFrameNo; _ulLastFlags[0]=pspo->spo_aubTextureFlags[iLayer];
RSSetTextureWrapping( pspo->spo_aubTextureFlags[iLayer]);
ptd->SetAsCurrent(iFrameNo);
// set rendering parameters if needed
RSSetTextureParametersMT( pspo->spo_aubTextureFlags[iLayer]);
}
// batch triangles
AddElements(pspo);
}
// flush leftovers
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERMT);
}
// render two textures for all triangles in polygon list
static void RSRender2TEX( ScenePolygon *pspoFirst, INDEX iLayer2)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERMT);
RSSetInitialTextureParametersMT();
// for all span polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{
ASSERT( pspo->spo_aptoTextures[0]!=NULL && pspo->spo_aptoTextures[iLayer2]!=NULL);
CTextureData *ptd0 = (CTextureData*)pspo->spo_aptoTextures[0]->GetData();
CTextureData *ptd1 = (CTextureData*)pspo->spo_aptoTextures[iLayer2]->GetData();
const INDEX iFrameNo0 = pspo->spo_aptoTextures[0]->GetFrame();
const INDEX iFrameNo1 = pspo->spo_aptoTextures[iLayer2]->GetFrame();
if( _ptdLastTex[0]!=ptd0 || _iLastFrameNo[0]!=iFrameNo0 || _ulLastFlags[0]!=pspo->spo_aubTextureFlags[0]
|| _ptdLastTex[1]!=ptd1 || _iLastFrameNo[1]!=iFrameNo1 || _ulLastFlags[1]!=pspo->spo_aubTextureFlags[iLayer2]) {
FlushElements();
_ptdLastTex[0]=ptd0; _iLastFrameNo[0]=iFrameNo0; _ulLastFlags[0]=pspo->spo_aubTextureFlags[0];
_ptdLastTex[1]=ptd1; _iLastFrameNo[1]=iFrameNo1; _ulLastFlags[1]=pspo->spo_aubTextureFlags[iLayer2];
// upload the second texture to unit 1
gfxSetTextureUnit(1);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[iLayer2]);
ptd1->SetAsCurrent(iFrameNo1);
// upload the first texture to unit 0
gfxSetTextureUnit(0);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[0]);
ptd0->SetAsCurrent(iFrameNo0);
// set rendering parameters if needed
RSSetTextureParametersMT( pspo->spo_aubTextureFlags[0]);
}
// render all triangles
AddElements(pspo);
}
// flush leftovers
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERMT);
}
// render two textures and shadowmap for all triangles in polygon list
static void RSRender2TEX_SHD( ScenePolygon *pspoFirst, INDEX iLayer2)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERMT);
RSSetInitialTextureParametersMT();
// for all span polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{
ASSERT( pspo->spo_aptoTextures[0]!=NULL
&& pspo->spo_aptoTextures[iLayer2]!=NULL
&& pspo->spo_psmShadowMap!=NULL);
// render batched triangles
FlushElements();
// upload the shadow to accelerator memory
gfxSetTextureUnit(2);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[SHADOWTEXTURE]);
pspo->spo_psmShadowMap->SetAsCurrent();
// prepare textures to be used by accelerator
CTextureData *ptd0 = (CTextureData*)pspo->spo_aptoTextures[0]->GetData();
CTextureData *ptd1 = (CTextureData*)pspo->spo_aptoTextures[iLayer2]->GetData();
const INDEX iFrameNo0 = pspo->spo_aptoTextures[0]->GetFrame();
const INDEX iFrameNo1 = pspo->spo_aptoTextures[iLayer2]->GetFrame();
gfxSetTextureUnit(0);
if( _ptdLastTex[0]!=ptd0 || _iLastFrameNo[0]!=iFrameNo0 || _ulLastFlags[0]!=pspo->spo_aubTextureFlags[0]
|| _ptdLastTex[1]!=ptd1 || _iLastFrameNo[1]!=iFrameNo1 || _ulLastFlags[1]!=pspo->spo_aubTextureFlags[iLayer2]) {
_ptdLastTex[0]=ptd0; _iLastFrameNo[0]=iFrameNo0; _ulLastFlags[0]=pspo->spo_aubTextureFlags[0];
_ptdLastTex[1]=ptd1; _iLastFrameNo[1]=iFrameNo1; _ulLastFlags[1]=pspo->spo_aubTextureFlags[iLayer2];
// upload the second texture to unit 1
gfxSetTextureUnit(1);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[iLayer2]);
ptd1->SetAsCurrent(iFrameNo1);
// upload the first texture to unit 0
gfxSetTextureUnit(0);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[0]);
ptd0->SetAsCurrent(iFrameNo0);
// set rendering parameters if needed
RSSetTextureParametersMT( pspo->spo_aubTextureFlags[0]);
}
// render all triangles
AddElements(pspo);
}
// flush leftovers
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERMT);
}
// render three textures for all triangles in polygon list
static void RSRender3TEX( ScenePolygon *pspoFirst)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERMT);
RSSetInitialTextureParametersMT();
// for all span polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{
ASSERT( pspo->spo_aptoTextures[0]!=NULL
&& pspo->spo_aptoTextures[1]!=NULL
&& pspo->spo_aptoTextures[2]!=NULL);
CTextureData *ptd0 = (CTextureData*)pspo->spo_aptoTextures[0]->GetData();
CTextureData *ptd1 = (CTextureData*)pspo->spo_aptoTextures[1]->GetData();
CTextureData *ptd2 = (CTextureData*)pspo->spo_aptoTextures[2]->GetData();
const INDEX iFrameNo0 = pspo->spo_aptoTextures[0]->GetFrame();
const INDEX iFrameNo1 = pspo->spo_aptoTextures[1]->GetFrame();
const INDEX iFrameNo2 = pspo->spo_aptoTextures[2]->GetFrame();
if( _ptdLastTex[0]!=ptd0 || _iLastFrameNo[0]!=iFrameNo0 || _ulLastFlags[0]!=pspo->spo_aubTextureFlags[0]
|| _ptdLastTex[1]!=ptd1 || _iLastFrameNo[1]!=iFrameNo1 || _ulLastFlags[1]!=pspo->spo_aubTextureFlags[1]
|| _ptdLastTex[2]!=ptd2 || _iLastFrameNo[2]!=iFrameNo2 || _ulLastFlags[2]!=pspo->spo_aubTextureFlags[2]) {
FlushElements();
_ptdLastTex[0]=ptd0; _iLastFrameNo[0]=iFrameNo0; _ulLastFlags[0]=pspo->spo_aubTextureFlags[0];
_ptdLastTex[1]=ptd1; _iLastFrameNo[1]=iFrameNo1; _ulLastFlags[1]=pspo->spo_aubTextureFlags[1];
_ptdLastTex[2]=ptd2; _iLastFrameNo[2]=iFrameNo2; _ulLastFlags[2]=pspo->spo_aubTextureFlags[2];
// upload the third texture to unit 2
gfxSetTextureUnit(2);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[2]);
ptd2->SetAsCurrent(iFrameNo2);
// upload the second texture to unit 1
gfxSetTextureUnit(1);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[1]);
ptd1->SetAsCurrent(iFrameNo1);
// upload the first texture to unit 0
gfxSetTextureUnit(0);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[0]);
ptd0->SetAsCurrent(iFrameNo0);
// set rendering parameters if needed
RSSetTextureParametersMT( pspo->spo_aubTextureFlags[0]);
}
// render all triangles
AddElements(pspo);
}
// flush leftovers
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERMT);
}
// render three textures and shadowmap for all triangles in polygon list
static void RSRender3TEX_SHD( ScenePolygon *pspoFirst)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERMT);
RSSetInitialTextureParametersMT();
// for all span polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{
ASSERT( pspo->spo_aptoTextures[0]!=NULL
&& pspo->spo_aptoTextures[1]!=NULL
&& pspo->spo_aptoTextures[2]!=NULL
&& pspo->spo_psmShadowMap!=NULL);
// render batched triangles
FlushElements();
// upload the shadow to accelerator memory
gfxSetTextureUnit(3);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[SHADOWTEXTURE]);
pspo->spo_psmShadowMap->SetAsCurrent();
// prepare textures to be used by accelerator
CTextureData *ptd0 = (CTextureData*)pspo->spo_aptoTextures[0]->GetData();
CTextureData *ptd1 = (CTextureData*)pspo->spo_aptoTextures[1]->GetData();
CTextureData *ptd2 = (CTextureData*)pspo->spo_aptoTextures[2]->GetData();
const INDEX iFrameNo0 = pspo->spo_aptoTextures[0]->GetFrame();
const INDEX iFrameNo1 = pspo->spo_aptoTextures[1]->GetFrame();
const INDEX iFrameNo2 = pspo->spo_aptoTextures[2]->GetFrame();
gfxSetTextureUnit(0);
if( _ptdLastTex[0]!=ptd0 || _iLastFrameNo[0]!=iFrameNo0 || _ulLastFlags[0]!=pspo->spo_aubTextureFlags[0]
|| _ptdLastTex[1]!=ptd1 || _iLastFrameNo[1]!=iFrameNo1 || _ulLastFlags[1]!=pspo->spo_aubTextureFlags[1]
|| _ptdLastTex[2]!=ptd2 || _iLastFrameNo[2]!=iFrameNo2 || _ulLastFlags[2]!=pspo->spo_aubTextureFlags[2]) {
_ptdLastTex[0]=ptd0; _iLastFrameNo[0]=iFrameNo0; _ulLastFlags[0]=pspo->spo_aubTextureFlags[0];
_ptdLastTex[1]=ptd1; _iLastFrameNo[1]=iFrameNo1; _ulLastFlags[1]=pspo->spo_aubTextureFlags[1];
_ptdLastTex[2]=ptd2; _iLastFrameNo[2]=iFrameNo2; _ulLastFlags[2]=pspo->spo_aubTextureFlags[2];
// upload the third texture to unit 2
gfxSetTextureUnit(2);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[2]);
ptd2->SetAsCurrent(iFrameNo2);
// upload the second texture to unit 1
gfxSetTextureUnit(1);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[1]);
ptd1->SetAsCurrent(iFrameNo1);
// upload the first texture to unit 0
gfxSetTextureUnit(0);
RSSetTextureWrapping( pspo->spo_aubTextureFlags[0]);
ptd0->SetAsCurrent(iFrameNo0);
// set rendering parameters if needed
RSSetTextureParametersMT( pspo->spo_aubTextureFlags[0]);
}
// render all triangles
AddElements(pspo);
}
// flush leftovers
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERMT);
}
// render fog for all affected triangles in polygon list
__forceinline void RSRenderFog( ScenePolygon *pspoFirst)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERFOG);
// for all scene polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{ // for all vertices in the polygon
const GFXTexCoord *ptex = &_atexPass[0][pspo->spo_iVtx0Pass];
for( INDEX i=0; i<pspo->spo_ctVtx; i++) {
// polygon is in fog, stop searching
if( InFog(ptex[i].t)) goto hasFog;
}
// hasn't got any fog, so skip it
continue;
hasFog:
// render all triangles
AddElements(pspo);
}
// all done
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERFOG);
}
// render haze for all affected triangles in polygon list
__forceinline void RSRenderHaze( ScenePolygon *pspoFirst)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERFOG);
// for all scene polygons in list
for( ScenePolygon *pspo=pspoFirst; pspo!=NULL; pspo=pspo->spo_pspoSucc)
{ // for all vertices in the polygon
const GFXTexCoord *ptex = &_atexPass[0][pspo->spo_iVtx0Pass];
for( INDEX i=0; i<pspo->spo_ctVtx; i++) {
// polygon is in haze, stop searching
if( InHaze(ptex[i].s)) goto hasHaze;
}
// hasn't got any haze, so skip it
continue;
hasHaze:
// render all triangles
AddElements(pspo);
}
// all done
FlushElements();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERFOG);
}
static void RSStartupFog(void)
{
// upload fog texture
gfxSetTextureWrapping( GFX_CLAMP, GFX_CLAMP);
gfxSetTexture( _fog_ulTexture, _fog_tpLocal);
// prepare fog rendering parameters
gfxEnableBlend();
gfxBlendFunc( GFX_SRC_ALPHA, GFX_INV_SRC_ALPHA);
// calculate fog mapping
_fFogMul = -1.0f / _fog_fp.fp_fFar;
}
static void RSStartupHaze(void)
{
// upload haze texture
gfxEnableTexture();
gfxSetTextureWrapping( GFX_CLAMP, GFX_CLAMP);
gfxSetTexture( _haze_ulTexture, _haze_tpLocal);
// prepare haze rendering parameters
gfxEnableBlend();
gfxBlendFunc( GFX_SRC_ALPHA, GFX_INV_SRC_ALPHA);
// calculate haze mapping
_fHazeMul = -1.0f / (_haze_hp.hp_fFar - _haze_hp.hp_fNear);
_fHazeAdd = _haze_hp.hp_fNear;
}
// process one group of polygons
void RSRenderGroupInternal( ScenePolygon *pspoGroup, ULONG ulGroupFlags);
void RSRenderGroup( ScenePolygon *pspoGroup, ULONG ulGroupFlags, ULONG ulTestedFlags)
{
// skip if the group is empty
if( pspoGroup==NULL) return;
ASSERT( !(ulTestedFlags&(GF_FOG|GF_HAZE))); // paranoia
// if multitexturing is enabled (start with 2-layer MT)
if( _ctUsableTexUnits>=2)
{
// if texture 1 could be merged with shadow
if( !(ulTestedFlags&GF_TX0_SHD)
&& (ulGroupFlags &GF_TX0)
&& !(ulGroupFlags &GF_TX1)
&& !(ulGroupFlags &GF_TX2)
&& (ulGroupFlags &GF_SHD))
{ // bin polygons that can use the merge and those that cannot
ScenePolygon *pspoST, *pspoMT;
RSBinByDualTexturing( pspoGroup, 0, SHADOWTEXTURE, &pspoST, &pspoMT);
// process the two groups separately
ulTestedFlags |= GF_TX0_SHD;
RSRenderGroup( pspoST, ulGroupFlags, ulTestedFlags);
ulGroupFlags &= ~(GF_TX0|GF_SHD);
ulGroupFlags |= GF_TX0_SHD;
RSRenderGroup( pspoMT, ulGroupFlags, ulTestedFlags);
return;
}
// if texture 1 could be merged with texture 2
if( !(ulTestedFlags&GF_TX0_TX1)
&& (ulGroupFlags &GF_TX0)
&& (ulGroupFlags &GF_TX1))
{ // bin polygons that can use the merge and those that cannot
ScenePolygon *pspoST, *pspoMT;
RSBinByDualTexturing( pspoGroup, 0, 1, &pspoST, &pspoMT);
// process the two groups separately
ulTestedFlags |= GF_TX0_TX1;
RSRenderGroup( pspoST, ulGroupFlags, ulTestedFlags);
ulGroupFlags &= ~(GF_TX0|GF_TX1);
ulGroupFlags |= GF_TX0_TX1;
RSRenderGroup( pspoMT, ulGroupFlags, ulTestedFlags);
return;
}
// if texture 1 could be merged with texture 3
if( !(ulTestedFlags&GF_TX0_TX2)
&& (ulGroupFlags &GF_TX0)
&& !(ulGroupFlags &GF_TX1)
&& (ulGroupFlags &GF_TX2))
{ // bin polygons that can use the merge and those that cannot
ScenePolygon *pspoST, *pspoMT;
RSBinByDualTexturing( pspoGroup, 0, 2, &pspoST, &pspoMT);
// process the two groups separately
ulTestedFlags |= GF_TX0_TX2;
RSRenderGroup( pspoST, ulGroupFlags, ulTestedFlags);
ulGroupFlags &= ~(GF_TX0|GF_TX2);
ulGroupFlags |= GF_TX0_TX2;
RSRenderGroup( pspoMT, ulGroupFlags, ulTestedFlags);
return;
}
// if texture 3 could be merged with shadow
if( !(ulTestedFlags&GF_TX2_SHD)
&& (ulGroupFlags &GF_TX0_TX1)
&& (ulGroupFlags &GF_TX2)
&& (ulGroupFlags &GF_SHD))
{ // bin polygons that can use the merge and those that cannot
ScenePolygon *pspoST, *pspoMT;
RSBinByDualTexturing( pspoGroup, 2, SHADOWTEXTURE, &pspoST, &pspoMT);
// process the two groups separately
ulTestedFlags |= GF_TX2_SHD;
RSRenderGroup( pspoST, ulGroupFlags, ulTestedFlags);
ulGroupFlags &= ~(GF_TX2|GF_SHD);
ulGroupFlags |= GF_TX2_SHD;
RSRenderGroup( pspoMT, ulGroupFlags, ulTestedFlags);
return;
}
}
// 4-layer multitexturing?
if( _ctUsableTexUnits>=4)
{
// if texture 1 and 2 could be merged with 3 and shadow
if( !(ulTestedFlags&GF_TX0_TX1_TX2_SHD)
&& (ulGroupFlags &GF_TX0_TX1)
&& (ulGroupFlags &GF_TX2_SHD))
{ // bin polygons that can use the merge and those that cannot
ScenePolygon *pspoST, *pspoMT;
RSBinByQuadTexturing( pspoGroup, &pspoST, &pspoMT);
// process the two groups separately
ulTestedFlags |= GF_TX0_TX1_TX2_SHD;
RSRenderGroup( pspoST, ulGroupFlags, ulTestedFlags);
ulGroupFlags &= ~(GF_TX0_TX1|GF_TX2_SHD);
ulGroupFlags |= GF_TX0_TX1_TX2_SHD;
RSRenderGroup( pspoMT, ulGroupFlags, ulTestedFlags);
return;
}
}
// 3-layer multitexturing?
if( _ctUsableTexUnits>=3)
{
// if texture 1 and 2 could be merged with 3
if( !(ulTestedFlags&GF_TX0_TX1_TX2)
&& (ulGroupFlags &GF_TX0_TX1)
&& (ulGroupFlags &GF_TX2))
{ // bin polygons that can use the merge and those that cannot
ScenePolygon *pspoST, *pspoMT;
RSBinByTripleTexturing( pspoGroup, 1, 2, &pspoST, &pspoMT);
// process the two groups separately
ulTestedFlags |= GF_TX0_TX1_TX2;
RSRenderGroup( pspoST, ulGroupFlags, ulTestedFlags);
ulGroupFlags &= ~(GF_TX0_TX1|GF_TX2);
ulGroupFlags |= GF_TX0_TX1_TX2;
RSRenderGroup( pspoMT, ulGroupFlags, ulTestedFlags);
return;
}
// if texture 1 and 2 could be merged with shadow
if( !(ulTestedFlags&GF_TX0_TX1_SHD)
&& (ulGroupFlags &GF_TX0_TX1)
&& !(ulGroupFlags &GF_TX2)
&& (ulGroupFlags &GF_SHD))
{ // bin polygons that can use the merge and those that cannot
ScenePolygon *pspoST, *pspoMT;
RSBinByTripleTexturing( pspoGroup, 1, SHADOWTEXTURE, &pspoST, &pspoMT);
// process the two groups separately
ulTestedFlags |= GF_TX0_TX1_SHD;
RSRenderGroup( pspoST, ulGroupFlags, ulTestedFlags);
ulGroupFlags &= ~(GF_TX0_TX1|GF_SHD);
ulGroupFlags |= GF_TX0_TX1_SHD;
RSRenderGroup( pspoMT, ulGroupFlags, ulTestedFlags);
return;
}
// if texture 1 and 3 could be merged with shadow
if( !(ulTestedFlags&GF_TX0_TX2_SHD)
&& (ulGroupFlags &GF_TX0_TX2)
&& !(ulGroupFlags &GF_TX1)
&& (ulGroupFlags &GF_SHD))
{ // bin polygons that can use the merge and those that cannot
ScenePolygon *pspoST, *pspoMT;
RSBinByTripleTexturing( pspoGroup, 2, SHADOWTEXTURE, &pspoST, &pspoMT);
// process the two groups separately
ulTestedFlags |= GF_TX0_TX2_SHD;
RSRenderGroup( pspoST, ulGroupFlags, ulTestedFlags);
ulGroupFlags &= ~(GF_TX0_TX2|GF_SHD);
ulGroupFlags |= GF_TX0_TX2_SHD;
RSRenderGroup( pspoMT, ulGroupFlags, ulTestedFlags);
return;
}
}
// render one group
extern INDEX ogl_iMaxBurstSize;
extern INDEX d3d_iMaxBurstSize;
ogl_iMaxBurstSize = Clamp( ogl_iMaxBurstSize, 0L, 9999L);
d3d_iMaxBurstSize = Clamp( d3d_iMaxBurstSize, 0L, 9999L);
const INDEX iMaxBurstSize =
(eAPI==GAT_OGL) ? ogl_iMaxBurstSize :
(eAPI==GAT_VK) ? 0 : d3d_iMaxBurstSize;
// if unlimited lock count
if( iMaxBurstSize==0)
{ // render whole group
RSRenderGroupInternal( pspoGroup, ulGroupFlags);
}
// if lock count is specified
else
{ // render group in segments
while( pspoGroup!=NULL)
{ // find segment size
INDEX ctVtx = 0;
ScenePolygon *pspoThis = pspoGroup;
ScenePolygon *pspoLast = pspoGroup;
while( ctVtx<iMaxBurstSize && pspoGroup!=NULL) {
ctVtx += pspoGroup->spo_ctVtx;
pspoLast = pspoGroup;
pspoGroup = pspoGroup->spo_pspoSucc;
} // render one group segment
pspoLast->spo_pspoSucc = NULL;
RSRenderGroupInternal( pspoThis, ulGroupFlags);
}
}
}
// internal group rendering routine
void RSRenderGroupInternal( ScenePolygon *pspoGroup, ULONG ulGroupFlags)
{
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERGROUPINTERNAL);
_pfGfxProfile.IncrementCounter( CGfxProfile::PCI_RS_POLYGONGROUPS);
// make vertex coordinates for all polygons in the group
RSMakeVertexCoordinates(pspoGroup);
// prepare vertex, texture and color arrays
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_LOCKARRAYS);
gfxSetVertexArray( &_avtxPass[0], _avtxPass.Count());
if(CVA_bWorld) gfxLockArrays();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_LOCKARRAYS);
// set alpha keying if required
if( ulGroupFlags & GF_KEY) gfxEnableAlphaTest();
else gfxDisableAlphaTest();
_iLastUnit = 0; // reset mulitex unit change
BOOL bUsedMT = FALSE;
BOOL bUsesMT = ulGroupFlags & (GF_TX0_TX1 | GF_TX0_TX2 | GF_TX0_SHD | GF_TX2_SHD
| GF_TX0_TX1_TX2 | GF_TX0_TX1_SHD | GF_TX0_TX2_SHD
| GF_TX0_TX1_TX2_SHD);
// dual texturing
if( ulGroupFlags & GF_TX0_SHD) {
RSSetTextureCoords( pspoGroup, SHADOWTEXTURE, 1);
RSSetTextureCoords( pspoGroup, 0, 0);
RSSetTextureColors( pspoGroup, GF_TX0|GF_SHD);
RSRenderTEX_SHD( pspoGroup, 0);
bUsedMT = TRUE;
}
else if( ulGroupFlags & GF_TX0_TX1) {
RSSetTextureCoords( pspoGroup, 1, 1);
RSSetTextureCoords( pspoGroup, 0, 0);
RSSetTextureColors( pspoGroup, GF_TX0|GF_TX1);
RSRender2TEX( pspoGroup, 1);
bUsedMT = TRUE;
}
else if( ulGroupFlags & GF_TX0_TX2) {
RSSetTextureCoords( pspoGroup, 2, 1);
RSSetTextureCoords( pspoGroup, 0, 0);
RSSetTextureColors( pspoGroup, GF_TX0|GF_TX2);
RSRender2TEX( pspoGroup, 2);
bUsedMT = TRUE;
}
// triple texturing
else if( ulGroupFlags & GF_TX0_TX1_TX2) {
RSSetTextureCoords( pspoGroup, 2, 2);
RSSetTextureCoords( pspoGroup, 1, 1);
RSSetTextureCoords( pspoGroup, 0, 0);
RSSetTextureColors( pspoGroup, GF_TX0|GF_TX1|GF_TX2);
RSRender3TEX( pspoGroup);
bUsedMT = TRUE;
}
else if( ulGroupFlags & GF_TX0_TX1_SHD) {
RSSetTextureCoords( pspoGroup, SHADOWTEXTURE, 2);
RSSetTextureCoords( pspoGroup, 1, 1);
RSSetTextureCoords( pspoGroup, 0, 0);
RSSetTextureColors( pspoGroup, GF_TX0|GF_TX1|GF_SHD);
RSRender2TEX_SHD( pspoGroup, 1);
bUsedMT = TRUE;
}
else if( ulGroupFlags & GF_TX0_TX2_SHD) {
RSSetTextureCoords( pspoGroup, SHADOWTEXTURE, 2);
RSSetTextureCoords( pspoGroup, 2, 1);
RSSetTextureCoords( pspoGroup, 0, 0);
RSSetTextureColors( pspoGroup, GF_TX0|GF_TX2|GF_SHD);
RSRender2TEX_SHD( pspoGroup, 2);
bUsedMT = TRUE;
}
// quad texturing
else if( ulGroupFlags & GF_TX0_TX1_TX2_SHD) {
RSSetTextureCoords( pspoGroup, SHADOWTEXTURE, 3);
RSSetTextureCoords( pspoGroup, 2, 2);
RSSetTextureCoords( pspoGroup, 1, 1);
RSSetTextureCoords( pspoGroup, 0, 0);
RSSetTextureColors( pspoGroup, GF_TX0|GF_TX1|GF_TX2|GF_SHD);
RSRender3TEX_SHD( pspoGroup);
bUsedMT = TRUE;
}
// if something was drawn and alpha keying was used
if( bUsedMT && (ulGroupFlags&GF_KEY)) {
// force z-buffer test to equal and disable subsequent alpha tests
gfxDepthFunc( GFX_EQUAL);
gfxDisableAlphaTest();
}
// dual texturing leftover
if( ulGroupFlags & GF_TX2_SHD) {
RSSetTextureCoords( pspoGroup, SHADOWTEXTURE, 1);
RSSetTextureCoords( pspoGroup, 2, 0);
RSSetTextureColors( pspoGroup, GF_TX2|GF_SHD);
RSRenderTEX_SHD( pspoGroup, 2);
bUsedMT = TRUE;
}
ASSERT( !bUsedMT==!bUsesMT);
// if some multi-tex units were used
if( bUsesMT) {
// disable them now
for( INDEX i=1; i<_ctUsableTexUnits; i++) {
gfxSetTextureUnit(i);
gfxDisableTexture();
}
_iLastUnit = 0;
gfxSetTextureUnit(0);
}
// if group has color for first layer
if( ulGroupFlags&GF_FLAT)
{ // render colors
if( _bTranslucentPass) {
// set opacity to 50%
if( !wld_bRenderTextures) RSSetConstantColors( 0x3F3F3F7F);
else RSSetPolygonColors( pspoGroup, 0x7F);
gfxEnableBlend();
gfxBlendFunc( GFX_SRC_ALPHA, GFX_INV_SRC_ALPHA);
} else {
// set opacity to 100%
if( !wld_bRenderTextures) RSSetConstantColors( 0x7F7F7FFF);
else RSSetPolygonColors( pspoGroup, CT_OPAQUE);
gfxDisableBlend();
}
gfxDisableTexture();
DrawAllElements( pspoGroup);
}
// if group has texture for first layer
if( ulGroupFlags&GF_TX0) {
// render texture 0
RSSetTextureCoords( pspoGroup, 0, 0);
RSSetTextureColors( pspoGroup, GF_TX0);
RSRenderTEX( pspoGroup, 0);
// eventually prepare subsequent layers for transparency
if( ulGroupFlags & GF_KEY) {
gfxDepthFunc( GFX_EQUAL);
gfxDisableAlphaTest();
}
}
// if group has texture for second layer
if( ulGroupFlags & GF_TX1) {
// render texture 1
RSSetTextureCoords( pspoGroup, 1, 0);
RSSetTextureColors( pspoGroup, GF_TX1);
RSRenderTEX( pspoGroup, 1);
}
// if group has texture for third layer
if( ulGroupFlags & GF_TX2) {
// render texture 2
RSSetTextureCoords( pspoGroup, 2, 0);
RSSetTextureColors( pspoGroup, GF_TX2);
RSRenderTEX( pspoGroup, 2);
}
// if group has shadow
if( ulGroupFlags & GF_SHD) {
// render shadow
RSSetTextureCoords( pspoGroup, SHADOWTEXTURE, 0);
RSSetTextureColors( pspoGroup, GF_SHD);
RSRenderSHD( pspoGroup);
}
// if group has aftershadow texture for second layer
if( ulGroupFlags & GF_TA1) {
// render texture 1
RSSetTextureCoords( pspoGroup, 1, 0);
RSSetTextureColors( pspoGroup, GF_TX1);
RSRenderTEX( pspoGroup, 1);
}
// if group has aftershadow texture for third layer
if( ulGroupFlags & GF_TA2) {
// render texture 2
RSSetTextureCoords( pspoGroup, 2, 0);
RSSetTextureColors( pspoGroup, GF_TX2);
RSRenderTEX( pspoGroup, 2);
}
// if group has fog
if( ulGroupFlags & GF_FOG) {
// render fog
RSStartupFog();
RSSetConstantColors( _fog_fp.fp_colColor);
RSSetFogCoordinates( pspoGroup);
RSRenderFog( pspoGroup);
}
// if group has haze
if( ulGroupFlags & GF_HAZE) {
// render haze
RSStartupHaze();
RSSetConstantColors( _haze_hp.hp_colColor);
RSSetHazeCoordinates( pspoGroup);
RSRenderHaze( pspoGroup);
}
// reset depth function and alpha keying back
// (maybe it was altered for transparent polygon rendering)
gfxDepthFunc( GFX_LESS_EQUAL);
gfxDisableAlphaTest();
// if group has selection
if( ulGroupFlags & GF_SEL) {
// render selection
gfxEnableBlend();
gfxBlendFunc( GFX_SRC_ALPHA, GFX_INV_SRC_ALPHA);
RSSetConstantColors( _colSelection|128);
gfxDisableTexture();
DrawAllElements( pspoGroup);
}
// render triangle wireframe if needed
extern INDEX wld_bShowTriangles;
if( wld_bShowTriangles) {
gfxEnableBlend();
gfxBlendFunc( GFX_SRC_ALPHA, GFX_INV_SRC_ALPHA);
RSSetConstantColors( C_mdYELLOW|222);
gfxDisableTexture();
// must write to front in z-buffer
gfxPolygonMode(GFX_LINE);
gfxEnableDepthTest();
gfxEnableDepthWrite();
gfxDepthFunc(GFX_ALWAYS);
gfxDepthRange( 0,0);
DrawAllElements(pspoGroup);
gfxDepthRange( _ppr->pr_fDepthBufferNear, _ppr->pr_fDepthBufferFar);
gfxDepthFunc(GFX_LESS_EQUAL);
if( _bTranslucentPass) gfxDisableDepthWrite();
gfxPolygonMode(GFX_FILL);
}
// all done
gfxUnlockArrays();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERGROUPINTERNAL);
}
static void RSPrepare(void)
{
// set general params
gfxCullFace(GFX_NONE);
gfxEnableDepthTest();
gfxEnableClipping();
}
static void RSEnd(void)
{
// reset unusual gfx API parameters
gfxSetTextureUnit(0);
gfxSetTextureModulation(1);
}
void RenderScene( CDrawPort *pDP, ScenePolygon *pspoFirst, CAnyProjection3D &prProjection,
COLOR colSelection, BOOL bTranslucent)
{
// check API
eAPI = _pGfx->gl_eCurrentAPI;
#ifdef SE1_D3D
ASSERT( eAPI==GAT_OGL || eAPI==GAT_D3D || eAPI==GAT_NONE);
#else // SE1_D3D
#ifdef SE1_VULKAN
ASSERT(eAPI == GAT_OGL || eAPI == GAT_VK || eAPI == GAT_NONE);
#else
ASSERT(eAPI == GAT_OGL || eAPI == GAT_NONE);
#endif // SE1_VULKAN
#endif // SE1_D3D
if( eAPI!=GAT_OGL
#ifdef SE1_D3D
&& eAPI!=GAT_D3D
#endif // SE1_D3D
#ifdef SE1_VULKAN
&& eAPI!=GAT_VK
#endif // SE1_VULKAN
) return;
// some cvars cannot be altered in multiplayer mode!
if( _bMultiPlayer) {
shd_bShowFlats = FALSE;
gfx_bRenderWorld = TRUE;
wld_bRenderShadowMaps = TRUE;
wld_bRenderTextures = TRUE;
wld_bRenderDetailPolygons = TRUE;
wld_bShowDetailTextures = FALSE;
wld_bShowTriangles = FALSE;
}
// skip if not rendering world
if( !gfx_bRenderWorld) return;
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RENDERSCENE);
// remember input parameters
ASSERT( pDP != NULL);
_ppr = (CPerspectiveProjection3D*)&*prProjection;
_pDP = pDP;
_colSelection = colSelection;
_bTranslucentPass = bTranslucent;
// clamp detail textures LOD biasing
wld_iDetailRemovingBias = Clamp( wld_iDetailRemovingBias, -9L, +9L);
// set perspective projection
_pDP->SetProjection(prProjection);
// adjust multi-texturing support (for clip-plane emulation thru texture units)
extern BOOL GFX_bClipPlane; // WATCHOUT: set by 'SetProjection()' !
extern INDEX gap_iUseTextureUnits;
extern INDEX ogl_bAlternateClipPlane;
INDEX ctMaxUsableTexUnits = _pGfx->gl_ctTextureUnits;
if( eAPI==GAT_OGL && ogl_bAlternateClipPlane && GFX_bClipPlane && ctMaxUsableTexUnits>1) ctMaxUsableTexUnits--;
_ctUsableTexUnits = Clamp( gap_iUseTextureUnits, 1L, ctMaxUsableTexUnits);
// prepare
RSPrepare();
// turn depth buffer writing on or off
if( bTranslucent) gfxDisableDepthWrite();
else gfxEnableDepthWrite();
// remove all polygons with no triangles from the polygon list
ScenePolygon *pspoNonDummy;
RSRemoveDummyPolygons( pspoFirst, &pspoNonDummy);
// check that layers of all shadows are up to date
RSCheckLayersUpToDate(pspoNonDummy);
// bin polygons to groups by texture passes
RSBinToGroups(pspoNonDummy);
// for each group
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RS_RENDERGROUP);
ASSERT( _apspoGroups[0]==NULL); // zero group must always be empty
for( INDEX iGroup=1; iGroup<_ctGroupsCount; iGroup++) {
// get the group polygon list and render it if not empty
ScenePolygon *pspoGroup = _apspoGroups[iGroup];
if( pspoGroup!=NULL) RSRenderGroup( pspoGroup, iGroup, 0);
}
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RS_RENDERGROUP);
// all done
RSEnd();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RENDERSCENE);
}
// renders only scene z-buffer
void RenderSceneZOnly( CDrawPort *pDP, ScenePolygon *pspoFirst, CAnyProjection3D &prProjection)
{
if( _bMultiPlayer) gfx_bRenderWorld = 1;
if( !gfx_bRenderWorld) return;
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RENDERSCENE_ZONLY);
// set perspective projection
ASSERT(pDP!=NULL);
pDP->SetProjection(prProjection);
// prepare
RSPrepare();
// set for depth-only rendering
const ULONG ulCurrentColorMask = gfxGetColorMask();
gfxSetColorMask(NONE);
gfxEnableDepthTest();
gfxEnableDepthWrite();
gfxDisableTexture();
// make vertex coordinates for all polygons in the group and render the polygons
RSMakeVertexCoordinates(pspoFirst);
gfxSetVertexArray( &_avtxPass[0], _avtxPass.Count());
gfxDisableColorArray();
DrawAllElements(pspoFirst);
// restore color masking
gfxSetColorMask( ulCurrentColorMask);
RSEnd();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RENDERSCENE_ZONLY);
}
// renders flat background of the scene
void RenderSceneBackground(CDrawPort *pDP, COLOR col)
{
if( _bMultiPlayer) gfx_bRenderWorld = 1;
if( !gfx_bRenderWorld) return;
// set orthographic projection
ASSERT(pDP!=NULL);
pDP->SetOrtho();
_pfGfxProfile.StartTimer( CGfxProfile::PTI_RENDERSCENE_BCG);
// prepare
gfxEnableDepthTest();
gfxDisableDepthWrite();
gfxDisableBlend();
gfxDisableAlphaTest();
gfxDisableTexture();
gfxEnableClipping();
col = AdjustColor( col, _slTexHueShift, _slTexSaturation);
GFXColor glcol(col|CT_OPAQUE);
const INDEX iW = pDP->GetWidth();
const INDEX iH = pDP->GetHeight();
// set arrays
gfxResetArrays();
GFXVertex *pvtx = _avtxCommon.Push(4);
GFXTexCoord *ptex = _atexCommon.Push(4);
GFXColor *pcol = _acolCommon.Push(4);
pvtx[0].x = 0; pvtx[0].y = 0; pvtx[0].z = 1;
pvtx[1].x = 0; pvtx[1].y = iH; pvtx[1].z = 1;
pvtx[2].x = iW; pvtx[2].y = iH; pvtx[2].z = 1;
pvtx[3].x = iW; pvtx[3].y = 0; pvtx[3].z = 1;
pcol[0] = glcol;
pcol[1] = glcol;
pcol[2] = glcol;
pcol[3] = glcol;
// render
_pGfx->gl_ctWorldTriangles += 2;
gfxFlushQuads();
_pfGfxProfile.StopTimer( CGfxProfile::PTI_RENDERSCENE_BCG);
}
| 65,071
|
C++
|
.cpp
| 1,658
| 34.586852
| 117
| 0.694357
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,536,199
|
SvkMatrix.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Vulkan/SvkMatrix.cpp
|
/* Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "stdh.h"
#ifdef SE1_VULKAN
void Svk_MatCopy(float *dest, const float *src)
{
memcpy(dest, src, 16 * sizeof(float));
}
void Svk_MatSetIdentity(float *result)
{
memset(result, 0, 16 * sizeof(float));
result[0] = result[5] =
result[10] = result[15] = 1.0f;
}
void Svk_MatMultiply(float *result, const float *a, const float *b)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
result[i * 4 + j] =
a[i * 4 + 0] * b[0 * 4 + j] +
a[i * 4 + 1] * b[1 * 4 + j] +
a[i * 4 + 2] * b[2 * 4 + j] +
a[i * 4 + 3] * b[3 * 4 + j];
}
}
}
void Svk_MatFrustum(float *result, float fLeft, float fRight, float fBottom, float fTop, float fNear, float fFar)
{
const float fRpL = fRight + fLeft; const float fRmL = fRight - fLeft; const float fFpN = fFar + fNear;
const float fTpB = fTop + fBottom; const float fTmB = fTop - fBottom; const float fFmN = fFar - fNear;
const float f2Fm2N = 2.0f * fFar - 2.0f * fNear;
result[0 * 4 + 0] = 2.0f * fNear / fRmL;
result[0 * 4 + 1] = 0.0f;
result[0 * 4 + 2] = 0.0f;
result[0 * 4 + 3] = 0.0f;
result[1 * 4 + 0] = 0.0f;
result[1 * 4 + 1] = -2.0f * fNear / fTmB; // 2.0f * fNear / fTmB;
result[1 * 4 + 2] = 0.0f;
result[1 * 4 + 3] = 0.0f;
result[2 * 4 + 0] = fRpL / fRmL;
result[2 * 4 + 1] = -fTpB / fTmB; // fTpB / fTmB;
result[2 * 4 + 2] = -(2 * fFar - fNear) / f2Fm2N; // -fFar / fFmN;
result[2 * 4 + 3] = -1.0f;
result[3 * 4 + 0] = 0.0f;
result[3 * 4 + 1] = 0.0f;
result[3 * 4 + 2] = -fFar * fNear / f2Fm2N; // -fFar * fNear / fFmN;
result[3 * 4 + 3] = 0.0f;
}
void Svk_MatOrtho(float *result, float fLeft, float fRight, float fBottom, float fTop, float fNear, float fFar)
{
const float fRpL = fRight + fLeft; const float fRmL = fRight - fLeft; const float fFpN = fFar + fNear;
const float fTpB = fTop + fBottom; const float fTmB = fTop - fBottom; const float fFmN = fFar - fNear;
const float f2Fm2N = 2 * fFar - 2 * fNear;
result[0 * 4 + 0] = 2.0f / fRmL;
result[0 * 4 + 1] = 0.0f;
result[0 * 4 + 2] = 0.0f;
result[0 * 4 + 3] = 0.0f;
result[1 * 4 + 0] = 0.0f;
result[1 * 4 + 1] = -2.0f / fTmB; // 2.0f / fTmB;
result[1 * 4 + 2] = 0.0f;
result[1 * 4 + 3] = 0.0f;
result[2 * 4 + 0] = 0.0f;
result[2 * 4 + 1] = 0.0f;
result[2 * 4 + 2] = -1.0f / f2Fm2N; // -1.0f / fFmN;
result[2 * 4 + 3] = 0.0f;
result[3 * 4 + 0] = -fRpL / fRmL;
result[3 * 4 + 1] = fTpB / fTmB; // -fTpB / fTmB;
result[3 * 4 + 2] = (fFar - 2.0f * fNear) / f2Fm2N;// -fNear / fFmN;
result[3 * 4 + 3] = 1.0f;
}
#endif // SE1_VULKAN
| 3,270
|
C++
|
.cpp
| 82
| 36.890244
| 113
| 0.603535
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,200
|
SvkTextures.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Vulkan/SvkTextures.cpp
|
/* Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "stdh.h"
#include <Engine/Graphics/GfxLibrary.h>
#include <Engine/Graphics/Vulkan/SvkMain.h>
#ifdef SE1_VULKAN
void SvkMain::CreateTexturesDataStructure()
{
ASSERT(!gl_VkTextures.IsAllocated());
// make hash table tall to reduce linear searches
gl_VkTextures.New(512, 8);
gl_VkLastTextureId = 0;
// average texture size with mipmaps in bytes
const uint32_t AvgTextureSize = 256 * 256 * 4 * 4 / 3;
gl_VkImageMemPool = new SvkMemoryPool(gl_VkDevice, AvgTextureSize * 512);
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
gl_VkTexturesToDelete[i] = new CStaticStackArray<SvkTextureObject>();
gl_VkTexturesToDelete[i]->SetAllocationStep(2048);
}
}
void SvkMain::DestroyTexturesDataStructure()
{
delete gl_VkImageMemPool;
// destroy all texture objects; memory handles will be ignored
// as image memory pool is freed already
gl_VkTextures.Map(DestroyTextureObject);
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
gl_VkTexturesToDelete[i]->Clear();
}
gl_VkTextures.Clear();
gl_VkLastTextureId = 0;
}
void SvkMain::SetTexture(uint32_t textureUnit, uint32_t textureId, SvkSamplerFlags samplerFlags)
{
ASSERT(textureUnit >= 0 && textureUnit < GFX_MAXTEXUNITS);
SvkTextureObject *psto = gl_VkTextures.TryGet(textureId);
if (psto == nullptr)
{
return;
}
gl_VkActiveTextures[textureUnit] = textureId;
psto->sto_SamplerFlags = samplerFlags;
}
VkDescriptorSet SvkMain::GetTextureDescriptor(uint32_t textureId)
{
SvkTextureObject *psto = gl_VkTextures.TryGet(textureId);
if (psto == nullptr)
{
return VK_NULL_HANDLE;
}
SvkTextureObject &sto = *psto;
// if wasn't uploaded
if (sto.sto_Image == VK_NULL_HANDLE)
{
return VK_NULL_HANDLE;
}
VkDescriptorSet descSet;
// allocate new
VkDescriptorSetAllocateInfo setAllocInfo = {};
setAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
setAllocInfo.pNext = nullptr;
setAllocInfo.descriptorPool = gl_VkTextureDescPools[gl_VkCmdBufferCurrent];
setAllocInfo.descriptorSetCount = 1;
setAllocInfo.pSetLayouts = &gl_VkDescSetLayoutTexture;
VkResult r = vkAllocateDescriptorSets(gl_VkDevice, &setAllocInfo, &descSet);
VK_CHECKERROR(r);
// prepare info for desc set update
VkDescriptorImageInfo imageInfo = {};
imageInfo.imageLayout = sto.sto_Layout;
imageInfo.imageView = sto.sto_ImageView;
imageInfo.sampler = GetSampler(sto.sto_SamplerFlags);
VkWriteDescriptorSet write = {};
write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write.dstSet = descSet;
write.dstBinding = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
write.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(gl_VkDevice, 1, &write, 0, nullptr);
return descSet;
}
void SvkMain::AddTextureToDeletion(uint32_t textureId)
{
SvkTextureObject *sto = gl_VkTextures.TryGet(textureId);
if (sto != nullptr)
{
gl_VkTexturesToDelete[gl_VkCmdBufferCurrent]->Push() = *sto;
gl_VkTextures.Delete(textureId);
}
}
uint32_t SvkMain::GetTexturePixCount(uint32_t textureId)
{
SvkTextureObject *psto = gl_VkTextures.TryGet(textureId);
if (psto == nullptr)
{
return 0;
}
return psto->sto_Width * psto->sto_Height;
}
void SvkMain::FreeDeletedTextures(uint32_t cmdBufferIndex)
{
auto &toDelete = *(gl_VkTexturesToDelete[cmdBufferIndex]);
for (INDEX i = 0; i < toDelete.Count(); i++)
{
SvkTextureObject &sto = toDelete[i];
// only if was uploaded
if (sto.sto_Image != VK_NULL_HANDLE)
{
// free image memory from pool
gl_VkImageMemPool->Free(sto.sto_MemoryHandle);
// free image, image view and desc set, if exist
DestroyTextureObject(sto);
}
}
toDelete.PopAll();
}
void SvkMain::DestroyTextureObject(SvkTextureObject &sto)
{
// if was uploaded
if (sto.sto_Image != VK_NULL_HANDLE)
{
vkDestroyImage(sto.sto_VkDevice, sto.sto_Image, nullptr);
vkDestroyImageView(sto.sto_VkDevice, sto.sto_ImageView, nullptr);
}
sto.Reset();
}
uint32_t SvkMain::CreateTexture()
{
uint32_t textureId = gl_VkLastTextureId++;
return CreateTexture(textureId);
}
uint32_t SvkMain::CreateTexture(uint32_t textureId)
{
SvkTextureObject sto = {};
sto.sto_VkDevice = gl_VkDevice;
gl_VkTextures.Add(textureId, sto);
return textureId;
}
void SvkMain::InitTexture32Bit(
uint32_t &textureId, VkFormat format, void *textureData,
VkExtent2D *mipLevels, uint32_t mipLevelsCount, bool onlyUpdate)
{
const uint32_t PixelSize = 4;
const uint32_t MaxMipLevelsCount = 32;
VkResult r;
SvkTextureObject *psto = gl_VkTextures.TryGet(textureId);
ASSERT(psto != nullptr);
SvkTextureObject &sto = *psto;
ASSERT(mipLevelsCount > 0 && mipLevelsCount < MaxMipLevelsCount);
if (!onlyUpdate && sto.sto_Image != VK_NULL_HANDLE)
{
onlyUpdate = true;
}
// if texture is already initialized, it can be only updated
ASSERT(sto.sto_Image == VK_NULL_HANDLE || (sto.sto_Image != VK_NULL_HANDLE && onlyUpdate));
if (onlyUpdate && (mipLevels[0].width != sto.sto_Width || mipLevels[0].height != sto.sto_Height))
{
// safely delete and create new with the same id
AddTextureToDeletion(textureId);
CreateTexture(textureId);
sto = gl_VkTextures.Get(textureId);
onlyUpdate = false;
}
sto.sto_Format = format;
sto.sto_Layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
sto.sto_Width = mipLevels[0].width;
sto.sto_Height = mipLevels[0].height;
// size of texture with all mipmaps
uint32_t textureBufferSize = 0;
for (uint32_t i = 0; i < mipLevelsCount; i++)
{
textureBufferSize += mipLevels[i].width * mipLevels[i].height * PixelSize;
}
// TODO: common staging memory
// -----
VkBuffer stagingBuffer;
VkDeviceMemory stagingMemory;
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = textureBufferSize;
bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
r = vkCreateBuffer(gl_VkDevice, &bufferInfo, nullptr, &stagingBuffer);
VK_CHECKERROR(r);
VkMemoryRequirements stagingMemoryReq;
vkGetBufferMemoryRequirements(gl_VkDevice, stagingBuffer, &stagingMemoryReq);
VkMemoryAllocateInfo stagingAllocInfo = {};
stagingAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
stagingAllocInfo.allocationSize = stagingMemoryReq.size;
stagingAllocInfo.memoryTypeIndex = GetMemoryTypeIndex(
stagingMemoryReq.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
r = vkAllocateMemory(gl_VkDevice, &stagingAllocInfo, nullptr, &stagingMemory);
VK_CHECKERROR(r);
r = vkBindBufferMemory(gl_VkDevice, stagingBuffer, stagingMemory, 0);
VK_CHECKERROR(r);
void *mapped;
r = vkMapMemory(gl_VkDevice, stagingMemory, 0, stagingMemoryReq.size, 0, &mapped);
VK_CHECKERROR(r);
memcpy(mapped, textureData, textureBufferSize);
vkUnmapMemory(gl_VkDevice, stagingMemory);
// -----
if (!onlyUpdate)
{
// create image
VkImageCreateInfo imageInfo = {};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.format = format;
imageInfo.extent.width = mipLevels[0].width;
imageInfo.extent.height = mipLevels[0].height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevelsCount;
imageInfo.arrayLayers = 1;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
// for shaders and loading into
imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
r = vkCreateImage(gl_VkDevice, &imageInfo, nullptr, &sto.sto_Image);
VK_CHECKERROR(r);
VkMemoryRequirements imageMemoryReq;
vkGetImageMemoryRequirements(gl_VkDevice, sto.sto_Image, &imageMemoryReq);
// allocate memory for image
VkMemoryAllocateInfo imageAllocInfo = {};
imageAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
imageAllocInfo.allocationSize = imageMemoryReq.size % imageMemoryReq.alignment == 0 ?
imageMemoryReq.size : imageMemoryReq.size + imageMemoryReq.alignment - imageMemoryReq.size % imageMemoryReq.alignment;
imageAllocInfo.memoryTypeIndex = GetMemoryTypeIndex(imageMemoryReq.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
uint32_t imageMemoryOffset;
sto.sto_MemoryHandle = gl_VkImageMemPool->Allocate(imageAllocInfo, imageMemoryReq, sto.sto_Memory, imageMemoryOffset);
VK_CHECKERROR(r);
r = vkBindImageMemory(gl_VkDevice, sto.sto_Image, sto.sto_Memory, imageMemoryOffset);
VK_CHECKERROR(r);
}
// prepare regions for copying
VkBufferImageCopy bufferCopyRegions[MaxMipLevelsCount];
memset(bufferCopyRegions, 0, mipLevelsCount * sizeof(VkBufferImageCopy));
uint32_t regionOffset = 0;
for (uint32_t i = 0; i < mipLevelsCount; i++)
{
VkBufferImageCopy ®ion = bufferCopyRegions[i];
region.bufferOffset = regionOffset;
region.imageExtent.width = mipLevels[i].width;
region.imageExtent.height = mipLevels[i].height;
region.imageExtent.depth = 1;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = i;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
regionOffset += mipLevels[i].width * mipLevels[i].height * PixelSize;
}
// TODO: common staging memory
// -----
VkCommandBufferAllocateInfo cmdInfo = {};
cmdInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmdInfo.commandPool = gl_VkCmdPools[gl_VkCmdBufferCurrent];
cmdInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmdInfo.commandBufferCount = 1;
VkCommandBuffer cmdBuffer = gl_VkCmdBuffers[gl_VkCmdBufferCurrent + gl_VkMaxCmdBufferCount];
VkCommandBufferBeginInfo cmdBeginInfo = {};
cmdBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
cmdBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
r = vkBeginCommandBuffer(cmdBuffer, &cmdBeginInfo);
VK_CHECKERROR(r);
// -----
// layout transition
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = sto.sto_Image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevelsCount;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
// prepare for transfer
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
vkCmdPipelineBarrier(
cmdBuffer,
VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, // for copying
0,
0, nullptr,
0, nullptr,
1, &barrier);
// copy with mipmaps
vkCmdCopyBufferToImage(
cmdBuffer,
stagingBuffer, // source
sto.sto_Image, // dest
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // image layout
mipLevelsCount,
bufferCopyRegions);
// prepare for reading in shaders
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
vkCmdPipelineBarrier(
cmdBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0, nullptr,
0, nullptr,
1, &barrier);
// TODO: common staging memory
// -----
r = vkEndCommandBuffer(cmdBuffer);
VK_CHECKERROR(r);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &cmdBuffer;
r = vkQueueSubmit(gl_VkQueueGraphics, 1, &submitInfo, VK_NULL_HANDLE);
VK_CHECKERROR(r);
r = vkQueueWaitIdle(gl_VkQueueGraphics);
VK_CHECKERROR(r);
vkResetCommandBuffer(cmdBuffer, VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
vkFreeMemory(gl_VkDevice, stagingMemory, nullptr);
vkDestroyBuffer(gl_VkDevice, stagingBuffer, nullptr);
// -----
VkImageViewCreateInfo viewInfo = {};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevelsCount;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
viewInfo.image = sto.sto_Image;
r = vkCreateImageView(gl_VkDevice, &viewInfo, nullptr, &sto.sto_ImageView);
VK_CHECKERROR(r);
ASSERT(sto.sto_Image != VK_NULL_HANDLE);
}
#endif
| 13,796
|
C++
|
.cpp
| 354
| 35.415254
| 124
| 0.752999
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,201
|
SvkQueries.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Vulkan/SvkQueries.cpp
|
/* Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "stdh.h"
#include <Engine/Graphics/Vulkan/SvkMain.h>
#ifdef SE1_VULKAN
void SvkMain::InitOcclusionQuerying()
{
// create query pool
VkQueryPoolCreateInfo queryPoolInfo = {};
queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
queryPoolInfo.queryType = VK_QUERY_TYPE_OCCLUSION;
queryPoolInfo.queryCount = SVK_OCCLUSION_QUERIES_MAX;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
VkResult r = vkCreateQueryPool(gl_VkDevice, &queryPoolInfo, nullptr, &gl_VkOcclusionQueryPools[i]);
VK_CHECKERROR(r);
}
CreateOcclusionPipeline();
}
void SvkMain::DestroyOcclusionQuerying()
{
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
vkDestroyQueryPool(gl_VkDevice, gl_VkOcclusionQueryPools[i], nullptr);
}
vkDestroyPipeline(gl_VkDevice, gl_VkPipelineOcclusion, nullptr);
}
void SvkMain::ResetOcclusionQueries(VkCommandBuffer cmd, uint32_t cmdIndex)
{
ASSERT(gl_VkCmdIsRecording);
gl_VkOcclusionQueryLast[cmdIndex] = 0;
vkCmdResetQueryPool(cmd, gl_VkOcclusionQueryPools[cmdIndex], 0, SVK_OCCLUSION_QUERIES_MAX);
}
uint32_t SvkMain::CreateOcclusionQuery(float fromx, float fromy, float tox, float toy, float z)
{
ASSERT(gl_VkCmdIsRecording);
ASSERT(fromx <= tox && fromy <= toy);
uint32_t queryId = gl_VkOcclusionQueryLast[gl_VkCmdBufferCurrent];
gl_VkOcclusionQueryLast[gl_VkCmdBufferCurrent]++;
// create data
float verts[] = {
fromx, fromy, z, 1,
fromx, toy, z, 1,
tox, toy, z, 1,
tox, fromy, z, 1
};
uint32_t indices[] = {
0, 1, 2,
2, 3, 0
};
// get buffers to draw
SvkDynamicBuffer vertexBuffer, indexBuffer;
GetVertexBuffer(sizeof(verts), vertexBuffer);
GetIndexBuffer(sizeof(indices), indexBuffer);
memcpy(vertexBuffer.sdb_Data, verts, sizeof(verts));
memcpy(indexBuffer.sdb_Data, indices, sizeof(indices));
VkCommandBuffer cmd = gl_VkCmdBuffers[gl_VkCmdBufferCurrent];
// begin new query
vkCmdBeginQuery(cmd, gl_VkOcclusionQueryPools[gl_VkCmdBufferCurrent], queryId, 0);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, gl_VkPipelineOcclusion);
// reset to prevent usage of this pipeline for a next object
gl_VkPreviousPipeline = nullptr;
vkCmdBindVertexBuffers(cmd, 0, 1, &vertexBuffer.sdb_Buffer, &vertexBuffer.sdb_CurrentOffset);
vkCmdBindIndexBuffer(cmd, indexBuffer.sdb_Buffer, indexBuffer.sdb_CurrentOffset, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(cmd, 6, 1, 0, 0, 0);
vkCmdEndQuery(cmd, gl_VkOcclusionQueryPools[gl_VkCmdBufferCurrent], queryId);
return queryId;
}
void SvkMain::GetOcclusionResults(uint32_t firstQuery, uint32_t queryCount, uint32_t *results)
{
VkResult r = vkGetQueryPoolResults(
gl_VkDevice, gl_VkOcclusionQueryPools[gl_VkCmdBufferCurrent],
firstQuery, queryCount,
queryCount * sizeof(uint32_t), results, sizeof(uint32_t),
VK_QUERY_RESULT_PARTIAL_BIT);
if (r != VK_NOT_READY)
{
VK_CHECKERROR(r);
}
}
#endif
| 3,607
|
C++
|
.cpp
| 90
| 37.133333
| 105
| 0.767622
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,202
|
SvkMemoryPool.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Vulkan/SvkMemoryPool.cpp
|
#include "StdH.h"
#include "SvkMemoryPool.h"
SvkMemoryPool::SvkMemoryPool(VkDevice device, uint32_t preferredSize)
{
smp_VkDevice = device;
smp_PreferredSize = preferredSize;
smp_BlockCount = 0;
smp_BlockSize = 0;
smp_VkMemory = VK_NULL_HANDLE;
smp_pNext = nullptr;
smp_FreeListHeadIndex = 0;
smp_AllocationCount = 0;
smp_VkMemoryTypeIndex = 0;
smp_HandleLastIndex = 0;
smp_NodeLastIndex = 0;
}
SvkMemoryPool::~SvkMemoryPool()
{
ASSERT(smp_VkDevice != VK_NULL_HANDLE);
if (smp_VkMemory != VK_NULL_HANDLE)
{
vkFreeMemory(smp_VkDevice, smp_VkMemory, nullptr);
}
if (smp_pNext != nullptr)
{
delete smp_pNext;
}
smp_Nodes.Clear();
smp_Handles.Clear();
smp_PreferredSize = 0;
smp_FreeListHeadIndex = 0;
smp_BlockCount = 0;
smp_BlockSize = 0;
smp_AllocationCount = 0;
smp_VkMemoryTypeIndex = 0;
smp_HandleLastIndex = 0;
smp_NodeLastIndex = 0;
}
void SvkMemoryPool::Init(uint32_t memoryTypeIndex, uint32_t alignment)
{
ASSERT(smp_VkMemory == VK_NULL_HANDLE);
smp_BlockSize = alignment;
smp_BlockCount = smp_PreferredSize / alignment + 1;
smp_VkMemoryTypeIndex = memoryTypeIndex;
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = smp_BlockCount * smp_BlockSize;
allocInfo.memoryTypeIndex = smp_VkMemoryTypeIndex;
VkResult r = vkAllocateMemory(smp_VkDevice, &allocInfo, nullptr, &smp_VkMemory);
ASSERT(r == VK_SUCCESS);
// allocate max node amount which is the same as block count
smp_Nodes.New(smp_BlockCount);
smp_FreeListHeadIndex = AddNode();
smp_Nodes[smp_FreeListHeadIndex].blockCount = smp_BlockCount;
smp_Nodes[smp_FreeListHeadIndex].blockIndex = 0;
smp_Nodes[smp_FreeListHeadIndex].nextNodeIndex = -1;
}
int32_t SvkMemoryPool::AddNode()
{
if (smp_RemovedIndices.Count() > 0)
{
return smp_RemovedIndices.Pop();
}
// smp_Nodes count is the same as smp_BlockCount
ASSERT(smp_NodeLastIndex + 1 < smp_Nodes.Count());
return smp_NodeLastIndex++;
}
void SvkMemoryPool::RemoveNode(int32_t removed)
{
smp_RemovedIndices.Push() = removed;
}
uint32_t SvkMemoryPool::Allocate(VkMemoryAllocateInfo allocInfo, VkMemoryRequirements memReqs, VkDeviceMemory &outMemory, uint32_t &outOffset)
{
smp_AllocationCount++;
ASSERT(allocInfo.sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
ASSERT(allocInfo.allocationSize > 0);
ASSERT(allocInfo.allocationSize % memReqs.alignment == 0);
if (smp_VkMemory == VK_NULL_HANDLE)
{
Init(allocInfo.memoryTypeIndex, memReqs.alignment);
}
ASSERT(smp_BlockSize > memReqs.alignment ?
smp_BlockSize % memReqs.alignment == 0 :
memReqs.alignment % smp_BlockSize == 0);
// align size
uint32_t allocSize = allocInfo.allocationSize;
uint32_t alignmentBlockCount = 0;
const uint32_t plAlgn = smp_BlockSize;
const uint32_t rqAlgn = memReqs.alignment;
if (plAlgn >= rqAlgn)
{
ASSERT(plAlgn % rqAlgn == 0);
}
else
{
ASSERT(rqAlgn % plAlgn == 0);
alignmentBlockCount = rqAlgn / plAlgn;
}
// make sure that memory types are same
ASSERTMSG(smp_VkMemoryTypeIndex == allocInfo.memoryTypeIndex, "Create new SvkMemoryPool with another memory type index");
// check sizes
ASSERT(smp_BlockCount * smp_BlockSize >= allocSize);
uint32_t reqBlockCount = allocSize / smp_BlockSize + (allocSize % smp_BlockSize > 0 ? 1 : 0);
int32_t prevNode = -1;
int32_t curNode = smp_FreeListHeadIndex;
while (curNode != -1)
{
// find first suitable
if (smp_Nodes[curNode].blockCount >= reqBlockCount)
{
if (alignmentBlockCount > 0)
{
uint32_t nextAlignment = smp_Nodes[curNode].blockIndex / alignmentBlockCount
+ (smp_Nodes[curNode].blockIndex % alignmentBlockCount > 0 ? 1 : 0);
nextAlignment *= alignmentBlockCount;
uint32_t blocksToAlign = nextAlignment - smp_Nodes[curNode].blockIndex;
if (blocksToAlign > 0)
{
uint32_t alignedBlockCount = smp_Nodes[curNode].blockCount - blocksToAlign;
if (alignedBlockCount >= reqBlockCount)
{
// if aligned is suitable, then add new node after cur
int32_t alignedNode = AddNode();
smp_Nodes[alignedNode].blockIndex = nextAlignment;
smp_Nodes[alignedNode].blockCount = alignedBlockCount;
smp_Nodes[alignedNode].nextNodeIndex = smp_Nodes[curNode].nextNodeIndex;
smp_Nodes[curNode].nextNodeIndex = alignedNode;
smp_Nodes[curNode].blockCount = blocksToAlign;
prevNode = curNode;
curNode = alignedNode;
}
else
{
prevNode = curNode;
curNode = smp_Nodes[curNode].nextNodeIndex;
continue;
}
}
}
uint32_t diff = smp_Nodes[curNode].blockCount - reqBlockCount;
AllocHandle &handle = smp_Handles.Push();
handle.id = smp_HandleLastIndex++;
handle.blockIndex = smp_Nodes[curNode].blockIndex;
handle.blockCount = reqBlockCount;
outMemory = smp_VkMemory;
outOffset = smp_Nodes[curNode].blockIndex * smp_BlockSize;
if (diff != 0)
{
// shift and reduce node's size
smp_Nodes[curNode].blockIndex += reqBlockCount;
smp_Nodes[curNode].blockCount -= reqBlockCount;
}
// if can merge next free range with previous one
else
{
if (prevNode == -1 && smp_Nodes[curNode].nextNodeIndex == -1)
{
// if only head, destroy it
ASSERT(curNode == smp_FreeListHeadIndex);
smp_FreeListHeadIndex = -1;
}
else if (prevNode != -1 && smp_Nodes[curNode].nextNodeIndex == -1)
{
// if there is prev, but not next
smp_Nodes[prevNode].nextNodeIndex = -1;
}
else if (prevNode == -1 && smp_Nodes[curNode].nextNodeIndex != -1)
{
// if there is next, but not prev; then it's head
ASSERT(curNode == smp_FreeListHeadIndex);
smp_FreeListHeadIndex = smp_Nodes[curNode].nextNodeIndex;
}
else
{
// if there are prev and next, skip current
smp_Nodes[prevNode].nextNodeIndex = smp_Nodes[curNode].nextNodeIndex;
}
RemoveNode(curNode);
}
return handle.id;
}
prevNode = curNode;
curNode = smp_Nodes[curNode].nextNodeIndex;
}
ASSERTALWAYS("Increase SvkMemoryPool block count or block size");
// TODO: memory pool chain
// if free list is empty or none is found, create new and slightly bigger
//smp_pNext = new SvkMemoryPool(smp_VkDevice, smp_BlockSize, (uint32_t)(smp_BlockCount * 1.25f));
//?allocInfo.allocationSize = allocSize;
//return smp_pNext->Allocate(allocInfo, outMemory, outOffset);
return 0;
}
#ifndef NDEBUG
struct DebugFreeListNode
{
int32_t nextNodeIndex;
uint32_t blockIndex;
uint32_t blockCount;
};
void CheckConsistency(int32_t smp_FreeListHeadIndex, void *psmp_Nodes)
{
CStaticArray<DebugFreeListNode> &smp_Nodes = *((CStaticArray<DebugFreeListNode>*)psmp_Nodes);
int32_t prevNodeD = -1;
int32_t curNodeD = smp_FreeListHeadIndex;
while (curNodeD != -1)
{
ASSERT(smp_Nodes[curNodeD].blockCount != 0);
if (prevNodeD != -1)
{
ASSERT(smp_Nodes[prevNodeD].blockIndex + smp_Nodes[prevNodeD].blockCount <= smp_Nodes[curNodeD].blockIndex);
}
prevNodeD = curNodeD;
curNodeD = smp_Nodes[curNodeD].nextNodeIndex;
}
}
#endif // !NDEBUG
void SvkMemoryPool::Free(uint32_t handle)
{
smp_AllocationCount--;
bool found = false;
uint32_t blockIndex, blockCount;
for (INDEX i = 0; i < smp_Handles.Count(); i++)
{
if (smp_Handles[i].id == handle)
{
blockIndex = smp_Handles[i].blockIndex;
blockCount = smp_Handles[i].blockCount;
// remove handle: just replace this with last and pop to remove duplicate
smp_Handles[i] = smp_Handles[smp_Handles.Count() - 1];
smp_Handles.Pop();
found = true;
break;
}
}
ASSERT(found);
// if there is no head, then just create it
if (smp_FreeListHeadIndex == -1)
{
smp_FreeListHeadIndex = AddNode();
smp_Nodes[smp_FreeListHeadIndex].blockCount = blockCount;
smp_Nodes[smp_FreeListHeadIndex].blockIndex = blockIndex;
smp_Nodes[smp_FreeListHeadIndex].nextNodeIndex = -1;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
return;
}
// find node that has block index less than given
int32_t prevNode = -1;
int32_t curNode = smp_FreeListHeadIndex;
while (curNode != -1)
{
// don't free already freed
ASSERT(smp_Nodes[curNode].blockIndex != blockIndex);
if (smp_Nodes[curNode].blockIndex > blockIndex)
{
break;
}
prevNode = curNode;
curNode = smp_Nodes[curNode].nextNodeIndex;
}
// if last is one that must be added to free list
if (curNode == -1)
{
ASSERT(prevNode != -1);
// if can merge with previous
if (smp_Nodes[prevNode].blockIndex + smp_Nodes[prevNode].blockCount == blockIndex)
{
smp_Nodes[prevNode].blockCount += blockCount;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
return;
}
else
{
// otherwise, create new block and link prev with it
int32_t newNode = AddNode();
smp_Nodes[newNode].blockIndex = blockIndex;
smp_Nodes[newNode].blockCount = blockCount;
smp_Nodes[newNode].nextNodeIndex = -1;
smp_Nodes[prevNode].nextNodeIndex = newNode;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
return;
}
}
ASSERT(blockIndex + blockCount <= smp_Nodes[curNode].blockIndex);
// if head is one that must be added to free list
if (prevNode == -1)
{
ASSERT(curNode == smp_FreeListHeadIndex);
// check if can merge
if (blockIndex + blockCount == smp_Nodes[curNode].blockIndex)
{
// then update existing
smp_Nodes[curNode].blockIndex = blockIndex;
smp_Nodes[curNode].blockCount += blockCount;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
}
else
{
// new separate node is required, then update head
smp_FreeListHeadIndex = AddNode();
smp_Nodes[smp_FreeListHeadIndex].blockIndex = blockIndex;
smp_Nodes[smp_FreeListHeadIndex].blockCount = blockCount;
smp_Nodes[smp_FreeListHeadIndex].nextNodeIndex = curNode;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
}
}
else
{
// if not head and not last;
// check if can merge with prev or next (relatively to new node)
bool withPrev = smp_Nodes[prevNode].blockIndex + smp_Nodes[prevNode].blockCount == blockIndex;
bool withNext = blockIndex + blockCount == smp_Nodes[curNode].blockIndex;
if (withPrev && withNext)
{
RemoveNode(curNode);
smp_Nodes[prevNode].blockCount += blockCount + smp_Nodes[curNode].blockCount;
smp_Nodes[prevNode].nextNodeIndex = smp_Nodes[curNode].nextNodeIndex;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
}
else if (withPrev)
{
smp_Nodes[prevNode].blockCount += blockCount;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
}
else if (withNext)
{
smp_Nodes[curNode].blockIndex = blockIndex;
smp_Nodes[curNode].blockCount += blockCount;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
}
else
{
int32_t newNode = AddNode();
smp_Nodes[newNode].blockIndex = blockIndex;
smp_Nodes[newNode].blockCount = blockCount;
smp_Nodes[newNode].nextNodeIndex = curNode;
smp_Nodes[prevNode].nextNodeIndex = newNode;
#ifndef NDEBUG
CheckConsistency(smp_FreeListHeadIndex, &smp_Nodes);
#endif // !NDEBUG
}
}
}
| 12,014
|
C++
|
.cpp
| 358
| 28.416201
| 142
| 0.684374
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,203
|
SvkDynamicBuffers.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Vulkan/SvkDynamicBuffers.cpp
|
/* Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "StdH.h"
#include <Engine/Graphics/Vulkan/SvkMain.h>
#ifdef SE1_VULKAN
void SvkMain::InitDynamicBuffers()
{
#ifndef NDEBUG
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
ASSERT(gl_VkDynamicVBGlobal.sdg_CurrentDynamicBufferSize == 0);
ASSERT(gl_VkDynamicIBGlobal.sdg_CurrentDynamicBufferSize == 0);
ASSERT(gl_VkDynamicUBGlobal.sdg_CurrentDynamicBufferSize == 0);
}
#endif // !NDEBUG
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
gl_VkDynamicToDelete[i] = new CStaticStackArray<SvkDBufferToDelete>();
gl_VkDynamicToDelete[i]->SetAllocationStep(256);
}
InitDynamicVertexBuffers(SVK_DYNAMIC_VERTEX_BUFFER_START_SIZE);
InitDynamicIndexBuffers(SVK_DYNAMIC_INDEX_BUFFER_START_SIZE);
InitDynamicUniformBuffers(SVK_DYNAMIC_UNIFORM_BUFFER_START_SIZE);
}
void SvkMain::InitDynamicVertexBuffers(uint32_t newSize)
{
// ASSERT(newSize < gl_VkPhProperties.limits.);
gl_VkDynamicVBGlobal.sdg_CurrentDynamicBufferSize = newSize;
InitDynamicBuffer(gl_VkDynamicVBGlobal, gl_VkDynamicVB, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
#ifndef NDEBUG
CPrintF("SVK: Allocated dynamic vertex buffer: %u MB.\n", gl_VkDynamicVBGlobal.sdg_CurrentDynamicBufferSize / 1024 / 1024);
#endif // !NDEBUG
}
void SvkMain::InitDynamicIndexBuffers(uint32_t newSize)
{
// ASSERT(newSize < gl_VkPhProperties.limits.);
gl_VkDynamicIBGlobal.sdg_CurrentDynamicBufferSize = newSize;
InitDynamicBuffer(gl_VkDynamicIBGlobal, gl_VkDynamicIB, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
#ifndef NDEBUG
CPrintF("SVK: Allocated dynamic index buffer: %u MB.\n", gl_VkDynamicIBGlobal.sdg_CurrentDynamicBufferSize / 1024 / 1024);
#endif // !NDEBUG
}
void SvkMain::InitDynamicUniformBuffers(uint32_t newSize)
{
// ASSERT(newSize < gl_VkPhProperties.limits.);
SvkDynamicBuffer uniformDynBuffers[gl_VkMaxCmdBufferCount];
gl_VkDynamicUBGlobal.sdg_CurrentDynamicBufferSize = newSize;
InitDynamicBuffer(gl_VkDynamicUBGlobal, uniformDynBuffers, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
#ifndef NDEBUG
CPrintF("SVK: Allocated dynamic uniform buffer: %u KB.\n", gl_VkDynamicUBGlobal.sdg_CurrentDynamicBufferSize / 1024);
#endif // !NDEBUG
// allocate descriptor sets for uniform buffers
VkDescriptorSetAllocateInfo descAllocInfo = {};
descAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
descAllocInfo.descriptorPool = gl_VkUniformDescPool;
descAllocInfo.descriptorSetCount = 1;
descAllocInfo.pSetLayouts = &gl_VkDescriptorSetLayout;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
VkDescriptorSet descSet;
vkAllocateDescriptorSets(gl_VkDevice, &descAllocInfo, &descSet);
VkDescriptorBufferInfo bufferInfo = {};
bufferInfo.buffer = uniformDynBuffers[i].sdb_Buffer;
// start in uniform buffer is 0
bufferInfo.offset = 0;
// max size for uniform data
bufferInfo.range = SVK_DYNAMIC_UNIFORM_MAX_ALLOC_SIZE;
// update descriptor set
VkWriteDescriptorSet write = {};
write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
write.dstSet = descSet;
write.dstBinding = 0;
write.dstArrayElement = 0;
write.descriptorCount = 1;
write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
write.pBufferInfo = &bufferInfo;
vkUpdateDescriptorSets(gl_VkDevice, 1, &write, 0, nullptr);
gl_VkDynamicUB[i].sdb_Buffer = uniformDynBuffers[i].sdb_Buffer;
gl_VkDynamicUB[i].sdb_CurrentOffset = uniformDynBuffers[i].sdb_CurrentOffset;
gl_VkDynamicUB[i].sdb_Data = uniformDynBuffers[i].sdb_Data;
gl_VkDynamicUB[i].sdu_DescriptorSet = descSet;
}
}
void SvkMain::InitDynamicBuffer(SvkDynamicBufferGlobal &dynBufferGlobal, SvkDynamicBuffer *buffers, VkBufferUsageFlags usage)
{
VkResult r;
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = dynBufferGlobal.sdg_CurrentDynamicBufferSize;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
buffers[i].sdb_CurrentOffset = 0;
r = vkCreateBuffer(gl_VkDevice, &bufferInfo, nullptr, &buffers[i].sdb_Buffer);
VK_CHECKERROR(r);
}
VkMemoryRequirements memReqs;
vkGetBufferMemoryRequirements(gl_VkDevice, buffers[0].sdb_Buffer, &memReqs);
uint32_t mod = memReqs.size % memReqs.alignment;
uint32_t alignedSize = mod == 0 ?
memReqs.size :
memReqs.size + memReqs.alignment - mod;
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = alignedSize * gl_VkMaxCmdBufferCount;
// VK_MEMORY_PROPERTY_HOST_COHERENT_BIT is not used, as buffers will be flushed maually
allocInfo.memoryTypeIndex = GetMemoryTypeIndex(memReqs.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
r = vkAllocateMemory(gl_VkDevice, &allocInfo, nullptr, &dynBufferGlobal.sdg_DynamicBufferMemory);
VK_CHECKERROR(r);
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
uint32_t offset = i * alignedSize;
r = vkBindBufferMemory(gl_VkDevice, buffers[i].sdb_Buffer, dynBufferGlobal.sdg_DynamicBufferMemory, offset);
VK_CHECKERROR(r);
}
void *data;
r = vkMapMemory(gl_VkDevice, dynBufferGlobal.sdg_DynamicBufferMemory,
0, alignedSize * gl_VkMaxCmdBufferCount, 0, &data);
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
uint32_t offset = i * alignedSize;
buffers[i].sdb_Data = (UBYTE *)data + offset;
}
}
void SvkMain::AddDynamicBufferToDeletion(SvkDynamicBufferGlobal &dynBufferGlobal, SvkDynamicBuffer *buffers)
{
auto &toDelete = gl_VkDynamicToDelete[gl_VkCmdBufferCurrent]->Push();
toDelete.sdd_Memory = dynBufferGlobal.sdg_DynamicBufferMemory;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
toDelete.sdd_Buffers[i] = buffers[i].sdb_Buffer;
toDelete.sdd_DescriptorSets[i] = VK_NULL_HANDLE;
}
}
void SvkMain::AddDynamicUniformToDeletion(SvkDynamicBufferGlobal &dynBufferGlobal, SvkDynamicUniform *buffers)
{
auto &toDelete = gl_VkDynamicToDelete[gl_VkCmdBufferCurrent]->Push();
toDelete.sdd_Memory = dynBufferGlobal.sdg_DynamicBufferMemory;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
toDelete.sdd_Buffers[i] = buffers[i].sdb_Buffer;
toDelete.sdd_DescriptorSets[i] = buffers[i].sdu_DescriptorSet;
}
}
void SvkMain::ClearCurrentDynamicOffsets(uint32_t cmdBufferIndex)
{
gl_VkDynamicVB[cmdBufferIndex].sdb_CurrentOffset = 0;
gl_VkDynamicIB[cmdBufferIndex].sdb_CurrentOffset = 0;
gl_VkDynamicUB[cmdBufferIndex].sdb_CurrentOffset = 0;
}
void SvkMain::GetVertexBuffer(uint32_t size, SvkDynamicBuffer &outDynBuffer)
{
SvkDynamicBuffer &commonBuffer = gl_VkDynamicVB[gl_VkCmdBufferCurrent];
SvkDynamicBufferGlobal &dynBufferGlobal = gl_VkDynamicVBGlobal;
// if not enough
if (commonBuffer.sdb_CurrentOffset + size > dynBufferGlobal.sdg_CurrentDynamicBufferSize)
{
AddDynamicBufferToDeletion(dynBufferGlobal, gl_VkDynamicVB);
vkUnmapMemory(gl_VkDevice, dynBufferGlobal.sdg_DynamicBufferMemory);
uint32_t newSize = dynBufferGlobal.sdg_CurrentDynamicBufferSize + 2 * SVK_DYNAMIC_VERTEX_BUFFER_START_SIZE;
InitDynamicVertexBuffers(newSize);
}
outDynBuffer.sdb_Buffer = commonBuffer.sdb_Buffer;
outDynBuffer.sdb_CurrentOffset = commonBuffer.sdb_CurrentOffset;
outDynBuffer.sdb_Data = (UBYTE *)commonBuffer.sdb_Data + commonBuffer.sdb_CurrentOffset;
commonBuffer.sdb_CurrentOffset += size;
}
void SvkMain::GetIndexBuffer(uint32_t size, SvkDynamicBuffer &outDynBuffer)
{
SvkDynamicBuffer &commonBuffer = gl_VkDynamicIB[gl_VkCmdBufferCurrent];
SvkDynamicBufferGlobal &dynBufferGlobal = gl_VkDynamicIBGlobal;
// if not enough
if (commonBuffer.sdb_CurrentOffset + size > dynBufferGlobal.sdg_CurrentDynamicBufferSize)
{
AddDynamicBufferToDeletion(dynBufferGlobal, gl_VkDynamicIB);
vkUnmapMemory(gl_VkDevice, dynBufferGlobal.sdg_DynamicBufferMemory);
uint32_t newSize = dynBufferGlobal.sdg_CurrentDynamicBufferSize + SVK_DYNAMIC_INDEX_BUFFER_START_SIZE;
InitDynamicIndexBuffers(newSize);
}
outDynBuffer.sdb_Buffer = commonBuffer.sdb_Buffer;
outDynBuffer.sdb_CurrentOffset = commonBuffer.sdb_CurrentOffset;
outDynBuffer.sdb_Data = (UBYTE *)commonBuffer.sdb_Data + commonBuffer.sdb_CurrentOffset;
commonBuffer.sdb_CurrentOffset += size;
}
void SvkMain::GetUniformBuffer(uint32_t size, SvkDynamicUniform &outDynUniform)
{
// size must be aligned by min uniform offset alignment
uint32_t alignment = gl_VkPhProperties.limits.minUniformBufferOffsetAlignment;
uint32_t mod = size % alignment;
uint32_t alignedSize = mod == 0 ? size : size + alignment - mod;
ASSERTMSG(alignedSize <= SVK_DYNAMIC_UNIFORM_MAX_ALLOC_SIZE, "Vulkan: Uniform max size is too small");
SvkDynamicUniform &commonBuffer = gl_VkDynamicUB[gl_VkCmdBufferCurrent];
SvkDynamicBufferGlobal &dynBufferGlobal = gl_VkDynamicUBGlobal;
// if not enough
if (commonBuffer.sdb_CurrentOffset + SVK_DYNAMIC_UNIFORM_MAX_ALLOC_SIZE > dynBufferGlobal.sdg_CurrentDynamicBufferSize)
{
AddDynamicUniformToDeletion(dynBufferGlobal, gl_VkDynamicUB);
vkUnmapMemory(gl_VkDevice, dynBufferGlobal.sdg_DynamicBufferMemory);
uint32_t newSize = dynBufferGlobal.sdg_CurrentDynamicBufferSize + SVK_DYNAMIC_UNIFORM_BUFFER_START_SIZE;
InitDynamicUniformBuffers(newSize);
}
outDynUniform.sdb_Buffer = commonBuffer.sdb_Buffer;
outDynUniform.sdb_CurrentOffset = commonBuffer.sdb_CurrentOffset;
outDynUniform.sdb_Data = (UBYTE *)commonBuffer.sdb_Data + commonBuffer.sdb_CurrentOffset;
outDynUniform.sdu_DescriptorSet = commonBuffer.sdu_DescriptorSet;
commonBuffer.sdb_CurrentOffset += alignedSize;
}
void SvkMain::FlushDynamicBuffersMemory()
{
VkMappedMemoryRange ranges[3];
memset(&ranges, 0, sizeof(ranges));
ranges[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
ranges[0].memory = gl_VkDynamicVBGlobal.sdg_DynamicBufferMemory;
ranges[0].size = VK_WHOLE_SIZE;
ranges[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
ranges[1].memory = gl_VkDynamicIBGlobal.sdg_DynamicBufferMemory;
ranges[1].size = VK_WHOLE_SIZE;
ranges[2].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
ranges[2].memory = gl_VkDynamicUBGlobal.sdg_DynamicBufferMemory;
ranges[2].size = VK_WHOLE_SIZE;
vkFlushMappedMemoryRanges(gl_VkDevice, 3, ranges);
}
void SvkMain::FreeUnusedDynamicBuffers(uint32_t cmdBufferIndex)
{
VkResult r;
auto &toDelete = *(gl_VkDynamicToDelete[cmdBufferIndex]);
for (uint32_t i = 0; i < toDelete.Count(); i++)
{
for (uint32_t j = 0; j < gl_VkMaxCmdBufferCount; j++)
{
vkDestroyBuffer(gl_VkDevice, toDelete[i].sdd_Buffers[j], nullptr);
if (toDelete[i].sdd_DescriptorSets[j] != VK_NULL_HANDLE)
{
r = vkFreeDescriptorSets(gl_VkDevice, gl_VkUniformDescPool, 1, &toDelete[i].sdd_DescriptorSets[j]);
VK_CHECKERROR(r);
}
}
vkFreeMemory(gl_VkDevice, toDelete[i].sdd_Memory, nullptr);
}
toDelete.PopAll();
}
void SvkMain::DestroyDynamicBuffers()
{
ASSERT(gl_VkDynamicVBGlobal.sdg_DynamicBufferMemory != VK_NULL_HANDLE);
ASSERT(gl_VkDynamicIBGlobal.sdg_DynamicBufferMemory != VK_NULL_HANDLE);
ASSERT(gl_VkDynamicUBGlobal.sdg_DynamicBufferMemory != VK_NULL_HANDLE);
VkResult r;
for (uint32_t i = 0; i < gl_VkMaxCmdBufferCount; i++)
{
FreeUnusedDynamicBuffers(i);
// delete array
delete gl_VkDynamicToDelete[i];
vkDestroyBuffer(gl_VkDevice, gl_VkDynamicVB[i].sdb_Buffer, nullptr);
vkDestroyBuffer(gl_VkDevice, gl_VkDynamicIB[i].sdb_Buffer, nullptr);
vkDestroyBuffer(gl_VkDevice, gl_VkDynamicUB[i].sdb_Buffer, nullptr);
gl_VkDynamicVB[i].sdb_Buffer = VK_NULL_HANDLE;
gl_VkDynamicIB[i].sdb_Buffer = VK_NULL_HANDLE;
gl_VkDynamicUB[i].sdb_Buffer = VK_NULL_HANDLE;
gl_VkDynamicVB[i].sdb_CurrentOffset = 0;
gl_VkDynamicIB[i].sdb_CurrentOffset = 0;
gl_VkDynamicUB[i].sdb_CurrentOffset = 0;
gl_VkDynamicVB[i].sdb_Data = nullptr;
gl_VkDynamicIB[i].sdb_Data = nullptr;
gl_VkDynamicUB[i].sdb_Data = nullptr;
r = vkFreeDescriptorSets(gl_VkDevice, gl_VkUniformDescPool, 1, &gl_VkDynamicUB[i].sdu_DescriptorSet);
VK_CHECKERROR(r);
gl_VkDynamicUB[i].sdu_DescriptorSet = VK_NULL_HANDLE;
}
vkUnmapMemory(gl_VkDevice, gl_VkDynamicVBGlobal.sdg_DynamicBufferMemory);
vkUnmapMemory(gl_VkDevice, gl_VkDynamicIBGlobal.sdg_DynamicBufferMemory);
vkUnmapMemory(gl_VkDevice, gl_VkDynamicUBGlobal.sdg_DynamicBufferMemory);
vkFreeMemory(gl_VkDevice, gl_VkDynamicVBGlobal.sdg_DynamicBufferMemory, nullptr);
vkFreeMemory(gl_VkDevice, gl_VkDynamicIBGlobal.sdg_DynamicBufferMemory, nullptr);
vkFreeMemory(gl_VkDevice, gl_VkDynamicUBGlobal.sdg_DynamicBufferMemory, nullptr);
gl_VkDynamicVBGlobal.sdg_DynamicBufferMemory = VK_NULL_HANDLE;
gl_VkDynamicIBGlobal.sdg_DynamicBufferMemory = VK_NULL_HANDLE;
gl_VkDynamicUBGlobal.sdg_DynamicBufferMemory = VK_NULL_HANDLE;
gl_VkDynamicVBGlobal.sdg_CurrentDynamicBufferSize = 0;
gl_VkDynamicIBGlobal.sdg_CurrentDynamicBufferSize = 0;
gl_VkDynamicUBGlobal.sdg_CurrentDynamicBufferSize = 0;
}
#endif
| 13,831
|
C++
|
.cpp
| 293
| 43.68942
| 125
| 0.776802
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,204
|
HUD.cpp
|
sultim-t_Serious-Engine-Vk/Sources/Entities/Common/HUD.cpp
|
#include "../StdH/StdH.h"
#include <Engine/Graphics/DrawPort.h>
#include <Entities/Player.h>
#include <Entities/PlayerWeapons.h>
#include <Entities/MusicHolder.h>
#include <Entities/EnemyBase.h>
#include <Entities/EnemyCounter.h>
// armor & health constants
// NOTE: these _do not_ reflect easy/tourist maxvalue adjustments. that is by design!
#define TOP_ARMOR 100
#define TOP_HEALTH 100
// cheats
extern INDEX cht_bEnable;
extern INDEX cht_bGod;
extern INDEX cht_bFly;
extern INDEX cht_bGhost;
extern INDEX cht_bInvisible;
extern FLOAT cht_fTranslationMultiplier;
// interface control
extern INDEX hud_bShowInfo;
extern INDEX hud_bShowLatency;
extern INDEX hud_bShowMessages;
extern INDEX hud_iShowPlayers;
extern INDEX hud_iSortPlayers;
extern FLOAT hud_fOpacity;
extern FLOAT hud_fScaling;
extern FLOAT hud_tmWeaponsOnScreen;
// player statistics sorting keys
enum SortKeys {
PSK_NAME = 1,
PSK_HEALTH = 2,
PSK_SCORE = 3,
PSK_MANA = 4,
PSK_FRAGS = 5,
PSK_DEATHS = 6,
};
// where is the bar lowest value
enum BarOrientations {
BO_LEFT = 1,
BO_RIGHT = 2,
BO_UP = 3,
BO_DOWN = 4,
};
// maximal mana for master status
#define MANA_MASTER 10000
// drawing variables
static const CPlayer *_penPlayer;
static CPlayerWeapons *_penWeapons;
static CDrawPort *_pDP;
static PIX _pixDPWidth, _pixDPHeight;
static FLOAT _fResolutionScaling;
static FLOAT _fCustomScaling;
static ULONG _ulAlphaHUD;
static COLOR _colHUD;
static TIME _tmNow = -1.0f;
static CFontData _fdNumbersFont;
// array for pointers of all players
CPlayer *_apenPlayers[NET_MAXGAMEPLAYERS] = {0};
// status bar textures
static CTextureObject _toHealth;
static CTextureObject _toArmor;
static CTextureObject _toOxygen;
static CTextureObject _toScore;
static CTextureObject _toHiScore;
static CTextureObject _toMessage;
static CTextureObject _toMana;
static CTextureObject _toFrags;
static CTextureObject _toDeaths;
// ammo textures
static CTextureObject _toAShells;
static CTextureObject _toABullets;
static CTextureObject _toARockets;
static CTextureObject _toAGrenades;
static CTextureObject _toANapalm;
static CTextureObject _toAElectricity;
static CTextureObject _toAIronBall;
// weapon textures
static CTextureObject _toWKnife;
static CTextureObject _toWColt;
static CTextureObject _toWSingleShotgun;
static CTextureObject _toWDoubleShotgun;
static CTextureObject _toWTommygun;
static CTextureObject _toWMinigun;
static CTextureObject _toWRocketLauncher;
static CTextureObject _toWGrenadeLauncher;
static CTextureObject _toWPipeBomb;
static CTextureObject _toWFlamer;
static CTextureObject _toWGhostBuster;
static CTextureObject _toWLaser;
static CTextureObject _toWIronCannon;
// tile texture (one has corners, edges and center)
static CTextureObject _toTile;
// all info about color transitions
struct ColorTransitionTable {
COLOR ctt_colFine; // color for values over 1.0
COLOR ctt_colHigh; // color for values from 1.0 to 'fMedium'
COLOR ctt_colMedium; // color for values from 'fMedium' to 'fLow'
COLOR ctt_colLow; // color for values under fLow
FLOAT ctt_fMediumHigh; // when to switch to high color (normalized float!)
FLOAT ctt_fLowMedium; // when to switch to medium color (normalized float!)
BOOL ctt_bSmooth; // should colors have smooth transition
};
static struct ColorTransitionTable _cttHUD;
// ammo's info structure
struct AmmoInfo {
CTextureObject *ai_ptoAmmo;
struct WeaponInfo *ai_pwiWeapon1;
struct WeaponInfo *ai_pwiWeapon2;
INDEX ai_iAmmoAmmount;
INDEX ai_iMaxAmmoAmmount;
INDEX ai_iLastAmmoAmmount;
TIME ai_tmAmmoChanged;
BOOL ai_bHasWeapon;
};
// weapons' info structure
struct WeaponInfo {
enum WeaponType wi_wtWeapon;
CTextureObject *wi_ptoWeapon;
struct AmmoInfo *wi_paiAmmo;
BOOL wi_bHasWeapon;
};
extern struct WeaponInfo _awiWeapons[18];
static struct AmmoInfo _aaiAmmo[8] = {
{ &_toAShells, &_awiWeapons[4], &_awiWeapons[5], 0, 0, 0, -9, FALSE },
{ &_toABullets, &_awiWeapons[6], &_awiWeapons[7], 0, 0, 0, -9, FALSE },
{ &_toARockets, &_awiWeapons[8], NULL, 0, 0, 0, -9, FALSE },
{ &_toAGrenades, &_awiWeapons[9], &_awiWeapons[10], 0, 0, 0, -9, FALSE },
{ &_toANapalm, &_awiWeapons[12], NULL, 0, 0, 0, -9, FALSE },
{ &_toAElectricity, &_awiWeapons[14], &_awiWeapons[15], 0, 0, 0, -9, FALSE },
{ &_toAIronBall, &_awiWeapons[16], NULL, 0, 0, 0, -9, FALSE },
{ &_toAIronBall, &_awiWeapons[17], NULL, 0, 0, 0, -9, FALSE },
};
struct WeaponInfo _awiWeapons[18] = {
{ WEAPON_NONE, NULL, NULL, FALSE }, // 0
{ WEAPON_KNIFE, &_toWKnife, NULL, FALSE }, // 1
{ WEAPON_COLT, &_toWColt, NULL, FALSE }, // 2
{ WEAPON_DOUBLECOLT, &_toWColt, NULL, FALSE }, // 3
{ WEAPON_SINGLESHOTGUN, &_toWSingleShotgun, &_aaiAmmo[0], FALSE }, // 4
{ WEAPON_DOUBLESHOTGUN, &_toWDoubleShotgun, &_aaiAmmo[0], FALSE }, // 5
{ WEAPON_TOMMYGUN, &_toWTommygun, &_aaiAmmo[1], FALSE }, // 6
{ WEAPON_MINIGUN, &_toWMinigun, &_aaiAmmo[1], FALSE }, // 7
{ WEAPON_ROCKETLAUNCHER, &_toWRocketLauncher, &_aaiAmmo[2], FALSE }, // 8
{ WEAPON_GRENADELAUNCHER, &_toWGrenadeLauncher, &_aaiAmmo[3], FALSE }, // 9
{ WEAPON_NONE, NULL, NULL, FALSE }, //{ WEAPON_PIPEBOMB, &_toWPipeBomb, &_aaiAmmo[3], FALSE }, // 10
{ WEAPON_NONE, NULL, NULL, FALSE }, // 11
{ WEAPON_NONE, NULL, NULL, FALSE }, //{ WEAPON_FLAMER, &_toWFlamer, &_aaiAmmo[4], FALSE }, // 12
{ WEAPON_NONE, NULL, NULL, FALSE }, // 13
{ WEAPON_LASER, &_toWLaser, &_aaiAmmo[5], FALSE }, // 14
{ WEAPON_NONE, NULL, NULL, FALSE }, //{ WEAPON_GHOSTBUSTER, &_toWGhostBuster, &_aaiAmmo[5], FALSE }, // 15
{ WEAPON_IRONCANNON, &_toWIronCannon, &_aaiAmmo[6], FALSE }, // 16
{ WEAPON_NONE, NULL, NULL, FALSE }, //{ WEAPON_NUKECANNON, &_toWNukeCannon, &_aaiAmmo[7], FALSE }, // 17
};
// compare functions for qsort()
static int qsort_CompareNames( const void *ppPEN0, const void *ppPEN1) {
CPlayer &en0 = **(CPlayer**)ppPEN0;
CPlayer &en1 = **(CPlayer**)ppPEN1;
CTString strName0 = en0.GetPlayerName();
CTString strName1 = en1.GetPlayerName();
return strnicmp( strName0, strName1, 8);
}
static int qsort_CompareScores( const void *ppPEN0, const void *ppPEN1) {
CPlayer &en0 = **(CPlayer**)ppPEN0;
CPlayer &en1 = **(CPlayer**)ppPEN1;
SLONG sl0 = en0.m_psGameStats.ps_iScore;
SLONG sl1 = en1.m_psGameStats.ps_iScore;
if( sl0<sl1) return +1;
else if( sl0>sl1) return -1;
else return 0;
}
static int qsort_CompareHealth( const void *ppPEN0, const void *ppPEN1) {
CPlayer &en0 = **(CPlayer**)ppPEN0;
CPlayer &en1 = **(CPlayer**)ppPEN1;
SLONG sl0 = (SLONG)ceil(en0.GetHealth());
SLONG sl1 = (SLONG)ceil(en1.GetHealth());
if( sl0<sl1) return +1;
else if( sl0>sl1) return -1;
else return 0;
}
static int qsort_CompareManas( const void *ppPEN0, const void *ppPEN1) {
CPlayer &en0 = **(CPlayer**)ppPEN0;
CPlayer &en1 = **(CPlayer**)ppPEN1;
SLONG sl0 = en0.m_iMana;
SLONG sl1 = en1.m_iMana;
if( sl0<sl1) return +1;
else if( sl0>sl1) return -1;
else return 0;
}
static int qsort_CompareFrags( const void *ppPEN0, const void *ppPEN1) {
CPlayer &en0 = **(CPlayer**)ppPEN0;
CPlayer &en1 = **(CPlayer**)ppPEN1;
SLONG sl0 = en0.m_psGameStats.ps_iKills;
SLONG sl1 = en1.m_psGameStats.ps_iKills;
if( sl0<sl1) return +1;
else if( sl0>sl1) return -1;
else return 0;
}
static int qsort_CompareDeaths( const void *ppPEN0, const void *ppPEN1) {
CPlayer &en0 = **(CPlayer**)ppPEN0;
CPlayer &en1 = **(CPlayer**)ppPEN1;
SLONG sl0 = en0.m_psGameStats.ps_iDeaths;
SLONG sl1 = en1.m_psGameStats.ps_iDeaths;
if( sl0<sl1) return +1;
else if( sl0>sl1) return -1;
else return 0;
}
#if 0 // DG: unused
static int qsort_CompareLatencies( const void *ppPEN0, const void *ppPEN1) {
CPlayer &en0 = **(CPlayer**)ppPEN0;
CPlayer &en1 = **(CPlayer**)ppPEN1;
SLONG sl0 = (SLONG)ceil(en0.m_tmLatency);
SLONG sl1 = (SLONG)ceil(en1.m_tmLatency);
if( sl0<sl1) return +1;
else if( sl0>sl1) return -1;
else return 0;
}
#endif // 0 (unused)
// prepare color transitions
static void PrepareColorTransitions( COLOR colFine, COLOR colHigh, COLOR colMedium, COLOR colLow,
FLOAT fMediumHigh, FLOAT fLowMedium, BOOL bSmooth)
{
_cttHUD.ctt_colFine = colFine;
_cttHUD.ctt_colHigh = colHigh;
_cttHUD.ctt_colMedium = colMedium;
_cttHUD.ctt_colLow = colLow;
_cttHUD.ctt_fMediumHigh = fMediumHigh;
_cttHUD.ctt_fLowMedium = fLowMedium;
_cttHUD.ctt_bSmooth = bSmooth;
}
// calculates shake ammount and color value depanding on value change
#define SHAKE_TIME (2.0f)
static COLOR AddShaker( PIX const pixAmmount, INDEX const iCurrentValue, INDEX &iLastValue,
TIME &tmChanged, FLOAT &fMoverX, FLOAT &fMoverY)
{
// update shaking if needed
fMoverX = fMoverY = 0.0f;
const TIME tmNow = _pTimer->GetLerpedCurrentTick();
if( iCurrentValue != iLastValue) {
iLastValue = iCurrentValue;
tmChanged = tmNow;
} else {
// in case of loading (timer got reseted)
tmChanged = ClampUp( tmChanged, tmNow);
}
// no shaker?
const TIME tmDelta = tmNow - tmChanged;
if( tmDelta > SHAKE_TIME) return NONE;
ASSERT( tmDelta>=0);
// shake, baby shake!
const FLOAT fAmmount = _fResolutionScaling * _fCustomScaling * pixAmmount;
const FLOAT fMultiplier = (SHAKE_TIME-tmDelta)/SHAKE_TIME *fAmmount;
const INDEX iRandomizer = (INDEX)(tmNow*511.0f)*fAmmount*iCurrentValue;
const FLOAT fNormRnd1 = (FLOAT)((iRandomizer ^ (iRandomizer>>9)) & 1023) * 0.0009775f; // 1/1023 - normalized
const FLOAT fNormRnd2 = (FLOAT)((iRandomizer ^ (iRandomizer>>7)) & 1023) * 0.0009775f; // 1/1023 - normalized
fMoverX = (fNormRnd1 -0.5f) * fMultiplier;
fMoverY = (fNormRnd2 -0.5f) * fMultiplier;
// clamp to adjusted ammount (pixels relative to resolution and HUD scale
fMoverX = Clamp( fMoverX, -fAmmount, fAmmount);
fMoverY = Clamp( fMoverY, -fAmmount, fAmmount);
if( tmDelta < SHAKE_TIME/3) return C_WHITE;
else return NONE;
//return FloatToInt(tmDelta*4) & 1 ? C_WHITE : NONE;
}
// get current color from local color transitions table
static COLOR GetCurrentColor( FLOAT fNormalizedValue)
{
// if value is in 'low' zone just return plain 'low' alert color
if( fNormalizedValue < _cttHUD.ctt_fLowMedium) return( _cttHUD.ctt_colLow & 0xFFFFFF00);
// if value is in out of 'extreme' zone just return 'extreme' color
if( fNormalizedValue > 1.0f) return( _cttHUD.ctt_colFine & 0xFFFFFF00);
COLOR col;
// should blend colors?
if( _cttHUD.ctt_bSmooth)
{ // lets do some interpolations
FLOAT fd, f1, f2;
COLOR col1, col2;
UBYTE ubH,ubS,ubV, ubH2,ubS2,ubV2;
// determine two colors for interpolation
if( fNormalizedValue > _cttHUD.ctt_fMediumHigh) {
f1 = 1.0f;
f2 = _cttHUD.ctt_fMediumHigh;
col1 = _cttHUD.ctt_colHigh;
col2 = _cttHUD.ctt_colMedium;
} else { // fNormalizedValue > _cttHUD.ctt_fLowMedium == TRUE !
f1 = _cttHUD.ctt_fMediumHigh;
f2 = _cttHUD.ctt_fLowMedium;
col1 = _cttHUD.ctt_colMedium;
col2 = _cttHUD.ctt_colLow;
}
// determine interpolation strength
fd = (fNormalizedValue-f2) / (f1-f2);
// convert colors to HSV
ColorToHSV( col1, ubH, ubS, ubV);
ColorToHSV( col2, ubH2, ubS2, ubV2);
// interpolate H, S and V components
ubH = (UBYTE)(ubH*fd + ubH2*(1.0f-fd));
ubS = (UBYTE)(ubS*fd + ubS2*(1.0f-fd));
ubV = (UBYTE)(ubV*fd + ubV2*(1.0f-fd));
// convert HSV back to COLOR
col = HSVToColor( ubH, ubS, ubV);
}
else
{ // simple color picker
col = _cttHUD.ctt_colMedium;
if( fNormalizedValue > _cttHUD.ctt_fMediumHigh) col = _cttHUD.ctt_colHigh;
}
// all done
return( col & 0xFFFFFF00);
}
// fill array with players' statistics (returns current number of players in game)
extern INDEX SetAllPlayersStats( INDEX iSortKey)
{
// determine maximum number of players for this session
INDEX iPlayers = 0;
INDEX iMaxPlayers = _penPlayer->GetMaxPlayers();
CPlayer *penCurrent;
// loop thru potentional players
for( INDEX i=0; i<iMaxPlayers; i++)
{ // ignore non-existent players
penCurrent = (CPlayer*)&*_penPlayer->GetPlayerEntity(i);
if( penCurrent==NULL) continue;
// fill in player parameters
_apenPlayers[iPlayers] = penCurrent;
// advance to next real player
iPlayers++;
}
// sort statistics by some key if needed
switch( iSortKey) {
case PSK_NAME: qsort( _apenPlayers, iPlayers, sizeof(CPlayer*), qsort_CompareNames); break;
case PSK_SCORE: qsort( _apenPlayers, iPlayers, sizeof(CPlayer*), qsort_CompareScores); break;
case PSK_HEALTH: qsort( _apenPlayers, iPlayers, sizeof(CPlayer*), qsort_CompareHealth); break;
case PSK_MANA: qsort( _apenPlayers, iPlayers, sizeof(CPlayer*), qsort_CompareManas); break;
case PSK_FRAGS: qsort( _apenPlayers, iPlayers, sizeof(CPlayer*), qsort_CompareFrags); break;
case PSK_DEATHS: qsort( _apenPlayers, iPlayers, sizeof(CPlayer*), qsort_CompareDeaths); break;
default: break; // invalid or NONE key specified so do nothing
}
// all done
return iPlayers;
}
// ----------------------- drawing functions
// draw border with filter
static void HUD_DrawBorder( FLOAT fCenterX, FLOAT fCenterY, FLOAT fSizeX, FLOAT fSizeY, COLOR colTiles)
{
// determine location
const FLOAT fCenterI = fCenterX*_pixDPWidth / 640.0f;
const FLOAT fCenterJ = fCenterY*_pixDPHeight / (480.0f * _pDP->dp_fWideAdjustment);
const FLOAT fSizeI = _fResolutionScaling*fSizeX;
const FLOAT fSizeJ = _fResolutionScaling*fSizeY;
const FLOAT fTileSize = 8*_fResolutionScaling*_fCustomScaling;
// determine exact positions
const FLOAT fLeft = fCenterI - fSizeI/2 -1;
const FLOAT fRight = fCenterI + fSizeI/2 +1;
const FLOAT fUp = fCenterJ - fSizeJ/2 -1;
const FLOAT fDown = fCenterJ + fSizeJ/2 +1;
const FLOAT fLeftEnd = fLeft + fTileSize;
const FLOAT fRightBeg = fRight - fTileSize;
const FLOAT fUpEnd = fUp + fTileSize;
const FLOAT fDownBeg = fDown - fTileSize;
// prepare texture
colTiles |= _ulAlphaHUD;
// put corners
_pDP->InitTexture( &_toTile, TRUE); // clamping on!
_pDP->AddTexture( fLeft, fUp, fLeftEnd, fUpEnd, colTiles);
_pDP->AddTexture( fRight,fUp, fRightBeg,fUpEnd, colTiles);
_pDP->AddTexture( fRight,fDown, fRightBeg,fDownBeg, colTiles);
_pDP->AddTexture( fLeft, fDown, fLeftEnd, fDownBeg, colTiles);
// put edges
_pDP->AddTexture( fLeftEnd,fUp, fRightBeg,fUpEnd, 0.4f,0.0f, 0.6f,1.0f, colTiles);
_pDP->AddTexture( fLeftEnd,fDown, fRightBeg,fDownBeg, 0.4f,0.0f, 0.6f,1.0f, colTiles);
_pDP->AddTexture( fLeft, fUpEnd, fLeftEnd, fDownBeg, 0.0f,0.4f, 1.0f,0.6f, colTiles);
_pDP->AddTexture( fRight, fUpEnd, fRightBeg,fDownBeg, 0.0f,0.4f, 1.0f,0.6f, colTiles);
// put center
_pDP->AddTexture( fLeftEnd, fUpEnd, fRightBeg, fDownBeg, 0.4f,0.4f, 0.6f,0.6f, colTiles);
_pDP->FlushRenderingQueue();
}
// draw icon texture (if color = NONE, use colortransitions structure)
static void HUD_DrawIcon( FLOAT fCenterX, FLOAT fCenterY, CTextureObject &toIcon,
COLOR colDefault, FLOAT fNormValue, BOOL bBlink)
{
// determine color
COLOR col = colDefault;
if( col==NONE) col = GetCurrentColor( fNormValue);
// determine blinking state
if( bBlink && fNormValue<=(_cttHUD.ctt_fLowMedium/2)) {
// activate blinking only if value is <= half the low edge
INDEX iCurrentTime = (INDEX)(_tmNow*4);
if( iCurrentTime&1) col = C_vdGRAY;
}
// determine location
const FLOAT fCenterI = fCenterX*_pixDPWidth / 640.0f;
const FLOAT fCenterJ = fCenterY*_pixDPHeight / (480.0f * _pDP->dp_fWideAdjustment);
// determine dimensions
CTextureData *ptd = (CTextureData*)toIcon.GetData();
const FLOAT fHalfSizeI = _fResolutionScaling*_fCustomScaling * ptd->GetPixWidth() *0.5f;
const FLOAT fHalfSizeJ = _fResolutionScaling*_fCustomScaling * ptd->GetPixHeight() *0.5f;
// done
_pDP->InitTexture( &toIcon);
_pDP->AddTexture( fCenterI-fHalfSizeI, fCenterJ-fHalfSizeJ,
fCenterI+fHalfSizeI, fCenterJ+fHalfSizeJ, col|_ulAlphaHUD);
_pDP->FlushRenderingQueue();
}
// draw text (or numbers, whatever)
static void HUD_DrawText( FLOAT fCenterX, FLOAT fCenterY, const CTString &strText,
COLOR colDefault, FLOAT fNormValue)
{
// determine color
COLOR col = colDefault;
if( col==NONE) col = GetCurrentColor( fNormValue);
// determine location
PIX pixCenterI = (PIX)(fCenterX*_pixDPWidth / 640.0f);
PIX pixCenterJ = (PIX)(fCenterY*_pixDPHeight / (480.0f * _pDP->dp_fWideAdjustment));
// done
_pDP->SetTextScaling( _fResolutionScaling*_fCustomScaling);
_pDP->PutTextCXY( strText, pixCenterI, pixCenterJ, col|_ulAlphaHUD);
}
// draw bar
static void HUD_DrawBar( FLOAT fCenterX, FLOAT fCenterY, PIX pixSizeX, PIX pixSizeY,
enum BarOrientations eBarOrientation, COLOR colDefault, FLOAT fNormValue)
{
// determine color
COLOR col = colDefault;
if( col==NONE) col = GetCurrentColor( fNormValue);
// determine location and size
PIX pixCenterI = (PIX)(fCenterX*_pixDPWidth / 640.0f);
PIX pixCenterJ = (PIX)(fCenterY*_pixDPHeight / (480.0f * _pDP->dp_fWideAdjustment));
PIX pixSizeI = (PIX)(_fResolutionScaling*pixSizeX);
PIX pixSizeJ = (PIX)(_fResolutionScaling*pixSizeY);
// fill bar background area
PIX pixLeft = pixCenterI-pixSizeI/2;
PIX pixUpper = pixCenterJ-pixSizeJ/2;
// determine bar position and inner size
switch( eBarOrientation) {
case BO_UP:
pixSizeJ *= fNormValue;
break;
case BO_DOWN:
pixUpper = pixUpper + (PIX)ceil(pixSizeJ * (1.0f-fNormValue));
pixSizeJ *= fNormValue;
break;
case BO_LEFT:
pixSizeI *= fNormValue;
break;
case BO_RIGHT:
pixLeft = pixLeft + (PIX)ceil(pixSizeI * (1.0f-fNormValue));
pixSizeI *= fNormValue;
break;
}
// done
_pDP->Fill( pixLeft, pixUpper, pixSizeI, pixSizeJ, col|_ulAlphaHUD);
}
// helper functions
// fill weapon and ammo table with current state
static void FillWeaponAmmoTables(void)
{
// ammo quantities
_aaiAmmo[0].ai_iAmmoAmmount = _penWeapons->m_iShells;
_aaiAmmo[0].ai_iMaxAmmoAmmount = _penWeapons->m_iMaxShells;
_aaiAmmo[1].ai_iAmmoAmmount = _penWeapons->m_iBullets;
_aaiAmmo[1].ai_iMaxAmmoAmmount = _penWeapons->m_iMaxBullets;
_aaiAmmo[2].ai_iAmmoAmmount = _penWeapons->m_iRockets;
_aaiAmmo[2].ai_iMaxAmmoAmmount = _penWeapons->m_iMaxRockets;
_aaiAmmo[3].ai_iAmmoAmmount = _penWeapons->m_iGrenades;
_aaiAmmo[3].ai_iMaxAmmoAmmount = _penWeapons->m_iMaxGrenades;
_aaiAmmo[4].ai_iAmmoAmmount = 0;//_penWeapons->m_iNapalm;
_aaiAmmo[4].ai_iMaxAmmoAmmount = 0;//_penWeapons->m_iMaxNapalm;
_aaiAmmo[5].ai_iAmmoAmmount = _penWeapons->m_iElectricity;
_aaiAmmo[5].ai_iMaxAmmoAmmount = _penWeapons->m_iMaxElectricity;
_aaiAmmo[6].ai_iAmmoAmmount = _penWeapons->m_iIronBalls;
_aaiAmmo[6].ai_iMaxAmmoAmmount = _penWeapons->m_iMaxIronBalls;
_aaiAmmo[7].ai_iAmmoAmmount = 0;//_penWeapons->m_iNukeBalls;
_aaiAmmo[7].ai_iMaxAmmoAmmount = 0;//_penWeapons->m_iMaxNukeBalls;
// prepare ammo table for weapon possesion
INDEX i, iAvailableWeapons = _penWeapons->m_iAvailableWeapons;
for( i=0; i<8; i++) _aaiAmmo[i].ai_bHasWeapon = FALSE;
// weapon possesion
for( i=WEAPON_NONE+1; i<WEAPON_LAST; i++)
{
if( _awiWeapons[i].wi_wtWeapon!=WEAPON_NONE)
{
// regular weapons
_awiWeapons[i].wi_bHasWeapon = (iAvailableWeapons&(1<<(_awiWeapons[i].wi_wtWeapon-1)));
if( _awiWeapons[i].wi_paiAmmo!=NULL) _awiWeapons[i].wi_paiAmmo->ai_bHasWeapon |= _awiWeapons[i].wi_bHasWeapon;
}
}
}
// main
// render interface (frontend) to drawport
// (units are in pixels for 640x480 resolution - for other res HUD will be scalled automatically)
extern void DrawHUD( const CPlayer *penPlayerCurrent, CDrawPort *pdpCurrent, BOOL bSnooping)
{
// no player - no info, sorry
if( penPlayerCurrent==NULL || (penPlayerCurrent->GetFlags()&ENF_DELETED)) return;
// find last values in case of predictor
CPlayer *penLast = (CPlayer*)penPlayerCurrent;
if( penPlayerCurrent->IsPredictor()) penLast = (CPlayer*)(((CPlayer*)penPlayerCurrent)->GetPredicted());
ASSERT( penLast!=NULL);
if( penLast==NULL) return; // !!!! just in case
// cache local variables
hud_fOpacity = Clamp( hud_fOpacity, 0.1f, 1.0f);
hud_fScaling = Clamp( hud_fScaling, 0.5f, 1.2f);
_penPlayer = penPlayerCurrent;
_penWeapons = (CPlayerWeapons*)&*_penPlayer->m_penWeapons;
_pDP = pdpCurrent;
_pixDPWidth = _pDP->GetWidth();
_pixDPHeight = _pDP->GetHeight();
_fCustomScaling = hud_fScaling;
_fResolutionScaling = (FLOAT)_pixDPWidth /640.0f;
_colHUD = C_GREEN;
_ulAlphaHUD = NormFloatToByte(hud_fOpacity);
_tmNow = _pTimer->CurrentTick();
// set HUD colorization;
COLOR colMax = _colHUD;
COLOR colTop = _colHUD;
COLOR colMid = _colHUD;
// adjust borders color in case of spying mode
COLOR colBorder = _colHUD;
if( bSnooping) {
UBYTE ubR,ubG,ubB;
ColorToRGB( colBorder, ubR,ubG,ubB);
colBorder = RGBToColor( ubG,ubB,ubR); // shift and xor color components
if( ((ULONG)(_tmNow*5))&1) {
colBorder = (colBorder>>1) & 0x7F7F7F00; // darken flash and scale
_fCustomScaling *= 0.933f;
}
}
// prepare font and text dimensions
CTString strValue;
PIX pixCharWidth;
FLOAT fValue, fNormValue, fCol, fRow;
_pDP->SetFont( &_fdNumbersFont);
pixCharWidth = _fdNumbersFont.GetWidth() + _fdNumbersFont.GetCharSpacing() +1;
FLOAT fChrUnit = pixCharWidth * _fCustomScaling;
const PIX pixTopBound = 6;
const PIX pixLeftBound = 6;
const PIX pixBottomBound = (480 * _pDP->dp_fWideAdjustment) -pixTopBound;
const PIX pixRightBound = 640-pixLeftBound;
FLOAT fOneUnit = (32+0) * _fCustomScaling; // unit size
FLOAT fAdvUnit = (32+4) * _fCustomScaling; // unit advancer
FLOAT fNextUnit = (32+8) * _fCustomScaling; // unit advancer
FLOAT fHalfUnit = fOneUnit * 0.5f;
FLOAT fMoverX, fMoverY;
COLOR colDefault;
// prepare and draw health info
fValue = ClampDn( _penPlayer->GetHealth(), 0.0f); // never show negative health
fNormValue = fValue/TOP_HEALTH;
strValue.PrintF( "%d", (SLONG)ceil(fValue));
PrepareColorTransitions( colMax, colTop, colMid, C_RED, 0.5f, 0.25f, FALSE);
fRow = pixBottomBound-fHalfUnit;
fCol = pixLeftBound+fHalfUnit;
colDefault = AddShaker( 5, fValue, penLast->m_iLastHealth, penLast->m_tmHealthChanged, fMoverX, fMoverY);
HUD_DrawBorder( fCol+fMoverX, fRow+fMoverY, fOneUnit, fOneUnit, colBorder);
fCol += fAdvUnit+fChrUnit*3/2 -fHalfUnit;
HUD_DrawBorder( fCol, fRow, fChrUnit*3, fOneUnit, colBorder);
HUD_DrawText( fCol, fRow, strValue, colDefault, fNormValue);
fCol -= fAdvUnit+fChrUnit*3/2 -fHalfUnit;
HUD_DrawIcon( fCol+fMoverX, fRow+fMoverY, _toHealth, _colHUD, fNormValue, TRUE);
// prepare and draw armor info (eventually)
fValue = _penPlayer->m_fArmor;
if( fValue > 0.0f) {
fNormValue = fValue/TOP_ARMOR;
strValue.PrintF( "%d", (SLONG)ceil(fValue));
PrepareColorTransitions( colMax, colTop, colMid, C_lGRAY, 0.5f, 0.25f, FALSE);
fRow = pixBottomBound- (fNextUnit+fHalfUnit);//*_pDP->dp_fWideAdjustment;
fCol = pixLeftBound+ fHalfUnit;
colDefault = AddShaker( 3, fValue, penLast->m_iLastArmor, penLast->m_tmArmorChanged, fMoverX, fMoverY);
HUD_DrawBorder( fCol+fMoverX, fRow+fMoverY, fOneUnit, fOneUnit, colBorder);
fCol += fAdvUnit+fChrUnit*3/2 -fHalfUnit;
HUD_DrawBorder( fCol, fRow, fChrUnit*3, fOneUnit, colBorder);
HUD_DrawText( fCol, fRow, strValue, NONE, fNormValue);
fCol -= fAdvUnit+fChrUnit*3/2 -fHalfUnit;
HUD_DrawIcon( fCol+fMoverX, fRow+fMoverY, _toArmor, _colHUD, fNormValue, FALSE);
}
// prepare and draw ammo and weapon info
CTextureObject *ptoCurrentAmmo=NULL, *ptoCurrentWeapon=NULL, *ptoWantedWeapon=NULL;
INDEX iCurrentWeapon = _penWeapons->m_iCurrentWeapon;
INDEX iWantedWeapon = _penWeapons->m_iWantedWeapon;
// determine corresponding ammo and weapon texture component
ptoCurrentWeapon = _awiWeapons[iCurrentWeapon].wi_ptoWeapon;
ptoWantedWeapon = _awiWeapons[iWantedWeapon].wi_ptoWeapon;
AmmoInfo *paiCurrent = _awiWeapons[iCurrentWeapon].wi_paiAmmo;
if( paiCurrent!=NULL) ptoCurrentAmmo = paiCurrent->ai_ptoAmmo;
// draw complete weapon info if knife isn't current weapon
if( ptoCurrentAmmo!=NULL && !GetSP()->sp_bInfiniteAmmo) {
// determine ammo quantities
FLOAT fMaxValue = _penWeapons->GetMaxAmmo();
fValue = _penWeapons->GetAmmo();
fNormValue = fValue / fMaxValue;
strValue.PrintF( "%d", (SLONG)ceil(fValue));
PrepareColorTransitions( colMax, colTop, colMid, C_RED, 0.5f, 0.25f, FALSE);
BOOL bDrawAmmoIcon = _fCustomScaling<=1.0f;
// draw ammo, value and weapon
fRow = pixBottomBound-fHalfUnit;
fCol = 175 + fHalfUnit;
colDefault = AddShaker( 4, fValue, penLast->m_iLastAmmo, penLast->m_tmAmmoChanged, fMoverX, fMoverY);
HUD_DrawBorder( fCol+fMoverX, fRow+fMoverY, fOneUnit, fOneUnit, colBorder);
fCol += fAdvUnit+fChrUnit*3/2 -fHalfUnit;
HUD_DrawBorder( fCol, fRow, fChrUnit*3, fOneUnit, colBorder);
if( bDrawAmmoIcon) {
fCol += fAdvUnit+fChrUnit*3/2 -fHalfUnit;
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, colBorder);
HUD_DrawIcon( fCol, fRow, *ptoCurrentAmmo, _colHUD, fNormValue, TRUE);
fCol -= fAdvUnit+fChrUnit*3/2 -fHalfUnit;
}
HUD_DrawText( fCol, fRow, strValue, colDefault, fNormValue);
fCol -= fAdvUnit+fChrUnit*3/2 -fHalfUnit;
HUD_DrawIcon( fCol+fMoverX, fRow+fMoverY, *ptoCurrentWeapon, _colHUD, fNormValue, !bDrawAmmoIcon);
} else if( ptoCurrentWeapon!=NULL) {
// draw only knife or colt icons (ammo is irrelevant)
fRow = pixBottomBound-fHalfUnit;
fCol = 205 + fHalfUnit;
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, colBorder);
HUD_DrawIcon( fCol, fRow, *ptoCurrentWeapon, _colHUD, fNormValue, FALSE);
}
// display all ammo infos
INDEX i;
FLOAT fAdv;
COLOR colIcon, colBar;
PrepareColorTransitions( colMax, colTop, colMid, C_RED, 0.5f, 0.25f, FALSE);
// reduce the size of icon slightly
_fCustomScaling = ClampDn( _fCustomScaling*0.8f, 0.5f);
const FLOAT fOneUnitS = fOneUnit *0.8f;
const FLOAT fAdvUnitS = fAdvUnit *0.8f;
//const FLOAT fNextUnitS = fNextUnit *0.8f;
const FLOAT fHalfUnitS = fHalfUnit *0.8f;
// prepare postition and ammo quantities
fRow = pixBottomBound-fHalfUnitS;
fCol = pixRightBound -fHalfUnitS;
const FLOAT fBarPos = fHalfUnitS*0.7f;
FillWeaponAmmoTables();
// loop thru all ammo types
if (!GetSP()->sp_bInfiniteAmmo) {
for( i=7; i>=0; i--) {
// if no ammo and hasn't got that weapon - just skip this ammo
AmmoInfo &ai = _aaiAmmo[i];
ASSERT( ai.ai_iAmmoAmmount>=0);
if( ai.ai_iAmmoAmmount==0 && !ai.ai_bHasWeapon) continue;
// display ammo info
colIcon = _colHUD;
if( ai.ai_iAmmoAmmount==0) colIcon = C_GRAY;
if( ptoCurrentAmmo == ai.ai_ptoAmmo) colIcon = C_WHITE;
fNormValue = (FLOAT)ai.ai_iAmmoAmmount / ai.ai_iMaxAmmoAmmount;
colBar = AddShaker( 4, ai.ai_iAmmoAmmount, ai.ai_iLastAmmoAmmount, ai.ai_tmAmmoChanged, fMoverX, fMoverY);
HUD_DrawBorder( fCol, fRow+fMoverY, fOneUnitS, fOneUnitS, colBorder);
HUD_DrawIcon( fCol, fRow+fMoverY, *_aaiAmmo[i].ai_ptoAmmo, colIcon, fNormValue, FALSE);
HUD_DrawBar( fCol+fBarPos, fRow+fMoverY, fOneUnitS/5, fOneUnitS-2, BO_DOWN, colBar, fNormValue);
// advance to next position
fCol -= fAdvUnitS;
}
}
// if weapon change is in progress
_fCustomScaling = hud_fScaling;
hud_tmWeaponsOnScreen = Clamp( hud_tmWeaponsOnScreen, 0.0f, 10.0f);
if( (_tmNow - _penWeapons->m_tmWeaponChangeRequired) < hud_tmWeaponsOnScreen) {
// determine number of weapons that player has
INDEX ctWeapons = 0;
for( i=WEAPON_NONE+1; i<WEAPON_LAST; i++) {
if( _awiWeapons[i].wi_wtWeapon!=WEAPON_NONE && _awiWeapons[i].wi_wtWeapon!=WEAPON_DOUBLECOLT &&
_awiWeapons[i].wi_bHasWeapon) ctWeapons++;
}
// display all available weapons
fRow = pixBottomBound - fHalfUnit - 3*fNextUnit;
fCol = 320.0f - (ctWeapons*fAdvUnit-fHalfUnit)/2.0f;
// display all available weapons
for( i=WEAPON_NONE+1; i<WEAPON_LAST; i++) {
// skip if hasn't got this weapon
if( _awiWeapons[i].wi_wtWeapon==WEAPON_NONE || _awiWeapons[i].wi_wtWeapon==WEAPON_DOUBLECOLT
/*|| _awiWeapons[i].wi_wtWeapon==WEAPON_NUKECANNON*/ || !_awiWeapons[i].wi_bHasWeapon) continue;
// display weapon icon
colIcon = _colHUD;
if( _awiWeapons[i].wi_paiAmmo!=NULL && _awiWeapons[i].wi_paiAmmo->ai_iAmmoAmmount==0) colIcon = C_dGRAY;
if( ptoWantedWeapon == _awiWeapons[i].wi_ptoWeapon) colIcon = C_WHITE;
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, colIcon);
HUD_DrawIcon( fCol, fRow, *_awiWeapons[i].wi_ptoWeapon, colIcon, 1.0f, FALSE);
// advance to next position
fCol += fAdvUnit;
}
}
const FLOAT fUpperSize = ClampDn(_fCustomScaling*0.5f, 0.5f)/_fCustomScaling;
_fCustomScaling*=fUpperSize;
ASSERT( _fCustomScaling>=0.5f);
fChrUnit *= fUpperSize;
fOneUnit *= fUpperSize;
fHalfUnit *= fUpperSize;
fAdvUnit *= fUpperSize;
fNextUnit *= fUpperSize;
// draw oxygen info if needed
BOOL bOxygenOnScreen = FALSE;
fValue = _penPlayer->en_tmMaxHoldBreath - (_pTimer->CurrentTick() - _penPlayer->en_tmLastBreathed);
if( _penPlayer->IsConnected() && (_penPlayer->GetFlags()&ENF_ALIVE) && fValue<30.0f) {
// prepare and draw oxygen info
fRow = pixTopBound + fOneUnit + fNextUnit;
fCol = 280.0f;
fAdv = fAdvUnit + fOneUnit*4/2 - fHalfUnit;
PrepareColorTransitions( colMax, colTop, colMid, C_RED, 0.5f, 0.25f, FALSE);
fNormValue = fValue/30.0f;
fNormValue = ClampDn(fNormValue, 0.0f);
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, colBorder);
HUD_DrawBorder( fCol+fAdv, fRow, fOneUnit*4, fOneUnit, colBorder);
HUD_DrawBar( fCol+fAdv, fRow, fOneUnit*4*0.975, fOneUnit*0.9375, BO_LEFT, NONE, fNormValue);
HUD_DrawIcon( fCol, fRow, _toOxygen, _colHUD, fNormValue, TRUE);
bOxygenOnScreen = TRUE;
}
// draw boss energy if needed
if( _penPlayer->m_penMainMusicHolder!=NULL) {
CMusicHolder &mh = (CMusicHolder&)*_penPlayer->m_penMainMusicHolder;
fNormValue = 0;
if( mh.m_penBoss!=NULL && (mh.m_penBoss->en_ulFlags&ENF_ALIVE)) {
CEnemyBase &eb = (CEnemyBase&)*mh.m_penBoss;
ASSERT( eb.m_fMaxHealth>0);
fValue = eb.GetHealth();
fNormValue = fValue/eb.m_fMaxHealth;
}
if( mh.m_penCounter!=NULL) {
CEnemyCounter &ec = (CEnemyCounter&)*mh.m_penCounter;
if (ec.m_iCount>0) {
fValue = ec.m_iCount;
fNormValue = fValue/ec.m_iCountFrom;
}
}
if (fNormValue>0) {
// prepare and draw boss energy info
PrepareColorTransitions( colMax, colTop, colMid, C_RED, 0.5f, 0.25f, FALSE);
fRow = pixTopBound + fOneUnit + fNextUnit;
fCol = 184.0f;
fAdv = fAdvUnit+ fOneUnit*16/2 -fHalfUnit;
if( bOxygenOnScreen) fRow += fNextUnit;
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, colBorder);
HUD_DrawBorder( fCol+fAdv, fRow, fOneUnit*16, fOneUnit, colBorder);
HUD_DrawBar( fCol+fAdv, fRow, fOneUnit*16*0.995, fOneUnit*0.9375, BO_LEFT, NONE, fNormValue);
HUD_DrawIcon( fCol, fRow, _toHealth, _colHUD, fNormValue, FALSE);
}
}
// determine scaling of normal text and play mode
const FLOAT fTextScale = (_fResolutionScaling+1) *0.5f;
const BOOL bSinglePlay = GetSP()->sp_bSinglePlayer;
const BOOL bCooperative = GetSP()->sp_bCooperative && !bSinglePlay;
const BOOL bScoreMatch = !GetSP()->sp_bCooperative && !GetSP()->sp_bUseFrags;
const BOOL bFragMatch = !GetSP()->sp_bCooperative && GetSP()->sp_bUseFrags;
COLOR colMana, colFrags, colDeaths, colHealth, colArmor;
COLOR colScore = _colHUD;
INDEX iScoreSum = 0;
// if not in single player mode, we'll have to calc (and maybe printout) other players' info
if( !bSinglePlay)
{
// set font and prepare font parameters
_pfdDisplayFont->SetVariableWidth();
_pDP->SetFont( _pfdDisplayFont);
_pDP->SetTextScaling( fTextScale);
FLOAT fCharHeight = (_pfdDisplayFont->GetHeight()-2)*fTextScale;
// generate and sort by mana list of active players
BOOL bMaxScore=TRUE, bMaxMana=TRUE, bMaxFrags=TRUE, bMaxDeaths=TRUE;
hud_iSortPlayers = Clamp( hud_iSortPlayers, (INDEX)-1, (INDEX)6);
SortKeys eKey = (SortKeys)hud_iSortPlayers;
if (hud_iSortPlayers==-1) {
if (bCooperative) eKey = PSK_HEALTH;
else if (bScoreMatch) eKey = PSK_SCORE;
else if (bFragMatch) eKey = PSK_FRAGS;
else { ASSERT(FALSE); eKey = PSK_NAME; }
}
if( bCooperative) eKey = (SortKeys)Clamp( (INDEX)eKey, (INDEX)0, (INDEX)3);
if( eKey==PSK_HEALTH && (bScoreMatch || bFragMatch)) { eKey = PSK_NAME; }; // prevent health snooping in deathmatch
INDEX iPlayers = SetAllPlayersStats(eKey);
// loop thru players
for( INDEX i=0; i<iPlayers; i++)
{ // get player name and mana
CPlayer *penPlayer = _apenPlayers[i];
const CTString strName = penPlayer->GetPlayerName();
const INDEX iScore = penPlayer->m_psGameStats.ps_iScore;
const INDEX iMana = penPlayer->m_iMana;
const INDEX iFrags = penPlayer->m_psGameStats.ps_iKills;
const INDEX iDeaths = penPlayer->m_psGameStats.ps_iDeaths;
const INDEX iHealth = ClampDn( (INDEX)ceil( penPlayer->GetHealth()), (INDEX)0);
const INDEX iArmor = ClampDn( (INDEX)ceil( penPlayer->m_fArmor), (INDEX)0);
CTString strScore, strMana, strFrags, strDeaths, strHealth, strArmor;
strScore.PrintF( "%d", iScore);
strMana.PrintF( "%d", iMana);
strFrags.PrintF( "%d", iFrags);
strDeaths.PrintF( "%d", iDeaths);
strHealth.PrintF( "%d", iHealth);
strArmor.PrintF( "%d", iArmor);
// detemine corresponding colors
colHealth = C_mlRED;
colMana = colScore = colFrags = colDeaths = colArmor = C_lGRAY;
if( iMana > _penPlayer->m_iMana) { bMaxMana = FALSE; colMana = C_WHITE; }
if( iScore > _penPlayer->m_psGameStats.ps_iScore) { bMaxScore = FALSE; colScore = C_WHITE; }
if( iFrags > _penPlayer->m_psGameStats.ps_iKills) { bMaxFrags = FALSE; colFrags = C_WHITE; }
if( iDeaths > _penPlayer->m_psGameStats.ps_iDeaths) { bMaxDeaths = FALSE; colDeaths = C_WHITE; }
if( penPlayer==_penPlayer) colScore = colMana = colFrags = colDeaths = _colHUD; // current player
if( iHealth>25) colHealth = _colHUD;
if( iArmor >25) colArmor = _colHUD;
// eventually print it out
if( hud_iShowPlayers==1 || (hud_iShowPlayers==-1 && !bSinglePlay)) {
// printout location and info aren't the same for deathmatch and coop play
const FLOAT fCharWidth = (PIX)((_pfdDisplayFont->GetWidth()-2) *fTextScale);
if( bCooperative) {
_pDP->PutTextR( strName+":", _pixDPWidth-8*fCharWidth, fCharHeight*i+fOneUnit*2, colScore |_ulAlphaHUD);
_pDP->PutText( "/", _pixDPWidth-4*fCharWidth, fCharHeight*i+fOneUnit*2, _colHUD |_ulAlphaHUD);
_pDP->PutTextC( strHealth, _pixDPWidth-6*fCharWidth, fCharHeight*i+fOneUnit*2, colHealth|_ulAlphaHUD);
_pDP->PutTextC( strArmor, _pixDPWidth-2*fCharWidth, fCharHeight*i+fOneUnit*2, colArmor |_ulAlphaHUD);
} else if( bScoreMatch) {
_pDP->PutTextR( strName+":", _pixDPWidth-12*fCharWidth, fCharHeight*i+fOneUnit*2, _colHUD |_ulAlphaHUD);
_pDP->PutText( "/", _pixDPWidth- 5*fCharWidth, fCharHeight*i+fOneUnit*2, _colHUD |_ulAlphaHUD);
_pDP->PutTextC( strScore, _pixDPWidth- 8*fCharWidth, fCharHeight*i+fOneUnit*2, colScore|_ulAlphaHUD);
_pDP->PutTextC( strMana, _pixDPWidth- 2*fCharWidth, fCharHeight*i+fOneUnit*2, colMana |_ulAlphaHUD);
} else { // fragmatch!
_pDP->PutTextR( strName+":", _pixDPWidth-8*fCharWidth, fCharHeight*i+fOneUnit*2, _colHUD |_ulAlphaHUD);
_pDP->PutText( "/", _pixDPWidth-4*fCharWidth, fCharHeight*i+fOneUnit*2, _colHUD |_ulAlphaHUD);
_pDP->PutTextC( strFrags, _pixDPWidth-6*fCharWidth, fCharHeight*i+fOneUnit*2, colFrags |_ulAlphaHUD);
_pDP->PutTextC( strDeaths, _pixDPWidth-2*fCharWidth, fCharHeight*i+fOneUnit*2, colDeaths|_ulAlphaHUD);
}
}
// calculate summ of scores (for coop mode)
iScoreSum += iScore;
}
// prepare color for local player printouts
bMaxScore ? colScore = C_WHITE : colScore = C_lGRAY;
bMaxMana ? colMana = C_WHITE : colMana = C_lGRAY;
bMaxFrags ? colFrags = C_WHITE : colFrags = C_lGRAY;
bMaxDeaths ? colDeaths = C_WHITE : colDeaths = C_lGRAY;
}
// printout player latency if needed
if( hud_bShowLatency) {
CTString strLatency;
strLatency.PrintF( "%4.0fms", _penPlayer->m_tmLatency*1000.0f);
PIX pixFontHeight = (PIX)(_pfdDisplayFont->GetHeight() *fTextScale +fTextScale+1);
_pfdDisplayFont->SetFixedWidth();
_pDP->SetFont( _pfdDisplayFont);
_pDP->SetTextScaling( fTextScale);
_pDP->SetTextCharSpacing( -2.0f*fTextScale);
_pDP->PutTextR( strLatency, _pixDPWidth, _pixDPHeight-pixFontHeight, C_WHITE|CT_OPAQUE);
}
// restore font defaults
_pfdDisplayFont->SetVariableWidth();
_pDP->SetFont( &_fdNumbersFont);
_pDP->SetTextCharSpacing(1);
// prepare output strings and formats depending on game type
FLOAT fWidthAdj = 8;
INDEX iScore = _penPlayer->m_psGameStats.ps_iScore;
INDEX iMana = _penPlayer->m_iMana;
if( bFragMatch) {
fWidthAdj = 4;
iScore = _penPlayer->m_psGameStats.ps_iKills;
iMana = _penPlayer->m_psGameStats.ps_iDeaths;
} else if( bCooperative) {
// in case of coop play, show squad (common) score
iScore = iScoreSum;
}
// prepare and draw score or frags info
strValue.PrintF( "%d", iScore);
fRow = pixTopBound +fHalfUnit;
fCol = pixLeftBound +fHalfUnit;
fAdv = fAdvUnit+ fChrUnit*fWidthAdj/2 -fHalfUnit;
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, colBorder);
HUD_DrawBorder( fCol+fAdv, fRow, fChrUnit*fWidthAdj, fOneUnit, colBorder);
HUD_DrawText( fCol+fAdv, fRow, strValue, colScore, 1.0f);
HUD_DrawIcon( fCol, fRow, _toFrags, colScore, 1.0f, FALSE);
// eventually draw mana info
if( bScoreMatch || bFragMatch) {
strValue.PrintF( "%d", iMana);
fRow = pixTopBound + fNextUnit+fHalfUnit;
fCol = pixLeftBound + fHalfUnit;
fAdv = fAdvUnit+ fChrUnit*fWidthAdj/2 -fHalfUnit;
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, colBorder);
HUD_DrawBorder( fCol+fAdv, fRow, fChrUnit*fWidthAdj, fOneUnit, colBorder);
HUD_DrawText( fCol+fAdv, fRow, strValue, colMana, 1.0f);
HUD_DrawIcon( fCol, fRow, _toDeaths, colMana, 1.0f, FALSE);
}
// if single player or cooperative mode
if( bSinglePlay || bCooperative)
{
// prepare and draw hiscore info
strValue.PrintF( "%d", Max(_penPlayer->m_iHighScore, _penPlayer->m_psGameStats.ps_iScore));
BOOL bBeating = _penPlayer->m_psGameStats.ps_iScore>_penPlayer->m_iHighScore;
fRow = pixTopBound+fHalfUnit;
fCol = 320.0f-fOneUnit-fChrUnit*8/2;
fAdv = fAdvUnit+ fChrUnit*8/2 -fHalfUnit;
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, colBorder);
HUD_DrawBorder( fCol+fAdv, fRow, fChrUnit*8, fOneUnit, colBorder);
HUD_DrawText( fCol+fAdv, fRow, strValue, NONE, bBeating ? 0.0f : 1.0f);
HUD_DrawIcon( fCol, fRow, _toHiScore, _colHUD, 1.0f, FALSE);
// prepare and draw unread messages
if( hud_bShowMessages && _penPlayer->m_ctUnreadMessages>0) {
strValue.PrintF( "%d", _penPlayer->m_ctUnreadMessages);
fRow = pixTopBound+fHalfUnit;
fCol = pixRightBound-fHalfUnit-fAdvUnit-fChrUnit*4;
const FLOAT tmIn = 0.5f;
const FLOAT tmOut = 0.5f;
const FLOAT tmStay = 2.0f;
FLOAT tmDelta = _pTimer->GetLerpedCurrentTick()-_penPlayer->m_tmAnimateInbox;
COLOR col = _colHUD;
if (tmDelta>0 && tmDelta<(tmIn+tmStay+tmOut) && bSinglePlay) {
FLOAT fRatio = 0.0f;
if (tmDelta<tmIn) {
fRatio = tmDelta/tmIn;
} else if (tmDelta>tmIn+tmStay) {
fRatio = (tmIn+tmStay+tmOut-tmDelta)/tmOut;
} else {
fRatio = 1.0f;
}
fRow+=fAdvUnit*5*fRatio;
fCol-=fAdvUnit*15*fRatio;
col = LerpColor(_colHUD, C_WHITE|0xFF, fRatio);
}
fAdv = fAdvUnit+ fChrUnit*4/2 -fHalfUnit;
HUD_DrawBorder( fCol, fRow, fOneUnit, fOneUnit, col);
HUD_DrawBorder( fCol+fAdv, fRow, fChrUnit*4, fOneUnit, col);
HUD_DrawText( fCol+fAdv, fRow, strValue, col, 1.0f);
HUD_DrawIcon( fCol, fRow, _toMessage, col, 0.0f, TRUE);
}
}
// draw cheat modes
if( GetSP()->sp_ctMaxPlayers==1) {
INDEX iLine=1;
ULONG ulAlpha = sin(_tmNow*16)*96 +128;
PIX pixFontHeight = _pfdConsoleFont->fd_pixCharHeight;
const COLOR colCheat = _colHUD;
_pDP->SetFont( _pfdConsoleFont);
_pDP->SetTextScaling( 1.0f);
const FLOAT fchtTM = cht_fTranslationMultiplier; // for text formatting sake :)
if( fchtTM > 1.0f) { _pDP->PutTextR( "turbo", _pixDPWidth-1, _pixDPHeight-pixFontHeight*iLine, colCheat|ulAlpha); iLine++; }
if( cht_bInvisible) { _pDP->PutTextR( "invisible", _pixDPWidth-1, _pixDPHeight-pixFontHeight*iLine, colCheat|ulAlpha); iLine++; }
if( cht_bGhost) { _pDP->PutTextR( "ghost", _pixDPWidth-1, _pixDPHeight-pixFontHeight*iLine, colCheat|ulAlpha); iLine++; }
if( cht_bFly) { _pDP->PutTextR( "fly", _pixDPWidth-1, _pixDPHeight-pixFontHeight*iLine, colCheat|ulAlpha); iLine++; }
if( cht_bGod) { _pDP->PutTextR( "god", _pixDPWidth-1, _pixDPHeight-pixFontHeight*iLine, colCheat|ulAlpha); iLine++; }
}
}
// initialized all whats need for drawing HUD
extern void InitHUD(void)
{
// try to
try {
// initialize and load HUD numbers font
DECLARE_CTFILENAME( fnFont, "Fonts\\Numbers3.fnt");
_fdNumbersFont.Load_t( fnFont);
//_fdNumbersFont.SetCharSpacing(0);
// initialize status bar textures
_toHealth.SetData_t( CTFILENAME("Textures\\Interface\\HSuper.tex"));
_toArmor.SetData_t( CTFILENAME("Textures\\Interface\\ArStrong.tex"));
_toOxygen.SetData_t( CTFILENAME("Textures\\Interface\\Oxygen-2.tex"));
_toFrags.SetData_t( CTFILENAME("Textures\\Interface\\IBead.tex"));
_toDeaths.SetData_t( CTFILENAME("Textures\\Interface\\ISkull.tex"));
_toScore.SetData_t( CTFILENAME("Textures\\Interface\\IScore.tex"));
_toHiScore.SetData_t( CTFILENAME("Textures\\Interface\\IHiScore.tex"));
_toMessage.SetData_t( CTFILENAME("Textures\\Interface\\IMessage.tex"));
_toMana.SetData_t( CTFILENAME("Textures\\Interface\\IValue.tex"));
// initialize ammo textures
_toAShells.SetData_t( CTFILENAME("Textures\\Interface\\AmShells.tex"));
_toABullets.SetData_t( CTFILENAME("Textures\\Interface\\AmBullets.tex"));
_toARockets.SetData_t( CTFILENAME("Textures\\Interface\\AmRockets.tex"));
_toAGrenades.SetData_t( CTFILENAME("Textures\\Interface\\AmGrenades.tex"));
_toANapalm.SetData_t( CTFILENAME("Textures\\Interface\\AmFuelReservoir.tex"));
_toAElectricity.SetData_t( CTFILENAME("Textures\\Interface\\AmElectricity.tex"));
_toAIronBall.SetData_t( CTFILENAME("Textures\\Interface\\AmCannon.tex"));
// initialize weapon textures
_toWKnife.SetData_t( CTFILENAME("Textures\\Interface\\WKnife.tex"));
_toWColt.SetData_t( CTFILENAME("Textures\\Interface\\WColt.tex"));
_toWSingleShotgun.SetData_t( CTFILENAME("Textures\\Interface\\WSingleShotgun.tex"));
_toWDoubleShotgun.SetData_t( CTFILENAME("Textures\\Interface\\WDoubleShotgun.tex"));
_toWTommygun.SetData_t( CTFILENAME("Textures\\Interface\\WTommygun.tex"));
_toWMinigun.SetData_t( CTFILENAME("Textures\\Interface\\WMinigun.tex"));
_toWRocketLauncher.SetData_t( CTFILENAME("Textures\\Interface\\WRocketLauncher.tex"));
_toWGrenadeLauncher.SetData_t( CTFILENAME("Textures\\Interface\\WGrenadeLauncher.tex"));
_toWPipeBomb.SetData_t( CTFILENAME("Textures\\Interface\\WPipeBomb.tex"));
_toWFlamer.SetData_t( CTFILENAME("Textures\\Interface\\WFlamer.tex"));
_toWGhostBuster.SetData_t( CTFILENAME("Textures\\Interface\\WGhostBuster.tex"));
_toWLaser.SetData_t( CTFILENAME("Textures\\Interface\\WLaser.tex"));
_toWIronCannon.SetData_t( CTFILENAME("Textures\\Interface\\WCannon.tex"));
// initialize tile texture
_toTile.SetData_t( CTFILENAME("Textures\\Interface\\Tile.tex"));
// set all textures as constant
((CTextureData*)_toHealth .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toArmor .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toOxygen .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toFrags .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toDeaths .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toScore .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toHiScore.GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toMessage.GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toMana .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toAShells .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toABullets .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toARockets .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toAGrenades .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toANapalm .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toAElectricity.GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toAIronBall .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWKnife .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWColt .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWSingleShotgun .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWDoubleShotgun .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWTommygun .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWMinigun .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWRocketLauncher .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWGrenadeLauncher.GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWPipeBomb .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWFlamer .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWGhostBuster .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWLaser .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toWIronCannon .GetData())->Force(TEX_CONSTANT);
((CTextureData*)_toTile .GetData())->Force(TEX_CONSTANT);
}
catch( char *strError) {
FatalError( strError);
}
}
// clean up
extern void EndHUD(void)
{
}
| 47,887
|
C++
|
.cpp
| 1,008
| 43.332341
| 153
| 0.680748
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,536,205
|
SeriousSam.cpp
|
sultim-t_Serious-Engine-Vk/Sources/SeriousSam/SeriousSam.cpp
|
/* Copyright (c) 2002-2012 Croteam Ltd.
Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "StdH.h"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <process.h>
#include <Engine/CurrentVersion.h>
#include <GameMP/Game.h>
#define DECL_DLL
#ifdef SS_THE_FIRST_ENCOUNTER
#include <Entities/Global.h>
#else
#include <EntitiesMP/Global.h>
#endif
#include "resource.h"
#include "SplashScreen.h"
#include "MainWindow.h"
#include "GlSettings.h"
#include "LevelInfo.h"
#include "LCDDrawing.h"
#include "CmdLine.h"
#include "Credits.h"
extern CGame *_pGame = NULL;
// application state variables
extern BOOL _bRunning = TRUE;
extern BOOL _bQuitScreen = TRUE;
extern BOOL bMenuActive = FALSE;
extern BOOL bMenuRendering = FALSE;
extern BOOL _bDefiningKey;
static BOOL _bReconsiderInput = FALSE;
extern PIX _pixDesktopWidth = 0; // desktop width when started (for some tests)
static INDEX sam_iMaxFPSActive = 500;
static INDEX sam_iMaxFPSInactive = 10;
static INDEX sam_bPauseOnMinimize = TRUE; // auto-pause when window has been minimized
extern INDEX sam_bWideScreen = FALSE;
extern FLOAT sam_fPlayerOffset = 0.0f;
// display mode settings
extern INDEX sam_bFullScreenActive = FALSE;
extern INDEX sam_iScreenSizeI = 1024; // current size of the window
extern INDEX sam_iScreenSizeJ = 768; // current size of the window
extern INDEX sam_iDisplayDepth = 0; // 0==default, 1==16bit, 2==32bit
extern INDEX sam_iDisplayAdapter = 0;
#ifdef SE1_VULKAN
extern INDEX sam_iGfxAPI = 1; // 1==Vulkan
#else
extern INDEX sam_iGfxAPI = 0; // 0==OpenGL
#endif // SE1_VULKAN
extern INDEX sam_bFirstStarted = FALSE;
extern FLOAT sam_tmDisplayModeReport = 5.0f;
extern INDEX sam_bShowAllLevels = FALSE;
extern INDEX sam_bMentalActivated = FALSE;
// network settings
extern CTString sam_strNetworkSettings = "";
// command line
extern CTString sam_strCommandLine = "";
// 0...app started for the first time
// 1...all ok
// 2...automatic fallback
static INDEX _iDisplayModeChangeFlag = 0;
static TIME _tmDisplayModeChanged = 100.0f; // when display mode was last changed
// rendering preferences for automatic settings
extern INDEX sam_iVideoSetup = 1; // 0==speed, 1==normal, 2==quality, 3==custom
// automatic adjustment of audio quality
extern BOOL sam_bAutoAdjustAudio = TRUE;
extern INDEX sam_bAutoPlayDemos = TRUE;
static INDEX _bInAutoPlayLoop = TRUE;
// menu calling
extern INDEX sam_bMenuSave = FALSE;
extern INDEX sam_bMenuLoad = FALSE;
extern INDEX sam_bMenuControls = FALSE;
extern INDEX sam_bMenuHiScore = FALSE;
extern INDEX sam_bToggleConsole = FALSE;
extern INDEX sam_iStartCredits = FALSE;
// for mod re-loading
extern CTFileName _fnmModToLoad = CTString("");
extern CTString _strModServerJoin = CTString("");
extern CTString _strURLToVisit = CTString("");
// state variables fo addon execution
// 0 - nothing
// 1 - start (invoke console)
// 2 - console invoked, waiting for one redraw
extern INDEX _iAddonExecState = 0;
extern CTFileName _fnmAddonToExec = CTString("");
// logo textures
static CTextureObject _toLogoCT;
static CTextureObject _toLogoODI;
static CTextureObject _toLogoEAX;
extern CTextureObject *_ptoLogoCT = NULL;
extern CTextureObject *_ptoLogoODI = NULL;
extern CTextureObject *_ptoLogoEAX = NULL;
#ifdef SS_THE_FIRST_ENCOUNTER
extern CTString sam_strVersion = "1.10";
extern CTString sam_strModName = TRANS( "- O P E N S O U R C E -" );
extern CTString sam_strFirstLevel = "Levels\\01_Hatshepsut.wld";
extern CTString sam_strIntroLevel = "Levels\\Intro.wld";
extern CTString sam_strGameName = "serioussamfe";
extern CTString sam_strTechTestLevel = "Levels\\TechTest.wld";
extern CTString sam_strTrainingLevel = "Levels\\KarnakDemo.wld";
#else
extern CTString sam_strVersion = "1.10";
extern CTString sam_strModName = TRANS( "- O P E N S O U R C E -" );
extern CTString sam_strFirstLevel = "Levels\\LevelsMP\\1_0_InTheLastEpisode.wld";
extern CTString sam_strIntroLevel = "Levels\\LevelsMP\\Intro.wld";
extern CTString sam_strGameName = "serioussamse";
extern CTString sam_strTechTestLevel = "Levels\\LevelsMP\\Technology\\TechTest.wld";
extern CTString sam_strTrainingLevel = "Levels\\KarnakDemo.wld";
#endif // SE_TFE
ENGINE_API extern INDEX snd_iFormat;
// main window canvas
CDrawPort *pdp;
CDrawPort *pdpNormal;
CDrawPort *pdpWideScreen;
CViewPort *pvpViewPort;
HINSTANCE _hInstance;
static void PlayDemo(void* pArgs)
{
CTString strDemoFilename = *NEXTARGUMENT(CTString*);
_gmMenuGameMode = GM_DEMO;
CTFileName fnDemo = "demos\\" + strDemoFilename + ".dem";
extern BOOL LSLoadDemo(const CTFileName &fnm);
LSLoadDemo(fnDemo);
}
static void ApplyRenderingPreferences(void)
{
ApplyGLSettings(TRUE);
}
extern void ApplyVideoMode(void)
{
StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ,
(enum DisplayDepth)sam_iDisplayDepth, sam_bFullScreenActive);
}
static void BenchMark(void)
{
_pGfx->Benchmark(pvpViewPort, pdp);
}
static void QuitGame(void)
{
_bRunning = FALSE;
_bQuitScreen = FALSE;
}
// check if another app is already running
static HANDLE _hLock = NULL;
static CTFileName _fnmLock;
static void DirectoryLockOn(void)
{
// create lock filename
_fnmLock = _fnmApplicationPath+"SeriousSam.loc";
// try to open lock file
_hLock = CreateFileA(
_fnmLock,
GENERIC_WRITE,
0/*no sharing*/,
NULL, // pointer to security attributes
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_DELETE_ON_CLOSE, // file attributes
NULL);
// if failed
if (_hLock==NULL || GetLastError()!=0) {
// report warning
CPrintF(TRANS("WARNING: SeriousSam didn't shut down properly last time!\n"));
}
}
static void DirectoryLockOff(void)
{
// if lock is open
if (_hLock!=NULL) {
// close it
CloseHandle(_hLock);
}
}
void End(void);
// automaticaly manage input enable/disable toggling
static BOOL _bInputEnabled = FALSE;
void UpdateInputEnabledState(void)
{
// do nothing if window is invalid
if( _hwndMain==NULL) return;
// input should be enabled if application is active
// and no menu is active and no console is active
BOOL bShouldBeEnabled = (!IsIconic(_hwndMain) && !bMenuActive && _pGame->gm_csConsoleState==CS_OFF
&& (_pGame->gm_csComputerState==CS_OFF || _pGame->gm_csComputerState==CS_ONINBACKGROUND))
|| _bDefiningKey;
// if should be turned off
if( (!bShouldBeEnabled && _bInputEnabled) || _bReconsiderInput) {
// disable it and remember new state
_pInput->DisableInput();
_bInputEnabled = FALSE;
}
// if should be turned on
if( bShouldBeEnabled && !_bInputEnabled) {
// enable it and remember new state
_pInput->EnableInput(_hwndMain);
_bInputEnabled = TRUE;
}
_bReconsiderInput = FALSE;
}
// automaticaly manage pause toggling
void UpdatePauseState(void)
{
BOOL bShouldPause = (_gmRunningGameMode==GM_SINGLE_PLAYER) && (bMenuActive ||
_pGame->gm_csConsoleState ==CS_ON || _pGame->gm_csConsoleState ==CS_TURNINGON || _pGame->gm_csConsoleState ==CS_TURNINGOFF ||
_pGame->gm_csComputerState==CS_ON || _pGame->gm_csComputerState==CS_TURNINGON || _pGame->gm_csComputerState==CS_TURNINGOFF);
_pNetwork->SetLocalPause(bShouldPause);
}
// limit current frame rate if neeeded
void LimitFrameRate(void)
{
// measure passed time for each loop
static CTimerValue tvLast(-1.0f);
CTimerValue tvNow = _pTimer->GetHighPrecisionTimer();
TIME tmCurrentDelta = (tvNow-tvLast).GetSeconds();
// limit maximum frame rate
sam_iMaxFPSActive = ClampDn( (INDEX)sam_iMaxFPSActive, 1L);
sam_iMaxFPSInactive = ClampDn( (INDEX)sam_iMaxFPSInactive, 1L);
INDEX iMaxFPS = sam_iMaxFPSActive;
if( IsIconic(_hwndMain)) iMaxFPS = sam_iMaxFPSInactive;
if(_pGame->gm_CurrentSplitScreenCfg==CGame::SSC_DEDICATED) {
iMaxFPS = ClampDn(iMaxFPS, 60L); // never go very slow if dedicated server
}
TIME tmWantedDelta = 1.0f / iMaxFPS;
if( tmCurrentDelta<tmWantedDelta) Sleep( (tmWantedDelta-tmCurrentDelta)*1000.0f);
// remember new time
tvLast = _pTimer->GetHighPrecisionTimer();
}
// load first demo
void StartNextDemo(void)
{
if (!sam_bAutoPlayDemos || !_bInAutoPlayLoop) {
_bInAutoPlayLoop = FALSE;
return;
}
// skip if no demos
if(_lhAutoDemos.IsEmpty()) {
_bInAutoPlayLoop = FALSE;
return;
}
// get first demo level and cycle the list
CLevelInfo *pli = LIST_HEAD(_lhAutoDemos, CLevelInfo, li_lnNode);
pli->li_lnNode.Remove();
_lhAutoDemos.AddTail(pli->li_lnNode);
// if intro
if (pli->li_fnLevel==sam_strIntroLevel) {
// start intro
_gmRunningGameMode = GM_NONE;
_pGame->gm_aiStartLocalPlayers[0] = 0;
_pGame->gm_aiStartLocalPlayers[1] = -1;
_pGame->gm_aiStartLocalPlayers[2] = -1;
_pGame->gm_aiStartLocalPlayers[3] = -1;
_pGame->gm_strNetworkProvider = "Local";
_pGame->gm_StartSplitScreenCfg = CGame::SSC_PLAY1;
_pShell->SetINDEX("gam_iStartDifficulty", CSessionProperties::GD_NORMAL);
_pShell->SetINDEX("gam_iStartMode", CSessionProperties::GM_FLYOVER);
CUniversalSessionProperties sp;
_pGame->SetSinglePlayerSession(sp);
_pGame->gm_bFirstLoading = TRUE;
if (_pGame->NewGame( sam_strIntroLevel, sam_strIntroLevel, sp)) {
_gmRunningGameMode = GM_INTRO;
}
// if not intro
} else {
// start the demo
_pGame->gm_StartSplitScreenCfg = CGame::SSC_OBSERVER;
_pGame->gm_aiStartLocalPlayers[0] = -1;
_pGame->gm_aiStartLocalPlayers[1] = -1;
_pGame->gm_aiStartLocalPlayers[2] = -1;
_pGame->gm_aiStartLocalPlayers[3] = -1;
// play the demo
_pGame->gm_strNetworkProvider = "Local";
_gmRunningGameMode = GM_NONE;
if( _pGame->StartDemoPlay( pli->li_fnLevel)) {
_gmRunningGameMode = GM_DEMO;
CON_DiscardLastLineTimes();
}
}
if (_gmRunningGameMode==GM_NONE) {
_bInAutoPlayLoop = FALSE;
}
}
BOOL _bCDPathFound = FALSE;
BOOL FileExistsOnHD(const CTString &strFile)
{
FILE *f = fopen(_fnmApplicationPath+strFile, "rb");
if (f!=NULL) {
fclose(f);
return TRUE;
} else {
return FALSE;
}
}
void TrimString(char *str)
{
int i = strlen(str);
if (str[i-1]=='\n' || str[i-1]=='\r') {
str[i-1]=0;
}
}
// run web browser and view an url
void RunBrowser(const char *strUrl)
{
int iResult = (int)ShellExecuteA( _hwndMain, "OPEN", strUrl, NULL, NULL, SW_SHOWMAXIMIZED);
if (iResult<32) {
// should report error?
NOTHING;
}
}
void LoadAndForceTexture(CTextureObject &to, CTextureObject *&pto, const CTFileName &fnm)
{
try {
to.SetData_t(fnm);
CTextureData *ptd = (CTextureData*)to.GetData();
ptd->Force( TEX_CONSTANT);
ptd = ptd->td_ptdBaseTexture;
if( ptd!=NULL) ptd->Force( TEX_CONSTANT);
pto = &to;
} catch( char *pchrError) {
(void*)pchrError;
pto = NULL;
}
}
void InitializeGame(void)
{
try {
#ifndef NDEBUG
#define GAMEDLL (_fnmApplicationExe.FileDir()+"Game"+_strModExt+"D.dll")
#else
#define GAMEDLL (_fnmApplicationExe.FileDir()+"Game"+_strModExt+".dll")
#endif
CTFileName fnmExpanded;
ExpandFilePath(EFP_READ, CTString(GAMEDLL), fnmExpanded);
CPrintF(TRANS("Loading game library '%s'...\n"), (const char *)fnmExpanded);
HMODULE hGame = LoadLibraryA(fnmExpanded);
if (hGame==NULL) {
ThrowF_t("%s", GetWindowsError(GetLastError()));
}
CGame* (*GAME_Create)(void) = (CGame* (*)(void))GetProcAddress(hGame, "GAME_Create");
if (GAME_Create==NULL) {
ThrowF_t("%s", GetWindowsError(GetLastError()));
}
_pGame = GAME_Create();
} catch (char *strError) {
FatalError("%s", strError);
}
// init game - this will load persistent symbols
_pGame->Initialize(CTString("Data\\SeriousSam.gms"));
}
BOOL Init( HINSTANCE hInstance, int nCmdShow, CTString strCmdLine)
{
_hInstance = hInstance;
ShowSplashScreen(hInstance);
// remember desktop width
_pixDesktopWidth = ::GetSystemMetrics(SM_CXSCREEN);
// prepare main window
MainWindow_Init();
OpenMainWindowInvisible();
// parse command line before initializing engine
ParseCommandLine(strCmdLine);
// initialize engine
SE_InitEngine(sam_strGameName);
SE_LoadDefaultFonts();
// now print the output of command line parsing
CPrintF("%s", cmd_strOutput);
// lock the directory
DirectoryLockOn();
// load all translation tables
InitTranslation();
try {
AddTranslationTablesDir_t(CTString("Data\\Translations\\"), CTString("*.txt"));
FinishTranslationTable();
} catch (char *strError) {
FatalError("%s", strError);
}
// always disable all warnings when in serious sam
_pShell->Execute( "con_bNoWarnings=1;");
// declare shell symbols
_pShell->DeclareSymbol("user void PlayDemo(CTString);", &PlayDemo);
_pShell->DeclareSymbol("persistent INDEX sam_bFullScreen;", &sam_bFullScreenActive);
_pShell->DeclareSymbol("persistent INDEX sam_iScreenSizeI;", &sam_iScreenSizeI);
_pShell->DeclareSymbol("persistent INDEX sam_iScreenSizeJ;", &sam_iScreenSizeJ);
_pShell->DeclareSymbol("persistent INDEX sam_iDisplayDepth;", &sam_iDisplayDepth);
_pShell->DeclareSymbol("persistent INDEX sam_iDisplayAdapter;", &sam_iDisplayAdapter);
_pShell->DeclareSymbol("persistent INDEX sam_iGfxAPI;", &sam_iGfxAPI);
_pShell->DeclareSymbol("persistent INDEX sam_bFirstStarted;", &sam_bFirstStarted);
_pShell->DeclareSymbol("persistent INDEX sam_bAutoAdjustAudio;", &sam_bAutoAdjustAudio);
_pShell->DeclareSymbol("persistent user INDEX sam_bWideScreen;", &sam_bWideScreen);
_pShell->DeclareSymbol("persistent user FLOAT sam_fPlayerOffset;", &sam_fPlayerOffset);
_pShell->DeclareSymbol("persistent user INDEX sam_bAutoPlayDemos;", &sam_bAutoPlayDemos);
_pShell->DeclareSymbol("persistent user INDEX sam_iMaxFPSActive;", &sam_iMaxFPSActive);
_pShell->DeclareSymbol("persistent user INDEX sam_iMaxFPSInactive;", &sam_iMaxFPSInactive);
_pShell->DeclareSymbol("persistent user INDEX sam_bPauseOnMinimize;", &sam_bPauseOnMinimize);
_pShell->DeclareSymbol("persistent user FLOAT sam_tmDisplayModeReport;", &sam_tmDisplayModeReport);
_pShell->DeclareSymbol("persistent user CTString sam_strNetworkSettings;", &sam_strNetworkSettings);
_pShell->DeclareSymbol("persistent user CTString sam_strIntroLevel;", &sam_strIntroLevel);
_pShell->DeclareSymbol("persistent user CTString sam_strGameName;", &sam_strGameName);
_pShell->DeclareSymbol("user CTString sam_strVersion;", &sam_strVersion);
_pShell->DeclareSymbol("user CTString sam_strFirstLevel;", &sam_strFirstLevel);
_pShell->DeclareSymbol("user CTString sam_strModName;", &sam_strModName);
_pShell->DeclareSymbol("persistent INDEX sam_bShowAllLevels;", &sam_bShowAllLevels);
_pShell->DeclareSymbol("persistent INDEX sam_bMentalActivated;", &sam_bMentalActivated);
_pShell->DeclareSymbol("user CTString sam_strTechTestLevel;", &sam_strTechTestLevel);
_pShell->DeclareSymbol("user CTString sam_strTrainingLevel;", &sam_strTrainingLevel);
_pShell->DeclareSymbol("user void Quit(void);", &QuitGame);
_pShell->DeclareSymbol("persistent user INDEX sam_iVideoSetup;", &sam_iVideoSetup);
_pShell->DeclareSymbol("user void ApplyRenderingPreferences(void);", &ApplyRenderingPreferences);
_pShell->DeclareSymbol("user void ApplyVideoMode(void);", &ApplyVideoMode);
_pShell->DeclareSymbol("user void Benchmark(void);", &BenchMark);
_pShell->DeclareSymbol("user INDEX sam_bMenuSave;", &sam_bMenuSave);
_pShell->DeclareSymbol("user INDEX sam_bMenuLoad;", &sam_bMenuLoad);
_pShell->DeclareSymbol("user INDEX sam_bMenuControls;", &sam_bMenuControls);
_pShell->DeclareSymbol("user INDEX sam_bMenuHiScore;", &sam_bMenuHiScore);
_pShell->DeclareSymbol("user INDEX sam_bToggleConsole;",&sam_bToggleConsole);
_pShell->DeclareSymbol("INDEX sam_iStartCredits;", &sam_iStartCredits);
InitializeGame();
_pNetwork->md_strGameID = sam_strGameName;
LCDInit();
if( sam_bFirstStarted) {
InfoMessage("%s", TRANS(
"SeriousSam is starting for the first time.\n"
"If you experience any problems, please consult\n"
"ReadMe file for troubleshooting information."));
}
// initialize sound library
snd_iFormat = Clamp( snd_iFormat, (INDEX)CSoundLibrary::SF_NONE, (INDEX)CSoundLibrary::SF_44100_16);
_pSound->SetFormat( (enum CSoundLibrary::SoundFormat)snd_iFormat);
if (sam_bAutoAdjustAudio) {
_pShell->Execute("include \"Scripts\\Addons\\SFX-AutoAdjust.ini\"");
}
// execute script given on command line
if (cmd_strScript!="") {
CPrintF("Command line script: '%s'\n", cmd_strScript);
CTString strCmd;
strCmd.PrintF("include \"%s\"", cmd_strScript);
_pShell->Execute(strCmd);
}
// load logo textures
LoadAndForceTexture(_toLogoCT, _ptoLogoCT, CTFILENAME("Textures\\Logo\\LogoCT.tex"));
LoadAndForceTexture(_toLogoODI, _ptoLogoODI, CTFILENAME("Textures\\Logo\\GodGamesLogo.tex"));
LoadAndForceTexture(_toLogoEAX, _ptoLogoEAX, CTFILENAME("Textures\\Logo\\LogoEAX.tex"));
// !! NOTE !! Re-enable these to allow mod support.
LoadStringVar(CTString("Data\\Var\\Sam_Version.var"), sam_strVersion);
LoadStringVar(CTString("Data\\Var\\ModName.var"), sam_strModName);
CPrintF(TRANS("Serious Sam version: %s\n"), sam_strVersion);
CPrintF(TRANS("Active mod: %s\n"), sam_strModName);
InitializeMenus();
// if there is a mod
if (_fnmMod!="") {
// execute the mod startup script
_pShell->Execute(CTString("include \"Scripts\\Mod_startup.ini\";"));
}
// init gl settings module
InitGLSettings();
// init level-info subsystem
LoadLevelsList();
LoadDemosList();
// apply application mode
StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ,
(enum DisplayDepth)sam_iDisplayDepth, sam_bFullScreenActive);
// set default mode reporting
if( sam_bFirstStarted) {
_iDisplayModeChangeFlag = 0;
sam_bFirstStarted = FALSE;
}
HideSplashScreen();
if (cmd_strPassword!="") {
_pShell->SetString("net_strConnectPassword", cmd_strPassword);
}
// if connecting to server from command line
if (cmd_strServer!="") {
CTString strPort = "";
if (cmd_iPort>0) {
_pShell->SetINDEX("net_iPort", cmd_iPort);
strPort.PrintF(":%d", cmd_iPort);
}
CPrintF(TRANS("Command line connection: '%s%s'\n"), cmd_strServer, strPort);
// go to join menu
_pGame->gam_strJoinAddress = cmd_strServer;
if (cmd_bQuickJoin) {
extern void JoinNetworkGame(void);
JoinNetworkGame();
} else {
StartMenus("join");
}
// if starting world from command line
} else if (cmd_strWorld!="") {
CPrintF(TRANS("Command line world: '%s'\n"), cmd_strWorld);
// try to start the game with that level
try {
if (cmd_iGoToMarker>=0) {
CPrintF(TRANS("Command line marker: %d\n"), cmd_iGoToMarker);
CTString strCommand;
strCommand.PrintF("cht_iGoToMarker = %d;", cmd_iGoToMarker);
_pShell->Execute(strCommand);
}
_pGame->gam_strCustomLevel = cmd_strWorld;
if (cmd_bServer) {
extern void StartNetworkGame(void);
StartNetworkGame();
} else {
extern void StartSinglePlayerGame(void);
StartSinglePlayerGame();
}
} catch (char *strError) {
CPrintF(TRANS("Cannot start '%s': '%s'\n"), cmd_strWorld, strError);
}
// if no relevant starting at command line
} else {
StartNextDemo();
}
return TRUE;
}
void End(void)
{
_pGame->DisableLoadingHook();
// cleanup level-info subsystem
ClearLevelsList();
ClearDemosList();
// destroy the main window and its canvas
if (pvpViewPort!=NULL) {
_pGfx->DestroyWindowCanvas( pvpViewPort);
pvpViewPort = NULL;
pdpNormal = NULL;
}
CloseMainWindow();
MainWindow_End();
DestroyMenus();
_pGame->End();
LCDEnd();
// unlock the directory
DirectoryLockOff();
SE_EndEngine();
}
// print display mode info if needed
void PrintDisplayModeInfo(void)
{
// skip if timed out
if( _pTimer->GetRealTimeTick() > (_tmDisplayModeChanged+sam_tmDisplayModeReport)) return;
// cache some general vars
SLONG slDPWidth = pdp->GetWidth();
SLONG slDPHeight = pdp->GetHeight();
if( pdp->IsDualHead()) slDPWidth/=2;
CDisplayMode dm;
dm.dm_pixSizeI = slDPWidth;
dm.dm_pixSizeJ = slDPHeight;
// determine proper text scale for statistics display
FLOAT fTextScale = (FLOAT)slDPWidth/640.0f;
// get resolution
CTString strRes;
extern CTString _strPreferencesDescription;
strRes.PrintF( "%dx%dx%s", slDPWidth, slDPHeight, _pGfx->gl_dmCurrentDisplayMode.DepthString());
if( dm.IsDualHead()) strRes += TRANS(" DualMonitor");
if( dm.IsWideScreen()) strRes += TRANS(" WideScreen");
if( _pGfx->gl_eCurrentAPI==GAT_OGL) strRes += " (OpenGL)";
#ifdef SE1_D3D
else if( _pGfx->gl_eCurrentAPI==GAT_D3D) strRes += " (Direct3D)";
#endif // SE1_D3D
#ifdef SE1_VULKAN
else if (_pGfx->gl_eCurrentAPI == GAT_VK) strRes += " (Vulkan)";
#endif // SE1_VULKAN
CTString strDescr;
strDescr.PrintF("\n%s (%s)\n", _strPreferencesDescription, RenderingPreferencesDescription(sam_iVideoSetup));
strRes+=strDescr;
// tell if application is started for the first time, or failed to set mode
if( _iDisplayModeChangeFlag==0) {
strRes += TRANS("Display mode set by default!");
} else if( _iDisplayModeChangeFlag==2) {
strRes += TRANS("Last mode set failed!");
}
// print it all
pdp->SetFont( _pfdDisplayFont);
pdp->SetTextScaling( fTextScale);
pdp->SetTextAspect( 1.0f);
pdp->PutText( strRes, slDPWidth*0.05f, slDPHeight*0.85f, LCDGetColor(C_GREEN|255, "display mode"));
}
// do the main game loop and render screen
void DoGame(void)
{
// set flag if not in game
if( !_pGame->gm_bGameOn) _gmRunningGameMode = GM_NONE;
if( _gmRunningGameMode==GM_DEMO && _pNetwork->IsDemoPlayFinished()
||_gmRunningGameMode==GM_INTRO && _pNetwork->IsGameFinished()) {
_pGame->StopGame();
_gmRunningGameMode = GM_NONE;
// load next demo
StartNextDemo();
if (!_bInAutoPlayLoop) {
// start menu
StartMenus();
}
}
// do the main game loop
if( _gmRunningGameMode != GM_NONE) {
_pGame->GameMainLoop();
// if game is not started
} else {
// just handle broadcast messages
_pNetwork->GameInactive();
}
if (sam_iStartCredits>0) {
Credits_On(sam_iStartCredits);
sam_iStartCredits = 0;
}
if (sam_iStartCredits<0) {
Credits_Off();
sam_iStartCredits = 0;
}
if( _gmRunningGameMode==GM_NONE) {
Credits_Off();
sam_iStartCredits = 0;
}
// redraw the view
if( !IsIconic(_hwndMain) && pdp!=NULL && pdp->Lock())
{
if( _gmRunningGameMode!=GM_NONE && !bMenuActive ) {
// handle pretouching of textures and shadowmaps
pdp->Unlock();
_pGame->GameRedrawView( pdp, (_pGame->gm_csConsoleState!=CS_OFF || bMenuActive)?0:GRV_SHOWEXTRAS);
pdp->Lock();
_pGame->ComputerRender(pdp);
pdp->Unlock();
CDrawPort dpScroller(pdp, TRUE);
dpScroller.Lock();
if (Credits_Render(&dpScroller)==0) {
Credits_Off();
}
dpScroller.Unlock();
pdp->Lock();
} else {
pdp->Fill( LCDGetColor(C_dGREEN|CT_OPAQUE, "bcg fill"));
}
// do menu
if( bMenuRendering) {
// clear z-buffer
pdp->FillZBuffer( ZBUF_BACK);
// remember if we should render menus next tick
bMenuRendering = DoMenu(pdp);
}
// print display mode info if needed
PrintDisplayModeInfo();
// render console
_pGame->ConsoleRender(pdp);
// done with all
pdp->Unlock();
// clear upper and lower parts of screen if in wide screen mode
if( pdp==pdpWideScreen && pdpNormal->Lock()) {
const PIX pixWidth = pdpWideScreen->GetWidth();
const PIX pixHeight = (pdpNormal->GetHeight() - pdpWideScreen->GetHeight()) /2;
const PIX pixJOfs = pixHeight + pdpWideScreen->GetHeight()-1;
pdpNormal->Fill( 0, 0, pixWidth, pixHeight, C_BLACK|CT_OPAQUE);
pdpNormal->Fill( 0, pixJOfs, pixWidth, pixHeight, C_BLACK|CT_OPAQUE);
pdpNormal->Unlock();
}
// show
pvpViewPort->SwapBuffers();
}
}
void TeleportPlayer(int iPosition)
{
CTString strCommand;
strCommand.PrintF( "cht_iGoToMarker = %d;", iPosition);
_pShell->Execute(strCommand);
}
CTextureObject _toStarField;
static FLOAT _fLastVolume = 1.0f;
void RenderStarfield(CDrawPort *pdp, FLOAT fStrength)
{
CTextureData *ptd = (CTextureData *)_toStarField.GetData();
// skip if no texture
if(ptd==NULL) return;
PIX pixSizeI = pdp->GetWidth();
PIX pixSizeJ = pdp->GetHeight();
FLOAT fStretch = pixSizeI/640.0f;
fStretch*=FLOAT(ptd->GetPixWidth())/ptd->GetWidth();
PIXaabbox2D boxScreen(PIX2D(0,0), PIX2D(pixSizeI, pixSizeJ));
MEXaabbox2D boxTexture(MEX2D(0, 0), MEX2D(pixSizeI/fStretch, pixSizeJ/fStretch));
pdp->PutTexture(&_toStarField, boxScreen, boxTexture, LerpColor(C_BLACK, C_WHITE, fStrength)|CT_OPAQUE);
}
FLOAT RenderQuitScreen(CDrawPort *pdp, CViewPort *pvp)
{
CDrawPort dpQuit(pdp, TRUE);
CDrawPort dpWide;
dpQuit.MakeWideScreen(&dpWide);
// redraw the view
if (!dpWide.Lock()) {
return 0;
}
dpWide.Fill(C_BLACK|CT_OPAQUE);
RenderStarfield(&dpWide, _fLastVolume);
FLOAT fVolume = Credits_Render(&dpWide);
_fLastVolume = fVolume;
dpWide.Unlock();
pvp->SwapBuffers();
return fVolume;
}
void QuitScreenLoop(void)
{
Credits_On(3);
CSoundObject soMusic;
try {
_toStarField.SetData_t(CTFILENAME("Textures\\Background\\Night01\\Stars01.tex"));
soMusic.Play_t(CTFILENAME("Music\\Credits.mp3"), SOF_NONGAME|SOF_MUSIC|SOF_LOOP);
} catch (char *strError) {
CPrintF("%s\n", strError);
}
// while it is still running
FOREVER {
FLOAT fVolume = RenderQuitScreen(pdp, pvpViewPort);
if (fVolume<=0) {
return;
}
// assure we can listen to non-3d sounds
soMusic.SetVolume(fVolume, fVolume);
_pSound->UpdateSounds();
// while there are any messages in the message queue
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
// if it is not a keyboard or mouse message
if(msg.message==WM_LBUTTONDOWN||
msg.message==WM_RBUTTONDOWN||
msg.message==WM_KEYDOWN) {
return;
}
}
//Sleep(5);
}
}
int SubMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
(void)hPrevInstance;
if( !Init( hInstance, nCmdShow, lpCmdLine )) return FALSE;
// initialy, application is running and active, console and menu are off
_bRunning = TRUE;
_bQuitScreen = TRUE;
_pGame->gm_csConsoleState = CS_OFF;
_pGame->gm_csComputerState = CS_OFF;
// bMenuActive = FALSE;
// bMenuRendering = FALSE;
// while it is still running
while( _bRunning && _fnmModToLoad=="")
{
// while there are any messages in the message queue
MSG msg;
while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE)) {
// if it is not a mouse message
if( !(msg.message>=WM_MOUSEFIRST && msg.message<=WM_MOUSELAST) ) {
// if not system key messages
if( !(msg.message==WM_KEYDOWN && msg.wParam==VK_F10
||msg.message==WM_SYSKEYDOWN)) {
// dispatch it
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// system commands (also send by the application itself)
if( msg.message==WM_SYSCOMMAND)
{
switch( msg.wParam & ~0x0F) {
// if should minimize
case SC_MINIMIZE:
if( _bWindowChanging) break;
_bWindowChanging = TRUE;
_bReconsiderInput = TRUE;
// if allowed, not already paused and only in single player game mode
if( sam_bPauseOnMinimize && !_pNetwork->IsPaused() && _gmRunningGameMode==GM_SINGLE_PLAYER) {
// pause game
_pNetwork->TogglePause();
}
// if in full screen
if( sam_bFullScreenActive) {
// reset display mode and minimize window
_pGfx->ResetDisplayMode();
ShowWindow(_hwndMain, SW_MINIMIZE);
// if not in full screen
} else {
// just minimize the window
ShowWindow(_hwndMain, SW_MINIMIZE);
}
break;
// if should restore
case SC_RESTORE:
if( _bWindowChanging) break;
_bWindowChanging = TRUE;
_bReconsiderInput = TRUE;
// if in full screen
if( sam_bFullScreenActive) {
ShowWindow(_hwndMain, SW_SHOWNORMAL);
// set the display mode once again
StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ,
(enum DisplayDepth)sam_iDisplayDepth, sam_bFullScreenActive);
// if not in full screen
} else {
// restore window
ShowWindow(_hwndMain, SW_SHOWNORMAL);
}
break;
// if should maximize
case SC_MAXIMIZE:
if( _bWindowChanging) break;
_bWindowChanging = TRUE;
_bReconsiderInput = TRUE;
// go to full screen
StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ,
(enum DisplayDepth)sam_iDisplayDepth, TRUE);
ShowWindow( _hwndMain, SW_SHOWNORMAL);
break;
}
}
// toggle full-screen on alt-enter
if( msg.message==WM_SYSKEYDOWN && msg.wParam==VK_RETURN && !IsIconic(_hwndMain)) {
StartNewMode( (GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ,
(enum DisplayDepth)sam_iDisplayDepth, !sam_bFullScreenActive);
}
// if application should stop
if( msg.message==WM_QUIT || msg.message==WM_CLOSE) {
// stop running
_bRunning = FALSE;
_bQuitScreen = FALSE;
}
// if application is deactivated or minimized
if( (msg.message==WM_ACTIVATE && (LOWORD(msg.wParam)==WA_INACTIVE || HIWORD(msg.wParam)))
|| msg.message==WM_CANCELMODE
|| msg.message==WM_KILLFOCUS
|| (msg.message==WM_ACTIVATEAPP && !msg.wParam)) {
// if application is running and in full screen mode
if( !_bWindowChanging && _bRunning) {
// minimize if in full screen
if( sam_bFullScreenActive) PostMessage(NULL, WM_SYSCOMMAND, SC_MINIMIZE, 0);
// just disable input if not in full screen
else _pInput->DisableInput();
}
}
// if application is activated or minimized
else if( (msg.message==WM_ACTIVATE && (LOWORD(msg.wParam)==WA_ACTIVE || LOWORD(msg.wParam)==WA_CLICKACTIVE))
|| msg.message==WM_SETFOCUS
|| (msg.message==WM_ACTIVATEAPP && msg.wParam)) {
// enable input back again if needed
_bReconsiderInput = TRUE;
}
if (msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE &&
(_gmRunningGameMode==GM_DEMO || _gmRunningGameMode==GM_INTRO)) {
_pGame->StopGame();
_gmRunningGameMode=GM_NONE;
}
if (_pGame->gm_csConsoleState==CS_TALK && msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE) {
_pGame->gm_csConsoleState = CS_OFF;
msg.message=WM_NULL;
}
BOOL bMenuForced = (_gmRunningGameMode==GM_NONE &&
(_pGame->gm_csConsoleState==CS_OFF || _pGame->gm_csConsoleState==CS_TURNINGOFF));
BOOL bMenuToggle = (msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE
&& (_pGame->gm_csComputerState==CS_OFF || _pGame->gm_csComputerState==CS_ONINBACKGROUND));
if( !bMenuActive) {
if( bMenuForced || bMenuToggle) {
// if console is active
if( _pGame->gm_csConsoleState==CS_ON || _pGame->gm_csConsoleState==CS_TURNINGON) {
// deactivate it
_pGame->gm_csConsoleState = CS_TURNINGOFF;
_iAddonExecState = 0;
}
// delete key down message so menu would not exit because of it
msg.message=WM_NULL;
// start menu
StartMenus();
}
} else {
if (bMenuForced && bMenuToggle && pgmCurrentMenu->gm_pgmParentMenu == NULL) {
// delete key down message so menu would not exit because of it
msg.message=WM_NULL;
}
}
// if neither menu nor console is running
if (!bMenuActive && (_pGame->gm_csConsoleState==CS_OFF || _pGame->gm_csConsoleState==CS_TURNINGOFF)) {
// if current menu is not root
if (!IsMenusInRoot()) {
// start current menu
StartMenus();
}
}
if (sam_bMenuSave) {
sam_bMenuSave = FALSE;
StartMenus("save");
}
if (sam_bMenuLoad) {
sam_bMenuLoad = FALSE;
StartMenus("load");
}
if (sam_bMenuControls) {
sam_bMenuControls = FALSE;
StartMenus("controls");
}
if (sam_bMenuHiScore) {
sam_bMenuHiScore = FALSE;
StartMenus("hiscore");
}
// interpret console key presses
if (_iAddonExecState==0) {
if (msg.message==WM_KEYDOWN) {
_pGame->ConsoleKeyDown(msg);
if (_pGame->gm_csConsoleState!=CS_ON) {
_pGame->ComputerKeyDown(msg);
}
} else if (msg.message==WM_KEYUP) {
// special handler for talk (not to invoke return key bind)
if( msg.wParam==VK_RETURN && _pGame->gm_csConsoleState==CS_TALK) _pGame->gm_csConsoleState = CS_OFF;
} else if (msg.message==WM_CHAR) {
_pGame->ConsoleChar(msg);
}
if (msg.message==WM_LBUTTONDOWN
||msg.message==WM_RBUTTONDOWN
||msg.message==WM_LBUTTONDBLCLK
||msg.message==WM_RBUTTONDBLCLK
||msg.message==WM_LBUTTONUP
||msg.message==WM_RBUTTONUP) {
if (_pGame->gm_csConsoleState!=CS_ON) {
_pGame->ComputerKeyDown(msg);
}
}
}
// if menu is active and no input on
if( bMenuActive && !_pInput->IsInputEnabled()) {
// pass keyboard/mouse messages to menu
if(msg.message==WM_KEYDOWN) {
MenuOnKeyDown( msg.wParam);
} else if (msg.message==WM_LBUTTONDOWN || msg.message==WM_LBUTTONDBLCLK) {
MenuOnKeyDown(VK_LBUTTON);
} else if (msg.message==WM_RBUTTONDOWN || msg.message==WM_RBUTTONDBLCLK) {
MenuOnKeyDown(VK_RBUTTON);
} else if (msg.message==WM_MOUSEMOVE) {
MenuOnMouseMove(LOWORD(msg.lParam), HIWORD(msg.lParam));
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x020A
#endif
} else if (msg.message==WM_MOUSEWHEEL) {
SWORD swDir = SWORD(UWORD(HIWORD(msg.wParam)));
if (swDir>0) {
MenuOnKeyDown(11);
} else if (swDir<0) {
MenuOnKeyDown(10);
}
} else if (msg.message==WM_CHAR) {
MenuOnChar(msg);
}
}
// if toggling console
BOOL bConsoleKey = sam_bToggleConsole || msg.message==WM_KEYDOWN &&
(MapVirtualKey(msg.wParam, 0)==41 // scan code for '~'
|| msg.wParam==VK_F1 || (msg.wParam==VK_ESCAPE && _iAddonExecState==3));
if(bConsoleKey && !_bDefiningKey)
{
sam_bToggleConsole = FALSE;
if( _iAddonExecState==3) _iAddonExecState = 0;
// if it is up, or pulling up
if( _pGame->gm_csConsoleState==CS_OFF || _pGame->gm_csConsoleState==CS_TURNINGOFF) {
// start it moving down and disable menu
_pGame->gm_csConsoleState = CS_TURNINGON;
// stop all IFeel effects
IFeel_StopEffect(NULL);
if( bMenuActive) {
StopMenus(FALSE);
}
// if it is down, or dropping down
} else if( _pGame->gm_csConsoleState==CS_ON || _pGame->gm_csConsoleState==CS_TURNINGON) {
// start it moving up
_pGame->gm_csConsoleState = CS_TURNINGOFF;
}
}
if (_pShell->GetINDEX("con_bTalk") && _pGame->gm_csConsoleState==CS_OFF) {
_pShell->SetINDEX("con_bTalk", FALSE);
_pGame->gm_csConsoleState = CS_TALK;
}
// if pause pressed
if (msg.message==WM_KEYDOWN && msg.wParam==VK_PAUSE) {
// toggle pause
_pNetwork->TogglePause();
}
// if command sent from external application
if (msg.message==WM_COMMAND) {
// if teleport player
if (msg.wParam==1001) {
// teleport player
TeleportPlayer(msg.lParam);
// restore
PostMessage(NULL, WM_SYSCOMMAND, SC_RESTORE, 0);
}
}
// if demo is playing
if (_gmRunningGameMode==GM_DEMO ||
_gmRunningGameMode==GM_INTRO ) {
// check if escape is pressed
BOOL bEscape = (msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE);
// check if console-invoke key is pressed
BOOL bTilde = (msg.message==WM_KEYDOWN &&
(msg.wParam==VK_F1 || MapVirtualKey(msg.wParam, 0)==41));// scan code for '~'
// check if any key is pressed
BOOL bAnyKey = (
(msg.message==WM_KEYDOWN && (msg.wParam==VK_SPACE || msg.wParam==VK_RETURN))||
msg.message==WM_LBUTTONDOWN||msg.message==WM_RBUTTONDOWN);
// if escape is pressed
if (bEscape) {
// stop demo
_pGame->StopGame();
_bInAutoPlayLoop = FALSE;
_gmRunningGameMode = GM_NONE;
// if any other key is pressed except console invoking
} else if (bAnyKey && !bTilde) {
// if not in menu or in console
if (!bMenuActive && !bMenuRendering && _pGame->gm_csConsoleState==CS_OFF) {
// skip to next demo
_pGame->StopGame();
_gmRunningGameMode = GM_NONE;
StartNextDemo();
}
}
}
} // loop while there are messages
// when all messages are removed, window has surely changed
_bWindowChanging = FALSE;
// get real cursor position
if( _pGame->gm_csComputerState!=CS_OFF && _pGame->gm_csComputerState!=CS_ONINBACKGROUND) {
POINT pt;
::GetCursorPos(&pt);
::ScreenToClient(_hwndMain, &pt);
_pGame->ComputerMouseMove(pt.x, pt.y);
}
// if addon is to be executed
if (_iAddonExecState==1) {
// print header and start console
CPrintF(TRANS("---- Executing addon: '%s'\n"), (const char*)_fnmAddonToExec);
sam_bToggleConsole = TRUE;
_iAddonExecState = 2;
// if addon is ready for execution
} else if (_iAddonExecState==2 && _pGame->gm_csConsoleState == CS_ON) {
// execute it
CTString strCmd;
strCmd.PrintF("include \"%s\"", (const char*)_fnmAddonToExec);
_pShell->Execute(strCmd);
CPrintF(TRANS("Addon done, press Escape to close console\n"));
_iAddonExecState = 3;
}
// automaticaly manage input enable/disable toggling
UpdateInputEnabledState();
// automaticaly manage pause toggling
UpdatePauseState();
// notify game whether menu is active
_pGame->gm_bMenuOn = bMenuActive;
// do the main game loop and render screen
DoGame();
// limit current frame rate if neeeded
LimitFrameRate();
} // end of main application loop
_pInput->DisableInput();
_pGame->StopGame();
if (_fnmModToLoad!="") {
char strCmd [64] = {0};
char strParam [128] = {0};
STARTUPINFOA cif;
ZeroMemory(&cif,sizeof(STARTUPINFOA));
PROCESS_INFORMATION pi;
strcpy_s(strCmd,"SeriousSam.exe");
strcpy_s(strParam," +game ");
strcat_s(strParam,_fnmModToLoad.FileName());
if (_strModServerJoin!="") {
strcat_s(strParam," +connect ");
strcat_s(strParam,_strModServerJoin);
strcat_s(strParam," +quickjoin");
}
if (CreateProcessA(strCmd,strParam,NULL,NULL,FALSE,CREATE_DEFAULT_ERROR_MODE,NULL,NULL,&cif,&pi) == FALSE)
{
MessageBox(0, L"error launching the Mod!\n", L"Serious Sam", MB_OK|MB_ICONERROR);
}
}
// invoke quit screen if needed
if( _bQuitScreen && _fnmModToLoad=="") QuitScreenLoop();
End();
return TRUE;
}
/*
void CheckModReload(void)
{
if (_fnmModToLoad!="") {
CTString strCommand = _fnmApplicationExe.FileDir()+"SeriousSam.exe";
//+mod "+_fnmModToLoad.FileName()+"\"";
CTString strMod = _fnmModToLoad.FileName();
const char *argv[7];
argv[0] = strCommand;
argv[1] = "+game";
argv[2] = strMod;
argv[3] = NULL;
if (_strModServerJoin!="") {
argv[3] = "+connect";
argv[4] = _strModServerJoin;
argv[5] = "+quickjoin";
argv[6] = NULL;
}
_execv(strCommand, argv);
}
}*/
void CheckTeaser(void)
{
CTFileName fnmTeaser = _fnmApplicationExe.FileDir()+CTString("AfterSam.exe");
if (fopen(fnmTeaser, "r")!=NULL) {
Sleep(500);
_execl(fnmTeaser, "\""+fnmTeaser+"\"", NULL);
}
}
void CheckBrowser(void)
{
if (_strURLToVisit!="") {
RunBrowser(_strURLToVisit);
}
}
int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
int iResult;
CTSTREAM_BEGIN {
iResult = SubMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
} CTSTREAM_END;
//CheckModReload();
CheckTeaser();
CheckBrowser();
return iResult;
}
// try to start a new display mode
BOOL TryToSetDisplayMode( enum GfxAPIType eGfxAPI, INDEX iAdapter, PIX pixSizeI, PIX pixSizeJ,
enum DisplayDepth eColorDepth, BOOL bFullScreenMode)
{
CDisplayMode dmTmp;
dmTmp.dm_ddDepth = eColorDepth;
CPrintF( TRANS(" Starting display mode: %dx%dx%s (%s)\n"),
pixSizeI, pixSizeJ, dmTmp.DepthString(),
bFullScreenMode ? TRANS("fullscreen") : TRANS("window"));
// mark to start ignoring window size/position messages until settled down
_bWindowChanging = TRUE;
// destroy canvas if existing
_pGame->DisableLoadingHook();
if( pvpViewPort!=NULL) {
_pGfx->DestroyWindowCanvas( pvpViewPort);
pvpViewPort = NULL;
pdpNormal = NULL;
}
// close the application window
CloseMainWindow();
// try to set new display mode
BOOL bSuccess;
// TODO: enable full screen for vulkan
#ifdef SE1_VULKAN
{
#else // SE1_VULKAN
if( bFullScreenMode) {
#ifdef SE1_D3D
if( eGfxAPI==GAT_D3D) OpenMainWindowFullScreen( pixSizeI, pixSizeJ);
#endif // SE1_D3D
bSuccess = _pGfx->SetDisplayMode( eGfxAPI, iAdapter, pixSizeI, pixSizeJ, eColorDepth);
if( bSuccess && eGfxAPI==GAT_OGL) OpenMainWindowFullScreen( pixSizeI, pixSizeJ);
} else {
#endif // SE1_VULKAN
#ifdef SE1_D3D
if( eGfxAPI==GAT_D3D) OpenMainWindowNormal( pixSizeI, pixSizeJ);
#endif // SE1_D3D
#ifdef SE1_VULKAN
if (eGfxAPI == GAT_VK) OpenMainWindowNormal(pixSizeI, pixSizeJ);
#endif // SE1_VULKAN
bSuccess = _pGfx->ResetDisplayMode( eGfxAPI);
if( bSuccess && eGfxAPI==GAT_OGL) OpenMainWindowNormal( pixSizeI, pixSizeJ);
#ifdef SE1_D3D
if( bSuccess && eGfxAPI==GAT_D3D) ResetMainWindowNormal();
#endif // SE1_D3D
}
// if new mode was set
if( bSuccess) {
// create canvas
ASSERT( pvpViewPort==NULL);
ASSERT( pdpNormal==NULL);
_pGfx->CreateWindowCanvas( _hwndMain, &pvpViewPort, &pdpNormal);
// erase context of both buffers (for the sake of wide-screen)
pdp = pdpNormal;
if( pdp!=NULL && pdp->Lock()) {
pdp->Fill(C_BLACK|CT_OPAQUE);
pdp->Unlock();
pvpViewPort->SwapBuffers();
pdp->Lock();
pdp->Fill(C_BLACK|CT_OPAQUE);
pdp->Unlock();
pvpViewPort->SwapBuffers();
}
// lets try some wide screen screaming :)
const PIX pixYBegAdj = pdp->GetHeight() * 21/24;
const PIX pixYEndAdj = pdp->GetHeight() * 3/24;
const PIX pixXEnd = pdp->GetWidth();
pdpWideScreen = new CDrawPort( pdp, PIXaabbox2D( PIX2D(0,pixYBegAdj), PIX2D(pixXEnd, pixYEndAdj)));
pdpWideScreen->dp_fWideAdjustment = 9.0f / 12.0f;
if( sam_bWideScreen) pdp = pdpWideScreen;
// initial screen fill and swap, just to get context running
BOOL bSuccess = FALSE;
if( pdp!=NULL && pdp->Lock()) {
pdp->Fill( LCDGetColor( C_dGREEN|CT_OPAQUE, "bcg fill"));
pdp->Unlock();
pvpViewPort->SwapBuffers();
bSuccess = TRUE;
}
_pGame->EnableLoadingHook(pdp);
// if the mode is not working, or is not accelerated
if( !bSuccess || !_pGfx->IsCurrentModeAccelerated())
{ // report error
CPrintF( TRANS("This mode does not support hardware acceleration.\n"));
// destroy canvas if existing
if( pvpViewPort!=NULL) {
_pGame->DisableLoadingHook();
_pGfx->DestroyWindowCanvas( pvpViewPort);
pvpViewPort = NULL;
pdpNormal = NULL;
}
// close the application window
CloseMainWindow();
// report failure
return FALSE;
}
// remember new settings
sam_bFullScreenActive = bFullScreenMode;
sam_iScreenSizeI = pixSizeI;
sam_iScreenSizeJ = pixSizeJ;
sam_iDisplayDepth = eColorDepth;
sam_iDisplayAdapter = iAdapter;
sam_iGfxAPI = eGfxAPI;
// report success
return TRUE;
// if couldn't set new mode
} else {
// close the application window
CloseMainWindow();
// report failure
return FALSE;
}
}
// list of possible display modes for recovery
const INDEX aDefaultModes[][3] =
{ // color, API, adapter
{ DD_DEFAULT, GAT_OGL, 0},
{ DD_16BIT, GAT_OGL, 0},
{ DD_16BIT, GAT_OGL, 1}, // 3dfx Voodoo2
#ifdef SE1_D3D
{ DD_DEFAULT, GAT_D3D, 0},
{ DD_16BIT, GAT_D3D, 0},
{ DD_16BIT, GAT_D3D, 1},
#endif // SE1_D3D
};
const INDEX ctDefaultModes = ARRAYCOUNT(aDefaultModes);
// start new display mode
void StartNewMode( enum GfxAPIType eGfxAPI, INDEX iAdapter, PIX pixSizeI, PIX pixSizeJ,
enum DisplayDepth eColorDepth, BOOL bFullScreenMode)
{
CPrintF( TRANS("\n* START NEW DISPLAY MODE ...\n"));
// try to set the mode
BOOL bSuccess = TryToSetDisplayMode( eGfxAPI, iAdapter, pixSizeI, pixSizeJ, eColorDepth, bFullScreenMode);
// if failed
if( !bSuccess)
{
// report failure and reset to default resolution
_iDisplayModeChangeFlag = 2; // failure
CPrintF( TRANS("Requested display mode could not be set!\n"));
pixSizeI = 640;
pixSizeJ = 480;
bFullScreenMode = TRUE;
// try to revert to one of recovery modes
for( INDEX iMode=0; iMode<ctDefaultModes; iMode++) {
eColorDepth = (DisplayDepth)aDefaultModes[iMode][0];
eGfxAPI = (GfxAPIType) aDefaultModes[iMode][1];
iAdapter = aDefaultModes[iMode][2];
CPrintF(TRANS("\nTrying recovery mode %d...\n"), iMode);
bSuccess = TryToSetDisplayMode( eGfxAPI, iAdapter, pixSizeI, pixSizeJ, eColorDepth, bFullScreenMode);
if( bSuccess) break;
}
// if all failed
if( !bSuccess) {
FatalError(TRANS(
"Cannot set display mode!\n"
"Serious Sam was unable to find display mode with hardware acceleration.\n"
"Make sure you install proper drivers for your video card as recommended\n"
"in documentation and set your desktop to 16 bit (65536 colors).\n"
"Please see ReadMe file for troubleshooting information.\n"));
}
// if succeeded
} else {
_iDisplayModeChangeFlag = 1; // all ok
}
// apply 3D-acc settings
ApplyGLSettings(FALSE);
// remember time of mode setting
_tmDisplayModeChanged = _pTimer->GetRealTimeTick();
}
| 48,117
|
C++
|
.cpp
| 1,300
| 31.865385
| 148
| 0.672862
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,536,206
|
MenuStuff.cpp
|
sultim-t_Serious-Engine-Vk/Sources/SeriousSam/GUI/Menus/MenuStuff.cpp
|
/* Copyright (c) 2002-2012 Croteam Ltd.
Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "StdH.h"
#include <Engine/Build.h>
#include "MenuStuff.h"
#define RADIOTRANS(str) ("ETRS" str)
extern CTString astrNoYes[] = {
RADIOTRANS("No"),
RADIOTRANS("Yes"),
};
extern CTString astrComputerInvoke[] = {
RADIOTRANS("Use"),
RADIOTRANS("Double-click use"),
};
extern CTString astrWeapon[] = {
RADIOTRANS("Only if new"),
RADIOTRANS("Never"),
RADIOTRANS("Always"),
RADIOTRANS("Only if stronger"),
};
extern PIX apixWidths[][2] = {
640, 480,
960, 720,
1024, 768,
1280, 960,
1280, 720,
1600, 900,
1920, 1080,
2048, 1152,
2560, 1440,
3200, 1800,
3840, 2160,
//320, 240,
//400, 300,
//512, 384,
//640, 240,
//640, 480,
//720, 540,
//800, 300,
//800, 600,
//960, 720,
//1024, 384,
//1024, 768,
//1152, 864,
//1280, 480,
//1280, 960,
//1600, 600,
//1600, 1200,
//1920, 720,
//1920, 1440,
//2048, 786,
//2048, 1536,
};
extern CTString astrCrosshair[] = {
"",
"Textures\\Interface\\Crosshairs\\Crosshair1.tex",
"Textures\\Interface\\Crosshairs\\Crosshair2.tex",
"Textures\\Interface\\Crosshairs\\Crosshair3.tex",
"Textures\\Interface\\Crosshairs\\Crosshair4.tex",
"Textures\\Interface\\Crosshairs\\Crosshair5.tex",
"Textures\\Interface\\Crosshairs\\Crosshair6.tex",
"Textures\\Interface\\Crosshairs\\Crosshair7.tex",
};
extern CTString astrMaxPlayersRadioTexts[] = {
RADIOTRANS("2"),
RADIOTRANS("3"),
RADIOTRANS("4"),
RADIOTRANS("5"),
RADIOTRANS("6"),
RADIOTRANS("7"),
RADIOTRANS("8"),
RADIOTRANS("9"),
RADIOTRANS("10"),
RADIOTRANS("11"),
RADIOTRANS("12"),
RADIOTRANS("13"),
RADIOTRANS("14"),
RADIOTRANS("15"),
RADIOTRANS("16"),
};
// here, we just reserve space for up to 16 different game types
// actual names are added later
extern CTString astrGameTypeRadioTexts[] = {
"", "", "", "", "",
"", "", "", "", "",
"", "", "", "", "",
"", "", "", "", "",
};
extern INDEX ctGameTypeRadioTexts = 1;
extern CTString astrDifficultyRadioTexts[] = {
RADIOTRANS("Tourist"),
RADIOTRANS("Easy"),
RADIOTRANS("Normal"),
RADIOTRANS("Hard"),
RADIOTRANS("Serious"),
RADIOTRANS("Mental"),
};
extern CTString astrSplitScreenRadioTexts[] = {
RADIOTRANS("1"),
RADIOTRANS("2 - split screen"),
RADIOTRANS("3 - split screen"),
RADIOTRANS("4 - split screen"),
};
extern CTString astrDisplayPrefsRadioTexts[] = {
RADIOTRANS("Speed"),
RADIOTRANS("Normal"),
RADIOTRANS("Quality"),
RADIOTRANS("Custom"),
};
extern CTString astrDisplayAPIRadioTexts[] = {
RADIOTRANS("OpenGL"),
#ifndef SE1_VULKAN
RADIOTRANS("Direct3D"),
#else // SE1_VULKAN
RADIOTRANS("Vulkan")
#endif // SE1_VULKAN
};
extern CTString astrBitsPerPixelRadioTexts[] = {
RADIOTRANS("Desktop"),
RADIOTRANS("16 BPP"),
RADIOTRANS("32 BPP"),
};
extern CTString astrFrequencyRadioTexts[] = {
RADIOTRANS("No sound"),
RADIOTRANS("11kHz"),
RADIOTRANS("22kHz"),
RADIOTRANS("44kHz"),
};
extern CTString astrSoundAPIRadioTexts[] = {
RADIOTRANS("WaveOut"),
RADIOTRANS("DirectSound"),
RADIOTRANS("EAX"),
};
ULONG GetSpawnFlagsForGameType(INDEX iGameType)
{
if (iGameType == -1) return SPF_SINGLEPLAYER;
// get function that will provide us the flags
CShellSymbol *pss = _pShell->GetSymbol("GetSpawnFlagsForGameTypeSS", /*bDeclaredOnly=*/ TRUE);
// if none
if (pss == NULL) {
// error
ASSERT(FALSE);
return 0;
}
ULONG(*pFunc)(INDEX) = (ULONG(*)(INDEX))pss->ss_pvValue;
return pFunc(iGameType);
}
BOOL IsMenuEnabled(const CTString &strMenuName)
{
// get function that will provide us the flags
CShellSymbol *pss = _pShell->GetSymbol("IsMenuEnabledSS", /*bDeclaredOnly=*/ TRUE);
// if none
if (pss == NULL) {
// error
ASSERT(FALSE);
return TRUE;
}
BOOL(*pFunc)(const CTString &) = (BOOL(*)(const CTString &))pss->ss_pvValue;
return pFunc(strMenuName);
}
// initialize game type strings table
void InitGameTypes(void)
{
// get function that will provide us the info about gametype
CShellSymbol *pss = _pShell->GetSymbol("GetGameTypeNameSS", /*bDeclaredOnly=*/ TRUE);
// if none
if (pss == NULL) {
// error
astrGameTypeRadioTexts[0] = "<???>";
ctGameTypeRadioTexts = 1;
return;
}
// for each mode
for (ctGameTypeRadioTexts = 0; ctGameTypeRadioTexts<ARRAYCOUNT(astrGameTypeRadioTexts); ctGameTypeRadioTexts++) {
// get the text
CTString(*pFunc)(INDEX) = (CTString(*)(INDEX))pss->ss_pvValue;
CTString strMode = pFunc(ctGameTypeRadioTexts);
// if no mode modes
if (strMode == "") {
// stop
break;
}
// add that mode
astrGameTypeRadioTexts[ctGameTypeRadioTexts] = strMode;
}
}
int qsort_CompareFileInfos_NameUp(const void *elem1, const void *elem2)
{
const CFileInfo &fi1 = **(CFileInfo **)elem1;
const CFileInfo &fi2 = **(CFileInfo **)elem2;
return strcmp(fi1.fi_strName, fi2.fi_strName);
}
int qsort_CompareFileInfos_NameDn(const void *elem1, const void *elem2)
{
const CFileInfo &fi1 = **(CFileInfo **)elem1;
const CFileInfo &fi2 = **(CFileInfo **)elem2;
return -strcmp(fi1.fi_strName, fi2.fi_strName);
}
int qsort_CompareFileInfos_FileUp(const void *elem1, const void *elem2)
{
const CFileInfo &fi1 = **(CFileInfo **)elem1;
const CFileInfo &fi2 = **(CFileInfo **)elem2;
return strcmp(fi1.fi_fnFile, fi2.fi_fnFile);
}
int qsort_CompareFileInfos_FileDn(const void *elem1, const void *elem2)
{
const CFileInfo &fi1 = **(CFileInfo **)elem1;
const CFileInfo &fi2 = **(CFileInfo **)elem2;
return -strcmp(fi1.fi_fnFile, fi2.fi_fnFile);
}
INDEX APIToSwitch(enum GfxAPIType gat)
{
switch (gat) {
case GAT_OGL: return 0;
#ifdef SE1_D3D
case GAT_D3D: return 1;
#endif // SE1_D3D
#ifdef SE1_VULKAN
case GAT_VK: return GAT_VK_INDEX;
#endif // SE1_VULKAN
default: ASSERT(FALSE); return 0;
}
}
enum GfxAPIType SwitchToAPI(INDEX i)
{
switch (i) {
case 0: return GAT_OGL;
#ifdef SE1_D3D
case 1: return GAT_D3D;
#endif // SE1_D3D
#ifdef SE1_VULKAN
case GAT_VK_INDEX: return GAT_VK;
#endif // SE1_VULKAN
default: ASSERT(FALSE); return GAT_OGL;
}
}
INDEX DepthToSwitch(enum DisplayDepth dd)
{
switch (dd) {
case DD_DEFAULT: return 0;
case DD_16BIT: return 1;
case DD_32BIT: return 2;
default: ASSERT(FALSE); return 0;
}
}
enum DisplayDepth SwitchToDepth(INDEX i)
{
switch (i) {
case 0: return DD_DEFAULT;
case 1: return DD_16BIT;
case 2: return DD_32BIT;
default: ASSERT(FALSE); return DD_DEFAULT;
}
}
// controls that are currently customized
CTFileName _fnmControlsToCustomize = CTString("");
void ControlsMenuOn()
{
_pGame->SavePlayersAndControls();
try {
_pGame->gm_ctrlControlsExtra.Load_t(_fnmControlsToCustomize);
}
catch (char *strError) {
WarningMessage(strError);
}
}
void ControlsMenuOff()
{
try {
if (_pGame->gm_ctrlControlsExtra.ctrl_lhButtonActions.Count()>0) {
_pGame->gm_ctrlControlsExtra.Save_t(_fnmControlsToCustomize);
}
}
catch (char *strError) {
FatalError(strError);
}
FORDELETELIST(CButtonAction, ba_lnNode, _pGame->gm_ctrlControlsExtra.ctrl_lhButtonActions, itAct) {
delete &itAct.Current();
}
_pGame->LoadPlayersAndControls();
}
| 7,836
|
C++
|
.cpp
| 291
| 24.268041
| 115
| 0.70321
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,536,207
|
MenuActions.cpp
|
sultim-t_Serious-Engine-Vk/Sources/SeriousSam/GUI/Menus/MenuActions.cpp
|
/* Copyright (c) 2002-2012 Croteam Ltd.
Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "StdH.h"
#include <Engine/Build.h>
#include "MenuManager.h"
#include "MenuStarters.h"
#include "MenuStuff.h"
#include "GUI/Components/MenuGadget.h"
#include "LevelInfo.h"
#include "VarList.h"
ENGINE_API extern INDEX snd_iFormat;
extern BOOL _bMouseUsedLast;
extern CMenuGadget *_pmgLastActivatedGadget;
extern CMenuGadget *_pmgUnderCursor;
static INDEX _ctAdapters = 0;
static CTString * _astrAdapterTexts = NULL;
static INDEX _ctResolutions = 0;
static CTString * _astrResolutionTexts = NULL;
static CDisplayMode *_admResolutionModes = NULL;
#define VOLUME_STEPS 50
// make description for a given resolution
static CTString GetResolutionDescription(CDisplayMode &dm)
{
CTString str;
// if dual head
if (dm.IsDualHead()) {
str.PrintF(TRANS("%dx%d double"), dm.dm_pixSizeI / 2, dm.dm_pixSizeJ);
// if widescreen
} else if (dm.IsWideScreen()) {
str.PrintF(TRANS("%dx%d wide"), dm.dm_pixSizeI, dm.dm_pixSizeJ);
// otherwise it is normal
} else {
str.PrintF("%dx%d", dm.dm_pixSizeI, dm.dm_pixSizeJ);
}
return str;
}
// make description for a given resolution
static void SetResolutionInList(INDEX iRes, PIX pixSizeI, PIX pixSizeJ)
{
ASSERT(iRes >= 0 && iRes<_ctResolutions);
CTString &str = _astrResolutionTexts[iRes];
CDisplayMode &dm = _admResolutionModes[iRes];
dm.dm_pixSizeI = pixSizeI;
dm.dm_pixSizeJ = pixSizeJ;
str = GetResolutionDescription(dm);
}
static void ResolutionToSize(INDEX iRes, PIX &pixSizeI, PIX &pixSizeJ)
{
ASSERT(iRes >= 0 && iRes<_ctResolutions);
CDisplayMode &dm = _admResolutionModes[iRes];
pixSizeI = dm.dm_pixSizeI;
pixSizeJ = dm.dm_pixSizeJ;
}
static void SizeToResolution(PIX pixSizeI, PIX pixSizeJ, INDEX &iRes)
{
for (iRes = 0; iRes<_ctResolutions; iRes++) {
CDisplayMode &dm = _admResolutionModes[iRes];
if (dm.dm_pixSizeI == pixSizeI && dm.dm_pixSizeJ == pixSizeJ) {
return;
}
}
// if none was found, search for default
for (iRes = 0; iRes<_ctResolutions; iRes++) {
CDisplayMode &dm = _admResolutionModes[iRes];
if (dm.dm_pixSizeI == 640 && dm.dm_pixSizeJ == 480) {
return;
}
}
// if still none found
ASSERT(FALSE); // this should never happen
// return first one
iRes = 0;
}
// ------------------------ CConfirmMenu implementation
extern CTFileName _fnmModToLoad;
extern CTString _strModServerJoin;
CTFileName _fnmModSelected;
CTString _strModURLSelected;
CTString _strModServerSelected;
static void ExitGame(void)
{
_bRunning = FALSE;
_bQuitScreen = TRUE;
}
static void ExitConfirm(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
gmCurrent._pConfimedYes = &ExitGame;
gmCurrent._pConfimedNo = NULL;
gmCurrent.gm_mgConfirmLabel.mg_strText = TRANS("ARE YOU SERIOUS?");
gmCurrent.gm_pgmParentMenu = pgmCurrentMenu;
gmCurrent.BeLarge();
ChangeToMenu(&gmCurrent);
}
static void StopCurrentGame(void)
{
_pGame->StopGame();
_gmRunningGameMode = GM_NONE;
StopMenus(TRUE);
StartMenus("");
}
static void StopConfirm(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
gmCurrent._pConfimedYes = &StopCurrentGame;
gmCurrent._pConfimedNo = NULL;
gmCurrent.gm_mgConfirmLabel.mg_strText = TRANS("ARE YOU SERIOUS?");
gmCurrent.gm_pgmParentMenu = pgmCurrentMenu;
gmCurrent.BeLarge();
ChangeToMenu(&gmCurrent);
}
static void ModLoadYes(void)
{
_fnmModToLoad = _fnmModSelected;
}
static void ModConnect(void)
{
_fnmModToLoad = _fnmModSelected;
_strModServerJoin = _strModServerSelected;
}
extern void ModConnectConfirm(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
if (_fnmModSelected == " ") {
_fnmModSelected = CTString("SeriousSam");
}
CTFileName fnmModPath = "Mods\\" + _fnmModSelected + "\\";
if (!FileExists(fnmModPath + "BaseWriteInclude.lst")
&& !FileExists(fnmModPath + "BaseWriteExclude.lst")
&& !FileExists(fnmModPath + "BaseBrowseInclude.lst")
&& !FileExists(fnmModPath + "BaseBrowseExclude.lst")) {
extern void ModNotInstalled(void);
ModNotInstalled();
return;
}
CPrintF(TRANS("Server is running a different MOD (%s).\nYou need to reload to connect.\n"), _fnmModSelected);
gmCurrent._pConfimedYes = &ModConnect;
gmCurrent._pConfimedNo = NULL;
gmCurrent.gm_mgConfirmLabel.mg_strText = TRANS("CHANGE THE MOD?");
gmCurrent.gm_pgmParentMenu = pgmCurrentMenu;
gmCurrent.BeLarge();
ChangeToMenu(&gmCurrent);
}
void SaveConfirm(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
extern void OnFileSaveOK(void);
gmCurrent._pConfimedYes = &OnFileSaveOK;
gmCurrent._pConfimedNo = NULL;
gmCurrent.gm_mgConfirmLabel.mg_strText = TRANS("OVERWRITE?");
gmCurrent.gm_pgmParentMenu = pgmCurrentMenu;
gmCurrent.BeLarge();
ChangeToMenu(&gmCurrent);
}
void ExitAndSpawnExplorer(void)
{
_bRunning = FALSE;
_bQuitScreen = FALSE;
extern CTString _strURLToVisit;
_strURLToVisit = _strModURLSelected;
}
void ModNotInstalled(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
gmCurrent._pConfimedYes = &ExitAndSpawnExplorer;
gmCurrent._pConfimedNo = NULL;
gmCurrent.gm_mgConfirmLabel.mg_strText.PrintF(
TRANS("You don't have MOD '%s' installed.\nDo you want to visit its web site?"), (const char*)_fnmModSelected);
gmCurrent.gm_pgmParentMenu = pgmCurrentMenu;
gmCurrent.BeSmall();
ChangeToMenu(&gmCurrent);
}
extern void ModConfirm(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
gmCurrent._pConfimedYes = &ModLoadYes;
gmCurrent._pConfimedNo = NULL;
gmCurrent.gm_mgConfirmLabel.mg_strText = TRANS("LOAD THIS MOD?");
gmCurrent.gm_pgmParentMenu = &_pGUIM->gmLoadSaveMenu;
gmCurrent.BeLarge();
ChangeToMenu(&gmCurrent);
}
static void RevertVideoSettings(void);
void VideoConfirm(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
// FIXUP: keyboard focus lost when going from full screen to window mode
// due to WM_MOUSEMOVE being sent
_bMouseUsedLast = FALSE;
_pmgUnderCursor = gmCurrent.gm_pmgSelectedByDefault;
gmCurrent._pConfimedYes = NULL;
gmCurrent._pConfimedNo = RevertVideoSettings;
gmCurrent.gm_mgConfirmLabel.mg_strText = TRANS("KEEP THIS SETTING?");
gmCurrent.gm_pgmParentMenu = pgmCurrentMenu;
gmCurrent.BeLarge();
ChangeToMenu(&gmCurrent);
}
static void ConfirmYes(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
if (gmCurrent._pConfimedYes != NULL) {
gmCurrent._pConfimedYes();
}
void MenuGoToParent(void);
MenuGoToParent();
}
static void ConfirmNo(void)
{
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
if (gmCurrent._pConfimedNo != NULL) {
gmCurrent._pConfimedNo();
}
void MenuGoToParent(void);
MenuGoToParent();
}
void InitActionsForConfirmMenu() {
CConfirmMenu &gmCurrent = _pGUIM->gmConfirmMenu;
gmCurrent.gm_mgConfirmYes.mg_pActivatedFunction = &ConfirmYes;
gmCurrent.gm_mgConfirmNo.mg_pActivatedFunction = &ConfirmNo;
}
// ------------------------ CMainMenu implementation
void InitActionsForMainMenu() {
CMainMenu &gmCurrent = _pGUIM->gmMainMenu;
gmCurrent.gm_mgSingle.mg_pActivatedFunction = &StartSinglePlayerMenu;
gmCurrent.gm_mgNetwork.mg_pActivatedFunction = StartNetworkMenu;
gmCurrent.gm_mgSplitScreen.mg_pActivatedFunction = &StartSplitScreenMenu;
gmCurrent.gm_mgDemo.mg_pActivatedFunction = &StartDemoLoadMenu;
gmCurrent.gm_mgMods.mg_pActivatedFunction = &StartModsLoadMenu;
gmCurrent.gm_mgHighScore.mg_pActivatedFunction = &StartHighScoreMenu;
gmCurrent.gm_mgOptions.mg_pActivatedFunction = &StartOptionsMenu;
gmCurrent.gm_mgQuit.mg_pActivatedFunction = &ExitConfirm;
}
// ------------------------ CInGameMenu implementation
// start load/save menus depending on type of game running
static void QuickSaveFromMenu()
{
_pShell->SetINDEX("gam_bQuickSave", 2); // force save with reporting
StopMenus(TRUE);
}
static void StopRecordingDemo(void)
{
_pNetwork->StopDemoRec();
void SetDemoStartStopRecText(void);
SetDemoStartStopRecText();
}
void InitActionsForInGameMenu()
{
CInGameMenu &gmCurrent = _pGUIM->gmInGameMenu;
gmCurrent.gm_mgQuickLoad.mg_pActivatedFunction = &StartCurrentQuickLoadMenu;
gmCurrent.gm_mgQuickSave.mg_pActivatedFunction = &QuickSaveFromMenu;
gmCurrent.gm_mgLoad.mg_pActivatedFunction = &StartCurrentLoadMenu;
gmCurrent.gm_mgSave.mg_pActivatedFunction = &StartCurrentSaveMenu;
gmCurrent.gm_mgHighScore.mg_pActivatedFunction = &StartHighScoreMenu;
gmCurrent.gm_mgOptions.mg_pActivatedFunction = &StartOptionsMenu;
gmCurrent.gm_mgStop.mg_pActivatedFunction = &StopConfirm;
gmCurrent.gm_mgQuit.mg_pActivatedFunction = &ExitConfirm;
}
extern void SetDemoStartStopRecText(void)
{
CInGameMenu &gmCurrent = _pGUIM->gmInGameMenu;
if (_pNetwork->IsRecordingDemo())
{
gmCurrent.gm_mgDemoRec.SetText(TRANS("STOP RECORDING"));
gmCurrent.gm_mgDemoRec.mg_strTip = TRANS("stop current recording");
gmCurrent.gm_mgDemoRec.mg_pActivatedFunction = &StopRecordingDemo;
} else {
gmCurrent.gm_mgDemoRec.SetText(TRANS("RECORD DEMO"));
gmCurrent.gm_mgDemoRec.mg_strTip = TRANS("start recording current game");
gmCurrent.gm_mgDemoRec.mg_pActivatedFunction = &StartDemoSaveMenu;
}
}
// ------------------------ CSinglePlayerMenu implementation
extern CTString sam_strTechTestLevel;
extern CTString sam_strTrainingLevel;
static void StartSinglePlayerGame_Normal(void);
static void StartTechTest(void)
{
_pGUIM->gmSinglePlayerNewMenu.gm_pgmParentMenu = &_pGUIM->gmSinglePlayerMenu;
_pGame->gam_strCustomLevel = sam_strTechTestLevel;
StartSinglePlayerGame_Normal();
}
static void StartTraining(void)
{
_pGUIM->gmSinglePlayerNewMenu.gm_pgmParentMenu = &_pGUIM->gmSinglePlayerMenu;
_pGame->gam_strCustomLevel = sam_strTrainingLevel;
ChangeToMenu(&_pGUIM->gmSinglePlayerNewMenu);
}
void InitActionsForSinglePlayerMenu()
{
CSinglePlayerMenu &gmCurrent = _pGUIM->gmSinglePlayerMenu;
gmCurrent.gm_mgNewGame.mg_pActivatedFunction = &StartSinglePlayerNewMenu;
gmCurrent.gm_mgCustom.mg_pActivatedFunction = &StartSelectLevelFromSingle;
gmCurrent.gm_mgQuickLoad.mg_pActivatedFunction = &StartSinglePlayerQuickLoadMenu;
gmCurrent.gm_mgLoad.mg_pActivatedFunction = &StartSinglePlayerLoadMenu;
gmCurrent.gm_mgTraining.mg_pActivatedFunction = &StartTraining;
gmCurrent.gm_mgTechTest.mg_pActivatedFunction = &StartTechTest;
gmCurrent.gm_mgPlayersAndControls.mg_pActivatedFunction = &StartChangePlayerMenuFromSinglePlayer;
gmCurrent.gm_mgOptions.mg_pActivatedFunction = &StartSinglePlayerGameOptions;
}
// ------------------------ CSinglePlayerNewMenu implementation
void StartSinglePlayerGame(void)
{
_pGame->gm_StartSplitScreenCfg = CGame::SSC_PLAY1;
_pGame->gm_aiStartLocalPlayers[0] = _pGame->gm_iSinglePlayer;
_pGame->gm_aiStartLocalPlayers[1] = -1;
_pGame->gm_aiStartLocalPlayers[2] = -1;
_pGame->gm_aiStartLocalPlayers[3] = -1;
_pGame->gm_strNetworkProvider = "Local";
CUniversalSessionProperties sp;
_pGame->SetSinglePlayerSession(sp);
if (_pGame->NewGame(_pGame->gam_strCustomLevel, _pGame->gam_strCustomLevel, sp))
{
StopMenus();
_gmRunningGameMode = GM_SINGLE_PLAYER;
} else {
_gmRunningGameMode = GM_NONE;
}
}
static void StartSinglePlayerGame_Tourist(void)
{
_pShell->SetINDEX("gam_iStartDifficulty", CSessionProperties::GD_TOURIST);
_pShell->SetINDEX("gam_iStartMode", CSessionProperties::GM_COOPERATIVE);
StartSinglePlayerGame();
}
static void StartSinglePlayerGame_Easy(void)
{
_pShell->SetINDEX("gam_iStartDifficulty", CSessionProperties::GD_EASY);
_pShell->SetINDEX("gam_iStartMode", CSessionProperties::GM_COOPERATIVE);
StartSinglePlayerGame();
}
static void StartSinglePlayerGame_Normal(void)
{
_pShell->SetINDEX("gam_iStartDifficulty", CSessionProperties::GD_NORMAL);
_pShell->SetINDEX("gam_iStartMode", CSessionProperties::GM_COOPERATIVE);
StartSinglePlayerGame();
}
static void StartSinglePlayerGame_Hard(void)
{
_pShell->SetINDEX("gam_iStartDifficulty", CSessionProperties::GD_HARD);
_pShell->SetINDEX("gam_iStartMode", CSessionProperties::GM_COOPERATIVE);
StartSinglePlayerGame();
}
static void StartSinglePlayerGame_Serious(void)
{
_pShell->SetINDEX("gam_iStartDifficulty", CSessionProperties::GD_EXTREME);
_pShell->SetINDEX("gam_iStartMode", CSessionProperties::GM_COOPERATIVE);
StartSinglePlayerGame();
}
static void StartSinglePlayerGame_Mental(void)
{
_pShell->SetINDEX("gam_iStartDifficulty", CSessionProperties::GD_EXTREME + 1);
_pShell->SetINDEX("gam_iStartMode", CSessionProperties::GM_COOPERATIVE);
StartSinglePlayerGame();
}
void InitActionsForSinglePlayerNewMenu() {
CSinglePlayerNewMenu &gmCurrent = _pGUIM->gmSinglePlayerNewMenu;
gmCurrent.gm_mgTourist.mg_pActivatedFunction = &StartSinglePlayerGame_Tourist;
gmCurrent.gm_mgEasy.mg_pActivatedFunction = &StartSinglePlayerGame_Easy;
gmCurrent.gm_mgMedium.mg_pActivatedFunction = &StartSinglePlayerGame_Normal;
gmCurrent.gm_mgHard.mg_pActivatedFunction = &StartSinglePlayerGame_Hard;
gmCurrent.gm_mgSerious.mg_pActivatedFunction = &StartSinglePlayerGame_Serious;
gmCurrent.gm_mgMental.mg_pActivatedFunction = &StartSinglePlayerGame_Mental;
}
// ------------------------ CPlayerProfileMenu implementation
static void ChangeCrosshair(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
pps->ps_iCrossHairType = iNew - 1;
}
static void ChangeWeaponSelect(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
pps->ps_iWeaponAutoSelect = iNew;
}
static void ChangeWeaponHide(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
if (iNew) {
pps->ps_ulFlags |= PSF_HIDEWEAPON;
} else {
pps->ps_ulFlags &= ~PSF_HIDEWEAPON;
}
}
static void Change3rdPerson(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
if (iNew) {
pps->ps_ulFlags |= PSF_PREFER3RDPERSON;
} else {
pps->ps_ulFlags &= ~PSF_PREFER3RDPERSON;
}
}
static void ChangeQuotes(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
if (iNew) {
pps->ps_ulFlags &= ~PSF_NOQUOTES;
} else {
pps->ps_ulFlags |= PSF_NOQUOTES;
}
}
static void ChangeAutoSave(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
if (iNew) {
pps->ps_ulFlags |= PSF_AUTOSAVE;
} else {
pps->ps_ulFlags &= ~PSF_AUTOSAVE;
}
}
static void ChangeCompDoubleClick(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
if (iNew) {
pps->ps_ulFlags &= ~PSF_COMPSINGLECLICK;
} else {
pps->ps_ulFlags |= PSF_COMPSINGLECLICK;
}
}
static void ChangeViewBobbing(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
if (iNew) {
pps->ps_ulFlags &= ~PSF_NOBOBBING;
} else {
pps->ps_ulFlags |= PSF_NOBOBBING;
}
}
static void ChangeSharpTurning(INDEX iNew)
{
INDEX iPlayer = *_pGUIM->gmPlayerProfile.gm_piCurrentPlayer;
CPlayerSettings *pps = (CPlayerSettings *)_pGame->gm_apcPlayers[iPlayer].pc_aubAppearance;
if (iNew) {
pps->ps_ulFlags |= PSF_SHARPTURNING;
} else {
pps->ps_ulFlags &= ~PSF_SHARPTURNING;
}
}
extern void PPOnPlayerSelect(void)
{
ASSERT(_pmgLastActivatedGadget != NULL);
if (_pmgLastActivatedGadget->mg_bEnabled) {
_pGUIM->gmPlayerProfile.SelectPlayer(((CMGButton *)_pmgLastActivatedGadget)->mg_iIndex);
}
}
void InitActionsForPlayerProfileMenu()
{
CPlayerProfileMenu &gmCurrent = _pGUIM->gmPlayerProfile;
gmCurrent.gm_mgCrosshair.mg_pOnTriggerChange = ChangeCrosshair;
gmCurrent.gm_mgWeaponSelect.mg_pOnTriggerChange = ChangeWeaponSelect;
gmCurrent.gm_mgWeaponHide.mg_pOnTriggerChange = ChangeWeaponHide;
gmCurrent.gm_mg3rdPerson.mg_pOnTriggerChange = Change3rdPerson;
gmCurrent.gm_mgQuotes.mg_pOnTriggerChange = ChangeQuotes;
gmCurrent.gm_mgAutoSave.mg_pOnTriggerChange = ChangeAutoSave;
gmCurrent.gm_mgCompDoubleClick.mg_pOnTriggerChange = ChangeCompDoubleClick;
gmCurrent.gm_mgSharpTurning.mg_pOnTriggerChange = ChangeSharpTurning;
gmCurrent.gm_mgViewBobbing.mg_pOnTriggerChange = ChangeViewBobbing;
gmCurrent.gm_mgCustomizeControls.mg_pActivatedFunction = &StartControlsMenuFromPlayer;
gmCurrent.gm_mgModel.mg_pActivatedFunction = &StartPlayerModelLoadMenu;
}
// ------------------------ CControlsMenu implementation
void InitActionsForControlsMenu()
{
CControlsMenu &gmCurrent = _pGUIM->gmControls;
gmCurrent.gm_mgButtons.mg_pActivatedFunction = &StartCustomizeKeyboardMenu;
gmCurrent.gm_mgAdvanced.mg_pActivatedFunction = &StartCustomizeAxisMenu;
gmCurrent.gm_mgPredefined.mg_pActivatedFunction = &StartControlsLoadMenu;
}
// ------------------------ CCustomizeAxisMenu implementation
void PreChangeAxis(INDEX iDummy)
{
_pGUIM->gmCustomizeAxisMenu.ApplyActionSettings();
}
void PostChangeAxis(INDEX iDummy)
{
_pGUIM->gmCustomizeAxisMenu.ObtainActionSettings();
}
void InitActionsForCustomizeAxisMenu()
{
CCustomizeAxisMenu &gmCurrent = _pGUIM->gmCustomizeAxisMenu;
gmCurrent.gm_mgActionTrigger.mg_pPreTriggerChange = PreChangeAxis;
gmCurrent.gm_mgActionTrigger.mg_pOnTriggerChange = PostChangeAxis;
}
// ------------------------ COptionsMenu implementation
void InitActionsForOptionsMenu()
{
COptionsMenu &gmCurrent = _pGUIM->gmOptionsMenu;
gmCurrent.gm_mgVideoOptions.mg_pActivatedFunction = &StartVideoOptionsMenu;
gmCurrent.gm_mgAudioOptions.mg_pActivatedFunction = &StartAudioOptionsMenu;
gmCurrent.gm_mgPlayerProfileOptions.mg_pActivatedFunction = &StartChangePlayerMenuFromOptions;
gmCurrent.gm_mgNetworkOptions.mg_pActivatedFunction = &StartNetworkSettingsMenu;
gmCurrent.gm_mgCustomOptions.mg_pActivatedFunction = &StartCustomLoadMenu;
gmCurrent.gm_mgAddonOptions.mg_pActivatedFunction = &StartAddonsLoadMenu;
}
// ------------------------ CVideoOptionsMenu implementation
static INDEX sam_old_bFullScreenActive;
static INDEX sam_old_iScreenSizeI;
static INDEX sam_old_iScreenSizeJ;
static INDEX sam_old_iDisplayDepth;
static INDEX sam_old_iDisplayAdapter;
static INDEX sam_old_iGfxAPI;
static INDEX sam_old_iVideoSetup; // 0==speed, 1==normal, 2==quality, 3==custom
static void FillResolutionsList(void)
{
CVideoOptionsMenu &gmCurrent = _pGUIM->gmVideoOptionsMenu;
// free resolutions
if (_astrResolutionTexts != NULL) {
delete[] _astrResolutionTexts;
}
if (_admResolutionModes != NULL) {
delete[] _admResolutionModes;
}
_ctResolutions = 0;
// if window
if (gmCurrent.gm_mgFullScreenTrigger.mg_iSelected == 0) {
// always has fixed resolutions, but not greater than desktop
_ctResolutions = ARRAYCOUNT(apixWidths);
_astrResolutionTexts = new CTString[_ctResolutions];
_admResolutionModes = new CDisplayMode[_ctResolutions];
extern PIX _pixDesktopWidth;
INDEX iRes = 0;
for (; iRes<_ctResolutions; iRes++) {
if (apixWidths[iRes][0]>_pixDesktopWidth) break;
SetResolutionInList(iRes, apixWidths[iRes][0], apixWidths[iRes][1]);
}
_ctResolutions = iRes;
// if fullscreen
} else {
// get resolutions list from engine
CDisplayMode *pdm = _pGfx->EnumDisplayModes(_ctResolutions,
SwitchToAPI(gmCurrent.gm_mgDisplayAPITrigger.mg_iSelected), gmCurrent.gm_mgDisplayAdaptersTrigger.mg_iSelected);
// allocate that much
_astrResolutionTexts = new CTString[_ctResolutions];
_admResolutionModes = new CDisplayMode[_ctResolutions];
// for each resolution
for (INDEX iRes = 0; iRes<_ctResolutions; iRes++) {
// add it to list
SetResolutionInList(iRes, pdm[iRes].dm_pixSizeI, pdm[iRes].dm_pixSizeJ);
}
}
gmCurrent.gm_mgResolutionsTrigger.mg_astrTexts = _astrResolutionTexts;
gmCurrent.gm_mgResolutionsTrigger.mg_ctTexts = _ctResolutions;
}
static void FillAdaptersList(void)
{
CVideoOptionsMenu &gmCurrent = _pGUIM->gmVideoOptionsMenu;
if (_astrAdapterTexts != NULL) {
delete[] _astrAdapterTexts;
}
_ctAdapters = 0;
INDEX iApi = SwitchToAPI(gmCurrent.gm_mgDisplayAPITrigger.mg_iSelected);
_ctAdapters = _pGfx->gl_gaAPI[iApi].ga_ctAdapters;
_astrAdapterTexts = new CTString[_ctAdapters];
for (INDEX iAdapter = 0; iAdapter<_ctAdapters; iAdapter++) {
_astrAdapterTexts[iAdapter] = _pGfx->gl_gaAPI[iApi].ga_adaAdapter[iAdapter].da_strRenderer;
}
gmCurrent.gm_mgDisplayAdaptersTrigger.mg_astrTexts = _astrAdapterTexts;
gmCurrent.gm_mgDisplayAdaptersTrigger.mg_ctTexts = _ctAdapters;
}
extern void UpdateVideoOptionsButtons(INDEX iSelected)
{
CVideoOptionsMenu &gmCurrent = _pGUIM->gmVideoOptionsMenu;
const BOOL _bVideoOptionsChanged = (iSelected != -1);
const BOOL bOGLEnabled = _pGfx->HasAPI(GAT_OGL);
#ifdef SE1_D3D
const BOOL bD3DEnabled = _pGfx->HasAPI(GAT_D3D);
ASSERT(bOGLEnabled || bD3DEnabled);
#else //
#ifdef SE1_VULKAN
const BOOL bVKEnabled = _pGfx->HasAPI(GAT_VK);
ASSERT(bOGLEnabled || bVKEnabled);
#else // SE1_VULKAN
ASSERT(bOGLEnabled);
#endif // SE1_VULKAN
#endif // SE1_D3D
CDisplayAdapter &da = _pGfx->gl_gaAPI[SwitchToAPI(gmCurrent.gm_mgDisplayAPITrigger.mg_iSelected)]
.ga_adaAdapter[gmCurrent.gm_mgDisplayAdaptersTrigger.mg_iSelected];
// number of available preferences is higher if video setup is custom
gmCurrent.gm_mgDisplayPrefsTrigger.mg_ctTexts = 3;
if (sam_iVideoSetup == 3) gmCurrent.gm_mgDisplayPrefsTrigger.mg_ctTexts++;
// enumerate adapters
FillAdaptersList();
// show or hide buttons
gmCurrent.gm_mgDisplayAPITrigger.mg_bEnabled = bOGLEnabled
#ifdef SE1_D3D
&& bD3DEnabled
#endif // SE1_D3D
#ifdef SE1_VULKAN
&& bVKEnabled
#endif // SE1_VULKAN
;
gmCurrent.gm_mgDisplayAdaptersTrigger.mg_bEnabled = _ctAdapters>1;
gmCurrent.gm_mgApply.mg_bEnabled = _bVideoOptionsChanged;
// determine which should be visible
gmCurrent.gm_mgFullScreenTrigger.mg_bEnabled = TRUE;
if (da.da_ulFlags&DAF_FULLSCREENONLY) {
gmCurrent.gm_mgFullScreenTrigger.mg_bEnabled = FALSE;
gmCurrent.gm_mgFullScreenTrigger.mg_iSelected = 1;
gmCurrent.gm_mgFullScreenTrigger.ApplyCurrentSelection();
}
gmCurrent.gm_mgBitsPerPixelTrigger.mg_bEnabled = TRUE;
if (gmCurrent.gm_mgFullScreenTrigger.mg_iSelected == 0) {
gmCurrent.gm_mgBitsPerPixelTrigger.mg_bEnabled = FALSE;
gmCurrent.gm_mgBitsPerPixelTrigger.mg_iSelected = DepthToSwitch(DD_DEFAULT);
gmCurrent.gm_mgBitsPerPixelTrigger.ApplyCurrentSelection();
} else if (da.da_ulFlags&DAF_16BITONLY) {
gmCurrent.gm_mgBitsPerPixelTrigger.mg_bEnabled = FALSE;
gmCurrent.gm_mgBitsPerPixelTrigger.mg_iSelected = DepthToSwitch(DD_16BIT);
gmCurrent.gm_mgBitsPerPixelTrigger.ApplyCurrentSelection();
}
// remember current selected resolution
PIX pixSizeI, pixSizeJ;
ResolutionToSize(gmCurrent.gm_mgResolutionsTrigger.mg_iSelected, pixSizeI, pixSizeJ);
// select same resolution again if possible
FillResolutionsList();
SizeToResolution(pixSizeI, pixSizeJ, gmCurrent.gm_mgResolutionsTrigger.mg_iSelected);
// apply adapter and resolutions
gmCurrent.gm_mgDisplayAdaptersTrigger.ApplyCurrentSelection();
gmCurrent.gm_mgResolutionsTrigger.ApplyCurrentSelection();
}
extern void InitVideoOptionsButtons(void)
{
CVideoOptionsMenu &gmCurrent = _pGUIM->gmVideoOptionsMenu;
if (sam_bFullScreenActive) {
gmCurrent.gm_mgFullScreenTrigger.mg_iSelected = 1;
} else {
gmCurrent.gm_mgFullScreenTrigger.mg_iSelected = 0;
}
gmCurrent.gm_mgDisplayAPITrigger.mg_iSelected = APIToSwitch((GfxAPIType)(INDEX)sam_iGfxAPI);
gmCurrent.gm_mgDisplayAdaptersTrigger.mg_iSelected = sam_iDisplayAdapter;
gmCurrent.gm_mgBitsPerPixelTrigger.mg_iSelected = DepthToSwitch((enum DisplayDepth)(INDEX)sam_iDisplayDepth);
FillResolutionsList();
SizeToResolution(sam_iScreenSizeI, sam_iScreenSizeJ, gmCurrent.gm_mgResolutionsTrigger.mg_iSelected);
gmCurrent.gm_mgDisplayPrefsTrigger.mg_iSelected = Clamp(int(sam_iVideoSetup), 0, 3);
gmCurrent.gm_mgFullScreenTrigger.ApplyCurrentSelection();
gmCurrent.gm_mgDisplayPrefsTrigger.ApplyCurrentSelection();
gmCurrent.gm_mgDisplayAPITrigger.ApplyCurrentSelection();
gmCurrent.gm_mgDisplayAdaptersTrigger.ApplyCurrentSelection();
gmCurrent.gm_mgResolutionsTrigger.ApplyCurrentSelection();
gmCurrent.gm_mgBitsPerPixelTrigger.ApplyCurrentSelection();
}
static void ApplyVideoOptions(void)
{
CVideoOptionsMenu &gmCurrent = _pGUIM->gmVideoOptionsMenu;
// Remember old video settings
sam_old_bFullScreenActive = sam_bFullScreenActive;
sam_old_iScreenSizeI = sam_iScreenSizeI;
sam_old_iScreenSizeJ = sam_iScreenSizeJ;
sam_old_iDisplayDepth = sam_iDisplayDepth;
sam_old_iDisplayAdapter = sam_iDisplayAdapter;
sam_old_iGfxAPI = sam_iGfxAPI;
sam_old_iVideoSetup = sam_iVideoSetup;
BOOL bFullScreenMode = gmCurrent.gm_mgFullScreenTrigger.mg_iSelected == 1;
PIX pixWindowSizeI, pixWindowSizeJ;
ResolutionToSize(gmCurrent.gm_mgResolutionsTrigger.mg_iSelected, pixWindowSizeI, pixWindowSizeJ);
enum GfxAPIType gat = SwitchToAPI(gmCurrent.gm_mgDisplayAPITrigger.mg_iSelected);
enum DisplayDepth dd = SwitchToDepth(gmCurrent.gm_mgBitsPerPixelTrigger.mg_iSelected);
const INDEX iAdapter = gmCurrent.gm_mgDisplayAdaptersTrigger.mg_iSelected;
// setup preferences
extern INDEX _iLastPreferences;
if (sam_iVideoSetup == 3) _iLastPreferences = 3;
sam_iVideoSetup = gmCurrent.gm_mgDisplayPrefsTrigger.mg_iSelected;
// force fullscreen mode if needed
CDisplayAdapter &da = _pGfx->gl_gaAPI[gat].ga_adaAdapter[iAdapter];
if (da.da_ulFlags & DAF_FULLSCREENONLY) bFullScreenMode = TRUE;
if (da.da_ulFlags & DAF_16BITONLY) dd = DD_16BIT;
// force window to always be in default colors
if (!bFullScreenMode) dd = DD_DEFAULT;
// (try to) set mode
StartNewMode(gat, iAdapter, pixWindowSizeI, pixWindowSizeJ, dd, bFullScreenMode);
// refresh buttons
InitVideoOptionsButtons();
UpdateVideoOptionsButtons(-1);
// ask user to keep or restore
if (bFullScreenMode) VideoConfirm();
}
static void RevertVideoSettings(void)
{
// restore previous variables
sam_bFullScreenActive = sam_old_bFullScreenActive;
sam_iScreenSizeI = sam_old_iScreenSizeI;
sam_iScreenSizeJ = sam_old_iScreenSizeJ;
sam_iDisplayDepth = sam_old_iDisplayDepth;
sam_iDisplayAdapter = sam_old_iDisplayAdapter;
sam_iGfxAPI = sam_old_iGfxAPI;
sam_iVideoSetup = sam_old_iVideoSetup;
// update the video mode
extern void ApplyVideoMode(void);
ApplyVideoMode();
// refresh buttons
InitVideoOptionsButtons();
UpdateVideoOptionsButtons(-1);
}
void InitActionsForVideoOptionsMenu()
{
CVideoOptionsMenu &gmCurrent = _pGUIM->gmVideoOptionsMenu;
gmCurrent.gm_mgDisplayPrefsTrigger.mg_pOnTriggerChange = &UpdateVideoOptionsButtons;
gmCurrent.gm_mgDisplayAPITrigger.mg_pOnTriggerChange = &UpdateVideoOptionsButtons;
gmCurrent.gm_mgDisplayAdaptersTrigger.mg_pOnTriggerChange = &UpdateVideoOptionsButtons;
gmCurrent.gm_mgFullScreenTrigger.mg_pOnTriggerChange = &UpdateVideoOptionsButtons;
gmCurrent.gm_mgResolutionsTrigger.mg_pOnTriggerChange = &UpdateVideoOptionsButtons;
gmCurrent.gm_mgBitsPerPixelTrigger.mg_pOnTriggerChange = &UpdateVideoOptionsButtons;
gmCurrent.gm_mgVideoRendering.mg_pActivatedFunction = &StartRenderingOptionsMenu;
gmCurrent.gm_mgApply.mg_pActivatedFunction = &ApplyVideoOptions;
}
// ------------------------ CAudioOptionsMenu implementation
extern void RefreshSoundFormat(void)
{
CAudioOptionsMenu &gmCurrent = _pGUIM->gmAudioOptionsMenu;
switch (_pSound->GetFormat())
{
case CSoundLibrary::SF_NONE: {gmCurrent.gm_mgFrequencyTrigger.mg_iSelected = 0; break; }
case CSoundLibrary::SF_11025_16: {gmCurrent.gm_mgFrequencyTrigger.mg_iSelected = 1; break; }
case CSoundLibrary::SF_22050_16: {gmCurrent.gm_mgFrequencyTrigger.mg_iSelected = 2; break; }
case CSoundLibrary::SF_44100_16: {gmCurrent.gm_mgFrequencyTrigger.mg_iSelected = 3; break; }
default: gmCurrent.gm_mgFrequencyTrigger.mg_iSelected = 0;
}
gmCurrent.gm_mgAudioAutoTrigger.mg_iSelected = Clamp(sam_bAutoAdjustAudio, 0, 1);
gmCurrent.gm_mgAudioAPITrigger.mg_iSelected = Clamp(_pShell->GetINDEX("snd_iInterface"), 0L, 2L);
gmCurrent.gm_mgWaveVolume.mg_iMinPos = 0;
gmCurrent.gm_mgWaveVolume.mg_iMaxPos = VOLUME_STEPS;
gmCurrent.gm_mgWaveVolume.mg_iCurPos = (INDEX)(_pShell->GetFLOAT("snd_fSoundVolume")*VOLUME_STEPS + 0.5f);
gmCurrent.gm_mgWaveVolume.ApplyCurrentPosition();
gmCurrent.gm_mgMPEGVolume.mg_iMinPos = 0;
gmCurrent.gm_mgMPEGVolume.mg_iMaxPos = VOLUME_STEPS;
gmCurrent.gm_mgMPEGVolume.mg_iCurPos = (INDEX)(_pShell->GetFLOAT("snd_fMusicVolume")*VOLUME_STEPS + 0.5f);
gmCurrent.gm_mgMPEGVolume.ApplyCurrentPosition();
gmCurrent.gm_mgAudioAutoTrigger.ApplyCurrentSelection();
gmCurrent.gm_mgAudioAPITrigger.ApplyCurrentSelection();
gmCurrent.gm_mgFrequencyTrigger.ApplyCurrentSelection();
}
static void ApplyAudioOptions(void)
{
CAudioOptionsMenu &gmCurrent = _pGUIM->gmAudioOptionsMenu;
sam_bAutoAdjustAudio = gmCurrent.gm_mgAudioAutoTrigger.mg_iSelected;
if (sam_bAutoAdjustAudio) {
_pShell->Execute("include \"Scripts\\Addons\\SFX-AutoAdjust.ini\"");
} else {
_pShell->SetINDEX("snd_iInterface", gmCurrent.gm_mgAudioAPITrigger.mg_iSelected);
switch (gmCurrent.gm_mgFrequencyTrigger.mg_iSelected)
{
case 0: {_pSound->SetFormat(CSoundLibrary::SF_NONE); break; }
case 1: {_pSound->SetFormat(CSoundLibrary::SF_11025_16); break; }
case 2: {_pSound->SetFormat(CSoundLibrary::SF_22050_16); break; }
case 3: {_pSound->SetFormat(CSoundLibrary::SF_44100_16); break; }
default: _pSound->SetFormat(CSoundLibrary::SF_NONE);
}
}
RefreshSoundFormat();
snd_iFormat = _pSound->GetFormat();
}
static void OnWaveVolumeChange(INDEX iCurPos)
{
_pShell->SetFLOAT("snd_fSoundVolume", iCurPos / FLOAT(VOLUME_STEPS));
}
static void WaveSliderChange(void)
{
CAudioOptionsMenu &gmCurrent = _pGUIM->gmAudioOptionsMenu;
gmCurrent.gm_mgWaveVolume.mg_iCurPos -= 5;
gmCurrent.gm_mgWaveVolume.ApplyCurrentPosition();
}
static void FrequencyTriggerChange(INDEX iDummy)
{
CAudioOptionsMenu &gmCurrent = _pGUIM->gmAudioOptionsMenu;
sam_bAutoAdjustAudio = 0;
gmCurrent.gm_mgAudioAutoTrigger.mg_iSelected = 0;
gmCurrent.gm_mgAudioAutoTrigger.ApplyCurrentSelection();
}
static void MPEGSliderChange(void)
{
CAudioOptionsMenu &gmCurrent = _pGUIM->gmAudioOptionsMenu;
gmCurrent.gm_mgMPEGVolume.mg_iCurPos -= 5;
gmCurrent.gm_mgMPEGVolume.ApplyCurrentPosition();
}
static void OnMPEGVolumeChange(INDEX iCurPos)
{
_pShell->SetFLOAT("snd_fMusicVolume", iCurPos / FLOAT(VOLUME_STEPS));
}
void InitActionsForAudioOptionsMenu()
{
CAudioOptionsMenu &gmCurrent = _pGUIM->gmAudioOptionsMenu;
gmCurrent.gm_mgFrequencyTrigger.mg_pOnTriggerChange = FrequencyTriggerChange;
gmCurrent.gm_mgWaveVolume.mg_pOnSliderChange = &OnWaveVolumeChange;
gmCurrent.gm_mgWaveVolume.mg_pActivatedFunction = WaveSliderChange;
gmCurrent.gm_mgMPEGVolume.mg_pOnSliderChange = &OnMPEGVolumeChange;
gmCurrent.gm_mgMPEGVolume.mg_pActivatedFunction = MPEGSliderChange;
gmCurrent.gm_mgApply.mg_pActivatedFunction = &ApplyAudioOptions;
}
// ------------------------ CVarMenu implementation
static void VarApply(void)
{
CVarMenu &gmCurrent = _pGUIM->gmVarMenu;
FlushVarSettings(TRUE);
gmCurrent.EndMenu();
gmCurrent.StartMenu();
}
void InitActionsForVarMenu() {
_pGUIM->gmVarMenu.gm_mgApply.mg_pActivatedFunction = &VarApply;
}
// ------------------------ CServersMenu implementation
extern CMGButton mgServerColumn[7];
extern CMGEdit mgServerFilter[7];
static void SortByColumn(int i)
{
CServersMenu &gmCurrent = _pGUIM->gmServersMenu;
if (gmCurrent.gm_mgList.mg_iSort == i) {
gmCurrent.gm_mgList.mg_bSortDown = !gmCurrent.gm_mgList.mg_bSortDown;
} else {
gmCurrent.gm_mgList.mg_bSortDown = FALSE;
}
gmCurrent.gm_mgList.mg_iSort = i;
}
static void SortByServer(void) { SortByColumn(0); }
static void SortByMap(void) { SortByColumn(1); }
static void SortByPing(void) { SortByColumn(2); }
static void SortByPlayers(void){ SortByColumn(3); }
static void SortByGame(void) { SortByColumn(4); }
static void SortByMod(void) { SortByColumn(5); }
static void SortByVer(void) { SortByColumn(6); }
extern void RefreshServerList(void)
{
_pNetwork->EnumSessions(_pGUIM->gmServersMenu.m_bInternet);
}
void RefreshServerListManually(void)
{
ChangeToMenu(&_pGUIM->gmServersMenu); // this refreshes the list and sets focuses
}
void InitActionsForServersMenu() {
_pGUIM->gmServersMenu.gm_mgRefresh.mg_pActivatedFunction = &RefreshServerList;
mgServerColumn[0].mg_pActivatedFunction = SortByServer;
mgServerColumn[1].mg_pActivatedFunction = SortByMap;
mgServerColumn[2].mg_pActivatedFunction = SortByPing;
mgServerColumn[3].mg_pActivatedFunction = SortByPlayers;
mgServerColumn[4].mg_pActivatedFunction = SortByGame;
mgServerColumn[5].mg_pActivatedFunction = SortByMod;
mgServerColumn[6].mg_pActivatedFunction = SortByVer;
}
// ------------------------ CNetworkMenu implementation
void InitActionsForNetworkMenu()
{
CNetworkMenu &gmCurrent = _pGUIM->gmNetworkMenu;
gmCurrent.gm_mgJoin.mg_pActivatedFunction = &StartNetworkJoinMenu;
gmCurrent.gm_mgStart.mg_pActivatedFunction = &StartNetworkStartMenu;
gmCurrent.gm_mgQuickLoad.mg_pActivatedFunction = &StartNetworkQuickLoadMenu;
gmCurrent.gm_mgLoad.mg_pActivatedFunction = &StartNetworkLoadMenu;
}
// ------------------------ CNetworkJoinMenu implementation
void InitActionsForNetworkJoinMenu()
{
CNetworkJoinMenu &gmCurrent = _pGUIM->gmNetworkJoinMenu;
gmCurrent.gm_mgLAN.mg_pActivatedFunction = &StartSelectServerLAN;
gmCurrent.gm_mgNET.mg_pActivatedFunction = &StartSelectServerNET;
gmCurrent.gm_mgOpen.mg_pActivatedFunction = &StartNetworkOpenMenu;
}
// ------------------------ CNetworkStartMenu implementation
extern void UpdateNetworkLevel(INDEX iDummy)
{
ValidateLevelForFlags(_pGame->gam_strCustomLevel,
GetSpawnFlagsForGameType(_pGUIM->gmNetworkStartMenu.gm_mgGameType.mg_iSelected));
_pGUIM->gmNetworkStartMenu.gm_mgLevel.mg_strText = FindLevelByFileName(_pGame->gam_strCustomLevel).li_strName;
}
void InitActionsForNetworkStartMenu()
{
CNetworkStartMenu &gmCurrent = _pGUIM->gmNetworkStartMenu;
gmCurrent.gm_mgLevel.mg_pActivatedFunction = &StartSelectLevelFromNetwork;
gmCurrent.gm_mgGameOptions.mg_pActivatedFunction = &StartGameOptionsFromNetwork;
gmCurrent.gm_mgStart.mg_pActivatedFunction = &StartSelectPlayersMenuFromNetwork;
}
// ------------------------ CSelectPlayersMenu implementation
static INDEX FindUnusedPlayer(void)
{
INDEX *ai = _pGame->gm_aiMenuLocalPlayers;
INDEX iPlayer = 0;
for (; iPlayer<8; iPlayer++) {
BOOL bUsed = FALSE;
for (INDEX iLocal = 0; iLocal<4; iLocal++) {
if (ai[iLocal] == iPlayer) {
bUsed = TRUE;
break;
}
}
if (!bUsed) {
return iPlayer;
}
}
ASSERT(FALSE);
return iPlayer;
}
extern void SelectPlayersFillMenu(void)
{
CSelectPlayersMenu &gmCurrent = _pGUIM->gmSelectPlayersMenu;
INDEX *ai = _pGame->gm_aiMenuLocalPlayers;
gmCurrent.gm_mgPlayer0Change.mg_iLocalPlayer = 0;
gmCurrent.gm_mgPlayer1Change.mg_iLocalPlayer = 1;
gmCurrent.gm_mgPlayer2Change.mg_iLocalPlayer = 2;
gmCurrent.gm_mgPlayer3Change.mg_iLocalPlayer = 3;
if (gmCurrent.gm_bAllowDedicated && _pGame->gm_MenuSplitScreenCfg == CGame::SSC_DEDICATED) {
gmCurrent.gm_mgDedicated.mg_iSelected = 1;
} else {
gmCurrent.gm_mgDedicated.mg_iSelected = 0;
}
gmCurrent.gm_mgDedicated.ApplyCurrentSelection();
if (gmCurrent.gm_bAllowObserving && _pGame->gm_MenuSplitScreenCfg == CGame::SSC_OBSERVER) {
gmCurrent.gm_mgObserver.mg_iSelected = 1;
} else {
gmCurrent.gm_mgObserver.mg_iSelected = 0;
}
gmCurrent.gm_mgObserver.ApplyCurrentSelection();
if (_pGame->gm_MenuSplitScreenCfg >= CGame::SSC_PLAY1) {
gmCurrent.gm_mgSplitScreenCfg.mg_iSelected = _pGame->gm_MenuSplitScreenCfg;
gmCurrent.gm_mgSplitScreenCfg.ApplyCurrentSelection();
}
BOOL bHasDedicated = gmCurrent.gm_bAllowDedicated;
BOOL bHasObserver = gmCurrent.gm_bAllowObserving;
BOOL bHasPlayers = TRUE;
if (bHasDedicated && gmCurrent.gm_mgDedicated.mg_iSelected) {
bHasObserver = FALSE;
bHasPlayers = FALSE;
}
if (bHasObserver && gmCurrent.gm_mgObserver.mg_iSelected) {
bHasPlayers = FALSE;
}
CMenuGadget *apmg[8];
memset(apmg, 0, sizeof(apmg));
INDEX i = 0;
if (bHasDedicated) {
gmCurrent.gm_mgDedicated.Appear();
apmg[i++] = &gmCurrent.gm_mgDedicated;
} else {
gmCurrent.gm_mgDedicated.Disappear();
}
if (bHasObserver) {
gmCurrent.gm_mgObserver.Appear();
apmg[i++] = &gmCurrent.gm_mgObserver;
} else {
gmCurrent.gm_mgObserver.Disappear();
}
for (INDEX iLocal = 0; iLocal<4; iLocal++) {
if (ai[iLocal]<0 || ai[iLocal]>7) {
ai[iLocal] = 0;
}
for (INDEX iCopy = 0; iCopy<iLocal; iCopy++) {
if (ai[iCopy] == ai[iLocal]) {
ai[iLocal] = FindUnusedPlayer();
}
}
}
gmCurrent.gm_mgPlayer0Change.Disappear();
gmCurrent.gm_mgPlayer1Change.Disappear();
gmCurrent.gm_mgPlayer2Change.Disappear();
gmCurrent.gm_mgPlayer3Change.Disappear();
if (bHasPlayers) {
gmCurrent.gm_mgSplitScreenCfg.Appear();
apmg[i++] = &gmCurrent.gm_mgSplitScreenCfg;
gmCurrent.gm_mgPlayer0Change.Appear();
apmg[i++] = &gmCurrent.gm_mgPlayer0Change;
if (gmCurrent.gm_mgSplitScreenCfg.mg_iSelected >= 1) {
gmCurrent.gm_mgPlayer1Change.Appear();
apmg[i++] = &gmCurrent.gm_mgPlayer1Change;
}
if (gmCurrent.gm_mgSplitScreenCfg.mg_iSelected >= 2) {
gmCurrent.gm_mgPlayer2Change.Appear();
apmg[i++] = &gmCurrent.gm_mgPlayer2Change;
}
if (gmCurrent.gm_mgSplitScreenCfg.mg_iSelected >= 3) {
gmCurrent.gm_mgPlayer3Change.Appear();
apmg[i++] = &gmCurrent.gm_mgPlayer3Change;
}
} else {
gmCurrent.gm_mgSplitScreenCfg.Disappear();
}
apmg[i++] = &gmCurrent.gm_mgStart;
// relink
for (INDEX img = 0; img<8; img++) {
if (apmg[img] == NULL) {
continue;
}
INDEX imgPred = (img + 8 - 1) % 8;
for (; imgPred != img; imgPred = (imgPred + 8 - 1) % 8) {
if (apmg[imgPred] != NULL) {
break;
}
}
INDEX imgSucc = (img + 1) % 8;
for (; imgSucc != img; imgSucc = (imgSucc + 1) % 8) {
if (apmg[imgSucc] != NULL) {
break;
}
}
apmg[img]->mg_pmgUp = apmg[imgPred];
apmg[img]->mg_pmgDown = apmg[imgSucc];
}
gmCurrent.gm_mgPlayer0Change.SetPlayerText();
gmCurrent.gm_mgPlayer1Change.SetPlayerText();
gmCurrent.gm_mgPlayer2Change.SetPlayerText();
gmCurrent.gm_mgPlayer3Change.SetPlayerText();
if (bHasPlayers && gmCurrent.gm_mgSplitScreenCfg.mg_iSelected >= 1) {
gmCurrent.gm_mgNotes.mg_strText = TRANS("Make sure you set different controls for each player!");
} else {
gmCurrent.gm_mgNotes.mg_strText = "";
}
}
extern void SelectPlayersApplyMenu(void)
{
CSelectPlayersMenu &gmCurrent = _pGUIM->gmSelectPlayersMenu;
if (gmCurrent.gm_bAllowDedicated && gmCurrent.gm_mgDedicated.mg_iSelected) {
_pGame->gm_MenuSplitScreenCfg = CGame::SSC_DEDICATED;
return;
}
if (gmCurrent.gm_bAllowObserving && gmCurrent.gm_mgObserver.mg_iSelected) {
_pGame->gm_MenuSplitScreenCfg = CGame::SSC_OBSERVER;
return;
}
_pGame->gm_MenuSplitScreenCfg = (enum CGame::SplitScreenCfg) gmCurrent.gm_mgSplitScreenCfg.mg_iSelected;
}
static void UpdateSelectPlayers(INDEX i)
{
SelectPlayersApplyMenu();
SelectPlayersFillMenu();
}
void InitActionsForSelectPlayersMenu()
{
CSelectPlayersMenu &gmCurrent = _pGUIM->gmSelectPlayersMenu;
gmCurrent.gm_mgDedicated.mg_pOnTriggerChange = UpdateSelectPlayers;
gmCurrent.gm_mgObserver.mg_pOnTriggerChange = UpdateSelectPlayers;
gmCurrent.gm_mgSplitScreenCfg.mg_pOnTriggerChange = UpdateSelectPlayers;
}
// ------------------------ CNetworkOpenMenu implementation
void InitActionsForNetworkOpenMenu()
{
_pGUIM->gmNetworkOpenMenu.gm_mgJoin.mg_pActivatedFunction = &StartSelectPlayersMenuFromOpen;
}
// ------------------------ CSplitScreenMenu implementation
void InitActionsForSplitScreenMenu()
{
CSplitScreenMenu &gmCurrent = _pGUIM->gmSplitScreenMenu;
gmCurrent.gm_mgStart.mg_pActivatedFunction = &StartSplitStartMenu;
gmCurrent.gm_mgQuickLoad.mg_pActivatedFunction = &StartSplitScreenQuickLoadMenu;
gmCurrent.gm_mgLoad.mg_pActivatedFunction = &StartSplitScreenLoadMenu;
}
// ------------------------ CSplitStartMenu implementation
void InitActionsForSplitStartMenu()
{
CSplitStartMenu &gmCurrent = _pGUIM->gmSplitStartMenu;
gmCurrent.gm_mgLevel.mg_pActivatedFunction = &StartSelectLevelFromSplit;
gmCurrent.gm_mgOptions.mg_pActivatedFunction = &StartGameOptionsFromSplitScreen;
gmCurrent.gm_mgStart.mg_pActivatedFunction = &StartSelectPlayersMenuFromSplit;
}
extern void UpdateSplitLevel(INDEX iDummy)
{
CSplitStartMenu &gmCurrent = _pGUIM->gmSplitStartMenu;
ValidateLevelForFlags(_pGame->gam_strCustomLevel,
GetSpawnFlagsForGameType(gmCurrent.gm_mgGameType.mg_iSelected));
gmCurrent.gm_mgLevel.mg_strText = FindLevelByFileName(_pGame->gam_strCustomLevel).li_strName;
}
| 42,451
|
C++
|
.cpp
| 1,073
| 36.585275
| 118
| 0.766316
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,536,210
|
VulkanInclude.h
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Vulkan/VulkanInclude.h
|
/* Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#ifndef SE_INCL_VULKANINCLUDE_H
#define SE_INCL_VULKANINCLUDE_H
#ifdef PRAGMA_ONCE
#pragma once
#endif
#ifdef SE1_VULKAN
#define VK_USE_PLATFORM_WIN32_KHR
#include <vulkan/vulkan.h>
#include <Engine/Graphics/Vulkan/SvkVertex.h>
#include <Engine/Graphics/Vulkan/SvkPipelineStates.h>
#include <Engine/Graphics/Vulkan/SvkSamplerStates.h>
#include <Engine/Templates/StaticArray.h>
#define gl_VkMaxCmdBufferCount 2
#define SVK_PREFERRED_SWAPCHAIN_SIZE 3
#define SVK_DESCRIPTOR_MAX_SET_COUNT 8192
#define SVK_DESCRIPTOR_MAX_SAMPLER_COUNT 8192
#define SVK_VERT_START_COUNT 4096
#define SVK_VERT_ALLOC_STEP 4096
#define SVK_DYNAMIC_VERTEX_BUFFER_START_SIZE (8 * 1024 * 1024)
#define SVK_DYNAMIC_INDEX_BUFFER_START_SIZE (2 * 1024 * 1024)
#define SVK_DYNAMIC_UNIFORM_BUFFER_START_SIZE (256 * 1024)
#define SVK_DYNAMIC_UNIFORM_MAX_ALLOC_SIZE 1024
#define SVK_RENDERPASS_COLOR_ATTACHMENT_INDEX 0
#define SVK_RENDERPASS_DEPTH_ATTACHMENT_INDEX 1
#define SVK_SAMPLER_LOD_BIAS (0.0f)
#define SVK_OCCLUSION_QUERIES_MAX 256
struct SvkTextureObject
{
public:
uint32_t sto_Width;
uint32_t sto_Height;
VkFormat sto_Format;
VkImage sto_Image;
VkImageView sto_ImageView;
VkImageLayout sto_Layout;
VkDeviceMemory sto_Memory;
uint32_t sto_MemoryHandle;
SvkSamplerFlags sto_SamplerFlags;
// for destruction
VkDevice sto_VkDevice;
public:
SvkTextureObject()
{
Reset();
}
void Reset()
{
sto_Width = sto_Height = 0;
sto_Format = VK_FORMAT_UNDEFINED;
sto_Image = VK_NULL_HANDLE;
sto_ImageView = VK_NULL_HANDLE;
sto_MemoryHandle = 0;
sto_Memory = VK_NULL_HANDLE;
sto_VkDevice = VK_NULL_HANDLE;
sto_Layout = VK_IMAGE_LAYOUT_UNDEFINED;
sto_SamplerFlags = 0;
}
};
struct SvkDynamicBuffer
{
VkBuffer sdb_Buffer;
VkDeviceSize sdb_CurrentOffset;
void* sdb_Data;
};
struct SvkDynamicUniform : public SvkDynamicBuffer
{
VkDescriptorSet sdu_DescriptorSet;
};
// Dynamic buffer to delete
struct SvkDBufferToDelete
{
VkBuffer sdd_Memory;
VkBuffer sdd_Buffers[gl_VkMaxCmdBufferCount];
// optional
VkDescriptorSet sdd_DescriptorSets[gl_VkMaxCmdBufferCount];
};
struct SvkDynamicBufferGlobal
{
uint32_t sdg_CurrentDynamicBufferSize;
VkDeviceMemory sdg_DynamicBufferMemory;
};
struct SvkPipelineState
{
VkDevice sps_Device;
SvkPipelineStateFlags sps_Flags;
VkPipeline sps_Pipeline;
};
struct SvkSamplerObject
{
VkDevice sso_Device;
VkSampler sso_Sampler;
};
struct SvkVertexLayout
{
CStaticArray<VkVertexInputBindingDescription> svl_Bindings;
CStaticArray<VkVertexInputAttributeDescription> svl_Attributes;
};
void Svk_MatCopy(float *dest, const float *src);
void Svk_MatSetIdentity(float *result);
void Svk_MatMultiply(float *result, const float *a, const float *b);
void Svk_MatFrustum(float *result, float fLeft, float fRight, float fBottom, float fTop, float fNear, float fFar);
void Svk_MatOrtho(float *result, float fLeft, float fRight, float fBottom, float fTop, float fNear, float fFar);
#endif
#endif
| 3,950
|
C++
|
.h
| 115
| 32.165217
| 114
| 0.736801
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,211
|
SvkMain.h
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Vulkan/SvkMain.h
|
#pragma once
#ifndef SE_INCL_SVKMAIN_H
#define SE_INCL_SVKMAIN_H
#ifdef PRAGMA_ONCE
#pragma once
#endif
#ifdef SE1_VULKAN
#include <Engine/Base/Timer.h>
#include <Engine/Base/CTString.h>
#include <Engine/Base/Lists.h>
#include <Engine/Math/Functions.h>
#include <Engine/Graphics/Adapter.h>
#include <Engine/Graphics/Color.h>
#include <Engine/Graphics/Vertex.h>
#include <Engine/Templates/StaticStackArray.cpp>
#include <Engine/Graphics/GfxLibrary.h>
#include <Engine/Graphics/Vulkan/VulkanInclude.h>
#include <Engine/Graphics/Vulkan/SvkStaticHashTable.h>
#include <Engine/Graphics/Vulkan/SvkMemoryPool.h>
#ifndef NDEBUG
extern void Vk_CheckError(VkResult r);
#define VK_CHECKERROR(r) Vk_CheckError(r);
#else
#define VK_CHECKERROR(r) (void)(0);
#endif
class SvkMain
{
public:
VkInstance gl_VkInstance;
VkDevice gl_VkDevice;
VkSurfaceKHR gl_VkSurface;
VkSwapchainKHR gl_VkSwapchain;
VkExtent2D gl_VkSwapChainExtent;
uint32_t gl_VkCurrentImageIndex;
VkFormat gl_VkSurfColorFormat;
VkColorSpaceKHR gl_VkSurfColorSpace;
VkFormat gl_VkSurfDepthFormat;
VkPresentModeKHR gl_VkSurfPresentMode;
CStaticArray<VkImage> gl_VkSwapchainImages;
CStaticArray<VkImageView> gl_VkSwapchainImageViews;
CStaticArray<VkImage> gl_VkSwapchainColorImages;
CStaticArray<VkDeviceMemory> gl_VkSwapchainColorMemory;
CStaticArray<VkImageView> gl_VkSwapchainColorImageViews;
CStaticArray<VkImage> gl_VkSwapchainDepthImages;
CStaticArray<VkDeviceMemory> gl_VkSwapchainDepthMemory;
CStaticArray<VkImageView> gl_VkSwapchainDepthImageViews;
CStaticArray<VkFramebuffer> gl_VkFramebuffers;
VkSemaphore gl_VkImageAvailableSemaphores[gl_VkMaxCmdBufferCount];
VkSemaphore gl_VkRenderFinishedSemaphores[gl_VkMaxCmdBufferCount];
VkFence gl_VkCmdFences[gl_VkMaxCmdBufferCount];
VkRenderPass gl_VkRenderPass;
VkDescriptorSetLayout gl_VkDescriptorSetLayout;
VkDescriptorSetLayout gl_VkDescSetLayoutTexture;
VkPipelineLayout gl_VkPipelineLayout;
VkPipelineLayout gl_VkPipelineLayoutOcclusion;
VkShaderModule gl_VkShaderModuleVert;
VkShaderModule gl_VkShaderModuleFrag;
VkShaderModule gl_VkShaderModuleFragAlpha;
VkShaderModule gl_VkShaderModuleVertOcclusion;
VkShaderModule gl_VkShaderModuleFragOcclusion;
VkRect2D gl_VkCurrentScissor;
VkViewport gl_VkCurrentViewport;
uint32_t gl_VkCmdBufferCurrent;
VkCommandPool gl_VkCmdPools[gl_VkMaxCmdBufferCount];
VkCommandBuffer gl_VkCmdBuffers[gl_VkMaxCmdBufferCount * 2];
bool gl_VkCmdIsRecording;
VkDescriptorPool gl_VkUniformDescPool;
SvkDynamicBufferGlobal gl_VkDynamicVBGlobal;
SvkDynamicBuffer gl_VkDynamicVB[gl_VkMaxCmdBufferCount];
SvkDynamicBufferGlobal gl_VkDynamicIBGlobal;
SvkDynamicBuffer gl_VkDynamicIB[gl_VkMaxCmdBufferCount];
SvkDynamicBufferGlobal gl_VkDynamicUBGlobal;
SvkDynamicUniform gl_VkDynamicUB[gl_VkMaxCmdBufferCount];
// dynamic buffers to delete
CStaticStackArray<SvkDBufferToDelete> *gl_VkDynamicToDelete[gl_VkMaxCmdBufferCount];
SvkSamplerFlags gl_VkGlobalSamplerState;
SvkStaticHashTable<SvkSamplerObject> gl_VkSamplers;
// all loaded textures
SvkStaticHashTable<SvkTextureObject> gl_VkTextures;
uint32_t gl_VkLastTextureId;
SvkMemoryPool *gl_VkImageMemPool;
VkDescriptorPool gl_VkTextureDescPools[gl_VkMaxCmdBufferCount];
CStaticStackArray<SvkTextureObject> *gl_VkTexturesToDelete[gl_VkMaxCmdBufferCount];
// pointers to currently active textures
uint32_t gl_VkActiveTextures[GFX_MAXTEXUNITS];
SvkPipelineStateFlags gl_VkGlobalState;
SvkPipelineState *gl_VkPreviousPipeline;
SvkStaticHashTable<SvkPipelineState> gl_VkPipelines;
VkPipelineCache gl_VkPipelineCache;
SvkVertexLayout *gl_VkDefaultVertexLayout;
VkPipeline gl_VkPipelineOcclusion;
VkPhysicalDevice gl_VkPhysDevice;
VkPhysicalDeviceMemoryProperties gl_VkPhMemoryProperties;
VkPhysicalDeviceProperties gl_VkPhProperties;
VkPhysicalDeviceFeatures gl_VkPhFeatures;
VkSurfaceCapabilitiesKHR gl_VkPhSurfCapabilities;
CStaticArray<VkSurfaceFormatKHR> gl_VkPhSurfFormats;
CStaticArray<VkPresentModeKHR> gl_VkPhSurfPresentModes;
CStaticArray<const char *> gl_VkPhysDeviceExtensions;
CStaticArray<const char *> gl_VkLayers;
VkSampleCountFlagBits gl_VkMaxSampleCount;
uint32_t gl_VkQueueFamGraphics;
uint32_t gl_VkQueueFamTransfer;
uint32_t gl_VkQueueFamPresent;
VkQueue gl_VkQueueGraphics;
VkQueue gl_VkQueueTransfer;
VkQueue gl_VkQueuePresent;
VkQueryPool gl_VkOcclusionQueryPools[gl_VkMaxCmdBufferCount];
uint32_t gl_VkOcclusionQueryLast[gl_VkMaxCmdBufferCount];
VkDebugUtilsMessengerEXT gl_VkDebugMessenger;
uint32_t gl_VkReloadTexturesTimer;
// current mesh
CStaticStackArray<SvkVertex> gl_VkVerts;
public:
SvkMain();
// Vulkan specific
BOOL InitDriver_Vulkan();
void EndDriver_Vulkan();
void Reset_Vulkan();
//BOOL InitDisplay_Vulkan(INDEX iAdapter, PIX pixSizeI, PIX pixSizeJ, enum DisplayDepth eColorDepth);
void InitContext_Vulkan();
BOOL SetCurrentViewport_Vulkan(CViewPort *pvp);
void SwapBuffers_Vulkan();
void SetViewport_Vulkan(float leftUpperX, float leftUpperY, float width, float height, float minDepth, float maxDepth);
BOOL PickPhysicalDevice();
BOOL InitSurface_Win32(HINSTANCE hinstance, HWND hwnd);
BOOL CreateDevice();
void CreateRenderPass();
void CreateSyncPrimitives();
void DestroySyncPrimitives();
void CreateVertexLayouts();
void DestroyVertexLayouts();
// create desc set layout and its pipeline layout
void CreateDescriptorSetLayouts();
void DestroyDescriptorSetLayouts();
void CreateShaderModules();
void DestroyShaderModules();
void CreateDescriptorPools();
void DestroyDescriptorPools();
void PrepareDescriptorSets(uint32_t cmdBufferIndex);
SvkPipelineState &GetPipeline(SvkPipelineStateFlags flags);
// create new pipeline and add it to list
SvkPipelineState &CreatePipeline(SvkPipelineStateFlags flags, const SvkVertexLayout &vertLayout,
VkShaderModule vertShader, VkShaderModule fragShader);
void CreatePipelineCache();
void DestroyPipelines();
void CreateOcclusionPipeline();
BOOL CreateSwapchainColor(uint32_t width, uint32_t height, uint32_t imageIndex, VkSampleCountFlagBits sampleCount);
BOOL CreateSwapchainDepth(uint32_t width, uint32_t height, uint32_t imageIndex, VkSampleCountFlagBits sampleCount);
void CreateCmdBuffers();
void DestroyCmdBuffers();
void InitDynamicBuffers();
void InitDynamicVertexBuffers(uint32_t newSize);
void InitDynamicIndexBuffers(uint32_t newSize);
void InitDynamicUniformBuffers(uint32_t newSize);
void InitDynamicBuffer(SvkDynamicBufferGlobal &dynBufferGlobal, SvkDynamicBuffer *buffers, VkBufferUsageFlags usage);
void ClearCurrentDynamicOffsets(uint32_t cmdBufferIndex);
void GetVertexBuffer(uint32_t size, SvkDynamicBuffer &outDynBuffer);
void GetIndexBuffer(uint32_t size, SvkDynamicBuffer &outDynBuffer);
void GetUniformBuffer(uint32_t size, SvkDynamicUniform &outDynUniform);
void FlushDynamicBuffersMemory();
void AddDynamicBufferToDeletion(SvkDynamicBufferGlobal &dynBufferGlobal, SvkDynamicBuffer *buffers);
void AddDynamicUniformToDeletion(SvkDynamicBufferGlobal &dynBufferGlobal, SvkDynamicUniform *buffers);
// free frame data: vertex, index, uniform buffers, descriptor sets
void FreeUnusedDynamicBuffers(uint32_t cmdBufferIndex);
// destroy all dynamic buffers data, including unused
void DestroyDynamicBuffers();
VkSampler GetSampler(SvkSamplerFlags flags);
VkSampler CreateSampler(SvkSamplerFlags flags);
void InitSamplers();
void DestroySamplers();
void CreateTexturesDataStructure();
void DestroyTexturesDataStructure();
VkDescriptorSet GetTextureDescriptor(uint32_t textureId);
void FreeDeletedTextures(uint32_t cmdBufferIndex);
static void DestroyTextureObject(SvkTextureObject &sto);
void InitOcclusionQuerying();
void DestroyOcclusionQuerying();
void ResetOcclusionQueries(VkCommandBuffer cmd, uint32_t cmdIndex);
uint32_t CreateOcclusionQuery(float fromx, float fromy, float tox, float toy, float z);
void GetOcclusionResults(uint32_t firstQuery, uint32_t queryCount, uint32_t *results);
void AcquireNextImage();
void StartFrame();
void EndFrame();
VkShaderModule CreateShaderModule(const uint32_t *spvCode, uint32_t codeSize);
// utils
BOOL GetQueues(VkPhysicalDevice physDevice,
uint32_t &graphicsQueueFamily, uint32_t &transferQueueFamily, uint32_t &presentQueueFamily);
BOOL CheckDeviceExtensions(VkPhysicalDevice physDevice, const CStaticArray<const char *> &requiredExtensions);
VkExtent2D GetSwapchainExtent(uint32_t width, uint32_t height);
uint32_t GetMemoryTypeIndex(uint32_t memoryTypeBits, VkFlags requirementsMask);
uint32_t GetMemoryTypeIndex(uint32_t memoryTypeBits, VkFlags requirementsMask, VkFlags preferredMask);
VkFormat FindSupportedFormat(const VkFormat *formats, uint32_t formatCount, VkImageTiling tiling, VkFormatFeatureFlags features);
void CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer &buffer, VkDeviceMemory &bufferMemory);
void CopyToDeviceMemory(VkDeviceMemory deviceMemory, const void *data, VkDeviceSize size);
public:
void CreateSwapchain(uint32_t width, uint32_t height);
void RecreateSwapchain(uint32_t newWidth, uint32_t newHeight);
void DestroySwapchain();
// get current global pipeline state
SvkPipelineStateFlags &GetPipelineState();
void UpdateViewportDepth(float minDepth, float maxDepth);
// Get current started cmd buffer to write in
VkCommandBuffer GetCurrentCmdBuffer();
void DrawTriangles(uint32_t indexCount, const uint32_t *indices);
void SetTexture(uint32_t textureUnit, uint32_t textureId, SvkSamplerFlags samplerFlags);
// create texture handler, texture IDs starts with 1, not 0
uint32_t CreateTexture();
// create texture handler with specified ID
uint32_t CreateTexture(uint32_t textureId);
// init texture; if onlyUpdate is true, texture will not be allocated
void InitTexture32Bit(
uint32_t &textureId, VkFormat format, void *textureData,
VkExtent2D *mipLevels, uint32_t mipLevelsCount, bool onlyUpdate);
// delete texture
void AddTextureToDeletion(uint32_t textureId);
// for statistics
uint32_t GetTexturePixCount(uint32_t textureId);
void ClearColor(int32_t x, int32_t y, uint32_t width, uint32_t height, float *rgba);
void ClearDepth(int32_t x, int32_t y, uint32_t width, uint32_t height, float depth);
void ClearColor(float *rgba);
void ClearDepth(float depth);
};
#endif
#endif
| 11,901
|
C++
|
.h
| 225
| 49.844444
| 147
| 0.731369
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,212
|
SvkMemoryPool.h
|
sultim-t_Serious-Engine-Vk/Sources/Engine/Graphics/Vulkan/SvkMemoryPool.h
|
/* Copyright (c) 2020 Sultim Tsyrendashiev
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#ifndef SE_INCL_SVKSTATICMEMORYPOOL_H
#define SE_INCL_SVKSTATICMEMORYPOOL_H
#ifdef PRAGMA_ONCE
#pragma once
#endif
#ifdef SE1_VULKAN
#include <Engine/Graphics/Vulkan/VulkanInclude.h>
#include <Engine/Templates/StaticStackArray.cpp>
class SvkMemoryPool
{
private:
struct FreeListNode
{
// index of the next node; -1 if none
int32_t nextNodeIndex;
uint32_t blockIndex;
uint32_t blockCount;
FreeListNode()
{
nextNodeIndex = -1;
blockIndex = blockCount = 0;
}
};
struct AllocHandle
{
uint32_t id;
uint32_t blockIndex;
uint32_t blockCount;
AllocHandle()
{
id = blockIndex = blockCount = 0;
}
};
private:
VkDevice smp_VkDevice;
VkDeviceMemory smp_VkMemory;
uint32_t smp_VkMemoryTypeIndex;
// next pool, if this became full
SvkMemoryPool *smp_pNext;
// all nodes
CStaticArray<FreeListNode> smp_Nodes;
// head of the free ranges list; -1 if none
int32_t smp_FreeListHeadIndex;
int32_t smp_NodeLastIndex;
CStaticStackArray<int32_t> smp_RemovedIndices;
// handles for freeing
CStaticStackArray<AllocHandle> smp_Handles;
uint32_t smp_HandleLastIndex;
uint32_t smp_PreferredSize;
// overall block count
uint32_t smp_BlockCount;
// size of one block in bytes, aligned
uint32_t smp_BlockSize;
// current allocation count
uint32_t smp_AllocationCount;
private:
void Init(uint32_t memoryTypeIndex, uint32_t alignment);
int32_t AddNode();
void RemoveNode(int32_t removed);
public:
SvkMemoryPool(VkDevice device, uint32_t preferredSize);
~SvkMemoryPool();
// Allocate memory with specified size, out params are memory and offset in it.
// Returns handle which must be used to free memory.
uint32_t Allocate(VkMemoryAllocateInfo allocInfo, VkMemoryRequirements memReqs, VkDeviceMemory &outMemory, uint32_t &outOffset);
// Free allocated memory. Handle is a number that was returned in Allocate.
void Free(uint32_t handle);
};
#endif // SE1_VULKAN
#endif
| 2,762
|
C++
|
.h
| 81
| 31.074074
| 130
| 0.739572
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,213
|
WeaponPositions.h
|
sultim-t_Serious-Engine-Vk/Sources/Entities/Common/WeaponPositions.h
|
#if 0 // use this part when manually setting weapon positions
_pShell->DeclareSymbol("persistent user FLOAT wpn_fH[30+1];", &wpn_fH);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fP[30+1];", &wpn_fP);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fB[30+1];", &wpn_fB);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fX[30+1];", &wpn_fX);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fY[30+1];", &wpn_fY);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fZ[30+1];", &wpn_fZ);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fFOV[30+1];", &wpn_fFOV);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fClip[30+1];", &wpn_fClip);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fFX[30+1];", &wpn_fFX);
_pShell->DeclareSymbol("persistent user FLOAT wpn_fFY[30+1];", &wpn_fFY);
// _pShell->DeclareSymbol("persistent user FLOAT wpn_fFZ[30+1];", &wpn_fFZ);
#else
/*
_pShell->DeclareSymbol("user FLOAT wpn_fFX[30+1];", &wpn_fFX);
_pShell->DeclareSymbol("user FLOAT wpn_fFY[30+1];", &wpn_fFY);
*/
#pragma warning(disable: 4305)
wpn_fH[0]=10;
wpn_fH[1]=-1;
wpn_fH[2]=-1;
wpn_fH[3]=-1;
wpn_fH[4]=2;
wpn_fH[5]=2;
wpn_fH[6]=(FLOAT)4;
wpn_fH[7]=(FLOAT)2;
wpn_fH[8]=(FLOAT)2;
wpn_fH[9]=(FLOAT)0.5;
wpn_fH[10]=(FLOAT)-12;
wpn_fH[11]=(FLOAT)4;
wpn_fH[12]=(FLOAT)4.6;
wpn_fH[13]=(FLOAT)0;
wpn_fH[14]=(FLOAT)1;
wpn_fH[15]=(FLOAT)2.2;
wpn_fH[16]=(FLOAT)2.5;
wpn_fH[17]=(FLOAT)0;
wpn_fH[18]=(FLOAT)0;
wpn_fH[19]=(FLOAT)0;
wpn_fH[20]=(FLOAT)0;
wpn_fH[21]=(FLOAT)0;
wpn_fH[22]=(FLOAT)0;
wpn_fH[23]=(FLOAT)0;
wpn_fH[24]=(FLOAT)0;
wpn_fH[25]=(FLOAT)0;
wpn_fH[26]=(FLOAT)0;
wpn_fH[27]=(FLOAT)0;
wpn_fH[28]=(FLOAT)0;
wpn_fH[29]=(FLOAT)0;
wpn_fH[30]=(FLOAT)0;
wpn_fP[0]=0;
wpn_fP[1]=10;
wpn_fP[2]=0;
wpn_fP[3]=0;
wpn_fP[4]=2;
wpn_fP[5]=1;
wpn_fP[6]=(FLOAT)3;
wpn_fP[7]=(FLOAT)0;
wpn_fP[8]=(FLOAT)1;
wpn_fP[9]=(FLOAT)2.5;
wpn_fP[10]=(FLOAT)0;
wpn_fP[11]=(FLOAT)0;
wpn_fP[12]=(FLOAT)2.8;
wpn_fP[13]=(FLOAT)0;
wpn_fP[14]=(FLOAT)3;
wpn_fP[15]=(FLOAT)4.7;
wpn_fP[16]=(FLOAT)6;
wpn_fP[17]=(FLOAT)0;
wpn_fP[18]=(FLOAT)0;
wpn_fP[19]=(FLOAT)0;
wpn_fP[20]=(FLOAT)0;
wpn_fP[21]=(FLOAT)0;
wpn_fP[22]=(FLOAT)0;
wpn_fP[23]=(FLOAT)0;
wpn_fP[24]=(FLOAT)0;
wpn_fP[25]=(FLOAT)0;
wpn_fP[26]=(FLOAT)0;
wpn_fP[27]=(FLOAT)0;
wpn_fP[28]=(FLOAT)0;
wpn_fP[29]=(FLOAT)0;
wpn_fP[30]=(FLOAT)0;
wpn_fB[0]=0;
wpn_fB[1]=6;
wpn_fB[2]=0;
wpn_fB[3]=0;
wpn_fB[4]=0;
wpn_fB[5]=0;
wpn_fB[6]=(FLOAT)0;
wpn_fB[7]=(FLOAT)0;
wpn_fB[8]=(FLOAT)0;
wpn_fB[9]=(FLOAT)0;
wpn_fB[10]=(FLOAT)0;
wpn_fB[11]=(FLOAT)0;
wpn_fB[12]=(FLOAT)0;
wpn_fB[13]=(FLOAT)0;
wpn_fB[14]=(FLOAT)0;
wpn_fB[15]=(FLOAT)0;
wpn_fB[16]=(FLOAT)0;
wpn_fB[17]=(FLOAT)0;
wpn_fB[18]=(FLOAT)0;
wpn_fB[19]=(FLOAT)0;
wpn_fB[20]=(FLOAT)0;
wpn_fB[21]=(FLOAT)0;
wpn_fB[22]=(FLOAT)0;
wpn_fB[23]=(FLOAT)0;
wpn_fB[24]=(FLOAT)0;
wpn_fB[25]=(FLOAT)0;
wpn_fB[26]=(FLOAT)0;
wpn_fB[27]=(FLOAT)0;
wpn_fB[28]=(FLOAT)0;
wpn_fB[29]=(FLOAT)0;
wpn_fB[30]=(FLOAT)0;
wpn_fX[0]=0.08;
wpn_fX[1]=0.23;
wpn_fX[2]=0.19;
wpn_fX[3]=0.19;
wpn_fX[4]=0.12;
wpn_fX[5]=0.13;
wpn_fX[6]=(FLOAT)0.121;
wpn_fX[7]=(FLOAT)0.137;
wpn_fX[8]=(FLOAT)0.17;
wpn_fX[9]=(FLOAT)0.155;
wpn_fX[10]=(FLOAT)0.16;
wpn_fX[11]=(FLOAT)0.204;
wpn_fX[12]=(FLOAT)0.204;
wpn_fX[13]=(FLOAT)0;
wpn_fX[14]=(FLOAT)0.141;
wpn_fX[15]=(FLOAT)0.169;
wpn_fX[16]=(FLOAT)0.17;
wpn_fX[17]=(FLOAT)0;
wpn_fX[18]=(FLOAT)0;
wpn_fX[19]=(FLOAT)0;
wpn_fX[20]=(FLOAT)0;
wpn_fX[21]=(FLOAT)0;
wpn_fX[22]=(FLOAT)0;
wpn_fX[23]=(FLOAT)0;
wpn_fX[24]=(FLOAT)0;
wpn_fX[25]=(FLOAT)0;
wpn_fX[26]=(FLOAT)0;
wpn_fX[27]=(FLOAT)0;
wpn_fX[28]=(FLOAT)0;
wpn_fX[29]=(FLOAT)0;
wpn_fX[30]=(FLOAT)0;
wpn_fY[0]=0;
wpn_fY[1]=-0.28;
wpn_fY[2]=-0.21;
wpn_fY[3]=-0.21;
wpn_fY[4]=-0.22;
wpn_fY[5]=-0.21;
wpn_fY[6]=(FLOAT)-0.213;
wpn_fY[7]=(FLOAT)-0.24;
wpn_fY[8]=(FLOAT)-0.325;
wpn_fY[9]=(FLOAT)-0.515;
wpn_fY[10]=(FLOAT)-0.2;
wpn_fY[11]=(FLOAT)-0.102;
wpn_fY[12]=(FLOAT)-0.306;
wpn_fY[13]=(FLOAT)0;
wpn_fY[14]=(FLOAT)-0.174;
wpn_fY[15]=(FLOAT)-0.232;
wpn_fY[16]=(FLOAT)-0.3;
wpn_fY[17]=(FLOAT)0;
wpn_fY[18]=(FLOAT)0;
wpn_fY[19]=(FLOAT)0;
wpn_fY[20]=(FLOAT)0;
wpn_fY[21]=(FLOAT)0;
wpn_fY[22]=(FLOAT)0;
wpn_fY[23]=(FLOAT)0;
wpn_fY[24]=(FLOAT)0;
wpn_fY[25]=(FLOAT)0;
wpn_fY[26]=(FLOAT)0;
wpn_fY[27]=(FLOAT)0;
wpn_fY[28]=(FLOAT)0;
wpn_fY[29]=(FLOAT)0;
wpn_fY[30]=(FLOAT)0;
wpn_fZ[0]=0;
wpn_fZ[1]=-0.44;
wpn_fZ[2]=-0.1;
wpn_fZ[3]=-0.1;
wpn_fZ[4]=-0.34;
wpn_fZ[5]=-0.364;
wpn_fZ[6]=(FLOAT)-0.285;
wpn_fZ[7]=(FLOAT)-0.328;
wpn_fZ[8]=(FLOAT)-0.24;
wpn_fZ[9]=(FLOAT)-0.130001;
wpn_fZ[10]=(FLOAT)-0.1;
wpn_fZ[11]=(FLOAT)0;
wpn_fZ[12]=(FLOAT)-0.57;
wpn_fZ[13]=(FLOAT)0;
wpn_fZ[14]=(FLOAT)-0.175;
wpn_fZ[15]=(FLOAT)-0.308;
wpn_fZ[16]=(FLOAT)-0.625;
wpn_fZ[17]=(FLOAT)0;
wpn_fZ[18]=(FLOAT)0;
wpn_fZ[19]=(FLOAT)0;
wpn_fZ[20]=(FLOAT)0;
wpn_fZ[21]=(FLOAT)0;
wpn_fZ[22]=(FLOAT)0;
wpn_fZ[23]=(FLOAT)0;
wpn_fZ[24]=(FLOAT)0;
wpn_fZ[25]=(FLOAT)0;
wpn_fZ[26]=(FLOAT)0;
wpn_fZ[27]=(FLOAT)0;
wpn_fZ[28]=(FLOAT)0;
wpn_fZ[29]=(FLOAT)0;
wpn_fZ[30]=(FLOAT)0;
wpn_fFOV[0]=2 * 1.18f;
wpn_fFOV[1]=41.5 * 1.18f;
wpn_fFOV[2]=57 * 1.18f;
wpn_fFOV[3]=57 * 1.18f;
wpn_fFOV[4]=41 * 1.18f;
wpn_fFOV[5]=52.5 * 1.18f;
wpn_fFOV[6]=(FLOAT)49 * 1.18f;
wpn_fFOV[7]=(FLOAT)66.9 * 1.18f;
wpn_fFOV[8]=(FLOAT)66 * 1.18f;
wpn_fFOV[9]=(FLOAT)85.5 * 1.18f;
wpn_fFOV[10]=(FLOAT)72 * 1.18f;
wpn_fFOV[11]=(FLOAT)80 * 1.18f;
wpn_fFOV[12]=(FLOAT)50 * 1.18f;
wpn_fFOV[13]=(FLOAT)80 * 1.18f;
wpn_fFOV[14]=(FLOAT)70.5 * 1.18f;
wpn_fFOV[15]=(FLOAT)52.5 * 1.18f;
wpn_fFOV[16]=(FLOAT)50 * 1.18f;
wpn_fFOV[17]=(FLOAT)0;
wpn_fFOV[18]=(FLOAT)0;
wpn_fFOV[19]=(FLOAT)0;
wpn_fFOV[20]=(FLOAT)0;
wpn_fFOV[21]=(FLOAT)0;
wpn_fFOV[22]=(FLOAT)0;
wpn_fFOV[23]=(FLOAT)0;
wpn_fFOV[24]=(FLOAT)0;
wpn_fFOV[25]=(FLOAT)0;
wpn_fFOV[26]=(FLOAT)0;
wpn_fFOV[27]=(FLOAT)0;
wpn_fFOV[28]=(FLOAT)0;
wpn_fFOV[29]=(FLOAT)0;
wpn_fFOV[30]=(FLOAT)0;
wpn_fClip[0]=0;
wpn_fClip[1]=0.1;
wpn_fClip[2]=0.1;
wpn_fClip[3]=0.1;
wpn_fClip[4]=0.1;
wpn_fClip[5]=0.1;
wpn_fClip[6]=0.1;
wpn_fClip[7]=0.1;
wpn_fClip[8]=0.1;
wpn_fClip[9]=0.1;
wpn_fClip[10]=0.1;
wpn_fClip[11]=0.1;
wpn_fClip[12]=0.1;
wpn_fClip[13]=0.1;
wpn_fClip[14]=0.1;
wpn_fClip[15]=0.1;
wpn_fClip[16]=0.1;
wpn_fClip[17]=0;
wpn_fClip[18]=0;
wpn_fClip[19]=0;
wpn_fClip[20]=0;
wpn_fClip[21]=0;
wpn_fClip[22]=0;
wpn_fClip[23]=0;
wpn_fClip[24]=0;
wpn_fClip[25]=0;
wpn_fClip[26]=0;
wpn_fClip[27]=0;
wpn_fClip[28]=0;
wpn_fClip[29]=0;
wpn_fClip[30]=0;
wpn_fFX[0]=(FLOAT)0;
wpn_fFX[1]=(FLOAT)0;
wpn_fFX[2]=(FLOAT)0;
wpn_fFX[3]=(FLOAT)0;
wpn_fFX[4]=(FLOAT)0;
wpn_fFX[5]=(FLOAT)0;
wpn_fFX[6]=(FLOAT)0;
wpn_fFX[7]=(FLOAT)0;
wpn_fFX[8]=(FLOAT)-0.1;
wpn_fFX[9]=(FLOAT)0;
wpn_fFX[10]=(FLOAT)0;
wpn_fFX[11]=(FLOAT)0;
wpn_fFX[12]=(FLOAT)0;
wpn_fFX[13]=(FLOAT)0;
wpn_fFX[14]=(FLOAT)-0.1;
wpn_fFX[15]=(FLOAT)0;
wpn_fFX[16]=(FLOAT)0.25;
wpn_fFX[17]=(FLOAT)0;
wpn_fFX[18]=(FLOAT)0;
wpn_fFX[19]=(FLOAT)0;
wpn_fFX[20]=(FLOAT)0;
wpn_fFX[21]=(FLOAT)0;
wpn_fFX[22]=(FLOAT)0;
wpn_fFX[23]=(FLOAT)0;
wpn_fFX[24]=(FLOAT)0;
wpn_fFX[25]=(FLOAT)0;
wpn_fFX[26]=(FLOAT)0;
wpn_fFX[27]=(FLOAT)0;
wpn_fFX[28]=(FLOAT)0;
wpn_fFX[29]=(FLOAT)0;
wpn_fFX[30]=(FLOAT)0;
wpn_fFY[0]=(FLOAT)0;
wpn_fFY[1]=(FLOAT)0;
wpn_fFY[2]=(FLOAT)0;
wpn_fFY[3]=(FLOAT)0;
wpn_fFY[4]=(FLOAT)0;
wpn_fFY[5]=(FLOAT)0;
wpn_fFY[6]=(FLOAT)0;
wpn_fFY[7]=(FLOAT)0;
wpn_fFY[8]=(FLOAT)0.11;
wpn_fFY[9]=(FLOAT)0;
wpn_fFY[10]=(FLOAT)0;
wpn_fFY[11]=(FLOAT)0;
wpn_fFY[12]=(FLOAT)0;
wpn_fFY[13]=(FLOAT)0;
wpn_fFY[14]=(FLOAT)-0.4;
wpn_fFY[15]=(FLOAT)0;
wpn_fFY[16]=(FLOAT)-0.5;
wpn_fFY[17]=(FLOAT)0;
wpn_fFY[18]=(FLOAT)0;
wpn_fFY[19]=(FLOAT)0;
wpn_fFY[20]=(FLOAT)0;
wpn_fFY[21]=(FLOAT)0;
wpn_fFY[22]=(FLOAT)0;
wpn_fFY[23]=(FLOAT)0;
wpn_fFY[24]=(FLOAT)0;
wpn_fFY[25]=(FLOAT)0;
wpn_fFY[26]=(FLOAT)0;
wpn_fFY[27]=(FLOAT)0;
wpn_fFY[28]=(FLOAT)0;
wpn_fFY[29]=(FLOAT)0;
wpn_fFY[30]=(FLOAT)0;
// tommygun
wpn_fH[6]=(FLOAT)4;
wpn_fP[6]=(FLOAT)3;
wpn_fB[6]=(FLOAT)0;
wpn_fX[6]=(FLOAT)0.121;
wpn_fY[6]=(FLOAT)-0.213;
wpn_fZ[6]=(FLOAT)-0.285;
wpn_fFOV[6]=(FLOAT)49 * 1.18f;
wpn_fClip[6]=0.1;
wpn_fFX[6]=(FLOAT)0;
wpn_fFY[6]=(FLOAT)0;
// grenade launcher
wpn_fH[9]=(FLOAT)2;
wpn_fP[9]=(FLOAT)6;
wpn_fB[9]=(FLOAT)0;
wpn_fX[9]=(FLOAT)0.14;
wpn_fY[9]=(FLOAT)-0.41;
wpn_fZ[9]=(FLOAT)-0.335001;
wpn_fFOV[9]=(FLOAT)44.5 * 1.18f;
wpn_fClip[9]=(FLOAT)0.1;
wpn_fFX[9]=(FLOAT)0;
wpn_fFY[9]=(FLOAT)0;
// iron cannon
wpn_fH[16]=(FLOAT)2.5;
wpn_fP[16]=(FLOAT)6;
wpn_fB[16]=(FLOAT)0;
wpn_fX[16]=(FLOAT)0.225;
wpn_fY[16]=(FLOAT)-0.345;
wpn_fZ[16]=(FLOAT)-0.57;
wpn_fFOV[16]=(FLOAT)57 * 1.18f;
wpn_fClip[16]=(FLOAT)0.1;
wpn_fFX[16]=(FLOAT)0.25;
wpn_fFY[16]=(FLOAT)-0.5;
#pragma warning(default: 4305)
#endif
| 8,428
|
C++
|
.h
| 363
| 22.112948
| 79
| 0.652017
|
sultim-t/Serious-Engine-Vk
| 35
| 11
| 2
|
GPL-2.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,214
|
SavE.cpp
|
FlagBrew_PKSM-Core/source/sav/SavE.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62, Pk11
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavE.hpp"
namespace pksm
{
SavE::SavE(const std::shared_ptr<u8[]>& dt) : Sav3(dt, {0x44, 0x988, 0xCA4})
{
game = Game::E;
OFS_PCItem = blockOfs[1] + 0x0498;
OFS_PouchHeldItem = blockOfs[1] + 0x0560;
OFS_PouchKeyItem = blockOfs[1] + 0x05D8;
OFS_PouchBalls = blockOfs[1] + 0x0650;
OFS_PouchTMHM = blockOfs[1] + 0x0690;
OFS_PouchBerry = blockOfs[1] + 0x0790;
eventFlag = blockOfs[2] + 0x2F0;
// EventConst = EventFlag + (EventFlagMax / 8);
// DaycareOffset = blockOfs[4] + 0x1B0;
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavE::validItems() const
{
static constexpr std::array validItems = {// Normal
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 65, 66, 67, 68, 69, 43, 44, 70, 71, 72, 73, 74, 75, 45, 46, 47, 48, 49,
50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 61, 63, 64, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227,
228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244,
245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
262, 263, 264,
// Ball
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
// Key
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
// TM
328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361,
362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377,
// Berry
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182,
183, 201, 202, 203, 204, 205, 206, 207, 208};
return {
std::pair{Pouch::NormalItem, std::span{validItems.begin(), validItems.begin() + 139} },
std::pair{Pouch::Ball, std::span{validItems.begin() + 139, validItems.begin() + 151}},
std::pair{
Pouch::KeyItem, std::span{validItems.begin() + 151, validItems.begin() + 180}},
std::pair{Pouch::TM, std::span{validItems.begin() + 180, validItems.begin() + 230}},
std::pair{Pouch::Berry, std::span{validItems.begin() + 230, validItems.end()} },
std::pair{Pouch::PCItem, std::span{validItems} }
};
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavE::validItems3() const
{
static constexpr std::array validItems = {// Normal
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 63, 64, 65, 66, 67,
68, 69, 70, 71, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 93, 94, 95, 96, 97,
98, 103, 104, 106, 107, 108, 109, 110, 111, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192,
193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 254,
255, 256, 257, 258,
// Ball
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
// TM
289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305,
306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322,
323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339,
340, 341, 342, 343, 344, 345, 346,
// Berry
133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166,
167, 168, 169, 170, 171, 172, 173, 174, 175,
// Key
259, 260, 261, 262, 263, 264, 265, 266, 268, 269, 270, 271, 272, 273, 274, 275, 276,
277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 349, 350, 351, 352, 353,
354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370,
371, 372, 373, 374, 375, 376};
return {
std::pair{Pouch::NormalItem, std::span{validItems.begin(), validItems.begin() + 139} },
std::pair{Pouch::Ball, std::span{validItems.begin() + 139, validItems.begin() + 151}},
std::pair{Pouch::TM, std::span{validItems.begin() + 151, validItems.begin() + 209}},
std::pair{Pouch::Berry, std::span{validItems.begin() + 209, validItems.begin() + 252}},
std::pair{Pouch::KeyItem, std::span{validItems.begin() + 252, validItems.end()} },
std::pair{Pouch::PCItem, std::span{validItems} }
};
}
}
| 6,894
|
C++
|
.cpp
| 112
| 52.4375
| 104
| 0.548988
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,215
|
SavSUMO.cpp
|
FlagBrew_PKSM-Core/source/sav/SavSUMO.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavSUMO.hpp"
#include "memecrypto.h"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include <algorithm>
namespace pksm
{
SavSUMO::SavSUMO(const std::shared_ptr<u8[]>& dt) : Sav7(dt, 0x6BE00)
{
game = Game::SM;
TrainerCard = 0x1200;
Misc = 0x4000;
PlayTime = 0x40C00;
LastViewedBox = 0x4DE3;
Box = 0x4E00;
Party = 0x1400;
PokeDex = 0x2A00;
PokeDexLanguageFlags = 0x2F50;
WondercardFlags = 0x65C00;
WondercardData = 0x65D00;
PCLayout = 0x4800;
PouchHeldItem = 0x0;
PouchKeyItem = 0x6B8;
PouchTMHM = 0x998;
PouchMedicine = 0xB48;
PouchBerry = 0xC48;
PouchZCrystals = 0xD68;
}
void SavSUMO::resign(void)
{
static constexpr u8 blockCount = 37;
static constexpr u32 csoff = 0x6BC1A;
for (u8 i = 0; i < blockCount; i++)
{
// Clear memecrypto data
if (LittleEndian::convertTo<u16>(&data[csoff + i * 8 - 2]) == 36)
{
std::fill_n(&data[chkofs[i] + 0x100], 0x80, 0);
}
LittleEndian::convertFrom<u16>(
&data[csoff + i * 8], pksm::crypto::crc16({&data[chkofs[i]], chklen[i]}));
}
static constexpr u32 checksumTableOffset = 0x6BC00;
static constexpr u32 checksumTableLength = 0x140;
static constexpr u32 memecryptoOffset = 0x6BB00;
auto hash = crypto::sha256({&data[checksumTableOffset], checksumTableLength});
u8 decryptedSignature[0x80];
reverseCrypt(&data[memecryptoOffset], decryptedSignature);
std::copy(hash.begin(), hash.end(), decryptedSignature);
memecrypto_sign(decryptedSignature, &data[memecryptoOffset], 0x80);
}
int SavSUMO::dexFormIndex(int species, int formct, int start) const
{
int formindex = start;
int f = 0;
for (u8 i = 0; i < 230; i += 2)
{
if (formtable[i] == species)
{
break;
}
f = formtable[i + 1];
formindex += f - 1;
}
return f > formct ? -1 : formindex;
}
int SavSUMO::dexFormCount(int species) const
{
for (u8 i = 0; i < 230; i += 2)
{
if (formtable[i] == species)
{
return formtable[i + 1];
}
}
return 0;
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavSUMO::validItems() const
{
static constexpr std::array NormalItem = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112, 116, 117, 118, 119, 135, 136, 137, 213,
214, 215, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265,
266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282,
283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299,
300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316,
317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 492, 493, 494, 495, 496, 497,
498, 499, 534, 535, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549,
550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 571, 572,
573, 576, 577, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 639, 640, 644,
646, 647, 648, 649, 650, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667,
668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684,
685, 699, 704, 710, 711, 715, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762,
763, 764, 767, 768, 769, 770, 795, 796, 844, 846, 849, 851, 853, 854, 855, 856, 879,
880, 881, 882, 883, 884, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915,
916, 917, 918, 919, 920};
static constexpr std::array KeyItem = {216, 465, 466, 628, 629, 631, 632, 638, 705, 706,
765, 773, 797, 841, 842, 843, 845, 847, 850, 857, 858, 860};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 618, 619, 620, 690,
691, 692, 693, 694};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 65, 66, 67, 134, 504, 565, 566, 567, 568, 569, 570, 591, 645, 708, 709,
852};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212, 686, 687, 688};
static constexpr std::array ZCrystals = {807, 808, 809, 810, 811, 812, 813, 814, 815, 816,
817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833,
834, 835};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} },
std::pair{Pouch::ZCrystals, std::span{ZCrystals} }
};
}
}
| 8,080
|
C++
|
.cpp
| 155
| 43.36129
| 100
| 0.553969
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,216
|
Sav6.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav6.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav6.hpp"
#include "pkx/PK6.hpp"
#include "utils/endian.hpp"
#include "utils/i18n.hpp"
#include "utils/random.hpp"
#include "utils/utils.hpp"
#include "wcx/WC6.hpp"
namespace pksm
{
u16 Sav6::TID(void) const
{
return LittleEndian::convertTo<u16>(&data[TrainerCard]);
}
void Sav6::TID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[TrainerCard], v);
}
u16 Sav6::SID(void) const
{
return LittleEndian::convertTo<u16>(&data[TrainerCard + 2]);
}
void Sav6::SID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[TrainerCard + 2], v);
}
GameVersion Sav6::version(void) const
{
return GameVersion(data[TrainerCard + 4]);
}
void Sav6::version(GameVersion v)
{
data[TrainerCard + 4] = u8(v);
}
Gender Sav6::gender(void) const
{
return Gender{data[TrainerCard + 5]};
}
void Sav6::gender(Gender v)
{
data[TrainerCard + 5] = u8(v);
}
u8 Sav6::subRegion(void) const
{
return data[TrainerCard + 0x26];
}
void Sav6::subRegion(u8 v)
{
data[TrainerCard + 0x26] = v;
}
u8 Sav6::country(void) const
{
return data[TrainerCard + 0x27];
}
void Sav6::country(u8 v)
{
data[TrainerCard + 0x27] = v;
}
u8 Sav6::consoleRegion(void) const
{
return data[TrainerCard + 0x2C];
}
void Sav6::consoleRegion(u8 v)
{
data[TrainerCard + 0x2C] = v;
}
Language Sav6::language(void) const
{
return Language(data[TrainerCard + 0x2D]);
}
void Sav6::language(Language v)
{
data[TrainerCard + 0x2D] = u8(v);
}
std::string Sav6::otName(void) const
{
return StringUtils::transString67(
StringUtils::getString(data.get(), TrainerCard + 0x48, 13));
}
void Sav6::otName(const std::string_view& v)
{
StringUtils::setString(data.get(), StringUtils::transString67(v), TrainerCard + 0x48, 13);
}
u32 Sav6::money(void) const
{
return LittleEndian::convertTo<u32>(&data[Trainer2 + 0x8]);
}
void Sav6::money(u32 v)
{
LittleEndian::convertFrom<u32>(&data[Trainer2 + 0x8], v);
}
u32 Sav6::BP(void) const
{
return LittleEndian::convertTo<u32>(&data[Trainer2 + (game == Game::XY ? 0x3C : 0x30)]);
}
void Sav6::BP(u32 v)
{
LittleEndian::convertFrom<u32>(&data[Trainer2 + (game == Game::XY ? 0x3C : 0x30)], v);
}
u8 Sav6::badges(void) const
{
u8& badgeBits = data[Trainer2 + 0xC];
u8 ret = 0;
for (size_t i = 0; i < sizeof(badgeBits) * 8; i++)
{
ret += (badgeBits & (1 << i)) ? 1 : 0;
}
return ret;
}
u16 Sav6::playedHours(void) const
{
return LittleEndian::convertTo<u16>(&data[PlayTime]);
}
void Sav6::playedHours(u16 v)
{
LittleEndian::convertFrom<u16>(&data[PlayTime], v);
}
u8 Sav6::playedMinutes(void) const
{
return data[PlayTime + 2];
}
void Sav6::playedMinutes(u8 v)
{
data[PlayTime + 2] = v;
}
u8 Sav6::playedSeconds(void) const
{
return data[PlayTime + 3];
}
void Sav6::playedSeconds(u8 v)
{
data[PlayTime + 3] = v;
}
u8 Sav6::currentBox(void) const
{
return data[LastViewedBox];
}
void Sav6::currentBox(u8 v)
{
data[LastViewedBox] = v;
}
u8 Sav6::unlockedBoxes(void) const
{
return data[LastViewedBox - 1];
}
void Sav6::unlockedBoxes(u8 v)
{
data[LastViewedBox - 1] = v;
}
u32 Sav6::boxOffset(u8 box, u8 slot) const
{
return Box + PK6::BOX_LENGTH * 30 * box + PK6::BOX_LENGTH * slot;
}
u32 Sav6::partyOffset(u8 slot) const
{
return Party + PK6::PARTY_LENGTH * slot;
}
std::unique_ptr<PKX> Sav6::pkm(u8 slot) const
{
return PKX::getPKM<Generation::SIX>(&data[partyOffset(slot)], PK6::PARTY_LENGTH);
}
void Sav6::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::SIX)
{
auto pk6 = pk.partyClone();
pk6->encrypt();
std::ranges::copy(pk6->rawData(), &data[partyOffset(slot)]);
}
}
std::unique_ptr<PKX> Sav6::pkm(u8 box, u8 slot) const
{
return PKX::getPKM<Generation::SIX>(&data[boxOffset(box, slot)], PK6::BOX_LENGTH);
}
void Sav6::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (pk.generation() == Generation::SIX)
{
auto pkm = pk.clone();
if (applyTrade)
{
trade(*pkm);
}
std::ranges::copy(
pkm->rawData().subspan(0, PK6::BOX_LENGTH), &data[boxOffset(box, slot)]);
}
}
void Sav6::trade(PKX& pk, const Date& date) const
{
if (pk.generation() == Generation::SIX)
{
PK6& pk6 = static_cast<PK6&>(pk);
if (pk6.egg())
{
if (otName() != pk6.otName() || TID() != pk6.TID() || SID() != pk6.SID() ||
gender() != pk6.otGender())
{
pk6.metLocation(30002);
pk6.metDate(date);
}
}
else if (otName() == pk6.otName() && TID() == pk6.TID() && SID() == pk6.SID() &&
gender() == pk6.otGender())
{
pk6.currentHandler(PKXHandler::OT);
if (!pk6.untraded() &&
(country() != pk6.geoCountry(0) || subRegion() != pk6.geoRegion(0)))
{
for (int i = 4; i > 0; i--)
{
pk6.geoCountry(pk6.geoCountry(i - 1), i);
pk6.geoRegion(pk6.geoRegion(i - 1), i);
}
pk6.geoCountry(0, country());
pk6.geoRegion(0, subRegion());
}
}
else
{
if (otName() != pk6.htName() || gender() != pk6.htGender() ||
(pk6.geoCountry(0) == 0 && pk6.geoRegion(0) == 0 && !pk6.untradedEvent()))
{
for (int i = 4; i > 0; i--)
{
pk6.geoCountry(pk6.geoCountry(i - 1), i);
pk6.geoRegion(pk6.geoRegion(i - 1), i);
}
pk6.geoCountry(0, country());
pk6.geoRegion(0, subRegion());
}
if (pk6.htName() != otName())
{
pk6.htFriendship(pk6.baseFriendship());
pk6.htAffection(0);
pk6.htName(otName());
}
pk6.currentHandler(PKXHandler::NonOT);
pk6.htGender(gender());
if (pk6.htMemory() == 0)
{
pk6.htMemory(4);
pk6.htTextVar(9);
pk6.htIntensity(1);
/*static constexpr u32 memoryBits[70] = {
0x000000, 0x04CBFD, 0x004BFD, 0x04CBFD, 0x04CBFD, 0xFFFBFB, 0x84FFF9,
0x47FFFF, 0xBF7FFA, 0x7660B0, 0x80BDF9, 0x88FB7A, 0x083F79, 0x0001FE, 0xCFEFFF,
0x84EBAF, 0xB368B0, 0x091F7E, 0x0320A0, 0x080DDD, 0x081A7B, 0x404030, 0x0FFFFF,
0x9A08BC, 0x089A7B, 0x0032AA, 0x80FF7A, 0x0FFFFF, 0x0805FD, 0x098278, 0x0B3FFF,
0x8BBFFA, 0x8BBFFE, 0x81A97C, 0x8BB97C, 0x8BBF7F, 0x8BBF7F, 0x8BBF7F, 0x8BBF7F,
0xAC3ABE, 0xBFFFFF, 0x8B837C, 0x848AFA, 0x88FFFE, 0x8B0B7C, 0xB76AB2, 0x8B1FFF,
0xBE7AB8, 0xB77EB8, 0x8C9FFD, 0xBF9BFF, 0xF408B0, 0xBCFE7A, 0x8F3F72, 0x90DB7A,
0xBCEBFF, 0xBC5838, 0x9C3FFE, 0x9CFFFF, 0x96D83A, 0xB770B0, 0x881F7A, 0x839F7A,
0x839F7A, 0x839F7A, 0x53897F, 0x41BB6F, 0x0C35FF, 0x8BBF7F, 0x8BBF7F
};*/
u32 bits = 0x04CBFD; // memoryBits[pk6.htMemory()];
while (true)
{
u32 feel = pksm::randomNumber(0, 19);
if ((bits & (1 << feel)) != 0)
{
pk6.htFeeling(feel);
break;
}
}
}
}
}
}
void Sav6::cryptBoxData(bool crypted)
{
for (u8 box = 0; box < maxBoxes(); box++)
{
for (u8 slot = 0; slot < 30; slot++)
{
std::unique_ptr<PKX> pk6 = PKX::getPKM<Generation::SIX>(
&data[boxOffset(box, slot)], PK6::BOX_LENGTH, true);
if (!crypted)
{
pk6->encrypt();
}
}
}
}
int Sav6::dexFormIndex(int species, int formct) const
{
if (formct < 1 || species < 0)
{
return -1; // invalid
}
if (game == Game::ORAS)
{
switch (species)
{
case 25:
return 189; // 7 Pikachu
case 720:
return 196; // 2 Hoopa
case 15:
return 198; // 2 Beedrill
case 18:
return 200; // 2 Pidgeot
case 80:
return 202; // 2 Slowbro
case 208:
return 204; // 2 Steelix
case 254:
return 206; // 2 Sceptile
case 260:
return 208; // 2 Swampert
case 302:
return 210; // 2 Sableye
case 319:
return 212; // 2 Sharpedo
case 323:
return 214; // 2 Camerupt
case 334:
return 216; // 2 Altaria
case 362:
return 218; // 2 Glalie
case 373:
return 220; // 2 Salamence
case 376:
return 222; // 2 Metagross
case 384:
return 224; // 2 Rayquaza
case 428:
return 226; // 2 Lopunny
case 475:
return 228; // 2 Gallade
case 531:
return 230; // 2 Audino
case 719:
return 232; // 2 Diancie
case 382:
return 234; // 2 Kyogre
case 383:
return 236; // 2 Groudon
case 493:
return 238; // 18 Arceus
case 649:
return 256; // 5 Genesect
case 676:
return 261; // 10 Furfrou
}
}
switch (species)
{
case 666:
return 83; // 20 Vivillion
case 669:
return 103; // 5 Flabébé
case 670:
return 108; // 6 Floette
case 671:
return 114; // 5 Florges
case 710:
return 119; // 4 Pumpkaboo
case 711:
return 123; // 4 Gourgeist
case 681:
return 127; // 2 Aegislash
case 716:
return 129; // 2 Xerneas
case 3:
return 131; // 2 Venusaur
case 6:
return 133; // 3 Charizard
case 9:
return 136; // 2 Blastoise
case 65:
return 138; // 2 Alakazam
case 94:
return 140; // 2 Gengar
case 115:
return 142; // 2 Kangaskhan
case 127:
return 144; // 2 Pinsir
case 130:
return 146; // 2 Gyarados
case 142:
return 148; // 2 Aerodactyl
case 150:
return 150; // 3 Mewtwo
case 181:
return 153; // 2 Ampharos
case 212:
return 155; // 2 Scizor
case 214:
return 157; // 2 Heracros
case 229:
return 159; // 2 Houndoom
case 248:
return 161; // 2 Tyranitar
case 257:
return 163; // 2 Blaziken
case 282:
return 165; // 2 Gardevoir
case 303:
return 167; // 2 Mawile
case 306:
return 169; // 2 Aggron
case 308:
return 171; // 2 Medicham
case 310:
return 173; // 2 Manetric
case 354:
return 175; // 2 Banette
case 359:
return 177; // 2 Absol
case 380:
return 179; // 2 Latias
case 381:
return 181; // 2 Latios
case 445:
return 183; // 2 Garchomp
case 448:
return 185; // 2 Lucario
case 460:
return 187; // 2 Abomasnow
case 646:
return 72; // 3 Kyurem
case 647:
return 75; // 2 Keldeo
case 642:
return 77; // 2 Thundurus
case 641:
return 79; // 2 Tornadus
case 645:
return 81; // 2 Landorus
case 201:
return 0; // 28 Unown
case 386:
return 28; // 4 Deoxys
case 492:
return 32; // 2 Shaymin
case 487:
return 34; // 2 Giratina
case 479:
return 36; // 6 Rotom
case 422:
return 42; // 2 Shellos
case 423:
return 44; // 2 Gastrodon
case 412:
return 46; // 3 Burmy
case 413:
return 49; // 3 Wormadam
case 351:
return 52; // 4 Castform
case 421:
return 56; // 2 Cherrim
case 585:
return 58; // 4 Deerling
case 586:
return 62; // 4 Sawsbuck
case 648:
return 66; // 2 Meloetta
case 555:
return 68; // 2 Darmanitan
case 550:
return 70; // 2 Basculin
default:
return -1;
}
}
void Sav6::dex(const PKX& pk)
{
if (!(availableSpecies().count(pk.species()) > 0) || pk.egg())
{
return;
}
const int brSize = 0x60;
int bit = u16(pk.species()) - 1;
int lang = u8(pk.language()) - 1;
if (lang > 5)
{
lang--; // 0-6 language vals
}
int gender = u8(pk.gender()) % 2; // genderless -> male
int shiny = pk.shiny() ? 1 : 0;
int shiftoff = brSize * (1 + gender + 2 * shiny); // after the Owned region
int bd = bit >> 3; // div8
int bm = bit & 7; // mod8
u8 mask = (u8)(1 << bm);
int ofs = PokeDex + 0x8 + bd;
// Owned quality flag
if (pk.version() < GameVersion::X && bit < 649 && game != Game::ORAS)
{ // Species: 1-649 for X/Y, and not for ORAS; Set the Foreign Owned Flag
data[ofs + 0x644] |= mask;
}
else if (pk.version() >= GameVersion::X || game == Game::ORAS)
{ // Set Native Owned Flag (should always happen)
data[ofs + (brSize * 0)] |= mask;
}
// Set the [Species/Gender/Shiny] Seen Flag
data[ofs + shiftoff] |= mask;
// Set the Display flag if none are set
bool displayed = false;
displayed |= (data[ofs + brSize * 5] & mask) != 0;
displayed |= (data[ofs + brSize * 6] & mask) != 0;
displayed |= (data[ofs + brSize * 7] & mask) != 0;
displayed |= (data[ofs + brSize * 8] & mask) != 0;
if (!displayed)
{ // offset is already biased by brSize, reuse shiftoff but for the display
// flags.
data[ofs + brSize * 4 + shiftoff] |= mask;
}
// Set the Language
if (lang < 0)
{
lang = 1;
}
data[PokeDexLanguageFlags + (bit * 7 + lang) / 8] |= (u8)(1 << ((bit * 7 + lang) % 8));
// Set DexNav count (only if not encountered previously)
if (game == Game::ORAS &&
LittleEndian::convertTo<u16>(&data[EncounterCount + (u16(pk.species()) - 1) * 2]) == 0)
{
LittleEndian::convertFrom<u16>(&data[EncounterCount + (u16(pk.species()) - 1) * 2], 1);
}
// Set Form flags
int fc = PersonalXYORAS::formCount(u16(pk.species()));
int f = dexFormIndex(u16(pk.species()), fc);
if (f < 0)
{
return;
}
int formLen = game == Game::XY ? 0x18 : 0x26;
int formDex = PokeDex + 0x8 + brSize * 9;
bit = f + pk.alternativeForm();
// Set Form Seen Flag
data[formDex + formLen * shiny + bit / 8] |= (u8)(1 << (bit % 8));
// Set Displayed Flag if necessary, check all flags
for (int i = 0; i < fc; i++)
{
bit = f + i;
if ((data[formDex + formLen * 2 + bit / 8] & (u8)(1 << (bit % 8))) != 0)
{ // Nonshiny
return; // already set
}
if ((data[formDex + formLen * 3 + bit / 8] & (u8)(1 << (bit % 8))) != 0)
{ // Shiny
return; // already set
}
}
bit = f + pk.alternativeForm();
data[formDex + formLen * (2 + shiny) + bit / 8] |= (u8)(1 << (bit % 8));
}
int Sav6::dexSeen(void) const
{
int ret = 0;
for (const auto& spec : availableSpecies())
{
u16 i = u16(spec);
int bitIndex = (i - 1) & 7;
for (int j = 0; j < 4; j++) // All seen flags: gender & shinies
{
int ofs = PokeDex + (0x68 + (j * 0x60)) + ((i - 1) >> 3);
if ((data[ofs] >> bitIndex & 1) != 0)
{
ret++;
break;
}
}
}
return ret;
}
int Sav6::dexCaught(void) const
{
int ret = 0;
for (const auto& spec : availableSpecies())
{
u16 i = u16(spec);
int bitIndex = (i - 1) & 7;
int ofs = PokeDex + 0x8 + ((i - 1) >> 3);
if ((data[ofs] >> bitIndex & 1) != 0)
{
ret++;
}
}
return ret;
}
void Sav6::mysteryGift(const WCX& wc, int& pos)
{
if (wc.generation() == Generation::SIX)
{
data[WondercardFlags + wc.ID() / 8] |= 0x1 << (wc.ID() % 8);
std::copy(wc.rawData(), wc.rawData() + WC6::length,
&data[WondercardData + WC6::length * pos]);
if (game == Game::ORAS && wc.ID() == 2048 && wc.object() == 726)
{
static constexpr u32 EON_MAGIC = 0x225D73C2;
LittleEndian::convertFrom<u32>(&data[0x319B8], EON_MAGIC);
LittleEndian::convertFrom<u32>(&data[0x319DE], EON_MAGIC);
}
pos = (pos + 1) % 24;
}
}
std::string Sav6::boxName(u8 box) const
{
return StringUtils::transString67(
StringUtils::getString(data.get(), PCLayout + 0x22 * box, 17));
}
void Sav6::boxName(u8 box, const std::string_view& name)
{
StringUtils::setString(
data.get(), StringUtils::transString67(name), PCLayout + 0x22 * box, 17);
}
u8 Sav6::boxWallpaper(u8 box) const
{
return data[0x4400 + 1054 + box];
}
void Sav6::boxWallpaper(u8 box, u8 v)
{
data[0x4400 + 1054 + box] = v;
}
u8 Sav6::partyCount(void) const
{
return data[Party + 6 * PK6::PARTY_LENGTH];
}
void Sav6::partyCount(u8 v)
{
data[Party + 6 * PK6::PARTY_LENGTH] = v;
}
std::unique_ptr<PKX> Sav6::emptyPkm() const
{
return PKX::getPKM<Generation::SIX>(nullptr, PK6::BOX_LENGTH);
}
int Sav6::currentGiftAmount(void) const
{
u8 t;
// 24 max wonder cards
for (t = 0; t < 24; t++)
{
bool empty = true;
for (u32 j = 0; j < WC6::length; j++)
{
if (data[WondercardData + t * WC6::length + j] != 0)
{
empty = false;
break;
}
}
if (empty)
{
break;
}
}
return t;
}
std::unique_ptr<WCX> Sav6::mysteryGift(int pos) const
{
return std::make_unique<WC6>(&data[WondercardData + pos * WC6::length]);
}
void Sav6::item(const Item& item, Pouch pouch, u16 slot)
{
Item6 inject = static_cast<Item6>(item);
auto write = inject.bytes();
switch (pouch)
{
case Pouch::NormalItem:
std::copy(write.begin(), write.end(), &data[PouchHeldItem + slot * 4]);
break;
case Pouch::KeyItem:
std::copy(write.begin(), write.end(), &data[PouchKeyItem + slot * 4]);
break;
case Pouch::TM:
std::copy(write.begin(), write.end(), &data[PouchTMHM + slot * 4]);
break;
case Pouch::Medicine:
std::copy(write.begin(), write.end(), &data[PouchMedicine + slot * 4]);
break;
case Pouch::Berry:
std::copy(write.begin(), write.end(), &data[PouchBerry + slot * 4]);
break;
default:
return;
}
}
std::unique_ptr<Item> Sav6::item(Pouch pouch, u16 slot) const
{
switch (pouch)
{
case Pouch::NormalItem:
return std::make_unique<Item6>(&data[PouchHeldItem + slot * 4]);
case Pouch::KeyItem:
return std::make_unique<Item6>(&data[PouchKeyItem + slot * 4]);
case Pouch::TM:
return std::make_unique<Item6>(&data[PouchTMHM + slot * 4]);
case Pouch::Medicine:
return std::make_unique<Item6>(&data[PouchMedicine + slot * 4]);
case Pouch::Berry:
return std::make_unique<Item6>(&data[PouchBerry + slot * 4]);
default:
return nullptr;
}
}
SmallVector<std::pair<Sav::Pouch, int>, 15> Sav6::pouches(void) const
{
return {
std::pair{Pouch::NormalItem, game == Game::XY ? 286 : 305},
std::pair{Pouch::KeyItem, game == Game::XY ? 31 : 47 },
std::pair{Pouch::TM, game == Game::XY ? 105 : 107},
std::pair{Pouch::Medicine, game == Game::XY ? 51 : 54 },
std::pair{Pouch::Berry, 67 }
};
}
}
| 24,856
|
C++
|
.cpp
| 731
| 22.529412
| 99
| 0.46889
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,217
|
SavXY.cpp
|
FlagBrew_PKSM-Core/source/sav/SavXY.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavXY.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include <algorithm>
namespace pksm
{
SavXY::SavXY(const std::shared_ptr<u8[]>& dt) : Sav6(dt, 0x65600)
{
game = Game::XY;
TrainerCard = 0x14000;
Trainer2 = 0x4200;
PlayTime = 0x1800;
Box = 0x22600;
Party = 0x14200;
PokeDex = 0x15000;
PokeDexLanguageFlags = 0x153C8;
EncounterCount = 0x0;
WondercardData = 0x1BD00;
WondercardFlags = 0x1BC00;
PCLayout = 0x4400;
LastViewedBox = 0x483F;
PouchHeldItem = 0x400;
PouchKeyItem = 0xA40;
PouchTMHM = 0xBC0;
PouchMedicine = 0xD68;
PouchBerry = 0xE68;
}
void SavXY::resign(void)
{
static constexpr u8 blockCount = 55;
static constexpr u32 csoff = 0x6541A;
for (u8 i = 0; i < blockCount; i++)
{
LittleEndian::convertFrom<u16>(
&data[csoff + i * 8], pksm::crypto::ccitt16({&data[chkofs[i]], chklen[i]}));
}
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavXY::validItems() const
{
static constexpr std::array NormalItem = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 116, 117, 118, 119, 135, 136,
213, 214, 215, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230,
231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281,
282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298,
299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315,
316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 492, 493, 494, 495, 496,
497, 498, 499, 500, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549,
550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 571, 572,
573, 576, 577, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 639, 640, 644,
646, 647, 648, 649, 650, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663,
664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680,
681, 682, 683, 684, 685, 699, 704, 710, 711, 715};
static constexpr std::array KeyItem = {216, 431, 442, 445, 446, 447, 450, 465, 466, 471,
628, 629, 631, 632, 638, 641, 642, 643, 689, 695, 696, 697, 698, 700, 701, 702, 703,
705, 712, 713, 714};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 618, 619, 620, 690,
691, 692, 693, 694, 420, 421, 422, 423, 424};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 134, 504, 565, 566, 567, 568, 569, 570, 571, 591, 645, 708, 709};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212, 686, 687, 688};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} }
};
}
}
| 6,176
|
C++
|
.cpp
| 108
| 49.138889
| 100
| 0.561623
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,218
|
Sav5.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav5.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav5.hpp"
#include "pkx/PK5.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include "utils/i18n.hpp"
#include "utils/utils.hpp"
#include "wcx/PGF.hpp"
namespace pksm
{
u16 Sav5::TID(void) const
{
return LittleEndian::convertTo<u16>(&data[Trainer1 + 0x14]);
}
void Sav5::TID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[Trainer1 + 0x14], v);
}
u16 Sav5::SID(void) const
{
return LittleEndian::convertTo<u16>(&data[Trainer1 + 0x16]);
}
void Sav5::SID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[Trainer1 + 0x16], v);
}
GameVersion Sav5::version(void) const
{
return GameVersion(data[Trainer1 + 0x1F]);
}
void Sav5::version(GameVersion v)
{
data[Trainer1 + 0x1F] = u8(v);
}
Gender Sav5::gender(void) const
{
return Gender{data[Trainer1 + 0x21]};
}
void Sav5::gender(Gender v)
{
data[Trainer1 + 0x21] = u8(v);
}
Language Sav5::language(void) const
{
return Language(data[Trainer1 + 0x1E]);
}
void Sav5::language(Language v)
{
data[Trainer1 + 0x1E] = u8(v);
}
std::string Sav5::otName(void) const
{
return StringUtils::transString45(
StringUtils::getString(data.get(), Trainer1 + 0x4, 8, u'\uFFFF'));
}
void Sav5::otName(const std::string_view& v)
{
StringUtils::setString(
data.get(), StringUtils::transString45(v), Trainer1 + 0x4, 8, u'\uFFFF', 0);
}
u32 Sav5::money(void) const
{
return LittleEndian::convertTo<u32>(&data[Trainer2]);
}
void Sav5::money(u32 v)
{
LittleEndian::convertFrom<u32>(&data[Trainer2], v);
}
u32 Sav5::BP(void) const
{
return LittleEndian::convertTo<u16>(&data[BattleSubway]);
}
void Sav5::BP(u32 v)
{
LittleEndian::convertFrom<u32>(&data[BattleSubway], v);
}
u8 Sav5::badges(void) const
{
u8& badgeBits = data[Trainer2 + 0x4];
u8 ret = 0;
for (size_t i = 0; i < sizeof(badgeBits) * 8; i++)
{
ret += (badgeBits & (1 << i)) ? 1 : 0;
}
return ret;
}
u16 Sav5::playedHours(void) const
{
return LittleEndian::convertTo<u16>(&data[Trainer1 + 0x24]);
}
void Sav5::playedHours(u16 v)
{
LittleEndian::convertFrom<u16>(&data[Trainer1 + 0x24], v);
}
u8 Sav5::playedMinutes(void) const
{
return data[Trainer1 + 0x26];
}
void Sav5::playedMinutes(u8 v)
{
data[Trainer1 + 0x26] = v;
}
u8 Sav5::playedSeconds(void) const
{
return data[Trainer1 + 0x27];
}
void Sav5::playedSeconds(u8 v)
{
data[Trainer1 + 0x27] = v;
}
u8 Sav5::currentBox(void) const
{
return data[PCLayout];
}
void Sav5::currentBox(u8 v)
{
data[PCLayout] = v;
}
u8 Sav5::unlockedBoxes(void) const
{
return data[PCLayout + 0x3DD];
}
void Sav5::unlockedBoxes(u8 v)
{
data[PCLayout + 0x3DD] = v;
}
u32 Sav5::boxOffset(u8 box, u8 slot) const
{
return Box + PK5::BOX_LENGTH * box * 30 + 0x10 * box + PK5::BOX_LENGTH * slot;
}
u32 Sav5::partyOffset(u8 slot) const
{
return Party + 8 + PK5::PARTY_LENGTH * slot;
}
std::unique_ptr<PKX> Sav5::pkm(u8 slot) const
{
return PKX::getPKM<Generation::FIVE>(&data[partyOffset(slot)], PK5::PARTY_LENGTH);
}
void Sav5::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::FIVE)
{
auto pk5 = pk.partyClone();
pk5->encrypt();
std::ranges::copy(pk5->rawData(), &data[partyOffset(slot)]);
}
}
std::unique_ptr<PKX> Sav5::pkm(u8 box, u8 slot) const
{
return PKX::getPKM<Generation::FIVE>(&data[boxOffset(box, slot)], PK5::BOX_LENGTH);
}
void Sav5::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (pk.generation() == Generation::FIVE)
{
auto pk5 = pk.clone();
if (applyTrade)
{
trade(*pk5);
}
std::ranges::copy(
pk5->rawData().subspan(0, PK5::BOX_LENGTH), &data[boxOffset(box, slot)]);
}
}
void Sav5::trade(PKX& pk, const Date& date) const
{
if (pk.generation() == Generation::FIVE && pk.egg() &&
(otName() != pk.otName() || TID() != pk.TID() || SID() != pk.SID() ||
gender() != pk.otGender()))
{
pk.metLocation(30003);
pk.metDate(date);
}
}
void Sav5::cryptBoxData(bool crypted)
{
for (u8 box = 0; box < maxBoxes(); box++)
{
for (u8 slot = 0; slot < 30; slot++)
{
std::unique_ptr<PKX> pk5 = PKX::getPKM<Generation::FIVE>(
&data[boxOffset(box, slot)], PK5::BOX_LENGTH, true);
if (!crypted)
{
pk5->encrypt();
}
}
}
}
int Sav5::dexFormIndex(int species, int formct) const
{
if (formct < 1 || species < 0)
{
return -1; // invalid
}
if (game == Game::B2W2)
{
switch (species)
{
case 646:
return 72; // 3 Kyurem
case 647:
return 75; // 2 Keldeo
case 642:
return 77; // 2 Thundurus
case 641:
return 79; // 2 Tornadus
case 645:
return 81; // 2 Landorus
}
}
switch (species)
{
case 201:
return 0; // 28 Unown
case 386:
return 28; // 4 Deoxys
case 492:
return 32; // 2 Shaymin
case 487:
return 34; // 2 Giratina
case 479:
return 36; // 6 Rotom
case 422:
return 42; // 2 Shellos
case 423:
return 44; // 2 Gastrodon
case 412:
return 46; // 3 Burmy
case 413:
return 49; // 3 Wormadam
case 351:
return 52; // 4 Castform
case 421:
return 56; // 2 Cherrim
case 585:
return 58; // 4 Deerling
case 586:
return 62; // 4 Sawsbuck
case 648:
return 66; // 2 Meloetta
case 555:
return 68; // 2 Darmanitan
case 550:
return 70; // 2 Basculin
default:
return -1;
}
}
void Sav5::dex(const PKX& pk)
{
if (!(availableSpecies().count(pk.species()) > 0) || pk.egg())
{
return;
}
const int brSize = 0x54;
int bit = u16(pk.species()) - 1;
int gender = u8(pk.gender()) % 2; // genderless -> male
int shiny = pk.shiny() ? 1 : 0;
int shift = shiny * 2 + gender + 1;
int shiftoff = shiny * brSize * 2 + gender * brSize + brSize;
int ofs = PokeDex + 0x8 + (bit >> 3);
// Set the Species Owned Flag
data[ofs + brSize * 0] |= (1 << (bit % 8));
// Set the [Species/Gender/Shiny] Seen Flag
data[PokeDex + 0x8 + shiftoff + bit / 8] |= (1 << (bit & 7));
// Set the Display flag if none are set
bool displayed = false;
displayed |= (data[ofs + brSize * 5] & (1 << (bit & 7))) != 0;
displayed |= (data[ofs + brSize * 6] & (1 << (bit & 7))) != 0;
displayed |= (data[ofs + brSize * 7] & (1 << (bit & 7))) != 0;
displayed |= (data[ofs + brSize * 8] & (1 << (bit & 7))) != 0;
if (!displayed)
{ // offset is already biased by brSize, reuse shiftoff but for the display
// flags.
data[ofs + brSize * (shift + 4)] |= (1 << (bit & 7));
}
// Set the Language
if (bit < 493) // shifted by 1, Gen5 species do not have international language bits
{
int lang = u8(pk.language()) - 1;
if (lang > 5)
{
lang--; // 0-6 language vals
}
if (lang < 0)
{
lang = 1;
}
data[PokeDexLanguageFlags + ((bit * 7 + lang) >> 3)] |= (1 << ((bit * 7 + lang) & 7));
}
// Formes
int fc = PersonalBWB2W2::formCount(u16(pk.species()));
int f = dexFormIndex(u16(pk.species()), fc);
if (f < 0)
{
return;
}
int formLen = game == Game::BW ? 0x9 : 0xB;
int formDex = PokeDex + 0x8 + brSize * 9;
bit = f + pk.alternativeForm();
// Set Form Seen Flag
data[formDex + formLen * shiny + (bit >> 3)] |= (1 << (bit & 7));
// Set displayed Flag if necessary, check all flags
for (int i = 0; i < fc; i++)
{
bit = f + i;
if ((data[formDex + formLen * 2 + (bit >> 3)] & (1 << (bit & 7))) != 0)
{ // Nonshiny
return; // already set
}
if ((data[formDex + formLen * 3 + (bit >> 3)] & (1 << (bit & 7))) != 0)
{ // Shiny
return; // already set
}
}
bit = f + pk.alternativeForm();
data[formDex + formLen * (2 + shiny) + (bit >> 3)] |= (1 << (bit & 7));
}
int Sav5::dexSeen(void) const
{
int ret = 0;
for (const auto& spec : availableSpecies())
{
u16 i = u16(spec);
int bitIndex = (i - 1) & 7;
for (int j = 0; j < 4; j++) // All seen flags: gender & shinies
{
int ofs = PokeDex + (0x5C + (j * 0x54)) + ((i - 1) >> 3);
if ((data[ofs] >> bitIndex & 1) != 0)
{
ret++;
break;
}
}
}
return ret;
}
int Sav5::dexCaught(void) const
{
int ret = 0;
for (const auto& spec : availableSpecies())
{
u16 i = u16(spec);
int bitIndex = (i - 1) & 7;
int ofs = PokeDex + 0x8 + ((i - 1) >> 3);
if ((data[ofs] >> bitIndex & 1) != 0)
{
ret++;
}
}
return ret;
}
void Sav5::mysteryGift(const WCX& wc, int& pos)
{
if (wc.generation() == Generation::FIVE)
{
data[WondercardFlags + (wc.ID() / 8)] |= 0x1 << (wc.ID() & 7);
std::copy(wc.rawData(), wc.rawData() + PGF::length,
&data[WondercardData + pos * PGF::length]);
pos = (pos + 1) % 12;
}
}
std::string Sav5::boxName(u8 box) const
{
return StringUtils::transString45(
StringUtils::getString(data.get(), PCLayout + 0x28 * box + 4, 9, u'\uFFFF'));
}
void Sav5::boxName(u8 box, const std::string_view& name)
{
StringUtils::setString(data.get(), StringUtils::transString45(name),
PCLayout + 0x28 * box + 4, 9, u'\uFFFF', 0);
}
u8 Sav5::boxWallpaper(u8 box) const
{
return data[PCLayout + 0x3C4 + box];
}
void Sav5::boxWallpaper(u8 box, u8 v)
{
data[PCLayout + 0x3C4 + box] = v;
}
u8 Sav5::partyCount(void) const
{
return data[Party + 4];
}
void Sav5::partyCount(u8 v)
{
data[Party + 4] = v;
}
std::unique_ptr<PKX> Sav5::emptyPkm() const
{
return PKX::getPKM<Generation::FIVE>(nullptr, PK5::BOX_LENGTH);
}
int Sav5::currentGiftAmount(void) const
{
u8 t;
// 12 max wonder cards
for (t = 0; t < 12; t++)
{
bool empty = true;
for (u32 j = 0; j < PGF::length; j++)
{
if (data[WondercardData + t * PGF::length + j] != 0)
{
empty = false;
break;
}
}
if (empty)
{
break;
}
}
return t;
}
void Sav5::cryptMysteryGiftData()
{
u32 seed = LittleEndian::convertTo<u32>(&data[0x1D290]);
pksm::crypto::pkm::crypt<0xA90>(&data[WondercardFlags], seed);
}
std::unique_ptr<WCX> Sav5::mysteryGift(int pos) const
{
return std::make_unique<PGF>(&data[WondercardData + pos * PGF::length]);
}
void Sav5::item(const Item& item, Pouch pouch, u16 slot)
{
Item5 inject = static_cast<Item5>(item);
auto write = inject.bytes();
switch (pouch)
{
case Pouch::NormalItem:
std::copy(write.begin(), write.end(), &data[PouchHeldItem + slot * 4]);
break;
case Pouch::KeyItem:
std::copy(write.begin(), write.end(), &data[PouchKeyItem + slot * 4]);
break;
case Pouch::TM:
std::copy(write.begin(), write.end(), &data[PouchTMHM + slot * 4]);
break;
case Pouch::Medicine:
std::copy(write.begin(), write.end(), &data[PouchMedicine + slot * 4]);
break;
case Pouch::Berry:
std::copy(write.begin(), write.end(), &data[PouchBerry + slot * 4]);
break;
default:
return;
}
}
std::unique_ptr<Item> Sav5::item(Pouch pouch, u16 slot) const
{
switch (pouch)
{
case Pouch::NormalItem:
return std::make_unique<Item5>(&data[PouchHeldItem + slot * 4]);
case Pouch::KeyItem:
return std::make_unique<Item5>(&data[PouchKeyItem + slot * 4]);
case Pouch::TM:
return std::make_unique<Item5>(&data[PouchTMHM + slot * 4]);
case Pouch::Medicine:
return std::make_unique<Item5>(&data[PouchMedicine + slot * 4]);
case Pouch::Berry:
return std::make_unique<Item5>(&data[PouchBerry + slot * 4]);
default:
return nullptr;
}
}
SmallVector<std::pair<Sav::Pouch, int>, 15> Sav5::pouches() const
{
return {
std::pair{Pouch::NormalItem, 261 },
std::pair{Pouch::KeyItem, game == Game::BW ? 19 : 27},
std::pair{Pouch::TM, 101 },
std::pair{Pouch::Medicine, 47 },
std::pair{Pouch::Berry, 64 }
};
}
}
| 16,297
|
C++
|
.cpp
| 502
| 23.11753
| 98
| 0.492783
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,219
|
Sav8.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav8.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav8.hpp"
#include "pkx/PK8.hpp"
#include <algorithm>
namespace pksm
{
Sav8::Sav8(const std::shared_ptr<u8[]>& dt, size_t length) : Sav(dt, length)
{
pksm::crypto::swsh::applyXor(dt, length);
blocks = pksm::crypto::swsh::getBlockList(dt, length);
}
std::shared_ptr<pksm::crypto::swsh::SCBlock> Sav8::getBlock(u32 key) const
{
// binary search
auto found = std::lower_bound(blocks.begin(), blocks.end(), key,
[](const std::shared_ptr<pksm::crypto::swsh::SCBlock>& block, u32 key)
{ return block->key() < key; });
if ((*found)->key() != key)
{
return nullptr;
}
return *found;
}
std::unique_ptr<PKX> Sav8::emptyPkm() const
{
return PKX::getPKM<Generation::EIGHT>(nullptr, PK8::BOX_LENGTH);
}
void Sav8::trade(PKX& pk, const Date& date) const
{
if (pk.generation() == Generation::EIGHT)
{
if (pk.egg())
{
if (pk.otName() != otName() || pk.TID() != TID() || pk.SID() != SID() ||
pk.gender() != gender())
{
pk.metLocation(30002);
pk.metDate(date);
}
}
else
{
if (pk.otName() != otName() || pk.TID() != TID() || pk.SID() != SID() ||
pk.gender() != gender())
{
pk.currentHandler(PKXHandler::OT);
}
else
{
pk.currentHandler(PKXHandler::NonOT);
PK8& pk8 = static_cast<PK8&>(pk);
pk8.htName(otName());
pk8.currentFriendship(pk.baseFriendship());
pk8.htGender(gender());
pk8.htLanguage(language());
}
}
}
}
void Sav8::finishEditing()
{
if (!encrypted)
{
for (auto& block : blocks)
{
block->encrypt();
}
pksm::crypto::swsh::applyXor(data, length);
pksm::crypto::swsh::sign(data, length);
}
encrypted = true;
}
void Sav8::beginEditing()
{
if (encrypted)
{
pksm::crypto::swsh::applyXor(data, length);
}
encrypted = false;
// I could decrypt every block here, but why not just let them be done on the fly via the
// functions that need them?
}
}
| 3,832
|
C++
|
.cpp
| 107
| 26.953271
| 97
| 0.55436
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,220
|
Item.cpp
|
FlagBrew_PKSM-Core/source/sav/Item.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Item.hpp"
namespace pksm
{
Item::operator Item1() const
{
Item1 ret;
ret.id(id());
ret.count(count());
return ret;
}
Item::operator Item2() const
{
Item2 ret;
ret.id(id());
ret.count(count());
return ret;
}
Item::operator Item3() const
{
Item3 ret;
ret.id(id());
ret.count(count());
if (generation() == Generation::THREE)
{
ret.securityKey(static_cast<const Item3*>(this)->securityKey());
}
return ret;
}
Item::operator Item4() const
{
Item4 ret;
ret.id(id());
ret.count(count());
return ret;
}
Item::operator Item5() const
{
Item5 ret;
ret.id(id());
ret.count(count());
return ret;
}
Item::operator Item6() const
{
Item6 ret;
ret.id(id());
ret.count(count());
return ret;
}
Item::operator Item7() const
{
Item7 ret;
ret.id(std::min<u16>(id(), 0x3FF));
ret.count(std::min<u16>(count(), 0x3FF));
ret.freeSpaceIndex(0);
ret.newFlag(false);
ret.reserved(false);
return ret;
}
Item::operator Item7b() const
{
Item7b ret;
ret.id(std::min<u16>(id(), 0x7FFF));
ret.count(std::min<u16>(count(), 0x7FFF));
ret.newFlag(false);
ret.reserved(false);
return ret;
}
Item::operator Item8() const
{
Item8 ret;
ret.id(std::min<u16>(id(), 0x7FFF));
ret.count(std::min<u16>(count(), 0x7FFF));
ret.newFlag(false);
ret.reserved(false);
return ret;
}
Item7::operator Item7b() const
{
Item7b ret;
ret.id(id()); // Capped at 0x3FF, so no need to cap it at 0x7FFF
ret.count(count());
ret.newFlag(newFlag());
ret.reserved(reserved());
return ret;
}
Item7::operator Item8() const
{
Item8 ret;
ret.id(id()); // Capped at 0x3FF, so no need to cap it at 0x7FFF
ret.count(count());
ret.newFlag(newFlag());
ret.reserved(reserved());
return ret;
}
Item7b::operator Item7() const
{
Item7 ret;
ret.id(std::min<u16>(id(), 0x3FF));
ret.count(std::min<u16>(count(), 0x3FF));
ret.freeSpaceIndex(0);
ret.newFlag(newFlag());
ret.reserved(reserved());
return ret;
}
Item7b::operator Item8() const
{
Item8 ret;
ret.id(id());
ret.count(count());
ret.newFlag(newFlag());
ret.reserved(reserved());
return ret;
}
Item8::operator Item7() const
{
Item7 ret;
ret.id(std::min<u16>(id(), 0x3FF));
ret.count(std::min<u16>(count(), 0x3FF));
ret.freeSpaceIndex(0);
ret.newFlag(newFlag());
ret.reserved(reserved());
return ret;
}
Item8::operator Item7b() const
{
Item7b ret;
ret.id(id());
ret.count(count());
ret.newFlag(newFlag());
ret.reserved(reserved());
return ret;
}
}
| 4,483
|
C++
|
.cpp
| 159
| 21.509434
| 76
| 0.578459
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,221
|
SavUSUM.cpp
|
FlagBrew_PKSM-Core/source/sav/SavUSUM.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavUSUM.hpp"
#include "memecrypto.h"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include <algorithm>
namespace pksm
{
SavUSUM::SavUSUM(const std::shared_ptr<u8[]>& dt) : Sav7(dt, 0x6CC00)
{
game = Game::USUM;
TrainerCard = 0x1400;
Misc = 0x4400;
PlayTime = 0x41000;
LastViewedBox = 0x51E3;
Box = 0x5200;
Party = 0x1600;
PokeDex = 0x2C00;
PokeDexLanguageFlags = 0x3150;
WondercardFlags = 0x66200;
WondercardData = 0x66300;
PCLayout = 0x4C00;
PouchHeldItem = 0x0;
PouchKeyItem = 0x6AC;
PouchTMHM = 0x9C4;
PouchMedicine = 0xB74;
PouchBerry = 0xC64;
PouchZCrystals = 0xD70;
BattleItems = 0xDFC;
}
void SavUSUM::resign(void)
{
static constexpr u8 blockCount = 39;
static constexpr u32 csoff = 0x6CA1A;
for (u8 i = 0; i < blockCount; i++)
{
// Clear memecrypto data
if (LittleEndian::convertTo<u16>(&data[csoff + i * 8 - 2]) == 36)
{
std::fill_n(&data[chkofs[i] + 0x100], 0x80, 0);
}
LittleEndian::convertFrom<u16>(
&data[csoff + i * 8], pksm::crypto::crc16({&data[chkofs[i]], chklen[i]}));
}
const u32 checksumTableOffset = 0x6CA00;
const u32 checksumTableLength = 0x150;
const u32 memecryptoOffset = 0x6C100;
auto hash = crypto::sha256({&data[checksumTableOffset], checksumTableLength});
u8 decryptedSignature[0x80];
reverseCrypt(&data[memecryptoOffset], decryptedSignature);
std::copy(hash.begin(), hash.end(), decryptedSignature);
memecrypto_sign(decryptedSignature, &data[memecryptoOffset], 0x80);
}
int SavUSUM::dexFormIndex(int species, int formct, int start) const
{
int formindex = start;
int f = 0;
for (u8 i = 0; i < 246; i += 2)
{
if (formtable[i] == species)
{
break;
}
f = formtable[i + 1];
formindex += f - 1;
}
return f > formct ? -1 : formindex;
}
int SavUSUM::dexFormCount(int species) const
{
for (u8 i = 0; i < 246; i += 2)
{
if (formtable[i] == species)
{
return formtable[i + 1];
}
}
return 0;
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavUSUM::validItems() const
{
static constexpr std::array NormalItem = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112, 116, 117, 118, 119, 135, 136, 137, 213,
214, 215, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265,
266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282,
283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299,
300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316,
317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 492, 493, 494, 495, 496, 497,
498, 499, 534, 535, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549,
550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 571, 572,
573, 576, 577, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 639, 640, 644,
646, 647, 648, 649, 650, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667,
668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684,
685, 699, 704, 710, 711, 715, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762,
763, 764, 767, 768, 769, 770, 795, 796, 844, 846, 849, 851, 853, 854, 855, 856, 879,
880, 881, 882, 883, 884, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915,
916, 917, 918, 919, 920};
static constexpr std::array KeyItem = {216, 440, 465, 466, 628, 629, 631, 632, 638, 705,
706, 765, 773, 797, 841, 842, 843, 845, 847, 850, 857, 858, 860, 933, 934, 935, 936,
937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 618, 619, 620, 690,
691, 692, 693, 694};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 65, 66, 67, 134, 504, 565, 566, 567, 568, 569, 570, 591, 645, 708, 709,
852};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212, 686, 687, 688};
static constexpr std::array ZCrystals = {807, 808, 809, 810, 811, 812, 813, 814, 815, 816,
817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833,
834, 835, 927, 928, 929, 930, 931, 932};
static constexpr std::array RotomPower = {
949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} },
std::pair{Pouch::ZCrystals, std::span{ZCrystals} },
std::pair{Pouch::RotomPower, std::span{RotomPower}}
};
}
}
| 8,404
|
C++
|
.cpp
| 160
| 43.64375
| 100
| 0.552181
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,222
|
SavB2W2.cpp
|
FlagBrew_PKSM-Core/source/sav/SavB2W2.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavB2W2.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include <algorithm>
namespace pksm
{
SavB2W2::SavB2W2(const std::shared_ptr<u8[]>& dt) : Sav5(dt, 0x80000)
{
game = Game::B2W2;
PCLayout = 0x0;
Trainer1 = 0x19400;
Trainer2 = 0x21100;
BattleSubway = 0x21B00;
Party = 0x18E00;
PokeDex = 0x21400;
PokeDexLanguageFlags = 0x21728;
WondercardFlags = 0x1C800;
WondercardData = 0x1C900;
PouchHeldItem = 0x18400;
PouchKeyItem = 0x188D8;
PouchTMHM = 0x18A24;
PouchMedicine = 0x18BD8;
PouchBerry = 0x18C98;
Box = 0x400;
}
void SavB2W2::resign(void)
{
const u8 blockCount = 74;
for (u8 i = 0; i < blockCount; i++)
{
u16 cs = pksm::crypto::ccitt16({&data[blockOfs[i]], lengths[i]});
LittleEndian::convertFrom<u16>(&data[chkMirror[i]], cs);
LittleEndian::convertFrom<u16>(&data[chkofs[i]], cs);
}
// Memories
// Note: Block 1 and its mirror are encrypted with pokecrypto. The commented lines show how
// they would be re-encrypted
// Block 1
{
static constexpr u32 offset = 0x7E000;
static constexpr u32 size_to_checksum = 0x368;
static constexpr u32 header_size = 0xC;
static constexpr u32 crc_offset_from_start = 0x8;
// u32 seed = LittleEndian::convertTo<u32>(data.get() + offset + size_to_checksum +
// header_size - 4);
// pksm::crypto::pkm::crypt<size_to_checksum - 4>(data.get() + offset
// + header_size, seed);
u16 crc = pksm::crypto::ccitt16({data.get() + offset + header_size, size_to_checksum});
LittleEndian::convertFrom<u16>(data.get() + offset + crc_offset_from_start, crc);
}
// Block 1 mirror
{
static constexpr u32 offset = 0x7E400;
static constexpr u32 size_to_checksum = 0x368;
static constexpr u32 header_size = 0xC;
static constexpr u32 crc_offset_from_start = 0x8;
// u32 seed = LittleEndian::convertTo<u32>(data.get() + offset + size_to_checksum +
// header_size - 4);
// pksm::crypto::pkm::crypt<size_to_checksum - 4>(data.get() + offset
// + header_size, seed);
u16 crc = pksm::crypto::ccitt16({data.get() + offset + header_size, size_to_checksum});
LittleEndian::convertFrom<u16>(data.get() + offset + crc_offset_from_start, crc);
}
// Block 2
{
static constexpr u32 offset = 0x7E800;
static constexpr u32 size_to_checksum = 0x214;
static constexpr u32 header_size = 0xC;
static constexpr u32 crc_offset_from_start = 0x8;
u16 crc = pksm::crypto::ccitt16({data.get() + offset + header_size, size_to_checksum});
LittleEndian::convertFrom<u16>(data.get() + offset + crc_offset_from_start, crc);
}
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavB2W2::validItems() const
{
static constexpr std::array NormalItem = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 116, 117, 118,
119, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 213, 214,
215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265,
266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282,
283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299,
300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316,
317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 492, 493, 494, 495, 496, 497,
498, 499, 500, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550,
551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 571, 572, 573,
575, 576, 577, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590};
static constexpr std::array KeyItem = {437, 442, 447, 450, 453, 458, 465, 466, 471, 504,
578, 616, 617, 621, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 618, 619, 620, 420,
421, 422, 423, 424, 425};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 134, 504, 565, 566, 567, 568, 569, 570, 591};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} }
};
}
}
| 7,998
|
C++
|
.cpp
| 141
| 47.808511
| 100
| 0.564054
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,223
|
Sav.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav.hpp"
#include "pkx/PB7.hpp"
#include "pkx/PK1.hpp"
#include "pkx/PK2.hpp"
#include "pkx/PK3.hpp"
#include "pkx/PK4.hpp"
#include "pkx/PK5.hpp"
#include "pkx/PK6.hpp"
#include "pkx/PK7.hpp"
#include "pkx/PK8.hpp"
#include "pkx/PKX.hpp"
#include "sav/Sav1.hpp"
#include "sav/Sav2.hpp"
#include "sav/SavB2W2.hpp"
#include "sav/SavBW.hpp"
#include "sav/SavDP.hpp"
#include "sav/SavE.hpp"
#include "sav/SavFRLG.hpp"
#include "sav/SavHGSS.hpp"
#include "sav/SavLGPE.hpp"
#include "sav/SavORAS.hpp"
#include "sav/SavPT.hpp"
#include "sav/SavRS.hpp"
#include "sav/SavSUMO.hpp"
#include "sav/SavSWSH.hpp"
#include "sav/SavUSUM.hpp"
#include "sav/SavXY.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include "utils/ValueConverter.hpp"
namespace pksm
{
std::unique_ptr<Sav> Sav::getSave(const std::shared_ptr<u8[]>& dt, size_t length)
{
std::unique_ptr<Sav> ret = nullptr;
switch (length)
{
case 0x6CC00:
ret = std::make_unique<SavUSUM>(dt);
break;
case 0x6BE00:
ret = std::make_unique<SavSUMO>(dt);
break;
case 0x76000:
ret = std::make_unique<SavORAS>(dt);
break;
case 0x65600:
ret = std::make_unique<SavXY>(dt);
break;
case 0x80000:
case 0x8007A:
ret = checkDSType(dt);
break;
case 0x20000:
case 0x20010:
ret = checkGBAType(dt);
break;
case 0x8000:
case 0x10000:
// Gen II VC saves
case 0x8010:
case 0x10010:
// Emulator standard saves
case 0x8030:
case 0x10030:
ret = checkGBType(dt, length);
break;
case 0xB8800:
case 0x100000:
ret = std::make_unique<SavLGPE>(dt, length);
break;
case SavSWSH::SIZE_G8SWSH:
case SavSWSH::SIZE_G8SWSH_1:
case SavSWSH::SIZE_G8SWSH_2:
case SavSWSH::SIZE_G8SWSH_2B:
case SavSWSH::SIZE_G8SWSH_3:
case SavSWSH::SIZE_G8SWSH_3A:
case SavSWSH::SIZE_G8SWSH_3B:
case SavSWSH::SIZE_G8SWSH_3C:
ret = std::make_unique<SavSWSH>(dt, length);
break;
default:
ret = std::unique_ptr<Sav>(nullptr);
break;
}
if (ret)
{
ret->fullLength = length;
}
return ret;
}
std::unique_ptr<Sav> Sav::checkGBType(const std::shared_ptr<u8[]>& dt, size_t length)
{
std::tuple<GameVersion, Language, bool> versionAndLanguage = Sav2::getVersion(dt);
if (get<2>(versionAndLanguage))
{
return std::make_unique<Sav2>(dt, length, versionAndLanguage);
}
switch (Sav1::getVersion(dt))
{
case Game::RGB:
return std::make_unique<Sav1>(dt, length);
case Game::Y:
return std::make_unique<Sav1>(dt, length); // in case anyone wants to
default:
return std::unique_ptr<Sav>(nullptr);
}
}
std::unique_ptr<Sav> Sav::checkGBAType(const std::shared_ptr<u8[]>& dt)
{
switch (Sav3::getVersion(dt))
{
case Game::RS:
return std::make_unique<SavRS>(dt);
case Game::E:
return std::make_unique<SavE>(dt);
case Game::FRLG:
return std::make_unique<SavFRLG>(dt);
default:
return std::unique_ptr<Sav>(nullptr);
}
}
bool Sav::isValidDSSave(const std::shared_ptr<u8[]>& dt)
{
u16 chk1 = LittleEndian::convertTo<u16>(&dt[0x24000 - 0x100 + 0x8C + 0xE]);
u16 actual1 = pksm::crypto::ccitt16({&dt[0x24000 - 0x100], 0x8C});
if (chk1 == actual1)
{
return true;
}
u16 chk2 = LittleEndian::convertTo<u16>(&dt[0x26000 - 0x100 + 0x94 + 0xE]);
u16 actual2 = pksm::crypto::ccitt16({&dt[0x26000 - 0x100], 0x94});
if (chk2 == actual2)
{
return true;
}
// Check for block identifiers
static constexpr size_t DP_OFFSET = 0xC100;
static constexpr size_t PT_OFFSET = 0xCF2C;
static constexpr size_t HGSS_OFFSET = 0xF628;
if (validSequence(dt, DP_OFFSET))
{
return true;
}
if (validSequence(dt, PT_OFFSET))
{
return true;
}
if (validSequence(dt, HGSS_OFFSET))
{
return true;
}
// Check the other save
if (validSequence(dt, DP_OFFSET + 0x40000))
{
return true;
}
if (validSequence(dt, PT_OFFSET + 0x40000))
{
return true;
}
if (validSequence(dt, HGSS_OFFSET + 0x40000))
{
return true;
}
return false;
}
std::unique_ptr<Sav> Sav::checkDSType(const std::shared_ptr<u8[]>& dt)
{
// Check for block identifiers
static constexpr size_t DP_OFFSET = 0xC100;
static constexpr size_t PT_OFFSET = 0xCF2C;
static constexpr size_t HGSS_OFFSET = 0xF628;
if (validSequence(dt, DP_OFFSET))
{
return std::make_unique<SavDP>(dt);
}
if (validSequence(dt, PT_OFFSET))
{
return std::make_unique<SavPT>(dt);
}
if (validSequence(dt, HGSS_OFFSET))
{
return std::make_unique<SavHGSS>(dt);
}
// Check the other save
if (validSequence(dt, DP_OFFSET + 0x40000))
{
return std::make_unique<SavDP>(dt);
}
if (validSequence(dt, PT_OFFSET + 0x40000))
{
return std::make_unique<SavPT>(dt);
}
if (validSequence(dt, HGSS_OFFSET + 0x40000))
{
return std::make_unique<SavHGSS>(dt);
}
// Check for BW/B2W2 checksums
u16 chk1 = LittleEndian::convertTo<u16>(&dt[0x24000 - 0x100 + 0x8C + 0xE]);
u16 actual1 = pksm::crypto::ccitt16({&dt[0x24000 - 0x100], 0x8C});
if (chk1 == actual1)
{
return std::make_unique<SavBW>(dt);
}
u16 chk2 = LittleEndian::convertTo<u16>(&dt[0x26000 - 0x100 + 0x94 + 0xE]);
u16 actual2 = pksm::crypto::ccitt16({&dt[0x26000 - 0x100], 0x94});
if (chk2 == actual2)
{
return std::make_unique<SavB2W2>(dt);
}
return nullptr;
}
bool Sav::validSequence(const std::shared_ptr<u8[]>& dt, size_t offset)
{
static constexpr u32 DATE_INTERNATIONAL = 0x20060623;
static constexpr u32 DATE_KOREAN = 0x20070903;
if (LittleEndian::convertTo<u32>(&dt[offset - 0xC]) != (offset & 0xFFFF))
{
return false;
}
return LittleEndian::convertTo<u32>(&dt[offset - 0x8]) == DATE_INTERNATIONAL ||
LittleEndian::convertTo<u32>(&dt[offset - 0x8]) == DATE_KOREAN;
}
std::unique_ptr<PKX> Sav::transfer(const PKX& pk)
{
switch (generation())
{
case Generation::ONE:
return pk.convertToG1(*this);
case Generation::TWO:
return pk.convertToG2(*this);
case Generation::THREE:
return pk.convertToG3(*this);
case Generation::FOUR:
return pk.convertToG4(*this);
case Generation::FIVE:
return pk.convertToG5(*this);
case Generation::SIX:
return pk.convertToG6(*this);
case Generation::SEVEN:
return pk.convertToG7(*this);
case Generation::LGPE:
return pk.convertToLGPE(*this);
case Generation::EIGHT:
return pk.convertToG8(*this);
case Generation::UNUSED:
return nullptr;
}
return nullptr;
}
void Sav::fixParty()
{
// Poor man's bubble sort-like thing
int numPkm = 6;
for (int i = 5; i > 0; i--)
{
auto checkPKM = pkm(i);
if (checkPKM->species() == Species::None)
{
numPkm--;
continue;
}
auto prevPKM = pkm(i - 1);
if (checkPKM->species() != Species::None && prevPKM->species() == Species::None)
{
pkm(*checkPKM, i - 1);
pkm(*prevPKM, i);
numPkm = 6;
i = 6; // reset loop
}
}
partyCount(numPkm);
}
u32 Sav::displayTID() const
{
switch (generation())
{
case Generation::ONE:
case Generation::TWO:
case Generation::THREE:
case Generation::FOUR:
case Generation::FIVE:
case Generation::SIX:
return TID();
case Generation::SEVEN:
case Generation::LGPE:
case Generation::EIGHT:
return u32(SID() << 16 | TID()) % 1000000;
case Generation::UNUSED:
return 0;
}
return 0;
}
u32 Sav::displaySID() const
{
switch (generation())
{
case Generation::THREE:
case Generation::FOUR:
case Generation::FIVE:
case Generation::SIX:
return SID();
case Generation::SEVEN:
case Generation::LGPE:
case Generation::EIGHT:
return u32(SID() << 16 | TID()) / 1000000;
case Generation::UNUSED:
case Generation::ONE:
case Generation::TWO:
return 0;
}
return 0;
}
Sav::BadTransferReason Sav::invalidTransferReason(const PKX& pk) const
{
bool moveBad = false;
for (int i = 0; i < 4; i++)
{
if (availableMoves().count(pk.move(i)) == 0)
{
moveBad = true;
break;
}
if (availableMoves().count(pk.relearnMove(i)) == 0)
{
moveBad = true;
break;
}
}
if (moveBad)
{
return BadTransferReason::MOVE;
}
if (availableSpecies().count(pk.species()) == 0)
{
return BadTransferReason::SPECIES;
}
if (pk.alternativeForm() >= formCount(pk.species()) &&
!((pk.species() == Species::Scatterbug || pk.species() == Species::Spewpa) &&
pk.alternativeForm() < formCount(Species::Vivillon)) &&
!((pk.species() == Species::Mothim) &&
pk.alternativeForm() < formCount(Species::Burmy)))
{
return BadTransferReason::FORM;
}
if (availableAbilities().count(pk.ability()) == 0)
{
if (generation() > Generation::TWO && pk.generation() > Generation::TWO)
{
return BadTransferReason::ABILITY;
}
}
if (generation() <= Generation::TWO)
{
const int heldItem2 = pk.generation() == Generation::ONE
? (int)static_cast<const PK1&>(pk).heldItem2()
: (pk.generation() == Generation::TWO
? (int)static_cast<const PK2&>(pk).heldItem2()
: (int)ItemConverter::nationalToG2(pk.heldItem()));
// Crystal only adds key items
if (VersionTables::availableItems(GameVersion::GD).count(heldItem2) == 0 ||
(heldItem2 == 0 && pk.heldItem() != 0))
{
return BadTransferReason::ITEM;
}
}
else if (generation() == Generation::THREE)
{
const int heldItem3 = pk.generation() == Generation::THREE
? (int)static_cast<const PK3&>(pk).heldItem3()
: (int)ItemConverter::nationalToG3(pk.heldItem());
if (availableItems().count(heldItem3) == 0 || (heldItem3 == 0 && pk.heldItem() != 0))
{
return BadTransferReason::ITEM;
}
}
else if (availableItems().count((int)pk.heldItem()) == 0 ||
(pk.generation() == Generation::THREE &&
pk.heldItem() == ItemConverter::ITEM_NOT_CONVERTIBLE))
{
return BadTransferReason::ITEM;
}
if (availableBalls().count(pk.ball()) == 0)
{
if (generation() > Generation::TWO)
{
return BadTransferReason::BALL;
}
}
return BadTransferReason::OKAY;
}
}
| 14,326
|
C++
|
.cpp
| 418
| 23.787081
| 97
| 0.526505
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,224
|
SavPT.cpp
|
FlagBrew_PKSM-Core/source/sav/SavPT.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavPT.hpp"
#include "wcx/PGT.hpp"
namespace pksm
{
SavPT::SavPT(const std::shared_ptr<u8[]>& dt) : Sav4(dt, 0x80000)
{
game = Game::Pt;
GBOOffset = 0xCF18;
SBOOffset = 0x1F0FC;
GBO();
SBO();
Trainer1 = 0x68 + gbo;
Party = 0xA0 + gbo;
PokeDex = 0x1328 + gbo;
WondercardFlags = 0xB4C0 + gbo;
WondercardData = 0xB5C0 + gbo;
PouchHeldItem = 0x630 + gbo;
PouchKeyItem = 0x8C4 + gbo;
PouchTMHM = 0x98C + gbo;
MailItems = 0xB1C + gbo;
PouchMedicine = 0xB4C + gbo;
PouchBerry = 0xBEC + gbo;
PouchBalls = 0xCEC + gbo;
BattleItems = 0xD28 + gbo;
PalPark = 0xC7F0 + gbo;
Box = 0xCF30 + sbo;
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavPT::validItems() const
{
static constexpr std::array NormalItem = {68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 135, 136, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,
233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249,
250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266,
267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283,
284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300,
301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317,
318, 319, 320, 321, 322, 323, 324, 325, 326, 327};
static constexpr std::array KeyItem = {428, 429, 430, 431, 432, 433, 434, 435, 436, 437,
438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454,
455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427};
static constexpr std::array Mail = {
137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212};
static constexpr std::array Ball = {1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
static constexpr std::array Battle = {55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Mail, std::span{Mail} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} },
std::pair{Pouch::Ball, std::span{Ball} },
std::pair{Pouch::Battle, std::span{Battle} }
};
}
SmallVector<std::pair<Sav::Pouch, int>, 15> SavPT::pouches(void) const
{
return {
std::pair{Pouch::NormalItem, 162},
std::pair{Pouch::KeyItem, 40 },
std::pair{Pouch::TM, 100},
std::pair{Pouch::Mail, 12 },
std::pair{Pouch::Medicine, 38 },
std::pair{Pouch::Berry, 64 },
std::pair{Pouch::Ball, 15 },
std::pair{Pouch::Battle, 13 }
};
}
}
| 6,073
|
C++
|
.cpp
| 111
| 46.279279
| 100
| 0.554492
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,225
|
SavHGSS.cpp
|
FlagBrew_PKSM-Core/source/sav/SavHGSS.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavHGSS.hpp"
#include "wcx/PGT.hpp"
namespace pksm
{
SavHGSS::SavHGSS(const std::shared_ptr<u8[]>& dt) : Sav4(dt, 0x80000)
{
game = Game::HGSS;
GBOOffset = 0xF614;
SBOOffset = 0x219FC;
GBO();
SBO();
Trainer1 = 0x64 + gbo;
Party = 0x98 + gbo;
PokeDex = 0x12B8 + gbo;
WondercardFlags = 0x9D3C + gbo;
WondercardData = 0x9E3C + gbo;
PouchHeldItem = 0x644 + gbo;
PouchKeyItem = 0x8D8 + gbo;
PouchTMHM = 0x9A0 + gbo;
MailItems = 0xB34 + gbo;
PouchMedicine = 0xB64 + gbo;
PouchBerry = 0xC04 + gbo;
PouchBalls = 0xD04 + gbo;
BattleItems = 0xD64 + gbo;
PalPark = 0xB3C0 + gbo;
Box = 0xF700 + sbo;
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavHGSS::validItems() const
{
static constexpr std::array NormalItem = {68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 135, 136, 213, 214, 215,
216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,
233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249,
250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266,
267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283,
284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300,
301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317,
318, 319, 320, 321, 322, 323, 324, 325, 326, 327};
static constexpr std::array KeyItem = {434, 435, 437, 444, 445, 446, 447, 450, 456, 464,
465, 466, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482,
483, 484, 501, 502, 503, 504, 532, 533, 534, 535, 536};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427};
static constexpr std::array Mail = {
137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212};
static constexpr std::array Ball = {1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 492,
493, 494, 495, 496, 497, 498, 499, 500};
static constexpr std::array Battle = {55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Mail, std::span{Mail} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} },
std::pair{Pouch::Ball, std::span{Ball} },
std::pair{Pouch::Battle, std::span{Battle} }
};
}
SmallVector<std::pair<Sav::Pouch, int>, 15> SavHGSS::pouches(void) const
{
return {
std::pair{Pouch::NormalItem, 162},
std::pair{Pouch::KeyItem, 38 },
std::pair{Pouch::TM, 100},
std::pair{Pouch::Mail, 12 },
std::pair{Pouch::Medicine, 38 },
std::pair{Pouch::Berry, 64 },
std::pair{Pouch::Ball, 24 },
std::pair{Pouch::Battle, 13 }
};
}
}
| 6,125
|
C++
|
.cpp
| 112
| 46.25
| 100
| 0.555278
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,226
|
Sav4.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav4.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav4.hpp"
#include "pkx/PK4.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include "utils/i18n.hpp"
#include "utils/utils.hpp"
#include "wcx/PGT.hpp"
namespace pksm
{
Sav4::CountType Sav4::compareCounters(u32 c1, u32 c2)
{
if (c1 == 0xFFFFFFFF && c2 != 0xFFFFFFFE)
{
return CountType::SECOND;
}
else if (c2 == 0xFFFFFFFF && c1 != 0xFFFFFFFE)
{
return CountType::FIRST;
}
else if (c1 > c2)
{
return CountType::FIRST;
}
else if (c2 > c1)
{
return CountType::SECOND;
}
else
{
return CountType::SAME;
}
}
void Sav4::GBO(void)
{
int ofs = GBOOffset;
u32 major1 = LittleEndian::convertTo<u32>(&data[ofs]),
major2 = LittleEndian::convertTo<u32>(&data[ofs + 0x40000]),
minor1 = LittleEndian::convertTo<u32>(&data[ofs + 4]),
minor2 = LittleEndian::convertTo<u32>(&data[ofs + 0x40004]);
CountType cmp = compareCounters(major1, major2);
if (cmp == CountType::FIRST)
{
gbo = 0;
}
else if (cmp == CountType::SECOND)
{
gbo = 0x40000;
}
else
{
cmp = compareCounters(minor1, minor2);
if (cmp == CountType::SECOND)
{
gbo = 0x40000;
}
else
{
gbo = 0;
}
}
}
void Sav4::SBO(void)
{
int ofs = SBOOffset;
u32 major1 = LittleEndian::convertTo<u32>(&data[ofs]),
major2 = LittleEndian::convertTo<u32>(&data[ofs + 0x40000]),
minor1 = LittleEndian::convertTo<u32>(&data[ofs + 4]),
minor2 = LittleEndian::convertTo<u32>(&data[ofs + 0x40004]);
CountType cmp = compareCounters(major1, major2);
if (cmp == CountType::FIRST)
{
sbo = 0;
}
else if (cmp == CountType::SECOND)
{
sbo = 0x40000;
}
else
{
cmp = compareCounters(minor1, minor2);
if (cmp == CountType::SECOND)
{
sbo = 0x40000;
}
else
{
sbo = 0;
}
}
}
void Sav4::resign(void)
{
u16 cs;
// start, end, chkoffset
int general[3] = {0x0,
game == Game::DP ? 0xC0EC
: game == Game::Pt ? 0xCF18
: 0xF618,
game == Game::DP ? 0xC0FE
: game == Game::Pt ? 0xCF2A
: 0xF626};
int storage[3] = {game == Game::DP ? 0xC100
: game == Game::Pt ? 0xCF2C
: 0xF700,
game == Game::DP ? 0x1E2CC
: game == Game::Pt ? 0x1F0FC
: 0x21A00,
game == Game::DP ? 0x1E2DE
: game == Game::Pt ? 0x1F10E
: 0x21A0E};
cs = pksm::crypto::ccitt16({&data[gbo + general[0]], (size_t)(general[1] - general[0])});
LittleEndian::convertFrom<u16>(&data[gbo + general[2]], cs);
cs = pksm::crypto::ccitt16({&data[sbo + storage[0]], (size_t)(storage[1] - storage[0])});
LittleEndian::convertFrom<u16>(&data[sbo + storage[2]], cs);
}
u16 Sav4::TID(void) const
{
return LittleEndian::convertTo<u16>(&data[Trainer1 + 0x10]);
}
void Sav4::TID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[Trainer1 + 0x10], v);
}
u16 Sav4::SID(void) const
{
return LittleEndian::convertTo<u16>(&data[Trainer1 + 0x12]);
}
void Sav4::SID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[Trainer1 + 0x12], v);
}
GameVersion Sav4::version(void) const
{
return game == Game::DP ? GameVersion::D
: game == Game::Pt ? GameVersion::Pt
: GameVersion::HG;
}
void Sav4::version(GameVersion) {}
Gender Sav4::gender(void) const
{
return Gender{data[Trainer1 + 0x18]};
}
void Sav4::gender(Gender v)
{
data[Trainer1 + 0x18] = u8(v);
}
Language Sav4::language(void) const
{
return Language(data[Trainer1 + 0x19]);
}
void Sav4::language(Language v)
{
data[Trainer1 + 0x19] = u8(v);
}
std::string Sav4::otName(void) const
{
return StringUtils::transString45(StringUtils::getString4(data.get(), Trainer1, 8));
}
void Sav4::otName(const std::string_view& v)
{
StringUtils::setString4(data.get(), StringUtils::transString45(v), Trainer1, 8);
}
u32 Sav4::money(void) const
{
return LittleEndian::convertTo<u32>(&data[Trainer1 + 0x14]);
}
void Sav4::money(u32 v)
{
LittleEndian::convertFrom<u32>(&data[Trainer1 + 0x14], v);
}
u32 Sav4::BP(void) const
{
return LittleEndian::convertTo<u16>(&data[Trainer1 + 0x20]);
} // Returns Coins @ Game Corner
void Sav4::BP(u32 v)
{
LittleEndian::convertFrom<u32>(&data[Trainer1 + 0x20], v);
}
u8 Sav4::badges(void) const
{
u8 badgeBits = data[Trainer1 + 0x1A];
u8 ret = 0;
for (size_t i = 0; i < sizeof(badgeBits) * 8; i++)
{
ret += (badgeBits & (1 << i)) ? 1 : 0;
}
if (game == Game::HGSS)
{
badgeBits = data[Trainer1 + 0x1F];
for (size_t i = 0; i < sizeof(badgeBits) * 8; i++)
{
ret += (badgeBits & (1 << i)) ? 1 : 0;
}
}
return ret;
}
u16 Sav4::playedHours(void) const
{
return LittleEndian::convertTo<u16>(&data[Trainer1 + 0x22]);
}
void Sav4::playedHours(u16 v)
{
LittleEndian::convertFrom<u16>(&data[Trainer1 + 0x22], v);
}
u8 Sav4::playedMinutes(void) const
{
return data[Trainer1 + 0x24];
}
void Sav4::playedMinutes(u8 v)
{
data[Trainer1 + 0x24] = v;
}
u8 Sav4::playedSeconds(void) const
{
return data[Trainer1 + 0x25];
}
void Sav4::playedSeconds(u8 v)
{
data[Trainer1 + 0x25] = v;
}
u8 Sav4::currentBox(void) const
{
int ofs = game == Game::HGSS ? boxOffset(maxBoxes(), 0) : Box - 4;
return data[ofs];
}
void Sav4::currentBox(u8 v)
{
int ofs = game == Game::HGSS ? boxOffset(maxBoxes(), 0) : Box - 4;
data[ofs] = v;
}
u32 Sav4::boxOffset(u8 box, u8 slot) const
{
return Box + PK4::BOX_LENGTH * box * 30 + (game == Game::HGSS ? box * 0x10 : 0) +
slot * PK4::BOX_LENGTH;
}
u32 Sav4::partyOffset(u8 slot) const
{
return Party + slot * PK4::PARTY_LENGTH;
}
std::unique_ptr<PKX> Sav4::pkm(u8 slot) const
{
return PKX::getPKM<Generation::FOUR>(&data[partyOffset(slot)], PK4::PARTY_LENGTH);
}
void Sav4::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::FOUR)
{
auto pk4 = pk.partyClone();
pk4->encrypt();
std::ranges::copy(pk4->rawData(), &data[partyOffset(slot)]);
}
}
std::unique_ptr<PKX> Sav4::pkm(u8 box, u8 slot) const
{
return PKX::getPKM<Generation::FOUR>(&data[boxOffset(box, slot)], PK4::BOX_LENGTH);
}
void Sav4::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (pk.generation() == Generation::FOUR)
{
auto pkm = pk.clone();
if (applyTrade)
{
trade(*pkm);
}
std::ranges::copy(
pkm->rawData().subspan(0, PK4::BOX_LENGTH), &data[boxOffset(box, slot)]);
}
}
void Sav4::trade(PKX& pk, const Date& date) const
{
if (pk.generation() == Generation::FOUR && pk.egg() &&
(otName() != pk.otName() || TID() != pk.TID() || SID() != pk.SID() ||
gender() != pk.otGender()))
{
pk.metLocation(2002);
pk.metDate(date);
}
}
void Sav4::cryptBoxData(bool crypted)
{
for (u8 box = 0; box < maxBoxes(); box++)
{
for (u8 slot = 0; slot < 30; slot++)
{
std::unique_ptr<PKX> pk4 = PKX::getPKM<Generation::FOUR>(
&data[boxOffset(box, slot)], PK4::BOX_LENGTH, true);
if (!crypted)
{
pk4->encrypt();
}
}
}
}
bool Sav4::giftsMenuActivated(void) const
{
return (data[gbo + 72] & 1) == 1;
}
void Sav4::giftsMenuActivated(bool v)
{
data[gbo + 72] &= 0xFE;
data[gbo + 72] |= v ? 1 : 0;
}
void Sav4::mysteryGift(const WCX& wc, int& pos)
{
if (wc.generation() == Generation::FOUR)
{
giftsMenuActivated(true);
data[WondercardFlags + (2047 >> 3)] = 0x80;
std::copy(wc.rawData(), wc.rawData() + PGT::length,
&data[WondercardData + pos * PGT::length]);
pos++;
if (game == Game::DP)
{
static constexpr u32 dpSlotActive = 0xEDB88320;
const int ofs = WondercardFlags + 0x100;
LittleEndian::convertFrom<u32>(&data[ofs + 4 * pos], dpSlotActive);
}
}
}
std::string Sav4::boxName(u8 box) const
{
return StringUtils::transString45(StringUtils::getString4(
data.get(), boxOffset(18, 0) + box * 0x28 + (game == Game::HGSS ? 0x8 : 0), 9));
}
void Sav4::boxName(u8 box, const std::string_view& name)
{
StringUtils::setString4(data.get(), StringUtils::transString45(name),
boxOffset(18, 0) + box * 0x28 + (game == Game::HGSS ? 0x8 : 0), 9);
}
int adjustWallpaper(int value, int shift)
{
// Pt's Special Wallpapers 1-8 are shifted by +0x8
// HG/SS Special Wallpapers 1-8 (Primo Phrases) are shifted by +0x10
if (value >= 0x10)
{ // special
return value + shift;
}
return value;
}
u8 Sav4::boxWallpaper(u8 box) const
{
int offset = boxOffset(maxBoxes(), 0);
if (game == Game::HGSS)
{
offset += 0x8;
}
offset += (maxBoxes() * 0x28) + box;
int v = data[offset];
if (game != Game::DP)
{
v = adjustWallpaper(v, -(game == Game::Pt ? 0x8 : 0x10));
}
return v;
}
void Sav4::boxWallpaper(u8 box, u8 v)
{
if (game != Game::DP)
{
v = adjustWallpaper(v, game == Game::Pt ? 0x8 : 0x10);
}
int offset = boxOffset(maxBoxes(), 0);
if (game == Game::HGSS)
{
offset += 0x8;
}
offset += (maxBoxes() * 0x28) + box;
if (offset < 0 || box > maxBoxes())
{
return;
}
data[offset] = v;
}
u8 Sav4::partyCount(void) const
{
return data[Party - 4];
}
void Sav4::partyCount(u8 v)
{
data[Party - 4] = v;
}
void Sav4::dex(const PKX& pk)
{
if (!(availableSpecies().count(pk.species()) > 0) || pk.egg())
{
return;
}
static constexpr int brSize = 0x40;
int bit = u16(pk.species()) - 1;
u8 mask = 1u << (bit & 7);
int ofs = PokeDex + (bit >> 3) + 0x4;
/* 4 BitRegions with 0x40*8 bits
* Region 0: Caught (Captured/Owned) flags
* Region 1: Seen flags
* Region 2/3: Toggle for gender display
* 4 possible states: 00, 01, 10, 11
* 00 - 1Seen: Male Only
* 01 - 2Seen: Male First, Female Second
* 10 - 2Seen: Female First, Male Second
* 11 - 1Seen: Female Only
* (bit1 ^ bit2) + 1 = forms in dex
* bit2 = male/female shown first toggle */
// Set the species() Owned Flag
data[ofs + brSize * 0] |= mask;
// Check if already Seen
if ((data[ofs + brSize * 1] & mask) == 0) // Not seen
{
data[ofs + brSize * 1] |= mask; // Set seen
u8 gr = pk.genderType();
switch (gr)
{
case 255: // Genderless
case 0: // Male Only
data[ofs + brSize * 2] &= ~mask;
data[ofs + brSize * 3] &= ~mask;
break;
case 254: // Female Only
data[ofs + brSize * 2] |= mask;
data[ofs + brSize * 3] |= mask;
break;
default: // Male or Female
bool m = (data[ofs + brSize * 2] & mask) != 0;
bool f = (data[ofs + brSize * 3] & mask) != 0;
if (m || f)
{ // bit already set?
break;
}
u8 gender = u8(pk.gender()) & 1;
data[ofs + brSize * 2] &= ~mask; // unset
data[ofs + brSize * 3] &= ~mask; // unset
gender ^= 1; // Set OTHER gender seen bit so it appears second
data[ofs + brSize * (2 + gender)] |= mask;
break;
}
}
int formOffset = PokeDex + 4 + (brSize * 4) + 4;
SmallVector<u8, 0x20> forms = getForms(pk.species());
if (forms.size() > 0)
{
if (pk.species() == Species::Unown)
{
for (u8 i = 0; i < 0x1C; i++)
{
u8 val = data[formOffset + 4 + i];
if (val == pk.alternativeForm())
{
break; // already set
}
if (val != 0xFF)
{
continue; // keep searching
}
data[formOffset + 4 + i] = u8(pk.alternativeForm());
break; // form now set
}
}
else if (pk.species() == Species::Pichu && game == Game::HGSS)
{
u8 form = pk.alternativeForm() == 1 ? 2 : u8(pk.gender());
if (checkInsertForm(forms, form))
{
setForms(forms, pk.species());
}
}
else
{
if (checkInsertForm(forms, pk.alternativeForm()))
{
setForms(forms, pk.species());
}
}
}
int dpl = 0;
if (game == Game::DP)
{
Species DPLangSpecies[] = {Species::Ekans, Species::Pikachu, Species::Psyduck,
Species::Ponyta, Species::Staryu, Species::Magikarp, Species::Wobbuffet,
Species::Heracross, Species::Sneasel, Species::Teddiursa, Species::Houndour,
Species::Wingull, Species::Slakoth, Species::Roselia};
for (int i = 0; i < 14; i++)
{
if (pk.species() == DPLangSpecies[i])
{
dpl = i + 1;
break;
}
}
if (dpl == 0)
{
return;
}
}
// Set the Language
int languageFlags = formOffset + (game == Game::HGSS ? 0x3C : 0x20);
int lang = u8(pk.language()) - 1;
switch (lang) // invert ITA/GER
{
case 3:
lang = 4;
break;
case 4:
lang = 3;
break;
}
if (lang > 5)
{
lang = 0; // no KOR+
}
lang = (lang < 0) ? 1 : lang; // default English
data[languageFlags + (game == Game::DP ? dpl : u16(pk.species()))] |= (u8)(1 << lang);
}
int Sav4::dexSeen(void) const
{
int ret = 0;
static constexpr int brSize = 0x40;
int ofs = PokeDex + 0x4;
for (const auto& spec : availableSpecies())
{
u16 i = u16(spec);
int bit = i - 1;
int bd = bit >> 3;
int bm = bit & 7;
if ((1 << bm & data[ofs + bd + brSize]) != 0)
{
ret++;
}
}
return ret;
}
int Sav4::dexCaught(void) const
{
int ret = 0;
int ofs = PokeDex + 0x4;
for (const auto& spec : availableSpecies())
{
u16 i = u16(spec);
int bit = i - 1;
int bd = bit >> 3;
int bm = bit & 7;
if ((1 << bm & data[ofs + bd]) != 0)
{
ret++;
}
}
return ret;
}
bool Sav4::checkInsertForm(SmallVector<u8, 0x20>& forms, u8 formNum)
{
SmallVector<u8, 0x20> dummy;
for (size_t i = 0; i < forms.size(); i++)
{
if (forms[i] == formNum)
{
return false;
}
dummy.emplace_back(0xFF);
}
if (std::equal(forms.begin(), forms.end(), dummy.begin()))
{
forms[0] = formNum;
return true;
}
// insert at first empty
u8 index = 255;
for (size_t i = 0; i < forms.size(); i++)
{
if (forms[i] == 255)
{
index = i;
break;
}
}
if (index == 255)
{
return false;
}
forms[index] = formNum;
return true;
}
SmallVector<u8, 0x20> Sav4::getForms(Species species)
{
static constexpr u8 brSize = 0x40;
if (species == Species::Deoxys)
{
u32 val =
data[PokeDex + 0x4 + 1 * brSize - 1] | (data[PokeDex + 0x4 + 2 * brSize - 1] << 8);
return getDexFormValues(val, 4, 4);
}
int formOffset = PokeDex + 4 + 4 * brSize + 4;
switch (species)
{
case Species::Shellos:
return getDexFormValues(data[formOffset + 0], 1, 2);
case Species::Gastrodon:
return getDexFormValues(data[formOffset + 1], 1, 2);
case Species::Burmy:
return getDexFormValues(data[formOffset + 2], 2, 3);
case Species::Wormadam:
return getDexFormValues(data[formOffset + 3], 2, 3);
case Species::Unown:
{
int ofs = formOffset + 4;
SmallVector<u8, 0x20> forms(0x1C);
std::copy(data.get() + ofs, data.get() + ofs + 0x1C, forms.begin());
return forms;
}
default:
break;
}
if (game == Game::DP)
{
return {};
}
int languageFlags = formOffset + (game == Game::HGSS ? 0x3C : 0x20);
int formOffset2 = languageFlags + 0x1F4;
switch (species)
{
case Species::Rotom:
return getDexFormValues(
LittleEndian::convertTo<u32>(data.get() + formOffset2), 3, 6);
case Species::Shaymin:
return getDexFormValues(data[formOffset2 + 4], 1, 2);
case Species::Giratina:
return getDexFormValues(data[formOffset2 + 5], 1, 2);
case Species::Pichu:
if (game == Game::HGSS)
{
return getDexFormValues(data[formOffset2 + 6], 2, 3);
}
default:
break;
}
return {};
}
SmallVector<u8, 0x20> Sav4::getDexFormValues(u32 v, u8 bitsPerForm, u8 readCt)
{
SmallVector<u8, 0x20> forms(readCt);
u8 n1 = 0xFF >> (8 - bitsPerForm);
for (int i = 0; i < readCt; i++)
{
u8 val = (v >> (i * bitsPerForm)) & n1;
forms[i] = n1 == val && bitsPerForm > 1 ? 255 : val;
}
if (bitsPerForm == 1 && forms[0] == forms[1] && forms[0] == 1)
{
forms[0] = forms[1] = 255;
}
return forms;
}
void Sav4::setForms(SmallVector<u8, 0x20> forms, Species species)
{
static constexpr u8 brSize = 0x40;
if (species == Species::Deoxys)
{
u32 newval = setDexFormValues(forms, 4, 4);
data[PokeDex + 0x4 + 1 * brSize - 1] = newval & 0xFF;
data[PokeDex + 0x4 + 2 * brSize - 1] = (newval >> 8) & 0xFF;
}
int formOffset = PokeDex + 4 + 4 * brSize + 4;
switch (species)
{
case Species::Shellos:
data[formOffset + 0] = u8(setDexFormValues(forms, 1, 2));
return;
case Species::Gastrodon:
data[formOffset + 1] = u8(setDexFormValues(forms, 1, 2));
return;
case Species::Burmy:
data[formOffset + 2] = u8(setDexFormValues(forms, 2, 3));
return;
case Species::Wormadam:
data[formOffset + 3] = u8(setDexFormValues(forms, 2, 3));
return;
case Species::Unown:
{
int ofs = formOffset + 4;
int len = forms.size();
for (size_t i = len; i < 0x1C; i++)
{
forms.emplace_back(0xFF);
}
std::copy(forms.begin(), forms.end(), data.get() + ofs);
return;
}
default:
break;
}
if (game == Game::DP)
{
return;
}
int languageFlags = formOffset + (game == Game::HGSS ? 0x3C : 0x20);
int formOffset2 = languageFlags + 0x1F4;
switch (species)
{
case Species::Rotom:
{
auto values = LittleEndian::convertFrom(setDexFormValues(forms, 3, 6));
for (size_t i = 0; i < values.size(); i++)
{
data[formOffset2 + i] = values[i];
}
return;
}
case Species::Shaymin:
{
data[formOffset2 + 4] = (u8)setDexFormValues(forms, 1, 2);
return;
}
case Species::Giratina:
{
data[formOffset2 + 5] = (u8)setDexFormValues(forms, 1, 2);
return;
}
case Species::Pichu:
{
if (game == Game::HGSS)
{
data[formOffset2 + 6] = (u8)setDexFormValues(forms, 2, 3);
return;
}
}
default:
break;
}
}
u32 Sav4::setDexFormValues(SmallVector<u8, 0x20> forms, u8 bitsPerForm, u8 readCt)
{
int n1 = 0xFF >> (8 - bitsPerForm);
u32 v = 0xFFFFFFFF << (readCt * bitsPerForm);
for (size_t i = 0; i < forms.size(); i++)
{
int val = forms[i];
if (val == 255)
{
val = n1;
}
v |= u32(val << (bitsPerForm * i));
}
return v;
}
std::unique_ptr<PKX> Sav4::emptyPkm() const
{
return PKX::getPKM<Generation::FOUR>(nullptr, PK4::BOX_LENGTH);
}
int Sav4::currentGiftAmount(void) const
{
u8 t;
for (t = 0; t < maxWondercards(); t++)
{
bool empty = true;
for (u32 j = 0; j < PGT::length; j++)
{
if (data[WondercardData + t * PGT::length + j] != 0)
{
empty = false;
break;
}
}
if (empty)
{
break;
}
}
return t;
}
std::unique_ptr<WCX> Sav4::mysteryGift(int pos) const
{
return std::make_unique<PGT>(data.get() + WondercardData + pos * PGT::length);
}
void Sav4::item(const Item& item, Pouch pouch, u16 slot)
{
Item4 inject = static_cast<Item4>(item);
auto write = inject.bytes();
switch (pouch)
{
case Pouch::NormalItem:
std::copy(write.begin(), write.end(), &data[PouchHeldItem + slot * 4]);
break;
case Pouch::KeyItem:
std::copy(write.begin(), write.end(), &data[PouchKeyItem + slot * 4]);
break;
case Pouch::TM:
std::copy(write.begin(), write.end(), &data[PouchTMHM + slot * 4]);
break;
case Pouch::Mail:
std::copy(write.begin(), write.end(), &data[MailItems + slot * 4]);
break;
case Pouch::Medicine:
std::copy(write.begin(), write.end(), &data[PouchMedicine + slot * 4]);
break;
case Pouch::Berry:
std::copy(write.begin(), write.end(), &data[PouchBerry + slot * 4]);
break;
case Pouch::Ball:
std::copy(write.begin(), write.end(), &data[PouchBalls + slot * 4]);
break;
case Pouch::Battle:
std::copy(write.begin(), write.end(), &data[BattleItems + slot * 4]);
break;
default:
return;
}
}
std::unique_ptr<Item> Sav4::item(Pouch pouch, u16 slot) const
{
switch (pouch)
{
case Pouch::NormalItem:
return std::make_unique<Item4>(&data[PouchHeldItem + slot * 4]);
case Pouch::KeyItem:
return std::make_unique<Item4>(&data[PouchKeyItem + slot * 4]);
case Pouch::TM:
return std::make_unique<Item4>(&data[PouchTMHM + slot * 4]);
case Pouch::Mail:
return std::make_unique<Item4>(&data[MailItems + slot * 4]);
case Pouch::Medicine:
return std::make_unique<Item4>(&data[PouchMedicine + slot * 4]);
case Pouch::Berry:
return std::make_unique<Item4>(&data[PouchBerry + slot * 4]);
case Pouch::Ball:
return std::make_unique<Item4>(&data[PouchBalls + slot * 4]);
case Pouch::Battle:
return std::make_unique<Item4>(&data[BattleItems + slot * 4]);
default:
return nullptr;
}
}
std::optional<std::array<std::unique_ptr<PK4>, 6>> Sav4::palPark() const
{
std::optional<std::array<std::unique_ptr<PK4>, 6>> ret = std::nullopt;
if (auto pk4 = PKX::getPKM<Generation::FOUR>(&data[PalPark], PK4::PARTY_LENGTH);
pk4->species() != pksm::Species::None)
{
ret = {std::move(pk4),
PKX::getPKM<Generation::FOUR>(
&data[PalPark + (PK4::PARTY_LENGTH * 1)], PK4::PARTY_LENGTH),
PKX::getPKM<Generation::FOUR>(
&data[PalPark + (PK4::PARTY_LENGTH * 2)], PK4::PARTY_LENGTH),
PKX::getPKM<Generation::FOUR>(
&data[PalPark + (PK4::PARTY_LENGTH * 3)], PK4::PARTY_LENGTH),
PKX::getPKM<Generation::FOUR>(
&data[PalPark + (PK4::PARTY_LENGTH * 4)], PK4::PARTY_LENGTH),
PKX::getPKM<Generation::FOUR>(
&data[PalPark + (PK4::PARTY_LENGTH * 5)], PK4::PARTY_LENGTH)};
}
return ret;
}
void Sav4::palPark(std::span<std::unique_ptr<PK4>, 0> mons)
{
for (int i = 0; i < 6; i++)
{
std::fill_n(&data[PalPark + i * PK4::PARTY_LENGTH], PK4::PARTY_LENGTH, 0);
}
}
void Sav4::palPark(std::span<std::unique_ptr<PK4>, 6> mons)
{
if (mons.size() != 6)
{
return;
}
for (int i = 0; i < 6; i++)
{
mons[i]->decrypt();
// Set the values that would normally be set by migration
mons[i]->metLevel(mons[i]->level());
mons[i]->encounterType(0); // encounter type 0 is palpark
mons[i]->metLocation(0x0037); // location is palpark
// Version should likely be set on the mon incoming to this function.
mons[i]->updatePartyData();
mons[i]->encrypt();
std::ranges::copy(mons[i]->rawData(), &data[PalPark + (PK4::PARTY_LENGTH * i)]);
}
}
}
| 30,197
|
C++
|
.cpp
| 900
| 22.625556
| 99
| 0.474068
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,227
|
Sav2.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav2.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav2.hpp"
#include "GameVersion.hpp"
#include "pkx/PK2.hpp"
#include "pkx/PKX.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include "utils/flagUtil.hpp"
#include "utils/i18n.hpp"
#include "utils/utils.hpp"
#include "wcx/WCX.hpp"
#include <algorithm>
#include <limits>
#include <stdlib.h>
namespace pksm
{
// the language class and version necessarily need to be found, may as well use them
Sav2::Sav2(const std::shared_ptr<u8[]>& data, u32 length,
std::tuple<GameVersion, Language, bool> versionAndLanguage)
: Sav(data, length)
{
versionOfGame = get<0>(versionAndLanguage);
lang = get<1>(versionAndLanguage);
japanese = lang == Language::JPN;
korean = lang == Language::KOR;
maxPkmInBox = japanese ? 30 : 20;
boxSize = japanese ? 0x54A : 0x450;
OFS_TID = 0x2009;
OFS_NAME = 0x200B;
if (korean)
{
OFS_TIME_PLAYED = 0x204D;
OFS_PALETTE = 0x2065;
OFS_MONEY = 0x23D3;
OFS_BADGES = 0x23DC;
OFS_TM_POUCH = 0x23DE;
OFS_ITEMS = 0x2417;
OFS_KEY_ITEMS = 0x2441;
OFS_BALLS = 0x245C;
OFS_PC_ITEMS = 0x2476;
OFS_CURRENT_BOX_INDEX = 0x26FC;
OFS_BOX_NAMES = 0x26FF;
OFS_PARTY = 0x28CC;
OFS_POKEDEX_CAUGHT = 0x2A8E;
OFS_POKEDEX_SEEN = 0x2AAE;
OFS_CHECKSUM_END = 0x2DAA;
OFS_CHECKSUM_ONE = 0x2DAB;
OFS_CURRENT_BOX = 0x2DAE;
OFS_CHECKSUM_TWO = 0x7E6B;
OFS_GENDER = 0xFFFFFFFF;
}
else if (japanese)
{
OFS_TIME_PLAYED = 0x2034;
OFS_PALETTE = 0x204C;
OFS_CURRENT_BOX = 0x2D10;
OFS_CHECKSUM_ONE = 0x2D0D;
OFS_CHECKSUM_TWO = 0x7F0D;
if (versionOfGame == GameVersion::C)
{
OFS_MONEY = 0x23BE;
OFS_BADGES = 0x23C7;
OFS_TM_POUCH = 0x23C9;
OFS_ITEMS = 0x2402;
OFS_KEY_ITEMS = 0x242C;
OFS_BALLS = 0x2447;
OFS_PC_ITEMS = 0x2461;
OFS_CURRENT_BOX_INDEX = 0x26E2;
OFS_BOX_NAMES = 0x26E5;
OFS_PARTY = 0x281A;
OFS_POKEDEX_CAUGHT = 0x29AA;
OFS_POKEDEX_SEEN = 0x29CA;
OFS_CHECKSUM_END = 0x2AE2;
OFS_GENDER = 0x8000;
}
else
{
OFS_MONEY = 0x23BC;
OFS_BADGES = 0x23C5;
OFS_TM_POUCH = 0x23C7;
OFS_ITEMS = 0x2400;
OFS_KEY_ITEMS = 0x242A;
OFS_BALLS = 0x2445;
OFS_PC_ITEMS = 0x245F;
OFS_CURRENT_BOX_INDEX = 0x2705;
OFS_BOX_NAMES = 0x2708;
OFS_PARTY = 0x283E;
OFS_POKEDEX_CAUGHT = 0x29CE;
OFS_POKEDEX_SEEN = 0x29EE;
OFS_CHECKSUM_END = 0x2C8B;
OFS_GENDER = 0xFFFFFFFF;
}
}
else
{
if (versionOfGame == GameVersion::C)
{
OFS_TIME_PLAYED = 0x2052;
OFS_PALETTE = 0x206A;
OFS_MONEY = 0x23DC;
OFS_BADGES = 0x23E5;
OFS_TM_POUCH = 0x23E7;
OFS_ITEMS = 0x2420;
OFS_KEY_ITEMS = 0x244A;
OFS_BALLS = 0x2465;
OFS_PC_ITEMS = 0x247F;
OFS_CURRENT_BOX_INDEX = 0x2700;
OFS_BOX_NAMES = 0x2703;
OFS_PARTY = 0x2865;
OFS_POKEDEX_CAUGHT = 0x2A27;
OFS_POKEDEX_SEEN = 0x2A47;
OFS_CHECKSUM_END = 0x2B82;
OFS_CHECKSUM_ONE = 0x2D0D;
OFS_CURRENT_BOX = 0x2D10;
OFS_GENDER = 0x3E3D;
OFS_CHECKSUM_TWO = 0x7F0D;
}
else
{
OFS_TIME_PLAYED = 0x2053;
OFS_PALETTE = 0x206B;
OFS_MONEY = 0x23DB;
OFS_BADGES = 0x23E4;
OFS_TM_POUCH = 0x23E6;
OFS_ITEMS = 0x241F;
OFS_KEY_ITEMS = 0x2449;
OFS_BALLS = 0x2464;
OFS_PC_ITEMS = 0x247E;
OFS_CURRENT_BOX_INDEX = 0x2724;
OFS_BOX_NAMES = 0x2727;
OFS_PARTY = 0x288A;
OFS_POKEDEX_CAUGHT = 0x2A4C;
OFS_POKEDEX_SEEN = 0x2A6C;
OFS_CHECKSUM_END = 0x2D68;
OFS_CHECKSUM_ONE = 0x2D69;
OFS_CURRENT_BOX = 0x2D6C;
OFS_CHECKSUM_TWO = 0x7E6D;
OFS_GENDER = 0xFFFFFFFF;
}
}
originalCurrentBox = currentBox();
if (lang == Language::ENG)
{
lang = StringUtils::guessLanguage12(otName());
}
}
std::tuple<GameVersion, Language, bool> Sav2::getVersion(const std::shared_ptr<u8[]>& dt)
{
GameVersion returnVersion = GameVersion::INVALID;
Language returnLanguage = Language::None;
bool saveFound = false;
if (validList(dt, 0x288A, 20) && validList(dt, 0x2D6C, 20))
{
returnVersion = GameVersion::GD;
returnLanguage = Language::ENG; // as well as all other languages not enumerated
saveFound = true;
}
else if (validList(dt, 0x2865, 20) && validList(dt, 0x2D10, 20))
{
returnVersion = GameVersion::C;
returnLanguage = Language::ENG;
saveFound = true;
}
else if (validList(dt, 0x2D10, 30))
{
if (validList(dt, 0x283E, 30))
{
returnVersion = GameVersion::GD;
returnLanguage = Language::JPN;
saveFound = true;
}
else if (validList(dt, 0x281A, 30))
{
returnVersion = GameVersion::C;
returnLanguage = Language::JPN;
saveFound = true;
}
}
else if (validList(dt, 0x28CC, 20) && validList(dt, 0x2DAE, 20))
{
returnVersion = GameVersion::GD;
returnLanguage = Language::KOR;
saveFound = true;
}
// there is no KOR crystal
return {returnVersion, returnLanguage, saveFound};
}
bool Sav2::validList(const std::shared_ptr<u8[]>& dt, size_t ofs, u8 slot)
{
return (dt[ofs] <= 30) && (dt[ofs + 1 + dt[ofs]] == 0xFF);
}
// max length of string + terminator
u8 Sav2::nameLength() const
{
return japanese ? 6 : 11;
}
u8 Sav2::PK2Length(void) const
{
return japanese ? PK2::JP_LENGTH_WITH_NAMES : PK2::INT_LENGTH_WITH_NAMES;
}
void Sav2::fixBoxes()
{
// Poor man's bubble sort-like thing
for (int i = 0; i < maxBoxes(); i++)
{
for (int j = maxPkmInBox - 1; j > 0; j--)
{
auto checkPKM = pkm(i, j);
if (checkPKM->species() == Species::None)
{
continue;
}
auto prevPKM = pkm(i, j - 1);
if (checkPKM->species() != Species::None && prevPKM->species() == Species::None)
{
pkm(*checkPKM, i, j - 1, false);
pkm(*prevPKM, i, j, false);
j = maxPkmInBox; // reset loop
}
}
fixBox(i);
}
}
void Sav2::finishEditing()
{
// we just pretend the secondary data copy doesn't exist, it's never used as long as we get
// the checksum for the primary copy right
fixBoxes();
fixParty();
fixItemLists();
std::copy(&data[OFS_CURRENT_BOX], &data[OFS_CURRENT_BOX] + boxSize,
&data[boxStart(originalCurrentBox, false)]);
if (currentBox() != originalCurrentBox)
{
std::copy(&data[boxStart(currentBox())], &data[boxStart(currentBox())] + boxSize,
&data[OFS_CURRENT_BOX]);
}
// no, i don't know why only the checksum is little-endian. also idk why PKHeX destroys the
// checksum for the secondary data copy
u16 checksum = crypto::bytewiseSum16({&data[OFS_TID], OFS_CHECKSUM_END - OFS_TID + 1});
LittleEndian::convertFrom<u16>(&data[OFS_CHECKSUM_ONE], checksum);
LittleEndian::convertFrom<u16>(&data[OFS_CHECKSUM_TWO], checksum);
originalCurrentBox = currentBox();
}
u16 Sav2::TID() const
{
return BigEndian::convertTo<u16>(&data[OFS_TID]);
}
void Sav2::TID(u16 v)
{
BigEndian::convertFrom<u16>(&data[OFS_TID], v);
}
GameVersion Sav2::version() const
{
return versionOfGame;
}
void Sav2::version(GameVersion v)
{
if ((v == GameVersion::C) ^ (versionOfGame != GameVersion::C))
{
versionOfGame = v;
}
}
Gender Sav2::gender() const
{
if (versionOfGame == GameVersion::C)
{
if (data[OFS_GENDER] > 1)
{
return Gender::Male;
}
return Gender{data[OFS_GENDER]};
}
return Gender::Male;
}
void Sav2::gender(Gender v)
{
if (versionOfGame == GameVersion::C)
{
if (v <= Gender::Female)
{
data[OFS_GENDER] = u8(v);
}
// this is the palette used to draw the player, always 0 (red) for male and 1 (blue)
// for female. it's present and 0 in Gold and Silver
data[OFS_PALETTE] = u8(v);
}
}
Language Sav2::language() const
{
return lang;
}
void Sav2::language(Language v)
{
if (((lang == Language::JPN) == (v == Language::JPN)) &&
((lang == Language::KOR) == (v == Language::KOR)))
{
lang = v;
}
}
std::string Sav2::otName() const
{
return StringUtils::getString2(
data.get(), OFS_NAME, japanese ? 6 : (korean ? 11 : 8), lang);
}
void Sav2::otName(const std::string_view& v)
{
StringUtils::setString2(data.get(), v, OFS_NAME, japanese ? 6 : (korean ? 11 : 8), lang);
}
// yay, they stopped using BCD
u32 Sav2::money() const
{
return BigEndian::convertTo<u32>(&data[OFS_MONEY]) >> 8;
}
void Sav2::money(u32 v)
{
if (v > 999999)
{
v = 999999;
}
data[OFS_MONEY] = v >> 16;
data[OFS_MONEY + 1] = (v >> 8) & 0x00FF;
data[OFS_MONEY + 2] = v & 0x0000FF;
}
u8 Sav2::badges() const
{
u8 sum = 0;
u16 badgeFlags = BigEndian::convertTo<u16>(&data[OFS_BADGES]);
for (int i = 0; i < 16; i++)
{
sum += (badgeFlags & (1 << i)) >> i;
}
return sum;
}
u16 Sav2::playedHours() const
{
return BigEndian::convertTo<u16>(&data[OFS_TIME_PLAYED]);
}
void Sav2::playedHours(u16 v)
{
BigEndian::convertFrom<u16>(&data[OFS_TIME_PLAYED], v);
}
u8 Sav2::playedMinutes() const
{
return data[OFS_TIME_PLAYED + 2];
}
void Sav2::playedMinutes(u8 v)
{
data[OFS_TIME_PLAYED + 2] = v;
}
u8 Sav2::playedSeconds() const
{
return data[OFS_TIME_PLAYED + 3];
}
void Sav2::playedSeconds(u8 v)
{
data[OFS_TIME_PLAYED + 3] = v;
}
u8 Sav2::currentBox() const
{
return data[OFS_CURRENT_BOX_INDEX] & 0x7F;
}
void Sav2::currentBox(u8 v)
{
data[OFS_CURRENT_BOX_INDEX] = (data[OFS_CURRENT_BOX_INDEX] & 0x80) | (v & 0x7F);
}
u32 Sav2::boxOffset(u8 box, u8 slot) const
{
return boxDataStart(box) + (slot * PK2::BOX_LENGTH);
}
u32 Sav2::boxOtNameOffset(u8 box, u8 slot) const
{
return boxDataStart(box) + (maxPkmInBox * PK2::BOX_LENGTH) + (slot * nameLength());
}
u32 Sav2::boxNicknameOffset(u8 box, u8 slot) const
{
return boxDataStart(box) + (maxPkmInBox * PK2::BOX_LENGTH) +
((maxPkmInBox + slot) * nameLength());
}
u32 Sav2::partyOffset(u8 slot) const
{
return OFS_PARTY + 8 + (slot * PK2::PARTY_LENGTH);
}
u32 Sav2::partyOtNameOffset(u8 slot) const
{
return OFS_PARTY + 8 + (6 * PK2::PARTY_LENGTH) + (slot * nameLength());
}
u32 Sav2::partyNicknameOffset(u8 slot) const
{
return OFS_PARTY + 8 + (6 * PK2::PARTY_LENGTH) + ((6 + slot) * nameLength());
}
u32 Sav2::boxStart(u8 box, bool obeyCurrentBoxMechanics) const
{
if (box == originalCurrentBox && obeyCurrentBoxMechanics)
{
return OFS_CURRENT_BOX;
}
if (!japanese)
{
if (box < maxBoxes() / 2)
{
return 0x4000 + (box * boxSize);
}
box -= maxBoxes() / 2;
return 0x6000 + (box * boxSize);
}
// huh
else
{
if (box < 6)
{
return 0x4000 + (box * boxSize);
}
box -= 6;
return 0x6000 + (box * boxSize);
}
}
u32 Sav2::boxDataStart(u8 box, bool obeyCurrentBoxMechanics) const
{
return boxStart(box, obeyCurrentBoxMechanics) + maxPkmInBox + 2;
}
// the PK1 and PK2 formats used by the community start with magic bytes, the second being
// species
std::unique_ptr<PKX> Sav2::pkm(u8 slot) const
{
if (slot >= partyCount())
{
return emptyPkm();
}
// using the larger of the two sizes to not dynamically allocate
u8 buffer[PK2::INT_LENGTH_WITH_NAMES] = {0x01, data[OFS_PARTY + 1 + slot], 0xFF};
std::copy(
&data[partyOffset(slot)], &data[partyOffset(slot)] + PK2::PARTY_LENGTH, buffer + 3);
std::copy(&data[partyOtNameOffset(slot)], &data[partyOtNameOffset(slot)] + nameLength(),
buffer + 3 + PK2::PARTY_LENGTH);
std::copy(&data[partyNicknameOffset(slot)], &data[partyNicknameOffset(slot)] + nameLength(),
buffer + 3 + PK2::PARTY_LENGTH + nameLength());
StringUtils::gbStringFailsafe(buffer, 3 + PK2::PARTY_LENGTH, nameLength());
StringUtils::gbStringFailsafe(buffer, 3 + PK2::PARTY_LENGTH + nameLength(), nameLength());
auto pk2 = PKX::getPKM<Generation::TWO>(buffer, PK2Length());
// has to be done now, since you can't do it in the PK2 initializer because of the nullptr
// case
if (language() == Language::KOR)
{
pk2->languageOverrideLimits(Language::KOR);
}
else if (language() != Language::JPN)
{
pk2->language(StringUtils::guessLanguage12(pk2->nickname()));
}
return pk2;
}
std::unique_ptr<PKX> Sav2::pkm(u8 box, u8 slot) const
{
if (slot >= maxPkmInBox || slot >= boxCount(box))
{
return emptyPkm();
}
u8 buffer[PK2::INT_LENGTH_WITH_NAMES] = {0x01, data[boxStart(box) + 1 + slot], 0xFF};
std::copy(
&data[boxOffset(box, slot)], &data[boxOffset(box, slot)] + PK2::BOX_LENGTH, buffer + 3);
std::copy(&data[boxOtNameOffset(box, slot)],
&data[boxOtNameOffset(box, slot)] + nameLength(), buffer + 3 + PK2::PARTY_LENGTH);
std::copy(&data[boxNicknameOffset(box, slot)],
&data[boxNicknameOffset(box, slot)] + nameLength(),
buffer + 3 + PK2::PARTY_LENGTH + nameLength());
StringUtils::gbStringFailsafe(buffer, 3 + PK2::PARTY_LENGTH, nameLength());
StringUtils::gbStringFailsafe(buffer, 3 + PK2::PARTY_LENGTH + nameLength(), nameLength());
auto pk2 = PKX::getPKM<Generation::TWO>(buffer, PK2Length());
pk2->updatePartyData();
if (language() == Language::KOR)
{
pk2->language(Language::KOR);
}
else if (language() != Language::JPN)
{
pk2->language(StringUtils::guessLanguage12(pk2->nickname()));
}
return pk2;
}
void Sav2::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::TWO)
{
if (slot >= partyCount())
{
if (slot > partyCount())
{
pkm(*emptyPkm(), slot - 1);
}
partyCount(slot + 1);
}
auto pk2 = pk.partyClone();
std::ranges::copy(
pk2->rawData().subspan(3, PK2::PARTY_LENGTH), &data[partyOffset(slot)]);
// korean has a page for INT characters
if (((language() == Language::JPN) != (pk2->language() == Language::JPN)) ||
((pk2->language() == Language::KOR) && (language() != Language::KOR)))
{
StringUtils::setString2(&data[partyNicknameOffset(slot)],
StringUtils::toUpper(pk2->species().localize(language())), 0, nameLength(),
language());
// check if it's the trade ot byte
if (pk2->rawData()[3 + PK2::PARTY_LENGTH] == 0x5D)
{
data[partyOtNameOffset(slot)] = 0x5D;
data[partyOtNameOffset(slot) + 1] = 0x50;
}
else
{
StringUtils::setString2(&data[partyOtNameOffset(slot)],
StringUtils::getTradeOT(language()), 0, nameLength(), language());
}
}
else
{
std::ranges::copy(pk2->rawData().subspan(3 + PK2::PARTY_LENGTH, nameLength()),
&data[partyOtNameOffset(slot)]);
std::ranges::copy(
pk2->rawData().subspan(3 + PK2::PARTY_LENGTH + nameLength(), nameLength()),
&data[partyNicknameOffset(slot)]);
}
data[OFS_PARTY + 1 + slot] = pk2->rawData()[1];
}
}
void Sav2::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (slot >= maxPkmInBox)
{
return;
}
if (pk.generation() == Generation::TWO)
{
auto pk2 = pk.clone(); // note that partyClone and clone are equivalent
if (applyTrade)
{
trade(*pk2);
}
if (slot >= boxCount(box))
{
if (slot > boxCount(box))
{
pkm(*emptyPkm(), box, slot - 1, false);
}
boxCount(box, slot + 1);
}
std::ranges::copy(
pk2->rawData().subspan(3, PK2::BOX_LENGTH), &data[boxOffset(box, slot)]);
if (((language() == Language::JPN) != (pk2->language() == Language::JPN)) ||
((pk2->language() == Language::KOR) && (language() != Language::KOR)))
{
StringUtils::setString2(&data[boxNicknameOffset(box, slot)],
StringUtils::toUpper(pk2->species().localize(language())), 0, nameLength(),
language());
if (pk2->rawData()[3 + PK2::BOX_LENGTH] == 0x5D)
{
data[boxOtNameOffset(box, slot)] = 0x5D;
data[boxOtNameOffset(box, slot) + 1] = 0x50;
}
else
{
StringUtils::setString2(&data[boxOtNameOffset(box, slot)],
StringUtils::toUpper(StringUtils::getTradeOT(language())), 0, nameLength(),
language());
}
}
else
{
std::ranges::copy(pk2->rawData().subspan(3 + PK2::PARTY_LENGTH, nameLength()),
&data[boxOtNameOffset(box, slot)]);
std::ranges::copy(
pk2->rawData().subspan(3 + PK2::PARTY_LENGTH + nameLength(), nameLength()),
&data[boxNicknameOffset(box, slot)]);
}
data[boxStart(box) + 1 + slot] = pk2->rawData()[1];
}
}
std::unique_ptr<PKX> Sav2::emptyPkm() const
{
return PKX::getPKM<Generation::TWO>(nullptr, PK2Length());
}
void Sav2::dex(const PKX& pk)
{
if (!(availableSpecies().count(pk.species()) > 0))
{
return;
}
setCaught(pk.species(), true);
setSeen(pk.species(), true);
}
bool Sav2::getCaught(Species species) const
{
int flag = u8(species) - 1;
int ofs = flag >> 3;
return FlagUtil::getFlag(data.get() + OFS_POKEDEX_CAUGHT, ofs, flag & 7);
}
void Sav2::setCaught(Species species, bool caught)
{
int flag = u8(species) - 1;
int ofs = flag >> 3;
FlagUtil::setFlag(data.get() + OFS_POKEDEX_CAUGHT, ofs, flag & 7, caught);
if (species == Species::Unown)
{
// set the form of Unown seen in the Pokedex to A
if (data[OFS_POKEDEX_SEEN + 0x1F + 28] == 0)
{
data[OFS_POKEDEX_SEEN + 0x1F + 28] = 1;
}
// set all the caught flags for Unown forms (allegedly to prevent crash)
for (int i = 1; i <= 26; i++)
{
data[OFS_POKEDEX_SEEN + 0x1F + i] = i;
}
}
}
bool Sav2::getSeen(Species species) const
{
int flag = u8(species) - 1;
int ofs = flag >> 3;
return FlagUtil::getFlag(data.get() + OFS_POKEDEX_SEEN, ofs, flag & 7);
}
void Sav2::setSeen(Species species, bool seen)
{
int flag = u8(species) - 1;
int ofs = flag >> 3;
FlagUtil::setFlag(data.get() + OFS_POKEDEX_SEEN, ofs, flag & 7, seen);
if (species == Species::Unown && data[OFS_POKEDEX_SEEN + 0x1F + 28] == 0)
{
// set the form of Unown seen in the Pokedex to A
data[OFS_POKEDEX_SEEN + 0x1F + 28] = 1; // A
}
}
int Sav2::dexSeen() const
{
return std::count_if(availableSpecies().begin(), availableSpecies().end(),
[this](const auto& spec) { return getSeen(spec); });
}
int Sav2::dexCaught() const
{
return std::count_if(availableSpecies().begin(), availableSpecies().end(),
[this](const auto& spec) { return getCaught(spec); });
}
std::string Sav2::boxName(u8 box) const
{
int boxNameLength = korean ? 17 : 9;
return StringUtils::getString2(
data.get(), OFS_BOX_NAMES + (box * boxNameLength), boxNameLength, lang);
}
void Sav2::boxName(u8 box, const std::string_view& name)
{
int boxNameLength = korean ? 17 : 9;
StringUtils::setString2(data.get(), name, OFS_BOX_NAMES + (box * boxNameLength),
boxNameLength, lang, boxNameLength);
}
u8 Sav2::partyCount() const
{
return data[OFS_PARTY];
}
void Sav2::partyCount(u8 count)
{
data[OFS_PARTY] = count;
}
u8 Sav2::boxCount(u8 box) const
{
return data[boxStart(box)];
}
void Sav2::boxCount(u8 box, u8 count)
{
data[boxStart(box)] = count;
}
void Sav2::fixBox(u8 box)
{
u8 count = 0;
while (count < maxPkmInBox)
{
if (pkm(box, count)->species() == Species::None)
{
break;
}
if (pkm(box, count)->egg())
{
data[boxStart(box) + 1 + count] = 0xFD;
}
else
{
data[boxStart(box) + 1 + count] = data[boxOffset(box, count)];
}
count++;
}
data[boxStart(box) + 1 + count] = 0xFF;
data[boxStart(box)] = count;
}
void Sav2::fixParty()
{
Sav::fixParty();
u8 count = 0;
while (count < 6)
{
if (pkm(count)->species() == Species::None)
{
break;
}
if (pkm(count)->egg())
{
data[OFS_PARTY + 1 + count] = 0xFD;
}
else
{
data[OFS_PARTY + 1 + count] = data[partyOffset(count)];
}
count++;
}
data[OFS_PARTY + 1 + count] = 0xFF;
data[OFS_PARTY] = count;
}
int Sav2::maxSlot() const
{
return maxBoxes() * maxPkmInBox;
}
int Sav2::maxBoxes() const
{
return japanese ? 9 : 14;
}
void Sav2::item(const Item& tItem, Pouch pouch, u16 slot)
{
if (slot >= pouchEntryCount(pouch))
{
pouchEntryCount(pouch, slot + 1);
}
Item2 item = static_cast<Item2>(tItem);
auto write = item.bytes();
int index = 0; // for TMs
switch (pouch)
{
case Pouch::TM:
while (tmItems2()[index] != write[0])
{
index++;
}
data[OFS_TM_POUCH + index] = write[1];
break;
case Pouch::NormalItem:
std::copy(write.begin(), write.end(), &data[OFS_ITEMS + 1 + (slot * 2)]);
break;
case Pouch::KeyItem:
data[OFS_KEY_ITEMS + 1 + slot] = write[0];
break;
case Pouch::Ball:
std::copy(write.begin(), write.end(), &data[OFS_BALLS + 1 + (slot * 2)]);
break;
case Pouch::PCItem:
std::copy(write.begin(), write.end(), &data[OFS_PC_ITEMS + 1 + (slot * 2)]);
break;
default:
return;
}
}
std::unique_ptr<Item> Sav2::item(Pouch pouch, u16 slot) const
{
if (slot >= pouchEntryCount(pouch))
{
return std::make_unique<Item2>(nullptr);
}
std::unique_ptr<Item2> returnVal;
std::array<u8, 2> itemData;
switch (pouch)
{
case Pouch::TM:
// apparently they store the counts of the TMs
itemData[0] = tmItems2()[slot];
itemData[1] = data[OFS_TM_POUCH + slot];
returnVal = std::make_unique<Item2>(itemData.data());
break;
case Pouch::NormalItem:
returnVal = std::make_unique<Item2>(&data[OFS_ITEMS + 1 + (slot * 2)]);
break;
case Pouch::KeyItem:
itemData[0] = data[OFS_KEY_ITEMS + 1 + slot];
itemData[1] = 1;
returnVal = std::make_unique<Item2>(itemData.data());
break;
case Pouch::Ball:
returnVal = std::make_unique<Item2>(&data[OFS_BALLS + 1 + (slot * 2)]);
break;
case Pouch::PCItem:
returnVal = std::make_unique<Item2>(&data[OFS_PC_ITEMS + 1 + (slot * 2)]);
break;
default:
return nullptr;
}
// 0xFF is a list terminator. In a normal game state it will be in an ID slot.
if (returnVal->id2() == 0xFF)
{
return std::make_unique<Item2>(nullptr);
}
return returnVal;
}
SmallVector<std::pair<Sav::Pouch, int>, 15> Sav2::pouches() const
{
return {
std::pair{Pouch::TM, 57},
std::pair{Pouch::NormalItem, 20},
std::pair{Pouch::KeyItem, 26},
std::pair{Pouch::Ball, 12},
std::pair{Pouch::PCItem, 50}
};
}
std::span<const int> Sav2::tmItems2() const
{
for (const auto& i : validItems2())
{
if (i.first == Pouch::TM)
{
return i.second;
}
}
return {};
}
SmallVector<std::pair<pksm::Sav::Pouch, std::span<const int>>, 15> Sav2::validItems2() const
{
static constexpr std::array validItems = {// TMs
191, 192, 193, 194, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208,
209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 221, 222, 223, 224, 225, 226,
227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243,
244, 245, 246, 247, 248, 249,
// Normal
3, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 51, 52, 53, 57,
60, 62, 63, 64, 65, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 111, 112, 113, 114, 117, 118, 119, 121, 122, 123, 124, 125, 126, 131, 132, 138,
139, 140, 143, 144, 146, 150, 151, 152, 156, 158, 163, 167, 168, 169, 170, 172, 173,
174, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
// Ball
1, 2, 4, 5, 157, 159, 160, 161, 164, 165, 166,
// Key
7, 54, 55, 58, 59, 61, 66, 67, 68, 69, 71, 127, 128, 130, 133, 134, 175, 178,
// Key for Crystal
70, 115, 116, 129};
return {
std::pair{Pouch::TM, std::span{validItems.begin(), validItems.begin() + 57} },
std::pair{
Pouch::NormalItem, std::span{validItems.begin() + 57, validItems.begin() + 188} },
std::pair{Pouch::Ball, std::span{validItems.begin() + 188, validItems.begin() + 199} },
std::pair{
Pouch::KeyItem, std::span{validItems.begin() + 199,
validItems.end() - (version() == GameVersion::C ? 0 : 4)}},
std::pair{
Pouch::PCItem, std::span{validItems.begin(),
validItems.end() - (version() == GameVersion::C ? 0 : 4)} }
};
}
SmallVector<std::pair<pksm::Sav::Pouch, std::span<const int>>, 15> Sav2::validItems() const
{
static constexpr std::array validItems = {// TMs
328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361,
362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 420,
421, 422, 423, 424, 425, 426,
// Normal
213, 81, 18, 19, 20, 21, 22, 23, 24, 25, 26, 17, 78, 79, 41, 82, 83, 84, 45, 46, 47, 48,
256, 49, 50, 60, 85, 257, 92, 63, 27, 28, 29, 55, 76, 77, 56, 30, 31, 32, 57, 58, 59,
61, 216, 891, 51, 38, 39, 40, 33, 217, 151, 890, 237, 244, 149, 153, 152, 245, 221, 156,
150, 485, 86, 87, 222, 487, 223, 486, 488, 224, 243, 248, 490, 241, 491, 489, 240, 473,
259, 228, 246, 242, 157, 88, 89, 229, 247, 504, 239, 258, 230, 34, 35, 36, 37, 238, 231,
90, 91, 249, 43, 232, 233, 250, 234, 154, 235, 44, 236, 80, 252, 155, 158,
// Ball
1, 2, 3, 4, 495, 493, 494, 492, 497, 498, 496,
// Key
450, 444, 445, 446, 447, 478, 464, 456, 484, 482, 475, 481, 479, 476, 480, 477, 483,
// Key for crystal
474, 472};
return {
std::pair{Pouch::TM, std::span{validItems.begin(), validItems.begin() + 57} },
std::pair{
Pouch::NormalItem, std::span{validItems.begin() + 57, validItems.begin() + 172} },
std::pair{Pouch::Ball, std::span{validItems.begin() + 172, validItems.begin() + 183} },
std::pair{
Pouch::KeyItem, std::span{validItems.begin() + 183,
validItems.end() - (version() == GameVersion::C ? 0 : 2)}},
std::pair{
Pouch::PCItem, std::span{validItems.begin(),
validItems.end() - (version() == GameVersion::C ? 0 : 2)} }
};
}
u8 Sav2::pouchEntryCount(Pouch pouch) const
{
switch (pouch)
{
// the TM/HM pocket is a bytefield for all of the TMs and HMs
case Pouch::TM:
return 255;
case Pouch::NormalItem:
return data[OFS_ITEMS] > 20 ? 0 : data[OFS_ITEMS];
case Pouch::KeyItem:
return data[OFS_KEY_ITEMS] > 26 ? 0 : data[OFS_KEY_ITEMS];
case Pouch::Ball:
return data[OFS_BALLS] > 12 ? 0 : data[OFS_BALLS];
case Pouch::PCItem:
return data[OFS_PC_ITEMS] > 50 ? 0 : data[OFS_PC_ITEMS];
default:
return 0;
}
}
void Sav2::pouchEntryCount(Pouch pouch, u8 v)
{
switch (pouch)
{
case Pouch::NormalItem:
data[OFS_ITEMS] = v;
break;
case Pouch::KeyItem:
data[OFS_KEY_ITEMS] = v;
break;
case Pouch::Ball:
data[OFS_BALLS] = v;
break;
case Pouch::PCItem:
data[OFS_PC_ITEMS] = v;
break;
case Pouch::TM:
default:
return;
}
}
void Sav2::fixItemLists()
{
// the TM pouch has neither a terminator nor a count
u8 count = 0;
while (count < 20 && item(Pouch::NormalItem, count)->id() != 0)
{
count++;
}
pouchEntryCount(Pouch::NormalItem, count);
data[OFS_ITEMS + 1 + (count * 2)] = 0xFF;
count = 0;
while (count < 26 && item(Pouch::KeyItem, count)->id() != 0)
{
count++;
}
pouchEntryCount(Pouch::KeyItem, count);
data[OFS_KEY_ITEMS + 1 + count] = 0xFF;
count = 0;
while (count < 12 && item(Pouch::Ball, count)->id() != 0)
{
count++;
}
pouchEntryCount(Pouch::Ball, count);
data[OFS_BALLS + 1 + (count * 2)] = 0xFF;
count = 0;
while (count < 50 && item(Pouch::PCItem, count)->id() != 0)
{
count++;
}
pouchEntryCount(Pouch::PCItem, count);
data[OFS_PC_ITEMS + 1 + (count * 2)] = 0xFF;
}
}
| 36,873
|
C++
|
.cpp
| 982
| 26.641548
| 132
| 0.491208
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,228
|
Sav1.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav1.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav1.hpp"
#include "pkx/PK1.hpp"
#include "pkx/PKX.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include "utils/flagUtil.hpp"
#include "utils/i18n.hpp"
#include "utils/utils.hpp"
#include "wcx/WCX.hpp"
#include <algorithm>
#include <limits>
#include <stdlib.h>
namespace pksm
{
Sav1::Sav1(const std::shared_ptr<u8[]>& data, u32 length) : Sav(data, length)
{
// checks if two boxes are valid
japanese = ((data[0x2ED5] <= 30) && (data[0x2ED5 + 1 + data[0x2ED5]] == 0xFF)) &&
((data[0x302D] <= 30) && (data[0x302D + 1 + data[0x302D]] == 0xFF));
lang = japanese ? Language::JPN : StringUtils::guessLanguage12(otName());
maxPkmInBox = japanese ? 30 : 20;
boxSize = japanese ? 0x566 : 0x462;
mainDataLength = japanese ? 0xFFC : 0xF8B;
bankBoxesSize = boxSize * (japanese ? 4 : 6);
OFS_DEX_CAUGHT = japanese ? 0x259E : 0x25A3;
OFS_DEX_SEEN = japanese ? 0x25B1 : 0x25B6;
OFS_BAG = japanese ? 0x25C4 : 0x25C9;
OFS_MONEY = japanese ? 0x25EE : 0x25F3;
OFS_BADGES = japanese ? 0x25F8 : 0x2602;
OFS_TID = japanese ? 0x25FB : 0x2605;
OFS_PC_ITEMS = japanese ? 0x27DC : 0x27E6;
OFS_CURRENT_BOX_INDEX = japanese ? 0x2842 : 0x284C;
OFS_HOURS = japanese ? 0x2CA0 : 0x2CED;
OFS_PARTY = japanese ? 0x2ED5 : 0x2F2C;
OFS_CURRENT_BOX = japanese ? 0x302D : 0x30C0;
OFS_MAIN_DATA_SUM = japanese ? 0x3594 : 0x3523;
OFS_BANK2_BOX_SUMS = 0x4000 + bankBoxesSize;
OFS_BANK3_BOX_SUMS = 0x6000 + bankBoxesSize;
originalCurrentBox = currentBox();
}
Sav::Game Sav1::getVersion(const std::shared_ptr<u8[]>& dt)
{
// for now it doesn't matter, the only difference is Pikachu's friendship and Pikachu surf
// score
return Game::RGB;
}
// max length of string + terminator
u8 Sav1::nameLength() const
{
return japanese ? 6 : 11;
}
u8 Sav1::PK1Length() const
{
return japanese ? PK1::JP_LENGTH_WITH_NAMES : PK1::INT_LENGTH_WITH_NAMES;
}
// ctrl-v the fixparty code, boxes are expected to be contiguous
void Sav1::fixBoxes()
{
// Poor man's bubble sort-like thing
for (int i = 0; i < maxBoxes(); i++)
{
int numPkm = maxPkmInBox;
for (int j = maxPkmInBox - 1; j > 0; j--)
{
auto checkPKM = pkm(i, j);
if (checkPKM->species() == Species::None)
{
numPkm--;
continue;
}
auto prevPKM = pkm(i, j - 1);
if (checkPKM->species() != Species::None && prevPKM->species() == Species::None)
{
pkm(*checkPKM, i, j - 1, false);
pkm(*prevPKM, i, j, false);
numPkm = maxPkmInBox;
j = maxPkmInBox; // reset loop
}
}
fixBox(i);
}
}
void Sav1::finishEditing()
{
if (playedHours() == 255 && playedMinutes() == 59 && playedSeconds() == 59)
{
data[OFS_HOURS + 4] = 59; // frame count
data[OFS_HOURS + 1] = 255; // maxed out timer
}
else
{
data[OFS_HOURS + 1] = 0;
}
fixBoxes();
fixParty();
fixItemLists();
std::copy(&data[OFS_CURRENT_BOX], &data[OFS_CURRENT_BOX] + boxSize,
&data[boxStart(originalCurrentBox, false)]);
if (currentBox() != originalCurrentBox)
{
std::copy(&data[boxStart(currentBox())], &data[boxStart(currentBox())] + boxSize,
&data[OFS_CURRENT_BOX]);
}
for (int box = 0; box < maxBoxes(); box++)
{
if (box < (maxBoxes() / 2))
{
data[OFS_BANK2_BOX_SUMS + 1 + box] =
crypto::diff8({&data[boxDataStart(box, false)], boxSize});
}
else
{
data[OFS_BANK3_BOX_SUMS + 1 + (box - (maxBoxes() / 2))] =
crypto::diff8({&data[boxDataStart(box, false)], boxSize});
}
}
data[OFS_MAIN_DATA_SUM] = crypto::diff8({&data[0x2598], mainDataLength});
data[OFS_BANK2_BOX_SUMS] = crypto::diff8({&data[0x4000], bankBoxesSize});
data[OFS_BANK3_BOX_SUMS] = crypto::diff8({&data[0x6000], bankBoxesSize});
originalCurrentBox = currentBox();
}
u16 Sav1::TID() const
{
return BigEndian::convertTo<u16>(&data[OFS_TID]);
}
void Sav1::TID(u16 v)
{
BigEndian::convertFrom<u16>(&data[OFS_TID], v);
}
Language Sav1::language() const
{
return lang;
}
void Sav1::language(Language v)
{
if (lang != Language::JPN && v != Language::JPN)
{
lang = v;
}
}
// INT has space for 10 characters + terminator, but the in-game keyboard only permits 7
std::string Sav1::otName() const
{
return StringUtils::getString1(data.get(), 0x2598, japanese ? 6 : 8, lang);
}
void Sav1::otName(const std::string_view& v)
{
StringUtils::setString1(data.get(), v, 0x2598, japanese ? 6 : 8, lang);
}
// why did they use BCD
u32 Sav1::money() const
{
return BigEndian::BCDtoUInteger<u32, 3>(&data[OFS_MONEY]);
}
void Sav1::money(u32 v)
{
BigEndian::UIntegerToBCD<u32, 3>(&data[OFS_MONEY], v);
}
u8 Sav1::badges() const
{
u8 sum = 0;
u8 badgeFlags = data[OFS_BADGES];
for (int i = 0; i < 8; i++)
{
sum += (badgeFlags & (1 << i)) >> i;
}
return sum;
}
u16 Sav1::playedHours() const
{
return u16(data[OFS_HOURS]);
}
void Sav1::playedHours(u16 v)
{
data[OFS_HOURS] = u8(v);
}
u8 Sav1::playedMinutes() const
{
return data[OFS_HOURS + 2];
}
void Sav1::playedMinutes(u8 v)
{
data[OFS_HOURS + 2] = v;
}
u8 Sav1::playedSeconds() const
{
return data[OFS_HOURS + 3];
}
void Sav1::playedSeconds(u8 v)
{
data[OFS_HOURS + 3] = v;
}
u8 Sav1::currentBox() const
{
return data[OFS_CURRENT_BOX_INDEX] & 0x7F;
}
void Sav1::currentBox(u8 v)
{
data[OFS_CURRENT_BOX_INDEX] = (data[OFS_CURRENT_BOX_INDEX] & 0x80) | (v & 0x7F);
}
u32 Sav1::boxOffset(u8 box, u8 slot) const
{
return boxDataStart(box) + (slot * PK1::BOX_LENGTH);
}
u32 Sav1::boxOtNameOffset(u8 box, u8 slot) const
{
return boxDataStart(box) + (maxPkmInBox * PK1::BOX_LENGTH) + (slot * nameLength());
}
u32 Sav1::boxNicknameOffset(u8 box, u8 slot) const
{
return boxDataStart(box) + (maxPkmInBox * PK1::BOX_LENGTH) +
((maxPkmInBox + slot) * nameLength());
}
u32 Sav1::partyOffset(u8 slot) const
{
return OFS_PARTY + 8 + (slot * PK1::PARTY_LENGTH);
}
u32 Sav1::partyOtNameOffset(u8 slot) const
{
return OFS_PARTY + 8 + (6 * PK1::PARTY_LENGTH) + (slot * nameLength());
}
u32 Sav1::partyNicknameOffset(u8 slot) const
{
return OFS_PARTY + 8 + (6 * PK1::PARTY_LENGTH) + ((6 + slot) * nameLength());
}
u32 Sav1::boxStart(u8 box, bool obeyCurrentBoxMechanics) const
{
if (box == originalCurrentBox && obeyCurrentBoxMechanics)
{
return OFS_CURRENT_BOX;
}
if (box < maxBoxes() / 2)
{
return 0x4000 + (box * boxSize);
}
box -= maxBoxes() / 2;
return 0x6000 + (box * boxSize);
}
u32 Sav1::boxDataStart(u8 box, bool obeyCurrentBoxMechanics) const
{
return boxStart(box, obeyCurrentBoxMechanics) + maxPkmInBox + 2;
}
// the PK1 and PK2 formats used by the community start with magic bytes, the second being
// species
std::unique_ptr<PKX> Sav1::pkm(u8 slot) const
{
if (slot >= partyCount())
{
return emptyPkm();
}
// using the larger of the two sizes to not dynamically allocate
u8 buffer[PK1::INT_LENGTH_WITH_NAMES] = {0x01, data[partyOffset(slot)], 0xFF};
std::copy(
&data[partyOffset(slot)], &data[partyOffset(slot)] + PK1::PARTY_LENGTH, buffer + 3);
std::copy(&data[partyOtNameOffset(slot)], &data[partyOtNameOffset(slot)] + nameLength(),
buffer + 3 + PK1::PARTY_LENGTH);
std::copy(&data[partyNicknameOffset(slot)], &data[partyNicknameOffset(slot)] + nameLength(),
buffer + 3 + PK1::PARTY_LENGTH + nameLength());
StringUtils::gbStringFailsafe(buffer, 3 + PK1::PARTY_LENGTH, nameLength());
StringUtils::gbStringFailsafe(buffer, 3 + PK1::PARTY_LENGTH + nameLength(), nameLength());
auto pk1 = PKX::getPKM<Generation::ONE>(buffer, PK1Length());
if (language() != Language::JPN)
{
pk1->language(StringUtils::guessLanguage12(pk1->nickname()));
}
return pk1;
}
std::unique_ptr<PKX> Sav1::pkm(u8 box, u8 slot) const
{
if (slot >= maxPkmInBox || slot >= boxCount(box))
{
return emptyPkm();
}
u8 buffer[PK1::INT_LENGTH_WITH_NAMES] = {0x01, data[boxOffset(box, slot)], 0xFF};
std::copy(
&data[boxOffset(box, slot)], &data[boxOffset(box, slot)] + PK1::BOX_LENGTH, buffer + 3);
std::copy(&data[boxOtNameOffset(box, slot)],
&data[boxOtNameOffset(box, slot)] + nameLength(), buffer + 3 + PK1::PARTY_LENGTH);
std::copy(&data[boxNicknameOffset(box, slot)],
&data[boxNicknameOffset(box, slot)] + nameLength(),
buffer + 3 + PK1::PARTY_LENGTH + nameLength());
StringUtils::gbStringFailsafe(buffer, 3 + PK1::PARTY_LENGTH, nameLength());
StringUtils::gbStringFailsafe(buffer, 3 + PK1::PARTY_LENGTH + nameLength(), nameLength());
auto pk1 = PKX::getPKM<Generation::ONE>(buffer, PK1Length());
pk1->updatePartyData();
if (language() != Language::JPN)
{
pk1->language(StringUtils::guessLanguage12(pk1->nickname()));
}
return pk1;
}
void Sav1::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::ONE)
{
if (slot >= partyCount())
{
if (slot > partyCount())
{
pkm(*emptyPkm(), slot - 1);
}
partyCount(slot + 1);
}
auto pk1 = pk.partyClone();
std::ranges::copy(
pk1->rawData().subspan(3, PK1::PARTY_LENGTH), &data[partyOffset(slot)]);
if ((pk.language() == Language::JPN) != (language() == Language::JPN))
{
StringUtils::setString1(&data[partyNicknameOffset(slot)],
StringUtils::toUpper(pk1->species().localize(language())), 0, nameLength(),
language());
// check if it's the trade ot byte
if (pk1->rawData()[3 + PK1::PARTY_LENGTH] == 0x5D)
{
data[partyOtNameOffset(slot)] = 0x5D;
data[partyOtNameOffset(slot) + 1] = 0x50;
}
else
{
StringUtils::setString1(&data[partyOtNameOffset(slot)],
StringUtils::getTradeOT(language()), 0, nameLength(), language());
}
}
else
{
std::ranges::copy(pk1->rawData().subspan(3 + PK1::PARTY_LENGTH, nameLength()),
&data[partyOtNameOffset(slot)]);
std::ranges::copy(
pk1->rawData().subspan(3 + PK1::PARTY_LENGTH + nameLength(), nameLength()),
&data[partyNicknameOffset(slot)]);
}
}
}
void Sav1::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (slot >= maxPkmInBox)
{
return;
}
if (pk.generation() == Generation::ONE)
{
auto pk1 = pk.clone(); // note that partyClone and clone are equivalent
if (applyTrade)
{
trade(*pk1);
}
static_cast<PK1*>(pk1.get())->boxLevel(pk1->level());
if (slot >= boxCount(box))
{
if (slot > boxCount(box))
{
pkm(*emptyPkm(), box, slot - 1, false);
}
boxCount(box, slot + 1);
}
std::ranges::copy(
pk1->rawData().subspan(3, PK1::BOX_LENGTH), &data[boxOffset(box, slot)]);
if ((pk.language() == Language::JPN) != (language() == Language::JPN))
{
StringUtils::setString1(&data[boxNicknameOffset(box, slot)],
StringUtils::toUpper(pk1->species().localize(language())), 0, nameLength(),
language());
if (pk1->rawData()[3 + PK1::BOX_LENGTH] == 0x5D)
{
data[boxOtNameOffset(box, slot)] = 0x5D;
data[boxOtNameOffset(box, slot) + 1] = 0x50;
}
else
{
StringUtils::setString1(&data[boxOtNameOffset(box, slot)],
StringUtils::toUpper(StringUtils::getTradeOT(language())), 0, nameLength(),
language());
}
}
else
{
std::ranges::copy(pk1->rawData().subspan(3 + PK1::PARTY_LENGTH, nameLength()),
&data[boxOtNameOffset(box, slot)]);
std::ranges::copy(
pk1->rawData().subspan(3 + PK1::PARTY_LENGTH + nameLength(), nameLength()),
&data[boxNicknameOffset(box, slot)]);
}
}
}
std::unique_ptr<PKX> Sav1::emptyPkm() const
{
return PKX::getPKM<Generation::ONE>(nullptr, PK1Length());
}
void Sav1::dex(const PKX& pk)
{
if (!(availableSpecies().count(pk.species()) > 0))
{
return;
}
setCaught(pk.species(), true);
setSeen(pk.species(), true);
}
bool Sav1::getCaught(Species species) const
{
int flag = u8(species) - 1;
int ofs = flag >> 3;
return FlagUtil::getFlag(data.get() + OFS_DEX_CAUGHT, ofs, flag & 7);
}
void Sav1::setCaught(Species species, bool caught)
{
int flag = u8(species) - 1;
int ofs = flag >> 3;
FlagUtil::setFlag(data.get() + OFS_DEX_CAUGHT, ofs, flag & 7, caught);
}
bool Sav1::getSeen(Species species) const
{
int flag = u8(species) - 1;
int ofs = flag >> 3;
return FlagUtil::getFlag(data.get() + OFS_DEX_SEEN, ofs, flag & 7);
}
void Sav1::setSeen(Species species, bool seen)
{
int flag = u8(species) - 1;
int ofs = flag >> 3;
FlagUtil::setFlag(data.get() + OFS_DEX_SEEN, ofs, flag & 7, seen);
}
int Sav1::dexSeen() const
{
return std::count_if(availableSpecies().begin(), availableSpecies().end(),
[this](const auto& spec) { return getSeen(spec); });
}
int Sav1::dexCaught() const
{
return std::count_if(availableSpecies().begin(), availableSpecies().end(),
[this](const auto& spec) { return getCaught(spec); });
}
u8 Sav1::partyCount() const
{
return data[OFS_PARTY];
}
void Sav1::partyCount(u8 count)
{
data[OFS_PARTY] = count;
}
u8 Sav1::boxCount(u8 box) const
{
return data[boxStart(box)];
}
void Sav1::boxCount(u8 box, u8 count)
{
data[boxStart(box)] = count;
}
void Sav1::fixBox(u8 box)
{
u8 count = 0;
while (pkm(box, count)->species() != Species::None)
{
// sets the species1 in a list that the game uses for speed
data[boxStart(box) + 1 + count] = data[boxOffset(box, count)];
count++;
}
data[boxStart(box) + 1 + count] = 0xFF;
data[boxStart(box)] = count;
}
void Sav1::fixParty()
{
Sav::fixParty();
u8 count = 0;
while (pkm(count)->species() != Species::None && count < 6)
{
data[OFS_PARTY + 1 + count] = data[partyOffset(count)];
count++;
}
data[OFS_PARTY + 1 + count] = 0xFF;
data[OFS_PARTY] = count;
}
int Sav1::maxSlot() const
{
return maxBoxes() * maxPkmInBox;
}
int Sav1::maxBoxes() const
{
return japanese ? 8 : 12;
}
void Sav1::item(const Item& tItem, Pouch pouch, u16 slot)
{
if (slot < (pouch == Pouch::NormalItem ? 20 : 50))
{
Item1 item = static_cast<Item1>(tItem);
auto write = item.bytes();
switch (pouch)
{
case Pouch::NormalItem:
std::copy(write.begin(), write.end(), &data[OFS_BAG + 1 + (slot * 2)]);
break;
case Pouch::PCItem:
std::copy(write.begin(), write.end(), &data[OFS_PC_ITEMS + 1 + (slot * 2)]);
break;
default:
return;
}
}
}
std::unique_ptr<Item> Sav1::item(Pouch pouch, u16 slot) const
{
std::unique_ptr<Item1> returnVal;
switch (pouch)
{
case Pouch::NormalItem:
returnVal = std::make_unique<Item1>(&data[OFS_BAG + 1 + (slot * 2)]);
break;
case Pouch::PCItem:
returnVal = std::make_unique<Item1>(&data[OFS_PC_ITEMS + 1 + (slot * 2)]);
break;
default:
return nullptr;
}
// 0xFF is a list terminator. In a normal game state it will be in an ID slot.
if (returnVal->id1() == 0xFF)
{
return std::make_unique<Item1>(nullptr);
}
return returnVal;
}
SmallVector<std::pair<Sav::Pouch, int>, 15> Sav1::pouches() const
{
return {
std::pair{Pouch::NormalItem, 20},
std::pair{Pouch::PCItem, 50}
};
}
SmallVector<std::pair<pksm::Sav::Pouch, std::span<const int>>, 15> Sav1::validItems1() const
{
static constexpr std::array validItems = {1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48,
49, 51, 52, 53, 54, 55, 56, 57, 58, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 196, 197, 198, 199, 200, 201, 202, 203, 204,
205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221,
222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238,
239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250};
return {
std::pair{Pouch::NormalItem, std::span{validItems}},
std::pair{Pouch::PCItem, std::span{validItems}}
};
}
SmallVector<std::pair<pksm::Sav::Pouch, std::span<const int>>, 15> Sav1::validItems() const
{
static constexpr std::array validItems = {1, 2, 3, 4, 442, 450, 81, 18, 19, 20, 21, 22, 23,
24, 25, 26, 17, 78, 79, 103, 82, 83, 84, 45, 46, 47, 48, 49, 50, 102, 101, 872, 60, 85,
876, 92, 63, 27, 28, 29, 55, 76, 77, 56, 30, 31, 32, 873, 877, 57, 58, 59, 61, 444, 875,
471, 874, 651, 878, 216, 445, 446, 447, 51, 38, 39, 40, 41, 420, 421, 422, 423, 424,
328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361,
362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377};
return {
std::pair{Pouch::NormalItem, std::span{validItems}},
std::pair{Pouch::PCItem, std::span{validItems}}
};
}
void Sav1::fixItemLists()
{
u8 count = 0;
while (count < 20 && item(Pouch::NormalItem, count)->id() != 0)
{
count++;
}
data[OFS_BAG] = count;
data[OFS_BAG + 1 + (count * 2)] = 0xFF;
count = 0;
while (count < 50 && item(Pouch::PCItem, count)->id() != 0)
{
count++;
}
data[OFS_PC_ITEMS] = count;
data[OFS_PC_ITEMS + 1 + (count * 2)] = 0xFF;
}
}
| 22,304
|
C++
|
.cpp
| 597
| 27.874372
| 100
| 0.530269
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,229
|
SavLGPE.cpp
|
FlagBrew_PKSM-Core/source/sav/SavLGPE.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavLGPE.hpp"
#include "pkx/PB7.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include "utils/i18n.hpp"
#include "utils/random.hpp"
#include "utils/utils.hpp"
#include "wcx/WB7.hpp"
#include <algorithm>
#include <bit>
namespace
{
bool isPKM(u8* pkmData)
{
if (LittleEndian::convertTo<u16>(pkmData + 8) == 0)
{
return false;
}
return true;
}
}
namespace pksm
{
SavLGPE::SavLGPE(const std::shared_ptr<u8[]>& dt, size_t length) : Sav(dt, length)
{
game = Game::LGPE;
PokeDex = 0x2A00;
}
u32 SavLGPE::boxOffset(u8 box, u8 slot) const
{
return 0x5C00 + box * 30 * PB7::PARTY_LENGTH + slot * PB7::PARTY_LENGTH;
}
u16 SavLGPE::partyBoxSlot(u8 slot) const
{
return LittleEndian::convertTo<u16>(&data[0x5A00 + slot * 2]);
}
void SavLGPE::partyBoxSlot(u8 slot, u16 v)
{
LittleEndian::convertFrom<u16>(&data[0x5A00 + slot * 2], v);
}
u32 SavLGPE::partyOffset(u8 slot) const
{
u16 boxSlot = partyBoxSlot(slot);
if (boxSlot == 1001)
{
return 0;
}
return boxOffset(boxSlot / 30, boxSlot % 30);
}
u16 SavLGPE::boxedPkm() const
{
return LittleEndian::convertTo<u16>(&data[0x5A00 + 14]);
}
void SavLGPE::boxedPkm(u16 v)
{
LittleEndian::convertFrom<u16>(&data[0x5A00 + 14], v);
}
u16 SavLGPE::followPkm() const
{
return LittleEndian::convertTo<u16>(&data[0x5A00 + 12]);
}
void SavLGPE::followPkm(u16 v)
{
LittleEndian::convertFrom<u16>(&data[0x5A00 + 12], v);
}
u8 SavLGPE::partyCount() const
{
u16 ret = 0;
for (int i = 0; i < 6; i++)
{
if (partyBoxSlot(i) != 1001)
{
ret++;
}
}
return ret;
}
void SavLGPE::partyCount(u8) {}
void SavLGPE::fixParty()
{
for (int i = 0; i < 5; i++)
{
if (partyBoxSlot(i) == 1001 && partyBoxSlot(i + 1) != 1001)
{
partyBoxSlot(i, partyBoxSlot(i + 1));
partyBoxSlot(i + 1, 1001);
i = -1;
}
}
}
void SavLGPE::compressBox()
{
u16 emptyIndex = 1001;
u8 emptyData[PB7::PARTY_LENGTH] = {0};
for (u16 i = 0; i < 1000; i++)
{
u32 offset = boxOffset(i / 30, i % 30);
if (emptyIndex == 1001 && !isPKM(&data[offset]))
{
emptyIndex = i;
}
else if (emptyIndex != 1001)
{
if (isPKM(&data[offset]))
{
u32 emptyOffset = boxOffset(emptyIndex / 30, emptyIndex % 30);
// Swap the two slots
std::copy(
&data[emptyOffset], &data[emptyOffset + PB7::PARTY_LENGTH], emptyData);
std::copy(&data[offset], &data[offset + PB7::PARTY_LENGTH], &data[emptyOffset]);
std::copy(emptyData, emptyData + PB7::PARTY_LENGTH, &data[offset]);
for (int j = 0; j < partyCount(); j++)
{
if (partyBoxSlot(j) == i)
{
partyBoxSlot(j, emptyIndex);
}
}
if (followPkm() == i)
{
followPkm(emptyIndex);
}
emptyIndex++;
}
}
}
}
void SavLGPE::resign()
{
const u8 blockCount = 21;
const u32 csoff = 0xB861A;
for (u8 i = 0; i < blockCount; i++)
{
LittleEndian::convertFrom<u16>(
&data[csoff + i * 8], pksm::crypto::crc16_noinvert({&data[chkofs[i]], chklen[i]}));
}
}
u16 SavLGPE::TID() const
{
return LittleEndian::convertTo<u16>(&data[0x1000]);
}
void SavLGPE::TID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[0x1000], v);
}
u16 SavLGPE::SID() const
{
return LittleEndian::convertTo<u16>(&data[0x1002]);
}
void SavLGPE::SID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[0x1002], v);
}
GameVersion SavLGPE::version() const
{
return GameVersion(data[0x1004]);
}
void SavLGPE::version(GameVersion v)
{
data[0x1004] = u8(v);
}
Gender SavLGPE::gender() const
{
return Gender{data[0x1005]};
}
void SavLGPE::gender(Gender v)
{
data[0x1005] = u8(v);
}
Language SavLGPE::language() const
{
return Language(data[0x1035]);
}
void SavLGPE::language(Language v)
{
data[0x1035] = u8(v);
}
std::string SavLGPE::otName() const
{
return StringUtils::getString(data.get(), 0x1000 + 0x38, 13);
}
void SavLGPE::otName(const std::string_view& v)
{
StringUtils::setString(data.get(), v, 0x1000 + 0x38, 13);
}
u32 SavLGPE::money() const
{
return LittleEndian::convertTo<u32>(&data[0x4C04]);
}
void SavLGPE::money(u32 v)
{
LittleEndian::convertFrom<u32>(&data[0x4C04], v);
}
u8 SavLGPE::badges() const
{
// struct
// {
// u8 unimportant1 : 4;
// u8 b1 : 1;
// u8 b2 : 1;
// u8 b3 : 1;
// u8 b4 : 1;
// u8 b5 : 1;
// u8 b6 : 1;
// u8 b7 : 1;
// u8 b8 : 1;
// u8 unimportant2 : 4;
// } badgeBits;
u8 badges = (LittleEndian::convertTo<u16>(&data[0x21b1]) >> 4) & 0xFF;
return std::popcount(badges);
}
u16 SavLGPE::playedHours(void) const
{
return LittleEndian::convertTo<u16>(&data[0x45400]);
}
void SavLGPE::playedHours(u16 v)
{
LittleEndian::convertFrom<u16>(&data[0x45400], v);
}
u8 SavLGPE::playedMinutes(void) const
{
return data[0x45402];
}
void SavLGPE::playedMinutes(u8 v)
{
data[0x45402] = v;
}
u8 SavLGPE::playedSeconds(void) const
{
return data[0x45403];
}
void SavLGPE::playedSeconds(u8 v)
{
data[0x45403] = v;
}
std::unique_ptr<PKX> SavLGPE::pkm(u8 slot) const
{
u32 off = partyOffset(slot);
if (off != 0)
{
return PKX::getPKM<Generation::LGPE>(&data[off], PB7::PARTY_LENGTH);
}
else
{
return emptyPkm();
}
}
std::unique_ptr<PKX> SavLGPE::pkm(u8 box, u8 slot) const
{
return PKX::getPKM<Generation::LGPE>(&data[boxOffset(box, slot)], PB7::PARTY_LENGTH);
}
void SavLGPE::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (pk.generation() == Generation::LGPE)
{
auto pb7 = pk.partyClone();
if (applyTrade)
{
trade(*pb7);
}
std::ranges::copy(
pb7->rawData().subspan(0, PB7::PARTY_LENGTH), &data[boxOffset(box, slot)]);
}
}
void SavLGPE::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::LGPE)
{
u32 off = partyOffset(slot);
u16 newSlot = partyBoxSlot(slot);
if (pk.species() == Species::None)
{
if (off != 0)
{
std::fill_n(&data[off], PB7::PARTY_LENGTH, 0);
}
partyBoxSlot(slot, 1001);
return;
}
if (off == 0)
{
for (int i = 999; i >= 0; i--)
{
if (!isPKM(&data[0x5C00 + i * PB7::PARTY_LENGTH]))
{
off = boxOffset(i / 30, i % 30);
newSlot = i;
break;
}
}
if (off == 0)
{
return;
}
}
auto pb7 = pk.partyClone();
std::ranges::copy(pb7->rawData().subspan(0, PB7::PARTY_LENGTH), &data[off]);
partyBoxSlot(slot, newSlot);
}
}
void SavLGPE::trade(PKX& pk, const Date& date) const
{
if (pk.generation() == Generation::LGPE)
{
PB7& pb7 = static_cast<PB7&>(pk);
if (pb7.egg() && !(otName() == pb7.otName() && TID() == pb7.TID() &&
SID() == pb7.SID() && gender() == pb7.otGender()))
{
pb7.metLocation(30002);
pb7.metDate(date);
}
else if (!(otName() == pb7.otName() && TID() == pb7.TID() && SID() == pb7.SID() &&
gender() == pb7.otGender()))
{
pb7.currentHandler(PKXHandler::OT);
}
else
{
if (pb7.htName() != otName())
{
pb7.htFriendship(pb7.currentFriendship()); // copy friendship instead of
// resetting (don't alter CP)
}
pb7.currentHandler(PKXHandler::NonOT);
pb7.htName(otName());
pb7.htGender(gender());
}
}
}
std::unique_ptr<PKX> SavLGPE::emptyPkm() const
{
return PKX::getPKM<Generation::LGPE>(nullptr, PB7::PARTY_LENGTH);
}
int SavLGPE::dexFormCount(int species) const
{
for (int i = 0; i < 62; i += 2)
{
if (formtable[i] == species)
{
return formtable[i + 1];
}
else if (formtable[i] > species)
{
return 0;
}
}
return 0;
}
int SavLGPE::dexFormIndex(int species, int formct, int start) const
{
int formindex = start;
int f = 0;
for (int i = 0; i < 62; i += 2)
{
if (formtable[i] == species)
{
break;
}
f = formtable[i + 1];
formindex += f - 1;
}
return f > formct ? -1 : formindex;
}
bool SavLGPE::sanitizeFormsToIterate(Species species, int& fs, int& fe, int formIn) const
{
switch (species)
{
case Species::Raticate: // 20:
case Species::Marowak: // 105:
fs = 0;
fe = 1;
return true;
default:
int count = dexFormCount(u16(species));
fs = fe = 0;
return count < formIn;
}
}
void SavLGPE::setDexFlags(int index, int gender, int shiny, int baseSpecies)
{
const int brSize = 0x8C;
int shift = gender | (shiny << 1);
int off = 0x2AF0;
int bd = index >> 3;
int bm = index & 7;
int bd1 = baseSpecies >> 3;
int bm1 = baseSpecies & 7;
int brSeen = shift * brSize;
data[off + brSeen + bd] |= (u8)(1 << bm);
bool displayed = false;
for (u8 i = 0; i < 4; i++)
{
int brDisplayed = (4 + i) * brSize;
displayed |= (data[off + brDisplayed + bd1] & (1 << bm1)) != 0;
}
if (!displayed && baseSpecies != index)
{
for (u8 i = 0; i < 4; i++)
{
int brDisplayed = (4 + i) * brSize;
displayed |= (data[off + brDisplayed + bd] & (1 << bm)) != 0;
}
}
if (displayed)
{
return;
}
data[off + (4 + shift) * brSize + bd] |= (1 << bm);
}
int SavLGPE::getDexFlags(int index, int baseSpecies) const
{
int ret = 0;
const int brSize = 0x8C;
int ofs = PokeDex + 0x08 + 0x80 + 0x68;
int bd = index >> 3;
int bm = index & 7;
int bd1 = baseSpecies >> 3;
int bm1 = baseSpecies & 7;
for (u8 i = 0; i < 4; i++)
{
if (data[ofs + i * brSize + bd] & (1 << bm))
{
ret++;
}
if (data[ofs + i * brSize + bd1] & (1 << bm1))
{
ret++;
}
}
return ret;
}
void SavLGPE::dex(const PKX& pk)
{
int n = u16(pk.species());
int MaxSpeciesID = 809;
int PokeDex = 0x2A00;
int PokeDexLanguageFlags = PokeDex + 0x550;
if (!(availableSpecies().count(pk.species()) > 0) || pk.egg())
{
return;
}
int bit = n - 1;
int bd = bit >> 3;
int bm = bit & 7;
int gender = u8(pk.gender()) % 2;
int shiny = pk.shiny() ? 1 : 0;
if (n == 351)
{
shiny = 0;
}
int shift = gender | (shiny << 1);
if (n == 327) // Spinda
{
if ((data[PokeDex + 0x84] & (1 << (shift + 4))) != 0)
{ // Already 2
LittleEndian::convertFrom<u32>(
&data[PokeDex + 0x8E8 + shift * 4], pk.encryptionConstant());
data[PokeDex + 0x84] |= (u8)(1 << shift);
}
else if ((data[PokeDex + 0x84] & (1 << shift)) == 0)
{ // Not yet 1
data[PokeDex + 0x84] |= (u8)(1 << shift); // 1
}
}
int off = PokeDex + 0x08 + 0x80;
data[off + bd] |= (1 << bm);
int formstart = pk.alternativeForm();
int formend = formstart;
int fs = 0, fe = 0;
if (sanitizeFormsToIterate(Species{u16(n)}, fs, fe, formstart))
{
formstart = fs;
formend = fe;
}
for (int form = formstart; form <= formend; form++)
{
int bitIndex = bit;
if (form > 0)
{
u8 fc = dexFormCount(n);
if (fc > 1)
{ // actually has forms
int f = dexFormIndex(n, fc, MaxSpeciesID - 1);
if (f >= 0)
{ // bit index valid
bitIndex = f + form;
}
}
}
setDexFlags(bitIndex, gender, shiny, n - 1);
}
int lang = u8(pk.language());
const int langCount = 9;
if (lang <= 10 && lang != 6 && lang != 0)
{
if (lang >= 7)
{
lang--;
}
lang--;
if (lang < 0)
{
lang = 1;
}
int lbit = bit * langCount + lang;
if (lbit >> 3 < 920)
{
data[PokeDexLanguageFlags + (lbit >> 3)] |= (u8)(1 << (lbit & 7));
}
}
}
int SavLGPE::dexSeen(void) const
{
int ret = 0;
for (const auto& species : availableSpecies())
{
int forms = formCount(species);
for (int form = 0; form < forms; form++)
{
int dexForms = form == 0 ? -1
: dexFormIndex(u16(species), forms,
u16(VersionTables::maxSpecies(version())) - 1);
int index = u16(species) - 1;
if (dexForms >= 0)
{
index = dexForms + form;
}
if (getDexFlags(index, u16(species)) > 0)
{
ret++;
break;
}
}
}
return ret;
}
int SavLGPE::dexCaught(void) const
{
int ret = 0;
for (const auto& species : availableSpecies())
{
if (data[PokeDex + 0x88 + (u16(species) - 1) / 8] & (1 << ((u16(species) - 1) % 8)))
{
ret++;
}
}
return ret;
}
void SavLGPE::cryptBoxData(bool crypted)
{
for (u8 box = 0; box < maxBoxes(); box++)
{
for (u8 slot = 0; slot < 30; slot++)
{
if (box * 30 + slot > 1000)
{
return;
}
std::unique_ptr<PKX> pb7 = PKX::getPKM<Generation::LGPE>(
&data[boxOffset(box, slot)], PB7::PARTY_LENGTH, true);
if (!crypted)
{
pb7->encrypt();
}
}
}
}
void SavLGPE::mysteryGift(const WCX& wc, int&)
{
if (wc.generation() == Generation::LGPE)
{
const WB7& wb7 = static_cast<const WB7&>(wc);
if (wb7.pokemon())
{
if (boxedPkm() == maxSlot())
{
return;
}
auto pb7 = PKX::getPKM<Generation::LGPE>(nullptr, PB7::BOX_LENGTH);
pb7->species(wb7.species());
pb7->alternativeForm(wb7.alternativeForm());
if (wb7.level() > 0)
{
pb7->level(wb7.level());
}
else
{
pb7->level(pksm::randomNumber(1, 100));
}
if (wb7.metLevel() > 0)
{
pb7->metLevel(wb7.metLevel());
}
else
{
pb7->metLevel(pb7->level());
}
pb7->TID(wb7.TID());
pb7->SID(wb7.SID());
for (int i = 0; i < 4; i++)
{
pb7->move(i, wb7.move(i));
pb7->relearnMove(i, wb7.move(i));
}
if (wb7.nature() == Nature::INVALID)
{
pb7->nature(Nature{u8(pksm::randomNumber(0, 24))});
}
else
{
pb7->nature(wb7.nature());
}
if (u8(wb7.gender()) == 3) // Invalid gender value
{
pb7->gender(PKX::genderFromRatio(pksm::randomNumber(0, 0xFFFFFFFF),
PersonalLGPE::gender(u16(wb7.species()))));
}
else
{
pb7->gender(wb7.gender());
}
pb7->heldItem(wb7.heldItem());
pb7->encryptionConstant(wb7.encryptionConstant());
if (wb7.version() != GameVersion::INVALID)
{
pb7->version(wb7.version());
}
else
{
pb7->version(version());
}
pb7->language(language());
pb7->ball(wb7.ball());
pb7->metLocation(wb7.metLocation());
pb7->eggLocation(wb7.eggLocation());
for (int i = 0; i < 6; i++)
{
pb7->awakened(Stat(i), wb7.awakened(Stat(i)));
pb7->ev(Stat(i), wb7.ev(Stat(i)));
}
if (wb7.nickname(language()).length() == 0)
{
pb7->nickname(pb7->species().localize(language()));
}
else
{
pb7->nickname(wb7.nickname(language()));
pb7->nicknamed(pb7->nickname() != pb7->species().localize(language()));
}
if (wb7.otName(language()).length() == 0)
{
pb7->otName(otName());
pb7->otGender(gender());
pb7->currentHandler(PKXHandler::OT);
}
else
{
pb7->otName(wb7.otName(language()));
pb7->htName(otName());
pb7->otGender(wb7.otGender());
pb7->htGender(gender());
pb7->otFriendship(PersonalLGPE::baseFriendship(pb7->formSpecies()));
pb7->currentHandler(PKXHandler::NonOT);
}
int numPerfectIVs = 0;
for (Stat stat :
{Stat::HP, Stat::ATK, Stat::DEF, Stat::SPD, Stat::SPATK, Stat::SPDEF})
{
if (wb7.iv(stat) - 0xFC < 3)
{
numPerfectIVs = wb7.iv(stat) - 0xFB;
break;
}
}
for (int iv = 0; iv < numPerfectIVs; iv++)
{
Stat setMeTo31 = Stat(pksm::randomNumber(0, 5));
while (pb7->iv(setMeTo31) == 31)
{
setMeTo31 = Stat(pksm::randomNumber(0, 5));
}
pb7->iv(setMeTo31, 31);
}
for (Stat stat :
{Stat::HP, Stat::ATK, Stat::DEF, Stat::SPD, Stat::SPATK, Stat::SPDEF})
{
if (pb7->iv(stat) != 31)
{
pb7->iv(stat, pksm::randomNumber(0, 31));
}
}
if (u16(wb7.otGender()) == 3)
{
pb7->TID(TID());
pb7->SID(SID());
}
// Sets the ability to the one specific to the formSpecies and sets abilitynumber
// (Why? Don't quite understand that)
switch (wb7.abilityType())
{
case 0:
case 1:
case 2:
pb7->setAbility(wb7.abilityType());
break;
case 3:
case 4:
pb7->setAbility(pksm::randomNumber(0, wb7.abilityType() - 2));
break;
}
switch (wb7.PIDType())
{
case 0: // Fixed value
pb7->PID(wb7.PID());
break;
case 1: // Random
pb7->PID(pksm::randomNumber(0, 0xFFFFFFFF));
break;
case 2: // Always shiny
pb7->PID(pksm::randomNumber(0, 0xFFFFFFFF));
pb7->shiny(true);
break;
case 3: // Never shiny
pb7->PID(pksm::randomNumber(0, 0xFFFFFFFF));
pb7->shiny(false);
break;
}
if (wb7.egg())
{
pb7->egg(true);
pb7->eggDate(wb7.date());
pb7->nickname(pb7->species().localize(language()));
pb7->nicknamed(true);
}
pb7->metDate(wb7.date());
pb7->currentFriendship(PersonalLGPE::baseFriendship(pb7->formSpecies()));
pb7->height(pksm::randomNumber(0, 255));
pb7->weight(pksm::randomNumber(0, 255));
pb7->fatefulEncounter(true);
pb7->refreshChecksum();
pkm(*pb7, boxedPkm());
boxedPkm(this->boxedPkm() + 1);
}
else if (wb7.item())
{
auto valid = validItems();
auto limits = pouches();
for (int itemNum = 0; itemNum < wb7.items(); itemNum++)
{
bool currentSet = false;
for (size_t pouch = 0; pouch < limits.size(); pouch++)
{
auto validPouch = std::ranges::find_if(valid,
[&](const auto& i) {
return i.first == limits[pouch].first;
})->second;
// Check this is the correct pouch
if (!currentSet && std::binary_search(validPouch.begin(), validPouch.end(),
wb7.object(itemNum)))
{
for (int slot = 0; slot < limits[pouch].second; slot++)
{
auto occupying = item(limits[pouch].first, slot);
if (occupying->id() == 0)
{
occupying->id(wb7.object(itemNum));
occupying->count(wb7.objectQuantity(itemNum));
static_cast<Item7b*>(occupying.get())->newFlag(true);
item(*occupying, limits[pouch].first, slot);
currentSet = true;
break;
}
else if (occupying->id() == wb7.object(itemNum) &&
limits[pouch].first != Pouch::TM)
{
occupying->count(occupying->count() + 1);
item(*occupying, limits[pouch].first, slot);
currentSet = true;
break;
}
}
}
}
}
}
}
}
void SavLGPE::item(const Item& item, Pouch pouch, u16 slot)
{
Item7b item7b = static_cast<Item7b>(item);
auto write = item7b.bytes();
switch (pouch)
{
case Pouch::Medicine:
if (slot < 60)
{
std::copy(write.begin(), write.end(), &data[slot * 4]);
}
break;
case Pouch::TM:
if (slot < 108)
{
std::copy(write.begin(), write.end(), &data[0xF0 + slot * 4]);
}
break;
case Pouch::Candy:
if (slot < 200)
{
std::copy(write.begin(), write.end(), &data[0x2A0 + slot * 4]);
}
break;
case Pouch::ZCrystals:
if (slot < 150)
{
std::copy(write.begin(), write.end(), &data[0x5C0 + slot * 4]);
}
break;
case Pouch::CatchingItem:
if (slot < 50)
{
std::copy(write.begin(), write.end(), &data[0x818 + slot * 4]);
}
break;
case Pouch::Battle:
if (slot < 150)
{
std::copy(write.begin(), write.end(), &data[0x8E0 + slot * 4]);
}
break;
case Pouch::KeyItem:
case Pouch::NormalItem:
if (slot < 150)
{
std::copy(write.begin(), write.end(), &data[0xB38 + slot * 4]);
}
break;
default:
break;
}
}
std::unique_ptr<Item> SavLGPE::item(Pouch pouch, u16 slot) const
{
switch (pouch)
{
case Pouch::Medicine:
return std::make_unique<Item7b>(&data[slot * 4]);
case Pouch::TM:
return std::make_unique<Item7b>(&data[0xF0 + slot * 4]);
case Pouch::Candy:
return std::make_unique<Item7b>(&data[0x2A0 + slot * 4]);
case Pouch::ZCrystals:
return std::make_unique<Item7b>(&data[0x5C0 + slot * 4]);
case Pouch::CatchingItem:
return std::make_unique<Item7b>(&data[0x818 + slot * 4]);
case Pouch::Battle:
return std::make_unique<Item7b>(&data[0x8E0 + slot * 4]);
case Pouch::KeyItem:
case Pouch::NormalItem:
return std::make_unique<Item7b>(&data[0xB38 + slot * 4]);
default:
return nullptr;
}
}
std::unique_ptr<WCX> SavLGPE::mysteryGift(int) const
{
return nullptr;
}
SmallVector<std::pair<Sav::Pouch, int>, 15> SavLGPE::pouches() const
{
return {
std::pair{Pouch::Medicine, 60 },
std::pair{Pouch::TM, 108},
std::pair{Pouch::Candy, 200},
std::pair{Pouch::ZCrystals, 150},
std::pair{Pouch::CatchingItem, 50 },
std::pair{Pouch::Battle, 150},
std::pair{Pouch::NormalItem, 150}
};
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavLGPE::validItems() const
{
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 38, 39, 40, 41, 709, 903};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387};
static constexpr std::array Candy = {50, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969,
970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986,
987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003,
1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017,
1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031,
1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045,
1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057};
static constexpr std::array ZCrystals = {51, 53, 81, 82, 83, 84, 85, 849};
static constexpr std::array CatchingItem = {
1, 2, 3, 4, 12, 164, 166, 168, 861, 862, 863, 864, 865, 866};
static constexpr std::array Battle = {55, 56, 57, 58, 59, 60, 61, 62, 656, 659, 660, 661,
662, 663, 671, 672, 675, 676, 678, 679, 760, 762, 770, 773};
static constexpr std::array NormalItem = {76, 77, 78, 79, 86, 87, 88, 89, 90, 91, 92, 93,
101, 102, 103, 113, 115, 121, 122, 123, 124, 125, 126, 127, 128, 442, 571, 632, 651,
795, 796, 872, 873, 874, 875, 876, 877, 878, 885, 886, 887, 888, 889, 890, 891, 892,
893, 894, 895, 896, 900, 901, 902};
return {
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Candy, std::span{Candy} },
std::pair{Pouch::ZCrystals, std::span{ZCrystals} },
std::pair{Pouch::CatchingItem, std::span{CatchingItem}},
std::pair{Pouch::Battle, std::span{Battle} },
std::pair{Pouch::NormalItem, std::span{NormalItem} }
};
}
}
| 33,084
|
C++
|
.cpp
| 939
| 22.075612
| 100
| 0.432328
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,230
|
SavORAS.cpp
|
FlagBrew_PKSM-Core/source/sav/SavORAS.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavORAS.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include <algorithm>
namespace pksm
{
SavORAS::SavORAS(const std::shared_ptr<u8[]>& dt) : Sav6(dt, 0x76000)
{
game = Game::ORAS;
TrainerCard = 0x14000;
Trainer2 = 0x04200;
PlayTime = 0x1800;
Box = 0x33000;
Party = 0x14200;
PokeDex = 0x15000;
PokeDexLanguageFlags = 0x15400;
EncounterCount = 0x15686;
WondercardData = 0x1CD00;
WondercardFlags = 0x1CC00;
PCLayout = 0x4400;
LastViewedBox = 0x483F;
PouchHeldItem = 0x400;
PouchKeyItem = 0xA40;
PouchTMHM = 0xBC0;
PouchMedicine = 0xD70;
PouchBerry = 0xE70;
}
void SavORAS::resign(void)
{
static constexpr u8 blockCount = 58;
static constexpr u32 csoff = 0x75E1A;
for (u8 i = 0; i < blockCount; i++)
{
LittleEndian::convertFrom<u16>(
&data[csoff + i * 8], pksm::crypto::ccitt16({&data[chkofs[i]], chklen[i]}));
}
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavORAS::validItems() const
{
static constexpr std::array NormalItem = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 116, 117, 118, 119, 135, 136,
213, 214, 215, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230,
231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281,
282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298,
299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315,
316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 492, 493, 494, 495, 496,
497, 498, 499, 500, 534, 535, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547,
548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564,
571, 572, 573, 576, 577, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 639,
640, 644, 646, 647, 648, 649, 650, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661,
662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678,
679, 680, 681, 682, 683, 684, 685, 699, 704, 710, 711, 715, 752, 753, 754, 755, 756,
757, 758, 759, 760, 761, 762, 763, 764, 767, 768, 769, 770};
static constexpr std::array KeyItem = {216, 431, 442, 445, 446, 447, 450, 457, 465, 466,
471, 474, 503, 628, 629, 631, 632, 638, 641, 642, 643, 689, 695, 696, 697, 698, 700,
701, 702, 703, 705, 712, 713, 714, 718, 719, 720, 721, 722, 724, 725, 726, 727, 728,
729, 730, 731, 732, 733, 734, 735, 736, 738, 739, 740, 741, 742, 743, 744, 751, 765,
771, 772, 774, 775};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 618, 619, 620, 690,
691, 692, 693, 694, 420, 421, 422, 423, 424, 425, 737};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 65, 66, 67, 134, 504, 565, 566, 567, 568, 569, 570, 571, 591, 645, 708,
709};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212, 686, 687, 688};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} }
};
}
}
| 6,534
|
C++
|
.cpp
| 112
| 50.0625
| 100
| 0.559938
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,231
|
SavRS.cpp
|
FlagBrew_PKSM-Core/source/sav/SavRS.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62, Pk11
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavRS.hpp"
namespace pksm
{
SavRS::SavRS(const std::shared_ptr<u8[]>& dt) : Sav3(dt, {0x44, 0x938, 0xC0C})
{
game = Game::RS;
OFS_PCItem = blockOfs[1] + 0x0498;
OFS_PouchHeldItem = blockOfs[1] + 0x0560;
OFS_PouchKeyItem = blockOfs[1] + 0x05B0;
OFS_PouchBalls = blockOfs[1] + 0x0600;
OFS_PouchTMHM = blockOfs[1] + 0x0640;
OFS_PouchBerry = blockOfs[1] + 0x0740;
eventFlag = blockOfs[2] + 0x2A0;
// EventConst = EventFlag + (EventFlagMax / 8);
// DaycareOffset = blockOfs[4] + 0x11C;
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavRS::validItems() const
{
static constexpr std::array<int, 273> validItems = {// Normal items
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 65, 66, 67, 68, 69, 43, 44, 70, 71, 72, 73, 74, 75, 45, 46, 47, 48, 49,
50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 61, 63, 64, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227,
228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244,
245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
262, 263, 264,
// Balls
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
// TMs
328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361,
362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377,
// Berries
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182,
183, 201, 202, 203, 204, 205, 206, 207, 208,
// Key items
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128};
return {
std::pair{Pouch::NormalItem, std::span{validItems.begin(), validItems.begin() + 139} },
std::pair{Pouch::Ball, std::span{validItems.begin() + 139, validItems.begin() + 151}},
std::pair{Pouch::TM, std::span{validItems.begin() + 151, validItems.begin() + 201}},
std::pair{Pouch::Berry, std::span{validItems.begin() + 201, validItems.begin() + 244}},
std::pair{Pouch::KeyItem, std::span{validItems.begin() + 244, validItems.end()} },
std::pair{Pouch::PCItem, std::span{validItems} }
};
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavRS::validItems3() const
{
static constexpr std::array validItems = {// Normal
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 63, 64, 65, 66, 67,
68, 69, 70, 71, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 93, 94, 95, 96, 97,
98, 103, 104, 106, 107, 108, 109, 110, 111, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192,
193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 254,
255, 256, 257, 258,
// Ball
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
// TM
289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305,
306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322,
323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339,
340, 341, 342, 343, 344, 345, 346,
// Berry
133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166,
167, 168, 169, 170, 171, 172, 173, 174, 175,
// Key
259, 260, 261, 262, 263, 264, 265, 266, 268, 269, 270, 271, 272, 273, 274, 275, 276,
277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288};
return {
std::pair{Pouch::NormalItem, std::span{validItems.begin(), validItems.begin() + 139} },
std::pair{Pouch::Ball, std::span{validItems.begin() + 139, validItems.begin() + 151}},
std::pair{Pouch::TM, std::span{validItems.begin() + 151, validItems.begin() + 209}},
std::pair{Pouch::Berry, std::span{validItems.begin() + 209, validItems.begin() + 252}},
std::pair{Pouch::KeyItem, std::span{validItems.begin() + 252, validItems.end()} },
std::pair{Pouch::PCItem, std::span{validItems} }
};
}
}
| 6,739
|
C++
|
.cpp
| 109
| 52.908257
| 104
| 0.552834
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,232
|
Sav3.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav3.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav3.hpp"
#include "pkx/PK3.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include "utils/flagUtil.hpp"
#include "utils/i18n.hpp"
#include "utils/utils.hpp"
#include "wcx/WCX.hpp"
#include <algorithm>
#include <limits>
#include <stdlib.h>
namespace pksm
{
void Sav3::loadBlocks()
{
std::array<int, BLOCK_COUNT> o1 = getBlockOrder(data, 0);
// I removed a length > 0x10000, since length should always be 0x20000 I think that's fine?
std::array<int, BLOCK_COUNT> o2 = getBlockOrder(data, 0xE000);
activeSAV = getActiveSaveIndex(data, o1, o2);
blockOrder = activeSAV == 0 ? o1 : o2;
for (int i = 0; i < BLOCK_COUNT; i++)
{
unsigned int index = std::distance(
blockOrder.begin(), std::find(blockOrder.begin(), blockOrder.end(), i));
blockOfs[i] = index == blockOrder.size() ? std::numeric_limits<int>::min()
: (index * SIZE_BLOCK) + ABO();
}
}
std::array<int, Sav3::BLOCK_COUNT> Sav3::getBlockOrder(const std::shared_ptr<u8[]>& dt, int ofs)
{
std::array<int, BLOCK_COUNT> order;
for (int i = 0; i < BLOCK_COUNT; i++)
{
order[i] = LittleEndian::convertTo<s16>(&dt[ofs + (i * SIZE_BLOCK) + 0xFF4]);
}
return order;
}
int Sav3::getActiveSaveIndex(const std::shared_ptr<u8[]>& dt,
std::array<int, BLOCK_COUNT>& blockOrder1, std::array<int, BLOCK_COUNT>& blockOrder2)
{
int zeroBlock1 = std::find(blockOrder1.begin(), blockOrder1.end(), 0) - blockOrder1.begin();
int zeroBlock2 = std::find(blockOrder2.begin(), blockOrder2.end(), 0) - blockOrder2.begin();
if (size_t(zeroBlock2) == blockOrder2.size())
{
return 0;
}
if (size_t(zeroBlock1) == blockOrder1.size())
{
return 1;
}
u32 count1 = LittleEndian::convertTo<u32>(&dt[(zeroBlock1 * SIZE_BLOCK) + 0x0FFC]);
u32 count2 = LittleEndian::convertTo<u32>(&dt[(zeroBlock2 * SIZE_BLOCK) + 0xEFFC]);
return count1 > count2 ? 0 : 1;
}
Sav::Game Sav3::getVersion(const std::shared_ptr<u8[]>& dt)
{
// Get block 0 offset
std::array<int, BLOCK_COUNT> o1 = getBlockOrder(dt, 0);
std::array<int, BLOCK_COUNT> o2 = getBlockOrder(dt, BLOCK_COUNT * SIZE_BLOCK);
int activeSAV = getActiveSaveIndex(dt, o1, o2);
std::array<int, BLOCK_COUNT>& order = activeSAV == 0 ? o1 : o2;
int ABO = activeSAV * SIZE_BLOCK * BLOCK_COUNT;
int blockOfs0 =
((std::find(order.begin(), order.end(), 0) - order.begin()) * SIZE_BLOCK) + ABO;
// Get version
u32 gameCode = LittleEndian::convertTo<u32>(&dt[blockOfs0 + 0xAC]);
switch (gameCode)
{
case 1:
return Game::FRLG; // fixed value
case 0:
return Game::RS; // no battle tower record data
default:
// Ruby doesn't set data as far down as Emerald.
// 00 FF 00 00 00 00 00 00 00 FF 00 00 00 00 00 00
// ^ byte pattern in Emerald saves, is all zero in Ruby/Sapphire as far as I can
// tell. Some saves have had data @ 0x550
if (LittleEndian::convertTo<u64>(&dt[blockOfs0 + 0xEE0]) != 0)
{
return Game::E;
}
if (LittleEndian::convertTo<u64>(&dt[blockOfs0 + 0xEE8]) != 0)
{
return Game::E;
}
return Game::RS;
}
}
Sav3::Sav3(const std::shared_ptr<u8[]>& dt, SmallVector<int, 3>&& flagOffsets)
: Sav(dt, 0x20000), seenFlagOffsets(std::forward<SmallVector<int, 3>&&>(flagOffsets))
{
loadBlocks();
// Japanese games are limited to 5 character OT names; any unused characters are 0xFF.
// 5 for JP, 7 for INT. There's always 1 terminator, thus we can check 0x6-0x7 being 0xFFFF
// = INT OT name is stored at the top of the first block.
japanese = LittleEndian::convertTo<s16>(&data[blockOfs[0] + 0x6]) == 0;
PokeDex = blockOfs[0] + 0x18;
seenFlagOffsets[0] += PokeDex;
seenFlagOffsets[1] += blockOfs[1];
seenFlagOffsets[2] += blockOfs[4];
initialize();
}
void Sav3::initialize(void)
{
// LoadEReaderBerryData();
// Sanity Check SeenFlagOffsets -- early saves may not have block 4 initialized yet
SmallVector<int, 3> seenFlagOffsetsTemp;
for (const auto& seenFlagOffset : seenFlagOffsets)
{
if (seenFlagOffset >= 0)
{
seenFlagOffsetsTemp.push_back(seenFlagOffset);
}
}
seenFlagOffsets = seenFlagOffsetsTemp;
}
u16 Sav3::calculateChecksum(std::span<const u8> data)
{
u32 sum = pksm::crypto::sum32(data);
return sum + (sum >> 16);
}
void Sav3::resign(void)
{
for (int i = 0; i < BLOCK_COUNT; i++)
{
int ofs = ABO() + (i * SIZE_BLOCK);
int index = blockOrder[i];
if (index == -1)
{
continue;
}
u16 chk = calculateChecksum({&data[ofs], chunkLength[index]});
LittleEndian::convertFrom<u16>(&data[ofs + 0xFF6], chk);
}
// Hall of Fame Checksums
{
u16 chk = calculateChecksum({&data[0x1C000], SIZE_BLOCK_USED});
LittleEndian::convertFrom<u16>(&data[0x1CFF4], chk);
}
{
u16 chk = calculateChecksum({&data[0x1D000], SIZE_BLOCK_USED});
LittleEndian::convertFrom<u16>(&data[0x1DFF4], chk);
}
}
u32 Sav3::securityKey(void) const
{
switch (game)
{
case Game::E:
return LittleEndian::convertTo<u32>(&data[blockOfs[0] + 0xAC]);
case Game::FRLG:
return LittleEndian::convertTo<u32>(&data[blockOfs[0] + 0xF20]);
default:
return 0u;
}
}
u16 Sav3::TID(void) const
{
return LittleEndian::convertTo<u16>(&data[blockOfs[0] + 0xA]);
}
void Sav3::TID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[blockOfs[0] + 0xA], v);
}
u16 Sav3::SID(void) const
{
return LittleEndian::convertTo<u16>(&data[blockOfs[0] + 0xC]);
}
void Sav3::SID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[blockOfs[0] + 0xC], v);
}
GameVersion Sav3::version(void) const
{
return game == Game::RS ? GameVersion::S
: game == Game::E ? GameVersion::E
: GameVersion::FR;
}
void Sav3::version(GameVersion) {}
Gender Sav3::gender(void) const
{
return Gender{data[blockOfs[0] + 8]};
}
void Sav3::gender(Gender v)
{
data[blockOfs[0] + 8] = u8(v);
}
Language Sav3::language(void) const
{
// TODO: Other languages? Is this unused?
return japanese ? Language::JPN : Language::ENG;
}
void Sav3::language(Language)
{
// TODO: Unused?
}
std::string Sav3::otName(void) const
{
return StringUtils::getString3(data.get(), blockOfs[0], japanese ? 5 : 7, japanese);
}
void Sav3::otName(const std::string_view& v)
{
StringUtils::setString3(
data.get(), v, blockOfs[0], japanese ? 5 : 7, japanese, japanese ? 5 : 7, 0xFF);
}
u32 Sav3::money(void) const
{
switch (game)
{
case Game::RS:
case Game::E:
return LittleEndian::convertTo<u32>(&data[blockOfs[1] + 0x490]) ^ securityKey();
case Game::FRLG:
return LittleEndian::convertTo<u32>(&data[blockOfs[1] + 0x290]) ^ securityKey();
default:
return int(game);
}
}
void Sav3::money(u32 v)
{
switch (game)
{
case Game::RS:
case Game::E:
LittleEndian::convertFrom<u32>(&data[blockOfs[1] + 0x0490], v ^ securityKey());
break;
case Game::FRLG:
LittleEndian::convertFrom<u32>(&data[blockOfs[1] + 0x0290], v ^ securityKey());
break;
default:
break;
}
}
// TODO:? Coins
u32 Sav3::BP(void) const
{
return LittleEndian::convertTo<u16>(&data[blockOfs[0] + 0xEB8]);
}
void Sav3::BP(u32 v)
{
if (v > 9999)
{
v = 9999;
}
LittleEndian::convertFrom<u16>(&data[blockOfs[0] + 0xEB8], v);
}
// TODO:? BPEarned
// TODO:? BerryPowder
bool Sav3::getEventFlag(int flagNumber) const
{
if (flagNumber >= 8 * (game == Game::E ? 300 : 288))
{
return 0;
}
int start = eventFlag;
if (game == Game::FRLG && flagNumber >= 0x500)
{
flagNumber -= 0x500;
start = blockOfs[2];
}
return FlagUtil::getFlag(data.get(), start + (flagNumber >> 3), flagNumber & 7);
}
void Sav3::setEventFlag(int flagNumber, bool value)
{
if (flagNumber >= 8 * (game == Game::E ? 300 : 288))
{
return;
}
int start = eventFlag;
if (game == Game::FRLG && flagNumber >= 0x500)
{
flagNumber -= 0x500;
start = blockOfs[2];
}
FlagUtil::setFlag(data.get(), start + (flagNumber >> 3), flagNumber & 7, value);
}
u8 Sav3::badges(void) const
{
int startFlag = 0;
switch (game)
{
case Game::FRLG:
startFlag = 0x820;
break;
case Game::RS:
startFlag = 0x807;
break;
case Game::E:
startFlag = 0x867;
default:
break;
}
int ret = 0;
for (int i = 0; i < 8; i++)
{
if (getEventFlag(startFlag + i))
{
ret++;
}
}
return ret;
}
u16 Sav3::playedHours(void) const
{
return LittleEndian::convertTo<u16>(&data[blockOfs[0] + 0xE]);
}
void Sav3::playedHours(u16 v)
{
LittleEndian::convertFrom<u16>(&data[blockOfs[0] + 0xE], v);
}
u8 Sav3::playedMinutes(void) const
{
return data[blockOfs[0] + 0x10];
}
void Sav3::playedMinutes(u8 v)
{
data[blockOfs[0] + 0x10] = v;
}
u8 Sav3::playedSeconds(void) const
{
return data[blockOfs[0] + 0x11];
}
void Sav3::playedSeconds(u8 v)
{
data[blockOfs[0] + 0x11] = v;
}
// TODO:? playedFrames, u8 at 0x12
u8 Sav3::currentBox(void) const
{
return data[blockOfs[5]];
}
void Sav3::currentBox(u8 v)
{
data[blockOfs[5]] = v;
}
u32 Sav3::boxOffset(u8 box, u8 slot) const
{
// Offset = blockOfs[block this slot is in] + slot offset
int fullOffset = 4 + (PK3::BOX_LENGTH * box * 30) + (PK3::BOX_LENGTH * slot);
div_t d = div(fullOffset, 0xF80);
// Box blocks start at 5
return blockOfs[d.quot + 5] + d.rem;
}
u32 Sav3::partyOffset(u8 slot) const
{
return blockOfs[1] + (game == Game::FRLG ? 0x38 : 0x238) + (PK3::PARTY_LENGTH * slot);
}
std::unique_ptr<PKX> Sav3::pkm(u8 slot) const
{
return PKX::getPKM<Generation::THREE>(&data[partyOffset(slot)], PK3::PARTY_LENGTH);
}
std::unique_ptr<PKX> Sav3::pkm(u8 box, u8 slot) const
{
u32 offset = boxOffset(box, slot);
// Is it split?
if ((offset % 0x1000) + PK3::BOX_LENGTH > 0xF80)
{
// Concatenate the data if so
u8 pkmData[PK3::BOX_LENGTH];
auto nextOut = std::copy(&data[offset], &data[(offset & 0xFFFFF000) | 0xF80], pkmData);
u32 nextOffset = boxOffset(box + (slot + 1) / 30, (slot + 1) % 30);
std::copy(&data[nextOffset & 0xFFFFF000], &data[nextOffset], nextOut);
return PKX::getPKM<Generation::THREE>(pkmData, PK3::BOX_LENGTH);
}
else
{
return PKX::getPKM<Generation::THREE>(&data[offset], PK3::BOX_LENGTH);
}
}
void Sav3::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::THREE)
{
auto pk3 = pk.partyClone();
pk3->encrypt();
std::ranges::copy(pk3->rawData(), &data[partyOffset(slot)]);
}
}
void Sav3::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (pk.generation() == Generation::THREE)
{
auto pk3 = pk.clone();
if (applyTrade)
{
trade(*pk3);
}
u32 offset = boxOffset(box, slot);
// Is it split?
if ((offset % 0x1000) + PK3::BOX_LENGTH > 0xF80)
{
// Copy into the correct positions if so
u32 firstSize = 0xF80 - (offset % 0x1000);
std::ranges::copy(pk3->rawData().subspan(0, firstSize), &data[offset]);
u32 nextOffset = boxOffset(box + (slot + 1) / 30, (slot + 1) % 30);
std::ranges::copy(pk3->rawData().subspan(firstSize, PK3::BOX_LENGTH - firstSize),
&data[nextOffset & 0xFFFFF000]);
}
else
{
std::ranges::copy(pk3->rawData(), &data[offset]);
}
}
}
void Sav3::trade(PKX&, const Date&) const {}
std::unique_ptr<PKX> Sav3::emptyPkm() const
{
return PKX::getPKM<Generation::THREE>(nullptr, PK3::BOX_LENGTH);
}
bool Sav3::canSetDex(Species species)
{
if (species == Species::None)
{
return false;
}
if (species > Species::Deoxys)
{
return false;
}
if (std::find_if(blockOfs.begin(), blockOfs.end(),
[](const int& val) { return val < 0; }) != blockOfs.end())
{
return false;
}
return true;
}
u32 Sav3::dexPIDUnown(void)
{
return LittleEndian::convertTo<u32>(&data[PokeDex + 0x4]);
}
void Sav3::dexPIDUnown(u32 v)
{
LittleEndian::convertFrom<u32>(&data[PokeDex + 0x4], v);
}
u32 Sav3::dexPIDSpinda(void)
{
return LittleEndian::convertTo<u32>(&data[PokeDex + 0x8]);
}
void Sav3::dexPIDSpinda(u32 v)
{
LittleEndian::convertFrom<u32>(&data[PokeDex + 0x8], v);
}
void Sav3::dex(const PKX& pk)
{
if (!canSetDex(pk.species()) || pk.egg())
{
return;
}
switch (pk.species())
{
case Species::Unown:
if (!getSeen(pk.species()))
{
dexPIDUnown(pk.PID());
}
break;
case Species::Spinda: // Spinda
if (!getSeen(pk.species()))
{
dexPIDSpinda(pk.PID());
}
break;
default:
break;
}
setCaught(pk.species(), true);
setSeen(pk.species(), true);
}
bool Sav3::getCaught(Species species) const
{
int bit = u16(species) - 1;
int ofs = bit >> 3;
int caughtOffset = PokeDex + 0x10;
return FlagUtil::getFlag(data.get(), caughtOffset + ofs, bit & 7);
}
void Sav3::setCaught(Species species, bool caught)
{
int bit = u16(species) - 1;
int ofs = bit >> 3;
int caughtOffset = PokeDex + 0x10;
FlagUtil::setFlag(data.get(), caughtOffset + ofs, bit & 7, caught);
}
bool Sav3::getSeen(Species species) const
{
int bit = u16(species) - 1;
int ofs = bit >> 3;
int seenOffset = PokeDex + 0x44;
return FlagUtil::getFlag(data.get(), seenOffset + ofs, bit & 7);
}
void Sav3::setSeen(Species species, bool seen)
{
int bit = u16(species) - 1;
int ofs = bit >> 3;
for (int o : seenFlagOffsets)
{
FlagUtil::setFlag(data.get(), o + ofs, bit & 7, seen);
}
}
int Sav3::dexSeen(void) const
{
return std::count_if(availableSpecies().begin(), availableSpecies().end(),
[this](const auto& spec) { return getSeen(spec); });
}
int Sav3::dexCaught(void) const
{
return std::count_if(availableSpecies().begin(), availableSpecies().end(),
[this](const auto& spec) { return getCaught(spec); });
}
// Unused
std::unique_ptr<WCX> Sav3::mysteryGift(int) const
{
return nullptr;
}
void Sav3::cryptBoxData(bool crypted)
{
for (u8 box = 0; box < maxBoxes(); box++)
{
for (u8 slot = 0; slot < 30; slot++)
{
u32 offset = boxOffset(box, slot);
bool split = (offset % 0x1000) + PK3::BOX_LENGTH > 0xF80;
// If it's split, it needs to get fully copied out and re-set in
// Otherwise, use the direct-modification constructor
std::unique_ptr<PKX> pk3;
if (split)
{
pk3 = pkm(box, slot);
}
else
{
pk3 = PKX::getPKM<Generation::THREE>(&data[offset], PK3::BOX_LENGTH, true);
}
if (!crypted)
{
pk3->encrypt();
}
if (split)
{
pkm(*pk3, box, slot, false);
}
}
}
}
std::string Sav3::boxName(u8 box) const
{
return StringUtils::getString3(
data.get(), boxOffset(maxBoxes(), 0) + (box * 9), 9, japanese);
}
void Sav3::boxName(u8 box, const std::string_view& v)
{
return StringUtils::setString3(
data.get(), v, boxOffset(maxBoxes(), 0) + (box * 9), 8, japanese, 9);
}
u8 Sav3::boxWallpaper(u8 box) const
{
int offset = boxOffset(maxBoxes(), 0);
offset += (maxBoxes() * 0x9) + box;
return data[offset];
}
void Sav3::boxWallpaper(u8 box, u8 v)
{
int offset = boxOffset(maxBoxes(), 0);
offset += (maxBoxes() * 0x9) + box;
data[offset] = v;
}
u8 Sav3::partyCount(void) const
{
return data[blockOfs[1] + (game == Game::FRLG ? 0x34 : 0x234)];
}
void Sav3::partyCount(u8 v)
{
data[blockOfs[1] + (game == Game::FRLG ? 0x34 : 0x234)] = v;
}
void Sav3::item(const Item& tItem, Pouch pouch, u16 slot)
{
Item3 item = static_cast<Item3>(tItem);
if (pouch == Pouch::PCItem)
{
item.securityKey(0);
}
else
{
item.securityKey(securityKey());
}
auto write = item.bytes();
switch (pouch)
{
case Pouch::NormalItem:
std::copy(write.begin(), write.end(), &data[OFS_PouchHeldItem + (slot * 4)]);
break;
case Pouch::KeyItem:
std::copy(write.begin(), write.end(), &data[OFS_PouchKeyItem + (slot * 4)]);
break;
case Pouch::Ball:
std::copy(write.begin(), write.end(), &data[OFS_PouchBalls + (slot * 4)]);
break;
case Pouch::TM:
std::copy(write.begin(), write.end(), &data[OFS_PouchTMHM + (slot * 4)]);
break;
case Pouch::Berry:
std::copy(write.begin(), write.end(), &data[OFS_PouchBerry + (slot * 4)]);
break;
case Pouch::PCItem:
std::copy(write.begin(), write.end(), &data[OFS_PCItem + (slot * 4)]);
break;
default:
return;
}
}
std::unique_ptr<Item> Sav3::item(Pouch pouch, u16 slot) const
{
switch (pouch)
{
case Pouch::NormalItem:
return std::make_unique<Item3>(
&data[OFS_PouchHeldItem + (slot * 4)], securityKey());
case Pouch::KeyItem:
return std::make_unique<Item3>(&data[OFS_PouchKeyItem + (slot * 4)], securityKey());
case Pouch::Ball:
return std::make_unique<Item3>(&data[OFS_PouchBalls + (slot * 4)], securityKey());
case Pouch::TM:
return std::make_unique<Item3>(&data[OFS_PouchTMHM + (slot * 4)], securityKey());
case Pouch::Berry:
return std::make_unique<Item3>(&data[OFS_PouchBerry + (slot * 4)], securityKey());
case Pouch::PCItem:
return std::make_unique<Item3>(&data[OFS_PCItem + (slot * 4)]);
default:
return nullptr;
}
}
SmallVector<std::pair<Sav::Pouch, int>, 15> Sav3::pouches(void) const
{
return {
std::pair{Pouch::NormalItem, (OFS_PouchKeyItem - OFS_PouchHeldItem) / 4},
std::pair{Pouch::KeyItem, (OFS_PouchBalls - OFS_PouchKeyItem) / 4 },
std::pair{Pouch::Ball, (OFS_PouchTMHM - OFS_PouchBalls) / 4 },
std::pair{Pouch::TM, (OFS_PouchBerry - OFS_PouchTMHM) / 4 },
std::pair{Pouch::Berry, game == Game::FRLG ? 43 : 46 },
std::pair{Pouch::PCItem, (OFS_PouchHeldItem - OFS_PCItem) / 4 }
};
}
u16 Sav3::rtcInitialDay(void) const
{
if (game == Game::FRLG)
{
return 0;
}
return LittleEndian::convertTo<u16>(&data[blockOfs[0] + 0x98]);
}
void Sav3::rtcInitialDay(u16 v)
{
if (game == Game::FRLG)
{
return;
}
LittleEndian::convertFrom<u16>(&data[blockOfs[0] + 0x98], v);
}
u8 Sav3::rtcInitialHour(void) const
{
if (game == Game::FRLG)
{
return 0;
}
return data[blockOfs[0] + 0x98 + 2];
}
void Sav3::rtcInitialHour(u8 v)
{
if (game == Game::FRLG)
{
return;
}
data[blockOfs[0] + 0x98 + 2] = v;
}
u8 Sav3::rtcInitialMinute(void) const
{
if (game == Game::FRLG)
{
return 0;
}
return data[blockOfs[0] + 0x98 + 3];
}
void Sav3::rtcInitialMinute(u8 v)
{
if (game == Game::FRLG)
{
return;
}
data[blockOfs[0] + 0x98 + 3] = v;
}
u8 Sav3::rtcInitialSecond(void) const
{
if (game == Game::FRLG)
{
return 0;
}
return data[blockOfs[0] + 0x98 + 4];
}
void Sav3::rtcInitialSecond(u8 v)
{
if (game == Game::FRLG)
{
return;
}
data[blockOfs[0] + 0x98 + 4] = v;
}
u16 Sav3::rtcElapsedDay(void) const
{
if (game == Game::FRLG)
{
return 0;
}
return LittleEndian::convertTo<u16>(&data[blockOfs[0] + 0xA0]);
}
void Sav3::rtcElapsedDay(u16 v)
{
if (game == Game::FRLG)
{
return;
}
LittleEndian::convertFrom<u16>(&data[blockOfs[0] + 0xA0], v);
}
u8 Sav3::rtcElapsedHour(void) const
{
if (game == Game::FRLG)
{
return 0;
}
return data[blockOfs[0] + 0xA0 + 2];
}
void Sav3::rtcElapsedHour(u8 v)
{
if (game == Game::FRLG)
{
return;
}
data[blockOfs[0] + 0xA0 + 2] = v;
}
u8 Sav3::rtcElapsedMinute(void) const
{
if (game == Game::FRLG)
{
return 0;
}
return data[blockOfs[0] + 0xA0 + 3];
}
void Sav3::rtcElapsedMinute(u8 v)
{
if (game == Game::FRLG)
{
return;
}
data[blockOfs[0] + 0xA0 + 3] = v;
}
u8 Sav3::rtcElapsedSecond(void) const
{
if (game == Game::FRLG)
{
return 0;
}
return data[blockOfs[0] + 0xA0 + 4];
}
void Sav3::rtcElapsedSecond(u8 v)
{
if (game == Game::FRLG)
{
return;
}
data[blockOfs[0] + 0xA0 + 4] = v;
}
}
| 25,992
|
C++
|
.cpp
| 795
| 23.427673
| 100
| 0.519748
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,233
|
SavSWSH.cpp
|
FlagBrew_PKSM-Core/source/sav/SavSWSH.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavSWSH.hpp"
#include "pkx/PK8.hpp"
#include "utils/endian.hpp"
#include "utils/i18n.hpp"
#include "utils/random.hpp"
#include "utils/utils.hpp"
#include "wcx/WC8.hpp"
#include <algorithm>
namespace
{
struct DexEntry
{
u64 seenNonShinyMale : 63;
u64 seenNonShinyMaleGiga : 1;
u64 seenNonShinyFemale : 63;
u64 seenNonShinyFemaleGiga : 1;
u64 seenShinyMale : 63;
u64 seenShinyMaleGiga : 1;
u64 seenShinyFemale : 63;
u64 seenShinyFemaleGiga : 1;
// Obtained info
u32 owned : 1;
u32 ownedGiga : 1;
u32 languages : 13; // flags
u32 displayFormID : 13; // value
u32 displayGiga : 1;
u32 displayGender : 2;
u32 displayShiny : 1;
u32 battled : 32;
u32 unk1 : 32;
u32 unk2 : 32;
};
static_assert(sizeof(DexEntry) == 0x30);
void setProperLocation(DexEntry& entry, u16 form, bool shiny, pksm::Gender gender)
{
if (gender == pksm::Gender::Female)
{
if (shiny)
{
entry.seenShinyFemale |= 1 << form;
}
else
{
entry.seenNonShinyFemale |= 1 << form;
}
}
else
{
if (shiny)
{
entry.seenShinyMale |= 1 << form;
}
else
{
entry.seenNonShinyMale |= 1 << form;
}
}
}
void setProperGiga(DexEntry& entry, bool giga, bool shiny, pksm::Gender gender)
{
if (gender == pksm::Gender::Female)
{
if (shiny)
{
entry.seenShinyFemaleGiga = giga ? 1 : 0;
}
else
{
entry.seenNonShinyFemaleGiga = giga ? 1 : 0;
}
}
else
{
if (shiny)
{
entry.seenShinyMaleGiga = giga ? 1 : 0;
}
else
{
entry.seenNonShinyMaleGiga = giga ? 1 : 0;
}
}
}
}
template <>
struct EndianTraits::EndianConvertible_s<DexEntry> : public std::true_type
{
};
template <>
constexpr DexEntry LittleEndian::convertTo<DexEntry>(const u8* data)
{
DexEntry ret{};
u64 v64 = LittleEndian::convertTo<u64>(data);
ret.seenNonShinyMale = v64;
ret.seenNonShinyMaleGiga = v64 >> 63;
v64 = LittleEndian::convertTo<u64>(data + 8);
ret.seenNonShinyFemale = v64;
ret.seenNonShinyFemaleGiga = v64 >> 63;
v64 = LittleEndian::convertTo<u64>(data + 16);
ret.seenShinyMale = v64;
ret.seenShinyMaleGiga = v64 >> 63;
v64 = LittleEndian::convertTo<u64>(data + 24);
ret.seenShinyFemale = v64;
ret.seenShinyFemaleGiga = v64 >> 63;
u32 v32 = LittleEndian::convertTo<u32>(data + 32);
ret.owned = v32 & 1;
ret.ownedGiga = (v32 >> 1) & 1;
ret.languages = (v32 >> 2) & 0x1FFF;
ret.displayFormID = (v32 >> 15) & 0x1FFF;
ret.displayGiga = (v32 >> 28) & 1;
ret.displayGender = (v32 >> 29) & 3;
ret.displayShiny = v32 >> 31;
ret.battled = LittleEndian::convertTo<u32>(data + 36);
ret.unk1 = LittleEndian::convertTo<u32>(data + 40);
ret.unk2 = LittleEndian::convertTo<u32>(data + 44);
return ret;
}
template <>
constexpr void LittleEndian::convertFrom<DexEntry>(u8* data, const DexEntry& entry)
{
u64 w64 = entry.seenNonShinyMale | (u64(entry.seenNonShinyMaleGiga) << 63);
LittleEndian::convertFrom<u64>(data, w64);
w64 = entry.seenNonShinyFemale | (u64(entry.seenNonShinyFemaleGiga) << 63);
LittleEndian::convertFrom<u64>(data + 8, w64);
w64 = entry.seenShinyMale | (u64(entry.seenShinyMaleGiga) << 63);
LittleEndian::convertFrom<u64>(data + 16, w64);
w64 = entry.seenShinyFemale | (u64(entry.seenShinyFemaleGiga) << 63);
LittleEndian::convertFrom<u64>(data + 24, w64);
u32 w32 = entry.owned | (entry.ownedGiga << 1) | (entry.languages << 2) |
(entry.displayFormID << 15) | (entry.displayGiga << 28) |
(entry.displayGender << 29) | (entry.displayShiny << 31);
LittleEndian::convertFrom<u32>(data + 32, w32);
LittleEndian::convertFrom<u32>(data + 36, entry.battled);
LittleEndian::convertFrom<u32>(data + 40, entry.unk1);
LittleEndian::convertFrom<u32>(data + 44, entry.unk2);
}
namespace pksm
{
SavSWSH::SavSWSH(const std::shared_ptr<u8[]>& dt, size_t length) : Sav8(dt, length)
{
game = Game::SWSH;
Box = 0x0d66012c;
WondercardData = 0x112d5141;
Party = 0x2985fe5d;
PokeDex = 0x4716c404;
ArmorDex = 0x3F936BA9;
CrownDex = 0x3C9366F0;
Items = 0x1177c2c4;
BoxLayout = 0x19722c89;
Misc = 0x1b882b09;
TrainerCard = 0x874da6fa;
PlayTime = 0x8cbbfd90;
Status = 0xf25c070e;
}
u16 SavSWSH::TID(void) const
{
return LittleEndian::convertTo<u16>(getBlock(Status)->decryptedData() + 0xA0);
}
void SavSWSH::TID(u16 v)
{
LittleEndian::convertFrom<u16>(getBlock(Status)->decryptedData() + 0xA0, v);
LittleEndian::convertFrom<u32>(getBlock(TrainerCard)->decryptedData() + 0x1C, displayTID());
}
u16 SavSWSH::SID(void) const
{
return LittleEndian::convertTo<u16>(getBlock(Status)->decryptedData() + 0xA2);
}
void SavSWSH::SID(u16 v)
{
LittleEndian::convertFrom<u16>(getBlock(Status)->decryptedData() + 0xA2, v);
LittleEndian::convertFrom<u32>(getBlock(TrainerCard)->decryptedData() + 0x1C, displayTID());
}
GameVersion SavSWSH::version(void) const
{
return GameVersion(getBlock(Status)->decryptedData()[0xA4]);
}
void SavSWSH::version(GameVersion v)
{
getBlock(Status)->decryptedData()[0xA4] = u8(v);
}
Gender SavSWSH::gender(void) const
{
return Gender{getBlock(Status)->decryptedData()[0xA5]};
}
void SavSWSH::gender(Gender v)
{
getBlock(Status)->decryptedData()[0xA5] = u8(v);
}
Language SavSWSH::language(void) const
{
return Language(getBlock(Status)->decryptedData()[0xA7]);
}
void SavSWSH::language(Language v)
{
getBlock(Status)->decryptedData()[0xA7] = u8(v);
}
std::string SavSWSH::otName(void) const
{
return StringUtils::getString(getBlock(Status)->decryptedData(), 0xB0, 13);
}
void SavSWSH::otName(const std::string_view& v)
{
StringUtils::setString(getBlock(Status)->decryptedData(), v, 0xB0, 13);
StringUtils::setString(getBlock(TrainerCard)->decryptedData(), v, 0, 13);
}
std::string SavSWSH::jerseyNum(void) const
{
return std::string((char*)getBlock(TrainerCard)->decryptedData() + 0x39, 3);
}
void SavSWSH::jerseyNum(const std::string_view& v)
{
for (size_t i = 0; i < std::min(v.size(), (size_t)3); i++)
{
getBlock(TrainerCard)->decryptedData()[0x39 + i] = v[i];
}
}
u32 SavSWSH::money(void) const
{
return LittleEndian::convertTo<u32>(getBlock(Misc)->decryptedData());
}
void SavSWSH::money(u32 v)
{
LittleEndian::convertFrom<u32>(getBlock(Misc)->decryptedData(), v);
}
u32 SavSWSH::BP(void) const
{
return LittleEndian::convertTo<u32>(getBlock(Misc)->decryptedData() + 4);
}
void SavSWSH::BP(u32 v)
{
LittleEndian::convertFrom<u32>(getBlock(Misc)->decryptedData() + 4, v);
}
u8 SavSWSH::badges(void) const
{
return getBlock(Misc)->decryptedData()[0x11C];
}
u16 SavSWSH::playedHours(void) const
{
return LittleEndian::convertTo<u16>(getBlock(PlayTime)->decryptedData());
}
void SavSWSH::playedHours(u16 v)
{
LittleEndian::convertFrom<u16>(getBlock(PlayTime)->decryptedData(), v);
}
u8 SavSWSH::playedMinutes(void) const
{
return getBlock(PlayTime)->decryptedData()[2];
}
void SavSWSH::playedMinutes(u8 v)
{
getBlock(PlayTime)->decryptedData()[2] = v;
}
u8 SavSWSH::playedSeconds(void) const
{
return getBlock(PlayTime)->decryptedData()[3];
}
void SavSWSH::playedSeconds(u8 v)
{
getBlock(PlayTime)->decryptedData()[3] = v;
}
void SavSWSH::item(const Item& item, Pouch pouch, u16 slot)
{
Item8 item8 = static_cast<Item8>(item);
auto write = item.bytes();
switch (pouch)
{
case Pouch::Medicine:
std::copy(write.begin(), write.end(), getBlock(Items)->decryptedData() + 4 * slot);
break;
case Pouch::Ball:
std::copy(
write.begin(), write.end(), getBlock(Items)->decryptedData() + 0xF0 + 4 * slot);
break;
case Pouch::Battle:
std::copy(write.begin(), write.end(),
getBlock(Items)->decryptedData() + 0x168 + 4 * slot);
break;
case Pouch::Berry:
std::copy(write.begin(), write.end(),
getBlock(Items)->decryptedData() + 0x1B8 + 4 * slot);
break;
case Pouch::NormalItem:
std::copy(write.begin(), write.end(),
getBlock(Items)->decryptedData() + 0x2F8 + 4 * slot);
break;
case Pouch::TM:
std::copy(write.begin(), write.end(),
getBlock(Items)->decryptedData() + 0xB90 + 4 * slot);
break;
case Pouch::Treasure:
std::copy(write.begin(), write.end(),
getBlock(Items)->decryptedData() + 0xED8 + 4 * slot);
break;
case Pouch::Ingredient:
std::copy(write.begin(), write.end(),
getBlock(Items)->decryptedData() + 0x1068 + 4 * slot);
break;
case Pouch::KeyItem:
std::copy(write.begin(), write.end(),
getBlock(Items)->decryptedData() + 0x11F8 + 4 * slot);
break;
default:
break;
}
}
std::unique_ptr<Item> SavSWSH::item(Pouch pouch, u16 slot) const
{
switch (pouch)
{
case Pouch::Medicine:
return std::make_unique<Item8>(getBlock(Items)->decryptedData() + 4 * slot);
case Pouch::Ball:
return std::make_unique<Item8>(getBlock(Items)->decryptedData() + 0xF0 + 4 * slot);
case Pouch::Battle:
return std::make_unique<Item8>(getBlock(Items)->decryptedData() + 0x168 + 4 * slot);
case Pouch::Berry:
return std::make_unique<Item8>(getBlock(Items)->decryptedData() + 0x1B8 + 4 * slot);
case Pouch::NormalItem:
return std::make_unique<Item8>(getBlock(Items)->decryptedData() + 0x2F8 + 4 * slot);
case Pouch::TM:
return std::make_unique<Item8>(getBlock(Items)->decryptedData() + 0xB90 + 4 * slot);
case Pouch::Treasure:
return std::make_unique<Item8>(getBlock(Items)->decryptedData() + 0xED8 + 4 * slot);
case Pouch::Ingredient:
return std::make_unique<Item8>(
getBlock(Items)->decryptedData() + 0x1068 + 4 * slot);
case Pouch::KeyItem:
return std::make_unique<Item8>(
getBlock(Items)->decryptedData() + 0x11F8 + 4 * slot);
default:
return std::make_unique<Item8>();
}
}
SmallVector<std::pair<Sav::Pouch, int>, 15> SavSWSH::pouches(void) const
{
return {
std::pair{Pouch::Medicine, 60 },
std::pair{Pouch::Ball, 30 },
std::pair{Pouch::Battle, 20 },
std::pair{Pouch::Berry, 80 },
std::pair{Pouch::NormalItem, 550},
std::pair{Pouch::TM, 210},
std::pair{Pouch::Treasure, 100},
std::pair{Pouch::Ingredient, 100},
std::pair{Pouch::KeyItem, 64 }
};
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavSWSH::validItems(void) const
{
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 54, 134, 54, 591, 708, 709, 852,
903};
static constexpr std::array Ball = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
492, 493, 494, 495, 496, 497, 498, 499, 500, 576, 851};
static constexpr std::array Battle = {55, 56, 57, 58, 59, 60, 61, 62, 63, 1580};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 169, 170, 171, 172, 173, 174, 184, 185, 186, 187, 188, 189, 190,
191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 686, 687, 688};
static constexpr std::array NormalItem = {45, 46, 47, 48, 49, 50, 51, 52, 53, 76, 77, 79,
80, 81, 82, 83, 84, 85, 107, 108, 109, 110, 112, 116, 117, 118, 119, 135, 136, 213, 214,
215, 217, 218, 219, 220, 221, 222, 223, 224, 225, 228, 234, 236, 237, 238, 239, 240,
241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 253, 254, 255, 257, 229, 230,
231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
248, 249, 259, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278,
279, 280, 281, 282, 283, 284, 250, 251, 252, 253, 254, 255, 257, 258, 259, 265, 266,
267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 285, 286, 287, 288, 289, 290, 291,
292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 277, 278, 279,
280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296,
297, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321,
325, 326, 537, 538, 539, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309,
310, 311, 312, 313, 314, 315, 316, 317, 318, 540, 541, 542, 543, 544, 545, 546, 547,
564, 565, 566, 567, 568, 569, 570, 639, 640, 644, 645, 646, 647, 319, 320, 321, 322,
323, 324, 325, 326, 485, 486, 487, 488, 489, 490, 491, 537, 538, 539, 540, 541, 542,
648, 649, 650, 846, 849, 879, 880, 881, 882, 883, 884, 904, 905, 906, 907, 908, 909,
910, 911, 912, 913, 543, 544, 545, 546, 547, 564, 565, 566, 567, 568, 569, 570, 639,
640, 644, 645, 646, 647, 648, 649, 650, 914, 915, 916, 917, 918, 919, 920, 1103, 1104,
1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 846, 849, 879, 880, 881,
882, 883, 884, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 1119,
1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1231, 1232, 1233, 1234,
1235, 1236, 1237, 917, 918, 919, 920, 1103, 1104, 1109, 1110, 1111, 1112, 1113, 1114,
1115, 1116, 1117, 1118, 1119, 1120, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245,
1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1121, 1122, 1123, 1124, 1125,
1126, 1127, 1128, 1129, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240,
1241, 1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254,
1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292,
1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306,
1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320,
1321, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334,
1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348,
1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362,
1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376,
1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390,
1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404,
1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418,
1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432,
1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446,
1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460,
1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474,
1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488,
1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499, 1500, 1501, 1502,
1503, 1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516,
1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530,
1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 1543, 1544,
1545, 1546, 1547, 1548, 1549, 1550, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558,
1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1572,
1573, 1574, 1575, 1576, 1577, 1578, 1581, 1582, 1588};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 618, 619, 620, 690,
691, 692, 693, 1230, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140,
1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154,
1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168,
1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182,
1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196,
1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210,
1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224,
1225, 1226, 1227, 1228, 1229, 1579};
static constexpr std::array Treasure = {86, 87, 88, 89, 90, 91, 92, 94, 106, 571, 580, 581,
582, 583, 795, 796, 1105, 1106, 1107, 1108};
static constexpr std::array Ingredient = {1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091,
1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1256, 1257, 1258, 1259, 1260, 1261,
1262, 1263, 1264};
static constexpr std::array KeyItem = {78, 628, 629, 631, 632, 628, 629, 631, 632, 638, 703,
703, 847, 943, 944, 945, 946, 943, 944, 945, 946, 1074, 1075, 1076, 1077, 1080, 1081,
1100, 1074, 1075, 1076, 1077, 1080, 1081, 1100, 1255, 1266, 1267, 1255, 1266, 1267,
1269, 1270, 1271, 1278, 1269, 1270, 1271, 1278, 1583, 1584, 1585, 1586, 1587, 1589};
return {
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Ball, std::span{Ball} },
std::pair{Pouch::Battle, std::span{Battle} },
std::pair{Pouch::Berry, std::span{Berry} },
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Treasure, std::span{Treasure} },
std::pair{Pouch::Ingredient, std::span{Ingredient}},
std::pair{Pouch::KeyItem, std::span{KeyItem} }
};
}
u8 SavSWSH::currentBox() const
{
return LittleEndian::convertTo<u32>(getBlock(0x017C3CBB)->decryptedData());
}
void SavSWSH::currentBox(u8 box)
{
LittleEndian::convertFrom<u32>(getBlock(0x017C3CBB)->decryptedData(), box);
}
std::string SavSWSH::boxName(u8 box) const
{
return StringUtils::getString(getBlock(BoxLayout)->decryptedData(), box * 0x22, 17);
}
void SavSWSH::boxName(u8 box, const std::string_view& name)
{
StringUtils::setString(getBlock(BoxLayout)->decryptedData(), name, box * 0x22, 17);
}
u8 SavSWSH::boxWallpaper(u8 box) const
{
return LittleEndian::convertTo<u32>(getBlock(0x017C3CBB)->decryptedData() + box * 4);
}
void SavSWSH::boxWallpaper(u8 box, u8 v)
{
LittleEndian::convertFrom<u32>(getBlock(0x2EB1B190)->decryptedData() + box * 4, v);
}
u32 SavSWSH::boxOffset(u8 box, u8 slot) const
{
return PK8::PARTY_LENGTH * slot + PK8::PARTY_LENGTH * 30 * box;
}
u32 SavSWSH::partyOffset(u8 slot) const
{
return PK8::PARTY_LENGTH * slot;
}
u8 SavSWSH::partyCount(void) const
{
return getBlock(Party)->decryptedData()[PK8::PARTY_LENGTH * 6];
}
void SavSWSH::partyCount(u8 count)
{
getBlock(Party)->decryptedData()[PK8::PARTY_LENGTH * 6] = count;
}
std::unique_ptr<PKX> SavSWSH::pkm(u8 slot) const
{
u32 offset = partyOffset(slot);
return PKX::getPKM<Generation::EIGHT>(
getBlock(Party)->decryptedData() + offset, PK8::PARTY_LENGTH);
}
std::unique_ptr<PKX> SavSWSH::pkm(u8 box, u8 slot) const
{
u32 offset = boxOffset(box, slot);
return PKX::getPKM<Generation::EIGHT>(
getBlock(Box)->decryptedData() + offset, PK8::PARTY_LENGTH);
}
void SavSWSH::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (pk.generation() == Generation::EIGHT)
{
auto pk8 = pk.partyClone();
if (applyTrade)
{
trade(*pk8);
}
std::ranges::copy(
pk8->rawData(), getBlock(Box)->decryptedData() + boxOffset(box, slot));
}
}
void SavSWSH::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::EIGHT)
{
auto pk8 = pk.partyClone();
pk8->encrypt();
std::ranges::copy(pk8->rawData(), getBlock(Party)->decryptedData() + partyOffset(slot));
}
}
void SavSWSH::cryptBoxData(bool crypted)
{
for (u8 box = 0; box < maxBoxes(); box++)
{
for (u8 slot = 0; slot < 30; slot++)
{
std::unique_ptr<PKX> pk8 = PKX::getPKM<Generation::EIGHT>(
getBlock(Box)->decryptedData() + boxOffset(box, slot), PK8::PARTY_LENGTH, true);
if (!crypted)
{
pk8->encrypt();
}
}
}
}
void SavSWSH::mysteryGift(const WCX& wc, int&)
{
if (wc.generation() == Generation::EIGHT)
{
const WC8& wc8 = static_cast<const WC8&>(wc);
if (wc8.pokemon())
{
int injectPosition = 0;
for (injectPosition = 0; injectPosition < maxSlot(); injectPosition++)
{
if (pkm(injectPosition / 30, injectPosition % 30)->species() == Species::None)
{
break;
}
}
// No place to put generated PK8!
if (injectPosition == maxSlot())
{
return;
}
auto pk8 = PKX::getPKM<Generation::EIGHT>(nullptr, PK8::BOX_LENGTH);
pk8->encryptionConstant(wc8.encryptionConstant()
? wc8.encryptionConstant()
: pksm::randomNumber(0, 0xFFFFFFFF));
pk8->TID(wc8.TID());
pk8->SID(wc8.SID());
pk8->species(wc8.species());
pk8->alternativeForm(wc8.alternativeForm());
pk8->level(wc8.level() ? wc8.level() : pksm::randomNumber(1, 100));
pk8->ball(wc8.ball() ? wc8.ball() : Ball::Poke);
pk8->metLevel(wc8.metLevel() ? wc8.metLevel() : pk8->level());
pk8->heldItem(wc8.heldItem());
for (size_t move = 0; move < 4; move++)
{
pk8->move(move, wc8.move(move));
pk8->relearnMove(move, wc8.relearnMove(move));
}
pk8->version(wc8.version() != GameVersion::INVALID ? wc8.version() : version());
std::string wcOT = wc8.otName(language());
if (wcOT.empty())
{
pk8->otName(otName());
pk8->otGender(gender());
}
else
{
pk8->otName(wcOT);
pk8->otGender(wc8.otGender() < Gender::Genderless ? wc8.otGender() : gender());
pk8->htName(otName());
pk8->htGender(gender());
pk8->htLanguage(language());
pk8->currentHandler(PKXHandler::NonOT);
}
pk8->otIntensity(wc8.otIntensity());
pk8->otMemory(wc8.otMemory());
pk8->otTextVar(wc8.otTextvar());
pk8->otFeeling(wc8.otFeeling());
pk8->fatefulEncounter(true);
for (Stat stat :
{Stat::HP, Stat::ATK, Stat::DEF, Stat::SPD, Stat::SPATK, Stat::SPDEF})
{
pk8->ev(stat, wc8.ev(stat));
}
pk8->canGiga(wc8.canGigantamax());
pk8->dynamaxLevel(wc8.dynamaxLevel());
pk8->metLocation(wc8.metLocation());
pk8->eggLocation(wc8.eggLocation());
if (wc8.otGender() >= Gender::Genderless)
{
pk8->TID(TID());
pk8->SID(SID());
}
if (pk8->species() == Species::Meowstic)
{
pk8->alternativeForm(u8(pk8->gender()));
}
pk8->metDate(Date::today());
Language nickLang = wc8.nicknameLanguage(language());
if (nickLang != Language(0))
{
pk8->language(nickLang);
}
else
{
pk8->language(language());
}
pk8->nicknamed(wc8.nicknamed(pk8->language()));
pk8->nickname(pk8->nicknamed() ? wc8.nickname(pk8->language())
: pk8->species().localize(pk8->language()));
static constexpr std::array<Ribbon, 98> RIBBONS_TO_TRANSFER = {
Ribbon::ChampionKalos, Ribbon::ChampionG3Hoenn, Ribbon::ChampionSinnoh,
Ribbon::BestFriends, Ribbon::Training, Ribbon::BattlerSkillful,
Ribbon::BattlerExpert, Ribbon::Effort, Ribbon::Alert, Ribbon::Shock,
Ribbon::Downcast, Ribbon::Careless, Ribbon::Relax, Ribbon::Snooze,
Ribbon::Smile, Ribbon::Gorgeous, Ribbon::Royal, Ribbon::GorgeousRoyal,
Ribbon::Artist, Ribbon::Footprint, Ribbon::Record, Ribbon::Legend,
Ribbon::Country, Ribbon::National, Ribbon::Earth, Ribbon::World,
Ribbon::Classic, Ribbon::Premier, Ribbon::Event, Ribbon::Birthday,
Ribbon::Special, Ribbon::Souvenir, Ribbon::Wishing, Ribbon::ChampionBattle,
Ribbon::ChampionRegional, Ribbon::ChampionNational, Ribbon::ChampionWorld,
Ribbon::MemoryContest, Ribbon::MemoryBattle, Ribbon::ChampionG6Hoenn,
Ribbon::ContestStar, Ribbon::MasterCoolness, Ribbon::MasterBeauty,
Ribbon::MasterCuteness, Ribbon::MasterCleverness, Ribbon::MasterToughness,
Ribbon::ChampionAlola, Ribbon::BattleRoyale, Ribbon::BattleTreeGreat,
Ribbon::BattleTreeMaster, Ribbon::ChampionGalar, Ribbon::TowerMaster,
Ribbon::MasterRank, Ribbon::MarkLunchtime, Ribbon::MarkSleepyTime,
Ribbon::MarkDusk, Ribbon::MarkDawn, Ribbon::MarkCloudy, Ribbon::MarkRainy,
Ribbon::MarkStormy, Ribbon::MarkSnowy, Ribbon::MarkBlizzard, Ribbon::MarkDry,
Ribbon::MarkSandstorm, Ribbon::MarkMisty, Ribbon::MarkDestiny,
Ribbon::MarkFishing, Ribbon::MarkCurry, Ribbon::MarkUncommon, Ribbon::MarkRare,
Ribbon::MarkRowdy, Ribbon::MarkAbsentMinded, Ribbon::MarkJittery,
Ribbon::MarkExcited, Ribbon::MarkCharismatic, Ribbon::MarkCalmness,
Ribbon::MarkIntense, Ribbon::MarkZonedOut, Ribbon::MarkJoyful,
Ribbon::MarkAngry, Ribbon::MarkSmiley, Ribbon::MarkTeary, Ribbon::MarkUpbeat,
Ribbon::MarkPeeved, Ribbon::MarkIntellectual, Ribbon::MarkFerocious,
Ribbon::MarkCrafty, Ribbon::MarkScowling, Ribbon::MarkKindly,
Ribbon::MarkFlustered, Ribbon::MarkPumpedUp, Ribbon::MarkZeroEnergy,
Ribbon::MarkPrideful, Ribbon::MarkUnsure, Ribbon::MarkHumble,
Ribbon::MarkThorny, Ribbon::MarkVigor, Ribbon::MarkSlump};
for (Ribbon ribbon : RIBBONS_TO_TRANSFER)
{
pk8->ribbon(ribbon, wc8.ribbon(ribbon));
}
if (wc8.egg())
{
pk8->eggDate(Date::today());
pk8->nickname(i18n::species(pk8->language(), Species::None));
pk8->nicknamed(true);
}
pk8->currentFriendship(pk8->baseFriendship());
pk8->height(pksm::randomNumber(0, 0x80) + pksm::randomNumber(0, 0x7F));
pk8->weight(pksm::randomNumber(0, 0x80) + pksm::randomNumber(0, 0x7F));
pk8->nature(wc8.nature() == Nature::INVALID ? Nature{u8(pksm::randomNumber(0, 24))}
: wc8.nature());
pk8->origNature(pk8->nature());
pk8->gender(
PKX::genderFromRatio(pksm::randomNumber(0, 0xFFFFFFFF), pk8->genderType()));
// Ability
switch (wc8.abilityType())
{
case 0:
case 1:
case 2:
pk8->setAbility(wc8.abilityType());
break;
case 3:
case 4:
pk8->setAbility(pksm::randomNumber(0, wc8.abilityType() - 2));
break;
}
// PID
switch (wc8.PIDType())
{
case 0: // Fixed value
pk8->PID(wc8.PID());
break;
case 1: // Random
pk8->PID(pksm::randomNumber(0, 0xFFFFFFFF));
break;
case 5: // Always star shiny
pk8->PID(pksm::randomNumber(0, 0xFFFFFFFF));
pk8->PID(((pk8->TID() ^ pk8->SID() ^ (pk8->PID() & 0xFFFF) ^ 1) << 16) |
(pk8->PID() & 0xFFFF));
break;
case 6: // Always square shiny
pk8->PID(pksm::randomNumber(0, 0xFFFFFFFF));
pk8->PID(((pk8->TID() ^ pk8->SID() ^ (pk8->PID() & 0xFFFF) ^ 0) << 16) |
(pk8->PID() & 0xFFFF));
break;
case 3: // Never shiny
pk8->PID(pksm::randomNumber(0, 0xFFFFFFFF));
pk8->shiny(false);
break;
}
// IVs
int numPerfectIVs = 0;
for (Stat stat :
{Stat::HP, Stat::ATK, Stat::DEF, Stat::SPD, Stat::SPATK, Stat::SPDEF})
{
if (wc8.iv(stat) - 0xFC < 3)
{
numPerfectIVs = wc8.iv(stat) - 0xFB;
break;
}
}
for (int iv = 0; iv < numPerfectIVs; iv++)
{
Stat setMeTo31 = Stat(pksm::randomNumber(0, 5));
while (pk8->iv(setMeTo31) == 31)
{
setMeTo31 = Stat(pksm::randomNumber(0, 5));
}
pk8->iv(setMeTo31, 31);
}
for (Stat stat :
{Stat::HP, Stat::ATK, Stat::DEF, Stat::SPD, Stat::SPATK, Stat::SPDEF})
{
if (pk8->iv(stat) != 31)
{
pk8->iv(stat, pksm::randomNumber(0, 31));
}
}
pk8->refreshChecksum();
pkm(*pk8, injectPosition / 30, injectPosition % 30, false);
}
else if (wc8.item())
{
auto valid = validItems();
auto limits = pouches();
for (int itemNum = 0; itemNum < wc8.items(); itemNum++)
{
bool currentSet = false;
for (size_t pouch = 0; pouch < limits.size(); pouch++)
{
auto validPouch = std::ranges::find_if(valid,
[&](const auto& i) {
return i.first == limits[pouch].first;
})->second;
// Check this is the correct pouch
if (!currentSet && std::binary_search(validPouch.begin(), validPouch.end(),
wc8.object(itemNum)))
{
for (int slot = 0; slot < limits[pouch].second; slot++)
{
auto occupying = item(limits[pouch].first, slot);
if (occupying->id() == 0)
{
occupying->id(wc8.object(itemNum));
occupying->count(wc8.objectQuantity(itemNum));
static_cast<Item8*>(occupying.get())->newFlag(true);
item(*occupying, limits[pouch].first, slot);
currentSet = true;
break;
}
else if (occupying->id() == wc8.object(itemNum) &&
limits[pouch].first != Pouch::TM)
{
occupying->count(occupying->count() + 1);
item(*occupying, limits[pouch].first, slot);
currentSet = true;
break;
}
}
}
}
}
}
else if (wc8.BP())
{
// TODO
}
else if (wc8.clothing())
{
// TODO
}
}
}
std::unique_ptr<WCX> SavSWSH::mysteryGift(int) const
{
return nullptr;
}
void SavSWSH::dex(const PKX& pk)
{
u8* entryAddr = nullptr;
if (!pk.egg())
{
if (u16 index = ((PK8&)pk).pokedexIndex())
{
entryAddr = getBlock(PokeDex)->decryptedData() + sizeof(DexEntry) * (index - 1);
}
else if (u16 index = static_cast<const PK8&>(pk).armordexIndex())
{
entryAddr = getBlock(ArmorDex)->decryptedData() + sizeof(DexEntry) * (index - 1);
}
else if (u16 index = static_cast<const PK8&>(pk).crowndexIndex())
{
entryAddr = getBlock(CrownDex)->decryptedData() + sizeof(DexEntry) * (index - 1);
}
}
if (entryAddr)
{
DexEntry entry = LittleEndian::convertTo<DexEntry>(entryAddr);
u16 form = pk.alternativeForm();
if (pk.species() == Species::Alcremie)
{
form *= 7;
form += static_cast<const PK8&>(pk).formDuration();
}
else if (pk.species() == Species::Eternatus)
{
form = 0;
setProperGiga(entry, true, pk.shiny(), pk.gender());
}
setProperLocation(entry, form, pk.shiny(), pk.gender());
entry.owned = 1;
entry.languages |= 1 << u8(pk.language());
entry.displayFormID = form;
entry.displayShiny = pk.shiny() ? 1 : 0;
if (entry.battled == 0)
{
entry.battled++;
}
LittleEndian::convertFrom<DexEntry>(entryAddr, entry);
}
}
int SavSWSH::dexSeen() const
{
int ret = 0;
for (const auto& i : availableSpecies())
{
u16 index = PersonalSWSH::pokedexIndex(u16(i));
u8* entryOffset = getBlock(PokeDex)->decryptedData() + index * sizeof(DexEntry);
for (size_t j = 0; j < 0x20; j++) // Entire seen region size
{
if (entryOffset[j])
{
ret++;
break;
}
}
}
return ret;
}
int SavSWSH::dexCaught() const
{
int ret = 0;
for (const auto& i : availableSpecies())
{
u16 index = PersonalSWSH::pokedexIndex(u16(i));
u8* entryOffset = getBlock(PokeDex)->decryptedData() + index * sizeof(DexEntry);
if (entryOffset[0x20] & 3)
{
ret++;
}
}
return ret;
}
}
| 40,530
|
C++
|
.cpp
| 894
| 32.534676
| 100
| 0.517505
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,234
|
SavFRLG.cpp
|
FlagBrew_PKSM-Core/source/sav/SavFRLG.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62, Pk11
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavFRLG.hpp"
namespace pksm
{
SavFRLG::SavFRLG(const std::shared_ptr<u8[]>& dt) : Sav3(dt, {0x44, 0x5F8, 0xB98})
{
game = Game::FRLG;
OFS_PCItem = blockOfs[1] + 0x0298;
OFS_PouchHeldItem = blockOfs[1] + 0x0310;
OFS_PouchKeyItem = blockOfs[1] + 0x03B8;
OFS_PouchBalls = blockOfs[1] + 0x0430;
OFS_PouchTMHM = blockOfs[1] + 0x0464;
OFS_PouchBerry = blockOfs[1] + 0x054C;
eventFlag = blockOfs[1] + 0xEE0;
// EventConst = blockOfs[2] + 0x80;
// DaycareOffset = blockOfs[4] + 0x100;
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavFRLG::validItems() const
{
static constexpr std::array validItems = {// Normal
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40, 41, 42, 65, 66, 67, 68, 69, 43, 44, 70, 71, 72, 73, 74, 75, 45, 46, 47, 48, 49,
50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 61, 63, 64, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227,
228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244,
245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
262, 263, 264,
// Ball
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
// Key
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
// TM
328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361,
362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377,
// Berry
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182,
183, 201, 202, 203, 204, 205, 206, 207, 208};
return {
std::pair{Pouch::NormalItem, std::span{validItems.begin(), validItems.begin() + 139} },
std::pair{Pouch::Ball, std::span{validItems.begin() + 139, validItems.begin() + 151}},
std::pair{
Pouch::KeyItem, std::span{validItems.begin() + 151, validItems.begin() + 180}},
std::pair{Pouch::TM, std::span{validItems.begin() + 180, validItems.begin() + 230}},
std::pair{Pouch::Berry, std::span{validItems.begin() + 230, validItems.end()} },
std::pair{Pouch::PCItem, std::span{validItems} }
};
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavFRLG::validItems3() const
{
static constexpr std::array validItems = {// Normal
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 63, 64, 65, 66, 67,
68, 69, 70, 71, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 93, 94, 95, 96, 97,
98, 103, 104, 106, 107, 108, 109, 110, 111, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192,
193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 254,
255, 256, 257, 258,
// Ball
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
// TM
289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305,
306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322,
323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339,
340, 341, 342, 343, 344, 345, 346,
// Berry
133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166,
167, 168, 169, 170, 171, 172, 173, 174, 175,
// Key
259, 260, 261, 262, 263, 264, 265, 266, 268, 269, 270, 271, 272, 273, 274, 275, 276,
277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 349, 350, 351, 352, 353,
354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370,
371, 372, 373, 374};
return {
std::pair{Pouch::NormalItem, std::span{validItems.begin(), validItems.begin() + 139} },
std::pair{Pouch::Ball, std::span{validItems.begin() + 139, validItems.begin() + 151}},
std::pair{Pouch::TM, std::span{validItems.begin() + 151, validItems.begin() + 209}},
std::pair{Pouch::Berry, std::span{validItems.begin() + 209, validItems.begin() + 252}},
std::pair{Pouch::KeyItem, std::span{validItems.begin() + 252, validItems.end()} },
std::pair{Pouch::PCItem, std::span{validItems} }
};
}
}
| 6,890
|
C++
|
.cpp
| 112
| 52.401786
| 104
| 0.549756
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,235
|
Sav7.cpp
|
FlagBrew_PKSM-Core/source/sav/Sav7.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.&gnu[g/licenses/]>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/Sav7.hpp"
#include "pkx/PK7.hpp"
#include "utils/endian.hpp"
#include "utils/i18n.hpp"
#include "utils/utils.hpp"
#include "wcx/WC7.hpp"
namespace pksm
{
u16 Sav7::TID(void) const
{
return LittleEndian::convertTo<u16>(&data[TrainerCard]);
}
void Sav7::TID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[TrainerCard], v);
}
u16 Sav7::SID(void) const
{
return LittleEndian::convertTo<u16>(&data[TrainerCard + 2]);
}
void Sav7::SID(u16 v)
{
LittleEndian::convertFrom<u16>(&data[TrainerCard + 2], v);
}
GameVersion Sav7::version(void) const
{
return GameVersion(data[TrainerCard + 4]);
}
void Sav7::version(GameVersion v)
{
data[TrainerCard + 4] = u8(v);
}
Gender Sav7::gender(void) const
{
return Gender{data[TrainerCard + 5]};
}
void Sav7::gender(Gender v)
{
data[TrainerCard + 5] = u8(v);
}
u8 Sav7::subRegion(void) const
{
return data[TrainerCard + 0x2E];
}
void Sav7::subRegion(u8 v)
{
data[TrainerCard + 0x2E] = v;
}
u8 Sav7::country(void) const
{
return data[TrainerCard + 0x2F];
}
void Sav7::country(u8 v)
{
data[TrainerCard + 0x2F] = v;
}
u8 Sav7::consoleRegion(void) const
{
return data[TrainerCard + 0x34];
}
void Sav7::consoleRegion(u8 v)
{
data[TrainerCard + 0x34] = v;
}
Language Sav7::language(void) const
{
return Language(data[TrainerCard + 0x35]);
}
void Sav7::language(Language v)
{
data[TrainerCard + 0x35] = u8(v);
}
std::string Sav7::otName(void) const
{
return StringUtils::transString67(
StringUtils::getString(data.get(), TrainerCard + 0x38, 13));
}
void Sav7::otName(const std::string_view& v)
{
return StringUtils::setString(
data.get(), StringUtils::transString67(v), TrainerCard + 0x38, 13);
}
u32 Sav7::money(void) const
{
return LittleEndian::convertTo<u32>(&data[Misc + 0x4]);
}
void Sav7::money(u32 v)
{
LittleEndian::convertFrom<u32>(&data[Misc + 0x4], v > 9999999 ? 9999999 : v);
}
u32 Sav7::BP(void) const
{
return LittleEndian::convertTo<u32>(&data[Misc + 0x11C]);
}
void Sav7::BP(u32 v)
{
LittleEndian::convertFrom<u32>(&data[Misc + 0x11C], v > 9999 ? 9999 : v);
}
u8 Sav7::badges(void) const
{
u32 badgeBits = (LittleEndian::convertTo<u32>(&data[Misc + 0x8]) << 13) >> 17;
u8 ret = 0;
for (size_t i = 0; i < sizeof(badgeBits) * 8; i++)
{
ret += (badgeBits & (u32(1) << i)) ? 1 : 0;
}
return ret;
}
u16 Sav7::playedHours(void) const
{
return LittleEndian::convertTo<u16>(&data[PlayTime]);
}
void Sav7::playedHours(u16 v)
{
LittleEndian::convertFrom<u16>(&data[PlayTime], v);
}
u8 Sav7::playedMinutes(void) const
{
return data[PlayTime + 2];
}
void Sav7::playedMinutes(u8 v)
{
data[PlayTime + 2] = v;
}
u8 Sav7::playedSeconds(void) const
{
return data[PlayTime + 3];
}
void Sav7::playedSeconds(u8 v)
{
data[PlayTime + 3] = v;
}
u8 Sav7::currentBox(void) const
{
return data[LastViewedBox];
}
void Sav7::currentBox(u8 v)
{
data[LastViewedBox] = v;
}
u8 Sav7::unlockedBoxes(void) const
{
return data[LastViewedBox - 2];
}
void Sav7::unlockedBoxes(u8 v)
{
data[LastViewedBox - 2] = v;
}
u32 Sav7::boxOffset(u8 box, u8 slot) const
{
return Box + PK7::BOX_LENGTH * 30 * box + PK7::BOX_LENGTH * slot;
}
u32 Sav7::partyOffset(u8 slot) const
{
return Party + PK7::PARTY_LENGTH * slot;
}
std::unique_ptr<PKX> Sav7::pkm(u8 slot) const
{
return PKX::getPKM<Generation::SEVEN>(&data[partyOffset(slot)], PK7::PARTY_LENGTH);
}
void Sav7::pkm(const PKX& pk, u8 slot)
{
if (pk.generation() == Generation::SEVEN)
{
auto pk7 = pk.partyClone();
pk7->encrypt();
std::ranges::copy(pk7->rawData(), &data[partyOffset(slot)]);
}
}
std::unique_ptr<PKX> Sav7::pkm(u8 box, u8 slot) const
{
return PKX::getPKM<Generation::SEVEN>(&data[boxOffset(box, slot)], PK7::BOX_LENGTH);
}
void Sav7::pkm(const PKX& pk, u8 box, u8 slot, bool applyTrade)
{
if (pk.generation() == Generation::SEVEN)
{
auto pkm = pk.clone();
if (applyTrade)
{
trade(*pkm);
}
std::ranges::copy(
pkm->rawData().subspan(0, PK7::BOX_LENGTH), &data[boxOffset(box, slot)]);
}
}
void Sav7::trade(PKX& pk, const Date& date) const
{
if (pk.generation() == Generation::SEVEN)
{
PK7& pk7 = static_cast<PK7&>(pk);
if (pk7.egg())
{
if (otName() != pk7.otName() || TID() != pk7.TID() || SID() != pk7.SID() ||
gender() != pk7.otGender())
{
pk7.metLocation(30002);
pk7.metDate(date);
}
}
else if (otName() == pk7.otName() && TID() == pk7.TID() && SID() == pk7.SID() &&
gender() == pk7.otGender())
{
pk7.currentHandler(PKXHandler::OT);
}
else
{
if (pk7.htName() != otName())
{
pk7.htFriendship(pk7.baseFriendship());
pk7.htAffection(0);
pk7.htName(otName());
}
pk7.currentHandler(PKXHandler::NonOT);
pk7.htGender(gender());
}
}
}
void Sav7::cryptBoxData(bool crypted)
{
for (u8 box = 0; box < maxBoxes(); box++)
{
for (u8 slot = 0; slot < 30; slot++)
{
std::unique_ptr<PKX> pk7 = PKX::getPKM<Generation::SEVEN>(
&data[boxOffset(box, slot)], PK7::BOX_LENGTH, true);
if (!crypted)
{
pk7->encrypt();
}
}
}
}
void Sav7::setDexFlags(int index, int gender, int shiny, int baseSpecies)
{
const int brSize = 0x8C;
int shift = gender | (shiny << 1);
int ofs = PokeDex + 0x08 + 0x80 + 0x68;
int bd = index >> 3;
int bm = index & 7;
int bd1 = baseSpecies >> 3;
int bm1 = baseSpecies & 7;
int brSeen = shift * brSize;
data[ofs + brSeen + bd] |= 1 << bm;
bool displayed = false;
for (u8 i = 0; i < 4; i++)
{
int brDisplayed = (4 + i) * brSize;
displayed |= (data[ofs + brDisplayed + bd1] & (1 << bm1)) != 0;
}
if (!displayed && baseSpecies != index)
{
for (u8 i = 0; i < 4; i++)
{
int brDisplayed = (4 + i) * brSize;
displayed |= (data[ofs + brDisplayed + bd] & (1 << bm)) != 0;
}
}
if (displayed)
{
return;
}
data[ofs + (4 + shift) * brSize + bd] |= (1 << bm);
}
int Sav7::getDexFlags(int index, int baseSpecies) const
{
int ret = 0;
const int brSize = 0x8C;
int ofs = PokeDex + 0x08 + 0x80 + 0x68;
int bd = index >> 3;
int bm = index & 7;
int bd1 = baseSpecies >> 3;
int bm1 = baseSpecies & 7;
for (u8 i = 0; i < 4; i++)
{
if (data[ofs + i * brSize + bd] & (1 << bm))
{
ret++;
}
if (data[ofs + i * brSize + bd1] & (1 << bm1))
{
ret++;
}
}
return ret;
}
bool Sav7::sanitizeFormsToIterate(Species species, int& fs, int& fe, int formIn) const
{
switch (species)
{
case Species::Castform: // Castform
fs = 0;
fe = 3;
return true;
case Species::Cherrim: // 421:
case Species::Darmanitan: // 555:
case Species::Meloetta: // 648:
case Species::Wishiwashi: // 746:
case Species::Mimikyu: // 778:
// Alolans
case Species::Raticate: // 020:
case Species::Marowak: // 105:
fs = 0;
fe = 1;
return true;
case Species::Gumshoos: // 735:
case Species::Salazzle: // 758:
case Species::Lurantis: // 754:
case Species::Vikavolt: // 738:
case Species::Kommoo: // 784:
case Species::Araquanid: // 752:
case Species::Togedemaru: // 777:
case Species::Ribombee: // 743:
case Species::Rockruff: // 744:
break;
case Species::Minior: // 774:
if (formIn <= 6)
{
break;
}
else
{
int count = dexFormCount(u16(species));
fs = 0;
fe = 0;
return count < formIn;
}
case Species::Zygarde: // 718:
if (formIn > 1)
{
break;
}
else
{
int count = dexFormCount(u16(species));
fs = 0;
fe = 0;
return count < formIn;
}
default:
break;
}
fs = 0;
fe = 0;
return true;
}
void Sav7::dex(const PKX& pk)
{
if (!(availableSpecies().count(pk.species()) > 0) || pk.egg())
{
return;
}
int bit = u16(pk.species()) - 1;
int bd = bit >> 3;
int bm = bit & 7;
int gender = u8(pk.gender()) % 2;
int shiny = pk.shiny() ? 1 : 0;
if (pk.species() == Species::Castform)
{
shiny = 0;
}
int shift = gender | (shiny << 1);
if (pk.species() == Species::Spinda)
{
if ((data[PokeDex + 0x84] & (1 << (shift + 4))) != 0)
{ // Already 2
LittleEndian::convertFrom<u32>(
&data[PokeDex + 0x8E8 + shift * 4], pk.encryptionConstant());
data[PokeDex + 0x84] |= (u8)(1 << shift);
}
else if ((data[PokeDex + 0x84] & (1 << shift)) == 0)
{ // Not yet 1
data[PokeDex + 0x84] |= (u8)(1 << shift); // 1
}
}
int off = PokeDex + 0x08 + 0x80;
data[off + bd] |= 1 << bm;
int formstart = pk.alternativeForm();
int formend = formstart;
int fs = 0, fe = 0;
if (sanitizeFormsToIterate(pk.species(), fs, fe, formstart))
{
formstart = fs;
formend = fe;
}
for (int form = formstart; form <= formend; form++)
{
int bitIndex = bit;
if (form > 0)
{
u8 fc = PersonalSMUSUM::formCount(u16(pk.species()));
if (fc > 1)
{ // actually has forms
int f = dexFormIndex(
u16(pk.species()), fc, u16(VersionTables::maxSpecies(version())) - 1);
if (f >= 0)
{ // bit index valid
bitIndex = f + form;
}
}
}
setDexFlags(bitIndex, gender, shiny, u16(pk.species()) - 1);
}
int lang = u8(pk.language());
const int langCount = 9;
if (lang <= 10 && lang != 6 && lang != 0)
{
if (lang >= 7)
{
lang--;
}
lang--;
if (lang < 0)
{
lang = 1;
}
int lbit = bit * langCount + lang;
if (lbit >> 3 < 920)
{
data[PokeDexLanguageFlags + (lbit >> 3)] |= (1 << (lbit & 7));
}
}
}
int Sav7::dexSeen(void) const
{
int ret = 0;
for (const auto& spec : availableSpecies())
{
u16 species = u16(spec);
int forms = formCount(spec);
for (int form = 0; form < forms; form++)
{
int dexForms = form == 0 ? -1
: dexFormIndex(species, forms,
u16(VersionTables::maxSpecies(version())) - 1);
int index = species - 1;
if (dexForms >= 0)
{
index = dexForms + form;
}
if (getDexFlags(index, species) > 0)
{
ret++;
break;
}
}
}
return ret;
}
int Sav7::dexCaught(void) const
{
int ret = 0;
for (const auto& spec : availableSpecies())
{
u16 i = u16(spec);
int bitIndex = (i - 1) & 7;
int ofs = PokeDex + 0x88 + ((i - 1) >> 3);
if ((data[ofs] >> bitIndex & 1) != 0)
{
ret++;
}
}
return ret;
}
void Sav7::mysteryGift(const WCX& wc, int& pos)
{
if (wc.generation() == Generation::SEVEN)
{
data[WondercardFlags + wc.ID() / 8] |= 0x1 << (wc.ID() % 8);
std::copy(wc.rawData(), wc.rawData() + WC7::length,
&data[WondercardData + WC7::length * pos]);
pos = (pos + 1) % maxWondercards();
}
}
std::string Sav7::boxName(u8 box) const
{
return StringUtils::transString67(
StringUtils::getString(data.get(), PCLayout + 0x22 * box, 17));
}
void Sav7::boxName(u8 box, const std::string_view& name)
{
StringUtils::setString(
data.get(), StringUtils::transString67(name), PCLayout + 0x22 * box, 17);
}
u8 Sav7::boxWallpaper(u8 box) const
{
return data[PCLayout + 1472 + box];
}
void Sav7::boxWallpaper(u8 box, u8 v)
{
data[PCLayout + 1472 + box] = v;
}
u8 Sav7::partyCount(void) const
{
return data[Party + 6 * PK7::PARTY_LENGTH];
}
void Sav7::partyCount(u8 v)
{
data[Party + 6 * PK7::PARTY_LENGTH] = v;
}
std::unique_ptr<PKX> Sav7::emptyPkm() const
{
return PKX::getPKM<Generation::SEVEN>(nullptr, PK7::BOX_LENGTH);
}
int Sav7::currentGiftAmount(void) const
{
u8 t;
// 48 max wonder cards
for (t = 0; t < 48; t++)
{
bool empty = true;
for (u32 j = 0; j < WC7::length; j++)
{
if (data[WondercardData + t * WC7::length + j] != 0)
{
empty = false;
break;
}
}
if (empty)
{
break;
}
}
return t;
}
std::unique_ptr<WCX> Sav7::mysteryGift(int pos) const
{
return std::make_unique<WC7>(&data[WondercardData + pos * WC7::length]);
}
void Sav7::item(const Item& item, Pouch pouch, u16 slot)
{
Item7 inject = static_cast<Item7>(item);
auto write = inject.bytes();
switch (pouch)
{
case Pouch::NormalItem:
std::copy(write.begin(), write.end(), &data[PouchHeldItem + slot * 4]);
break;
case Pouch::KeyItem:
std::copy(write.begin(), write.end(), &data[PouchKeyItem + slot * 4]);
break;
case Pouch::TM:
std::copy(write.begin(), write.end(), &data[PouchTMHM + slot * 4]);
break;
case Pouch::Medicine:
std::copy(write.begin(), write.end(), &data[PouchMedicine + slot * 4]);
break;
case Pouch::Berry:
std::copy(write.begin(), write.end(), &data[PouchBerry + slot * 4]);
break;
case Pouch::ZCrystals:
std::copy(write.begin(), write.end(), &data[PouchZCrystals + slot * 4]);
break;
case Pouch::RotomPower:
std::copy(write.begin(), write.end(), &data[BattleItems + slot * 4]);
break;
default:
return;
}
}
std::unique_ptr<Item> Sav7::item(Pouch pouch, u16 slot) const
{
switch (pouch)
{
case Pouch::NormalItem:
return std::make_unique<Item7>(&data[PouchHeldItem + slot * 4]);
case Pouch::KeyItem:
return std::make_unique<Item7>(&data[PouchKeyItem + slot * 4]);
case Pouch::TM:
return std::make_unique<Item7>(&data[PouchTMHM + slot * 4]);
case Pouch::Medicine:
return std::make_unique<Item7>(&data[PouchMedicine + slot * 4]);
case Pouch::Berry:
return std::make_unique<Item7>(&data[PouchBerry + slot * 4]);
case Pouch::ZCrystals:
return std::make_unique<Item7>(&data[PouchZCrystals + slot * 4]);
case Pouch::RotomPower:
return std::make_unique<Item7>(&data[BattleItems + slot * 4]);
default:
return nullptr;
}
}
SmallVector<std::pair<Sav::Pouch, int>, 15> Sav7::pouches(void) const
{
SmallVector<std::pair<Pouch, int>, 15> pouches = {
std::pair{Pouch::NormalItem, game == Game::SM ? 430 : 427},
std::pair{Pouch::KeyItem, game == Game::SM ? 184 : 198},
std::pair{Pouch::TM, 108 },
std::pair{Pouch::Medicine, game == Game::SM ? 64 : 60 },
std::pair{Pouch::Berry, game == Game::SM ? 72 : 67 },
std::pair{Pouch::ZCrystals, game == Game::SM ? 30 : 35 }
};
if (game == Game::USUM)
{
pouches.push_back({Pouch::RotomPower, 11});
}
return pouches;
}
}
| 20,195
|
C++
|
.cpp
| 625
| 22.032
| 94
| 0.474519
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,236
|
SavDP.cpp
|
FlagBrew_PKSM-Core/source/sav/SavDP.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavDP.hpp"
#include "wcx/PGT.hpp"
namespace pksm
{
SavDP::SavDP(const std::shared_ptr<u8[]>& dt) : Sav4(dt, 0x80000)
{
game = Game::DP;
GBOOffset = 0xC0EC;
SBOOffset = 0x1E2CC;
GBO();
SBO();
Trainer1 = 0x64 + gbo;
Party = 0x98 + gbo;
PokeDex = 0x12DC + gbo;
WondercardFlags = 0xA6D0 + gbo;
WondercardData = 0xA7FC + gbo;
PouchHeldItem = 0x624 + gbo;
PouchKeyItem = 0x8B8 + gbo;
PouchTMHM = 0x980 + gbo;
MailItems = 0xB10 + gbo;
PouchMedicine = 0xB40 + gbo;
PouchBerry = 0xBE0 + gbo;
PouchBalls = 0xCE0 + gbo;
BattleItems = 0xD1C + gbo;
PalPark = 0xBA28 + gbo;
Box = 0xC104 + sbo;
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavDP::validItems() const
{
static constexpr std::array NormalItem = {68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 135, 136, 213, 214, 215, 216,
217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250,
251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267,
268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301,
302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318,
319, 320, 321, 322, 323, 324, 325, 326, 327};
static constexpr std::array KeyItem = {428, 429, 430, 431, 432, 433, 434, 435, 436, 437,
438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454,
455, 456, 457, 458, 459, 460, 461, 462, 463, 464};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427};
static constexpr std::array Mail = {
137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212};
static constexpr std::array Ball = {1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
static constexpr std::array Battle = {55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Mail, std::span{Mail} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} },
std::pair{Pouch::Ball, std::span{Ball} },
std::pair{Pouch::Battle, std::span{Battle} }
};
}
SmallVector<std::pair<Sav::Pouch, int>, 15> SavDP::pouches(void) const
{
return {
std::pair{Pouch::NormalItem, 161},
std::pair{Pouch::KeyItem, 37 },
std::pair{Pouch::TM, 100},
std::pair{Pouch::Mail, 12 },
std::pair{Pouch::Medicine, 38 },
std::pair{Pouch::Berry, 64 },
std::pair{Pouch::Ball, 15 },
std::pair{Pouch::Battle, 13 }
};
}
}
| 6,030
|
C++
|
.cpp
| 111
| 46.027027
| 99
| 0.557155
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,237
|
SavBW.cpp
|
FlagBrew_PKSM-Core/source/sav/SavBW.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "sav/SavBW.hpp"
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include <algorithm>
namespace pksm
{
SavBW::SavBW(const std::shared_ptr<u8[]>& dt) : Sav5(dt, 0x80000)
{
game = Game::BW;
PCLayout = 0x0;
Trainer1 = 0x19400;
Trainer2 = 0x21200;
BattleSubway = 0x21D00;
Party = 0x18E00;
PokeDex = 0x21600;
PokeDexLanguageFlags = 0x21920;
WondercardFlags = 0x1C800;
WondercardData = 0x1C900;
PouchHeldItem = 0x18400;
PouchKeyItem = 0x188D8;
PouchTMHM = 0x18A24;
PouchMedicine = 0x18BD8;
PouchBerry = 0x18C98;
Box = 0x400;
}
void SavBW::resign(void)
{
const u8 blockCount = 70;
for (u8 i = 0; i < blockCount; i++)
{
u16 cs = pksm::crypto::ccitt16({&data[blockOfs[i]], lengths[i]});
LittleEndian::convertFrom<u16>(&data[chkMirror[i]], cs);
LittleEndian::convertFrom<u16>(&data[chkofs[i]], cs);
}
}
SmallVector<std::pair<Sav::Pouch, std::span<const int>>, 15> SavBW::validItems() const
{
static constexpr std::array NormalItem = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 116, 117, 118,
119, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 213, 214,
215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265,
266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282,
283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299,
300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316,
317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 492, 493, 494, 495, 496, 497,
498, 499, 500, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550,
551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 571, 572, 573,
575, 576, 577, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590};
static constexpr std::array KeyItem = {437, 442, 447, 450, 465, 466, 471, 504, 533, 574,
578, 579, 616, 617, 621, 623, 624, 625, 626};
static constexpr std::array TM = {328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338,
339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355,
356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389,
390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406,
407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 618, 619, 620, 420,
421, 422, 423, 424, 425};
static constexpr std::array Medicine = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 134, 504, 565, 566, 567, 568, 569, 570, 591};
static constexpr std::array Berry = {149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210,
211, 212};
return {
std::pair{Pouch::NormalItem, std::span{NormalItem}},
std::pair{Pouch::KeyItem, std::span{KeyItem} },
std::pair{Pouch::TM, std::span{TM} },
std::pair{Pouch::Medicine, std::span{Medicine} },
std::pair{Pouch::Berry, std::span{Berry} }
};
}
}
| 5,823
|
C++
|
.cpp
| 103
| 48.669903
| 100
| 0.565949
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,238
|
i18n_location.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_location.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/Generation.hpp"
#include "i18n_internal.hpp"
namespace i18n
{
struct Locations
{
std::map<u16, std::string> locations2;
std::map<u16, std::string> locations3;
std::map<u16, std::string> locations4;
std::map<u16, std::string> locations5;
std::map<u16, std::string> locations6;
std::map<u16, std::string> locations7;
std::map<u16, std::string> locationsLGPE;
std::map<u16, std::string> locations8;
void clear() noexcept
{
locations2.clear();
locations3.clear();
locations4.clear();
locations5.clear();
locations6.clear();
locations7.clear();
locationsLGPE.clear();
locations8.clear();
}
};
std::unordered_map<pksm::Language, Locations> locationss = std::invoke(
[]
{
std::unordered_map<pksm::Language, Locations> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initLocation(pksm::Language lang)
{
Locations tmp;
load(lang, "/locations2.txt", tmp.locations2);
load(lang, "/locations3.txt", tmp.locations3);
load(lang, "/locations4.txt", tmp.locations4);
load(lang, "/locations5.txt", tmp.locations5);
load(lang, "/locations6.txt", tmp.locations6);
load(lang, "/locations7.txt", tmp.locations7);
load(lang, "/locationsLGPE.txt", tmp.locationsLGPE);
load(lang, "/locations8.txt", tmp.locations8);
locationss.insert_or_assign(lang, std::move(tmp));
}
void exitLocation(pksm::Language lang)
{
locationss[lang].clear();
}
const std::string& location(pksm::Language lang, pksm::Generation gen, u16 v)
{
checkInitialized(lang);
switch (gen)
{
case pksm::Generation::TWO:
if (locationss[lang].locations2.count(v) > 0)
{
return locationss[lang].locations2[v];
}
break;
case pksm::Generation::THREE:
if (locationss[lang].locations3.count(v) > 0)
{
return locationss[lang].locations3[v];
}
break;
case pksm::Generation::FOUR:
if (locationss[lang].locations4.count(v) > 0)
{
return locationss[lang].locations4[v];
}
break;
case pksm::Generation::FIVE:
if (locationss[lang].locations5.count(v) > 0)
{
return locationss[lang].locations5[v];
}
break;
case pksm::Generation::SIX:
if (locationss[lang].locations6.count(v) > 0)
{
return locationss[lang].locations6[v];
}
break;
case pksm::Generation::SEVEN:
if (locationss[lang].locations7.count(v) > 0)
{
return locationss[lang].locations7[v];
}
break;
case pksm::Generation::LGPE:
if (locationss[lang].locationsLGPE.count(v) > 0)
{
return locationss[lang].locationsLGPE[v];
}
break;
case pksm::Generation::EIGHT:
if (locationss[lang].locations8.count(v) > 0)
{
return locationss[lang].locations8[v];
}
break;
case pksm::Generation::UNUSED:
case pksm::Generation::ONE:
break;
}
return emptyString;
}
const std::map<u16, std::string>& rawLocations(pksm::Language lang, pksm::Generation g)
{
checkInitialized(lang);
switch (g)
{
case pksm::Generation::TWO:
return locationss[lang].locations2;
case pksm::Generation::THREE:
return locationss[lang].locations3;
case pksm::Generation::FOUR:
return locationss[lang].locations4;
case pksm::Generation::FIVE:
return locationss[lang].locations5;
case pksm::Generation::SIX:
return locationss[lang].locations6;
case pksm::Generation::SEVEN:
return locationss[lang].locations7;
case pksm::Generation::LGPE:
return locationss[lang].locationsLGPE;
case pksm::Generation::EIGHT:
return locationss[lang].locations8;
case pksm::Generation::UNUSED:
case pksm::Generation::ONE:
break;
}
return emptyU16Map;
}
}
| 6,137
|
C++
|
.cpp
| 162
| 27.12963
| 91
| 0.564605
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,239
|
i18n_move.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_move.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> moves = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initMove(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/moves.txt", vec);
moves.insert_or_assign(lang, std::move(vec));
}
void exitMove(pksm::Language lang)
{
moves[lang].clear();
}
const std::string& move(pksm::Language lang, pksm::Move val)
{
checkInitialized(lang);
if (size_t(val) < moves[lang].size())
{
return moves[lang][size_t(val)];
}
return emptyString;
}
const std::vector<std::string>& rawMoves(pksm::Language lang)
{
checkInitialized(lang);
return moves[lang];
}
}
const std::string& pksm::internal::Move_impl::localize(pksm::Language lang) const
{
return i18n::move(lang, *this);
}
| 2,372
|
C++
|
.cpp
| 64
| 32.203125
| 85
| 0.665797
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,240
|
i18n_form.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_form.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/GameVersion.hpp"
#include "enums/Species.hpp"
#include "i18n_internal.hpp"
#include "personal/personal.hpp"
#include "utils/VersionTables.hpp"
#include <ranges>
#include <span>
namespace
{
constexpr size_t Default = 0;
constexpr size_t Alolan = 1;
constexpr size_t RockStar = 2;
constexpr size_t Belle = 3;
constexpr size_t PopStar = 4;
constexpr size_t PhD = 5;
constexpr size_t Libre = 6;
constexpr size_t Cosplay = 7;
constexpr size_t Original = 8;
constexpr size_t Hoenn = 9;
constexpr size_t Sinnoh = 10;
constexpr size_t Unova = 11;
constexpr size_t Kalos = 12;
constexpr size_t Alola = 13;
constexpr size_t A = 14;
constexpr size_t B = 15;
constexpr size_t C = 16;
constexpr size_t D = 17;
constexpr size_t E = 18;
constexpr size_t F = 19;
constexpr size_t G = 20;
constexpr size_t H = 21;
constexpr size_t I = 22;
constexpr size_t J = 23;
constexpr size_t K = 24;
constexpr size_t L = 25;
constexpr size_t M = 26;
constexpr size_t N = 27;
constexpr size_t O = 28;
constexpr size_t P = 29;
constexpr size_t Q = 30;
constexpr size_t R = 31;
constexpr size_t S = 32;
constexpr size_t T = 33;
constexpr size_t U = 34;
constexpr size_t V = 35;
constexpr size_t W = 36;
constexpr size_t X = 37;
constexpr size_t Y = 38;
constexpr size_t Z = 39;
constexpr size_t ExclamationPoint = 40;
constexpr size_t QuestionMark = 41;
constexpr size_t Normal = 42;
constexpr size_t Attack = 43;
constexpr size_t Defense = 44;
constexpr size_t Speed = 45;
constexpr size_t Plant = 46;
constexpr size_t Sandy = 47;
constexpr size_t Trash = 48;
constexpr size_t WestSea = 49;
constexpr size_t EastSea = 50;
constexpr size_t Heat = 51;
constexpr size_t Wash = 52;
constexpr size_t Fridge = 53;
constexpr size_t Fan = 54;
constexpr size_t Mow = 55;
constexpr size_t Altered = 56;
constexpr size_t Origin = 57;
constexpr size_t Land = 58;
constexpr size_t Sky = 59;
constexpr size_t RedStriped = 60;
constexpr size_t BlueStriped = 61;
constexpr size_t Spring = 62;
constexpr size_t Summer = 63;
constexpr size_t Autumn = 64;
constexpr size_t Winter = 65;
constexpr size_t Incarnate = 66;
constexpr size_t Therian = 67;
constexpr size_t WhiteKyurem = 68;
constexpr size_t Black = 69;
constexpr size_t Ordinary = 70;
constexpr size_t Resolute = 71;
constexpr size_t Aria = 72;
constexpr size_t Pirouette = 73;
constexpr size_t BattleBond = 74;
constexpr size_t IcySnow = 75;
constexpr size_t Polar = 76;
constexpr size_t Tundra = 77;
constexpr size_t Continental = 78;
constexpr size_t Garden = 79;
constexpr size_t Elegant = 80;
constexpr size_t Meadow = 81;
constexpr size_t Modern = 82;
constexpr size_t Marine = 83;
constexpr size_t Archipelago = 84;
constexpr size_t HighPlains = 85;
constexpr size_t Sandstorm = 86;
constexpr size_t River = 87;
constexpr size_t Monsoon = 88;
constexpr size_t Savanna = 89;
constexpr size_t Sun = 90;
constexpr size_t Ocean = 91;
constexpr size_t Jungle = 92;
constexpr size_t Fancy = 93;
constexpr size_t PokeBall = 94;
constexpr size_t RedFlower = 95;
constexpr size_t YellowFlower = 96;
constexpr size_t OrangeFlower = 97;
constexpr size_t BlueFlower = 98;
constexpr size_t WhiteFlower = 99;
constexpr size_t EternalFlower = 100;
constexpr size_t Natural = 101;
constexpr size_t Heart = 102;
constexpr size_t Star = 103;
constexpr size_t Diamond = 104;
constexpr size_t Debutante = 105;
constexpr size_t Matron = 106;
constexpr size_t Dandy = 107;
constexpr size_t LaReine = 108;
constexpr size_t Kabuki = 109;
constexpr size_t Pharaoh = 110;
constexpr size_t Average = 111;
constexpr size_t Small = 112;
constexpr size_t Large = 113;
constexpr size_t Super = 114;
constexpr size_t _50Percent = 115;
constexpr size_t _10Percent = 116;
constexpr size_t _10Percent_PC = 117;
constexpr size_t _50Percent_PC = 118;
constexpr size_t Confined = 119;
constexpr size_t Unbound = 120;
constexpr size_t Baile = 121;
constexpr size_t PomPom = 122;
constexpr size_t Pau = 123;
constexpr size_t Sensu = 124;
constexpr size_t Midday = 125;
constexpr size_t Midnight = 126;
constexpr size_t Dusk = 127;
constexpr size_t CoveredRed = 128;
constexpr size_t CoveredOrange = 129;
constexpr size_t CoveredYellow = 130;
constexpr size_t CoveredGreen = 131;
constexpr size_t CoveredBlue = 132;
constexpr size_t CoveredIndigo = 133;
constexpr size_t CoveredViolet = 134;
constexpr size_t Red = 135;
constexpr size_t Orange = 136;
constexpr size_t Yellow = 137;
constexpr size_t Green = 138;
constexpr size_t Blue = 139;
constexpr size_t Indigo = 140;
constexpr size_t Violet = 141;
constexpr size_t OriginalColor = 142;
constexpr size_t SpikyEared = 143;
constexpr size_t Female = 144;
constexpr size_t Totem = 145;
constexpr size_t Mega = 146;
constexpr size_t DawnWings = 147;
constexpr size_t DuskMane = 148;
constexpr size_t Ultra = 149;
constexpr size_t Primal = 150;
constexpr size_t MegaX = 151;
constexpr size_t MegaY = 152;
constexpr size_t Partner = 153;
constexpr size_t _100Percent = 154;
constexpr size_t Fighting = 155;
constexpr size_t Flying = 156;
constexpr size_t Poison = 157;
constexpr size_t Ground = 158;
constexpr size_t Rock = 159;
constexpr size_t Bug = 160;
constexpr size_t Ghost = 161;
constexpr size_t Steel = 162;
constexpr size_t Fire = 163;
constexpr size_t Water = 164;
constexpr size_t Grass = 165;
constexpr size_t Electric = 166;
constexpr size_t Psychic = 167;
constexpr size_t Ice = 168;
constexpr size_t Dragon = 169;
constexpr size_t Dark = 170;
constexpr size_t Fairy = 171;
constexpr size_t Overcast = 172;
constexpr size_t Sunshine = 173;
constexpr size_t Zen = 174;
constexpr size_t Ash = 175;
constexpr size_t Shield = 176;
constexpr size_t Blade = 177;
constexpr size_t Solo = 178;
constexpr size_t School = 179;
constexpr size_t Sunny = 180;
constexpr size_t Rainy = 181;
constexpr size_t Snowy = 182;
constexpr size_t Galarian = 183;
constexpr size_t Gigantamax = 184;
constexpr size_t Gulping = 185;
constexpr size_t Gorging = 186;
constexpr size_t LowKey = 187;
constexpr size_t RubyCream = 188;
constexpr size_t MatchaCream = 189;
constexpr size_t MintCream = 190;
constexpr size_t LemonCream = 191;
constexpr size_t SaltedCream = 192;
constexpr size_t RubySwirl = 193;
constexpr size_t CaramelSwirl = 194;
constexpr size_t RainbowSwirl = 195;
constexpr size_t NoiceFace = 196;
constexpr size_t HangryMode = 197;
constexpr size_t Crowned = 198;
constexpr size_t Eternamax = 199;
constexpr size_t AmpedForm = 200;
constexpr size_t VanillaCream = 201;
constexpr size_t Phony = 202;
constexpr size_t Antique = 203;
constexpr size_t World = 204;
constexpr size_t SingleStrike = 205;
constexpr size_t RapidStrike = 206;
constexpr size_t Dada = 207;
constexpr size_t IceRider = 208;
constexpr size_t ShadowRider = 209;
}
#define FA(...) \
[]<std::array Values = {__VA_ARGS__}>() consteval \
->std::span<const typename decltype(Values)::value_type> \
{ \
return Values; \
} \
()
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> formss = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initForm(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/forms.txt", vec);
formss.insert_or_assign(lang, std::move(vec));
}
void exitForm(pksm::Language lang)
{
formss[lang].clear();
}
std::span<const size_t> formIndices(pksm::GameVersion version, pksm::Species species)
{
// TODO: Gigantamax. How do those work?
u8 forms = pksm::VersionTables::formCount(version, species);
std::span<const size_t> ret = FA(Default);
switch (species)
{
case pksm::Species::Venusaur:
ret = FA(Default, Mega);
break;
case pksm::Species::Charizard:
ret = FA(Default, MegaX, MegaY);
break;
case pksm::Species::Blastoise:
ret = FA(Default, Mega);
break;
case pksm::Species::Beedrill:
ret = FA(Default, Mega);
break;
case pksm::Species::Pidgeot:
ret = FA(Default, Mega);
break;
case pksm::Species::Rattata:
ret = FA(Default, Alolan);
break;
case pksm::Species::Raticate:
ret = FA(Default, Alolan, Totem);
break;
case pksm::Species::Pikachu:
switch ((pksm::Generation)version)
{
case pksm::Generation::SIX:
ret = FA(Default, RockStar, Belle, PopStar, PhD, Libre, Cosplay);
break;
case pksm::Generation::SEVEN:
case pksm::Generation::LGPE:
case pksm::Generation::EIGHT:
ret = FA(Default, Original, Hoenn, Sinnoh, Unova, Kalos, Alola, Partner,
Default, World);
break;
default:
break;
}
break;
case pksm::Species::Raichu:
ret = FA(Default, Alolan);
break;
case pksm::Species::Sandshrew:
case pksm::Species::Sandslash:
ret = FA(Default, Alolan);
break;
case pksm::Species::Vulpix:
case pksm::Species::Ninetales:
ret = FA(Default, Alolan);
break;
case pksm::Species::Diglett:
case pksm::Species::Dugtrio:
ret = FA(Default, Alolan);
break;
case pksm::Species::Meowth:
ret = FA(Default, Alolan, Galarian);
break;
case pksm::Species::Persian:
ret = FA(Default, Alolan);
break;
case pksm::Species::Alakazam:
ret = FA(Default, Mega);
break;
case pksm::Species::Geodude:
case pksm::Species::Graveler:
case pksm::Species::Golem:
ret = FA(Default, Alolan);
break;
case pksm::Species::Ponyta:
case pksm::Species::Rapidash:
ret = FA(Default, Galarian);
break;
case pksm::Species::Slowpoke:
ret = FA(Default, Galarian);
break;
case pksm::Species::Slowbro:
switch ((pksm::Generation)version)
{
case pksm::Generation::SIX:
case pksm::Generation::SEVEN:
ret = FA(Default, Mega);
break;
case pksm::Generation::EIGHT:
ret = FA(Default, Galarian);
break;
default:
break;
}
break;
case pksm::Species::Slowking:
ret = FA(Default, Galarian);
break;
case pksm::Species::Farfetchd:
ret = FA(Default, Galarian);
break;
case pksm::Species::Grimer:
case pksm::Species::Muk:
ret = FA(Default, Alolan);
break;
case pksm::Species::Gengar:
ret = FA(Default, Mega);
break;
case pksm::Species::Exeggutor:
ret = FA(Default, Alolan);
break;
case pksm::Species::Marowak:
ret = FA(Default, Alolan, Totem);
break;
case pksm::Species::Weezing:
ret = FA(Default, Galarian);
break;
case pksm::Species::Kangaskhan:
ret = FA(Default, Mega);
break;
case pksm::Species::MrMime:
ret = FA(Default, Galarian);
break;
case pksm::Species::Pinsir:
ret = FA(Default, Mega);
break;
case pksm::Species::Gyarados:
ret = FA(Default, Mega);
break;
case pksm::Species::Eevee:
ret = FA(Default, Default);
break;
case pksm::Species::Aerodactyl:
ret = FA(Default, Mega);
break;
case pksm::Species::Articuno:
ret = FA(Default, Galarian);
break;
case pksm::Species::Zapdos:
ret = FA(Default, Galarian);
break;
case pksm::Species::Moltres:
ret = FA(Default, Galarian);
break;
case pksm::Species::Mewtwo:
ret = FA(Default, MegaX, MegaY);
break;
case pksm::Species::Pichu:
ret = FA(Default, SpikyEared);
break;
case pksm::Species::Ampharos:
ret = FA(Default, Mega);
break;
case pksm::Species::Unown:
ret = FA(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z, ExclamationPoint, QuestionMark);
break;
case pksm::Species::Steelix:
ret = FA(Default, Mega);
break;
case pksm::Species::Scizor:
ret = FA(Default, Mega);
break;
case pksm::Species::Heracross:
ret = FA(Default, Mega);
break;
case pksm::Species::Corsola:
ret = FA(Default, Galarian);
break;
case pksm::Species::Houndoom:
ret = FA(Default, Mega);
break;
case pksm::Species::Tyranitar:
ret = FA(Default, Mega);
break;
case pksm::Species::Sceptile:
ret = FA(Default, Mega);
break;
case pksm::Species::Blaziken:
ret = FA(Default, Mega);
break;
case pksm::Species::Swampert:
ret = FA(Default, Mega);
break;
case pksm::Species::Zigzagoon:
case pksm::Species::Linoone:
ret = FA(Default, Galarian);
break;
case pksm::Species::Gardevoir:
ret = FA(Default, Mega);
break;
case pksm::Species::Sableye:
ret = FA(Default, Mega);
break;
case pksm::Species::Mawile:
ret = FA(Default, Mega);
break;
case pksm::Species::Aggron:
ret = FA(Default, Mega);
break;
case pksm::Species::Medicham:
ret = FA(Default, Mega);
break;
case pksm::Species::Manectric:
ret = FA(Default, Mega);
break;
case pksm::Species::Sharpedo:
ret = FA(Default, Mega);
break;
case pksm::Species::Camerupt:
ret = FA(Default, Mega);
break;
case pksm::Species::Altaria:
ret = FA(Default, Mega);
break;
case pksm::Species::Castform:
ret = FA(Default, Sunny, Rainy, Snowy);
break;
case pksm::Species::Banette:
ret = FA(Default, Mega);
break;
case pksm::Species::Absol:
ret = FA(Default, Mega);
break;
case pksm::Species::Glalie:
ret = FA(Default, Mega);
break;
case pksm::Species::Salamence:
ret = FA(Default, Mega);
break;
case pksm::Species::Metagross:
ret = FA(Default, Mega);
break;
case pksm::Species::Latias:
ret = FA(Default, Mega);
break;
case pksm::Species::Latios:
ret = FA(Default, Mega);
break;
case pksm::Species::Kyogre:
ret = FA(Default, Primal);
break;
case pksm::Species::Groudon:
ret = FA(Default, Primal);
break;
case pksm::Species::Rayquaza:
ret = FA(Default, Mega);
break;
case pksm::Species::Deoxys:
ret = FA(Normal, Attack, Defense, Speed);
break;
case pksm::Species::Burmy:
ret = FA(Plant, Sandy, Trash);
break;
case pksm::Species::Wormadam:
ret = FA(Plant, Sandy, Trash);
break;
case pksm::Species::Cherrim:
ret = FA(Overcast, Sunshine);
break;
case pksm::Species::Shellos:
ret = FA(WestSea, EastSea);
break;
case pksm::Species::Gastrodon:
ret = FA(WestSea, EastSea);
break;
case pksm::Species::Lopunny:
ret = FA(Default, Mega);
break;
case pksm::Species::Garchomp:
ret = FA(Default, Mega);
break;
case pksm::Species::Lucario:
ret = FA(Default, Mega);
break;
case pksm::Species::Abomasnow:
ret = FA(Default, Mega);
break;
case pksm::Species::Gallade:
ret = FA(Default, Mega);
break;
case pksm::Species::Rotom:
ret = FA(Default, Heat, Wash, Fridge, Fan, Mow);
break;
case pksm::Species::Giratina:
ret = FA(Altered, Origin);
break;
case pksm::Species::Shaymin:
ret = FA(Land, Sky);
break;
case pksm::Species::Arceus:
ret = FA(Default, Fighting, Flying, Poison, Ground, Rock, Bug, Ghost, Steel, Fire,
Water, Grass, Electric, Psychic, Ice, Dragon, Dark, Fairy);
break;
case pksm::Species::Audino:
ret = FA(Default, Mega);
break;
case pksm::Species::Basculin:
ret = FA(RedStriped, BlueStriped);
break;
case pksm::Species::Darumaka:
ret = FA(Default, Galarian);
break;
case pksm::Species::Darmanitan:
ret = FA(Default, Zen, Galarian, Zen);
break;
case pksm::Species::Yamask:
ret = FA(Default, Galarian);
break;
case pksm::Species::Deerling:
case pksm::Species::Sawsbuck:
ret = FA(Spring, Summer, Autumn, Winter);
break;
case pksm::Species::Stunfisk:
ret = FA(Default, Galarian);
break;
case pksm::Species::Tornadus:
ret = FA(Incarnate, Therian);
break;
case pksm::Species::Thundurus:
ret = FA(Incarnate, Therian);
break;
case pksm::Species::Landorus:
ret = FA(Incarnate, Therian);
break;
case pksm::Species::Kyurem:
ret = FA(Default, WhiteKyurem, Black);
break;
case pksm::Species::Keldeo:
ret = FA(Ordinary, Resolute);
break;
case pksm::Species::Meloetta:
ret = FA(Aria, Pirouette);
break;
case pksm::Species::Genesect:
ret = FA(Default, Water, Electric, Fire, Ice);
break;
case pksm::Species::Greninja:
ret = FA(Default, BattleBond, Ash);
break;
case pksm::Species::Scatterbug:
case pksm::Species::Spewpa:
case pksm::Species::Vivillon:
ret = FA(IcySnow, Polar, Tundra, Continental, Garden, Elegant, Meadow, Modern,
Marine, Archipelago, HighPlains, Sandstorm, River, Monsoon, Savanna, Sun, Ocean,
Jungle, Fancy, PokeBall);
break;
case pksm::Species::Flabebe:
ret = FA(RedFlower, YellowFlower, OrangeFlower, BlueFlower, WhiteFlower);
break;
case pksm::Species::Floette:
ret = FA(
RedFlower, YellowFlower, OrangeFlower, BlueFlower, WhiteFlower, EternalFlower);
break;
case pksm::Species::Florges:
ret = FA(RedFlower, YellowFlower, OrangeFlower, BlueFlower, WhiteFlower);
break;
case pksm::Species::Furfrou:
ret = FA(Natural, Heart, Star, Diamond, Debutante, Matron, Dandy, LaReine, Kabuki,
Pharaoh);
break;
case pksm::Species::Meowstic:
ret = FA(Default, Female);
break;
case pksm::Species::Aegislash:
ret = FA(Shield, Blade);
break;
case pksm::Species::Pumpkaboo:
ret = FA(Average, Small, Large, Super);
break;
case pksm::Species::Gourgeist:
ret = FA(Average, Small, Large, Super);
break;
case pksm::Species::Zygarde:
ret = FA(_50Percent, _10Percent, _10Percent_PC, _50Percent_PC, _100Percent);
break;
case pksm::Species::Diancie:
ret = FA(Default, Mega);
break;
case pksm::Species::Hoopa:
ret = FA(Confined, Unbound);
break;
case pksm::Species::Gumshoos:
ret = FA(Default, Totem);
break;
case pksm::Species::Vikavolt:
ret = FA(Default, Totem);
break;
case pksm::Species::Oricorio:
ret = FA(Baile, PomPom, Pau, Sensu);
break;
case pksm::Species::Ribombee:
ret = FA(Default, Totem);
break;
case pksm::Species::Rockruff:
ret = FA(Default, Dusk);
break;
case pksm::Species::Lycanroc:
ret = FA(Midday, Midnight, Dusk);
break;
case pksm::Species::Wishiwashi:
ret = FA(Solo, School);
break;
case pksm::Species::Araquanid:
ret = FA(Default, Totem);
break;
case pksm::Species::Lurantis:
ret = FA(Default, Totem);
break;
case pksm::Species::Salazzle:
ret = FA(Default, Totem);
break;
case pksm::Species::Silvally:
ret = FA(Default, Fighting, Flying, Poison, Ground, Rock, Bug, Ghost, Steel, Fire,
Water, Grass, Electric, Psychic, Ice, Dragon, Dark, Fairy);
break;
case pksm::Species::Minior:
ret = FA(CoveredRed, CoveredOrange, CoveredYellow, CoveredGreen, CoveredBlue,
CoveredIndigo, CoveredViolet, Red, Orange, Yellow, Green, Blue, Indigo, Violet);
break;
case pksm::Species::Togedemaru:
ret = FA(Default, Totem);
break;
case pksm::Species::Mimikyu:
ret = FA(Default, Default, Totem, Totem);
break;
case pksm::Species::Kommoo:
ret = FA(Default, Totem);
break;
case pksm::Species::Necrozma:
ret = FA(Default, DawnWings, DuskMane, Ultra);
break;
case pksm::Species::Magearna:
ret = FA(Default, OriginalColor);
break;
case pksm::Species::Cramorant:
ret = FA(Default, Gulping, Gorging);
break;
case pksm::Species::Toxtricity:
ret = FA(AmpedForm, LowKey);
break;
case pksm::Species::Indeedee:
ret = FA(Default, Female);
break;
case pksm::Species::Sinistea:
case pksm::Species::Polteageist:
ret = FA(Phony, Antique);
break;
case pksm::Species::Alcremie:
ret = FA(VanillaCream, RubyCream, MatchaCream, MintCream, LemonCream, SaltedCream,
RubySwirl, CaramelSwirl, RainbowSwirl);
break;
case pksm::Species::Eiscue:
ret = FA(Default, NoiceFace);
break;
case pksm::Species::Morpeko:
ret = FA(Default, HangryMode);
break;
case pksm::Species::Zacian:
ret = FA(Default, Crowned);
break;
case pksm::Species::Zamazenta:
ret = FA(Default, Crowned);
break;
case pksm::Species::Eternatus:
ret = FA(Default, Eternamax);
break;
case pksm::Species::Urshifu:
ret = FA(SingleStrike, RapidStrike);
break;
case pksm::Species::Zarude:
ret = FA(Default, Dada);
break;
case pksm::Species::Calyrex:
ret = FA(Default, IceRider, ShadowRider);
break;
default:
break;
}
return ret.subspan(0, forms);
}
const std::string& form(
pksm::Language lang, pksm::GameVersion version, pksm::Species species, u8 form)
{
checkInitialized(lang);
auto indices = formIndices(version, species);
if (form < indices.size())
{
size_t index = indices[form];
if (index < formss[lang].size())
{
return formss[lang][index];
}
}
return emptyString;
}
SmallVector<std::string, 0x20> forms(
pksm::Language lang, pksm::GameVersion version, pksm::Species species)
{
checkInitialized(lang);
SmallVector<std::string, 0x20> ret;
auto indices = formIndices(version, species);
for (const auto& index : indices)
{
if (index < formss[lang].size())
{
ret.emplace_back(formss[lang][index]);
}
else
{
ret.emplace_back("");
}
}
return ret;
}
}
| 31,486
|
C++
|
.cpp
| 786
| 28.276081
| 100
| 0.486819
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,241
|
i18n_species.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_species.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/Species.hpp"
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> speciess = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initSpecies(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/species.txt", vec);
speciess.insert_or_assign(lang, std::move(vec));
}
void exitSpecies(pksm::Language lang)
{
speciess[lang].clear();
}
const std::string& species(pksm::Language lang, pksm::Species val)
{
checkInitialized(lang);
if (size_t(val) < speciess[lang].size())
{
return speciess[lang][size_t(val)];
}
return emptyString;
}
const std::vector<std::string>& rawSpecies(pksm::Language lang)
{
checkInitialized(lang);
return speciess[lang];
}
}
const std::string& pksm::internal::Species_impl::localize(pksm::Language lang) const
{
return i18n::species(lang, *this);
}
| 2,442
|
C++
|
.cpp
| 65
| 32.753846
| 88
| 0.672858
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,242
|
i18n_game.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_game.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/GameVersion.hpp"
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> games = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initGame(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/games.txt", vec);
games.insert_or_assign(lang, std::move(vec));
}
void exitGame(pksm::Language lang)
{
games[lang].clear();
}
const std::string& game(pksm::Language lang, pksm::GameVersion val)
{
checkInitialized(lang);
if (u8(val) < games[lang].size())
{
return games[lang][u8(val)];
}
return emptyString;
}
const std::vector<std::string>& rawGames(pksm::Language lang)
{
checkInitialized(lang);
return games[lang];
}
}
| 2,282
|
C++
|
.cpp
| 61
| 32.42623
| 85
| 0.665763
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,243
|
i18n_type.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_type.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/Type.hpp"
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> types = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initType(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/types.txt", vec);
types.insert_or_assign(lang, std::move(vec));
}
void exitType(pksm::Language lang)
{
types[lang].clear();
}
const std::string& type(pksm::Language lang, pksm::Type val)
{
checkInitialized(lang);
if (size_t(val) < types[lang].size())
{
return types[lang][size_t(val)];
}
return emptyString;
}
const std::vector<std::string>& rawTypes(pksm::Language lang)
{
checkInitialized(lang);
return types[lang];
}
}
const std::string& pksm::internal::Type_impl::localize(pksm::Language lang) const
{
return i18n::type(lang, *this);
}
| 2,398
|
C++
|
.cpp
| 65
| 32.092308
| 85
| 0.66681
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,244
|
i18n_geo.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_geo.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::map<u8, std::string>> countries = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::map<u8, std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
std::unordered_map<pksm::Language, std::map<u8, std::map<u8, std::string>>> subregions =
std::invoke(
[]
{
std::unordered_map<pksm::Language, std::map<u8, std::map<u8, std::string>>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
std::string subregionFileName(u8 region)
{
std::string ret = "/subregions/000.txt";
for (int pos = 0; pos < 3; pos++)
{
char setMe = '0' + (region % 10);
ret[ret.size() - 5 - pos] = setMe;
region /= 10;
}
return ret;
}
void initGeo(pksm::Language lang)
{
std::map<u8, std::string> tmp;
load(lang, "/countries.txt", tmp);
auto [place, inserted] = countries.insert_or_assign(lang, std::move(tmp));
std::map<u8, std::map<u8, std::string>> tmp2;
for (auto i = place->second.begin(); i != place->second.end(); i++)
{
load(lang, subregionFileName(i->first), tmp2[i->first]);
}
subregions.insert_or_assign(lang, std::move(tmp2));
}
void exitGeo(pksm::Language lang)
{
countries[lang].clear();
subregions[lang].clear();
}
const std::string& subregion(pksm::Language lang, u8 country, u8 v)
{
checkInitialized(lang);
if (subregions[lang].count(country) > 0)
{
if (subregions[lang][country].count(v) > 0)
{
return subregions[lang][country][v];
}
}
return emptyString;
}
const std::string& country(pksm::Language lang, u8 v)
{
checkInitialized(lang);
if (countries[lang].count(v) > 0)
{
return countries[lang][v];
}
return emptyString;
}
const std::map<u8, std::string>& rawCountries(pksm::Language lang)
{
checkInitialized(lang);
return countries[lang];
}
const std::map<u8, std::string>& rawSubregions(pksm::Language lang, u8 country)
{
checkInitialized(lang);
if (subregions[lang].count(country) > 0)
{
return subregions[lang][country];
}
return emptyU8Map;
}
}
| 3,905
|
C++
|
.cpp
| 107
| 29.345794
| 96
| 0.599525
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,245
|
i18n_item.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_item.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> items = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
std::unordered_map<pksm::Language, std::vector<std::string>> items1 = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
std::unordered_map<pksm::Language, std::vector<std::string>> items2 = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
std::unordered_map<pksm::Language, std::vector<std::string>> items3 = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initItem(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/items.txt", vec);
// HM07 & HM08
vec[426] = vec[425].substr(0, vec[425].size() - 1) + '7';
vec[427] = vec[425].substr(0, vec[425].size() - 1) + '8';
items.insert_or_assign(lang, std::move(vec));
}
void initItem1(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/items1.txt", vec);
items1.insert_or_assign(lang, std::move(vec));
}
void initItem2(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/items2.txt", vec);
items2.insert_or_assign(lang, std::move(vec));
}
void initItem3(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/items3.txt", vec);
items3.insert_or_assign(lang, std::move(vec));
}
void exitItem(pksm::Language lang)
{
items[lang].clear();
}
void exitItem1(pksm::Language lang)
{
items1[lang].clear();
}
void exitItem2(pksm::Language lang)
{
items2[lang].clear();
}
void exitItem3(pksm::Language lang)
{
items3[lang].clear();
}
const std::string& item(pksm::Language lang, u16 val)
{
checkInitialized(lang);
if (val < items[lang].size())
{
return items[lang][val];
}
return emptyString;
}
const std::string& item1(pksm::Language lang, u8 val)
{
checkInitialized(lang);
if (val < items1[lang].size())
{
return items1[lang][val];
}
return emptyString;
}
const std::string& item2(pksm::Language lang, u8 val)
{
checkInitialized(lang);
if (val < items2[lang].size())
{
return items2[lang][val];
}
return emptyString;
}
const std::string& item3(pksm::Language lang, u16 val)
{
checkInitialized(lang);
if (val < items3[lang].size())
{
return items3[lang][val];
}
return emptyString;
}
const std::vector<std::string>& rawItems(pksm::Language lang)
{
checkInitialized(lang);
return items[lang];
}
const std::vector<std::string>& rawItems1(pksm::Language lang)
{
checkInitialized(lang);
return items1[lang];
}
const std::vector<std::string>& rawItems2(pksm::Language lang)
{
checkInitialized(lang);
return items2[lang];
}
const std::vector<std::string>& rawItems3(pksm::Language lang)
{
checkInitialized(lang);
return items3[lang];
}
}
| 5,131
|
C++
|
.cpp
| 156
| 26.025641
| 86
| 0.605327
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,246
|
i18n_ball.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_ball.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/Ball.hpp"
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> balls = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initBall(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/balls.txt", vec);
balls.insert_or_assign(lang, std::move(vec));
}
void exitBall(pksm::Language lang)
{
balls[lang].clear();
}
const std::string& ball(pksm::Language lang, pksm::Ball val)
{
checkInitialized(lang);
if (size_t(val) < balls[lang].size())
{
return balls[lang][size_t(val)];
}
return emptyString;
}
const std::vector<std::string>& rawBalls(pksm::Language lang)
{
checkInitialized(lang);
return balls[lang];
}
}
const std::string& pksm::internal::Ball_impl::localize(pksm::Language lang) const
{
return i18n::ball(lang, *this);
}
| 2,398
|
C++
|
.cpp
| 65
| 32.092308
| 85
| 0.66681
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,247
|
i18n_ability.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_ability.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/Ability.hpp"
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> abilities = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initAbility(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/abilities.txt", vec);
abilities.insert_or_assign(lang, std::move(vec));
}
void exitAbility(pksm::Language lang)
{
abilities[lang].clear();
}
const std::string& ability(pksm::Language lang, pksm::Ability val)
{
checkInitialized(lang);
if (size_t(val) < abilities[lang].size())
{
return abilities[lang][size_t(val)];
}
return emptyString;
}
const std::vector<std::string>& rawAbilities(pksm::Language lang)
{
checkInitialized(lang);
return abilities[lang];
}
}
const std::string& pksm::internal::Ability_impl::localize(pksm::Language lang) const
{
return i18n::ability(lang, *this);
}
| 2,451
|
C++
|
.cpp
| 65
| 32.907692
| 89
| 0.674233
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,248
|
i18n_nature.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_nature.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/Nature.hpp"
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> natures = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initNature(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/natures.txt", vec);
natures.insert_or_assign(lang, std::move(vec));
}
void exitNature(pksm::Language lang)
{
natures[lang].clear();
}
const std::string& nature(pksm::Language lang, pksm::Nature val)
{
checkInitialized(lang);
if (size_t(val) < natures[lang].size())
{
return natures[lang][size_t(val)];
}
return emptyString;
}
const std::vector<std::string>& rawNatures(pksm::Language lang)
{
checkInitialized(lang);
return natures[lang];
}
}
const std::string& pksm::internal::Nature_impl::localize(pksm::Language lang) const
{
return i18n::nature(lang, *this);
}
| 2,428
|
C++
|
.cpp
| 65
| 32.553846
| 87
| 0.671053
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,249
|
i18n_ribbon.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n_ribbon.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/Ribbon.hpp"
#include "i18n_internal.hpp"
namespace i18n
{
std::unordered_map<pksm::Language, std::vector<std::string>> ribbons = std::invoke(
[]
{
std::unordered_map<pksm::Language, std::vector<std::string>> ret;
MAP(MAKE_GENERIC_LANGMAP, LANGUAGES_TO_USE)
return ret;
});
void initRibbon(pksm::Language lang)
{
std::vector<std::string> vec;
load(lang, "/ribbons.txt", vec);
ribbons.insert_or_assign(lang, std::move(vec));
}
void exitRibbon(pksm::Language lang)
{
ribbons[lang].clear();
}
const std::string& ribbon(pksm::Language lang, pksm::Ribbon val)
{
checkInitialized(lang);
if (size_t(val) < ribbons[lang].size())
{
return ribbons[lang][size_t(val)];
}
return emptyString;
}
const std::vector<std::string>& rawRibbons(pksm::Language lang)
{
checkInitialized(lang);
return ribbons[lang];
}
}
const std::string& pksm::internal::Ribbon_impl::localize(pksm::Language lang) const
{
return i18n::ribbon(lang, *this);
}
| 2,428
|
C++
|
.cpp
| 65
| 32.553846
| 87
| 0.671053
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,250
|
Language.cpp
|
FlagBrew_PKSM-Core/source/i18n/Language.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "enums/Language.hpp"
#include "enums/Generation.hpp"
#include <algorithm>
#include <array>
namespace pksm
{
namespace internal
{
constexpr std::array<Language, 6> G13Langs = {Language::JPN, Language::ENG, Language::FRE,
Language::GER, Language::SPA, Language::ITA};
constexpr std::array<Language, 7> G24Langs = {Language::JPN, Language::ENG, Language::FRE,
Language::GER, Language::SPA, Language::ITA, Language::KOR};
constexpr std::array<Language, 9> G7Langs = {Language::JPN, Language::ENG, Language::FRE,
Language::GER, Language::SPA, Language::ITA, Language::KOR, Language::CHS,
Language::CHT};
}
Language getSafeLanguage(Generation gen, Language orig)
{
switch (gen)
{
case Generation::ONE:
case Generation::THREE:
if (std::find(internal::G13Langs.begin(), internal::G13Langs.end(), orig) !=
internal::G13Langs.end())
{
return orig;
}
return Language::ENG;
case Generation::TWO:
case Generation::FOUR:
case Generation::FIVE:
case Generation::SIX:
if (std::find(internal::G24Langs.begin(), internal::G24Langs.end(), orig) !=
internal::G24Langs.end())
{
return orig;
}
return Language::ENG;
case Generation::SEVEN:
case Generation::LGPE:
case Generation::EIGHT:
if (std::find(internal::G7Langs.begin(), internal::G7Langs.end(), orig) !=
internal::G7Langs.end())
{
return orig;
}
return Language::ENG;
case Generation::UNUSED:
break;
}
return Language::ENG;
}
}
| 3,226
|
C++
|
.cpp
| 78
| 32.589744
| 98
| 0.608142
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,251
|
i18n.cpp
|
FlagBrew_PKSM-Core/source/i18n/i18n.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "i18n_internal.hpp"
#include "utils/utils.hpp"
#include <algorithm>
#include <array>
#include <functional>
#include <list>
#define MAKE_MAP(lang) ret.emplace(pksm::Language::lang, LangState::UNINITIALIZED);
#define TO_STRING_CASE(lang) \
case pksm::Language::lang: \
{ \
static const std::string str = #lang; \
return str; \
}
#define TO_IF_STRING(lang) \
if (value == #lang) \
return pksm::Language::lang;
#define TO_FOLDER_CASE(lang) \
case pksm::Language::lang: \
return StringUtils::toLower(#lang);
namespace i18n
{
#ifdef _PKSMCORE_DISABLE_THREAD_SAFETY
std::unordered_map<pksm::Language, LangState> languages = std::invoke(
[]()
{
std::unordered_map<pksm::Language, LangState> ret;
MAP(MAKE_MAP, LANGUAGES_TO_USE);
return ret;
});
#else
std::unordered_map<pksm::Language, std::atomic<LangState>> languages = std::invoke(
[]()
{
std::unordered_map<pksm::Language, std::atomic<LangState>> ret;
MAP(MAKE_MAP, LANGUAGES_TO_USE);
return ret;
});
#endif
std::list<initCallback> initCallbacks = {initAbility, initBall, initForm, initGame, initGeo,
initType, initItem, initItem1, initItem2, initItem3, initLocation, initMove, initNature,
initRibbon, initSpecies};
std::list<exitCallback> exitCallbacks = {exitAbility, exitBall, exitForm, exitGame, exitGeo,
exitType, exitItem, exitItem1, exitItem2, exitItem3, exitLocation, exitMove, exitNature,
exitRibbon, exitSpecies};
void init(pksm::Language lang)
{
auto found = languages.find(lang);
// Should never happen, but might as well check
if (found == languages.end())
{
found = languages.find(pksm::Language::ENG);
}
#ifdef _PKSMCORE_DISABLE_THREAD_SAFETY
if (found->second == LangState::UNINITIALIZED)
{
found->second = LangState::INITIALIZING;
#else
LangState expected = LangState::UNINITIALIZED;
if (found->second.compare_exchange_strong(expected, LangState::INITIALIZING))
{
#endif
for (const auto& callback : initCallbacks)
{
callback(lang);
}
found->second = LangState::INITIALIZED;
#ifndef _PKSMCORE_DISABLE_THREAD_SAFETY
found->second.notify_all();
#endif
}
}
void exit(void)
{
for (auto& lang : languages)
{
if (lang.second != LangState::UNINITIALIZED)
{
#ifndef _PKSMCORE_DISABLE_THREAD_SAFETY
while (lang.second != LangState::INITIALIZED)
{
lang.second.wait(LangState::INITIALIZING);
}
#endif
for (const auto& callback : exitCallbacks)
{
callback(lang.first);
}
lang.second = LangState::UNINITIALIZED;
}
}
}
const std::string& langString(pksm::Language l)
{
static const std::string ENG = "ENG";
switch (l)
{
MAP(TO_STRING_CASE, LANGUAGES_TO_USE)
default:
return ENG;
}
}
pksm::Language langFromString(const std::string_view& value)
{
MAP(TO_IF_STRING, LANGUAGES_TO_USE)
return pksm::Language::ENG;
}
std::string folder(pksm::Language lang)
{
switch (lang)
{
MAP(TO_FOLDER_CASE, LANGUAGES_TO_USE)
default:
return "eng";
}
return "eng";
}
void load(pksm::Language lang, const std::string& name, std::vector<std::string>& array)
{
std::string path = io::exists(_PKSMCORE_LANG_FOLDER + folder(lang) + name)
? _PKSMCORE_LANG_FOLDER + folder(lang) + name
: _PKSMCORE_LANG_FOLDER + folder(pksm::Language::ENG) + name;
std::string tmp;
FILE* values = fopen(path.c_str(), "rt");
if (values)
{
if (ferror(values))
{
fclose(values);
return;
}
char* data = static_cast<char*>(malloc(128));
size_t size = 0;
while (!feof(values) && !ferror(values))
{
size = std::max(size, (size_t)128);
if (_PKSMCORE_GETLINE_FUNC(&data, &size, values) >= 0)
{
tmp = std::string(data);
tmp = tmp.substr(0, tmp.find('\n'));
array.emplace_back(tmp.substr(0, tmp.find('\r')));
}
else
{
break;
}
}
fclose(values);
free(data);
}
}
void addInitCallback(initCallback callback)
{
auto i = std::find(initCallbacks.begin(), initCallbacks.end(), callback);
if (i == initCallbacks.end())
{
initCallbacks.emplace_back(callback);
}
}
void removeInitCallback(initCallback callback)
{
auto i = std::find(initCallbacks.begin(), initCallbacks.end(), callback);
while (i != initCallbacks.end())
{
initCallbacks.erase(i);
i = std::find(initCallbacks.begin(), initCallbacks.end(), callback);
}
}
void addExitCallback(exitCallback callback)
{
auto i = std::find(exitCallbacks.begin(), exitCallbacks.end(), callback);
if (i == exitCallbacks.end())
{
exitCallbacks.emplace_back(callback);
}
}
void removeExitCallback(exitCallback callback)
{
auto i = std::find(exitCallbacks.begin(), exitCallbacks.end(), callback);
while (i != exitCallbacks.end())
{
exitCallbacks.erase(i);
i = std::find(exitCallbacks.begin(), exitCallbacks.end(), callback);
}
}
}
| 7,952
|
C++
|
.cpp
| 210
| 29.285714
| 100
| 0.535344
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,252
|
personal.cpp
|
FlagBrew_PKSM-Core/source/personal/personal.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "personal/personal.hpp"
#include "personal1.h"
#include "personal2.h"
#include "personal3.h"
#include "personal4.h"
#include "personal5.h"
#include "personal6.h"
#include "personal7.h"
#include "personal7b.h"
#include "personal8.h"
#include "utils/endian.hpp"
#include <memory>
#define READ_PERSONAL(name, size) readPersonal(_PKSMCORE_PERSONAL_FOLDER name, size)
namespace
{
std::unique_ptr<u8[]> readPersonal(std::string_view path, size_t nominalSize)
{
FILE* personal = fopen(path.data(), "rb");
if (personal)
{
fseek(personal, 0, SEEK_END);
size_t size = ftell(personal);
rewind(personal);
if (nominalSize != size)
{
throw std::runtime_error("Personal size does not match");
}
std::unique_ptr<u8[]> ret = std::unique_ptr<u8[]>{new u8[size]};
if (fread(ret.get(), 1, size, personal) != size)
{
throw std::runtime_error("Could not read all of personal file");
}
fclose(personal);
return ret;
}
else
{
throw std::runtime_error("Could not open personal file `" + std::string(path) + "`");
}
}
const u8* personal7b()
{
static auto personal = READ_PERSONAL("personal7b", personal7b_size);
return personal.get();
}
const u8* personal7()
{
static auto personal = READ_PERSONAL("personal7", personal7_size);
return personal.get();
}
const u8* personal6()
{
static auto personal = READ_PERSONAL("personal6", personal6_size);
return personal.get();
}
const u8* personal5()
{
static auto personal = READ_PERSONAL("personal5", personal5_size);
return personal.get();
}
const u8* personal4()
{
static auto personal = READ_PERSONAL("personal4", personal4_size);
return personal.get();
}
const u8* personal8()
{
static auto personal = READ_PERSONAL("personal8", personal8_size);
return personal.get();
}
const u8* personal3()
{
static auto personal = READ_PERSONAL("personal3", personal3_size);
return personal.get();
}
const u8* personal2()
{
static auto personal = READ_PERSONAL("personal2", personal2_size);
return personal.get();
}
const u8* personal1()
{
static auto personal = READ_PERSONAL("personal1", personal1_size);
return personal.get();
}
}
namespace pksm
{
namespace PersonalLGPE
{
u8 baseHP(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x0];
}
u8 baseAtk(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x1];
}
u8 baseDef(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x2];
}
u8 baseSpe(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x3];
}
u8 baseSpa(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x4];
}
u8 baseSpd(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x5];
}
Type type1(u16 species)
{
return Type{personal7b()[species * personal7b_entrysize + 0x6]};
}
Type type2(u16 species)
{
return Type{personal7b()[species * personal7b_entrysize + 0x7]};
}
u8 gender(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x8];
}
u8 baseFriendship(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x9];
}
u8 expType(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0xA];
}
Ability ability(u16 species, u8 n)
{
return Ability{personal7b()[species * personal7b_entrysize + 0xB + n]};
}
u16 formStatIndex(u16 species)
{
return LittleEndian::convertTo<u16>(
personal7b() + species * personal7b_entrysize + 0xE);
}
u8 formCount(u16 species)
{
return personal7b()[species * personal7b_entrysize + 0x10];
}
}
namespace PersonalSMUSUM
{
u8 baseHP(u16 species)
{
return personal7()[species * personal7_entrysize + 0x0];
}
u8 baseAtk(u16 species)
{
return personal7()[species * personal7_entrysize + 0x1];
}
u8 baseDef(u16 species)
{
return personal7()[species * personal7_entrysize + 0x2];
}
u8 baseSpe(u16 species)
{
return personal7()[species * personal7_entrysize + 0x3];
}
u8 baseSpa(u16 species)
{
return personal7()[species * personal7_entrysize + 0x4];
}
u8 baseSpd(u16 species)
{
return personal7()[species * personal7_entrysize + 0x5];
}
Type type1(u16 species)
{
return Type{personal7()[species * personal7_entrysize + 0x6]};
}
Type type2(u16 species)
{
return Type{personal7()[species * personal7_entrysize + 0x7]};
}
u8 gender(u16 species)
{
return personal7()[species * personal7_entrysize + 0x8];
}
u8 baseFriendship(u16 species)
{
return personal7()[species * personal7_entrysize + 0x9];
}
u8 expType(u16 species)
{
return personal7()[species * personal7_entrysize + 0xA];
}
Ability ability(u16 species, u8 n)
{
return Ability{personal7()[species * personal7_entrysize + 0xB + n]};
}
u16 formStatIndex(u16 species)
{
return LittleEndian::convertTo<u16>(personal7() + species * personal7_entrysize + 0xE);
}
u8 formCount(u16 species)
{
return personal7()[species * personal7_entrysize + 0x10];
}
}
namespace PersonalXYORAS
{
u8 baseHP(u16 species)
{
return personal6()[species * personal6_entrysize + 0x0];
}
u8 baseAtk(u16 species)
{
return personal6()[species * personal6_entrysize + 0x1];
}
u8 baseDef(u16 species)
{
return personal6()[species * personal6_entrysize + 0x2];
}
u8 baseSpe(u16 species)
{
return personal6()[species * personal6_entrysize + 0x3];
}
u8 baseSpa(u16 species)
{
return personal6()[species * personal6_entrysize + 0x4];
}
u8 baseSpd(u16 species)
{
return personal6()[species * personal6_entrysize + 0x5];
}
Type type1(u16 species)
{
return Type{personal6()[species * personal6_entrysize + 0x6]};
}
Type type2(u16 species)
{
return Type{personal6()[species * personal6_entrysize + 0x7]};
}
u8 gender(u16 species)
{
return personal6()[species * personal6_entrysize + 0x8];
}
u8 baseFriendship(u16 species)
{
return personal6()[species * personal6_entrysize + 0x9];
}
u8 expType(u16 species)
{
return personal6()[species * personal6_entrysize + 0xA];
}
Ability ability(u16 species, u8 n)
{
return Ability{personal6()[species * personal6_entrysize + 0xB + n]};
}
u16 formStatIndex(u16 species)
{
return LittleEndian::convertTo<u16>(personal6() + species * personal6_entrysize + 0xE);
}
u8 formCount(u16 species)
{
return personal6()[species * personal6_entrysize + 0x10];
}
}
namespace PersonalBWB2W2
{
u8 baseHP(u16 species)
{
return personal5()[species * personal5_entrysize + 0x0];
}
u8 baseAtk(u16 species)
{
return personal5()[species * personal5_entrysize + 0x1];
}
u8 baseDef(u16 species)
{
return personal5()[species * personal5_entrysize + 0x2];
}
u8 baseSpe(u16 species)
{
return personal5()[species * personal5_entrysize + 0x3];
}
u8 baseSpa(u16 species)
{
return personal5()[species * personal5_entrysize + 0x4];
}
u8 baseSpd(u16 species)
{
return personal5()[species * personal5_entrysize + 0x5];
}
Type type1(u16 species)
{
return Type{personal5()[species * personal5_entrysize + 0x6]};
}
Type type2(u16 species)
{
return Type{personal5()[species * personal5_entrysize + 0x7]};
}
u8 gender(u16 species)
{
return personal5()[species * personal5_entrysize + 0x8];
}
u8 baseFriendship(u16 species)
{
return personal5()[species * personal5_entrysize + 0x9];
}
u8 expType(u16 species)
{
return personal5()[species * personal5_entrysize + 0xA];
}
Ability ability(u16 species, u8 n)
{
return Ability{personal5()[species * personal5_entrysize + 0xB + n]};
}
u16 formStatIndex(u16 species)
{
return LittleEndian::convertTo<u16>(personal5() + species * personal5_entrysize + 0xE);
}
u8 formCount(u16 species)
{
return personal5()[species * personal5_entrysize + 0x10];
}
}
namespace PersonalDPPtHGSS
{
u8 baseHP(u16 species)
{
return personal4()[species * personal4_entrysize + 0x0];
}
u8 baseAtk(u16 species)
{
return personal4()[species * personal4_entrysize + 0x1];
}
u8 baseDef(u16 species)
{
return personal4()[species * personal4_entrysize + 0x2];
}
u8 baseSpe(u16 species)
{
return personal4()[species * personal4_entrysize + 0x3];
}
u8 baseSpa(u16 species)
{
return personal4()[species * personal4_entrysize + 0x4];
}
u8 baseSpd(u16 species)
{
return personal4()[species * personal4_entrysize + 0x5];
}
Type type1(u16 species)
{
u8 typeVal = personal4()[species * personal4_entrysize + 0x6];
if (typeVal > 8)
{
return Type{u8(typeVal - 1)};
}
else
{
return Type{typeVal};
}
}
Type type2(u16 species)
{
u8 typeVal = personal4()[species * personal4_entrysize + 0x7];
if (typeVal > 8)
{
return Type{u8(typeVal - 1)};
}
else
{
return Type{typeVal};
}
}
u8 gender(u16 species)
{
return personal4()[species * personal4_entrysize + 0x8];
}
u8 baseFriendship(u16 species)
{
return personal4()[species * personal4_entrysize + 0x9];
}
u8 expType(u16 species)
{
return personal4()[species * personal4_entrysize + 0xA];
}
Ability ability(u16 species, u8 n)
{
return Ability{personal4()[species * personal4_entrysize + 0xB + n]};
}
u16 formStatIndex(u16 species)
{
return LittleEndian::convertTo<u16>(personal4() + species * personal4_entrysize + 0xD);
}
// Normalized to fit with other formCounts' return values
u8 formCount(u16 species)
{
if (species == 201)
{
return 28;
}
else
{
u8 count = personal4()[species * personal4_entrysize + 0xF];
if (count == 0)
{
return 1;
}
return count;
}
}
}
namespace PersonalSWSH
{
u8 baseHP(u16 species)
{
return personal8()[species * personal8_entrysize + 0x0];
}
u8 baseAtk(u16 species)
{
return personal8()[species * personal8_entrysize + 0x1];
}
u8 baseDef(u16 species)
{
return personal8()[species * personal8_entrysize + 0x2];
}
u8 baseSpe(u16 species)
{
return personal8()[species * personal8_entrysize + 0x3];
}
u8 baseSpa(u16 species)
{
return personal8()[species * personal8_entrysize + 0x4];
}
u8 baseSpd(u16 species)
{
return personal8()[species * personal8_entrysize + 0x5];
}
Type type1(u16 species)
{
return Type{personal8()[species * personal8_entrysize + 0x6]};
}
Type type2(u16 species)
{
return Type{personal8()[species * personal8_entrysize + 0x7]};
}
u8 gender(u16 species)
{
return personal8()[species * personal8_entrysize + 0x8];
}
u8 baseFriendship(u16 species)
{
return personal8()[species * personal8_entrysize + 0x9];
}
u8 expType(u16 species)
{
return personal8()[species * personal8_entrysize + 0xA];
}
u8 formCount(u16 species)
{
return personal8()[species * personal8_entrysize + 0xB];
}
Ability ability(u16 species, u8 n)
{
return Ability{LittleEndian::convertTo<u16>(
personal8() + species * personal8_entrysize + 0xC + 2 * n)};
}
u16 formStatIndex(u16 species)
{
return LittleEndian::convertTo<u16>(personal8() + species * personal8_entrysize + 0x12);
}
u16 pokedexIndex(u16 species)
{
return LittleEndian::convertTo<u16>(personal8() + species * personal8_entrysize + 0x14);
}
u16 armordexIndex(u16 species)
{
return LittleEndian::convertTo<u16>(personal8() + species * personal8_entrysize + 0x16);
}
u16 crowndexIndex(u16 species)
{
return LittleEndian::convertTo<u16>(personal8() + species + personal8_entrysize + 0x18);
}
bool canLearnTR(u16 species, u8 trID)
{
return (personal8()[species * personal8_entrysize + 0x1A + (trID >> 3)] &
(1 << (trID & 7))) != 0
? true
: false;
}
}
namespace PersonalRSFRLGE
{
u8 baseHP(u16 species)
{
return personal3()[species * personal3_entrysize + 0x0];
}
u8 baseAtk(u16 species)
{
return personal3()[species * personal3_entrysize + 0x1];
}
u8 baseDef(u16 species)
{
return personal3()[species * personal3_entrysize + 0x2];
}
u8 baseSpe(u16 species)
{
return personal3()[species * personal3_entrysize + 0x3];
}
u8 baseSpa(u16 species)
{
return personal3()[species * personal3_entrysize + 0x4];
}
u8 baseSpd(u16 species)
{
return personal3()[species * personal3_entrysize + 0x5];
}
Type type1(u16 species)
{
u8 typeVal = personal3()[species * personal3_entrysize + 0x6];
if (typeVal > 8)
{
return Type{u8(typeVal - 1)};
}
else
{
return Type{typeVal};
}
}
Type type2(u16 species)
{
u8 typeVal = personal3()[species * personal3_entrysize + 0x7];
if (typeVal > 8)
{
return Type{u8(typeVal - 1)};
}
else
{
return Type{typeVal};
}
}
u8 gender(u16 species)
{
return personal3()[species * personal3_entrysize + 0x8];
}
u8 baseFriendship(u16 species)
{
return personal3()[species * personal3_entrysize + 0x9];
}
u8 expType(u16 species)
{
return personal3()[species * personal3_entrysize + 0xA];
}
Ability ability(u16 species, u8 n)
{
return Ability{personal3()[species * personal3_entrysize + 0xB + n]};
}
u8 formCount(u16 species)
{
switch (species)
{
default:
return 1;
case 201: // Unown
return 28;
case 386: // Deoxys
case 351: // Castform
return 4;
}
}
}
namespace PersonalGSC
{
u8 baseHP(u8 species)
{
return personal2()[species * personal2_entrysize + 0x0];
}
u8 baseAtk(u8 species)
{
return personal2()[species * personal2_entrysize + 0x1];
}
u8 baseDef(u8 species)
{
return personal2()[species * personal2_entrysize + 0x2];
}
u8 baseSpe(u8 species)
{
return personal2()[species * personal2_entrysize + 0x3];
}
u8 baseSpa(u8 species)
{
return personal2()[species * personal2_entrysize + 0x4];
}
u8 baseSpd(u8 species)
{
return personal2()[species * personal2_entrysize + 0x5];
}
Type type1(u8 species)
{
u8 typeVal = personal2()[species * personal2_entrysize + 0x6];
if (typeVal >= 20)
{
return Type{u8(typeVal - 11)};
}
else if (typeVal >= 7) // compensating for bird type
{
return Type{u8(typeVal - 1)};
}
else
{
return Type{typeVal};
}
}
Type type2(u8 species)
{
u8 typeVal = personal2()[species * personal2_entrysize + 0x7];
if (typeVal >= 20)
{
return Type{u8(typeVal - 11)};
}
else if (typeVal >= 7)
{
return Type{u8(typeVal - 1)};
}
else
{
return Type{typeVal};
}
}
u8 gender(u8 species)
{
return personal2()[species * personal2_entrysize + 0x8];
}
u8 expType(u8 species)
{
return personal2()[species * personal2_entrysize + 0x9];
}
u8 formCount(u16 species)
{
switch (species)
{
default:
return 1;
case 201: // Unown
return 26;
}
}
}
namespace PersonalRGBY
{
u8 baseHP(u8 species)
{
return personal1()[species * personal1_entrysize + 0x0];
}
u8 baseAtk(u8 species)
{
return personal1()[species * personal1_entrysize + 0x1];
}
u8 baseDef(u8 species)
{
return personal1()[species * personal1_entrysize + 0x2];
}
u8 baseSpe(u8 species)
{
return personal1()[species * personal1_entrysize + 0x3];
}
u8 baseSpad(u8 species)
{
return personal1()[species * personal1_entrysize + 0x4];
}
Type type1(u8 species)
{
u8 typeVal = personal1()[species * personal1_entrysize + 0x5];
if (typeVal >= 20)
{
return Type{u8(typeVal - 11)};
}
else if (typeVal >= 7)
{
return Type{u8(typeVal - 1)};
}
else
{
return Type{typeVal};
}
}
Type type2(u8 species)
{
u8 typeVal = personal1()[species * personal1_entrysize + 0x6];
if (typeVal >= 20)
{
return Type{u8(typeVal - 11)};
}
else if (typeVal >= 7)
{
return Type{u8(typeVal - 1)};
}
else
{
return Type{typeVal};
}
}
u8 catchRate(u8 species)
{
return personal1()[species * personal1_entrysize + 0x7];
}
u8 expType(u8 species)
{
return personal1()[species * personal1_entrysize + 0x8];
}
}
}
| 22,501
|
C++
|
.cpp
| 738
| 20.411924
| 100
| 0.526936
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,253
|
ValueConverter.cpp
|
FlagBrew_PKSM-Core/source/utils/ValueConverter.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "utils/ValueConverter.hpp"
#include "enums/Species.hpp"
#include "g1values.hpp"
#include "g2values.hpp"
#include "g3values.hpp"
#include <algorithm>
namespace pksm
{
Species SpeciesConverter::g1ToNational(u8 v)
{
if (v < internal::g1ToSpecies.size())
{
return Species{internal::g1ToSpecies[v]};
}
return Species::None;
}
u8 SpeciesConverter::nationalToG1(Species v)
{
if (u16(v) < internal::speciesToG1.size())
{
return internal::speciesToG1[u16(v)];
}
return 0;
}
Species SpeciesConverter::g3ToNational(u16 v)
{
if (v < internal::g3ToSpecies.size())
{
return Species{internal::g3ToSpecies[v]};
}
return Species::None;
}
u16 SpeciesConverter::nationalToG3(Species v)
{
if (u16(v) < internal::speciesToG3.size())
{
return internal::speciesToG3[u16(v)];
}
return 0;
}
u16 ItemConverter::g1ToNational(u8 v)
{
//"v < internal::g1ToItem.size()" is always true due to a size of 256
return internal::g1ToItem[v];
}
u8 ItemConverter::nationalToG1(u16 v)
{
if (v == 0)
{
return 0;
}
auto it = std::find(internal::g1ToItem.begin(), internal::g1ToItem.end(), v);
if (it == internal::g1ToItem.end())
{
return 0;
}
return std::distance(internal::g1ToItem.begin(), it);
}
u16 ItemConverter::g2ToNational(u8 v)
{
//"v < internal::g2ToItem.size()" is always true due to a size of 256
return internal::g2ToItem[v];
}
u8 ItemConverter::nationalToG2(u16 v)
{
if (v == 0)
{
return 0;
}
auto it = std::find(internal::g2ToItem.begin(), internal::g2ToItem.end(), v);
if (it == internal::g2ToItem.end())
{
return 0;
}
return std::distance(internal::g2ToItem.begin(), it);
}
u16 ItemConverter::g3ToNational(u16 v)
{
if (v < internal::g3ToItem.size())
{
return internal::g3ToItem[v];
}
return 0;
}
u16 ItemConverter::nationalToG3(u16 v)
{
if (v == 0)
{
return 0;
}
auto it = std::find(internal::g3ToItem.begin(), internal::g3ToItem.end(), v);
if (it == internal::g3ToItem.end())
{
return 0;
}
return std::distance(internal::g3ToItem.begin(), it);
}
}
| 3,854
|
C++
|
.cpp
| 123
| 24.853659
| 85
| 0.609631
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,255
|
crypto_swsh.cpp
|
FlagBrew_PKSM-Core/source/utils/crypto_swsh.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "utils/crypto.hpp"
#include "utils/endian.hpp"
#include <bit>
namespace pksm::crypto::swsh
{
namespace internal
{
// clang-format off
constexpr std::array<u8, 127> xorpad = {
0xA0, 0x92, 0xD1, 0x06, 0x07, 0xDB, 0x32, 0xA1, 0xAE, 0x01, 0xF5, 0xC5, 0x1E, 0x84, 0x4F, 0xE3,
0x53, 0xCA, 0x37, 0xF4, 0xA7, 0xB0, 0x4D, 0xA0, 0x18, 0xB7, 0xC2, 0x97, 0xDA, 0x5F, 0x53, 0x2B,
0x75, 0xFA, 0x48, 0x16, 0xF8, 0xD4, 0x8A, 0x6F, 0x61, 0x05, 0xF4, 0xE2, 0xFD, 0x04, 0xB5, 0xA3,
0x0F, 0xFC, 0x44, 0x92, 0xCB, 0x32, 0xE6, 0x1B, 0xB9, 0xB1, 0x2E, 0x01, 0xB0, 0x56, 0x53, 0x36,
0xD2, 0xD1, 0x50, 0x3D, 0xDE, 0x5B, 0x2E, 0x0E, 0x52, 0xFD, 0xDF, 0x2F, 0x7B, 0xCA, 0x63, 0x50,
0xA4, 0x67, 0x5D, 0x23, 0x17, 0xC0, 0x52, 0xE1, 0xA6, 0x30, 0x7C, 0x2B, 0xB6, 0x70, 0x36, 0x5B,
0x2A, 0x27, 0x69, 0x33, 0xF5, 0x63, 0x7B, 0x36, 0x3F, 0x26, 0x9B, 0xA3, 0xED, 0x7A, 0x53, 0x00,
0xA4, 0x48, 0xB3, 0x50, 0x9E, 0x14, 0xA0, 0x52, 0xDE, 0x7E, 0x10, 0x2B, 0x1B, 0x77, 0x6E
};
constexpr std::array<u8, 64> hashBegin = {
0x9E, 0xC9, 0x9C, 0xD7, 0x0E, 0xD3, 0x3C, 0x44, 0xFB, 0x93, 0x03, 0xDC, 0xEB, 0x39, 0xB4, 0x2A,
0x19, 0x47, 0xE9, 0x63, 0x4B, 0xA2, 0x33, 0x44, 0x16, 0xBF, 0x82, 0xA2, 0xBA, 0x63, 0x55, 0xB6,
0x3D, 0x9D, 0xF2, 0x4B, 0x5F, 0x7B, 0x6A, 0xB2, 0x62, 0x1D, 0xC2, 0x1B, 0x68, 0xE5, 0xC8, 0xB5,
0x3A, 0x05, 0x90, 0x00, 0xE8, 0xA8, 0x10, 0x3D, 0xE2, 0xEC, 0xF0, 0x0C, 0xB2, 0xED, 0x4F, 0x6D,
};
constexpr std::array<u8, 64> hashEnd = {
0xD6, 0xC0, 0x1C, 0x59, 0x8B, 0xC8, 0xB8, 0xCB, 0x46, 0xE1, 0x53, 0xFC, 0x82, 0x8C, 0x75, 0x75,
0x13, 0xE0, 0x45, 0xDF, 0x32, 0x69, 0x3C, 0x75, 0xF0, 0x59, 0xF8, 0xD9, 0xA2, 0x5F, 0xB2, 0x17,
0xE0, 0x80, 0x52, 0xDB, 0xEA, 0x89, 0x73, 0x99, 0x75, 0x79, 0xAF, 0xCB, 0x2E, 0x80, 0x07, 0xE6,
0xF1, 0x26, 0xE0, 0x03, 0x0A, 0xE6, 0x6F, 0xF6, 0x41, 0xBF, 0x7E, 0x59, 0xC2, 0xAE, 0x55, 0xFD,
};
// clang-format on
std::array<u8, 32> computeHash(u8* data, size_t length)
{
SHA256 context;
context.update({internal::hashBegin});
context.update(std::span{data, length});
context.update({internal::hashEnd});
return context.finish();
}
class XorShift32
{
private:
u32 mCounter = 0;
u32 mSeed;
static void advance(u32& key)
{
key ^= key << 2;
key ^= key >> 15;
key ^= key << 13;
}
public:
explicit XorShift32(u32 seed)
{
u32 count = std::popcount(seed);
for (u32 i = 0; i < count; i++)
{
advance(seed);
}
mSeed = seed;
}
u8 next()
{
u8 ret = (mSeed >> (mCounter << 3)) & 0xFF;
if (mCounter == 3)
{
advance(mSeed);
mCounter = 0;
}
else
{
++mCounter;
}
return ret;
}
u32 next32()
{
return next() | (u32(next()) << 8) | (u32(next()) << 16) | (u32(next()) << 24);
}
};
class CryptoException : public std::exception
{
public:
explicit CryptoException(const std::string& message)
: mMessage("CryptoException: " + message)
{
}
const char* what() const noexcept override { return mMessage.c_str(); }
private:
std::string mMessage;
};
}
void applyXor(std::shared_ptr<u8[]> data, size_t length)
{
for (size_t i = 0; i < length - 32; i++)
{
data[i] ^= internal::xorpad[i % internal::xorpad.size()];
}
}
void sign(std::shared_ptr<u8[]> data, size_t length)
{
if (length > 32)
{
auto hash = internal::computeHash(data.get(), length - 32);
std::copy(hash.begin(), hash.end(), data.get() + length - 32);
}
}
bool verify(std::shared_ptr<u8[]> data, size_t length)
{
if (length <= 32)
{
return false;
}
auto hash = internal::computeHash(data.get(), length - 32);
for (size_t i = 0; i < 32; i++)
{
if (hash[i] != data[length - 32 + i])
{
return false;
}
}
return true;
}
std::vector<std::shared_ptr<SCBlock>> getBlockList(std::shared_ptr<u8[]> data, size_t length)
{
std::vector<std::shared_ptr<SCBlock>> ret;
size_t offset = 0;
while (offset < length - 32)
{
ret.emplace_back(new SCBlock(data, offset));
}
return ret;
}
SCBlock::SCBlock(std::shared_ptr<u8[]> data, size_t& offset) : data(data), myOffset(offset)
{
// Key size
offset += 4;
internal::XorShift32 xorShift(key());
type = SCBlockType(data[offset] ^= xorShift.next());
switch (type)
{
case SCBlockType::Bool1:
case SCBlockType::Bool2:
case SCBlockType::Bool3:
// No extra data
offset++;
break;
case SCBlockType::Object:
{
dataLength =
LittleEndian::convertTo<u32>(data.get() + offset + 1) ^ xorShift.next32();
LittleEndian::convertFrom<u32>(data.get() + offset + 1, dataLength);
for (size_t i = 0; i < dataLength; i++)
{
data[offset + 5 + i] ^= xorShift.next();
}
offset += 5 + dataLength;
}
break;
case SCBlockType::Array:
{
dataLength =
LittleEndian::convertTo<u32>(data.get() + offset + 1) ^ xorShift.next32();
LittleEndian::convertFrom<u32>(data.get() + offset + 1, dataLength);
subtype = SCBlockType(data[offset + 5] ^= xorShift.next());
switch (subtype)
{
case SCBlockType::Bool3:
// An array of booleans
for (size_t i = 0; i < dataLength; i++)
{
data[offset + 6 + i] ^= xorShift.next();
}
offset += 6 + dataLength;
break;
case SCBlockType::U8:
case SCBlockType::U16:
case SCBlockType::U32:
case SCBlockType::U64:
case SCBlockType::S8:
case SCBlockType::S16:
case SCBlockType::S32:
case SCBlockType::S64:
case SCBlockType::Float:
case SCBlockType::Double:
{
size_t entrySize = arrayEntrySize(subtype);
for (size_t i = 0; i < dataLength * entrySize; i++)
{
data[offset + 6 + i] ^= xorShift.next();
}
offset += 6 + (dataLength * entrySize);
}
break;
default:
throw internal::CryptoException(
"Decoding block: Key: " + std::to_string(key()) +
"\nSubtype: " + std::to_string(u8(type)));
}
}
break;
case SCBlockType::U8:
case SCBlockType::U16:
case SCBlockType::U32:
case SCBlockType::U64:
case SCBlockType::S8:
case SCBlockType::S16:
case SCBlockType::S32:
case SCBlockType::S64:
case SCBlockType::Float:
case SCBlockType::Double:
{
size_t entrySize = arrayEntrySize(type);
for (size_t i = 0; i < entrySize; i++)
{
data[offset + 1 + i] ^= xorShift.next();
}
offset += 1 + entrySize;
}
break;
default:
throw internal::CryptoException("Decoding block: Key: " + std::to_string(key()) +
"\nType: " + std::to_string(u8(type)));
}
}
void SCBlock::encrypt()
{
if (!currentlyEncrypted)
{
internal::XorShift32 xorShift(key());
for (size_t i = 0; i < encryptedDataSize() - 4; i++)
{
data[myOffset + 4 + i] ^= xorShift.next();
}
currentlyEncrypted = true;
}
}
void SCBlock::decrypt()
{
if (currentlyEncrypted)
{
internal::XorShift32 xorShift(key());
for (size_t i = 0; i < encryptedDataSize() - 4; i++)
{
data[myOffset + 4 + i] ^= xorShift.next();
}
currentlyEncrypted = false;
}
}
u32 SCBlock::key() const
{
return LittleEndian::convertTo<u32>(&data[myOffset]);
}
void SCBlock::key(u32 v)
{
LittleEndian::convertFrom<u32>(&data[myOffset], v);
}
size_t SCBlock::arrayEntrySize(SCBlockType type)
{
switch (type)
{
case SCBlockType::Bool3:
case SCBlockType::U8:
case SCBlockType::S8:
return 1;
case SCBlockType::U16:
case SCBlockType::S16:
return 2;
case SCBlockType::U32:
case SCBlockType::S32:
case SCBlockType::Float:
return 4;
case SCBlockType::U64:
case SCBlockType::S64:
case SCBlockType::Double:
return 8;
default:
throw internal::CryptoException("Type size unknown: " + std::to_string(u32(type)));
}
}
size_t SCBlock::headerSize(SCBlockType type)
{
switch (type)
{
case SCBlockType::Bool1:
case SCBlockType::Bool2:
case SCBlockType::Bool3:
case SCBlockType::U8:
case SCBlockType::U16:
case SCBlockType::U32:
case SCBlockType::U64:
case SCBlockType::S8:
case SCBlockType::S16:
case SCBlockType::S32:
case SCBlockType::S64:
case SCBlockType::Float:
case SCBlockType::Double:
return 5; // key + type
case SCBlockType::Object:
return 9; // key + type + length
case SCBlockType::Array:
return 10; // key + type + subtype + length
default:
throw internal::CryptoException("Type size unknown: " + std::to_string(u32(type)));
}
}
size_t SCBlock::encryptedDataSize()
{
static constexpr int baseSize = 4 + 1; // key + type
switch (type)
{
case SCBlockType::Bool1:
case SCBlockType::Bool2:
case SCBlockType::Bool3:
return baseSize;
case SCBlockType::Object:
return baseSize + 4 + dataLength; // + datalength variable + actual data
case SCBlockType::Array:
return baseSize + 5 +
dataLength *
arrayEntrySize(subtype); // + subtype + datalength variable + actual data
case SCBlockType::U8:
case SCBlockType::U16:
case SCBlockType::U32:
case SCBlockType::U64:
case SCBlockType::S8:
case SCBlockType::S16:
case SCBlockType::S32:
case SCBlockType::S64:
case SCBlockType::Float:
case SCBlockType::Double:
return baseSize + arrayEntrySize(type); // + actual data
default:
throw internal::CryptoException("Type size unknown: " + std::to_string(u32(type)));
}
}
}
| 13,755
|
C++
|
.cpp
| 361
| 25.692521
| 107
| 0.499888
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,256
|
crypto_sha256.cpp
|
FlagBrew_PKSM-Core/source/utils/crypto_sha256.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "utils/crypto.hpp"
#include <bit>
#define SHA256_BLOCK_SIZE 32
namespace
{
inline u32 CH(u32 x, u32 y, u32 z)
{
return (x & y) ^ (~x & z);
}
inline u32 MAJ(u32 x, u32 y, u32 z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
inline u32 EP0(u32 x)
{
return std::rotr(x, 2) ^ std::rotr(x, 13) ^ std::rotr(x, 22);
}
inline u32 EP1(u32 x)
{
return std::rotr(x, 6) ^ std::rotr(x, 11) ^ std::rotr(x, 25);
}
inline u32 SIG0(u32 x)
{
return std::rotr(x, 7) ^ std::rotr(x, 18) ^ (x >> 3);
}
inline u32 SIG1(u32 x)
{
return std::rotr(x, 17) ^ std::rotr(x, 19) ^ (x >> 10);
}
}
namespace pksm::crypto
{
namespace internal
{
constexpr u32 sha256_table[64] = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e,
0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624,
0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3,
0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
}
std::array<u8, 32> sha256(std::span<const u8> buf)
{
SHA256 context;
context.update(buf);
return context.finish();
}
void SHA256::update()
{
uint32_t a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];
for (i = 0, j = 0; i < 16; ++i, j += 4)
{
m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]);
}
for (; i < 64; ++i)
{
m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
}
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
f = state[5];
g = state[6];
h = state[7];
for (i = 0; i < 64; ++i)
{
t1 = h + EP1(e) + CH(e, f, g) + internal::sha256_table[i] + m[i];
t2 = EP0(a) + MAJ(a, b, c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
void SHA256::update(std::span<const u8> buf)
{
for (size_t i = 0; i < buf.size(); i++)
{
data[dataLength++] = buf[i];
if (dataLength == 64)
{
update();
bitLength += 512;
dataLength = 0;
}
}
}
std::array<u8, 32> SHA256::finish()
{
std::array<u8, 32> ret;
uint32_t i = dataLength;
// Pad whatever data is left in the buffer.
if (dataLength < 56)
{
data[i++] = 0x80;
while (i < 56)
{
data[i++] = 0x00;
}
}
else
{
data[i++] = 0x80;
while (i < 64)
{
data[i++] = 0x00;
}
update();
std::fill_n(data, 56, 0);
}
// Append to the padding the total message's length in bits and transform.
bitLength += dataLength * 8;
data[63] = bitLength;
data[62] = bitLength >> 8;
data[61] = bitLength >> 16;
data[60] = bitLength >> 24;
data[59] = bitLength >> 32;
data[58] = bitLength >> 40;
data[57] = bitLength >> 48;
data[56] = bitLength >> 56;
update();
// Since this implementation uses little endian byte ordering and SHA uses big endian,
// reverse all the bytes when copying the final state to the output hash.
for (i = 0; i < 4; ++i)
{
ret[i] = (state[0] >> (24 - i * 8)) & 0x000000ff;
ret[i + 4] = (state[1] >> (24 - i * 8)) & 0x000000ff;
ret[i + 8] = (state[2] >> (24 - i * 8)) & 0x000000ff;
ret[i + 12] = (state[3] >> (24 - i * 8)) & 0x000000ff;
ret[i + 16] = (state[4] >> (24 - i * 8)) & 0x000000ff;
ret[i + 20] = (state[5] >> (24 - i * 8)) & 0x000000ff;
ret[i + 24] = (state[6] >> (24 - i * 8)) & 0x000000ff;
ret[i + 28] = (state[7] >> (24 - i * 8)) & 0x000000ff;
}
return ret;
}
}
| 6,289
|
C++
|
.cpp
| 180
| 26.75
| 95
| 0.521768
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,257
|
crypto_sha1.cpp
|
FlagBrew_PKSM-Core/source/utils/crypto_sha1.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "utils/crypto.hpp"
namespace pksm::crypto
{
std::array<u8, 20> sha1(std::span<const u8> data)
{
SHA1 context;
context.update(data);
return context.finish();
}
void SHA1::update()
{
u32 w[80];
for (size_t i = 0; i < 16; i++)
{
w[i] = (data[i * 4 + 0] << 24) | (data[i * 4 + 1] << 16) | (data[i * 4 + 2] << 8) |
(data[i * 4 + 3] << 0);
}
for (size_t i = 16; i < 80; i++)
{
w[i] = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16];
w[i] = std::rotl(w[i], 1);
}
u32 a = state[0], b = state[1], c = state[2], d = state[3], e = state[4];
for (size_t i = 0; i < 80; i++)
{
u32 f, k;
if (i < 20)
{
f = (b & c) | ((~b) & d);
k = 0x5A827999;
}
else if (i < 40)
{
f = b ^ c ^ d;
k = 0x6ED9EBA1;
}
else if (i < 60)
{
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
}
else if (i < 80)
{
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
u32 temp = std::rotl(a, 5) + f + e + k + w[i];
e = d;
d = c;
c = std::rotl(b, 30);
b = a;
a = temp;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
}
void SHA1::update(std::span<const u8> buf)
{
for (size_t i = 0; i < buf.size(); i++)
{
data[dataLength++] = buf[i];
if (dataLength == 64)
{
update();
bitLength += 512;
dataLength = 0;
}
}
}
std::array<u8, 20> SHA1::finish()
{
std::array<u8, 20> ret;
uint32_t i = dataLength;
// Pad whatever data is left in the buffer.
if (dataLength < 56)
{
data[i++] = 0x80;
while (i < 56)
{
data[i++] = 0x00;
}
}
else
{
data[i++] = 0x80;
while (i < 64)
{
data[i++] = 0x00;
}
update();
std::fill_n(data, 56, 0);
}
// Append to the padding the total message's length in bits and transform.
bitLength += dataLength * 8;
data[63] = bitLength;
data[62] = bitLength >> 8;
data[61] = bitLength >> 16;
data[60] = bitLength >> 24;
data[59] = bitLength >> 32;
data[58] = bitLength >> 40;
data[57] = bitLength >> 48;
data[56] = bitLength >> 56;
update();
// Since this implementation uses little endian byte ordering and SHA uses big endian,
// reverse all the bytes when copying the final state to the output hash.
for (i = 0; i < 4; ++i)
{
ret[i] = (state[0] >> (24 - i * 8)) & 0x000000ff;
ret[i + 4] = (state[1] >> (24 - i * 8)) & 0x000000ff;
ret[i + 8] = (state[2] >> (24 - i * 8)) & 0x000000ff;
ret[i + 12] = (state[3] >> (24 - i * 8)) & 0x000000ff;
ret[i + 16] = (state[4] >> (24 - i * 8)) & 0x000000ff;
}
return ret;
}
}
| 4,780
|
C++
|
.cpp
| 144
| 23.930556
| 95
| 0.465051
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,258
|
random.cpp
|
FlagBrew_PKSM-Core/source/utils/random.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "utils/random.hpp"
#include "../../pcg-cpp/include/pcg_random.hpp"
#include "utils/DateTime.hpp"
#ifndef _PKSMCORE_CONFIGURED
#include "PKSMCORE_CONFIG.h"
#endif
namespace
{
#ifdef _PKSMCORE_DISABLE_THREAD_SAFETY
pcg32 randomNumbers;
std::uniform_int_distribution<u32> distrib;
bool seeded = false;
#else
thread_local pcg32 randomNumbers;
thread_local std::uniform_int_distribution<u32> distrib;
thread_local bool seeded = false;
#endif
}
pksm::UniformRandomBitGenerator::result_type
pksm::UniformRandomBitGenerator::operator()() const noexcept
{
return randomNumbers(max());
}
u32 pksm::randomNumber(u32 minInclusive, u32 maxInclusive)
{
if (!seeded)
{
DateTime now = DateTime::now();
std::seed_seq seq = std::initializer_list<u32>{
now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()};
seedRand(seq);
}
return distrib(
randomNumbers, std::uniform_int_distribution<u32>::param_type{minInclusive, maxInclusive});
}
void pksm::seedRand(u32 seed)
{
randomNumbers.seed(seed);
seeded = true;
}
void pksm::seedRand(std::seed_seq& seed)
{
randomNumbers.seed(seed);
seeded = true;
}
| 2,499
|
C++
|
.cpp
| 70
| 32.7
| 99
| 0.717472
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,259
|
flagUtil.cpp
|
FlagBrew_PKSM-Core/source/utils/flagUtil.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62, Pk11
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "utils/flagUtil.hpp"
bool pksm::FlagUtil::getFlag(const u8* data, int offset, int bitIndex)
{
bitIndex &= 7; // ensure bit access is 0-7
return (data[offset] >> bitIndex & 1) != 0;
}
void pksm::FlagUtil::setFlag(u8* data, int offset, int bitIndex, bool v)
{
bitIndex &= 7; // ensure bit access is 0-7
data[offset] &= ~(1 << bitIndex);
data[offset] |= (v ? 1 : 0) << bitIndex;
}
| 1,690
|
C++
|
.cpp
| 37
| 43.405405
| 76
| 0.706061
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,536,260
|
VersionTables.cpp
|
FlagBrew_PKSM-Core/source/utils/VersionTables.cpp
|
/*
* This file is part of PKSM-Core
* Copyright (C) 2016-2022 Bernardo Giordano, Admiral Fish, piepie62, Pk11
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "utils/VersionTables.hpp"
#include "personal/personal.hpp"
#include "ppCount.hpp"
#include <algorithm>
#include <functional>
namespace
{
template <typename T>
requires std::is_enum_v<T> || std::integral<T> || requires { typename T::EnumType; }
inline std::set<T> create_set_consecutive(const T& begin, const T& end)
{
std::set<T> set;
if constexpr (std::is_integral_v<T>)
{
for (T i = begin; i <= end; i++)
{
set.insert(i);
}
}
else if constexpr (std::is_enum_v<T>)
{
using INT = std::underlying_type_t<T>;
for (INT i = INT(begin); i <= INT(end); i++)
{
set.insert(T(i));
}
}
else
{
using INT = std::underlying_type_t<typename T::EnumType>;
for (INT i = INT(begin); i <= INT(end); i++)
{
set.insert(T(i));
}
}
return set;
}
}
namespace pksm
{
const std::set<int>& VersionTables::availableItems(GameVersion version)
{
static const std::set<int> emptySet;
switch (version)
{
case GameVersion::RD:
case GameVersion::GN:
case GameVersion::BU:
case GameVersion::YW:
{
static const std::set<int> items = {0, 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45,
46, 47, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 60, 61, 62, 63, 64, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214,
215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230,
231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246,
247, 248, 249, 250};
return items;
}
case GameVersion::GD:
case GameVersion::SV:
{
static const std::set<int> items = {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 51, 52, 53, 54, 55, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 101,
102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 117, 118, 119,
121, 122, 123, 124, 125, 126, 127, 128, 130, 131, 132, 133, 134, 138, 139, 140,
143, 144, 146, 150, 151, 152, 156, 157, 158, 159, 160, 161, 163, 164, 165, 166,
167, 168, 169, 170, 172, 173, 174, 175, 178, 180, 181, 182, 183, 184, 185, 186,
187, 188, 189, 191, 192, 193, 194, 196, 197, 198, 199, 200, 201, 202, 203, 204,
205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 221,
222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237,
238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249};
return items;
}
case GameVersion::C:
{
static const std::set<int> items = {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 51, 52, 53, 54, 55, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
117, 118, 119, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133,
134, 138, 139, 140, 143, 144, 146, 150, 151, 152, 156, 157, 158, 159, 160, 161,
163, 164, 165, 166, 167, 168, 169, 170, 172, 173, 174, 175, 178, 180, 181, 182,
183, 184, 185, 186, 187, 188, 189, 191, 192, 193, 194, 196, 197, 198, 199, 200,
201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216,
217, 218, 219, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249};
return items;
}
case GameVersion::R:
case GameVersion::S:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 348); });
return items;
}
case GameVersion::FR:
case GameVersion::LG:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 374); });
return items;
}
case GameVersion::E:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 376); });
return items;
}
case GameVersion::D:
case GameVersion::P:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 464); });
return items;
}
case GameVersion::Pt:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 467); });
return items;
}
case GameVersion::HG:
case GameVersion::SS:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 536); });
return items;
}
case GameVersion::B:
case GameVersion::W:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 632); });
return items;
}
case GameVersion::B2:
case GameVersion::W2:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 638); });
return items;
}
case GameVersion::X:
case GameVersion::Y:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 717); });
return items;
}
case GameVersion::OR:
case GameVersion::AS:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 775); });
return items;
}
case GameVersion::SN:
case GameVersion::MN:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 920); });
return items;
}
case GameVersion::US:
case GameVersion::UM:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 959); });
return items;
}
case GameVersion::GE:
case GameVersion::GP:
{
static const std::set<int> items = {0, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 38, 39, 40, 41, 709, 903, 328, 329, 330, 331, 332, 333, 334,
335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350,
351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366,
367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382,
383, 384, 385, 386, 387, 50, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969,
970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985,
986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000,
1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013,
1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026,
1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039,
1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052,
1053, 1054, 1055, 1056, 1057, 51, 53, 81, 82, 83, 84, 85, 849, 1, 2, 3, 4, 12,
164, 166, 168, 861, 862, 863, 864, 865, 866, 55, 56, 57, 58, 59, 60, 61, 62,
656, 659, 660, 661, 662, 663, 671, 672, 675, 676, 678, 679, 760, 762, 770, 773,
76, 77, 78, 79, 86, 87, 88, 89, 90, 91, 92, 93, 101, 102, 103, 113, 115, 121,
122, 123, 124, 125, 126, 127, 128, 442, 571, 632, 651, 795, 796, 872, 873, 874,
875, 876, 877, 878, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896,
900, 901, 902};
return items;
}
case GameVersion::SW:
case GameVersion::SH:
{
static const std::set<int> items =
std::invoke([]() { return create_set_consecutive<int>(0, 1607); });
return items;
}
default:
return emptySet;
}
}
const std::set<Move>& VersionTables::availableMoves(GameVersion version)
{
static const std::set<Move> emptySet;
switch (version)
{
case GameVersion::RD:
case GameVersion::GN:
case GameVersion::BU:
case GameVersion::YW:
{
static const std::set<Move> items = std::invoke(
[]() { return create_set_consecutive<Move>(Move::None, Move::Struggle); });
return items;
}
case GameVersion::GD:
case GameVersion::SV:
case GameVersion::C:
{
static const std::set<Move> items = std::invoke(
[]() { return create_set_consecutive<Move>(Move::None, Move::BeatUp); });
return items;
}
case GameVersion::R:
case GameVersion::S:
case GameVersion::FR:
case GameVersion::LG:
case GameVersion::E:
{
static const std::set<Move> items = std::invoke(
[]() { return create_set_consecutive<Move>(Move::None, Move::PsychoBoost); });
return items;
}
case GameVersion::D:
case GameVersion::P:
case GameVersion::Pt:
case GameVersion::HG:
case GameVersion::SS:
{
static const std::set<Move> items = std::invoke(
[]() { return create_set_consecutive<Move>(Move::None, Move::ShadowForce); });
return items;
}
case GameVersion::B:
case GameVersion::W:
case GameVersion::B2:
case GameVersion::W2:
{
static const std::set<Move> items = std::invoke(
[]() { return create_set_consecutive<Move>(Move::None, Move::FusionBolt); });
return items;
}
case GameVersion::X:
case GameVersion::Y:
{
static const std::set<Move> items = std::invoke(
[]() { return create_set_consecutive<Move>(Move::None, Move::LightofRuin); });
return items;
}
case GameVersion::OR:
case GameVersion::AS:
{
static const std::set<Move> items = std::invoke([]()
{ return create_set_consecutive<Move>(Move::None, Move::HyperspaceFury); });
return items;
}
case GameVersion::SN:
case GameVersion::MN:
{
static const std::set<Move> items = std::invoke(
[]() { return create_set_consecutive<Move>(Move::None, Move::MindBlown); });
return items;
}
case GameVersion::US:
case GameVersion::UM:
{
static const std::set<Move> items = std::invoke(
[]() {
return create_set_consecutive<Move>(Move::None, Move::ClangorousSoulblaze);
});
return items;
}
case GameVersion::GE:
case GameVersion::GP:
{
static const std::set<Move> items = {Move::None, Move::Pound, Move::KarateChop,
Move::DoubleSlap, Move::CometPunch, Move::MegaPunch, Move::PayDay,
Move::FirePunch, Move::IcePunch, Move::ThunderPunch, Move::Scratch,
Move::ViseGrip, Move::Guillotine, Move::RazorWind, Move::SwordsDance, Move::Cut,
Move::Gust, Move::WingAttack, Move::Whirlwind, Move::Fly, Move::Bind,
Move::Slam, Move::VineWhip, Move::Stomp, Move::DoubleKick, Move::MegaKick,
Move::JumpKick, Move::RollingKick, Move::SandAttack, Move::Headbutt,
Move::HornAttack, Move::FuryAttack, Move::HornDrill, Move::Tackle,
Move::BodySlam, Move::Wrap, Move::TakeDown, Move::Thrash, Move::DoubleEdge,
Move::TailWhip, Move::PoisonSting, Move::Twineedle, Move::PinMissile,
Move::Leer, Move::Bite, Move::Growl, Move::Roar, Move::Sing, Move::Supersonic,
Move::SonicBoom, Move::Disable, Move::Acid, Move::Ember, Move::Flamethrower,
Move::Mist, Move::WaterGun, Move::HydroPump, Move::Surf, Move::IceBeam,
Move::Blizzard, Move::Psybeam, Move::BubbleBeam, Move::AuroraBeam,
Move::HyperBeam, Move::Peck, Move::DrillPeck, Move::Submission, Move::LowKick,
Move::Counter, Move::SeismicToss, Move::Strength, Move::Absorb, Move::MegaDrain,
Move::LeechSeed, Move::Growth, Move::RazorLeaf, Move::SolarBeam,
Move::PoisonPowder, Move::StunSpore, Move::SleepPowder, Move::PetalDance,
Move::StringShot, Move::DragonRage, Move::FireSpin, Move::ThunderShock,
Move::Thunderbolt, Move::ThunderWave, Move::Thunder, Move::RockThrow,
Move::Earthquake, Move::Fissure, Move::Dig, Move::Toxic, Move::Confusion,
Move::Psychic, Move::Hypnosis, Move::Meditate, Move::Agility, Move::QuickAttack,
Move::Rage, Move::Teleport, Move::NightShade, Move::Mimic, Move::Screech,
Move::DoubleTeam, Move::Recover, Move::Harden, Move::Minimize,
Move::Smokescreen, Move::ConfuseRay, Move::Withdraw, Move::DefenseCurl,
Move::Barrier, Move::LightScreen, Move::Haze, Move::Reflect, Move::FocusEnergy,
Move::Bide, Move::Metronome, Move::MirrorMove, Move::SelfDestruct,
Move::EggBomb, Move::Lick, Move::Smog, Move::Sludge, Move::BoneClub,
Move::FireBlast, Move::Waterfall, Move::Clamp, Move::Swift, Move::SkullBash,
Move::SpikeCannon, Move::Constrict, Move::Amnesia, Move::Kinesis,
Move::SoftBoiled, Move::HighJumpKick, Move::Glare, Move::DreamEater,
Move::PoisonGas, Move::Barrage, Move::LeechLife, Move::LovelyKiss,
Move::SkyAttack, Move::Transform, Move::Bubble, Move::DizzyPunch, Move::Spore,
Move::Flash, Move::Psywave, Move::Splash, Move::AcidArmor, Move::Crabhammer,
Move::Explosion, Move::FurySwipes, Move::Bonemerang, Move::Rest,
Move::RockSlide, Move::HyperFang, Move::Sharpen, Move::Conversion,
Move::TriAttack, Move::SuperFang, Move::Slash, Move::Substitute, Move::Protect,
Move::SludgeBomb, Move::Outrage, Move::Megahorn, Move::Encore, Move::IronTail,
Move::Crunch, Move::MirrorCoat, Move::ShadowBall, Move::FakeOut, Move::HeatWave,
Move::WillOWisp, Move::Facade, Move::Taunt, Move::HelpingHand, Move::Superpower,
Move::BrickBreak, Move::Yawn, Move::BulkUp, Move::CalmMind, Move::Roost,
Move::Feint, Move::Uturn, Move::SuckerPunch, Move::FlareBlitz, Move::PoisonJab,
Move::DarkPulse, Move::AirSlash, Move::XScissor, Move::BugBuzz,
Move::DragonPulse, Move::NastyPlot, Move::IceShard, Move::FlashCannon,
Move::PowerWhip, Move::StealthRock, Move::AquaJet, Move::QuiverDance,
Move::FoulPlay, Move::ClearSmog, Move::Scald, Move::ShellSmash,
Move::DragonTail, Move::DrillRun, Move::PlayRough, Move::Moonblast,
Move::HappyHour, Move::DazzlingGleam, Move::Celebrate, Move::HoldHands,
Move::ZippyZap, Move::SplishySplash, Move::FloatyFall, Move::BouncyBubble,
Move::BuzzyBuzz, Move::SizzlySlide, Move::GlitzyGlow, Move::BaddyBad,
Move::SappySeed, Move::FreezyFrost, Move::SparklySwirl, Move::DoubleIronBash};
return items;
}
case GameVersion::SW:
case GameVersion::SH:
{
static const std::set<Move> items = std::invoke(
[]() { return create_set_consecutive<Move>(Move::None, Move::EerieSpell); });
return items;
}
default:
return emptySet;
}
}
const std::set<Species>& VersionTables::availableSpecies(GameVersion version)
{
static const std::set<Species> emptySet;
switch (version)
{
case GameVersion::RD:
case GameVersion::GN:
case GameVersion::BU:
case GameVersion::YW:
{
static const std::set<Species> items = std::invoke([]()
{ return create_set_consecutive<Species>(Species::Bulbasaur, Species::Mew); });
return items;
}
case GameVersion::GD:
case GameVersion::SV:
case GameVersion::C:
{
static const std::set<Species> items = std::invoke(
[]() {
return create_set_consecutive<Species>(Species::Bulbasaur, Species::Celebi);
});
return items;
}
case GameVersion::R:
case GameVersion::S:
case GameVersion::FR:
case GameVersion::LG:
case GameVersion::E:
{
static const std::set<Species> items = std::invoke(
[]() {
return create_set_consecutive<Species>(Species::Bulbasaur, Species::Deoxys);
});
return items;
}
case GameVersion::D:
case GameVersion::P:
case GameVersion::Pt:
case GameVersion::HG:
case GameVersion::SS:
{
static const std::set<Species> items = std::invoke(
[]() {
return create_set_consecutive<Species>(Species::Bulbasaur, Species::Arceus);
});
return items;
}
case GameVersion::B:
case GameVersion::W:
case GameVersion::B2:
case GameVersion::W2:
{
static const std::set<Species> items = std::invoke(
[]() {
return create_set_consecutive<Species>(
Species::Bulbasaur, Species::Genesect);
});
return items;
}
case GameVersion::X:
case GameVersion::Y:
case GameVersion::OR:
case GameVersion::AS:
{
static const std::set<Species> items = std::invoke(
[]() {
return create_set_consecutive<Species>(
Species::Bulbasaur, Species::Volcanion);
});
return items;
}
case GameVersion::SN:
case GameVersion::MN:
{
static const std::set<Species> items = std::invoke(
[]() {
return create_set_consecutive<Species>(
Species::Bulbasaur, Species::Marshadow);
});
return items;
}
case GameVersion::US:
case GameVersion::UM:
{
static const std::set<Species> items = std::invoke(
[]() {
return create_set_consecutive<Species>(
Species::Bulbasaur, Species::Zeraora);
});
return items;
}
case GameVersion::GE:
case GameVersion::GP:
{
static const std::set<Species> items = std::invoke(
[]()
{
auto ret =
create_set_consecutive<Species>(Species::Bulbasaur, Species::Mew);
ret.emplace(Species::Meltan);
ret.emplace(Species::Melmetal);
return ret;
});
return items;
}
case GameVersion::SW:
case GameVersion::SH:
{
static const std::set<Species> items = {Species::Bulbasaur, Species::Ivysaur,
Species::Venusaur, Species::Charmander, Species::Charmeleon, Species::Charizard,
Species::Squirtle, Species::Wartortle, Species::Blastoise, Species::Caterpie,
Species::Metapod, Species::Butterfree, Species::Pikachu, Species::Raichu,
Species::Clefairy, Species::Clefable, Species::Vulpix, Species::Ninetales,
Species::Oddish, Species::Gloom, Species::Vileplume, Species::Diglett,
Species::Dugtrio, Species::Meowth, Species::Persian, Species::Growlithe,
Species::Arcanine, Species::Machop, Species::Machoke, Species::Machamp,
Species::Ponyta, Species::Rapidash, Species::Farfetchd, Species::Shellder,
Species::Cloyster, Species::Gastly, Species::Haunter, Species::Gengar,
Species::Onix, Species::Krabby, Species::Kingler, Species::Hitmonlee,
Species::Hitmonchan, Species::Koffing, Species::Weezing, Species::Rhyhorn,
Species::Rhydon, Species::Goldeen, Species::Seaking, Species::MrMime,
Species::Magikarp, Species::Gyarados, Species::Lapras, Species::Ditto,
Species::Eevee, Species::Vaporeon, Species::Jolteon, Species::Flareon,
Species::Snorlax, Species::Mewtwo, Species::Mew, Species::Hoothoot,
Species::Noctowl, Species::Chinchou, Species::Lanturn, Species::Pichu,
Species::Cleffa, Species::Togepi, Species::Togetic, Species::Natu,
Species::Xatu, Species::Bellossom, Species::Sudowoodo, Species::Wooper,
Species::Quagsire, Species::Espeon, Species::Umbreon, Species::Wobbuffet,
Species::Steelix, Species::Qwilfish, Species::Shuckle, Species::Sneasel,
Species::Swinub, Species::Piloswine, Species::Corsola, Species::Remoraid,
Species::Octillery, Species::Delibird, Species::Mantine, Species::Tyrogue,
Species::Hitmontop, Species::Larvitar, Species::Pupitar, Species::Tyranitar,
Species::Celebi, Species::Zigzagoon, Species::Linoone, Species::Lotad,
Species::Lombre, Species::Ludicolo, Species::Seedot, Species::Nuzleaf,
Species::Shiftry, Species::Wingull, Species::Pelipper, Species::Ralts,
Species::Kirlia, Species::Gardevoir, Species::Nincada, Species::Ninjask,
Species::Shedinja, Species::Sableye, Species::Mawile, Species::Electrike,
Species::Manectric, Species::Roselia, Species::Wailmer, Species::Wailord,
Species::Torkoal, Species::Trapinch, Species::Vibrava, Species::Flygon,
Species::Lunatone, Species::Solrock, Species::Barboach, Species::Whiscash,
Species::Corphish, Species::Crawdaunt, Species::Baltoy, Species::Claydol,
Species::Feebas, Species::Milotic, Species::Duskull, Species::Dusclops,
Species::Wynaut, Species::Snorunt, Species::Glalie, Species::Jirachi,
Species::Budew, Species::Roserade, Species::Combee, Species::Vespiquen,
Species::Cherubi, Species::Cherrim, Species::Shellos, Species::Gastrodon,
Species::Drifloon, Species::Drifblim, Species::Stunky, Species::Skuntank,
Species::Bronzor, Species::Bronzong, Species::Bonsly, Species::MimeJr,
Species::Munchlax, Species::Riolu, Species::Lucario, Species::Hippopotas,
Species::Hippowdon, Species::Skorupi, Species::Drapion, Species::Croagunk,
Species::Toxicroak, Species::Mantyke, Species::Snover, Species::Abomasnow,
Species::Weavile, Species::Rhyperior, Species::Togekiss, Species::Leafeon,
Species::Glaceon, Species::Mamoswine, Species::Gallade, Species::Dusknoir,
Species::Froslass, Species::Rotom, Species::Purrloin, Species::Liepard,
Species::Munna, Species::Musharna, Species::Pidove, Species::Tranquill,
Species::Unfezant, Species::Roggenrola, Species::Boldore, Species::Gigalith,
Species::Woobat, Species::Swoobat, Species::Drilbur, Species::Excadrill,
Species::Timburr, Species::Gurdurr, Species::Conkeldurr, Species::Tympole,
Species::Palpitoad, Species::Seismitoad, Species::Throh, Species::Sawk,
Species::Cottonee, Species::Whimsicott, Species::Basculin, Species::Darumaka,
Species::Darmanitan, Species::Maractus, Species::Dwebble, Species::Crustle,
Species::Scraggy, Species::Scrafty, Species::Sigilyph, Species::Yamask,
Species::Cofagrigus, Species::Trubbish, Species::Garbodor, Species::Minccino,
Species::Cinccino, Species::Gothita, Species::Gothorita, Species::Gothitelle,
Species::Solosis, Species::Duosion, Species::Reuniclus, Species::Vanillite,
Species::Vanillish, Species::Vanilluxe, Species::Karrablast,
Species::Escavalier, Species::Frillish, Species::Jellicent, Species::Joltik,
Species::Galvantula, Species::Ferroseed, Species::Ferrothorn, Species::Klink,
Species::Klang, Species::Klinklang, Species::Elgyem, Species::Beheeyem,
Species::Litwick, Species::Lampent, Species::Chandelure, Species::Axew,
Species::Fraxure, Species::Haxorus, Species::Cubchoo, Species::Beartic,
Species::Shelmet, Species::Accelgor, Species::Stunfisk, Species::Golett,
Species::Golurk, Species::Pawniard, Species::Bisharp, Species::Rufflet,
Species::Braviary, Species::Vullaby, Species::Mandibuzz, Species::Heatmor,
Species::Durant, Species::Deino, Species::Zweilous, Species::Hydreigon,
Species::Cobalion, Species::Terrakion, Species::Virizion, Species::Reshiram,
Species::Zekrom, Species::Kyurem, Species::Keldeo, Species::Bunnelby,
Species::Diggersby, Species::Pancham, Species::Pangoro, Species::Espurr,
Species::Meowstic, Species::Honedge, Species::Doublade, Species::Aegislash,
Species::Spritzee, Species::Aromatisse, Species::Swirlix, Species::Slurpuff,
Species::Inkay, Species::Malamar, Species::Binacle, Species::Barbaracle,
Species::Helioptile, Species::Heliolisk, Species::Sylveon, Species::Hawlucha,
Species::Goomy, Species::Sliggoo, Species::Goodra, Species::Phantump,
Species::Trevenant, Species::Pumpkaboo, Species::Gourgeist, Species::Bergmite,
Species::Avalugg, Species::Noibat, Species::Noivern, Species::Rowlet,
Species::Dartrix, Species::Decidueye, Species::Litten, Species::Torracat,
Species::Incineroar, Species::Popplio, Species::Brionne, Species::Primarina,
Species::Grubbin, Species::Charjabug, Species::Vikavolt, Species::Cutiefly,
Species::Ribombee, Species::Wishiwashi, Species::Mareanie, Species::Toxapex,
Species::Mudbray, Species::Mudsdale, Species::Dewpider, Species::Araquanid,
Species::Morelull, Species::Shiinotic, Species::Salandit, Species::Salazzle,
Species::Stufful, Species::Bewear, Species::Bounsweet, Species::Steenee,
Species::Tsareena, Species::Oranguru, Species::Passimian, Species::Wimpod,
Species::Golisopod, Species::Pyukumuku, Species::TypeNull, Species::Silvally,
Species::Turtonator, Species::Togedemaru, Species::Mimikyu, Species::Drampa,
Species::Dhelmise, Species::Jangmoo, Species::Hakamoo, Species::Kommoo,
Species::Cosmog, Species::Cosmoem, Species::Solgaleo, Species::Lunala,
Species::Necrozma, Species::Marshadow, Species::Zeraora, Species::Meltan,
Species::Melmetal, Species::Grookey, Species::Thwackey, Species::Rillaboom,
Species::Scorbunny, Species::Raboot, Species::Cinderace, Species::Sobble,
Species::Drizzile, Species::Inteleon, Species::Skwovet, Species::Greedent,
Species::Rookidee, Species::Corvisquire, Species::Corviknight, Species::Blipbug,
Species::Dottler, Species::Orbeetle, Species::Nickit, Species::Thievul,
Species::Gossifleur, Species::Eldegoss, Species::Wooloo, Species::Dubwool,
Species::Chewtle, Species::Drednaw, Species::Yamper, Species::Boltund,
Species::Rolycoly, Species::Carkol, Species::Coalossal, Species::Applin,
Species::Flapple, Species::Appletun, Species::Silicobra, Species::Sandaconda,
Species::Cramorant, Species::Arrokuda, Species::Barraskewda, Species::Toxel,
Species::Toxtricity, Species::Sizzlipede, Species::Centiskorch,
Species::Clobbopus, Species::Grapploct, Species::Sinistea, Species::Polteageist,
Species::Hatenna, Species::Hattrem, Species::Hatterene, Species::Impidimp,
Species::Morgrem, Species::Grimmsnarl, Species::Obstagoon, Species::Perrserker,
Species::Cursola, Species::Sirfetchd, Species::MrRime, Species::Runerigus,
Species::Milcery, Species::Alcremie, Species::Falinks, Species::Pincurchin,
Species::Snom, Species::Frosmoth, Species::Stonjourner, Species::Eiscue,
Species::Indeedee, Species::Morpeko, Species::Cufant, Species::Copperajah,
Species::Dracozolt, Species::Arctozolt, Species::Dracovish, Species::Arctovish,
Species::Duraludon, Species::Dreepy, Species::Drakloak, Species::Dragapult,
Species::Zacian, Species::Zamazenta, Species::Eternatus,
// Isle of Armor
Species::Sandshrew, Species::Sandslash, Species::Jigglypuff,
Species::Wigglytuff, Species::Psyduck, Species::Golduck, Species::Poliwag,
Species::Poliwhirl, Species::Poliwrath, Species::Abra, Species::Kadabra,
Species::Alakazam, Species::Tentacool, Species::Tentacruel, Species::Slowpoke,
Species::Slowbro, Species::Magnemite, Species::Magneton, Species::Exeggcute,
Species::Exeggutor, Species::Cubone, Species::Marowak, Species::Lickitung,
Species::Chansey, Species::Tangela, Species::Kangaskhan, Species::Horsea,
Species::Seadra, Species::Staryu, Species::Starmie, Species::Scyther,
Species::Pinsir, Species::Tauros, Species::Igglybuff, Species::Marill,
Species::Azumarill, Species::Politoed, Species::Slowking, Species::Dunsparce,
Species::Scizor, Species::Heracross, Species::Skarmory, Species::Kingdra,
Species::Porygon2, Species::Miltank, Species::Blissey, Species::Whismur,
Species::Loudred, Species::Exploud, Species::Azurill, Species::Carvanha,
Species::Sharpedo, Species::Shinx, Species::Luxio, Species::Luxray,
Species::Buneary, Species::Lopunny, Species::Happiny, Species::Magnezone,
Species::Lickilicky, Species::Tangrowth, Species::PorygonZ, Species::Lillipup,
Species::Herdier, Species::Stoutland, Species::Venipede, Species::Whirlipede,
Species::Scolipede, Species::Petilil, Species::Lilligant, Species::Sandile,
Species::Krokorok, Species::Krookodile, Species::Zorua, Species::Zoroark,
Species::Emolga, Species::Foongus, Species::Amoonguss, Species::Mienfoo,
Species::Mienshao, Species::Druddigon, Species::Bouffalant, Species::Larvesta,
Species::Volcarona, Species::Fletchling, Species::Fletchinder,
Species::Talonflame, Species::Skrelp, Species::Dragalge, Species::Clauncher,
Species::Clawitzer, Species::Dedenne, Species::Klefki, Species::Rockruff,
Species::Lycanroc, Species::Fomantis, Species::Lurantis, Species::Comfey,
Species::Sandygast, Species::Palossand, Species::Magearna, Species::Kubfu,
Species::Urshifu, Species::Zarude,
// Crown Tundra
Species::Regieleki, Species::Regidrago, Species::Glastrier, Species::Spectrier,
Species::Calyrex, Species::Articuno, Species::Zapdos, Species::Moltres,
Species::Slowking, Species::NidoranF, Species::Nidorina, Species::Nidoqueen,
Species::NidoranM, Species::Nidorino, Species::Nidoking, Species::Zubat,
Species::Golbat, Species::Jynx, Species::Electabuzz, Species::Magmar,
Species::Omanyte, Species::Omastar, Species::Kabuto, Species::Kabutops,
Species::Aerodactyl, Species::Dratini, Species::Dragonair, Species::Dragonite,
Species::Crobat, Species::Smoochum, Species::Elekid, Species::Magby,
Species::Raikou, Species::Entei, Species::Suicune, Species::Lugia,
Species::HoOh, Species::Treecko, Species::Grovyle, Species::Sceptile,
Species::Torchic, Species::Combusken, Species::Blaziken, Species::Mudkip,
Species::Marshtomp, Species::Swampert, Species::Aron, Species::Lairon,
Species::Aggron, Species::Swablu, Species::Altaria, Species::Lileep,
Species::Cradily, Species::Anorith, Species::Armaldo, Species::Absol,
Species::Spheal, Species::Sealeo, Species::Walrein, Species::Relicanth,
Species::Bagon, Species::Shelgon, Species::Salamence, Species::Beldum,
Species::Metang, Species::Metagross, Species::Regirock, Species::Regice,
Species::Registeel, Species::Latias, Species::Latios, Species::Kyogre,
Species::Groudon, Species::Rayquaza, Species::Spiritomb, Species::Gible,
Species::Gabite, Species::Garchomp, Species::Electivire, Species::Magmortar,
Species::Uxie, Species::Mesprit, Species::Azelf, Species::Dialga,
Species::Palkia, Species::Heatran, Species::Regigigas, Species::Giratina,
Species::Cresselia, Species::Victini, Species::Audino, Species::Tirtouga,
Species::Carracosta, Species::Archen, Species::Archeops, Species::Cryogonal,
Species::Tornadus, Species::Thundurus, Species::Landorus, Species::Genesect,
Species::Tyrunt, Species::Tyrantrum, Species::Amaura, Species::Aurorus,
Species::Carbink, Species::Xerneas, Species::Yveltal, Species::Zygarde,
Species::Diancie, Species::Volcanion, Species::TapuKoko, Species::TapuLele,
Species::TapuBulu, Species::TapuFini, Species::Nihilego, Species::Buzzwole,
Species::Pheromosa, Species::Xurkitree, Species::Celesteela, Species::Kartana,
Species::Guzzlord, Species::Poipole, Species::Naganadel, Species::Stakataka,
Species::Blacephalon};
return items;
}
default:
return emptySet;
}
}
const std::set<Ability>& VersionTables::availableAbilities(GameVersion version)
{
static const std::set<Ability> emptySet;
switch (version)
{
case GameVersion::RD:
case GameVersion::GN:
case GameVersion::BU:
case GameVersion::YW:
{
static const std::set<Ability> items = {Ability::None};
return items;
}
case GameVersion::GD:
case GameVersion::SV:
case GameVersion::C:
{
static const std::set<Ability> items = {Ability::None};
return items;
}
case GameVersion::R:
case GameVersion::S:
case GameVersion::FR:
case GameVersion::LG:
case GameVersion::E:
{
static const std::set<Ability> items = std::invoke(
[]() {
return create_set_consecutive<Ability>(
Ability::Stench, Ability::TangledFeet);
});
return items;
}
case GameVersion::D:
case GameVersion::P:
case GameVersion::Pt:
case GameVersion::HG:
case GameVersion::SS:
{
static const std::set<Ability> items = std::invoke(
[]() {
return create_set_consecutive<Ability>(Ability::Stench, Ability::BadDreams);
});
return items;
}
case GameVersion::B:
case GameVersion::W:
case GameVersion::B2:
case GameVersion::W2:
{
static const std::set<Ability> items = std::invoke(
[]() {
return create_set_consecutive<Ability>(Ability::Stench, Ability::Teravolt);
});
return items;
}
case GameVersion::X:
case GameVersion::Y:
{
static const std::set<Ability> items = std::invoke(
[]() {
return create_set_consecutive<Ability>(Ability::Stench, Ability::AuraBreak);
});
return items;
}
case GameVersion::OR:
case GameVersion::AS:
{
static const std::set<Ability> items = std::invoke(
[]() {
return create_set_consecutive<Ability>(
Ability::Stench, Ability::DeltaStream);
});
return items;
}
case GameVersion::SN:
case GameVersion::MN:
{
static const std::set<Ability> items = std::invoke(
[]() {
return create_set_consecutive<Ability>(
Ability::Stench, Ability::PrismArmor);
});
return items;
}
case GameVersion::US:
case GameVersion::UM:
{
static const std::set<Ability> items = std::invoke(
[]() {
return create_set_consecutive<Ability>(
Ability::Stench, Ability::Neuroforce);
});
return items;
}
case GameVersion::GE:
case GameVersion::GP:
{
static const std::set<Ability> items = std::invoke(
[]() {
return create_set_consecutive<Ability>(
Ability::Stench, Ability::Neuroforce);
});
return items;
}
case GameVersion::SW:
case GameVersion::SH:
{
static const std::set<Ability> items = std::invoke([]()
{ return create_set_consecutive<Ability>(Ability::Stench, Ability::AsOneG); });
return items;
}
default:
return emptySet;
}
}
const std::set<Ball>& VersionTables::availableBalls(GameVersion version)
{
static const std::set<Ball> emptySet;
switch ((Generation)version)
{
case Generation::ONE:
{
static const std::set<Ball> items = std::invoke(
[]() { return create_set_consecutive<Ball>(Ball::Master, Ball::Safari); });
return items;
}
case Generation::TWO:
{
static const std::set<Ball> items = {Ball::Master, Ball::Ultra, Ball::Great,
Ball::Poke, Ball::Safari, Ball::Fast, Ball::Level, Ball::Lure, Ball::Heavy,
Ball::Love, Ball::Friend, Ball::Moon};
return items;
}
case Generation::THREE:
{
static const std::set<Ball> items = std::invoke(
[]() { return create_set_consecutive<Ball>(Ball::Master, Ball::Premier); });
return items;
}
case Generation::FOUR:
{
static const std::set<Ball> items = std::invoke(
[]() { return create_set_consecutive<Ball>(Ball::Master, Ball::Sport); });
return items;
}
case Generation::FIVE:
case Generation::SIX:
{
static const std::set<Ball> items = std::invoke(
[]() { return create_set_consecutive<Ball>(Ball::Master, Ball::Dream); });
return items;
}
case Generation::SEVEN:
case Generation::LGPE:
case Generation::EIGHT:
{
static const std::set<Ball> items = std::invoke(
[]() { return create_set_consecutive<Ball>(Ball::Master, Ball::Beast); });
return items;
}
default:
return emptySet;
}
}
int VersionTables::maxItem(GameVersion version)
{
switch (version)
{
case GameVersion::RD:
case GameVersion::GN:
case GameVersion::BU:
case GameVersion::YW:
return 250;
case GameVersion::GD:
case GameVersion::SV:
case GameVersion::C:
return 249;
case GameVersion::R:
case GameVersion::S:
case GameVersion::FR:
case GameVersion::LG:
case GameVersion::E:
return 374;
case GameVersion::D:
case GameVersion::P:
return 464;
case GameVersion::Pt:
return 467;
case GameVersion::HG:
case GameVersion::SS:
return 536;
case GameVersion::B:
case GameVersion::W:
return 632;
case GameVersion::B2:
case GameVersion::W2:
return 638;
case GameVersion::X:
case GameVersion::Y:
return 717;
case GameVersion::OR:
case GameVersion::AS:
return 775;
case GameVersion::SN:
case GameVersion::MN:
return 920;
case GameVersion::US:
case GameVersion::UM:
return 959;
case GameVersion::GE:
case GameVersion::GP:
return 1057;
case GameVersion::SW:
case GameVersion::SH:
return 1607;
default:
return 0;
}
}
Move VersionTables::maxMove(GameVersion version)
{
switch (version)
{
case GameVersion::RD:
case GameVersion::GN:
case GameVersion::BU:
case GameVersion::YW:
return Move::Substitute; // technically it's Struggle
case GameVersion::GD:
case GameVersion::SV:
case GameVersion::C:
return Move::BeatUp;
case GameVersion::R:
case GameVersion::S:
case GameVersion::FR:
case GameVersion::LG:
case GameVersion::E:
return Move::PsychoBoost;
case GameVersion::D:
case GameVersion::P:
case GameVersion::Pt:
case GameVersion::HG:
case GameVersion::SS:
return Move::ShadowForce;
case GameVersion::B:
case GameVersion::W:
case GameVersion::B2:
case GameVersion::W2:
return Move::FusionBolt;
case GameVersion::X:
case GameVersion::Y:
return Move::LightofRuin;
case GameVersion::OR:
case GameVersion::AS:
return Move::HyperspaceFury;
case GameVersion::SN:
case GameVersion::MN:
return Move::MindBlown;
case GameVersion::US:
case GameVersion::UM:
return Move::ClangorousSoulblaze;
case GameVersion::GE:
case GameVersion::GP:
return Move::DoubleIronBash;
case GameVersion::SW:
case GameVersion::SH:
return Move::EerieSpell;
default:
return Move::None;
}
}
Species VersionTables::maxSpecies(GameVersion version)
{
switch (version)
{
case GameVersion::RD:
case GameVersion::GN:
case GameVersion::BU:
case GameVersion::YW:
return Species::Mew;
case GameVersion::GD:
case GameVersion::SV:
case GameVersion::C:
return Species::Celebi;
case GameVersion::R:
case GameVersion::S:
case GameVersion::FR:
case GameVersion::LG:
case GameVersion::E:
return Species::Deoxys;
case GameVersion::D:
case GameVersion::P:
case GameVersion::Pt:
case GameVersion::HG:
case GameVersion::SS:
return Species::Arceus;
case GameVersion::B:
case GameVersion::W:
case GameVersion::B2:
case GameVersion::W2:
return Species::Genesect;
case GameVersion::X:
case GameVersion::Y:
case GameVersion::OR:
case GameVersion::AS:
return Species::Volcanion;
case GameVersion::SN:
case GameVersion::MN:
return Species::Marshadow;
case GameVersion::US:
case GameVersion::UM:
return Species::Zeraora;
case GameVersion::GE:
case GameVersion::GP:
return Species::Melmetal;
case GameVersion::SW:
case GameVersion::SH:
return Species::Calyrex;
default:
return Species::None;
}
}
Ability VersionTables::maxAbility(GameVersion version)
{
switch (version)
{
case GameVersion::R:
case GameVersion::S:
case GameVersion::FR:
case GameVersion::LG:
case GameVersion::E:
return Ability::TangledFeet;
case GameVersion::D:
case GameVersion::P:
case GameVersion::Pt:
case GameVersion::HG:
case GameVersion::SS:
return Ability::BadDreams;
case GameVersion::B:
case GameVersion::W:
case GameVersion::B2:
case GameVersion::W2:
return Ability::Teravolt;
case GameVersion::X:
case GameVersion::Y:
return Ability::AuraBreak;
case GameVersion::OR:
case GameVersion::AS:
return Ability::DeltaStream;
case GameVersion::SN:
case GameVersion::MN:
return Ability::PrismArmor;
case GameVersion::US:
case GameVersion::UM:
return Ability::Neuroforce;
case GameVersion::GE:
case GameVersion::GP:
return Ability::Neuroforce;
case GameVersion::SW:
case GameVersion::SH:
return Ability::AsOneG;
default:
return Ability::None;
}
}
Ball VersionTables::maxBall(GameVersion version)
{
switch ((Generation)version)
{
case Generation::ONE:
return Ball::Safari;
case Generation::TWO:
return Ball::Moon;
case Generation::THREE:
return Ball::Premier;
case Generation::FOUR:
return Ball::Sport;
case Generation::FIVE:
case Generation::SIX:
return Ball::Dream;
case Generation::SEVEN:
case Generation::LGPE:
case Generation::EIGHT:
return Ball::Beast;
default:
return Ball::None;
}
}
u8 VersionTables::formCount(GameVersion version, Species species)
{
switch (version)
{
case GameVersion::GD:
case GameVersion::SV:
case GameVersion::C:
return PersonalGSC::formCount(u16(species));
case GameVersion::R:
case GameVersion::S:
case GameVersion::FR:
case GameVersion::LG:
case GameVersion::E:
return PersonalRSFRLGE::formCount(u16(species));
case GameVersion::D:
case GameVersion::P:
if (species == Species::Rotom || species == Species::Giratina ||
species == Species::Shaymin)
{
return 1;
}
// falls through
case GameVersion::Pt:
if (species == Species::Pichu)
{
return 1;
}
// falls through
case GameVersion::HG:
case GameVersion::SS:
return PersonalDPPtHGSS::formCount(u16(species));
case GameVersion::B:
case GameVersion::W:
if (species == Species::Tornadus || species == Species::Thundurus ||
species == Species::Landorus || species == Species::Kyurem ||
species == Species::Keldeo)
{
return 1;
}
// falls through
case GameVersion::B2:
case GameVersion::W2:
return PersonalBWB2W2::formCount(u16(species));
case GameVersion::X:
case GameVersion::Y:
if (species == Species::Beedrill || species == Species::Pidgeot ||
species == Species::Pikachu || species == Species::Slowbro ||
species == Species::Steelix || species == Species::Sceptile ||
species == Species::Swampert || species == Species::Sableye ||
species == Species::Sharpedo || species == Species::Camerupt ||
species == Species::Altaria || species == Species::Glalie ||
species == Species::Salamence || species == Species::Metagross ||
species == Species::Kyogre || species == Species::Groudon ||
species == Species::Rayquaza || species == Species::Lopunny ||
species == Species::Gallade || species == Species::Audino ||
species == Species::Hoopa || species == Species::Diancie)
{
return 1;
}
// falls through
case GameVersion::OR:
case GameVersion::AS:
return PersonalXYORAS::formCount(u16(species));
case GameVersion::SN:
case GameVersion::MN:
if (species == Species::Lycanroc)
{
return 2;
}
if (species == Species::Pikachu)
{
return 7;
}
if (species == Species::Necrozma || species == Species::Ribombee ||
species == Species::Araquanid || species == Species::Togedemaru)
{
return 1;
}
if (species == Species::Marowak)
{
return 2;
}
// falls through
case GameVersion::US:
case GameVersion::UM:
return PersonalSMUSUM::formCount(u16(species));
case GameVersion::GE:
case GameVersion::GP:
return PersonalLGPE::formCount(u16(species));
case GameVersion::SW:
case GameVersion::SH:
return PersonalSWSH::formCount(u16(species));
default:
return 1;
}
}
u8 VersionTables::movePP(pksm::Generation gen, Move move, u8 ppUps)
{
if (move == pksm::Move::INVALID || move == pksm::Move::None ||
size_t(move) >= internal::PP_G8.size())
{
return 0;
}
u8 val = 0;
switch (gen)
{
case pksm::Generation::EIGHT:
case pksm::Generation::SEVEN:
val = internal::PP_G8[size_t(move)];
break;
case pksm::Generation::SIX:
{
auto found = std::find_if(internal::PPDiff_G6.begin(), internal::PPDiff_G6.end(),
[move](const std::pair<pksm::Move, u8>& v) { return v.first == move; });
if (found != internal::PPDiff_G6.end())
{
val = found->second;
}
else
{
val = internal::PP_G8[size_t(move)];
}
}
break;
case pksm::Generation::FIVE:
{
auto found = std::find_if(internal::PPDiff_G5.begin(), internal::PPDiff_G5.end(),
[move](const std::pair<pksm::Move, u8>& v) { return v.first == move; });
if (found != internal::PPDiff_G5.end())
{
val = found->second;
}
else
{
val = internal::PP_G8[size_t(move)];
}
}
break;
case pksm::Generation::FOUR:
{
auto found = std::find_if(internal::PPDiff_G4.begin(), internal::PPDiff_G4.end(),
[move](const std::pair<pksm::Move, u8>& v) { return v.first == move; });
if (found != internal::PPDiff_G4.end())
{
val = found->second;
}
else
{
val = internal::PP_G8[size_t(move)];
}
}
break;
// So... no PP changes for Gen I and II moves occurred until Gen IV. Nice.
case pksm::Generation::ONE:
case pksm::Generation::TWO:
case pksm::Generation::THREE:
{
auto found =
std::find_if(internal::PPDiff_G123.begin(), internal::PPDiff_G123.end(),
[move](const std::pair<pksm::Move, u8>& v) { return v.first == move; });
if (found != internal::PPDiff_G123.end())
{
val = found->second;
}
else
{
val = internal::PP_G8[size_t(move)];
}
}
break;
case pksm::Generation::LGPE:
{
auto found =
std::find_if(internal::PPDiff_LGPE.begin(), internal::PPDiff_LGPE.end(),
[move](const std::pair<pksm::Move, u8>& v) { return v.first == move; });
if (found != internal::PPDiff_LGPE.end())
{
val = found->second;
}
else
{
val = internal::PP_G8[size_t(move)];
}
}
break;
default:
return 0;
}
// Stupid thing G1/2 does: they can't store above 63 for PP value
if (gen <= pksm::Generation::TWO && val == 40)
{
return val + 7 * ppUps;
}
return val + ((val / 5) * ppUps);
}
}
| 61,024
|
C++
|
.cpp
| 1,256
| 32.855892
| 100
| 0.517096
|
FlagBrew/PKSM-Core
| 35
| 9
| 2
|
GPL-3.0
|
9/20/2024, 10:44:35 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.