-- Shared helpers for battle_* scripts. Load with: dofile(os.getenv("TBG_LIB")) local L = {} -- Savestate calls are only legal inside an exec callback for the main CPU. function L.inExec(fn) local ref ref = emu.addMemoryCallback(function() emu.removeMemoryCallback(ref, emu.callbackType.exec, 0, 0xFFFFFF, emu.cpuType.snes) fn() end, emu.callbackType.exec, 0, 0xFFFFFF, emu.cpuType.snes) end function L.save(path) L.inExec(function() local h = io.open(path, "wb"); h:write(emu.createSavestate()); h:close() end) end function L.load(path) L.inExec(function() local h = io.open(path, "rb"); emu.loadSavestate(h:read("a")); h:close() end) end function L.pc() local s = emu.getState(); return (s["cpu.k"] << 16) | s["cpu.pc"] end function L.wram(a, n) local t = {}; for i = 0, n - 1 do t[#t + 1] = emu.read(a + i, emu.memType.snesWorkRam) end; return t end function L.dumpWram(path) local t = {}; for i = 0, 0x1FFFF do t[#t + 1] = string.char(emu.read(i, emu.memType.snesWorkRam)) end local h = io.open(path, "wb"); h:write(table.concat(t)); h:close() end function L.shot(path) local h = io.open(path, "wb"); h:write(emu.takeScreenshot()); h:close() end -- input plan: "frame:btn+btn[/hold],..." on port 0; "p2@frame:btn" for port 1 function L.inputPlan(spec) local ev = {} for item in (spec or ""):gmatch("[^,]+") do local port, f, b, hold = 0, nil, nil, 4 local p2 = item:match("^p2@") if p2 then port = 1; item = item:sub(4) end f, b = item:match("^(%d+):([%w+]+)") local hh = item:match("/(%d+)$"); if hh then hold = tonumber(hh) end if f then ev[#ev + 1] = {f = tonumber(f), b = b, hold = hold, port = port} end end return ev end return L