foxygit / fake-08-xbox360 Log in
commit 5646c31ad0f5e9c73c207b68e4f7c6c244dd00d6
Author:     Jon Bell <j.to.the.bell@gmail.com>
AuthorDate: Fri Aug 5 19:43:11 2022 -0600
Commit:     Jon Bell <j.to.the.bell@gmail.com>
CommitDate: Fri Aug 5 19:43:11 2022 -0600

    WIP- super basic lua state saving POC working
---
 platform/SDL2Desktop/Makefile            |  2 +-
 platform/SDL2Desktop/source/SDL2Host.cpp |  4 ++
 platform/libretro/fake08_libretro.info   | 18 +++++++++
 platform/libretro/libretro.cpp           | 44 +++++++++++++++++++--
 source/Audio.cpp                         |  2 +-
 source/Audio.h                           |  4 +-
 source/PicoRam.h                         | 22 ++++++++++-
 source/host.h                            |  3 ++
 source/hostCommonFunctions.cpp           | 30 +++++++++++++++
 source/p8GlobalLuaFunctions.h            | 65 ++++++++++++++++++++++++++++++++
 source/vm.cpp                            | 65 +++++++++++++++++++++++++++++++-
 source/vm.h                              |  3 ++
 test/audiotests.cpp                      |  2 +-
 13 files changed, 252 insertions(+), 12 deletions(-)

diff --git a/platform/SDL2Desktop/Makefile b/platform/SDL2Desktop/Makefile
index 8c40cec..13892b0 100644
--- a/platform/SDL2Desktop/Makefile
+++ b/platform/SDL2Desktop/Makefile
@@ -16,7 +16,7 @@ INCLUDES	:=	${INCLUDES}
 #---------------------------------------------------------------------------------
 CC = $(CXX)

-CFLAGS	:=	-g -Ofast -Wall -Wno-deprecated -ffunction-sections -std=c++17 \
+CFLAGS	:=	-g -Wall -Wno-deprecated -ffunction-sections -std=c++17 \
 			$(DEFINES)

 CFLAGS	+=	$(INCLUDE) -DVER_STR=\"$(APP_VERSION)\"
diff --git a/platform/SDL2Desktop/source/SDL2Host.cpp b/platform/SDL2Desktop/source/SDL2Host.cpp
index 3fc3b29..473989a 100644
--- a/platform/SDL2Desktop/source/SDL2Host.cpp
+++ b/platform/SDL2Desktop/source/SDL2Host.cpp
@@ -125,6 +125,10 @@ InputState_t Host::scanInput(){
                     case SDLK_x:     currKDown |= P8_KEY_O; break;
                     case SDLK_c:     currKDown |= P8_KEY_X; break;
                     case SDLK_r:     stretchKeyPressed = true; break;
+                    case SDLK_F2:    currKDown |= P8_KEY_7; break;
+
+                    //case SDLK_F2:    currKBKey = "F2"; currKBDown = true; break;
+                    //case SDLK_F4:    currKBKey = "F4"; currKBDown = true; break;
                 }
                 break;

diff --git a/platform/libretro/fake08_libretro.info b/platform/libretro/fake08_libretro.info
new file mode 100644
index 0000000..f25b569
--- /dev/null
+++ b/platform/libretro/fake08_libretro.info
@@ -0,0 +1,18 @@
+# Software Information
+display_name = "Pico-8 (FAKE-08)"
+authors = "jtothebell"
+corename = "FAKE-08"
+categories = "Emulator"
+license = "MIT"
+permissions = ""
+display_version = "v0.0.2.18"
+
+# Hardware Information
+manufacturer = "Lexaloffle"
+systemname = "Pico-8"
+systemid = "pico8"
+
+# Libretro Features
+supports_no_game = "true"
+savestate = "true"
+savestate_features = "serialized"
diff --git a/platform/libretro/libretro.cpp b/platform/libretro/libretro.cpp
index 9dbcdb7..ef40013 100644
--- a/platform/libretro/libretro.cpp
+++ b/platform/libretro/libretro.cpp
@@ -84,6 +84,7 @@ EXPORT void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb;

 EXPORT void retro_init()
 {
+    printf("********** retro init\n");
     //called once. do setup (create host and vm?)
     _host = new Host();

@@ -117,6 +118,7 @@ EXPORT void retro_init()

 EXPORT void retro_deinit()
 {
+    printf("**********r retro deinit\n");
     //delete things created in init
     _vm->CloseCart();
     _host->oneTimeCleanup();
@@ -288,19 +290,54 @@ EXPORT void retro_run()
     frame++;
 }

+
 EXPORT size_t retro_serialize_size()
 {
-    return 0;
+    //lua memory is 2 MB in size
+    //https://www.lexaloffle.com/dl/docs/pico-8_manual.html
+    //section 6.7: Memory
+    printf("********** getting serialize size\n");
+    return sizeof(PicoRam) + sizeof(audioState_t) + 1024*1024*2;
 }

 EXPORT bool retro_serialize(void *data, size_t size)
 {
-    return false;
+    printf("********** retro_serialize\n");
+    const int expectedSize = retro_serialize_size();
+    if (size > expectedSize) {
+        printf("********** size > expected size\n");
+        size = expectedSize;
+    }
+    else if (size < expectedSize) {
+        printf("********** size < expected size\n");
+        return false;
+    }
+
+
+    saveState_t* saveState = (saveState_t*)data;
+
+    memcpy(&saveState->memory, _memory->data, sizeof(PicoRam));
+    memcpy(&saveState->audioState, _audio->getAudioState(), sizeof(audioState_t));
+    std::string luaState = _vm->serializeLuaState();
+    printf("serialized luaState: %s\n", luaState.c_str());
+    memcpy(&saveState->luaStateStr, luaState.c_str(), luaState.length());
+
+
+    return true;
 }

 EXPORT bool retro_unserialize(const void *data, size_t size)
 {
-    return false;
+    printf("********** retro_unserialize\n");
+    saveState_t* saveState = (saveState_t*)data;
+
+    memcpy(_memory->data, &saveState->memory, sizeof(PicoRam));
+    memcpy(_audio->getAudioState(), &saveState->audioState, sizeof(audioState_t));
+    printf("serialized luaState: %s\n",  saveState->luaStateStr);
+    std::string luaStateStr = saveState->luaStateStr;
+    _vm->deserializeLuaState(luaStateStr);
+
+    return true;
 }

 EXPORT void retro_cheat_reset()
@@ -335,6 +372,7 @@ EXPORT unsigned retro_get_region()

 EXPORT void *retro_get_memory_data(unsigned id)
 {
+    //move cart data saving to here?
     return nullptr;
 }

diff --git a/source/Audio.cpp b/source/Audio.cpp
index 3d943fe..45bba99 100644
--- a/source/Audio.cpp
+++ b/source/Audio.cpp
@@ -40,7 +40,7 @@ void Audio::resetAudioState() {
     _audioState._musicChannel.offset = 0.f;
 }

-audioState* Audio::getAudioState() {
+audioState_t* Audio::getAudioState() {
     return &_audioState;
 }

diff --git a/source/Audio.h b/source/Audio.h
index cd22961..8ba45cf 100644
--- a/source/Audio.h
+++ b/source/Audio.h
@@ -88,7 +88,7 @@ enum

 class Audio {
     PicoRam* _memory;
-    audioState _audioState;
+    audioState_t _audioState;

     int16_t getSampleForChannel(int channel);

@@ -98,7 +98,7 @@ class Audio {
     Audio(PicoRam* memory);

     void resetAudioState();
-    audioState* getAudioState();
+    audioState_t* getAudioState();

     void api_sfx(int sfx, int channel, int offset);
     void api_music(int pattern, int16_t fade_len, int16_t mask);
diff --git a/source/PicoRam.h b/source/PicoRam.h
index 9c361c4..ad23ddc 100644
--- a/source/PicoRam.h
+++ b/source/PicoRam.h
@@ -140,7 +140,7 @@ struct sfxChannel {
     float prev_vol = 0;
 };

-struct audioState {
+struct audioState_t {
     musicChannel _musicChannel;
     sfxChannel _sfxChannels[4];
 };
@@ -290,4 +290,22 @@ struct PicoRam

         uint8_t data[0x10000];
     };
-};
\ No newline at end of file
+};
+
+/*
+struct saveState_t
+{
+    union
+    {
+        struct
+        {
+            PicoRam memory;
+            audioState_t audioState;
+            char luaStateStr[1024*1024*2];
+
+        };
+
+        uint8_t data[sizeof(PicoRam) + sizeof(audioState_t) + 1024*1024*2];
+    };
+};
+*/
diff --git a/source/host.h b/source/host.h
index 906bf7b..ae9a2b9 100644
--- a/source/host.h
+++ b/source/host.h
@@ -133,6 +133,9 @@ class Host {

     void saveCartData(std::string cartDataKey, std::string contents);

+    size_t getFileContents(std::string fileName, char* buffer);
+    void writeBufferToFile(std::string cartDataKey, char* buffer, size_t length);
+
     std::string getCartDirectory();

     //settings
diff --git a/source/hostCommonFunctions.cpp b/source/hostCommonFunctions.cpp
index 1ce7a11..2a0aa50 100644
--- a/source/hostCommonFunctions.cpp
+++ b/source/hostCommonFunctions.cpp
@@ -217,6 +217,36 @@ void Host::saveCartData(std::string cartDataKey, std::string contents) {
 	}
 }

+size_t Host::getFileContents(std::string fileName, char* buffer) {
+	std::string absPath = _logFilePrefix + "cdata/" + fileName;
+    //get_file_bin_contents(absPath, buffer, length);
+	FILE * file = freopen(absPath.c_str(), "rb", stderr);
+    if( file != NULL ) {
+		//Initialize data
+		size_t len;
+		fread(&len, sizeof(len), 1, file);
+		fread(buffer, sizeof(char), len, file);
+
+        fclose(file);
+
+		return len;
+	}
+
+	return 0;
+}
+
+void Host::writeBufferToFile(std::string fileName, char* buffer, size_t length) {
+	std::string absPath = _logFilePrefix + "cdata/" + fileName;
+    FILE * file = freopen(absPath.c_str(), "w", stderr);
+    if( file != NULL ) {
+		//Initialize data
+		fwrite(&length, sizeof(length), 1, file);
+		fwrite(buffer, sizeof(char), length, file);
+
+        fclose(file);
+	}
+}
+
 //settings

 int Host::getSetting(std::string sname) {
diff --git a/source/p8GlobalLuaFunctions.h b/source/p8GlobalLuaFunctions.h
index 25919b5..54d7e5c 100644
--- a/source/p8GlobalLuaFunctions.h
+++ b/source/p8GlobalLuaFunctions.h
@@ -273,6 +273,71 @@ poke4, memcpy, memset, max, min, mid, flr,
 ceil, cos, sin, atan2, rnd, srand, band,
 bor, bxor, bnot, shl, shr, lshr, rotl, rotr

+--save state code modified from ps4-p8
+//https://github.com/voliva/ps4-p8/blob/ecba7f93ef9ba73ccb121b45ede6f46e651cef65/pico8_ps4/lua_lang_fns.cpp
+//MIT license
+
+eris.perm = {}
+eris.unperm = {}
+eris.original_G = {}
+
+eris.init_persist_all = function()
+  -- lua pairs is not sorted. The order is actually random, changes on every execution (wtf?)
+
+  eris.settings("path", true)
+
+  local keyset={}
+  local n=0
+  for k,v in pairs(_G) do
+    n=n+1
+    keyset[n]=k
+  end
+  table.sort(keyset)
+  local i=0
+  for i=1,n do
+    local k=keyset[i]
+    local v=_G[k]
+    eris.perm[v] = i
+    eris.unperm[i] = v
+    eris.original_G[k] = v
+  end
+end
+
+eris.persist_all = function()
+  local new_symbols = {}
+  printh("persist_all")
+  for k,v in pairs(_G) do
+    if eris.original_G[k] != v then
+       printh("adding key: " .. k .. ": " .. tostr(v))
+       new_symbols[k] = v
+    end
+  end
+
+  local result = eris.persist(eris.perm, new_symbols)
+  printh("result: ")
+  for i=1, #result do
+    printh(tostr(i).."  "..tostr(ord(result, i)))
+  end
+  printh("end of result")
+
+  return result;
+end
+
+eris.restore_all = function(persisted)
+  printh("persisted: ")
+  for i=1, #persisted do
+    printh(tostr(i).."  "..tostr(ord(persisted, i)))
+  end
+  printh("end of persisted")
+  printh("restore_all- iterating symbols first")
+  local new_symbols = eris.unpersist(eris.unperm, persisted)
+  for k,v in pairs(new_symbols) do
+    printh("restoring key: " .. k .. ": " .. tostr(v))
+  end
+  for k,v in pairs(new_symbols) do
+    _G[k] = v
+  end
+end
 )#";


diff --git a/source/vm.cpp b/source/vm.cpp
index 8b1d6ea..be2bcb1 100644
--- a/source/vm.cpp
+++ b/source/vm.cpp
@@ -333,6 +333,23 @@ bool Vm::loadCart(Cart* cart) {
     //pop the _init fuction off the stack now that we're done with it
     lua_pop(_luaState, 0);

+    // Push the eris.init_persist_all function on the top of the lua stack (or nil if it doesn't exist)
+    printf("********trying to call eris.init_persist_all\n");
+    lua_getglobal(_luaState, "eris");
+	lua_getfield(_luaState, -1, "init_persist_all");
+
+    if (lua_pcall(_luaState, 0, 0, 0)){
+        printf("********error trying to call eris.init_persist_all\n");
+        printf("Error setting up lua persistence: %s\n", lua_tostring(_luaState, -1));
+        Logger_Write("Error setting up lua persistence: %s\n", lua_tostring(_luaState, -1));
+        lua_pop(_luaState, 1);
+        return false;
+    }
+
+    //pop the eris.init_persist_all fuction off the stack now that we're done with it
+    lua_pop(_luaState, 1);
+    printf("********succeeded calling eris.init_persist_all\n");
+
     //check for update, mark correct target fps
     lua_getglobal(_luaState, "_update60");
     if (lua_isfunction(_luaState, -1)) {
@@ -502,12 +519,23 @@ void Vm::deserializeCartDataToMemory(std::string cartDataStr) {
             _memory->data[0x5e00 + idxStart + 3] = bytesVector[idxEnd - 3];
         }
     }
-
 }

+#define SAVESTATEBUFFSIZE 1024*1024*2
+static char saveStateBuffer[SAVESTATEBUFFSIZE];
+
 void Vm::UpdateAndDraw() {
     update_buttons();

+    if (_input->btnp(7) && _input->btn(3)) {
+        size_t length = _host->getFileContents("testsavestate.state", saveStateBuffer);
+        deserializeLuaState(saveStateBuffer, length);
+    }
+    else if (_input->btnp(7)) {
+        size_t length = serializeLuaState(saveStateBuffer);
+        _host->writeBufferToFile("testsavestate.state", saveStateBuffer, length);
+    }
+
     _picoFrameCount++;

     if (_cartChangeQueued) {
@@ -1139,4 +1167,37 @@ std::string Vm::getLuaLine(string filename, int linenumber) {

     return line;

-}
\ No newline at end of file
+}
+
+
+size_t Vm::serializeLuaState(char* dest) {
+    lua_getglobal(_luaState, "eris");
+	lua_getfield(_luaState, -1, "persist_all");
+
+	if (lua_pcall(_luaState, 0, 1, 0) != 0) {
+		std::string e = lua_tostring(_luaState, -1);
+		lua_pop(_luaState, 1);
+		return 0;
+	}
+
+	size_t len;
+	const char* result = lua_tolstring(_luaState, -1, &len);
+    memcpy(dest, result, len);
+	lua_pop(_luaState, 2);
+
+    return len;
+}
+
+void Vm::deserializeLuaState(const char* src, size_t len) {
+    lua_getglobal(_luaState, "eris");
+	lua_getfield(_luaState, -1, "restore_all");
+	lua_pushlstring(_luaState, src, len);
+
+	if (lua_pcall(_luaState, 1, 0, 0) != 0) {
+		std::string e = lua_tostring(_luaState, -1);
+		lua_pop(_luaState, 1);
+		return;
+	}
+	lua_pop(_luaState, 1);
+}
+
diff --git a/source/vm.h b/source/vm.h
index 9c19308..2107b04 100644
--- a/source/vm.h
+++ b/source/vm.h
@@ -160,5 +160,8 @@ class Vm {

     string getCartBreadcrumb();
     string getCartParam();
+
+    size_t serializeLuaState(char* dest);
+    void deserializeLuaState(const char* src, size_t len);
 };

diff --git a/test/audiotests.cpp b/test/audiotests.cpp
index d816b8c..79bc055 100644
--- a/test/audiotests.cpp
+++ b/test/audiotests.cpp
@@ -7,7 +7,7 @@ TEST_CASE("audio class behaves as expected") {
     PicoRam picoRam;
     picoRam.Reset();
     Audio* audio = new Audio(&picoRam);
-    audioState* audioState = audio->getAudioState();
+    audioState_t* audioState = audio->getAudioState();

     SUBCASE("Audio constructor sets sfx channels to -1") {
         bool allChannelsOff = true;