25 Commits
Author SHA1 Message Date
4DBug 6e9790bf2a extensions: submodule pointers -> the rewritten extension commits on their remotes (imcurveedit-luau 4998eaf, imgradient-luau 227f1a0, imgui-memory-editor-luau 8249fe2, imnodes-luau 357fc01, imsequencer-luau d09550e; same trees as the old 9769fd0 / 21b3b2d / 3c9aca1 / 363fd65 / a911077, which no longer exist upstream)
Build & Release / build (push) Canceled after 0s
2026-10-25 06:23:44 -05:00
4DBug d1818970b5 0.4.4
Build & Release / build (push) Canceled after 0s
Performance update (Roblox), no API changes; pixels identical to 0.4.3.
- Raster: solid spans 4-8 px per loop iteration, full-width rows copied in blocks, bit32 colour unpacking (colorpicker -19%, implot -13%, fonts -16%)
- Raster: axis-aligned edges tested once per row / column, AA fringe rows with alpha 0 skipped, triangle / line quad spans from per-side edge slots, narrow spans (vertical lines, histogram bars) without row bookkeeping (plots up to -25%)
- ImPlot rect fills (heatmaps, bars) drawn as one primitive instead of two triangles (implot -3.5%)
- DirtyRects: greedy diff of a tile's old and new primitive list, so scrolling no longer redraws everything after the first shifted row (scroll: 14.1k -> 4.3k pixels rasterized per frame)
- Hover recolors skip tile hashing and redraw only the affected tiles; unrolled per-primitive vertex hash; per-command primitive data (CollectPrims -10%)
- Library: @native table layout functions, trunc helpers, ImDrawListSplitter:Merge() via table.move (demo -2..4% instructions)
- stb_truetype: CFF-only / font-init functions no longer @native, -312 KB native code (more headroom under Studio's native code budget)
- Fix: clicking right after the Studio/game window regains focus (without moving the mouse first) did nothing
- Extensions: submodules point at the current implot-luau, imguicolortextedit-luau, implot3d-luau and imguizmo-luau commits
- tests: t_recolor_pixels, t_scroll_pixels, native_size.py (native code budget check)
2026-10-25 05:44:24 -05:00
4DBug b83d09de0c Roblox backend: forget the last mouse position when the window gains / loses focus (losing focus clears imgui's mouse to unavailable and NewFrame only resends a moved mouse, so a click on return without moving first landed nowhere); rebuilt build/ImGui.luau 2026-10-25 05:44:24 -05:00
4DBug 3bac70663f build: rebuild Roblox bundle + worker (span slots, ImPlot rect pairs, greedy dirty-rect diff, per-command primitive data, table natives, trunc helpers) 2026-10-24 06:09:18 -05:00
4DBug 132660be9a tools/test: t_scroll_pixels.luau (stress window with table + wrapped text scrolling down / up, resizing from the bottom-right and the top-left, composite every 3 frames: incremental must equal a forced full redraw; catches DirtyRects list-diff mistakes) + check_all.sh 'scroll_pixels' check 2026-10-24 06:06:32 -05:00
4DBug 7c21be04de Roblox backend: a primitive's texture, texture id, vertex buffer and clip rect are its draw command's (PrimCmd -> Cmd* arrays, numbered through the frame) instead of 7 per-primitive arrays: CollectPrims writes 11 instead of 17 values per primitive, HashTiles / RasterRect / PrimHash / Parallel.Tile read them through PrimCmd (headless instructions per frame: implot -0.23M, plots -0.1M, scroll -0.09M, fonts -0.08M, resize -0.03M; CollectPrims -10%; pixels identical) 2026-10-24 05:55:53 -05:00
4DBug 8e6abeede9 Roblox DirtyRects: a greedy diff of the tile's old and new primitive list (lookahead 8 entries for the one that resyncs both, so an inserted or removed run is skipped; same flat rect: strips) instead of pairing them only by position when the counts match: a row scrolled out of or into a tile, or an entry shifted by one, no longer redraws every primitive after it. Any order-preserving pairing is exact. Two unpaired entries without a resync: the positional pass as before (mostly changed lists: new font size, animated plots) (headless: scroll PixelsRasterized 14.1k -> 4.3k/frame, Raster -25%, resize_tl 106k -> 82k px, resize 82k -> 78k px; instructions scroll -0.4M/frame, resize_tl -0.2M, others within +-0.1M; pixels identical) 2026-10-24 05:35:18 -05:00
4DBug b119b07676 Roblox HashTiles: the per-primitive vertex hash unrolled (2 vertices for quads, 3 for triangles, 4 for line quads / triangle pairs; was a loop with a branch per vertex; same math, same order: hashes identical) (headless instructions: scroll -0.1M/frame, resize -0.06M; Hash stage -5..9% plots/implot) 2026-10-24 05:34:25 -05:00
4DBug 9ef8a623cc tools/test/native_size.py: native code size of the bundle per module / source file / function vs the Studio limit (one script's native code must fit one ~4 MB block or none of it is compiled; measured in Studio: native at 4,083,418 bytes, interpreted from 4,103,258; master 3,153,274 = 77%, ~900 KB headroom); check_all.sh 'native' check; PORTING.md note 2026-10-24 05:33:08 -05:00
4DBug ff7a04187c Tables: @native TableUpdateLayout(), TableSetupDrawChannels(), TableSetupColumnFlags() (once per table per frame, the largest interpreted cost of table-heavy windows: demo_all -2.5% instructions; +176 KB native code, paid for by the stb_truetype trim; draw data identical) 2026-10-24 04:54:21 -05:00
4DBug b87012f08f stb_truetype: no @native on CFF-only functions (charstring interpreter, CFF index/dict parsing, cubic tesselation) and font-init-only ones (InitFont, table directory): never run per frame for TrueType fonts, native code -312 KB (Studio shares one native code budget across scripts); per-frame cost unchanged (fonts scenario instructions identical), startup -3% instructions (less to compile) 2026-10-24 04:54:21 -05:00
4DBug ca621e1082 Trunc helpers: _Trunc/ImTrunc @native, ImTrunc64 its own hoisted function (was an alias of _Trunc: AddRect()/AddRectFilled() called a non-native function per rect), IM_TRUNC/IM_ROUND hoisted + @native; bundle.py: A's local budget counts the hoisted functions (main chunk stays under 200 locals) (demo_all -1.7% instructions; draw data identical) 2026-10-24 04:54:21 -05:00
4DBug f2658b755e ImDrawListSplitter:Merge(): copy each channel's indices with table.move() (upstream memcpy) instead of a per-index loop in interpreted code (stress hover -0.8% instructions; draw data identical) 2026-10-24 04:54:21 -05:00
4DBug 620660ccf9 Roblox backend: flat triangle pairs a b c + a b d (ImPlot PrimRectFill: heatmap cells, bars; one colour, one uv) are one primitive (kind 5): per row both triangles' spans exactly as DrawTriangle computes them, one fill where they touch (opaque: or overlap), else each in order; pairs DrawTriangle would walk by columns, or degenerate ones, still go to the two calls (tile hash kind field * 8; replay: implot -3.5%; randomized 800k cases vs the two DrawTriangle calls identical; pixels identical) 2026-10-24 04:30:29 -05:00
4DBug 5ae58c6b57 Roblox raster: narrow flat spans (opaque <= 8 px, translucent <= 4 px wide: vertical lines, histogram bars) skip the uniform-row bookkeeping and only mark pending damage; translucent ones blend per pixel (cached per destination value), one pixel wide in one loop down the column (replay: plots -13%, implot -3%, resize -2%; pixels identical) 2026-10-24 04:16:31 -05:00
4DBug 8520257086 Roblox raster: triangle / line quad spans from per-side edge slots (one estimate + short search per side, no per-edge branches per row; horizontal / vertical edges bound the row / column range once), line quad texels blended without the per-texel cache and opaque-texel branches (replay: implot -5%, plots -5%, colorpicker -2.5%; pixels identical) 2026-10-24 04:08:59 -05:00
4DBug 8611bfb4ed build: rebuild Roblox bundle + worker (recolor patch, unrolled span/row writes, axis-aligned edge and alpha-0 edge skips) 2026-10-23 23:52:00 -05:00
4DBug b3e9390653 extensions: submodule pointers -> the rewritten extension commits on their remotes (implot-luau 7199224, imguicolortextedit-luau a340940, implot3d-luau 6ff7fb1, imguizmo-luau a71a223; same trees as the old 2bc5700 / 0592ed6 / b30d2ff / 93f4569, which no longer exist upstream) 2026-10-23 23:51:47 -05:00
4DBug 752ae2e887 Roblox raster: vertex-colour triangles skip a row / column lying on an edge whose two vertices have alpha 0 (an AA fringe's outer edge sits on pixel centres; the interpolated alpha is exactly 0 there, so it drew nothing) (replay: plots -3%, resize -1.5%; pixels identical) 2026-10-23 23:41:50 -05:00
4DBug c0fc18177f Roblox raster: an axis-aligned edge (A = 0 for rows, B = 0 for columns) is tested once per row / column instead of per pixel by the span search: AA fringes and shaded fills next to a vertical / horizontal edge no longer scan empty rows / columns pixel by pixel (replay: implot -8%, plots -12%, resize -5%; pixels identical) 2026-10-23 23:39:02 -05:00
4DBug 5c076f65d5 Roblox raster: solid spans 4-8 pixels per loop iteration (FillRow; a native loop iteration costs more than a few writes), opaque column walks 4 rows per iteration, translucent black over opaque 4 pixels per iteration without the cache (colour picker SV square), full-width span rows copied in doubling blocks (CopyRows), bit32 colour unpacking instead of % / floor (replay in Studio: colorpicker -19%, implot -13%, fonts -16%; pixels identical) 2026-10-23 23:39:02 -05:00
4DBug d1db51dded Roblox backend: PatchDrawList skips primitives with no vertex in the listed vertices' offset range before the DriftSet lookups (hover recolor patch -25%, drift moves too) 2026-10-23 23:19:40 -05:00
4DBug cef7a1209e Roblox backend: recolored draw lists (same vertex positions, a few vertices' colour / uv changed, e.g. hover) skip HashTiles: CompareDrawList 4 lists them, PatchDrawList gives those primitives their real hashes (PrimHash / FlatTileHash) and redraws just their tiles, leaving the tiles exactly as the full path would; t_recolor_pixels (incremental vs forced, also parallel) in check_all 2026-10-23 23:19:40 -05:00
4DBug 951d18fda2 Roblox backend: HashTiles mixes the primitive kind into its bounds term instead of two extra % after the second vertex (gradient rects, ImPlot line quads; implot Hash -4%, same pixels) 2026-10-23 23:19:40 -05:00
4DBug 006c8c4a34 tools/test: prof.py finds run.py's linemap in $TMPDIR (tempfile.mkdtemp), not only /tmp 2026-10-23 22:32:53 -05:00
31 changed files with 2869 additions and 746 deletions

No files matched your search

+1 -1
View File
@@ -116,7 +116,7 @@ The Style Editor (`ImGui.ShowStyleEditor()`) and the Metrics/Debugger (`ImGui.Sh
### Getting Started & Integration (Roblox) ### Getting Started & Integration (Roblox)
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/[email protected].3"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source: With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/[email protected].4"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source:
1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped. 1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped.
2. Sync with [Rojo](https://rojo.space): [`default.project.json`](/default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`. 2. Sync with [Rojo](https://rojo.space): [`default.project.json`](/default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`.
+1 -1
View File
@@ -113,7 +113,7 @@ The Style Editor (`ImGui.ShowStyleEditor()`) and the Metrics/Debugger (`ImGui.Sh
### Getting Started & Integration (Roblox) ### Getting Started & Integration (Roblox)
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/[email protected].3"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source: With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/[email protected].4"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source:
1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped. 1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped.
2. Sync with [Rojo](https://rojo.space): [`default.project.json`](default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`. 2. Sync with [Rojo](https://rojo.space): [`default.project.json`](default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`.
+11 -3
View File
@@ -140,7 +140,7 @@ function ImGui_ImplRoblox_Init(parent, render_scale)
Textures = Textures.Records, MouseX = -1, MouseY = -1, Textures = Textures.Records, MouseX = -1, MouseY = -1,
Layers = {}, Overlays = {}, OverlayHolders = {}, OverlayShown = {}, FrameNo = 0, Scale = render_scale or 1, Layers = {}, Overlays = {}, OverlayHolders = {}, OverlayShown = {}, FrameNo = 0, Scale = render_scale or 1,
TilesActive = false, RenderRate = 60, BusyRenderRate = 0, RedrawBudget = 0, HeartbeatCount = 0, TilesActive = false, RenderRate = 60, BusyRenderRate = 0, RedrawBudget = 0, HeartbeatCount = 0,
NextRender = 0, LastPrimCount = 0, ForceRedraw = true, NextRender = 0, LastCmdCount = 0, ForceRedraw = true,
} }
io.BackendPlatformUserData = BackendData io.BackendPlatformUserData = BackendData
EditableImages.Backends[BackendData] = true EditableImages.Backends[BackendData] = true
@@ -217,8 +217,16 @@ function ImGui_ImplRoblox_Init(parent, render_scale)
BackendData.HeartbeatCount += 1 BackendData.HeartbeatCount += 1
end) end)
connect(UserInputService.WindowFocused, function() ImGui.GetIO():AddFocusEvent(true) end) -- (losing focus clears imgui's mouse to "unavailable"; NewFrame only resends a moved mouse, so on return forget the
connect(UserInputService.WindowFocusReleased, function() ImGui.GetIO():AddFocusEvent(false) end) -- last position: a click on a field without moving the mouse first would otherwise land nowhere)
connect(UserInputService.WindowFocused, function()
ImGui.GetIO():AddFocusEvent(true)
BackendData.MouseX, BackendData.MouseY = nil, nil
end)
connect(UserInputService.WindowFocusReleased, function()
ImGui.GetIO():AddFocusEvent(false)
BackendData.MouseX, BackendData.MouseY = nil, nil
end)
end end
-- Text proxy (opt-in): a hidden TextBox holds focus while a text field is active (OS typing, paste, copy/cut) -- Text proxy (opt-in): a hidden TextBox holds focus while a text field is active (OS typing, paste, copy/cut)
+17 -7
View File
@@ -170,7 +170,8 @@ function M.DestroyTiles(BackendData)
end end
-- Snapshot compared exactly with the next frame's list: 1 = identical (only restack), 2 = moved by whole pixels -- Snapshot compared exactly with the next frame's list: 1 = identical (only restack), 2 = moved by whole pixels
-- (only move the layers), 0 = changed. Per command: clip (4 f64), ElemCount, IdxOffset, VtxOffset (u32), tex id -- (only move the layers), 3 = moved with drifted vertices, 4 = same positions, a few vertices' uv / colour changed
-- (both list those in Drift), 0 = changed. Per command: clip (4 f64), ElemCount, IdxOffset, VtxOffset (u32), tex id
-- (f64), kind (u8), unclipped (u8), bounds of its primitives (4 x i32). -- (f64), kind (u8), unclipped (u8), bounds of its primitives (4 x i32).
local CMD_STRIDE = 70 local CMD_STRIDE = 70
@@ -291,17 +292,24 @@ function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
-- translation from the first vertex: whole pixels only, and only with DisplayPos at 0 (so it stays exact) -- translation from the first vertex: whole pixels only, and only with DisplayPos at 0 (so it stays exact)
local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8) local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8)
if dx ~= dx or dy ~= dy then return 0 end if dx ~= dx or dy ~= dy then return 0 end
local nd = 0
if dx == 0 and dy == 0 then if dx == 0 and dy == 0 then
-- per vertex: x y u v as f64s + col, not readstring == (that allocated 2 vertex-buffer strings per list per -- per vertex: x y u v as f64s + col, not readstring == (that allocated 2 vertex-buffer strings per list per
-- frame: GC spikes) or 9 u32s (3x slower). Equal f64s have equal bits except +-0: their sign words decide. -- frame: GC spikes) or 9 u32s (3x slower). Equal f64s have equal bits except +-0: their sign words decide.
-- Same position, other uv / colour (hover, a changed colour): listed ("recolored"), up to MAX_DRIFT.
for v = 0, nv - VTX_STRIDE, VTX_STRIDE do for v = 0, nv - VTX_STRIDE, VTX_STRIDE do
local x, y, u, w = readf64(vb, v), readf64(vb, v + 8), readf64(vb, v + 16), readf64(vb, v + 24) local x, y, u, w = readf64(vb, v), readf64(vb, v + 8), readf64(vb, v + 16), readf64(vb, v + 24)
if x ~= readf64(sv, v) or y ~= readf64(sv, v + 8) or u ~= readf64(sv, v + 16) if x ~= readf64(sv, v) or y ~= readf64(sv, v + 8) then return 0 end
or w ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32) then if (x == 0 or y == 0)
and (readu32(vb, v + 4) ~= readu32(sv, v + 4) or readu32(vb, v + 12) ~= readu32(sv, v + 12)) then
return 0 return 0
end end
if x == 0 or y == 0 or u == 0 or w == 0 then if u ~= readf64(sv, v + 16) or w ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32)
for p = v + 4, v + 28, 8 do if readu32(vb, p) ~= readu32(sv, p) then return 0 end end or ((u == 0 or w == 0)
and (readu32(vb, v + 20) ~= readu32(sv, v + 20) or readu32(vb, v + 28) ~= readu32(sv, v + 28))) then
if nd >= MAX_DRIFT then return 0 end
nd += 1
Drift[nd] = v
end end
end end
else else
@@ -361,7 +369,9 @@ function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
or draw_list._ContentClipY0 ~= set.SnapContentY0 or draw_list._ContentClipX1 ~= set.SnapContentX1 or draw_list._ContentClipY0 ~= set.SnapContentY0 or draw_list._ContentClipX1 ~= set.SnapContentX1
or draw_list._ContentClipY1 ~= set.SnapContentY1 or draw_list._ScrollOriginX ~= set.SnapScrollX or draw_list._ContentClipY1 ~= set.SnapContentY1 or draw_list._ScrollOriginX ~= set.SnapScrollX
or draw_list._ScrollOriginY ~= set.SnapScrollY) then return 0 end or draw_list._ScrollOriginY ~= set.SnapScrollY) then return 0 end
return 1 if nd == 0 then return 1 end
M.DriftCount = nd
return 4, 0, 0
end end
if set.SnapHasContent and not (ShiftedExact(set.SnapContentX0, dx, draw_list._ContentClipX0) if set.SnapHasContent and not (ShiftedExact(set.SnapContentX0, dx, draw_list._ContentClipX0)
and ShiftedExact(set.SnapContentY0, dy, draw_list._ContentClipY0) and ShiftedExact(set.SnapContentY0, dy, draw_list._ContentClipY0)
@@ -372,7 +382,7 @@ function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
-- vertices off the exact shift ("drift": trig-generated ones round differently, often when a coordinate crosses a -- vertices off the exact shift ("drift": trig-generated ones round differently, often when a coordinate crosses a
-- power of two) are listed. All their floor / ceil / ceil(- 0.5) (CollectPrims' bounds) shifted: 3, only the tiles -- power of two) are listed. All their floor / ceil / ceil(- 0.5) (CollectPrims' bounds) shifted: 3, only the tiles
-- of their primitives change; else 0 (the full path still gets the list: tile hashes don't see an ulp) -- of their primitives change; else 0 (the full path still gets the list: tile hashes don't see an ulp)
local nd, consistent = 0, true local consistent = true
for v = 0, nv - VTX_STRIDE, VTX_STRIDE do for v = 0, nv - VTX_STRIDE, VTX_STRIDE do
if readf64(vb, v + 16) ~= readf64(sv, v + 16) or readf64(vb, v + 24) ~= readf64(sv, v + 24) if readf64(vb, v + 16) ~= readf64(sv, v + 16) or readf64(vb, v + 24) ~= readf64(sv, v + 24)
or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end or readu32(vb, v + 32) ~= readu32(sv, v + 32) then return 0 end
+17 -15
View File
@@ -6,13 +6,14 @@ local Render = IM_INCLUDE("roblox/render.lua")
local Players = game:GetService("Players") local Players = game:GetService("Players")
local EditableImages, Records = Textures.EditableImages, Textures.Records local EditableImages, Records = Textures.EditableImages, Textures.Records
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = Render.PrimA, Render.PrimB, Render.PrimC, Render.PrimD, local PrimA, PrimB, PrimC, PrimD, PrimGradient = Render.PrimA, Render.PrimB, Render.PrimC, Render.PrimD,
Render.PrimTexture, Render.PrimGradient Render.PrimGradient
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = Render.PrimClipX0, Render.PrimClipY0, Render.PrimClipX1, local PrimCmd, CmdTexture, CmdTexId, CmdVtxBuffer = Render.PrimCmd, Render.CmdTexture, Render.CmdTexId,
Render.PrimClipY1 Render.CmdVtxBuffer
local CmdClipX0, CmdClipY0, CmdClipX1, CmdClipY1 = Render.CmdClipX0, Render.CmdClipY0, Render.CmdClipX1,
Render.CmdClipY1
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = Render.PrimBoundsX0, Render.PrimBoundsY0, local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = Render.PrimBoundsX0, Render.PrimBoundsY0,
Render.PrimBoundsX1, Render.PrimBoundsY1 Render.PrimBoundsX1, Render.PrimBoundsY1
local PrimTexId, PrimVtxBuffer = Render.PrimTexId, Render.PrimVtxBuffer
local M = Render.Parallel local M = Render.Parallel
local writei32, writef64, copy = buffer.writei32, buffer.writef64, buffer.copy local writei32, writef64, copy = buffer.writei32, buffer.writef64, buffer.copy
@@ -162,28 +163,29 @@ function M.Tile(img, list, count: number, x0: number, y0: number, tox: number, t
local p = list[k] local p = list[k]
if stamp[p] ~= st then if stamp[p] ~= st then
stamp[p], poff[p] = st, pn stamp[p], poff[p] = st, pn
local d, t = PrimD[p], PrimTexture[p] local cmd = PrimCmd[p]
local d, t = PrimD[p], CmdTexture[cmd]
local gk = PrimGradient[p] local gk = PrimGradient[p]
writei32(P, pn, d and (gk and gk + 1 or 1) or 0) writei32(P, pn, d and (gk and gk + 1 or 1) or 0)
writei32(P, pn + 4, t and PrimTexId[p] or -1) writei32(P, pn + 4, t and CmdTexId[cmd] or -1)
if t then if t then
u[t] = PrimTexId[p] u[t] = CmdTexId[cmd]
end end
writei32(P, pn + 8, PrimClipX0[p]) writei32(P, pn + 8, CmdClipX0[cmd])
writei32(P, pn + 12, PrimClipY0[p]) writei32(P, pn + 12, CmdClipY0[cmd])
writei32(P, pn + 16, PrimClipX1[p]) writei32(P, pn + 16, CmdClipX1[cmd])
writei32(P, pn + 20, PrimClipY1[p]) writei32(P, pn + 20, CmdClipY1[cmd])
writei32(P, pn + 24, PrimBoundsX0[p]) writei32(P, pn + 24, PrimBoundsX0[p])
writei32(P, pn + 28, PrimBoundsY0[p]) writei32(P, pn + 28, PrimBoundsY0[p])
writei32(P, pn + 32, PrimBoundsX1[p]) writei32(P, pn + 32, PrimBoundsX1[p])
writei32(P, pn + 36, PrimBoundsY1[p]) writei32(P, pn + 36, PrimBoundsY1[p])
local vb = PrimVtxBuffer[p] local vb = CmdVtxBuffer[cmd]
copy(P, pn + REC_A, vb, PrimA[p], VTX) copy(P, pn + REC_A, vb, PrimA[p], VTX)
copy(P, pn + REC_C, vb, PrimC[p], VTX) copy(P, pn + REC_C, vb, PrimC[p], VTX)
if not d or gk == 3 then if not d or gk == 3 or gk == 4 then
copy(P, pn + REC_B, vb, PrimB[p], VTX) copy(P, pn + REC_B, vb, PrimB[p], VTX)
end end
if gk == 3 then copy(P, pn + REC_D, vb, d, VTX) end if gk == 3 or gk == 4 then copy(P, pn + REC_D, vb, d, VTX) end
pn += REC pn += REC
end end
writei32(T, to, poff[p]) writei32(T, to, poff[p])
+595 -147
View File
@@ -9,9 +9,9 @@ local readi32 = buffer.readi32
local M = { local M = {
TILE = 128, TILE = 128,
-- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs. -- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs.
-- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad), tex id (-1: none), -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad, 5 triangle pair), tex id
-- clip x0 y0 x1 y1, bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64, -- (-1: none), clip x0 y0 x1 y1, bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v
-- col u32): a at REC_A, c at REC_C, b at REC_B, d at REC_D. -- f64, col u32): a at REC_A, c at REC_C, b at REC_B, d at REC_D.
-- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32). -- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32).
VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32, VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32,
} }
@@ -33,6 +33,53 @@ local function PairF64(v: number): number | false
writeu32(PairScratch, 4, v) writeu32(PairScratch, 4, v)
return readf64(PairScratch, 0) return readf64(PairScratch, 0)
end end
-- Solid span [o, o1] (byte offsets of its first and last pixel) of value packed (pair: PairF64(packed) or false). A
-- native loop iteration costs more than a few writes: 8 (pairs) or 4 pixels per iteration.
@native
local function FillRow(buf: buffer, o: number, o1: number, packed: number, pair: number | false)
if pair then
while o + 24 < o1 do
writef64(buf, o, pair)
writef64(buf, o + 8, pair)
writef64(buf, o + 16, pair)
writef64(buf, o + 24, pair)
o += 32
end
while o < o1 do
writef64(buf, o, pair)
o += 8
end
if o == o1 then writeu32(buf, o, packed) end
return
end
while o + 12 <= o1 do
writeu32(buf, o, packed)
writeu32(buf, o + 4, packed)
writeu32(buf, o + 8, packed)
writeu32(buf, o + 12, packed)
o += 16
end
while o <= o1 do
writeu32(buf, o, packed)
o += 4
end
end
-- Rows 1 .. n - 1 below the span at o (len bytes) get its pixels. A span as wide as the target: the rows are
-- contiguous, copied in doubling blocks (log2 n calls instead of n).
@native
local function CopyRows(buf: buffer, o: number, len: number, n: number)
local stride = TargetWidth * 4
if len == stride then
local done = 1
while done < n do
local c = min(done, n - done)
buffer.copy(buf, o + done * stride, buf, o, c * stride)
done += c
end
else
for k = 1, n - 1 do buffer.copy(buf, o + k * stride, buf, o, len) end
end
end
local PrevRow = buffer.create(1024) local PrevRow = buffer.create(1024)
-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else -- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else
@@ -133,34 +180,30 @@ end
local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number, local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number,
b: number, a: number) b: number, a: number)
if a <= 0 then return end if a <= 0 then return end
if PX0 < PX1 then
ApplyDamage(PX0, PY0, PX1, PY1)
PX1 = PX0
end
local w4 = (x1 - x0 - 1) * 4 local w4 = (x1 - x0 - 1) * 4
local span = x1 - x0 local span = x1 - x0
if a >= 255 and span <= 8 then
-- opaque and narrow (vertical lines, histogram bars): writes (a call per row costs more), and the uniform rows
-- just lose the span (pending damage, merged with the neighbours' like any primitive's), no per-row bookkeeping:
-- a narrow span rarely becomes the larger uniform piece of its rows
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local stride = TargetWidth * 4
local first = (y0 * TargetWidth + x0) * 4 + TargetBase
for o = first, first + (y1 - y0 - 1) * stride, stride do
for oo = o, o + w4, 4 do writeu32(TargetBuffer, oo, packed) end
end
Shrink(x0, y0, x1, y1)
return
end
if a >= 255 then if a >= 255 then
if PX0 < PX1 then
ApplyDamage(PX0, PY0, PX1, PY1)
PX1 = PX0
end
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local first = (y0 * TargetWidth + x0) * 4 + TargetBase local first = (y0 * TargetWidth + x0) * 4 + TargetBase
local pair = span >= 16 and PairF64(packed) FillRow(TargetBuffer, first, first + w4, packed, span >= 16 and PairF64(packed))
if pair then CopyRows(TargetBuffer, first, w4 + 4, y1 - y0)
local o, o1 = first, first + w4
while o < o1 do
writef64(TargetBuffer, o, pair)
o += 8
end
if o == o1 then writeu32(TargetBuffer, o, packed) end
else
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end
end
if span <= 8 then -- narrow (vertical lines): writes, a call per row costs more
local stride = TargetWidth * 4
for o = first + stride, first + (y1 - y0 - 1) * stride, stride do
for oo = o, o + w4, 4 do writeu32(TargetBuffer, oo, packed) end
end
else
for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4 + TargetBase, TargetBuffer, first, w4 + 4) end
end
-- now uniform: per row keep whichever piece is larger (the same for following rows with the same piece) -- now uniform: per row keep whichever piece is larger (the same for following rows with the same piece)
local y = y0 local y = y0
while y < y1 do while y < y1 do
@@ -190,6 +233,46 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
local rs, gs, bs = r * sa, g * sa, b * sa local rs, gs, bs = r * sa, g * sa, b * sa
local black = rs == 0 and gs == 0 and bs == 0 local black = rs == 0 and gs == 0 and bs == 0
local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination
if span <= 4 then
-- narrow (vertical lines): blended per pixel (the uniform-row lookups per row cost more than the blend, which
-- is cached per destination value, the same result as the uniform path's); the rows just lose the span
-- (pending damage, like a narrow opaque span)
local stride = TargetWidth * 4
local first = (y0 * TargetWidth + x0) * 4 + TargetBase
-- rows x pixels; one pixel wide: one loop down the column
local olast, ilen, istep = first + (y1 - y0 - 1) * stride, w4, 4
if span == 1 then olast, ilen, istep = first, olast - first, stride end
for o0 = first, olast, stride do
for o = o0, o0 + ilen, istep do
local d = readu32(TargetBuffer, o)
if d == last_d then
writeu32(TargetBuffer, o, last_v)
elseif d < 16777216 then
writeu32(TargetBuffer, o, packed0)
else
last_d = d
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256
+ floor(bs + db * ns + 0.5) * 65536 + 4278190080
else
local k = rshift(d, 24) * c1
local oa = sa + k
local inv = 1 / oa
last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256
+ floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(TargetBuffer, o, last_v)
end
end
end
Shrink(x0, y0, x1, y1)
return
end
if PX0 < PX1 then
ApplyDamage(PX0, PY0, PX1, PY1)
PX1 = PX0
end
local prev_o, prev_v = 0, -1 -- previous row: filled with prev_v (-1: blended) local prev_o, prev_v = 0, -1 -- previous row: filled with prev_v (-1: blended)
local wide, has_prev = span >= 32 and y1 - y0 > 1, false local wide, has_prev = span >= 32 and y1 - y0 > 1, false
local y = y0 local y = y0
@@ -222,17 +305,7 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
if v == prev_v and span > 8 then -- (a call: slower than a few writes) if v == prev_v and span > 8 then -- (a call: slower than a few writes)
buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4) buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4)
else else
local pair = span >= 16 and PairF64(v) FillRow(TargetBuffer, o0, o0 + w4, v, span >= 16 and PairF64(v))
if pair then
local o, o1 = o0, o0 + w4
while o < o1 do
writef64(TargetBuffer, o, pair)
o += 8
end
if o == o1 then writeu32(TargetBuffer, o, v) end
else
for o = o0, o0 + w4, 4 do writeu32(TargetBuffer, o, v) end
end
end end
local na, nb, nv = ra, rb, d local na, nb, nv = ra, rb, d
if span >= x0 - ra and span >= rb - x1 then if span >= x0 - ra and span >= rb - x1 then
@@ -245,16 +318,21 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
RowX0[y], RowX1[y], RowV[y] = na, nb, nv RowX0[y], RowX1[y], RowV[y] = na, nb, nv
y += 1 y += 1
local stride = TargetWidth * 4 local stride = TargetWidth * 4
local o = o0 local n = 1
while y < y1 and RowX0[y] == ra and RowX1[y] == rb and RowV[y] == d do while y < y1 and RowX0[y] == ra and RowX1[y] == rb and RowV[y] == d do
o += stride
if span <= 8 then
for oo = o, o + w4, 4 do writeu32(TargetBuffer, oo, v) end
else
buffer.copy(TargetBuffer, o, TargetBuffer, o0, w4 + 4)
end
RowX0[y], RowX1[y], RowV[y] = na, nb, nv RowX0[y], RowX1[y], RowV[y] = na, nb, nv
y += 1 y += 1
n += 1
end
local o = o0 + (n - 1) * stride
if n > 1 then
if span <= 8 then
for oy = o0 + stride, o, stride do
for oo = oy, oy + w4, 4 do writeu32(TargetBuffer, oo, v) end
end
else
CopyRows(TargetBuffer, o0, w4 + 4, n)
end
end end
prev_o, prev_v, has_prev = o, v, false prev_o, prev_v, has_prev = o, v, false
continue continue
@@ -275,7 +353,27 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
prev_o, prev_v = o0, -1 prev_o, prev_v = o0, -1
if black then if black then
-- (black: rs + x is x, so the opaque case is just the scaled destination; colour picker SV square) -- (black: rs + x is x, so the opaque case is just the scaled destination; colour picker SV square)
for o = o0, o0 + w4, 4 do -- opaque destination pixels four per iteration, computed directly (rarely repeated: no cache)
local o, oe = o0, o0 + w4
while o + 8 < oe do
local d, d2 = readu32(TargetBuffer, o), readu32(TargetBuffer, o + 4)
local d3, d4 = readu32(TargetBuffer, o + 8), readu32(TargetBuffer, o + 12)
if d < 4278190080 or d2 < 4278190080 or d3 < 4278190080 or d4 < 4278190080 then break end
writeu32(TargetBuffer, o,
floor(band(d, 255) * ns + 0.5) + floor(band(rshift(d, 8), 255) * ns + 0.5) * 256
+ floor(band(rshift(d, 16), 255) * ns + 0.5) * 65536 + 4278190080)
writeu32(TargetBuffer, o + 4,
floor(band(d2, 255) * ns + 0.5) + floor(band(rshift(d2, 8), 255) * ns + 0.5) * 256
+ floor(band(rshift(d2, 16), 255) * ns + 0.5) * 65536 + 4278190080)
writeu32(TargetBuffer, o + 8,
floor(band(d3, 255) * ns + 0.5) + floor(band(rshift(d3, 8), 255) * ns + 0.5) * 256
+ floor(band(rshift(d3, 16), 255) * ns + 0.5) * 65536 + 4278190080)
writeu32(TargetBuffer, o + 12,
floor(band(d4, 255) * ns + 0.5) + floor(band(rshift(d4, 8), 255) * ns + 0.5) * 256
+ floor(band(rshift(d4, 16), 255) * ns + 0.5) * 65536 + 4278190080)
o += 16
end
for o = o, oe, 4 do
local d = readu32(TargetBuffer, o) local d = readu32(TargetBuffer, o)
if d ~= last_d then if d ~= last_d then
last_d = d last_d = d
@@ -326,7 +424,7 @@ end
@native @native
local function UnpackColor(col: number) local function UnpackColor(col: number)
return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 return band(col, 255), band(rshift(col, 8), 255), band(rshift(col, 16), 255), rshift(col, 24)
end end
@native @native
@@ -402,7 +500,7 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
continue continue
end end
local d, key, al = 0, -1, 0 local d, key, al = 0, -1, 0
if tv % 16777216 == 16777215 then if band(tv, 16777215) == 16777215 then
al = rshift(tv, 24) al = rshift(tv, 24)
d = readu32(dbuf, o) d = readu32(dbuf, o)
key = gen + d key = gen + d
@@ -489,10 +587,14 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0 local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0
-- UnpackColor / SampleTexture inlined (a call costs more than the math) -- UnpackColor / SampleTexture inlined (a call costs more than the math)
local ca, cb, cc = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), readu32(vbuf, vc + 32) local ca, cb, cc = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), readu32(vbuf, vc + 32)
local ra, ga, ba, aa = ca % 256, floor(ca / 256) % 256, floor(ca / 65536) % 256, floor(ca / 16777216) % 256 local ra, ga, ba, aa = band(ca, 255), band(rshift(ca, 8), 255), band(rshift(ca, 16), 255), rshift(ca, 24)
local rb, gb, bb, ab, rc, gc, bc, ac = ra, ga, ba, aa, ra, ga, ba, aa local rb, gb, bb, ab, rc, gc, bc, ac = ra, ga, ba, aa, ra, ga, ba, aa
if cb ~= ca then rb, gb, bb, ab = cb % 256, floor(cb / 256) % 256, floor(cb / 65536) % 256, floor(cb / 16777216) % 256 end if cb ~= ca then
if cc ~= ca then rc, gc, bc, ac = cc % 256, floor(cc / 256) % 256, floor(cc / 65536) % 256, floor(cc / 16777216) % 256 end rb, gb, bb, ab = band(cb, 255), band(rshift(cb, 8), 255), band(rshift(cb, 16), 255), rshift(cb, 24)
end
if cc ~= ca then
rc, gc, bc, ac = band(cc, 255), band(rshift(cc, 8), 255), band(rshift(cc, 16), 255), rshift(cc, 24)
end
local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16), local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16),
readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
@@ -535,33 +637,86 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
if cconst then r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 end if cconst then r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 end
local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0
if textured then tw, th, tbuf = t.Width, t.Height, t.Buffer end if textured then tw, th, tbuf = t.Width, t.Height, t.Buffer end
-- Interpolated alpha on an edge whose two vertices have alpha 0 (an AA fringe's outer edge, which sits on pixel
-- centres) is 0: the edge's own weight is 0 there, so a row / column on it draws nothing
local interp = not flat and not cconst
local z0, z1, z2 = interp and ab == 0 and ac == 0, interp and aa == 0 and ac == 0, interp and aa == 0 and ab == 0
if not textured and (maxx - minx) * 2 < maxy - miny then if not textured and (maxx - minx) * 2 < maxy - miny then
-- tall sliver (vertical AA fringe): walk columns, same per-pixel edge and colour math as the rows below (each -- tall sliver (vertical AA fringe): walk columns, same per-pixel edge and colour math as the rows below (each
-- pixel blended once, so the order does not matter): no empty-row passes -- pixel blended once, so the order does not matter): no empty-row passes
local m0, m1, m2 = B0 ~= 0 and -1 / B0 or 0, B1 ~= 0 and -1 / B1 or 0, B2 ~= 0 and -1 / B2 or 0 -- (edge slots like the rows below, along y: B > 0 bounds a column from above, B < 0 from below; an edge with
-- B = 0 (vertical: w is the same on the whole column, B * py is 0) passes a run of columns: the column range)
local T1A, T1B, T1C, T1M, T1t, T2A, T2B, T2C, T2M, T2t = 0, 0, 1e9, -1, false, 0, 0, 1e9, -1, false
local U1A, U1B, U1C, U1M, U1t, U2A, U2B, U2C, U2M, U2t = 0, 0, 1e9, 1, false, 0, 0, 1e9, 1, false
local VA, VC, Vtl, Vz = 0, 1e9, false, false
local t1, u1 = false, false -- (slot 1 taken)
if B0 > 0 then
T1A, T1B, T1C, T1M, T1t, t1 = A0, B0, C0, -1 / B0, tl0, true
elseif B0 < 0 then
U1A, U1B, U1C, U1M, U1t, u1 = A0, B0, C0, -1 / B0, tl0, true
else
VA, VC, Vtl, Vz = A0, C0, tl0, z0
end
if B1 > 0 then
if not t1 then
T1A, T1B, T1C, T1M, T1t, t1 = A1, B1, C1, -1 / B1, tl1, true
else
T2A, T2B, T2C, T2M, T2t = A1, B1, C1, -1 / B1, tl1
end
elseif B1 < 0 then
if not u1 then
U1A, U1B, U1C, U1M, U1t, u1 = A1, B1, C1, -1 / B1, tl1, true
else
U2A, U2B, U2C, U2M, U2t = A1, B1, C1, -1 / B1, tl1
end
else
VA, VC, Vtl, Vz = A1, C1, tl1, z1
end
if B2 > 0 then
if not t1 then
T1A, T1B, T1C, T1M, T1t, t1 = A2, B2, C2, -1 / B2, tl2, true
else
T2A, T2B, T2C, T2M, T2t = A2, B2, C2, -1 / B2, tl2
end
elseif B2 < 0 then
if not u1 then
U1A, U1B, U1C, U1M, U1t, u1 = A2, B2, C2, -1 / B2, tl2, true
else
U2A, U2B, U2C, U2M, U2t = A2, B2, C2, -1 / B2, tl2
end
else
VA, VC, Vtl, Vz = A2, C2, tl2, z2
end
if VA ~= 0 then
local py = miny + 0.5
while minx <= maxx do
local w = VA * (minx + 0.5) + (0 * py + VC)
if (w > 0 or (w == 0 and Vtl)) and not (w == 0 and Vz) then break end
minx += 1
end
while maxx > minx do
local w = VA * (maxx + 0.5) + (0 * py + VC)
if (w > 0 or (w == 0 and Vtl)) and not (w == 0 and Vz) then break end
maxx -= 1
end
end
local stride = TargetWidth * 4 local stride = TargetWidth * 4
for x = minx, maxx do for x = minx, maxx do
local px = x + 0.5 local px = x + 0.5
local yt, yb = miny, maxy local f1, f2, g1, g2 = T1A * px + T1C, T2A * px + T2C, U1A * px + U1C, U2A * px + U2C
local f0, f1, f2 = A0 * px + C0, A1 * px + C1, A2 * px + C2 local yt = max(miny, floor(f1 * T1M - 0.500001), floor(f2 * T2M - 0.500001))
if B0 > 0 then yt = max(yt, floor(f0 * m0 - 0.500001)) elseif B0 < 0 then yb = min(yb, ceil(f0 * m0 - 0.499999)) end local yb = min(maxy, ceil(g1 * U1M - 0.499999), ceil(g2 * U2M - 0.499999))
if B1 > 0 then yt = max(yt, floor(f1 * m1 - 0.500001)) elseif B1 < 0 then yb = min(yb, ceil(f1 * m1 - 0.499999)) end
if B2 > 0 then yt = max(yt, floor(f2 * m2 - 0.500001)) elseif B2 < 0 then yb = min(yb, ceil(f2 * m2 - 0.499999)) end
while yt <= yb do while yt <= yb do
local py = yt + 0.5 local py = yt + 0.5
local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) local w1, w2 = T1A * px + (T1B * py + T1C), T2A * px + (T2B * py + T2C)
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then if (w1 > 0 or (w1 == 0 and T1t)) and (w2 > 0 or (w2 == 0 and T2t)) then break end
break
end
yt += 1 yt += 1
end end
while yb > yt do while yb >= yt do
local py = yb + 0.5 local py = yb + 0.5
local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) local w1, w2 = U1A * px + (U1B * py + U1C), U2A * px + (U2B * py + U2C)
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then if (w1 > 0 or (w1 == 0 and U1t)) and (w2 > 0 or (w2 == 0 and U2t)) then break end
break
end
yb -= 1 yb -= 1
end end
if yt > yb then continue end if yt > yb then continue end
@@ -570,7 +725,20 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
-- the row path's flat spans (BlendPixel's math, per-span constants, cached per destination value) -- the row path's flat spans (BlendPixel's math, per-span constants, cached per destination value)
local o1 = o + (yb - yt) * stride local o1 = o + (yb - yt) * stride
if f_opaque then if f_opaque then
for oo = o, o1, stride do writeu32(dbuf, oo, f_packed) end -- (4 pixels per iteration: a native loop iteration costs more than a few writes)
local s4 = stride * 4
local oo = o
while oo + s4 <= o1 + stride do
writeu32(dbuf, oo, f_packed)
writeu32(dbuf, oo + stride, f_packed)
writeu32(dbuf, oo + stride * 2, f_packed)
writeu32(dbuf, oo + stride * 3, f_packed)
oo += s4
end
while oo <= o1 do
writeu32(dbuf, oo, f_packed)
oo += stride
end
continue continue
end end
local last_d, last_v = -1, 0 local last_d, last_v = -1, 0
@@ -637,46 +805,69 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
return return
end end
-- Row spans. Each edge bounds a row from one side: w is monotone in x (A * px + e rounds monotonically), so the
-- pixels passing an edge are a run open to one side (A > 0: to the right, top-left so w >= 0 passes; A < 0: to
-- the left, w > 0), and the span is [first pixel passing the left edges, last passing the right ones]. Edges go
-- in slots per side (L, R; a spare slot is a dummy edge with w = 1e9, never binding), so a row is an estimate and
-- a short search per side, without per-edge branches. A horizontal edge (A = 0: w is e on the whole row) passes
-- a run of rows instead (e is monotone in y): the row range.
local L1A, L1B, L1C, L1N, L2A, L2B, L2C, L2N = 0, 0, 1e9, -1, 0, 0, 1e9, -1
local R1A, R1B, R1C, R1N, R2A, R2B, R2C, R2N = 0, 0, 1e9, 1, 0, 0, 1e9, 1
local HB, HC, Htl, Hz = 0, 1e9, false, false
local l1, r1 = false, false -- (slot 1 taken)
if A0 > 0 then
L1A, L1B, L1C, L1N, l1 = A0, B0, C0, n0, true
elseif A0 < 0 then
R1A, R1B, R1C, R1N, r1 = A0, B0, C0, n0, true
else
HB, HC, Htl, Hz = B0, C0, tl0, z0
end
if A1 > 0 then
if not l1 then L1A, L1B, L1C, L1N, l1 = A1, B1, C1, n1, true else L2A, L2B, L2C, L2N = A1, B1, C1, n1 end
elseif A1 < 0 then
if not r1 then R1A, R1B, R1C, R1N, r1 = A1, B1, C1, n1, true else R2A, R2B, R2C, R2N = A1, B1, C1, n1 end
else
HB, HC, Htl, Hz = B1, C1, tl1, z1
end
if A2 > 0 then
if not l1 then L1A, L1B, L1C, L1N, l1 = A2, B2, C2, n2, true else L2A, L2B, L2C, L2N = A2, B2, C2, n2 end
elseif A2 < 0 then
if not r1 then R1A, R1B, R1C, R1N, r1 = A2, B2, C2, n2, true else R2A, R2B, R2C, R2N = A2, B2, C2, n2 end
else
HB, HC, Htl, Hz = B2, C2, tl2, z2
end
if HB ~= 0 then
while miny <= maxy do
local e = HB * (miny + 0.5) + HC
if (e > 0 or (e == 0 and Htl)) and not (e == 0 and Hz) then break end
miny += 1
end
while maxy > miny do
local e = HB * (maxy + 0.5) + HC
if (e > 0 or (e == 0 and Htl)) and not (e == 0 and Hz) then break end
maxy -= 1
end
end
for y = miny, maxy do for y = miny, maxy do
local py = y + 0.5 local py = y + 0.5
local xl, xr = minx, maxx
local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2 local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2
local f1, f2, g1, g2 = L1B * py + L1C, L2B * py + L2C, R1B * py + R1C, R2B * py + R2C
-- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide) -- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide)
if A0 > 0 then local xl = max(minx, floor(f1 * L1N - 0.500001), floor(f2 * L2N - 0.500001))
xl = max(xl, floor(e0 * n0 - 0.500001)) local xr = min(maxx, ceil(g1 * R1N - 0.499999), ceil(g2 * R2N - 0.499999))
elseif A0 < 0 then
xr = min(xr, ceil(e0 * n0 - 0.499999))
end
if A1 > 0 then
xl = max(xl, floor(e1 * n1 - 0.500001))
elseif A1 < 0 then
xr = min(xr, ceil(e1 * n1 - 0.499999))
end
if A2 > 0 then
xl = max(xl, floor(e2 * n2 - 0.500001))
elseif A2 < 0 then
xr = min(xr, ceil(e2 * n2 - 0.499999))
end
-- An estimate inside (minx, maxx) is never in the span: the pixel centre is >= 1e-6 outside the crossing it -- An estimate inside (minx, maxx) is never in the span: the pixel centre is >= 1e-6 outside the crossing it
-- estimates, and with |A * px| and |e| below 2^17 * |A| the test's rounding error is far below 1e-6 * |A| (the -- estimates, and with |A * px| and |e| below 2^17 * |A| the test's rounding error is far below 1e-6 * |A| (the
-- test reads the same e). Testing from the next pixel gives the same span. -- test reads the same e). Testing from the next pixel gives the same span.
if xl > minx and xl <= xr then xl += 1 end if xl > minx and xl <= xr then xl += 1 end
while xl <= xr do while xl <= xr do
local px = xl + 0.5 local px = xl + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 if L1A * px + f1 >= 0 and L2A * px + f2 >= 0 then break end
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
xl += 1 xl += 1
end end
if xr < maxx and xr > xl then xr -= 1 end if xr < maxx and xr > xl then xr -= 1 end
while xr > xl do while xr >= xl do
local px = xr + 0.5 local px = xr + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 if R1A * px + g1 > 0 and R2A * px + g2 > 0 then break end
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
xr -= 1 xr -= 1
end end
if xl > xr then continue end if xl > xr then continue end
@@ -684,15 +875,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
if flat then if flat then
local o1 = o + (xr - xl) * 4 local o1 = o + (xr - xl) * 4
if f_opaque then if f_opaque then
if f_pair then FillRow(dbuf, o, o1, f_packed, f_pair)
while o < o1 do
writef64(dbuf, o, f_pair)
o += 8
end
if o == o1 then writeu32(dbuf, o, f_packed) end
else
for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end
end
continue continue
end end
local last_d, last_v = -1, 0 local last_d, last_v = -1, 0
@@ -816,6 +999,212 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end end
end end
-- One triangle's row walk as DrawTriangle sets it up (same edges, orientation, edge slots and row range; see its rows):
-- clipped bounds, then the L1 L2 R1 R2 slots (A, B, C, n). For flat triangles only (no alpha-0 edge rows).
@native
local function TriangleSlots(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, cx0: number,
cy0: number, cx1: number, cy1: number)
local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)
if area < 0 then
x1, y1, x2, y2 = x2, y2, x1, y1
end
local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1)
local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1)
local A0, B0 = y1 - y2, x2 - x1
local C0 = -(A0 * x1 + B0 * y1)
local A1, B1 = y2 - y0, x0 - x2
local C1 = -(A1 * x2 + B1 * y2)
local A2, B2 = y0 - y1, x1 - x0
local C2 = -(A2 * x0 + B2 * y0)
local L1A, L1B, L1C, L1N, L2A, L2B, L2C, L2N = 0, 0, 1e9, -1, 0, 0, 1e9, -1
local R1A, R1B, R1C, R1N, R2A, R2B, R2C, R2N = 0, 0, 1e9, 1, 0, 0, 1e9, 1
local HB, HC, Htl = 0, 1e9, false
local l1, r1 = false, false
if A0 > 0 then
L1A, L1B, L1C, L1N, l1 = A0, B0, C0, -1 / A0, true
elseif A0 < 0 then
R1A, R1B, R1C, R1N, r1 = A0, B0, C0, -1 / A0, true
else
HB, HC, Htl = B0, C0, B0 > 0
end
if A1 > 0 then
if not l1 then L1A, L1B, L1C, L1N, l1 = A1, B1, C1, -1 / A1, true else L2A, L2B, L2C, L2N = A1, B1, C1, -1 / A1 end
elseif A1 < 0 then
if not r1 then R1A, R1B, R1C, R1N, r1 = A1, B1, C1, -1 / A1, true else R2A, R2B, R2C, R2N = A1, B1, C1, -1 / A1 end
else
HB, HC, Htl = B1, C1, B1 > 0
end
if A2 > 0 then
if not l1 then L1A, L1B, L1C, L1N, l1 = A2, B2, C2, -1 / A2, true else L2A, L2B, L2C, L2N = A2, B2, C2, -1 / A2 end
elseif A2 < 0 then
if not r1 then R1A, R1B, R1C, R1N, r1 = A2, B2, C2, -1 / A2, true else R2A, R2B, R2C, R2N = A2, B2, C2, -1 / A2 end
else
HB, HC, Htl = B2, C2, B2 > 0
end
if HB ~= 0 and minx <= maxx then
while miny <= maxy do
local e = HB * (miny + 0.5) + HC
if e > 0 or (e == 0 and Htl) then break end
miny += 1
end
while maxy > miny do
local e = HB * (maxy + 0.5) + HC
if e > 0 or (e == 0 and Htl) then break end
maxy -= 1
end
end
return minx, maxx, miny, maxy, L1A, L1B, L1C, L1N, L2A, L2B, L2C, L2N, R1A, R1B, R1C, R1N, R2A, R2B, R2C, R2N
end
-- Flat triangle pair a b c + a b d, one colour, constant uv (ImPlot PrimRectFill: heatmap cells, bars). The same pixels
-- and values as the two DrawTriangle calls: per row each triangle's span exactly as DrawTriangle computes it (a flat
-- triangle's pixels are the same whether walked by rows or columns: the same per-pixel edge tests), then one fill when
-- the spans touch (opaque: or overlap; a pixel inside both gets the same value twice), else each span in order (a
-- translucent pixel inside both is blended twice, first for a b c, as before). Saves the second triangle's setup, a
-- span fill per row, and the column walk of tall bars.
@native
local function DrawTriPair(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, vd: number, t, cx0: number,
cy0: number, cx1: number, cy1: number, ox: number, oy: number)
local ax, ay = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy
local bx, by = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy
local cx, cy = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy
local dx, dy = readf64(vbuf, vd) - ox, readf64(vbuf, vd + 8) - oy
-- (DrawTriangle walks a tall triangle by columns, whose span estimates may differ from the rows' for an almost
-- vertical edge: then the two calls, like a degenerate triangle)
if (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) == 0 or (bx - ax) * (dy - ay) - (by - ay) * (dx - ax) == 0
or (min(ceil(max(ax, bx, cx)), cx1 - 1) - max(floor(min(ax, bx, cx)), cx0)) * 2
< min(ceil(max(ay, by, cy)), cy1 - 1) - max(floor(min(ay, by, cy)), cy0)
or (min(ceil(max(ax, bx, dx)), cx1 - 1) - max(floor(min(ax, bx, dx)), cx0)) * 2
< min(ceil(max(ay, by, dy)), cy1 - 1) - max(floor(min(ay, by, dy)), cy0) then
DrawTriangle(dbuf, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy)
DrawTriangle(dbuf, vbuf, va, vb, vd, t, cx0, cy0, cx1, cy1, ox, oy)
return
end
-- DrawTriangle's flat colour (the texel folded in like there)
local col = readu32(vbuf, va + 32)
local ra, ga, ba, aa = band(col, 255), band(rshift(col, 8), 255), band(rshift(col, 16), 255), rshift(col, 24)
if t then
local tw0, th0 = t.Width, t.Height
local tx, ty = floor(readf64(vbuf, va + 16) * tw0), floor(readf64(vbuf, va + 24) * th0)
if tx < 0 then tx = 0 elseif tx >= tw0 then tx = tw0 - 1 end
if ty < 0 then ty = 0 elseif ty >= th0 then ty = th0 - 1 end
local to, tb0 = (ty * tw0 + tx) * 4, t.Buffer
if readu32(tb0, to) ~= 4294967295 then
local tr, tg, tb, ta = readu8(tb0, to), readu8(tb0, to + 1), readu8(tb0, to + 2), readu8(tb0, to + 3)
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
end
end
if aa <= 0 then return end
local f_opaque = aa >= 255
local f_packed = floor(ra + 0.5) + floor(ga + 0.5) * 256 + floor(ba + 0.5) * 65536
+ (f_opaque and 4278190080 or floor(aa + 0.5) * 16777216)
local f_pair: number | false = f_opaque and PairF64(f_packed)
local f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = 0, 0, 0, 0, 0, 0
if not f_opaque then
f_sa = aa / 255
f_ns = 1 - f_sa
f_c1 = f_ns / 255
f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa
end
local minx1, maxx1, miny1, maxy1, P1A, P1B, P1C, P1N, P2A, P2B, P2C, P2N, Q1A, Q1B, Q1C, Q1N, Q2A, Q2B, Q2C, Q2N =
TriangleSlots(ax, ay, bx, by, cx, cy, cx0, cy0, cx1, cy1)
local minx2, maxx2, miny2, maxy2, S1A, S1B, S1C, S1N, S2A, S2B, S2C, S2N, T1A, T1B, T1C, T1N, T2A, T2B, T2C, T2N =
TriangleSlots(ax, ay, bx, by, dx, dy, cx0, cy0, cx1, cy1)
if minx1 > maxx1 then miny1 = maxy1 + 1 end -- (empty)
if minx2 > maxx2 then miny2 = maxy2 + 1 end
local ylo, yhi = miny1, maxy1
if miny1 > maxy1 then
ylo, yhi = miny2, maxy2
elseif miny2 <= maxy2 then
ylo, yhi = min(miny1, miny2), max(maxy1, maxy2)
end
if ylo > yhi then return end
Shrink(min(minx1, minx2), ylo, max(maxx1, maxx2) + 1, yhi + 1)
for y = ylo, yhi do
local py = y + 0.5
local l1, r1, l2, r2 = 0, -1, 0, -1
if y >= miny1 and y <= maxy1 then
local f1, f2, g1, g2 = P1B * py + P1C, P2B * py + P2C, Q1B * py + Q1C, Q2B * py + Q2C
local xl = max(minx1, floor(f1 * P1N - 0.500001), floor(f2 * P2N - 0.500001))
local xr = min(maxx1, ceil(g1 * Q1N - 0.499999), ceil(g2 * Q2N - 0.499999))
if xl > minx1 and xl <= xr then xl += 1 end
while xl <= xr do
local px = xl + 0.5
if P1A * px + f1 >= 0 and P2A * px + f2 >= 0 then break end
xl += 1
end
if xr < maxx1 and xr > xl then xr -= 1 end
while xr >= xl do
local px = xr + 0.5
if Q1A * px + g1 > 0 and Q2A * px + g2 > 0 then break end
xr -= 1
end
l1, r1 = xl, xr
end
if y >= miny2 and y <= maxy2 then
local f1, f2, g1, g2 = S1B * py + S1C, S2B * py + S2C, T1B * py + T1C, T2B * py + T2C
local xl = max(minx2, floor(f1 * S1N - 0.500001), floor(f2 * S2N - 0.500001))
local xr = min(maxx2, ceil(g1 * T1N - 0.499999), ceil(g2 * T2N - 0.499999))
if xl > minx2 and xl <= xr then xl += 1 end
while xl <= xr do
local px = xl + 0.5
if S1A * px + f1 >= 0 and S2A * px + f2 >= 0 then break end
xl += 1
end
if xr < maxx2 and xr > xl then xr -= 1 end
while xr >= xl do
local px = xr + 0.5
if T1A * px + g1 > 0 and T2A * px + g2 > 0 then break end
xr -= 1
end
l2, r2 = xl, xr
end
if l1 > r1 then
if l2 > r2 then continue end
l1, r1, l2, r2 = l2, r2, 0, -1
elseif l2 <= r2 and (l2 == r1 + 1 or l1 == r2 + 1 or (f_opaque and l2 <= r1 and l1 <= r2)) then
l1, r1, l2, r2 = min(l1, l2), max(r1, r2), 0, -1
end
local row = y * TargetWidth * 4 + TargetBase
if f_opaque then
FillRow(dbuf, row + l1 * 4, row + r1 * 4, f_packed, f_pair)
if l2 <= r2 then FillRow(dbuf, row + l2 * 4, row + r2 * 4, f_packed, f_pair) end
continue
end
-- DrawTriangle's flat translucent span (same math, cached per destination value), per span in order
local last_d, last_v = -1, 0
for k = 1, 2 do
if k == 2 then
if l2 > r2 then break end
l1, r1 = l2, r2
end
for oo = row + l1 * 4, row + r1 * 4, 4 do
local d = readu32(dbuf, oo)
if d == last_d then
writeu32(dbuf, oo, last_v)
elseif d < 16777216 then
writeu32(dbuf, oo, f_packed)
else
last_d = d
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
last_v = floor(f_rs + dr * f_ns + 0.5) + floor(f_gs + dg * f_ns + 0.5) * 256
+ floor(f_bs + db * f_ns + 0.5) * 65536 + 4278190080
else
local kk = rshift(d, 24) * f_c1
local oa = f_sa + kk
local inv = 1 / oa
last_v = floor((f_rs + dr * kk) * inv + 0.5) + floor((f_gs + dg * kk) * inv + 0.5) * 256
+ floor((f_bs + db * kk) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(dbuf, oo, last_v)
end
end
end
end
end
-- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as -- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as
-- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad. -- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad.
@native @native
@@ -836,7 +1225,7 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local miny, maxy = max(floor(min(y0, y1, y2, y3)), cy0), min(ceil(max(y0, y1, y2, y3)), cy1 - 1) local miny, maxy = max(floor(min(y0, y1, y2, y3)), cy0), min(ceil(max(y0, y1, y2, y3)), cy1 - 1)
if minx > maxx or miny > maxy then return end if minx > maxx or miny > maxy then return end
local col = readu32(vbuf, va + 32) local col = readu32(vbuf, va + 32)
local ra, ga, ba, aa = col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 local ra, ga, ba, aa = band(col, 255), band(rshift(col, 8), 255), band(rshift(col, 16), 255), rshift(col, 24)
if aa <= 0 then return end if aa <= 0 then return end
local ua, vva, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) local ua, vva, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
-- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P -- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P
@@ -878,33 +1267,93 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
trow = ty * tw * 4 trow = ty * tw * 4
end end
local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255
local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 -- (edge slots and row range like DrawTriangle's rows; up to 3 edges on a side, 2 horizontal)
local L1A, L1B, L1C, L1N, L2A, L2B, L2C, L2N, L3A, L3B, L3C, L3N = 0, 0, 1e9, -1, 0, 0, 1e9, -1, 0, 0, 1e9, -1
local R1A, R1B, R1C, R1N, R2A, R2B, R2C, R2N, R3A, R3B, R3C, R3N = 0, 0, 1e9, 1, 0, 0, 1e9, 1, 0, 0, 1e9, 1
local H1B, H1C, H1t, H2B, H2C, H2t = 0, 1e9, false, 0, 1e9, false
local nl, nr = 0, 0
if A0 > 0 then
if nl == 0 then L1A, L1B, L1C, L1N = A0, B0, C0, n0 elseif nl == 1 then L2A, L2B, L2C, L2N = A0, B0, C0, n0
else L3A, L3B, L3C, L3N = A0, B0, C0, n0 end
nl += 1
elseif A0 < 0 then
if nr == 0 then R1A, R1B, R1C, R1N = A0, B0, C0, n0 elseif nr == 1 then R2A, R2B, R2C, R2N = A0, B0, C0, n0
else R3A, R3B, R3C, R3N = A0, B0, C0, n0 end
nr += 1
elseif H1B == 0 then
H1B, H1C, H1t = B0, C0, tl0
else
H2B, H2C, H2t = B0, C0, tl0
end
if A1 > 0 then
if nl == 0 then L1A, L1B, L1C, L1N = A1, B1, C1, n1 elseif nl == 1 then L2A, L2B, L2C, L2N = A1, B1, C1, n1
else L3A, L3B, L3C, L3N = A1, B1, C1, n1 end
nl += 1
elseif A1 < 0 then
if nr == 0 then R1A, R1B, R1C, R1N = A1, B1, C1, n1 elseif nr == 1 then R2A, R2B, R2C, R2N = A1, B1, C1, n1
else R3A, R3B, R3C, R3N = A1, B1, C1, n1 end
nr += 1
elseif H1B == 0 then
H1B, H1C, H1t = B1, C1, tl1
else
H2B, H2C, H2t = B1, C1, tl1
end
if A2 > 0 then
if nl == 0 then L1A, L1B, L1C, L1N = A2, B2, C2, n2 elseif nl == 1 then L2A, L2B, L2C, L2N = A2, B2, C2, n2
else L3A, L3B, L3C, L3N = A2, B2, C2, n2 end
nl += 1
elseif A2 < 0 then
if nr == 0 then R1A, R1B, R1C, R1N = A2, B2, C2, n2 elseif nr == 1 then R2A, R2B, R2C, R2N = A2, B2, C2, n2
else R3A, R3B, R3C, R3N = A2, B2, C2, n2 end
nr += 1
elseif H1B == 0 then
H1B, H1C, H1t = B2, C2, tl2
else
H2B, H2C, H2t = B2, C2, tl2
end
if A3 > 0 then
if nl == 0 then L1A, L1B, L1C, L1N = A3, B3, C3, n3 elseif nl == 1 then L2A, L2B, L2C, L2N = A3, B3, C3, n3
else L3A, L3B, L3C, L3N = A3, B3, C3, n3 end
nl += 1
elseif A3 < 0 then
if nr == 0 then R1A, R1B, R1C, R1N = A3, B3, C3, n3 elseif nr == 1 then R2A, R2B, R2C, R2N = A3, B3, C3, n3
else R3A, R3B, R3C, R3N = A3, B3, C3, n3 end
nr += 1
elseif H1B == 0 then
H1B, H1C, H1t = B3, C3, tl3
else
H2B, H2C, H2t = B3, C3, tl3
end
if H1B ~= 0 then
while miny <= maxy do
local py = miny + 0.5
local e, e2 = H1B * py + H1C, H2B * py + H2C
if (e > 0 or (e == 0 and H1t)) and (e2 > 0 or (e2 == 0 and H2t)) then break end
miny += 1
end
while maxy > miny do
local py = maxy + 0.5
local e, e2 = H1B * py + H1C, H2B * py + H2C
if (e > 0 or (e == 0 and H1t)) and (e2 > 0 or (e2 == 0 and H2t)) then break end
maxy -= 1
end
end
for y = miny, maxy do for y = miny, maxy do
local py = y + 0.5 local py = y + 0.5
local xl, xr = minx, maxx local f1, f2, f3 = L1B * py + L1C, L2B * py + L2C, L3B * py + L3C
local e0, e1, e2, e3 = B0 * py + C0, B1 * py + C1, B2 * py + C2, B3 * py + C3 local g1, g2, g3 = R1B * py + R1C, R2B * py + R2C, R3B * py + R3C
if A0 > 0 then xl = max(xl, floor(e0 * n0 - 0.500001)) elseif A0 < 0 then xr = min(xr, ceil(e0 * n0 - 0.499999)) end local xl = max(minx, floor(f1 * L1N - 0.500001), floor(f2 * L2N - 0.500001), floor(f3 * L3N - 0.500001))
if A1 > 0 then xl = max(xl, floor(e1 * n1 - 0.500001)) elseif A1 < 0 then xr = min(xr, ceil(e1 * n1 - 0.499999)) end local xr = min(maxx, ceil(g1 * R1N - 0.499999), ceil(g2 * R2N - 0.499999), ceil(g3 * R3N - 0.499999))
if A2 > 0 then xl = max(xl, floor(e2 * n2 - 0.500001)) elseif A2 < 0 then xr = min(xr, ceil(e2 * n2 - 0.499999)) end
if A3 > 0 then xl = max(xl, floor(e3 * n3 - 0.500001)) elseif A3 < 0 then xr = min(xr, ceil(e3 * n3 - 0.499999)) end
if xl > minx and xl <= xr then xl += 1 end -- (an estimate is never in the span: see DrawTriangle) if xl > minx and xl <= xr then xl += 1 end -- (an estimate is never in the span: see DrawTriangle)
while xl <= xr do while xl <= xr do
local px = xl + 0.5 local px = xl + 0.5
local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 if L1A * px + f1 >= 0 and L2A * px + f2 >= 0 and L3A * px + f3 >= 0 then break end
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2))
and (w3 > 0 or (w3 == 0 and tl3)) then
break
end
xl += 1 xl += 1
end end
if xr < maxx and xr > xl then xr -= 1 end if xr < maxx and xr > xl then xr -= 1 end
while xr > xl do while xr >= xl do
local px = xr + 0.5 local px = xr + 0.5
local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 if R1A * px + g1 > 0 and R2A * px + g2 > 0 and R3A * px + g3 > 0 then break end
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2))
and (w3 > 0 or (w3 == 0 and tl3)) then
break
end
xr -= 1 xr -= 1
end end
if xl > xr then continue end if xl > xr then continue end
@@ -922,35 +1371,30 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
tv = readu32(tbuf, (ty * tw + tx) * 4) tv = readu32(tbuf, (ty * tw + tx) * 4)
end end
if tv ~= last_tv then -- BlendPixel inlined (same math; an opaque texel over a colour gives fa = 1, fn = 0, k = 0: the same values
last_tv = tv -- as its opaque branch, so no branch on it: every unpredictable branch costs more than the math)
sa = rshift(tv, 24) * a255 local ta = rshift(tv, 24)
sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 if ta > 0 then
s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 local sa = ta * a255
fa = sa / 255 local sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255
fn = 1 - fa local fa = sa / 255
fk = (1 - fa) / 255
end
-- BlendPixel inlined (same math)
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
elseif sa > 0 then
local d = readu32(dbuf, o) local d = readu32(dbuf, o)
if d < 16777216 then if d >= 4278190080 then
writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) local fn = 1 - fa
writeu32(dbuf, o, floor(sr * fa + band(d, 255) * fn + 0.5)
+ floor(sg * fa + band(rshift(d, 8), 255) * fn + 0.5) * 256
+ floor(sb * fa + band(rshift(d, 16), 255) * fn + 0.5) * 65536 + 4278190080)
elseif d < 16777216 then
writeu32(dbuf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536
+ floor(sa + 0.5) * 16777216)
else else
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then local k = rshift(d, 24) * ((1 - fa) / 255)
writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 local oa = fa + k
+ floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) local inv2 = 1 / oa
else writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5)
local k = rshift(d, 24) * fk + floor((sg * fa + dg * k) * inv2 + 0.5) * 256
local oa = fa + k + floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
local inv2 = 1 / oa
writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5)
+ floor((sg * fa + dg * k) * inv2 + 0.5) * 256
+ floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end end
end end
o += 4 o += 4
@@ -1049,7 +1493,8 @@ function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number)
end end
end end
-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd) -- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd), 5 flat
-- triangle pair (va vb vc + va vb vd)
@native @native
local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: number, tox: number, local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: number, tox: number,
toy: number, cx0: number, cy0: number, cx1: number, cy1: number) toy: number, cx0: number, cy0: number, cx1: number, cy1: number)
@@ -1059,6 +1504,9 @@ local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, v
elseif kind == 4 then elseif kind == 4 then
DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, t, cx0, cy0, cx1, cy1, tox, toy) DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, t, cx0, cy0, cx1, cy1, tox, toy)
return return
elseif kind == 5 then
DrawTriPair(TargetBuffer, vbuf, va, vb, vc, vd, t, cx0, cy0, cx1, cy1, tox, toy)
return
end end
local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox,
readf64(vbuf, vc + 8) - toy readf64(vbuf, vc + 8) - toy
+305 -83
View File
@@ -28,20 +28,22 @@ local P1, P2 = 2147483647, 2147483629 -- two independent 31 bit hashes per tile
local LAYER_KEEP_FRAMES = 120 local LAYER_KEEP_FRAMES = 120
local MAX_DEFER_FRAMES = 8 -- a changed tile is redrawn at the latest this many frames later, even over the budget local MAX_DEFER_FRAMES = 8 -- a changed tile is redrawn at the latest this many frames later, even over the budget
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = {}, {}, {}, {}, {}, {} local PrimA, PrimB, PrimC, PrimD, PrimGradient = {}, {}, {}, {}, {}
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = {}, {}, {}, {}
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = {}, {}, {}, {} local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = {}, {}, {}, {}
local PrimTexId, PrimVtxBuffer = {}, {} -- a primitive's draw command (index into Cmd*, numbered through the frame): its texture, vertex buffer and clip
local PrimCmd = {}
local CmdTexture, CmdTexId, CmdVtxBuffer = {}, {}, {}
local CmdClipX0, CmdClipY0, CmdClipX1, CmdClipY1 = {}, {}, {}, {}
local CmdCount = 0
-- flat rect (one colour, one uv or untextured): HashTiles hashes its clipped rect per tile -- flat rect (one colour, one uv or untextured): HashTiles hashes its clipped rect per tile
local PrimFlat = {} local PrimFlat = {}
-- the current draw list's primitives per layer kind (filled by CollectPrims): count, and min bounds for kinds 1 and 3 -- the current draw list's primitives per layer kind (filled by CollectPrims): count, and min bounds for kinds 1 and 3
local LayerPrims1, LayerPrims2, LayerPrims3 = {}, {}, {} local LayerPrims1, LayerPrims2, LayerPrims3 = {}, {}, {}
local Kind1Count, Kind2Count, Kind3Count, Kind1X, Kind1Y, Kind3X, Kind3Y = 0, 0, 0, 0, 0, 0, 0 local Kind1Count, Kind2Count, Kind3Count, Kind1X, Kind1Y, Kind3X, Kind3Y = 0, 0, 0, 0, 0, 0, 0
M.PrimA, M.PrimB, M.PrimC, M.PrimD = PrimA, PrimB, PrimC, PrimD M.PrimA, M.PrimB, M.PrimC, M.PrimD, M.PrimGradient = PrimA, PrimB, PrimC, PrimD, PrimGradient
M.PrimTexture, M.PrimGradient = PrimTexture, PrimGradient
M.PrimClipX0, M.PrimClipY0, M.PrimClipX1, M.PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1
M.PrimBoundsX0, M.PrimBoundsY0, M.PrimBoundsX1, M.PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 M.PrimBoundsX0, M.PrimBoundsY0, M.PrimBoundsX1, M.PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1
M.PrimTexId, M.PrimVtxBuffer = PrimTexId, PrimVtxBuffer M.PrimCmd, M.CmdTexture, M.CmdTexId, M.CmdVtxBuffer = PrimCmd, CmdTexture, CmdTexId, CmdVtxBuffer
M.CmdClipX0, M.CmdClipY0, M.CmdClipX1, M.CmdClipY1 = CmdClipX0, CmdClipY0, CmdClipX1, CmdClipY1
-- Adds [a, c) x [b, d) to the n dirty rects DX0..DY1 (merged unless that wastes area), returns the count -- Adds [a, c) x [b, d) to the n dirty rects DX0..DY1 (merged unless that wastes area), returns the count
EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 = {}, {}, {}, {} EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 = {}, {}, {}, {}
@@ -75,6 +77,56 @@ end
-- their hashes get DriftMark* (new every frame) added, so their tiles are redrawn even when the hash doesn't see the ulp -- their hashes get DriftMark* (new every frame) added, so their tiles are redrawn even when the hash doesn't see the ulp
local DriftSet, DriftOn, DriftMark1, DriftMark2 = table.create(4096, false), false, 0, 0 local DriftSet, DriftOn, DriftMark1, DriftMark2 = table.create(4096, false), false, 0, 0
-- One primitive's HashTiles entry hash, for PatchDrawList (the same math as HashTiles' inlined copy: keep both equal).
-- Returns h1, h2 and the flat signature (>= 0: a flat rect, whose per-tile hash is FlatTileHash's)
@native
local function PrimHash(p, lx0, ly0, ox, oy)
local cmd = PrimCmd[p]
local vbuf, va, vd, tex_id = CmdVtxBuffer[cmd], PrimA[p], PrimD[p], CmdTexId[cmd]
if PrimFlat[p] then
local RectColor, RectUV = readu32(vbuf, va + 32), readf64(vbuf, va + 16) * 8192 + readf64(vbuf, va + 24)
return 0, 0, ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1
end
local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0,
PrimBoundsY1[p] - ly0
local gk, v2, v3, nv = PrimGradient[p], PrimC[p], PrimB[p], 3
local g = gk or 0
local h1 = (((cx0 * 8191 + cy0) * 8191 + cx1) * 8 + g) % P1
local h2 = (((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) * 8 + g) % P2
local vax, vay = lx0 + ox, ly0 + oy
if vd then
nv = (gk == 3 or gk == 4) and 4 or 2
else
v2, v3 = v3, v2
end
local v = va
for k = 1, nv do
if k == 2 then v = v2 elseif k == 3 then v = v3 elseif k == 4 then v = vd end
local x, y = readf64(vbuf, v) - vax, readf64(vbuf, v + 8) - vay
local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24)
local c = readu32(vbuf, v + 32)
h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1
h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2
end
return h1, h2, -1
end
-- A flat rect's hash in tile (tx, ty) (HashTiles' per-tile flat hash)
@native
local function FlatTileHash(p, lx0, ly0, tx, ty)
local cmd = PrimCmd[p]
local vbuf, va, tex_id = CmdVtxBuffer[cmd], PrimA[p], CmdTexId[cmd]
local RectColor, RectUV = readu32(vbuf, va + 32), readf64(vbuf, va + 16) * 8192 + readf64(vbuf, va + 24)
local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0,
PrimBoundsY1[p] - ly0
local px0, py0 = tx * TILE, ty * TILE
local ix0, iy0 = max(cx0 - px0, 0), max(cy0 - py0, 0)
local ix1, iy1 = min(cx1 - px0, TILE), min(cy1 - py0, TILE)
local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1
return ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1,
((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2
end
-- HashTiles scratch, per touched tile (slot = its index in layer.Touched): tile key -> slot, its list, count, hashes -- HashTiles scratch, per touched tile (slot = its index in layer.Touched): tile key -> slot, its list, count, hashes
local KeySlot, SlotCount, SlotHash1, SlotHash2 = {}, {}, {}, {} local KeySlot, SlotCount, SlotHash1, SlotHash2 = {}, {}, {}, {}
local SlotList, SlotListHash1, SlotListHash2, SlotListFlat = {}, {}, {}, {} local SlotList, SlotListHash1, SlotListHash2, SlotListFlat = {}, {}, {}, {}
@@ -91,18 +143,19 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy)
local TileXs, TileYs = layer.TileX, layer.TileY local TileXs, TileYs = layer.TileX, layer.TileY
-- upvalues as locals: cheaper in the hot loop -- upvalues as locals: cheaper in the hot loop
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1
local PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat = local PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimCmd, CmdTexId, CmdVtxBuffer, PrimFlat =
PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimCmd, CmdTexId, CmdVtxBuffer, PrimFlat
local KeySlot, SlotCount, SlotHash1, SlotHash2 = KeySlot, SlotCount, SlotHash1, SlotHash2 local KeySlot, SlotCount, SlotHash1, SlotHash2 = KeySlot, SlotCount, SlotHash1, SlotHash2
local SlotList, SlotListHash1, SlotListHash2, SlotListFlat = SlotList, SlotListHash1, SlotListHash2, SlotListFlat local SlotList, SlotListHash1, SlotListHash2, SlotListFlat = SlotList, SlotListHash1, SlotListHash2, SlotListFlat
local TILE = TILE local TILE = TILE
for pi = 1, np do for pi = 1, np do
local p = plist[pi] local p = plist[pi]
local tex_id = PrimTexId[p] local cmd = PrimCmd[p]
local tex_id = CmdTexId[cmd]
-- hash the clipped bounds, not the clip: a window clipped by the fixed viewport stays hash-stable when moved -- hash the clipped bounds, not the clip: a window clipped by the fixed viewport stays hash-stable when moved
local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0, local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0,
PrimBoundsY1[p] - ly0 PrimBoundsY1[p] - ly0
local vbuf = PrimVtxBuffer[p] local vbuf = CmdVtxBuffer[cmd]
local va, vd = PrimA[p], PrimD[p] local va, vd = PrimA[p], PrimD[p]
-- flat rect: hash its clipped rect per tile, so resizing only changes the tiles its edges cross -- flat rect: hash its clipped rect per tile, so resizing only changes the tiles its edges cross
local FlatRect, RectColor, RectUV = PrimFlat[p], 0, 0 local FlatRect, RectColor, RectUV = PrimFlat[p], 0, 0
@@ -114,30 +167,40 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy)
if FlatRect then if FlatRect then
FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1 FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1
else else
h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1 -- the kind (gk: 0 triangle / plain quad, 1 / 2 gradient, 3 line quad, 4 triangle pair) mixed into the
h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2 -- bounds: no extra %
local gk = PrimGradient[p]
local g = gk or 0
h1 = (((cx0 * 8191 + cy0) * 8191 + cx1) * 8 + g) % P1
h2 = (((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) * 8 + g) % P2
local vax, vay = lx0 + ox, ly0 + oy local vax, vay = lx0 + ox, ly0 + oy
-- vertices: triangle a, b, c; axis aligned quad a, c (CollectPrims checked that b, d follow from them + kind); -- vertices: triangle a, b, c; axis aligned quad a, c (CollectPrims checked that b, d follow from them + kind);
-- line quad (any shape) a, c, b, d. The kind is mixed in after the second vertex. -- line quad, triangle pair (any shape) a, c, b, d. Unrolled (PrimHash's loop, same math): one % per hash,
local gk, v2, v3, nv = PrimGradient[p], PrimC[p], PrimB[p], 3 -- h < 2^31, so h * 48271 + the terms (|x|, |y| < 2^15, uv < 2^14, c < 2^32) stays below 2^53
if vd then local x, y = readf64(vbuf, va) - vax, readf64(vbuf, va + 8) - vay
nv = gk == 3 and 4 or 2 local uv = readf64(vbuf, va + 16) * 8192 + readf64(vbuf, va + 24)
else local c = readu32(vbuf, va + 32)
v2, v3 = v3, v2 h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1
end h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2
local v = va local v = vd and PrimC[p] or PrimB[p]
for k = 1, nv do x, y = readf64(vbuf, v) - vax, readf64(vbuf, v + 8) - vay
if k == 2 then v = v2 elseif k == 3 then v = v3 elseif k == 4 then v = vd end uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24)
-- inlined (a call per vertex costs more than the hash): one % per hash, h < 2^31, so h * 48271 + the c = readu32(vbuf, v + 32)
-- terms (|x|, |y| < 2^15, uv < 2^14, c < 2^32) stays below 2^53 h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1
local x, y = readf64(vbuf, v) - vax, readf64(vbuf, v + 8) - vay h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2
local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24) if not vd or gk == 3 or gk == 4 then
local c = readu32(vbuf, v + 32) v = vd and PrimB[p] or PrimC[p]
x, y = readf64(vbuf, v) - vax, readf64(vbuf, v + 8) - vay
uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24)
c = readu32(vbuf, v + 32)
h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1 h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1
h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2 h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2
if k == 2 and gk then if vd then
h1 = (h1 * 48271 + gk) % P1 x, y = readf64(vbuf, vd) - vax, readf64(vbuf, vd + 8) - vay
h2 = (h2 * 16807 + gk * 3) % P2 uv = readf64(vbuf, vd + 16) * 8192 + readf64(vbuf, vd + 24)
c = readu32(vbuf, vd + 32)
h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1
h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2
end end
end end
if DriftOn and (DriftSet[va // VTX_STRIDE + 1] or DriftSet[PrimB[p] // VTX_STRIDE + 1] if DriftOn and (DriftSet[va // VTX_STRIDE + 1] or DriftSet[PrimB[p] // VTX_STRIDE + 1]
@@ -284,6 +347,97 @@ end
-- the new primitive bounds in the tile (clipped to it); swapped with the tile's Drawn* after a redraw -- the new primitive bounds in the tile (clipped to it); swapped with the tile's Drawn* after a redraw
local NewX0, NewY0, NewX1, NewY1 = {}, {}, {}, {} local NewX0, NewY0, NewX1, NewY1 = {}, {}, {}, {}
-- DirtyRects' list diff: how far ahead it looks for the entry that resyncs the old and new list, after how many
-- unpaired entries without a resync it gives up
local DIFF_WINDOW, DIFF_MISSES = 8, 2
-- DirtyRects' rects for old entries [i, oe] / new [i, ne] (prefix and suffix equal) from a greedy diff that pairs equal
-- entries of both lists in order (any order-preserving pairing is exact: a pixel no unpaired primitive touches is
-- covered by the same primitives in the same order), so a row scrolled in or out or an item inserted doesn't redraw
-- everything after it. -1: DIFF_MISSES unpaired entries without a resync (mostly changed: a new font size, animated
-- plots), DirtyRects' positional pass is cheaper there (fewer, larger rects, no lookahead)
@native
local function GreedyRects(tile, ListHash1, ListHash2, lf, i, oe, ne)
local DrawnHash1, DrawnHash2, DrawnX0, DrawnY0, DrawnX1, DrawnY1, of = tile.DrawnHash1, tile.DrawnHash2,
tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1, tile.DrawnFlat
local NX0, NY0, NX1, NY1 = NewX0, NewY0, NewX1, NewY1
local DX0, DY0, DX1, DY1, AddRect = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1,
EditableImages.DY1, EditableImages.AddRect
local DirtyCount = 0
local oi, ni, misses = i, i, 0
while oi <= oe and ni <= ne do
local h1, h2, o1, o2 = ListHash1[ni], ListHash2[ni], DrawnHash1[oi], DrawnHash2[oi]
if o1 == h1 and o2 == h2 then
oi += 1
ni += 1
continue
end
-- the nearest resync: old oi .. oi + skip - 1 gone, or new ni .. ni + skip - 1 inserted
local skip, gone = 0, false
for dd = 1, DIFF_WINDOW do
if oi + dd <= oe and DrawnHash1[oi + dd] == h1 and DrawnHash2[oi + dd] == h2 then
skip, gone = dd, true
break
end
if ni + dd <= ne and ListHash1[ni + dd] == o1 and ListHash2[ni + dd] == o2 then
skip = dd
break
end
end
local ko1, kn1 = oi, ni
if skip > 0 then
if gone then ko1, kn1 = oi + skip - 1, ni - 1 else ko1, kn1 = oi - 1, ni + skip - 1 end
misses = 0
elseif lf[ni] >= 0 and lf[ni] == of[oi] then
-- same flat rect, new bounds: only the strips between the old and new edges can differ
local a, b, c, d = NX0[ni], NY0[ni], NX1[ni], NY1[ni]
local oa, ob, oc, od = DrawnX0[oi], DrawnY0[oi], DrawnX1[oi], DrawnY1[oi]
local uy0, uy1 = min(b, ob), max(d, od)
local ux0, ux1 = min(a, oa), max(c, oc)
if a ~= oa then DirtyCount = AddRect(DirtyCount, ux0, uy0, max(a, oa), uy1) end
if c ~= oc then DirtyCount = AddRect(DirtyCount, min(c, oc), uy0, ux1, uy1) end
if b ~= ob then DirtyCount = AddRect(DirtyCount, ux0, uy0, ux1, max(b, ob)) end
if d ~= od then DirtyCount = AddRect(DirtyCount, ux0, min(d, od), ux1, uy1) end
ko1, kn1 = oi - 1, ni - 1
else
misses += 1
if misses >= DIFF_MISSES then return -1 end
end
for k = oi, ko1 do
local a, b, c, d = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]
if DirtyCount == 0 or a < DX0[1] or b < DY0[1] or c > DX1[1] or d > DY1[1] then
DirtyCount = AddRect(DirtyCount, a, b, c, d)
end
end
for k = ni, kn1 do
local a, b, c, d = NX0[k], NY0[k], NX1[k], NY1[k]
if DirtyCount == 0 or a < DX0[1] or b < DY0[1] or c > DX1[1] or d > DY1[1] then
DirtyCount = AddRect(DirtyCount, a, b, c, d)
end
end
if skip == 0 then
oi += 1
ni += 1
elseif gone then
oi += skip
else
ni += skip
end
end
for k = oi, oe do
local a, b, c, d = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]
if DirtyCount == 0 or a < DX0[1] or b < DY0[1] or c > DX1[1] or d > DY1[1] then
DirtyCount = AddRect(DirtyCount, a, b, c, d)
end
end
for k = ni, ne do
local a, b, c, d = NX0[k], NY0[k], NX1[k], NY1[k]
if DirtyCount == 0 or a < DX0[1] or b < DY0[1] or c > DX1[1] or d > DY1[1] then
DirtyCount = AddRect(DirtyCount, a, b, c, d)
end
end
return DirtyCount
end
@native @native
local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1) local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1)
@@ -324,37 +478,44 @@ local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0,
j += 1 j += 1
end end
local of, lf = tile.DrawnFlat, layer.TileListFlat[key] local of, lf = tile.DrawnFlat, layer.TileListFlat[key]
local paired = DrawnCount - j - i == count - j - i -- the lists differ in old [i, DrawnCount - j] / new [i, count - j]
for k = i, count - j do DirtyCount = GreedyRects(tile, ListHash1, ListHash2, lf, i, DrawnCount - j, count - j)
local a, b, c, d = NX0[k], NY0[k], NX1[k], NY1[k] if DirtyCount < 0 then
local oa, ob, oc, od = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] -- positional (the lists mostly changed)
if paired and DrawnHash1[k] == ListHash1[k] and DrawnHash2[k] == ListHash2[k] then DirtyCount = 0
-- same primitive at the same place in both lists: every pixel it covers is either in a changed one's local paired = DrawnCount - j - i == count - j - i
-- rect or drawn by the same primitives in the same order for k = i, count - j do
continue local a, b, c, d = NX0[k], NY0[k], NX1[k], NY1[k]
elseif paired and lf[k] >= 0 and lf[k] == of[k] then local oa, ob, oc, od = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]
-- same flat rect, new bounds: only the strips between the old and new edges can differ if paired and DrawnHash1[k] == ListHash1[k] and DrawnHash2[k] == ListHash2[k] then
local uy0, uy1 = min(b, ob), max(d, od) -- same primitive at the same place in both lists: every pixel it covers is either in a changed
local ux0, ux1 = min(a, oa), max(c, oc) -- one's rect or drawn by the same primitives in the same order
if a ~= oa then DirtyCount = AddRect(DirtyCount, ux0, uy0, max(a, oa), uy1) end continue
if c ~= oc then DirtyCount = AddRect(DirtyCount, min(c, oc), uy0, ux1, uy1) end elseif paired and lf[k] >= 0 and lf[k] == of[k] then
if b ~= ob then DirtyCount = AddRect(DirtyCount, ux0, uy0, ux1, max(b, ob)) end -- same flat rect, new bounds: only the strips between the old and new edges can differ
if d ~= od then DirtyCount = AddRect(DirtyCount, ux0, min(d, od), ux1, uy1) end local uy0, uy1 = min(b, ob), max(d, od)
else local ux0, ux1 = min(a, oa), max(c, oc)
-- (inside the first rect: AddRect would merge it there, changing nothing; skip the call. Animated if a ~= oa then DirtyCount = AddRect(DirtyCount, ux0, uy0, max(a, oa), uy1) end
-- plots change hundreds of primitives per tile) if c ~= oc then DirtyCount = AddRect(DirtyCount, min(c, oc), uy0, ux1, uy1) end
if b ~= ob then DirtyCount = AddRect(DirtyCount, ux0, uy0, ux1, max(b, ob)) end
if d ~= od then DirtyCount = AddRect(DirtyCount, ux0, min(d, od), ux1, uy1) end
else
-- (inside the first rect: AddRect would merge it there, changing nothing; skip the call.
-- Animated plots change hundreds of primitives per tile)
if DirtyCount == 0 or a < DX0[1] or b < DY0[1] or c > DX1[1] or d > DY1[1] then
DirtyCount = AddRect(DirtyCount, a, b, c, d)
end
if k <= DrawnCount - j
and (DirtyCount == 0 or oa < DX0[1] or ob < DY0[1] or oc > DX1[1] or od > DY1[1]) then
DirtyCount = AddRect(DirtyCount, oa, ob, oc, od)
end
end
end
for k = count - j + 1, DrawnCount - j do
local a, b, c, d = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]
if DirtyCount == 0 or a < DX0[1] or b < DY0[1] or c > DX1[1] or d > DY1[1] then if DirtyCount == 0 or a < DX0[1] or b < DY0[1] or c > DX1[1] or d > DY1[1] then
DirtyCount = AddRect(DirtyCount, a, b, c, d) DirtyCount = AddRect(DirtyCount, a, b, c, d)
end end
if k <= DrawnCount - j and (DirtyCount == 0 or oa < DX0[1] or ob < DY0[1] or oc > DX1[1] or od > DY1[1]) then
DirtyCount = AddRect(DirtyCount, oa, ob, oc, od)
end
end
end
for k = count - j + 1, DrawnCount - j do
local a, b, c, d = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]
if DirtyCount == 0 or a < DX0[1] or b < DY0[1] or c > DX1[1] or d > DY1[1] then
DirtyCount = AddRect(DirtyCount, a, b, c, d)
end end
end end
end end
@@ -412,12 +573,14 @@ local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1)
or PrimBoundsY1[p] - y0 <= ry0 then or PrimBoundsY1[p] - y0 <= ry0 then
continue continue
end end
local cx0, cy0 = max(PrimClipX0[p] - x0, rx0), max(PrimClipY0[p] - y0, ry0) local cmd = PrimCmd[p]
local cx1, cy1 = min(PrimClipX1[p] - x0, rx1), min(PrimClipY1[p] - y0, ry1) local cx0, cy0 = max(CmdClipX0[cmd] - x0, rx0), max(CmdClipY0[cmd] - y0, ry0)
local cx1, cy1 = min(CmdClipX1[cmd] - x0, rx1), min(CmdClipY1[cmd] - y0, ry1)
if cx0 >= cx1 or cy0 >= cy1 then continue end if cx0 >= cx1 or cy0 >= cy1 then continue end
local kind, gk = 0, PrimGradient[p] local kind, gk = 0, PrimGradient[p]
if PrimD[p] then kind = gk and gk + 1 or 1 end if PrimD[p] then kind = gk and gk + 1 or 1 end
DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], PrimD[p] or 0, tox, toy, cx0, cy0, cx1, cy1) DrawPrim(kind, CmdTexture[cmd], CmdVtxBuffer[cmd], PrimA[p], PrimB[p], PrimC[p], PrimD[p] or 0, tox, toy, cx0, cy0,
cx1, cy1)
end end
end end
@@ -609,9 +772,8 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d) ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d)
end end
-- upvalues as locals: cheaper in the hot loop -- upvalues as locals: cheaper in the hot loop
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat = local PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimFlat, PrimCmd = PrimA, PrimB, PrimC, PrimD, PrimGradient,
PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat PrimFlat, PrimCmd
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1
local LayerPrims1, LayerPrims2, LayerPrims3 = LayerPrims1, LayerPrims2, LayerPrims3 local LayerPrims1, LayerPrims2, LayerPrims3 = LayerPrims1, LayerPrims2, LayerPrims3
local ci = 0 local ci = 0
@@ -650,6 +812,10 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
if cx1 > cx0 and cy1 > cy0 then if cx1 > cx0 and cy1 > cy0 then
local tex_id = pcmd:GetTexID() local tex_id = pcmd:GetTexID()
local t = BackendData.Textures[tex_id] local t = BackendData.Textures[tex_id]
local cmd = CmdCount + 1
CmdCount = cmd
CmdTexture[cmd], CmdTexId[cmd], CmdVtxBuffer[cmd] = t, tex_id, vbuf
CmdClipX0[cmd], CmdClipY0[cmd], CmdClipX1[cmd], CmdClipY1[cmd] = cx0, cy0, cx1, cy1
local vo = pcmd.VtxOffset local vo = pcmd.VtxOffset
local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount
while i <= last do while i <= last do
@@ -703,6 +869,23 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
bx1 = ceil(max(pax, pbx, pcx, pdx) - ox) + 1 bx1 = ceil(max(pax, pbx, pcx, pdx) - ox) + 1
by1 = ceil(max(pay, pby, pcy, pdy) - oy) + 1 by1 = ceil(max(pay, pby, pcy, pdy) - oy) + 1
end end
elseif i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == idx[i + 1] then
-- flat triangle pair a b c + a b d (ImPlot PrimRectFill: heatmap cells, bars): one colour, one
-- uv (or no texture), any shape; the bounds are the two triangles' together
local d = (vo + idx[i + 5] - 1) * VTX_STRIDE
local col = readu32(vbuf, va + 32)
if readu32(vbuf, vb + 32) == col and readu32(vbuf, vc + 32) == col and readu32(vbuf, d + 32) == col then
local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24)
if not t or (readf64(vbuf, vb + 16) == tax and readf64(vbuf, vb + 24) == tay
and readf64(vbuf, vc + 16) == tax and readf64(vbuf, vc + 24) == tay
and readf64(vbuf, d + 16) == tax and readf64(vbuf, d + 24) == tay) then
local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8)
vd, gk = d, 4
bx0, by0 = floor(min(pax, pbx, pcx, pdx) - ox), floor(min(pay, pby, pcy, pdy) - oy)
bx1 = ceil(max(pax, pbx, pcx, pdx) - ox) + 1
by1 = ceil(max(pay, pby, pcy, pdy) - oy) + 1
end
end
end end
if vd then if vd then
i = i + 6 i = i + 6
@@ -721,9 +904,7 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
if by1 > cy1 then by1 = cy1 end if by1 > cy1 then by1 = cy1 end
if bx0 < bx1 and by0 < by1 then if bx0 < bx1 and by0 < by1 then
n = n + 1 n = n + 1
PrimA[n], PrimB[n], PrimC[n], PrimD[n], PrimTexture[n], PrimGradient[n], PrimTexId[n], PrimA[n], PrimB[n], PrimC[n], PrimD[n], PrimGradient[n], PrimCmd[n] = va, vb, vc, vd, gk, cmd
PrimVtxBuffer[n] = va, vb, vc, vd, t, gk, tex_id, vbuf
PrimClipX0[n], PrimClipY0[n], PrimClipX1[n], PrimClipY1[n] = cx0, cy0, cx1, cy1
PrimBoundsX0[n], PrimBoundsY0[n], PrimBoundsX1[n], PrimBoundsY1[n] = bx0, by0, bx1, by1 PrimBoundsX0[n], PrimBoundsY0[n], PrimBoundsX1[n], PrimBoundsY1[n] = bx0, by0, bx1, by1
PrimFlat[n] = flat PrimFlat[n] = flat
if kind == 2 then if kind == 2 then
@@ -799,21 +980,32 @@ local function LayerOrigin(draw_list, kind, ox, oy)
return floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy) return floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy)
end end
local PatchLayers, PatchKeys, PatchPrim = {}, {}, {} local PatchLayers, PatchKeys, PatchPrim, PatchH1, PatchH2, PatchSig = {}, {}, {}, {}, {}, {}
-- CompareDrawList 3: moved by whole pixels, but a few vertices drifted off the exact shift (same bounds). CollectPrims -- CompareDrawList 3: moved by whole pixels, but a few vertices drifted off the exact shift (same bounds). CollectPrims
-- ran and gave the primitive sequence the tile lists were built from: the lists stay (indices moved to this frame's) -- ran and gave the primitive sequence the tile lists were built from: the lists stay (indices moved to this frame's)
-- and every tile keeps its pixels, except those with a primitive using a drifted vertex: those entries' hashes change -- and every tile keeps its pixels, except those with a primitive using a drifted vertex: those entries' hashes change
-- (DriftMark), so the tile redraws just them. Changes nothing when it returns false (the caller takes the full path). -- (DriftMark), so the tile redraws just them. Changes nothing when it returns false (the caller takes the full path).
-- recolor (CompareDrawList 4: not moved, a few vertices' uv / colour changed): the same, but those primitives get
-- their real hashes (PrimHash, flat rects too), so the tiles end up exactly as HashTiles + DrawLayer would leave them.
-- Their kind must be the same (so the same bounds and tiles; the other primitives' entries are equal by construction).
@native @native
local function PatchDrawList(BackendData, set, draw_list, n0, n, dx, dy, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1) local function PatchDrawList(BackendData, set, draw_list, n0, n, dx, dy, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1,
recolor)
table.clear(PatchPrim) table.clear(PatchPrim)
local SigA, SigD = set.PrimSigA, set.PrimSigD local SigA, SigD, SigG = set.PrimSigA, set.PrimSigD, set.PrimSigG
if not SigA or set.PrimN ~= n - n0 then return false end if not SigA or set.PrimN ~= n - n0 then return false end
for m = 1, n - n0 do for m = 1, n - n0 do
local p = n0 + m local p = n0 + m
if PrimA[p] ~= SigA[m] or PrimD[p] ~= SigD[m] then return false end if PrimA[p] ~= SigA[m] or PrimD[p] ~= SigD[m] then return false end
end end
-- the listed vertices' byte offset range
local Drift, lo, hi = Layers.Drift, math.huge, -1
for k = 1, Layers.DriftCount do
local v = Drift[k]
if v < lo then lo = v end
if v > hi then hi = v end
end
local np = 0 local np = 0
for kind = 1, 3 do for kind = 1, 3 do
local layer = set[kind] local layer = set[kind]
@@ -840,12 +1032,21 @@ local function PatchDrawList(BackendData, set, draw_list, n0, n, dx, dy, ox, oy,
local TileCounts, Tiles = layer.TileCounts, layer.Tiles local TileCounts, Tiles = layer.TileCounts, layer.Tiles
for m = 1, count do for m = 1, count do
local p = plist[m] local p = plist[m]
local vd = PrimD[p] local va, vb, vc, vd = PrimA[p], PrimB[p], PrimC[p], PrimD[p]
if PrimFlat[p] -- (most primitives use no vertex in the listed ones' range: two compares per vertex, no lookups)
or not (DriftSet[PrimA[p] // VTX_STRIDE + 1] or DriftSet[PrimB[p] // VTX_STRIDE + 1] if (va < lo or va > hi) and (vb < lo or vb > hi) and (vc < lo or vc > hi)
or DriftSet[PrimC[p] // VTX_STRIDE + 1] or (vd and DriftSet[vd // VTX_STRIDE + 1])) then and (not vd or vd < lo or vd > hi) then
continue continue
end end
if (PrimFlat[p] and not recolor)
or not (DriftSet[va // VTX_STRIDE + 1] or DriftSet[vb // VTX_STRIDE + 1]
or DriftSet[vc // VTX_STRIDE + 1] or (vd and DriftSet[vd // VTX_STRIDE + 1])) then
continue
end
if recolor then
if PrimGradient[p] ~= SigG[p - n0] then return false end
PatchH1[p], PatchH2[p], PatchSig[p] = PrimHash(p, lx0, ly0, ox, oy)
end
PatchPrim[p] = true PatchPrim[p] = true
local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0, local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0,
PrimBoundsY1[p] - ly0 PrimBoundsY1[p] - ly0
@@ -895,16 +1096,28 @@ local function PatchDrawList(BackendData, set, draw_list, n0, n, dx, dy, ox, oy,
table.move(tile.DrawnHash1, 1, count, 1, LH1) table.move(tile.DrawnHash1, 1, count, 1, LH1)
table.move(tile.DrawnHash2, 1, count, 1, LH2) table.move(tile.DrawnHash2, 1, count, 1, LH2)
table.move(tile.DrawnFlat, 1, count, 1, layer.TileListFlat[key]) table.move(tile.DrawnFlat, 1, count, 1, layer.TileListFlat[key])
local lx0, ly0 = LayerOrigin(draw_list, kind, ox, oy)
local LF = layer.TileListFlat[key]
local h1, h2 = 0, 0 local h1, h2 = 0, 0
for k = 1, count do for k = 1, count do
if PatchPrim[list[k]] then local p = list[k]
if not PatchPrim[p] then
-- (unchanged entry)
elseif not recolor then
LH1[k], LH2[k] = (LH1[k] + DriftMark1) % P1, (LH2[k] + DriftMark2) % P2 LH1[k], LH2[k] = (LH1[k] + DriftMark1) % P1, (LH2[k] + DriftMark2) % P2
else
local sig = PatchSig[p]
if sig >= 0 then
LH1[k], LH2[k] = FlatTileHash(p, lx0, ly0, layer.TileX[key], layer.TileY[key])
else
LH1[k], LH2[k] = PatchH1[p], PatchH2[p]
end
LF[k] = sig
end end
h1 = (h1 * 48271 + LH1[k]) % P1 h1 = (h1 * 48271 + LH1[k]) % P1
h2 = (h2 * 16807 + LH2[k] + k) % P2 h2 = (h2 * 16807 + LH2[k] + k) % P2
end end
layer.TileHash1[key], layer.TileHash2[key] = h1, h2 layer.TileHash1[key], layer.TileHash2[key] = h1, h2
local lx0, ly0 = LayerOrigin(draw_list, kind, ox, oy)
local x0, y0 = lx0 + layer.TileX[key] * TILE, ly0 + layer.TileY[key] * TILE local x0, y0 = lx0 + layer.TileX[key] * TILE, ly0 + layer.TileY[key] * TILE
local vx0, vy0, vx1, vy1 = 0, 0, TILE, TILE local vx0, vy0, vx1, vy1 = 0, 0, TILE, TILE
if layer.Root ~= layer.Frame then if layer.Root ~= layer.Frame then
@@ -974,6 +1187,7 @@ function M.RenderDrawData(draw_data)
Parallel.Active = Parallel.On and not Parallel.Config.Inline Parallel.Active = Parallel.On and not Parallel.Config.Inline
local n = 0 local n = 0
CmdCount = 0
local z = 0 local z = 0
local AnyDeferred = false local AnyDeferred = false
for _, draw_list in draw_data.CmdLists:iter() do for _, draw_list in draw_data.CmdLists:iter() do
@@ -1004,19 +1218,26 @@ function M.RenderDrawData(draw_data)
if nd > 0 then if nd > 0 then
local Drift = Layers.Drift local Drift = Layers.Drift
for k = 1, nd do DriftSet[Drift[k] // VTX_STRIDE + 1] = true end for k = 1, nd do DriftSet[Drift[k] // VTX_STRIDE + 1] = true end
DriftOn, DriftMark1, DriftMark2 = true, (FrameNo * 7907 + 12345) % P1, (FrameNo * 7919 + 54321) % P2 -- (recolored vertices, 4: only for PatchDrawList; the full path hashes them like any other)
DriftOn, DriftMark1, DriftMark2 = same == 3, (FrameNo * 7907 + 12345) % P1, (FrameNo * 7919 + 54321) % P2
end end
if same == 3 then if same == 3 or same == 4 then
PB("ImGui drift patch") PB("ImGui drift patch")
if EditableImages.StageTiming then EditableImages.BeginStage() end if EditableImages.StageTiming then EditableImages.BeginStage() end
local patched = PatchDrawList(BackendData, set, draw_list, n0, n, sdx, sdy, ox, oy, LimitX0, LimitY0, local patched = PatchDrawList(BackendData, set, draw_list, n0, n, sdx, sdy, ox, oy, LimitX0, LimitY0,
LimitX1, LimitY1) LimitX1, LimitY1, same == 4)
if EditableImages.StageTiming then EditableImages.EndStage("Raster") end if EditableImages.StageTiming then EditableImages.EndStage("Raster") end
PE() PE()
if patched then if patched then
for k = 1, nd do DriftSet[Layers.Drift[k] // VTX_STRIDE + 1] = false end for k = 1, nd do DriftSet[Layers.Drift[k] // VTX_STRIDE + 1] = false end
DriftOn = false DriftOn = false
z = ReuseDrawList(BackendData, set, draw_list, 2, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight) if same == 4 then
-- the snapshot: only vertex bytes changed
buffer.copy(set.SnapVtx, 0, draw_list.VtxBuffer.Buf, 0, set.SnapVtxBytes)
z = ReuseDrawList(BackendData, set, draw_list, 1, 0, 0, z, ox, oy, ScreenWidth, ScreenHeight)
else
z = ReuseDrawList(BackendData, set, draw_list, 2, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight)
end
continue continue
end end
end end
@@ -1038,6 +1259,7 @@ function M.RenderDrawData(draw_data)
set.PrimBase, set.PrimN = n0, n - n0 set.PrimBase, set.PrimN = n0, n - n0
set.PrimSigA = table.move(PrimA, n0 + 1, n, 1, set.PrimSigA or {}) set.PrimSigA = table.move(PrimA, n0 + 1, n, 1, set.PrimSigA or {})
set.PrimSigD = table.move(PrimD, n0 + 1, n, 1, set.PrimSigD or {}) set.PrimSigD = table.move(PrimD, n0 + 1, n, 1, set.PrimSigD or {})
set.PrimSigG = table.move(PrimGradient, n0 + 1, n, 1, set.PrimSigG or {})
end end
end end
if ListDeferred then AnyDeferred = true end if ListDeferred then AnyDeferred = true end
@@ -1046,8 +1268,8 @@ function M.RenderDrawData(draw_data)
SweepLayers(BackendData, FrameNo) SweepLayers(BackendData, FrameNo)
-- drop references so old vertex tables can be collected -- drop references so old vertex tables can be collected
for k = n + 1, BackendData.LastPrimCount do PrimTexture[k], PrimVtxBuffer[k] = nil, nil end for k = CmdCount + 1, BackendData.LastCmdCount do CmdTexture[k], CmdVtxBuffer[k] = nil, nil end
BackendData.LastPrimCount = n BackendData.LastCmdCount = CmdCount
-- Tiles left for later: if the app doesn't submit a new frame, Heartbeat finishes them from this draw data -- Tiles left for later: if the app doesn't submit a new frame, Heartbeat finishes them from this draw data
if AnyDeferred then if AnyDeferred then
BackendData.Stale = draw_data BackendData.Stale = draw_data
+1 -1
View File
@@ -1 +1 @@
[[49, "imgui.lua"], [22804, "imgui_demo.lua"], [34664, "imgui_draw.lua"], [43090, "imgui_h.lua"], [46100, "roblox/raster.lua"], [47259, "roblox/textures.lua"], [47510, "roblox/layers.lua"], [47922, "roblox/overlays.lua"], [48003, "roblox/render.lua"], [49076, "roblox/parallel.lua"], [49606, "roblox/patches.lua"], [49891, "imgui_impl_roblox.lua"], [50395, "imgui_impl_roblox_fonts.lua"], [56800, "imgui_internal.lua"], [60775, "imgui_tables.lua"], [65900, "imgui_widgets.lua"], [78288, "imstb_rectpack.lua"], [78965, "imstb_textedit.lua"], [80507, "imstb_truetype.lua"], [83468, "imstd_minstdio.lua"]] [[57, "imgui.lua"], [22812, "imgui_demo.lua"], [34672, "imgui_draw.lua"], [43097, "imgui_h.lua"], [46107, "roblox/raster.lua"], [47714, "roblox/textures.lua"], [47965, "roblox/layers.lua"], [48387, "roblox/overlays.lua"], [48468, "roblox/render.lua"], [49763, "roblox/parallel.lua"], [50295, "roblox/patches.lua"], [50580, "imgui_impl_roblox.lua"], [51092, "imgui_impl_roblox_fonts.lua"], [57497, "imgui_internal.lua"], [61482, "imgui_tables.lua"], [66610, "imgui_widgets.lua"], [78998, "imstb_rectpack.lua"], [79675, "imstb_textedit.lua"], [81217, "imstb_truetype.lua"], [84151, "imstd_minstdio.lua"]]
+975 -292
View File
File diff suppressed because it is too large. Load diff
+595 -147
View File
@@ -18,9 +18,9 @@ local readi32 = buffer.readi32
local M = { local M = {
TILE = 128, TILE = 128,
-- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs. -- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs.
-- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad), tex id (-1: none), -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad, 5 triangle pair), tex id
-- clip x0 y0 x1 y1, bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64, -- (-1: none), clip x0 y0 x1 y1, bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v
-- col u32): a at REC_A, c at REC_C, b at REC_B, d at REC_D. -- f64, col u32): a at REC_A, c at REC_C, b at REC_B, d at REC_D.
-- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32). -- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32).
VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32, VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32,
} }
@@ -42,6 +42,53 @@ local function PairF64(v: number): number | false
writeu32(PairScratch, 4, v) writeu32(PairScratch, 4, v)
return readf64(PairScratch, 0) return readf64(PairScratch, 0)
end end
-- Solid span [o, o1] (byte offsets of its first and last pixel) of value packed (pair: PairF64(packed) or false). A
-- native loop iteration costs more than a few writes: 8 (pairs) or 4 pixels per iteration.
@native
local function FillRow(buf: buffer, o: number, o1: number, packed: number, pair: number | false)
if pair then
while o + 24 < o1 do
writef64(buf, o, pair)
writef64(buf, o + 8, pair)
writef64(buf, o + 16, pair)
writef64(buf, o + 24, pair)
o += 32
end
while o < o1 do
writef64(buf, o, pair)
o += 8
end
if o == o1 then writeu32(buf, o, packed) end
return
end
while o + 12 <= o1 do
writeu32(buf, o, packed)
writeu32(buf, o + 4, packed)
writeu32(buf, o + 8, packed)
writeu32(buf, o + 12, packed)
o += 16
end
while o <= o1 do
writeu32(buf, o, packed)
o += 4
end
end
-- Rows 1 .. n - 1 below the span at o (len bytes) get its pixels. A span as wide as the target: the rows are
-- contiguous, copied in doubling blocks (log2 n calls instead of n).
@native
local function CopyRows(buf: buffer, o: number, len: number, n: number)
local stride = TargetWidth * 4
if len == stride then
local done = 1
while done < n do
local c = min(done, n - done)
buffer.copy(buf, o + done * stride, buf, o, c * stride)
done += c
end
else
for k = 1, n - 1 do buffer.copy(buf, o + k * stride, buf, o, len) end
end
end
local PrevRow = buffer.create(1024) local PrevRow = buffer.create(1024)
-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else -- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else
@@ -142,34 +189,30 @@ end
local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number, local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number,
b: number, a: number) b: number, a: number)
if a <= 0 then return end if a <= 0 then return end
if PX0 < PX1 then
ApplyDamage(PX0, PY0, PX1, PY1)
PX1 = PX0
end
local w4 = (x1 - x0 - 1) * 4 local w4 = (x1 - x0 - 1) * 4
local span = x1 - x0 local span = x1 - x0
if a >= 255 and span <= 8 then
-- opaque and narrow (vertical lines, histogram bars): writes (a call per row costs more), and the uniform rows
-- just lose the span (pending damage, merged with the neighbours' like any primitive's), no per-row bookkeeping:
-- a narrow span rarely becomes the larger uniform piece of its rows
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local stride = TargetWidth * 4
local first = (y0 * TargetWidth + x0) * 4 + TargetBase
for o = first, first + (y1 - y0 - 1) * stride, stride do
for oo = o, o + w4, 4 do writeu32(TargetBuffer, oo, packed) end
end
Shrink(x0, y0, x1, y1)
return
end
if a >= 255 then if a >= 255 then
if PX0 < PX1 then
ApplyDamage(PX0, PY0, PX1, PY1)
PX1 = PX0
end
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local first = (y0 * TargetWidth + x0) * 4 + TargetBase local first = (y0 * TargetWidth + x0) * 4 + TargetBase
local pair = span >= 16 and PairF64(packed) FillRow(TargetBuffer, first, first + w4, packed, span >= 16 and PairF64(packed))
if pair then CopyRows(TargetBuffer, first, w4 + 4, y1 - y0)
local o, o1 = first, first + w4
while o < o1 do
writef64(TargetBuffer, o, pair)
o += 8
end
if o == o1 then writeu32(TargetBuffer, o, packed) end
else
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end
end
if span <= 8 then -- narrow (vertical lines): writes, a call per row costs more
local stride = TargetWidth * 4
for o = first + stride, first + (y1 - y0 - 1) * stride, stride do
for oo = o, o + w4, 4 do writeu32(TargetBuffer, oo, packed) end
end
else
for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4 + TargetBase, TargetBuffer, first, w4 + 4) end
end
-- now uniform: per row keep whichever piece is larger (the same for following rows with the same piece) -- now uniform: per row keep whichever piece is larger (the same for following rows with the same piece)
local y = y0 local y = y0
while y < y1 do while y < y1 do
@@ -199,6 +242,46 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
local rs, gs, bs = r * sa, g * sa, b * sa local rs, gs, bs = r * sa, g * sa, b * sa
local black = rs == 0 and gs == 0 and bs == 0 local black = rs == 0 and gs == 0 and bs == 0
local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination
if span <= 4 then
-- narrow (vertical lines): blended per pixel (the uniform-row lookups per row cost more than the blend, which
-- is cached per destination value, the same result as the uniform path's); the rows just lose the span
-- (pending damage, like a narrow opaque span)
local stride = TargetWidth * 4
local first = (y0 * TargetWidth + x0) * 4 + TargetBase
-- rows x pixels; one pixel wide: one loop down the column
local olast, ilen, istep = first + (y1 - y0 - 1) * stride, w4, 4
if span == 1 then olast, ilen, istep = first, olast - first, stride end
for o0 = first, olast, stride do
for o = o0, o0 + ilen, istep do
local d = readu32(TargetBuffer, o)
if d == last_d then
writeu32(TargetBuffer, o, last_v)
elseif d < 16777216 then
writeu32(TargetBuffer, o, packed0)
else
last_d = d
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256
+ floor(bs + db * ns + 0.5) * 65536 + 4278190080
else
local k = rshift(d, 24) * c1
local oa = sa + k
local inv = 1 / oa
last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256
+ floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(TargetBuffer, o, last_v)
end
end
end
Shrink(x0, y0, x1, y1)
return
end
if PX0 < PX1 then
ApplyDamage(PX0, PY0, PX1, PY1)
PX1 = PX0
end
local prev_o, prev_v = 0, -1 -- previous row: filled with prev_v (-1: blended) local prev_o, prev_v = 0, -1 -- previous row: filled with prev_v (-1: blended)
local wide, has_prev = span >= 32 and y1 - y0 > 1, false local wide, has_prev = span >= 32 and y1 - y0 > 1, false
local y = y0 local y = y0
@@ -231,17 +314,7 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
if v == prev_v and span > 8 then -- (a call: slower than a few writes) if v == prev_v and span > 8 then -- (a call: slower than a few writes)
buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4) buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4)
else else
local pair = span >= 16 and PairF64(v) FillRow(TargetBuffer, o0, o0 + w4, v, span >= 16 and PairF64(v))
if pair then
local o, o1 = o0, o0 + w4
while o < o1 do
writef64(TargetBuffer, o, pair)
o += 8
end
if o == o1 then writeu32(TargetBuffer, o, v) end
else
for o = o0, o0 + w4, 4 do writeu32(TargetBuffer, o, v) end
end
end end
local na, nb, nv = ra, rb, d local na, nb, nv = ra, rb, d
if span >= x0 - ra and span >= rb - x1 then if span >= x0 - ra and span >= rb - x1 then
@@ -254,16 +327,21 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
RowX0[y], RowX1[y], RowV[y] = na, nb, nv RowX0[y], RowX1[y], RowV[y] = na, nb, nv
y += 1 y += 1
local stride = TargetWidth * 4 local stride = TargetWidth * 4
local o = o0 local n = 1
while y < y1 and RowX0[y] == ra and RowX1[y] == rb and RowV[y] == d do while y < y1 and RowX0[y] == ra and RowX1[y] == rb and RowV[y] == d do
o += stride
if span <= 8 then
for oo = o, o + w4, 4 do writeu32(TargetBuffer, oo, v) end
else
buffer.copy(TargetBuffer, o, TargetBuffer, o0, w4 + 4)
end
RowX0[y], RowX1[y], RowV[y] = na, nb, nv RowX0[y], RowX1[y], RowV[y] = na, nb, nv
y += 1 y += 1
n += 1
end
local o = o0 + (n - 1) * stride
if n > 1 then
if span <= 8 then
for oy = o0 + stride, o, stride do
for oo = oy, oy + w4, 4 do writeu32(TargetBuffer, oo, v) end
end
else
CopyRows(TargetBuffer, o0, w4 + 4, n)
end
end end
prev_o, prev_v, has_prev = o, v, false prev_o, prev_v, has_prev = o, v, false
continue continue
@@ -284,7 +362,27 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
prev_o, prev_v = o0, -1 prev_o, prev_v = o0, -1
if black then if black then
-- (black: rs + x is x, so the opaque case is just the scaled destination; colour picker SV square) -- (black: rs + x is x, so the opaque case is just the scaled destination; colour picker SV square)
for o = o0, o0 + w4, 4 do -- opaque destination pixels four per iteration, computed directly (rarely repeated: no cache)
local o, oe = o0, o0 + w4
while o + 8 < oe do
local d, d2 = readu32(TargetBuffer, o), readu32(TargetBuffer, o + 4)
local d3, d4 = readu32(TargetBuffer, o + 8), readu32(TargetBuffer, o + 12)
if d < 4278190080 or d2 < 4278190080 or d3 < 4278190080 or d4 < 4278190080 then break end
writeu32(TargetBuffer, o,
floor(band(d, 255) * ns + 0.5) + floor(band(rshift(d, 8), 255) * ns + 0.5) * 256
+ floor(band(rshift(d, 16), 255) * ns + 0.5) * 65536 + 4278190080)
writeu32(TargetBuffer, o + 4,
floor(band(d2, 255) * ns + 0.5) + floor(band(rshift(d2, 8), 255) * ns + 0.5) * 256
+ floor(band(rshift(d2, 16), 255) * ns + 0.5) * 65536 + 4278190080)
writeu32(TargetBuffer, o + 8,
floor(band(d3, 255) * ns + 0.5) + floor(band(rshift(d3, 8), 255) * ns + 0.5) * 256
+ floor(band(rshift(d3, 16), 255) * ns + 0.5) * 65536 + 4278190080)
writeu32(TargetBuffer, o + 12,
floor(band(d4, 255) * ns + 0.5) + floor(band(rshift(d4, 8), 255) * ns + 0.5) * 256
+ floor(band(rshift(d4, 16), 255) * ns + 0.5) * 65536 + 4278190080)
o += 16
end
for o = o, oe, 4 do
local d = readu32(TargetBuffer, o) local d = readu32(TargetBuffer, o)
if d ~= last_d then if d ~= last_d then
last_d = d last_d = d
@@ -335,7 +433,7 @@ end
@native @native
local function UnpackColor(col: number) local function UnpackColor(col: number)
return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 return band(col, 255), band(rshift(col, 8), 255), band(rshift(col, 16), 255), rshift(col, 24)
end end
@native @native
@@ -411,7 +509,7 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
continue continue
end end
local d, key, al = 0, -1, 0 local d, key, al = 0, -1, 0
if tv % 16777216 == 16777215 then if band(tv, 16777215) == 16777215 then
al = rshift(tv, 24) al = rshift(tv, 24)
d = readu32(dbuf, o) d = readu32(dbuf, o)
key = gen + d key = gen + d
@@ -498,10 +596,14 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0 local n0, n1, n2 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0
-- UnpackColor / SampleTexture inlined (a call costs more than the math) -- UnpackColor / SampleTexture inlined (a call costs more than the math)
local ca, cb, cc = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), readu32(vbuf, vc + 32) local ca, cb, cc = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), readu32(vbuf, vc + 32)
local ra, ga, ba, aa = ca % 256, floor(ca / 256) % 256, floor(ca / 65536) % 256, floor(ca / 16777216) % 256 local ra, ga, ba, aa = band(ca, 255), band(rshift(ca, 8), 255), band(rshift(ca, 16), 255), rshift(ca, 24)
local rb, gb, bb, ab, rc, gc, bc, ac = ra, ga, ba, aa, ra, ga, ba, aa local rb, gb, bb, ab, rc, gc, bc, ac = ra, ga, ba, aa, ra, ga, ba, aa
if cb ~= ca then rb, gb, bb, ab = cb % 256, floor(cb / 256) % 256, floor(cb / 65536) % 256, floor(cb / 16777216) % 256 end if cb ~= ca then
if cc ~= ca then rc, gc, bc, ac = cc % 256, floor(cc / 256) % 256, floor(cc / 65536) % 256, floor(cc / 16777216) % 256 end rb, gb, bb, ab = band(cb, 255), band(rshift(cb, 8), 255), band(rshift(cb, 16), 255), rshift(cb, 24)
end
if cc ~= ca then
rc, gc, bc, ac = band(cc, 255), band(rshift(cc, 8), 255), band(rshift(cc, 16), 255), rshift(cc, 24)
end
local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16), local ua, vva, ub, vvb, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vb + 16),
readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) readf64(vbuf, vb + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
@@ -544,33 +646,86 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
if cconst then r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 end if cconst then r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 end
local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0
if textured then tw, th, tbuf = t.Width, t.Height, t.Buffer end if textured then tw, th, tbuf = t.Width, t.Height, t.Buffer end
-- Interpolated alpha on an edge whose two vertices have alpha 0 (an AA fringe's outer edge, which sits on pixel
-- centres) is 0: the edge's own weight is 0 there, so a row / column on it draws nothing
local interp = not flat and not cconst
local z0, z1, z2 = interp and ab == 0 and ac == 0, interp and aa == 0 and ac == 0, interp and aa == 0 and ab == 0
if not textured and (maxx - minx) * 2 < maxy - miny then if not textured and (maxx - minx) * 2 < maxy - miny then
-- tall sliver (vertical AA fringe): walk columns, same per-pixel edge and colour math as the rows below (each -- tall sliver (vertical AA fringe): walk columns, same per-pixel edge and colour math as the rows below (each
-- pixel blended once, so the order does not matter): no empty-row passes -- pixel blended once, so the order does not matter): no empty-row passes
local m0, m1, m2 = B0 ~= 0 and -1 / B0 or 0, B1 ~= 0 and -1 / B1 or 0, B2 ~= 0 and -1 / B2 or 0 -- (edge slots like the rows below, along y: B > 0 bounds a column from above, B < 0 from below; an edge with
-- B = 0 (vertical: w is the same on the whole column, B * py is 0) passes a run of columns: the column range)
local T1A, T1B, T1C, T1M, T1t, T2A, T2B, T2C, T2M, T2t = 0, 0, 1e9, -1, false, 0, 0, 1e9, -1, false
local U1A, U1B, U1C, U1M, U1t, U2A, U2B, U2C, U2M, U2t = 0, 0, 1e9, 1, false, 0, 0, 1e9, 1, false
local VA, VC, Vtl, Vz = 0, 1e9, false, false
local t1, u1 = false, false -- (slot 1 taken)
if B0 > 0 then
T1A, T1B, T1C, T1M, T1t, t1 = A0, B0, C0, -1 / B0, tl0, true
elseif B0 < 0 then
U1A, U1B, U1C, U1M, U1t, u1 = A0, B0, C0, -1 / B0, tl0, true
else
VA, VC, Vtl, Vz = A0, C0, tl0, z0
end
if B1 > 0 then
if not t1 then
T1A, T1B, T1C, T1M, T1t, t1 = A1, B1, C1, -1 / B1, tl1, true
else
T2A, T2B, T2C, T2M, T2t = A1, B1, C1, -1 / B1, tl1
end
elseif B1 < 0 then
if not u1 then
U1A, U1B, U1C, U1M, U1t, u1 = A1, B1, C1, -1 / B1, tl1, true
else
U2A, U2B, U2C, U2M, U2t = A1, B1, C1, -1 / B1, tl1
end
else
VA, VC, Vtl, Vz = A1, C1, tl1, z1
end
if B2 > 0 then
if not t1 then
T1A, T1B, T1C, T1M, T1t, t1 = A2, B2, C2, -1 / B2, tl2, true
else
T2A, T2B, T2C, T2M, T2t = A2, B2, C2, -1 / B2, tl2
end
elseif B2 < 0 then
if not u1 then
U1A, U1B, U1C, U1M, U1t, u1 = A2, B2, C2, -1 / B2, tl2, true
else
U2A, U2B, U2C, U2M, U2t = A2, B2, C2, -1 / B2, tl2
end
else
VA, VC, Vtl, Vz = A2, C2, tl2, z2
end
if VA ~= 0 then
local py = miny + 0.5
while minx <= maxx do
local w = VA * (minx + 0.5) + (0 * py + VC)
if (w > 0 or (w == 0 and Vtl)) and not (w == 0 and Vz) then break end
minx += 1
end
while maxx > minx do
local w = VA * (maxx + 0.5) + (0 * py + VC)
if (w > 0 or (w == 0 and Vtl)) and not (w == 0 and Vz) then break end
maxx -= 1
end
end
local stride = TargetWidth * 4 local stride = TargetWidth * 4
for x = minx, maxx do for x = minx, maxx do
local px = x + 0.5 local px = x + 0.5
local yt, yb = miny, maxy local f1, f2, g1, g2 = T1A * px + T1C, T2A * px + T2C, U1A * px + U1C, U2A * px + U2C
local f0, f1, f2 = A0 * px + C0, A1 * px + C1, A2 * px + C2 local yt = max(miny, floor(f1 * T1M - 0.500001), floor(f2 * T2M - 0.500001))
if B0 > 0 then yt = max(yt, floor(f0 * m0 - 0.500001)) elseif B0 < 0 then yb = min(yb, ceil(f0 * m0 - 0.499999)) end local yb = min(maxy, ceil(g1 * U1M - 0.499999), ceil(g2 * U2M - 0.499999))
if B1 > 0 then yt = max(yt, floor(f1 * m1 - 0.500001)) elseif B1 < 0 then yb = min(yb, ceil(f1 * m1 - 0.499999)) end
if B2 > 0 then yt = max(yt, floor(f2 * m2 - 0.500001)) elseif B2 < 0 then yb = min(yb, ceil(f2 * m2 - 0.499999)) end
while yt <= yb do while yt <= yb do
local py = yt + 0.5 local py = yt + 0.5
local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) local w1, w2 = T1A * px + (T1B * py + T1C), T2A * px + (T2B * py + T2C)
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then if (w1 > 0 or (w1 == 0 and T1t)) and (w2 > 0 or (w2 == 0 and T2t)) then break end
break
end
yt += 1 yt += 1
end end
while yb > yt do while yb >= yt do
local py = yb + 0.5 local py = yb + 0.5
local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2) local w1, w2 = U1A * px + (U1B * py + U1C), U2A * px + (U2B * py + U2C)
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then if (w1 > 0 or (w1 == 0 and U1t)) and (w2 > 0 or (w2 == 0 and U2t)) then break end
break
end
yb -= 1 yb -= 1
end end
if yt > yb then continue end if yt > yb then continue end
@@ -579,7 +734,20 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
-- the row path's flat spans (BlendPixel's math, per-span constants, cached per destination value) -- the row path's flat spans (BlendPixel's math, per-span constants, cached per destination value)
local o1 = o + (yb - yt) * stride local o1 = o + (yb - yt) * stride
if f_opaque then if f_opaque then
for oo = o, o1, stride do writeu32(dbuf, oo, f_packed) end -- (4 pixels per iteration: a native loop iteration costs more than a few writes)
local s4 = stride * 4
local oo = o
while oo + s4 <= o1 + stride do
writeu32(dbuf, oo, f_packed)
writeu32(dbuf, oo + stride, f_packed)
writeu32(dbuf, oo + stride * 2, f_packed)
writeu32(dbuf, oo + stride * 3, f_packed)
oo += s4
end
while oo <= o1 do
writeu32(dbuf, oo, f_packed)
oo += stride
end
continue continue
end end
local last_d, last_v = -1, 0 local last_d, last_v = -1, 0
@@ -646,46 +814,69 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
return return
end end
-- Row spans. Each edge bounds a row from one side: w is monotone in x (A * px + e rounds monotonically), so the
-- pixels passing an edge are a run open to one side (A > 0: to the right, top-left so w >= 0 passes; A < 0: to
-- the left, w > 0), and the span is [first pixel passing the left edges, last passing the right ones]. Edges go
-- in slots per side (L, R; a spare slot is a dummy edge with w = 1e9, never binding), so a row is an estimate and
-- a short search per side, without per-edge branches. A horizontal edge (A = 0: w is e on the whole row) passes
-- a run of rows instead (e is monotone in y): the row range.
local L1A, L1B, L1C, L1N, L2A, L2B, L2C, L2N = 0, 0, 1e9, -1, 0, 0, 1e9, -1
local R1A, R1B, R1C, R1N, R2A, R2B, R2C, R2N = 0, 0, 1e9, 1, 0, 0, 1e9, 1
local HB, HC, Htl, Hz = 0, 1e9, false, false
local l1, r1 = false, false -- (slot 1 taken)
if A0 > 0 then
L1A, L1B, L1C, L1N, l1 = A0, B0, C0, n0, true
elseif A0 < 0 then
R1A, R1B, R1C, R1N, r1 = A0, B0, C0, n0, true
else
HB, HC, Htl, Hz = B0, C0, tl0, z0
end
if A1 > 0 then
if not l1 then L1A, L1B, L1C, L1N, l1 = A1, B1, C1, n1, true else L2A, L2B, L2C, L2N = A1, B1, C1, n1 end
elseif A1 < 0 then
if not r1 then R1A, R1B, R1C, R1N, r1 = A1, B1, C1, n1, true else R2A, R2B, R2C, R2N = A1, B1, C1, n1 end
else
HB, HC, Htl, Hz = B1, C1, tl1, z1
end
if A2 > 0 then
if not l1 then L1A, L1B, L1C, L1N, l1 = A2, B2, C2, n2, true else L2A, L2B, L2C, L2N = A2, B2, C2, n2 end
elseif A2 < 0 then
if not r1 then R1A, R1B, R1C, R1N, r1 = A2, B2, C2, n2, true else R2A, R2B, R2C, R2N = A2, B2, C2, n2 end
else
HB, HC, Htl, Hz = B2, C2, tl2, z2
end
if HB ~= 0 then
while miny <= maxy do
local e = HB * (miny + 0.5) + HC
if (e > 0 or (e == 0 and Htl)) and not (e == 0 and Hz) then break end
miny += 1
end
while maxy > miny do
local e = HB * (maxy + 0.5) + HC
if (e > 0 or (e == 0 and Htl)) and not (e == 0 and Hz) then break end
maxy -= 1
end
end
for y = miny, maxy do for y = miny, maxy do
local py = y + 0.5 local py = y + 0.5
local xl, xr = minx, maxx
local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2 local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2
local f1, f2, g1, g2 = L1B * py + L1C, L2B * py + L2C, R1B * py + R1C, R2B * py + R2C
-- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide) -- (e * n is -e / A within an ulp; the 1e-6 margin covers that, and the exact tests below decide)
if A0 > 0 then local xl = max(minx, floor(f1 * L1N - 0.500001), floor(f2 * L2N - 0.500001))
xl = max(xl, floor(e0 * n0 - 0.500001)) local xr = min(maxx, ceil(g1 * R1N - 0.499999), ceil(g2 * R2N - 0.499999))
elseif A0 < 0 then
xr = min(xr, ceil(e0 * n0 - 0.499999))
end
if A1 > 0 then
xl = max(xl, floor(e1 * n1 - 0.500001))
elseif A1 < 0 then
xr = min(xr, ceil(e1 * n1 - 0.499999))
end
if A2 > 0 then
xl = max(xl, floor(e2 * n2 - 0.500001))
elseif A2 < 0 then
xr = min(xr, ceil(e2 * n2 - 0.499999))
end
-- An estimate inside (minx, maxx) is never in the span: the pixel centre is >= 1e-6 outside the crossing it -- An estimate inside (minx, maxx) is never in the span: the pixel centre is >= 1e-6 outside the crossing it
-- estimates, and with |A * px| and |e| below 2^17 * |A| the test's rounding error is far below 1e-6 * |A| (the -- estimates, and with |A * px| and |e| below 2^17 * |A| the test's rounding error is far below 1e-6 * |A| (the
-- test reads the same e). Testing from the next pixel gives the same span. -- test reads the same e). Testing from the next pixel gives the same span.
if xl > minx and xl <= xr then xl += 1 end if xl > minx and xl <= xr then xl += 1 end
while xl <= xr do while xl <= xr do
local px = xl + 0.5 local px = xl + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 if L1A * px + f1 >= 0 and L2A * px + f2 >= 0 then break end
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
xl += 1 xl += 1
end end
if xr < maxx and xr > xl then xr -= 1 end if xr < maxx and xr > xl then xr -= 1 end
while xr > xl do while xr >= xl do
local px = xr + 0.5 local px = xr + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2 if R1A * px + g1 > 0 and R2A * px + g2 > 0 then break end
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
xr -= 1 xr -= 1
end end
if xl > xr then continue end if xl > xr then continue end
@@ -693,15 +884,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
if flat then if flat then
local o1 = o + (xr - xl) * 4 local o1 = o + (xr - xl) * 4
if f_opaque then if f_opaque then
if f_pair then FillRow(dbuf, o, o1, f_packed, f_pair)
while o < o1 do
writef64(dbuf, o, f_pair)
o += 8
end
if o == o1 then writeu32(dbuf, o, f_packed) end
else
for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end
end
continue continue
end end
local last_d, last_v = -1, 0 local last_d, last_v = -1, 0
@@ -825,6 +1008,212 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end end
end end
-- One triangle's row walk as DrawTriangle sets it up (same edges, orientation, edge slots and row range; see its rows):
-- clipped bounds, then the L1 L2 R1 R2 slots (A, B, C, n). For flat triangles only (no alpha-0 edge rows).
@native
local function TriangleSlots(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, cx0: number,
cy0: number, cx1: number, cy1: number)
local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)
if area < 0 then
x1, y1, x2, y2 = x2, y2, x1, y1
end
local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1)
local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1)
local A0, B0 = y1 - y2, x2 - x1
local C0 = -(A0 * x1 + B0 * y1)
local A1, B1 = y2 - y0, x0 - x2
local C1 = -(A1 * x2 + B1 * y2)
local A2, B2 = y0 - y1, x1 - x0
local C2 = -(A2 * x0 + B2 * y0)
local L1A, L1B, L1C, L1N, L2A, L2B, L2C, L2N = 0, 0, 1e9, -1, 0, 0, 1e9, -1
local R1A, R1B, R1C, R1N, R2A, R2B, R2C, R2N = 0, 0, 1e9, 1, 0, 0, 1e9, 1
local HB, HC, Htl = 0, 1e9, false
local l1, r1 = false, false
if A0 > 0 then
L1A, L1B, L1C, L1N, l1 = A0, B0, C0, -1 / A0, true
elseif A0 < 0 then
R1A, R1B, R1C, R1N, r1 = A0, B0, C0, -1 / A0, true
else
HB, HC, Htl = B0, C0, B0 > 0
end
if A1 > 0 then
if not l1 then L1A, L1B, L1C, L1N, l1 = A1, B1, C1, -1 / A1, true else L2A, L2B, L2C, L2N = A1, B1, C1, -1 / A1 end
elseif A1 < 0 then
if not r1 then R1A, R1B, R1C, R1N, r1 = A1, B1, C1, -1 / A1, true else R2A, R2B, R2C, R2N = A1, B1, C1, -1 / A1 end
else
HB, HC, Htl = B1, C1, B1 > 0
end
if A2 > 0 then
if not l1 then L1A, L1B, L1C, L1N, l1 = A2, B2, C2, -1 / A2, true else L2A, L2B, L2C, L2N = A2, B2, C2, -1 / A2 end
elseif A2 < 0 then
if not r1 then R1A, R1B, R1C, R1N, r1 = A2, B2, C2, -1 / A2, true else R2A, R2B, R2C, R2N = A2, B2, C2, -1 / A2 end
else
HB, HC, Htl = B2, C2, B2 > 0
end
if HB ~= 0 and minx <= maxx then
while miny <= maxy do
local e = HB * (miny + 0.5) + HC
if e > 0 or (e == 0 and Htl) then break end
miny += 1
end
while maxy > miny do
local e = HB * (maxy + 0.5) + HC
if e > 0 or (e == 0 and Htl) then break end
maxy -= 1
end
end
return minx, maxx, miny, maxy, L1A, L1B, L1C, L1N, L2A, L2B, L2C, L2N, R1A, R1B, R1C, R1N, R2A, R2B, R2C, R2N
end
-- Flat triangle pair a b c + a b d, one colour, constant uv (ImPlot PrimRectFill: heatmap cells, bars). The same pixels
-- and values as the two DrawTriangle calls: per row each triangle's span exactly as DrawTriangle computes it (a flat
-- triangle's pixels are the same whether walked by rows or columns: the same per-pixel edge tests), then one fill when
-- the spans touch (opaque: or overlap; a pixel inside both gets the same value twice), else each span in order (a
-- translucent pixel inside both is blended twice, first for a b c, as before). Saves the second triangle's setup, a
-- span fill per row, and the column walk of tall bars.
@native
local function DrawTriPair(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, vd: number, t, cx0: number,
cy0: number, cx1: number, cy1: number, ox: number, oy: number)
local ax, ay = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy
local bx, by = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy
local cx, cy = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy
local dx, dy = readf64(vbuf, vd) - ox, readf64(vbuf, vd + 8) - oy
-- (DrawTriangle walks a tall triangle by columns, whose span estimates may differ from the rows' for an almost
-- vertical edge: then the two calls, like a degenerate triangle)
if (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) == 0 or (bx - ax) * (dy - ay) - (by - ay) * (dx - ax) == 0
or (min(ceil(max(ax, bx, cx)), cx1 - 1) - max(floor(min(ax, bx, cx)), cx0)) * 2
< min(ceil(max(ay, by, cy)), cy1 - 1) - max(floor(min(ay, by, cy)), cy0)
or (min(ceil(max(ax, bx, dx)), cx1 - 1) - max(floor(min(ax, bx, dx)), cx0)) * 2
< min(ceil(max(ay, by, dy)), cy1 - 1) - max(floor(min(ay, by, dy)), cy0) then
DrawTriangle(dbuf, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy)
DrawTriangle(dbuf, vbuf, va, vb, vd, t, cx0, cy0, cx1, cy1, ox, oy)
return
end
-- DrawTriangle's flat colour (the texel folded in like there)
local col = readu32(vbuf, va + 32)
local ra, ga, ba, aa = band(col, 255), band(rshift(col, 8), 255), band(rshift(col, 16), 255), rshift(col, 24)
if t then
local tw0, th0 = t.Width, t.Height
local tx, ty = floor(readf64(vbuf, va + 16) * tw0), floor(readf64(vbuf, va + 24) * th0)
if tx < 0 then tx = 0 elseif tx >= tw0 then tx = tw0 - 1 end
if ty < 0 then ty = 0 elseif ty >= th0 then ty = th0 - 1 end
local to, tb0 = (ty * tw0 + tx) * 4, t.Buffer
if readu32(tb0, to) ~= 4294967295 then
local tr, tg, tb, ta = readu8(tb0, to), readu8(tb0, to + 1), readu8(tb0, to + 2), readu8(tb0, to + 3)
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
end
end
if aa <= 0 then return end
local f_opaque = aa >= 255
local f_packed = floor(ra + 0.5) + floor(ga + 0.5) * 256 + floor(ba + 0.5) * 65536
+ (f_opaque and 4278190080 or floor(aa + 0.5) * 16777216)
local f_pair: number | false = f_opaque and PairF64(f_packed)
local f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = 0, 0, 0, 0, 0, 0
if not f_opaque then
f_sa = aa / 255
f_ns = 1 - f_sa
f_c1 = f_ns / 255
f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa
end
local minx1, maxx1, miny1, maxy1, P1A, P1B, P1C, P1N, P2A, P2B, P2C, P2N, Q1A, Q1B, Q1C, Q1N, Q2A, Q2B, Q2C, Q2N =
TriangleSlots(ax, ay, bx, by, cx, cy, cx0, cy0, cx1, cy1)
local minx2, maxx2, miny2, maxy2, S1A, S1B, S1C, S1N, S2A, S2B, S2C, S2N, T1A, T1B, T1C, T1N, T2A, T2B, T2C, T2N =
TriangleSlots(ax, ay, bx, by, dx, dy, cx0, cy0, cx1, cy1)
if minx1 > maxx1 then miny1 = maxy1 + 1 end -- (empty)
if minx2 > maxx2 then miny2 = maxy2 + 1 end
local ylo, yhi = miny1, maxy1
if miny1 > maxy1 then
ylo, yhi = miny2, maxy2
elseif miny2 <= maxy2 then
ylo, yhi = min(miny1, miny2), max(maxy1, maxy2)
end
if ylo > yhi then return end
Shrink(min(minx1, minx2), ylo, max(maxx1, maxx2) + 1, yhi + 1)
for y = ylo, yhi do
local py = y + 0.5
local l1, r1, l2, r2 = 0, -1, 0, -1
if y >= miny1 and y <= maxy1 then
local f1, f2, g1, g2 = P1B * py + P1C, P2B * py + P2C, Q1B * py + Q1C, Q2B * py + Q2C
local xl = max(minx1, floor(f1 * P1N - 0.500001), floor(f2 * P2N - 0.500001))
local xr = min(maxx1, ceil(g1 * Q1N - 0.499999), ceil(g2 * Q2N - 0.499999))
if xl > minx1 and xl <= xr then xl += 1 end
while xl <= xr do
local px = xl + 0.5
if P1A * px + f1 >= 0 and P2A * px + f2 >= 0 then break end
xl += 1
end
if xr < maxx1 and xr > xl then xr -= 1 end
while xr >= xl do
local px = xr + 0.5
if Q1A * px + g1 > 0 and Q2A * px + g2 > 0 then break end
xr -= 1
end
l1, r1 = xl, xr
end
if y >= miny2 and y <= maxy2 then
local f1, f2, g1, g2 = S1B * py + S1C, S2B * py + S2C, T1B * py + T1C, T2B * py + T2C
local xl = max(minx2, floor(f1 * S1N - 0.500001), floor(f2 * S2N - 0.500001))
local xr = min(maxx2, ceil(g1 * T1N - 0.499999), ceil(g2 * T2N - 0.499999))
if xl > minx2 and xl <= xr then xl += 1 end
while xl <= xr do
local px = xl + 0.5
if S1A * px + f1 >= 0 and S2A * px + f2 >= 0 then break end
xl += 1
end
if xr < maxx2 and xr > xl then xr -= 1 end
while xr >= xl do
local px = xr + 0.5
if T1A * px + g1 > 0 and T2A * px + g2 > 0 then break end
xr -= 1
end
l2, r2 = xl, xr
end
if l1 > r1 then
if l2 > r2 then continue end
l1, r1, l2, r2 = l2, r2, 0, -1
elseif l2 <= r2 and (l2 == r1 + 1 or l1 == r2 + 1 or (f_opaque and l2 <= r1 and l1 <= r2)) then
l1, r1, l2, r2 = min(l1, l2), max(r1, r2), 0, -1
end
local row = y * TargetWidth * 4 + TargetBase
if f_opaque then
FillRow(dbuf, row + l1 * 4, row + r1 * 4, f_packed, f_pair)
if l2 <= r2 then FillRow(dbuf, row + l2 * 4, row + r2 * 4, f_packed, f_pair) end
continue
end
-- DrawTriangle's flat translucent span (same math, cached per destination value), per span in order
local last_d, last_v = -1, 0
for k = 1, 2 do
if k == 2 then
if l2 > r2 then break end
l1, r1 = l2, r2
end
for oo = row + l1 * 4, row + r1 * 4, 4 do
local d = readu32(dbuf, oo)
if d == last_d then
writeu32(dbuf, oo, last_v)
elseif d < 16777216 then
writeu32(dbuf, oo, f_packed)
else
last_d = d
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
last_v = floor(f_rs + dr * f_ns + 0.5) + floor(f_gs + dg * f_ns + 0.5) * 256
+ floor(f_bs + db * f_ns + 0.5) * 65536 + 4278190080
else
local kk = rshift(d, 24) * f_c1
local oa = f_sa + kk
local inv = 1 / oa
last_v = floor((f_rs + dr * kk) * inv + 0.5) + floor((f_gs + dg * kk) * inv + 0.5) * 256
+ floor((f_bs + db * kk) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(dbuf, oo, last_v)
end
end
end
end
end
-- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as -- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as
-- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad. -- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad.
@native @native
@@ -845,7 +1234,7 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local miny, maxy = max(floor(min(y0, y1, y2, y3)), cy0), min(ceil(max(y0, y1, y2, y3)), cy1 - 1) local miny, maxy = max(floor(min(y0, y1, y2, y3)), cy0), min(ceil(max(y0, y1, y2, y3)), cy1 - 1)
if minx > maxx or miny > maxy then return end if minx > maxx or miny > maxy then return end
local col = readu32(vbuf, va + 32) local col = readu32(vbuf, va + 32)
local ra, ga, ba, aa = col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256 local ra, ga, ba, aa = band(col, 255), band(rshift(col, 8), 255), band(rshift(col, 16), 255), rshift(col, 24)
if aa <= 0 then return end if aa <= 0 then return end
local ua, vva, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) local ua, vva, uc, vvc = readf64(vbuf, va + 16), readf64(vbuf, va + 24), readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
-- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P -- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P
@@ -887,33 +1276,93 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
trow = ty * tw * 4 trow = ty * tw * 4
end end
local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255 local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255
local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 -- (edge slots and row range like DrawTriangle's rows; up to 3 edges on a side, 2 horizontal)
local L1A, L1B, L1C, L1N, L2A, L2B, L2C, L2N, L3A, L3B, L3C, L3N = 0, 0, 1e9, -1, 0, 0, 1e9, -1, 0, 0, 1e9, -1
local R1A, R1B, R1C, R1N, R2A, R2B, R2C, R2N, R3A, R3B, R3C, R3N = 0, 0, 1e9, 1, 0, 0, 1e9, 1, 0, 0, 1e9, 1
local H1B, H1C, H1t, H2B, H2C, H2t = 0, 1e9, false, 0, 1e9, false
local nl, nr = 0, 0
if A0 > 0 then
if nl == 0 then L1A, L1B, L1C, L1N = A0, B0, C0, n0 elseif nl == 1 then L2A, L2B, L2C, L2N = A0, B0, C0, n0
else L3A, L3B, L3C, L3N = A0, B0, C0, n0 end
nl += 1
elseif A0 < 0 then
if nr == 0 then R1A, R1B, R1C, R1N = A0, B0, C0, n0 elseif nr == 1 then R2A, R2B, R2C, R2N = A0, B0, C0, n0
else R3A, R3B, R3C, R3N = A0, B0, C0, n0 end
nr += 1
elseif H1B == 0 then
H1B, H1C, H1t = B0, C0, tl0
else
H2B, H2C, H2t = B0, C0, tl0
end
if A1 > 0 then
if nl == 0 then L1A, L1B, L1C, L1N = A1, B1, C1, n1 elseif nl == 1 then L2A, L2B, L2C, L2N = A1, B1, C1, n1
else L3A, L3B, L3C, L3N = A1, B1, C1, n1 end
nl += 1
elseif A1 < 0 then
if nr == 0 then R1A, R1B, R1C, R1N = A1, B1, C1, n1 elseif nr == 1 then R2A, R2B, R2C, R2N = A1, B1, C1, n1
else R3A, R3B, R3C, R3N = A1, B1, C1, n1 end
nr += 1
elseif H1B == 0 then
H1B, H1C, H1t = B1, C1, tl1
else
H2B, H2C, H2t = B1, C1, tl1
end
if A2 > 0 then
if nl == 0 then L1A, L1B, L1C, L1N = A2, B2, C2, n2 elseif nl == 1 then L2A, L2B, L2C, L2N = A2, B2, C2, n2
else L3A, L3B, L3C, L3N = A2, B2, C2, n2 end
nl += 1
elseif A2 < 0 then
if nr == 0 then R1A, R1B, R1C, R1N = A2, B2, C2, n2 elseif nr == 1 then R2A, R2B, R2C, R2N = A2, B2, C2, n2
else R3A, R3B, R3C, R3N = A2, B2, C2, n2 end
nr += 1
elseif H1B == 0 then
H1B, H1C, H1t = B2, C2, tl2
else
H2B, H2C, H2t = B2, C2, tl2
end
if A3 > 0 then
if nl == 0 then L1A, L1B, L1C, L1N = A3, B3, C3, n3 elseif nl == 1 then L2A, L2B, L2C, L2N = A3, B3, C3, n3
else L3A, L3B, L3C, L3N = A3, B3, C3, n3 end
nl += 1
elseif A3 < 0 then
if nr == 0 then R1A, R1B, R1C, R1N = A3, B3, C3, n3 elseif nr == 1 then R2A, R2B, R2C, R2N = A3, B3, C3, n3
else R3A, R3B, R3C, R3N = A3, B3, C3, n3 end
nr += 1
elseif H1B == 0 then
H1B, H1C, H1t = B3, C3, tl3
else
H2B, H2C, H2t = B3, C3, tl3
end
if H1B ~= 0 then
while miny <= maxy do
local py = miny + 0.5
local e, e2 = H1B * py + H1C, H2B * py + H2C
if (e > 0 or (e == 0 and H1t)) and (e2 > 0 or (e2 == 0 and H2t)) then break end
miny += 1
end
while maxy > miny do
local py = maxy + 0.5
local e, e2 = H1B * py + H1C, H2B * py + H2C
if (e > 0 or (e == 0 and H1t)) and (e2 > 0 or (e2 == 0 and H2t)) then break end
maxy -= 1
end
end
for y = miny, maxy do for y = miny, maxy do
local py = y + 0.5 local py = y + 0.5
local xl, xr = minx, maxx local f1, f2, f3 = L1B * py + L1C, L2B * py + L2C, L3B * py + L3C
local e0, e1, e2, e3 = B0 * py + C0, B1 * py + C1, B2 * py + C2, B3 * py + C3 local g1, g2, g3 = R1B * py + R1C, R2B * py + R2C, R3B * py + R3C
if A0 > 0 then xl = max(xl, floor(e0 * n0 - 0.500001)) elseif A0 < 0 then xr = min(xr, ceil(e0 * n0 - 0.499999)) end local xl = max(minx, floor(f1 * L1N - 0.500001), floor(f2 * L2N - 0.500001), floor(f3 * L3N - 0.500001))
if A1 > 0 then xl = max(xl, floor(e1 * n1 - 0.500001)) elseif A1 < 0 then xr = min(xr, ceil(e1 * n1 - 0.499999)) end local xr = min(maxx, ceil(g1 * R1N - 0.499999), ceil(g2 * R2N - 0.499999), ceil(g3 * R3N - 0.499999))
if A2 > 0 then xl = max(xl, floor(e2 * n2 - 0.500001)) elseif A2 < 0 then xr = min(xr, ceil(e2 * n2 - 0.499999)) end
if A3 > 0 then xl = max(xl, floor(e3 * n3 - 0.500001)) elseif A3 < 0 then xr = min(xr, ceil(e3 * n3 - 0.499999)) end
if xl > minx and xl <= xr then xl += 1 end -- (an estimate is never in the span: see DrawTriangle) if xl > minx and xl <= xr then xl += 1 end -- (an estimate is never in the span: see DrawTriangle)
while xl <= xr do while xl <= xr do
local px = xl + 0.5 local px = xl + 0.5
local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 if L1A * px + f1 >= 0 and L2A * px + f2 >= 0 and L3A * px + f3 >= 0 then break end
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2))
and (w3 > 0 or (w3 == 0 and tl3)) then
break
end
xl += 1 xl += 1
end end
if xr < maxx and xr > xl then xr -= 1 end if xr < maxx and xr > xl then xr -= 1 end
while xr > xl do while xr >= xl do
local px = xr + 0.5 local px = xr + 0.5
local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3 if R1A * px + g1 > 0 and R2A * px + g2 > 0 and R3A * px + g3 > 0 then break end
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2))
and (w3 > 0 or (w3 == 0 and tl3)) then
break
end
xr -= 1 xr -= 1
end end
if xl > xr then continue end if xl > xr then continue end
@@ -931,35 +1380,30 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
tv = readu32(tbuf, (ty * tw + tx) * 4) tv = readu32(tbuf, (ty * tw + tx) * 4)
end end
if tv ~= last_tv then -- BlendPixel inlined (same math; an opaque texel over a colour gives fa = 1, fn = 0, k = 0: the same values
last_tv = tv -- as its opaque branch, so no branch on it: every unpredictable branch costs more than the math)
sa = rshift(tv, 24) * a255 local ta = rshift(tv, 24)
sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255 if ta > 0 then
s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 local sa = ta * a255
fa = sa / 255 local sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255
fn = 1 - fa local fa = sa / 255
fk = (1 - fa) / 255
end
-- BlendPixel inlined (same math)
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
elseif sa > 0 then
local d = readu32(dbuf, o) local d = readu32(dbuf, o)
if d < 16777216 then if d >= 4278190080 then
writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) local fn = 1 - fa
writeu32(dbuf, o, floor(sr * fa + band(d, 255) * fn + 0.5)
+ floor(sg * fa + band(rshift(d, 8), 255) * fn + 0.5) * 256
+ floor(sb * fa + band(rshift(d, 16), 255) * fn + 0.5) * 65536 + 4278190080)
elseif d < 16777216 then
writeu32(dbuf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536
+ floor(sa + 0.5) * 16777216)
else else
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then local k = rshift(d, 24) * ((1 - fa) / 255)
writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 local oa = fa + k
+ floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) local inv2 = 1 / oa
else writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5)
local k = rshift(d, 24) * fk + floor((sg * fa + dg * k) * inv2 + 0.5) * 256
local oa = fa + k + floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
local inv2 = 1 / oa
writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5)
+ floor((sg * fa + dg * k) * inv2 + 0.5) * 256
+ floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end end
end end
o += 4 o += 4
@@ -1058,7 +1502,8 @@ function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number)
end end
end end
-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd) -- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd), 5 flat
-- triangle pair (va vb vc + va vb vd)
@native @native
local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: number, tox: number, local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: number, tox: number,
toy: number, cx0: number, cy0: number, cx1: number, cy1: number) toy: number, cx0: number, cy0: number, cx1: number, cy1: number)
@@ -1068,6 +1513,9 @@ local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, v
elseif kind == 4 then elseif kind == 4 then
DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, t, cx0, cy0, cx1, cy1, tox, toy) DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, t, cx0, cy0, cx1, cy1, tox, toy)
return return
elseif kind == 5 then
DrawTriPair(TargetBuffer, vbuf, va, vb, vc, vd, t, cx0, cy0, cx1, cy1, tox, toy)
return
end end
local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox,
readf64(vbuf, vc + 8) - toy readf64(vbuf, vc + 8) - toy
+3
View File
@@ -26,6 +26,9 @@ there, but keep this port's existing data structures and conventions. Read the s
`repeat ... until true` with `break`, and an explicit flag when the loop itself must break out of the wrapper. `repeat ... until true` with `break`, and an explicit flag when the loop itself must break out of the wrapper.
- Luau has a limit of 200 locals per function and 255 upvalues; split huge functions (like demo sections) into - Luau has a limit of 200 locals per function and 255 upvalues; split huge functions (like demo sections) into
several local/global functions. several local/global functions.
- `@native` has a budget: all native code of one script must fit in one ~4 MB block, or Roblox compiles none of it
(every function of the bundle runs interpreted, silently). `tools/test/native_size.py --top 30` shows the bundle's
size and headroom (part of check_all.sh); put `@native` only on functions that run every frame.
## Portability (LÖVE build) ## Portability (LÖVE build)
- Library code must stay valid **Lua 5.1/LuaJIT syntax** apart from `@native` lines (stripped for LÖVE): no `+=`, `//`, - Library code must stay valid **Lua 5.1/LuaJIT syntax** apart from `@native` lines (stripped for LÖVE): no `+=`, `//`,
+5 -6
View File
@@ -4729,12 +4729,11 @@ function MT.ImDrawListSplitter:Merge(draw_list)
cmd_write = cmd_write + 1 cmd_write = cmd_write + 1
end end
end end
if ch._IdxBuffer.Size > 0 then local sz = ch._IdxBuffer.Size
local src_idx = ch._IdxBuffer.Data if sz > 0 then
for n = 1, ch._IdxBuffer.Size do -- [Luau] table.move() (C++ memcpy) instead of a per-index loop
dst_idx[idx_write] = src_idx[n] table.move(ch._IdxBuffer.Data, 1, sz, idx_write, dst_idx)
idx_write = idx_write + 1 idx_write = idx_write + sz
end
end end
end end
draw_list._IdxWritePtr = idx_write draw_list._IdxWritePtr = idx_write
+11 -1
View File
@@ -233,18 +233,24 @@ function ImLerp(a, b, t)
end end
--@hoist --@hoist
@native
local function _Trunc(val) if val >= 0 then return mathFloor(val) else return mathCeil(val) end end local function _Trunc(val) if val >= 0 then return mathFloor(val) else return mathCeil(val) end end
--- @overload fun(v: float): float --- @overload fun(v: float): float
--- @overload fun(v: ImVec2): ImVec2 --- @overload fun(v: ImVec2): ImVec2
--@hoist --@hoist
@native
function ImTrunc(v) function ImTrunc(v)
if type(v) == "number" then return _Trunc(v) if type(v) == "number" then return _Trunc(v)
elseif type(v) == "table" then return ImVec2(_Trunc(v.x), _Trunc(v.y)) elseif type(v) == "table" then return ImVec2(_Trunc(v.x), _Trunc(v.y))
end end
end end
ImTrunc64 = _Trunc -- [Luau] its own (hoisted) function instead of `ImTrunc64 = _Trunc`: calls get inlined (e.g. AddRect()) instead of calling
-- a separate function
--@hoist
@native
function ImTrunc64(val) if val >= 0 then return mathFloor(val) else return mathCeil(val) end end
-- Consider using the bit-hack version (search for "0x1p120f"). -- Consider using the bit-hack version (search for "0x1p120f").
--- @param f float --- @param f float
@@ -264,7 +270,11 @@ function ImIsTruncated(x) return x % 1 == 0 end -- (float)(int)x == x
-- Returns true if all parameters are whole numbers. -- Returns true if all parameters are whole numbers.
function ImIsTruncated4(x, y, z, w) return x % 1 == 0 and y % 1 == 0 and z % 1 == 0 and w % 1 == 0 end function ImIsTruncated4(x, y, z, w) return x % 1 == 0 and y % 1 == 0 and z % 1 == 0 and w % 1 == 0 end
--@hoist
@native
function IM_TRUNC(VAL) return math.floor(VAL) end -- Positive values only! function IM_TRUNC(VAL) return math.floor(VAL) end -- Positive values only!
--@hoist
@native
function IM_ROUND(VAL) return math.floor(VAL + 0.5) end -- Positive values only! function IM_ROUND(VAL) return math.floor(VAL + 0.5) end -- Positive values only!
--@hoist --@hoist
+3
View File
@@ -934,6 +934,7 @@ function ImGui.TableQueueSetColumnDisplayOrder(table_, column_n, dst_order)
end end
-- Adjust flags: default width mode + stretch columns are not allowed when auto extending -- Adjust flags: default width mode + stretch columns are not allowed when auto extending
@native
local function TableSetupColumnFlags(table_, column, column_n, flags_in) local function TableSetupColumnFlags(table_, column, column_n, flags_in)
local flags = flags_in local flags = flags_in
@@ -993,6 +994,7 @@ end
-- Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first. -- Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first.
-- FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns. -- FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns.
-- Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns? -- Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns?
@native
function ImGui.TableUpdateLayout(table_) function ImGui.TableUpdateLayout(table_)
local g = GImGui local g = GImGui
local temp_data = table_.TempData local temp_data = table_.TempData
@@ -2961,6 +2963,7 @@ end
-- - FreezeRows --> 2+D+N*2 (unless scrolling value is zero) -- - FreezeRows --> 2+D+N*2 (unless scrolling value is zero)
-- - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero) -- - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero)
-- Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0. -- Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0.
@native
function ImGui.TableSetupDrawChannels(table_) function ImGui.TableSetupDrawChannels(table_)
local freeze_row_multiplier = (table_.FreezeRowsCount > 0) and 2 or 1 local freeze_row_multiplier = (table_.FreezeRowsCount > 0) and 2 or 1
local channels_for_row = (band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0) and 1 or table_.ColumnsEnabledCount local channels_for_row = (band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0) and 1 or table_.ColumnsEnabledCount
-27
View File
@@ -373,7 +373,6 @@ end
--- @param bounds bool --- @param bounds bool
--- @return stbtt__csctx --- @return stbtt__csctx
--- @nodiscard --- @nodiscard
@native
local function STBTT__CSCTX_INIT(bounds) local function STBTT__CSCTX_INIT(bounds)
local this = stbtt__csctx() local this = stbtt__csctx()
@@ -580,7 +579,6 @@ local function stbtt__buf_range(b, o, s)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__cff_get_index(b) local function stbtt__cff_get_index(b)
local count, start, offsize local count, start, offsize
start = b.cursor start = b.cursor
@@ -595,7 +593,6 @@ local function stbtt__cff_get_index(b)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__cff_int(b) local function stbtt__cff_int(b)
local b0 = stbtt__buf_get8(b) local b0 = stbtt__buf_get8(b)
if b0 >= 32 and b0 <= 246 then return b0 - 139 if b0 >= 32 and b0 <= 246 then return b0 - 139
@@ -609,7 +606,6 @@ local function stbtt__cff_int(b)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__cff_skip_operand(b) local function stbtt__cff_skip_operand(b)
local v local v
local b0 = stbtt__buf_peek8(b) local b0 = stbtt__buf_peek8(b)
@@ -631,7 +627,6 @@ end
--- @param key int --- @param key int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__dict_get(b, key) local function stbtt__dict_get(b, key)
stbtt__buf_seek(b, 0) stbtt__buf_seek(b, 0)
while b.cursor < b.size do while b.cursor < b.size do
@@ -653,7 +648,6 @@ end
--- @param outcount int --- @param outcount int
--- @return int[] --- @return int[]
--- @nodiscard --- @nodiscard
@native
local function stbtt__dict_get_ints(b, key, outcount) local function stbtt__dict_get_ints(b, key, outcount)
local operands = stbtt__dict_get(b, key) local operands = stbtt__dict_get(b, key)
local out = {} local out = {}
@@ -665,7 +659,6 @@ local function stbtt__dict_get_ints(b, key, outcount)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__cff_index_count(b) local function stbtt__cff_index_count(b)
stbtt__buf_seek(b, 0) stbtt__buf_seek(b, 0)
return stbtt__buf_get16(b) return stbtt__buf_get16(b)
@@ -675,7 +668,6 @@ end
--- @param i int --- @param i int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__cff_index_get(b, i) local function stbtt__cff_index_get(b, i)
local count, offsize, start, _end local count, offsize, start, _end
stbtt__buf_seek(b, 0) stbtt__buf_seek(b, 0)
@@ -738,7 +730,6 @@ local function stbtt_tag4(p, c0, c1, c2, c3, offset) offset = offset or 0; retur
@native @native
local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end
@native
local function stbtt__isfont(font) local function stbtt__isfont(font)
-- check the version number -- check the version number
if stbtt_tag4(font, 49, 0, 0, 0) then return true end -- TrueType 1 if stbtt_tag4(font, 49, 0, 0, 0) then return true end -- TrueType 1
@@ -750,7 +741,6 @@ local function stbtt__isfont(font)
end end
-- @OPTIMIZE: binary search -- @OPTIMIZE: binary search
@native
local function stbtt__find_table(data, font_start, tag) local function stbtt__find_table(data, font_start, tag)
local num_tables = ttUSHORT(data, font_start + 4) local num_tables = ttUSHORT(data, font_start + 4)
local tabledir = font_start + 12 local tabledir = font_start + 12
@@ -763,7 +753,6 @@ local function stbtt__find_table(data, font_start, tag)
return 0 return 0
end end
@native
local function stbtt_GetFontOffsetForIndex_internal(font_collection, index) local function stbtt_GetFontOffsetForIndex_internal(font_collection, index)
-- if it's just a font, there's only one valid index -- if it's just a font, there's only one valid index
if stbtt__isfont(font_collection) then if stbtt__isfont(font_collection) then
@@ -787,7 +776,6 @@ end
--- @param cff stbtt__buf --- @param cff stbtt__buf
--- @param fontdict stbtt__buf --- @param fontdict stbtt__buf
@native
local function stbtt__get_subrs(cff, fontdict) local function stbtt__get_subrs(cff, fontdict)
local private_loc = stbtt__dict_get_ints(fontdict, 18, 2) local private_loc = stbtt__dict_get_ints(fontdict, 18, 2)
if (private_loc[2] == 0 or private_loc[1] == 0) then if (private_loc[2] == 0 or private_loc[1] == 0) then
@@ -803,7 +791,6 @@ local function stbtt__get_subrs(cff, fontdict)
end end
--- @return bool --- @return bool
@native
local function stbtt_InitFont_internal(info, data, fontstart) local function stbtt_InitFont_internal(info, data, fontstart)
local cmap local cmap
local numTables local numTables
@@ -1379,7 +1366,6 @@ end
--- @param c stbtt__csctx --- @param c stbtt__csctx
--- @param x stbtt_int32 --- @param x stbtt_int32
--- @param y stbtt_int32 --- @param y stbtt_int32
@native
local function stbtt__track_vertex(c, x, y) local function stbtt__track_vertex(c, x, y)
if x > c.max_x or not c.started then c.max_x = x end if x > c.max_x or not c.started then c.max_x = x end
if y > c.max_y or not c.started then c.max_y = y end if y > c.max_y or not c.started then c.max_y = y end
@@ -1396,7 +1382,6 @@ end
--- @param cy stbtt_int32 --- @param cy stbtt_int32
--- @param cx1 stbtt_int32 --- @param cx1 stbtt_int32
--- @param cy1 stbtt_int32 --- @param cy1 stbtt_int32
@native
local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1) local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1)
if c.bounds then if c.bounds then
stbtt__track_vertex(c, x, y) stbtt__track_vertex(c, x, y)
@@ -1412,7 +1397,6 @@ local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1)
end end
--- @param ctx stbtt__csctx --- @param ctx stbtt__csctx
@native
local function stbtt__csctx_close_shape(ctx) local function stbtt__csctx_close_shape(ctx)
if ctx.first_x ~= ctx.x or ctx.first_y ~= ctx.y then if ctx.first_x ~= ctx.x or ctx.first_y ~= ctx.y then
stbtt__csctx_v(ctx, STBTT_VTX.LINE, trunc(ctx.first_x), trunc(ctx.first_y), 0, 0, 0, 0) stbtt__csctx_v(ctx, STBTT_VTX.LINE, trunc(ctx.first_x), trunc(ctx.first_y), 0, 0, 0, 0)
@@ -1422,7 +1406,6 @@ end
--- @param ctx stbtt__csctx --- @param ctx stbtt__csctx
--- @param dx float --- @param dx float
--- @param dy float --- @param dy float
@native
local function stbtt__csctx_rmove_to(ctx, dx, dy) local function stbtt__csctx_rmove_to(ctx, dx, dy)
stbtt__csctx_close_shape(ctx) stbtt__csctx_close_shape(ctx)
ctx.x = ctx.x + dx ctx.x = ctx.x + dx
@@ -1435,7 +1418,6 @@ end
--- @param ctx stbtt__csctx --- @param ctx stbtt__csctx
--- @param dx float --- @param dx float
--- @param dy float --- @param dy float
@native
local function stbtt__csctx_rline_to(ctx, dx, dy) local function stbtt__csctx_rline_to(ctx, dx, dy)
ctx.x = ctx.x + dx ctx.x = ctx.x + dx
ctx.y = ctx.y + dy ctx.y = ctx.y + dy
@@ -1449,7 +1431,6 @@ end
--- @param dy2 float --- @param dy2 float
--- @param dx3 float --- @param dx3 float
--- @param dy3 float --- @param dy3 float
@native
local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3) local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3)
local cx1 = ctx.x + dx1 local cx1 = ctx.x + dx1
local cy1 = ctx.y + dy1 local cy1 = ctx.y + dy1
@@ -1460,7 +1441,6 @@ local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3)
stbtt__csctx_v(ctx, STBTT_VTX.CUBIC, trunc(ctx.x), trunc(ctx.y), trunc(cx1), trunc(cy1), trunc(cx2), trunc(cy2)) stbtt__csctx_v(ctx, STBTT_VTX.CUBIC, trunc(ctx.x), trunc(ctx.y), trunc(cx1), trunc(cy1), trunc(cx2), trunc(cy2))
end end
@native
local function stbtt__get_subr(idx, n) local function stbtt__get_subr(idx, n)
local count = stbtt__cff_index_count(idx) local count = stbtt__cff_index_count(idx)
local bias = 107 local bias = 107
@@ -1476,7 +1456,6 @@ local function stbtt__get_subr(idx, n)
return stbtt__cff_index_get(idx, n) return stbtt__cff_index_get(idx, n)
end end
@native
local function stbtt__cid_get_glyph_subrs(info, glyph_index) local function stbtt__cid_get_glyph_subrs(info, glyph_index)
local fdselect = info.fdselect local fdselect = info.fdselect
local fdselector = -1 local fdselector = -1
@@ -1507,7 +1486,6 @@ end
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param glyph_index int --- @param glyph_index int
--- @param c stbtt__csctx --- @param c stbtt__csctx
@native
local function stbtt__run_charstring(info, glyph_index, c) local function stbtt__run_charstring(info, glyph_index, c)
local in_header = true local in_header = true
local maskbits = 0 local maskbits = 0
@@ -1781,7 +1759,6 @@ end
--- @param glyph_index int --- @param glyph_index int
--- @return int num_vertices --- @return int num_vertices
--- @return stbtt_vertex[]? vertices --- @return stbtt_vertex[]? vertices
@native
function stbtt__GetGlyphShapeT2(info, glyph_index) function stbtt__GetGlyphShapeT2(info, glyph_index)
-- runs the charstring twice, once to count and once to output (to avoid realloc) -- runs the charstring twice, once to count and once to output (to avoid realloc)
local vertices = nil local vertices = nil
@@ -1807,7 +1784,6 @@ end
--- @return int y0 --- @return int y0
--- @return int x1 --- @return int x1
--- @return int y1 --- @return int y1
@native
function stbtt__GetGlyphInfoT2(info, glyph_index) function stbtt__GetGlyphInfoT2(info, glyph_index)
local c = STBTT__CSCTX_INIT(true) local c = STBTT__CSCTX_INIT(true)
local r = stbtt__run_charstring(info, glyph_index, c) local r = stbtt__run_charstring(info, glyph_index, c)
@@ -2568,7 +2544,6 @@ end
--- @param objspace_flatness_squared float --- @param objspace_flatness_squared float
--- @param n int --- @param n int
--- @return int num_points # updated num_points passed in --- @return int num_points # updated num_points passed in
@native
local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n) local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n)
-- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough -- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
local dx0 = x1 - x0 local dx0 = x1 - x0
@@ -2929,7 +2904,6 @@ end
-- return '0' for index 0, and -1 for all other indices. -- return '0' for index 0, and -1 for all other indices.
--- @param data table --- @param data table
--- @param index int --- @param index int
@native
function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end
-- Given an offset into the file that defines a font, this function builds -- Given an offset into the file that defines a font, this function builds
@@ -2940,7 +2914,6 @@ function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForI
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param data table --- @param data table
--- @param offset int --- @param offset int
@native
function stbtt_InitFont(info, data, offset) return stbtt_InitFont_internal(info, data, offset) end function stbtt_InitFont(info, data, offset) return stbtt_InitFont_internal(info, data, offset) end
return { return {
+5 -4
View File
@@ -44,9 +44,10 @@ if "--target" in sys.argv:
i = sys.argv.index("--target"); LOVE = sys.argv[i + 1] == "love"; del sys.argv[i:i + 2] i = sys.argv.index("--target"); LOVE = sys.argv[i + 1] == "love"; del sys.argv[i:i + 2]
sys.argv = [a for a in sys.argv if a != "--no-demo"] sys.argv = [a for a in sys.argv if a != "--no-demo"]
OPT = {x: os.environ.get("IMGUI_BUNDLE_NOOPT") != "1" and os.environ.get("IMGUI_BUNDLE_NO_" + x) != "1" for x in "ABCEL"} OPT = {x: os.environ.get("IMGUI_BUNDLE_NOOPT") != "1" and os.environ.get("IMGUI_BUNDLE_NO_" + x) != "1" for x in "ABCEL"}
# A limits: Luau 200 locals in the main chunk (+ helpers, __FILES, ...), 200 upvalues per function; LuaJIT 60 upvalues # A limits: Luau 200 locals in the main chunk (A's hot globals + C's hoisted functions <= MAX_LOCALS, + helpers, __FILES,
# per function (margin left for nested functions that also capture file locals) # ...), 200 upvalues per function; LuaJIT 60 upvalues per function (margin left for nested functions that also capture
MAX_LOCALS, MAX_UPVALUES = 160, (45 if LOVE else 150) # file locals)
MAX_LOCALS, MAX_UPVALUES = 169, (45 if LOVE else 150)
TARGET = "love" if LOVE else "roblox" TARGET = "love" if LOVE else "roblox"
BACKEND = "imgui_impl_%s.lua" % TARGET BACKEND = "imgui_impl_%s.lua" % TARGET
BACKEND_DIR = os.path.join(ROOT, "backends", TARGET) # every *.lua in it is bundled (*.luau, e.g. the worker, is not) BACKEND_DIR = os.path.join(ROOT, "backends", TARGET) # every *.lua in it is bundled (*.luau, e.g. the worker, is not)
@@ -281,7 +282,7 @@ if OPT["A"]:
used = list(used.values()) used = list(used.values())
taken = [len(u & set(hoisted_names + re.findall(r"\w+", HOIST_DEPS.split("=")[0]))) for u in used] taken = [len(u & set(hoisted_names + re.findall(r"\w+", HOIST_DEPS.split("=")[0]))) for u in used]
for n in sorted((n for n in count if n not in hoisted_names), key=lambda n: (-count[n], n)): for n in sorted((n for n in count if n not in hoisted_names), key=lambda n: (-count[n], n)):
if len(hot) == MAX_LOCALS: break if len(hot) + len(hoisted_names) >= MAX_LOCALS: break
if all(taken[i] < MAX_UPVALUES for i, u in enumerate(used) if n in u): if all(taken[i] < MAX_UPVALUES for i, u in enumerate(used) if n in u):
hot.append(n) hot.append(n)
taken = [c + (n in u) for c, u in zip(taken, used)] taken = [c + (n in u) for c, u in zip(taken, used)]
+3
View File
@@ -41,6 +41,8 @@ CHECKS=(
"pixels|PIXELS SAME|a=\$($R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo PIXELS SAME" "pixels|PIXELS SAME|a=\$($R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_pixels.luau --frames 600 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo PIXELS SAME"
"move_pixels|MOVEPIX SAME|a=\$($R --main tools/test/scripts/t_move_pixels.luau --frames 245 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_move_pixels.luau --frames 245 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo MOVEPIX SAME" "move_pixels|MOVEPIX SAME|a=\$($R --main tools/test/scripts/t_move_pixels.luau --frames 245 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_move_pixels.luau --frames 245 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo MOVEPIX SAME"
"scene_pixels|SCENEPIX SAME|M='--module BenchScenes=tools/test/bench_scenes.luau'; [ -f extensions/implot-luau/ImPlot.lua ] && M=\"\$M --module ImPlot=extensions/implot-luau/ImPlot.lua\"; a=\$($R --main tools/test/scripts/t_scene_pixels.luau --frames 170 \$M | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_scene_pixels.luau --frames 170 \$M | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo SCENEPIX SAME" "scene_pixels|SCENEPIX SAME|M='--module BenchScenes=tools/test/bench_scenes.luau'; [ -f extensions/implot-luau/ImPlot.lua ] && M=\"\$M --module ImPlot=extensions/implot-luau/ImPlot.lua\"; a=\$($R --main tools/test/scripts/t_scene_pixels.luau --frames 170 \$M | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_scene_pixels.luau --frames 170 \$M | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo SCENEPIX SAME"
"scroll_pixels|SCROLLPIX SAME|a=\$($R --main tools/test/scripts/t_scroll_pixels.luau --frames 212 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_scroll_pixels.luau --frames 212 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo SCROLLPIX SAME"
"recolor_pixels|RECOLORPIX SAME|a=\$($R --main tools/test/scripts/t_recolor_pixels.luau --frames 140 | grep -P '^PIX\t'); b=\$(RUN_FLAGS=ARG_FORCE=true $R --main tools/test/scripts/t_recolor_pixels.luau --frames 140 | grep -P '^PIX\t'); [ -n \"\$a\" ] && [ \"\$a\" = \"\$b\" ] && echo RECOLORPIX SAME"
"rect_flip|RECTFLIP OK|$R --main tools/test/scripts/t_rect_flip.luau --frames 30" "rect_flip|RECTFLIP OK|$R --main tools/test/scripts/t_rect_flip.luau --frames 30"
"tile_bound|TILEBOUND OK|$R --main tools/test/scripts/t_tile_bound.luau --frames 200" "tile_bound|TILEBOUND OK|$R --main tools/test/scripts/t_tile_bound.luau --frames 200"
"parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 620" "parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 620"
@@ -48,6 +50,7 @@ CHECKS=(
"assets_scroll|ASSETS OK|$R --main tools/test/scripts/t_assets_scroll.luau --frames 1010" "assets_scroll|ASSETS OK|$R --main tools/test/scripts/t_assets_scroll.luau --frames 1010"
"shot|wrote|python3 tools/test/shot.py /tmp/imgui_shot.png --app" "shot|wrote|python3 tools/test/shot.py /tmp/imgui_shot.png --app"
"registers|REGS OK|mkdir -p $T/regs && python3 tools/bundle.py $T/regs >/dev/null && h=\"\$(printf 'local _h%d = {} ' \$(seq 20))\" && grep -q \"^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$\" $T/regs/ImGui.luau && for f in $T/regs/*.luau; do { echo \"\$h\"; sed \"/^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$/a \$h\" \$f; } > \$f.h && luau-compile -O0 --null \$f.h || exit 1; done && ! grep -q require $T/regs/ImGuiWorker.client.luau && echo REGS OK" "registers|REGS OK|mkdir -p $T/regs && python3 tools/bundle.py $T/regs >/dev/null && h=\"\$(printf 'local _h%d = {} ' \$(seq 20))\" && grep -q \"^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$\" $T/regs/ImGui.luau && for f in $T/regs/*.luau; do { echo \"\$h\"; sed \"/^__FILES\\['imgui_impl_roblox.lua'\\] = function()\$/a \$h\" \$f; } > \$f.h && luau-compile -O0 --null \$f.h || exit 1; done && ! grep -q require $T/regs/ImGuiWorker.client.luau && echo REGS OK"
"native|NATIVE OK|python3 tools/test/native_size.py"
"love|DRAWHASH|python3 tools/bundle.py --target love >/dev/null && luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic && luajit tools/test/love/t_examples.lua" "love|DRAWHASH|python3 tools/bundle.py --target love >/dev/null && luajit tools/test/love/t_drawhash.lua 60 Widgets,Basic && luajit tools/test/love/t_examples.lua"
) )
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Native code size of the Roblox bundle (and the worker), per ModuleScript, per source file and per function.
python3 tools/test/native_size.py # bundles to a temp dir, measures ImGui.luau + ImGuiWorker.client.luau
python3 tools/test/native_size.py --top 40 # also the 40 largest @native functions (with source file:line)
python3 tools/test/native_size.py a.luau ... # measure given files (e.g. an extension: ImPlot.lua)
Why: Roblox compiles each script's @native functions together into ONE allocation that must fit in one 4 MB block
of executable memory (Luau CodeGen's CodeAllocator, LuauCodeGenBlockSize). A module whose native code is bigger gets
NO native code at all, silently: every @native function of it runs interpreted (Studio: render 4-9x slower). Measured
in Studio (probe bundles, Oct 2026): native up to 4,083,418 bytes, interpreted from 4,103,258 bytes (sizes as reported
by luau-compile 0.738 --codegennull -O2 for x64). The Luau CLI fails a little later (~4.18 MB), and `run.py` puts the
bundle, the main script and every --module into one chunk, so headless runs with ImPlot hit it ~0.5 MB earlier.
Prints NATIVE OK when every module is under BUDGET (margin for compiler version drift), NATIVE OVER otherwise."""
import argparse, glob, json, os, shutil, subprocess, sys, tempfile, collections
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
STUDIO_LIMIT = 4083418 # largest module measured native in Studio (next probe, 4,103,258, ran interpreted)
BUDGET = 3900000 # NATIVE OVER above this (~180 KB margin below the Studio limit)
LC = shutil.which("luau-compile") or (sorted(glob.glob("/nix/store/*-luau-*/bin/luau-compile")) or ["luau-compile"])[-1]
def measure(path):
stats = tempfile.mktemp(suffix=".json")
subprocess.run([LC, "--codegennull", "-O2", "--record-stats=function", "--stats-file=" + stats, path],
check=True, stdout=subprocess.DEVNULL)
d = json.load(open(stats)); os.remove(stats)
d = next(iter(d.values())) if "codegen" not in d else d
return d["codegen"], d["lowerStats"]["functions"]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("files", nargs="*")
ap.add_argument("--top", type=int, default=0)
a = ap.parse_args()
files = a.files
if not files:
out = tempfile.mkdtemp(prefix="imgui_native_")
subprocess.run([sys.executable, os.path.join(ROOT, "tools", "bundle.py"), out], check=True, stdout=subprocess.DEVNULL)
files = [os.path.join(out, "ImGui.luau"), os.path.join(out, "ImGuiWorker.client.luau")]
ok = True
for path in files:
total, fns = measure(path)
lmp = os.path.join(os.path.dirname(path), "ImGui.linemap.json")
lm = json.load(open(lmp)) if os.path.basename(path) == "ImGui.luau" and os.path.exists(lmp) else []
def loc(n):
best = None
for start, name in lm:
if start <= n: best = (start, name)
return (best[1], n - best[0] + 1) if best else (os.path.basename(path), n)
over = total > BUDGET
ok = ok and not over
print("%s: %d bytes native (%d functions), %.0f%% of the Studio module limit, %d KB headroom%s" % (
os.path.basename(path), total, len(fns), 100 * total / STUDIO_LIMIT, (STUDIO_LIMIT - total) // 1024,
" OVER BUDGET" if over else ""))
if lm:
byfile = collections.Counter()
for f in fns: byfile[loc(f["line"])[0]] += f["asmSize"]
for name, size in byfile.most_common(): print(" %8.1f KB %s" % (size / 1024, name))
for f in sorted(fns, key=lambda f: -f["asmSize"])[:a.top]:
print(" %8.1f KB %-40s %s:%d" % ((f["asmSize"] / 1024, f["name"] or "?") + loc(f["line"])))
print("NATIVE OK" if ok else "NATIVE OVER")
sys.exit(0 if ok else 1)
main()
+2 -1
View File
@@ -2,7 +2,8 @@
# Summarise profile.out from `run.py --profile`: top functions by self and inclusive samples, mapped to source file lines # Summarise profile.out from `run.py --profile`: top functions by self and inclusive samples, mapped to source file lines
import collections, json, os, re, sys, glob import collections, json, os, re, sys, glob
path = sys.argv[1] if len(sys.argv) > 1 else "profile.out" path = sys.argv[1] if len(sys.argv) > 1 else "profile.out"
tmp = max(glob.glob("/tmp/imgui_test_*/ImGui.linemap.json"), key=os.path.getmtime) import tempfile # run.py uses tempfile.mkdtemp, i.e. $TMPDIR (not always /tmp)
tmp = max(glob.glob(os.path.join(tempfile.gettempdir(), "imgui_test_*/ImGui.linemap.json")) + glob.glob("/tmp/imgui_test_*/ImGui.linemap.json"), key=os.path.getmtime)
lm = json.load(open(tmp)) lm = json.load(open(tmp))
def loc(n): def loc(n):
if not n.isdigit(): return "C" if not n.isdigit(): return "C"
+145
View File
@@ -0,0 +1,145 @@
-- Pixel oracle for the "recolored" path (CompareDrawList 4 + PatchDrawList recolor: same vertex positions, a few
-- vertices' colour / uv changed, e.g. hover): animated style colours on buttons, text, frames, a colour button, a
-- scrolled child, a wide button over several tiles and AddRectFilledMultiColor cycling flat <-> gradient (kind changes
-- fall back to the full path), between still frames, structure changes, hover, a colour picker (too many changed
-- vertices) and a tile limit (deferred tiles). Composites the ScreenGui every few frames and prints "PIX <frame> <hash>".
-- Run with RUN_FLAGS="ARG_FORCE=true" for a full redraw every frame: incremental output must match it exactly (also with
-- ARG_PAR=true: the parallel executor).
-- python3 tools/test/run.py --main tools/test/scripts/t_recolor_pixels.luau --frames 140 --quiet --roblox
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
ImGui.CreateContext()
G.ImGui_ImplRoblox.Init()
G.ImGui_ImplRoblox.SetRenderRate(0)
if ARG_PAR then G.ImGui_ImplRoblox.EnableParallel({ Sync = true, Actors = 4 }) end
local io = ImGui.GetIO()
local Col = G.ImGuiCol
local W, H = 1280, 760
local SW, SH = 720, 560 -- composited area (the windows are inside it)
local hsv = ImVec4(0.4, 0.7, 0.2, 1)
local function composite(gui)
local screen = buffer.create(SW * SH * 3)
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
local kids = inst:GetChildren()
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end)
for _, c in ipairs(kids) do
if c.Visible ~= false then
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
if c.ClipsDescendants then
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
end
if c.ClassName == "ImageLabel" then
local img = c.ImageContent.Object
local px, sz = img.Pixels, img.Size.X
for ty = 0, sz - 1 do
local sy = y + ty
if sy >= cy0 and sy < cy1 then
for tx = 0, sz - 1 do
local sx = x + tx
if sx >= cx0 and sx < cx1 then
local o = (ty * sz + tx) * 4
local a = buffer.readu8(px, o + 3)
if a > 0 then
local d = (sy * SW + sx) * 3
local fa = a / 255
for ch = 0, 2 do
local v = buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa)
buffer.writeu8(screen, d + ch, math.floor(v + 0.5))
end
end
end
end
end
end
end
walk(c, x, y, cx0, cy0, cx1, cy1)
end
end
end
walk(gui, 0, 0, 0, 0, SW, SH)
local h = 0
for i = 0, SW * SH * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end
return h
end
-- phases: name, frames
local PHASES = { { "recolor", 24 }, { "still", 6 }, { "grow", 8 }, { "recolor", 16 }, { "hover", 24 },
{ "picker", 10 }, { "limit", 30 }, { "recolor", 12 }, { "still", 6 } }
local frame, pi, pf, extra, t = 0, 1, 0, 0, 0
game:GetService("RunService").Stepped:Connect(function()
local ph = PHASES[pi]
if not ph then return end
frame += 1
pf += 1
local name = ph[1]
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(1200, 740)
io.BackendPlatformUserData.TileLimit = name == "limit" and 2 or nil
if name == "recolor" or name == "limit" then t += 1 end
if name == "grow" and pf % 3 == 0 then extra += 1 end
if name == "hover" then io:AddMousePosEvent(50 + (pf * 37) % 420, 60 + (pf * 29) % 300) end
if name == "picker" then hsv.x = (hsv.x + 0.03) % 1 end
ImGui.NewFrame()
local c1 = ImVec4(0.5 + 0.5 * math.sin(t * 0.3), 0.4, 0.5 + 0.5 * math.cos(t * 0.2), 1)
local c2 = ImVec4(0.2, 0.5 + 0.5 * math.sin(t * 0.25), 0.3, 0.6 + 0.4 * math.cos(t * 0.4))
ImGui.SetNextWindowPos(ImVec2(20, 20), G.ImGuiCond.Always)
ImGui.SetNextWindowSize(ImVec2(470, 520), G.ImGuiCond.Always)
ImGui.Begin("Recolor")
ImGui.PushStyleColor(Col.Button, c1)
ImGui.PushStyleColor(Col.FrameBg, c2)
for i = 1, 6 do
ImGui.Button("Button " .. i)
if i % 3 ~= 0 then ImGui.SameLine() end
end
ImGui.Button("A wide button over several tiles", ImVec2(400, 40))
ImGui.PopStyleColor(2)
ImGui.TextColored(c1, "Coloured text %d", 7)
ImGui.ColorButton("##cb", c2)
ImGui.SameLine()
local dl = ImGui.GetWindowDrawList()
local p = ImGui.GetCursorScreenPos()
-- flat (t % 8 < 2), horizontal / vertical gradient otherwise: kind changes take the full path
local u1 = ImGui.GetColorU32(c1)
local u2 = (t % 8 < 2) and u1 or ImGui.GetColorU32(c2)
if t % 16 < 8 then
dl:AddRectFilledMultiColor(p, ImVec2(p.x + 140, p.y + 30), u1, u2, u2, u1)
else
dl:AddRectFilledMultiColor(p, ImVec2(p.x + 140, p.y + 30), u1, u1, u2, u2)
end
ImGui.Dummy(ImVec2(140, 30))
for i = 1, extra do ImGui.Text("Extra line %d", i) end
ImGui.BeginChild("scrolled", ImVec2(0, 200), G.ImGuiChildFlags.Borders)
ImGui.SetScrollY(37)
ImGui.PushStyleColor(Col.Text, c1)
for i = 1, 20 do ImGui.Text("Child line %d", i) end
ImGui.PopStyleColor()
ImGui.PushStyleColor(Col.Button, c2)
ImGui.Button("Child button")
ImGui.PopStyleColor()
ImGui.EndChild()
_ = ImGui.Checkbox("Check", true)
ImGui.End()
if name == "picker" or pi > 6 then
ImGui.SetNextWindowPos(ImVec2(500, 20), G.ImGuiCond.Always)
ImGui.SetNextWindowSize(ImVec2(210, 300), G.ImGuiCond.Always)
ImGui.Begin("Picker")
ImGui.ColorPicker4("##p", hsv, G.ImGuiColorEditFlags.PickerHueBar)
ImGui.End()
end
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if ARG_PAR then G.ImGui_ImplRoblox.FinishParallel() end
-- (checkpoints: exact as long as no tile is deferred, i.e. not during "limit"; the frame after it redraws them)
if name ~= "limit" and (frame % 3 == 0 or pf == ph[2]) then
print("PIX", name, frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
end
if pf == ph[2] then
pi += 1
pf = 0
if not PHASES[pi] then print("RECOLORPIX DONE") end
end
end)
+99
View File
@@ -0,0 +1,99 @@
-- Scroll / resize pixel oracle (like t_pixels): the bench's stress window (buttons + sliders, a 60 x 6 table with row
-- backgrounds and borders, wrapped text) scrolls by 6 px a frame (down, then up), resizes from the bottom-right, then
-- from the top-left, "PIX <frame> <hash>" every 3 frames. Rows entering / leaving tiles and items shifting by one in a
-- tile's primitive list exercise DirtyRects' list diff. Run with RUN_FLAGS="ARG_FORCE=true" for a full redraw every
-- frame: incremental output must match it exactly.
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
local ImGui, ImVec2 = G.ImGui, G.ImVec2
ImGui.CreateContext()
G.ImGui_ImplRoblox.Init()
G.ImGui_ImplRoblox.SetRenderRate(0)
if ARG_TILELIMIT then ImGui.GetIO().BackendPlatformUserData.TileLimit = ARG_TILELIMIT end
local io = ImGui.GetIO()
local W, H = 1280, 760
local function composite(gui)
local screen = buffer.create(W * H * 3)
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
local kids = inst:GetChildren()
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end)
for _, c in ipairs(kids) do
if c.Visible ~= false then
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
if c.ClipsDescendants then
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
end
if c.ClassName == "ImageLabel" then
local img = c.ImageContent.Object
local px, sz = img.Pixels, img.Size.X
for ty = 0, sz - 1 do
local sy = y + ty
if sy >= cy0 and sy < cy1 then
for tx = 0, sz - 1 do
local sx = x + tx
if sx >= cx0 and sx < cx1 then
local o = (ty * sz + tx) * 4
local a = buffer.readu8(px, o + 3)
if a > 0 then
local d = (sy * W + sx) * 3
local fa = a / 255
for ch = 0, 2 do
local v = buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa)
buffer.writeu8(screen, d + ch, math.floor(v + 0.5))
end
end
end
end
end
end
end
walk(c, x, y, cx0, cy0, cx1, cy1)
end
end
end
walk(gui, 0, 0, 0, 0, W, H)
local h = 0
for i = 0, W * H * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end
return h
end
local frame = 0
local pos, size, scroll, slider, check = ImVec2(60, 40), ImVec2(520, 640), 0, 0.5, true
local LAST = 210
game:GetService("RunService").Stepped:Connect(function()
frame += 1
if frame > LAST then return end
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(1200, 740)
if frame > 4 and frame <= 60 then scroll += 6
elseif frame > 60 and frame <= 100 then scroll -= 7
elseif frame > 100 and frame <= 150 then size = ImVec2(size.x + 3, size.y - 2)
elseif frame > 150 and frame <= 200 then pos, size = ImVec2(pos.x + 2, pos.y + 2), ImVec2(size.x - 2, size.y - 2) end
ImGui.NewFrame()
ImGui.SetNextWindowPos(pos, G.ImGuiCond.Always); ImGui.SetNextWindowSize(size, G.ImGuiCond.Always)
ImGui.Begin("Stress")
ImGui.SetScrollY(scroll)
for i = 1, 20 do
ImGui.Button("Button " .. i); ImGui.SameLine()
slider = ImGui.SliderFloat("##s" .. i, slider, 0, 1)
end
_, check = ImGui.Checkbox("Checkbox", check)
if ImGui.BeginTable("tbl", 6, bit32.bor(G.ImGuiTableFlags.Borders, G.ImGuiTableFlags.RowBg)) then
for r = 1, 60 do
ImGui.TableNextRow()
for c = 1, 6 do ImGui.TableNextColumn(); ImGui.Text("r%d c%d", r, c) end
end
ImGui.EndTable()
end
for i = 1, 40 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog, again and again.", i) end
ImGui.End()
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if frame % 3 == 0 then
print("PIX", frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
end
if frame == LAST then print("SCROLLPIX DONE") end
end)
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "4dbug/imgui-luau" name = "4dbug/imgui-luau"
version = "0.4.3" version = "0.4.4"
registry = "https://github.com/UpliftGames/wally-index" registry = "https://github.com/UpliftGames/wally-index"
realm = "shared" realm = "shared"
license = "MIT" license = "MIT"