run_pico
Execute pico8 code that doesn't depend on graphics/sound apis. (This module can also be executed directly to do this)
1#!/usr/bin/env python3 2"""Execute pico8 code that doesn't depend on graphics/sound apis. (This module can also be executed directly to do this)""" 3from utils import * 4from pico_defs import encode_p8str, decode_p8str, from_p8str, to_p8str, Memory, get_res_path 5from pico_cart import read_cart_autodetect 6from codecs import register as codec_register, CodecInfo 7 8def _lupaz8_module(): 9 try: 10 from lupaz8 import luaz8 # type: ignore 11 except ImportError: 12 throw("You need lupaz8 (a fork of lupa) to execute pico8 scripts (do 'python -m pip install lupaz8')") 13 return luaz8 14 15k_p8_codec = CodecInfo(lambda i: (encode_p8str(i), len(i)), 16 lambda i: (decode_p8str(i), len(i))) 17def p8_codec_search(name): 18 if name == "p8scii": 19 return k_p8_codec 20codec_register(p8_codec_search) 21 22def picoscript_from_p8str(text, unicaps=False): 23 """A version of from_p8str that's usable from a pico8 script (bytes/p8scii string -> utf8 string)""" 24 return from_p8str(text, unicaps).encode() # encode to prevent encoding as p8str again 25 26def picoscript_to_p8str(mess): 27 """A version of to_p8str that's usable from a pico8 script (utf8 string -> bytes/p8scii string)""" 28 return to_p8str(encode_p8str(mess).decode()) # mess is utf8 encoded as p8str, so must unmess first 29 30def picoscript_to_memory(mess): 31 """Constructs a Memory (a type of bytearray) from a bytes/p8scii string""" 32 if isinstance(mess, str): 33 mess = encode_p8str(mess) 34 return Memory(mess) 35 36def picoscript_from_memory(bytearray): 37 """Gets a bytes/p8scii string from a Memory (or any bytearray)""" 38 return bytes(bytearray) 39 40# general note - a python int is passed to lua only when it can't fit into a pico8 integer (16-bit signed) 41# there is currently no reliable way to do overflow-free arithmetic on ints because of that 42# (but you can always convert to fixnum to get signed 32bit arithmetic. or use python.builtins.eval) 43 44def picoscript_to_fixnum(v): 45 """Converts an integer (pico8 or python) to a 16.16 pico8 number""" 46 return float(v) / 0x10000 47 48def picoscript_from_fixnum(v): 49 """Converts a 16.16 pico8 number into an integer (pico8 or python - whichever can hold it)""" 50 v = int(v * 0x10000) 51 if v < 0: 52 v += 0x100000000 53 return v 54 55def picoscript_print(tostr, *args): 56 if not args: return 57 print(from_p8str(tostr(args[0]))) 58 return 0 59 60def picoscript_printh(tostr, *args): 61 if not args: return 62 val, filename, overwrite = list_unpack(args, 3) 63 val = from_p8str(tostr(val)) 64 if not filename: 65 eprint(val) 66 elif overwrite: 67 file_write_text(filename, val + "\n") 68 else: 69 file_append_text(filename, val + "\n") 70 71class StopError(CheckError): 72 pass 73 74def picoscript_stop(tostr, *args): 75 raise StopError(from_p8str(tostr(args[0])) if args else "stop() called") 76 77def picoscript_rompeek(mem, off, count=None): 78 if count != None: 79 return tuple(picoscript_rompeek(mem, off + i) for i in range(count)) 80 return mem.get8(int(off)) 81def picoscript_rompeek2(mem, off, count=None): 82 if count != None: 83 return tuple(picoscript_rompeek2(mem, off + i * 2) for i in range(count)) 84 return float(mem.get16(int(off))) 85def picoscript_rompeek4(mem, off, count=None): 86 if count != None: 87 return tuple(picoscript_rompeek4(mem, off + i * 4) for i in range(count)) 88 return picoscript_to_fixnum(mem.get32(int(off))) 89 90def picoscript_rompoke(mem, off, *data): 91 for datum in data: 92 mem.set8(off, datum) 93 off += 1 94def picoscript_rompoke2(mem, off, *data): 95 for datum in data: 96 mem.set16(off, datum) 97 off += 2 98def picoscript_rompoke4(mem, off, *data): 99 for datum in data: 100 mem.set32(off, picoscript_from_fixnum(datum)) 101 off += 4 102 103def picoscript_rommemcpy(dmem, dest, smem, src, len): 104 dmem.copy8(dest, src, len, smem) 105 106def picoscript_rommemset(mem, off, val, len): 107 mem.fill8(off, val, len) 108 109def create_runtime(): 110 runtime = _lupaz8_module().LuaRuntime(encoding="p8scii", source_encoding="p8scii", 111 overflow_handler=True, unpack_returned_tuples=True) 112 p8globs = runtime.globals() 113 114 tostr = p8globs.tostr 115 p8globs.print = lambda *a: picoscript_print(tostr, *a) # to stdout 116 p8globs.printh = lambda *a: picoscript_printh(tostr, *a) # to stderr or file 117 p8globs.stop = lambda *a: picoscript_stop(tostr, *a) 118 119 p8globs.rompeek = picoscript_rompeek 120 p8globs.rompeek2 = picoscript_rompeek2 121 p8globs.rompeek4 = picoscript_rompeek4 122 p8globs.rompoke = picoscript_rompoke 123 p8globs.rompoke2 = picoscript_rompoke2 124 p8globs.rompoke4 = picoscript_rompoke4 125 p8globs.rommemcpy = picoscript_rommemcpy 126 p8globs.rommemset = picoscript_rommemset 127 128 shrinko = p8globs.shrinko = runtime.table() 129 shrinko.from_utf8 = shrinko.to_p8str = picoscript_to_p8str 130 shrinko.to_utf8 = shrinko.from_p8str = picoscript_from_p8str 131 shrinko.to_memory = picoscript_to_memory 132 shrinko.from_memory = picoscript_from_memory 133 shrinko.to_fixnum = picoscript_to_fixnum 134 shrinko.from_fixnum = picoscript_from_fixnum 135 136 return runtime 137 138g_runtime = None 139def get_runtime(): 140 global g_runtime 141 if not g_runtime: 142 g_runtime = create_runtime() 143 return g_runtime 144 145def lua_type(obj): 146 return _lupaz8_module().lua_type(obj) 147 148def exec_pico_code(code): 149 return get_runtime().execute(code) 150 151def exec_pico_script_by_path(path): 152 cart = read_cart_autodetect(path) # for includes/etc 153 154 return get_runtime().execute(cart.code, name=path, mode='t') 155 156g_pico_imports = {} 157def import_pico_script(module_name): 158 module = g_pico_imports.get(module_name) 159 if module is None: 160 path_pfx = path_join(get_res_path(), module_name.replace(".", "/")) 161 for ext in [".lua", ".py"]: 162 path = path_pfx + ext 163 if path_exists(path): 164 module = exec_pico_script_by_path(path) 165 if module is None: 166 module = True 167 g_pico_imports[module_name] = module 168 return module 169 raise ModuleNotFoundError(module_name) 170 return module 171 172if __name__ == "__main__": 173 try: 174 arg = list_get(sys.argv, 1) 175 if arg == "-c": 176 exec_pico_code(list_get(sys.argv, 2)) 177 elif arg: 178 exec_pico_script_by_path(arg) 179 else: 180 print("Usage: <path> OR -c <cmd>") 181 except CheckError as e: 182 print(f"ERROR - {e}")
k_p8_codec =
<codecs.CodecInfo object for encoding None>
def
p8_codec_search(name):
def
picoscript_from_p8str(text, unicaps=False):
23def picoscript_from_p8str(text, unicaps=False): 24 """A version of from_p8str that's usable from a pico8 script (bytes/p8scii string -> utf8 string)""" 25 return from_p8str(text, unicaps).encode() # encode to prevent encoding as p8str again
A version of from_p8str that's usable from a pico8 script (bytes/p8scii string -> utf8 string)
def
picoscript_to_p8str(mess):
27def picoscript_to_p8str(mess): 28 """A version of to_p8str that's usable from a pico8 script (utf8 string -> bytes/p8scii string)""" 29 return to_p8str(encode_p8str(mess).decode()) # mess is utf8 encoded as p8str, so must unmess first
A version of to_p8str that's usable from a pico8 script (utf8 string -> bytes/p8scii string)
def
picoscript_to_memory(mess):
31def picoscript_to_memory(mess): 32 """Constructs a Memory (a type of bytearray) from a bytes/p8scii string""" 33 if isinstance(mess, str): 34 mess = encode_p8str(mess) 35 return Memory(mess)
Constructs a Memory (a type of bytearray) from a bytes/p8scii string
def
picoscript_from_memory(bytearray):
37def picoscript_from_memory(bytearray): 38 """Gets a bytes/p8scii string from a Memory (or any bytearray)""" 39 return bytes(bytearray)
Gets a bytes/p8scii string from a Memory (or any bytearray)
def
picoscript_to_fixnum(v):
45def picoscript_to_fixnum(v): 46 """Converts an integer (pico8 or python) to a 16.16 pico8 number""" 47 return float(v) / 0x10000
Converts an integer (pico8 or python) to a 16.16 pico8 number
def
picoscript_from_fixnum(v):
49def picoscript_from_fixnum(v): 50 """Converts a 16.16 pico8 number into an integer (pico8 or python - whichever can hold it)""" 51 v = int(v * 0x10000) 52 if v < 0: 53 v += 0x100000000 54 return v
Converts a 16.16 pico8 number into an integer (pico8 or python - whichever can hold it)
def
picoscript_print(tostr, *args):
def
picoscript_printh(tostr, *args):
An error meant to be caught and displayed as-is, like AssertionError but for user errors
def
picoscript_stop(tostr, *args):
def
picoscript_rompeek(mem, off, count=None):
def
picoscript_rompeek2(mem, off, count=None):
def
picoscript_rompeek4(mem, off, count=None):
def
picoscript_rompoke(mem, off, *data):
def
picoscript_rompoke2(mem, off, *data):
def
picoscript_rompoke4(mem, off, *data):
def
picoscript_rommemcpy(dmem, dest, smem, src, len):
def
picoscript_rommemset(mem, off, val, len):
def
create_runtime():
110def create_runtime(): 111 runtime = _lupaz8_module().LuaRuntime(encoding="p8scii", source_encoding="p8scii", 112 overflow_handler=True, unpack_returned_tuples=True) 113 p8globs = runtime.globals() 114 115 tostr = p8globs.tostr 116 p8globs.print = lambda *a: picoscript_print(tostr, *a) # to stdout 117 p8globs.printh = lambda *a: picoscript_printh(tostr, *a) # to stderr or file 118 p8globs.stop = lambda *a: picoscript_stop(tostr, *a) 119 120 p8globs.rompeek = picoscript_rompeek 121 p8globs.rompeek2 = picoscript_rompeek2 122 p8globs.rompeek4 = picoscript_rompeek4 123 p8globs.rompoke = picoscript_rompoke 124 p8globs.rompoke2 = picoscript_rompoke2 125 p8globs.rompoke4 = picoscript_rompoke4 126 p8globs.rommemcpy = picoscript_rommemcpy 127 p8globs.rommemset = picoscript_rommemset 128 129 shrinko = p8globs.shrinko = runtime.table() 130 shrinko.from_utf8 = shrinko.to_p8str = picoscript_to_p8str 131 shrinko.to_utf8 = shrinko.from_p8str = picoscript_from_p8str 132 shrinko.to_memory = picoscript_to_memory 133 shrinko.from_memory = picoscript_from_memory 134 shrinko.to_fixnum = picoscript_to_fixnum 135 shrinko.from_fixnum = picoscript_from_fixnum 136 137 return runtime
g_runtime =
None
def
get_runtime():
def
lua_type(obj):
def
exec_pico_code(code):
def
exec_pico_script_by_path(path):
g_pico_imports =
{}
def
import_pico_script(module_name):
158def import_pico_script(module_name): 159 module = g_pico_imports.get(module_name) 160 if module is None: 161 path_pfx = path_join(get_res_path(), module_name.replace(".", "/")) 162 for ext in [".lua", ".py"]: 163 path = path_pfx + ext 164 if path_exists(path): 165 module = exec_pico_script_by_path(path) 166 if module is None: 167 module = True 168 g_pico_imports[module_name] = module 169 return module 170 raise ModuleNotFoundError(module_name) 171 return module