Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/bit_world/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@
- Never slice a panel's buffer from Python (`buf[a:b] = ...`): on an ESP32-S3 each row costs milliseconds. Copy rectangles with `FrameBuffer.blit`, as `restore_rects` does.
- Draw into frames from `make_fb` or `make_canvas`. On MicroPython they draw with the built-in framebuf, which allocates nothing, and send text, `text16`, `blit_alpha` and big copies to a pygraphics `FrameBuffer` made by `gfx_frame` with `areas=False`, so those return nothing either; a pygraphics without that keyword returns a new `Area` from each. A frame that allocates a few kilobytes collects every few seconds, and on an ESP32 with PSRAM a collection stops the picture for about 200 ms. Measure with `gc.mem_alloc()` around `update` and `draw_changes`, and keep text and tuples out of the per-frame path when their values haven't changed.
- Keep what changes every frame in whole numbers: positions in fixed point, timers in milliseconds, repaint rectangles in reused arrays. On MicroPython every float result is a new heap object, and one particle's position, speed and life made three a frame.
- Big pixel buffers come from `pixel_bytes` in `bit_palette.py`: an `offheap.Buffer` where the firmware has `offheap`, else a bytearray. The collector skips a Buffer's bytes: on an ESP32-S31 the frame a collection lands in went from 240-290 ms to 47-71 ms, and `gc.collect()` from about 195 ms to 25 ms. A memoryview of a Buffer doesn't keep it alive, so keep the Buffer itself beside any view, as the acts' `bg_buf` and the sprites' `atlas_buf` do.
20 changes: 18 additions & 2 deletions apps/bit_world/bit_palette.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@
except ImportError: # CPython and CircuitPython: pygraphics draws everything
framebuf = None

try:
from offheap import Buffer as OffHeapBuffer
except ImportError: # CPython, CircuitPython and firmware without offheap
OffHeapBuffer = None

# Change these to match your setup.
REF_WIDTH = 800 # Reference landscape design width in pixels
REF_HEIGHT = 480 # Reference landscape design height in pixels
Expand Down Expand Up @@ -376,9 +381,20 @@ def make_draw(fb):
return Draw(getattr(fb, "gfx", fb))


# Build a reusable RGB565 frame tuple (bytearray, frame from make_canvas).
# n zeroed bytes for pixels. With offheap they live outside the garbage-collected
# heap, which reads every word of a bytearray at each collection: on an ESP32 the
# three 800x480 backgrounds made every collection stop the picture for 200 ms or
# more. Keep the returned object for as long as anything draws into it, because a
# memoryview of it doesn't keep it alive.
def pixel_bytes(n):
if OffHeapBuffer is None:
return bytearray(n)
return OffHeapBuffer(n)


# Build a reusable RGB565 frame tuple (pixel_bytes, frame from make_canvas).
def make_fb(w, h, fill_color=None):
buf = bytearray(w * h * 2)
buf = pixel_bytes(w * h * 2)
fb = make_canvas(buf, w, h)
if fill_color is not None:
fb.fill(fill_color)
Expand Down
10 changes: 5 additions & 5 deletions apps/bit_world/bit_sprites.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
Stores all multi-shade pixel-art grids and 8-bit radial alpha glow masks inside
one contiguous bytes literal wrapped in a memoryview (following the iconkit
frozen-flash pattern). At startup, unpacks scaled RGB565 sprites into a single
shared bytearray atlas and renders antialiased glows directly from memoryview
shared atlas and renders antialiased glows directly from memoryview
slices via FrameBuffer.blit_alpha.

Needs: pygraphics, bit_palette.
"""

from bit_palette import KEY, PALETTE_LUT, make_canvas
from bit_palette import KEY, PALETTE_LUT, make_canvas, pixel_bytes

# Flat tuple of (offset, width, height) descriptors into DATA for each sprite.
SPRITE_META = (
Expand Down Expand Up @@ -509,7 +509,7 @@ def _unpack_into(meta_idx, scale, flip_x, view_slice):


class SpriteBank:
"""Unpack all scaled sprites into one shared bytearray atlas and expose glows."""
"""Unpack all scaled sprites into one shared atlas and expose glows."""

def __init__(self, layout):
self.layout = layout
Expand Down Expand Up @@ -548,13 +548,13 @@ def __init__(self, layout):
specs.append((27, self.game_px, False))
specs.append((28, self.prop_px, False))

# Compute total atlas bytes so we make only a single bytearray allocation.
# Compute total atlas bytes so we make only a single allocation.
total_bytes = 0
for meta_idx, sc, _ in specs:
_, sw, sh = SPRITE_META[meta_idx]
total_bytes += (sw * sc) * (sh * sc) * 2

self.atlas_buf = bytearray(total_bytes)
self.atlas_buf = pixel_bytes(total_bytes)
self.atlas_mv = memoryview(self.atlas_buf)

unpacked = []
Expand Down
3 changes: 3 additions & 0 deletions apps/bit_world/bit_world.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
VOID,
WHITE,
Layout,
OffHeapBuffer,
PanelState,
draw_pixel_panel,
draw_pixel_wipe,
Expand Down Expand Up @@ -117,6 +118,8 @@ def __init__(self):
# the sound and the acts' smaller objects, the last of them can find no
# piece big enough on a heap with plenty free in total.
gc.collect()
if OffHeapBuffer is None and sys.implementation.name == "micropython":
print("Bit World: this firmware has no offheap, so the frames are in the heap and each collection pauses the picture")
if not self.direct:
self.screen_buf, self.screen_fb = make_fb(WIDTH, HEIGHT, VOID)
self.screen_draw = make_draw(self.screen_fb)
Expand Down
2 changes: 1 addition & 1 deletion tools/app_packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@
"_audioif", "_thread", "_usbhost", "array", "asyncio", "audioairwindows", "audiobiquad", "audiobusio", "audiocore",
"audiofeatures", "audiomixer", "btclassic", "audiomp3", "audiopump", "audiospeed", "cameraif", "castif", "earful",
"errno", "esp32", "espdl", "framebuf", "gc", "h264enc", "image", "jpegio", "json", "lvgl", "machine",
"math", "mdns", "micropython", "microcontroller", "network", "numpy", "os", "platform", "ppa", "random",
"math", "mdns", "micropython", "microcontroller", "network", "numpy", "offheap", "os", "platform", "ppa", "random",
"scipy", "select", "socket", "ssl", "struct", "svgio", "synthio", "sys", "tflite", "time", "uasyncio", "uctypes", "ulab",
"usb",
}
Expand Down