pico_cart

Functions for working with pico8 carts (See Cart, read_cart, write_cart)

  1"""Functions for working with pico8 carts (See `Cart`, `read_cart`, `write_cart`)"""
  2
  3from utils import *
  4from media_utils import Image, PixelFormat
  5from pico_defs import *
  6from pico_compress import compress_code, uncompress_code, get_compressed_size, print_size
  7import hashlib, base64
  8
  9class CartFormat(Enum):
 10    """An enum representing the supported cart formats"""
 11    auto = p8 = png = lua = rom = tiny_rom = clip = url = code = js = pod = bin = dat = label = spritesheet = ...
 12
 13    @property
 14    def is_input(m):
 15        return m != m.bin
 16    @property
 17    def is_output(m):
 18        return m not in (m.auto, m.dat)
 19    @property
 20    def is_ext(m):
 21        return m not in (m.auto, m.tiny_rom, m.code, m.label, m.spritesheet)
 22    @property
 23    def is_src(m):
 24        return m in (m.p8, m.lua, m.code)
 25    @property
 26    def is_export(m):
 27        return m in (m.js, m.pod, m.bin, m.dat)
 28    @property
 29    def is_exposed(m):
 30        return m != m.code
 31    
 32    @classproperty
 33    def default_src(m):
 34        return m.p8
 35    @classproperty
 36    def default_dir(m):
 37        return None
 38
 39class Cart:
 40    """A pico8 cart, including its code (as a p8str), rom (as a Memory), and more"""
 41
 42    def __init__(m, code="", rom=None, label=None, path="", name=""):
 43        m.version_id = get_default_pico8_version()
 44        m.version_tuple = get_pico8_version_tuple(m.version_id)
 45        m.platform = get_default_platform()
 46        m.default_version = m.default_platform = True
 47        m.rom = rom.copy() if rom else mem_create_rom()
 48        m.path = path
 49        m.name = name if name else path_basename(path) if path else ""
 50        m.code = code
 51        m.code_map = ()
 52        m.code_rom = None
 53        m.label = label
 54        m.meta = defaultdict(list)
 55
 56    def copy(m):
 57        return deepcopy(m)
 58
 59    @property
 60    def title(m):
 61        """Returns the cart's title, as a p8str"""
 62        title_meta = m.meta.get("title")
 63        if title_meta is None:
 64            title = ""
 65            for line in m.code.split("\n", 2)[:2]: # (splitlines isn't appropriate for p8str)
 66                match = re.fullmatch(r"-- ?(.*)", line)
 67                if match:
 68                    title += match.group(1)
 69                title += "\n"
 70            return title.rstrip("\n")
 71        else:
 72            return "\n".join(to_p8str(line) for line in title_meta)
 73
 74    @title.setter
 75    def title(m, value):
 76        """Sets the cart's title, from a p8str"""
 77        m.meta["title"] = from_p8str(value).splitlines()
 78    
 79    def set_raw_title(m, title_lines):
 80        m.meta["title"] = title_lines
 81
 82    def set_code_without_title(m, code):
 83        old_title = m.title
 84        m.code = code
 85        if old_title != m.title:
 86            m.title = old_title
 87
 88    def set_version(m, id):
 89        m.version_id = id
 90        m.version_tuple = get_pico8_version_tuple(id)
 91        m.default_version = False
 92
 93def read_code_from_rom(r, keep_compression=False, **opts):
 94    code_rom = None
 95    if keep_compression:
 96        start_pos = r.pos()
 97        code_rom = Memory(k_code_size)
 98        code_rom.set_block(0, r.bytes(k_code_size, allow_eof=True))
 99        r.setpos(start_pos)
100
101    return uncompress_code(r, **opts), code_rom
102
103def read_cart_from_rom(buffer, path=None, allow_tiny=False, **opts):
104    cart = Cart(path=path)
105    
106    with BinaryReader(BytesIO(buffer), big_end = True) as r:
107        if r.len() < k_cart_size and allow_tiny: # tiny rom, code only
108            cart.code, cart.code_rom = read_code_from_rom(r, **opts)
109        
110        else:
111            cart.rom.replace(r.bytes(k_rom_size))
112            cart.code, cart.code_rom = read_code_from_rom(r, **opts)
113
114            r.setpos(k_cart_size)
115            if r.pos() < r.len():
116                cart.version_id = r.u8()
117                version = r.u8(), r.u8(), r.u8()
118                cart.platform = chr(r.u8())
119                cart.version_tuple = (*version, r.u8())
120                cart.default_version = cart.default_platform = False
121                hash = r.bytes(20)
122
123                if hash != bytes(20) and hash != hashlib.sha1(buffer[:k_cart_size]).digest():
124                    throw("corrupted cart (wrong hash)")
125
126    return cart
127
128def write_cart_to_rom(cart, with_trailer=False, keep_compression=False, **opts):
129    io = BytesIO(bytes(k_cart_size + (k_trailer_size if with_trailer else 0)))
130
131    with BinaryWriter(io, big_end = True) as w:
132        w.bytes(cart.rom)
133
134        if keep_compression and cart.code_rom != None:
135            w.bytes(cart.code_rom)
136        else:
137            compress_code(w, cart.code, **opts)
138
139        if with_trailer:
140            w.setpos(k_cart_size)
141            w.u8(cart.version_id)
142            w.u8(cart.version_tuple[0])
143            w.u8(cart.version_tuple[1])
144            w.u8(cart.version_tuple[2])
145            w.u8(ord(cart.platform))
146            w.u8(cart.version_tuple[3])
147            w.bytes(hashlib.sha1(io.getvalue()[:k_cart_size]).digest())
148
149        return io.getvalue()
150
151def write_cart_to_tiny_rom(cart, force_compress=False, keep_compression=False, **opts):
152    io = BytesIO()
153
154    with BinaryWriter(io, big_end = True) as w:
155        if keep_compression and cart.code_rom != None:
156            with BinaryReader(BytesIO(cart.code_rom), big_end = True) as code_r:
157                compressed_size = get_compressed_size(code_r)
158            
159            w.bytes(cart.code_rom.get_block(0, compressed_size))
160        else:
161            compress_code(w, cart.code, force_compress=True, **opts)
162
163            if len(io.getvalue()) > len(cart.code):
164                io = BytesIO(encode_p8str(cart.code))
165
166        return io.getvalue()
167
168k_cart_image_size = Point(160, 205)
169k_label_size = Point(128, 128)
170k_label_offset = Point(16, 24)
171k_title_offset = Point(18, 167)
172k_title_spacing = Point(0, 2)
173k_title_size = Point(31 * 4, 16)
174
175def palette_to_palmap(palette):
176    return {(c.r & ~3, c.g & ~3, c.b & ~3): i for i, c in enumerate(palette)}
177
178k_palette_rgb_6bpp_map = palette_to_palmap(k_palette)
179k_png_header = b"\x89PNG\r\n\x1a\n"
180k_qoi_header = b"qoif"
181
182def load_image_of_size(f, valid_size, format=PixelFormat.rgba8, is_qoi=False):
183    r = BinaryReader(f)
184    if is_qoi:
185        if r.bytes(4) != k_qoi_header:
186            throw("Not a valid qoi")
187        r.subpos(4)
188    else:
189        if r.bytes(8) != k_png_header:
190            throw("Not a valid png")
191        r.subpos(8)
192
193    image = Image.load(f, format)
194    if image.size != valid_size:
195        throw("Png has wrong size")
196
197    return image
198
199def find_best_in_palette_map(palmap, r, g, b):
200    min_delta, best_idx = math.inf, 0
201    for (tr, tg, tb), idx in palmap.items():
202        delta = abs(tr - r) + abs(tg - g) + abs(tb - b)
203        if delta < min_delta:
204            min_delta, best_idx = delta, idx
205    return best_idx
206
207def surface_pixels_to_screenshot(pixels, offset=Point.zero, palmap=k_palette_rgb_6bpp_map):
208    screenshot = MultidimArray(k_label_size, 0)
209
210    for y in range(k_label_size.y):
211        for x in range(k_label_size.x):
212            r, g, b, a = pixels[Point(x, y) + offset]
213            palidx = palmap.get((r & ~3, g & ~3, b & ~3))
214            if palidx is None:
215                palidx = find_best_in_palette_map(palmap, r, g, b)
216            screenshot[x, y] = palidx
217
218    return screenshot
219
220def read_cart_from_image(data, **opts):
221    image = load_image_of_size(BytesIO(data), k_cart_image_size)
222    width, height = image.size
223
224    data = bytearray()
225    pixels = image.pixels
226
227    for y in range(height):
228        for x in range(width):
229            r, g, b, a = pixels[x, y]
230            byte = ((b & 3) << 0) | ((g & 3) << 2) | ((r & 3) << 4) | ((a & 3) << 6)
231            data.append(byte)
232
233    cart = read_cart_from_rom(data, **opts)
234    cart.label = surface_pixels_to_screenshot(pixels, k_label_offset)
235    return cart
236
237def draw_text_on_image(image, text, offset, size, spacing=Point.zero):
238    with file_open(path_join(get_res_path(), "font.png")) as font_f:
239        font_surf = Image.load(font_f)
240        x, y = 0, 0
241        for ch in text:
242            chi = ord(ch)
243            chrect = Rect(chi % 16 * 8, chi // 16 * 6, 8 if chi >= 0x80 else 4, 6)
244            new_x = x + chrect.w + spacing.x
245            if ch == '\n':
246                new_x -= x
247                x = 0
248                y += chrect.h + spacing.y
249                if y >= size.y:
250                    break
251                else:
252                    continue
253            if new_x <= size.x:
254                image.draw(font_surf, offset + Point(x, y), chrect)
255            x = new_x
256
257def create_screenshot_surface(screenshot, transparent=False, palette=k_palette):
258    screenshot_surf = Image.create(*k_label_size)
259    screenshot_pixels = screenshot_surf.pixels
260    for y in range(k_label_size.y):
261        for x in range(k_label_size.x):
262            i = screenshot[x, y]
263            color = palette[i]
264            if transparent and i == 0:
265                color = color.set_a(0)
266            screenshot_pixels[x, y] = color
267    return screenshot_surf
268
269def write_cart_to_image(cart, template_image=None, template_only=False, optimize_image=False, **opts):
270    output = write_cart_to_rom(cart, with_trailer=True, **opts)
271
272    if not template_image:
273        template_image = path_join(get_res_path(), "template.png")
274
275    with file_open(template_image) as template_f:
276        image = load_image_of_size(template_f, k_cart_image_size)
277        width, height = image.size
278
279        if not template_only:
280            if cart.label:
281                label_surf = create_screenshot_surface(cart.label, transparent=True)
282                image.draw(label_surf, k_label_offset)
283            if cart.title:
284                draw_text_on_image(image, cart.title, k_title_offset, k_title_size, k_title_spacing)
285        
286        pixels = image.pixels
287
288        for y in range(height):
289            for x in range(width):
290                i = x + y * width
291                byte = output[i]
292                r, g, b, a = pixels[x,y]
293                b = (b & ~3) | (byte & 3)
294                g = (g & ~3) | ((byte >> 2) & 3)
295                r = (r & ~3) | ((byte >> 4) & 3)
296                a = (a & ~3) | ((byte >> 6) & 3)
297                pixels[x, y] = (r, g, b, a)
298
299        if optimize_image:
300            return image.save(optimize=True)
301        else:
302            return image.save()
303
304def get_real_palette(idx_palette=None, return_palmap=False):
305    if idx_palette is None:
306        palette = k_palette
307    else:
308        palette = []
309        for idx in idx_palette:
310            if 0 <= idx < 0x10:
311                palette.append(k_palette[idx])
312            else: # accept just about anything for alt. colors
313                palette.append(k_palette[0x10 + (idx & 0xf)])
314        while len(palette) < 0x10:
315            palette.append(k_palette[len(palette)])
316    
317    if return_palmap:
318        return palette_to_palmap(palette)
319    else:
320        return palette
321
322def read_cart_label(data, path=None, **_):
323    image = load_image_of_size(BytesIO(data), k_label_size)
324    label = surface_pixels_to_screenshot(image.pixels)
325
326    return Cart(path=path, label=label)
327
328def read_cart_spritesheet(data, path=None, palette=None, **_):
329    image = load_image_of_size(BytesIO(data), k_label_size)
330
331    palmap = get_real_palette(palette, return_palmap=True)
332    spritesheet = surface_pixels_to_screenshot(image.pixels, palmap=palmap)
333
334    cart = Cart(path=path)
335    for y in range(128):
336        for x in range(128):
337            cart.rom.set4(mem_sprite_addr(x, y), spritesheet[x, y] & 0xf)
338    return cart
339
340def write_cart_label(cart, **_):
341    label = cart.label or MultidimArray(k_label_size, 0)
342    return create_screenshot_surface(label, transparent=True).save()
343
344def write_cart_spritesheet(cart, palette=None, **_):
345    spritesheet = MultidimArray(k_label_size, 0)    
346    for y in range(128):
347        for x in range(128):
348            spritesheet[x, y] = cart.rom.get4(mem_sprite_addr(x, y))
349
350    palette = get_real_palette(palette)
351    return create_screenshot_surface(spritesheet, palette=palette).save()
352
353k_p8_prefix = "pico-8 cartridge"
354k_meta_prefix = "meta:"
355
356def read_cart_from_source(data, path=None, raw=False, preprocess_hook=None, **opts):
357    cart = Cart(path=path)
358    
359    def nybbles(line):
360        for b in line:
361            yield int(b, 16)
362    
363    def nybble_groups(line, n):
364        for i in range(0, len(line), n):
365            yield nybbles(line[i:i+n].ljust(n, "0"))
366    
367    def bytes(line):
368        for i in range(0, len(line), 2):
369            yield int(line[i:i+2].ljust(2, "0"), 16)
370    
371    def ext_nybbles(line):
372        for b in line:
373            if 'v' >= b.lower() >= 'g':
374                yield ord(b.lower()) - ord('g') + 16
375            else:
376                yield int(b, 16)
377      
378    def p8_split_lines(str):
379        split = re.split("\r?\n", str)
380        if split and not split[-1]:
381            split.pop()
382        return split
383
384    if not raw and not data.startswith(k_p8_prefix) and not data.startswith("__lua__"): # fallback to raw
385        raw = True
386    
387    header = "lua" if raw else None
388    code = []
389    code_line = 0
390    y = 0
391    for line_i, line in enumerate(p8_split_lines(data)):
392        try:
393            clean = line.strip()
394            
395            if line.startswith("__") and clean.endswith("__") and not raw: # may end with whitespace
396                header = clean[2:-2]
397                y = 0
398                
399            elif header == "lua":
400                if y == 0:
401                    code_line = line_i
402                else:
403                    code.append("\n")
404                code.append(to_p8str(line))
405                y += 1
406                
407            elif header == "gfx" and clean and y < 0x80:
408                x = 0
409                for b in nybbles(clean):
410                    if x < 0x80:
411                        cart.rom.set4(mem_sprite_addr(x, y), b)
412                        x += 1
413                y += 1
414                    
415            elif header == "map" and clean and y < 0x40: # usually 0x20
416                x = 0
417                for b in bytes(clean):
418                    if x < 0x80:
419                        cart.rom.set8(mem_map_addr(x, y), b)
420                        x += 1
421                y += 1
422                    
423            elif header == "gff" and clean and y < 2:
424                x = 0
425                for b in bytes(clean):
426                    if x < 0x80:
427                        cart.rom.set8(mem_flag_addr(x, y), b)
428                        x += 1
429                y += 1
430                
431            elif header == "sfx" and clean and y < 0x40:
432                x = 0
433                for b in bytes(clean[:8]):
434                    cart.rom.set8(mem_sfx_info_addr(y, x), b)
435                    x += 1
436                x = 0
437                for bph, bpl, bw, bv, be in nybble_groups(clean[8:], 5):
438                    if x < 0x20:
439                        value = bpl | ((bph & 0x3) << 4) | ((bw & 0x7) << 6) | ((bv & 0x7) << 9) | ((be & 0x7) << 12) | ((bw & 0x8) << 12) 
440                        cart.rom.set16(mem_sfx_addr(y, x), value)
441                        x += 1
442                y += 1
443                
444            elif header == "music" and clean and y < 0x40:
445                x = 0
446                flags = next(bytes(clean[:2]))
447                for b in bytes(clean[3:]):
448                    if x < 4:
449                        value = b | (((flags >> x) & 1) << 7) 
450                        cart.rom.set8(mem_music_addr(y, x), value)
451                        x += 1
452                y += 1
453
454            elif header == "label" and clean and y < 0x80:
455                if cart.label is None:
456                    cart.label = MultidimArray(k_label_size, 0)
457                x = 0
458                for b in ext_nybbles(clean):
459                    if x < 0x80:
460                        cart.label[x, y] = b
461                        x += 1
462                y += 1
463
464            elif header and header.startswith(k_meta_prefix):
465                cart.meta[header[len(k_meta_prefix):]].append(line.rstrip('\n'))
466                
467            elif header == None and clean.startswith("version "):
468                cart.set_version(int(clean.split()[1]))
469
470        except ValueError:
471            throw(f"Invalid {header} line in p8 file (line #{line_i + 1})")
472            
473    preprocess = default(preprocess_hook, preprocess_code)
474    cart.code, cart.code_map = preprocess(path, "".join(code), code_line, **opts)
475    return cart
476
477def write_cart_to_source(cart, unicode_caps=False, sections=None, **_):
478    lines = [k_p8_prefix + " // http://www.pico-8.com"]
479    lines.append(f"version {cart.version_id}")
480    defrom = mem_create_rom()
481
482    def include(section):
483        return sections is None or section in sections
484
485    def nybbles(data):
486        return "".join('%01x' % b for b in data)
487    
488    def nybble_groups(data):
489        return "".join([nybbles(group) for group in data])
490    
491    def bytes(data):
492        return "".join('%02x' % b for b in data)
493
494    def ext_nybbles(data):
495        return "".join(('%01x' % b if b < 16 else chr(b - 16 + ord('g'))) for b in data)
496
497    def get_needed_lines(max_lines, addr_func, size):
498        lines = max_lines
499        for y in reversed(range(max_lines)):
500            if cart.rom.cmpeqwith8(addr_func(y), size, defrom):
501                lines -= 1
502            else:
503                break
504        return lines
505
506    if include("lua"):
507        lines.append("__lua__")
508        lines.append(from_p8str(cart.code, unicaps=unicode_caps))
509
510    if include("gfx"):
511        gfx_lines = get_needed_lines(0x80, lambda y: mem_sprite_addr(0, y)[0], 0x40)
512        if gfx_lines:
513            lines.append("__gfx__")
514            for y in range(gfx_lines):
515                lines.append(nybbles(cart.rom.get4(mem_sprite_addr(x, y)) for x in range(128)))
516
517    if include("map"):
518        map_lines = get_needed_lines(0x20, lambda y: mem_map_addr(0, y), 0x80)
519        if map_lines:
520            lines.append("__map__")
521            for y in range(map_lines):
522                lines.append(bytes(cart.rom.get8(mem_map_addr(x, y)) for x in range(128)))
523
524    if include("gff"):
525        gff_lines = get_needed_lines(2, lambda y: mem_flag_addr(0, y), 0x80)
526        if gff_lines:
527            lines.append("__gff__")
528            for y in range(gff_lines):
529                lines.append(bytes(cart.rom.get8(mem_flag_addr(x, y)) for x in range(128)))
530
531    if include("sfx"):
532        sfx_lines = get_needed_lines(0x40, lambda y: mem_sfx_addr(y, 0), 0x44)
533        if sfx_lines:
534            lines.append("__sfx__")
535            for y in range(sfx_lines):
536                info = bytes(cart.rom.get8(mem_sfx_info_addr(y, x)) for x in range(4))
537                notes = (cart.rom.get16(mem_sfx_addr(y, x)) for x in range(32))
538                note_groups = nybble_groups(((n >> 4) & 0x3, n & 0xf, ((n >> 6) & 0x7) | (n >> 12) & 0x8, (n >> 9) & 0x7, (n >> 12) & 0x7) for n in notes)
539                lines.append(info + note_groups)
540
541    if include("music"):
542        music_lines = get_needed_lines(0x40, lambda y: mem_music_addr(y, 0), 0x4)
543        if music_lines:
544            lines.append("__music__")
545            for y in range(music_lines):
546                chans = [cart.rom.get8(mem_music_addr(y, x)) for x in range(4)]
547                flags = bytes((sum(((ch >> 7) & 1) << i for i, ch in enumerate(chans)),))
548                ids = bytes(ch & 0x7f for ch in chans)
549                lines.append(flags + " " + ids)
550    
551    if include("label") and cart.label and any(cart.label.array):
552        lines.append("__label__")
553        for y in range(128):
554            lines.append(ext_nybbles(cart.label[x, y] for x in range(128)))
555    
556    for meta, metalines in cart.meta.items():
557        if include(k_meta_prefix + meta):
558            lines.append(f"__{k_meta_prefix + meta}__")
559            lines += metalines
560
561    return "\n".join(lines) + "\n"
562
563def write_cart_to_raw_source(cart, with_header=False, unicode_caps=False, **_):
564    source = from_p8str(cart.code, unicaps=unicode_caps)
565    if with_header:
566        source = "__lua__\n" + source
567    return source
568
569def iter_rect(width, height):
570    for y in range(height):
571        for x in range(width):
572            yield x, y
573
574k_base64_chars = string.ascii_uppercase + string.ascii_lowercase + string.digits + "_-"
575k_base64_alt_chars = k_base64_chars[62:].encode()
576k_base64_char_map = {ch: i for i, ch in enumerate(k_base64_chars)}
577
578def pico_base64_encode(data):
579    return base64.b64encode(data, k_base64_alt_chars)
580
581def pico_base64_decode(data, validate=False):
582    return base64.b64decode(data, k_base64_alt_chars, validate=validate)
583
584def print_url_size(size, **kwargs):
585    print_size("url", size - k_url_prefix_size, k_url_size, **kwargs)
586
587def read_cart_from_url(url, size_handler=None, **opts):
588    if size_handler:
589        print_url_size(len(url), prefix="input", handler=size_handler)
590
591    if "?" not in url:
592        throw("Invalid url - no '?'")
593
594    code, gfx = None, None
595    
596    url_params = url.split("?", 1)[1]
597    for url_param in url_params.split("&"):
598        if "=" not in url_param:
599            throw(f"Invalid url param: {url_param}")
600        
601        key, value = url_param.split("=", 1)
602        if key == "c":
603            code = value
604        elif key == "g":
605            gfx = value
606        else:
607            throw(f"Unknown url param: {key}")
608
609    cart = Cart()
610
611    if code:
612        codebuf = pico_base64_decode(code, validate=True).ljust(k_code_size, b'\0')
613        with BinaryReader(BytesIO(codebuf), big_end = True) as r:
614            cart.code, cart.code_rom = read_code_from_rom(r, **opts)
615
616    if gfx:
617        i = 0
618        rect = iter_rect(128, 128)
619        while i < len(gfx):
620            val = k_base64_char_map[gfx[i]]
621            i += 1
622
623            color = val & 0xf
624            count = (val >> 4) + 1
625            if count == 4:
626                count += k_base64_char_map[gfx[i]]
627                i += 1
628
629            for _ in range(count):
630                x, y = next(rect)
631                cart.rom.set4(mem_sprite_addr(x, y), color)
632
633    return cart
634
635k_url_prefix = "https://www.pico-8-edu.com"
636
637def write_cart_to_url(cart, url_prefix=k_url_prefix, force_compress=False, size_handler=None, **opts):
638    raw_code = write_cart_to_tiny_rom(cart, **opts)        
639    code = pico_base64_encode(raw_code)
640
641    rect = iter_rect(128, 128)
642    gfx = []
643    x, y = next(rect)
644    done = False
645    while not done:
646        color = cart.rom.get4(mem_sprite_addr(x, y))
647        total_count = 1
648        for x, y in rect:
649            next_color = cart.rom.get4(mem_sprite_addr(x, y))
650            if next_color == color:
651                total_count += 1
652            else:
653                break
654        else:
655            done = True
656            if color == 0:
657                total_count = 0
658
659        while total_count > 0:
660            count = min(total_count, 63 + 4)
661            total_count -= count
662
663            val = (min(count - 1, 3) << 4) | color
664            gfx.append(k_base64_chars[val])
665
666            if count >= 4:
667                gfx.append(k_base64_chars[count - 4])
668
669    url = url_prefix
670    url += "/?c=" + code.decode()
671    if gfx:
672        url += "&g=" + "".join(gfx)
673    
674    if size_handler:
675        print_url_size(len(url), handler=size_handler)
676        
677    check(len(url) - k_url_prefix_size <= k_url_size, "url has too many characters!")
678    return url
679
680k_clip_prefix = "[cart]"
681k_clip_suffix = "[/cart]"
682
683def read_raw_from_clip(clip):
684    if clip.startswith(k_clip_prefix) and clip.endswith(k_clip_suffix):
685        return bytes.fromhex(clip[len(k_clip_prefix):-len(k_clip_suffix)])        
686    else:
687        throw("Invalid clipboard tag")
688
689def read_cart_from_clip(clip, **opts):
690    data = read_raw_from_clip(clip)
691    return read_cart_from_image(data, **opts)
692
693def write_raw_to_clip(data):
694    return k_clip_prefix + data.hex() + k_clip_suffix
695
696def write_cart_to_clip(cart, **opts):
697    return write_raw_to_clip(write_cart_to_image(cart, **opts))
698
699def read_cart_autodetect(path, **opts):
700    data = file_read(path)
701
702    if data.startswith(k_png_header):
703        return read_cart_from_image(data, path=path, **opts)
704
705    text = data.decode(errors="surrogateescape")
706
707    # cart?
708    if text.startswith(k_p8_prefix) or text.startswith("__lua__"):
709        return read_cart_from_source(text, path=path, **opts)
710        
711    # clip?
712    if text.startswith(k_clip_prefix):
713        return read_cart_from_clip(text.rstrip(), path=path, **opts)
714
715    # url?
716    if text.startswith(k_url_prefix):
717        return read_cart_from_url(text.rstrip(), path=path, **opts)
718
719    # plain text?
720    return read_cart_from_source(text, raw=True, path=path, **opts)
721
722def read_cart(path: str, format: CartFormat = None, **opts):
723    """Read a cart from the given path, assuming it is in the given format"""
724    if format in (None, CartFormat.auto):
725        return read_cart_autodetect(path, **opts)
726    elif format in (CartFormat.p8, CartFormat.code):
727        return read_cart_from_source(file_read_maybe_text(path), path=path, **opts)
728    elif format == CartFormat.png:
729        return read_cart_from_image(file_read(path), path=path, **opts)
730    elif format in (CartFormat.rom, CartFormat.tiny_rom):
731        return read_cart_from_rom(file_read(path), path=path, allow_tiny=True, **opts)
732    elif format == CartFormat.clip:
733        return read_cart_from_clip(file_read_text(path).rstrip(), path=path, **opts)
734    elif format == CartFormat.url:
735        return read_cart_from_url(file_read_text(path).rstrip(), path=path, **opts)
736    elif format == CartFormat.lua:
737        return read_cart_from_source(file_read_maybe_text(path), raw=True, path=path, **opts)
738    elif format == CartFormat.label:
739        return read_cart_label(file_read(path), path=path, **opts)
740    elif format == CartFormat.spritesheet:
741        return read_cart_spritesheet(file_read(path), path=path, **opts)
742    elif format.is_export:
743        return read_from_cart_export(path, format, **opts)
744    else:
745        throw(f"invalid format for reading: {format}")
746
747def write_cart(path: str, cart: Cart, format: CartFormat, **opts):
748    """Writes a cart to the given path in the given format"""
749    if format == CartFormat.p8:
750        file_write_text(path, write_cart_to_source(cart, **opts))
751    elif format == CartFormat.png:
752        file_write(path, write_cart_to_image(cart, **opts))
753    elif format == CartFormat.rom:
754        file_write(path, write_cart_to_rom(cart, **opts))
755    elif format == CartFormat.tiny_rom:
756        file_write(path, write_cart_to_tiny_rom(cart, **opts))
757    elif format == CartFormat.clip:
758        file_write_text(path, write_cart_to_clip(cart, **opts))
759    elif format == CartFormat.url:
760        file_write_text(path, write_cart_to_url(cart, **opts))
761    elif format == CartFormat.lua:
762        file_write_text(path, write_cart_to_raw_source(cart, **opts))
763    elif format == CartFormat.code:
764        file_write_text(path, write_cart_to_raw_source(cart, with_header=True, **opts))
765    elif format == CartFormat.label:
766        file_write(path, write_cart_label(cart, **opts))
767    elif format == CartFormat.spritesheet:
768        file_write(path, write_cart_spritesheet(cart, **opts))
769    elif format.is_export:
770        write_to_cart_export(path, cart, format, **opts)
771    else:
772        throw(f"invalid format for writing: {format}")
773
774def get_bbs_cart_url(id, lang=Language.pico8):
775    if not id.startswith("#"):
776        throw("invalid bbs id - # prefix expected")
777
778    if lang == Language.pico8:
779        category = 7
780    elif lang == Language.picotron:
781        category = 8
782    else:
783        throw("invalid bbs cart language")
784
785    from urllib.parse import urlencode
786    params = {"lid": id[1:], "cat": category}
787
788    return "https://www.lexaloffle.com/bbs/get_cart.php?" + urlencode(params)
789
790k_pico_sections = ("lua", "gfx", "map", "gff", "sfx", "music", "label", "meta:*")
791
792def merge_cart(dest: Cart, src: Cart, sections: list):
793    """Copy the given sections (see k_pico_sections) from src to dest"""
794
795    for section in sections:
796        if section == "lua":
797            dest.code, dest.code_map, dest.code_rom = src.code, src.code_map, src.code_rom
798        elif section == "gfx":
799            dest.rom.copyfrom8(k_mem_sprites_addr, k_mem_map_addr - k_mem_sprites_addr, src.rom)
800        elif section == "map":
801            dest.rom.copyfrom8(k_mem_map_addr, k_mem_flag_addr - k_mem_map_addr, src.rom)
802        elif section == "gff":
803            dest.rom.copyfrom8(k_mem_flag_addr, k_mem_music_addr - k_mem_flag_addr, src.rom)
804        elif section == "music":
805            dest.rom.copyfrom8(k_mem_music_addr, k_mem_sfx_addr - k_mem_music_addr, src.rom)
806        elif section == "sfx":
807            dest.rom.copyfrom8(k_mem_sfx_addr, k_rom_size - k_mem_sfx_addr, src.rom)
808        elif section == "label":
809            dest.label = src.label
810        elif section.startswith(k_meta_prefix):
811            meta_name = section[len(k_meta_prefix):]
812            dest.meta[meta_name] = src.name[meta_name]
813        else:
814            throw(f"unknown cart section: '{section}'")
815
816def write_cart_version(cart):
817    if cart.default_version:
818        print("no version info")
819    else:
820        print("version:", format_pico8_version(cart.version_tuple))
821        print("raw version: %d (%d.%d.%d.%d)" % (cart.version_id, *cart.version_tuple))
822
823    if not cart.default_platform:
824        print("platform:", format_platform(cart.platform))
825
826from pico_export import read_from_cart_export, write_to_cart_export
827from pico_preprocess import preprocess_code
class CartFormat(utils.Enum):
10class CartFormat(Enum):
11    """An enum representing the supported cart formats"""
12    auto = p8 = png = lua = rom = tiny_rom = clip = url = code = js = pod = bin = dat = label = spritesheet = ...
13
14    @property
15    def is_input(m):
16        return m != m.bin
17    @property
18    def is_output(m):
19        return m not in (m.auto, m.dat)
20    @property
21    def is_ext(m):
22        return m not in (m.auto, m.tiny_rom, m.code, m.label, m.spritesheet)
23    @property
24    def is_src(m):
25        return m in (m.p8, m.lua, m.code)
26    @property
27    def is_export(m):
28        return m in (m.js, m.pod, m.bin, m.dat)
29    @property
30    def is_exposed(m):
31        return m != m.code
32    
33    @classproperty
34    def default_src(m):
35        return m.p8
36    @classproperty
37    def default_dir(m):
38        return None

An enum representing the supported cart formats

CartFormat(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}")
is_input
14    @property
15    def is_input(m):
16        return m != m.bin
is_output
17    @property
18    def is_output(m):
19        return m not in (m.auto, m.dat)
is_ext
20    @property
21    def is_ext(m):
22        return m not in (m.auto, m.tiny_rom, m.code, m.label, m.spritesheet)
is_src
23    @property
24    def is_src(m):
25        return m in (m.p8, m.lua, m.code)
is_export
26    @property
27    def is_export(m):
28        return m in (m.js, m.pod, m.bin, m.dat)
is_exposed
29    @property
30    def is_exposed(m):
31        return m != m.code
def default_src(unknown):

Method decorator that turns it into a read-only class property

def default_dir(unknown):

Method decorator that turns it into a read-only class property

value
tiny_rom = CartFormat.tiny_rom
spritesheet = CartFormat.spritesheet
class Cart:
40class Cart:
41    """A pico8 cart, including its code (as a p8str), rom (as a Memory), and more"""
42
43    def __init__(m, code="", rom=None, label=None, path="", name=""):
44        m.version_id = get_default_pico8_version()
45        m.version_tuple = get_pico8_version_tuple(m.version_id)
46        m.platform = get_default_platform()
47        m.default_version = m.default_platform = True
48        m.rom = rom.copy() if rom else mem_create_rom()
49        m.path = path
50        m.name = name if name else path_basename(path) if path else ""
51        m.code = code
52        m.code_map = ()
53        m.code_rom = None
54        m.label = label
55        m.meta = defaultdict(list)
56
57    def copy(m):
58        return deepcopy(m)
59
60    @property
61    def title(m):
62        """Returns the cart's title, as a p8str"""
63        title_meta = m.meta.get("title")
64        if title_meta is None:
65            title = ""
66            for line in m.code.split("\n", 2)[:2]: # (splitlines isn't appropriate for p8str)
67                match = re.fullmatch(r"-- ?(.*)", line)
68                if match:
69                    title += match.group(1)
70                title += "\n"
71            return title.rstrip("\n")
72        else:
73            return "\n".join(to_p8str(line) for line in title_meta)
74
75    @title.setter
76    def title(m, value):
77        """Sets the cart's title, from a p8str"""
78        m.meta["title"] = from_p8str(value).splitlines()
79    
80    def set_raw_title(m, title_lines):
81        m.meta["title"] = title_lines
82
83    def set_code_without_title(m, code):
84        old_title = m.title
85        m.code = code
86        if old_title != m.title:
87            m.title = old_title
88
89    def set_version(m, id):
90        m.version_id = id
91        m.version_tuple = get_pico8_version_tuple(id)
92        m.default_version = False

A pico8 cart, including its code (as a p8str), rom (as a Memory), and more

Cart(code='', rom=None, label=None, path='', name='')
43    def __init__(m, code="", rom=None, label=None, path="", name=""):
44        m.version_id = get_default_pico8_version()
45        m.version_tuple = get_pico8_version_tuple(m.version_id)
46        m.platform = get_default_platform()
47        m.default_version = m.default_platform = True
48        m.rom = rom.copy() if rom else mem_create_rom()
49        m.path = path
50        m.name = name if name else path_basename(path) if path else ""
51        m.code = code
52        m.code_map = ()
53        m.code_rom = None
54        m.label = label
55        m.meta = defaultdict(list)
def copy(m):
57    def copy(m):
58        return deepcopy(m)
title
60    @property
61    def title(m):
62        """Returns the cart's title, as a p8str"""
63        title_meta = m.meta.get("title")
64        if title_meta is None:
65            title = ""
66            for line in m.code.split("\n", 2)[:2]: # (splitlines isn't appropriate for p8str)
67                match = re.fullmatch(r"-- ?(.*)", line)
68                if match:
69                    title += match.group(1)
70                title += "\n"
71            return title.rstrip("\n")
72        else:
73            return "\n".join(to_p8str(line) for line in title_meta)

Returns the cart's title, as a p8str

def set_raw_title(m, title_lines):
80    def set_raw_title(m, title_lines):
81        m.meta["title"] = title_lines
def set_code_without_title(m, code):
83    def set_code_without_title(m, code):
84        old_title = m.title
85        m.code = code
86        if old_title != m.title:
87            m.title = old_title
def set_version(m, id):
89    def set_version(m, id):
90        m.version_id = id
91        m.version_tuple = get_pico8_version_tuple(id)
92        m.default_version = False
def read_code_from_rom(r, keep_compression=False, **opts):
 94def read_code_from_rom(r, keep_compression=False, **opts):
 95    code_rom = None
 96    if keep_compression:
 97        start_pos = r.pos()
 98        code_rom = Memory(k_code_size)
 99        code_rom.set_block(0, r.bytes(k_code_size, allow_eof=True))
100        r.setpos(start_pos)
101
102    return uncompress_code(r, **opts), code_rom
def read_cart_from_rom(buffer, path=None, allow_tiny=False, **opts):
104def read_cart_from_rom(buffer, path=None, allow_tiny=False, **opts):
105    cart = Cart(path=path)
106    
107    with BinaryReader(BytesIO(buffer), big_end = True) as r:
108        if r.len() < k_cart_size and allow_tiny: # tiny rom, code only
109            cart.code, cart.code_rom = read_code_from_rom(r, **opts)
110        
111        else:
112            cart.rom.replace(r.bytes(k_rom_size))
113            cart.code, cart.code_rom = read_code_from_rom(r, **opts)
114
115            r.setpos(k_cart_size)
116            if r.pos() < r.len():
117                cart.version_id = r.u8()
118                version = r.u8(), r.u8(), r.u8()
119                cart.platform = chr(r.u8())
120                cart.version_tuple = (*version, r.u8())
121                cart.default_version = cart.default_platform = False
122                hash = r.bytes(20)
123
124                if hash != bytes(20) and hash != hashlib.sha1(buffer[:k_cart_size]).digest():
125                    throw("corrupted cart (wrong hash)")
126
127    return cart
def write_cart_to_rom(cart, with_trailer=False, keep_compression=False, **opts):
129def write_cart_to_rom(cart, with_trailer=False, keep_compression=False, **opts):
130    io = BytesIO(bytes(k_cart_size + (k_trailer_size if with_trailer else 0)))
131
132    with BinaryWriter(io, big_end = True) as w:
133        w.bytes(cart.rom)
134
135        if keep_compression and cart.code_rom != None:
136            w.bytes(cart.code_rom)
137        else:
138            compress_code(w, cart.code, **opts)
139
140        if with_trailer:
141            w.setpos(k_cart_size)
142            w.u8(cart.version_id)
143            w.u8(cart.version_tuple[0])
144            w.u8(cart.version_tuple[1])
145            w.u8(cart.version_tuple[2])
146            w.u8(ord(cart.platform))
147            w.u8(cart.version_tuple[3])
148            w.bytes(hashlib.sha1(io.getvalue()[:k_cart_size]).digest())
149
150        return io.getvalue()
def write_cart_to_tiny_rom(cart, force_compress=False, keep_compression=False, **opts):
152def write_cart_to_tiny_rom(cart, force_compress=False, keep_compression=False, **opts):
153    io = BytesIO()
154
155    with BinaryWriter(io, big_end = True) as w:
156        if keep_compression and cart.code_rom != None:
157            with BinaryReader(BytesIO(cart.code_rom), big_end = True) as code_r:
158                compressed_size = get_compressed_size(code_r)
159            
160            w.bytes(cart.code_rom.get_block(0, compressed_size))
161        else:
162            compress_code(w, cart.code, force_compress=True, **opts)
163
164            if len(io.getvalue()) > len(cart.code):
165                io = BytesIO(encode_p8str(cart.code))
166
167        return io.getvalue()
k_cart_image_size = Point(x=160, y=205)
k_label_size = Point(x=128, y=128)
k_label_offset = Point(x=16, y=24)
k_title_offset = Point(x=18, y=167)
k_title_spacing = Point(x=0, y=2)
k_title_size = Point(x=124, y=16)
def palette_to_palmap(palette):
176def palette_to_palmap(palette):
177    return {(c.r & ~3, c.g & ~3, c.b & ~3): i for i, c in enumerate(palette)}
k_palette_rgb_6bpp_map = {(0, 0, 0): 0, (28, 40, 80): 1, (124, 36, 80): 2, (0, 132, 80): 3, (168, 80, 52): 4, (92, 84, 76): 5, (192, 192, 196): 6, (252, 240, 232): 7, (252, 0, 76): 8, (252, 160, 0): 9, (252, 236, 36): 10, (0, 228, 52): 11, (40, 172, 252): 12, (128, 116, 156): 13, (252, 116, 168): 14, (252, 204, 168): 15, (40, 24, 20): 16, (16, 28, 52): 17, (64, 32, 52): 18, (16, 80, 88): 19, (116, 44, 40): 20, (72, 48, 56): 21, (160, 136, 120): 22, (240, 236, 124): 23, (188, 16, 80): 24, (252, 108, 36): 25, (168, 228, 44): 26, (0, 180, 64): 27, (4, 88, 180): 28, (116, 68, 100): 29, (252, 108, 88): 30, (252, 156, 128): 31}
k_png_header = b'\x89PNG\r\n\x1a\n'
k_qoi_header = b'qoif'
def load_image_of_size(f, valid_size, format=PixelFormat.rgba8, is_qoi=False):
183def load_image_of_size(f, valid_size, format=PixelFormat.rgba8, is_qoi=False):
184    r = BinaryReader(f)
185    if is_qoi:
186        if r.bytes(4) != k_qoi_header:
187            throw("Not a valid qoi")
188        r.subpos(4)
189    else:
190        if r.bytes(8) != k_png_header:
191            throw("Not a valid png")
192        r.subpos(8)
193
194    image = Image.load(f, format)
195    if image.size != valid_size:
196        throw("Png has wrong size")
197
198    return image
def find_best_in_palette_map(palmap, r, g, b):
200def find_best_in_palette_map(palmap, r, g, b):
201    min_delta, best_idx = math.inf, 0
202    for (tr, tg, tb), idx in palmap.items():
203        delta = abs(tr - r) + abs(tg - g) + abs(tb - b)
204        if delta < min_delta:
205            min_delta, best_idx = delta, idx
206    return best_idx
def surface_pixels_to_screenshot( pixels, offset=Point(x=0, y=0), palmap={(0, 0, 0): 0, (28, 40, 80): 1, (124, 36, 80): 2, (0, 132, 80): 3, (168, 80, 52): 4, (92, 84, 76): 5, (192, 192, 196): 6, (252, 240, 232): 7, (252, 0, 76): 8, (252, 160, 0): 9, (252, 236, 36): 10, (0, 228, 52): 11, (40, 172, 252): 12, (128, 116, 156): 13, (252, 116, 168): 14, (252, 204, 168): 15, (40, 24, 20): 16, (16, 28, 52): 17, (64, 32, 52): 18, (16, 80, 88): 19, (116, 44, 40): 20, (72, 48, 56): 21, (160, 136, 120): 22, (240, 236, 124): 23, (188, 16, 80): 24, (252, 108, 36): 25, (168, 228, 44): 26, (0, 180, 64): 27, (4, 88, 180): 28, (116, 68, 100): 29, (252, 108, 88): 30, (252, 156, 128): 31}):
208def surface_pixels_to_screenshot(pixels, offset=Point.zero, palmap=k_palette_rgb_6bpp_map):
209    screenshot = MultidimArray(k_label_size, 0)
210
211    for y in range(k_label_size.y):
212        for x in range(k_label_size.x):
213            r, g, b, a = pixels[Point(x, y) + offset]
214            palidx = palmap.get((r & ~3, g & ~3, b & ~3))
215            if palidx is None:
216                palidx = find_best_in_palette_map(palmap, r, g, b)
217            screenshot[x, y] = palidx
218
219    return screenshot
def read_cart_from_image(data, **opts):
221def read_cart_from_image(data, **opts):
222    image = load_image_of_size(BytesIO(data), k_cart_image_size)
223    width, height = image.size
224
225    data = bytearray()
226    pixels = image.pixels
227
228    for y in range(height):
229        for x in range(width):
230            r, g, b, a = pixels[x, y]
231            byte = ((b & 3) << 0) | ((g & 3) << 2) | ((r & 3) << 4) | ((a & 3) << 6)
232            data.append(byte)
233
234    cart = read_cart_from_rom(data, **opts)
235    cart.label = surface_pixels_to_screenshot(pixels, k_label_offset)
236    return cart
def draw_text_on_image(image, text, offset, size, spacing=Point(x=0, y=0)):
238def draw_text_on_image(image, text, offset, size, spacing=Point.zero):
239    with file_open(path_join(get_res_path(), "font.png")) as font_f:
240        font_surf = Image.load(font_f)
241        x, y = 0, 0
242        for ch in text:
243            chi = ord(ch)
244            chrect = Rect(chi % 16 * 8, chi // 16 * 6, 8 if chi >= 0x80 else 4, 6)
245            new_x = x + chrect.w + spacing.x
246            if ch == '\n':
247                new_x -= x
248                x = 0
249                y += chrect.h + spacing.y
250                if y >= size.y:
251                    break
252                else:
253                    continue
254            if new_x <= size.x:
255                image.draw(font_surf, offset + Point(x, y), chrect)
256            x = new_x
def create_screenshot_surface( screenshot, transparent=False, 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)]):
258def create_screenshot_surface(screenshot, transparent=False, palette=k_palette):
259    screenshot_surf = Image.create(*k_label_size)
260    screenshot_pixels = screenshot_surf.pixels
261    for y in range(k_label_size.y):
262        for x in range(k_label_size.x):
263            i = screenshot[x, y]
264            color = palette[i]
265            if transparent and i == 0:
266                color = color.set_a(0)
267            screenshot_pixels[x, y] = color
268    return screenshot_surf
def write_cart_to_image( cart, template_image=None, template_only=False, optimize_image=False, **opts):
270def write_cart_to_image(cart, template_image=None, template_only=False, optimize_image=False, **opts):
271    output = write_cart_to_rom(cart, with_trailer=True, **opts)
272
273    if not template_image:
274        template_image = path_join(get_res_path(), "template.png")
275
276    with file_open(template_image) as template_f:
277        image = load_image_of_size(template_f, k_cart_image_size)
278        width, height = image.size
279
280        if not template_only:
281            if cart.label:
282                label_surf = create_screenshot_surface(cart.label, transparent=True)
283                image.draw(label_surf, k_label_offset)
284            if cart.title:
285                draw_text_on_image(image, cart.title, k_title_offset, k_title_size, k_title_spacing)
286        
287        pixels = image.pixels
288
289        for y in range(height):
290            for x in range(width):
291                i = x + y * width
292                byte = output[i]
293                r, g, b, a = pixels[x,y]
294                b = (b & ~3) | (byte & 3)
295                g = (g & ~3) | ((byte >> 2) & 3)
296                r = (r & ~3) | ((byte >> 4) & 3)
297                a = (a & ~3) | ((byte >> 6) & 3)
298                pixels[x, y] = (r, g, b, a)
299
300        if optimize_image:
301            return image.save(optimize=True)
302        else:
303            return image.save()
def get_real_palette(idx_palette=None, return_palmap=False):
305def get_real_palette(idx_palette=None, return_palmap=False):
306    if idx_palette is None:
307        palette = k_palette
308    else:
309        palette = []
310        for idx in idx_palette:
311            if 0 <= idx < 0x10:
312                palette.append(k_palette[idx])
313            else: # accept just about anything for alt. colors
314                palette.append(k_palette[0x10 + (idx & 0xf)])
315        while len(palette) < 0x10:
316            palette.append(k_palette[len(palette)])
317    
318    if return_palmap:
319        return palette_to_palmap(palette)
320    else:
321        return palette
def read_cart_label(data, path=None, **_):
323def read_cart_label(data, path=None, **_):
324    image = load_image_of_size(BytesIO(data), k_label_size)
325    label = surface_pixels_to_screenshot(image.pixels)
326
327    return Cart(path=path, label=label)
def read_cart_spritesheet(data, path=None, palette=None, **_):
329def read_cart_spritesheet(data, path=None, palette=None, **_):
330    image = load_image_of_size(BytesIO(data), k_label_size)
331
332    palmap = get_real_palette(palette, return_palmap=True)
333    spritesheet = surface_pixels_to_screenshot(image.pixels, palmap=palmap)
334
335    cart = Cart(path=path)
336    for y in range(128):
337        for x in range(128):
338            cart.rom.set4(mem_sprite_addr(x, y), spritesheet[x, y] & 0xf)
339    return cart
def write_cart_label(cart, **_):
341def write_cart_label(cart, **_):
342    label = cart.label or MultidimArray(k_label_size, 0)
343    return create_screenshot_surface(label, transparent=True).save()
def write_cart_spritesheet(cart, palette=None, **_):
345def write_cart_spritesheet(cart, palette=None, **_):
346    spritesheet = MultidimArray(k_label_size, 0)    
347    for y in range(128):
348        for x in range(128):
349            spritesheet[x, y] = cart.rom.get4(mem_sprite_addr(x, y))
350
351    palette = get_real_palette(palette)
352    return create_screenshot_surface(spritesheet, palette=palette).save()
k_p8_prefix = 'pico-8 cartridge'
k_meta_prefix = 'meta:'
def read_cart_from_source(data, path=None, raw=False, preprocess_hook=None, **opts):
357def read_cart_from_source(data, path=None, raw=False, preprocess_hook=None, **opts):
358    cart = Cart(path=path)
359    
360    def nybbles(line):
361        for b in line:
362            yield int(b, 16)
363    
364    def nybble_groups(line, n):
365        for i in range(0, len(line), n):
366            yield nybbles(line[i:i+n].ljust(n, "0"))
367    
368    def bytes(line):
369        for i in range(0, len(line), 2):
370            yield int(line[i:i+2].ljust(2, "0"), 16)
371    
372    def ext_nybbles(line):
373        for b in line:
374            if 'v' >= b.lower() >= 'g':
375                yield ord(b.lower()) - ord('g') + 16
376            else:
377                yield int(b, 16)
378      
379    def p8_split_lines(str):
380        split = re.split("\r?\n", str)
381        if split and not split[-1]:
382            split.pop()
383        return split
384
385    if not raw and not data.startswith(k_p8_prefix) and not data.startswith("__lua__"): # fallback to raw
386        raw = True
387    
388    header = "lua" if raw else None
389    code = []
390    code_line = 0
391    y = 0
392    for line_i, line in enumerate(p8_split_lines(data)):
393        try:
394            clean = line.strip()
395            
396            if line.startswith("__") and clean.endswith("__") and not raw: # may end with whitespace
397                header = clean[2:-2]
398                y = 0
399                
400            elif header == "lua":
401                if y == 0:
402                    code_line = line_i
403                else:
404                    code.append("\n")
405                code.append(to_p8str(line))
406                y += 1
407                
408            elif header == "gfx" and clean and y < 0x80:
409                x = 0
410                for b in nybbles(clean):
411                    if x < 0x80:
412                        cart.rom.set4(mem_sprite_addr(x, y), b)
413                        x += 1
414                y += 1
415                    
416            elif header == "map" and clean and y < 0x40: # usually 0x20
417                x = 0
418                for b in bytes(clean):
419                    if x < 0x80:
420                        cart.rom.set8(mem_map_addr(x, y), b)
421                        x += 1
422                y += 1
423                    
424            elif header == "gff" and clean and y < 2:
425                x = 0
426                for b in bytes(clean):
427                    if x < 0x80:
428                        cart.rom.set8(mem_flag_addr(x, y), b)
429                        x += 1
430                y += 1
431                
432            elif header == "sfx" and clean and y < 0x40:
433                x = 0
434                for b in bytes(clean[:8]):
435                    cart.rom.set8(mem_sfx_info_addr(y, x), b)
436                    x += 1
437                x = 0
438                for bph, bpl, bw, bv, be in nybble_groups(clean[8:], 5):
439                    if x < 0x20:
440                        value = bpl | ((bph & 0x3) << 4) | ((bw & 0x7) << 6) | ((bv & 0x7) << 9) | ((be & 0x7) << 12) | ((bw & 0x8) << 12) 
441                        cart.rom.set16(mem_sfx_addr(y, x), value)
442                        x += 1
443                y += 1
444                
445            elif header == "music" and clean and y < 0x40:
446                x = 0
447                flags = next(bytes(clean[:2]))
448                for b in bytes(clean[3:]):
449                    if x < 4:
450                        value = b | (((flags >> x) & 1) << 7) 
451                        cart.rom.set8(mem_music_addr(y, x), value)
452                        x += 1
453                y += 1
454
455            elif header == "label" and clean and y < 0x80:
456                if cart.label is None:
457                    cart.label = MultidimArray(k_label_size, 0)
458                x = 0
459                for b in ext_nybbles(clean):
460                    if x < 0x80:
461                        cart.label[x, y] = b
462                        x += 1
463                y += 1
464
465            elif header and header.startswith(k_meta_prefix):
466                cart.meta[header[len(k_meta_prefix):]].append(line.rstrip('\n'))
467                
468            elif header == None and clean.startswith("version "):
469                cart.set_version(int(clean.split()[1]))
470
471        except ValueError:
472            throw(f"Invalid {header} line in p8 file (line #{line_i + 1})")
473            
474    preprocess = default(preprocess_hook, preprocess_code)
475    cart.code, cart.code_map = preprocess(path, "".join(code), code_line, **opts)
476    return cart
def write_cart_to_source(cart, unicode_caps=False, sections=None, **_):
478def write_cart_to_source(cart, unicode_caps=False, sections=None, **_):
479    lines = [k_p8_prefix + " // http://www.pico-8.com"]
480    lines.append(f"version {cart.version_id}")
481    defrom = mem_create_rom()
482
483    def include(section):
484        return sections is None or section in sections
485
486    def nybbles(data):
487        return "".join('%01x' % b for b in data)
488    
489    def nybble_groups(data):
490        return "".join([nybbles(group) for group in data])
491    
492    def bytes(data):
493        return "".join('%02x' % b for b in data)
494
495    def ext_nybbles(data):
496        return "".join(('%01x' % b if b < 16 else chr(b - 16 + ord('g'))) for b in data)
497
498    def get_needed_lines(max_lines, addr_func, size):
499        lines = max_lines
500        for y in reversed(range(max_lines)):
501            if cart.rom.cmpeqwith8(addr_func(y), size, defrom):
502                lines -= 1
503            else:
504                break
505        return lines
506
507    if include("lua"):
508        lines.append("__lua__")
509        lines.append(from_p8str(cart.code, unicaps=unicode_caps))
510
511    if include("gfx"):
512        gfx_lines = get_needed_lines(0x80, lambda y: mem_sprite_addr(0, y)[0], 0x40)
513        if gfx_lines:
514            lines.append("__gfx__")
515            for y in range(gfx_lines):
516                lines.append(nybbles(cart.rom.get4(mem_sprite_addr(x, y)) for x in range(128)))
517
518    if include("map"):
519        map_lines = get_needed_lines(0x20, lambda y: mem_map_addr(0, y), 0x80)
520        if map_lines:
521            lines.append("__map__")
522            for y in range(map_lines):
523                lines.append(bytes(cart.rom.get8(mem_map_addr(x, y)) for x in range(128)))
524
525    if include("gff"):
526        gff_lines = get_needed_lines(2, lambda y: mem_flag_addr(0, y), 0x80)
527        if gff_lines:
528            lines.append("__gff__")
529            for y in range(gff_lines):
530                lines.append(bytes(cart.rom.get8(mem_flag_addr(x, y)) for x in range(128)))
531
532    if include("sfx"):
533        sfx_lines = get_needed_lines(0x40, lambda y: mem_sfx_addr(y, 0), 0x44)
534        if sfx_lines:
535            lines.append("__sfx__")
536            for y in range(sfx_lines):
537                info = bytes(cart.rom.get8(mem_sfx_info_addr(y, x)) for x in range(4))
538                notes = (cart.rom.get16(mem_sfx_addr(y, x)) for x in range(32))
539                note_groups = nybble_groups(((n >> 4) & 0x3, n & 0xf, ((n >> 6) & 0x7) | (n >> 12) & 0x8, (n >> 9) & 0x7, (n >> 12) & 0x7) for n in notes)
540                lines.append(info + note_groups)
541
542    if include("music"):
543        music_lines = get_needed_lines(0x40, lambda y: mem_music_addr(y, 0), 0x4)
544        if music_lines:
545            lines.append("__music__")
546            for y in range(music_lines):
547                chans = [cart.rom.get8(mem_music_addr(y, x)) for x in range(4)]
548                flags = bytes((sum(((ch >> 7) & 1) << i for i, ch in enumerate(chans)),))
549                ids = bytes(ch & 0x7f for ch in chans)
550                lines.append(flags + " " + ids)
551    
552    if include("label") and cart.label and any(cart.label.array):
553        lines.append("__label__")
554        for y in range(128):
555            lines.append(ext_nybbles(cart.label[x, y] for x in range(128)))
556    
557    for meta, metalines in cart.meta.items():
558        if include(k_meta_prefix + meta):
559            lines.append(f"__{k_meta_prefix + meta}__")
560            lines += metalines
561
562    return "\n".join(lines) + "\n"
def write_cart_to_raw_source(cart, with_header=False, unicode_caps=False, **_):
564def write_cart_to_raw_source(cart, with_header=False, unicode_caps=False, **_):
565    source = from_p8str(cart.code, unicaps=unicode_caps)
566    if with_header:
567        source = "__lua__\n" + source
568    return source
def iter_rect(width, height):
570def iter_rect(width, height):
571    for y in range(height):
572        for x in range(width):
573            yield x, y
k_base64_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'
k_base64_alt_chars = b'_-'
k_base64_char_map = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25, 'a': 26, 'b': 27, 'c': 28, 'd': 29, 'e': 30, 'f': 31, 'g': 32, 'h': 33, 'i': 34, 'j': 35, 'k': 36, 'l': 37, 'm': 38, 'n': 39, 'o': 40, 'p': 41, 'q': 42, 'r': 43, 's': 44, 't': 45, 'u': 46, 'v': 47, 'w': 48, 'x': 49, 'y': 50, 'z': 51, '0': 52, '1': 53, '2': 54, '3': 55, '4': 56, '5': 57, '6': 58, '7': 59, '8': 60, '9': 61, '_': 62, '-': 63}
def pico_base64_encode(data):
579def pico_base64_encode(data):
580    return base64.b64encode(data, k_base64_alt_chars)
def pico_base64_decode(data, validate=False):
582def pico_base64_decode(data, validate=False):
583    return base64.b64decode(data, k_base64_alt_chars, validate=validate)
def read_cart_from_url(url, size_handler=None, **opts):
588def read_cart_from_url(url, size_handler=None, **opts):
589    if size_handler:
590        print_url_size(len(url), prefix="input", handler=size_handler)
591
592    if "?" not in url:
593        throw("Invalid url - no '?'")
594
595    code, gfx = None, None
596    
597    url_params = url.split("?", 1)[1]
598    for url_param in url_params.split("&"):
599        if "=" not in url_param:
600            throw(f"Invalid url param: {url_param}")
601        
602        key, value = url_param.split("=", 1)
603        if key == "c":
604            code = value
605        elif key == "g":
606            gfx = value
607        else:
608            throw(f"Unknown url param: {key}")
609
610    cart = Cart()
611
612    if code:
613        codebuf = pico_base64_decode(code, validate=True).ljust(k_code_size, b'\0')
614        with BinaryReader(BytesIO(codebuf), big_end = True) as r:
615            cart.code, cart.code_rom = read_code_from_rom(r, **opts)
616
617    if gfx:
618        i = 0
619        rect = iter_rect(128, 128)
620        while i < len(gfx):
621            val = k_base64_char_map[gfx[i]]
622            i += 1
623
624            color = val & 0xf
625            count = (val >> 4) + 1
626            if count == 4:
627                count += k_base64_char_map[gfx[i]]
628                i += 1
629
630            for _ in range(count):
631                x, y = next(rect)
632                cart.rom.set4(mem_sprite_addr(x, y), color)
633
634    return cart
k_url_prefix = 'https://www.pico-8-edu.com'
def write_cart_to_url( cart, url_prefix='https://www.pico-8-edu.com', force_compress=False, size_handler=None, **opts):
638def write_cart_to_url(cart, url_prefix=k_url_prefix, force_compress=False, size_handler=None, **opts):
639    raw_code = write_cart_to_tiny_rom(cart, **opts)        
640    code = pico_base64_encode(raw_code)
641
642    rect = iter_rect(128, 128)
643    gfx = []
644    x, y = next(rect)
645    done = False
646    while not done:
647        color = cart.rom.get4(mem_sprite_addr(x, y))
648        total_count = 1
649        for x, y in rect:
650            next_color = cart.rom.get4(mem_sprite_addr(x, y))
651            if next_color == color:
652                total_count += 1
653            else:
654                break
655        else:
656            done = True
657            if color == 0:
658                total_count = 0
659
660        while total_count > 0:
661            count = min(total_count, 63 + 4)
662            total_count -= count
663
664            val = (min(count - 1, 3) << 4) | color
665            gfx.append(k_base64_chars[val])
666
667            if count >= 4:
668                gfx.append(k_base64_chars[count - 4])
669
670    url = url_prefix
671    url += "/?c=" + code.decode()
672    if gfx:
673        url += "&g=" + "".join(gfx)
674    
675    if size_handler:
676        print_url_size(len(url), handler=size_handler)
677        
678    check(len(url) - k_url_prefix_size <= k_url_size, "url has too many characters!")
679    return url
k_clip_prefix = '[cart]'
k_clip_suffix = '[/cart]'
def read_raw_from_clip(clip):
684def read_raw_from_clip(clip):
685    if clip.startswith(k_clip_prefix) and clip.endswith(k_clip_suffix):
686        return bytes.fromhex(clip[len(k_clip_prefix):-len(k_clip_suffix)])        
687    else:
688        throw("Invalid clipboard tag")
def read_cart_from_clip(clip, **opts):
690def read_cart_from_clip(clip, **opts):
691    data = read_raw_from_clip(clip)
692    return read_cart_from_image(data, **opts)
def write_raw_to_clip(data):
694def write_raw_to_clip(data):
695    return k_clip_prefix + data.hex() + k_clip_suffix
def write_cart_to_clip(cart, **opts):
697def write_cart_to_clip(cart, **opts):
698    return write_raw_to_clip(write_cart_to_image(cart, **opts))
def read_cart_autodetect(path, **opts):
700def read_cart_autodetect(path, **opts):
701    data = file_read(path)
702
703    if data.startswith(k_png_header):
704        return read_cart_from_image(data, path=path, **opts)
705
706    text = data.decode(errors="surrogateescape")
707
708    # cart?
709    if text.startswith(k_p8_prefix) or text.startswith("__lua__"):
710        return read_cart_from_source(text, path=path, **opts)
711        
712    # clip?
713    if text.startswith(k_clip_prefix):
714        return read_cart_from_clip(text.rstrip(), path=path, **opts)
715
716    # url?
717    if text.startswith(k_url_prefix):
718        return read_cart_from_url(text.rstrip(), path=path, **opts)
719
720    # plain text?
721    return read_cart_from_source(text, raw=True, path=path, **opts)
def read_cart(path: str, format: CartFormat = None, **opts):
723def read_cart(path: str, format: CartFormat = None, **opts):
724    """Read a cart from the given path, assuming it is in the given format"""
725    if format in (None, CartFormat.auto):
726        return read_cart_autodetect(path, **opts)
727    elif format in (CartFormat.p8, CartFormat.code):
728        return read_cart_from_source(file_read_maybe_text(path), path=path, **opts)
729    elif format == CartFormat.png:
730        return read_cart_from_image(file_read(path), path=path, **opts)
731    elif format in (CartFormat.rom, CartFormat.tiny_rom):
732        return read_cart_from_rom(file_read(path), path=path, allow_tiny=True, **opts)
733    elif format == CartFormat.clip:
734        return read_cart_from_clip(file_read_text(path).rstrip(), path=path, **opts)
735    elif format == CartFormat.url:
736        return read_cart_from_url(file_read_text(path).rstrip(), path=path, **opts)
737    elif format == CartFormat.lua:
738        return read_cart_from_source(file_read_maybe_text(path), raw=True, path=path, **opts)
739    elif format == CartFormat.label:
740        return read_cart_label(file_read(path), path=path, **opts)
741    elif format == CartFormat.spritesheet:
742        return read_cart_spritesheet(file_read(path), path=path, **opts)
743    elif format.is_export:
744        return read_from_cart_export(path, format, **opts)
745    else:
746        throw(f"invalid format for reading: {format}")

Read a cart from the given path, assuming it is in the given format

def write_cart( path: str, cart: Cart, format: CartFormat, **opts):
748def write_cart(path: str, cart: Cart, format: CartFormat, **opts):
749    """Writes a cart to the given path in the given format"""
750    if format == CartFormat.p8:
751        file_write_text(path, write_cart_to_source(cart, **opts))
752    elif format == CartFormat.png:
753        file_write(path, write_cart_to_image(cart, **opts))
754    elif format == CartFormat.rom:
755        file_write(path, write_cart_to_rom(cart, **opts))
756    elif format == CartFormat.tiny_rom:
757        file_write(path, write_cart_to_tiny_rom(cart, **opts))
758    elif format == CartFormat.clip:
759        file_write_text(path, write_cart_to_clip(cart, **opts))
760    elif format == CartFormat.url:
761        file_write_text(path, write_cart_to_url(cart, **opts))
762    elif format == CartFormat.lua:
763        file_write_text(path, write_cart_to_raw_source(cart, **opts))
764    elif format == CartFormat.code:
765        file_write_text(path, write_cart_to_raw_source(cart, with_header=True, **opts))
766    elif format == CartFormat.label:
767        file_write(path, write_cart_label(cart, **opts))
768    elif format == CartFormat.spritesheet:
769        file_write(path, write_cart_spritesheet(cart, **opts))
770    elif format.is_export:
771        write_to_cart_export(path, cart, format, **opts)
772    else:
773        throw(f"invalid format for writing: {format}")

Writes a cart to the given path in the given format

def get_bbs_cart_url(id, lang=Language.pico8):
775def get_bbs_cart_url(id, lang=Language.pico8):
776    if not id.startswith("#"):
777        throw("invalid bbs id - # prefix expected")
778
779    if lang == Language.pico8:
780        category = 7
781    elif lang == Language.picotron:
782        category = 8
783    else:
784        throw("invalid bbs cart language")
785
786    from urllib.parse import urlencode
787    params = {"lid": id[1:], "cat": category}
788
789    return "https://www.lexaloffle.com/bbs/get_cart.php?" + urlencode(params)
k_pico_sections = ('lua', 'gfx', 'map', 'gff', 'sfx', 'music', 'label', 'meta:*')
def merge_cart(dest: Cart, src: Cart, sections: list):
793def merge_cart(dest: Cart, src: Cart, sections: list):
794    """Copy the given sections (see k_pico_sections) from src to dest"""
795
796    for section in sections:
797        if section == "lua":
798            dest.code, dest.code_map, dest.code_rom = src.code, src.code_map, src.code_rom
799        elif section == "gfx":
800            dest.rom.copyfrom8(k_mem_sprites_addr, k_mem_map_addr - k_mem_sprites_addr, src.rom)
801        elif section == "map":
802            dest.rom.copyfrom8(k_mem_map_addr, k_mem_flag_addr - k_mem_map_addr, src.rom)
803        elif section == "gff":
804            dest.rom.copyfrom8(k_mem_flag_addr, k_mem_music_addr - k_mem_flag_addr, src.rom)
805        elif section == "music":
806            dest.rom.copyfrom8(k_mem_music_addr, k_mem_sfx_addr - k_mem_music_addr, src.rom)
807        elif section == "sfx":
808            dest.rom.copyfrom8(k_mem_sfx_addr, k_rom_size - k_mem_sfx_addr, src.rom)
809        elif section == "label":
810            dest.label = src.label
811        elif section.startswith(k_meta_prefix):
812            meta_name = section[len(k_meta_prefix):]
813            dest.meta[meta_name] = src.name[meta_name]
814        else:
815            throw(f"unknown cart section: '{section}'")

Copy the given sections (see k_pico_sections) from src to dest

def write_cart_version(cart):
817def write_cart_version(cart):
818    if cart.default_version:
819        print("no version info")
820    else:
821        print("version:", format_pico8_version(cart.version_tuple))
822        print("raw version: %d (%d.%d.%d.%d)" % (cart.version_id, *cart.version_tuple))
823
824    if not cart.default_platform:
825        print("platform:", format_platform(cart.platform))