foxygit / fake-08-xbox360 Log in
commit 0c1d75742b281e226f5dd615129757291e019b76
Author:     jtothebell <j.to.the.bell@gmail.com>
AuthorDate: Tue Nov 10 06:28:03 2020 -0700
Commit:     jtothebell <j.to.the.bell@gmail.com>
CommitDate: Tue Nov 10 06:28:03 2020 -0700

    Add rnd and srand (port from zepto8)

    most carts that were working seem to be working again.
    There was some performance regression that will need to be addressed
---
 source/PicoRam.h              |   2 +-
 source/cart.cpp               |   5 --
 source/p8GlobalLuaFunctions.h |  15 +++++
 source/picoluaapi.cpp         |  23 +++++++
 source/picoluaapi.h           |   3 +
 source/vm.cpp                 |  45 +++++++++++++
 source/vm.h                   |   9 +++
 test/carts/arithmetictest.p8  |  36 +++++++++++
 test/endtoendtests.cpp        | 144 ++++++++++++++++++++++++++++++++++++++++++
 test/vmtests.cpp              |   2 +
 10 files changed, 278 insertions(+), 6 deletions(-)

diff --git a/source/PicoRam.h b/source/PicoRam.h
index fdcd98e..fd2beca 100644
--- a/source/PicoRam.h
+++ b/source/PicoRam.h
@@ -150,7 +150,7 @@ struct drawState_t {
 struct hwState_t {
     uint8_t audioHardwareState[4];

-    uint8_t rngState[8];
+    uint32_t rngState[2];

     uint8_t buttonStates[8];

diff --git a/source/cart.cpp b/source/cart.cpp
index 7ba3ecf..b913985 100644
--- a/source/cart.cpp
+++ b/source/cart.cpp
@@ -19,7 +19,6 @@

 #include "logger.h"

-#include "cartPatcher.h"
 #include "emojiconversion.h"

 #include "FakoBios.h"
@@ -359,10 +358,6 @@ Cart::Cart(std::string filename){
     else {
         return;
     }
-
-    const char * patched = getPatchedLua(LuaString.c_str());
-
-    LuaString = patched;
 }

 Cart::~Cart(){
diff --git a/source/p8GlobalLuaFunctions.h b/source/p8GlobalLuaFunctions.h
index 6ccbc92..e6c2718 100644
--- a/source/p8GlobalLuaFunctions.h
+++ b/source/p8GlobalLuaFunctions.h
@@ -52,6 +52,17 @@ function del(a, dv)
 	end
 end

+//from zepto 8 bios.p8
+function deli(c,i)
+    if c != nil then
+        -- delete at i if specified, otherwise at the end
+        i=i and mid(1,i\1,#c) or #c
+        local v=c[i]
+        for j=i,#c-1 do c[j]=c[j+1] end
+        return v
+    end
+end
+
 ---------------------------------
 --Coroutines
 ---------------------------------
@@ -65,6 +76,10 @@ costatus = coroutine.status
 ---------------------------------
 trace = debug.traceback

+sub = string.sub
+pack = table.pack
+unpack = table.unpack
+
 --Button emoji variables
 ⬅️ = 0
 ➡️ = 1
diff --git a/source/picoluaapi.cpp b/source/picoluaapi.cpp
index b26ac0d..06dffa9 100644
--- a/source/picoluaapi.cpp
+++ b/source/picoluaapi.cpp
@@ -723,6 +723,29 @@ int printh(lua_State *L) {
     return 0;
 }

+int rnd(lua_State *L) {
+    if (lua_gettop(L) == 0) {
+        fix32 val = _vmForLuaApi->api_rnd();
+
+        lua_pushnumber(L, val);
+    }
+    else {
+        fix32 range = lua_tonumber(L,1);
+        fix32 val = _vmForLuaApi->api_rnd(range);
+
+        lua_pushnumber(L, val);
+    }
+
+    return 1;
+}
+
+int srand(lua_State *L) {
+    fix32 seed = lua_tonumber(L,1);
+    _vmForLuaApi->api_srand(seed);
+
+    return 0;
+}
+
 int listcarts(lua_State *L) {
     //get cart list from VM (who should get it from host)
     vector<string> carts = _vmForLuaApi->GetCartList();
diff --git a/source/picoluaapi.h b/source/picoluaapi.h
index 2148d1d..c9dee8a 100644
--- a/source/picoluaapi.h
+++ b/source/picoluaapi.h
@@ -95,6 +95,9 @@ int loadbioscart(lua_State *L);

 //system functions

+int rnd(lua_State *L);
+int srand(lua_State *L);
+
 //api.tonum(val)

 //api.tostr(val, hex)
diff --git a/source/vm.cpp b/source/vm.cpp
index 3f401a5..d23a213 100644
--- a/source/vm.cpp
+++ b/source/vm.cpp
@@ -1,5 +1,6 @@
 #include <string>
 #include <functional>
+#include <chrono>
 #include <math.h>

 #include <string.h>
@@ -19,8 +20,11 @@
   #include <lua.h>
   #include <lualib.h>
   #include <lauxlib.h>
+  #include <fix32.h>
 //}

+using namespace z8;
+
 Vm::Vm(
     PicoRam* memory,
     Graphics* graphics,
@@ -99,6 +103,10 @@ bool Vm::loadCart(Cart* cart) {
     //reset memory (may have to be more selective about zeroing out to be accurate?)
     _memory->Reset();

+    //seed rng
+    auto now = std::chrono::high_resolution_clock::now();
+    api_srand(fix32::frombits((int32_t)now.time_since_epoch().count()));
+
     //set graphics state
     _graphics->color();
     _graphics->clip();
@@ -122,8 +130,12 @@ bool Vm::loadCart(Cart* cart) {
     // initialize Lua interpreter
     _luaState = luaL_newstate();

+    lua_setpico8memory(_luaState, (uint8_t *)&_memory->data);
     // load Lua base libraries (print / math / etc)
     luaL_openlibs(_luaState);
+	//luaopen_debug(_luaState);
+	//luaopen_string(_luaState);
+    lua_pushglobaltable(_luaState);

     //load in global lua fuctions for pico 8
     auto convertedGlobalLuaFunctions = convert_emojis(p8GlobalLuaFunctions);
@@ -202,6 +214,10 @@ bool Vm::loadCart(Cart* cart) {
     lua_register(_luaState, "printh", printh);
     lua_register(_luaState, "stat", stat);

+    //rng
+    lua_register(_luaState, "rnd", rnd);
+    lua_register(_luaState, "srand", srand);
+
     //system
     lua_register(_luaState, "__listcarts", listcarts);
     lua_register(_luaState, "__loadcart", loadcart);
@@ -569,3 +585,32 @@ void Vm::vm_memcpy(int destaddr, int sourceaddr, int len){

     memcpy(&_memory->data[destaddr], &_memory->data[sourceaddr], len);
 }
+
+void Vm::update_prng()
+{
+    auto rngState = _memory->hwState.rngState;
+    rngState[1] = rngState[0] + ((rngState[1] >> 16) | (rngState[1] << 16));
+    rngState[0] += rngState[1];
+}
+
+fix32 Vm::api_rnd()
+{
+    return api_rnd((fix32)1);
+}
+
+fix32 Vm::api_rnd(fix32 in_range)
+{
+    update_prng();
+    uint32_t b = _memory->hwState.rngState[1];
+    uint32_t range = in_range.bits();
+    return fix32::frombits(range > 0 ? b % range : 0);
+}
+
+void Vm::api_srand(fix32 seed)
+{
+    auto rngState = _memory->hwState.rngState;
+    rngState[0] = seed ? seed.bits() : 0xdeadbeef;
+    rngState[1] = rngState[0] ^ 0xbead29ba;
+    for (int i = 0; i < 32; ++i)
+        update_prng();
+}
diff --git a/source/vm.h b/source/vm.h
index 2c39e3f..c4982be 100644
--- a/source/vm.h
+++ b/source/vm.h
@@ -12,8 +12,11 @@ using namespace std;
   #include <lua.h>
   #include <lualib.h>
   #include <lauxlib.h>
+  #include <fix32.h>
 //}

+using namespace z8;
+
 class Vm {
     PicoRam* _memory;

@@ -97,5 +100,11 @@ class Vm {

     void vm_memset(int destaddr, uint8_t val, int len);
     void vm_memcpy(int destaddr, int sourceaddr, int len);
+
+    void update_prng();
+
+    fix32 api_rnd();
+    fix32 api_rnd(fix32 inRange);
+    void api_srand(fix32 seed);
 };

diff --git a/test/carts/arithmetictest.p8 b/test/carts/arithmetictest.p8
new file mode 100644
index 0000000..ae25bf5
--- /dev/null
+++ b/test/carts/arithmetictest.p8
@@ -0,0 +1,36 @@
+pico-8 cartridge // http://www.pico-8.com
+version 29
+__lua__
+frames = 0
+tbl = { 1, 2, 3, 4}
+function _update()
+ firstrand = rnd()
+ frames+=1
+ result = frames * 10
+ result2 = frames / 5
+ result3 = 5.6 - 2
+ srand(10)
+ result4 = rnd()
+ result5 = rnd(100)
+
+ tblcount = #tbl
+ rndcount = rnd(tblcount)
+ ceilcount = ceil(rndcount)
+end
+
+function _draw()
+ cls()
+ print(frames)
+ print(result)
+ print(result2)
+ print(result3)
+ print(result4)
+ print(result5)
+end
+__gfx__
+00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+00700700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+00077000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+00077000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
+00700700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
diff --git a/test/endtoendtests.cpp b/test/endtoendtests.cpp
index 10f6b27..621250f 100644
--- a/test/endtoendtests.cpp
+++ b/test/endtoendtests.cpp
@@ -1,5 +1,7 @@
 #include <string>
 #include <vector>
+#include <sstream>
+#include <algorithm>

 #include "doctest.h"
 #include "../libs/lodepng/lodepng.h"
@@ -273,6 +275,148 @@ TEST_CASE("Loading and running carts") {

         vm->CloseCart();
     }
+    SUBCASE("Simple Arithmetic Cart"){
+        vm->LoadCart("carts/arithmetictest.p8");

+        SUBCASE("No error reported"){
+            CHECK(vm->GetBiosError() == "");
+        }
+        SUBCASE("addition works"){
+            vm->UpdateAndDraw(0, 0);
+
+            bool additionWorks = vm->ExecuteLua(
+                "function additiontest()\n"
+                " return frames == 1\n"
+                "end\n",
+                "additiontest");
+
+            CHECK(additionWorks);
+        }
+        SUBCASE("multiplication works"){
+            vm->UpdateAndDraw(0, 0);
+
+            bool multiplicationWorks = vm->ExecuteLua(
+                "function multiplicationtest()\n"
+                " return result == 10\n"
+                "end\n",
+                "multiplicationtest");
+
+            CHECK(multiplicationWorks);
+        }
+        SUBCASE("division works"){
+            vm->UpdateAndDraw(0, 0);
+
+            bool divisionWorks = vm->ExecuteLua(
+                "function divisiontest()\n"
+                " return result2 == 0.2\n"
+                "end\n",
+                "divisiontest");
+
+            CHECK(divisionWorks);
+        }
+        SUBCASE("subtraction works"){
+            vm->UpdateAndDraw(0, 0);
+
+            bool subtractionWorks = vm->ExecuteLua(
+                "function subtractiontest()\n"
+                " return result3 == 3.6\n"
+                "end\n",
+                "subtractiontest");
+
+            CHECK(subtractionWorks);
+        }
+        SUBCASE("rnd returns between 0 and 1, and can add"){
+            vm->UpdateAndDraw(0, 0);
+
+            bool rndWorks = vm->ExecuteLua(
+                "function rndtest()\n"
+                " return result4 > 0 and result4 < 1\n"
+                "end\n",
+                "rndtest");
+
+            CHECK(rndWorks);
+        }
+        SUBCASE("rnd returns between 0 and 1 without calling srand first"){
+            vm->UpdateAndDraw(0, 0);
+
+            bool rndWorks = vm->ExecuteLua(
+                "function firstrndtest()\n"
+                " return firstrand > 0 and firstrand < 1\n"
+                "end\n",
+                "firstrndtest");
+
+            CHECK(rndWorks);
+        }
+        SUBCASE("# returns count of array"){
+            vm->UpdateAndDraw(0, 0);
+
+            bool rndWorks = vm->ExecuteLua(
+                "function counttest()\n"
+                " return tblcount == 4\n"
+                "end\n",
+                "counttest");
+
+            CHECK(rndWorks);
+        }
+        SUBCASE("ceil works"){
+            vm->UpdateAndDraw(0, 0);
+
+            bool ceilWorks = vm->ExecuteLua(
+                "function ceiltest()\n"
+                " return ceilcount == 1\n"
+                "end\n",
+                "ceiltest");
+
+            CHECK(ceilWorks);
+        }
+
+        vm->CloseCart();
+    }
+
+    SUBCASE("api loaded with cart load") {
+
+        vm->LoadCart("carts/cartparsetest.p8");
+
+        SUBCASE("all api functions exist"){
+            vector<string> apiFunctions {
+                "time", "t", "sub", "chr", "ord", "tostr", "tonum",
+                "add", "del", "deli", "clip", "color", "pal", "palt",
+                "fillp", "pget", "pset", "sget", "sset", "fget",
+                "fset", "circ", "circfill", "rect", "rectfill", "oval",
+                "ovalfill", "line", "spr", "sspr", "mget", "mset",
+                "tline", "peek", "poke", "peek2", "poke2", "peek4",
+                "poke4", "memcpy", "memset", "max", "min", "mid", "flr",
+                "ceil", "cos", "sin", "atan2", "rnd", "srand", "band",
+                "bor", "bxor", "bnot", "shl", "shr", "lshr", "rotl", "rotr"
+            };
+
+            vector<string> expectedMissing {
+                "oval", "ovalfill", "tline"
+            };
+
+            string missing = "";
+
+            for (auto apiFunction : apiFunctions) {
+                if (std::find(expectedMissing.begin(), expectedMissing.end(), apiFunction) != expectedMissing.end())
+                {
+                    continue;
+                }
+
+                std::stringstream ss;
+                ss << "function globalfunctest()\n  return " << apiFunction << " ~= nil\n  end\n";
+
+                bool functionExists = vm->ExecuteLua(ss.str(), "globalfunctest");
+
+                if (!functionExists) {
+                    missing = missing + ", " + apiFunction;
+                }
+            }
+
+            CHECK_MESSAGE(missing.length() == 0, missing);
+        }
+
+        vm->CloseCart();
+    }
+
     delete vm;
 }
\ No newline at end of file
diff --git a/test/vmtests.cpp b/test/vmtests.cpp
index 4dc01af..af84b11 100644
--- a/test/vmtests.cpp
+++ b/test/vmtests.cpp
@@ -235,6 +235,8 @@ TEST_CASE("Vm memory functions") {
         CHECK_EQ(memory->hwState.audioHardwareState[0], 3);
     }
     SUBCASE("poking rng state") {
+        //rng gets seeded, we need to zero it out to test this easier
+        memory->hwState.rngState[0] = 0;
         vm->vm_poke(0x5f44, 20);

         CHECK_EQ(memory->hwState.rngState[0], 20);