refactor: update and format SlippiGame

This commit is contained in:
Nikhil Narayana 2022-06-15 22:11:28 -07:00
commit 9392df6991
2 changed files with 666 additions and 687 deletions

View file

@ -4,28 +4,24 @@
#include "SlippiGame.h" #include "SlippiGame.h"
namespace Slippi namespace Slippi {
{ //**********************************************************************
//********************************************************************** //* Event Handlers
//* Event Handlers //**********************************************************************
//********************************************************************** // The read operators will read a value and increment the index so the next read
// The read operators will read a value and increment the index so the next read // will read in the correct location
// will read in the correct location uint8_t readByte(uint8_t *a, int &idx, uint32_t maxSize, uint8_t defaultValue) {
uint8_t readByte(uint8_t* a, int& idx, uint32_t maxSize, uint8_t defaultValue) if (idx >= (int)maxSize) {
{
if (idx >= (int)maxSize)
{
idx += 1; idx += 1;
return defaultValue; return defaultValue;
} }
return a[idx++]; return a[idx++];
} }
uint16_t readHalf(uint8_t* a, int& idx, uint32_t maxSize, uint16_t defaultValue) uint16_t readHalf(uint8_t *a, int &idx, uint32_t maxSize,
{ uint16_t defaultValue) {
if (idx >= (int)maxSize) if (idx >= (int)maxSize) {
{
idx += 2; idx += 2;
return defaultValue; return defaultValue;
} }
@ -33,40 +29,36 @@ namespace Slippi
uint16_t value = a[idx] << 8 | a[idx + 1]; uint16_t value = a[idx] << 8 | a[idx + 1];
idx += 2; idx += 2;
return value; return value;
} }
uint32_t readWord(uint8_t* a, int& idx, uint32_t maxSize, uint32_t defaultValue) uint32_t readWord(uint8_t *a, int &idx, uint32_t maxSize,
{ uint32_t defaultValue) {
if (idx >= (int)maxSize) if (idx >= (int)maxSize) {
{
idx += 4; idx += 4;
return defaultValue; return defaultValue;
} }
uint32_t value = a[idx] << 24 | a[idx + 1] << 16 | a[idx + 2] << 8 | a[idx + 3]; uint32_t value =
a[idx] << 24 | a[idx + 1] << 16 | a[idx + 2] << 8 | a[idx + 3];
idx += 4; idx += 4;
return value; return value;
} }
float readFloat(uint8_t* a, int& idx, uint32_t maxSize, float defaultValue) float readFloat(uint8_t *a, int &idx, uint32_t maxSize, float defaultValue) {
{ uint32_t bytes = readWord(a, idx, maxSize, *(uint32_t *)(&defaultValue));
uint32_t bytes = readWord(a, idx, maxSize, *(uint32_t*)(&defaultValue)); return *(float *)(&bytes);
return *(float*)(&bytes); }
}
void handleGameInit(Game* game, uint32_t maxSize) void handleGameInit(Game *game, uint32_t maxSize) {
{
int idx = 0; int idx = 0;
// Read version number // Read version number
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++) {
{
game->version[i] = readByte(data, idx, maxSize, 0); game->version[i] = readByte(data, idx, maxSize, 0);
} }
// Read entire game info header // Read entire game info header
for (int i = 0; i < GAME_INFO_HEADER_SIZE; i++) for (int i = 0; i < GAME_INFO_HEADER_SIZE; i++) {
{
game->settings.header[i] = readWord(data, idx, maxSize, 0); game->settings.header[i] = readWord(data, idx, maxSize, 0);
} }
@ -75,18 +67,15 @@ namespace Slippi
// Read UCF toggle bytes // Read UCF toggle bytes
bool shouldRead = game->version[0] >= 1; bool shouldRead = game->version[0] >= 1;
for (int i = 0; i < UCF_TOGGLE_SIZE; i++) for (int i = 0; i < UCF_TOGGLE_SIZE; i++) {
{
uint32_t value = shouldRead ? readWord(data, idx, maxSize, 0) : 0; uint32_t value = shouldRead ? readWord(data, idx, maxSize, 0) : 0;
game->settings.ucfToggles[i] = value; game->settings.ucfToggles[i] = value;
} }
// Read nametag for each player // Read nametag for each player
std::array<std::array<uint16_t, NAMETAG_SIZE>, 4> playerNametags; std::array<std::array<uint16_t, NAMETAG_SIZE>, 4> playerNametags;
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++) {
{ for (int j = 0; j < NAMETAG_SIZE; j++) {
for (int j = 0; j < NAMETAG_SIZE; j++)
{
playerNametags[i][j] = readHalf(data, idx, maxSize, 0); playerNametags[i][j] = readHalf(data, idx, maxSize, 0);
} }
} }
@ -97,19 +86,40 @@ namespace Slippi
// Read isFrozenPS byte // Read isFrozenPS byte
game->settings.isFrozenPS = readByte(data, idx, maxSize, 0); game->settings.isFrozenPS = readByte(data, idx, maxSize, 0);
// Read minorScene byte
game->settings.minorScene = readByte(data, idx, maxSize, 0);
// Read majorScene byte
game->settings.majorScene = readByte(data, idx, maxSize, 0);
// Read display name for each player
std::array<std::array<uint8_t, DISPLAY_NAME_SIZE>, 4> playerDisplayNames;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < DISPLAY_NAME_SIZE; j++) {
playerDisplayNames[i][j] = readByte(data, idx, maxSize, 0);
}
}
// Read connectCodes
std::array<std::array<uint8_t, CONNECT_CODE_SIZE>, 4> playerConnectCodes;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < CONNECT_CODE_SIZE; j++) {
playerConnectCodes[i][j] = readByte(data, idx, maxSize, 0);
}
}
// Pull header data into struct // Pull header data into struct
int player1Pos = 24; // This is the index of the first players character info int player1Pos = 24; // This is the index of the first players character info
std::array<uint32_t, Slippi::GAME_INFO_HEADER_SIZE> gameInfoHeader = game->settings.header; std::array<uint32_t, Slippi::GAME_INFO_HEADER_SIZE> gameInfoHeader =
for (int i = 0; i < 4; i++) game->settings.header;
{ for (int i = 0; i < 4; i++) {
// this is the position in the array that this player's character info is // this is the position in the array that this player's character info is
// stored // stored
int pos = player1Pos + (9 * i); int pos = player1Pos + (9 * i);
uint32_t playerInfo = gameInfoHeader[pos]; uint32_t playerInfo = gameInfoHeader[pos];
uint8_t playerType = (playerInfo & 0x00FF0000) >> 16; uint8_t playerType = (playerInfo & 0x00FF0000) >> 16;
if (playerType == 0x3) if (playerType == 0x3) {
{
// Player type 3 is an empty slot // Player type 3 is an empty slot
continue; continue;
} }
@ -122,6 +132,8 @@ namespace Slippi
p.playerType = playerType; p.playerType = playerType;
p.characterColor = playerInfo & 0xFF; p.characterColor = playerInfo & 0xFF;
p.nametag = playerNametags[i]; p.nametag = playerNametags[i];
p.displayName = playerDisplayNames[i];
p.connectCode = playerConnectCodes[i];
// Add player settings to result // Add player settings to result
game->settings.players[i] = p; game->settings.players[i] = p;
@ -131,33 +143,29 @@ namespace Slippi
auto majorVersion = game->version[0]; auto majorVersion = game->version[0];
auto minorVersion = game->version[1]; auto minorVersion = game->version[1];
if (majorVersion > 3 || (majorVersion == 3 && minorVersion >= 1)) if (majorVersion > 3 || (majorVersion == 3 && minorVersion >= 1)) {
{
// After version 3.1.0 we added a dynamic gecko loading process. These // After version 3.1.0 we added a dynamic gecko loading process. These
// are needed before starting the game. areSettingsLoaded will be set // are needed before starting the game. areSettingsLoaded will be set
// to true when they are received // to true when they are received
game->areSettingsLoaded = false; game->areSettingsLoaded = false;
} } else if (majorVersion > 1 || (majorVersion == 1 && minorVersion >= 6)) {
else if (majorVersion > 1 || (majorVersion == 1 && minorVersion >= 6))
{
// Indicate settings loaded immediately if after version 1.6.0 // Indicate settings loaded immediately if after version 1.6.0
// Sheik game info was added in this version and so we no longer // Sheik game info was added in this version and so we no longer
// need to wait // need to wait
game->areSettingsLoaded = true; game->areSettingsLoaded = true;
} }
} }
void handleGeckoList(Game* game, uint32_t maxSize) void handleGeckoList(Game *game, uint32_t maxSize) {
{
game->settings.geckoCodes.clear(); game->settings.geckoCodes.clear();
game->settings.geckoCodes.insert(game->settings.geckoCodes.end(), data, data + maxSize); game->settings.geckoCodes.insert(game->settings.geckoCodes.end(), data,
data + maxSize);
// File is good to load // File is good to load
game->areSettingsLoaded = true; game->areSettingsLoaded = true;
} }
void handleFrameStart(Game* game, uint32_t maxSize) void handleFrameStart(Game *game, uint32_t maxSize) {
{
int idx = 0; int idx = 0;
// Check frame count // Check frame count
@ -165,7 +173,7 @@ namespace Slippi
game->frameCount = frameCount; game->frameCount = frameCount;
auto frameUniquePtr = std::make_unique<FrameData>(); auto frameUniquePtr = std::make_unique<FrameData>();
FrameData* frame = frameUniquePtr.get(); FrameData *frame = frameUniquePtr.get();
frame->frame = frameCount; frame->frame = frameCount;
frame->randomSeedExists = true; frame->randomSeedExists = true;
@ -176,10 +184,9 @@ namespace Slippi
frame->numSinceStart = game->frames.size(); frame->numSinceStart = game->frames.size();
game->frames.push_back(std::move(frameUniquePtr)); game->frames.push_back(std::move(frameUniquePtr));
game->framesByIndex[frameCount] = frame; game->framesByIndex[frameCount] = frame;
} }
void handlePreFrameUpdate(Game* game, uint32_t maxSize) void handlePreFrameUpdate(Game *game, uint32_t maxSize) {
{
int idx = 0; int idx = 0;
// Check frame count // Check frame count
@ -187,11 +194,10 @@ namespace Slippi
game->frameCount = frameCount; game->frameCount = frameCount;
auto frameUniquePtr = std::make_unique<FrameData>(); auto frameUniquePtr = std::make_unique<FrameData>();
FrameData* frame = frameUniquePtr.get(); FrameData *frame = frameUniquePtr.get();
bool isNewFrame = true; bool isNewFrame = true;
if (game->framesByIndex.count(frameCount)) if (game->framesByIndex.count(frameCount)) {
{
// If this frame already exists, get the current frame // If this frame already exists, get the current frame
frame = game->frames.back().get(); frame = game->frames.back().get();
isNewFrame = false; isNewFrame = false;
@ -226,40 +232,36 @@ namespace Slippi
p.lTrigger = readFloat(data, idx, maxSize, 0); p.lTrigger = readFloat(data, idx, maxSize, 0);
p.rTrigger = readFloat(data, idx, maxSize, 0); p.rTrigger = readFloat(data, idx, maxSize, 0);
if (asmEvents[EVENT_PRE_FRAME_UPDATE] >= 59) if (asmEvents[EVENT_PRE_FRAME_UPDATE] >= 59) {
{
p.joystickXRaw = readByte(data, idx, maxSize, 0); p.joystickXRaw = readByte(data, idx, maxSize, 0);
} }
uint32_t noPercent = 0xFFFFFFFF; uint32_t noPercent = 0xFFFFFFFF;
p.percent = readFloat(data, idx, maxSize, *(float*)(&noPercent)); p.percent = readFloat(data, idx, maxSize, *(float *)(&noPercent));
// Add player data to frame // Add player data to frame
std::unordered_map<uint8_t, PlayerFrameData>* target; std::unordered_map<uint8_t, PlayerFrameData> *target;
target = isFollower ? &frame->followers : &frame->players; target = isFollower ? &frame->followers : &frame->players;
// Set the player data for the player or follower // Set the player data for the player or follower
target->operator[](playerSlot) = p; target->operator[](playerSlot) = p;
// Add frame to game // Add frame to game
if (isNewFrame) if (isNewFrame) {
{
frame->numSinceStart = game->frames.size(); frame->numSinceStart = game->frames.size();
game->frames.push_back(std::move(frameUniquePtr)); game->frames.push_back(std::move(frameUniquePtr));
game->framesByIndex[frameCount] = frame; game->framesByIndex[frameCount] = frame;
} }
} }
void handlePostFrameUpdate(Game* game, uint32_t maxSize) void handlePostFrameUpdate(Game *game, uint32_t maxSize) {
{
int idx = 0; int idx = 0;
// Check frame count // Check frame count
int32_t frameCount = readWord(data, idx, maxSize, 0); int32_t frameCount = readWord(data, idx, maxSize, 0);
FrameData* frame; FrameData *frame;
if (game->framesByIndex.count(frameCount)) if (game->framesByIndex.count(frameCount)) {
{
// If this frame already exists, get the current frame // If this frame already exists, get the current frame
frame = game->frames.back().get(); frame = game->frames.back().get();
} }
@ -272,62 +274,60 @@ namespace Slippi
uint8_t playerSlot = readByte(data, idx, maxSize, 0); uint8_t playerSlot = readByte(data, idx, maxSize, 0);
uint8_t isFollower = readByte(data, idx, maxSize, 0); uint8_t isFollower = readByte(data, idx, maxSize, 0);
PlayerFrameData* p = isFollower ? &frame->followers[playerSlot] : &frame->players[playerSlot]; PlayerFrameData *p =
isFollower ? &frame->followers[playerSlot] : &frame->players[playerSlot];
p->internalCharacterId = readByte(data, idx, maxSize, 0); p->internalCharacterId = readByte(data, idx, maxSize, 0);
// Check if a player started as sheik and update // Check if a player started as sheik and update
if (frameCount == GAME_FIRST_FRAME && p->internalCharacterId == GAME_SHEIK_INTERNAL_ID) if (frameCount == GAME_FIRST_FRAME &&
{ p->internalCharacterId == GAME_SHEIK_INTERNAL_ID) {
game->settings.players[playerSlot].characterId = GAME_SHEIK_EXTERNAL_ID; game->settings.players[playerSlot].characterId = GAME_SHEIK_EXTERNAL_ID;
} }
// Set settings loaded if this is the last character // Set settings loaded if this is the last character
if (frameCount == GAME_FIRST_FRAME) if (frameCount == GAME_FIRST_FRAME) {
{
uint8_t lastPlayerIndex = 0; uint8_t lastPlayerIndex = 0;
for (auto it = frame->players.begin(); it != frame->players.end(); ++it) for (auto it = frame->players.begin(); it != frame->players.end(); ++it) {
{ if (it->first <= lastPlayerIndex) {
if (it->first <= lastPlayerIndex)
{
continue; continue;
} }
lastPlayerIndex = it->first; lastPlayerIndex = it->first;
} }
}
}
void handleFrameEnd(Game* game, uint32_t maxSize) { if (playerSlot >= lastPlayerIndex) {
game->areSettingsLoaded = true;
}
}
}
void handleFrameEnd(Game *game, uint32_t maxSize) {
int idx = 0; int idx = 0;
int32_t frameCount = readWord(data, idx, maxSize, 0); int32_t frameCount = readWord(data, idx, maxSize, 0);
int32_t lastFinalizedFrame = readWord(data, idx, maxSize, frameCount); int32_t lastFinalizedFrame = readWord(data, idx, maxSize, frameCount);
game->lastFinalizedFrame = lastFinalizedFrame; game->lastFinalizedFrame = lastFinalizedFrame;
} }
void handleGameEnd(Game* game, uint32_t maxSize) void handleGameEnd(Game *game, uint32_t maxSize) {
{
int idx = 0; int idx = 0;
game->winCondition = readByte(data, idx, maxSize, 0); game->winCondition = readByte(data, idx, maxSize, 0);
} }
// This function gets the position where the raw data starts // This function gets the position where the raw data starts
int getRawDataPosition(std::ifstream* f) int getRawDataPosition(std::ifstream *f) {
{
char buffer[2]; char buffer[2];
f->seekg(0, std::ios::beg); f->seekg(0, std::ios::beg);
f->read(buffer, 2); f->read(buffer, 2);
if (buffer[0] == 0x36) if (buffer[0] == 0x36) {
{
return 0; return 0;
} }
if (buffer[0] != '{') if (buffer[0] != '{') {
{
// TODO: Do something here to cause an error // TODO: Do something here to cause an error
return 0; return 0;
} }
@ -336,12 +336,10 @@ namespace Slippi
// TODO: For now since raw is the first element the data will always start at // TODO: For now since raw is the first element the data will always start at
// 15 // 15
return 15; return 15;
} }
uint32_t getRawDataLength(std::ifstream* f, int position, int fileSize) uint32_t getRawDataLength(std::ifstream *f, int position, int fileSize) {
{ if (position == 0) {
if (position == 0)
{
return fileSize; return fileSize;
} }
@ -349,28 +347,28 @@ namespace Slippi
f->seekg(position - 4, std::ios::beg); f->seekg(position - 4, std::ios::beg);
f->read(buffer, 4); f->read(buffer, 4);
uint8_t* byteBuf = (uint8_t*)&buffer[0]; uint8_t *byteBuf = (uint8_t *)&buffer[0];
uint32_t length = byteBuf[0] << 24 | byteBuf[1] << 16 | byteBuf[2] << 8 | byteBuf[3]; uint32_t length =
byteBuf[0] << 24 | byteBuf[1] << 16 | byteBuf[2] << 8 | byteBuf[3];
return length; return length;
} }
std::unordered_map<uint8_t, uint32_t> getMessageSizes(std::ifstream* f, int position) std::unordered_map<uint8_t, uint32_t> getMessageSizes(std::ifstream *f,
{ int position) {
char buffer[2]; char buffer[2];
f->seekg(position, std::ios::beg); f->seekg(position, std::ios::beg);
f->read(buffer, 2); f->read(buffer, 2);
if (buffer[0] != EVENT_PAYLOAD_SIZES) if (buffer[0] != EVENT_PAYLOAD_SIZES) {
{
return {}; return {};
} }
int payloadLength = buffer[1]; int payloadLength = buffer[1];
std::unordered_map<uint8_t, uint32_t> messageSizes = { {EVENT_PAYLOAD_SIZES, payloadLength} }; std::unordered_map<uint8_t, uint32_t> messageSizes = {
{EVENT_PAYLOAD_SIZES, payloadLength}};
std::vector<char> messageSizesBuffer(payloadLength - 1); std::vector<char> messageSizesBuffer(payloadLength - 1);
f->read(&messageSizesBuffer[0], payloadLength - 1); f->read(&messageSizesBuffer[0], payloadLength - 1);
for (int i = 0; i < payloadLength - 1; i += 3) for (int i = 0; i < payloadLength - 1; i += 3) {
{
uint8_t command = messageSizesBuffer[i]; uint8_t command = messageSizesBuffer[i];
// Extract the bytes in u8s. Without this the chars don't or together well // Extract the bytes in u8s. Without this the chars don't or together well
@ -382,12 +380,10 @@ namespace Slippi
} }
return messageSizes; return messageSizes;
} }
void SlippiGame::processData() void SlippiGame::processData() {
{ if (isProcessingComplete) {
if (isProcessingComplete)
{
// If we have finished processing this file, return // If we have finished processing this file, return
return; return;
} }
@ -395,20 +391,17 @@ namespace Slippi
// This function will process as much data as possible // This function will process as much data as possible
int startPos = (int)file->tellg(); int startPos = (int)file->tellg();
file->seekg(startPos); file->seekg(startPos);
if (startPos == 0) if (startPos == 0) {
{
file->seekg(0, std::ios::end); file->seekg(0, std::ios::end);
int len = (int)file->tellg(); int len = (int)file->tellg();
if (len < 2) if (len < 2) {
{
// If we can't read message sizes payload size yet, return // If we can't read message sizes payload size yet, return
return; return;
} }
int rawDataPos = getRawDataPosition(file.get()); int rawDataPos = getRawDataPosition(file.get());
int rawDataLen = len - rawDataPos; int rawDataLen = len - rawDataPos;
if (rawDataLen < 2) if (rawDataLen < 2) {
{
// If we don't have enough raw data yet to read the replay file, return // If we don't have enough raw data yet to read the replay file, return
// Reset to begining so that the startPos condition will be hit again // Reset to begining so that the startPos condition will be hit again
file->seekg(0); file->seekg(0);
@ -422,8 +415,7 @@ namespace Slippi
file->read(buffer, 2); file->read(buffer, 2);
file->seekg(startPos); file->seekg(startPos);
auto messageSizesSize = (int)buffer[1]; auto messageSizesSize = (int)buffer[1];
if (rawDataLen < messageSizesSize) if (rawDataLen < messageSizesSize) {
{
// If we haven't received the full payload sizes message, return // If we haven't received the full payload sizes message, return
// Reset to begining so that the startPos condition will be hit again // Reset to begining so that the startPos condition will be hit again
file->seekg(0); file->seekg(0);
@ -441,8 +433,7 @@ namespace Slippi
// log << "Size to read: " << sizeToRead << "\n"; // log << "Size to read: " << sizeToRead << "\n";
// log << "Start Pos: " << startPos << "\n"; // log << "Start Pos: " << startPos << "\n";
// log << "End Pos: " << endPos << "\n\n"; // log << "End Pos: " << endPos << "\n\n";
if (sizeToRead <= 0) if (sizeToRead <= 0) {
{
return; return;
} }
@ -450,8 +441,7 @@ namespace Slippi
file->read(&newData[0], sizeToRead); file->read(&newData[0], sizeToRead);
int newDataPos = 0; int newDataPos = 0;
while (newDataPos < sizeToRead) while (newDataPos < sizeToRead) {
{
auto command = newData[newDataPos]; auto command = newData[newDataPos];
auto payloadSize = asmEvents[command]; auto payloadSize = asmEvents[command];
@ -460,35 +450,32 @@ namespace Slippi
// log << "Command: " << buff << " | Payload Size: " << payloadSize << "\n"; // log << "Command: " << buff << " | Payload Size: " << payloadSize << "\n";
auto remainingLen = sizeToRead - newDataPos; auto remainingLen = sizeToRead - newDataPos;
if (remainingLen < ((int)payloadSize + 1)) if (remainingLen < ((int)payloadSize + 1)) {
{
// Here we don't have enough data to read the whole payload // Here we don't have enough data to read the whole payload
// Will be processed after getting more data (hopefully) // Will be processed after getting more data (hopefully)
file->seekg(-remainingLen, std::ios::cur); file->seekg(-remainingLen, std::ios::cur);
return; return;
} }
data = (uint8_t*)&newData[newDataPos + 1]; data = (uint8_t *)&newData[newDataPos + 1];
uint8_t isSplitComplete = false; uint8_t isSplitComplete = false;
uint32_t outerPayloadSize = payloadSize; uint32_t outerPayloadSize = payloadSize;
// Handle a split message, combining in until we possess the entire message // Handle a split message, combining in until we possess the entire message
if (command == EVENT_SPLIT_MESSAGE) if (command == EVENT_SPLIT_MESSAGE) {
{ if (shouldResetSplitMessageBuf) {
if (shouldResetSplitMessageBuf)
{
splitMessageBuf.clear(); splitMessageBuf.clear();
shouldResetSplitMessageBuf = false; shouldResetSplitMessageBuf = false;
} }
int _ = 0; int _ = 0;
uint16_t blockSize = readHalf(&data[SPLIT_MESSAGE_INTERNAL_DATA_LEN], _, payloadSize, 0); uint16_t blockSize =
readHalf(&data[SPLIT_MESSAGE_INTERNAL_DATA_LEN], _, payloadSize, 0);
splitMessageBuf.insert(splitMessageBuf.end(), data, data + blockSize); splitMessageBuf.insert(splitMessageBuf.end(), data, data + blockSize);
isSplitComplete = data[SPLIT_MESSAGE_INTERNAL_DATA_LEN + 3]; isSplitComplete = data[SPLIT_MESSAGE_INTERNAL_DATA_LEN + 3];
if (isSplitComplete) if (isSplitComplete) {
{
// Transform this message into a different message // Transform this message into a different message
command = data[SPLIT_MESSAGE_INTERNAL_DATA_LEN + 2]; command = data[SPLIT_MESSAGE_INTERNAL_DATA_LEN + 2];
data = &splitMessageBuf[0]; data = &splitMessageBuf[0];
@ -497,8 +484,7 @@ namespace Slippi
} }
} }
switch (command) switch (command) {
{
case EVENT_GAME_INIT: case EVENT_GAME_INIT:
handleGameInit(game.get(), payloadSize); handleGameInit(game.get(), payloadSize);
break; break;
@ -514,6 +500,9 @@ namespace Slippi
case EVENT_POST_FRAME_UPDATE: case EVENT_POST_FRAME_UPDATE:
handlePostFrameUpdate(game.get(), payloadSize); handlePostFrameUpdate(game.get(), payloadSize);
break; break;
case EVENT_FRAME_END:
handleFrameEnd(game.get(), payloadSize);
break;
case EVENT_GAME_END: case EVENT_GAME_END:
handleGameEnd(game.get(), payloadSize); handleGameEnd(game.get(), payloadSize);
isProcessingComplete = true; isProcessingComplete = true;
@ -532,25 +521,26 @@ namespace Slippi
payloadSize = isSplitComplete ? outerPayloadSize : payloadSize; payloadSize = isSplitComplete ? outerPayloadSize : payloadSize;
newDataPos += payloadSize + 1; newDataPos += payloadSize + 1;
} }
} }
std::unique_ptr<SlippiGame> SlippiGame::FromFile(std::string path) std::unique_ptr<SlippiGame> SlippiGame::FromFile(std::string path) {
{
auto result = std::make_unique<SlippiGame>(); auto result = std::make_unique<SlippiGame>();
result->game = std::make_unique<Game>(); result->game = std::make_unique<Game>();
result->path = path; result->path = path;
#ifdef _WIN32 #ifdef _WIN32
// On Windows, we need to convert paths to std::wstring to deal with UTF-8 // On Windows, we need to convert paths to std::wstring to deal with UTF-8
std::wstring convertedPath = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(path); std::wstring convertedPath =
result->file = std::make_unique<std::ifstream>(convertedPath, std::ios::in | std::ios::binary); std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(path);
result->file = std::make_unique<std::ifstream>(
convertedPath, std::ios::in | std::ios::binary);
#else #else
result->file = std::make_unique<std::ifstream>(path, std::ios::in | std::ios::binary); result->file =
std::make_unique<std::ifstream>(path, std::ios::in | std::ios::binary);
#endif #endif
// result->log.open("log.txt"); // result->log.open("log.txt");
if (!result->file->is_open()) if (!result->file->is_open()) {
{
return nullptr; return nullptr;
} }
@ -566,74 +556,61 @@ namespace Slippi
// SlippiGame* result = processFile((uint8_t*)&rawData[0], rawDataLength); // SlippiGame* result = processFile((uint8_t*)&rawData[0], rawDataLength);
return std::move(result); return std::move(result);
} }
bool SlippiGame::IsProcessingComplete() bool SlippiGame::IsProcessingComplete() { return isProcessingComplete; }
{
return isProcessingComplete;
}
bool SlippiGame::AreSettingsLoaded() bool SlippiGame::AreSettingsLoaded() {
{
processData(); processData();
return game->areSettingsLoaded; return game->areSettingsLoaded;
} }
bool SlippiGame::DoesFrameExist(int32_t frame) bool SlippiGame::DoesFrameExist(int32_t frame) {
{
processData(); processData();
return (bool)game->framesByIndex.count(frame); return static_cast<bool>(game->framesByIndex.count(frame));
} }
std::array<uint8_t, 4> SlippiGame::GetVersion() std::array<uint8_t, 4> SlippiGame::GetVersion() { return game->version; }
{
return game->version;
}
std::string SlippiGame::GetVersionString() std::string SlippiGame::GetVersionString() {
{
char version[30]; char version[30];
sprintf(version, "%d.%d.%d", game->version[0], game->version[1], game->version[2]); sprintf(version, "%d.%d.%d", game->version[0], game->version[1],
game->version[2]);
return std::string(version); return std::string(version);
} }
FrameData* SlippiGame::GetFrame(int32_t frame) { FrameData *SlippiGame::GetFrame(int32_t frame) {
// Get the frame we want // Get the frame we want
return game->framesByIndex.at(frame); return game->framesByIndex.at(frame);
} }
FrameData* SlippiGame::GetFrameAt(uint32_t pos) FrameData *SlippiGame::GetFrameAt(uint32_t pos) {
{ if (pos >= game->frames.size()) {
if (pos >= game->frames.size())
{
return nullptr; return nullptr;
} }
// Get the frame we want // Get the frame we want
return game->frames[pos].get(); return game->frames[pos].get();
} }
int32_t SlippiGame::GetLastFinalizedFrame() { int32_t SlippiGame::GetLastFinalizedFrame() {
processData(); processData();
return game->lastFinalizedFrame; return game->lastFinalizedFrame;
} }
int32_t SlippiGame::GetLatestIndex() { int32_t SlippiGame::GetLatestIndex() {
processData(); processData();
return game->frameCount; return game->frameCount;
} }
GameSettings* SlippiGame::GetSettings() GameSettings *SlippiGame::GetSettings() {
{
processData(); processData();
return &game->settings; return &game->settings;
} }
bool SlippiGame::DoesPlayerExist(int8_t port) { bool SlippiGame::DoesPlayerExist(int8_t port) {
return game->settings.players.find(port) != game->settings.players.end(); return game->settings.players.find(port) != game->settings.players.end();
} }
uint8_t SlippiGame::GetGameEndMethod() { uint8_t SlippiGame::GetGameEndMethod() { return game->winCondition; }
return game->winCondition;
}
} // namespace Slippi } // namespace Slippi

View file

@ -9,32 +9,33 @@
#include <vector> #include <vector>
namespace Slippi { namespace Slippi {
const uint8_t EVENT_SPLIT_MESSAGE = 0x10; const uint8_t EVENT_SPLIT_MESSAGE = 0x10;
const uint8_t EVENT_PAYLOAD_SIZES = 0x35; const uint8_t EVENT_PAYLOAD_SIZES = 0x35;
const uint8_t EVENT_GAME_INIT = 0x36; const uint8_t EVENT_GAME_INIT = 0x36;
const uint8_t EVENT_PRE_FRAME_UPDATE = 0x37; const uint8_t EVENT_PRE_FRAME_UPDATE = 0x37;
const uint8_t EVENT_POST_FRAME_UPDATE = 0x38; const uint8_t EVENT_POST_FRAME_UPDATE = 0x38;
const uint8_t EVENT_GAME_END = 0x39; const uint8_t EVENT_GAME_END = 0x39;
const uint8_t EVENT_FRAME_START = 0x3A; const uint8_t EVENT_FRAME_START = 0x3A;
const uint8_t EVENT_FRAME_END = 0x3C; const uint8_t EVENT_FRAME_END = 0x3C;
const uint8_t EVENT_GECKO_LIST = 0x3D; const uint8_t EVENT_GECKO_LIST = 0x3D;
const uint8_t GAME_INFO_HEADER_SIZE = 78; const uint8_t GAME_INFO_HEADER_SIZE = 78;
const uint8_t UCF_TOGGLE_SIZE = 8; const uint8_t UCF_TOGGLE_SIZE = 8;
const uint8_t NAMETAG_SIZE = 8; const uint8_t NAMETAG_SIZE = 8;
const uint8_t DISPLAY_NAME_SIZE = 31; const uint8_t DISPLAY_NAME_SIZE = 31;
const uint8_t CONNECT_CODE_SIZE = 10; const uint8_t CONNECT_CODE_SIZE = 10;
const int32_t GAME_FIRST_FRAME = -123; const int32_t GAME_FIRST_FRAME = -123;
const int32_t PLAYBACK_FIRST_SAVE = -122; const int32_t PLAYBACK_FIRST_SAVE = -122;
const uint8_t GAME_SHEIK_INTERNAL_ID = 0x7; const uint8_t GAME_SHEIK_INTERNAL_ID = 0x7;
const uint8_t GAME_SHEIK_EXTERNAL_ID = 0x13; const uint8_t GAME_SHEIK_EXTERNAL_ID = 0x13;
const uint32_t SPLIT_MESSAGE_INTERNAL_DATA_LEN = 512; const uint32_t SPLIT_MESSAGE_INTERNAL_DATA_LEN = 512;
static uint8_t* data; static uint8_t *data;
typedef struct { typedef struct {
// Every player update has its own rng seed because it might change in between players // Every player update has its own rng seed because it might change in between
// players
uint32_t randomSeed; uint32_t randomSeed;
uint8_t internalCharacterId; uint8_t internalCharacterId;
@ -49,23 +50,25 @@ namespace Slippi {
uint8_t comboCount; uint8_t comboCount;
uint8_t lastHitBy; uint8_t lastHitBy;
//Controller information // Controller information
float joystickX; float joystickX;
float joystickY; float joystickY;
float cstickX; float cstickX;
float cstickY; float cstickY;
float trigger; float trigger;
uint32_t buttons; //This will include multiple "buttons" pressed on special buttons. For example I think pressing z sets 3 bits uint32_t buttons; // This will include multiple "buttons" pressed on special
// buttons. For example I think pressing z sets 3 bits
//This is extra controller information // This is extra controller information
uint16_t physicalButtons; //A better representation of what a player is actually pressing uint16_t physicalButtons; // A better representation of what a player is
// actually pressing
float lTrigger; float lTrigger;
float rTrigger; float rTrigger;
uint8_t joystickXRaw; uint8_t joystickXRaw;
} PlayerFrameData; } PlayerFrameData;
typedef struct FrameData { typedef struct FrameData {
int32_t frame; int32_t frame;
uint32_t numSinceStart; uint32_t numSinceStart;
bool randomSeedExists = false; bool randomSeedExists = false;
@ -73,10 +76,10 @@ namespace Slippi {
bool inputsFullyFetched = false; bool inputsFullyFetched = false;
std::unordered_map<uint8_t, PlayerFrameData> players; std::unordered_map<uint8_t, PlayerFrameData> players;
std::unordered_map<uint8_t, PlayerFrameData> followers; std::unordered_map<uint8_t, PlayerFrameData> followers;
} FrameData; } FrameData;
typedef struct { typedef struct {
//Static data // Static data
uint8_t characterId; uint8_t characterId;
uint8_t characterColor; uint8_t characterColor;
uint8_t playerType; uint8_t playerType;
@ -84,10 +87,10 @@ namespace Slippi {
std::array<uint16_t, NAMETAG_SIZE> nametag; std::array<uint16_t, NAMETAG_SIZE> nametag;
std::array<uint8_t, DISPLAY_NAME_SIZE> displayName; std::array<uint8_t, DISPLAY_NAME_SIZE> displayName;
std::array<uint8_t, CONNECT_CODE_SIZE> connectCode; std::array<uint8_t, CONNECT_CODE_SIZE> connectCode;
} PlayerSettings; } PlayerSettings;
typedef struct { typedef struct {
uint16_t stage; //Stage ID uint16_t stage; // Stage ID
uint32_t randomSeed; uint32_t randomSeed;
std::array<uint32_t, GAME_INFO_HEADER_SIZE> header; std::array<uint32_t, GAME_INFO_HEADER_SIZE> header;
std::array<uint32_t, UCF_TOGGLE_SIZE> ucfToggles; std::array<uint32_t, UCF_TOGGLE_SIZE> ucfToggles;
@ -97,11 +100,11 @@ namespace Slippi {
uint8_t minorScene; uint8_t minorScene;
uint8_t majorScene; uint8_t majorScene;
std::vector<uint8_t> geckoCodes; std::vector<uint8_t> geckoCodes;
} GameSettings; } GameSettings;
typedef struct Game { typedef struct Game {
std::array<uint8_t, 4> version; std::array<uint8_t, 4> version;
std::unordered_map<int32_t, FrameData*> framesByIndex; std::unordered_map<int32_t, FrameData *> framesByIndex;
std::vector<std::unique_ptr<FrameData>> frames; std::vector<std::unique_ptr<FrameData>> frames;
GameSettings settings; GameSettings settings;
bool areSettingsLoaded = false; bool areSettingsLoaded = false;
@ -109,37 +112,36 @@ namespace Slippi {
int32_t frameCount; // Current/last frame count int32_t frameCount; // Current/last frame count
int32_t lastFinalizedFrame = -124; int32_t lastFinalizedFrame = -124;
//From OnGameEnd event // From OnGameEnd event
uint8_t winCondition; uint8_t winCondition;
} Game; } Game;
// TODO: This shouldn't be static. Doesn't matter too much atm because we always // TODO: This shouldn't be static. Doesn't matter too much atm because we always
// TODO: only read one file at a time // TODO: only read one file at a time
static std::unordered_map<uint8_t, uint32_t> asmEvents = { static std::unordered_map<uint8_t, uint32_t> asmEvents = {
{ EVENT_GAME_INIT, 320 }, {EVENT_GAME_INIT, 320},
{ EVENT_PRE_FRAME_UPDATE, 58 }, {EVENT_PRE_FRAME_UPDATE, 58},
{ EVENT_POST_FRAME_UPDATE, 33 }, {EVENT_POST_FRAME_UPDATE, 33},
{ EVENT_GAME_END, 1 }, {EVENT_GAME_END, 1},
{ EVENT_FRAME_START, 8 } {EVENT_FRAME_START, 8}};
};
class SlippiGame class SlippiGame {
{ public:
public:
static std::unique_ptr<SlippiGame> FromFile(std::string path); static std::unique_ptr<SlippiGame> FromFile(std::string path);
bool AreSettingsLoaded(); bool AreSettingsLoaded();
bool DoesFrameExist(int32_t frame); bool DoesFrameExist(int32_t frame);
std::array<uint8_t, 4> GetVersion(); std::array<uint8_t, 4> GetVersion();
std::string GetVersionString(); std::string GetVersionString();
FrameData* GetFrame(int32_t frame); FrameData *GetFrame(int32_t frame);
FrameData* GetFrameAt(uint32_t pos); FrameData *GetFrameAt(uint32_t pos);
int32_t GetLastFinalizedFrame(); int32_t GetLastFinalizedFrame();
int32_t GetLatestIndex(); int32_t GetLatestIndex();
GameSettings* GetSettings(); GameSettings *GetSettings();
uint8_t GetGameEndMethod(); uint8_t GetGameEndMethod();
bool DoesPlayerExist(int8_t port); bool DoesPlayerExist(int8_t port);
bool IsProcessingComplete(); bool IsProcessingComplete();
private:
private:
std::unique_ptr<Game> game; std::unique_ptr<Game> game;
std::unique_ptr<std::ifstream> file; std::unique_ptr<std::ifstream> file;
std::vector<uint8_t> rawData; std::vector<uint8_t> rawData;
@ -150,5 +152,5 @@ namespace Slippi {
bool isProcessingComplete = false; bool isProcessingComplete = false;
void processData(); void processData();
}; };
} } // namespace Slippi