From 01b6b2480e75e2604c6a07625ed922ed847aa8db Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Sun, 25 Oct 2026 23:34:14 +0100 Subject: [PATCH 01/19] perf(A1): instrument world, presentation and Nitro audio phases --- docs/frame-profile-sections.md | 34 ++++++++++++++++++++++++++ mods/DRAMATIC_SHAPE/lib/VoxelScene.lua | 11 +++++++++ src/audio/NitroAudio.lua | 3 +++ src/render/Renderer.lua | 6 +++++ src/render/TileRenderer.lua | 6 +++++ src/world/OverworldController.lua | 25 +++++++++++++++++++ 6 files changed, 85 insertions(+) create mode 100644 docs/frame-profile-sections.md diff --git a/docs/frame-profile-sections.md b/docs/frame-profile-sections.md new file mode 100644 index 000000000..7814e4ce3 --- /dev/null +++ b/docs/frame-profile-sections.md @@ -0,0 +1,34 @@ +# Frame-profile sections for world, presentation and DS audio + +F11 enables the existing `FrameProfile` report. These additional sections use +its shared no-op closer when profiling is disabled; there is no new setting. +All labels begin with spaces, so nested timings do not get counted again as +top-level frame time. Multiple spans with the same label accumulate. + +| Label | Work measured | +| --- | --- | +| `world: tiles` | Initial map/neighbour draws, declined-pipeline fallback and the flat upper layer | +| `world: entities` | Flat ghosts, main and above-layer entities, or tilted billboards | +| `world: FX` | Flat/tilted effect groups, pipeline `ctx.drawFx` and final map overlays | +| `tiles: ensureWindow` | Window validation/refill, including cached and missing-art returns | +| `renderer: zone blit` | Actual `blitCanvas` calls, including the unshaded fallback | +| `renderer: present pipeline` | Present processing and final native output | +| `voxel: sun pass` | Shadow preparation, including cache-hit/rate-limit decisions | +| `voxel: terrain` | Main and neighbouring terrain submission, per eye | +| `voxel: water` | Water draw-list construction, planar reflection and water submission, per eye | +| `voxel: cards` | Main character and staged-battle card submission, per eye | +| `audio: Nitro render` | One DS mixer block, including SoundData creation | + +These are wall-clock submission timings, not GPU execution times. Reflection +copies of cards contribute to the water section; the cards section measures +the visible scene's card pass. The world labels describe selected drawing +phases rather than an exhaustive partition of `drawWorld`; setup, sorting and +other work remain visible in the enclosing section. Voxel timings run inside +the selected world pipeline. Hook names, arguments and dispatch order are +unchanged. An exception still takes its existing cleanup/error path; an +unfinished span is discarded by the existing profiler contract. + +A1 adds observability and makes no performance claim. Desktop before/after +frame timings and ARM/device timings: **not measured**. Capture the same scene, +viewport, camera, mod configuration and profile window when measuring later +optimizations. Profiling itself is disabled by F11 / `FrameProfile.setEnabled(false)`. diff --git a/mods/DRAMATIC_SHAPE/lib/VoxelScene.lua b/mods/DRAMATIC_SHAPE/lib/VoxelScene.lua index 888e4e994..dc5a0786c 100644 --- a/mods/DRAMATIC_SHAPE/lib/VoxelScene.lua +++ b/mods/DRAMATIC_SHAPE/lib/VoxelScene.lua @@ -14,6 +14,7 @@ local V = ... local Mat4 = V.require("Mat4") local Perf = V.require("Perf") +local FrameProfile = require("src.core.FrameProfile") -- The PERFORMANCE tier's ceilings (lib/Tier.lua). Top-level here rather -- than lazily as in ShadowMap/Water/AntiAlias: Tier requires nothing from -- this mod, so there is no load order to protect, and the sun's rate @@ -2669,8 +2670,10 @@ function VoxelScene.render(state, w, h, vw, vh, paletteFor, eyes) -- reaches far north and barely south, which is right for every rung -- but a head free to face south. local shCx, shCy = FirstPerson.shadowCenter(cx, cy, vh) + local closeSun = FrameProfile.section(" voxel: sun pass") castShadows(state, terrain, nbMesh, posed, shCx, shCy, vw, vh, atlasFor, water, nbWater, battleCards, battleToken) + closeSun() -- Everything between beginScene and endScene, as one function: the flat -- path runs it once, a VR frame runs it once PER EYE -- same posed @@ -2678,12 +2681,15 @@ function VoxelScene.render(state, w, h, vw, vh, paletteFor, eyes) -- about anything but their viewpoint. local function drawScene() + local closeTerrain = FrameProfile.section(" voxel: terrain") Voxel3D.draw(terrain, atlasFor(state.map), nil) for i, nb in ipairs(state.neighbors or {}) do Voxel3D.draw(nbMesh[i], atlasFor(nb.map), Mat4.translate(nb.ox, 0, nb.oy)) end + closeTerrain() + -- Without a shadow map (headless, or a driver that could not make the -- canvas) the old flat decals stand in: ground-only, characters only, -- but better than a world with nothing under anybody. They go down @@ -2768,6 +2774,7 @@ function VoxelScene.render(state, w, h, vw, vh, paletteFor, eyes) -- lake would otherwise wear one as a black smear. Water covers them, -- which is the same answer the shadow map's own pass gives (see -- ShadowMap.sprites) -- people do not shadow water either way. + local closeWater = FrameProfile.section(" voxel: water") local waterDraws = {} if water then waterDraws[#waterDraws + 1] = { water, atlasFor(state.map), nil } @@ -2803,6 +2810,8 @@ function VoxelScene.render(state, w, h, vw, vh, paletteFor, eyes) planarTex, planarY) end + closeWater() + -- AND THE RIPPLE RINGS ON TOP OF IT, BEFORE ANYBODY IS STANDING IN IT. -- -- THIS LINE'S POSITION IS THE WHOLE FIX. Reported from play: "the ripples @@ -2864,10 +2873,12 @@ function VoxelScene.render(state, w, h, vw, vh, paletteFor, eyes) -- drawEntity resolves the lean-over-the-wall-in-front case, and a -- character genuinely behind a building is far deeper and loses the -- test, so buildings and trees really occlude. + local closeCards = FrameProfile.section(" voxel: cards") drawCast(state, posed, atlasFor) -- and the staged fight's mons over them, exactly as they were painted -- into the water's reflection copy a few lines up (see drawBattleCards) drawBattleCards() + closeCards() -- tall grass last, pulled camera-ward exactly as far as the characters -- were (same per-vertex shader bias, so grass never drifts either): -- relative depth between a walker and the tuft row south of their feet diff --git a/src/audio/NitroAudio.lua b/src/audio/NitroAudio.lua index c27fff829..81b0caf87 100644 --- a/src/audio/NitroAudio.lua +++ b/src/audio/NitroAudio.lua @@ -1,5 +1,6 @@ -- Nintendo DS SSEQ transport over the ROM's SBNK/SWAR instruments. -- PCM/ADPCM mixing is local; no replacement MIDI soundfont is used. +local FrameProfile = require("src.core.FrameProfile") local Sdat=require('src.import.Gen4Sdat') local Audio={};local Player={};Player.__index=Player local archives,players={},setmetatable({}, {__mode="k"}) @@ -194,6 +195,7 @@ function Player:tick() for _,v in ipairs(self.voices) do v.ticks=v.ticks-1;if v.ticks<=0 and v.release==0 then v.release=math.floor(RATE*0.04) end end end function Player:render() + local closeRender=FrameProfile.section(" audio: Nitro render") local sound=love.sound.newSoundData(BLOCK,RATE,16,2) for i=0,BLOCK-1 do self.tickPhase=self.tickPhase+self.tempo*48/60/RATE @@ -215,6 +217,7 @@ function Player:render() sound:setSample(i,1,math.max(-1,math.min(1,left))) sound:setSample(i,2,math.max(-1,math.min(1,right))) end + closeRender() return sound end function Player:update() diff --git a/src/render/Renderer.lua b/src/render/Renderer.lua index 7cff87285..07fafd583 100644 --- a/src/render/Renderer.lua +++ b/src/render/Renderer.lua @@ -6,6 +6,7 @@ -- neighbor filtering. -- Spec: docs/new-features.md (survey zoom) +local FrameProfile = require("src.core.FrameProfile") local Zoom = require("src.render.Zoom") local Tilt = require("src.render.Tilt") local PaletteFX = require("src.render.PaletteFX") @@ -686,11 +687,13 @@ end -- render.compose mod can composite the world/UI canvases into its own layout. function Renderer:blitCanvas(canvas, sx, sy, zoneList, zoneSx, zoneSy, bx, by, boxX, boxY, boxW, boxH, dpiX, dpiY) + local closeBlit = FrameProfile.section(" renderer: zone blit") local shader = zoneList and zoneList[1] and PaletteFX.shader() or nil if not shader then love.graphics.setScissor(boxX, boxY, boxW, boxH) love.graphics.draw(canvas, bx, by, 0, sx, sy) love.graphics.setScissor() + closeBlit() return end love.graphics.setShader(shader) @@ -713,6 +716,7 @@ function Renderer:blitCanvas(canvas, sx, sy, zoneList, zoneSx, zoneSy, end love.graphics.setScissor() love.graphics.setShader() + closeBlit() end -- THE BARS, FILLED WITH THE EDGE THEY FRAME. @@ -1393,6 +1397,7 @@ function Renderer:endFrame(zones, worldZones) end if present then + local closePresent = FrameProfile.section(" renderer: present pipeline") love.graphics.setCanvas() -- Post-process pipelines run over the finished composite -- world, UI -- and all -- and before GBC FX, so a blur or colour grade is what the @@ -1410,6 +1415,7 @@ function Renderer:endFrame(zones, worldZones) love.graphics.setColor(1, 1, 1, 1) love.graphics.draw(composed, 0, 0) end + closePresent() end self.worldActive = false self.uprightActive = false diff --git a/src/render/TileRenderer.lua b/src/render/TileRenderer.lua index b82fc4cfb..c55510fc7 100644 --- a/src/render/TileRenderer.lua +++ b/src/render/TileRenderer.lua @@ -8,6 +8,7 @@ -- a single static SpriteBatch covering the map plus a border-block ring -- (the ring plays the role of the GB border blocks around small maps). +local FrameProfile = require("src.core.FrameProfile") local Assets = require("src.render.Assets") local Logger = require("src.core.Logger") local Probe = require("src.core.Probe") @@ -1793,6 +1794,7 @@ function TileRenderer:setWin(tx0, ty0, tx1, ty1) end function TileRenderer:ensureWindow(camX, camY, vw, vh) + local closeWindow = FrameProfile.section(" tiles: ensureWindow") local W, H = self.bodyTilesW, self.bodyTilesH vw = vw or W * 8 -- a nil view (headless draw) means the whole body vh = vh or H * 8 @@ -1844,6 +1846,7 @@ function TileRenderer:ensureWindow(camX, camY, vw, vh) end if win and tx0 >= win.tx0 and ty0 >= win.ty0 and tx1 <= win.tx1 and ty1 <= win.ty1 then + closeWindow() return -- still inside the last fill end -- refill with margin so the next few scrolled pixels stay covered @@ -1920,6 +1923,7 @@ function TileRenderer:ensureWindow(camX, camY, vw, vh) cells, drew, W, H, tostring(self.gen3.slots)) end self:setWin(tx0, ty0, tx1, ty1) + closeWindow() return end @@ -1928,6 +1932,7 @@ function TileRenderer:ensureWindow(camX, camY, vw, vh) -- player, and leave the reason in the log (gen3SheetsFor already logged it). if not self.image then self:setWin(tx0, ty0, tx1, ty1) + closeWindow() return end if not self.winBatch then @@ -1970,6 +1975,7 @@ function TileRenderer:ensureWindow(camX, camY, vw, vh) end end self:setWin(tx0, ty0, tx1, ty1) + closeWindow() end -- draw the static tile window, then its animated overdraw, at the camera offset diff --git a/src/world/OverworldController.lua b/src/world/OverworldController.lua index 05f6dc9d0..5d5d65ae8 100644 --- a/src/world/OverworldController.lua +++ b/src/world/OverworldController.lua @@ -9,6 +9,7 @@ -- surfing, Cut trees, trainer sight lines, and dispatches interactions to -- map scripts (data/scripts/), marts, nurses or extracted text. +local FrameProfile = require("src.core.FrameProfile") local Assets = require("src.render.Assets") local Camera = require("src.render.Camera") local Collision = require("src.world.Collision") @@ -16678,6 +16679,7 @@ function OverworldState:drawWorld() -- path below on the vanilla flat/tilt draw local override if not pipelineId then + local closeTiles = FrameProfile.section(" world: tiles") self.map.renderer:drawBorderFill(cam.x, bgY, vw, vh) self.map.renderer:draw(cam.x, bgY, vw, vh) for _, nb in ipairs(self.neighbors) do @@ -16687,6 +16689,7 @@ function OverworldState:drawWorld() if self.g3MirageTower then require("src.world.Gen3MirageTower").drawTower(self, cam) end + closeTiles() end -- per-billboard SGB palette source; only needed (and only paid for) when -- tilting. nil headless / on stale palettes -> billboards go uncolorized. @@ -17401,6 +17404,7 @@ function OverworldState:drawWorld() -- Deliberately unscaled by depth, like :billboard: an effect keeps its -- crisp authored size and only its anchor moves. ctx.drawFx = function(project, scale) + local closeFx = FrameProfile.section(" world: FX") scale = scale or pscale local colors = ctx.spriteColors() local function at(drawFn, wx, wy) @@ -17471,6 +17475,7 @@ function OverworldState:drawWorld() if pt.active then radarOne = pt; at(fxRadarOne, pt.x * 16 + 8, pt.y * 16 + 16) end end radarOne = nil + closeFx() end override = Pipelines.drawWorld(pipelineId, ctx) -- world post-processes (a miniature-diorama blur, a colour grade) fold @@ -17484,11 +17489,13 @@ function OverworldState:drawWorld() -- was retired). The ground pass was skipped on its behalf above, so -- draw it now and fall through to the flat path below rather than -- compositing an empty canvas. + local closeTiles = FrameProfile.section(" world: tiles") self.map.renderer:drawBorderFill(cam.x, bgY, vw, vh) self.map.renderer:draw(cam.x, bgY, vw, vh) for _, nb in ipairs(self.neighbors) do nb.map.renderer:drawMapOnly(cam.x - nb.ox, bgY - nb.oy, vw, vh) end + closeTiles() end end @@ -17581,6 +17588,7 @@ function OverworldState:drawWorld() -- The COLLISION GRID IS UNTOUCHED by any of this. It is in map pixels and -- stays there; only the picture is projected, which is why a compressed -- world still walks the same. + local closeGhosts = FrameProfile.section(" world: entities") for _, g in ipairs(self.ghosts) do -- A GHOST GOES THROUGH THE FREE CAMERA TOO. -- @@ -17606,6 +17614,7 @@ function OverworldState:drawWorld() end if not drawn then g.npc:draw(cam.x - g.ox, cam.y - g.oy) end end + closeGhosts() -- HIDDEN MEANS HIDDEN, for the player as much as for anybody. -- -- Two Gen 3 things write this and neither had a reader: the @@ -17909,6 +17918,7 @@ function OverworldState:drawWorld() and groundForRise:beginSprites() then spriteDepthGround = groundForRise end + local closeEntities = FrameProfile.section(" world: entities") for _, e in ipairs(self.entities) do if self:gen3AboveTopLayer(e) then onTop = onTop or {} @@ -17925,6 +17935,7 @@ function OverworldState:drawWorld() spriteDepthGround:endSprites() spriteDepthGround = nil end + closeEntities() -- The Gen 3 top layer goes on AFTER the entity pass and before the -- field effects: it is the half of every metatile the player walks -- behind -- treetops, upper storeys, the far rail of a bridge. On a @@ -17956,6 +17967,7 @@ function OverworldState:drawWorld() self:eachEmote(fxEmote) emoteEarly = true end + local closeTiles = FrameProfile.section(" world: tiles") aim(self.map.renderer, 0, 0) self.map.renderer:drawAbove(cam.x, bgY, vw, vh) aim(self.map.renderer) @@ -17966,8 +17978,12 @@ function OverworldState:drawWorld() aim(nb.map.renderer) end end + closeTiles() + closeEntities = FrameProfile.section(" world: entities") for _, e in ipairs(onTop or {}) do drawEntity(e) end + closeEntities() + local closeFx = FrameProfile.section(" world: FX") fxHeal() fxDust() fxCutTree() @@ -17988,6 +18004,7 @@ function OverworldState:drawWorld() fxRod() -- Smoke keeps the template's priority 0, above the ship and map layers. fxSSAnneSmoke() + closeFx() else -- === TILT PATH: ground-hugging FX stay on the projected ground, all -- standing things billboard upright over it in a separate pass. ====== @@ -17997,6 +18014,7 @@ function OverworldState:drawWorld() -- draws them last, over the sprites, in the same canvas; here the two -- layers are separate and composited ground-under-upright, so drawing -- them now into the still-active ground canvas is order-equivalent. + local closeFx = FrameProfile.section(" world: FX") fxHeal() fxDust() fxCutTree() @@ -18004,6 +18022,7 @@ function OverworldState:drawWorld() -- ...and the gates with them: they are behind every upright sprite (see -- drawGen3Gates), so the ground canvas is exactly where they belong self:drawGen3Gates(cam) + closeFx() Game.renderer:beginUprightPass() @@ -18024,6 +18043,7 @@ function OverworldState:drawWorld() end table.sort(items, function(a, b) return a.y < b.y end) + local closeEntities = FrameProfile.section(" world: entities") for _, it in ipairs(items) do if it.kind == "ghost" then -- ghosts billboard just like real entities (foot offset folds in the @@ -18059,6 +18079,8 @@ function OverworldState:drawWorld() end end + closeEntities() + closeFx = FrameProfile.section(" world: FX") -- Standing world FX: each billboards at the ground foot of the -- character it belongs to, so it stays upright over the tilted ground. -- emote bubble -> the spotting NPC's foot (rides above its head) @@ -18100,6 +18122,7 @@ function OverworldState:drawWorld() radarOne = nil Game.renderer:endUprightPass() + closeFx() end -- LAST IN THE WORLD PASS, over everything the cave contains: the black @@ -18107,6 +18130,7 @@ function OverworldState:drawWorld() -- drawUI because it is anchored to the PLAYER, not to the screen -- the -- cartridge can put it at a fixed (120,80) because its camera never lets -- the player leave the middle, and this port's does at a map edge. + local closeFx = FrameProfile.section(" world: FX") self:drawGen3Flash(cam, vw, vh) -- the Mirage Tower's falling fossil and ceiling crumbs: OAM priority 0 if self.g3MirageTower or self.g3MirageCrumbles then @@ -18118,6 +18142,7 @@ function OverworldState:drawWorld() -- in the world pass rather than the UI pass for the same reason the flash -- is: it is anchored to a CELL, not to the screen. self:drawGen3Decorate(cam) + closeFx() end -- The cursor the DECORATE row hands the player: the decoration's own From 5507ef2f5f5a4b869470d7861ad6fec39daa1422 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:47:27 +0100 Subject: [PATCH 02/19] perf(P1): skip redundant software pacing after VSync presentation --- docs/frame-pacing.md | 47 +++++++++ main.lua | 23 +---- src/core/FrameCap.lua | 44 +++++++++ tests/engine/frame_pacing.lua | 153 ++++++++++++++++++++++++++++++ tools/check_frame_pacing.py | 50 ++++++++++ tools/frame-pacing-check/conf.lua | 7 ++ tools/frame-pacing-check/main.lua | 94 ++++++++++++++++++ 7 files changed, 400 insertions(+), 18 deletions(-) create mode 100644 docs/frame-pacing.md create mode 100644 tests/engine/frame_pacing.lua create mode 100644 tools/check_frame_pacing.py create mode 100644 tools/frame-pacing-check/conf.lua create mode 100644 tools/frame-pacing-check/main.lua diff --git a/docs/frame-pacing.md b/docs/frame-pacing.md new file mode 100644 index 000000000..d3b291cf2 --- /dev/null +++ b/docs/frame-pacing.md @@ -0,0 +1,47 @@ +# P1: VSync and the software deadline + +The run loop records whether it actually presented a frame. After presentation, +`FrameCap.pace` skips the software wait when VSync is active and the FPS cap is +at least the reported display refresh rate. Without presentation, with VSync +off, with an unknown rate, or with a lower FPS cap, the existing carried +deadline, one-millisecond sleep chunks and stall re-anchor remain active. + +The default-on rollback switch is independent of all other performance work: + +```lua +require("src.core.FrameCap").vsyncPacing = false +``` + +Display flags are sampled at most once per second to avoid allocating their +table each frame. Provider/VSync changes invalidate that sample; other display +rate changes are observed on the next periodic sample. Existing option values, +simulation timing, mod interfaces and callback call sites are unchanged. + +`frame pacing: sleep` in the existing F11 FrameProfile measures the helper, +including its software wait. `present (GPU wait / vsync)` retains its original +scope. Removing a redundant software wait can move wall time into present +without changing FPS. + +The owned-window probe runs the real helper and FrameProfile with the switch +off/on, each after 120 warm-up frames and over 120 measured frames. Run through +the guarded launcher: + +```sh +python3 tools/check_frame_pacing.py --love /path/to/love --report /path/to/owned/qa/report.json +``` + +An older public checkout can use `--qa-tools /path/to/fork/tools`. The launcher +pins inputs, uses a separate QA identity, retains raw profile logs and records +SHA-256 hashes of the actual measured source files alongside the Git parent. + +Observed macOS/arm64, 60-Hz display, VSync 1, cap 60: + +| Backend | Software wait off/on, ms/frame | Present off/on, ms/frame | CPU off/on, ms/frame | +| --- | ---: | ---: | ---: | +| LÖVE 11.5 OpenGL | 0.00 / 0.01 | 16.59 / 16.54 | 0.672 / 0.790 | +| LÖVE 12 Metal | 16.43 / 0.01 | 0.13 / 16.56 | 0.769 / 0.629 | + +Both enabled runs made zero extra sleep calls and stayed near 60 FPS, with no +measured interval exceeding 1.5 display periods. These short blank-window +checks establish the pacing decision and its profiler scope. They do not +establish a universal CPU/FPS gain, loaded-world behavior, or handheld results. diff --git a/main.lua b/main.lua index 18325ffdf..3b1f7c1ac 100644 --- a/main.lua +++ b/main.lua @@ -1261,12 +1261,14 @@ function love.run() closeU() end + local presented = false if love.graphics and love.graphics.isActive() then love.graphics.origin() love.graphics.clear(love.graphics.getBackgroundColor()) if love.draw then love.draw() end local closeP = FrameProfile.section("present (GPU wait / vsync)") love.graphics.present() + presented = true closeP() end -- Counted after present, so a frame in the trace means a frame that was @@ -1299,24 +1301,9 @@ function love.run() if love.timer then if paced then - -- Sleep out the remainder of the frame budget, measured from the - -- carried deadline, in small chunks so the OS timer stays - -- responsive. vsync is untouched: when it already paces slower - -- than the cap the remainder is <= 0 and this rounds to a no-op. - local budget = 1 / FrameCap.current - nextFrame = nextFrame + budget - local now = love.timer.getTime() - -- A stall (alt-tab, a GC pause, a blocked import) can leave the - -- deadline more than a full budget in the past; re-anchor to now so - -- we pace the next frame rather than burst uncapped to catch up. - if now - nextFrame > budget then - nextFrame = now - end - while true do - local remaining = nextFrame - love.timer.getTime() - if remaining <= 0 then break end - love.timer.sleep(remaining < 0.001 and remaining or 0.001) - end + local closeSleep = FrameProfile.section("frame pacing: sleep") + nextFrame = FrameCap.pace(love.timer, love.window, presented, nextFrame) + closeSleep() else love.timer.sleep(0.001) end diff --git a/src/core/FrameCap.lua b/src/core/FrameCap.lua index 2e5b36feb..09dbd7e98 100644 --- a/src/core/FrameCap.lua +++ b/src/core/FrameCap.lua @@ -25,6 +25,50 @@ FrameCap.DEFAULT = 60 -- save editor are paced before any save applies its stored option. FrameCap.current = FrameCap.DEFAULT +-- P1 rollback switch. Each frame still falls back to software pacing when +-- there was no present, VSync is off, or the display rate is unavailable. +FrameCap.vsyncPacing = true +local _refreshWindow, _refreshVsync, _refreshAt, _refreshRate +local REFRESH_POLL_SECONDS = 1 + +local function presentationPaces(window, now) + if not (window and window.getVSync and window.getMode) then return false end + local vsync = window.getVSync() + if type(vsync) ~= "number" or vsync == 0 then + _refreshVsync = vsync + return false + end + -- getMode returns a new flags table: sample it once a second rather than + -- allocate one each frame. Provider/VSync changes invalidate the sample; + -- display-rate changes are observed on the next periodic sample. + if window ~= _refreshWindow or vsync ~= _refreshVsync or not _refreshAt + or now < _refreshAt or now - _refreshAt >= REFRESH_POLL_SECONDS then + local _, _, flags = window.getMode() + local rate = type(flags) == "table" and tonumber(flags.refreshrate) + _refreshWindow, _refreshVsync, _refreshAt = window, vsync, now + _refreshRate = rate and rate > 0 and rate < math.huge and rate or nil + end + return _refreshRate ~= nil and FrameCap.current >= _refreshRate +end + +-- The run loop owns the deadline and passes back the returned value. Keeping +-- the original fallback here lets tests exercise the real pacing operation. +function FrameCap.pace(timer, window, presented, nextFrame) + local now = timer.getTime() + if FrameCap.vsyncPacing and presented and presentationPaces(window, now) then + return now + end + local budget = 1 / FrameCap.current + nextFrame = nextFrame + budget + if now - nextFrame > budget then nextFrame = now end + while true do + local remaining = nextFrame - timer.getTime() + if remaining <= 0 then break end + timer.sleep(remaining < 0.001 and remaining or 0.001) + end + return nextFrame +end + -- Nearest valid step for an arbitrary value (a hand-edited options.lua or -- an old save with no fpsCap key), so a bad number degrades to something -- sane; nil / non-numbers fall back to the default. A value below MIN or diff --git a/tests/engine/frame_pacing.lua b/tests/engine/frame_pacing.lua new file mode 100644 index 000000000..27a96b39e --- /dev/null +++ b/tests/engine/frame_pacing.lua @@ -0,0 +1,153 @@ +local T = require("tests.harness") +local Cap = require("src.core.FrameCap") +local function clock(start) + local now, sleeps, total = start or 0, 0, 0 + return { + getTime = function() + return now + end, + sleep = function(dt) + now = now + dt + sleeps = sleeps + 1 + total = total + dt + end, + advance = function(dt) + now = now + dt + end, + sleeps = function() + return sleeps, total + end, + } +end +local function window(sync, rate) + local calls = 0 + return { + getVSync = function() + return sync + end, + getMode = function() + calls = calls + 1 + return 320, 240, { refreshrate = rate } + end, + modeCalls = function() + return calls + end, + set = function(s, r) + sync, rate = s, r + end, + } +end +Cap.current = 60 +T.eq(Cap.vsyncPacing, true, "P1 switch defaults on") +for _, sync in ipairs({ 1, -1, 2 }) do + local timer, w = clock(), window(sync, 60) + local nextFrame = 0 + for _ = 1, 60 do + timer.advance(1 / 60) + nextFrame = Cap.pace(timer, w, true, nextFrame) + end + T.eq(timer.sleeps(), 0, "active VSync at the cap receives no additional sleep") + T.eq(w.modeCalls(), 1, "display flags are not allocated each frame") +end +for _, case in ipairs({ + { sync = 0, rate = 60, presented = true }, + { sync = 1, rate = 144, presented = true }, + { sync = 1, rate = 0, presented = true }, + { sync = 1, rate = 60, presented = false }, +}) do + local timer, w = clock(), window(case.sync, case.rate) + local deadline = Cap.pace(timer, w, case.presented, 0) + T.check(timer.sleeps() > 0, "software cap remains for disabled/unknown/faster/unpresented cases") + T.check(math.abs(deadline - 1 / 60) < 1e-9, "software deadline remains one frame ahead") +end +local timer, w = clock(), window(1, 60) +Cap.vsyncPacing = false +Cap.pace(timer, w, true, 0) +T.check(timer.sleeps() > 0, "P1 switch restores software pacing") +T.eq(w.modeCalls(), 0, "disabled P1 does not query display flags") +Cap.vsyncPacing = true +timer, w = clock(), window(1, 60) +local deadline = Cap.pace(timer, w, true, 0) +w.set(0, 60) +deadline = Cap.pace(timer, w, true, deadline) +T.check(math.abs(deadline - 1 / 60) < 1e-9, "turning VSync off resumes the carried software deadline") +timer.advance(1) +deadline = Cap.pace(timer, w, true, deadline) +T.eq(deadline, timer.getTime(), "stalls re-anchor instead of accumulating catch-up frames") +deadline = Cap.pace(timer, w, true, deadline) +T.eq(deadline, timer.getTime(), "software pacing resumes after a stall") +timer, w = clock(), window(1, 60) +Cap.pace(timer, w, true, 0) +w.set(1, 144) +timer.advance(1.01) +deadline = Cap.pace(timer, w, true, timer.getTime()) +T.check(timer.sleeps() > 0, "display rate changes refresh the software-cap decision") +T.eq(w.modeCalls(), 2, "display sample refresh is bounded") +timer = clock() +Cap.pace(timer, nil, true, 0) +T.check(timer.sleeps() > 0, "headless provider absence retains the software cap") + +-- Execute the actual run-loop body with native present/timer boundaries +-- substituted, so a correct helper wired to the wrong loop still fails. +local file = assert(io.open("main.lua", "r")) +local source = file:read("*a") +file:close() +local start = assert(source:find("function love.run()", 1, true)) +for _, active in ipairs({ true, false }) do + local fake = clock() + fake.step = function() + return 1 / 60 + end + local presents = 0 + local noop = function() end + local env = { + love = { + timer = fake, + window = window(1, 60), + graphics = { + isActive = function() + return active + end, + origin = noop, + clear = noop, + getBackgroundColor = function() + return 0, 0, 0, 1 + end, + present = function() + presents = presents + 1 + fake.advance(1 / 60 - 0.001) + end, + }, + }, + BootTrace = { mark = noop, frame = noop }, + Frames = { tick = noop }, + FrameProfile = { + section = function() + return noop + end, + }, + WindowFrame = { + draw = function(fn) + fn() + end, + }, + GraphicsStack = { drain = noop }, + pacingEnabled = function() + return true + end, + lastLogFlush = 0, + } + setmetatable(env, { __index = _G }) + local chunk + if setfenv then + chunk = assert(loadstring(source:sub(start), "@main.lua:love.run")) + setfenv(chunk, env) + else + chunk = assert(load(source:sub(start), "@main.lua:love.run", "t", env)) + end + chunk() + env.love.run()() + T.eq(presents, active and 1 or 0, "actual main loop presents only active graphics") + T.eq(fake.sleeps() > 0, not active, "actual main loop bypasses sleep only after native presentation") +end +T.finish() diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py new file mode 100644 index 000000000..952e314da --- /dev/null +++ b/tools/check_frame_pacing.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Run owned-window VSync pacing measurements through the local QA guard.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--love', type=Path, required=True) + parser.add_argument('--report', type=Path, required=True) + parser.add_argument('--qa-tools', type=Path) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + sys.path.insert(0, str(args.qa_tools or root / 'tools')) + try: + from qa_storage import qa_source, qa_cache, qa_profile, qa_run + except ImportError: + parser.error('QA storage guard is required; provide --qa-tools') + qa_source(root) + qa_source(args.love.resolve()) + qa_cache(args.report.parent) + args.report.parent.mkdir(parents=True, exist_ok=True) + identity = 'oasc-gen2recomp-qa-frame-pacing-' + str(time.time_ns()) + qa_profile(Path.home() / 'Library/Application Support/LOVE' / identity) + result = qa_run([str(args.love.resolve()), str(root / 'tools/frame-pacing-check')], + cwd=root, env=dict(os.environ, POKEPORT_IDENTITY=identity, + FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1'), + capture_output=True, text=True, timeout=90) + args.report.with_suffix('.log').write_text(result.stdout + result.stderr) + records = [line.removeprefix('P1_NATIVE_RESULT ') for line in result.stdout.splitlines() + if line.startswith('P1_NATIVE_RESULT ')] + if result.returncode or len(records) != 1: + raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) + report = json.loads(records[0]) + report['source'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip() + files = ('main.lua', 'src/core/FrameCap.lua', 'src/core/FrameProfile.lua', + 'tools/frame-pacing-check/main.lua', 'tools/frame-pacing-check/conf.lua') + report['sha256'] = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} + args.report.write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/tools/frame-pacing-check/conf.lua b/tools/frame-pacing-check/conf.lua new file mode 100644 index 000000000..79551e6d7 --- /dev/null +++ b/tools/frame-pacing-check/conf.lua @@ -0,0 +1,7 @@ +function love.conf(t) + assert(os.getenv("FRAME_PACING_QA_GUARDED") == "1", "use tools/check_frame_pacing.py") + t.identity = assert(os.getenv("POKEPORT_IDENTITY")) + t.window.title = "Frame pacing QA" + t.window.width, t.window.height, t.window.vsync = 320, 180, 1 + t.modules.audio = false +end diff --git a/tools/frame-pacing-check/main.lua b/tools/frame-pacing-check/main.lua new file mode 100644 index 000000000..e280a2d74 --- /dev/null +++ b/tools/frame-pacing-check/main.lua @@ -0,0 +1,94 @@ +local root = assert(os.getenv("FRAME_PACING_REPO")) +package.path = root .. "/?.lua;" .. root .. "/?/init.lua;" .. package.path +local Cap = require("src.core.FrameCap") +local Profile = require("src.core.FrameProfile") +local Json = require("src.link.Json") +local phase, frame, deadline, last, started, cpuStarted = 1, 0, 0, 0, 0, 0 +local sleeps, intervals, results = 0, {}, {} +local WINDOW, WARMUP = 120, 120 +local timer = { + getTime = love.timer.getTime, + sleep = function(dt) + sleeps = sleeps + 1 + love.timer.sleep(dt) + end, +} +local _, _, mode = love.window.getMode() +local refresh = tonumber(mode.refreshrate) or 0 +Cap.current = refresh > 0 and refresh or 60 +local function startPhase() + Profile.setEnabled(false) + Cap.vsyncPacing = phase == 2 + frame, sleeps, intervals = 0, 0, {} + deadline = timer.getTime() +end +local function finishPhase() + local long = 0 + for _, interval in ipairs(intervals) do + if refresh > 0 and interval > 1.5 / refresh then + long = long + 1 + end + end + table.sort(intervals) + results[phase] = { + enabled = Cap.vsyncPacing, + frames = WINDOW, + seconds = timer.getTime() - started, + medianMs = intervals[math.floor(#intervals / 2)] * 1000, + p95Ms = intervals[math.ceil(#intervals * 0.95)] * 1000, + maxMs = intervals[#intervals] * 1000, + framesOver1_5Periods = long, + extraSleepCalls = sleeps, + processCpuMsPerFrame = (os.clock() - cpuStarted) / WINDOW * 1000, + } + if phase == 2 then + if refresh > 0 and love.window.getVSync() ~= 0 then + assert(sleeps == 0, "VSync phase still slept") + end + print("P1_NATIVE_RESULT " .. Json.encode({ + refresh = refresh, + vsync = love.window.getVSync(), + cap = Cap.current, + os = love.system.getOS(), + arch = jit and jit.arch or "unknown", + renderer = love.graphics.getRendererInfo(), + phases = results, + })) + return true + end + phase = 2 + startPhase() +end +function love.run() + startPhase() + return function() + love.event.pump() + for name in love.event.poll() do + if name == "quit" then + return 1 + end + end + if frame == WARMUP then + sleeps = 0 + Profile.setEnabled(true) + started, last = timer.getTime(), timer.getTime() + cpuStarted = os.clock() + end + love.graphics.clear(0.03, 0.04, 0.06) + local close = Profile.section("present (GPU wait / vsync)") + love.graphics.present() + close() + close = Profile.section("frame pacing: sleep") + deadline = Cap.pace(timer, love.window, true, deadline) + close() + frame = frame + 1 + if frame > WARMUP then + local now = timer.getTime() + intervals[#intervals + 1], last = now - last, now + Profile.frame() + end + if frame == WARMUP + WINDOW and finishPhase() then + return 0 + end + end +end From 65c30879f50bae1e9912f79f227fb45a7b670643 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 02:12:49 +0100 Subject: [PATCH 03/19] perf(P2): tune incremental GC and spend bounded idle deadline time --- docs/gc-frame-budget.md | 51 ++++++++++++ main.lua | 6 +- src/core/FrameCap.lua | 11 ++- src/core/GCFrameBudget.lua | 86 ++++++++++++++++++++ src/core/Game.lua | 16 ++-- src/core/Performance.lua | 12 +++ tests/engine/gc_frame_budget.lua | 126 ++++++++++++++++++++++++++++++ tools/check_frame_pacing.py | 11 ++- tools/frame-pacing-check/gc.lua | 124 +++++++++++++++++++++++++++++ tools/frame-pacing-check/main.lua | 4 + 10 files changed, 429 insertions(+), 18 deletions(-) create mode 100644 docs/gc-frame-budget.md create mode 100644 src/core/GCFrameBudget.lua create mode 100644 tests/engine/gc_frame_budget.lua create mode 100644 tools/frame-pacing-check/gc.lua diff --git a/docs/gc-frame-budget.md b/docs/gc-frame-budget.md new file mode 100644 index 000000000..abee388ba --- /dev/null +++ b/docs/gc-frame-budget.md @@ -0,0 +1,51 @@ +# P2: incremental GC in unused deadline time + +`Performance.gcBudget` defaults to `true`. At boot the collector uses pause 120 +and step multiplier 300. Each concrete `Performance.CAPS` row additionally has +`gcPause`, `gcStepMul` and `gcBudgetSeconds`; tiers may reduce the default +0.0005-second idle allowance. No options are rewritten. + +The ordinary engine's fixed `step(1)` moves out of `Game:update`. The run loop +uses no-argument incremental steps before its remaining software wait. It starts +no further step after the earlier of the actual deadline and the half-millisecond +allowance, and stops on completion of a cycle. An expired deadline or a stopped +collector receives no work. VSync never gets an invented future budget; only +the actual remainder of its carried deadline is eligible, and no extra sleep +is added after VSync. + +The budget is cooperative: a single indivisible collector step can finish past +the boundary. It is not a preemption guarantee for an arbitrary heap/finalizer. +The F11 child section `frame pacing: gc budget` is nested in the existing +`frame pacing: sleep` section, so the parent includes collection plus waiting. + +The fork's pre-existing Gen3 `Game3.stepGC` delegation stays at its original +update boundary with the original arguments/behavior. A frame owned by that +public seam gets no second idle GC service. Its delegated/custom work remains +outside the engine idle allowance. This preserves consumers that replace it. + +The independent rollback switch is: + +```lua +require("src.core.Performance").gcBudget = false +``` + +The next frame restores the previous pause/multiplier and uses the old native +update step. The separate P1 switch and callback interfaces are unchanged. + +`tools/check_frame_pacing.py --gc --love /path/to/love --report /owned/qa/gc.json` +runs the guarded native comparison. P1 stays enabled for both phases; only P2 +changes. The workload allocates 512 short tables per frame, with 120 warm-up +and 120 measured frames per phase. Raw FrameProfile logs, original tuning, +heap samples and measured-source SHA-256 hashes are retained. + +Observed composed fork, macOS/arm64, 60 Hz, VSync 1, cap 60: + +| Backend | Original fixed step, ms/frame | New idle mean / max, ms | Heap peak before / after, KiB | +| --- | ---: | ---: | ---: | +| LÖVE 11.5 OpenGL | 0.00 (rounded) | 0.098 / 0.499 | 918 / 775 | +| LÖVE 12 Metal | 0.00 (rounded) | 0.120 / 0.278 | 1,179 / 692 | + +Short-workload CPU means were 1.012 → 0.920 ms/frame and 0.717 → 0.651 ms/frame, +respectively. Both retained approximately 60 FPS and restored the original +200/200 tuning when disabled. These are bounded synthetic allocation checks, +not full-game heap, long-session, arbitrary-finalizer or handheld measurements. diff --git a/main.lua b/main.lua index 3b1f7c1ac..0416fe53f 100644 --- a/main.lua +++ b/main.lua @@ -1208,6 +1208,9 @@ end function love.run() BootTrace.mark("love.run enter") + local Performance = require("src.core.Performance") + local GCFrameBudget = require("src.core.GCFrameBudget") + GCFrameBudget.configure(Performance) if love.load then love.load(love.arg.parseGameArguments(arg), arg) end BootTrace.mark("love.load returned") @@ -1245,6 +1248,7 @@ function love.run() -- update dt if love.timer then dt = love.timer.step() end + GCFrameBudget.beginFrame(Performance) -- call update and draw -- @@ -1302,7 +1306,7 @@ function love.run() if love.timer then if paced then local closeSleep = FrameProfile.section("frame pacing: sleep") - nextFrame = FrameCap.pace(love.timer, love.window, presented, nextFrame) + nextFrame = FrameCap.pace(love.timer, love.window, presented, nextFrame, GCFrameBudget.idle) closeSleep() else love.timer.sleep(0.001) diff --git a/src/core/FrameCap.lua b/src/core/FrameCap.lua index 09dbd7e98..763e116f2 100644 --- a/src/core/FrameCap.lua +++ b/src/core/FrameCap.lua @@ -53,14 +53,19 @@ end -- The run loop owns the deadline and passes back the returned value. Keeping -- the original fallback here lets tests exercise the real pacing operation. -function FrameCap.pace(timer, window, presented, nextFrame) +function FrameCap.pace(timer, window, presented, nextFrame, idleWork) local now = timer.getTime() + local budget = 1 / FrameCap.current + nextFrame = nextFrame + budget if FrameCap.vsyncPacing and presented and presentationPaces(window, now) then + if idleWork then + idleWork(timer, nextFrame) + return timer.getTime() + end return now end - local budget = 1 / FrameCap.current - nextFrame = nextFrame + budget if now - nextFrame > budget then nextFrame = now end + if idleWork then idleWork(timer, nextFrame) end while true do local remaining = nextFrame - timer.getTime() if remaining <= 0 then break end diff --git a/src/core/GCFrameBudget.lua b/src/core/GCFrameBudget.lua new file mode 100644 index 000000000..146d95f48 --- /dev/null +++ b/src/core/GCFrameBudget.lua @@ -0,0 +1,86 @@ +-- Cooperative incremental collection in otherwise unused frame time. +local Profile = require("src.core.FrameProfile") +local Budget = {} +local MAX_SECONDS = 0.0005 +local _collector, _priorPause, _priorMul, _pause, _mul +local _enabled, _seconds, _canQueryRunning, _facadeStepped = false, 0, false, false + +local function nonnegative(value, fallback) + if type(value) ~= "number" or value ~= value or value < 0 or value == math.huge then + return fallback + end + return value +end + +local function restoreTuning() + if _collector and _priorPause ~= nil then + _collector("setpause", _priorPause) + _collector("setstepmul", _priorMul) + end + _collector, _priorPause, _priorMul, _pause, _mul = nil, nil, nil, nil, nil +end + +function Budget.configure(performance, collector) + collector = collector or collectgarbage + if not performance.gcBudget or type(collector) ~= "function" then + restoreTuning() + _enabled = false + return + end + if _collector ~= collector then + restoreTuning() + end + local caps = performance.CAPS[performance.tier] or {} + local pause = math.floor(nonnegative(caps.gcPause, performance.GC_PAUSE)) + local mul = math.floor(nonnegative(caps.gcStepMul, performance.GC_STEP_MUL)) + if not _collector then + _collector = collector + _priorPause = collector("setpause", pause) + _priorMul = collector("setstepmul", mul) + _canQueryRunning = pcall(collector, "isrunning") + else + if pause ~= _pause then + collector("setpause", pause) + end + if mul ~= _mul then + collector("setstepmul", mul) + end + end + _pause, _mul = pause, mul + _seconds = math.min(MAX_SECONDS, nonnegative(caps.gcBudgetSeconds, performance.GC_BUDGET_SECONDS)) + _enabled = true +end + +function Budget.beginFrame(performance, collector) + _facadeStepped = false + Budget.configure(performance, collector) +end + +-- An existing public compatibility method retains ownership of its frame. +-- Its call, arguments and return behavior are not replaced by idle collection. +function Budget._facadeHandled() + _facadeStepped = true +end + +function Budget.idle(timer, deadline) + if not _enabled or _facadeStepped or _seconds <= 0 then + return 0 + end + local start = timer.getTime() + local stop = math.min(deadline, start + _seconds) + if stop <= start or (_canQueryRunning and not _collector("isrunning")) then + return 0 + end + local close = Profile.section(" frame pacing: gc budget") + local steps = 0 + while timer.getTime() < stop do + steps = steps + 1 + if _collector("step") then + break + end + end + close() + return steps +end + +return Budget diff --git a/src/core/Game.lua b/src/core/Game.lua index 9dc07ce9d..9be08083e 100644 --- a/src/core/Game.lua +++ b/src/core/Game.lua @@ -10,6 +10,8 @@ local Renderer = require("src.render.Renderer") local SaveData = require("src.core.SaveData") local StateStack = require("src.core.StateStack") local FrameProfile = require("src.core.FrameProfile") +local Performance = require("src.core.Performance") +local GCFrameBudget = require("src.core.GCFrameBudget") local TouchControls = require("src.core.TouchControls") local ModLoader = require("src.mods.Loader") local ModRuntime = require("src.mods.Runtime") @@ -635,19 +637,11 @@ function Game:update(dt) pcall(function() require("src.core.DiscordPresence").update(dt) end) close() end - -- Steady-state memory backstop: advance the incremental collector one - -- small step every rendered frame. The heavy GPU objects are now freed - -- explicitly (map eviction, battle exit, canvas/renderer swaps), so this - -- only has to keep ordinary Lua-heap garbage (per-frame tables/closures) - -- from drifting upward over a long session, and to spread collection out - -- so the default lazy schedule never batches it into a visible pause. - -- ONE INCREMENTAL GC STEP PER FRAME. Cheap on a small heap and not - -- obviously cheap under a mod that allocates a world's worth of geometry, - -- which is exactly the case being measured -- so it is named rather than - -- assumed. + -- Ordinary engine collection moves to spare deadline time in love.run. + -- P2 disabled retains the original native update step. if collectgarbage then local close = FrameProfile.section(" update: gc step") - collectgarbage("step", 1) + if not Performance.gcBudget then collectgarbage("step", 1) end close() end end diff --git a/src/core/Performance.lua b/src/core/Performance.lua index 861121ddd..359ba0811 100644 --- a/src/core/Performance.lua +++ b/src/core/Performance.lua @@ -42,6 +42,13 @@ local Performance = {} +-- P2 is independently reversible. Tier rows can reduce the idle budget or +-- tune the collector without changing the persisted presentation options. +Performance.gcBudget = true +Performance.GC_PAUSE = 120 +Performance.GC_STEP_MUL = 300 +Performance.GC_BUDGET_SECONDS = 0.0005 + -- Option-row order (auto first, then most to least capable). Performance.TIERS = { "auto", "high", "balanced", "low" } @@ -60,6 +67,11 @@ Performance.CAPS = { balanced = { tilt = false, gbcfx = false, survey = true, fpsMax = false }, low = { tilt = false, gbcfx = false, survey = false, fpsMax = 60 }, } +for _, caps in pairs(Performance.CAPS) do + caps.gcPause = Performance.GC_PAUSE + caps.gcStepMul = Performance.GC_STEP_MUL + caps.gcBudgetSeconds = Performance.GC_BUDGET_SECONDS +end -- Live resolved tier (never "auto"); Game:applyOptions sets it and the -- renderer / options row read it back. Defaults to the unclamped tier so diff --git a/tests/engine/gc_frame_budget.lua b/tests/engine/gc_frame_budget.lua new file mode 100644 index 000000000..974ba084e --- /dev/null +++ b/tests/engine/gc_frame_budget.lua @@ -0,0 +1,126 @@ +local T = require("tests.harness") +local Performance = require("src.core.Performance") +local Budget = require("src.core.GCFrameBudget") +local Cap = require("src.core.FrameCap") + +local function setup(cost) + local state = { now = 0, pause = 200, mul = 200, steps = 0, running = true, stepArgs = {}, sleeps = 0 } + local timer = { + getTime = function() + return state.now + end, + sleep = function(dt) + state.now = state.now + dt + state.sleeps = state.sleeps + 1 + end, + } + local function collector(command, ...) + local value = (...) + if command == "setpause" then + local old = state.pause + state.pause = value + return old + end + if command == "setstepmul" then + local old = state.mul + state.mul = value + return old + end + if command == "isrunning" then + return state.running + end + assert(command == "step", "unexpected collector command") + state.steps = state.steps + 1 + state.stepArgs[#state.stepArgs + 1] = select("#", ...) + state.now = state.now + (cost or 0.0001) + return state.completeAt and state.steps >= state.completeAt or false + end + return state, timer, collector +end +T.eq(Performance.gcBudget, true, "P2 defaults on") +T.eq(Performance.GC_PAUSE, 120, "requested collector pause") +T.eq(Performance.GC_STEP_MUL, 300, "requested collector step multiplier") +for _, tier in ipairs({ "high", "balanced", "low" }) do + T.eq(Performance.CAPS[tier].gcBudgetSeconds, 0.0005, "tier carries the default idle budget") +end +local state, timer, gc = setup() +Performance.tier = "high" +Budget.beginFrame(Performance, gc) +T.eq(state.pause, 120, "frame applies requested pause") +T.eq(state.mul, 300, "frame applies requested step multiplier") +local steps = Budget.idle(timer, 0.01) +T.eq(steps, 5, "idle work stops at the half-millisecond budget") +for _, n in ipairs(state.stepArgs) do + T.eq(n, 0, "incremental step has no fixed kilobyte argument") +end +local before = state.steps +T.eq(Budget.idle(timer, state.now), 0, "no collector work starts at an exhausted deadline") +T.eq(state.steps, before, "expired deadline leaves collector untouched") +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +T.eq(Budget.idle(timer, 0.00025), 3, "shorter deadline bounds started steps") +T.check(state.now <= 0.00035, "indivisible work can overshoot by at most one tested step") +state, timer, gc = setup() +state.completeAt = 2 +Budget.beginFrame(Performance, gc) +T.eq(Budget.idle(timer, 0.01), 2, "completed cycle does not immediately start another cycle") +state.running = false +T.eq(Budget.idle(timer, 0.01), 0, "a stopped collector is not restarted") +state.running = true +Budget._facadeHandled() +T.eq(Budget.idle(timer, 0.01), 0, "existing public GC delegation retains its frame") +Budget.beginFrame(Performance, gc) +T.check(Budget.idle(timer, 0.01) > 0, "next frame resets compatibility delegation ownership") +Performance.gcBudget = false +Budget.beginFrame(Performance, gc) +T.eq(state.pause, 200, "disable restores previous collector pause") +T.eq(state.mul, 200, "disable restores previous step multiplier") +T.eq(Budget.idle(timer, 0.01), 0, "disabled P2 does no idle collector work") +Performance.gcBudget = true +local caps = Performance.CAPS.low +local oldPause, oldMul, oldSeconds = caps.gcPause, caps.gcStepMul, caps.gcBudgetSeconds +caps.gcPause, caps.gcStepMul, caps.gcBudgetSeconds = 140, 250, 0.0002 +Performance.tier = "low" +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +T.eq(state.pause, 140, "tier-specific pause is respected") +T.eq(state.mul, 250, "tier-specific step multiplier is respected") +T.eq(Budget.idle(timer, 0.01), 2, "tier can reduce the idle budget") +caps.gcBudgetSeconds = 0.01 +Budget.beginFrame(Performance, gc) +before = state.steps +Budget.idle(timer, state.now + 0.1) +T.check(state.steps - before <= 6, "tier override cannot exceed the half-millisecond ceiling") +caps.gcPause, caps.gcStepMul, caps.gcBudgetSeconds = oldPause, oldMul, oldSeconds +Performance.tier = "high" +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +Cap.current, Cap.vsyncPacing = 60, false +local deadline = Cap.pace(timer, nil, false, 0, Budget.idle) +T.eq(state.steps, 5, "actual software pacing performs bounded GC before sleeping") +T.check(state.sleeps > 0, "software pacing sleeps after collection") +T.check(math.abs(deadline - 1 / 60) < 1e-9, "collection does not move the software deadline") +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +Cap.vsyncPacing = true +local window = { + getVSync = function() + return 1 + end, + getMode = function() + return 320, 180, { refreshrate = 60 } + end, +} +state.now = 1 / 60 - 0.0003 +Cap.pace(timer, window, true, 0, Budget.idle) +T.check(state.steps > 0 and state.steps <= 4, "VSync uses only actual remaining deadline time") +T.eq(state.sleeps, 0, "VSync receives no extra sleep after collection") +state, timer, gc = setup() +Budget.beginFrame(Performance, gc) +state.now = 1 / 60 + 0.001 +Cap.pace(timer, window, true, 0, Budget.idle) +T.eq(state.steps, 0, "late VSync present receives no invented idle budget") +Performance.gcBudget = false +Budget.configure(Performance, gc) +Performance.gcBudget = true +T.finish() diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py index 952e314da..f9addab0a 100644 --- a/tools/check_frame_pacing.py +++ b/tools/check_frame_pacing.py @@ -15,6 +15,7 @@ def main(): parser.add_argument('--love', type=Path, required=True) parser.add_argument('--report', type=Path, required=True) parser.add_argument('--qa-tools', type=Path) + parser.add_argument('--gc', action='store_true', help='compare fixed-step GC with the P2 idle budget') args = parser.parse_args() root = Path(__file__).resolve().parents[1] sys.path.insert(0, str(args.qa_tools or root / 'tools')) @@ -30,17 +31,21 @@ def main(): qa_profile(Path.home() / 'Library/Application Support/LOVE' / identity) result = qa_run([str(args.love.resolve()), str(root / 'tools/frame-pacing-check')], cwd=root, env=dict(os.environ, POKEPORT_IDENTITY=identity, - FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1'), + FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1', + FRAME_PACING_GC='1' if args.gc else '0'), capture_output=True, text=True, timeout=90) args.report.with_suffix('.log').write_text(result.stdout + result.stderr) - records = [line.removeprefix('P1_NATIVE_RESULT ') for line in result.stdout.splitlines() - if line.startswith('P1_NATIVE_RESULT ')] + prefix = 'P2_NATIVE_RESULT ' if args.gc else 'P1_NATIVE_RESULT ' + records = [line.removeprefix(prefix) for line in result.stdout.splitlines() if line.startswith(prefix)] if result.returncode or len(records) != 1: raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) report = json.loads(records[0]) report['source'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip() files = ('main.lua', 'src/core/FrameCap.lua', 'src/core/FrameProfile.lua', 'tools/frame-pacing-check/main.lua', 'tools/frame-pacing-check/conf.lua') + if args.gc: + files += ('src/core/Performance.lua', 'src/core/GCFrameBudget.lua', 'src/core/Game.lua', + 'tools/frame-pacing-check/gc.lua') report['sha256'] = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} args.report.write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, indent=2)) diff --git a/tools/frame-pacing-check/gc.lua b/tools/frame-pacing-check/gc.lua new file mode 100644 index 000000000..80067fa1e --- /dev/null +++ b/tools/frame-pacing-check/gc.lua @@ -0,0 +1,124 @@ +local Cap = require("src.core.FrameCap") +local Performance = require("src.core.Performance") +local Budget = require("src.core.GCFrameBudget") +local Profile = require("src.core.FrameProfile") +local Json = require("src.link.Json") +local phase, frame, deadline, started, cpuStarted = 1, 0, 0, 0, 0 +local WINDOW, WARMUP = 120, 120 +local results, _trash = {}, nil +local witness = { key = "retained native data", value = 2712 } +local legacySteps, idleSteps, idleTotal, idleMax, heapPeak = 0, 0, 0, 0, 0 +local timer = { getTime = love.timer.getTime, sleep = love.timer.sleep } +local _, _, mode = love.window.getMode() +Cap.current = tonumber(mode.refreshrate) or 60 +if Cap.current <= 0 then + Cap.current = 60 +end +Cap.vsyncPacing = true +local originalPause = collectgarbage("setpause", 120) +collectgarbage("setpause", originalPause) +local originalMul = collectgarbage("setstepmul", 300) +collectgarbage("setstepmul", originalMul) + +local function resetStats() + legacySteps, idleSteps, idleTotal, idleMax, heapPeak = 0, 0, 0, 0, 0 +end +local function idle(clock, target) + local start = clock.getTime() + local steps = Budget.idle(clock, target) + if steps > 0 then + local duration = clock.getTime() - start + idleSteps, idleTotal = idleSteps + steps, idleTotal + duration + idleMax = math.max(idleMax, duration) + end +end +local function startPhase() + Profile.setEnabled(false) + Performance.gcBudget = phase == 2 + Budget.configure(Performance) + collectgarbage("collect") + frame = 0 + resetStats() + deadline = timer.getTime() +end +local function finishPhase() + assert(witness.key == "retained native data" and witness.value == 2712) + assert(_trash[512][2] == 512) + results[phase] = { + enabled = Performance.gcBudget, + frames = WINDOW, + seconds = timer.getTime() - started, + processCpuMsPerFrame = (os.clock() - cpuStarted) / WINDOW * 1000, + legacySteps = legacySteps, + idleSteps = idleSteps, + idleMeanMs = idleTotal / WINDOW * 1000, + idleMaxMs = idleMax * 1000, + heapPeakKiB = heapPeak, + } + if phase == 2 then + Performance.gcBudget = false + Budget.configure(Performance) + local pause = collectgarbage("setpause", originalPause) + local mul = collectgarbage("setstepmul", originalMul) + assert(pause == originalPause and mul == originalMul, "disable did not restore GC tuning") + print("P2_NATIVE_RESULT " .. Json.encode({ + os = love.system.getOS(), + arch = jit and jit.arch or "unknown", + renderer = love.graphics.getRendererInfo(), + refresh = mode.refreshrate, + vsync = love.window.getVSync(), + cap = Cap.current, + originalPause = originalPause, + originalStepMul = originalMul, + phases = results, + })) + return true + end + phase = 2 + startPhase() +end +function love.run() + startPhase() + return function() + love.event.pump() + for name in love.event.poll() do + if name == "quit" then + return 1 + end + end + if frame == WARMUP then + resetStats() + Profile.setEnabled(true) + started, cpuStarted = timer.getTime(), os.clock() + end + Budget.beginFrame(Performance) + local close = Profile.section("update: allocation workload") + local rows = {} + for index = 1, 512 do + rows[index] = { frame, index, a = index * 2, b = index * 3 } + end + _trash = rows + close() + if not Performance.gcBudget then + close = Profile.section(" update: gc step") + collectgarbage("step", 1) + legacySteps = legacySteps + 1 + close() + end + love.graphics.clear(0.03, 0.04, 0.06) + close = Profile.section("present (GPU wait / vsync)") + love.graphics.present() + close() + close = Profile.section("frame pacing: sleep") + deadline = Cap.pace(timer, love.window, true, deadline, idle) + close() + frame = frame + 1 + if frame > WARMUP then + heapPeak = math.max(heapPeak, collectgarbage("count")) + Profile.frame() + end + if frame == WARMUP + WINDOW and finishPhase() then + return 0 + end + end +end diff --git a/tools/frame-pacing-check/main.lua b/tools/frame-pacing-check/main.lua index e280a2d74..5bb9948d3 100644 --- a/tools/frame-pacing-check/main.lua +++ b/tools/frame-pacing-check/main.lua @@ -1,5 +1,9 @@ local root = assert(os.getenv("FRAME_PACING_REPO")) package.path = root .. "/?.lua;" .. root .. "/?/init.lua;" .. package.path +if os.getenv("FRAME_PACING_GC") == "1" then + require("tools.frame-pacing-check.gc") + return +end local Cap = require("src.core.FrameCap") local Profile = require("src.core.FrameProfile") local Json = require("src.link.Json") From 0956e2e1773739fb619475dc8f1d8578532bc8cd Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 02:32:56 +0100 Subject: [PATCH 04/19] Respect already-loaded native GC delegation without loading a provider --- src/core/Game.lua | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/Game.lua b/src/core/Game.lua index 9be08083e..8aa932b54 100644 --- a/src/core/Game.lua +++ b/src/core/Game.lua @@ -637,11 +637,14 @@ function Game:update(dt) pcall(function() require("src.core.DiscordPresence").update(dt) end) close() end + -- Keep an already-loaded native GC delegation at its update boundary. -- Ordinary engine collection moves to spare deadline time in love.run. - -- P2 disabled retains the original native update step. if collectgarbage then local close = FrameProfile.section(" update: gc step") - if not Performance.gcBudget then collectgarbage("step", 1) end + local facade = package.loaded["src.core.Game3"] + local handled = type(facade) == "table" and type(facade._stepGC) == "function" and facade._stepGC(self) + if handled then GCFrameBudget._facadeHandled() end + if not handled and not Performance.gcBudget then collectgarbage("step", 1) end close() end end From cb62f9404efd9bfbf34c92c5187d2357c0084cd2 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 02:42:49 +0100 Subject: [PATCH 05/19] Validate measured source fingerprints before and after native probes --- tools/check_frame_pacing.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py index f9addab0a..160706770 100644 --- a/tools/check_frame_pacing.py +++ b/tools/check_frame_pacing.py @@ -5,7 +5,6 @@ import json import os from pathlib import Path -import subprocess import sys import time @@ -25,6 +24,14 @@ def main(): parser.error('QA storage guard is required; provide --qa-tools') qa_source(root) qa_source(args.love.resolve()) + files = ('main.lua', 'src/core/FrameCap.lua', 'src/core/FrameProfile.lua', + 'tools/frame-pacing-check/main.lua', 'tools/frame-pacing-check/conf.lua') + if args.gc: + files += ('src/core/Performance.lua', 'src/core/GCFrameBudget.lua', 'src/core/Game.lua', + 'tools/frame-pacing-check/gc.lua') + hashes = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} + source = qa_run(['git', 'rev-parse', 'HEAD'], cwd=root, text=True, + capture_output=True, check=True).stdout.strip() qa_cache(args.report.parent) args.report.parent.mkdir(parents=True, exist_ok=True) identity = 'oasc-gen2recomp-qa-frame-pacing-' + str(time.time_ns()) @@ -40,13 +47,15 @@ def main(): if result.returncode or len(records) != 1: raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) report = json.loads(records[0]) - report['source'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip() - files = ('main.lua', 'src/core/FrameCap.lua', 'src/core/FrameProfile.lua', - 'tools/frame-pacing-check/main.lua', 'tools/frame-pacing-check/conf.lua') - if args.gc: - files += ('src/core/Performance.lua', 'src/core/GCFrameBudget.lua', 'src/core/Game.lua', - 'tools/frame-pacing-check/gc.lua') - report['sha256'] = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} + if any(hashlib.sha256((root / name).read_bytes()).hexdigest() != digest for name, digest in hashes.items()): + raise RuntimeError('Measured source changed during the pacing probe') + if qa_run(['git', 'rev-parse', 'HEAD'], cwd=root, text=True, + capture_output=True, check=True).stdout.strip() != source: + raise RuntimeError('Measured commit changed during the pacing probe') + report['source'] = source + report['sha256'] = hashes + report['minimumFreeGiB'] = 20 + report['playerProfilesUsed'] = False args.report.write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, indent=2)) From f0d4234a0c61f72fc1ec266626439563143b47ad Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 03:26:44 +0100 Subject: [PATCH 06/19] perf(P3): cache hot dependencies and retain private render scratch --- docs/hot-path-dispatch.md | 51 +++++++++++ src/core/Game.lua | 47 +++++++--- src/core/HotModules.lua | 34 ++++++++ src/core/Performance.lua | 2 + src/render/PaletteFX.lua | 3 +- src/render/Renderer.lua | 100 ++++++++++++++------- tests/engine/hot_modules.lua | 52 +++++++++++ tests/engine/hot_renderer_records.lua | 121 ++++++++++++++++++++++++++ tools/check_frame_pacing.py | 12 ++- tools/frame-pacing-check/hot.lua | 114 ++++++++++++++++++++++++ tools/frame-pacing-check/main.lua | 8 ++ 11 files changed, 494 insertions(+), 50 deletions(-) create mode 100644 docs/hot-path-dispatch.md create mode 100644 src/core/HotModules.lua create mode 100644 tests/engine/hot_modules.lua create mode 100644 tests/engine/hot_renderer_records.lua create mode 100644 tools/frame-pacing-check/hot.lua diff --git a/docs/hot-path-dispatch.md b/docs/hot-path-dispatch.md new file mode 100644 index 000000000..2905c39dd --- /dev/null +++ b/docs/hot-path-dispatch.md @@ -0,0 +1,51 @@ +# P3: native update/draw dependency dispatch + +`Performance.hotPathHoist` defaults to `true`. Set it to `false` to restore +per-call require/pcall dispatch, the per-frame blit closure and fresh native +presentation records independently of P1/P2. + +`HotModules` lazily retains successful module values. Live fields and explicit +replacement or clearing of `package.loaded` remain observable; failed optional +loads are not cached. The Discord update uses its existing protected call with +the original `dt`, without allocating a wrapper closure after initialization. +No module path, hook argument or hook ordering changes. + +The renderer's blit adapter carries DPI as explicit arguments and still calls +the public `blitCanvas` method. Its existing `uiPresentation` field becomes an +engine-owned live view. A table installed there by a consumer is never mutated +by the reuse path. + +Only the unwrapped native renderer may borrow the private viewport scratch. +Public `endFrame` calls always return detached records, and replacing that +method bypasses the private shortcut. HUD hook arguments are detached at the +moment of dispatch, including a hook registered during compose/output. The +fork's window UI also retains its public record path. Scratch is never included +in a hook record. + +Run `tools/check_frame_pacing.py --hot-path --love /path/to/love --report +/owned/qa/hot.json` through the QA storage guard. The owned synthetic state draws +a rectangle through real `Game:draw`, canvases and composition. Each switch +phase has 120 warm-up and 120 measured frames at 60 Hz, VSync 1, P1 enabled. +The log contains the actual F11 `draw: whole frame` section; raw JSON also records +total draw wall time, process CPU, source fingerprints and an untimed require +counter. This is not a complete overworld, battle or mod scene. Profiling is on +in both measured phases. + +Measured on macOS arm64 (milliseconds/frame, switch off → on): + +| Tree / backend | F11 draw (rounded) | Raw draw mean | Process CPU | require calls | +| --- | ---: | ---: | ---: | ---: | +| Fork / LÖVE 11.5 OpenGL | 0.16 → 0.21 | 0.166 → 0.218 | 0.787 → 0.919 | 15 → 6 | +| Fork / LÖVE 12 Metal | 16.36 → 16.38 | 16.373 → 16.383 | 1.134 → 1.026 | 15 → 6 | +| Public adaptation / LÖVE 11.5 OpenGL | 0.30 → 0.22 | 0.315 → 0.222 | 1.227 → 0.992 | 12 → 5 | +| Public adaptation / LÖVE 12 Metal | 16.43 → 16.40 | 16.440 → 16.410 | 0.849 → 1.003 | 12 → 5 | + +Queue submission can absorb GPU/VSync waiting in Metal; these are wall-time +sections, not isolated GPU durations. The short runs show reduced dependency +dispatch and known allocations, with mixed CPU/timing results. They do not +establish a general frame-rate or CPU improvement. Dedicated ARM handheld, +Android, long-session and full-game measurements: not measured. + +Regression checks cover cached dependency identity/replacement/retry, detached +public and late HUD records, method wrappers, DPI forwarding and private native +reuse. Existing output/hook tests and the compatibility acceptance are retained. diff --git a/src/core/Game.lua b/src/core/Game.lua index 8aa932b54..044c6546c 100644 --- a/src/core/Game.lua +++ b/src/core/Game.lua @@ -12,6 +12,7 @@ local StateStack = require("src.core.StateStack") local FrameProfile = require("src.core.FrameProfile") local Performance = require("src.core.Performance") local GCFrameBudget = require("src.core.GCFrameBudget") +local HotModules = require("src.core.HotModules") local TouchControls = require("src.core.TouchControls") local ModLoader = require("src.mods.Loader") local ModRuntime = require("src.mods.Runtime") @@ -588,7 +589,7 @@ function Game:updateCameraStick(dt) end function Game:update(dt) - require('src.pokemon.Gen4PoketchState').tick(self, dt) + HotModules.get('src.pokemon.Gen4PoketchState').tick(self, dt) local panel=self.secondScreenPointerOwner local top=self.stack and self.stack.top and self.stack:top() if panel and panel~=top and panel.updatePresentation then @@ -614,7 +615,7 @@ function Game:update(dt) local close = FrameProfile.section(" update: music") while self.audioAccum >= step do self.audioAccum = self.audioAccum - step - require("src.core.Music").update(Data) + HotModules.get("src.core.Music").update(Data) end close() end @@ -622,19 +623,24 @@ function Game:update(dt) -- frame dt (not the fixed logic step) for a smooth ~0.25s glide. do local close = FrameProfile.section(" update: tilt") - require("src.render.Tilt").update(dt) + HotModules.get("src.render.Tilt").update(dt) close() end -- mod render pipelines tween on the same real-frame clock, for the same -- reason: they are presentational, so fast-forward must not speed them up do local close = FrameProfile.section(" pipelines: update") - require("src.render.Pipelines").update(dt) + HotModules.get("src.render.Pipelines").update(dt) close() end do local close = FrameProfile.section(" update: discord") - pcall(function() require("src.core.DiscordPresence").update(dt) end) + if Performance.hotPathHoist then + local ok, Discord = HotModules.optional("src.core.DiscordPresence") + if ok and type(Discord) == "table" then pcall(Discord.update, dt) end + else + pcall(function() require("src.core.DiscordPresence").update(dt) end) + end close() end -- Keep an already-loaded native GC delegation at its update boundary. @@ -913,7 +919,7 @@ Game.centerClassicZones = centerClassicZones function Game:draw() local closeDraw = FrameProfile.section("draw: whole frame") - local screenLayout=require('src.ui.SecondScreen') + local screenLayout=HotModules.get('src.ui.SecondScreen') Renderer.splitViewport=nil if screenLayout.combined(self) then local w,h=love.graphics.getDimensions() @@ -931,25 +937,25 @@ function Game:draw() -- Single-screen generations use the physical Android lower panel as a live -- save companion without changing the game's own screen mode. do - local okC, Companion = pcall(require, "src.ui.SaveCompanion") + local okC, Companion = HotModules.optional("src.ui.SaveCompanion") if okC and Companion and Companion.tick then pcall(Companion.tick, self) end end do - local okSS, SS = pcall(require, "src.ui.SecondScreen") + local okSS, SS = HotModules.optional("src.ui.SecondScreen") if okSS and SS.mode and (SS.mode(self) == "display" or SS.combined(self)) and not self.secondScreenDrawnThisFrame then - local version = require("src.core.GameVersion").info() + local version = HotModules.get("src.core.GameVersion").info() local family = version and version.family -- THE WATCH ONLY ONCE IT IS ON THE WRIST: Platinum's lower screen shows -- the Pokétch after `enablepoketch` (Jubilife) and nothing before; Black -- and White's is the C-Gear, not Platinum's watch (not built yet), so -- theirs stays blank too - local poketchOn = require("src.pokemon.Gen4PoketchState").owned(self.save) + local poketchOn = HotModules.get("src.pokemon.Gen4PoketchState").owned(self.save) local panelModule = family == "hgss" and "src.ui.HgssFieldPanel" or (family ~= "bw" and poketchOn and "src.ui.Gen4Poketch") or nil local okP, Poketch = false, nil - if panelModule then okP, Poketch = pcall(require, panelModule) end + if panelModule then okP, Poketch = HotModules.optional(panelModule) end if not panelModule then pcall(SS.draw, self, function() love.graphics.setColor(0, 0, 0, 1) @@ -988,7 +994,7 @@ function Game:draw() -- has to get out, and because the GPU readback wants the drawing finished. -- A no-op in every other mode and on every machine with one screen. do - local okSS, SS = pcall(require, "src.ui.SecondScreen") + local okSS, SS = HotModules.optional("src.ui.SecondScreen") if okSS and SS.flush then pcall(SS.flush, self) end end FrameProfile.frame() @@ -1001,6 +1007,14 @@ function Game:toggleFrameProfile() return FrameProfile.toggle() end +local function viewportSnapshot(viewport) + return { + width=viewport.width,height=viewport.height,gameX=viewport.gameX,gameY=viewport.gameY, + gameWidth=viewport.gameWidth,gameHeight=viewport.gameHeight,scale=viewport.scale, + dpiX=viewport.dpiX,dpiY=viewport.dpiY, + } +end + function Game:_draw() -- the UI canvas clears transparent when the overworld's world pass -- shows through beneath it; opaque full-screen states get the classic @@ -1165,11 +1179,18 @@ function Game:_draw() if worldDrawn and self.overworld.sgbWorldZones then worldZones = self.overworld:sgbWorldZones() end - local viewport = Renderer:endFrame(zones, worldZones) + local viewport, privateViewport + if Performance.hotPathHoist and Renderer.endFrame == Renderer._nativeEndFrame then + viewport = Renderer:_endFrameForEngine(zones, worldZones) + privateViewport = true + else + viewport = Renderer:endFrame(zones, worldZones) + end -- Persistent tool status is screen-space UI: draw it over the completed -- render pipeline with exact playfield/margin geometry, but below mobile -- controls. It never becomes an updating game state. if ModRuntime.wantsHook("render.hud") then + if privateViewport then viewport = viewportSnapshot(viewport) end ModRuntime.call("render.hud", function() end, self, viewport) end -- on-screen mobile controls: pure screen-space, over the finished frame diff --git a/src/core/HotModules.lua b/src/core/HotModules.lua new file mode 100644 index 000000000..316773c7b --- /dev/null +++ b/src/core/HotModules.lua @@ -0,0 +1,34 @@ +-- Lazy dependency upvalues shared by native update/draw sites. Public require +-- paths stay intact; replacing/clearing package.loaded remains observable. +local Performance = require("src.core.Performance") +local Hot = {} +local _modules = {} + +function Hot.get(name) + if Performance.hotPathHoist then + local module = _modules[name] + if module and package.loaded[name] == module then + return module + end + module = require(name) + _modules[name] = module + return module + end + return require(name) +end + +function Hot.optional(name) + if Performance.hotPathHoist then + local module = _modules[name] + if module and package.loaded[name] == module then + return true, module + end + end + local ok, module = pcall(require, name) + if ok and Performance.hotPathHoist then + _modules[name] = module + end + return ok, module +end + +return Hot diff --git a/src/core/Performance.lua b/src/core/Performance.lua index 359ba0811..a7fcea886 100644 --- a/src/core/Performance.lua +++ b/src/core/Performance.lua @@ -45,6 +45,8 @@ local Performance = {} -- P2 is independently reversible. Tier rows can reduce the idle budget or -- tune the collector without changing the persisted presentation options. Performance.gcBudget = true +-- P3: cache hot-path dependencies and reuse engine-private presentation data. +Performance.hotPathHoist = true Performance.GC_PAUSE = 120 Performance.GC_STEP_MUL = 300 Performance.GC_BUDGET_SECONDS = 0.0005 diff --git a/src/render/PaletteFX.lua b/src/render/PaletteFX.lua index 88984d94b..731d74675 100644 --- a/src/render/PaletteFX.lua +++ b/src/render/PaletteFX.lua @@ -20,6 +20,7 @@ -- (data/palettes_yellow.lua / ROM cgbBase). local GameVersion = require("src.core.GameVersion") +local HotModules = require("src.core.HotModules") local PaletteFX = {} @@ -309,7 +310,7 @@ end -- it), so the zone now covers it whatever generation is running. On a Game -- Boy dataset those are 160x144 and this is the same rect it always was. function PaletteFX.whole(colors) - local ok, Renderer = pcall(require, "src.render.Renderer") + local ok, Renderer = HotModules.optional("src.render.Renderer") local w = ok and Renderer and (Renderer.uiWidth or Renderer.WIDTH) or 160 local h = ok and Renderer and (Renderer.uiHeight or Renderer.HEIGHT) or 144 -- zone() takes INCLUSIVE tile bounds, so the last tile index is size/8 - 1; diff --git a/src/render/Renderer.lua b/src/render/Renderer.lua index 7cff87285..d8aab0c30 100644 --- a/src/render/Renderer.lua +++ b/src/render/Renderer.lua @@ -12,6 +12,8 @@ local PaletteFX = require("src.render.PaletteFX") local Pipelines = require("src.render.Pipelines") local PixelCanvas = require("src.render.PixelCanvas") local Runtime = require("src.mods.Runtime") +local Performance = require("src.core.Performance") +local HotModules = require("src.core.HotModules") -- RESOLVED ONCE, NOT EVERY FRAME. These three were `require`d from inside -- beginFrame and endFrame -- three string hashes into package.loaded on every @@ -291,7 +293,7 @@ function Renderer:worldViewSize() -- Gen 1-3 render native border tiles beyond the map. Capping their view -- here and enlarging it during presentation silently changes the user's -- zoom on every building/route transition and makes small-map zoom inert. - if bw and bh and require("src.core.GameVersion").isGen4() then + if bw and bh and HotModules.get("src.core.GameVersion").isGen4() then local uw, uh = self:uiSize() -- Never below the screen the generation was drawn for, so a map at least -- that big comes out exactly the size it did before. @@ -312,7 +314,7 @@ end -- keep the projected ground plane covering the receded corners; filling with -- it would undo the growth it just asked for. function Renderer:worldPresentationScale(sp, pw, ph, vw, vh) - if self.worldBoundsW and require("src.core.GameVersion").isGen4() and not Tilt.active() then + if self.worldBoundsW and HotModules.get("src.core.GameVersion").isGen4() and not Tilt.active() then return math.max(sp, pw / vw, ph / vh) end return sp @@ -416,7 +418,7 @@ function Renderer:drawBattleWipe(wipe, ww, wh, ox, oy, vpw, vph, Sx, Sy, source) -- required here rather than at the top: BattleTransition reaches the -- renderer through game.renderer at draw time, and a module-level require -- would put the two files in a load cycle - local BattleTransition = require("src.render.BattleTransition") + local BattleTransition = HotModules.get("src.render.BattleTransition") local order = BattleTransition.gridOrder(wipe.style, cols, rows) if order then @@ -826,7 +828,34 @@ end -- scissored through the shade-remap shader, later zones on top. -- When GBC FX is active the composite is drawn into presentCanvas and -- presented through the GBC FX shader as a final pass. -function Renderer:endFrame(zones, worldZones) +-- Native blits keep the frame's DPI in explicit arguments, including nested +-- drawing. The public blitCanvas seam retains its original signature/dispatch. +function Renderer:_blitAtDpi(dpiX, dpiY, canvas, sx, sy, zoneList, zoneSx, zoneSy, + bx, by, boxX, boxY, boxW, boxH) + return self:blitCanvas(canvas, sx, sy, zoneList, zoneSx, zoneSy, + bx, by, boxX, boxY, boxW, boxH, dpiX, dpiY) +end + +local _viewportScratch = {} +local _uiPresentationOwners = setmetatable({}, {__mode="k"}) +local function viewportResult(private, ww, wh, ox, oy, vpw, vph, scale, dpiX, dpiY) + local out = private and _viewportScratch or {} + out.width, out.height, out.gameX, out.gameY = ww, wh, ox, oy + out.gameWidth, out.gameHeight, out.scale = vpw, vph, scale + out.dpiX, out.dpiY = dpiX, dpiY + return out +end +local function uiPresentation(self, x, y, w, h, sx, sy) + local out = _uiPresentationOwners[self] + if not Performance.hotPathHoist or not out or self.uiPresentation ~= out then + out = {} + _uiPresentationOwners[self] = out + end + out.x, out.y, out.w, out.h, out.scaleX, out.scaleY = x, y, w, h, sx, sy + self.uiPresentation = out +end + +local function endFrame(self, zones, worldZones, privateViewport) love.graphics.setCanvas() local ww, wh, pw, ph, dpiX, dpiY = displayMetrics() -- Sp = integer framebuffer pixels per GB pixel; @@ -855,7 +884,7 @@ function Renderer:endFrame(zones, worldZones) local uvpw, uvph = uiw * Ux, uih * Uy local uox = math.floor((pw - uiw * Up) / 2) / dpiX local uoy = math.floor((ph - uih * Up) / 2) / dpiY - self.uiPresentation = {x=uox,y=uoy,w=uvpw,h=uvph,scaleX=Ux,scaleY=Uy} + uiPresentation(self, uox, uoy, uvpw, uvph, Ux, Uy) local GBCFX = gbcFX() -- Forced mono/Classic modes still need a whole-screen zone when a state -- exposes no SGB packets (raw DMG canvas), so sendColors can remap. @@ -895,14 +924,14 @@ function Renderer:endFrame(zones, worldZones) -- took its Gen 1 branch, with Gen 1's tile geometry, over Gen 3 -- data. GameVersion.generation() is the same answer for Gen 1 and -- Gen 2 and the right one for Gen 3. - generation = require("src.core.GameVersion").generation(), + generation = HotModules.get("src.core.GameVersion").generation(), worldOverride = self.worldOverride, worldActive = self.worldActive and true or false, zones = zones, worldZones = worldZones, ww = ww, wh = wh, pw = pw, ph = ph, ox = ox, oy = oy, vpw = vpw, vph = vph, uiw = uiw, uih = uih, scale = Sp, Sx = Sx, Sy = Sy, dpiX = dpiX, dpiY = dpiY, - secondScreen = require("src.render.SecondScreen"), + secondScreen = HotModules.get("src.render.SecondScreen"), } if Runtime.call("render.compose", function() return false end, self, ctx) == true then self.worldActive = false @@ -910,10 +939,7 @@ function Renderer:endFrame(zones, worldZones) self.uiOverride = nil self.worldOverride = nil PaletteFX.setPass(nil) - return { - width = ww, height = wh, gameX = ox, gameY = oy, - gameWidth = vpw, gameHeight = vph, scale = Sp, dpiX = dpiX, dpiY = dpiY, - } + return viewportResult(privateViewport, ww, wh, ox, oy, vpw, vph, Sp, dpiX, dpiY) end end @@ -972,7 +998,7 @@ function Renderer:endFrame(zones, worldZones) -- a visibly brighter border. local clearR, clearG, clearB = 0, 0, 0 if not self.worldActive then - local ok, Game = pcall(require, "src.core.Game") + local ok, Game = HotModules.optional("src.core.Game") local stack = ok and Game and Game.stack local base = stack and stack.visibleBase and stack:visibleBase() local state = base and stack.states and stack.states[base] @@ -1015,10 +1041,13 @@ function Renderer:endFrame(zones, worldZones) -- see Renderer:blitCanvas; bound here to the frame's dpi so the composite -- call sites below stay unchanged. - local function blit(canvas, sx, sy, zoneList, zoneSx, zoneSy, - bx, by, boxX, boxY, boxW, boxH) - return self:blitCanvas(canvas, sx, sy, zoneList, zoneSx, zoneSy, - bx, by, boxX, boxY, boxW, boxH, dpiX, dpiY) + local blit = self._blitAtDpi + if not Performance.hotPathHoist then + blit = function(_self, _dx, _dy, canvas, sx, sy, zoneList, zoneSx, zoneSy, + bx, by, boxX, boxY, boxW, boxH) + return self:blitCanvas(canvas, sx, sy, zoneList, zoneSx, zoneSy, + bx, by, boxX, boxY, boxW, boxH, dpiX, dpiY) + end end -- A PUBLISHER MAY HAVE FREED ITS CANVAS SINCE IT HANDED IT OVER. @@ -1078,7 +1107,7 @@ function Renderer:endFrame(zones, worldZones) -- iOS flip a second time turns Platinum upside down while its UI remains -- upright. local loveMajor = love.getVersion() - local gen = require("src.core.GameVersion").generation() + local gen = HotModules.get("src.core.GameVersion").generation() if love.system and love.system.getOS and love.system.getOS() == "iOS" and loveMajor >= 12 @@ -1114,9 +1143,9 @@ function Renderer:endFrame(zones, worldZones) Tilt.active() and self:drawTiltedWorld(worldZones or zones, sx, sy, wox, woy, present) if not projected then if worldZones then - blit(self.worldCanvas, sx, sy, worldZones, sx, sy, wox, woy, 0, 0, ww, wh) + blit(self, dpiX, dpiY, self.worldCanvas, sx, sy, worldZones, sx, sy, wox, woy, 0, 0, ww, wh) else - blit(self.worldCanvas, sx, sy, zones, Sx, Sy, wox, woy, 0, 0, ww, wh) + blit(self, dpiX, dpiY, self.worldCanvas, sx, sy, zones, Sx, Sy, wox, woy, 0, 0, ww, wh) end -- OBP-baked overworld sprites replay on top of the zone pass (GBC -- mode per-object coloring; see PaletteFX.markSpriteRedraw). Grass @@ -1233,7 +1262,7 @@ function Renderer:endFrame(zones, worldZones) -- it wants the whole window rather than a fixed box in the middle of one. -- The bag, the party menu, the mart, the Pokenav, the title and the battle -- all say so; the overworld does not, so the map is still never bled. - local okGame, GameMod = pcall(require, "src.core.Game") + local okGame, GameMod = HotModules.optional("src.core.Game") local fills = okGame and GameMod and GameMod.fillScaleInStack(GameMod.stack) or false -- ...AND NOT A BATTLE. @@ -1274,12 +1303,12 @@ function Renderer:endFrame(zones, worldZones) and not GameMod.edgeBleedAllowedInStack(GameMod.stack) then fills = false end - if fills and require("src.core.GameVersion").isGen3() then + if fills and HotModules.get("src.core.GameVersion").isGen3() then self:bleedEdges(self.canvas, Ux, Uy, uox, uoy, ww, wh) end local uiSource=self.uiOverride or self.canvas local uiFactor=uiSource:getWidth()/uiw - blit(uiSource, Ux/uiFactor, Uy/uiFactor, zones, Ux, Uy, uox, uoy, uox, uoy, uvpw, uvph) + blit(self, dpiX, dpiY, uiSource, Ux/uiFactor, Uy/uiFactor, zones, Ux, Uy, uox, uoy, uox, uoy, uvpw, uvph) else local rest = { { uox, uoy, uvpw, uvph } } local placed = {} @@ -1301,7 +1330,7 @@ function Renderer:endFrame(zones, worldZones) -- desktop it IS the window: love.window.getSafeArea is absent or returns -- the full surface, so rect() answers 0, 0, ww, wh and every number below -- is what it has always been. Which is exactly why only mobile saw this. - local sax, say, saw, sah = require("src.core.SafeArea").rect() + local sax, say, saw, sah = HotModules.get("src.core.SafeArea").rect() if self.splitViewport then saw=math.max(0,math.min(saw,ww-sax));sah=math.max(0,math.min(sah,wh-say)) end @@ -1329,13 +1358,13 @@ function Renderer:endFrame(zones, worldZones) rest = subtractRect(rest, uox + a.x * Ux, uoy + a.y * Uy, dw, dh) end for _, r in ipairs(rest) do - blit(self.canvas, Ux, Uy, zones, Ux, Uy, uox, uoy, r[1], r[2], r[3], r[4]) + blit(self, dpiX, dpiY, self.canvas, Ux, Uy, zones, Ux, Uy, uox, uoy, r[1], r[2], r[3], r[4]) end for _, p in ipairs(placed) do -- shift the draw origin so canvas pixel (a.x, a.y) lands on (dx, dy). -- The zone scissors are computed from the same origin, so an SGB -- region travels with the element instead of staying in the letterbox. - blit(self.canvas, Ux, Uy, zones, Ux, Uy, + blit(self, dpiX, dpiY, self.canvas, Ux, Uy, zones, Ux, Uy, p.dx - p.a.x * Ux, p.dy - p.a.y * Uy, p.dx, p.dy, p.dw, p.dh) end end @@ -1345,7 +1374,7 @@ function Renderer:endFrame(zones, worldZones) -- origin and scale it used, so a queued rect covers exactly the pixels it -- replaces -- and UNDER the wipe and veil below, which are screen-wide -- effects that on hardware nothing escapes. - require("src.render.NativeOverlay").flush(uox, uoy, Ux, Uy) + HotModules.get("src.render.NativeOverlay").flush(uox, uoy, Ux, Uy) -- The battle wipe covers the whole surface, letterbox included, so it goes -- over the finished composite rather than under the UI blit. On hardware @@ -1416,13 +1445,18 @@ function Renderer:endFrame(zones, worldZones) self.uiOverride = nil self.worldOverride = nil PaletteFX.setPass(nil) - return { - width = ww, height = wh, - gameX = ox, gameY = oy, - gameWidth = vpw, gameHeight = vph, - scale = Sp, - dpiX = dpiX, dpiY = dpiY, - } + return viewportResult(privateViewport, ww, wh, ox, oy, vpw, vph, Sp, dpiX, dpiY) +end + +-- Public callers (including wrappers installed by mods) always receive a new +-- record. Only the unwrapped native path may borrow the private result. +function Renderer:endFrame(zones, worldZones) + return endFrame(self, zones, worldZones, false) end +Renderer._nativeEndFrame = Renderer.endFrame +function Renderer:_endFrameForEngine(zones, worldZones) + return endFrame(self, zones, worldZones, Performance.hotPathHoist) +end + return Renderer diff --git a/tests/engine/hot_modules.lua b/tests/engine/hot_modules.lua new file mode 100644 index 000000000..a234303cf --- /dev/null +++ b/tests/engine/hot_modules.lua @@ -0,0 +1,52 @@ +local T = require("tests.harness") +local Performance = require("src.core.Performance") +local Hot = require("src.core.HotModules") +local name = "tests.hot_module_probe" +local originalRequire = require +local calls, loads = 0, 0 +package.preload[name] = function() + loads = loads + 1 + return { generation = loads } +end +_G.require = function(path, ...) + calls = calls + 1 + return originalRequire(path, ...) +end +Performance.hotPathHoist = true +local first = Hot.get(name) +T.eq(loads, 1, "cold dependency is loaded once") +T.eq(Hot.get(name), first, "warm module retains identity") +T.eq(calls, 1, "warm path avoids require dispatch") +first.liveField = "changed" +T.eq(Hot.get(name).liveField, "changed", "module field mutations remain live") +local replacement = { generation = 20 } +package.loaded[name] = replacement +T.eq(Hot.get(name), replacement, "explicit package.loaded replacement is observed") +package.loaded[name] = nil +T.eq(Hot.get(name).generation, 2, "clearing package.loaded reloads the dependency") +Performance.hotPathHoist = false +local before = calls +Hot.get(name) +Hot.get(name) +T.eq(calls - before, 2, "P3 disabled restores normal require dispatch") +Performance.hotPathHoist = true +package.loaded[name] = nil +package.preload[name] = function() + error("deliberate optional load failure") +end +local ok = Hot.optional(name) +T.eq(ok, false, "optional dependency errors remain contained") +package.loaded[name] = nil +package.preload[name] = function() + return replacement +end +local value +ok, value = Hot.optional(name) +T.check(ok and value == replacement, "failed loads are not memoized as successful modules") +before = calls +ok, value = Hot.optional(name) +T.check(ok and value == replacement, "optional warm module retains its result") +T.eq(calls, before, "optional warm path avoids pcall/require dispatch") +_G.require = originalRequire +package.loaded[name], package.preload[name] = nil, nil +T.finish() diff --git a/tests/engine/hot_renderer_records.lua b/tests/engine/hot_renderer_records.lua new file mode 100644 index 000000000..4d4fd3eff --- /dev/null +++ b/tests/engine/hot_renderer_records.lua @@ -0,0 +1,121 @@ +local T = require("tests.harness") +love = require("tests.love_stub") +local Performance = require("src.core.Performance") +local Version = require("src.core.GameVersion") +Version.set("red") +local Renderer = require("src.render.Renderer") +local Game = require("src.core.Game") +local Runtime = require("src.mods.Runtime") +local Hooks = require("src.mods.Hooks") +local Stack = require("src.core.StateStack") +local w, h = 640, 480 +love.graphics.getDimensions = function() + return w, h +end +love.graphics.getPixelDimensions = function() + return w, h +end +Renderer:init() +local function present(private) + Renderer:beginFrame() + if private then + return Renderer:_endFrameForEngine() + end + return Renderer:endFrame() +end +for _, enabled in ipairs({ false, true }) do + Performance.hotPathHoist = enabled + w, h = 640, 480 + local first = present() + local oldUI = Renderer.uiPresentation + w, h = 800, 600 + local second = present() + T.check(first ~= second, "public endFrame returns detached records with P3 " .. tostring(enabled)) + T.eq(first.width, 640, "retained public viewport keeps its original width") + T.eq(second.width, 800, "next public viewport has current width") + T.eq(oldUI == Renderer.uiPresentation, enabled, "existing renderer-owned UI view follows the switch") +end +Performance.hotPathHoist = true +local first = present(true) +T.eq(present(true), first, "unobserved native result can reuse private storage") +local foreign = { custom = true } +Renderer.uiPresentation = foreign +present() +T.check(Renderer.uiPresentation ~= foreign, "engine does not reuse a replacement owned by a mod") +T.eq(foreign.x, nil, "replacement supplied by a mod is not mutated") +local realBlit = Renderer.blitCanvas +local forwarded +Renderer.blitCanvas = function(self, ...) + forwarded = { self, ... } + return "forwarded" +end +local canvas, zones = {}, {} +T.eq( + Renderer:_blitAtDpi(1.5, 2, canvas, 3, 4, zones, 5, 6, 7, 8, 9, 10, 11, 12), + "forwarded", + "hoisted blit preserves the public return" +) +T.eq(forwarded[1], Renderer, "hoisted blit preserves the public receiver") +T.eq(forwarded[2], canvas, "hoisted blit preserves canvas identity") +T.eq(forwarded[5], zones, "hoisted blit preserves zone identity") +T.eq(forwarded[14], 1.5, "hoisted blit keeps horizontal DPI in the original position") +T.eq(forwarded[15], 2, "hoisted blit keeps vertical DPI in the original position") +Renderer.blitCanvas = realBlit + +local hooks = Hooks.new() +Runtime.hooks = hooks +local state = { draw = function() end } +local stack = setmetatable({ states = { state } }, { __index = Stack }) +local fake = setmetatable( + { stack = stack, overworld = {}, data = require("tests.modkit.fixtures").fresh(), save = { options = {} } }, + { __index = Game } +) +local received = {} +hooks:wrap("render.hud", function(nextFn, game, viewport) + T.eq(game, fake, "HUD receives the original game") + received[#received + 1] = viewport + return nextFn(game, viewport) +end, 0, "retention") +w, h = 640, 480 +fake:_draw() +w, h = 800, 600 +fake:_draw() +T.check(received[1] ~= received[2], "HUD never receives recycled private results") +T.eq(received[1].width, 640, "retained HUD viewport remains unchanged") +T.eq(received[2].width, 800, "next HUD viewport receives current geometry") +local original = Renderer.endFrame +local wrapped, offered = 0, nil +Renderer.endFrame = function(self, ...) + wrapped = wrapped + 1 + offered = original(self, ...) + offered.modField = "kept" + return offered +end +fake:_draw() +T.eq(wrapped, 1, "existing public endFrame wrapper is not bypassed") +T.eq(received[#received], offered, "wrapper record is forwarded without replacing its identity") +T.eq(received[#received].modField, "kept", "wrapper-added fields remain available") +Renderer.endFrame = original +hooks:removeOwner("retention") +received = {} +local installed = false +hooks:wrap("render.compose", function(nextFn, ...) + if not installed then + installed = true + hooks:wrap("render.hud", function(nextHud, game, viewport) + received[#received + 1] = viewport + return nextHud(game, viewport) + end, 0, "late-hud") + end + return nextFn(...) +end, 0, "late-compose") +w, h = 640, 480 +fake:_draw() +w, h = 800, 600 +fake:_draw() +T.check(received[1] ~= received[2], "a HUD registered during compose also receives detached records") +T.eq(received[1].width, 640, "late registration does not leak mutable native metrics") +hooks:removeOwner("late-hud") +hooks:removeOwner("late-compose") +-- Window UI is absent from this engine base; the fork exercises that path. +T.finish() diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py index 160706770..2f8a694a6 100644 --- a/tools/check_frame_pacing.py +++ b/tools/check_frame_pacing.py @@ -14,7 +14,9 @@ def main(): parser.add_argument('--love', type=Path, required=True) parser.add_argument('--report', type=Path, required=True) parser.add_argument('--qa-tools', type=Path) - parser.add_argument('--gc', action='store_true', help='compare fixed-step GC with the P2 idle budget') + workload = parser.add_mutually_exclusive_group() + workload.add_argument('--gc', action='store_true', help='compare fixed-step GC with the P2 idle budget') + workload.add_argument('--hot-path', action='store_true', help='compare actual native update/draw dependency dispatch') args = parser.parse_args() root = Path(__file__).resolve().parents[1] sys.path.insert(0, str(args.qa_tools or root / 'tools')) @@ -29,6 +31,9 @@ def main(): if args.gc: files += ('src/core/Performance.lua', 'src/core/GCFrameBudget.lua', 'src/core/Game.lua', 'tools/frame-pacing-check/gc.lua') + if args.hot_path: + files += ('src/core/Game.lua', 'src/core/HotModules.lua', 'src/core/Performance.lua', + 'src/render/Renderer.lua', 'src/render/PaletteFX.lua', 'tools/frame-pacing-check/hot.lua') hashes = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} source = qa_run(['git', 'rev-parse', 'HEAD'], cwd=root, text=True, capture_output=True, check=True).stdout.strip() @@ -39,10 +44,11 @@ def main(): result = qa_run([str(args.love.resolve()), str(root / 'tools/frame-pacing-check')], cwd=root, env=dict(os.environ, POKEPORT_IDENTITY=identity, FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1', - FRAME_PACING_GC='1' if args.gc else '0'), + FRAME_PACING_GC='1' if args.gc else '0', + FRAME_PACING_HOT='1' if args.hot_path else '0'), capture_output=True, text=True, timeout=90) args.report.with_suffix('.log').write_text(result.stdout + result.stderr) - prefix = 'P2_NATIVE_RESULT ' if args.gc else 'P1_NATIVE_RESULT ' + prefix = 'P3_NATIVE_RESULT ' if args.hot_path else 'P2_NATIVE_RESULT ' if args.gc else 'P1_NATIVE_RESULT ' records = [line.removeprefix(prefix) for line in result.stdout.splitlines() if line.startswith(prefix)] if result.returncode or len(records) != 1: raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) diff --git a/tools/frame-pacing-check/hot.lua b/tools/frame-pacing-check/hot.lua new file mode 100644 index 000000000..8c8fdec9a --- /dev/null +++ b/tools/frame-pacing-check/hot.lua @@ -0,0 +1,114 @@ +local Version = require("src.core.GameVersion") +Version.set("red") +local Game = require("src.core.Game") +local Renderer = require("src.render.Renderer") +local Stack = require("src.core.StateStack") +local Performance = require("src.core.Performance") +local Cap = require("src.core.FrameCap") +local Profile = require("src.core.FrameProfile") +local Json = require("src.link.Json") +local graphics = love.graphics +Game.data = require("tests.modkit.fixtures").fresh() +Game.save = { version = "red", options = {}, player = {}, modData = {} } +Game.overworld = {} +Game.stack = setmetatable( + { + states = { + { + draw = function() + graphics.setColor(0.2, 0.4, 0.6, 1) + graphics.rectangle("fill", 16, 16, 96, 80) + graphics.setColor(1, 1, 1, 1) + end, + }, + }, + }, + { __index = Stack } +) +Renderer:init() +local phase, frame, deadline, started, cpuStarted = 1, 0, 0, 0, 0 +local WINDOW, WARMUP = 120, 120 +local drawTotal, drawMax, requireCalls, requires = 0, 0, 0, {} +local results = {} +local _, _, mode = love.window.getMode() +Cap.current = tonumber(mode.refreshrate) or 60 +if Cap.current <= 0 then + Cap.current = 60 +end +Cap.vsyncPacing = true + +local function countRequires() + local original = require + requireCalls, requires = 0, {} + _G.require = function(name, ...) + requireCalls = requireCalls + 1 + requires[name] = (requires[name] or 0) + 1 + return original(name, ...) + end + local ok, err = pcall(Game.draw, Game) + _G.require = original + assert(ok, err) +end +local function startPhase() + Profile.setEnabled(false) + Performance.hotPathHoist = phase == 2 + frame, drawTotal, drawMax = 0, 0, 0 + deadline = love.timer.getTime() +end +local function finishPhase() + results[phase] = { + enabled = Performance.hotPathHoist, + frames = WINDOW, + seconds = love.timer.getTime() - started, + drawMeanMs = drawTotal / WINDOW * 1000, + drawMaxMs = drawMax * 1000, + processCpuMsPerFrame = (os.clock() - cpuStarted) / WINDOW * 1000, + requireCalls = requireCalls, + requires = requires, + } + if phase == 2 then + print("P3_NATIVE_RESULT " .. Json.encode({ + os = love.system.getOS(), + arch = jit and jit.arch or "unknown", + renderer = graphics.getRendererInfo(), + refresh = mode.refreshrate, + vsync = love.window.getVSync(), + cap = Cap.current, + phases = results, + scope = "Native Game:draw and real canvas composition over owned synthetic content, no world/battle/mod scene", + })) + return true + end + phase = 2 + startPhase() +end +function love.run() + startPhase() + return function() + love.event.pump() + for name in love.event.poll() do + if name == "quit" then + return 1 + end + end + if frame == WARMUP then + countRequires() + Profile.setEnabled(true) + started, cpuStarted = love.timer.getTime(), os.clock() + end + local start = love.timer.getTime() + Game:draw() + if frame >= WARMUP then + local elapsed = love.timer.getTime() - start + drawTotal, drawMax = drawTotal + elapsed, math.max(drawMax, elapsed) + end + local close = Profile.section("present (GPU wait / vsync)") + graphics.present() + close() + deadline = Cap.pace(love.timer, love.window, true, deadline) + frame = frame + 1 + if frame == WARMUP + WINDOW and finishPhase() then + return 0 + end + end +end diff --git a/tools/frame-pacing-check/main.lua b/tools/frame-pacing-check/main.lua index 5bb9948d3..282369558 100644 --- a/tools/frame-pacing-check/main.lua +++ b/tools/frame-pacing-check/main.lua @@ -1,9 +1,17 @@ local root = assert(os.getenv("FRAME_PACING_REPO")) package.path = root .. "/?.lua;" .. root .. "/?/init.lua;" .. package.path +function love.errorhandler(message) + print(debug.traceback(tostring(message),2)) + return function()return 1 end +end if os.getenv("FRAME_PACING_GC") == "1" then require("tools.frame-pacing-check.gc") return end +if os.getenv("FRAME_PACING_HOT") == "1" then + require("tools.frame-pacing-check.hot") + return +end local Cap = require("src.core.FrameCap") local Profile = require("src.core.FrameProfile") local Json = require("src.link.Json") From 56a69480fe17068b4d625a024519d2c9d8419ae4 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 03:34:03 +0100 Subject: [PATCH 07/19] Cover current native draw imports and refresh upstream qualification --- docs/hot-path-dispatch.md | 4 ++-- src/core/Game.lua | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/hot-path-dispatch.md b/docs/hot-path-dispatch.md index 2905c39dd..d1632f35b 100644 --- a/docs/hot-path-dispatch.md +++ b/docs/hot-path-dispatch.md @@ -37,8 +37,8 @@ Measured on macOS arm64 (milliseconds/frame, switch off → on): | --- | ---: | ---: | ---: | ---: | | Fork / LÖVE 11.5 OpenGL | 0.16 → 0.21 | 0.166 → 0.218 | 0.787 → 0.919 | 15 → 6 | | Fork / LÖVE 12 Metal | 16.36 → 16.38 | 16.373 → 16.383 | 1.134 → 1.026 | 15 → 6 | -| Public adaptation / LÖVE 11.5 OpenGL | 0.30 → 0.22 | 0.315 → 0.222 | 1.227 → 0.992 | 12 → 5 | -| Public adaptation / LÖVE 12 Metal | 16.43 → 16.40 | 16.440 → 16.410 | 0.849 → 1.003 | 12 → 5 | +| Public adaptation on ed5189c2 / LÖVE 11.5 OpenGL | 0.21 → 0.21 | 0.223 → 0.215 | 0.952 → 0.936 | 14 → 5 | +| Public adaptation on ed5189c2 / LÖVE 12 Metal | 16.44 → 16.44 | 16.455 → 16.449 | 0.844 → 0.831 | 14 → 5 | Queue submission can absorb GPU/VSync waiting in Metal; these are wall-time sections, not isolated GPU durations. The short runs show reduced dependency diff --git a/src/core/Game.lua b/src/core/Game.lua index 769362451..33cfccb16 100644 --- a/src/core/Game.lua +++ b/src/core/Game.lua @@ -1127,8 +1127,8 @@ function Game:_draw() end end local baseState = self.stack.states[drawFrom] - local SuperSample = require("src.render.SuperSample") - if not worldDrawn and baseState and require("src.core.GameVersion").isNds() + local SuperSample = HotModules.get("src.render.SuperSample") + if not worldDrawn and baseState and HotModules.get("src.core.GameVersion").isNds() and SuperSample.singleScreen(self) and not SuperSample.active then SuperSample.draw(self, self.stack:top(), drawStates) else From 391dc765020b14678aca4f1302e82d8af8b6b359 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 03:51:23 +0100 Subject: [PATCH 08/19] perf(P4): hoist world draw bodies and reuse private cover lists --- docs/world-draw-hot-paths.md | 52 + src/core/Performance.lua | 2 + src/world/OverworldController.lua | 1665 +++++++++++++++------------- tests/engine/world_draw_hot.lua | 135 +++ tests/world_draw/fixture.lua | 118 ++ tools/check_frame_pacing.py | 11 +- tools/frame-pacing-check/main.lua | 4 + tools/frame-pacing-check/world.lua | 138 +++ 8 files changed, 1353 insertions(+), 772 deletions(-) create mode 100644 docs/world-draw-hot-paths.md create mode 100644 tests/engine/world_draw_hot.lua create mode 100644 tests/world_draw/fixture.lua create mode 100644 tools/frame-pacing-check/world.lua diff --git a/docs/world-draw-hot-paths.md b/docs/world-draw-hot-paths.md new file mode 100644 index 000000000..30a70b297 --- /dev/null +++ b/docs/world-draw-hot-paths.md @@ -0,0 +1,52 @@ +# P4: native world draw dispatch and private worklists + +`Performance.worldDrawHoist` defaults to `true`. Set it to `false` to disable +private list reuse and whole-loop protection and restore per-frame bound FX, +height/entity/focus adapters and individual protected entity draws. The switch +is independent of P1–P3. + +Native FX bodies, entity drawing, ground rise and canopy focus are methods with +explicit frame arguments. Ordinary flat draws use these methods directly. +Fresh no-argument bindings remain at public pipeline and billboard callback +seams: a retained FX callback must keep its own frame/camera. No record, method +signature, hook order or render pipeline field changes. + +Reflectors use a private counted instance list; removed entities are released. +Reflection cover cells use two private numeric columns and a reusable seen set. +Nested draws borrow separate work storage while the outer lease is busy. +An overridden public `rippleCells` still receives fresh pair tables in the old +shape. None of the new pools is included in a public callback record. + +The ordinary entity loop has one protected call. Its original sprite-depth +cleanup still runs before the original error is rethrown. The deferred above- +terrain pass retains its original ordering after the top layer. + +The guarded native host runs 64 synthetic rectangle actors through actual +`drawWorld`, reflection coverage, FX and native canvas composition. There is no +ROM, save/profile, extracted asset or mod scene. Each phase has 120 warm-up and +120 measured frames; VSync 1, 60 Hz, P1/P3 enabled. GC is stopped in each measured +window to expose allocation growth, then restarted. Heap growth includes all +host/profiler allocations and is not retained memory or a leak measurement. + +Observed macOS arm64, switch off → on: + +| Tree / backend | F11 world entities, ms/frame | F11 FX, ms/frame | Raw draw mean, ms | CPU, ms/frame | Heap growth / 120 frames, KiB | +| --- | ---: | ---: | ---: | ---: | ---: | +| Fork / LÖVE 11.5 OpenGL | 0.04 → 0.05 | 0.01 → 0.01 | 0.395 → 0.468 | 1.101 → 1.243 | 2758 → 1059 | +| Fork / LÖVE 12 Metal | 0.02 → 0.02 | 0.01 → 0.01 | 16.405 → 16.408 | 0.728 → 0.703 | 2748 → 1043 | +| Public adaptation / LÖVE 11.5 OpenGL | 0.03 → 0.02 | 0.01 → 0.01 | 0.270 → 0.241 | 0.911 → 0.801 | 2758 → 1059 | +| Public adaptation / LÖVE 12 Metal | 0.02 → 0.02 | 0.01 → 0.01 | 16.417 → 16.407 | 0.612 → 0.597 | 2749 → 1043 | + +Untimed protected calls fall from 55 to 1 in this scene (nine actors are deferred +to the above-terrain pass). Heap growth is about 61% lower. Short timing results +are mixed, and Metal can place GPU/VSync waiting in submission. No general FPS +or CPU improvement is established. Full game, Android, dedicated ARM handheld +and long session: not measured. + +Reproduce with `tools/check_frame_pacing.py --world-draw --love /path/to/love +--report /owned/qa/world.json`. The guarded runner retains raw F11 logs and +measured-source fingerprints. `tests/engine/world_draw_hot.lua` exercises four +editions, operation order/coordinates, batch-call count, private list reuse, +shrinking lists, public ripple records, reentrant covers, retained FX callbacks +and sprite-depth cleanup. A separate local comparison with the unchanged +pre-P4 controller also matched all draw traces in those four editions. diff --git a/src/core/Performance.lua b/src/core/Performance.lua index a7fcea886..c7bd61b1a 100644 --- a/src/core/Performance.lua +++ b/src/core/Performance.lua @@ -47,6 +47,8 @@ local Performance = {} Performance.gcBudget = true -- P3: cache hot-path dependencies and reuse engine-private presentation data. Performance.hotPathHoist = true +-- P4: independent world-draw closure, list and protection optimization. +Performance.worldDrawHoist = true Performance.GC_PAUSE = 120 Performance.GC_STEP_MUL = 300 Performance.GC_BUDGET_SECONDS = 0.0005 diff --git a/src/world/OverworldController.lua b/src/world/OverworldController.lua index 7e052d703..2f2b0787c 100644 --- a/src/world/OverworldController.lua +++ b/src/world/OverworldController.lua @@ -10,6 +10,7 @@ -- map scripts (data/scripts/), marts, nurses or extracted text. local FrameProfile = require("src.core.FrameProfile") +local Performance = require("src.core.Performance") local Assets = require("src.render.Assets") local Camera = require("src.render.Camera") local Collision = require("src.world.Collision") @@ -16855,6 +16856,820 @@ function OverworldState:poseBerryTrees() end end +-- Only public callback seams bind a frame; ordinary draws pass context explicitly. +local function bindWorldFx(fn, state, cam) + return function() return fn(state, cam) end +end + +-- the Pokémon Center heal machine (PokeCenterOAMData): the monitor +-- tile over the machine's screen and one ball per healed mon in two +-- mirrored columns, all blinking during the jingle flash. The GB +-- draws it at fixed screen coords with the player's cell BG-aligned +-- at (64,64); anchoring those coords to where the player stood keeps +-- the overlay on the machine at any zoom. +function OverworldState:_worldFxHeal(cam) + if not self.healAnim then return end + local ha = self.healAnim + -- HOENN'S MACHINE IS NOT AN OAM TABLE. + -- + -- Everything below this block is the Game Boy's: two 8x8 tiles out of + -- field.overworldFx.healMachine at coordinates a table in the ROM gives. + -- Emerald has no such table -- its machine is a field effect whose two + -- sprites are created by machine code, and where they go is four + -- immediates INSIDE that code. extractHealMachine reads them, and the + -- record it writes carries the positions already measured from the corner + -- of the player's own cell, so nothing here has to know where the + -- cartridge's camera puts anybody. + if GameVersion.isGen4() then return end + if self:drawGen3Heal(ha, cam) then return end + local fxDef = Game.data.field.overworldFx + if self.healMachineImg == nil and fxDef and fxDef.healMachine then + local ok, img = pcall(love.graphics.newImage, fxDef.healMachine.path) + self.healMachineImg = ok and img or false + end + local img = self.healMachineImg + if img then + if not self.healMachineQuads then + local w, h = img:getWidth(), img:getHeight() + self.healMachineQuads = { + love.graphics.newQuad(0, 0, 8, 8, w, h), -- monitor ($7c) + love.graphics.newQuad(0, 8, 8, 8, w, h), -- ball ($7d) + } + end + -- The machine carries its OWN four colours. HealMachineAnim.LoadPalettes + -- (04:$6434) copies them over OBJ palette 6 before the animation runs -- + -- which is why every row of its OAM table names palette 6 -- and they are + -- white / light orange / red / black: a Poke Ball. Nothing was applying + -- any palette at all, so the sheet drew in the DMG greys it is decoded + -- in and a Pokemon Center healed with grey balls. + local def = fxDef and fxDef.healMachine + local objPal = def and def.gen2ObjPal + local basePal = (objPal and objPal[1] and objPal) or PaletteFX.GRAYS + -- the jingle flash recolors the machine sprites in place + -- (FlashSprite8Times XORs rOBP1; the sprites never disappear): + -- ha.visible == false is the flashed half of each beat, drawn with + -- the light/dark shades swapped instead of skipped + local shader + if (not ha.visible) or basePal ~= PaletteFX.GRAYS then + shader = PaletteFX.shader() + if shader then + PaletteFX.sendColors(shader, ha.visible and basePal + or PaletteFX.permute(basePal, HEAL_FLASH_MAP)) + love.graphics.setShader(shader) + end + end + -- TileRenderer windows with -floor(cam), so the overlay must use the + -- same snap or a fractional camera (odd fill/tilt view sizes) parks + -- the balls a pixel off the machine tiles + local ox = ha.px - 64 - math.floor(cam.x) + local oy = ha.py - 64 - math.floor(cam.y) + -- Gen2 puts these sprites somewhere else entirely. Its + -- HealMachineAnim.PC_ElmsLab_OAM (04:$63BC) has the monitor at x 26/30 + -- and the balls at x 24/32; Gen1's PokeCenterOAMData has the balls at + -- 40/48. The extractor reads that OAM table straight off the cartridge + -- into field.overworldFx.healMachine, so use it where it exists and keep + -- the Gen1 constants as the fallback -- drawn at Gen1's offsets the + -- whole overlay sat a full 16px right of the Gen2 machine. + local monitor = (def and def.monitor) or { { 44, 20 } } + local balls = (def and def.balls) or HEAL_BALL_XY + love.graphics.setColor(1, 1, 1, 1) + for _, m in ipairs(monitor) do + love.graphics.draw(img, self.healMachineQuads[1], ox + m[1], oy + m[2]) + end + for i = 1, math.min(ha.lit, #balls) do + local b = balls[i] + if b[3] then -- right column: OAM_XFLIP + love.graphics.draw(img, self.healMachineQuads[2], + ox + b[1] + 8, oy + b[2], 0, -1, 1) + else + love.graphics.draw(img, self.healMachineQuads[2], + ox + b[1], oy + b[2]) + end + end + if shader then love.graphics.setShader() end + end +end + +-- the Cut/boulder dust puff: the smoke tile drawn 2x2 over the cell, +-- flickering (AnimateBoulderDust XORs the OBJ palette every step) +function OverworldState:_worldFxDust(cam) + if not self.dustAnim then return end + local fxDef = Game.data.field.overworldFx + local smoke = fxDef and fxDef.smoke + if smoke then + if self.smokeImg == nil then + local ok, img = pcall(love.graphics.newImage, smoke.path) + self.smokeImg = ok and img or false + end + if self.smokeImg then + local da = self.dustAnim + local dx = da.x * 16 - cam.x + local dy = da.y * 16 - cam.y + local flicker = math.floor(da.frames / 4) % 2 == 0 + love.graphics.setColor(1, 1, 1, flicker and 1 or 0.55) + for i = 0, 1 do + for j = 0, 1 do + love.graphics.draw(self.smokeImg, dx + i * 8, dy + j * 8) + end + end + love.graphics.setColor(1, 1, 1, 1) + end + end +end + +-- FireRed's S.S. Anne departure uses two ordinary OBJ sprites that are not +-- object events: a looping 16x32 wake behind the ship and 16x16 smoke puffs +-- from its funnel. Special 401 owns their exact lifetime/positions; this +-- pass only turns that state into the extracted ROM frames. +function OverworldState:_worldSsAnneArt(cam) + local def = Game.data.constants and Game.data.constants.gen3SSAnneFx + if not def then return nil end + if self.ssAnneWakeImg == nil then + local ok, img = pcall(Assets.image, def.wake) + self.ssAnneWakeImg = ok and img or false + end + if self.ssAnneSmokeImg == nil then + local ok, img = pcall(Assets.image, def.smoke) + self.ssAnneSmokeImg = ok and img or false + end + if self.ssAnneWakeImg and not self.ssAnneWakeQuads then + local w, h = self.ssAnneWakeImg:getDimensions() + self.ssAnneWakeQuads = { + love.graphics.newQuad(0, 0, 16, 32, w, h), + love.graphics.newQuad(16, 0, 16, 32, w, h), + } + end + if self.ssAnneSmokeImg and not self.ssAnneSmokeQuads then + local w, h = self.ssAnneSmokeImg:getDimensions() + self.ssAnneSmokeQuads = {} + for i = 0, 3 do + self.ssAnneSmokeQuads[i + 1] = love.graphics.newQuad(i * 16, 0, 16, 16, w, h) + end + end + return self.ssAnneWakeImg, self.ssAnneSmokeImg +end + +function OverworldState:_worldFxSSAnneWake(cam) + local fx = self.ssAnneDepartureFx + if not (fx and fx.boat) then return end + local wake = self:_worldSsAnneArt(cam) + if not (wake and self.ssAnneWakeQuads) then return end + local age = math.min(fx.wakeAge or 0, 132) + local cx = fx.boat.px + (fx.boat.shiftPx or 0) + 8 - cam.x + + 80 + math.floor(age / 6) + if cx < -18 then return end + local frame = math.floor(age / 12) % 2 + 1 + love.graphics.setColor(1, 1, 1, 1) + love.graphics.draw(wake, self.ssAnneWakeQuads[frame], + math.floor(cx - 8), 109 - 16) +end + +function OverworldState:_worldFxSSAnneSmoke(cam) + local fx = self.ssAnneDepartureFx + if not (fx and fx.smoke and #fx.smoke > 0) then return end + local _, smoke = self:_worldSsAnneArt(cam) + if not (smoke and self.ssAnneSmokeQuads) then return end + love.graphics.setColor(1, 1, 1, 1) + for _, puff in ipairs(fx.smoke) do + local age = puff.age or 0 + local frame + if age < 10 then frame = 1 + elseif age < 30 then frame = 2 + elseif age < 50 then frame = 3 + else frame = 4 end + local cx = puff.x + math.floor(age / 4) + love.graphics.draw(smoke, self.ssAnneSmokeQuads[frame], + math.floor(cx - 8), 78 - 8) + end +end + +-- the watering can's water: droplets arcing down onto the soil, and a +-- sparkle on the last few frames as it soaks in +function OverworldState:_worldFxWater(cam) + if not self.waterAnim then return end + local wa = self.waterAnim + local total = wa.total or 40 + local age = total - wa.frames + local dx = wa.x * 16 - cam.x + local dy = wa.y * 16 - cam.y + love.graphics.setColor(0.55, 0.80, 0.98, 0.95) + for i = 0, 5 do + -- each droplet falls on its own phase, so they read as a stream + local t = ((age * 3 + i * 7) % 24) / 24 + local px = dx + 2 + i * 2 + t * 10 + local py = dy - 6 + t * 20 + if py < dy + 16 then + love.graphics.rectangle("fill", px, py, 2, 3) + end + end + -- the soak: a brief bright ring once the water has been falling a while + if age > total * 0.55 then + local k = (age - total * 0.55) / (total * 0.45) + love.graphics.setColor(1, 1, 1, 0.8 * (1 - k)) + love.graphics.rectangle("fill", dx + 2, dy + 12, 12, 2) + end + love.graphics.setColor(1, 1, 1, 1) +end + +-- the cut tree splitting apart (AnimCut): top half slides right, +-- bottom half slides left, 1px per frame, flickering as they go +function OverworldState:_worldFxCutTree(cam) + if not self.cutAnim then return end + local fxDef = Game.data.field.overworldFx + local tree = fxDef and fxDef.cutTree + if not tree then return end + if self.cutTreeImg == nil then + local ok, img = pcall(love.graphics.newImage, tree.path) + self.cutTreeImg = ok and img or false + end + local img = self.cutTreeImg + if not img then return end + if not self.cutTreeQuads then + local w, h = img:getWidth(), img:getHeight() + self.cutTreeQuads = { + love.graphics.newQuad(0, 0, 16, 8, w, h), -- top half + love.graphics.newQuad(0, 8, 16, 8, w, h), -- bottom half + } + end + local ca = self.cutAnim + local off = (ca.total or 8) - ca.frames + local dx = ca.x * 16 - cam.x + local dy = ca.y * 16 - cam.y + local flicker = ca.frames % 2 == 0 + love.graphics.setColor(1, 1, 1, flicker and 1 or 0.55) + love.graphics.draw(img, self.cutTreeQuads[1], dx + off, dy) + love.graphics.draw(img, self.cutTreeQuads[2], dx - off, dy + 8) + love.graphics.setColor(1, 1, 1, 1) +end + +-- the "!" bubble above a trainer who spotted the player +-- the tile-anchored sparkle: an OAM sprite in the cartridge, so it rides +-- the camera the way a body does rather than the background's shake +function OverworldState:_worldFxSparkle(cam) + love.graphics.setColor(1, 1, 1, 1) + self:drawSparkles(cam.x, cam.y) +end + +-- ...and ONE of them, for the two paths that cannot draw the set in screen +-- space: each sparkle sits on its own cell, so a projected scene has to +-- anchor each one separately. The upvalue is set immediately before each +-- call and cleared after, which is the same shape the emote path uses for +-- the one NPC it belongs to. +function OverworldState:_worldFxSparkleOne(cam, item) + local s = item + if not s then return end + local sprite = self:sparkleSprite() + if not sprite then return end + local frame = self:sparkleFrame(s.clock) + if not frame then return end + love.graphics.setColor(1, 1, 1, 1) + sprite:drawFixedFrame(s.px, s.py + 4, cam.x, cam.y, frame) +end + +-- THE POKE RADAR'S PATCHES, one at a time like the sparkles +function OverworldState:_worldFxRadarOne(cam, item) + local pt = item + if not pt then return end + require("src.world.Gen4Radar").drawPatch(pt, pt.x * 16 - cam.x, pt.y * 16 - cam.y, + love.timer and love.timer.getTime() * 60 or 0) +end + +function OverworldState:_worldFxRadar(cam) + for _, pt in ipairs((self.gen4Radar and self.gen4Radar.active and self.gen4Radar.patches) or {}) do + if pt.active then self:_worldFxRadarOne(cam, pt) end + end + radarOne = nil +end + +function OverworldState:_worldFxEmote(cam) + if not (self.emote and self.emote.npc) then return end + -- bubble = false is a silent hold (a Pikachu emotion that plays a + -- cry with no bubble still pauses the world for its beat) + if self.emote.bubble == false then return end + local npc = self.emote.npc + -- SINNOH'S OWN BUBBLE, ON TOP OF THE HEAD, IN THE GROUND'S PROJECTION. + -- + -- Reported from play: *"were missing the proper exclamation point above + -- trainers when they see you for battle and its not above their heads"*. + -- Platinum had neither art source below, so it fell to the hand-drawn box, + -- placed with flat 2D arithmetic that knows nothing of terrain height or + -- the tilt -- so it landed across the face. + -- + -- The cartridge (src/overlay005/ov5_021F5A10.c, see Gen4Emotes): a 16x16 + -- billboard from fldeff.narc whose plane rises 0..16 from an anchor 32 + -- units above the owner's drawn position -- the top of a 32-unit + -- character -- bouncing 6, 10, 12, 12, 10, 6, 0 and then holding. So the + -- bubble's bottom edge sits on the sprite's top edge, centred on it, and + -- it is drawn through exactly the transform the sprite is: the same + -- terrain rise, and `freeEntity` when a 3D camera owns the frame. + local g4emotes = Game.data and Game.data.gen4_emotes + local g4ground = self.map and self.map.renderer and self.map.renderer.gen4Ground + if g4emotes and g4ground and npc.sprite then + local Gen4Emotes = require("src.import.Gen4Emotes") + local kind = (self.emote.bubble == "double" or self.emote.bubble == 2) + and g4emotes.double and "double" or "exclamation" + -- BW's "?", note and "..." by name (Gen5MoveExec), when the cache has them + local named = self.emote.bubble + if type(named) == "string" and named ~= "double" and type(g4emotes[named]) == "table" then + kind = named + end + local record = g4emotes[kind] + self.gen4EmoteImages = self.gen4EmoteImages or {} + local img = self.gen4EmoteImages[kind] + if img == nil and record and record.rgba then + local okI, made = pcall(function() + local data = love.image.newImageData(record.width, record.height, + "rgba8", record.rgba) + local image = love.graphics.newImage(data) + image:setFilter("nearest", "nearest") + return image + end) + img = okI and made or false + self.gen4EmoteImages[kind] = img + end + if img then + local age = math.max(0, (self.emote.totalFrames or Gen4Emotes.FRAMES) + - (self.emote.frames or 0)) + -- HEARTGOLD / SOULSILVER: the cartridge's own anchor, 32 world units + -- over the owner through the camera now drawing, the player + -- included (src/world/Gen4EmoteDraw.lua); Platinum below, unchanged + local EmoteDraw = require("src.world.Gen4EmoteDraw") + if EmoteDraw.applies(self.map) then + EmoteDraw.draw(self, g4ground, npc, cam, record, img, age) + return + end + local bx, by, rise = OverworldState.gen4EmoteSpot(g4ground, npc, cam, + record, age) + local function draw() + love.graphics.setColor(1, 1, 1, 1) + love.graphics.draw(img, bx, by) + end + local free = g4ground.freeMode and g4ground:freeMode() + if free then + -- Depth-tested where the cartridge's billboard actually is -- the + -- middle of a bubble 32 units up -- not at its trainer's feet. + g4ground:freeEntity(npc.px or 0, npc.py or 0, cam.x, cam.y, rise, draw, + Gen4Emotes.LIFT + 8) + else + draw() + end + return + end + end + -- WHERE IT HANGS, which the cartridge states outright. + -- + -- Reported from play: the bubble "should appear above the trainers head". + -- It was four pixels right of them and six low, which on a 16x32 walker + -- put it across the face rather than over it. + -- + -- The icon's own sprite callback (0B4724) copies the owner's position + -- every frame and offsets it by exactly one thing: + -- + -- icon->x = owner->x + -- icon->y = owner->y - 16 + -- + -- and a GBA sprite's x/y is its CENTRE (the corner comes from + -- centerToCornerVec), so this is "the icon's centre sits sixteen pixels + -- above the owner's" -- which is a different top-left offset for a 16x16 + -- object than for a 16x32 one, and is why one number could never be right + -- for both. Stated as centres it falls out the same for either: the x + -- offsets cancel whatever the sprite's width, and the y is the owner's + -- half-height less the icon's eight plus the sixteen. + local half = math.floor(((npc.sprite and npc.sprite.tileH) or 16) / 2) + local ex = npc.px - cam.x + local ey = npc.py - cam.y - 12 - half + local bubble = Game.data.field.emotionBubbles + local drawn = false + + -- HOENN'S OWN BUBBLE, which is not on the Game Boy's sheet. + -- + -- The "!" over a trainer's head is three 16x16 icons hanging off a sprite + -- template that only a field-effect script reaches (see extractEmotes) -- + -- which is why every sweep of the field-effect tables missed it. A Gen 3 + -- dataset that has them draws them; one that does not falls through to + -- the Game Boy sheet and then to the box below, exactly as before. + local icons = (Game.data.constants or {}).gen3Emotes + if icons then + local role = GEN3_EMOTE_ROLES[self.emote.bubble or 1] or "exclamation" + local record = icons[role] + local path = record and record.image + if path then + self.gen3EmoteImages = self.gen3EmoteImages or {} + local held = self.gen3EmoteImages[path] + if held == nil then + local okImg, img = pcall(require("src.render.Assets").image, path) + held = (okImg and img) or false + self.gen3EmoteImages[path] = held + end + if held then + local age = math.max(0, (self.emote.totalFrames or 60) + - self.emote.frames) + local frame = 0 + local left = age + for _, step in ipairs(record.timeline or {}) do + local duration = tonumber(step[2]) or 1 + if left < duration then + frame = tonumber(step[1]) or 0 + break + end + left = left - duration + frame = tonumber(step[1]) or frame + end + -- SpriteCB_TrainerIcons starts data[3] at -5, accumulates it into + -- data[4], and increments that velocity until the offset returns 0. + local bounce, velocity = 0, -5 + for _ = 1, math.min(age + 1, 11) do + bounce = bounce + velocity + if bounce ~= 0 then velocity = velocity + 1 else velocity = 0 end + end + local fw, fh = tonumber(record.width) or 16, tonumber(record.height) or 16 + local iw, ih = held:getDimensions() + local q = nil + if (tonumber(record.frames) or 1) > 1 then + self.gen3EmoteQuads = self.gen3EmoteQuads or {} + local key = path .. ":" .. tostring(frame) + q = self.gen3EmoteQuads[key] + if not q then + q = love.graphics.newQuad(frame * fw, 0, fw, fh, iw, ih) + self.gen3EmoteQuads[key] = q + end + end + love.graphics.setColor(1, 1, 1, 1) + if q then love.graphics.draw(held, q, ex, ey + bounce) + else love.graphics.draw(held, ex, ey + bounce) end + drawn = true + end + end + end + if not drawn and bubble and bubble.path then + local ok, img = pcall(function() + self.emoteImg = self.emoteImg or obpEmoteImage(bubble.path) + return self.emoteImg + end) + -- EXCLAMATION_BUBBLE is index 0 -> first crop; the emote command + -- picks question/happy crops instead + local bi = self.emote.bubble or 1 + local rect = bubble.bubbles and bubble.bubbles[bi] + if ok and img and rect then + love.graphics.setColor(1, 1, 1, 1) + -- one Quad per bubble crop, cached: this draws every frame the "!" + -- (or the emote-command crops) is up, so a fresh Quad here churned + -- the GC. The bubble set is small and fixed, so the cache is bounded. + self.emoteQuads = self.emoteQuads or {} + local q = self.emoteQuads[bi] + if not q then + q = love.graphics.newQuad(rect.x, rect.y, rect.w, rect.h, + img:getDimensions()) + self.emoteQuads[bi] = q + end + love.graphics.draw(img, q, ex, ey) + drawn = true + end + end + if not drawn then + local Font = require("src.render.Font") + love.graphics.setColor(1, 1, 1, 1) + love.graphics.rectangle("fill", ex, ey, 10, 12) + love.graphics.setColor(0, 0, 0, 1) + love.graphics.rectangle("line", ex + 0.5, ey + 0.5, 10, 12) + Font.draw("!", ex + 1, ey + 2) + love.graphics.setColor(1, 1, 1, 1) + end +end + +-- the FLY bird sweeping off with the player +function OverworldState:_worldFxBird(cam) + if not self.flyAnim then return end + -- FireRed has a dedicated five-frame 64x64 field-effect bird. Frames 1 + -- and 3 already contain Red/Leaf riding it during fly-out, so use the + -- cartridge sheet directly instead of substituting the selected mon's + -- battle front sprite. + local frlg = Game.data.constants and Game.data.constants.gen3FRLGFlyBird + if frlg and frlg.path then + if self.flyBirdImg == nil then + local ok, img = pcall(love.graphics.newImage, frlg.path) + self.flyBirdImg = ok and img or false + end + if self.flyBirdImg then + local gender = ((Game.save or {}).player or {}).gender == "girl" + and "girl" or "boy" + local frame = ((frlg.flyOut or {})[gender]) or (gender == "girl" and 3 or 1) + local fw = frlg.frameWidth or 64 + local fh = frlg.frameHeight or 64 + self.flyBirdQuads = self.flyBirdQuads or {} + if not self.flyBirdQuads[frame] then + local iw, ih = self.flyBirdImg:getDimensions() + self.flyBirdQuads[frame] = love.graphics.newQuad( + 0, frame * fh, fw, fh, iw, ih) + end + local t = math.max(0, math.min(48, 48 - self.flyAnim.frames)) + local reach = 16 + local dx, dy + if t <= reach then + local k = 1 - t / reach + dx, dy = -96 * k, -72 * k + else + local k = (t - reach) / (48 - reach) + dx, dy = -120 * k * k, -96 * k * k + end + local px = math.floor(self.player.px - cam.x + 8 - fw / 2 + dx) + local py = math.floor(self.player.py - cam.y + 8 - fh / 2 + dy) + love.graphics.setColor(1, 1, 1, 1) + love.graphics.draw(self.flyBirdImg, self.flyBirdQuads[frame], px, py) + require("src.render.PaletteFX").markTrueColor(px, py, fw, fh) + return + end + end + local birdId = FieldDefaults.fieldValue(Game.data, "playerSprites", "fly") + if not self.birdSprite and birdId and Game.data.sprites[birdId] then + local SR = require("src.render.SpriteRenderer") + self.birdSprite = SR.new(Game.data.sprites[birdId]) + end + if self.birdSprite then + local t = 48 - self.flyAnim.frames + local bx = self.player.px - t * 4 + local by = self.player.py - math.floor(t * 1.5) + love.graphics.setColor(1, 1, 1, 1) + self.birdSprite:draw(bx, by, cam.x, cam.y, "left", + math.floor(t / 4) % 2, false) + return + end + + -- Legacy fallback for datasets that predate the ROM-extracted FireRed + -- bird above. Keep it for old caches/other games, but current FireRed + -- imports should never reach this branch. + -- + -- Reported from play, twice: "ensure the animation of the flying type + -- pokemon swooping up my player plays after the fly hm transition" and + -- then "Theres still no fly swoop". The machinery above has been here the + -- whole time and has never had a sprite to draw: it wants + -- playerSprites.fly, and no Gen 3 cache carries one. + -- + -- IT WAS LOOKED FOR PROPERLY THIS TIME, and it is not where a sheet like + -- that would be. Emerald's fly bird is not an object-event graphics row + -- -- the three 64x64 rows in that table are Rayquaza twice and the cable + -- car, and every 32x32 row is a person or a legendary -- and it is not + -- hanging off any field-effect script either: not one of the sixty-seven + -- scripts loads tiles, and no native any of them calls reaches a sprite + -- template with frames that size. It is loaded by C, from a sheet only + -- the fly task names, and nothing the import can currently follow gets to + -- it. + -- + -- So the departure is drawn with something this port certainly does have + -- and the cartridge's own bird is not: the FRONT SPRITE OF THE POKEMON + -- THAT IS ACTUALLY CARRYING YOU -- the same one the field-move sweep just + -- showed. It stoops in from the upper left, meets the player, and lifts + -- away with them. Reconstructed, and said so; the moment the bird IS + -- found, playerSprites.fly makes the branch above win again and this is + -- never reached. + local mon = self.flyAnim.mon + if not mon then return end + if self.flyMonImg == nil then + local okPath, path = pcall(function() + return require("src.pokemon.Sprites").path( + Game.data, mon.species, "front", { mon = mon }) + end) + local img + if okPath and type(path) == "string" then + local okImg, loaded = pcall(love.graphics.newImage, path) + img = okImg and loaded or nil + end + self.flyMonImg = img or false + end + if not self.flyMonImg then return end + local total = 48 + local t = math.max(0, math.min(total, total - self.flyAnim.frames)) + -- the stoop: in over sixteen frames, away over the rest, and the two + -- meet on the player rather than anywhere else + local reach = 16 + local dx, dy + if t <= reach then + local k = 1 - t / reach + dx, dy = -96 * k, -72 * k + else + local k = (t - reach) / (total - reach) + dx, dy = -120 * k * k, -96 * k * k + end + local iw, ih = self.flyMonImg:getDimensions() + local px = math.floor(self.player.px - cam.x + 8 - iw / 2 + dx) + local py = math.floor(self.player.py - cam.y + 8 - ih / 2 + dy) + love.graphics.setColor(1, 1, 1, 1) + love.graphics.draw(self.flyMonImg, px, py) + require("src.render.PaletteFX").markTrueColor(px, py, iw, ih) +end + +-- fishing pose: the rod tile over the faced water (gfx/fishing.asm) +function OverworldState:_worldFxRod(cam) + if not self.fishing then return end + local fx = Game.data.field.overworldFx + local rod = fx and fx.fishingRod + if rod then + if self.rodImg == nil then + local ok, img = pcall(love.graphics.newImage, rod.path) + self.rodImg = ok and img or false + end + if self.rodImg then + local p = self.player + local oam = ROD_OAM[self.fishing.facing] or ROD_OAM.down + if not self.rodQuads then + -- one quad per 8x8 tile of the stacked sheet (ROD_OAM.tile) + local iw, ih = self.rodImg:getDimensions() + self.rodQuads = {} + for i = 0, math.floor(ih / 8) - 1 do + self.rodQuads[i] = love.graphics.newQuad(0, i * 8, 8, 8, iw, ih) + end + end + local quad = self.rodQuads[oam.tile] + -- the sprite's top-left is 4px above its cell (SpriteRenderer:draw) + local rx = p.px - cam.x + oam.dx + local ry = p.py - cam.y - 4 + oam.dy + love.graphics.setColor(1, 1, 1, 1) + if quad and oam.flip then + love.graphics.draw(self.rodImg, quad, rx + 8, ry, 0, -1, 1) + elseif quad then + love.graphics.draw(self.rodImg, quad, rx, ry) + end + end + end +end + +function OverworldState:_worldRise(e, groundForRise, groundSin, cam) + if not groundForRise then return 0 end + local rise = groundForRise:rise(e.px + (e.shiftPx or 0) + 8, e.py + 8) + -- A SPRITE OFFSET (MapObject_SetSpritePosOffset: the surf mount's ride, + -- the Distortion World cast's flights) in the field view: up by the + -- camera's height lean, toward it by the ground's + local so = e.spriteOffset + if so and (so.lift or so.oz) then + rise = rise + (so.lift or 0) * (groundForRise.heightScale or 0) + - (so.oz or 0) * (groundForRise.groundScale or 1) + end + if groundSin >= 1 then return rise end + return (e.py - cam.y) * (1 - groundSin) + rise +end + +function OverworldState:_worldDrawEntity(e, cam, bgY, freeGround, groundForRise, groundSin, grassColors, spriteDepthGround, shadows, riseOf) + if not (self.flyAnim and self:hasFlyBird() and e == self.player) + and not e.hidden and not e.berryVisualEmpty and not plotIsEmpty(e) then + -- A FREE CAMERA PLACES ITS OWN CHARACTERS. + -- + -- Reported from play: *"isnt keeping the player the right size"*, with a + -- screenshot of a third-person Twinleaf in correct perspective and two + -- characters standing in it at flat 2D scale. They were drawn by the + -- line below, which places every sprite at `py - camY` -- the field + -- camera's 1:1 mapping, and simply not this camera's. + -- + -- `freeEntity` runs THIS SAME DRAW inside a transform, so nothing here + -- learns about projection and the entity keeps owning its own sprite, + -- frame and palette. + -- + -- In FIRST person the player is the eye, so drawing them puts their own + -- back across the middle of the view. + if freeGround then + if not (freeGround:freeMode() == "first" and e == self.player) then + local rise = riseOf(self, e, groundForRise, groundSin, cam) + -- ...AND WHICH WAY THEY FACE ON SCREEN. + -- + -- Reported from play: *"when i orbit the camera 180 degrees if i + -- walk left it looks like hes walking right"*. `screenToWorld` + -- turns the PRESS into a world direction, so the step is right; + -- the sprite then showed that world facing under a camera that is + -- no longer looking north, so the artwork was the one thing still + -- in the old frame. `worldToScreen` is its inverse, and the pair + -- are inverses because the camera sits between them. + -- + -- Set and restored around the draw rather than threaded through, + -- because `facing` is what every pose, animation and follower path + -- in the entity reads, and none of them should learn about cameras. + local view, saved = freeGround.view3d, e.facing + if view and view.worldToScreen then + e.facing = view:worldToScreen(saved) + end + freeGround:freeEntity((e.px or 0), (e.py or 0), cam.x, cam.y, rise, + function() e:draw(cam.x, cam.y + rise) end, + nil, require("src.world.Gen4SurfMount").poseFor(e, e == self.player and self.dwPose or nil)) + e.facing = saved + end + -- Deliberately without the flat shadow and the grass overdraw below: + -- both are drawn in screen space against a ground plane this camera + -- does not have, and a shadow in the wrong place is worse than none. + return + end + -- IN THE WORLD'S DEPTH on Sinnoh's cartridge camera + -- (Gen4Ground:beginSprites): the billboard origin's depth, so a prop in + -- front of a character hides them; nil leaves the draw as it was + local depth = spriteDepthGround and spriteDepthGround:billboardDepth( + (e.px or 0) + (e.shiftPx or 0), e.py or 0, + e.spriteOffset and e.spriteOffset.lift, e.spriteOffset and e.spriteOffset.oz) + -- UNDER the sprite, and lifted by the same terrain rise it is, so a + -- character on a slope keeps their feet on it. + if shadows then + if depth then + spriteDepthGround:withSpriteDepth(depth, function() + shadows:draw(self.map, e, cam.x, cam.y, e == self.player, riseOf(self, e, groundForRise, groundSin, cam)) + end, false) + else + shadows:draw(self.map, e, cam.x, cam.y, e == self.player, riseOf(self, e, groundForRise, groundSin, cam)) + end + end + if depth then + spriteDepthGround:withSpriteDepth(depth, function() e:draw(cam.x, cam.y + riseOf(self, e, groundForRise, groundSin, cam)) end) + else + e:draw(cam.x, cam.y + riseOf(self, e, groundForRise, groundSin, cam)) + end + -- tall grass overdraws the sprite's feet (GB sprite priority); + -- the overdraw is BG tiles, so it rides the shake offset too + love.graphics.setColor(1, 1, 1, 1) + if self.map:isGrassCell(e.cellX, e.cellY) then + if not self:drawGen3Grass(e.cellX, e.cellY, cam.x, bgY, + self:gen3GrassFrame(e, false)) then + self.map.renderer:drawCellBottom(e.cellX, e.cellY, cam.x, bgY) + if grassColors then + self.map.renderer:markCellBottomRedraw(e.cellX, e.cellY, + cam.x, bgY, grassColors) + end + end + end + if e.targetX and self.map:isGrassCell(e.targetX, e.targetY) then + if not self:drawGen3Grass(e.targetX, e.targetY, cam.x, bgY, + self:gen3GrassFrame(e, true)) then + self.map.renderer:drawCellBottom(e.targetX, e.targetY, cam.x, bgY) + if grassColors then + self.map.renderer:markCellBottomRedraw(e.targetX, e.targetY, + cam.x, bgY, grassColors) + end + end + end + end +end + +function OverworldState:_worldAim(renderer, ox, oy, feetX, feetZ) + local g4 = renderer and renderer.gen4Ground + if g4 then + if ox then g4.focusX, g4.focusZ = feetX - ox, feetZ - oy + else g4.focusX, g4.focusZ = nil, nil end + end +end + +-- Private cell columns never cross the public rippleCells seam. +local nativeRippleCells = OverworldState.rippleCells +function OverworldState:_worldAddCoverCell(pool, cx, cy) + local key = cx * 4096 + cy + if pool.seen[key] then return end + pool.seen[key] = true + local n = pool.n + 1 + pool.n, pool.x[n], pool.y[n] = n, cx, cy +end + +function OverworldState:_worldReflectionCover(reflectors, count, renderer, cam, bgY) + local pool = self._worldCover + if not pool then + pool = {x={}, y={}, seen={}, n=0} + self._worldCover = pool + elseif pool.busy then + pool = {x={}, y={}, seen={}, n=0} + end + pool.busy = true + local oldN = pool.n + pool.n = 0 + for key in pairs(pool.seen) do pool.seen[key] = nil end + for i = 1, count do + local cx0, cy0, cx1, cy1 = self:reflectionRect(reflectors[i]) + if cx0 then + for cy = cy0, cy1 do + for cx = cx0, cx1 do self:_worldAddCoverCell(pool, cx, cy) end + end + end + end + for _, r in ipairs(self.ripples or {}) do + for cy = math.floor(r.py / 16), math.floor((r.py + 15) / 16) do + for cx = math.floor(r.px / 16), math.floor((r.px + 15) / 16) do + self:_worldAddCoverCell(pool, cx, cy) + end + end + end + for i = pool.n + 1, oldN do pool.x[i], pool.y[i] = nil, nil end + for i = 1, pool.n do + renderer:drawReflectionCover(pool.x[i], pool.y[i], cam.x, bgY) + end + pool.busy = nil +end + +function OverworldState:_worldEntityLoop(drawEntity, cam, bgY, freeGround, groundForRise, + groundSin, grassColors, spriteDepthGround, shadows, riseOf) + local onTop + for _, e in ipairs(self.entities) do + if self:gen3AboveTopLayer(e) then + onTop = onTop or {} + onTop[#onTop + 1] = e + else + drawEntity(self, e, cam, bgY, freeGround, groundForRise, groundSin, + grassColors, spriteDepthGround, shadows, riseOf) + end + end + return onTop +end + function OverworldState:drawWorld() -- Dark-map BG shade shift, armed for the whole frame before anything draws. -- home/fade.asm's LoadGBPal writes ONE rBGP for the screen, so terrain, the @@ -16946,638 +17761,23 @@ function OverworldState:drawWorld() -- in their historical order. (Bodies are byte-identical to the pre-tilt -- inline code, so the flat draw sequence is unchanged.) - -- the Pokémon Center heal machine (PokeCenterOAMData): the monitor - -- tile over the machine's screen and one ball per healed mon in two - -- mirrored columns, all blinking during the jingle flash. The GB - -- draws it at fixed screen coords with the player's cell BG-aligned - -- at (64,64); anchoring those coords to where the player stood keeps - -- the overlay on the machine at any zoom. - local function fxHeal() - if not self.healAnim then return end - local ha = self.healAnim - -- HOENN'S MACHINE IS NOT AN OAM TABLE. - -- - -- Everything below this block is the Game Boy's: two 8x8 tiles out of - -- field.overworldFx.healMachine at coordinates a table in the ROM gives. - -- Emerald has no such table -- its machine is a field effect whose two - -- sprites are created by machine code, and where they go is four - -- immediates INSIDE that code. extractHealMachine reads them, and the - -- record it writes carries the positions already measured from the corner - -- of the player's own cell, so nothing here has to know where the - -- cartridge's camera puts anybody. - if GameVersion.isGen4() then return end - if self:drawGen3Heal(ha, cam) then return end - local fxDef = Game.data.field.overworldFx - if self.healMachineImg == nil and fxDef and fxDef.healMachine then - local ok, img = pcall(love.graphics.newImage, fxDef.healMachine.path) - self.healMachineImg = ok and img or false - end - local img = self.healMachineImg - if img then - if not self.healMachineQuads then - local w, h = img:getWidth(), img:getHeight() - self.healMachineQuads = { - love.graphics.newQuad(0, 0, 8, 8, w, h), -- monitor ($7c) - love.graphics.newQuad(0, 8, 8, 8, w, h), -- ball ($7d) - } - end - -- The machine carries its OWN four colours. HealMachineAnim.LoadPalettes - -- (04:$6434) copies them over OBJ palette 6 before the animation runs -- - -- which is why every row of its OAM table names palette 6 -- and they are - -- white / light orange / red / black: a Poke Ball. Nothing was applying - -- any palette at all, so the sheet drew in the DMG greys it is decoded - -- in and a Pokemon Center healed with grey balls. - local def = fxDef and fxDef.healMachine - local objPal = def and def.gen2ObjPal - local basePal = (objPal and objPal[1] and objPal) or PaletteFX.GRAYS - -- the jingle flash recolors the machine sprites in place - -- (FlashSprite8Times XORs rOBP1; the sprites never disappear): - -- ha.visible == false is the flashed half of each beat, drawn with - -- the light/dark shades swapped instead of skipped - local shader - if (not ha.visible) or basePal ~= PaletteFX.GRAYS then - shader = PaletteFX.shader() - if shader then - PaletteFX.sendColors(shader, ha.visible and basePal - or PaletteFX.permute(basePal, HEAL_FLASH_MAP)) - love.graphics.setShader(shader) - end - end - -- TileRenderer windows with -floor(cam), so the overlay must use the - -- same snap or a fractional camera (odd fill/tilt view sizes) parks - -- the balls a pixel off the machine tiles - local ox = ha.px - 64 - math.floor(cam.x) - local oy = ha.py - 64 - math.floor(cam.y) - -- Gen2 puts these sprites somewhere else entirely. Its - -- HealMachineAnim.PC_ElmsLab_OAM (04:$63BC) has the monitor at x 26/30 - -- and the balls at x 24/32; Gen1's PokeCenterOAMData has the balls at - -- 40/48. The extractor reads that OAM table straight off the cartridge - -- into field.overworldFx.healMachine, so use it where it exists and keep - -- the Gen1 constants as the fallback -- drawn at Gen1's offsets the - -- whole overlay sat a full 16px right of the Gen2 machine. - local monitor = (def and def.monitor) or { { 44, 20 } } - local balls = (def and def.balls) or HEAL_BALL_XY - love.graphics.setColor(1, 1, 1, 1) - for _, m in ipairs(monitor) do - love.graphics.draw(img, self.healMachineQuads[1], ox + m[1], oy + m[2]) - end - for i = 1, math.min(ha.lit, #balls) do - local b = balls[i] - if b[3] then -- right column: OAM_XFLIP - love.graphics.draw(img, self.healMachineQuads[2], - ox + b[1] + 8, oy + b[2], 0, -1, 1) - else - love.graphics.draw(img, self.healMachineQuads[2], - ox + b[1], oy + b[2]) - end - end - if shader then love.graphics.setShader() end - end - end - - -- the Cut/boulder dust puff: the smoke tile drawn 2x2 over the cell, - -- flickering (AnimateBoulderDust XORs the OBJ palette every step) - local function fxDust() - if not self.dustAnim then return end - local fxDef = Game.data.field.overworldFx - local smoke = fxDef and fxDef.smoke - if smoke then - if self.smokeImg == nil then - local ok, img = pcall(love.graphics.newImage, smoke.path) - self.smokeImg = ok and img or false - end - if self.smokeImg then - local da = self.dustAnim - local dx = da.x * 16 - cam.x - local dy = da.y * 16 - cam.y - local flicker = math.floor(da.frames / 4) % 2 == 0 - love.graphics.setColor(1, 1, 1, flicker and 1 or 0.55) - for i = 0, 1 do - for j = 0, 1 do - love.graphics.draw(self.smokeImg, dx + i * 8, dy + j * 8) - end - end - love.graphics.setColor(1, 1, 1, 1) - end - end - end - - -- FireRed's S.S. Anne departure uses two ordinary OBJ sprites that are not - -- object events: a looping 16x32 wake behind the ship and 16x16 smoke puffs - -- from its funnel. Special 401 owns their exact lifetime/positions; this - -- pass only turns that state into the extracted ROM frames. - local function ssAnneArt() - local def = Game.data.constants and Game.data.constants.gen3SSAnneFx - if not def then return nil end - if self.ssAnneWakeImg == nil then - local ok, img = pcall(Assets.image, def.wake) - self.ssAnneWakeImg = ok and img or false - end - if self.ssAnneSmokeImg == nil then - local ok, img = pcall(Assets.image, def.smoke) - self.ssAnneSmokeImg = ok and img or false - end - if self.ssAnneWakeImg and not self.ssAnneWakeQuads then - local w, h = self.ssAnneWakeImg:getDimensions() - self.ssAnneWakeQuads = { - love.graphics.newQuad(0, 0, 16, 32, w, h), - love.graphics.newQuad(16, 0, 16, 32, w, h), - } - end - if self.ssAnneSmokeImg and not self.ssAnneSmokeQuads then - local w, h = self.ssAnneSmokeImg:getDimensions() - self.ssAnneSmokeQuads = {} - for i = 0, 3 do - self.ssAnneSmokeQuads[i + 1] = love.graphics.newQuad(i * 16, 0, 16, 16, w, h) - end - end - return self.ssAnneWakeImg, self.ssAnneSmokeImg - end - - local function fxSSAnneWake() - local fx = self.ssAnneDepartureFx - if not (fx and fx.boat) then return end - local wake = ssAnneArt() - if not (wake and self.ssAnneWakeQuads) then return end - local age = math.min(fx.wakeAge or 0, 132) - local cx = fx.boat.px + (fx.boat.shiftPx or 0) + 8 - cam.x - + 80 + math.floor(age / 6) - if cx < -18 then return end - local frame = math.floor(age / 12) % 2 + 1 - love.graphics.setColor(1, 1, 1, 1) - love.graphics.draw(wake, self.ssAnneWakeQuads[frame], - math.floor(cx - 8), 109 - 16) - end - - local function fxSSAnneSmoke() - local fx = self.ssAnneDepartureFx - if not (fx and fx.smoke and #fx.smoke > 0) then return end - local _, smoke = ssAnneArt() - if not (smoke and self.ssAnneSmokeQuads) then return end - love.graphics.setColor(1, 1, 1, 1) - for _, puff in ipairs(fx.smoke) do - local age = puff.age or 0 - local frame - if age < 10 then frame = 1 - elseif age < 30 then frame = 2 - elseif age < 50 then frame = 3 - else frame = 4 end - local cx = puff.x + math.floor(age / 4) - love.graphics.draw(smoke, self.ssAnneSmokeQuads[frame], - math.floor(cx - 8), 78 - 8) - end - end - - -- the watering can's water: droplets arcing down onto the soil, and a - -- sparkle on the last few frames as it soaks in - local function fxWater() - if not self.waterAnim then return end - local wa = self.waterAnim - local total = wa.total or 40 - local age = total - wa.frames - local dx = wa.x * 16 - cam.x - local dy = wa.y * 16 - cam.y - love.graphics.setColor(0.55, 0.80, 0.98, 0.95) - for i = 0, 5 do - -- each droplet falls on its own phase, so they read as a stream - local t = ((age * 3 + i * 7) % 24) / 24 - local px = dx + 2 + i * 2 + t * 10 - local py = dy - 6 + t * 20 - if py < dy + 16 then - love.graphics.rectangle("fill", px, py, 2, 3) - end - end - -- the soak: a brief bright ring once the water has been falling a while - if age > total * 0.55 then - local k = (age - total * 0.55) / (total * 0.45) - love.graphics.setColor(1, 1, 1, 0.8 * (1 - k)) - love.graphics.rectangle("fill", dx + 2, dy + 12, 12, 2) - end - love.graphics.setColor(1, 1, 1, 1) - end - - -- the cut tree splitting apart (AnimCut): top half slides right, - -- bottom half slides left, 1px per frame, flickering as they go - local function fxCutTree() - if not self.cutAnim then return end - local fxDef = Game.data.field.overworldFx - local tree = fxDef and fxDef.cutTree - if not tree then return end - if self.cutTreeImg == nil then - local ok, img = pcall(love.graphics.newImage, tree.path) - self.cutTreeImg = ok and img or false - end - local img = self.cutTreeImg - if not img then return end - if not self.cutTreeQuads then - local w, h = img:getWidth(), img:getHeight() - self.cutTreeQuads = { - love.graphics.newQuad(0, 0, 16, 8, w, h), -- top half - love.graphics.newQuad(0, 8, 16, 8, w, h), -- bottom half - } - end - local ca = self.cutAnim - local off = (ca.total or 8) - ca.frames - local dx = ca.x * 16 - cam.x - local dy = ca.y * 16 - cam.y - local flicker = ca.frames % 2 == 0 - love.graphics.setColor(1, 1, 1, flicker and 1 or 0.55) - love.graphics.draw(img, self.cutTreeQuads[1], dx + off, dy) - love.graphics.draw(img, self.cutTreeQuads[2], dx - off, dy + 8) - love.graphics.setColor(1, 1, 1, 1) - end - - -- the "!" bubble above a trainer who spotted the player - -- the tile-anchored sparkle: an OAM sprite in the cartridge, so it rides - -- the camera the way a body does rather than the background's shake - local function fxSparkle() - love.graphics.setColor(1, 1, 1, 1) - self:drawSparkles(cam.x, cam.y) - end - - -- ...and ONE of them, for the two paths that cannot draw the set in screen - -- space: each sparkle sits on its own cell, so a projected scene has to - -- anchor each one separately. The upvalue is set immediately before each - -- call and cleared after, which is the same shape the emote path uses for - -- the one NPC it belongs to. - local sparkleOne = nil - local function fxSparkleOne() - local s = sparkleOne - if not s then return end - local sprite = self:sparkleSprite() - if not sprite then return end - local frame = self:sparkleFrame(s.clock) - if not frame then return end - love.graphics.setColor(1, 1, 1, 1) - sprite:drawFixedFrame(s.px, s.py + 4, cam.x, cam.y, frame) - end - - -- THE POKE RADAR'S PATCHES, one at a time like the sparkles - local radarOne = nil - local function fxRadarOne() - local pt = radarOne - if not pt then return end - require("src.world.Gen4Radar").drawPatch(pt, pt.x * 16 - cam.x, pt.y * 16 - cam.y, - love.timer and love.timer.getTime() * 60 or 0) - end - local function fxRadar() - for _, pt in ipairs((self.gen4Radar and self.gen4Radar.active and self.gen4Radar.patches) or {}) do - if pt.active then radarOne = pt; fxRadarOne() end - end - radarOne = nil - end - - local function fxEmote() - if not (self.emote and self.emote.npc) then return end - -- bubble = false is a silent hold (a Pikachu emotion that plays a - -- cry with no bubble still pauses the world for its beat) - if self.emote.bubble == false then return end - local npc = self.emote.npc - -- SINNOH'S OWN BUBBLE, ON TOP OF THE HEAD, IN THE GROUND'S PROJECTION. - -- - -- Reported from play: *"were missing the proper exclamation point above - -- trainers when they see you for battle and its not above their heads"*. - -- Platinum had neither art source below, so it fell to the hand-drawn box, - -- placed with flat 2D arithmetic that knows nothing of terrain height or - -- the tilt -- so it landed across the face. - -- - -- The cartridge (src/overlay005/ov5_021F5A10.c, see Gen4Emotes): a 16x16 - -- billboard from fldeff.narc whose plane rises 0..16 from an anchor 32 - -- units above the owner's drawn position -- the top of a 32-unit - -- character -- bouncing 6, 10, 12, 12, 10, 6, 0 and then holding. So the - -- bubble's bottom edge sits on the sprite's top edge, centred on it, and - -- it is drawn through exactly the transform the sprite is: the same - -- terrain rise, and `freeEntity` when a 3D camera owns the frame. - local g4emotes = Game.data and Game.data.gen4_emotes - local g4ground = self.map and self.map.renderer and self.map.renderer.gen4Ground - if g4emotes and g4ground and npc.sprite then - local Gen4Emotes = require("src.import.Gen4Emotes") - local kind = (self.emote.bubble == "double" or self.emote.bubble == 2) - and g4emotes.double and "double" or "exclamation" - -- BW's "?", note and "..." by name (Gen5MoveExec), when the cache has them - local named = self.emote.bubble - if type(named) == "string" and named ~= "double" and type(g4emotes[named]) == "table" then - kind = named - end - local record = g4emotes[kind] - self.gen4EmoteImages = self.gen4EmoteImages or {} - local img = self.gen4EmoteImages[kind] - if img == nil and record and record.rgba then - local okI, made = pcall(function() - local data = love.image.newImageData(record.width, record.height, - "rgba8", record.rgba) - local image = love.graphics.newImage(data) - image:setFilter("nearest", "nearest") - return image - end) - img = okI and made or false - self.gen4EmoteImages[kind] = img - end - if img then - local age = math.max(0, (self.emote.totalFrames or Gen4Emotes.FRAMES) - - (self.emote.frames or 0)) - -- HEARTGOLD / SOULSILVER: the cartridge's own anchor, 32 world units - -- over the owner through the camera now drawing, the player - -- included (src/world/Gen4EmoteDraw.lua); Platinum below, unchanged - local EmoteDraw = require("src.world.Gen4EmoteDraw") - if EmoteDraw.applies(self.map) then - EmoteDraw.draw(self, g4ground, npc, cam, record, img, age) - return - end - local bx, by, rise = OverworldState.gen4EmoteSpot(g4ground, npc, cam, - record, age) - local function draw() - love.graphics.setColor(1, 1, 1, 1) - love.graphics.draw(img, bx, by) - end - local free = g4ground.freeMode and g4ground:freeMode() - if free then - -- Depth-tested where the cartridge's billboard actually is -- the - -- middle of a bubble 32 units up -- not at its trainer's feet. - g4ground:freeEntity(npc.px or 0, npc.py or 0, cam.x, cam.y, rise, draw, - Gen4Emotes.LIFT + 8) - else - draw() - end - return - end - end - -- WHERE IT HANGS, which the cartridge states outright. - -- - -- Reported from play: the bubble "should appear above the trainers head". - -- It was four pixels right of them and six low, which on a 16x32 walker - -- put it across the face rather than over it. - -- - -- The icon's own sprite callback (0B4724) copies the owner's position - -- every frame and offsets it by exactly one thing: - -- - -- icon->x = owner->x - -- icon->y = owner->y - 16 - -- - -- and a GBA sprite's x/y is its CENTRE (the corner comes from - -- centerToCornerVec), so this is "the icon's centre sits sixteen pixels - -- above the owner's" -- which is a different top-left offset for a 16x16 - -- object than for a 16x32 one, and is why one number could never be right - -- for both. Stated as centres it falls out the same for either: the x - -- offsets cancel whatever the sprite's width, and the y is the owner's - -- half-height less the icon's eight plus the sixteen. - local half = math.floor(((npc.sprite and npc.sprite.tileH) or 16) / 2) - local ex = npc.px - cam.x - local ey = npc.py - cam.y - 12 - half - local bubble = Game.data.field.emotionBubbles - local drawn = false - - -- HOENN'S OWN BUBBLE, which is not on the Game Boy's sheet. - -- - -- The "!" over a trainer's head is three 16x16 icons hanging off a sprite - -- template that only a field-effect script reaches (see extractEmotes) -- - -- which is why every sweep of the field-effect tables missed it. A Gen 3 - -- dataset that has them draws them; one that does not falls through to - -- the Game Boy sheet and then to the box below, exactly as before. - local icons = (Game.data.constants or {}).gen3Emotes - if icons then - local role = GEN3_EMOTE_ROLES[self.emote.bubble or 1] or "exclamation" - local record = icons[role] - local path = record and record.image - if path then - self.gen3EmoteImages = self.gen3EmoteImages or {} - local held = self.gen3EmoteImages[path] - if held == nil then - local okImg, img = pcall(require("src.render.Assets").image, path) - held = (okImg and img) or false - self.gen3EmoteImages[path] = held - end - if held then - local age = math.max(0, (self.emote.totalFrames or 60) - - self.emote.frames) - local frame = 0 - local left = age - for _, step in ipairs(record.timeline or {}) do - local duration = tonumber(step[2]) or 1 - if left < duration then - frame = tonumber(step[1]) or 0 - break - end - left = left - duration - frame = tonumber(step[1]) or frame - end - -- SpriteCB_TrainerIcons starts data[3] at -5, accumulates it into - -- data[4], and increments that velocity until the offset returns 0. - local bounce, velocity = 0, -5 - for _ = 1, math.min(age + 1, 11) do - bounce = bounce + velocity - if bounce ~= 0 then velocity = velocity + 1 else velocity = 0 end - end - local fw, fh = tonumber(record.width) or 16, tonumber(record.height) or 16 - local iw, ih = held:getDimensions() - local q = nil - if (tonumber(record.frames) or 1) > 1 then - self.gen3EmoteQuads = self.gen3EmoteQuads or {} - local key = path .. ":" .. tostring(frame) - q = self.gen3EmoteQuads[key] - if not q then - q = love.graphics.newQuad(frame * fw, 0, fw, fh, iw, ih) - self.gen3EmoteQuads[key] = q - end - end - love.graphics.setColor(1, 1, 1, 1) - if q then love.graphics.draw(held, q, ex, ey + bounce) - else love.graphics.draw(held, ex, ey + bounce) end - drawn = true - end - end - end - if not drawn and bubble and bubble.path then - local ok, img = pcall(function() - self.emoteImg = self.emoteImg or obpEmoteImage(bubble.path) - return self.emoteImg - end) - -- EXCLAMATION_BUBBLE is index 0 -> first crop; the emote command - -- picks question/happy crops instead - local bi = self.emote.bubble or 1 - local rect = bubble.bubbles and bubble.bubbles[bi] - if ok and img and rect then - love.graphics.setColor(1, 1, 1, 1) - -- one Quad per bubble crop, cached: this draws every frame the "!" - -- (or the emote-command crops) is up, so a fresh Quad here churned - -- the GC. The bubble set is small and fixed, so the cache is bounded. - self.emoteQuads = self.emoteQuads or {} - local q = self.emoteQuads[bi] - if not q then - q = love.graphics.newQuad(rect.x, rect.y, rect.w, rect.h, - img:getDimensions()) - self.emoteQuads[bi] = q - end - love.graphics.draw(img, q, ex, ey) - drawn = true - end - end - if not drawn then - local Font = require("src.render.Font") - love.graphics.setColor(1, 1, 1, 1) - love.graphics.rectangle("fill", ex, ey, 10, 12) - love.graphics.setColor(0, 0, 0, 1) - love.graphics.rectangle("line", ex + 0.5, ey + 0.5, 10, 12) - Font.draw("!", ex + 1, ey + 2) - love.graphics.setColor(1, 1, 1, 1) - end - end - - -- the FLY bird sweeping off with the player - local function fxBird() - if not self.flyAnim then return end - -- FireRed has a dedicated five-frame 64x64 field-effect bird. Frames 1 - -- and 3 already contain Red/Leaf riding it during fly-out, so use the - -- cartridge sheet directly instead of substituting the selected mon's - -- battle front sprite. - local frlg = Game.data.constants and Game.data.constants.gen3FRLGFlyBird - if frlg and frlg.path then - if self.flyBirdImg == nil then - local ok, img = pcall(love.graphics.newImage, frlg.path) - self.flyBirdImg = ok and img or false - end - if self.flyBirdImg then - local gender = ((Game.save or {}).player or {}).gender == "girl" - and "girl" or "boy" - local frame = ((frlg.flyOut or {})[gender]) or (gender == "girl" and 3 or 1) - local fw = frlg.frameWidth or 64 - local fh = frlg.frameHeight or 64 - self.flyBirdQuads = self.flyBirdQuads or {} - if not self.flyBirdQuads[frame] then - local iw, ih = self.flyBirdImg:getDimensions() - self.flyBirdQuads[frame] = love.graphics.newQuad( - 0, frame * fh, fw, fh, iw, ih) - end - local t = math.max(0, math.min(48, 48 - self.flyAnim.frames)) - local reach = 16 - local dx, dy - if t <= reach then - local k = 1 - t / reach - dx, dy = -96 * k, -72 * k - else - local k = (t - reach) / (48 - reach) - dx, dy = -120 * k * k, -96 * k * k - end - local px = math.floor(self.player.px - cam.x + 8 - fw / 2 + dx) - local py = math.floor(self.player.py - cam.y + 8 - fh / 2 + dy) - love.graphics.setColor(1, 1, 1, 1) - love.graphics.draw(self.flyBirdImg, self.flyBirdQuads[frame], px, py) - require("src.render.PaletteFX").markTrueColor(px, py, fw, fh) - return - end - end - local birdId = FieldDefaults.fieldValue(Game.data, "playerSprites", "fly") - if not self.birdSprite and birdId and Game.data.sprites[birdId] then - local SR = require("src.render.SpriteRenderer") - self.birdSprite = SR.new(Game.data.sprites[birdId]) - end - if self.birdSprite then - local t = 48 - self.flyAnim.frames - local bx = self.player.px - t * 4 - local by = self.player.py - math.floor(t * 1.5) - love.graphics.setColor(1, 1, 1, 1) - self.birdSprite:draw(bx, by, cam.x, cam.y, "left", - math.floor(t / 4) % 2, false) - return - end - - -- Legacy fallback for datasets that predate the ROM-extracted FireRed - -- bird above. Keep it for old caches/other games, but current FireRed - -- imports should never reach this branch. - -- - -- Reported from play, twice: "ensure the animation of the flying type - -- pokemon swooping up my player plays after the fly hm transition" and - -- then "Theres still no fly swoop". The machinery above has been here the - -- whole time and has never had a sprite to draw: it wants - -- playerSprites.fly, and no Gen 3 cache carries one. - -- - -- IT WAS LOOKED FOR PROPERLY THIS TIME, and it is not where a sheet like - -- that would be. Emerald's fly bird is not an object-event graphics row - -- -- the three 64x64 rows in that table are Rayquaza twice and the cable - -- car, and every 32x32 row is a person or a legendary -- and it is not - -- hanging off any field-effect script either: not one of the sixty-seven - -- scripts loads tiles, and no native any of them calls reaches a sprite - -- template with frames that size. It is loaded by C, from a sheet only - -- the fly task names, and nothing the import can currently follow gets to - -- it. - -- - -- So the departure is drawn with something this port certainly does have - -- and the cartridge's own bird is not: the FRONT SPRITE OF THE POKEMON - -- THAT IS ACTUALLY CARRYING YOU -- the same one the field-move sweep just - -- showed. It stoops in from the upper left, meets the player, and lifts - -- away with them. Reconstructed, and said so; the moment the bird IS - -- found, playerSprites.fly makes the branch above win again and this is - -- never reached. - local mon = self.flyAnim.mon - if not mon then return end - if self.flyMonImg == nil then - local okPath, path = pcall(function() - return require("src.pokemon.Sprites").path( - Game.data, mon.species, "front", { mon = mon }) - end) - local img - if okPath and type(path) == "string" then - local okImg, loaded = pcall(love.graphics.newImage, path) - img = okImg and loaded or nil - end - self.flyMonImg = img or false - end - if not self.flyMonImg then return end - local total = 48 - local t = math.max(0, math.min(total, total - self.flyAnim.frames)) - -- the stoop: in over sixteen frames, away over the rest, and the two - -- meet on the player rather than anywhere else - local reach = 16 - local dx, dy - if t <= reach then - local k = 1 - t / reach - dx, dy = -96 * k, -72 * k - else - local k = (t - reach) / (total - reach) - dx, dy = -120 * k * k, -96 * k * k - end - local iw, ih = self.flyMonImg:getDimensions() - local px = math.floor(self.player.px - cam.x + 8 - iw / 2 + dx) - local py = math.floor(self.player.py - cam.y + 8 - ih / 2 + dy) - love.graphics.setColor(1, 1, 1, 1) - love.graphics.draw(self.flyMonImg, px, py) - require("src.render.PaletteFX").markTrueColor(px, py, iw, ih) - end - - -- fishing pose: the rod tile over the faced water (gfx/fishing.asm) - local function fxRod() - if not self.fishing then return end - local fx = Game.data.field.overworldFx - local rod = fx and fx.fishingRod - if rod then - if self.rodImg == nil then - local ok, img = pcall(love.graphics.newImage, rod.path) - self.rodImg = ok and img or false - end - if self.rodImg then - local p = self.player - local oam = ROD_OAM[self.fishing.facing] or ROD_OAM.down - if not self.rodQuads then - -- one quad per 8x8 tile of the stacked sheet (ROD_OAM.tile) - local iw, ih = self.rodImg:getDimensions() - self.rodQuads = {} - for i = 0, math.floor(ih / 8) - 1 do - self.rodQuads[i] = love.graphics.newQuad(0, i * 8, 8, 8, iw, ih) - end - end - local quad = self.rodQuads[oam.tile] - -- the sprite's top-left is 4px above its cell (SpriteRenderer:draw) - local rx = p.px - cam.x + oam.dx - local ry = p.py - cam.y - 4 + oam.dy - love.graphics.setColor(1, 1, 1, 1) - if quad and oam.flip then - love.graphics.draw(self.rodImg, quad, rx + 8, ry, 0, -1, 1) - elseif quad then - love.graphics.draw(self.rodImg, quad, rx, ry) - end - end - end - end + local sparkleOne, radarOne + local boundFx = not Performance.worldDrawHoist or pipelineId or tilt + local fxHeal = boundFx and bindWorldFx(self._worldFxHeal, self, cam) or self._worldFxHeal + local fxDust = boundFx and bindWorldFx(self._worldFxDust, self, cam) or self._worldFxDust + local fxSSAnneWake = boundFx and bindWorldFx(self._worldFxSSAnneWake, self, cam) or self._worldFxSSAnneWake + local fxSSAnneSmoke = boundFx and bindWorldFx(self._worldFxSSAnneSmoke, self, cam) or self._worldFxSSAnneSmoke + local fxWater = boundFx and bindWorldFx(self._worldFxWater, self, cam) or self._worldFxWater + local fxCutTree = boundFx and bindWorldFx(self._worldFxCutTree, self, cam) or self._worldFxCutTree + local fxSparkle = boundFx and bindWorldFx(self._worldFxSparkle, self, cam) or self._worldFxSparkle + local fxSparkleOne + if boundFx then fxSparkleOne = function() return self:_worldFxSparkleOne(cam, sparkleOne) end end + local fxRadarOne + if boundFx then fxRadarOne = function() return self:_worldFxRadarOne(cam, radarOne) end end + local fxRadar = boundFx and bindWorldFx(self._worldFxRadar, self, cam) or self._worldFxRadar + local fxEmote = bindWorldFx(self._worldFxEmote, self, cam) + local fxBird = boundFx and bindWorldFx(self._worldFxBird, self, cam) or self._worldFxBird + local fxRod = boundFx and bindWorldFx(self._worldFxRod, self, cam) or self._worldFxRod if pipelineId then -- === PIPELINE PATH: a mod owns the world pass. ====================== @@ -17703,8 +17903,8 @@ function OverworldState:drawWorld() -- The S.S. Anne effects are authored in screen OAM coordinates for this -- fixed-camera cutscene. Keep them as an upright overlay for a custom -- world pipeline; the flat/tilt paths place the wake behind the ship. - fxSSAnneWake() - fxSSAnneSmoke() + fxSSAnneWake(self, cam) + fxSSAnneSmoke(self, cam) for _, sp in ipairs(self.sparkles or {}) do sparkleOne = sp at(fxSparkleOne, sp.px + 8, sp.py + 16) @@ -17761,19 +17961,9 @@ function OverworldState:drawWorld() and groundForRise:freeMode()) and groundForRise or nil local groundSin = groundForRise and groundForRise.scale and select(1, groundForRise:scale()) or 1 - local function riseOf(e) - if not groundForRise then return 0 end - local rise = groundForRise:rise(e.px + (e.shiftPx or 0) + 8, e.py + 8) - -- A SPRITE OFFSET (MapObject_SetSpritePosOffset: the surf mount's ride, - -- the Distortion World cast's flights) in the field view: up by the - -- camera's height lean, toward it by the ground's - local so = e.spriteOffset - if so and (so.lift or so.oz) then - rise = rise + (so.lift or 0) * (groundForRise.heightScale or 0) - - (so.oz or 0) * (groundForRise.groundScale or 1) - end - if groundSin >= 1 then return rise end - return (e.py - cam.y) * (1 - groundSin) + rise + local riseOf = self._worldRise + if not Performance.worldDrawHoist then + riseOf = function(_self, e) return self:_worldRise(e, groundForRise, groundSin, cam) end end if override then @@ -17865,7 +18055,6 @@ function OverworldState:drawWorld() -- ...AND A PLOT'S ANSWER CHANGES WHILE YOU ARE STANDING THERE. A tree -- is planted, grows and is picked without the map reloading, so its -- emptiness is asked at draw time rather than remembered at spawn. - local plotEmpty = plotIsEmpty -- the ground whose depth the entity pass is drawing into, while it is local spriteDepthGround = nil -- SINNOH'S CHARACTERS STAND ON SOMETHING. Built once per frame rather @@ -17877,98 +18066,11 @@ function OverworldState:drawWorld() shadows = require("src.render.Gen4Shadows").forMap(Game.data) or false self.gen4Shadows = shadows end - local function drawEntity(e) - if not (self.flyAnim and self:hasFlyBird() and e == self.player) - and not e.hidden and not e.berryVisualEmpty and not plotEmpty(e) then - -- A FREE CAMERA PLACES ITS OWN CHARACTERS. - -- - -- Reported from play: *"isnt keeping the player the right size"*, with a - -- screenshot of a third-person Twinleaf in correct perspective and two - -- characters standing in it at flat 2D scale. They were drawn by the - -- line below, which places every sprite at `py - camY` -- the field - -- camera's 1:1 mapping, and simply not this camera's. - -- - -- `freeEntity` runs THIS SAME DRAW inside a transform, so nothing here - -- learns about projection and the entity keeps owning its own sprite, - -- frame and palette. - -- - -- In FIRST person the player is the eye, so drawing them puts their own - -- back across the middle of the view. - if freeGround then - if not (freeGround:freeMode() == "first" and e == self.player) then - local rise = riseOf(e) - -- ...AND WHICH WAY THEY FACE ON SCREEN. - -- - -- Reported from play: *"when i orbit the camera 180 degrees if i - -- walk left it looks like hes walking right"*. `screenToWorld` - -- turns the PRESS into a world direction, so the step is right; - -- the sprite then showed that world facing under a camera that is - -- no longer looking north, so the artwork was the one thing still - -- in the old frame. `worldToScreen` is its inverse, and the pair - -- are inverses because the camera sits between them. - -- - -- Set and restored around the draw rather than threaded through, - -- because `facing` is what every pose, animation and follower path - -- in the entity reads, and none of them should learn about cameras. - local view, saved = freeGround.view3d, e.facing - if view and view.worldToScreen then - e.facing = view:worldToScreen(saved) - end - freeGround:freeEntity((e.px or 0), (e.py or 0), cam.x, cam.y, rise, - function() e:draw(cam.x, cam.y + rise) end, - nil, require("src.world.Gen4SurfMount").poseFor(e, e == self.player and self.dwPose or nil)) - e.facing = saved - end - -- Deliberately without the flat shadow and the grass overdraw below: - -- both are drawn in screen space against a ground plane this camera - -- does not have, and a shadow in the wrong place is worse than none. - return - end - -- IN THE WORLD'S DEPTH on Sinnoh's cartridge camera - -- (Gen4Ground:beginSprites): the billboard origin's depth, so a prop in - -- front of a character hides them; nil leaves the draw as it was - local depth = spriteDepthGround and spriteDepthGround:billboardDepth( - (e.px or 0) + (e.shiftPx or 0), e.py or 0, - e.spriteOffset and e.spriteOffset.lift, e.spriteOffset and e.spriteOffset.oz) - -- UNDER the sprite, and lifted by the same terrain rise it is, so a - -- character on a slope keeps their feet on it. - if shadows then - if depth then - spriteDepthGround:withSpriteDepth(depth, function() - shadows:draw(self.map, e, cam.x, cam.y, e == self.player, riseOf(e)) - end, false) - else - shadows:draw(self.map, e, cam.x, cam.y, e == self.player, riseOf(e)) - end - end - if depth then - spriteDepthGround:withSpriteDepth(depth, function() e:draw(cam.x, cam.y + riseOf(e)) end) - else - e:draw(cam.x, cam.y + riseOf(e)) - end - -- tall grass overdraws the sprite's feet (GB sprite priority); - -- the overdraw is BG tiles, so it rides the shake offset too - love.graphics.setColor(1, 1, 1, 1) - if self.map:isGrassCell(e.cellX, e.cellY) then - if not self:drawGen3Grass(e.cellX, e.cellY, cam.x, bgY, - self:gen3GrassFrame(e, false)) then - self.map.renderer:drawCellBottom(e.cellX, e.cellY, cam.x, bgY) - if grassColors then - self.map.renderer:markCellBottomRedraw(e.cellX, e.cellY, - cam.x, bgY, grassColors) - end - end - end - if e.targetX and self.map:isGrassCell(e.targetX, e.targetY) then - if not self:drawGen3Grass(e.targetX, e.targetY, cam.x, bgY, - self:gen3GrassFrame(e, true)) then - self.map.renderer:drawCellBottom(e.targetX, e.targetY, cam.x, bgY) - if grassColors then - self.map.renderer:markCellBottomRedraw(e.targetX, e.targetY, - cam.x, bgY, grassColors) - end - end - end + local drawEntity = self._worldDrawEntity + if not Performance.worldDrawHoist then + drawEntity = function(_self, e) + return self:_worldDrawEntity(e, cam, bgY, freeGround, groundForRise, groundSin, + grassColors, spriteDepthGround, shadows, riseOf) end end @@ -18023,16 +18125,25 @@ function OverworldState:drawWorld() -- rectangle each, which is precisely what a scissor is. It is set per -- cell and intersected with whatever clip the caller already had, so a -- reflection is painted once per water cell it falls across. - local reflectors = {} + local reflectors = Performance.worldDrawHoist and self._worldReflectors or nil + if not reflectors or reflectors.busy then + reflectors = {n=0} + if Performance.worldDrawHoist and not self._worldReflectors then self._worldReflectors = reflectors end + end + reflectors.busy = true + local oldReflectors, reflectorCount = reflectors.n, 0 for _, e in ipairs(self.entities) do if not e.hidden and e.drawReflection then e.reflects = self:reflectionSearch(e) if e.reflects then e.reflectStill = self:stillReflection(e.reflects) - reflectors[#reflectors + 1] = e + reflectorCount = reflectorCount + 1 + reflectors[reflectorCount] = e end end end + for i = reflectorCount + 1, oldReflectors do reflectors[i] = nil end + reflectors.n = reflectorCount self.reflectProbe = (self.reflectProbe or 0) + 1 if self.reflectProbe % 90 == 1 then local p, set = self.player, Game and Game.data and Game.data.constants @@ -18122,6 +18233,9 @@ function OverworldState:drawWorld() love.graphics.setColor(1, 1, 1, 1) local renderer = self.map.renderer if renderer.drawReflectionCover then + if Performance.worldDrawHoist and self.rippleCells == nativeRippleCells then + self:_worldReflectionCover(reflectors, reflectorCount, renderer, cam, bgY) + else local seen, cells = {}, {} for _, e in ipairs(reflectors) do local cx0, cy0, cx1, cy1 = self:reflectionRect(e) @@ -18141,15 +18255,17 @@ function OverworldState:drawWorld() for _, cell in ipairs(cells) do renderer:drawReflectionCover(cell[1], cell[2], cam.x, bgY) end + end end end + reflectors.busy = nil -- The rotating gates sit under the entity pass; the S.S. Anne wake has -- priority below the ship and therefore belongs immediately before it. self:drawGen3Gates(cam) -- OBJ priority 2 and a later sprite id put the wake behind the ship at the -- same priority on hardware. Draw it immediately before the entity pass. - fxSSAnneWake() + fxSSAnneWake(self, cam) local onTop = nil -- SINNOH'S CARTRIDGE CAMERA: the characters go into the world's own depth -- buffer (Gen4Ground:beginSprites) so props in front of them hide them @@ -18158,18 +18274,28 @@ function OverworldState:drawWorld() spriteDepthGround = groundForRise end local closeEntities = FrameProfile.section(" world: entities") + if Performance.worldDrawHoist then + local okE, result = pcall(self._worldEntityLoop, self, drawEntity, cam, bgY, freeGround, + groundForRise, groundSin, grassColors, spriteDepthGround, shadows, riseOf) + if not okE then + if spriteDepthGround then spriteDepthGround:endSprites(); spriteDepthGround = nil end + error(result, 0) + end + onTop = result + else for _, e in ipairs(self.entities) do if self:gen3AboveTopLayer(e) then onTop = onTop or {} onTop[#onTop + 1] = e else - local okE, errE = pcall(drawEntity, e) + local okE, errE = pcall(drawEntity, self, e, cam, bgY, freeGround, groundForRise, groundSin, grassColors, spriteDepthGround, shadows, riseOf) if not okE then if spriteDepthGround then spriteDepthGround:endSprites(); spriteDepthGround = nil end error(errE, 0) end end end + end if spriteDepthGround then spriteDepthGround:endSprites() spriteDepthGround = nil @@ -18186,11 +18312,10 @@ function OverworldState:drawWorld() -- not the player at every zoom. Cleared after, so a stale focus can never -- outlive the frame it was true for. local feetX, feetZ = (self.player.px or 0) + 8, (self.player.py or 0) + 8 - local function aim(renderer, ox, oy) - local g4 = renderer and renderer.gen4Ground - if g4 then - if ox then g4.focusX, g4.focusZ = feetX - ox, feetZ - oy - else g4.focusX, g4.focusZ = nil, nil end + local aim = self._worldAim + if not Performance.worldDrawHoist then + aim = function(_self, renderer, ox, oy) + return self:_worldAim(renderer, ox, oy, feetX, feetZ) end end -- THE "!" GOES IN WHILE A FREE CAMERA'S 3D PASS IS STILL OPEN. @@ -18207,28 +18332,28 @@ function OverworldState:drawWorld() emoteEarly = true end local closeTiles = FrameProfile.section(" world: tiles") - aim(self.map.renderer, 0, 0) + aim(self, self.map.renderer, 0, 0, feetX, feetZ) self.map.renderer:drawAbove(cam.x, bgY, vw, vh) - aim(self.map.renderer) + aim(self, self.map.renderer, nil, nil, feetX, feetZ) for _, nb in ipairs(self.neighbors) do if nb.map.renderer.drawAbove then - aim(nb.map.renderer, nb.ox, nb.oy) + aim(self, nb.map.renderer, nb.ox, nb.oy, feetX, feetZ) nb.map.renderer:drawAbove(cam.x - nb.ox, bgY - nb.oy, vw, vh) - aim(nb.map.renderer) + aim(self, nb.map.renderer, nil, nil, feetX, feetZ) end end closeTiles() closeEntities = FrameProfile.section(" world: entities") - for _, e in ipairs(onTop or {}) do drawEntity(e) end + for _, e in ipairs(onTop or {}) do drawEntity(self, e, cam, bgY, freeGround, groundForRise, groundSin, grassColors, spriteDepthGround, shadows, riseOf) end closeEntities() local closeFx = FrameProfile.section(" world: FX") - fxHeal() - fxDust() - fxCutTree() - fxWater() + fxHeal(self, cam) + fxDust(self, cam) + fxCutTree(self, cam) + fxWater(self, cam) if not emoteEarly then self:eachEmote(fxEmote) end - fxRadar() + fxRadar(self, cam) -- BLACK / WHITE: the phenomenon spot and the rod's lure (Gen5Phenomena) if GameVersion.isGen5() then local g5ground = self.map and self.map.renderer and self.map.renderer.gen4Ground @@ -18238,11 +18363,11 @@ function OverworldState:drawWorld() end -- HGSS: the Dowsing MCHN's reading (src/world/HgssDowsing.lua) if self.hgssDowsing then require("src.world.HgssDowsing").draw(self, vw, vh) end - fxSparkle() - fxBird() - fxRod() + fxSparkle(self, cam) + fxBird(self, cam) + fxRod(self, cam) -- Smoke keeps the template's priority 0, above the ship and map layers. - fxSSAnneSmoke() + fxSSAnneSmoke(self, cam) closeFx() else -- === TILT PATH: ground-hugging FX stay on the projected ground, all @@ -18254,10 +18379,10 @@ function OverworldState:drawWorld() -- layers are separate and composited ground-under-upright, so drawing -- them now into the still-active ground canvas is order-equivalent. local closeFx = FrameProfile.section(" world: FX") - fxHeal() - fxDust() - fxCutTree() - fxWater() + fxHeal(self, cam) + fxDust(self, cam) + fxCutTree(self, cam) + fxWater(self, cam) -- ...and the gates with them: they are behind every upright sprite (see -- drawGen3Gates), so the ground canvas is exactly where they belong self:drawGen3Gates(cam) @@ -18265,7 +18390,7 @@ function OverworldState:drawWorld() Game.renderer:beginUprightPass() - fxSSAnneWake() + fxSSAnneWake(self, cam) -- One y-sorted list of ALL upright billboards -- sprites (player, NPCs, -- ghosts) -- keyed on baseline world y (the foot / base row). Farther @@ -18298,7 +18423,7 @@ function OverworldState:drawWorld() local fy = e.py - cam.y + 16 local colors = zoneColorsAt(zones, fx, fy) self:billboard(fx, fy, vw, vh, colors, false, - function() e:draw(cam.x, cam.y + riseOf(e)) end) + function() e:draw(cam.x, cam.y + riseOf(self, e, groundForRise, groundSin, cam)) end) -- tall-grass feet overdraw glued to the sprite: same anchor + depth -- so it keeps hiding the feet, color-0-keyed palette so its white -- gaps still show the sprite through (drawCellBottomRaw lets the @@ -18341,7 +18466,7 @@ function OverworldState:drawWorld() local fy = self.player.py - cam.y + 16 self:billboard(fx, fy, vw, vh, zoneColorsAt(zones, fx, fy), false, fxRod) end - fxSSAnneSmoke() + fxSSAnneSmoke(self, cam) for _, sp in ipairs(self.sparkles or {}) do sparkleOne = sp local fx = sp.px - cam.x + 8 diff --git a/tests/engine/world_draw_hot.lua b/tests/engine/world_draw_hot.lua new file mode 100644 index 000000000..a80c4a2dc --- /dev/null +++ b/tests/engine/world_draw_hot.lua @@ -0,0 +1,135 @@ +local T = require("tests.harness") +love = require("tests.love_stub") +local Version = require("src.core.GameVersion") +local Performance = require("src.core.Performance") +local World = require("src.world.OverworldController") +local Fixture = require("tests.world_draw.fixture") +local originalPcall = pcall +for _, version in ipairs({ "red", "gold", "emerald", "platinum" }) do + Version.set(version) + local f = Fixture.new(32) + local world = f.world + Performance.worldDrawHoist = false + world:drawWorld() + f.reset() + local beforeCalls = 0 + _G.pcall = function(...) + beforeCalls = beforeCalls + 1 + return originalPcall(...) + end + world:drawWorld() + _G.pcall = originalPcall + local before = f.trace() + f.reset() + Performance.worldDrawHoist = true + local afterCalls = 0 + _G.pcall = function(...) + afterCalls = afterCalls + 1 + return originalPcall(...) + end + world:drawWorld() + _G.pcall = originalPcall + T.same(f.trace(), before, version .. " keeps tile/reflection/entity/top-layer/FX draw order and coordinates") + T.check(beforeCalls > afterCalls, version .. " reduces protected calls for the entity pass") + T.eq(afterCalls, 1, version .. " has one protected ordinary entity loop") + local list, cover = world._worldReflectors, world._worldCover + world:drawWorld() + T.eq(world._worldReflectors, list, "reflector list is private and reused") + T.eq(world._worldCover, cover, "parallel cover columns are private and reused") + world.entities = { world.player } + world.ripples = {} + world:drawWorld() + T.eq(list.n, 0, "shrinking frame clears reflector count") + T.eq(list[1], nil, "shrinking frame releases stale entity references") +end +Version.set("red") +local f = Fixture.new(3) +local world = f.world +local retained = {} +world.rippleCells = function(self, out, seen) + retained[#retained + 1] = out + T.check(out ~= self._worldCover, "public replacement never receives a private pool") + return World.rippleCells(self, out, seen) +end +world:drawWorld() +world:drawWorld() +T.check(retained[1] ~= retained[2], "public ripple wrapper keeps fresh cell records") +T.check(retained[1][1] ~= retained[2][1], "public cell pairs remain detached") +local ended = 0 +world.map.renderer.gen4Ground = { + rise = function() + return 0 + end, + billboardDepth = function() + return nil + end, + beginSprites = function() + return true + end, + endSprites = function() + ended = ended + 1 + end, +} +world.player.draw = function() + error("synthetic entity failure") +end +local ok, err = pcall(World.drawWorld, world) +T.eq(ok, false, "entity errors are propagated") +T.check(tostring(err):find("synthetic entity failure", 1, true) ~= nil, "original entity error remains visible") +T.eq(ended, 1, "sprite depth pass closes exactly once on failure") +-- Nested cover drawing must not overwrite the outer borrowed columns. +local nested = false +local visited = {} +world.rippleCells = World.rippleCells +world.map.renderer.drawReflectionCover = function(_, cx, cy) + visited[#visited + 1] = cx .. ":" .. cy + if not nested then + nested = true + world:_worldReflectionCover({}, 0, { drawReflectionCover = function() end }, world.camera, 0) + end +end +world:_worldReflectionCover({ world.entities[2] }, 1, world.map.renderer, world.camera, 0) +T.same( + visited, + { "2:3", "3:3", "2:4", "3:4", "0:1", "1:1", "0:2", "1:2" }, + "nested cover work cannot clobber the outer columns" +) +-- A pipeline may retain its no-argument FX callbacks after a later frame. +local P = require("src.render.Pipelines") +local saved = + { worldPipeline = P.worldPipeline, drawWorld = P.drawWorld, worldPresent = P.worldPresent, level = P.level } +local frames = {} +P.worldPipeline = function() + return "synthetic", {} +end +P.drawWorld = function(_, ctx) + frames[#frames + 1] = ctx + return {} +end +P.worldPresent = function(canvas) + return canvas +end +P.level = function() + return 1 +end +local scene = Fixture.new(2) +scene.world:drawWorld() +scene.world.camera = { x = 67, y = 5 } +scene.world:drawWorld() +T.check(frames[1] ~= frames[2] and frames[1].fx ~= frames[2].fx, "public pipeline frames and FX tables remain detached") +T.check(frames[1].fx.water ~= frames[2].fx.water, "public FX callbacks keep their own frame binding") +local positions = {} +local rectangle = love.graphics.rectangle +love.graphics.rectangle = function(_, x) + positions[#positions + 1] = x +end +frames[1].fx.water() +local oldX = positions[1] +positions = {} +frames[2].fx.water() +T.eq(oldX - positions[1], 64, "retained zero-argument callback keeps the original camera") +love.graphics.rectangle = rectangle +for name, value in pairs(saved) do + P[name] = value +end +T.finish("world draw hot paths") diff --git a/tests/world_draw/fixture.lua b/tests/world_draw/fixture.lua new file mode 100644 index 000000000..d7f8f773c --- /dev/null +++ b/tests/world_draw/fixture.lua @@ -0,0 +1,118 @@ +-- Owned synthetic draw scene: no ROM, profile, asset extraction or game progress. +local F = {} +function F.new(count, options) + local World = options and options.worldModule or require("src.world.OverworldController") + local Game = require("src.core.Game") + -- The normal enter lifecycle supplies this shared engine reference. The + -- isolated rendering fixture has no map loader or save lifecycle to enter. + for index = 1, 100 do + local name = debug.getupvalue(World.drawWorld, index) + if not name then + break + end + if name == "Game" then + debug.setupvalue(World.drawWorld, index, Game) + break + end + end + Game.data = { field = { overworldFx = {} }, constants = {}, sprites = {} } + Game.save = { options = {} } + local trace = {} + local function mark(name, ...) + if options and options.quiet then + return + end + local row = { name, ... } + for i = 1, #row do + row[i] = tostring(row[i]) + end + trace[#trace + 1] = table.concat(row, ":") + end + local renderer = {} + for _, name in ipairs({ "drawBorderFill", "draw", "drawMapOnly", "drawAbove", "drawReflectionCover" }) do + renderer[name] = function(_, ...) + mark(name, ...) + end + end + local world = setmetatable({ + camera = { x = 3, y = 5 }, + map = { + id = "SYNTHETIC", + renderer = renderer, + isGrassCell = function() + return false + end, + }, + neighbors = {}, + ghosts = {}, + entities = {}, + gen4Shadows = false, + waterAnim = { x = 1, y = 1, frames = 12, total = 40 }, + ripples = { { px = 15, py = 31, clock = 0 } }, + }, { __index = World }) + for i = 1, count or 3 do + local e = { + px = i * 16, + py = i * 16, + cellX = i, + cellY = i, + facing = "down", + above = i % 7 == 0, + draw = function(self, cx, cy) + mark("entity", self.cellX, cx, cy) + end, + drawReflection = function(self, cx, cy) + mark("reflection", self.cellX, cx, cy) + end, + } + world.entities[i] = e + end + world.player = world.entities[1] + world.reflectionSearch = function(_, e) + return e.cellX % 2 == 0 and { { e.cellX, e.cellY + 1 } } or nil + end + world.stillReflection = function() + return false + end + world.reflectionRect = function(_, e) + return e.cellX, e.cellY + 1, e.cellX + 1, e.cellY + 2 + end + world.gen3AboveTopLayer = function(_, e) + return e.above + end + world.drawRipples = function(_, cx, cy) + mark("ripples", cx, cy) + end + world.drawGen3Gates = function() + mark("gates") + end + world.drawGen3Flash = function() + mark("flash") + end + world.drawGen3Decorate = function() + mark("decoration") + end + world.placeFreeCamera = function() end + world.reflectProbe, world.reflectProbe2 = 1, 1 + Game.renderer = { + worldViewSize = function() + return 160, 144 + end, + fitScale = function() + return 1 + end, + setWorldOverride = function() end, + } + return { + world = world, + game = Game, + trace = function() + return trace + end, + reset = function() + trace = {} + end, + mark = mark, + } +end +return F diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py index 2f8a694a6..a46da9de5 100644 --- a/tools/check_frame_pacing.py +++ b/tools/check_frame_pacing.py @@ -17,6 +17,7 @@ def main(): workload = parser.add_mutually_exclusive_group() workload.add_argument('--gc', action='store_true', help='compare fixed-step GC with the P2 idle budget') workload.add_argument('--hot-path', action='store_true', help='compare actual native update/draw dependency dispatch') + workload.add_argument('--world-draw', action='store_true', help='compare native world entity/FX dispatch over synthetic content') args = parser.parse_args() root = Path(__file__).resolve().parents[1] sys.path.insert(0, str(args.qa_tools or root / 'tools')) @@ -34,6 +35,11 @@ def main(): if args.hot_path: files += ('src/core/Game.lua', 'src/core/HotModules.lua', 'src/core/Performance.lua', 'src/render/Renderer.lua', 'src/render/PaletteFX.lua', 'tools/frame-pacing-check/hot.lua') + if args.world_draw: + files += ('src/core/Game.lua', 'src/core/Performance.lua', 'src/core/HotModules.lua', + 'src/world/OverworldController.lua', 'src/render/Renderer.lua', + 'src/render/PaletteFX.lua', 'src/render/Pipelines.lua', + 'tests/world_draw/fixture.lua', 'tools/frame-pacing-check/world.lua') hashes = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} source = qa_run(['git', 'rev-parse', 'HEAD'], cwd=root, text=True, capture_output=True, check=True).stdout.strip() @@ -45,10 +51,11 @@ def main(): cwd=root, env=dict(os.environ, POKEPORT_IDENTITY=identity, FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1', FRAME_PACING_GC='1' if args.gc else '0', - FRAME_PACING_HOT='1' if args.hot_path else '0'), + FRAME_PACING_HOT='1' if args.hot_path else '0', + FRAME_PACING_WORLD='1' if args.world_draw else '0'), capture_output=True, text=True, timeout=90) args.report.with_suffix('.log').write_text(result.stdout + result.stderr) - prefix = 'P3_NATIVE_RESULT ' if args.hot_path else 'P2_NATIVE_RESULT ' if args.gc else 'P1_NATIVE_RESULT ' + prefix = 'P4_NATIVE_RESULT ' if args.world_draw else 'P3_NATIVE_RESULT ' if args.hot_path else 'P2_NATIVE_RESULT ' if args.gc else 'P1_NATIVE_RESULT ' records = [line.removeprefix(prefix) for line in result.stdout.splitlines() if line.startswith(prefix)] if result.returncode or len(records) != 1: raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) diff --git a/tools/frame-pacing-check/main.lua b/tools/frame-pacing-check/main.lua index 282369558..8f689eaf0 100644 --- a/tools/frame-pacing-check/main.lua +++ b/tools/frame-pacing-check/main.lua @@ -12,6 +12,10 @@ if os.getenv("FRAME_PACING_HOT") == "1" then require("tools.frame-pacing-check.hot") return end +if os.getenv("FRAME_PACING_WORLD") == "1" then + require("tools.frame-pacing-check.world") + return +end local Cap = require("src.core.FrameCap") local Profile = require("src.core.FrameProfile") local Json = require("src.link.Json") diff --git a/tools/frame-pacing-check/world.lua b/tools/frame-pacing-check/world.lua new file mode 100644 index 000000000..6b4bd3ff5 --- /dev/null +++ b/tools/frame-pacing-check/world.lua @@ -0,0 +1,138 @@ +local Version = require("src.core.GameVersion") +Version.set("red") +local Renderer = require("src.render.Renderer") +local Performance = require("src.core.Performance") +local Cap = require("src.core.FrameCap") +local Profile = require("src.core.FrameProfile") +local Json = require("src.link.Json") +local scene = require("tests.world_draw.fixture").new(64, { quiet = true }) +local world, graphics = scene.world, love.graphics +scene.game.renderer = Renderer +Renderer:init() +world.map.renderer.drawBorderFill = function(_, cx, cy, w, h) + graphics.setColor(0.2, 0.4, 0.5, 1) + graphics.rectangle("fill", 0, 0, w, h) +end +world.map.renderer.draw = function() + graphics.setColor(0.3, 0.5, 0.4, 1) + for y = 0, 8 do + for x = 0, 9 do + graphics.rectangle("fill", x * 16, y * 16, 14, 14) + end + end +end +world.map.renderer.drawReflectionCover = function(_, cx, cy, camX, camY) + graphics.setColor(0.2, 0.4, 0.5, 0.3) + graphics.rectangle("fill", cx * 16 - camX, cy * 16 - camY, 16, 16) +end +for i, e in ipairs(world.entities) do + e.px, e.py = (i % 10) * 16, math.floor(i / 10) * 16 + e.cellX, e.cellY = math.floor(e.px / 16), math.floor(e.py / 16) + e.draw = function(actor, cx, cy) + graphics.setColor(0.8, 0.3, 0.2, 1) + graphics.rectangle("fill", actor.px - cx, actor.py - cy, 8, 12) + end + e.drawReflection = function(actor, cx, cy) + graphics.setColor(0.8, 0.3, 0.2, 0.5) + graphics.rectangle("fill", actor.px - cx, actor.py - cy + 16, 8, 12) + end +end +local phase, frame, deadline, started, cpuStarted = 1, 0, 0, 0, 0 +local WINDOW, WARMUP = 120, 120 +local drawTotal, drawMax, protectedCalls, heapStart = 0, 0, 0, 0 +local results = {} +local _, _, mode = love.window.getMode() +Cap.current = tonumber(mode.refreshrate) or 60 +if Cap.current <= 0 then + Cap.current = 60 +end +Cap.vsyncPacing = true +local function draw() + local close = Profile.section("draw: whole frame") + Renderer:beginFrame(true) + Renderer:beginWorldPass() + world:drawWorld() + Renderer:endWorldPass() + Renderer:endFrame() + close() + Profile.frame() +end +local function startPhase() + Profile.setEnabled(false) + Performance.worldDrawHoist = phase == 2 + collectgarbage("restart") + frame, drawTotal, drawMax = 0, 0, 0 + deadline = love.timer.getTime() +end +local function finishPhase() + results[phase] = { + enabled = Performance.worldDrawHoist, + frames = WINDOW, + seconds = love.timer.getTime() - started, + drawMeanMs = drawTotal / WINDOW * 1000, + drawMaxMs = drawMax * 1000, + processCpuMsPerFrame = (os.clock() - cpuStarted) / WINDOW * 1000, + protectedCalls = protectedCalls, + heapGrowthKiB = collectgarbage("count") - heapStart, + } + collectgarbage("restart") + if phase == 2 then + print( + "P4_NATIVE_RESULT " + .. Json.encode({ + os = love.system.getOS(), + arch = jit and jit.arch or "unknown", + renderer = graphics.getRendererInfo(), + refresh = mode.refreshrate, + vsync = love.window.getVSync(), + cap = Cap.current, + entities = #world.entities, + phases = results, + scope = "Native drawWorld/entity/reflection/FX loops with synthetic 64-actor rectangles; no ROM assets or mod scene; GC stopped during each measured window", + }) + ) + return true + end + phase = 2 + startPhase() +end +function love.run() + startPhase() + return function() + love.event.pump() + for name in love.event.poll() do + if name == "quit" then + return 1 + end + end + if frame == WARMUP then + local original = pcall + protectedCalls = 0 + _G.pcall = function(...) + protectedCalls = protectedCalls + 1 + return original(...) + end + draw() + _G.pcall = original + collectgarbage("collect") + collectgarbage("stop") + Profile.setEnabled(true) + heapStart = collectgarbage("count") + started, cpuStarted = love.timer.getTime(), os.clock() + end + local before = love.timer.getTime() + draw() + if frame >= WARMUP then + local elapsed = love.timer.getTime() - before + drawTotal, drawMax = drawTotal + elapsed, math.max(drawMax, elapsed) + end + local close = Profile.section("present (GPU wait / vsync)") + graphics.present() + close() + deadline = Cap.pace(love.timer, love.window, true, deadline) + frame = frame + 1 + if frame == WARMUP + WINDOW and finishPhase() then + return 0 + end + end +end From 28e158fd17d2213ff918aea81128b07dba34f2aa Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 04:21:29 +0100 Subject: [PATCH 09/19] perf(P5): cache native palette vectors and pixel-aligned zone geometry --- docs/palette-zone-cache.md | 65 +++++++ src/core/Performance.lua | 2 + src/render/PaletteFX.lua | 75 ++++++++ src/render/Renderer.lua | 86 +++++++++- tests/engine/palette_zone_cache.lua | 157 +++++++++++++++++ tools/check_frame_pacing.py | 10 +- tools/frame-pacing-check/main.lua | 4 + tools/frame-pacing-check/palette.lua | 246 +++++++++++++++++++++++++++ 8 files changed, 641 insertions(+), 4 deletions(-) create mode 100644 docs/palette-zone-cache.md create mode 100644 tests/engine/palette_zone_cache.lua create mode 100644 tools/frame-pacing-check/palette.lua diff --git a/docs/palette-zone-cache.md b/docs/palette-zone-cache.md new file mode 100644 index 000000000..912434625 --- /dev/null +++ b/docs/palette-zone-cache.md @@ -0,0 +1,65 @@ +# P5: palette uploads and cropped zone quads + +`Performance.paletteZoneCache` defaults to `true`; set it to `false` to restore +four fresh uniform vectors per zone and the original full-canvas/scissor blit. +This switch is independent of P1–P4. + +Native uploads compute effective palette row indices without allocating the +intermediate inverted/shade-mapped palette tables. The public `effectiveColors` +and `permute` methods retain their existing return shape/identity behavior. +The names `c0`, `c1`, `c2`, `c3` remain unchanged; no uniform packing is introduced. + +Each shader has a weakly held private last-value record and four reusable +vectors. All twelve normalized floats are compared; only changed rows are sent +inside one contiguous native blit. Every later blit starts with a full upload, +so direct raw shader writes between blits cannot leave stale colors. Public +`sendColors` calls always upload. Custom table send providers still receive fresh +vectors. Replacing public palette methods, graphics draw or shader dispatch +disables batch assumptions and preserves the original call seam. + +The native nearest-filtered texture path uses one private cached Quad with +`setViewport`, clipped to the source canvas and the old pixel coverage. It is +limited to identity transforms, positive whole-framebuffer-pixel magnification +and origins, matching X/Y target DPI and nonnegative clipping boxes. Fractional +zoom/origins, flipped/scaled/rotated views, anisotropic DPI, linear filtering, +high-DPI source textures and compound render targets use the original path. +LÖVE 12 additionally requires target DPI 1/2/4 for exact half-pixel rounding. +Zones and their palettes are never changed or pooled. + +LÖVE 11 truncates logical scissor arguments before DPI conversion; LÖVE 12 uses +float arguments and rounds physical scissor values. The crop deliberately +matches the existing behavior in each supported path. Primary API/backend +sources: [11.5 Lua API](https://github.com/love2d/love/blob/11.5/src/modules/graphics/wrap_Graphics.cpp#L524), +[11.5 backend](https://github.com/love2d/love/blob/11.5/src/modules/graphics/opengl/Graphics.cpp#L968), +[12 Lua API](https://github.com/love2d/love/blob/main/src/modules/graphics/wrap_Graphics.cpp), +[12 Metal backend](https://github.com/love2d/love/blob/main/src/modules/graphics/metal/Graphics.mm). + +The guarded `tools/check_frame_pacing.py --palette-zones --love /path/to/love +--report /owned/qa/palette.json` first compares actual GPU readbacks byte for +byte. Each backend passes 432 cases across Red/Gold, four display modes, +shade-register remapping, overlapping/true-color zones, clipping, transforms, +three target densities, fractional origins/zoom and source filtering/density. +OpenGL exercises 48 optimized and 384 fallback cases; Metal 16 optimized and +416 fallback cases. First versions of the crop failed these tests and were +restricted/corrected before qualification. Uniform behavior has 491 focused +checks, including in-place palette mutations, raw shader writes between blits, +public wrappers and fresh consumer-owned vectors. + +The timed workload draws 96 equal-palette zones over owned generated source +pixels, with 120 warm-up + 120 measured frames per switch phase, macOS arm64, +60 Hz/VSync 1. GC is stopped during each measured window to expose allocation +growth, then restarted. Heap growth includes host/profiler work and is not +retained memory or a leak measurement. Shader:send calls fall from 384 to four +per contiguous identical-palette blit; later blits still resynchronize. + +| Tree / backend | F11 zone blit, ms/frame | Raw draw mean, ms | CPU, ms/frame | Heap growth / 120 frames, KiB | +| --- | ---: | ---: | ---: | ---: | +| Fork / LÖVE 11.5 OpenGL | 0.34 → 0.42 | 0.358 → 0.451 | 0.956 → 1.210 | 4368 → 49 | +| Fork / LÖVE 12 Metal | 16.39 → 16.40 | 16.397 → 16.407 | 0.630 → 0.613 | 4369 → 49 | +| Public adaptation / LÖVE 11.5 OpenGL | 0.41 → 0.22 | 0.445 → 0.243 | 0.968 → 0.705 | 4368 → 49 | +| Public adaptation / LÖVE 12 Metal | 16.37 → 16.35 | 16.376 → 16.364 | 0.759 → 0.735 | 4368 → 49 | + +Timing/CPU results are mixed across short runs; no general FPS/CPU gain is +established. Metal queue submission can include GPU/VSync waiting. Full-game, +Android, dedicated ARM handheld and long session: not measured. Reports retain +the exact measured source fingerprints and raw F11 logs. diff --git a/src/core/Performance.lua b/src/core/Performance.lua index c7bd61b1a..8e42d3b93 100644 --- a/src/core/Performance.lua +++ b/src/core/Performance.lua @@ -49,6 +49,8 @@ Performance.gcBudget = true Performance.hotPathHoist = true -- P4: independent world-draw closure, list and protection optimization. Performance.worldDrawHoist = true +-- P5: palette upload batching and cropped zone quads. +Performance.paletteZoneCache = true Performance.GC_PAUSE = 120 Performance.GC_STEP_MUL = 300 Performance.GC_BUDGET_SECONDS = 0.0005 diff --git a/src/render/PaletteFX.lua b/src/render/PaletteFX.lua index 731d74675..aa85b113a 100644 --- a/src/render/PaletteFX.lua +++ b/src/render/PaletteFX.lua @@ -21,6 +21,9 @@ local GameVersion = require("src.core.GameVersion") local HotModules = require("src.core.HotModules") +local Performance = require("src.core.Performance") +local nativeDraw = love and love.graphics and love.graphics.draw +local nativeSetShader = love and love.graphics and love.graphics.setShader local PaletteFX = {} @@ -1182,7 +1185,60 @@ end -- send a 4-color (0-255 RGB) palette to the shade-remap shader, after -- applying the active COLORS display mode +local nativeEffectiveColors, nativePermute = PaletteFX.effectiveColors, PaletteFX.permute +local _uniforms = setmetatable({}, {__mode="k"}) +local UNIFORM_NAMES = {"c0", "c1", "c2", "c3"} + +-- Native upload code resolves rows by index, never by a borrowed public palette. +local function effectiveSource(c) + if PaletteFX.effectiveColors ~= nativeEffectiveColors or PaletteFX.permute ~= nativePermute then + return PaletteFX.effectiveColors(c), 1, 2, 3, 4 + end + if not c then return nil end + local mode = gen2Native() and "gbc" or PaletteFX.mode or "gbc" + local reverse = mode == "og_inv" or mode == "gbc_inv" + if mode == "og" or mode == "og_inv" then c = PaletteFX.GRAYS + elseif mode == "classic" then c = PaletteFX.CLASSIC end + local a, b, d, e = 1, 2, 3, 4 + if shadeMap then a,b,d,e = shadeMap[0]+1,shadeMap[1]+1,shadeMap[2]+1,shadeMap[3]+1 end + if reverse then a,b,d,e = 5-a,5-b,5-d,5-e end + return c, a, b, d, e +end +local function uniformState(shader) + local state = _uniforms[shader] + if not state then + state = {rows={{},{},{},{}}} + _uniforms[shader] = state + end + return state +end +local function uploadRow(shader, state, index, color, force) + local row = state.rows[index] + local r,g,b = color[1]/255,color[2]/255,color[3]/255 + if force or not state.valid or row[1] ~= r or row[2] ~= g or row[3] ~= b then + row[1],row[2],row[3] = r,g,b + shader:send(UNIFORM_NAMES[index], row) + end +end +local function uploadColors(shader, c, state, force) + local source,a,b,d,e = effectiveSource(c) + if not source then return end + uploadRow(shader,state,1,source[a],force) + uploadRow(shader,state,2,source[b],force) + uploadRow(shader,state,3,source[d],force) + uploadRow(shader,state,4,source[e],force) + state.valid = true +end +local function nativeShader(shader) + return type(shader) == "userdata" and shader.typeOf and shader:typeOf("Shader") +end + +-- A caller can write raw shader uniforms between public calls. Each public +-- call therefore uploads unconditionally. Reused vectors stay inside LÖVE. function PaletteFX.sendColors(shader, c) + if Performance.paletteZoneCache and nativeShader(shader) then + return uploadColors(shader, c, uniformState(shader), true) + end c = PaletteFX.effectiveColors(c) if not c then return end shader:send("c0", { c[1][1] / 255, c[1][2] / 255, c[1][3] / 255 }) @@ -1190,5 +1246,24 @@ function PaletteFX.sendColors(shader, c) shader:send("c2", { c[3][1] / 255, c[3][2] / 255, c[3][3] / 255 }) shader:send("c3", { c[4][1] / 255, c[4][2] / 255, c[4][3] / 255 }) end +PaletteFX._nativeSendColors = PaletteFX.sendColors + +-- Cache validity is limited to one contiguous native blit. There are no mod +-- callbacks between its zones; every later blit starts with a full upload. +function PaletteFX._beginColorBatch(shader) + if not Performance.paletteZoneCache or not nativeShader(shader) + or PaletteFX.effectiveColors ~= nativeEffectiveColors or PaletteFX.permute ~= nativePermute + or love.graphics.draw ~= nativeDraw or love.graphics.setShader ~= nativeSetShader then return nil end + local state = uniformState(shader) + if state.busy then state = {rows={{},{},{},{}}} end + state.valid, state.busy = false, true + return state +end +function PaletteFX._sendColorsInBatch(shader, c, state) + return uploadColors(shader, c, state, false) +end +function PaletteFX._endColorBatch(state) + if state then state.busy = nil end +end return PaletteFX diff --git a/src/render/Renderer.lua b/src/render/Renderer.lua index da0b3754c..391e05581 100644 --- a/src/render/Renderer.lua +++ b/src/render/Renderer.lua @@ -683,6 +683,76 @@ local function withTrueColor(zoneList, pass) return merged end +-- Cropped zone geometry is equivalent only on a native nearest-filtered, +-- pixel-density-matched, untransformed target. Public unusual layouts keep +-- their established scissor path (including flips and anisotropic DPI). +local rasterMajor = love and love.getVersion and love.getVersion() or 11 +local function wholePixel(value) + return math.abs(value - math.floor(value + 0.5)) <= 1e-7 +end +local function truncate(value) + return value < 0 and math.ceil(value) or math.floor(value) +end +local function zonePixelSpan(first, last, density) + local lo,hi = math.floor(first*density),math.ceil(last*density) + if rasterMajor < 12 then + -- The 11.x Lua API truncates logical scissor arguments before DPI conversion. + local left = truncate(truncate((lo+0.5)/density)*density) + local width = truncate(truncate((hi-lo+0.5)/density)*density) + return left/density,(left+width)/density + end + -- 12.x rounds float scissor values. This path is used only for power-of-two + -- DPI so the existing half-pixel padding is exactly representable. + return (lo+1)/density,(hi+2)/density +end +local function zoneQuad(self, canvas, sx, sy, bx, by, dpiX, dpiY) + if not Performance.paletteZoneCache or type(canvas) ~= "userdata" or not canvas.typeOf + or not (canvas:typeOf("Canvas") or canvas:typeOf("Texture")) + or sx <= 0 or sy <= 0 then return nil end + if not canvas.getDPIScale or canvas:getDPIScale() ~= 1 then return nil end + if not canvas.getFilter or canvas:getFilter() ~= "nearest" then return nil end + local g = love.graphics + if not (g.newQuad and g.transformPoint) then return nil end + local target = g.getCanvas() + if target and type(target) ~= "userdata" then return nil end + local density = target and target.getDPIScale and target:getDPIScale() or g.getDPIScale() + if math.abs(density - (dpiX or 1)) > 1e-7 or math.abs(density - (dpiY or 1)) > 1e-7 then return nil end + -- Fractional magnification/origins can put sample centres exactly on a + -- texel boundary. Cropping then changes floating-point tie rounding. + if not (wholePixel(sx*density) and wholePixel(sy*density) + and wholePixel(bx*density) and wholePixel(by*density)) then return nil end + if rasterMajor >= 12 and density ~= 1 and density ~= 2 and density ~= 4 then return nil end + local x0,y0 = g.transformPoint(0,0) + local xx,xy = g.transformPoint(1,0) + local yx,yy = g.transformPoint(0,1) + if x0 ~= 0 or y0 ~= 0 or xx ~= 1 or xy ~= 0 or yx ~= 0 or yy ~= 1 then return nil end + local quad = self._zoneQuad + if not quad then + local w,h = canvas:getDimensions() + quad = g.newQuad(0,0,w,h,w,h) + self._zoneQuad = quad + end + return quad +end +function Renderer:_drawZoneQuad(quad, canvas, sx, sy, zoneSx, zoneSy, bx, by, + boxX, boxY, boxW, boxH, dpiX, dpiY, z) + local x,y = bx + z.x*zoneSx, by + z.y*zoneSy + local x2,y2 = math.min(x+z.w*zoneSx,boxX+boxW),math.min(y+z.h*zoneSy,boxY+boxH) + x,y = math.max(x,boxX),math.max(y,boxY) + if x2 <= x or y2 <= y then return false end + dpiX,dpiY = dpiX or 1,dpiY or 1 + -- The old scissor rounds starts down and ends up in physical pixels. + x,x2 = zonePixelSpan(x,x2,dpiX) + y,y2 = zonePixelSpan(y,y2,dpiY) + local cw,ch = canvas:getDimensions() + local qx,qy = math.max(0,(x-bx)/sx),math.max(0,(y-by)/sy) + local qx2,qy2 = math.min(cw,(x2-bx)/sx),math.min(ch,(y2-by)/sy) + if qx2 <= qx or qy2 <= qy then return false end + quad:setViewport(qx,qy,qx2-qx,qy2-qy,cw,ch) + love.graphics.draw(canvas,quad,bx+qx*sx,by+qy*sy,0,sx,sy) + return true +end + -- Palette-correct blit of `canvas` at (sx, sy) LOVE-unit scales into origin -- (bx, by), scissored to the (boxX, boxY, boxW, boxH) screen rect. zoneSx/ -- zoneSy convert zone coords (canvas-space) into screen units. Public so a @@ -699,9 +769,14 @@ function Renderer:blitCanvas(canvas, sx, sy, zoneList, zoneSx, zoneSy, return end love.graphics.setShader(shader) + local colorBatch = PaletteFX.sendColors == PaletteFX._nativeSendColors + and PaletteFX._beginColorBatch(shader) or nil -- a colors == false zone is the trueColor opt-out: its rect draws with -- no shader at all. Nothing sets one without a mod, so a vanilla zone -- list never toggles and issues exactly the calls it always did. + local quad = zoneSx > 0 and zoneSy > 0 and boxX >= 0 and boxY >= 0 + and zoneQuad(self, canvas, sx, sy, bx, by, dpiX, dpiY) or nil + if quad then love.graphics.setScissor() end local bare = false for _, z in ipairs(zoneList) do local plain = z.colors == false @@ -709,8 +784,14 @@ function Renderer:blitCanvas(canvas, sx, sy, zoneList, zoneSx, zoneSy, bare = plain love.graphics.setShader(not plain and shader or nil) end - if not plain then PaletteFX.sendColors(shader, z.colors) end - if scissorClamped(bx + z.x * zoneSx, by + z.y * zoneSy, + if not plain then + if colorBatch then PaletteFX._sendColorsInBatch(shader, z.colors, colorBatch) + else PaletteFX.sendColors(shader, z.colors) end + end + if quad then + self:_drawZoneQuad(quad, canvas, sx, sy, zoneSx, zoneSy, bx, by, + boxX, boxY, boxW, boxH, dpiX, dpiY, z) + elseif scissorClamped(bx + z.x * zoneSx, by + z.y * zoneSy, z.w * zoneSx, z.h * zoneSy, boxX, boxY, boxW, boxH, dpiX, dpiY) then love.graphics.draw(canvas, bx, by, 0, sx, sy) @@ -718,6 +799,7 @@ function Renderer:blitCanvas(canvas, sx, sy, zoneList, zoneSx, zoneSy, end love.graphics.setScissor() love.graphics.setShader() + PaletteFX._endColorBatch(colorBatch) closeBlit() end diff --git a/tests/engine/palette_zone_cache.lua b/tests/engine/palette_zone_cache.lua new file mode 100644 index 000000000..de520e464 --- /dev/null +++ b/tests/engine/palette_zone_cache.lua @@ -0,0 +1,157 @@ +local T = require("tests.harness") +love = require("tests.love_stub") +local Version = require("src.core.GameVersion") +local Performance = require("src.core.Performance") +local P = require("src.render.PaletteFX") +local Renderer = require("src.render.Renderer") +local base = { { 255, 240, 220 }, { 180, 150, 120 }, { 80, 50, 30 }, { 5, 3, 1 } } +local function shader() + local records = {} + local methods = { + typeOf = function(_, kind) + return kind == "Shader" + end, + send = function(_, name, value) + records[#records + 1] = { name, { value[1], value[2], value[3] }, value } + end, + } + local object = methods + if newproxy then + object = newproxy(true) + getmetatable(object).__index = methods + end + return object, records +end +for _, version in ipairs({ "red", "gold" }) do + Version.set(version) + for _, mode in ipairs(P.MODES) do + P.mode = mode + for _, map in ipairs({ false, { [0] = 0, [1] = 3, [2] = 1, [3] = 2 } }) do + P.setShadeMap(map or nil) + local expected = P.effectiveColors(base) + local sh, records = shader() + local state = { rows = { {}, {}, {}, {} } } + P._sendColorsInBatch(sh, base, state) + for i = 1, 4 do + T.eq(records[i][1], "c" .. (i - 1), "uniform names remain unchanged") + for channel = 1, 3 do + T.eq(records[i][2][channel], expected[i][channel] / 255, version .. "/" .. mode .. " row mapping") + end + end + P._sendColorsInBatch(sh, base, state) + T.eq(#records, 4, "unchanged twelve floats skip redundant uploads") + end + end +end +Version.set("red") +P.mode = "gbc" +P.setShadeMap(nil) +local sh, records = shader() +local state = { rows = { {}, {}, {}, {} } } +P._sendColorsInBatch(sh, base, state) +base[2][1] = 181 +P._sendColorsInBatch(sh, base, state) +T.eq(#records, 5, "in-place palette mutation invalidates the affected row") +T.eq(records[5][1], "c1", "only changed row is uploaded") +local custom = P.effectiveColors +P.effectiveColors = function(c) + return { c[4], c[3], c[2], c[1] } +end +P._sendColorsInBatch(sh, base, state) +T.eq(records[#records][2][1], base[1][1] / 255, "public effectiveColors override is honored") +P.effectiveColors = custom +local oldPermute = P.permute +P.permute = function(c) + return { c[4], c[3], c[2], c[1] } +end +P._sendColorsInBatch(sh, base, state) +T.eq(records[#records][2][1], base[1][1] / 255, "public permute override is honored") +P.permute = oldPermute +local plain, plainRecords = shader() +Performance.paletteZoneCache = true +P.sendColors(plain, base) +P.sendColors(plain, base) +T.eq(#plainRecords, 8, "public calls always resend after possible external shader writes") +local fake = { + send = function(self, name, value) + self[#self + 1] = value + end, +} +P.sendColors(fake, base) +P.sendColors(fake, base) +T.check(fake[1] ~= fake[5], "consumer-provided send callbacks retain fresh public vectors") +local shaderFactory = P.shader +P.shader = function() + return sh +end +local zones = { + { x = 0, y = 0, w = 16, h = 16, colors = base }, + { x = 0, y = 0, w = 16, h = 16, colors = base }, + { + x = 0, + y = 0, + w = 16, + h = 16, + colors = base, + }, +} +local canvas = love.graphics.newCanvas(16, 16) +local function blit() + Renderer:blitCanvas(canvas, 1, 1, zones, 1, 1, 0, 0, 0, 0, 16, 16, 1, 1) +end +records = {} +local count = 0 +local sender = P.sendColors +P.sendColors = function(...) + count = count + 1 + return sender(...) +end +blit() +T.eq(count, 3, "public sendColors wrapper is still called for every original zone") +P.sendColors = sender +local real, sent = shader() +P.shader = function() + return real +end +Performance.paletteZoneCache = true +blit() +local perBlit = newproxy and 4 or 12 +T.eq(#sent, perBlit, "native contiguous blit skips repeated rows only on real shader-shaped userdata") +real:send("c0", { 0.4, 0.5, 0.6 }) +blit() +T.eq(#sent, perBlit * 2 + 1, "new blit resets validity after external raw shader writes") +T.same( + sent[perBlit + 2][2], + { base[1][1] / 255, base[1][2] / 255, base[1][3] / 255 }, + "first upload restores the native palette" +) +Performance.paletteZoneCache = false +local before = #sent +blit() +T.eq(#sent - before, 12, "P5 off restores four sends for every zone") +Performance.paletteZoneCache = true +local oldDraw = love.graphics.draw +love.graphics.draw = function(...) + return oldDraw(...) +end +before = #sent +blit() +T.eq(#sent - before, 12, "a graphics callback override disables cache assumptions") +love.graphics.draw = oldDraw +P.shader = shaderFactory +local q = { + setViewport = function(self, ...) + self.viewport = { ... } + end, +} +local draw = love.graphics.draw +local drawn +love.graphics.draw = function(...) + drawn = { ... } +end +Renderer:_drawZoneQuad(q, canvas, 2, 2, 2, 2, 0, 0, 3, 5, 20, 20, 1, 1, { x = 0, y = 0, w = 16, h = 16 }) +T.same(q.viewport, { 1.5, 2.5, 10, 10, 16, 16 }, "quad viewport crops source coordinates to the original clip") +T.eq(drawn[3], 3, "cropped quad retains horizontal origin mapping") +T.eq(drawn[4], 5, "cropped quad retains vertical origin mapping") +love.graphics.draw = draw +T.finish("palette uploads and zone quads") diff --git a/tools/check_frame_pacing.py b/tools/check_frame_pacing.py index a46da9de5..cbe6b211c 100644 --- a/tools/check_frame_pacing.py +++ b/tools/check_frame_pacing.py @@ -18,6 +18,7 @@ def main(): workload.add_argument('--gc', action='store_true', help='compare fixed-step GC with the P2 idle budget') workload.add_argument('--hot-path', action='store_true', help='compare actual native update/draw dependency dispatch') workload.add_argument('--world-draw', action='store_true', help='compare native world entity/FX dispatch over synthetic content') + workload.add_argument('--palette-zones', action='store_true', help='verify native zone pixels and compare palette upload batching') args = parser.parse_args() root = Path(__file__).resolve().parents[1] sys.path.insert(0, str(args.qa_tools or root / 'tools')) @@ -40,6 +41,10 @@ def main(): 'src/world/OverworldController.lua', 'src/render/Renderer.lua', 'src/render/PaletteFX.lua', 'src/render/Pipelines.lua', 'tests/world_draw/fixture.lua', 'tools/frame-pacing-check/world.lua') + if args.palette_zones: + files += ('src/core/Performance.lua', 'src/core/HotModules.lua', + 'src/render/Renderer.lua', 'src/render/PaletteFX.lua', + 'tools/frame-pacing-check/palette.lua') hashes = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in files} source = qa_run(['git', 'rev-parse', 'HEAD'], cwd=root, text=True, capture_output=True, check=True).stdout.strip() @@ -52,10 +57,11 @@ def main(): FRAME_PACING_REPO=str(root), FRAME_PACING_QA_GUARDED='1', FRAME_PACING_GC='1' if args.gc else '0', FRAME_PACING_HOT='1' if args.hot_path else '0', - FRAME_PACING_WORLD='1' if args.world_draw else '0'), + FRAME_PACING_WORLD='1' if args.world_draw else '0', + FRAME_PACING_PALETTE='1' if args.palette_zones else '0'), capture_output=True, text=True, timeout=90) args.report.with_suffix('.log').write_text(result.stdout + result.stderr) - prefix = 'P4_NATIVE_RESULT ' if args.world_draw else 'P3_NATIVE_RESULT ' if args.hot_path else 'P2_NATIVE_RESULT ' if args.gc else 'P1_NATIVE_RESULT ' + prefix = 'P5_NATIVE_RESULT ' if args.palette_zones else 'P4_NATIVE_RESULT ' if args.world_draw else 'P3_NATIVE_RESULT ' if args.hot_path else 'P2_NATIVE_RESULT ' if args.gc else 'P1_NATIVE_RESULT ' records = [line.removeprefix(prefix) for line in result.stdout.splitlines() if line.startswith(prefix)] if result.returncode or len(records) != 1: raise RuntimeError('native pacing probe failed; see ' + str(args.report.with_suffix('.log'))) diff --git a/tools/frame-pacing-check/main.lua b/tools/frame-pacing-check/main.lua index 8f689eaf0..83722749e 100644 --- a/tools/frame-pacing-check/main.lua +++ b/tools/frame-pacing-check/main.lua @@ -16,6 +16,10 @@ if os.getenv("FRAME_PACING_WORLD") == "1" then require("tools.frame-pacing-check.world") return end +if os.getenv("FRAME_PACING_PALETTE") == "1" then + require("tools.frame-pacing-check.palette") + return +end local Cap = require("src.core.FrameCap") local Profile = require("src.core.FrameProfile") local Json = require("src.link.Json") diff --git a/tools/frame-pacing-check/palette.lua b/tools/frame-pacing-check/palette.lua new file mode 100644 index 000000000..8bc00e13c --- /dev/null +++ b/tools/frame-pacing-check/palette.lua @@ -0,0 +1,246 @@ +local Version = require("src.core.GameVersion") +local Performance = require("src.core.Performance") +local Renderer = require("src.render.Renderer") +local Palette = require("src.render.PaletteFX") +local Profile = require("src.core.FrameProfile") +local Cap = require("src.core.FrameCap") +local Json = require("src.link.Json") +local g = love.graphics +local colors = { { 255, 230, 200 }, { 180, 120, 80 }, { 50, 100, 150 }, { 5, 10, 15 } } +local other = { { 210, 240, 180 }, { 110, 160, 90 }, { 20, 70, 120 }, { 0, 0, 0 } } +local pixels = love.image.newImageData(32, 24) +pixels:mapPixel(function(x, y) + local shade = (math.floor(x / 2) + math.floor(y / 3)) % 4 / 3 + return shade, shade, shade, (x + y) % 7 == 0 and 0.5 or 1 +end) +local image = g.newImage(pixels) +image:setFilter("nearest", "nearest") +local function makeSource(density, filter) + local source = g.newCanvas(32, 24, { dpiscale = density }) + source:setFilter(filter or "nearest", filter or "nearest") + g.setCanvas(source) + g.origin() + g.clear(0, 0, 0, 0) + g.setColor(1, 1, 1, 1) + g.setBlendMode("replace") + g.draw(image) + g.setBlendMode("alpha") + return source +end +local source = makeSource(1) +local highSource = makeSource(2) +local linearSource = makeSource(1, "linear") +local zones = { + { x = 0, y = 0, w = 32, h = 8, colors = colors }, + { x = 0, y = 8, w = 32, h = 8, colors = colors }, + { x = 0, y = 16, w = 32, h = 8, colors = colors }, + { x = 5.2, y = 4.1, w = 15.6, h = 10.7, colors = other }, + { x = 10.5, y = 9.5, w = 5.2, h = 7.3, colors = false }, + { x = -3, y = -4, w = 8, h = 6, colors = colors }, + { x = 30, y = 21, w = 8, h = 6, colors = colors }, +} +local checked, quadCases, fallbackCases = 0, 0, 0 +local cases = {} +for _, density in ipairs({ 1, 1.25, 2.625 }) do + for _, scale in ipairs({ 1, 1.75, 2.625 }) do + for _, origin in ipairs({ 0, 3.2 }) do + cases[#cases + 1] = { density = density, scale = scale, x = origin, y = origin + 1.1 } + end + end +end +for _, kind in ipairs({ "anisotropic", "translate", "rotate", "highSource", "linearSource", "flip" }) do + cases[#cases + 1] = { density = 1.25, scale = 1.75, x = 3.2, y = 4.1, kind = kind } +end +for _, density in ipairs({ 1, 1.25, 2.625 }) do + cases[#cases + 1] = { density = density, scale = 3 / density, x = 2 / density, y = 3 / density } +end +local originalShader = Palette.shader +local function pixelChecks() + for _, version in ipairs({ "red", "gold" }) do + Version.set(version) + for _, mode in ipairs({ "gbc", "gbc_inv", "og_inv", "classic" }) do + Palette.mode = mode + for _, shade in ipairs({ false, { [0] = 2, [1] = 3, [2] = 3, [3] = 3 } }) do + Palette.setShadeMap(shade or nil) + for index, c in ipairs(cases) do + local target = g.newCanvas(96, 80, { dpiscale = c.density }) + local selected = c.kind == "highSource" and highSource + or c.kind == "linearSource" and linearSource + or source + local xScale = c.kind == "flip" and -c.scale or c.scale + local dpiY = c.kind == "anisotropic" and c.density * 1.05 or c.density + local before + local quadCount = 0 + for _, enabled in ipairs({ false, true }) do + Performance.paletteZoneCache = enabled + g.setCanvas(target) + g.origin() + g.clear(0.1, 0.2, 0.3, 1) + g.setColor(1, 1, 1, 1) + if c.kind == "translate" then + g.translate(1.2, 2.3) + end + if c.kind == "rotate" then + g.rotate(0.07) + end + local actualDraw = Renderer._drawZoneQuad + Renderer._drawZoneQuad = function(self, ...) + quadCount = quadCount + 1 + return actualDraw(self, ...) + end + Renderer:blitCanvas( + selected, + xScale, + c.scale, + zones, + c.scale, + c.scale, + c.x, + c.y, + 2.3, + 3.1, + 75.7, + 58.8, + c.density, + dpiY + ) + Renderer._drawZoneQuad = actualDraw + g.setCanvas() + g.origin() + local data = target:newImageData() + local bytes = data:getString() + data:release() + if not enabled then + before = bytes + else + if before ~= bytes then + local changed = 0 + for i = 1, #bytes do + if bytes:byte(i) ~= before:byte(i) then + changed = changed + 1 + end + end + error( + ("zone pixel mismatch %s/%s/shade=%s/case=%d/%s, %d bytes"):format( + version, + mode, + tostring(shade ~= false), + index, + c.kind or "native", + changed + ) + ) + end + end + end + target:release() + checked = checked + 1 + if quadCount > 0 then + quadCases = quadCases + 1 + else + fallbackCases = fallbackCases + 1 + end + end + end + end + end + assert(quadCases > 0 and fallbackCases > 0, "both optimized and compatibility geometry paths must be exercised") + Palette.mode = "gbc" + Palette.setShadeMap(nil) + Version.set("red") +end +local phase, frame, deadline, started, cpuStarted = 1, 0, 0, 0, 0 +local WARMUP, WINDOW = 120, 120 +local drawTotal, drawMax, heapStart = 0, 0, 0 +local results = {} +local _, _, mode = love.window.getMode() +Cap.current = tonumber(mode.refreshrate) or 60 +if Cap.current <= 0 then + Cap.current = 60 +end +Cap.vsyncPacing = true +local repeated = {} +for y = 0, 11 do + for x = 0, 7 do + repeated[#repeated + 1] = { x = x * 4, y = y * 2, w = 4, h = 2, colors = colors } + end +end +local function draw() + g.origin() + g.clear(0.1, 0.2, 0.3, 1) + g.setColor(1, 1, 1, 1) + Renderer:blitCanvas(source, 4, 4, repeated, 4, 4, 32, 32, 32, 32, 128, 96, 1, 1) + Profile.frame() +end +local function startPhase() + Profile.setEnabled(false) + Performance.paletteZoneCache = phase == 2 + collectgarbage("restart") + frame, drawTotal, drawMax = 0, 0, 0 + deadline = love.timer.getTime() +end +local function finishPhase() + results[phase] = { + enabled = Performance.paletteZoneCache, + frames = WINDOW, + seconds = love.timer.getTime() - started, + drawMeanMs = drawTotal / WINDOW * 1000, + drawMaxMs = drawMax * 1000, + processCpuMsPerFrame = (os.clock() - cpuStarted) / WINDOW * 1000, + heapGrowthKiB = collectgarbage("count") - heapStart, + } + collectgarbage("restart") + if phase == 2 then + Palette.shader = originalShader + print("P5_NATIVE_RESULT " .. Json.encode({ + os = love.system.getOS(), + arch = jit and jit.arch or "unknown", + renderer = g.getRendererInfo(), + refresh = mode.refreshrate, + vsync = love.window.getVSync(), + cap = Cap.current, + pixelCases = checked, + quadCases = quadCases, + fallbackCases = fallbackCases, + zones = #repeated, + phases = results, + scope = "Exact GPU pixel comparisons over owned generated source; timed 96-zone native blits; GC stopped in measured windows, no ROM/mod/game scene", + })) + return true + end + phase = 2 + startPhase() +end +function love.run() + pixelChecks() + startPhase() + return function() + love.event.pump() + for name in love.event.poll() do + if name == "quit" then + return 1 + end + end + if frame == WARMUP then + collectgarbage("collect") + collectgarbage("stop") + Profile.setEnabled(true) + heapStart = collectgarbage("count") + started, cpuStarted = love.timer.getTime(), os.clock() + end + local before = love.timer.getTime() + draw() + if frame >= WARMUP then + local elapsed = love.timer.getTime() - before + drawTotal, drawMax = drawTotal + elapsed, math.max(drawMax, elapsed) + end + local close = Profile.section("present (GPU wait / vsync)") + g.present() + close() + deadline = Cap.pace(love.timer, love.window, true, deadline) + frame = frame + 1 + if frame == WARMUP + WINDOW and finishPhase() then + return 0 + end + end +end From 09ce3901249659b908035a9a22048c9448ef8de5 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:20:15 +0200 Subject: [PATCH 10/19] test: align updater fixtures with Gen2 release assets --- tests/engine/update_check_tests.lua | 28 ++++++++++++++++++++------- tests/engine/update_tests.lua | 30 +++++++++++++++++++++-------- 2 files changed, 43 insertions(+), 15 deletions(-) diff --git a/tests/engine/update_check_tests.lua b/tests/engine/update_check_tests.lua index 698c5c9f7..4df8fec72 100644 --- a/tests/engine/update_check_tests.lua +++ b/tests/engine/update_check_tests.lua @@ -13,22 +13,36 @@ local Json = require("src.link.Json") -- releaseUrl is the fixed public landing page the UI links on needs_full eq(Check.releaseUrl(), - "https://github.com/bryanthaboi/gen1recomp/releases/latest", + "https://github.com/UNDERdecoded/Gen2Recomped/releases/latest", "releaseUrl points at the repo's latest release") -- parseRelease: a well-formed release with the .love payload and its sums local body = Json.encode({ tag_name = "v1.4.2", assets = { - { name = "gen1recomp-1.4.2-macos.zip", browser_download_url = "http://x/mac", size = 10 }, - { name = "gen1recomp-1.4.2.love", browser_download_url = "http://x/love", size = 12345 }, + { name = "Gen2Recomped-1.4.2-macos.zip", browser_download_url = "http://x/mac", size = 10 }, + { name = "Gen2Recomped-1.4.2.love", browser_download_url = "http://x/love", size = 12345 }, { name = "sha256sums.txt", browser_download_url = "http://x/sums", size = 99 }, }, }) +-- A same-version Gen1 payload is not a fallback for a missing Gen2 asset. +local foreign = Check.parseRelease(Json.encode({tag_name="v1.4.2", assets={ + {name="gen1recomp-1.4.2.love",browser_download_url="http://x/foreign",size=88}, + {name="Gen2Recomped-1.4.2-macos.zip",browser_download_url="http://x/zip",size=99}, +}})) +check(foreign ~= nil, "a release without a matching game payload still parses") +eq(foreign.payload,nil,"Gen1 and platform archives never substitute for the Gen2 payload") +local competing = Check.parseRelease(Json.encode({tag_name="v1.4.2", assets={ + {name="gen1recomp-1.4.2.love",browser_download_url="http://x/foreign",size=88}, + {name="Gen2Recomped-1.4.2.love",browser_download_url="http://x/correct",size=123}, +}})) +check(competing.payload ~= nil,"exact Gen2 payload wins among same-version assets") +eq(competing.payload and competing.payload.url,"http://x/correct","foreign game asset is ignored even when listed first") + local rel = Check.parseRelease(body) check(rel ~= nil, "parseRelease accepts a valid release") eq(rel.version, "1.4.2", "leading v stripped from tag_name") -eq(rel.payloadName, "gen1recomp-1.4.2.love", "payload name derived from version") +eq(rel.payloadName, "Gen2Recomped-1.4.2.love", "payload name derived from version") eq(rel.payload.url, "http://x/love", "payload asset url picked") eq(rel.payload.size, 12345, "payload asset size picked") eq(rel.sums.url, "http://x/sums", "sums asset url picked") @@ -50,13 +64,13 @@ eq(Check.parseRelease(Json.encode({ foo = 1 })), nil, "missing tag_name rejected -- parseSums: shasum -a 256 format, tolerating the '*' binary marker, a './' -- prefix and CRLF line endings; unrelated lines are skipped local sums = - "aaaa1111 gen1recomp-1.4.2.love\n" .. + "aaaa1111 Gen2Recomped-1.4.2.love\n" .. "BBBB2222 *./sha256sums.txt\r\n" .. "not a checksum line\n" local map = Check.parseSums(sums) -eq(map["gen1recomp-1.4.2.love"], "aaaa1111", "bare-name sum parsed") +eq(map["Gen2Recomped-1.4.2.love"], "aaaa1111", "bare-name sum parsed") eq(map["sha256sums.txt"], "bbbb2222", "* marker and ./ prefix stripped, lowered") -eq(Check.parseSums(sums, "gen1recomp-1.4.2.love"), "aaaa1111", "targeted lookup returns the hash") +eq(Check.parseSums(sums, "Gen2Recomped-1.4.2.love"), "aaaa1111", "targeted lookup returns the hash") eq(Check.parseSums(sums, "missing.love"), nil, "targeted lookup misses cleanly") -- pickAsset guards a non-table assets field diff --git a/tests/engine/update_tests.lua b/tests/engine/update_tests.lua index 9bf67171e..d150e43f6 100644 --- a/tests/engine/update_tests.lua +++ b/tests/engine/update_tests.lua @@ -193,11 +193,11 @@ end -- --------------------------------------------------------------------------- local assets = { - { name = "gen1recomp-1.4.2-macos.zip", browser_download_url = "http://x/mac", size = 10 }, - { name = "gen1recomp-1.4.2.love", browser_download_url = "http://x/love", size = 12345 }, + { name = "Gen2Recomped-1.4.2-macos.zip", browser_download_url = "http://x/mac", size = 10 }, + { name = "Gen2Recomped-1.4.2.love", browser_download_url = "http://x/love", size = 12345 }, { name = "sha256sums.txt", browser_download_url = "http://x/sums", size = 99 }, } -local picked = Check.pickAsset(assets, "gen1recomp-1.4.2.love") +local picked = Check.pickAsset(assets, "Gen2Recomped-1.4.2.love") check(picked ~= nil, "pickAsset finds an asset by exact name") eq(picked.url, "http://x/love", "pickAsset returns the download url") eq(picked.size, 12345, "pickAsset returns the numeric size") @@ -223,10 +223,24 @@ local body = Json.encode({ tag_name = "v1.4.2", assets = assets, }) +-- A same-version Gen1 payload is not a fallback for a missing Gen2 asset. +local foreign = Check.parseRelease(Json.encode({tag_name="v1.4.2", assets={ + {name="gen1recomp-1.4.2.love",browser_download_url="http://x/foreign",size=88}, + {name="Gen2Recomped-1.4.2-macos.zip",browser_download_url="http://x/zip",size=99}, +}})) +check(foreign ~= nil, "a release without a matching game payload still parses") +eq(foreign.payload,nil,"Gen1 and platform archives never substitute for the Gen2 payload") +local competing = Check.parseRelease(Json.encode({tag_name="v1.4.2", assets={ + {name="gen1recomp-1.4.2.love",browser_download_url="http://x/foreign",size=88}, + {name="Gen2Recomped-1.4.2.love",browser_download_url="http://x/correct",size=123}, +}})) +check(competing.payload ~= nil,"exact Gen2 payload wins among same-version assets") +eq(competing.payload and competing.payload.url,"http://x/correct","foreign game asset is ignored even when listed first") + local rel = Check.parseRelease(body) check(rel ~= nil, "parseRelease accepts a valid release") eq(rel.version, "1.4.2", "parseRelease strips the leading v from tag_name") -eq(rel.payloadName, "gen1recomp-1.4.2.love", "parseRelease derives the payload name from the version") +eq(rel.payloadName, "Gen2Recomped-1.4.2.love", "parseRelease derives the payload name from the version") eq(rel.payload.url, "http://x/love", "parseRelease picks the payload asset url") eq(rel.payload.size, 12345, "parseRelease picks the payload asset size") eq(rel.sums.url, "http://x/sums", "parseRelease picks the sums asset url") @@ -268,18 +282,18 @@ eq(literal, nil, "parseRelease returns nil on a non-object JSON literal") -- standard " " lines, the '*' binary marker, a './' prefix, CRLF -- endings and mixed hash case; junk lines are skipped local sums = - "aaaa1111 gen1recomp-1.4.2.love\n" .. + "aaaa1111 Gen2Recomped-1.4.2.love\n" .. "BBBB2222 *./sha256sums.txt\r\n" .. "deadBEEF ./nested.love\n" .. "not a checksum line at all\n" local map = Check.parseSums(sums) -eq(map["gen1recomp-1.4.2.love"], "aaaa1111", "parseSums reads a bare-name line") +eq(map["Gen2Recomped-1.4.2.love"], "aaaa1111", "parseSums reads a bare-name line") eq(map["sha256sums.txt"], "bbbb2222", "parseSums strips the * marker and ./ prefix and lowercases") eq(map["nested.love"], "deadbeef", "parseSums lowercases a mixed-case hash and strips ./") eq(map["not a checksum line at all"], nil, "parseSums skips lines that are not checksums") -- the target form returns just that file's hash (hit / miss) -eq(Check.parseSums(sums, "gen1recomp-1.4.2.love"), "aaaa1111", "parseSums(target) returns the matching hash") +eq(Check.parseSums(sums, "Gen2Recomped-1.4.2.love"), "aaaa1111", "parseSums(target) returns the matching hash") eq(Check.parseSums(sums, "missing.love"), nil, "parseSums(target) misses cleanly on an unknown file") -- degenerate inputs: empty text yields an empty map, a targeted miss is nil, @@ -294,7 +308,7 @@ eq(Check.parseSums(nil, "anything"), nil, "parseSums(nil, target) returns nil wi -- --------------------------------------------------------------------------- eq(Check.releaseUrl(), - "https://github.com/bryanthaboi/gen1recomp/releases/latest", + "https://github.com/UNDERdecoded/Gen2Recomped/releases/latest", "releaseUrl points at the repo's latest release") T.finish("update") From 03b7ecb06303b7d06044e010167f809e1431be1e Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:21:42 +0200 Subject: [PATCH 11/19] test: cover twelve-action rebinding without fixed row indices --- tests/engine/rebind_capture_bug510.lua | 41 ++++++++++++++++------ tests/engine/rebind_swap_clear_bug589.lua | 42 +++++++++++++++-------- 2 files changed, 58 insertions(+), 25 deletions(-) diff --git a/tests/engine/rebind_capture_bug510.lua b/tests/engine/rebind_capture_bug510.lua index e5d13d311..f36306d15 100644 --- a/tests/engine/rebind_capture_bug510.lua +++ b/tests/engine/rebind_capture_bug510.lua @@ -48,8 +48,13 @@ local function openMenu(game) return bm end --- rows are BindingsMenu's BUTTONS order; 5 = A, 6 = B -local ROW_A, ROW_B = 5, 6 +-- Find actions by their public menu row metadata, not by a generation's order. +local function row(menu, action) + for i, item in ipairs(menu.items) do + if item.button and item.button.id == action then return i end + end + error("missing controls row: " .. action) +end -- The mechanism, pinned so a future "just apply it immediately" revert -- fails here: a rebind overwrites whatever the key used to do, so B = Z @@ -73,14 +78,14 @@ check(game.save.options.bindings == nil, "escaping a capture writes no binding") eq(game.wroteOptions, 0, "and does not touch options on disk") -bm.index = ROW_B +bm.index = row(bm, "b") press(bm, "a") bm:onKeyPressed("z") check(game.save.options.bindings == nil, "a capture holds its press; nothing stores before the release (#589)") bm:onKeyReleased("z") eq(game.save.options.bindings.b.key, "z", "releasing the press stores B = Z") -eq(bm.items[ROW_B].right, "Z/B", "the row shows the new key straight away") +eq(bm.items[row(bm, "b")].right, "Z/B", "the row shows the new key straight away") eq(game.wroteOptions, 1, "the choice persists immediately") eq(Input.keyBindings["z"], "a", "but the live map still reads Z as A while the screen is open (#510)") @@ -90,12 +95,12 @@ eq(#game.stack.states, 1, "capturing Z does not close the screen") -- inherits B's previous key and no key serves two rows (#589) eq(game.save.options.bindings.a.key, "x", "capturing A's key for B hands A the old B key") -eq(bm.items[ROW_A].right, "X/A", "and the A row redraws with it") +eq(bm.items[row(bm, "a")].right, "X/A", "and the A row redraws with it") -- the next Z the player presses is still confirm, so the A row can be armed -bm.index = ROW_A +bm.index = row(bm, "a") press(bm, "a") -eq(bm.capture, bm.items[ROW_A], "the A row arms instead of the screen closing") +eq(bm.capture, bm.items[row(bm, "a")], "the A row arms instead of the screen closing") bm:onKeyPressed("x") bm:onKeyReleased("x") eq(game.save.options.bindings.a.key, "x", "re-capturing A's own key keeps it") @@ -117,16 +122,18 @@ eq(Input.keyBindings["z"], "b", "a reload reaches the same map as the close") Input:init() local padGame = newGame() local padBm = openMenu(padGame) -padBm.index = ROW_B +padBm.index = row(padBm, "b") press(padBm, "a") padBm:onGamepadPressed("y") padBm:onGamepadReleased("y") eq(padGame.save.options.bindings.b.pad, "y", "a pad capture stores") -eq(Input.padBindings["y"], nil, "and stays out of the live pad map until close") +eq(Input.padBindings["y"], "x", "pad Y keeps its default DS X action until close") +eq(padGame.save.options.bindings.x.pad, "b", "DS X inherits the captured row's pad B") +eq(Input.padBindings["b"], "b", "the donor swap is also deferred until close") -- a second input going down while the first is held backs the capture out -- with no keyboard in reach, the pad's Escape (#589) -padBm.index = ROW_A +padBm.index = row(padBm, "a") press(padBm, "a") padBm:onGamepadPressed("x") padBm:onGamepadPressed("b") @@ -139,6 +146,20 @@ eq(padGame.save.options.bindings.a, nil, press(padBm, "b") eq(Input.padBindings["y"], "b", "closing commits the pad half too") +eq(Input.padBindings["b"], "x", "closing commits the DS X donor half") + +-- A genuinely unbound input must also remain absent until the screen closes. +Input:init() +local spareGame = newGame() +local spareBm = openMenu(spareGame) +spareBm.index = row(spareBm, "a") +press(spareBm, "a") +spareBm:onGamepadPressed("leftstick") +spareBm:onGamepadReleased("leftstick") +eq(spareGame.save.options.bindings.a.pad, "leftstick", "unbound pad capture stores") +eq(Input.padBindings.leftstick, nil, "unbound pad remains absent while the menu is open") +press(spareBm, "b") +eq(Input.padBindings.leftstick, "a", "closing activates the newly bound pad") Input:init() T.finish("rebind_capture_bug510") diff --git a/tests/engine/rebind_swap_clear_bug589.lua b/tests/engine/rebind_swap_clear_bug589.lua index 0e49d03d0..7ccca5fe0 100644 --- a/tests/engine/rebind_swap_clear_bug589.lua +++ b/tests/engine/rebind_swap_clear_bug589.lua @@ -54,8 +54,12 @@ local function settleChoice(state) for _ = 1, Timing.YES_NO_ANSWER do state:update(1 / 60) end end --- rows are BindingsMenu's BUTTONS order -local ROW_A, ROW_B, ROW_SELECT = 5, 6, 8 +local function row(menu, action) + for i, item in ipairs(menu.items) do + if item.button and item.button.id == action then return i end + end + error("missing controls row: " .. action) +end -- ---- (a) pad capture swaps with the row that owns the button -------------- @@ -64,9 +68,9 @@ local game = newGame() local bm = BindingsMenu.new(game) game.stack:push(bm) -bm.index = ROW_A +bm.index = row(bm, "a") press(bm, "a") -eq(bm.capture, bm.items[ROW_A], "A arms the A row") +eq(bm.capture, bm.items[row(bm, "a")], "A arms the A row") bm:onGamepadPressed("b") check(game.save.options.bindings == nil, "a pad capture holds its press; nothing stores before the release") @@ -75,8 +79,8 @@ local bindings = game.save.options.bindings eq(bindings.a.pad, "b", "releasing pad B stores it on the A row") eq(bindings.b.pad, "a", "and the B row, which owned pad B, inherits the A row's old pad (#589)") -eq(bm.items[ROW_A].right, "Z/B", "the A row redraws with the new pad") -eq(bm.items[ROW_B].right, "X/A", "so does the B row") +eq(bm.items[row(bm, "a")].right, "Z/B", "the A row redraws with the new pad") +eq(bm.items[row(bm, "b")].right, "X/A", "so does the B row") -- after applying, every row's effective pad is unique and none is lost Input:applyBindings(bindings) @@ -89,13 +93,21 @@ for button, action in pairs(Input.padBindings) do seen[action] = button actions[#actions + 1] = action end -eq(#actions, 8, "all eight actions still have exactly one pad button") +eq(#actions, 12, "all twelve actions still have exactly one pad button") +local unchanged = { + up = "dpup", down = "dpdown", left = "dpleft", right = "dpright", + x = "y", y = "x", start = "start", select = "back", + l = "leftshoulder", r = "rightshoulder", +} +for action, button in pairs(unchanged) do + eq(seen[action], button, "A/B swap preserves the binding for " .. action) +end Input:init() -- ---- (b) a second input while the first is held cancels ------------------- -- key then key: the straggling release of the first press writes nothing -bm.index = ROW_SELECT +bm.index = row(bm, "select") press(bm, "a") bm:onKeyPressed("q") bm:onKeyPressed("w") @@ -121,17 +133,17 @@ check(bindings.select == nil, "press alone commits nothing (#589)") eq(game.wroteOptions, writesAfterSwap, "and touches nothing on disk") bm:onKeyReleased("q") eq(bindings.select.key, "q", "the release is the commit") -eq(bm.items[ROW_SELECT].right, "Q/BACK", "the row shows the new key") +eq(bm.items[row(bm, "select")].right, "Q/BACK", "the row shows the new key") -- ---- (d) SELECT on a row forgets its rebind ------------------------------- press(bm, "select") check(bindings.select == nil, "SELECT drops the row's overlay entry (#589)") -eq(bm.items[ROW_SELECT].right, "TAB/BACK", "the row falls back to the default") +eq(bm.items[row(bm, "select")].right, "TAB/BACK", "the row falls back to the default") -- the swapped B row clears the same way; a second SELECT on the now -- default row is a no-op, not a write local writes = game.wroteOptions -bm.index = ROW_B +bm.index = row(bm, "b") press(bm, "select") eq(game.wroteOptions, writes + 1, "clearing the swapped B row writes once") check(game.save.options.bindings.b == nil, "and drops its overlay entry") @@ -141,7 +153,7 @@ eq(game.wroteOptions, writes + 1, "clearing an already-default row writes nothin -- ---- (e) START confirms, then drops the whole overlay --------------------- -- rebuild a dirty overlay to reset -bm.index = ROW_A +bm.index = row(bm, "a") press(bm, "a") bm:onKeyPressed("p") bm:onKeyReleased("p") @@ -158,7 +170,7 @@ press(box, "a") settleChoice(box) eq(game.stack:top(), bm, "answering pops the box") check(game.save.options.bindings ~= nil, "NO keeps the bindings (defaultNo)") -eq(bm.items[ROW_A].right, "P/B", "and the rows keep showing them") +eq(bm.items[row(bm, "a")].right, "P/B", "and the rows keep showing them") -- again, flip to YES: the overlay goes away and every row reads default press(bm, "start") @@ -167,8 +179,8 @@ press(box, "up") press(box, "a") settleChoice(box) check(game.save.options.bindings == nil, "YES clears options.bindings (#589)") -eq(bm.items[ROW_A].right, "Z/A", "the A row reads its default again") -eq(bm.items[ROW_B].right, "X/B", "so does the B row the swap had touched") +eq(bm.items[row(bm, "a")].right, "Z/A", "the A row reads its default again") +eq(bm.items[row(bm, "b")].right, "X/B", "so does the B row the swap had touched") -- closing after the reset leaves the live map at the defaults press(bm, "b") From 41458bf97a3bd3bbeac463c0395a54e112595a7b Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:22:34 +0200 Subject: [PATCH 12/19] test: exercise profiled Game methods with complete fixtures --- tests/engine/soft_reset_bug563.lua | 26 ++++++++++++++++++++++---- tests/engine/tool_mod_hooks.lua | 15 ++++++++------- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/tests/engine/soft_reset_bug563.lua b/tests/engine/soft_reset_bug563.lua index 65fb22445..fe8fdcf7d 100644 --- a/tests/engine/soft_reset_bug563.lua +++ b/tests/engine/soft_reset_bug563.lua @@ -106,8 +106,9 @@ check(stepChord(), "reaching 16 again from the restart") -- before stack:update, so it fires from a battle, a menu or a cutscene and -- not just from the overworld (#563). local function fakeGame() - local game = { input = Input, save = {}, returned = 0 } + local game = setmetatable({ input = Input, save = {}, returned = 0 }, { __index = Game }) game.stack = { + states = { {} }, -- a live state, so the real empty-stack guard does not recover updates = 0, update = function(self) self.updates = self.updates + 1 end, } @@ -117,7 +118,23 @@ end local game = fakeGame() holdKeys("z", "x", "escape", "tab") +-- Observe the real profiling wrapper as well as its real _step body. A reset +-- returns early from _step, but must still close the outer profiling scope. +local FrameProfile = require("src.core.FrameProfile") +local savedSection = FrameProfile.section +local opened, closed = 0, 0 +FrameProfile.section = function(name) + local close = savedSection(name) + if name == " step: whole" then opened = opened + 1 end + return function() + if name == " step: whole" then closed = closed + 1 end + close() + end +end for _ = 1, HOLD_STEPS do Game.step(game, 1 / 60) end +FrameProfile.section = savedSection +eq(opened, HOLD_STEPS, "every logic step enters the real profiling wrapper") +eq(closed, HOLD_STEPS, "the reset early return closes its profiling scope") eq(game.returned, 1, "Game:step falls back to the title on the 16th step") eq(game.stack.updates, HOLD_STEPS - 1, "and the state on top never gets that step, whatever it was") @@ -131,16 +148,17 @@ local bare = fakeGame() bare.input = { step = function() end, isDown = function() return false end } for _ = 1, HOLD_STEPS * 2 do Game.step(bare, 1 / 60) end eq(bare.returned, 0, "an input with no chord bookkeeping never resets") +eq(bare.stack.updates, HOLD_STEPS * 2, "an input stand-in still updates the real state stack") -- ---- the on-screen overlay --------------------------------------------- -- Force the overlay live the way a phone would have it. img is only ever --- tested for truthiness on the input path (drawing is what reads it), so a --- placeholder keeps this suite off love.graphics.newImage. +-- checked per button on the input path. Provide each available control +-- without asking love.graphics to load actual image assets. Input:init() TouchControls:init() TouchControls.active, TouchControls.enabled = true, true -TouchControls.img = { stub = true } +TouchControls.img = { a = {}, b = {}, start = {}, select = {}, dpad = {} } local L = TouchControls:layout() -- One finger, one control: touchpressed returns on its first hit, so no diff --git a/tests/engine/tool_mod_hooks.lua b/tests/engine/tool_mod_hooks.lua index 36f1f2a01..d92ac0aad 100644 --- a/tests/engine/tool_mod_hooks.lua +++ b/tests/engine/tool_mod_hooks.lua @@ -8,6 +8,7 @@ package.path = "./?.lua;./?/init.lua;" .. package.path local T = require("tests.modkit") local Hooks = require("src.mods.Hooks") local Runtime = require("src.mods.Runtime") +local Game = require("src.core.Game") local savedEvents, savedHooks, savedErrors = Runtime.events, Runtime.hooks, Runtime.errors @@ -19,14 +20,14 @@ Runtime.hooks = hooks -- ordering rather than merely checking that a hook was registered. do local order = {} - local fake = { + local fake = setmetatable({ input = { step = function() order[#order + 1] = "input" end }, - stack = { update = function(_, dt) + stack = { states = { {} }, update = function(_, dt) order[#order + 1] = "world" T.eq(dt, 1 / 60, "the world receives the fixed-step dt") end }, save = {}, - } + }, { __index = Game }) hooks:wrap("input.step", function(nextFn, game, dt) T.check(game == fake, "input.step receives the live Game object") T.eq(dt, 1 / 60, "input.step receives the fixed-step dt") @@ -71,10 +72,10 @@ end -- the live snapshot in preparation for disk IO. do local captured = false - local fake = { + local fake = setmetatable({ save = {}, overworld = { captureSave = function() captured = true end }, - } + }, { __index = Game }) hooks:wrap("save.write", function(nextFn, game) T.check(game == fake, "save.write receives the live Game object") return false @@ -112,14 +113,14 @@ do -- Game:draw iterates stack.states and calls each state's draw (it no -- longer goes through stack:draw), so the fixture must put a drawable -- state on the stack to observe composition order. - local fake = { + local fake = setmetatable({ overworld = {}, stack = { states = { { draw = function() order[#order + 1] = "states" end }, }, }, - } + }, { __index = Game }) function fake.stack:visibleBase() return 1 end function fake.stack:top() return self.states[#self.states] end From ca26f6cd3feae302feaa6baffa5495b8d4d6cbff Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:23:35 +0200 Subject: [PATCH 13/19] test: execute quit-event veto and Android shutdown paths --- tests/engine/quit_thread_shutdown.lua | 85 +++++++++++++++++++++++---- 1 file changed, 72 insertions(+), 13 deletions(-) diff --git a/tests/engine/quit_thread_shutdown.lua b/tests/engine/quit_thread_shutdown.lua index a0dff35be..19cfd28ac 100644 --- a/tests/engine/quit_thread_shutdown.lua +++ b/tests/engine/quit_thread_shutdown.lua @@ -192,18 +192,77 @@ check(quitHook:find('package.loaded["src.update.Check"].shutdown', 1, true) ~= n -- so the quit event exits the process outright. It has to sit after the -- love.quit() veto test, or the editor's abort-quit path would die on a quit -- it refused. -local quitBranch = mainSrc:match('if name == "quit" then(.-)\n%s*end\n') -check(quitBranch ~= nil, "love.run still handles the quit event") -quitBranch = quitBranch or "" -local vetoAt = quitBranch:find("not love%.quit()") -local osAt = quitBranch:find("os%.exit") -local androidAt = quitBranch:find('getOS() == "Android"', 1, true) -check(vetoAt ~= nil and osAt ~= nil and vetoAt < osAt, - "the process exit runs only after love.quit declined to veto") -check(androidAt ~= nil and androidAt < osAt, - "the process exit is gated on Android") -local exits = 0 -for _ in mainSrc:gmatch("os%.exit") do exits = exits + 1 end -eq(exits, 1, "os.exit appears once, at the quit event") +-- Execute the actual run-loop function in an isolated environment. Scanning +-- nested `end`s or counting os.exit in comments cannot prove veto behavior. +local runAt = assert(mainSrc:find("\nfunction love.run()", 1, true)) +local runSource = mainSrc:sub(runAt + 1) +local function quitFrame(platform, answer, code, noCallback) + local calls, exits = {}, {} + local function record(name) calls[#calls + 1] = name end + local env = setmetatable({ + BootTrace = { mark = function() end, frame = function() record("frame") end }, + Frames = { tick = function() record("tick") end }, + FrameProfile = { section = function() return function() end end }, + pacingEnabled = function() return false end, + os = { exit = function(value) record("exit"); exits[#exits + 1] = value end }, + love = { + handlers = { quit = function() record("dispatch") end }, + update = function() record("update") end, + event = { + pump = function() end, + poll = function() + local sent = false + return function() + if not sent then sent = true; return "quit", code end + end + end, + }, + }, + }, { __index = _G }) + if platform then env.love.system = { getOS = function() return platform end } end + if not noCallback then + env.love.quit = function() record("quit"); return answer end + end + local compile = loadstring or load + local chunk + if setfenv then + chunk = assert(compile(runSource, "@main.lua:love.run")) + setfenv(chunk, env) + else + chunk = assert(load(runSource, "@main.lua:love.run", "t", env)) + end + chunk() + local result = env.love.run()() + return result, table.concat(calls, ","), exits +end + +for _, platform in ipairs({ "Android", "Windows", "OS X", "Linux", "NX", false }) do + local label = tostring(platform) + for _, code in ipairs({ 0, 7, false }) do + -- false is a table-friendly sentinel for an omitted exit status. + local expected = code or 0 + for _, noCallback in ipairs({ false, true }) do + for _, answer in ipairs({ false, "nil" }) do + local callbackAnswer = answer + if answer == "nil" then callbackAnswer = nil end + local result, order, exits = quitFrame(platform, callbackAnswer, code or nil, noCallback) + local prefix = noCallback and "" or "quit" + eq(result, expected, label .. ": accepted quit returns its exit status") + if platform == "Android" then + eq(#exits, 1, "Android exits exactly once after accepting quit") + eq(exits[1], expected, "Android forwards the requested exit status") + eq(order, prefix == "" and "exit" or "quit,exit", "shutdown precedes process exit") + else + eq(#exits, 0, label .. ": accepted quit does not force a process exit") + eq(order, prefix, label .. ": no further frame work after accepted quit") + end + end + end + end + local result, order, exits = quitFrame(platform, true, 7) + eq(result, nil, label .. ": veto keeps the frame running") + eq(#exits, 0, label .. ": veto never exits the process") + eq(order, "quit,dispatch,update,frame,tick", label .. ": veto resumes event and frame processing") +end T.finish("quit thread shutdown") From 86aada927c50bdcd98f9ae9dc66559ceb42defbe Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:24:10 +0200 Subject: [PATCH 14/19] test: pin continuous wide-battle animation anchor mapping --- tests/engine/wide_battle_layout.lua | 39 +++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/tests/engine/wide_battle_layout.lua b/tests/engine/wide_battle_layout.lua index 5571af399..dadf125cf 100644 --- a/tests/engine/wide_battle_layout.lua +++ b/tests/engine/wide_battle_layout.lua @@ -38,13 +38,38 @@ T.eq(WideBattle.navigate(1, 4, pressing("right")), 2, T.eq(WideBattle.navigate(1, 4, pressing("a")), nil, "navigate leaves A / B / SELECT to the battle engine") --- animation frames shift as one rigid group toward the side they play on -local px, py = WideBattle.animationOffset({ { x = 24 }, { x = 64 } }) -T.eq(px, 20, "a player-side frame lands on the player anchor") -T.eq(py, 8, "a player-side frame lands on the player baseline") -local ex, ey = WideBattle.animationOffset({ { x = 104 }, { x = 144 } }) -T.eq(ex, 136, "an enemy-side frame lands on the enemy anchor") -T.eq(ey, 0, "an enemy-side frame lands on the enemy baseline") +-- OAM x is the right edge of an 8px sprite. These groups are centered on +-- the authored player (26) and enemy (124) anchors, rather than merely +-- falling somewhere on their half of the 160px screen. +local px, py = WideBattle.animationOffset({ { x = 14 }, { x = 46 } }) +T.eq(px, 20, "the player anchor maps to its wide-layout offset") +T.eq(py, 8, "the player anchor maps to its wide-layout baseline") +local ex, ey = WideBattle.animationOffset({ { x = 112 }, { x = 144 } }) +T.eq(ex, 136, "the enemy anchor maps to its wide-layout offset") +T.eq(ey, 0, "the enemy anchor maps to its wide-layout baseline") + +local function offset(x, wantX, wantY, label) + local dx, dy = WideBattle.animationOffset({ { x = x } }) + T.eq(dx, wantX, label .. " horizontal offset") + T.eq(dy, wantY, label .. " vertical offset") +end +offset(30, 20, 8, "single sprite at the player anchor") +offset(128, 136, 0, "single sprite at the enemy anchor") +offset(79, 78, 4, "midpoint between anchors") +-- Wobble must continue across the anchor instead of sticking at it. +offset(29, 19, 8, "one pixel before the player anchor") +offset(31, 21, 8, "one pixel after the player anchor") +offset(127, 135, 0, "one pixel before the enemy anchor") +offset(129, 137, 0, "one pixel after the enemy anchor") +-- Bounded overshoot lets balls leave the picture without unbounded offsets. +offset(-1000, -3, 10, "far left overshoot") +offset(1000, 159, -2, "far right overshoot") +local rx, ry = WideBattle.animationOffset({ { x = 46 }, { x = 14 } }) +T.eq(rx, px, "sprite ordering does not change the rigid frame offset") +T.eq(ry, py, "sprite ordering does not change the baseline") +local emptyX, emptyY = WideBattle.animationOffset({}) +T.eq(emptyX, 0, "an empty frame has no horizontal offset") +T.eq(emptyY, 0, "an empty frame has no vertical offset") -- the surface: a request outside the bounds falls back to the GB screen, -- and the canvas is only reallocated when the size actually changes From 03fc570e4cfedb6a3bbfd0bdcfa92ab0e2a418b7 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:28:05 +0200 Subject: [PATCH 15/19] test: audit and pin the current Gen2 link fingerprint surface --- tests/engine/gate_fingerprint.lua | 38 ++++++++++++++++++- tests/goldens/fixture_fingerprint.md | 36 ++++++++++++++++++ tests/goldens/fixture_fingerprint.txt | 2 +- .../goldens/fixture_fingerprint_sections.txt | 7 ++++ 4 files changed, 80 insertions(+), 3 deletions(-) create mode 100644 tests/goldens/fixture_fingerprint.md create mode 100644 tests/goldens/fixture_fingerprint_sections.txt diff --git a/tests/engine/gate_fingerprint.lua b/tests/engine/gate_fingerprint.lua index 731996016..85fb65a72 100644 --- a/tests/engine/gate_fingerprint.lua +++ b/tests/engine/gate_fingerprint.lua @@ -9,8 +9,8 @@ -- itself, and would silently make two builds of the same engine refuse to -- link. Here it flips one hex string and fails. -- --- Regenerate deliberately with scripts/test.sh --bless after recording the --- intended parity change; never automatically. +-- Regenerate deliberately after auditing each changed surface section; see +-- tests/goldens/fixture_fingerprint.md. Never update expected values automatically. package.path = "./?.lua;./?/init.lua;" .. package.path @@ -37,6 +37,40 @@ local golden = readGolden(GOLDEN) T.check(golden ~= nil, "the committed fixture fingerprint golden exists: " .. GOLDEN) T.eq(actual, golden, "fixture fingerprint matches the committed golden") +-- Section pins make a registry addition reviewable without treating a whole +-- digest change as permission to bless unrelated species or move changes. +local sectionFile = assert(io.open("tests/goldens/fixture_fingerprint_sections.txt", "r")) +local expectedSections = {} +for line in sectionFile:lines() do + local name, expected = line:match("^(%S+)%s+(%x+)$") + if name then expectedSections[name] = expected end +end +sectionFile:close() +local sectionCount = 0 +for name, body in Fingerprint.surface(data, {}):gmatch("%[([^%]]+)%]([^%[]*)") do + sectionCount = sectionCount + 1 + T.eq(Fingerprint.digest("[" .. name .. "]" .. body), expectedSections[name], + "audited fixture surface section: " .. name) + expectedSections[name] = nil +end +T.eq(sectionCount, 7, "the fixture has seven populated fingerprint sections") +T.eq(next(expectedSections), nil, "all committed section pins were checked") + +-- Platinum's four dynamic-power effects were added in 3252aec. They are +-- native full handlers, and removing any one must change link compatibility. +local sinnoh = { + "POWER_BASED_ON_LOW_SPEED", "INCREASE_POWER_WITH_MORE_HP", + "DOUBLE_POWER_WHEN_BELOW_HALF", "DOUBLE_POWER_HEAL_SLEEP", +} +for _, id in ipairs(sinnoh) do + T.eq(data.move_effects[id].kind, "full", "Sinnoh effect is registered: " .. id) + local copy = T.fixtures.fresh() + local copyRun = T.sdk.loadNone({ data = copy }) + copy.move_effects[id] = nil + T.neq(Fingerprint.compute(copy, {}), actual, "omitting " .. id .. " changes compatibility") + copyRun.release() +end + -- determinism: same data, same digest. A fingerprint that folded a table -- address or a pairs() order would pass once and fail in CI. T.eq(Fingerprint.compute(data, {}), actual, "the fingerprint is stable within a process") diff --git a/tests/goldens/fixture_fingerprint.md b/tests/goldens/fixture_fingerprint.md new file mode 100644 index 000000000..d8cc8e062 --- /dev/null +++ b/tests/goldens/fixture_fingerprint.md @@ -0,0 +1,36 @@ +# Fixture link fingerprint audit + +The previous `7de3051a7b3c108e` pin was already stale at Gen2Recomped's +`0b8c9c4` import: that checkout computes `8c94d595cd60ca69` against its own +ROM-free fixtures. It is not a baseline that current Gen2 data can satisfy. + +At upstream `13af468b97dc37015d14ad5c71d7f067c3ee810d`, the same production +serializer and digest compute `41e69caf4afa35ab`. Comparing the canonical +`Fingerprint.surface(data, {})` strings against `0b8c9c4` changes **only** +`move_effects`: commit `3252aec` adds these four full-handler registry records: + +- `POWER_BASED_ON_LOW_SPEED` (Gyro Ball) +- `INCREASE_POWER_WITH_MORE_HP` (Wring Out / Crush Grip) +- `DOUBLE_POWER_WHEN_BELOW_HALF` (Brine) +- `DOUBLE_POWER_HEAL_SLEEP` (Wake-Up Slap) + +No records were removed or altered in the serialized surface comparison. +The current surface has 198 effect records. Species, moves, type chart, +statuses, constants and mod list are byte-identical to the imported checkout. +An independent Python implementation using integer XOR, multiplication by +16777619 and modulo 2**32 in both lanes also produces the current digest. +No fingerprint algorithm, allowlist, cache or production registry is changed +by this test repair. + +`fixture_fingerprint_sections.txt` pins each populated section separately so +future intentional registry additions cannot hide changes in another section. +`gate_fingerprint.lua` retains all prior mutation and determinism assertions, +and additionally proves that removing any of the four Sinnoh registrations +changes compatibility. An empty `link_fields` registry has no serialized +section; a future nonempty one requires a deliberate new section pin. + +To audit a future change, load a fresh `tests.modkit` fixture with +`T.sdk.loadNone({data=data})`, compare `Fingerprint.surface(data,{})` section +by section, and then update only reviewed pins. Run the gate again and keep +the mutation assertions enabled. The ROM-dependent vanilla golden is separate +and was not re-blessed by this update. diff --git a/tests/goldens/fixture_fingerprint.txt b/tests/goldens/fixture_fingerprint.txt index 3ab0752dc..77ad32cd7 100644 --- a/tests/goldens/fixture_fingerprint.txt +++ b/tests/goldens/fixture_fingerprint.txt @@ -1 +1 @@ -7de3051a7b3c108e +41e69caf4afa35ab diff --git a/tests/goldens/fixture_fingerprint_sections.txt b/tests/goldens/fixture_fingerprint_sections.txt new file mode 100644 index 000000000..2e9081fa0 --- /dev/null +++ b/tests/goldens/fixture_fingerprint_sections.txt @@ -0,0 +1,7 @@ +pokemon 0ad4d8a59c0daa59 +moves 54b3cb2c1776ed48 +type_chart cc5bd80d003bd459 +statuses 68247ced2ed19a21 +move_effects 3bef37494ca4a845 +constants e4cf6f91ff122fa5 +mods 6a9ee9de68f78902 From f07b48b0f63af0235f0eb19d8393d136ab9c0789 Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:29:42 +0200 Subject: [PATCH 16/19] test: cover six native producers through the public mod API --- tests/engine/native_mod_seams.lua | 234 ++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 tests/engine/native_mod_seams.lua diff --git a/tests/engine/native_mod_seams.lua b/tests/engine/native_mod_seams.lua new file mode 100644 index 000000000..6d3794059 --- /dev/null +++ b/tests/engine/native_mod_seams.lua @@ -0,0 +1,234 @@ +-- Native producers, observed through a sandboxed mod loaded by the real SDK. +-- Do not emit these events from the test: a missing call site must fail here. +package.path = "./?.lua;./?/init.lua;" .. package.path +local T = require("tests.modkit") +local Runtime = require("src.mods.Runtime") +local Game = require("src.core.Game") +local GameVersion = require("src.core.GameVersion") +local Overworld = require("src.world.OverworldController") +local BirchSpeech = require("src.ui.BirchSpeech") +local Gen4Battle = require("src.battle.Gen4Battle") +local Pokemon = require("src.pokemon.Pokemon") + +local savedVersion = GameVersion.get() +local savedGame = {} +for _, key in ipairs({ "data", "save", "stack", "input", "overworld", "world", "renderer" }) do + savedGame[key] = { Game[key] } +end +GameVersion.set("red") +local data = T.fixtures.fresh() +local run = T.sdk.loadMods( + { "mods/seam_probe" }, + { + data = data, + fs = T.sdk.memfs({ + ["mods/seam_probe/manifest.json"] = [[{ + "id":"seam_probe", "name":"Native seam probe", "version":"1.0.0", + "api":2, "entry":"main.lua", "affects_link":false + }]], + ["mods/seam_probe/main.lua"] = [[ + local mod = ... + local seen = {} + mod.exports.seen = seen + local names = { + "intro.birch_speech.started", "intro.birch_speech.finished", + "pokemon.egg_hatched", "world.blocks_replaced", "world.tick", + } + for _, name in ipairs(names) do + seen[name] = {} + mod.events:on(name, function(payload) + local events = seen[name] + events[#events + 1] = payload + end) + end + mod.exports.hideHUD = true + mod.exports.hudCalls = 0 + mod.hooks:wrap("battle.status_hud_visible", function(nextFn, battle) + mod.exports.hudCalls = mod.exports.hudCalls + 1 + mod.exports.battle = battle + if mod.exports.hideHUD then return false end + return nextFn(battle) + end) + ]], + }), + } +) +T.eq(#run.errors, 0, "the public-API probe loads without errors") +local exports = assert(run.loader.exports.seam_probe) +local seen = exports.seen +local stack = { states = {} } +function stack:push(state) + self.states[#self.states + 1] = state +end +function stack:pop() + return table.remove(self.states) +end +function stack:top() + return self.states[#self.states] +end +Game.data, Game.stack = data, stack +Game.save = { player = { map = "FIX_TOWN", name = "TEST", id = 123 }, options = {} } +Game.input = { + wasPressed = function() + return false + end, + isDown = function() + return false + end, +} +Game.renderer = { + worldViewSize = function() + return 160, 144 + end, +} + +-- enter() establishes the native module's Game reference and real runner. +-- Map loading is the ROM/graphics boundary; provide a tiny idle map there. +local map = { + id = "FIX_TOWN", + def = { width = 2, height = 2 }, + blockPatch = {}, + renderer = { + rebuilds = 0, + rebuild = function(self) + self.rebuilds = self.rebuilds + 1 + end, + }, + warpAtCell = function() + return nil + end, +} +function map:blockAt(bx, by) + return self.blockPatch[by * 2 + bx + 1] or 0 +end +local world = setmetatable({ + setMap = function(self) + self.map = map + self.player = { + cellX = 0, + cellY = 0, + px = 0, + py = 0, + update = function() + return false + end, + } + self.npcs, self.ghosts, self.entities, self.cast = {}, {}, {}, {} + end, +}, { __index = Overworld }) +world:enter("FIX_TOWN", 0, 0, "down") + +-- Birch start and finish reach subscribers at their real lifecycle boundary. +GameVersion.set("emerald") +data.constants.gen3Intro = { lines = { "WELCOME", "WORLD", "PLAYER", "GENDER" } } +data.text.WELCOME, data.text.GENDER = "Welcome!", "Boy or girl?" +local done = false +local speech = BirchSpeech.new(Game, function() + done = true +end) +stack:push(speech) +speech:enter() +T.eq(#seen["intro.birch_speech.started"], 1, "enter publishes one Birch start") +T.eq(seen["intro.birch_speech.started"][1].speech, speech, "start identifies the live speech") +T.check(stack:top() ~= speech, "start advances into the first real text box") +stack:pop() +speech.answers = { name = "TEST", gender = "girl" } +speech:finish() +T.eq(#seen["intro.birch_speech.finished"], 1, "finish publishes one Birch completion") +local finished = seen["intro.birch_speech.finished"][1] +T.eq(finished.speech, speech, "finish identifies the same speech") +T.eq(finished.answers, speech.answers, "finish carries the recorded answers") +T.check(done and #stack.states == 0, "finish then closes the speech and calls its continuation") + +-- Batch block changes publish only actual writes, clipped to map dimensions. +GameVersion.set("red") +T.eq(world:replaceBlocks({ 1, 0, 2, 0, 99 }), true, "native batch changes map blocks") +T.eq(#seen["world.blocks_replaced"], 1, "batch emits one event") +T.eq(seen["world.blocks_replaced"][1].mapId, "FIX_TOWN", "batch reports the map") +T.eq(seen["world.blocks_replaced"][1].count, 2, "batch counts changed cells only") +T.eq(map.blockPatch[1], 1, "first block is written") +T.eq(map.blockPatch[3], 2, "second changed block is written") +T.eq(map.blockPatch[5], nil, "extra input cannot extend the map") +T.eq(map.renderer.rebuilds, 1, "batch rebuilds once") +T.eq(world:replaceBlocks({ 1, 0, 2, 0 }), false, "identical batch does nothing") +T.eq(world:replaceBlocks(nil), false, "missing batch does nothing") +T.eq(#seen["world.blocks_replaced"], 1, "no-op batches publish no event") + +-- A headless logic update emits even though draw() was never called. +world:update(1 / 60) +T.eq(#seen["world.tick"], 1, "native update publishes one simulation tick") +local tick = seen["world.tick"][1] +T.eq(tick.dt, 1 / 60, "tick carries the simulation dt") +T.eq(tick.mapId, "FIX_TOWN", "tick carries the active map") +T.eq(tick.overworld, world, "tick identifies the native world") +T.eq(tick.scripted, false, "an idle runner is reported as idle") +world.runner:run({ { "wait", 5 } }) +T.eq(world.runner:isRunning(), true, "the native wait command holds a script open") +world:update(1 / 30) +T.eq(#seen["world.tick"], 2, "scripted updates still publish exactly one tick") +T.eq(seen["world.tick"][2].scripted, true, "tick reports the real running script") +T.eq(seen["world.tick"][2].dt, 1 / 30, "tick does not hardcode the frame interval") + +-- Hatching is announced after the native dialogue callback, with a healed +-- ordinary Pokemon rather than an egg. Use Emerald to avoid Johto's second +-- nickname prompt; the native hatch method itself remains under test. +GameVersion.set("emerald") +local egg = Pokemon.new(data, "FIXMON_A", 5, function(a) + return a +end) +egg.isEgg, egg.eggSteps, egg.eggCycles = true, 0, 0 +egg.hp, egg.status = 1, "PSN" +T.eq(world:hatchEgg(egg), true, "native hatch accepts the egg") +T.eq(#seen["pokemon.egg_hatched"], 0, "hatch is not announced before dialogue finishes") +local box = stack:pop() +T.check(box ~= nil, "hatch opens its native text box") +box.onDone() +T.eq(#seen["pokemon.egg_hatched"], 1, "dialogue completion publishes the hatch") +T.eq(seen["pokemon.egg_hatched"][1].mon, egg, "hatch identifies the live Pokemon") +T.eq(egg.isEgg, nil, "the announced Pokemon is no longer an egg") +T.eq(egg.eggSteps, nil, "hatch clears egg step bookkeeping") +T.eq(egg.eggCycles, nil, "hatch clears egg cycle bookkeeping") +T.eq(egg.hp, egg.stats.hp, "hatch heals HP before publication") +T.eq(egg.status, nil, "hatch cures status before publication") +T.eq(egg.happiness, 120, "hatch applies base happiness before publication") +T.eq(world:hatchEgg(nil), false, "missing egg is rejected") +T.eq(#seen["pokemon.egg_hatched"], 1, "rejected hatch does not publish") + +-- A public wrapper can suppress native Sinnoh/Unova healthboxes before any +-- battler/graphics access. Returning true prevents fallback Game Boy panels. +GameVersion.set("platinum") +local battle = {} +T.eq(Gen4Battle.drawHealthboxes(battle), true, "hidden native HUD is handled") +T.eq(exports.hudCalls, 1, "native healthbox draw consults the public hook") +T.eq(exports.battle, battle, "the hook receives the live battle") +exports.hideHUD = false +T.eq( + Gen4Battle.drawHealthboxes(battle), + false, + "delegating preserves the native fallback when healthbox art is absent" +) +T.eq(exports.hudCalls, 2, "delegation still goes through the public wrapper") +exports.hideHUD = true +GameVersion.set("black") +T.eq(Gen4Battle.drawHealthboxes(battle), true, "the shared native path also hides Unova boxes") +T.eq(exports.hudCalls, 3, "Unova consults the same public wrapper") + +T.eq(#run.errors, 0, "native callbacks produce no attributed mod errors") +run.loader.events:removeOwner("seam_probe") +run.loader.hooks:removeOwner("seam_probe") +for _, name in ipairs({ + "intro.birch_speech.started", + "intro.birch_speech.finished", + "pokemon.egg_hatched", + "world.blocks_replaced", + "world.tick", +}) do + T.eq(Runtime.wants(name), false, "unloading removes subscription: " .. name) +end +T.eq(Runtime.wantsHook("battle.status_hud_visible"), false, "unloading removes the HUD hook") +run.release() +GameVersion.set(savedVersion) +for key, value in pairs(savedGame) do + Game[key] = value[1] +end +T.finish("native public mod seams") From 1c29953cca7ef49b73334875169a6f42a0db0b93 Mon Sep 17 00:00:00 2001 From: Roxas2712 Date: Mon, 26 Oct 2026 04:19:27 +0100 Subject: [PATCH 17/19] Translate new transfer, hatch and athlete fallback messages at display time --- src/pokemon/Gen45Hatch.lua | 7 ++++--- src/ui/Gen5PokeTransferScreen.lua | 13 +++++++------ src/ui/HgssAthleteShop.lua | 9 +++++---- src/ui/HgssPokeathlonTeamInfo.lua | 3 ++- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/pokemon/Gen45Hatch.lua b/src/pokemon/Gen45Hatch.lua index d03ff8bf1..edc23cab0 100644 --- a/src/pokemon/Gen45Hatch.lua +++ b/src/pokemon/Gen45Hatch.lua @@ -6,6 +6,7 @@ -- bank (Pt 357, HGSS 187). Black / White keep all three in one bank, 260. -- Each falls back to the engine's English when the cache lacks the line. +local Strings = require("src.core.Strings") local Gen45Hatch = {} Gen45Hatch.LINES = { @@ -37,9 +38,9 @@ end -- The three lines, with `name` (the species) filled in. function Gen45Hatch.lines(game, name) local rows = Gen45Hatch.LINES[family() or "platinum"] - return line(game, rows.oh, name, "Oh?"), - line(game, rows.hatched, name, ("%s hatched from the Egg!"):format(name)), - line(game, rows.ask, name, ("Would you like to nickname the newly\nhatched %s?"):format(name)) + return line(game, rows.oh, name, Strings("Oh?")), + line(game, rows.hatched, name, Strings("%s hatched from the Egg!", name)), + line(game, rows.ask, name, Strings("Would you like to nickname the newly\nhatched %s?", name)) end return Gen45Hatch diff --git a/src/ui/Gen5PokeTransferScreen.lua b/src/ui/Gen5PokeTransferScreen.lua index 0f4be03ad..a710de122 100644 --- a/src/ui/Gen5PokeTransferScreen.lua +++ b/src/ui/Gen5PokeTransferScreen.lua @@ -103,11 +103,12 @@ function S:picked(e) for i, p in ipairs(self.picks) do if p == e then return i end end end -local REFUSE = { - egg = "An Egg cannot be transferred.", - item = "A Pokémon holding an item cannot\nbe transferred.", - hm = "This Pokémon knows a hidden move.\nIt cannot be transferred.", -} +local function refusal(reason) + if reason == "egg" then return Strings("An Egg cannot be transferred.") end + if reason == "item" then return Strings("A Pokémon holding an item cannot\nbe transferred.") end + if reason == "hm" then return Strings("This Pokémon knows a hidden move.\nIt cannot be transferred.") end + return Strings("This Pokémon cannot be transferred.") +end function S:toggle(e) local at = self:picked(e) @@ -115,7 +116,7 @@ function S:toggle(e) if #self.picks >= T().MONS then return end if not e.walker then local why = T().refusal(self.srcData, e.raw) - if why then return self:say(Strings(REFUSE[why] or "This Pokémon cannot be transferred.")) end + if why then return self:say(refusal(why)) end end self.picks[#self.picks + 1] = e if #self.picks == T().MONS then diff --git a/src/ui/HgssAthleteShop.lua b/src/ui/HgssAthleteShop.lua index d9d51199d..7db88187b 100644 --- a/src/ui/HgssAthleteShop.lua +++ b/src/ui/HgssAthleteShop.lua @@ -30,6 +30,7 @@ -- (overlay 31's line for that case was not traced); a taken prize is drawn -- like any other (whether overlay 31 dims it was not read). +local Strings = require("src.core.Strings") local T = require("src.import.Gen4Text") local M = {} @@ -101,7 +102,7 @@ local function choose(self) return end self.mode, self.yesNo = "confirm", 1 - self.message = bank(self, 46, "Would you like\n" .. (def.name or "") .. "?", def.name or "") + self.message = bank(self, 46, Strings("Would you like\n%s?", def.name or ""), def.name or "") end local function transact(self) @@ -115,15 +116,15 @@ local function transact(self) if self.athlon.kind == "daily" then if isApricorn(id) then require("src.world.HgssApricorns").give(save, id - M.APRICORN_FIRST, 1) - self.message = bank(self, 49, "All right, here you go.\nCome back anytime!") + self.message = bank(self, 49, Strings("All right, here you go.\nCome back anytime!")) else require("src.inventory.Bag").add(save, id, 1, self.game.data) - self.message = self:line(6, "Here you are!\nThank you!", def.name or "", self:pocketName(def)) + self.message = self:line(6, Strings("Here you are!\nThank you!"), def.name or "", self:pocketName(def)) end S.takeDaily(save, self.cursor - 1) else S.giveCard(save, (tonumber(id) or 0) - M.DATA_CARD_01) - self.message = bank(self, 49, "All right, here you go.\nCome back anytime!") + self.message = bank(self, 49, Strings("All right, here you go.\nCome back anytime!")) end -- MartData_SubCurrency (PokeathlonSave_SubAthletePoints: not below 0) and -- GAME_STAT_CURRENCY_SPENT diff --git a/src/ui/HgssPokeathlonTeamInfo.lua b/src/ui/HgssPokeathlonTeamInfo.lua index aa75d3eaa..7a5c33749 100644 --- a/src/ui/HgssPokeathlonTeamInfo.lua +++ b/src/ui/HgssPokeathlonTeamInfo.lua @@ -48,6 +48,7 @@ -- * the OBJ set's sequence 5 (a sparkle, created hidden at the Medals and -- never shown by ov97) and 6 are not drawn +local Strings = require("src.core.Strings") local Font = require("src.render.Font") local T = require("src.import.Gen4Text") @@ -199,7 +200,7 @@ function M.draw(game, opts) elseif r.gender == "female" then text(game, line(game, 3, "♀"), 76, 120, 3, 4) end for _, l in ipairs(M.LABELS) do text(game, line(game, l[1], ""), 104, l[2]) end local sp = speciesName(game, mon) - text(game, line(game, 9, "Medals won by\n" .. sp, sp), 8, 152) + text(game, line(game, 9, Strings("Medals won by\n%s", sp), sp), 8, 152) -- the OBJs: the picture, the stars and arrows, the Medals local pic = picture(game, mon) if pic then From f88942e31d1c257468e8b3cbc3a2e5dd4f312f7b Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:45:56 +0100 Subject: [PATCH 18/19] Audit current native effect registrations and register cure text sources --- src/battle/Gen4MoveEffects.lua | 10 +++++++--- tests/goldens/fixture_fingerprint.md | 11 +++++++++++ tests/goldens/fixture_fingerprint.txt | 2 +- tests/goldens/fixture_fingerprint_sections.txt | 2 +- 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/battle/Gen4MoveEffects.lua b/src/battle/Gen4MoveEffects.lua index 2bd10da81..4f1447ee2 100644 --- a/src/battle/Gen4MoveEffects.lua +++ b/src/battle/Gen4MoveEffects.lua @@ -509,9 +509,13 @@ F.REMOVE_PROTECT = { local FLAVOR_STAT = { [11] = "attack", [12] = "spatk", [13] = "speed", [14] = "spdef", [15] = "defense" } local STAT_UP = { [16] = "attack", [17] = "defense", [18] = "speed", [19] = "spatk", [20] = "spdef" } local CURE = { [1] = "PAR", [2] = "SLP", [3] = "PSN", [4] = "BRN", [5] = "FRZ" } -local CURE_TEXT = { PAR = "%s was\ncured of paralysis!", SLP = "%s woke up!", - PSN = "%s was\ncured of poisoning!", BRN = "%s's\nburn was healed!", - FRZ = "%s thawed out!" } +local CURE_TEXT = { + PAR = Strings.source("%s was\ncured of paralysis!"), + SLP = Strings.source("%s woke up!"), + PSN = Strings.source("%s was\ncured of poisoning!"), + BRN = Strings.source("%s's\nburn was healed!"), + FRZ = Strings.source("%s thawed out!"), +} local function eat(battle, eater, effect, param, def, out) local max = maxHp(eater) diff --git a/tests/goldens/fixture_fingerprint.md b/tests/goldens/fixture_fingerprint.md index d8cc8e062..55c09281f 100644 --- a/tests/goldens/fixture_fingerprint.md +++ b/tests/goldens/fixture_fingerprint.md @@ -34,3 +34,14 @@ To audit a future change, load a fresh `tests.modkit` fixture with by section, and then update only reviewed pins. Run the gate again and keep the mutation assertions enabled. The ROM-dependent vanilla golden is separate and was not re-blessed by this update. + +## Current upstream Gen4 effect registrations + +Upstream `8d5b4387` adds 53 native Gen4 effect registrations through +`Gen4MoveEffects` and the existing non-destructive registry merge. Comparing +canonical fixture surfaces against `ed5189c2` changes only `move_effects`: +53 additions, no removals, and no changed existing kind/revision records. +The other six populated sections remain byte-identical. The whole fingerprint +is now `884a4b379d3e2f83`, and the effect section is `1c01a759e13618d5`. +The production serializer, digest and all gate mutation assertions remain +unchanged. These pins acknowledge the new upstream registry surface. diff --git a/tests/goldens/fixture_fingerprint.txt b/tests/goldens/fixture_fingerprint.txt index 77ad32cd7..d43cb64a0 100644 --- a/tests/goldens/fixture_fingerprint.txt +++ b/tests/goldens/fixture_fingerprint.txt @@ -1 +1 @@ -41e69caf4afa35ab +884a4b379d3e2f83 diff --git a/tests/goldens/fixture_fingerprint_sections.txt b/tests/goldens/fixture_fingerprint_sections.txt index 2e9081fa0..4437d24e9 100644 --- a/tests/goldens/fixture_fingerprint_sections.txt +++ b/tests/goldens/fixture_fingerprint_sections.txt @@ -2,6 +2,6 @@ pokemon 0ad4d8a59c0daa59 moves 54b3cb2c1776ed48 type_chart cc5bd80d003bd459 statuses 68247ced2ed19a21 -move_effects 3bef37494ca4a845 +move_effects 1c01a759e13618d5 constants e4cf6f91ff122fa5 mods 6a9ee9de68f78902 From c89369556cf30328264a41b2d0f523785cb0c0ee Mon Sep 17 00:00:00 2001 From: Roxas2712 <41802861+Roxas2712@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:52:12 +0100 Subject: [PATCH 19/19] Verify current native Gen4 fog and poison-step band presentation --- tests/engine/gen4_performance_merge.lua | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 tests/engine/gen4_performance_merge.lua diff --git a/tests/engine/gen4_performance_merge.lua b/tests/engine/gen4_performance_merge.lua new file mode 100644 index 000000000..ddf7221cd --- /dev/null +++ b/tests/engine/gen4_performance_merge.lua @@ -0,0 +1,64 @@ +-- Copyright (c) 2026 Roxas2712. See LICENSE-ROXAS2712.md. +-- New native fog and poison-step bands must survive the draw-path merge. +local T = require("tests.harness") +love = require("tests.love_stub") +local Version = require("src.core.GameVersion") +local Performance = require("src.core.Performance") +local Fixture = require("tests.world_draw.fixture") +local GymFx = require("src.world.Gen4GymFx") +Version.set("platinum") +local originalFog = GymFx.spriteFog +for _, enabled in ipairs({ false, true }) do + Performance.worldDrawHoist = enabled + local scene = Fixture.new(9) + scene.world.map.def = { gen4DepthFog = {} } + local fogBuilds, drawn = 0, 0 + GymFx.spriteFog = function() + fogBuilds = fogBuilds + 1 + return function() return 0.25 end + end + for _, entity in ipairs(scene.world.entities) do + entity.draw = function() + drawn = drawn + 1 + local r, g, b, a = love.graphics.getColor() + T.same({ r, g, b, a }, { 0.25, 0.25, 0.25, 1 }, "native fog reaches each ordinary and top-layer sprite") + end + end + scene.world:drawWorld() + T.eq(fogBuilds, 1, "native fog provider is evaluated once per world pass") + T.eq(drawn, 9, "all native sprites retain their draw") + T.same({ love.graphics.getColor() }, { 1, 1, 1, 1 }, "sprite tint is restored after fog") +end +GymFx.spriteFog = originalFog +local Renderer = require("src.render.Renderer") +Renderer:init() +local originalBlit = Renderer.blitCanvas +for _, enabled in ipairs({ false, true }) do + Performance.hotPathHoist = enabled + Renderer:beginFrame() + Renderer:beginWorldPass() + Renderer:endWorldPass() + Renderer.worldWobble = 2 + local bands, positive, negative = 0, false, false + local firstX + Renderer.blitCanvas = function(self, canvas, sx, sy, zones, zsx, zsy, ox, oy, cx, cy, cw, ch, dpiX, dpiY) + if canvas ~= Renderer.worldCanvas then + return originalBlit(self, canvas, sx, sy, zones, zsx, zsy, ox, oy, cx, cy, cw, ch, dpiX, dpiY) + end + T.eq(self, Renderer, "native bands keep the renderer receiver") + T.eq(canvas, Renderer.worldCanvas, "native bands keep the world canvas") + T.check(type(dpiX) == "number" and type(dpiY) == "number", "band calls keep both DPI arguments") + T.check(type(cy) == "number" and ch > 0, "band calls retain a nonempty clipped region") + bands = bands + 1 + firstX = firstX or ox + if ox > firstX then positive = true end + if ox < firstX then negative = true end + return originalBlit(self, canvas, sx, sy, zones, zsx, zsy, ox, oy, cx, cy, cw, ch, dpiX, dpiY) + end + Renderer:endFrame() + T.check(bands > 2, "native poison wobble retains multiple world bands") + T.check(positive or negative, "native bands alternate their horizontal displacement") + T.eq(Renderer.worldWobble, nil, "native poison wobble remains a one-frame effect") +end +Renderer.blitCanvas = originalBlit +T.finish("current native Gen4 render integration")