From dbe56a9feeebf93c7666a6e33c3458a8d801fa1c Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 5 Dec 2026 17:17:42 +0100 Subject: [PATCH 1/4] Voidskim performance improved and icons replcaed --- Apps/Voidskim/PERFORMANCE.md | 112 ++++++ Apps/Voidskim/README.md | 5 +- Apps/Voidskim/icon.svg | 2 +- Apps/Voidskim/icon_mono.svg | 2 +- Apps/Voidskim/main/Source/JetConfig.hpp | 16 +- Apps/Voidskim/main/Source/core/Game.cpp | 5 + Apps/Voidskim/main/Source/core/Game.h | 5 +- Apps/Voidskim/main/Source/main.cpp | 18 +- .../main/Source/platform/DisplayOutput.cpp | 347 ++++++++++++++++-- .../main/Source/platform/DisplayOutput.h | 27 +- .../main/Source/platform/Profiler.cpp | 106 ++++++ Apps/Voidskim/main/Source/platform/Profiler.h | 88 +++++ .../main/Source/render/WorldRenderer.cpp | 118 ++++-- .../main/Source/render/WorldRenderer.h | 12 +- Apps/Voidskim/manifest.properties | 5 +- 15 files changed, 776 insertions(+), 92 deletions(-) create mode 100644 Apps/Voidskim/PERFORMANCE.md create mode 100644 Apps/Voidskim/main/Source/platform/Profiler.cpp create mode 100644 Apps/Voidskim/main/Source/platform/Profiler.h diff --git a/Apps/Voidskim/PERFORMANCE.md b/Apps/Voidskim/PERFORMANCE.md new file mode 100644 index 0000000..b94e0d2 --- /dev/null +++ b/Apps/Voidskim/PERFORMANCE.md @@ -0,0 +1,112 @@ +# Performance + +What was tried to make Voidskim faster on ESP32 devices, what helped and what didn't. Measured on an ESP32-S3 with a 320x240 SPI display (LilyGO T-Deck) and an ESP32-P4 with a 1280x720 MIPI-DSI display (M5Stack Tab5, frame 640x360 scaled up by the PPA). Medium 3D quality (75%) unless stated; the default is high. + +## Measuring + +`main/Source/platform/Profiler.h` logs the frame time per phase every 3 seconds (`VOIDSKIM_PROFILE`, on by default): + +``` +VoidskimProfile: 25.6 fps, ms/frame: update 1.49, 3D 20.06, scale 4.58, overlay 3.20, present 5.29, total 39.08 +``` + +- `update`: game logic and simulation. +- `3D`: Jet's transform, sort and rasterisation. +- `scale`: scaling the 3D up into the frame. +- `overlay`: HUD, menus and touch controls. +- `present`: sending the frame to the display. With the display task (see below), it's only the wait for the display task to be ready for the next frame. + +A second line shows what the 3D culled, averaged per frame: + +``` +VoidskimProfile: 3D per frame: objects of after frustum cull, triangles queued, rasterised, of +``` + +- `objects`: meshes that survived Jet's frustum cull (bounding sphere, then bounding box), out of all meshes. The track is one mesh per 8 samples (32 m), plus the start gantry and each craft. +- `queued`: triangles of those meshes left after per-triangle culling (back faces, zero area, near/far plane). +- `rasterised`: triangles that drew pixels. + +A third line shows the display task (see below), per frame: + +``` +VoidskimProfile: Display per frame: convert 12.50 ms, waiting for a band buffer 15.27 ms, send 27.28 ms +``` + +- `convert`: the frame converted to the panel's pixel format, a band of rows at a time. On chips with a PPA (P4, S31): the PPA scaling and rotating the frame into the panel's frame buffer. +- `waiting`: the conversion waiting for the sender to free a band buffer (software path only). +- `send`: `display_draw_bitmap()` sending the bands over the bus. With the panel's own frame buffers (Tab5) it only switches buffers, ~0.1 ms. + +## Where it stands + +About 36 fps at medium quality, 35 at high: update ~1.3 ms, 3D ~9.5 ms (high ~12), scale ~4.6 ms, overlay ~3.6 ms, so the game needs ~20 ms per frame. Sending a frame takes ~27 ms (150 KB over SPI), which caps the frame rate at ~36 fps, so the game waits for the display. A faster frame needs a faster SPI clock (firmware) or fewer bytes sent. + +On the ESP32-P4 (Tab5): ~36 fps in a race, ~23 in the menu (from ~26 and ~18). Update ~0.7 ms, 3D ~8.5 ms, scale ~14 ms, overlay ~2 ms (menu ~17 ms), and the PPA needs ~21 ms per frame on the display task. The game is the limit: mostly the software scale-up into the 640x360 frame, and the menu's semi-transparent panels. + +## Starting point + +About 18 fps: update ~1.5 ms, 3D ~17 ms, scale ~4.7 ms, overlay ~3–6 ms, present ~24 ms. Sending the frame to the display took almost half of every frame. + +## What helped + +### Sending frames on the other core: 18 → 26 fps + +`present` mostly waits for the SPI display bus. The game runs on core 1. A display task on core 0 now converts and sends a frame while the game draws the next one into a second frame buffer (`DisplayOutput`, `Game::setFramebuffer()`). A frame now takes as long as the slower of the two, not both together. `present` dropped from ~24 ms to 0–6 ms of waiting. + +Costs a second frame buffer in PSRAM (150 KB at 320x240). Used for colour displays on dual core chips without a PPA. Monochrome displays, chips with a PPA (P4, S31) and single core chips still send frames on the game's core. + +### Converting a band while the previous one is sent: 26 → 36 fps + +`display_draw_bitmap()` blocks until a band has been sent, so the display task converted (~10 ms per frame) and sent (~27 ms) one after the other: ~38 ms per frame, whatever the game did. A sender task now does the sending, while the display task converts the next band into a second band buffer (16 KB of internal DMA RAM). A frame now takes as long as sending it. + +### Half width rendering with fast span fills: 3D 20 → 9.5 ms + +Jet's fast span fills (`JET_FAST_SIMPLE_SPANS`) fill each row of a flat triangle with 32-bit stores. Without them, every pixel goes through the general rasteriser loop (edge tests and dither per pixel). Jet only enables them with `HALF_WIDTH_BUFFERS` (one stored pixel per two columns) and without `DEPTH_ALPHA_BLEND` (distance fog). With `FAST_Z` the fog is one alpha per triangle, which the span path dithers already, so `JetConfig.hpp` turns them on with the fog kept. The 3D has half the horizontal resolution; the HUD and menus keep the full resolution. On its own this didn't raise the frame rate, as the display was the limit then. + +The 3D buffer rows must start 16-byte aligned: Jet's ESP32-S3 clear uses 128-bit stores that ignore the low address bits. An unaligned buffer had them overwrite the heap header in front of it, which crashed the app on exit (`WorldRenderer::applyResolution()`). + +### The display task on chips with a PPA (P4, S31) + +The PPA scale and `display_draw_bitmap()` (~17 ms) run on the display task too. Two things went wrong on the Tab5 first, both showing as flashes: + +- **Cache write-back on the wrong core.** Each P4 core has its own L1 data cache. The frame was written back from the CPU caches (`esp_cache_msync()`) for the PPA on the display task's core, which misses lines still dirty in the drawing core's cache: the PPA read stale parts of the frame. Worst in the menu, whose semi-transparent panels write a lot. `present()` now does the write-back on the core that drew the frame. +- **Suspected: writing into the buffer on screen.** The Tab5 allows tearing, so `display_draw_bitmap()` with a panel frame buffer only queues the switch, and the other buffer is on screen until the next refresh. A test that waited 17 ms after each switch before the next PPA write made no visible difference once the cache write-back was fixed, so it was removed. + +### Welding vertices + +Faces that meet now share their corners (`MeshBuilder` in `WorldRenderer.cpp`), so Jet transforms each corner once per frame instead of once per face that uses it. On Harbor Loop: 9116 → 2813 vertices. Its effect on the frame rate wasn't measured on its own (it went in with the first profiling build), but it costs nothing and saves memory. + +## What didn't help + +### Voxels instead of polygons + +Considered, not built. The world is a thin ribbon of track over an empty void. A voxel ray caster pays for every pixel, and void pixels are its worst case (a ray marches to its full distance). It also reads the voxel data at random places in PSRAM, which is slow. Cheap heightmap voxels (one height per column) can't draw tunnels, bridges, overpasses or the underside of the track. Polygons draw a few hundred visible triangles, so they're the cheaper choice for this scene. + +### Rendering into internal RAM: at most 1 fps + +(Measured before the fast span fills, with the general rasteriser loop.) + + +The theory: Jet's painter's algorithm writes most pixels several times, and PSRAM is much slower than internal RAM, so a render target in internal RAM should be faster. There isn't enough internal RAM for a whole frame (the largest free block is ~31 KB, a frame is 86–150 KB). So the 3D was rasterised in bands of rows into a 16 KB internal buffer (Jet's `prepareFrame()` / `clearBand()` / `rasterizeBand()`), and each band was copied into the frame. + +Result: `3D` didn't get faster (it got a little slower: triangles crossing band edges are set up once per band). Only the scale-up got faster, 4.7 → 3.1 ms, as it read from internal RAM. In total at most 1 fps. The rasteriser is limited by the CPU, not by memory: most likely the ESP32-S3's data cache absorbs the overdraw, since a triangle writes neighbouring pixels. Removed again: all frame buffers are in PSRAM, which keeps internal RAM free for the system. + +### Better frustum culling: not needed + +Jet already culls each mesh against the view (bounding sphere, then bounding box) and then each triangle (back faces, zero area, near/far plane). The profiler's second line shows it works: during a race 11–12 of 43 meshes survive, ~300 of ~4900 triangles are queued and ~250 rasterised. The bounding boxes are large (each track mesh includes its pillars and towers), but tighter ones can't save much when only ~300 triangles are left. The 3D time (~20 ms for ~250 triangles at 240x180) went into filling pixels, not into vertices or culling: see the fast span fills above. + +### Scaling the 3D up with the PPA (P4, S31): no gain, and flashes + +The CPU scales the 3D up into the 640x360 frame in ~14 ms. The game's task got a PPA client of its own to do that, with 3D sizes that the PPA's 1/16 scale steps scale exactly (medium became 512x288). Measured on the Tab5: the same ~36 fps in a race and ~23 in the menu. `scale` only dropped to ~10–11 ms, as the game waited while the display task used the PPA (~20 ms per frame), and the 3D got slower (~8.5 → ~12 ms), most likely from the PPA's PSRAM traffic. The flashes came back too, and the PPA's smoothed scaling lost the sharp pixel look of the nearest neighbour scale-up. Removed, together with dropping the display task's cache write-back of the panel buffer after the PPA (~1 ms, tried at the same time). + +The PPA is the limit on the P4 now: it scales and rotates every frame to the panel, ~20 ms. + +### Enabling Jet's ESP32 mode + +Not possible. Jet's ESP32 mode places its hot functions in IRAM, and an ELF-loaded app can't do that (see `JetPlatform.h`). Jet's ESP32-S3 SIMD code paths don't depend on it and are already on. + +## Ideas not tried yet + +- `overlay` sometimes takes 9–13 ms (menus, pause, touch controls drawn), against ~3.6 ms during a race. Then the game needs more than the display's ~27 ms and the frame rate drops to ~28–33 fps. Worth profiling which 2D drawing it is. +- A faster SPI clock for the panel, in the firmware's device configuration: the display is the limit now. +- Less overdraw: pillars, towers and cliff faces extend far below the track (`DEBUG_OVERDRAW` in `JetConfig.hpp` shows it). Matters again once the display is faster. +- The menu's semi-transparent panels take ~17 ms on the P4: draw them opaque, or once into a cached layer. diff --git a/Apps/Voidskim/README.md b/Apps/Voidskim/README.md index ee9cf2e..32b901a 100644 --- a/Apps/Voidskim/README.md +++ b/Apps/Voidskim/README.md @@ -19,7 +19,7 @@ With no opponents it's a time trial: the HUD shows the current lap time and the | Pause | Escape, P | | pause button (top) | | Menus | arrows, Enter, Escape/Backspace, or the race keys | roll, click | tap a row (left half goes back, right half forward) | -**Settings** (in the main menu, and in the pause menu during a race) has the audio (music and effects, effects only, or off), the **3D quality** (low renders the world at 50% of the width and height and scales it up, medium, the default, at 75%, high at the full resolution: lower is faster on big screens, while the HUD and menus stay sharp), a frame rate counter, the **touch layout** (steering buttons on the left and the others on the right, or the other way round) and **Controls**, where you change the keys: pick a control and a slot, then press the new key (each control has two). A key belongs to one control at a time, so taking a key moves it. **Defaults** restores the keys above. Settings are saved in `settings.txt` in the app's user data directory. +**Settings** (in the main menu, and in the pause menu during a race) has the audio (music and effects, effects only, or off), the **3D quality** (low renders the world at 50% of the height and 25% of the width and scales it up, medium at 75% and 37.5%, high, the default, at the full height and half the width: lower is faster on big screens, while the HUD and menus stay sharp), a frame rate counter, the **touch layout** (steering buttons on the left and the others on the right, or the other way round) and **Controls**, where you change the keys: pick a control and a slot, then press the new key (each control has two). A key belongs to one control at a time, so taking a key moves it. **Defaults** restores the keys above. Settings are saved in `settings.txt` in the app's user data directory. Touch controls are shown on devices with a touch screen. They hide when you use a keyboard and come back when you touch the screen. @@ -99,7 +99,7 @@ main/Source/ `core/` and `render/` only use standard C++, so they also build into a desktop harness (used to render the test screenshots and to tune the AI and craft balance). -The game renders at a reduced resolution with the display's aspect ratio, at most 400x240 (640x360 on chips with a PPA). It's then scaled up and rotated to the panel: in hardware on ESP32-P4/S31, in software elsewhere. Monochrome and greyscale panels get an ordered dither. +The game renders at a reduced resolution with the display's aspect ratio, at most 400x240 (640x360 on chips with a PPA). It's then scaled up and rotated to the panel: in hardware on ESP32-P4/S31, in software elsewhere. Monochrome panels get an ordered dither, with black lines along the edges between faces. Greyscale panels show the frame's brightness. On dual core chips, a display task on the other core scales (with the PPA) or converts and sends each frame while the game draws the next one into a second frame buffer. Without a PPA, it converts a band of rows while a sender task sends the previous one. See [PERFORMANCE.md](PERFORMANCE.md). ### Networking (not implemented yet) @@ -136,5 +136,6 @@ The game thread only posts to the synth, and an audio task renders it into Tacti ## Notes +- [PERFORMANCE.md](PERFORMANCE.md) has frame time measurements, and what was tried to make the game faster. - Jet is built without its ESP32 mode: an ELF-loaded app can't place code in IRAM, so `JetPlatform.h` turns those placement attributes into no-ops. - `platform/CxxRuntime.cpp` provides `__cxa_atexit` for Jet's static scratch buffers. They're freed when the game exits. diff --git a/Apps/Voidskim/icon.svg b/Apps/Voidskim/icon.svg index 4ec54f0..7cc5d46 100644 --- a/Apps/Voidskim/icon.svg +++ b/Apps/Voidskim/icon.svg @@ -1 +1 @@ - + \ No newline at end of file diff --git a/Apps/Voidskim/icon_mono.svg b/Apps/Voidskim/icon_mono.svg index ba15066..36a70ee 100644 --- a/Apps/Voidskim/icon_mono.svg +++ b/Apps/Voidskim/icon_mono.svg @@ -1 +1 @@ - + \ No newline at end of file diff --git a/Apps/Voidskim/main/Source/JetConfig.hpp b/Apps/Voidskim/main/Source/JetConfig.hpp index 224fa64..12df152 100644 --- a/Apps/Voidskim/main/Source/JetConfig.hpp +++ b/Apps/Voidskim/main/Source/JetConfig.hpp @@ -162,7 +162,10 @@ // resolution; the display driver doubles each pixel on scanout. // Halves framebuffer RAM and fill bandwidth — critical on ESP32 SRAM. // Set to 0 on platforms with sufficient memory (e.g. high-res / large-RAM targets). -#define HALF_WIDTH_BUFFERS 0 +// Voidskim: on. The rasteriser's fast span fills (JET_FAST_SIMPLE_SPANS in Renderer.cpp) need it, +// and it halves the pixels to fill. WorldRenderer doubles the columns when scaling into the frame. +#define HALF_WIDTH_BUFFERS 1 + // FIELD_BUFFERS: Split the framebuffer into two half-height packed buffers — // one for even output rows, one for odd. The rasterizer alternates which @@ -324,3 +327,14 @@ // 10,792 bytes of static RAM. Use lookupSin/lookupCos rather than indexing the // full float_sin_table symbol, which is absent in this mode. Default 0. // #define JET_COMPACT_TRIG_TABLE 1 + +// --------------------------------------------------------------------------- +// Voidskim: fast span fills with fog +// --------------------------------------------------------------------------- +// Voidskim: Jet only enables its fast span fills when DEPTH_ALPHA_BLEND is off, but with FAST_Z the +// fog is one alpha per triangle (Renderer.cpp, "Triangle-level depth fog"), which the span path +// already dithers with SCREEN_DOOR_ALPHA. So they're turned on here, keeping the fog. Without this, +// every pixel goes through the general rasteriser loop (edge tests and dither per pixel). +#if FAST_Z && HALF_WIDTH_BUFFERS && !Z_BUFFERING && !Z_BRIGHTNESS && !NOISE_ALPHA && !DEBUG_OVERDRAW && !RENDER_TILE_BUFFER && MAX_PICK_QUERIES == 0 +#define JET_FAST_SIMPLE_SPANS 1 +#endif diff --git a/Apps/Voidskim/main/Source/core/Game.cpp b/Apps/Voidskim/main/Source/core/Game.cpp index 09d83d0..ed660d5 100644 --- a/Apps/Voidskim/main/Source/core/Game.cpp +++ b/Apps/Voidskim/main/Source/core/Game.cpp @@ -86,6 +86,11 @@ int Game::textScale() const { return std::max(1, canvas.height / 170); } +void Game::setFramebuffer(uint16_t* framebuffer) { + canvas.pixels = framebuffer; + world.setOutput(framebuffer); +} + bool Game::init(uint16_t* framebuffer, int width, int height, const GameConfig& gameConfig) { canvas = { framebuffer, width, height, nullptr }; config = gameConfig; diff --git a/Apps/Voidskim/main/Source/core/Game.h b/Apps/Voidskim/main/Source/core/Game.h index d9f2f10..40d3722 100644 --- a/Apps/Voidskim/main/Source/core/Game.h +++ b/Apps/Voidskim/main/Source/core/Game.h @@ -34,6 +34,9 @@ class Game { /** @param framebuffer RGB565, width x height, owned by the caller */ bool init(uint16_t* framebuffer, int width, int height, const GameConfig& config); + /** Renders the next frames into another buffer of the same size (double buffering). */ + void setFramebuffer(uint16_t* framebuffer); + /** Where sound goes. Optional: without it the game is silent. Must outlive the game. */ void setSound(SoundSystem* soundSystem) { sound = soundSystem; @@ -128,7 +131,7 @@ class Game { bool settingsFromPause = false; // opened from the pause menu: return there, over the frozen race bool showFps = false; bool steerOnRight = false; // touch controls mirrored: the steering buttons right, the others left - int quality = 1; // 3D resolution: 0 low, 1 medium (default), 2 high (full); the HUD and menus stay sharp + int quality = 2; // 3D resolution: 0 low, 1 medium, 2 high (default, full); the HUD and menus stay sharp void applyQuality(); // Frames per second, counted over half a second float fpsTime = 0.0f; diff --git a/Apps/Voidskim/main/Source/main.cpp b/Apps/Voidskim/main/Source/main.cpp index 4137001..4d7c6e2 100644 --- a/Apps/Voidskim/main/Source/main.cpp +++ b/Apps/Voidskim/main/Source/main.cpp @@ -7,6 +7,7 @@ #include "platform/CxxRuntime.h" #include "platform/DisplayOutput.h" #include "platform/PlatformInput.h" +#include "platform/Profiler.h" #include #include @@ -163,9 +164,20 @@ static void runGame(GameTaskParams& params) { const float frameTime = (float)(now - last) / 1000.0f; last = now; input.poll(state, now); - game->update(state, frameTime); - game->render(); - output.present(game->uiMask()); + { + hd::profile::Scope scope(hd::profile::Phase::Update); + game->update(state, frameTime); + } + { + hd::profile::Scope scope(hd::profile::Phase::Render); + game->render(); + } + { + hd::profile::Scope scope(hd::profile::Phase::Present); + output.present(game->uiMask()); + } + game->setFramebuffer(output.frame()); + hd::profile::frameDone(); vTaskDelay(1); // let lower priority tasks (and the watchdog) run } if (audioStarted) { diff --git a/Apps/Voidskim/main/Source/platform/DisplayOutput.cpp b/Apps/Voidskim/main/Source/platform/DisplayOutput.cpp index 50933cc..5cc762d 100644 --- a/Apps/Voidskim/main/Source/platform/DisplayOutput.cpp +++ b/Apps/Voidskim/main/Source/platform/DisplayOutput.cpp @@ -1,10 +1,14 @@ #include "DisplayOutput.h" +#include "Profiler.h" #include +#include +#include #include #include #ifdef ESP_PLATFORM +#include #include #endif @@ -24,9 +28,14 @@ constexpr auto* TAG = "VoidskimDisplay"; // Monochrome: UI pixels brighter than this are white constexpr uint32_t UI_THRESHOLD = 96; - -// Internal RAM to leave free for the system after placing the frame buffer there -constexpr size_t INTERNAL_RESERVE_BYTES = 96 * 1024; +// Monochrome: an edge line is drawn where a world pixel is at least this much brighter (luma, +// 0-255) than a neighbour, and at least EDGE_MIN_LUMA bright itself +constexpr uint32_t EDGE_LUMA_STEP = 40; +constexpr uint32_t EDGE_MIN_LUMA = 64; +// ...and the darker side continues this many pixels: further than a fog dither dot is wide. Fog +// dots are at least 2 columns wide, as the 3D renders at half width. +constexpr int EDGE_DEPTH_X = 3; +constexpr int EDGE_DEPTH_Y = 2; // The largest frame the game renders. Software 3D costs per pixel, so a big panel gets a smaller // frame, scaled up. Chips with a PPA have the CPU (and the hardware scaler) for more. @@ -50,7 +59,99 @@ bool swapRedBlue = false; // then need a DMA bounce buffer of the same size, which doesn't fit in internal RAM. uint16_t* bandBuffer = nullptr; int bandRows = 0; +size_t bandBytes = 0; constexpr size_t BAND_BYTES = 16 * 1024; + +#ifdef ESP_PLATFORM +// With the display task: a sender task sends one band while the display task converts the next +// into the other buffer (display_draw_bitmap() blocks until the band is sent). Both alternate +// between the two buffers: bandFree[i] when sendBands[i] may be written, bandReady[i] when it's +// ready to send. +struct BandJob { + int32_t xStart, yStart, xEnd, yEnd; + bool last; // of the frame + bool stop; // ends the sender task +}; +uint16_t* sendBands[2] = { nullptr, nullptr }; +BandJob bandJobs[2] = {}; +SemaphoreHandle_t bandFree[2] = { nullptr, nullptr }; +SemaphoreHandle_t bandReady[2] = { nullptr, nullptr }; +TaskHandle_t senderTask = nullptr; +int converterBand = 0; // the next buffer the converter writes +Device* senderDisplay = nullptr; + +void senderTaskMain(void*) { + int band = 0; + uint64_t send = 0; + while (true) { + xSemaphoreTake(bandReady[band], portMAX_DELAY); + const BandJob job = bandJobs[band]; + if (job.stop) { + xSemaphoreGive(bandFree[band]); + break; + } + const uint64_t start = hd::profile::now(); + display_draw_bitmap(senderDisplay, job.xStart, job.yStart, job.xEnd, job.yEnd, sendBands[band]); + send += hd::profile::now() - start; + if (job.last) { + hd::profile::addDisplaySend((uint32_t)send); + send = 0; + } + xSemaphoreGive(bandFree[band]); + band = 1 - band; + } + vTaskSuspend(nullptr); // deleted by stopSender() +} + +bool startSender(Device* display) { + sendBands[0] = bandBuffer; + const MemoryPolicy bandPolicy = { .required = MEMORY_CAPABILITY_INTERNAL | MEMORY_CAPABILITY_DMA, .desired = 0, .alignment = 4 }; + sendBands[1] = (uint16_t*)memory_alloc_with_policy(bandBytes, &bandPolicy); + bool ok = sendBands[1] != nullptr; + for (int i = 0; i < 2 && ok; i++) { + bandFree[i] = xSemaphoreCreateBinary(); + bandReady[i] = xSemaphoreCreateBinary(); + ok = bandFree[i] != nullptr && bandReady[i] != nullptr; + if (ok) xSemaphoreGive(bandFree[i]); + } + senderDisplay = display; + converterBand = 0; + if (ok && xTaskCreatePinnedToCoreWithCaps(senderTaskMain, "voidskim_send", 3072, nullptr, 6, &senderTask, 0, + MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) != pdPASS) { + senderTask = nullptr; + ok = false; + } + if (!ok) { + for (int i = 0; i < 2; i++) { + if (bandFree[i] != nullptr) vSemaphoreDelete(bandFree[i]); + if (bandReady[i] != nullptr) vSemaphoreDelete(bandReady[i]); + bandFree[i] = bandReady[i] = nullptr; + } + memory_free(sendBands[1]); + sendBands[0] = sendBands[1] = nullptr; + } + return ok; +} + +void stopSender() { + if (senderTask == nullptr) return; + // Both buffers back: every band is sent, and the sender waits for converterBand next + xSemaphoreTake(bandFree[0], portMAX_DELAY); + xSemaphoreTake(bandFree[1], portMAX_DELAY); + bandJobs[converterBand] = { 0, 0, 0, 0, false, true }; + xSemaphoreGive(bandReady[converterBand]); + xSemaphoreTake(bandFree[converterBand], portMAX_DELAY); // the sender has left its loop + vTaskDeleteWithCaps(senderTask); + senderTask = nullptr; + for (int i = 0; i < 2; i++) { + vSemaphoreDelete(bandFree[i]); + vSemaphoreDelete(bandReady[i]); + bandFree[i] = bandReady[i] = nullptr; + } + memory_free(sendBands[1]); + sendBands[0] = sendBands[1] = nullptr; +} +#endif uint8_t* screenBuffer = nullptr; // Gray8/Mono: the whole screen size_t screenStride = 0; @@ -82,6 +183,11 @@ inline uint8_t luma565(uint16_t c) { return (uint8_t)((77u * r + 150u * g + 29u * b) >> 8); } +uint16_t* allocateFrame(size_t bytes) { + const MemoryPolicy policy = { .required = 0, .desired = MEMORY_CAPABILITY_EXTERNAL, .alignment = 64 }; + return (uint16_t*)memory_alloc_with_policy(bytes, &policy); +} + } // namespace bool DisplayOutput::init(Device* displayDevice, const ScreenInfo& info) { @@ -113,28 +219,18 @@ bool DisplayOutput::init(Device* displayDevice, const ScreenInfo& info) { LOG_I(TAG, "Display %dx%d (rotation %d): frame %dx%d, scale %.2f", userWidth, userHeight, screen.drawRotation, frameWidth, frameHeight, (double)scale); - // Internal RAM renders fastest, but only when it fits with room to spare: Wi-Fi, Bluetooth and - // the drivers need internal RAM too (running out crashes them). Otherwise PSRAM. - // 64-byte aligned, as it's also the PPA's input. + // In PSRAM: internal RAM is too small for a frame on most devices and, measured, makes little + // difference (see PERFORMANCE.md). 64-byte aligned, as it's also the PPA's input. const size_t frameBytes = (size_t)frameWidth * frameHeight * 2; - bool frameInternal = false; - if (memory_heap_largest_block() >= frameBytes + INTERNAL_RESERVE_BYTES && memory_heap_free() >= frameBytes + INTERNAL_RESERVE_BYTES) { - const MemoryPolicy internalPolicy = { .required = MEMORY_CAPABILITY_INTERNAL, .desired = 0, .alignment = 64 }; - frame_ = (uint16_t*)memory_alloc_with_policy(frameBytes, &internalPolicy); - frameInternal = frame_ != nullptr; - } - if (frame_ == nullptr) { - const MemoryPolicy externalPolicy = { .required = 0, .desired = MEMORY_CAPABILITY_EXTERNAL, .alignment = 64 }; - frame_ = (uint16_t*)memory_alloc_with_policy(frameBytes, &externalPolicy); - } - LOG_I(TAG, "Frame buffer (%u bytes) in %s RAM", (unsigned)frameBytes, frameInternal ? "internal" : "external"); + frames[0] = allocateFrame(frameBytes); + backFrame = 0; xMap = (uint16_t*)memory_alloc(uw * sizeof(uint16_t)); yMap = (uint16_t*)memory_alloc(uh * sizeof(uint16_t)); - if (frame_ == nullptr || xMap == nullptr || yMap == nullptr) { + if (frames[0] == nullptr || xMap == nullptr || yMap == nullptr) { LOG_E(TAG, "Out of memory for the frame"); return false; } - memset(frame_, 0, (size_t)frameWidth * frameHeight * 2); + memset(frames[0], 0, frameBytes); for (int x = 0; x < uw; x++) xMap[x] = (uint16_t)(x * frameWidth / uw); for (int y = 0; y < uh; y++) yMap[y] = (uint16_t)(y * frameHeight / uh); return initOutput(); @@ -176,6 +272,7 @@ bool DisplayOutput::initOutput() { LOG_E(TAG, "Failed to register PPA client"); return false; } + startPresentTask(); return true; #else pixelMode = PixelMode::Rgb16; @@ -200,7 +297,8 @@ bool DisplayOutput::initOutput() { const MemoryPolicy bandPolicy = { .required = MEMORY_CAPABILITY_INTERNAL | MEMORY_CAPABILITY_DMA, .desired = 0, .alignment = 4 }; for (size_t bytes = BAND_BYTES; bytes >= 1024 && bandBuffer == nullptr; bytes /= 2) { bandRows = std::max(1, (int)(bytes / ((size_t)bandWidth * 2))); - bandBuffer = (uint16_t*)memory_alloc_with_policy((size_t)bandWidth * bandRows * 2, &bandPolicy); + bandBytes = (size_t)bandWidth * bandRows * 2; + bandBuffer = (uint16_t*)memory_alloc_with_policy(bandBytes, &bandPolicy); } if (bandBuffer == nullptr) { LOG_E(TAG, "Out of internal memory for the output buffer"); @@ -213,11 +311,102 @@ bool DisplayOutput::initOutput() { display_draw_bitmap(display, 0, y, (int32_t)screen.drawWidth, yEnd, bandBuffer); } (void)fbSize; + startPresentTask(); return true; #endif } +void DisplayOutput::startPresentTask() { +#ifdef ESP_PLATFORM + // Sending a frame mostly waits on the display bus: on a dual core chip another task does that + // while the game draws the next frame into a second buffer. The game runs on core 1 (main.cpp). + if (portNUM_PROCESSORS < 2) { + return; + } + const size_t frameBytes = (size_t)frameWidth * frameHeight * 2; + frames[1] = allocateFrame(frameBytes); + if (frames[1] == nullptr) { + LOG_W(TAG, "No memory for a second frame: frames are sent on the game's core"); + return; + } + memset(frames[1], 0, frameBytes); + SemaphoreHandle_t request = xSemaphoreCreateBinary(); + SemaphoreHandle_t idle = xSemaphoreCreateBinary(); + TaskHandle_t task = nullptr; + presentStopping = false; + if (request != nullptr && idle != nullptr) { + presentRequest = request; + presentIdle = idle; + xSemaphoreGive(idle); + if (xTaskCreatePinnedToCoreWithCaps(presentTaskMain, "voidskim_display", 4096, this, 5, &task, 0, + MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) != pdPASS) { + task = nullptr; + } + } + if (task == nullptr) { + LOG_W(TAG, "Couldn't start the display task: frames are sent on the game's core"); + if (request != nullptr) vSemaphoreDelete(request); + if (idle != nullptr) vSemaphoreDelete(idle); + presentRequest = nullptr; + presentIdle = nullptr; + memory_free(frames[1]); + frames[1] = nullptr; + return; + } + presentTask = task; +#if HD_USE_PPA + LOG_I(TAG, "Frames are scaled and sent on core 0 while the next one is drawn"); +#else + if (startSender(display)) { + LOG_I(TAG, "Frames are sent on core 0 while the next one is drawn, converting a band while the previous one is sent"); + } else { + LOG_I(TAG, "Frames are sent on core 0 while the next one is drawn"); + } +#endif +#endif +} + +void DisplayOutput::presentTaskMain(void* arg) { +#ifdef ESP_PLATFORM + auto* self = static_cast(arg); + auto request = (SemaphoreHandle_t)self->presentRequest; + auto idle = (SemaphoreHandle_t)self->presentIdle; + while (true) { + xSemaphoreTake(request, portMAX_DELAY); + if (self->presentStopping) break; + self->presentFrame(self->presentSource, nullptr); + xSemaphoreGive(idle); + } + xSemaphoreGive(idle); + vTaskSuspend(nullptr); // deleted by stopPresentTask() +#else + (void)arg; +#endif +} + +void DisplayOutput::stopPresentTask() { +#ifdef ESP_PLATFORM + if (presentTask == nullptr) { + return; + } + auto request = (SemaphoreHandle_t)presentRequest; + auto idle = (SemaphoreHandle_t)presentIdle; + xSemaphoreTake(idle, portMAX_DELAY); // the last frame is sent + presentStopping = true; + xSemaphoreGive(request); + xSemaphoreTake(idle, portMAX_DELAY); // the task has left its loop + vTaskDeleteWithCaps((TaskHandle_t)presentTask); + stopSender(); + vSemaphoreDelete(request); + vSemaphoreDelete(idle); + presentTask = nullptr; + presentRequest = nullptr; + presentIdle = nullptr; +#endif +} + void DisplayOutput::shutdown() { + stopPresentTask(); #if HD_USE_PPA if (ppaClient != nullptr) { ppa_unregister_client(ppaClient); @@ -232,8 +421,10 @@ void DisplayOutput::shutdown() { bandBuffer = nullptr; memory_free(screenBuffer); screenBuffer = nullptr; - memory_free(frame_); - frame_ = nullptr; + memory_free(frames[0]); + memory_free(frames[1]); + frames[0] = frames[1] = nullptr; + backFrame = 0; memory_free(xMap); xMap = nullptr; memory_free(yMap); @@ -243,12 +434,31 @@ void DisplayOutput::shutdown() { void DisplayOutput::present(const uint8_t* uiMask) { #if HD_USE_PPA - esp_cache_msync(frame_, (size_t)frameWidth * frameHeight * 2, ESP_CACHE_MSYNC_FLAG_DIR_C2M); + // Write the frame back from the CPU caches for the PPA, on the core that drew it: each core has + // its own L1 data cache, and a write-back from the display task's core may miss this core's lines. + esp_cache_msync(frames[backFrame], (size_t)frameWidth * frameHeight * 2, ESP_CACHE_MSYNC_FLAG_DIR_C2M); +#endif +#ifdef ESP_PLATFORM + if (presentTask != nullptr) { + // Wait for the display task to finish the previous frame, then hand it this one + xSemaphoreTake((SemaphoreHandle_t)presentIdle, portMAX_DELAY); + presentSource = frames[backFrame]; + xSemaphoreGive((SemaphoreHandle_t)presentRequest); + backFrame = 1 - backFrame; + return; + } +#endif + presentFrame(frames[backFrame], uiMask); +} + +void DisplayOutput::presentFrame(const uint16_t* source, const uint8_t* uiMask) { +#if HD_USE_PPA + (void)uiMask; uint16_t* target = usingHwFrameBuffer ? hwFrameBuffers[backBufferIndex] : outputBuffer; const size_t fbSize = (size_t)screen.drawWidth * screen.drawHeight * 2; ppa_srm_oper_config_t srm = { .in = { - .buffer = frame_, + .buffer = source, .pic_w = (uint32_t)frameWidth, .pic_h = (uint32_t)frameHeight, .block_w = (uint32_t)frameWidth, @@ -282,22 +492,26 @@ void DisplayOutput::present(const uint8_t* uiMask) { .mode = PPA_TRANS_MODE_BLOCKING, .user_data = nullptr, }; + const uint64_t scaleStart = hd::profile::now(); ppa_do_scale_rotate_mirror(ppaClient, &srm); esp_cache_msync(target, fbSize, ESP_CACHE_MSYNC_FLAG_DIR_C2M); + const uint64_t sendStart = hd::profile::now(); display_draw_bitmap(display, 0, 0, (int32_t)screen.drawWidth, (int32_t)screen.drawHeight, target); + hd::profile::addDisplay((uint32_t)(sendStart - scaleStart), 0); + hd::profile::addDisplaySend((uint32_t)(hd::profile::now() - sendStart)); if (usingHwFrameBuffer) { backBufferIndex = 1 - backBufferIndex; } #else - presentSoftware(uiMask); + presentSoftware(source, uiMask); #endif } -void DisplayOutput::presentSoftware(const uint8_t* uiMask) { +void DisplayOutput::presentSoftware(const uint16_t* source, const uint8_t* uiMask) { // Calls write(rx, ry, pixel) for each pixel of the draw rectangle. Draw-local (rx, ry) shows // user-local 0: (rx, ry), 1: (uw - 1 - ry, rx), 2: (uw - 1 - rx, uh - 1 - ry), 3: (ry, uh - 1 - rx) auto forEachPixel = [&](int rowStart, int rowEnd, auto write) { - const uint16_t* src = frame_; + const uint16_t* src = source; const int stride = frameWidth; for (int ry = rowStart; ry < rowEnd; ry++) { switch (screen.drawRotation) { @@ -326,37 +540,95 @@ void DisplayOutput::presentSoftware(const uint8_t* uiMask) { }; if (pixelMode == PixelMode::Rgb16) { - uint16_t* out = bandBuffer; const int stride = dw; +#ifdef ESP_PLATFORM + if (senderTask != nullptr) { + uint64_t convert = 0, wait = 0; + for (int bandStart = 0; bandStart < dh; bandStart += bandRows) { + const int bandEnd = std::min(dh, bandStart + bandRows); + const int band = converterBand; + const uint64_t waitStart = hd::profile::now(); + xSemaphoreTake(bandFree[band], portMAX_DELAY); + const uint64_t convertStart = hd::profile::now(); + uint16_t* out = sendBands[band]; + forEachPixel(bandStart, bandEnd, [&](int rx, int ry, const uint16_t* p) { out[(ry - bandStart) * stride + rx] = toPanel(*p); }); + bandJobs[band] = { dx, dy + bandStart, dx + dw, dy + bandEnd, bandEnd >= dh, false }; + xSemaphoreGive(bandReady[band]); + converterBand = 1 - band; + wait += convertStart - waitStart; + convert += hd::profile::now() - convertStart; + } + hd::profile::addDisplay((uint32_t)convert, (uint32_t)wait); + return; + } +#endif + uint16_t* out = bandBuffer; + uint64_t convert = 0, send = 0; for (int bandStart = 0; bandStart < dh; bandStart += bandRows) { const int bandEnd = std::min(dh, bandStart + bandRows); + const uint64_t convertStart = hd::profile::now(); forEachPixel(bandStart, bandEnd, [&](int rx, int ry, const uint16_t* p) { out[(ry - bandStart) * stride + rx] = toPanel(*p); }); + const uint64_t sendStart = hd::profile::now(); // Synchronous: the driver is done with the buffer when this returns display_draw_bitmap(display, dx, dy + bandStart, dx + dw, dy + bandEnd, bandBuffer); + convert += sendStart - convertStart; + send += hd::profile::now() - sendStart; } + hd::profile::addDisplay((uint32_t)convert, 0); + hd::profile::addDisplaySend((uint32_t)send); return; } - // Monochrome/greyscale: the 3D world gets an ordered dither, brightened a little (roughly a 0.7 + if (pixelMode == PixelMode::Gray8) { + // Greyscale: the frame's brightness as is, no dither needed + forEachPixel(0, dh, [&](int rx, int ry, const uint16_t* p) { + screenBuffer[(size_t)(dy + ry) * screenStride + dx + rx] = luma565(*p); + }); + display_draw_bitmap(display, 0, 0, (int32_t)screen.drawWidth, (int32_t)screen.drawHeight, screenBuffer); + return; + } + + // Monochrome: the 3D world gets an ordered dither, brightened a little (roughly a 0.7 // gamma). UI pixels (marked in the game's mask) are plain black or white, so text stays crisp. + // + // A dither blurs the edges between faces of similar brightness, so edges get a black line: the + // world is flat shaded, so every face edge is a jump in brightness between neighbouring pixels. + // The line goes on the brighter side, so a bright shape on a dark background keeps its size. + // Fog is drawn as a dither pattern of dots, 1-2 pixels across, which would all get outlines: so + // the darker side has to stay darker a few pixels further on (EDGE_DEPTH_*), as a face does. + const auto isWorld = [&](int index) { return uiMask == nullptr || uiMask[index] == 0; }; + const auto isEdge = [&](int index, uint32_t l) { + if (l < EDGE_MIN_LUMA) return false; // a dark pixel can't get a visible black line + const int fx = index % frameWidth; + const int fy = index / frameWidth; + const auto darker = [&](int other) { return isWorld(other) && l >= luma565(source[other]) + EDGE_LUMA_STEP; }; + // step: towards the neighbour, room: pixels available in that direction, depth: how far on + // the darker side has to continue + const auto darkerSide = [&](int step, int room, int depth) { + return room >= depth && darker(index + step) && darker(index + step * depth); + }; + return darkerSide(1, frameWidth - 1 - fx, EDGE_DEPTH_X) || + darkerSide(-1, fx, EDGE_DEPTH_X) || + darkerSide(frameWidth, frameHeight - 1 - fy, EDGE_DEPTH_Y) || + darkerSide(-frameWidth, fy, EDGE_DEPTH_Y); + }; forEachPixel(0, dh, [&](int rx, int ry, const uint16_t* p) { const int x = dx + rx; const int y = dy + ry; + const int index = (int)(p - source); const uint32_t l = luma565(*p); bool white; - if (uiMask != nullptr && uiMask[p - frame_]) { + if (!isWorld(index)) { white = l > UI_THRESHOLD; + } else if (isEdge(index, l)) { + white = false; } else { const uint32_t bright = (l + (uint32_t)std::sqrt((float)(l * 255u))) / 2; white = bright > (uint32_t)(BAYER8[y & 7][x & 7] * 4 + 2); } uint8_t* row = screenBuffer + (size_t)y * screenStride; - if (pixelMode == PixelMode::Mono) { - const uint8_t mask = (uint8_t)(0x80 >> (x & 7)); - row[x >> 3] = white ? (row[x >> 3] | mask) : (row[x >> 3] & (uint8_t)~mask); - } else { - row[x] = white ? 0xFF : 0x00; - } + const uint8_t mask = (uint8_t)(0x80 >> (x & 7)); + row[x >> 3] = white ? (row[x >> 3] | mask) : (row[x >> 3] & (uint8_t)~mask); }); display_draw_bitmap(display, 0, 0, (int32_t)screen.drawWidth, (int32_t)screen.drawHeight, screenBuffer); } @@ -389,5 +661,6 @@ bool DisplayOutput::mapTouch(int touchX, int touchY, int& outX, int& outY) const } bool DisplayOutput::isMonochrome() const { - return pixelMode != PixelMode::Rgb16; + // Greyscale shows the frame's shades as they are: it doesn't need the black and white UI + return pixelMode == PixelMode::Mono; } diff --git a/Apps/Voidskim/main/Source/platform/DisplayOutput.h b/Apps/Voidskim/main/Source/platform/DisplayOutput.h index 4d72caf..1aae8ff 100644 --- a/Apps/Voidskim/main/Source/platform/DisplayOutput.h +++ b/Apps/Voidskim/main/Source/platform/DisplayOutput.h @@ -29,19 +29,23 @@ class DisplayOutput { bool init(Device* display, const ScreenInfo& screen); void shutdown(); - /** The frame to render into: width() x height() RGB565 pixels. */ - uint16_t* frame() { return frame_; } + /** + * The frame to render into: width() x height() RGB565 pixels. Can change after each present(): + * with two frames, one is sent to the display while the next is drawn into the other. + */ + uint16_t* frame() { return frames[backFrame]; } int width() const { return frameWidth; } int height() const { return frameHeight; } /** - * Shows the frame. + * Shows the frame. With two frames this only hands it to the display task on the other core, + * after waiting for the frame before it to be sent; frame() is then the other frame. * @param uiMask on monochrome displays: frame pixels that are UI (1) rather than 3D world (0), * or nullptr to dither everything */ void present(const uint8_t* uiMask = nullptr); - /** @return whether the display is black and white (or greyscale), so frames get dithered */ + /** @return whether the display is black and white, so frames get dithered (greyscale isn't) */ bool isMonochrome() const; /** Maps a raw touch coordinate to frame coordinates. @return false when outside the frame */ @@ -50,7 +54,14 @@ class DisplayOutput { private: Device* display = nullptr; ScreenInfo screen; - uint16_t* frame_ = nullptr; + uint16_t* frames[2] = { nullptr, nullptr }; + int backFrame = 0; + // Sends frames on the other core (software output on dual core chips), or nullptr + void* presentTask = nullptr; + void* presentRequest = nullptr; // semaphore: a frame is ready to send + void* presentIdle = nullptr; // semaphore: the display task is done with its frame + const uint16_t* presentSource = nullptr; + bool presentStopping = false; int frameWidth = 0; int frameHeight = 0; int userWidth = 0; @@ -63,5 +74,9 @@ class DisplayOutput { uint16_t* yMap = nullptr; bool initOutput(); - void presentSoftware(const uint8_t* uiMask); + void startPresentTask(); + void stopPresentTask(); + static void presentTaskMain(void* arg); + void presentFrame(const uint16_t* source, const uint8_t* uiMask); + void presentSoftware(const uint16_t* source, const uint8_t* uiMask); }; diff --git a/Apps/Voidskim/main/Source/platform/Profiler.cpp b/Apps/Voidskim/main/Source/platform/Profiler.cpp new file mode 100644 index 0000000..e062152 --- /dev/null +++ b/Apps/Voidskim/main/Source/platform/Profiler.cpp @@ -0,0 +1,106 @@ +#include "Profiler.h" + +#if VOIDSKIM_PROFILE + +#include + +#include +#include + +namespace hd::profile { + +constexpr auto* TAG = "VoidskimProfile"; +constexpr uint64_t LOG_INTERVAL_MICROS = 3000000; + +namespace { + +uint64_t totals[(int)Phase::Count] = {}; +uint32_t frames = 0; +// Sums over the frames that rendered 3D +uint64_t sceneObjects = 0, sceneDrawnObjects = 0, sceneTriangles = 0, sceneQueued = 0, sceneRasterized = 0; +uint32_t sceneFrames = 0; +// Written by the display task +std::atomic displayConvert { 0 }, displayWait { 0 }, displayFrames { 0 }; +std::atomic displaySend { 0 }, sentFrames { 0 }; +uint64_t periodStart = 0; + +double milliseconds(Phase phase) { + return (double)totals[(int)phase] / 1000.0 / (double)frames; +} + +} // namespace + +uint64_t now() { + return get_micros_since_boot(); +} + +void add(Phase phase, uint64_t micros) { + totals[(int)phase] += micros; +} + +void addScene(const SceneCounts& counts) { + sceneObjects += (uint64_t)counts.objects; + sceneDrawnObjects += (uint64_t)counts.drawnObjects; + sceneTriangles += (uint64_t)counts.triangles; + sceneQueued += (uint64_t)counts.queuedTriangles; + sceneRasterized += (uint64_t)counts.rasterizedTriangles; + sceneFrames++; +} + +void logTrack(int vertices, int verticesBeforeMerging, int meshes) { + LOG_I(TAG, "Track: %d vertices (%d before merging shared corners), %d meshes", vertices, verticesBeforeMerging, meshes); +} + +void addDisplay(uint32_t convertMicros, uint32_t waitMicros) { + displayConvert += convertMicros; + displayWait += waitMicros; + displayFrames++; +} + +void addDisplaySend(uint32_t sendMicros) { + displaySend += sendMicros; + sentFrames++; +} + +void frameDone() { + frames++; + const uint64_t time = now(); + if (periodStart == 0) { + periodStart = time; + return; + } + const uint64_t elapsed = time - periodStart; + if (elapsed < LOG_INTERVAL_MICROS) { + return; + } + // The HUD and menus: whatever Game::render() spends outside the 3D + const double overlay = milliseconds(Phase::Render) - milliseconds(Phase::World3D) - milliseconds(Phase::ScaleUp); + LOG_I(TAG, "%.1f fps, ms/frame: update %.2f, 3D %.2f, scale %.2f, overlay %.2f, present %.2f, total %.2f", + (double)frames * 1000000.0 / (double)elapsed, + milliseconds(Phase::Update), milliseconds(Phase::World3D), milliseconds(Phase::ScaleUp), overlay, + milliseconds(Phase::Present), (double)elapsed / 1000.0 / (double)frames); + if (sceneFrames > 0) { + const auto average = [](uint64_t sum) { return (unsigned)(sum / sceneFrames); }; + LOG_I(TAG, "3D per frame: objects %u of %u after frustum cull, triangles %u queued, %u rasterised, of %u", + average(sceneDrawnObjects), average(sceneObjects), average(sceneQueued), average(sceneRasterized), + average(sceneTriangles)); + } + const uint32_t converted = displayFrames.exchange(0); + const uint32_t convert = displayConvert.exchange(0); + const uint32_t wait = displayWait.exchange(0); + const uint32_t sent = sentFrames.exchange(0); + const uint32_t send = displaySend.exchange(0); + if (converted > 0 && sent > 0) { + LOG_I(TAG, "Display per frame: convert %.2f ms, waiting %.2f ms, send %.2f ms", + (double)convert / 1000.0 / converted, (double)wait / 1000.0 / converted, (double)send / 1000.0 / sent); + } + sceneObjects = sceneDrawnObjects = sceneTriangles = sceneQueued = sceneRasterized = 0; + sceneFrames = 0; + for (auto& total : totals) total = 0; + frames = 0; + periodStart = time; +} + +} // namespace hd::profile + +#endif diff --git a/Apps/Voidskim/main/Source/platform/Profiler.h b/Apps/Voidskim/main/Source/platform/Profiler.h new file mode 100644 index 0000000..07de565 --- /dev/null +++ b/Apps/Voidskim/main/Source/platform/Profiler.h @@ -0,0 +1,88 @@ +#pragma once + +#include + +// Per-phase frame timing in the log, every few seconds. 0 compiles it out. +#ifndef VOIDSKIM_PROFILE +#define VOIDSKIM_PROFILE 1 +#endif + +namespace hd::profile { + +enum class Phase { + Update, // game logic + Render, // Game::render() as a whole: the 3D world below, then the HUD and menus + World3D, // Jet: transform, sort, rasterise + ScaleUp, // the 3D into the frame, scaled up when its resolution is lower + Present, // the frame to the display: with a display task, the wait for it to be free + Count, +}; + +#if VOIDSKIM_PROFILE + +uint64_t now(); +void add(Phase phase, uint64_t micros); + +/** + * What the 3D renderer culled in a frame: objects (meshes) in the scene and after the frustum cull, + * triangles in the scene, queued after per-triangle culling and actually rasterised. + */ +struct SceneCounts { + int objects = 0; + int drawnObjects = 0; + int triangles = 0; + int queuedTriangles = 0; + int rasterizedTriangles = 0; +}; +void addScene(const SceneCounts& counts); + +/** + * One frame converted to the panel's format, and how long the conversion waited for a free band + * buffer (the sender being behind). Safe to call from another task than frameDone(). + */ +void addDisplay(uint32_t convertMicros, uint32_t waitMicros); + +/** One frame sent by the display driver. Safe to call from another task than frameDone(). */ +void addDisplaySend(uint32_t sendMicros); + +/** Logs the size of a track's meshes once, when it's built. */ +void logTrack(int vertices, int verticesBeforeMerging, int meshes); +/** Call once per frame: logs the averages every few seconds. */ +void frameDone(); + +class Scope { +public: + explicit Scope(Phase phase) : phase(phase), start(now()) {} + ~Scope() { add(phase, now() - start); } + Scope(const Scope&) = delete; + Scope& operator=(const Scope&) = delete; +private: + Phase phase; + uint64_t start; +}; + +#else + +inline uint64_t now() { return 0; } +inline void add(Phase, uint64_t) {} +struct SceneCounts { + int objects = 0; + int drawnObjects = 0; + int triangles = 0; + int queuedTriangles = 0; + int rasterizedTriangles = 0; +}; +inline void addScene(const SceneCounts&) {} +inline void logTrack(int, int, int) {} +inline void addDisplay(uint32_t, uint32_t) {} +inline void addDisplaySend(uint32_t) {} +inline void frameDone() {} + +class Scope { +public: + explicit Scope(Phase) {} +}; + +#endif + +} // namespace hd::profile diff --git a/Apps/Voidskim/main/Source/render/WorldRenderer.cpp b/Apps/Voidskim/main/Source/render/WorldRenderer.cpp index 7c8f3ec..ac81ff6 100644 --- a/Apps/Voidskim/main/Source/render/WorldRenderer.cpp +++ b/Apps/Voidskim/main/Source/render/WorldRenderer.cpp @@ -3,11 +3,13 @@ #include #include "Draw2D.h" +#include "../platform/Profiler.h" #include "Jet.hpp" #include #include +#include namespace hd { @@ -25,6 +27,9 @@ constexpr float CLIFF_DEPTH = 26.0f; // how far the rock goes down on either sid constexpr int CLIFF_SAMPLES = 3; // road samples on either side of a gap that stand on rock constexpr float HOVER_HEIGHT = 0.75f; constexpr float FOV_DEGREES = 72.0f; +constexpr size_t ROW_ALIGN_BYTES = 16; // see applyResolution() +// 3D columns per aligned row chunk: two columns per stored pixel (HALF_WIDTH_BUFFERS) +constexpr int ROW_ALIGN_COLUMNS = (int)(ROW_ALIGN_BYTES / sizeof(uint16_t)) * 2; namespace { @@ -88,16 +93,15 @@ class MeshBuilder { if (flip) { normal = normal * -1.0f; } - const uint16_t base = (uint16_t)object->vertices.size(); - addVertex(a); - addVertex(b); - addVertex(c); - addVertex(d); + const uint16_t ia = addVertex(a); + const uint16_t ib = addVertex(b); + const uint16_t ic = addVertex(c); + const uint16_t id = addVertex(d); Material* m = forced != nullptr ? forced : material(shaded ? shade(rgb, normal) : rgb); if (flip) { - object->addFace(base, (uint16_t)(base + 3), (uint16_t)(base + 2), (uint16_t)(base + 1), m); + object->addFace(ia, id, ic, ib, m); } else { - object->addFace(base, (uint16_t)(base + 1), (uint16_t)(base + 2), (uint16_t)(base + 3), m); + object->addFace(ia, ib, ic, id, m); } } @@ -107,15 +111,14 @@ class MeshBuilder { if (flip) { normal = normal * -1.0f; } - const uint16_t base = (uint16_t)object->vertices.size(); - addVertex(a); - addVertex(b); - addVertex(c); + const uint16_t ia = addVertex(a); + const uint16_t ib = addVertex(b); + const uint16_t ic = addVertex(c); Material* m = material(shade(rgb, normal)); if (flip) { - object->addTriangle(base, (uint16_t)(base + 2), (uint16_t)(base + 1), m); + object->addTriangle(ia, ic, ib, m); } else { - object->addTriangle(base, (uint16_t)(base + 1), (uint16_t)(base + 2), m); + object->addTriangle(ia, ib, ic, m); } } @@ -159,14 +162,34 @@ class MeshBuilder { return shadeRgb(rgb, std::min(1.1f, 0.45f + 0.55f * lambert / up)); } + /** Corners added, counting every corner shared by several faces again. */ + size_t cornerCount() const { return corners; } + private: Object* object; std::function material; - - void addVertex(const P3& p) { + // Faces that meet share their corners: each vertex is transformed once per frame instead of + // once per face that uses it. Vertices carry only a position (flat shading, the colour is the + // face's material), so equal positions can always be merged. + std::unordered_map vertexIndex; + size_t corners = 0; + + uint16_t addVertex(const P3& p) { + corners++; + const Vector3 position = toJet(p); + // 21 bits per axis: Jet units are 1/16 m, so +-65 km + const auto axis = [](int32_t v) { return (uint64_t)((uint32_t)v & 0x1FFFFFu); }; + const uint64_t key = axis(position.x) | (axis(position.y) << 21) | (axis(position.z) << 42); + const auto found = vertexIndex.find(key); + if (found != vertexIndex.end()) { + return found->second; + } + const uint16_t index = (uint16_t)object->vertices.size(); Object::Vertex v; - v.position = toJet(p); + v.position = position; object->addVertex(v); + vertexIndex.emplace(key, index); + return index; } }; @@ -193,28 +216,31 @@ void WorldRenderer::setResolutionPercent(int percent) { } void WorldRenderer::applyResolution() { - if (resolutionPercent >= 100) { - width = outputWidth; - height = outputHeight; - framebuffer = output; - lowResolution.clear(); - lowResolution.shrink_to_fit(); - columnSource.clear(); - } else { - width = std::max(16, outputWidth * resolutionPercent / 100); - height = std::max(16, outputHeight * resolutionPercent / 100); - lowResolution.assign((size_t)width * height, 0); - framebuffer = lowResolution.data(); - columnSource.resize(outputWidth); - for (int x = 0; x < outputWidth; x++) { - columnSource[x] = (uint16_t)std::min(width - 1, (x * width + width / 2) / outputWidth); - } + // Jet is built with HALF_WIDTH_BUFFERS (see JetConfig.hpp): it renders one pixel per two columns, + // so its buffer rows are width / 2 pixels long, and scaleUp() doubles them back into the frame. + // + // Jet clears rows with 16-byte vector stores on the ESP32-S3, which ignore the low 4 bits of the + // address: every row must start 16-byte aligned, or the clear writes before it. A misaligned + // buffer had the clear overwrite the heap's header in front of it, which crashed on exit. + // So the buffer is 16-byte aligned and its rows are a multiple of 16 bytes. + const int percent = std::min(100, resolutionPercent); + width = std::max(ROW_ALIGN_COLUMNS, (outputWidth * percent / 100) / ROW_ALIGN_COLUMNS * ROW_ALIGN_COLUMNS); + height = std::max(16, outputHeight * percent / 100); + const int stride = width / 2; + lowResolution.assign((size_t)stride * height + ROW_ALIGN_BYTES / sizeof(uint16_t), 0); + const uintptr_t start = (uintptr_t)lowResolution.data(); + framebuffer = (uint16_t*)((start + ROW_ALIGN_BYTES - 1) & ~(uintptr_t)(ROW_ALIGN_BYTES - 1)); + columnSource.resize(outputWidth); + for (int x = 0; x < outputWidth; x++) { + const int column = std::min(width - 1, (x * width + width / 2) / outputWidth); + columnSource[x] = (uint16_t)(column / 2); } skyRows.assign(height, 0); } void WorldRenderer::scaleUp() { // Nearest neighbour: each output row copies a low resolution row, or repeats the row above it + const int stride = width / 2; int previousSource = -1; for (int y = 0; y < outputHeight; y++) { const int sourceRow = std::min(height - 1, (y * height + height / 2) / outputHeight); @@ -223,7 +249,7 @@ void WorldRenderer::scaleUp() { memcpy(destination, destination - outputWidth, (size_t)outputWidth * sizeof(uint16_t)); continue; } - const uint16_t* source = framebuffer + (size_t)sourceRow * width; + const uint16_t* source = framebuffer + (size_t)sourceRow * stride; const uint16_t* map = columnSource.data(); for (int x = 0; x < outputWidth; x++) { destination[x] = source[map[x]]; @@ -294,6 +320,8 @@ void WorldRenderer::buildTrack(const Track& track) { const P3 up { 0, 1, 0 }; const P3 down { 0, -1, 0 }; Random random(0xC0FFEEu ^ (uint32_t)count); + size_t cornersAdded = 0; + size_t verticesKept = 0; for (int chunkStart = 0; chunkStart < count; chunkStart += CHUNK_SAMPLES) { auto object = std::make_unique(); @@ -467,13 +495,17 @@ void WorldRenderer::buildTrack(const Track& track) { } } + cornersAdded += mesh.cornerCount(); if (!object->vertices.empty()) { + verticesKept += object->vertices.size(); object->calculateBoundingBox(); scene->addObject(object.get()); objects.push_back(std::move(object)); } } + profile::logTrack((int)verticesKept, (int)cornersAdded, (int)objects.size()); + // Start gantry: two posts and a beam over the line { auto object = std::make_unique(); @@ -680,11 +712,29 @@ void WorldRenderer::updateShowcase(const RaceSim& race, float time) { void WorldRenderer::render() { if (scene) { - scene->render(); + { + profile::Scope scope(profile::Phase::World3D); + scene->render(); + } +#if VOIDSKIM_PROFILE + profile::SceneCounts counts; + int vertices = 0; + scene->getStatistics(counts.objects, counts.triangles, vertices); + counts.drawnObjects = scene->lastFrameDrawnObjects; + counts.queuedTriangles = scene->lastFrameDrawnTriangles; + counts.rasterizedTriangles = scene->lastFrameRasterizedTriangles; + profile::addScene(counts); +#endif if (framebuffer != output) { + profile::Scope scope(profile::Phase::ScaleUp); scaleUp(); } } } +void WorldRenderer::setOutput(uint16_t* buffer) { + // The 3D always renders into its own buffer (half width), so only where it's scaled to changes + output = buffer; +} + } // namespace hd diff --git a/Apps/Voidskim/main/Source/render/WorldRenderer.h b/Apps/Voidskim/main/Source/render/WorldRenderer.h index c5a28ed..eea5880 100644 --- a/Apps/Voidskim/main/Source/render/WorldRenderer.h +++ b/Apps/Voidskim/main/Source/render/WorldRenderer.h @@ -27,10 +27,14 @@ class WorldRenderer { /** Renders into an RGB565 buffer of width x height pixels. */ bool init(uint16_t* framebuffer, int width, int height); + /** Renders into another buffer of the same size from now on. */ + void setOutput(uint16_t* framebuffer); + /** - * The 3D resolution, as a percentage of the buffer's width and height (25..100). Below 100 the - * world renders into a smaller buffer of its own, which render() scales up into the frame, so - * whatever is drawn on top afterwards (HUD, menus) keeps the full resolution. + * The 3D resolution, as a percentage of the buffer's width and height (25..100). The world + * renders into a buffer of its own, at half that width (Jet's HALF_WIDTH_BUFFERS), which render() + * scales up into the frame, so whatever is drawn on top afterwards (HUD, menus) keeps the full + * resolution. * Takes effect at the next build(). */ void setResolutionPercent(int percent); @@ -69,7 +73,7 @@ class WorldRenderer { int outputWidth = 0; int outputHeight = 0; int resolutionPercent = 100; - std::vector lowResolution; + std::vector lowResolution; // storage for framebuffer when it's not the frame (aligned within) std::vector columnSource; // per output column: the low resolution column it shows uint16_t* framebuffer = nullptr; int width = 0; // of the 3D rendering diff --git a/Apps/Voidskim/manifest.properties b/Apps/Voidskim/manifest.properties index 4a0595f..af371ae 100644 --- a/Apps/Voidskim/manifest.properties +++ b/Apps/Voidskim/manifest.properties @@ -2,11 +2,12 @@ manifest.version=0.3 target.sdk=0.8.0-dev target.platforms=all id=tactility.voidskim -version.name=0.3.0 -version.code=3 +version.name=0.4.0 +version.code=4 name=Voidskim description.short=Arcade 3D hover racing description=Race hovering craft around floating tracks against computer opponents. Hit the ramps to jump the gaps, and mind the edges without barriers: fall off and you lose a few seconds.\n\nFour tracks (one a knot of bridges and tunnels), three craft with their own handling, and three difficulty levels. Tracks, craft and music are plain text files you can edit or add to.\n\nPlay with a keyboard, a trackball or the on-screen touch controls. app.0.id=tactility.voidskim app.0.name=Voidskim app.0.binary=voidskim +app.0.stack.depth=6144 From c4c02232f1bce8b4df2e27bf3143a951a0c8d6c0 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 5 Dec 2026 20:54:28 +0100 Subject: [PATCH 2/4] Fix for gridnav in WebBrowser --- Apps/WebBrowser/main/Source/Browser.cpp | 30 ++++++++++++++----------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/Apps/WebBrowser/main/Source/Browser.cpp b/Apps/WebBrowser/main/Source/Browser.cpp index 0b5d5b4..6a72343 100644 --- a/Apps/WebBrowser/main/Source/Browser.cpp +++ b/Apps/WebBrowser/main/Source/Browser.cpp @@ -764,7 +764,7 @@ lv_obj_t* createHeaderButton(Context* ctx, lv_obj_t* parent, const char* symbol, return button; } -/** A row of header buttons that the arrow keys move along */ +/** A row of header widgets that the arrow keys move along */ lv_obj_t* createHeaderGroup(lv_obj_t* parent, int32_t spacing) { lv_obj_t* group = lv_obj_create(parent); lv_obj_remove_style_all(group); @@ -898,16 +898,16 @@ void createBrowserScreen(Context* ctx, lv_obj_t* parent) { lv_obj_set_style_pad_row(parent, 2, 0); const int32_t spacing = lvgl_theme_lerp(LV_DPX(2), LV_DPX(6), lvgl_theme_get_spacing()); - lv_obj_t* header = lv_obj_create(parent); - lv_obj_remove_style_all(header); - lv_obj_set_size(header, LV_PCT(100), LV_SIZE_CONTENT); - lv_obj_set_flex_flow(header, LV_FLEX_FLOW_ROW); + // One grid navigation for the whole header: left and right move between close, address and the actions + lv_obj_t* header = createHeaderGroup(parent, spacing); + lv_obj_set_width(header, LV_PCT(100)); lv_obj_set_flex_align(header, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); lv_obj_set_style_pad_left(header, spacing, 0); lv_obj_set_style_pad_right(header, spacing, 0); - lv_obj_set_style_pad_column(header, spacing, 0); + lv_obj_add_event_cb(header, onHeaderFocused, LV_EVENT_FOCUSED, ctx); + lv_obj_add_event_cb(header, onAddressDefocused, LV_EVENT_DEFOCUSED, ctx); - createHeaderButton(ctx, createHeaderGroup(header, spacing), LV_SYMBOL_CLOSE, onExit); + createHeaderButton(ctx, header, LV_SYMBOL_CLOSE, onExit); ctx->address = lv_textarea_create(header); lv_textarea_set_one_line(ctx->address, true); @@ -921,10 +921,9 @@ void createBrowserScreen(Context* ctx, lv_obj_t* parent) { lv_obj_add_event_cb(ctx->address, onAddressDefocused, LV_EVENT_DEFOCUSED, ctx); ctx->addressText.clear(); - lv_obj_t* actions = createHeaderGroup(header, spacing); - ctx->back = createHeaderButton(ctx, actions, LV_SYMBOL_LEFT, onBack); - ctx->forward = createHeaderButton(ctx, actions, LV_SYMBOL_RIGHT, onForward); - createHeaderButton(ctx, actions, LV_SYMBOL_BARS, onOverflow); + ctx->back = createHeaderButton(ctx, header, LV_SYMBOL_LEFT, onBack); + ctx->forward = createHeaderButton(ctx, header, LV_SYMBOL_RIGHT, onForward); + createHeaderButton(ctx, header, LV_SYMBOL_BARS, onOverflow); createPageView(ctx, parent); lv_obj_set_style_pad_left(ctx->status, spacing, 0); @@ -1180,7 +1179,10 @@ void forgetWidgets(Context* ctx) { system_bars_set_page_button_callbacks(nullptr, nullptr, nullptr); system_bars_set_page_buttons_visible(false); ctx->pageView.destroy(); - if (ctx->address != nullptr) lv_obj_remove_event_cb(ctx->address, onAddressDefocused); + if (ctx->address != nullptr) { + lv_obj_remove_event_cb(ctx->address, onAddressDefocused); + lv_obj_remove_event_cb(lv_obj_get_parent(ctx->address), onAddressDefocused); + } ctx->address = nullptr; ctx->back = nullptr; ctx->forward = nullptr; @@ -1405,7 +1407,9 @@ void browserRunActions(Context* ctx) { const std::string url = web::urlFromInput(action.text); if (url.empty()) break; ctx->pageView.focus(); - navigate(ctx, url, LoadMode::Normal, -1, 0); + // The address of the current page loads it again in its history entry, instead of adding one + const bool same = ctx->current >= 0 && ctx->history[ctx->current].url == url; + navigate(ctx, url, LoadMode::Normal, same ? ctx->current : -1, 0); break; } case ActionType::Back: From 3ace7d9eb16efa1f8f407c4382be4e18d79c472a Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 5 Dec 2026 20:54:41 +0100 Subject: [PATCH 3/4] Update terminal docs for upcoming firmware --- Apps/BusyBoxVi/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Apps/BusyBoxVi/README.md b/Apps/BusyBoxVi/README.md index 929d6c9..4ebe3c3 100644 --- a/Apps/BusyBoxVi/README.md +++ b/Apps/BusyBoxVi/README.md @@ -22,7 +22,7 @@ vi [-c CMD] [-R] [-H] [FILE]... - `.` repeat, undo, `:set` options (autoindent, ignorecase, showmatch, tabstop) Not supported: regular expressions, `:!` shell commands, signals (suspend/resize). -The terminal has no Home/End/PgUp/PgDn keys: use `0`, `$`, `Ctrl+B` and `Ctrl+F`. +The terminal has no PgUp/PgDn keys: use `Ctrl+B` and `Ctrl+F`. ## Source From a7f6ba14fdc7cb7122c71e0ac53b1e4d0f19a232 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sat, 5 Dec 2026 21:06:15 +0100 Subject: [PATCH 4/4] Bump versions --- Apps/BusyBoxVi/manifest.properties | 4 ++-- Apps/WebBrowser/manifest.properties | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Apps/BusyBoxVi/manifest.properties b/Apps/BusyBoxVi/manifest.properties index 7fdc878..84d5886 100644 --- a/Apps/BusyBoxVi/manifest.properties +++ b/Apps/BusyBoxVi/manifest.properties @@ -2,8 +2,8 @@ manifest.version=0.3 target.sdk=0.8.0-dev target.platforms=all id=tactility.busyboxvi -version.name=0.9.1 -version.code=10 +version.name=0.9.2 +version.code=11 name=BusyBox vi description.short=BusyBox vi text editor description=The BusyBox vi text editor, for use from the Terminal app.\n\nRun: vi [-c CMD] [-R] [-H] [FILE]...\n\nSupports colon commands (:w, :q, :wq, :e, :r, :s/old/new/), yank and put, marks, plain-text search, repeat, undo and :set options. Regular expressions, shell commands and suspend are not supported. The terminal has no Home, End, PgUp or PgDn keys: use 0, $, Ctrl+B and Ctrl+F. diff --git a/Apps/WebBrowser/manifest.properties b/Apps/WebBrowser/manifest.properties index e23b513..3c90d51 100644 --- a/Apps/WebBrowser/manifest.properties +++ b/Apps/WebBrowser/manifest.properties @@ -2,8 +2,8 @@ manifest.version=0.3 target.sdk=0.8.0-dev target.platforms=esp32,esp32s3,esp32p4,esp32s31,linux-x86_64 id=tactility.webbrowser -version.name=0.3.1 -version.code=4 +version.name=0.3.2 +version.code=5 name=Web Browser description.short=Text-first web browser description=Reads web pages as text, with selectable links, history and a cache. Simple search and filter forms work. No CSS, JavaScript or cookies. HTTPS certificates are verified with the certificates of the device. Built on top of the Lexbor engine.