pico_defs

Definitions from the pico8 world - such as Memory, p8str, fixnum, etc.

  1"""Definitions from the pico8 world - such as `Memory`, `p8str`, `fixnum`, etc."""
  2
  3from utils import *
  4from media_utils import Color
  5
  6class Language(Enum):
  7    """The supported lua languages"""
  8
  9    pico8 = picotron = ...
 10
 11class Memory(bytearray):
 12    """A pico8 memory block - a bytearray with some convenience functions like get/set16, get/set4, etc."""
 13
 14    def copy(m):
 15        return Memory(m)
 16
 17    def replace(m, src):
 18        m[:] = src
 19    
 20    def clear(m):
 21        m.fill8(0, 0, len(m))
 22
 23    def size(m):
 24        return len(m)
 25
 26    def get8(m, i):
 27        return m[i]
 28
 29    def set8(m, i, v):
 30        m[i] = v
 31        
 32    def get_block(m, start, size):
 33        return m[start:start+size]
 34        
 35    def set_block(m, start, src):
 36        m[start:start+len(src)] = src
 37
 38    def copy8(m, dest, src, size, src_memory = None):
 39        m.set_block(dest, (src_memory or m).get_block(src, size))
 40    
 41    def copyfrom8(m, addr, size, src_memory):
 42        m.copy8(addr, addr, size, src_memory)
 43        
 44    def fill8(m, dest, value, size):
 45        m.set_block(dest, bytearray((value,)) * size)
 46        
 47    def cmpeq8(m, src1, src2, size, other_memory = None):
 48        return m.get_block(src1, size) == (other_memory or m).get_block(src2, size)
 49    
 50    def cmpeqwith8(m, src, size, other_memory = None):
 51        return m.cmpeq8(src, src, size, other_memory)
 52        
 53    def get16(m, i):
 54        return m.get8(i) | (m.get8(i + 1) << 8)
 55    
 56    def set16(m, i, v):
 57        m.set8(i, v & 0xff)
 58        m.set8(i + 1, (v >> 8) & 0xff)
 59
 60    def get32(m, i):
 61        return m.get16(i) | (m.get16(i + 2) << 16)
 62
 63    def set32(m, i, v):
 64        m.set16(i, v & 0xffff)
 65        m.set16(i + 2, (v >> 16) & 0xffff)
 66        
 67    def get8_bits(m, i, shift, mask):
 68        return (m.get8(i) >> shift) & mask
 69
 70    def set8_bits(m, i, shift, mask, v):
 71        m.set8(i, (m.get8(i) & ~(mask << shift)) | ((v & mask) << shift))
 72
 73    def get4(m, ix):
 74        i, high = ix
 75        return m.get8_bits(i, 4 if high else 0, 0xf)
 76
 77    def set4(m, ix, value):
 78        i, high = ix
 79        m.set8_bits(i, 4 if high else 0, 0xf, value)
 80
 81k_mem_sprites_addr = 0
 82k_mem_map_addr = 0x2000
 83k_mem_flag_addr = 0x3000
 84k_mem_music_addr = 0x3100
 85k_mem_sfx_addr = 0x3200
 86
 87def mem_sprite_addr(x, y):
 88    """Convert an (x,y) coord to a sprite address, for use with Memory.get/set4"""
 89    return k_mem_sprites_addr + y * 0x40 + (x >> 1), (x & 1)
 90    
 91def mem_map_addr(x, y):
 92    """Convert an (x,y) coord to a map address"""
 93    if y >= 0x20: y -= 0x40  # in effect
 94    return k_mem_map_addr + y * 0x80 + x
 95
 96def mem_flag_addr(tile, y=0):
 97    """Convert a tile number to the sprite's flags address"""
 98    return k_mem_flag_addr + y * 0x80 + tile
 99
100def mem_music_addr(music, ch):
101    """Returns the address of the given channel of the given music"""
102    return k_mem_music_addr + music * 0x4 + ch
103    
104def mem_sfx_addr(sound, note):
105    """Return the address of the given note of the given sfx"""
106    return k_mem_sfx_addr + sound * 0x44 + note * 0x2
107    
108def mem_sfx_info_addr(sound, i):
109    """Return the address of the i-th info byte of the given sfx"""
110    return mem_sfx_addr(sound, 0x20) + i
111
112def mem_create_rom():
113    rom = Memory(k_rom_size)
114    for i in range(0x40):
115        rom.set8(mem_sfx_info_addr(i, 1), 0x1 if i == 0 else 0x10)
116        for ch in range(4):
117            rom.set8(mem_music_addr(i, ch), 0x41 + ch)
118    return rom
119
120k_rom_size = 0x4300 # size of the part of the pico8 cart that gets copied to the pico8 Memory
121k_cart_size = 0x8000 # size of the entire pico8 cart
122k_code_size = k_cart_size - k_rom_size # size of the code in a pico8 cart
123k_trailer_size = 0x20 # size of the pico8 cart trailer in png format
124k_url_size = 2040 # max. size of a pico8 url
125k_url_prefix_size = 4
126
127# the pico8 palette
128k_palette = [
129    Color(0x00, 0x00, 0x00, 0xff), # black
130    Color(0x1d, 0x2b, 0x53, 0xff), # dark blue
131    Color(0x7e, 0x25, 0x53, 0xff), # magenta
132    Color(0x00, 0x87, 0x51, 0xff), # dark green
133    Color(0xab, 0x52, 0x36, 0xff), # dark brown
134    Color(0x5f, 0x57, 0x4f, 0xff), # dark gray
135    Color(0xc2, 0xc3, 0xc7, 0xff), # gray
136    Color(0xff, 0xf1, 0xe8, 0xff), # white
137    Color(0xff, 0x00, 0x4d, 0xff), # hot pink
138    Color(0xff, 0xa3, 0x00, 0xff), # orange
139    Color(0xff, 0xec, 0x27, 0xff), # yellow
140    Color(0x00, 0xe4, 0x36, 0xff), # green
141    Color(0x29, 0xad, 0xff, 0xff), # light blue
142    Color(0x83, 0x76, 0x9c, 0xff), # violet
143    Color(0xff, 0x77, 0xa8, 0xff), # pink
144    Color(0xff, 0xcc, 0xaa, 0xff), # light pink
145    # alt. colors
146    Color(0x29, 0x18, 0x14, 0xff),
147    Color(0x11, 0x1D, 0x35, 0xff),
148    Color(0x42, 0x21, 0x36, 0xff),
149    Color(0x12, 0x53, 0x59, 0xff),
150    Color(0x74, 0x2F, 0x29, 0xff),
151    Color(0x49, 0x33, 0x3B, 0xff),
152    Color(0xA2, 0x88, 0x79, 0xff),
153    Color(0xF3, 0xEF, 0x7D, 0xff),
154    Color(0xBE, 0x12, 0x50, 0xff),
155    Color(0xFF, 0x6C, 0x24, 0xff),
156    Color(0xA8, 0xE7, 0x2E, 0xff),
157    Color(0x00, 0xB5, 0x43, 0xff),
158    Color(0x06, 0x5A, 0xB5, 0xff),
159    Color(0x75, 0x46, 0x65, 0xff),
160    Color(0xFF, 0x6E, 0x59, 0xff),
161    Color(0xFF, 0x9D, 0x81, 0xff),
162]
163
164 # the pico8 character set
165k_charset = [
166    '\0', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '\t', '\n', 'ᵇ', 'ᶜ', '\r', 'ᵉ', 'ᶠ',
167    '▮', '■', '□', '⁙', '⁘', '‖', '◀', '▶', '「', '」', '¥', '•', '、', '。', '゛', '゜'
168]
169for i in range(0x20, 0x7f):
170    k_charset.append(chr(i))
171k_charset += [
172    '○',
173    # note: some of the below have variant selector #16 at the end
174    '█','▒','🐱','⬇️','░','✽','●','♥','☉','웃','⌂','⬅️','😐','♪','🅾️','◆',
175    '…','➡️','★','⧗','⬆️','ˇ','∧','❎','▤','▥','あ','い','う','え','お','か',
176    'き','く','け','こ','さ','し','す','せ','そ','た','ち','つ','て','と','な','に',
177    'ぬ','ね','の','は','ひ','ふ','へ','ほ','ま','み','む','め','も','や','ゆ','よ',
178    'ら','り','る','れ','ろ','わ','を','ん','っ','ゃ','ゅ','ょ','ア','イ','ウ','エ',
179    'オ','カ','キ','ク','ケ','コ','サ','シ','ス','セ','ソ','タ','チ','ツ','テ','ト',
180    'ナ','ニ','ヌ','ネ','ノ','ハ','ヒ','フ','ヘ','ホ','マ','ミ','ム','メ','モ','ヤ',
181    'ユ','ヨ','ラ','リ','ル','レ','ロ','ワ','ヲ','ン','ッ','ャ','ュ','ョ','◜','◝'
182]
183assert len(k_charset) == 0x100
184
185# maps unicode characters or 2-char-strings to pico8 char index
186k_charset_map = {ch: i for i, ch in enumerate(k_charset)}
187
188k_unicap_chars = ['𝘢','𝘣','𝘤','𝘥','𝘦','𝘧','𝘨','𝘩','𝘪','𝘫','𝘬','𝘭','𝘮','𝘯','𝘰','𝘱','𝘲','𝘳','𝘴','𝘵','𝘶','𝘷','𝘸','𝘹','𝘺','𝘻']
189
190k_charset_map.update((ch, i) for i, ch in enumerate(k_unicap_chars, start=ord('A')))
191
192# a variant of the pico8 character set that uses unicode italics for capital characters (used by pico8 for copy/paste)
193k_unicap_charset = k_charset[:ord('A')] + k_unicap_chars + k_charset[ord('Z')+1:]
194assert len(k_unicap_charset) == 0x100
195
196class p8str:
197    """A string where each character is between '\0' and '\xff' and represents
198       the corresponding pico8 character.
199       Currently, this isn't actually a real type but a convention on how python's `str` is used -
200       use `to_p8str` and `from_p8str` (or `encode_p8str` and `decode_p8str`) instead of this class"""
201
202def to_p8str(text):
203    """Convert a unicode string to a pico8 string"""
204    result = []
205    ignore_next = False
206    for i, ch in enumerate(text):
207        if ord(ch) < 0x80:
208            result.append(ch)
209        elif ch in k_charset_map:
210            result.append(chr(k_charset_map[ch]))
211        elif ignore_next:
212            ignore_next = False
213            continue
214        elif (chpair := ch + str_get(text, i + 1, '')) in k_charset_map:
215            result.append(chr(k_charset_map[chpair]))
216            ignore_next = True
217        else:
218            # pico8 just reinterprets characters it doesn't understand as bytes
219            for byte in ch.encode(errors="surrogateescape"):
220                result.append(chr(byte))
221    return "".join(result)
222
223def from_p8str(text, unicaps=False):
224    """Convert a pico8 string to a unicode string. unicaps determines whether to use unicode italics for capital letters"""
225    charset = k_unicap_charset if unicaps else k_charset
226    return "".join(charset[ord(ch)] for ch in text)
227
228def encode_p8str(text):
229    """Encode a pico8 string into bytes"""
230    return bytes(ord(ch) for ch in text)
231
232def decode_p8str(bytes):
233    """Decodes bytes into a pico8 string"""
234    return "".join(chr(b) for b in bytes)
235
236to_pico_chars = to_p8str ; """@private legacy name"""
237from_pico_chars = from_p8str ; """@private legacy name"""
238
239# luastr - uses python's standard surrogate scheme to handle non-unicode chars
240
241def encode_luastr(text):
242    return text.encode(errors="surrogateescape")
243
244def decode_luastr(bytes):
245    return bytes.decode(errors="surrogateescape")
246
247# langstr - p8str or luastr
248# (in practice, picotron also uses p8scii, but at a 'higher level' than pico8 does)
249
250def to_langstr(text, lang):
251    if lang == Language.pico8:
252        return to_p8str(text)
253    else:
254        return text # already valid
255    
256def from_langstr(text, lang):
257    if lang == Language.pico8:
258        return from_p8str(text)
259    else:
260        return text # up to caller to properly handle utf errors
261
262class fixnum:
263    """An integer representing a 16.16 pico8 fixed-point number
264       Currently, this isn't actually a real type but a convention on how python's `int` is used - 
265       use `num_to_fixnum`, `fixnum_to_num`, etc"""
266
267k_fixnum_mask = 0xffffffff
268
269def num_to_fixnum(value):
270    """convert a python int or real to a fixnum"""
271    return int(value * (1 << 16)) & k_fixnum_mask
272
273def fixnum_is_negative(value):
274    """Return whether the fixnum is negative"""
275    return bool(value & 0x80000000)
276
277def fixnum_to_num(value):
278    """convert a fixnum to a python int or real"""
279    neg = fixnum_is_negative(value)
280    if neg:
281        value = (-value) & k_fixnum_mask
282    if value & 0xffff:
283        value /= (1 << 16)
284    else:
285        value >>= 16 # preserve int-ness
286    return -value if neg else value
287
288def fixnum_is_whole(value):
289    return (value & 0xffff) == 0
290
291def fixnum_to_whole(value):
292    return value >> 16
293
294def fixnum_to_signed(value):
295    if value & 0x80000000:
296        value -= 0x100000000
297    return value
298
299def is_signed_fixnum_in_range(value):
300    return -0x80000000 <= value < 0x80000000
301
302# luaint - a signed 64-bit integer, as supported by lua 5.4
303
304k_luaint_mask = 0xffffffffffffffff
305
306def num_to_luaint(value):
307    value &= k_luaint_mask
308    if value & 0x8000000000000000:
309        value -= 0x10000000000000000
310    return value
311
312def is_luaint_in_range(value):
313    return -0x8000000000000000 <= value <= 0x7fffffffffffffff
314
315# floats are represented as-is, but here are some utils
316
317def float_is_negative(value):
318    return math.copysign(1.0, value) < 0
319
320def float_is_negzero(value):
321    return value == 0 and float_is_negative(value)
322
323# pico-8 versions
324
325k_version_tuples = {
326    28: (0,2,0,0),
327    29: (0,2,1,0),
328    30: (0,2,2,0),
329    31: (0,2,2,1),
330    32: (0,2,2,2),
331    33: (0,2,3,0),
332    34: (0,2,4,0),
333    35: (0,2,4,1),
334    36: (0,2,4,2),
335    37: (0,2,5,0),
336    38: (0,2,5,2),
337    39: (0,2,5,4),
338    40: (0,2,5,5),
339    41: (0,2,5,6),
340    42: (0,2,6,1),
341    43: (0,2,7,0),
342}
343
344def get_default_pico8_version():
345    """The default pico8 version we generate (not necessarily the latest we support)"""
346    version_id = 42 # TODO - update as newer versions get more common
347    return maybe_int(os.getenv("PICO8_VERSION_ID"), version_id)
348
349def get_latest_pico8_version():
350    """The latest pico8 version we support"""
351    if os.getenv("PICO8_VERSION_LATEST_IS_DEFAULT"): # for tests
352        return get_default_pico8_version()
353    else:
354        return max(k_version_tuples)
355
356def get_default_platform():
357    """The default platform we generate"""
358    # (there's also 'E' - see format_platform)
359    platform = 'w' if os.name == 'nt' else 'x' if sys.platform == 'darwin' else 'l'
360    return os.getenv("PICO8_PLATFORM_CHAR", platform)
361
362def format_platform(platform):
363    """given a platform char, return a description of the platform"""
364    if platform == 'w':
365        return '[w]indows'
366    elif platform == 'x':
367        return 'macos[x]'
368    elif platform == 'l':
369        return '[l]inux'
370    elif platform == 'E':
371        return '[E]mscripten' # or [E]ducation?
372    else:
373        return 'platform=[%s]' % platform
374
375def get_pico8_version_tuple(id):
376    """Maps a pico8 version id to a tuple representing the actual version (e.g. (0,2,4,1) is v0.2.4b)"""
377    version = k_version_tuples.get(id)
378    if version is None:
379        if id >= 28:
380            eprint(f"warning - unknown version id {id}, outputting wrong version number (should be benign)")
381            version = k_version_tuples.get(get_default_pico8_version(), (0,0,0,0)) # better than nothing?
382        elif id >= 19:
383            version = (0,2,0,0) # early 0.2.0 betas?
384        elif id >= 8:
385            version = (0,1,5+id,0) # 13 .. 23
386        else:
387            version = (0,0,0,0)
388    return version
389
390def format_pico8_version(tuple):
391    """given a version id, return the textual form of the pico8 version"""
392    if tuple[1] >= 2:
393        letter = string.ascii_lowercase[tuple[3]] if 26 > tuple[3] > 0 else ""
394        return "v%d.%d.%d%s" % (tuple[0], tuple[1], tuple[2], letter)
395    else:
396        return "pre-v0.2.0" # the tuple doesn't correspond to the real version here (TBD - find out the old versions per version id)
397
398def parse_pico8_version(str):
399    """parse a textual form of the pico8 version into a version id"""
400    match = re.fullmatch(r"v(\d+).(\d+).(\d+)([a-z]?)", str)
401    if match:
402        tuple = match.groups()
403        letter_idx = string.ascii_lowercase.index(tuple[3]) if tuple[3] else 0
404        tuple = (int(tuple[0]), int(tuple[1]), int(tuple[2]), letter_idx)
405        
406        if tuple[1] < 2:
407            throw("pre-v0.2.0 versions are not supported - you must specify the raw numeric version if you know it") # (same TBD as above)
408        max_key = -1
409        for key, value in k_version_tuples.items():
410            if tuple >= value:
411                max_key = max(max_key, key)
412        if k_version_tuples[max_key] != tuple:
413            if max_key == get_latest_pico8_version ():
414                throw(f"the version {str} is too new and not known yet - you must specify the raw number version if you know it")
415            else:
416                eprint(f"the version {str} has been changed to {format_pico8_version(k_version_tuples[max_key])} - the closest known version with its own version id")
417        return max_key
418    else:
419        key = maybe_int(str)
420        if key is None:
421            throw(f"the version {str} is not in valid format (should be e.g. v0.2.6b)")
422        return key
423
424def get_res_path():
425    return path_dirname(path_resolve(__file__))
class Language(utils.Enum):
 7class Language(Enum):
 8    """The supported lua languages"""
 9
10    pico8 = picotron = ...

The supported lua languages

Language(value)
172        def __init__(m, value):
173            if value in full_value_name_map:
174                m.value = value
175            elif value in full_name_value_map:
176                m.value = full_name_value_map[value]
177            else:
178                raise ValueError(f"{value} not value of {cls_name}")
value
pico8 = Language.pico8
picotron = Language.picotron
class Memory(builtins.bytearray):
12class Memory(bytearray):
13    """A pico8 memory block - a bytearray with some convenience functions like get/set16, get/set4, etc."""
14
15    def copy(m):
16        return Memory(m)
17
18    def replace(m, src):
19        m[:] = src
20    
21    def clear(m):
22        m.fill8(0, 0, len(m))
23
24    def size(m):
25        return len(m)
26
27    def get8(m, i):
28        return m[i]
29
30    def set8(m, i, v):
31        m[i] = v
32        
33    def get_block(m, start, size):
34        return m[start:start+size]
35        
36    def set_block(m, start, src):
37        m[start:start+len(src)] = src
38
39    def copy8(m, dest, src, size, src_memory = None):
40        m.set_block(dest, (src_memory or m).get_block(src, size))
41    
42    def copyfrom8(m, addr, size, src_memory):
43        m.copy8(addr, addr, size, src_memory)
44        
45    def fill8(m, dest, value, size):
46        m.set_block(dest, bytearray((value,)) * size)
47        
48    def cmpeq8(m, src1, src2, size, other_memory = None):
49        return m.get_block(src1, size) == (other_memory or m).get_block(src2, size)
50    
51    def cmpeqwith8(m, src, size, other_memory = None):
52        return m.cmpeq8(src, src, size, other_memory)
53        
54    def get16(m, i):
55        return m.get8(i) | (m.get8(i + 1) << 8)
56    
57    def set16(m, i, v):
58        m.set8(i, v & 0xff)
59        m.set8(i + 1, (v >> 8) & 0xff)
60
61    def get32(m, i):
62        return m.get16(i) | (m.get16(i + 2) << 16)
63
64    def set32(m, i, v):
65        m.set16(i, v & 0xffff)
66        m.set16(i + 2, (v >> 16) & 0xffff)
67        
68    def get8_bits(m, i, shift, mask):
69        return (m.get8(i) >> shift) & mask
70
71    def set8_bits(m, i, shift, mask, v):
72        m.set8(i, (m.get8(i) & ~(mask << shift)) | ((v & mask) << shift))
73
74    def get4(m, ix):
75        i, high = ix
76        return m.get8_bits(i, 4 if high else 0, 0xf)
77
78    def set4(m, ix, value):
79        i, high = ix
80        m.set8_bits(i, 4 if high else 0, 0xf, value)

A pico8 memory block - a bytearray with some convenience functions like get/set16, get/set4, etc.

def copy(m):
15    def copy(m):
16        return Memory(m)

Return a copy of B.

def replace(m, src):
18    def replace(m, src):
19        m[:] = src

Return a copy with all occurrences of substring old replaced by new.

count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

def clear(m):
21    def clear(m):
22        m.fill8(0, 0, len(m))

Remove all items from the bytearray.

def size(m):
24    def size(m):
25        return len(m)
def get8(m, i):
27    def get8(m, i):
28        return m[i]
def set8(m, i, v):
30    def set8(m, i, v):
31        m[i] = v
def get_block(m, start, size):
33    def get_block(m, start, size):
34        return m[start:start+size]
def set_block(m, start, src):
36    def set_block(m, start, src):
37        m[start:start+len(src)] = src
def copy8(m, dest, src, size, src_memory=None):
39    def copy8(m, dest, src, size, src_memory = None):
40        m.set_block(dest, (src_memory or m).get_block(src, size))
def copyfrom8(m, addr, size, src_memory):
42    def copyfrom8(m, addr, size, src_memory):
43        m.copy8(addr, addr, size, src_memory)
def fill8(m, dest, value, size):
45    def fill8(m, dest, value, size):
46        m.set_block(dest, bytearray((value,)) * size)
def cmpeq8(m, src1, src2, size, other_memory=None):
48    def cmpeq8(m, src1, src2, size, other_memory = None):
49        return m.get_block(src1, size) == (other_memory or m).get_block(src2, size)
def cmpeqwith8(m, src, size, other_memory=None):
51    def cmpeqwith8(m, src, size, other_memory = None):
52        return m.cmpeq8(src, src, size, other_memory)
def get16(m, i):
54    def get16(m, i):
55        return m.get8(i) | (m.get8(i + 1) << 8)
def set16(m, i, v):
57    def set16(m, i, v):
58        m.set8(i, v & 0xff)
59        m.set8(i + 1, (v >> 8) & 0xff)
def get32(m, i):
61    def get32(m, i):
62        return m.get16(i) | (m.get16(i + 2) << 16)
def set32(m, i, v):
64    def set32(m, i, v):
65        m.set16(i, v & 0xffff)
66        m.set16(i + 2, (v >> 16) & 0xffff)
def get8_bits(m, i, shift, mask):
68    def get8_bits(m, i, shift, mask):
69        return (m.get8(i) >> shift) & mask
def set8_bits(m, i, shift, mask, v):
71    def set8_bits(m, i, shift, mask, v):
72        m.set8(i, (m.get8(i) & ~(mask << shift)) | ((v & mask) << shift))
def get4(m, ix):
74    def get4(m, ix):
75        i, high = ix
76        return m.get8_bits(i, 4 if high else 0, 0xf)
def set4(m, ix, value):
78    def set4(m, ix, value):
79        i, high = ix
80        m.set8_bits(i, 4 if high else 0, 0xf, value)
k_mem_sprites_addr = 0
k_mem_map_addr = 8192
k_mem_flag_addr = 12288
k_mem_music_addr = 12544
k_mem_sfx_addr = 12800
def mem_sprite_addr(x, y):
88def mem_sprite_addr(x, y):
89    """Convert an (x,y) coord to a sprite address, for use with Memory.get/set4"""
90    return k_mem_sprites_addr + y * 0x40 + (x >> 1), (x & 1)

Convert an (x,y) coord to a sprite address, for use with Memory.get/set4

def mem_map_addr(x, y):
92def mem_map_addr(x, y):
93    """Convert an (x,y) coord to a map address"""
94    if y >= 0x20: y -= 0x40  # in effect
95    return k_mem_map_addr + y * 0x80 + x

Convert an (x,y) coord to a map address

def mem_flag_addr(tile, y=0):
97def mem_flag_addr(tile, y=0):
98    """Convert a tile number to the sprite's flags address"""
99    return k_mem_flag_addr + y * 0x80 + tile

Convert a tile number to the sprite's flags address

def mem_music_addr(music, ch):
101def mem_music_addr(music, ch):
102    """Returns the address of the given channel of the given music"""
103    return k_mem_music_addr + music * 0x4 + ch

Returns the address of the given channel of the given music

def mem_sfx_addr(sound, note):
105def mem_sfx_addr(sound, note):
106    """Return the address of the given note of the given sfx"""
107    return k_mem_sfx_addr + sound * 0x44 + note * 0x2

Return the address of the given note of the given sfx

def mem_sfx_info_addr(sound, i):
109def mem_sfx_info_addr(sound, i):
110    """Return the address of the i-th info byte of the given sfx"""
111    return mem_sfx_addr(sound, 0x20) + i

Return the address of the i-th info byte of the given sfx

def mem_create_rom():
113def mem_create_rom():
114    rom = Memory(k_rom_size)
115    for i in range(0x40):
116        rom.set8(mem_sfx_info_addr(i, 1), 0x1 if i == 0 else 0x10)
117        for ch in range(4):
118            rom.set8(mem_music_addr(i, ch), 0x41 + ch)
119    return rom
k_rom_size = 17152
k_cart_size = 32768
k_code_size = 15616
k_trailer_size = 32
k_url_size = 2040
k_url_prefix_size = 4
k_palette = [Color(r=0, g=0, b=0, a=255), Color(r=29, g=43, b=83, a=255), Color(r=126, g=37, b=83, a=255), Color(r=0, g=135, b=81, a=255), Color(r=171, g=82, b=54, a=255), Color(r=95, g=87, b=79, a=255), Color(r=194, g=195, b=199, a=255), Color(r=255, g=241, b=232, a=255), Color(r=255, g=0, b=77, a=255), Color(r=255, g=163, b=0, a=255), Color(r=255, g=236, b=39, a=255), Color(r=0, g=228, b=54, a=255), Color(r=41, g=173, b=255, a=255), Color(r=131, g=118, b=156, a=255), Color(r=255, g=119, b=168, a=255), Color(r=255, g=204, b=170, a=255), Color(r=41, g=24, b=20, a=255), Color(r=17, g=29, b=53, a=255), Color(r=66, g=33, b=54, a=255), Color(r=18, g=83, b=89, a=255), Color(r=116, g=47, b=41, a=255), Color(r=73, g=51, b=59, a=255), Color(r=162, g=136, b=121, a=255), Color(r=243, g=239, b=125, a=255), Color(r=190, g=18, b=80, a=255), Color(r=255, g=108, b=36, a=255), Color(r=168, g=231, b=46, a=255), Color(r=0, g=181, b=67, a=255), Color(r=6, g=90, b=181, a=255), Color(r=117, g=70, b=101, a=255), Color(r=255, g=110, b=89, a=255), Color(r=255, g=157, b=129, a=255)]
k_charset = ['\x00', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '\t', '\n', 'ᵇ', 'ᶜ', '\r', 'ᵉ', 'ᶠ', '▮', '■', '□', '⁙', '⁘', '‖', '◀', '▶', '「', '」', '¥', '•', '、', '。', '゛', '゜', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '○', '█', '▒', '🐱', '⬇️', '░', '✽', '●', '♥', '☉', '웃', '⌂', '⬅️', '😐', '♪', '🅾️', '◆', '…', '➡️', '★', '⧗', '⬆️', 'ˇ', '∧', '❎', '▤', '▥', 'あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し', 'す', 'せ', 'そ', 'た', 'ち', 'つ', 'て', 'と', 'な', 'に', 'ぬ', 'ね', 'の', 'は', 'ひ', 'ふ', 'へ', 'ほ', 'ま', 'み', 'む', 'め', 'も', 'や', 'ゆ', 'よ', 'ら', 'り', 'る', 'れ', 'ろ', 'わ', 'を', 'ん', 'っ', 'ゃ', 'ゅ', 'ょ', 'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク', 'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ヲ', 'ン', 'ッ', 'ャ', 'ュ', 'ョ', '◜', '◝']
k_charset_map = {'\x00': 0, '¹': 1, '²': 2, '³': 3, '⁴': 4, '⁵': 5, '⁶': 6, '⁷': 7, '⁸': 8, '\t': 9, '\n': 10, 'ᵇ': 11, 'ᶜ': 12, '\r': 13, 'ᵉ': 14, 'ᶠ': 15, '▮': 16, '■': 17, '□': 18, '⁙': 19, '⁘': 20, '‖': 21, '◀': 22, '▶': 23, '「': 24, '」': 25, '¥': 26, '•': 27, '、': 28, '。': 29, '゛': 30, '゜': 31, ' ': 32, '!': 33, '"': 34, '#': 35, '$': 36, '%': 37, '&': 38, "'": 39, '(': 40, ')': 41, '*': 42, '+': 43, ',': 44, '-': 45, '.': 46, '/': 47, '0': 48, '1': 49, '2': 50, '3': 51, '4': 52, '5': 53, '6': 54, '7': 55, '8': 56, '9': 57, ':': 58, ';': 59, '<': 60, '=': 61, '>': 62, '?': 63, '@': 64, 'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70, 'G': 71, 'H': 72, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'M': 77, 'N': 78, 'O': 79, 'P': 80, 'Q': 81, 'R': 82, 'S': 83, 'T': 84, 'U': 85, 'V': 86, 'W': 87, 'X': 88, 'Y': 89, 'Z': 90, '[': 91, '\\': 92, ']': 93, '^': 94, '_': 95, '`': 96, 'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101, 'f': 102, 'g': 103, 'h': 104, 'i': 105, 'j': 106, 'k': 107, 'l': 108, 'm': 109, 'n': 110, 'o': 111, 'p': 112, 'q': 113, 'r': 114, 's': 115, 't': 116, 'u': 117, 'v': 118, 'w': 119, 'x': 120, 'y': 121, 'z': 122, '{': 123, '|': 124, '}': 125, '~': 126, '○': 127, '█': 128, '▒': 129, '🐱': 130, '⬇️': 131, '░': 132, '✽': 133, '●': 134, '♥': 135, '☉': 136, '웃': 137, '⌂': 138, '⬅️': 139, '😐': 140, '♪': 141, '🅾️': 142, '◆': 143, '…': 144, '➡️': 145, '★': 146, '⧗': 147, '⬆️': 148, 'ˇ': 149, '∧': 150, '❎': 151, '▤': 152, '▥': 153, 'あ': 154, 'い': 155, 'う': 156, 'え': 157, 'お': 158, 'か': 159, 'き': 160, 'く': 161, 'け': 162, 'こ': 163, 'さ': 164, 'し': 165, 'す': 166, 'せ': 167, 'そ': 168, 'た': 169, 'ち': 170, 'つ': 171, 'て': 172, 'と': 173, 'な': 174, 'に': 175, 'ぬ': 176, 'ね': 177, 'の': 178, 'は': 179, 'ひ': 180, 'ふ': 181, 'へ': 182, 'ほ': 183, 'ま': 184, 'み': 185, 'む': 186, 'め': 187, 'も': 188, 'や': 189, 'ゆ': 190, 'よ': 191, 'ら': 192, 'り': 193, 'る': 194, 'れ': 195, 'ろ': 196, 'わ': 197, 'を': 198, 'ん': 199, 'っ': 200, 'ゃ': 201, 'ゅ': 202, 'ょ': 203, 'ア': 204, 'イ': 205, 'ウ': 206, 'エ': 207, 'オ': 208, 'カ': 209, 'キ': 210, 'ク': 211, 'ケ': 212, 'コ': 213, 'サ': 214, 'シ': 215, 'ス': 216, 'セ': 217, 'ソ': 218, 'タ': 219, 'チ': 220, 'ツ': 221, 'テ': 222, 'ト': 223, 'ナ': 224, 'ニ': 225, 'ヌ': 226, 'ネ': 227, 'ノ': 228, 'ハ': 229, 'ヒ': 230, 'フ': 231, 'ヘ': 232, 'ホ': 233, 'マ': 234, 'ミ': 235, 'ム': 236, 'メ': 237, 'モ': 238, 'ヤ': 239, 'ユ': 240, 'ヨ': 241, 'ラ': 242, 'リ': 243, 'ル': 244, 'レ': 245, 'ロ': 246, 'ワ': 247, 'ヲ': 248, 'ン': 249, 'ッ': 250, 'ャ': 251, 'ュ': 252, 'ョ': 253, '◜': 254, '◝': 255, '𝘢': 65, '𝘣': 66, '𝘤': 67, '𝘥': 68, '𝘦': 69, '𝘧': 70, '𝘨': 71, '𝘩': 72, '𝘪': 73, '𝘫': 74, '𝘬': 75, '𝘭': 76, '𝘮': 77, '𝘯': 78, '𝘰': 79, '𝘱': 80, '𝘲': 81, '𝘳': 82, '𝘴': 83, '𝘵': 84, '𝘶': 85, '𝘷': 86, '𝘸': 87, '𝘹': 88, '𝘺': 89, '𝘻': 90}
k_unicap_chars = ['𝘢', '𝘣', '𝘤', '𝘥', '𝘦', '𝘧', '𝘨', '𝘩', '𝘪', '𝘫', '𝘬', '𝘭', '𝘮', '𝘯', '𝘰', '𝘱', '𝘲', '𝘳', '𝘴', '𝘵', '𝘶', '𝘷', '𝘸', '𝘹', '𝘺', '𝘻']
k_unicap_charset = ['\x00', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '\t', '\n', 'ᵇ', 'ᶜ', '\r', 'ᵉ', 'ᶠ', '▮', '■', '□', '⁙', '⁘', '‖', '◀', '▶', '「', '」', '¥', '•', '、', '。', '゛', '゜', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', '𝘢', '𝘣', '𝘤', '𝘥', '𝘦', '𝘧', '𝘨', '𝘩', '𝘪', '𝘫', '𝘬', '𝘭', '𝘮', '𝘯', '𝘰', '𝘱', '𝘲', '𝘳', '𝘴', '𝘵', '𝘶', '𝘷', '𝘸', '𝘹', '𝘺', '𝘻', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '○', '█', '▒', '🐱', '⬇️', '░', '✽', '●', '♥', '☉', '웃', '⌂', '⬅️', '😐', '♪', '🅾️', '◆', '…', '➡️', '★', '⧗', '⬆️', 'ˇ', '∧', '❎', '▤', '▥', 'あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し', 'す', 'せ', 'そ', 'た', 'ち', 'つ', 'て', 'と', 'な', 'に', 'ぬ', 'ね', 'の', 'は', 'ひ', 'ふ', 'へ', 'ほ', 'ま', 'み', 'む', 'め', 'も', 'や', 'ゆ', 'よ', 'ら', 'り', 'る', 'れ', 'ろ', 'わ', 'を', 'ん', 'っ', 'ゃ', 'ゅ', 'ょ', 'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク', 'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ヲ', 'ン', 'ッ', 'ャ', 'ュ', 'ョ', '◜', '◝']
class p8str:
197class p8str:
198    """A string where each character is between '\0' and '\xff' and represents
199       the corresponding pico8 character.
200       Currently, this isn't actually a real type but a convention on how python's `str` is used -
201       use `to_p8str` and `from_p8str` (or `encode_p8str` and `decode_p8str`) instead of this class"""

A string where each character is between '' and 'ÿ' and represents the corresponding pico8 character. Currently, this isn't actually a real type but a convention on how python's str is used - use to_p8str and from_p8str (or encode_p8str and decode_p8str) instead of this class

def to_p8str(text):
203def to_p8str(text):
204    """Convert a unicode string to a pico8 string"""
205    result = []
206    ignore_next = False
207    for i, ch in enumerate(text):
208        if ord(ch) < 0x80:
209            result.append(ch)
210        elif ch in k_charset_map:
211            result.append(chr(k_charset_map[ch]))
212        elif ignore_next:
213            ignore_next = False
214            continue
215        elif (chpair := ch + str_get(text, i + 1, '')) in k_charset_map:
216            result.append(chr(k_charset_map[chpair]))
217            ignore_next = True
218        else:
219            # pico8 just reinterprets characters it doesn't understand as bytes
220            for byte in ch.encode(errors="surrogateescape"):
221                result.append(chr(byte))
222    return "".join(result)

Convert a unicode string to a pico8 string

def from_p8str(text, unicaps=False):
224def from_p8str(text, unicaps=False):
225    """Convert a pico8 string to a unicode string. unicaps determines whether to use unicode italics for capital letters"""
226    charset = k_unicap_charset if unicaps else k_charset
227    return "".join(charset[ord(ch)] for ch in text)

Convert a pico8 string to a unicode string. unicaps determines whether to use unicode italics for capital letters

def encode_p8str(text):
229def encode_p8str(text):
230    """Encode a pico8 string into bytes"""
231    return bytes(ord(ch) for ch in text)

Encode a pico8 string into bytes

def decode_p8str(bytes):
233def decode_p8str(bytes):
234    """Decodes bytes into a pico8 string"""
235    return "".join(chr(b) for b in bytes)

Decodes bytes into a pico8 string

def encode_luastr(text):
242def encode_luastr(text):
243    return text.encode(errors="surrogateescape")
def decode_luastr(bytes):
245def decode_luastr(bytes):
246    return bytes.decode(errors="surrogateescape")
def to_langstr(text, lang):
251def to_langstr(text, lang):
252    if lang == Language.pico8:
253        return to_p8str(text)
254    else:
255        return text # already valid
def from_langstr(text, lang):
257def from_langstr(text, lang):
258    if lang == Language.pico8:
259        return from_p8str(text)
260    else:
261        return text # up to caller to properly handle utf errors
class fixnum:
263class fixnum:
264    """An integer representing a 16.16 pico8 fixed-point number
265       Currently, this isn't actually a real type but a convention on how python's `int` is used - 
266       use `num_to_fixnum`, `fixnum_to_num`, etc"""

An integer representing a 16.16 pico8 fixed-point number Currently, this isn't actually a real type but a convention on how python's int is used - use num_to_fixnum, fixnum_to_num, etc

k_fixnum_mask = 4294967295
def num_to_fixnum(value):
270def num_to_fixnum(value):
271    """convert a python int or real to a fixnum"""
272    return int(value * (1 << 16)) & k_fixnum_mask

convert a python int or real to a fixnum

def fixnum_is_negative(value):
274def fixnum_is_negative(value):
275    """Return whether the fixnum is negative"""
276    return bool(value & 0x80000000)

Return whether the fixnum is negative

def fixnum_to_num(value):
278def fixnum_to_num(value):
279    """convert a fixnum to a python int or real"""
280    neg = fixnum_is_negative(value)
281    if neg:
282        value = (-value) & k_fixnum_mask
283    if value & 0xffff:
284        value /= (1 << 16)
285    else:
286        value >>= 16 # preserve int-ness
287    return -value if neg else value

convert a fixnum to a python int or real

def fixnum_is_whole(value):
289def fixnum_is_whole(value):
290    return (value & 0xffff) == 0
def fixnum_to_whole(value):
292def fixnum_to_whole(value):
293    return value >> 16
def fixnum_to_signed(value):
295def fixnum_to_signed(value):
296    if value & 0x80000000:
297        value -= 0x100000000
298    return value
def is_signed_fixnum_in_range(value):
300def is_signed_fixnum_in_range(value):
301    return -0x80000000 <= value < 0x80000000
k_luaint_mask = 18446744073709551615
def num_to_luaint(value):
307def num_to_luaint(value):
308    value &= k_luaint_mask
309    if value & 0x8000000000000000:
310        value -= 0x10000000000000000
311    return value
def is_luaint_in_range(value):
313def is_luaint_in_range(value):
314    return -0x8000000000000000 <= value <= 0x7fffffffffffffff
def float_is_negative(value):
318def float_is_negative(value):
319    return math.copysign(1.0, value) < 0
def float_is_negzero(value):
321def float_is_negzero(value):
322    return value == 0 and float_is_negative(value)
k_version_tuples = {28: (0, 2, 0, 0), 29: (0, 2, 1, 0), 30: (0, 2, 2, 0), 31: (0, 2, 2, 1), 32: (0, 2, 2, 2), 33: (0, 2, 3, 0), 34: (0, 2, 4, 0), 35: (0, 2, 4, 1), 36: (0, 2, 4, 2), 37: (0, 2, 5, 0), 38: (0, 2, 5, 2), 39: (0, 2, 5, 4), 40: (0, 2, 5, 5), 41: (0, 2, 5, 6), 42: (0, 2, 6, 1), 43: (0, 2, 7, 0)}
def get_default_pico8_version():
345def get_default_pico8_version():
346    """The default pico8 version we generate (not necessarily the latest we support)"""
347    version_id = 42 # TODO - update as newer versions get more common
348    return maybe_int(os.getenv("PICO8_VERSION_ID"), version_id)

The default pico8 version we generate (not necessarily the latest we support)

def get_latest_pico8_version():
350def get_latest_pico8_version():
351    """The latest pico8 version we support"""
352    if os.getenv("PICO8_VERSION_LATEST_IS_DEFAULT"): # for tests
353        return get_default_pico8_version()
354    else:
355        return max(k_version_tuples)

The latest pico8 version we support

def get_default_platform():
357def get_default_platform():
358    """The default platform we generate"""
359    # (there's also 'E' - see format_platform)
360    platform = 'w' if os.name == 'nt' else 'x' if sys.platform == 'darwin' else 'l'
361    return os.getenv("PICO8_PLATFORM_CHAR", platform)

The default platform we generate

def format_platform(platform):
363def format_platform(platform):
364    """given a platform char, return a description of the platform"""
365    if platform == 'w':
366        return '[w]indows'
367    elif platform == 'x':
368        return 'macos[x]'
369    elif platform == 'l':
370        return '[l]inux'
371    elif platform == 'E':
372        return '[E]mscripten' # or [E]ducation?
373    else:
374        return 'platform=[%s]' % platform

given a platform char, return a description of the platform

def get_pico8_version_tuple(id):
376def get_pico8_version_tuple(id):
377    """Maps a pico8 version id to a tuple representing the actual version (e.g. (0,2,4,1) is v0.2.4b)"""
378    version = k_version_tuples.get(id)
379    if version is None:
380        if id >= 28:
381            eprint(f"warning - unknown version id {id}, outputting wrong version number (should be benign)")
382            version = k_version_tuples.get(get_default_pico8_version(), (0,0,0,0)) # better than nothing?
383        elif id >= 19:
384            version = (0,2,0,0) # early 0.2.0 betas?
385        elif id >= 8:
386            version = (0,1,5+id,0) # 13 .. 23
387        else:
388            version = (0,0,0,0)
389    return version

Maps a pico8 version id to a tuple representing the actual version (e.g. (0,2,4,1) is v0.2.4b)

def format_pico8_version(tuple):
391def format_pico8_version(tuple):
392    """given a version id, return the textual form of the pico8 version"""
393    if tuple[1] >= 2:
394        letter = string.ascii_lowercase[tuple[3]] if 26 > tuple[3] > 0 else ""
395        return "v%d.%d.%d%s" % (tuple[0], tuple[1], tuple[2], letter)
396    else:
397        return "pre-v0.2.0" # the tuple doesn't correspond to the real version here (TBD - find out the old versions per version id)

given a version id, return the textual form of the pico8 version

def parse_pico8_version(str):
399def parse_pico8_version(str):
400    """parse a textual form of the pico8 version into a version id"""
401    match = re.fullmatch(r"v(\d+).(\d+).(\d+)([a-z]?)", str)
402    if match:
403        tuple = match.groups()
404        letter_idx = string.ascii_lowercase.index(tuple[3]) if tuple[3] else 0
405        tuple = (int(tuple[0]), int(tuple[1]), int(tuple[2]), letter_idx)
406        
407        if tuple[1] < 2:
408            throw("pre-v0.2.0 versions are not supported - you must specify the raw numeric version if you know it") # (same TBD as above)
409        max_key = -1
410        for key, value in k_version_tuples.items():
411            if tuple >= value:
412                max_key = max(max_key, key)
413        if k_version_tuples[max_key] != tuple:
414            if max_key == get_latest_pico8_version ():
415                throw(f"the version {str} is too new and not known yet - you must specify the raw number version if you know it")
416            else:
417                eprint(f"the version {str} has been changed to {format_pico8_version(k_version_tuples[max_key])} - the closest known version with its own version id")
418        return max_key
419    else:
420        key = maybe_int(str)
421        if key is None:
422            throw(f"the version {str} is not in valid format (should be e.g. v0.2.6b)")
423        return key

parse a textual form of the pico8 version into a version id

def get_res_path():
425def get_res_path():
426    return path_dirname(path_resolve(__file__))