49 Commits
Author SHA1 Message Date
4DBug 23e31fcf3c 0.4.3
Build & Release / build (push) Canceled after 0s
Performance update (Roblox), no API changes; draw data and pixels identical to 0.4.2.
- Unchanged check: CompareDrawList reads vertices as f64 + col (3x fewer reads), moved lists shift their snapshot in place
- Collect/hash ~40% cheaper per changed draw list; DirtyRects without copies, skips unchanged prims at the same position
- Raster straight into the upload buffer (no CopySubRect; Upload -80..90%), uniform row intervals, faster glyph blits, pending damage rect, two-pixel span writes, inlined blends in gradient/interpolating triangles, tall flat triangles as spans
- Tiles: no 64 KB CPU buffer per tile, 4 prewarmed tiles in the free list; atlas record buffers reused on repack
- Fix: windows moved by whole pixels could keep stale pixels where trig-generated vertices drift by 1 ulp (t_move_pixels)
- Library: @native on hot helpers, fewer temporaries (Begin, widgets, tables, PlotEx, colour checkerboard), pooled ImDrawCmd / style / group stack entries (55 -> 31 KB/frame on the bench scene); faster glyph baking (repack O(n), vertical-edge fast path)
- backends/roblox/patches.lua: Luau-tuned RenderText/AddText/text-size cache hit (Roblox only)
- bundle.py optimization L: library-internal ImGui.Foo calls become locals (Roblox; hookable deny-list: Begin, End, TreeNode*, CollapsingHeader, ItemAdd, ItemHoverable, ItemSize, BeginTabItem, ShowDemoWindow; IMGUI_BUNDLE_NO_L=1 turns it off)
- Parallel: Actors free destroyed textures (leak), send only changed glyph rects
- Extensions: implot-luau (range renderers, tick reuse, @native per-point paths), imguicolortextedit-luau (widest line + selection cached), implot3d-luau, imguizmo-luau (@native math)
- LÖVE backend: RegisterCanvas()/UnregisterTexture(), ReadFile via love.filesystem root
- tests: t_move_pixels, t_scene_pixels, t_stress, t_stress2 + bench_scenes.luau
2026-10-21 04:04:31 -05:00
4DBug 694d56a78f LÖVE backend: ReadFile also tries the root as a love.filesystem path (works in .love/fused builds); RegisterCanvas()/UnregisterTexture() to show an existing Texture/Canvas without the backend owning it; rebuilt build/imgui_love.lua 2026-10-21 04:03:58 -05:00
4DBug 635cf6647b build: rebuild Roblox bundle + worker (round 3: rasterizer gradients/lines, library plots/colour pickers/Begin temporaries) 2026-10-21 03:50:40 -05:00
4DBug 90efb0c6e1 extensions: imguicolortextedit-luau -> 0592ed6 (TextEditor: widest line + selected text cached, @native glyph loops), implot3d-luau -> b30d2ff, imguizmo-luau -> 93f4569 (@native per-point/math paths) 2026-10-21 03:50:31 -05:00
4DBug 6eb91d17e4 extensions: implot-luau -> 2bc5700 (round 3 ImPlot performance: range renderers, @native per-point helpers, tick reuse) 2026-10-21 03:35:40 -05:00
4DBug dfdfea5ea7 Roblox backend: RasterRect tests a primitive's bounds against the rect before reading its clip (most of a tile's primitives miss a small dirty rect) 2026-10-21 03:35:32 -05:00
4DBug c85b2dbb96 Roblox raster: solid spans written two pixels per writef64 (the pixel twice as a normal double; per pixel otherwise), translucent black spans without the colour terms (colour picker SV square), triangle / line quad rows start past an estimate that is never in the span (replay: colorpicker -13%, plots -7%, implot -5%; pixels identical) 2026-10-21 03:35:32 -05:00
4DBug 12059f2646 Roblox backend: DirtyRects skips AddRect for a changed primitive inside the first dirty rect (where AddRect would merge it, unchanged) 2026-10-21 03:35:32 -05:00
4DBug d99864c315 Roblox raster: per-pixel blend/texel sample inlined in the interpolating triangle paths (rows and columns) and gradient kind 2 (a call per pixel cost more than the math), colours unpacked inline (shared when equal), white texels not folded, flat span constants only when translucent; line quads: bounds before edge setup, fixed texel row when v is constant; narrow solid spans written instead of copied per row (replay: colorpicker -14%, plots -14%, implot -3%; pixels identical) 2026-10-21 03:35:32 -05:00
4DBug b2c8ce7a00 tools/test: t_scene_pixels (bench scenes animated, composited every 8 frames: incremental == forced redraw), in check_all (ImPlot scene when extensions/implot-luau is checked out) 2026-10-21 03:35:32 -05:00
4DBug a2e19627fe tools/test: hashes.sh finds luau/luajit in the nix store when the pinned paths are gone (like check_all.sh) 2026-10-21 03:00:35 -05:00
4DBug 278f978d3e Library: fewer temporaries per window, child, input field, separator text and resizable table: Begin() skips CalcWindowAutoFitSize() when no axis auto-fits (result unused; still called when a size callback would see it), scalar scrollbar/auto-fit/avail/needed sizes, ScrollbarSizes updated in place, scratch viewport/visibility rects, OuterRectClipped and the previous-child overlap test without ImRects; RenderWindowOuterBorders() scratch corner; EndChild() scratch size/bb; InputTextEx() scalar label/frame/inner sizes, scratch total_bb and (single-line, until ItemAdd() accepts it) frame_bb, so clipped fields allocate nothing; SeparatorTextEx() scratch sizes/rect/positions; TableUpdateBorders() scratch hit rect
demo_all scene headless: 825 -> 553 KB/frame allocated (Begin 5.3 -> 1.4 KB per window, InputTextEx 0.8 KB -> 0 per
clipped field), user instructions/frame -1.3%. GC steps in that scene cost ~+1.5 ms on 2-4 frames per cycle, so
cycles get ~1/3 rarer. Draw data unchanged.
2026-10-21 03:00:23 -05:00
4DBug 30afa19ed1 Library: PlotEx() without per-point temporaries (scalar tp0/tp1 and ImLerp, two scratch corners only read by AddLine()/AddRectFilled(), scalar frame/inner/total rects) and @native; RenderColorRectWithAlphaCheckerboard() with scratch cell corners and @native; @native ShadeVertsLinearColorGradientKeepAlpha() and _PathArcToN() (color picker hue wheel)
plots scene headless --roblox (interleaved A/B): lib lowq ~0.35 -> ~0.27 ms/frame; colorpicker lib lowq ~0.43 ->
~0.38 ms/frame. Draw data unchanged (STRESS2HASH of all scenes, draw hashes).
2026-10-21 03:00:23 -05:00
4DBug 2ff5225f49 Library: @native on DebugNodeFontGlyphsForSrcMask() (the font atlas glyph grids: a 256-entry scan per codepoint block + 256 AddRect/RenderChar per open block) and on small helpers called from native code (IM_ASSERT, IM_ASSERT_USER_ERROR_RET, ImHashStr's memo, ImVector __index/push_back/pop_back/back/iter)
demo_all scene (whole demo open, headless --roblox, interleaved A/B): lib ~10.1 -> ~9.1 ms/frame, user
instructions/frame -5%; draw data unchanged.
2026-10-21 03:00:23 -05:00
4DBug 5fa9889a37 tools/test: bench_scenes.luau (plots, colorpicker, implot, demo_all scenes shared by the Studio bench and headless runs) and t_stress2.luau (library + backend time and draw checksum per scene) 2026-10-21 01:58:35 -05:00
4DBug 6f4ec3c2b7 build: rebuild Roblox bundle + worker (round 2: bundle-time ImGui.* localization, patches.lua, library allocations, backend raster/bookkeeping) 2026-10-21 01:29:48 -05:00
4DBug 701156b5cc Roblox backend: reuse the destroyed atlas texture record's buffer for the next one of the same size (repack)
buffer.create of a 512 KB atlas costs ~0.1-1.8 ms in Studio (spiky); a repack creates one every few frames
in the font size scenario.
2026-10-21 01:24:28 -05:00
4DBug 086e66cb3e Roblox backend: keep 4 prewarmed tiles in the free list (Heartbeat, one per call, never evicting)
A growing layer takes them instead of creating an EditableImage + ImageLabel mid-frame (~90 us per tile in
Studio vs ~7 us from the free list). GetTile: one path for new and recycled tiles (NewTile).
2026-10-21 01:24:28 -05:00
4DBug 162fa80075 Roblox raster: tall flat triangles (column walk) write spans like the row path (no BlendPixel call per pixel)
Opaque: direct writes; translucent: the row path's per-span constants + per-destination cache. Same math,
bit-identical (replay hash, t_pixels, t_composite, t_parallel). Replay: triangles ~13 -> ~9 ms, total -5%.
2026-10-21 01:24:28 -05:00
4DBug 31d09640bf Roblox backend: DirtyRects skips primitives unchanged at the same list position (paired lists)
Every pixel such a primitive covers is either inside a changed primitive's rect or drawn by the same
primitives in the same order. Headless: 7% fewer pixels rasterized on resize, raster+upload -6..-9%.
2026-10-21 01:24:28 -05:00
4DBug 53b3489f68 Roblox backend: moved draw lists with drifted vertices: redraw just what they touch (and always redraw it)
A window moved by whole pixels often has a few trig-generated vertices off the exact shift by an ulp (when a
coordinate crosses a power of two): CompareDrawList fell back to the full Collect + Hash (~1/4 of moving
frames), and the tile hashes don't see an ulp, so those primitives were never redrawn (stale pixels vs a
forced redraw, e.g. a moving Bullet). Now CompareDrawList lists the drifted vertices; if all their floor /
ceil (CollectPrims' bounds) shifted too it returns 3: PatchDrawList keeps the tile lists (same primitive
sequence, checked) and marks only the drifted primitives' entries changed (DriftMark, new each frame), so
their tiles redraw just those rects. Otherwise the full path marks them the same way.
2026-10-21 01:24:28 -05:00
4DBug 2fc6d75ef8 tools/test: t_move_pixels (moving window with circles / rounded rects / bullets: incremental == forced redraw), in check_all 2026-10-21 01:24:28 -05:00
4DBug f2648316e7 bundle.py: optimization L (Roblox): library-internal ImGui.Foo reads in function bodies become per-file locals ImGui_Foo (file function or a wrapper around it, within the 200 locals/upvalues limits), bound after every IM_INCLUDE; only names assigned once at load time, patchable deny-list (Begin/End/TreeNode*/CollapsingHeader/ItemAdd/ItemHoverable/ItemSize/BeginTabItem/ShowDemoWindow) stays a table lookup; IMGUI_BUNDLE_NO_L=1 turns it off
ImGui has ~1000 keys, so Luau's inline cache (hash slots < 256) missed most ImGui.Foo lookups. 722 names localized;
draw hashes identical, LÖVE bundle unchanged, IMGUI_BUNDLE_NO_L=1 reproduces the previous bundle byte for byte.
2026-10-21 01:20:39 -05:00
4DBug 328f13a3c4 Library: tables without per-instance temporaries in BeginTableEx()/TableUpdateLayout()/TableMergeDrawChannels() (scratch rects, scalar outer size); ImDrawListSplitter::Merge() keeps the command it merges away past Size for reuse (was 6 new ImDrawCmd per table per frame): 435 -> 247 tables/frame allocated for 10 small tables in a window
Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug f3387cfe76 Library: no temporaries in Checkbox()'s check mark, Bullet(), Dummy(), NewLine(), ArrowButton[Ex](), InvisibleButton(), MenuItemEx() and InputScalar()'s step buttons
Per widget headless: MenuItem 658 -> 119 B, Bullet 611 -> 0 B, ArrowButton 634 -> 7 B, Checkbox 74 -> 7 B, NewLine 112 -> 0 B, Dummy/InvisibleButton 448/673 -> 112 B (the caller's own ImVec2). Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug 2b5887d166 Library: no temporaries in Selectable(), RadioButton(), SeparatorEx(), LabelText(), BeginCombo(), SmallButton(), ProgressBar() and the single-line InputTextEx() path (scratch rects/vectors only read by callees, scalar text sizes, shared read-only defaults; the multi-line backup of LastItemData only built when multi-line)
Per widget headless (bytes allocated, time): Selectable 724 -> 7 B, -15%; RadioButton 857 -> 7 B, -15%; Separator 336 -> 0 B, -14%; LabelText 1555 -> 0 B, -33%; BeginCombo 1541 -> 6 B, -17%; InputFloat 3838 -> 1741 B, -15%; ProgressBar 986 -> 437 B, -10%. Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug 9c965297ee Library: PushStyleColor()/PushStyleVar*()/BeginGroup() reuse the stack entry left past Size by the matching pop (C++ copies them into the vector's storage), EndGroup() without temporaries: no garbage per push/group (was 288/193/1952 bytes), per widget headless: PushStyleColor -14%, PushStyleVar -12%, BeginGroup+EndGroup -34%, DragFloat3 -11%
Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug de8e2fef08 Library: fewer temporaries per window in Begin() (scalar TitleBarRect()/CollapseButton() rects, viewport clip and contains tests, visibility rect, CalcWindowSizeAfterConstraint() writes its own copy, title bar rect only built for a hovered window): 21.4 -> 18.8 KB/frame allocated for one window of buttons/sliders, 46.6 -> 42.5 KB/frame in the Studio bench scene
Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug 015cd40172 Library: ImDrawList reuses its ImDrawCmd objects (AddDrawCmd() takes the command left past Size by last frame's resize(0)/pop_back(), Merge() swaps instead of clearing channel slots), _CmdHeader reset in place: ~9 KB/frame less garbage in the Studio bench scene
Draw data unchanged.
2026-10-21 01:14:31 -05:00
4DBug c740729106 Roblox backend: patches.lua, Luau-tuned replacements of hot library internals (text rendering, text size cache hit)
New backend module installed when the backend loads (the library sources stay the 1:1 port): MT.ImFont.RenderText and
MT.ImDrawList.AddText share one native core (clip rect as numbers, PrimReserve inlined, no CPU fine clip branches,
AddText without the clip rect copy and extra call); ImFontCalcTextSizeXY checks its cache hit first. Uncommon cases
(byte-table text, CPU fine clip, > 10k bytes unwrapped, texture change mid-text) go to the originals. One switch per
patch (Enabled), M.Set() for in-process A/B. Draw hashes, composite pixels identical; imgui time -3..-4% (Studio
in-process A/B and headless).
2026-10-21 01:04:21 -05:00
4DBug 76cfcf6e12 build: rebuild Roblox bundle + worker (backend and library performance work since 0.4.2) 2026-10-20 20:52:38 -05:00
4DBug 90363f4a6e Library: @native on small, frequently called helpers (style color stack, tree push/pop, indent, item size, draw list clip/cmd, glyph lookup, table column helpers)
Picked from a per-function call census of the whole demo opened (hundreds of calls/frame each); +~100 KB of native
code. Whole demo open (headless --roblox) 10.35 -> 9.84 ms/frame together with the previous commits; draw data unchanged.
2026-10-20 15:19:28 -05:00
4DBug b05d2535c0 tools/test: t_stress.luau, headless copy of the Studio bench scene (library CPU per frame + draw checksum) 2026-10-20 15:19:28 -05:00
4DBug 70df13d409 Library: drop @native from once-per-window/frame giants, fewer slow lookups in text helpers
- Begin/End/NewFrame/UpdateMouseInputs back to interpreted: ~520 KB of native code (Begin alone 369 KB, +30% of the
  bundle's native code) for ~5 us/frame; native code is a game-wide budget in Roblox
- GetCurrentWindow(): read g.CurrentWindow once (the key sits in a hash slot >= 256 of the ~300-field context, which
  Luau's inline cache can't predict, so every read is a slow lookup)
- FindRenderedTextEnd(): strings use string.find/string.len directly (no ImMemchr() call, no `#` on a string)
- CalcTextSize(): calls CalcTextSizeXY() directly (one wrapper level less); TextEx(): string.len() for strings

Draw data unchanged.
2026-10-20 15:19:28 -05:00
4DBug 46551df26b Library: fewer calls/lookups per text item, table cell and frame
- Text(): TextV() inlined (one vararg call less per formatted Text); TextEx(): CalcTextSize() inlined
- ImFontCalcTextSizeXY / RenderText / CalcWordWrapPosition: GetFontBaked() fast path inlined (LastBaked check)
- TableBeginCell(): SetWindowClipRectBeforeSetChannel() inlined; SetCurrentChannel(): skip the TexRef field reads
  when both commands share the same TexRef (as ImDrawCmd_HeaderCompare already does)
- UpdateKeyboardInputs / UpdateKeyRoutingTable: loop-invariant field reads hoisted
- `#` on strings replaced by string.len() in ImFontCalcTextSizeXY (`#` is not a native fast path)

Headless --roblox: stress+demo 0.98 -> 0.89 ms/frame, empty frame 0.085 -> 0.067 ms; draw data unchanged.
2026-10-20 15:19:28 -05:00
4DBug 713cd3c22a Library: @native on hot interpreted paths (Begin/End, NewFrame key loops, table rows, sliders, buttons, wrapped text, GetFontBaked)
Fewer native<->interpreter transitions on the per-item call chains. Stress+demo headless (--roblox) 0.98 -> 0.93 ms/frame,
draw data unchanged.
2026-10-20 15:19:28 -05:00
4DBug b75f183ecf Roblox backend: tiles no longer allocate a 64 KB CPU pixel buffer each (unused since dirty rects are rasterized straight into upload buffers) 2026-10-20 15:12:11 -05:00
4DBug 5f23d260fd Roblox backend raster: damage to the uniform rows collected in one pending rect (applied when a span needs them); spans process runs of rows with the same uniform piece at once 2026-10-20 15:11:51 -05:00
4DBug a20b7fcacf Roblox backend raster: uniform rows are only valid inside the last ClearRect (no reset passes) 2026-10-20 15:11:51 -05:00
4DBug efe16cc1e8 Roblox backend raster: glyph blits read consecutive texels without the column table, cache white-texel blends per alpha 2026-10-20 15:11:51 -05:00
4DBug 7a453fd8b7 Roblox backend raster: uniform region tracked per row instead of one rect (translucent spans over uniform rows fill instead of blending per pixel) 2026-10-20 15:11:51 -05:00
4DBug ad32fa4bd1 Roblox backend: rasterize dirty rects straight into the upload buffer (no CopySubRect, no cold 64 KB tile buffer) 2026-10-20 15:11:51 -05:00
4DBug 360e7b70bc Font atlas: ImTextureData:Create() reuses the pixel table of the last atlas texture removed after the backend destroyed it (same byte size, zero-filled with table.move doubling) instead of a new 512K-entry table per repack (texadd 92 -> 44 ms, bake bench -8% run side by side; atlas/glyph checksums and draw hashes unchanged) 2026-10-20 14:47:54 -05:00
4DBug 08953d4270 Parallel: Actors free destroyed textures (each atlas grow/repack left a full copy in every Actor), atlas patches send the updated glyph rects instead of whole row spans and are built once per version for all Actors (fonts tex sends 151 -> 91 KB/frame in Studio, TexBytes 35.6 -> 22.2 MB headless); Actor texture handling moved to Raster.ApplyTextures, which Sync mode now runs on per-Actor copies so t_parallel checks it; t_parallel fonts scenario (new size per frame), check_all runs 620 frames 2026-10-20 14:47:54 -05:00
4DBug 19083b757d Faster glyph baking: atlas repack finds RectsIndex entries by the loop index (index_from_ptr was O(n^2) per repack), stb_truetype vertical edges (all of ProggyClean's) without stbtt__handle_clipped_edge calls, FlattenCurves with locals + inlined add_point, @native trunc (sorted-edges 215 -> 107 ms, repack 330 -> 184 ms on bake bench; glyph bitmaps, atlas and draw hashes unchanged) 2026-10-20 14:47:54 -05:00
4DBug c3119740e4 Textures: typed, unrolled RGBA/Alpha8 row conversion (no zero-skip branch): new 512x256 atlas record 0.54 -> 0.30 ms headless, pixels unchanged 2026-10-20 14:47:54 -05:00
4DBug 2ffc355ffe Roblox render: hot loop locals, native DrawLayer, DirtyRects without copies
- CollectPrims / HashTiles / DirtyRects: the Prim* / slot tables as locals (upvalue access per element was
  measurable: Collect -13%, Hash -8%)
- CollectPrims notes flat rects (PrimFlat): HashTiles no longer re-reads uvs, gradient and texture per quad
- HashTiles: one loop over a primitive's tiles instead of nested for loops (most touch one tile)
- DrawLayer, SweepTiles @native (per-tile bookkeeping -33%)
- DirtyRects: clipped bounds computed once (content bounds from them); the tile's Drawn* hash/flat lists are
  swapped with the layer's lists and the bounds with a scratch set instead of copied per entry
Headless full re-collect of the demo vs 0.4.2: Collect -24%, Hash -48%, bookkeeping -32%. Pixels identical
(t_pixels, t_composite, t_parallel, TileLimit run).
2026-10-20 14:47:19 -05:00
4DBug ba9d529935 Roblox render: cheaper CollectPrims + HashTiles (per changed draw list)
HashTiles: a touched tile's count/hashes/lists live in slot arrays for the call (one KeySlot lookup per tile
switch instead of ~7 hash-table reads/writes; consecutive primitives alternate tiles ~40% of the time), the
vertex hash is inlined (HashVertex calls weren't inlined and cost more than the hashing), tile ranges come
from the already-relative bounds. Hash values are unchanged.
CollectPrims: the axis aligned rect test runs before the textured line-quad test (mutually exclusive, so the
result is the same; glyphs no longer read their colours/uvs twice), clipped/limit/extent checks per command
from the command's bounds instead of per primitive, and primitives go to their layer lists while collecting
(no PrimKind pass in DrawLists).
Headless full re-collect of the demo (1500 prims): Collect -10%, Hash -35%.
2026-10-20 14:47:19 -05:00
4DBug b62997f2c3 Roblox backend: faster unchanged check: CompareDrawList compares vertices as 4 f64 + col (3x fewer reads), indices 4 per step; a moved list's snapshot is shifted in place (ShiftSnapshot) instead of re-snapshotted from another list's Cmd* data 2026-10-20 13:56:21 -05:00
38 changed files with 12095 additions and 8025 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)
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/[email protected].2"` 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].3"` 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.
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)
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/[email protected].2"` 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].3"` 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.
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`.
+18
View File
@@ -231,6 +231,9 @@ local function ReadFile(filename)
local data = love.filesystem.getInfo(filename) and love.filesystem.read(filename)
if data then return data end
local bd = ImGui_ImplLOVE_GetBackendData()
local lf = bd and bd.Root ~= "" and bd.Root .. filename -- root may also be a love.filesystem path (works in .love/fused)
data = lf and love.filesystem.getInfo(lf) and love.filesystem.read(lf)
if data then return data end
local f = io.open(((bd and bd.Root) or "") .. filename, "rb")
if not f then return nil end
data = f:read("*a"); f:close()
@@ -328,6 +331,19 @@ function ImGui_ImplLOVE_DestroyTexture(tex_ref)
if image then image:release(); bd.Textures[tex_ref._TexID] = nil end
end
--- Register an existing LÖVE Texture/Canvas (not owned: never released by the backend). Returns an ImTextureRef.
function ImGui_ImplLOVE_RegisterCanvas(drawable)
local bd = ImGui_ImplLOVE_GetBackendData()
bd.TextureCount = bd.TextureCount + 1
bd.Textures[bd.TextureCount] = drawable
return ImTextureRef(bd.TextureCount)
end
--- Forget a registered texture without releasing it.
function ImGui_ImplLOVE_UnregisterTexture(tex_ref)
ImGui_ImplLOVE_GetBackendData().Textures[tex_ref._TexID] = nil
end
---------------------------------------------------------
-- RENDERING: one streamed Mesh per draw list; vertices converted from the port's flat VtxBuffer (f64 x, y, u, v,
-- u32 col; 36 bytes) to LÖVE's float x, y, u, v + byte rgba (20 bytes); indices -> 0-based uint32 vertex map.
@@ -526,6 +542,8 @@ ImGui_ImplLove = {
RenderDrawData = ImGui_ImplLOVE_RenderDrawData,
CreateTexture = ImGui_ImplLOVE_CreateTexture,
DestroyTexture = ImGui_ImplLOVE_DestroyTexture,
RegisterCanvas = ImGui_ImplLOVE_RegisterCanvas,
UnregisterTexture = ImGui_ImplLOVE_UnregisterTexture,
MouseMoved = MouseMoved,
MousePressed = MousePressed,
MouseReleased = MouseReleased,
+3
View File
@@ -4,6 +4,8 @@ local Textures = IM_INCLUDE("roblox/textures.lua")
local Layers = IM_INCLUDE("roblox/layers.lua")
local Render = IM_INCLUDE("roblox/render.lua")
local Parallel = IM_INCLUDE("roblox/parallel.lua")
-- Luau-tuned replacements of hot library internals, installed when this file loads (see patches.lua)
local Patches = IM_INCLUDE("roblox/patches.lua")
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
@@ -211,6 +213,7 @@ function ImGui_ImplRoblox_Init(parent, render_scale)
elseif BackendData.Stale and BackendData.HeartbeatCount > BackendData.StaleHeartbeat then
ImGui_ImplRoblox_RenderDrawData(BackendData.Stale)
end
Layers.Prewarm()
BackendData.HeartbeatCount += 1
end)
+119 -44
View File
@@ -2,7 +2,7 @@
local Raster = IM_INCLUDE("roblox/raster.lua")
local Textures = IM_INCLUDE("roblox/textures.lua")
local floor, max = math.floor, math.max
local floor, ceil, max = math.floor, math.ceil, math.max
local readu32, writeu32, readf64, writef64 = buffer.readu32, buffer.writeu32, buffer.readf64, buffer.writef64
local TILE = Raster.TILE
local EditableImages = Textures.EditableImages
@@ -94,47 +94,55 @@ function EditableImages.FreeTile(layer, key, recycle)
nil, nil, nil, nil, nil
end
-- A new tile (transparent image, hidden unparented label), nil over the EditableImage budget
local function NewTile()
local img = EditableImages.Create(TILE, TILE)
if not img then return nil end
local label = Instance.new("ImageLabel")
label.Name = "Tile"
label.BackgroundTransparency = 1
label.BorderSizePixel = 0
label.ResampleMode = Enum.ResamplerMode.Pixelated
label.ImageContent = Content.fromObject(img)
label.Visible = false
return {
Image = img, Label = label,
Hash1 = -1, Hash2 = -1, Visible = false, Used = 0,
ContentX0 = TILE, ContentY0 = TILE, ContentX1 = 0, ContentY1 = 0,
ValidX0 = 0, ValidY0 = 0, ValidX1 = TILE, ValidY1 = TILE,
Scale = false, Active = nil, Parent = nil,
DrawnCount = -1, DrawnHash1 = {}, DrawnHash2 = {}, DrawnFlat = {},
DrawnX0 = {}, DrawnY0 = {}, DrawnX1 = {}, DrawnY1 = {},
}
end
-- Keeps PREWARM tiles in the free list (Heartbeat, one per call, never evicting): a layer that grows takes them instead
-- of creating EditableImages + labels mid-frame (~90 us per tile in Studio, ~7 us from the free list)
local PREWARM = 4
function M.Prewarm()
local pool = EditableImages.Pool
if #pool < PREWARM and EditableImages.Bytes + TILE * TILE * 4 <= EditableImages.Cap then
local tile = NewTile()
if tile then table.insert(pool, 1, tile) end -- (at the bottom: recycled tiles keep their parent, used first)
end
end
function M.GetTile(BackendData, layer, key, tx, ty)
local tile = layer.Tiles[key]
if tile then return tile end
local scale = BackendData.Scale
local old = table.remove(EditableImages.Pool)
local label, img
if old then
label, img = old.Label, old.Image
else
img = EditableImages.Create(TILE, TILE)
if not img then return nil end -- over the budget even after eviction: the caller skips this tile this frame
label = Instance.new("ImageLabel")
label.Name = "Tile"
label.BackgroundTransparency = 1
label.BorderSizePixel = 0
label.ResampleMode = Enum.ResamplerMode.Pixelated
label.ImageContent = Content.fromObject(img)
label.Visible = false
end
if not old or old.Scale ~= scale then label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) end
-- Content*: content bounds; Valid*: where the image pixels are current. A recycled tile keeps both (they still
-- describe its image): its first draw is a full one (DrawnCount -1) that only clears old + new content bounds.
tile = table.remove(EditableImages.Pool) or NewTile()
if not tile then return nil end -- over the budget even after eviction: the caller skips this tile this frame
local label = tile.Label
if tile.Scale ~= scale then label.Size = UDim2.fromOffset(TILE / scale, TILE / scale) end
label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale)
if not old or old.Active ~= BackendData.TilesActive then label.Active = BackendData.TilesActive end
if not old or old.Parent ~= layer.Frame then label.Parent = layer.Frame end
-- Content*: content bounds; Valid*: where Buffer == image pixels. A recycled tile keeps both (they still describe
-- its image): its first draw is a full one (DrawnCount -1) that only clears old + new content bounds.
if old then
tile = old
tile.Hash1, tile.Hash2, tile.Visible, tile.Used, tile.Deferred, tile.DrawnCount =
-1, -1, false, BackendData.FrameNo, nil, -1
tile.Scale, tile.Active, tile.Parent = scale, BackendData.TilesActive, layer.Frame
else
tile = {
Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4),
Hash1 = -1, Hash2 = -1, Visible = false, Used = BackendData.FrameNo,
ContentX0 = TILE, ContentY0 = TILE, ContentX1 = 0, ContentY1 = 0,
ValidX0 = 0, ValidY0 = 0, ValidX1 = TILE, ValidY1 = TILE,
Scale = scale, Active = BackendData.TilesActive, Parent = layer.Frame,
DrawnCount = -1, DrawnHash1 = {}, DrawnHash2 = {}, DrawnFlat = {},
DrawnX0 = {}, DrawnY0 = {}, DrawnX1 = {}, DrawnY1 = {},
}
end
if tile.Active ~= BackendData.TilesActive then label.Active = BackendData.TilesActive end
if tile.Parent ~= layer.Frame then label.Parent = layer.Frame end
tile.Hash1, tile.Hash2, tile.Visible, tile.Used, tile.Deferred, tile.DrawnCount =
-1, -1, false, BackendData.FrameNo, nil, -1
tile.Scale, tile.Active, tile.Parent = scale, BackendData.TilesActive, layer.Frame
layer.Tiles[key] = tile
if EditableImages.StageTiming then EditableImages.AddStat("TilesCreated", 1) end
return tile
@@ -222,6 +230,37 @@ function M.Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
set.SnapOK = true
end
-- The snapshot of a list CompareDrawList found moved by (dx, dy): only its vertices, clip rects, content clip,
-- scroll origin, primitive bounds and extents move (counts, indices, kinds are equal; Cmd* describe another list now)
@native
function M.ShiftSnapshot(set, draw_list, dx, dy)
buffer.copy(set.SnapVtx, 0, draw_list.VtxBuffer.Buf, 0, set.SnapVtxBytes)
local sc, o = set.SnapCmds, 0
for _, pcmd in draw_list.CmdBuffer:iter() do
local c = pcmd.ClipRect
writef64(sc, o, c.x)
writef64(sc, o + 8, c.y)
writef64(sc, o + 16, c.z)
writef64(sc, o + 24, c.w)
if buffer.readu8(sc, o + 53) ~= 0 then
buffer.writei32(sc, o + 54, buffer.readi32(sc, o + 54) + dx)
buffer.writei32(sc, o + 58, buffer.readi32(sc, o + 58) + dy)
buffer.writei32(sc, o + 62, buffer.readi32(sc, o + 62) + dx)
buffer.writei32(sc, o + 66, buffer.readi32(sc, o + 66) + dy)
end
o += CMD_STRIDE
end
if set.SnapHasContent then
set.SnapContentX0, set.SnapContentY0, set.SnapContentX1, set.SnapContentY1 = draw_list._ContentClipX0,
draw_list._ContentClipY0, draw_list._ContentClipX1, draw_list._ContentClipY1
set.SnapScrollX, set.SnapScrollY = draw_list._ScrollOriginX, draw_list._ScrollOriginY
end
set.SnapExtentX0 += dx
set.SnapExtentY0 += dy
set.SnapExtentX1 += dx
set.SnapExtentY1 += dy
end
-- a + d == b exactly, with no rounding in a + d (so every later "x - origin" gives the same result as before the move)
@native
local function ShiftedExact(a, d, b)
@@ -231,8 +270,14 @@ local function ShiftedExact(a, d, b)
return (a - (s - bb)) + (d - bb) == 0
end
-- vertex byte offsets of the last CompareDrawList's drifted vertices (moved by about an ulp off the exact shift)
local MAX_DRIFT = 256
local Drift = table.create(MAX_DRIFT, 0)
M.Drift, M.DriftCount = Drift, 0
@native
function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
M.DriftCount = 0
if not set or not set.SnapOK then return 0 end
local nv = draw_list.VtxBuffer.Size * VTX_STRIDE
local ni, ncmd = draw_list.IdxBuffer.Size, draw_list.CmdBuffer.Size
@@ -247,8 +292,18 @@ function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
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 == 0 and dy == 0 then
-- u32 loop, not readstring ==: that allocated 2 vertex-buffer strings per list per frame (GC spikes)
for o = 0, nv - 4, 4 do if readu32(vb, o) ~= readu32(sv, o) then return 0 end end
-- 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.
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)
if x ~= readf64(sv, v) or y ~= readf64(sv, v + 8) or u ~= readf64(sv, v + 16)
or w ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32) then
return 0
end
if x == 0 or y == 0 or u == 0 or w == 0 then
for p = v + 4, v + 28, 8 do if readu32(vb, p) ~= readu32(sv, p) then return 0 end end
end
end
else
if dx ~= floor(dx) or dy ~= floor(dy) or ox ~= 0 or oy ~= 0 or not set.SnapLimitFree then return 0 end
-- everything must stay as far from the clip limits as before (nothing newly clamped)
@@ -258,7 +313,13 @@ function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
end
end
local idx, si = draw_list.IdxBuffer.Data, set.SnapIdx
for i = 1, ni do if idx[i] ~= si[i] then return 0 end end
local n4 = ni - ni % 4
for i = 1, n4, 4 do
if idx[i] ~= si[i] or idx[i + 1] ~= si[i + 1] or idx[i + 2] ~= si[i + 2] or idx[i + 3] ~= si[i + 3] then
return 0
end
end
for i = n4 + 1, ni do if idx[i] ~= si[i] then return 0 end end
local sc, o = set.SnapCmds, 0
local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1,
draw_list._ContentClipY1
@@ -308,13 +369,27 @@ function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
and ShiftedExact(set.SnapContentY1, dy, draw_list._ContentClipY1)
and ShiftedExact(set.SnapScrollX, dx, draw_list._ScrollOriginX)
and ShiftedExact(set.SnapScrollY, dy, draw_list._ScrollOriginY)) then return 0 end
-- 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
-- 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
for v = 0, nv - VTX_STRIDE, VTX_STRIDE do
if not ShiftedExact(readf64(sv, v), dx, readf64(vb, v))
or not ShiftedExact(readf64(sv, v + 8), dy, readf64(vb, v + 8))
or 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
local ax, ay, bx, by = readf64(sv, v), readf64(sv, v + 8), readf64(vb, v), readf64(vb, v + 8)
if not ShiftedExact(ax, dx, bx) or not ShiftedExact(ay, dy, by) then
if nd >= MAX_DRIFT then return 0 end
nd += 1
Drift[nd] = v
if floor(bx) ~= floor(ax) + dx or ceil(bx) ~= ceil(ax) + dx or ceil(bx - 0.5) ~= ceil(ax - 0.5) + dx
or floor(by) ~= floor(ay) + dy or ceil(by) ~= ceil(ay) + dy or ceil(by - 0.5) ~= ceil(ay - 0.5) + dy then
consistent = false
end
end
end
return 2, dx, dy
M.DriftCount = nd
if nd == 0 then return 2, dx, dy end
return consistent and 3 or 0, dx, dy
end
function M.ShiftLayer(layer, dx, dy, scale)
+88 -6
View File
@@ -68,6 +68,23 @@ local pending, by_id, batch_no = {}, {}, 0
local open = false
local actors, ready, conns, folder = {}, false, {}, nil
local sent = {}
-- ids of destroyed textures each Actor holds a copy of, sent with its next job (the Actor drops them)
local drops = {}
local NO_DROPS = {}
local sync_tex = {} -- Sync mode: the "Actors'" texture copies
EditableImages.TextureDropped = function(id, rec)
if not rec then
return
end
for a = 1, NA do
local s = sent[a]
if s and s[rec] ~= nil then
s[rec] = nil
local d = drops[a]
d[#d + 1] = id
end
end
end
local function grow(b: buffer, need: number): buffer
local n = buffer.len(b)
@@ -251,6 +268,46 @@ local function fullCopy(rec, v: number): buffer
return rec.Head
end
-- The pixels changed between versions had and v (rows y0..y1 of rec): the updated rects (rect list -> worker copies
-- each rect's rows), or the whole rows when they are smaller. Built once per (had, v), shared by every Actor.
local function patchCopy(rec, had: number, v: number, y0: number, y1: number): (buffer, any)
if rec.PatchHad == had and rec.PatchV == v then
return rec.Patch, rec.PatchAt
end
local row, src = rec.Width * 4, rec.Buffer
local log, area = rec.Log, 0
for k = had + 1, v do
local r = log[k][3]
if r then
for i = 1, #r, 4 do area += r[i + 2] * r[i + 3] end
end
end
local patch, at
if area * 4 < (y1 - y0) * row then
patch, at = buffer.create(area * 4), {}
local o, n = 0, 0
for k = had + 1, v do
local r = log[k][3]
if r then
for i = 1, #r, 4 do
local x, y, w, h = r[i], r[i + 1], r[i + 2], r[i + 3]
at[n + 1], at[n + 2], at[n + 3], at[n + 4] = x, y, w, h
n += 4
for yy = y, y + h - 1 do
copy(patch, o, src, (yy * rec.Width + x) * 4, w * 4)
o += w * 4
end
end
end
end
else
patch, at = buffer.create((y1 - y0) * row), y0 * row
copy(patch, 0, src, y0 * row, (y1 - y0) * row)
end
rec.PatchHad, rec.PatchV, rec.Patch, rec.PatchAt = had, v, patch, at
return patch, at
end
function M.Flush()
local n = jobs.N
if n == 0 then
@@ -321,22 +378,45 @@ function M.Flush()
tex[#tex + 1] = { id, buf, rec.Width, rec.Height, rec.Fill or 0 }
Stats.TexBytes += buffer.len(buf)
elseif y1 > y0 then
local row = rec.Width * 4
local patch = buffer.create((y1 - y0) * row)
copy(patch, 0, rec.Buffer, y0 * row, (y1 - y0) * row)
tex[#tex + 1] = { id, false, rec.Width, rec.Height, y0 * row, patch }
local patch, at = patchCopy(rec, had, v, y0, y1)
tex[#tex + 1] = { id, false, rec.Width, rec.Height, at, patch }
Stats.TexBytes += buffer.len(patch)
end
Stats.TexSends += 1
end
end
Stats.SendBytes += Pn[a] + tl
local d = drops[a]
if #d > 0 then
drops[a] = {}
else
d = NO_DROPS
end
if cfg.Sync then
-- like an Actor: own texture copies, kept by the same messages (SendMessage copies: clone the buffers)
local st = sync_tex[a]
if not st then
st = {}
sync_tex[a] = st
end
local msg = table.create(#tex)
for i, u in tex do
local c = table.clone(u)
for k, x in c do
if type(x) == "buffer" then
local nb = buffer.create(buffer.len(x))
copy(nb, 0, x)
c[k] = nb
end
end
msg[i] = c
end
Raster.ApplyTextures(st, msg, d)
if not (cfg.SyncDrop and a % 2 == 0) then
b.Res[a] = RasterJobs(P, T, tl, Records)
b.Res[a] = RasterJobs(P, T, tl, st)
end
else
actors[a]:SendMessage("job", batch_no, P, T, tex, tl)
actors[a]:SendMessage("job", batch_no, P, T, tex, tl, d)
end
end
if par then
@@ -365,6 +445,8 @@ local function setActors(n)
Tb[a] = Tb[a] or buffer.create(1024)
used[a] = used[a] or {}
sent[a] = setmetatable({}, { __mode = "k" })
drops[a] = {}
sync_tex[a] = nil
end
reset()
end
+284
View File
@@ -0,0 +1,284 @@
-- Patches: Luau/Roblox-tuned replacements of hot library internals, installed when the backend loads.
-- The library sources stay a 1:1 port (and run on LÖVE); these versions use buffers, typed natives and specialized fast
-- paths instead. Every patch must be exactly equivalent (same draw data, IDs, pixels): uncommon cases are handed back to
-- the original function. Only method tables / globals the callers look up at call time are replaced (MT.*), never a
-- library local. Enabled holds one switch per patch (bisecting: set one to false and rebuild; M.Set() switches at run
-- time for A/B timing).
local M = {}
M.Enabled = {
RenderText = true, -- MT.ImFont.RenderText: Lua string, no CPU fine clip
AddText = true, -- MT.ImDrawList.AddText: same, calling the RenderText core directly
CalcTextSize = true, -- ImFontCalcTextSizeXY: cache hit of an unwrapped whole string, checked first
}
local MT = ImGui.GetMetatables()
local byte, floor = string.byte, math.floor
local band, bor = bit32.band, bit32.bor
local writef64, writeu32 = buffer.writef64, buffer.writeu32
local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- same values as imgui_draw.lua's locals
local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE
------------------------------------------------------------------------------------------------------------------------
-- Text: ImFont:RenderText() for a Lua string without CPU fine clip (and < 10k bytes unless wrapped) as one function
-- taking the clip rect as numbers, PrimReserve() inlined, no fine clip branches in the glyph loop. Same vertex/index
-- writes in the same order. ImDrawList:AddText() calls it directly (no clip rect copy, one call less).
------------------------------------------------------------------------------------------------------------------------
local RenderText_Orig = MT.ImFont.RenderText
local AddText_Orig = MT.ImDrawList.AddText
local text_clip_rect = ImVec4() -- only for the texture-change fallback
-- imgui_draw.lua's local ImTextCalcWordWrapNextLineStart() for a Lua string: trim trailing blanks, skip one '\n'
local function WordWrapNextLineStart(text: string, pos: number, text_end: number, flags: number): number
if band(flags, ImDrawTextFlags.WrapKeepBlanks) == 0 then
while pos < text_end do
local c = byte(text, pos)
if c ~= 32 and c ~= 9 then break end
pos += 1
end
end
if pos < text_end and byte(text, pos) == 10 then
pos += 1
end
return pos
end
-- Returns false (nothing done) when the original must handle it: CPU fine clip, or unloaded glyphs changed the texture
@native
local function RenderTextCore(font, draw_list, size: number, x: number, y: number, col: number, clip_x1: number, clip_y1: number, clip_x2: number, clip_y2: number, text: string, s: number, text_end: number, wrap_width: number, flags: number): boolean
if y > clip_y2 then
return true
end
flags = bor(flags, draw_list.Flags)
if band(flags, ImDrawTextFlags.CpuFineClip) ~= 0 then
return false
end
if band(flags, ImDrawFlags.TextNoPixelSnap) == 0 then
x = floor(x)
y = floor(y)
end
local baked = font.LastBaked
if not (baked and baked.Size == floor(size + 0.5) and baked.RasterizerDensity == font.CurrentRasterizerDensity) then
baked = font:GetFontBaked(size)
end
local scale: number = size / baked.Size
local origin_x = x
local line_height = size
local word_wrap_enabled = wrap_width > 0.0
-- Fast-forward to first visible line
if y + line_height < clip_y1 then
while y + line_height < clip_y1 and s < text_end do
local line_end = ImMemchr(text, '\n', s)
if word_wrap_enabled then
s = ImFontCalcWordWrapPositionEx(font, size, text, s, (line_end ~= nil) and line_end or text_end, wrap_width, flags)
s = WordWrapNextLineStart(text, s, text_end, flags)
else
s = (line_end ~= nil) and (line_end + 1) or text_end
end
y = y + line_height
end
end
if s == text_end then
return true
end
local vtx_count_max = (text_end - s) * 4
local idx_count_max = (text_end - s) * 6
-- PrimReserve(idx_count_max, vtx_count_max) inlined
if (draw_list._VtxCurrentIdx + vtx_count_max >= 65536) and (band(draw_list.Flags, ImDrawFlags.UseVtxOffset) ~= 0) then
draw_list._CmdHeader.VtxOffset = draw_list.VtxBuffer.Size + 1
draw_list:_OnChangedVtxOffset()
end
local cmd_buffer = draw_list.CmdBuffer
local cmd_count = cmd_buffer.Size
local draw_cmd = cmd_buffer.Data[cmd_count]
local elem_count = draw_cmd.ElemCount + idx_count_max
draw_cmd.ElemCount = elem_count
local vtx_buffer = draw_list.VtxBuffer
local vtx_write: number = vtx_buffer.Size + 1
local vtx_new_size = vtx_write - 1 + vtx_count_max
if vtx_new_size > vtx_buffer.Capacity then vtx_buffer:resize(vtx_new_size) else vtx_buffer.Size = vtx_new_size end
local idx_buffer = draw_list.IdxBuffer
local idx_write: number = idx_buffer.Size + 1
local idx_new_size = idx_write - 1 + idx_count_max
if idx_new_size > idx_buffer.Capacity then idx_buffer:resize(idx_new_size) else idx_buffer.Size = idx_new_size end
local idx_begin = idx_write
local vtx_index: number = draw_list._VtxCurrentIdx
local idx_data = idx_buffer.Data
local vtx_data: buffer = vtx_buffer.Buf
local color_untinted = bor(col, 0x00FFFFFF)
local lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data
local word_wrap_eol: number? = nil
while s < text_end do
if word_wrap_enabled then
if not word_wrap_eol then
word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, text, s, text_end, wrap_width - (x - origin_x), flags)
lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data
end
if s >= word_wrap_eol then
x = origin_x
y += line_height
if y > clip_y2 then
break
end
word_wrap_eol = nil
s = WordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks
continue
end
end
local c: number = byte(text, s)
if c < 0x80 then
s += 1
else
local wanted, out_char = ImStd.ImTextCharFromUtf8(text, s, text_end)
c = out_char
s += wanted
end
if c < 32 then
if c == 10 then
x = origin_x
y += line_height
if y > clip_y2 then
break
end
continue
end
if c == 13 then
continue
end
end
local glyph
local gi = (c < lookup_n) and lookup[c + 1] or nil
if gi ~= nil and gi ~= IM_FONTGLYPH_INDEX_NOT_FOUND and gi ~= IM_FONTGLYPH_INDEX_UNUSED then
glyph = glyphs[gi]
else
glyph = baked:FindGlyph(c)
lookup, lookup_n, glyphs = baked.IndexLookup.Data, baked.IndexLookup.Size, baked.Glyphs.Data
end
local char_width: number = glyph.AdvanceX * scale
if glyph.Visible then
local x1: number = x + glyph.X0 * scale
local x2: number = x + glyph.X1 * scale
if x1 <= clip_x2 and x2 >= clip_x1 then
local y1: number = y + glyph.Y0 * scale
local y2: number = y + glyph.Y1 * scale
local u1: number, v1: number, u2: number, v2: number = glyph.U0, glyph.V0, glyph.U1, glyph.V1
local glyph_col = glyph.Colored and color_untinted or col
local o = (vtx_write - 1) * 36
writef64(vtx_data, o, x1); writef64(vtx_data, o + 8, y1); writef64(vtx_data, o + 16, u1); writef64(vtx_data, o + 24, v1); writeu32(vtx_data, o + 32, glyph_col)
writef64(vtx_data, o + 36, x2); writef64(vtx_data, o + 44, y1); writef64(vtx_data, o + 52, u2); writef64(vtx_data, o + 60, v1); writeu32(vtx_data, o + 68, glyph_col)
writef64(vtx_data, o + 72, x2); writef64(vtx_data, o + 80, y2); writef64(vtx_data, o + 88, u2); writef64(vtx_data, o + 96, v2); writeu32(vtx_data, o + 104, glyph_col)
writef64(vtx_data, o + 108, x1); writef64(vtx_data, o + 116, y2); writef64(vtx_data, o + 124, u1); writef64(vtx_data, o + 132, v2); writeu32(vtx_data, o + 140, glyph_col)
idx_data[idx_write] = vtx_index; idx_data[idx_write + 1] = vtx_index + 1; idx_data[idx_write + 2] = vtx_index + 2
idx_data[idx_write + 3] = vtx_index; idx_data[idx_write + 4] = vtx_index + 2; idx_data[idx_write + 5] = vtx_index + 3
vtx_write += 4
vtx_index += 4
idx_write += 6
end
end
x += char_width
end
if cmd_count ~= cmd_buffer.Size then
-- Unloaded glyphs changed the texture: undo (like the original's edge case), the caller redoes it with the original
IM_ASSERT(cmd_buffer.Data[cmd_buffer.Size].ElemCount == 0)
cmd_buffer:pop_back()
draw_list:PrimUnreserve(idx_count_max, vtx_count_max)
draw_list:AddDrawCmd()
return false
end
-- Give back unused vertices (clipped ones, blanks)
vtx_buffer.Size = vtx_write - 1
idx_buffer.Size = idx_write - 1
draw_cmd.ElemCount = elem_count - (idx_count_max - (idx_write - idx_begin))
draw_list._VtxWritePtr = vtx_write
draw_list._IdxWritePtr = idx_write
draw_list._VtxCurrentIdx = vtx_index
return true
end
@native
local function RenderText(self, draw_list, size: number, pos, col: number, clip_rect, text, text_begin: number, text_end: number, wrap_width: number?, flags: number?)
if type(text) ~= "string" or (text_end - text_begin > 1e4 and not (wrap_width ~= nil and wrap_width > 0.0))
or not RenderTextCore(self, draw_list, size, pos.x, pos.y, col, clip_rect.x, clip_rect.y, clip_rect.z, clip_rect.w, text, text_begin, text_end, wrap_width or 0.0, flags or 0) then
return RenderText_Orig(self, draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags)
end
end
@native
local function AddText(self, font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect)
if cpu_fine_clip_rect ~= nil or type(text) ~= "string" or text_end == nil
or (type(font) == "table" and type(font[1]) == "number") then
return AddText_Orig(self, font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect)
end
if text_begin == nil then text_begin = 1 end
if band(col, 0xFF000000) == 0 or text_begin == text_end then
return
end
if font == nil then
font = self._Data.Font
end
if font_size == 0.0 then
font_size = self._Data.FontSize
end
local cr = self._CmdHeader.ClipRect
if (text_end - text_begin > 1e4 and not (wrap_width ~= nil and wrap_width > 0.0))
or not RenderTextCore(font, self, font_size, pos.x, pos.y, col, cr.x, cr.y, cr.z, cr.w, text, text_begin, text_end, wrap_width or 0.0, 0) then
local clip_rect = text_clip_rect
clip_rect.x = cr.x; clip_rect.y = cr.y; clip_rect.z = cr.z; clip_rect.w = cr.w
RenderText_Orig(font, self, font_size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, 0)
end
end
------------------------------------------------------------------------------------------------------------------------
-- CalcTextSize: ImFontCalcTextSizeXY() answers most calls from its per baked font cache (whole string, no wrap/limit);
-- check that case first, with the same conditions, and hand everything else to the original.
------------------------------------------------------------------------------------------------------------------------
local CalcTextSizeXY_Orig = ImFontCalcTextSizeXY
local TEXT_SIZE_CACHE_MAX = 4096 -- imgui_draw.lua's local: a full cache is reset by the original before looking up
@native
local function CalcTextSizeXY(font, size: number, max_width: number, wrap_width: number, text, text_begin, text_end_display, text_end, out_offset, flags)
if wrap_width <= 0.0 and text_begin == 1 and type(text) == "string" and out_offset == nil and max_width >= FLT_MAX
and (flags == nil or band(flags, ImDrawTextFlags.StopOnNewLine) == 0) then
local baked = font.LastBaked
if baked and baked.Size == floor(size + 0.5) and baked.RasterizerDensity == font.CurrentRasterizerDensity then
local cache = baked._TextSizeCache
if cache ~= nil and baked._TextSizeCacheN < TEXT_SIZE_CACHE_MAX then
local e = cache[text]
if e then
local text_len1 = string.len(text) + 1
if (text_end == nil or text_end == text_len1) and (text_end_display == nil or text_end_display == text_len1) then
return e[1] * (size / baked.Size), e[2] * size, text_len1
end
end
end
end
end
return CalcTextSizeXY_Orig(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags)
end
------------------------------------------------------------------------------------------------------------------------
-- name -> function(on) installing the patch or restoring the original
local Install = {
RenderText = function(on) MT.ImFont.RenderText = on and RenderText or RenderText_Orig end,
AddText = function(on) MT.ImDrawList.AddText = on and AddText or AddText_Orig end,
CalcTextSize = function(on) ImFontCalcTextSizeXY = on and CalcTextSizeXY or CalcTextSizeXY_Orig end,
}
-- Switches a patch at run time (tests time both versions in one process)
function M.Set(name: string, on: boolean)
Install[name](on)
end
for name in Install do
M.Set(name, M.Enabled[name])
end
return M
+503 -144
View File
@@ -2,7 +2,7 @@
-- Target: RGBA8 row-major (ImU32 is already R | G<<8 | B<<16 | A<<24), non-premultiplied "over" onto transparent.
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local readf64 = buffer.readf64
local readf64, writef64 = buffer.readf64, buffer.writef64
local band, rshift = bit32.band, bit32.rshift
local readi32 = buffer.readi32
@@ -17,7 +17,22 @@ local M = {
}
local TILE = M.TILE
local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0
-- Pixel (x, y) of the target is at byte (y * TargetWidth + x) * 4 + TargetBase: a target can be a sub-rectangle of the
-- tile (raster straight into the upload buffer)
local TargetBuffer: buffer, TargetWidth, TargetBase = buffer.create(0), 0, 0
-- Solid spans are written two pixels per writef64 (a write costs about the same at either width): the f64 whose bytes
-- are the pixel twice. Only for a normal double (exponent field not 0 or all ones), which every load and store keeps
-- bit for bit; else PairF64 returns false and spans are written per pixel.
local PairScratch = buffer.create(8)
@native
local function PairF64(v: number): number | false
local e = band(rshift(v, 20), 2047)
if e == 0 or e == 2047 then return false end
writeu32(PairScratch, 0, v)
writeu32(PairScratch, 4, v)
return readf64(PairScratch, 0)
end
local PrevRow = buffer.create(1024)
-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else
@@ -39,33 +54,50 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean
return false
end
local RectColumns = table.create(256, 0)
-- DrawRect's per-alpha blend cache: GlyphKey[alpha] = GlyphGen + destination value -> GlyphValue[alpha]. GlyphGen
-- (a multiple of 2^32) changes with the vertex colour.
local GlyphKey, GlyphValue = table.create(256, -1), table.create(256, 0)
GlyphKey[0], GlyphValue[0] = -1, 0
local GlyphCol, GlyphGen = -1, 0
-- Uniform region: [UX0, UX1) x [UY0, UY1) of the target holds only the pixel value UV (empty when UX0 >= UX1).
-- Set by ClearRect and by solid rects; shrunk by everything drawn over it. A solid rect inside it blends one pixel and
-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel.
local UX0, UY0, UX1, UY1, UV = 0, 0, 0, 0, 0
-- Uniform rows: [RowX0[y], RowX1[y]) of target row y holds only the pixel value RowV[y] (empty when RowX0 >= RowX1).
-- Set by ClearRect and by solid spans; shrunk by everything drawn over it. A solid span inside it blends one pixel and
-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. Only the rows of the last
-- ClearRect are valid: drawing must stay inside it (callers clip every primitive to the cleared rect).
local RowX0, RowX1, RowV = table.create(TILE, 0), table.create(TILE, 0), table.create(TILE, 0)
RowX0[0], RowX1[0], RowV[0] = 0, 0, 0
-- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece outside it
-- Drawing changed [x0, x1) x [y0, y1): keep the larger uniform piece of each row outside it
@native
local function Shrink(x0: number, y0: number, x1: number, y1: number)
if x0 >= UX1 or x1 <= UX0 or y0 >= UY1 or y1 <= UY0 or UX0 >= UX1 then return end
local h, w = UY1 - UY0, UX1 - UX0
local left, right, top, bottom = (x0 - UX0) * h, (UX1 - x1) * h, (y0 - UY0) * w, (UY1 - y1) * w
local best = max(left, right, top, bottom)
if best <= 0 then
UX1 = UX0
elseif best == left then
UX1 = x0
elseif best == right then
UX0 = x1
elseif best == top then
UY1 = y0
else
UY0 = y1
local function ApplyDamage(x0: number, y0: number, x1: number, y1: number)
for y = y0, y1 - 1 do
local a, b = RowX0[y], RowX1[y]
if x0 < b and x1 > a then
if x0 - a >= b - x1 then RowX1[y] = x0 else RowX0[y] = x1 end
end
end
end
-- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync.
-- Only FillSpan reads the uniform rows: damage is collected into one pending rect (nearby rects merged: a text line's
-- glyphs, a shape's triangles) and applied when FillSpan runs. Over-shrinking only loses uniform pixels.
local PX0, PY0, PX1, PY1 = 0, 0, 0, 0 -- pending damage (none when PX0 >= PX1)
@native
local function Shrink(x0: number, y0: number, x1: number, y1: number)
if PX0 >= PX1 then
PX0, PY0, PX1, PY1 = x0, y0, x1, y1
return
end
local ux0, uy0, ux1, uy1 = min(x0, PX0), min(y0, PY0), max(x1, PX1), max(y1, PY1)
if (ux1 - ux0) * (uy1 - uy0) <= ((x1 - x0) * (y1 - y0) + (PX1 - PX0) * (PY1 - PY0)) * 1.25 + 256 then
PX0, PY0, PX1, PY1 = ux0, uy0, ux1, uy1
return
end
ApplyDamage(PX0, PY0, PX1, PY1)
PX0, PY0, PX1, PY1 = x0, y0, x1, y1
end
-- The blend, for reference: every rasterizer loop inlines this math (a call per pixel costs more than the blend), the
-- span paths with per-span constants: keep them in sync. Not called.
@native
local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number)
if a >= 255 then
@@ -95,57 +127,177 @@ local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number,
end
end
-- Wide spans (>= 32 px) over non-uniform rows: rows usually blend over identical rows, so a row whose destination
-- repeats the previous one's copies its result
@native
local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number,
b: number, a: number)
if a <= 0 then return end
local w4 = (x1 - x0 - 1) * 4
if x0 >= UX0 and y0 >= UY0 and x1 <= UX1 and y1 <= UY1 and a < 255 then
-- over one value: FillSpan's per-pixel result for d = UV, then fill
local d, v = UV, 0
if d < 16777216 then
v = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216
else
local sa = a / 255
local ns = 1 - sa
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
v = floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256
+ floor(b * sa + db * ns + 0.5) * 65536 + 4278190080
else
local k = rshift(d, 24) * (ns / 255)
local oa = sa + k
local inv = 1 / oa
v = floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256
+ floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
end
local first = (y0 * TargetWidth + x0) * 4
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, v) end
for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end
UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, v
return
if PX0 < PX1 then
ApplyDamage(PX0, PY0, PX1, PY1)
PX1 = PX0
end
local w4 = (x1 - x0 - 1) * 4
local span = x1 - x0
if a >= 255 then
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local first = (y0 * TargetWidth + x0) * 4
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end
for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end
-- now uniform: keep whichever region is larger
local area = (x1 - x0) * (y1 - y0)
Shrink(x0, y0, x1, y1)
if area > (UX1 - UX0) * (UY1 - UY0) or UX0 >= UX1 then UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, packed end
local first = (y0 * TargetWidth + x0) * 4 + TargetBase
local pair = span >= 16 and PairF64(packed)
if pair then
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)
local y = y0
while y < y1 do
local ra, rb = RowX0[y], RowX1[y]
local na, nb = ra, rb
if x0 < rb and x1 > ra then
if x0 - ra >= rb - x1 then nb = x0 else na = x1 end
end
if span > nb - na then
repeat
RowX0[y], RowX1[y], RowV[y] = x0, x1, packed
y += 1
until y >= y1 or RowX0[y] ~= ra or RowX1[y] ~= rb
else
repeat
RowX0[y], RowX1[y] = na, nb
y += 1
until y >= y1 or RowX0[y] ~= ra or RowX1[y] ~= rb
end
end
return
end
Shrink(x0, y0, x1, y1)
local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216
local sa = a / 255
local ns = 1 - sa
local c1 = ns / 255
local rs, gs, bs = r * sa, g * sa, b * sa
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
for y = y0, y1 - 1 do
local o0 = (y * TargetWidth + x0) * 4
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 y = y0
while y < y1 do
local o0 = (y * TargetWidth + x0) * 4 + TargetBase
local ra, rb = RowX0[y], RowX1[y]
if x0 >= ra and x1 <= rb then
-- over one value: the per-pixel result for d = RowV[y], then fill; following rows with the same uniform
-- piece get the same result
local d = RowV[y]
if d ~= last_d then
last_d = d
if d < 16777216 then
last_v = packed0
else
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
end
end
local v = last_v
if v == prev_v and span > 8 then -- (a call: slower than a few writes)
buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4)
else
local pair = 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
local na, nb, nv = ra, rb, d
if span >= x0 - ra and span >= rb - x1 then
na, nb, nv = x0, x1, v
elseif x0 - ra >= rb - x1 then
nb = x0
else
na = x1
end
RowX0[y], RowX1[y], RowV[y] = na, nb, nv
y += 1
local stride = TargetWidth * 4
local o = o0
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
y += 1
end
prev_o, prev_v, has_prev = o, v, false
continue
end
if x0 < rb and x1 > ra then
if x0 - ra >= rb - x1 then RowX1[y] = x0 else RowX0[y] = x1 end
end
if wide then
local repeats = RowRepeats(o0, w4 + 4, has_prev)
has_prev = true
if repeats then
buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4)
prev_o, prev_v = o0, -1
y += 1
continue
end
end
prev_o, prev_v = o0, -1
if black then
-- (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
local d = readu32(TargetBuffer, o)
if d ~= last_d then
last_d = d
if d >= 4278190080 then
last_v = 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
elseif d < 16777216 then
last_v = packed0
else
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
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
end
writeu32(TargetBuffer, o, last_v)
end
y += 1
continue
end
for o = o0, o0 + w4, 4 do
local d = readu32(TargetBuffer, o)
if d == last_d then
@@ -168,6 +320,7 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
writeu32(TargetBuffer, o, last_v)
end
end
y += 1
end
end
@@ -202,23 +355,7 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
end
if a <= 0 then return end
if a >= 255 or px1 - px0 < 32 or (px0 >= UX0 and py0 >= UY0 and px1 <= UX1 and py1 <= UY1) then
FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a)
return
end
-- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result
Shrink(px0, py0, px1, py1)
local len = (px1 - px0) * 4
local prev_o = 0
for y = py0, py1 - 1 do
local o = (y * TargetWidth + px0) * 4
if RowRepeats(o, len, y > py0) then
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
else
FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a)
end
prev_o = o
end
FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a)
return
end
@@ -230,18 +367,31 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
local cols = RectColumns
local ident = col == 4294967295
local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0
local step = true
for c = 1, ncol do
local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
cols[c] = tx * 4
if c > 1 and tx * 4 ~= cols[c - 1] + 4 then step = false end
end
-- white translucent texels (font atlas): blend result cached per alpha for one destination value and colour
if col ~= GlyphCol then
GlyphCol = col
GlyphGen += 4294967296
if GlyphGen >= 4503599627370496 then -- 2^52: keys must stay exact
GlyphGen = 4294967296
for k = 0, 255 do GlyphKey[k] = -1 end
end
end
local gen = GlyphGen
for y = py0, py1 - 1 do
local ty = floor((v0 + (y + 0.5 - y0) * dv) * th)
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local trow4 = ty * tw * 4
local o = (y * TargetWidth + px0) * 4
local o = (y * TargetWidth + px0) * 4 + TargetBase
local tb0 = trow4 + cols[1] - 4
for c = 1, ncol do
local tv = readu32(tbuf, trow4 + cols[c])
local tv = readu32(tbuf, step and tb0 + c * 4 or trow4 + cols[c])
if tv < 16777216 then
o += 4
continue
@@ -251,6 +401,17 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
o += 4
continue
end
local d, key, al = 0, -1, 0
if tv % 16777216 == 16777215 then
al = rshift(tv, 24)
d = readu32(dbuf, o)
key = gen + d
if GlyphKey[al] == key then
writeu32(dbuf, o, GlyphValue[al])
o += 4
continue
end
end
-- BlendPixel inlined (same math)
if tv ~= last_tv then
last_tv = tv
@@ -261,27 +422,35 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
fn = 1 - fa
fk = (1 - fa) / 255
end
local v = -1
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
v = s_opaque + 4278190080
elseif sa > 0 then
local d = readu32(dbuf, o)
if key < 0 then d = readu32(dbuf, o) end
if d < 16777216 then
writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216)
v = s_opaque + floor(sa + 0.5) * 16777216
else
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256
+ floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080)
v = floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256
+ floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080
else
local k = rshift(d, 24) * fk
local oa = fa + k
local inv = 1 / oa
writeu32(dbuf, o, floor((sr * fa + dr * k) * inv + 0.5)
+ floor((sg * fa + dg * k) * inv + 0.5) * 256
+ floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
v = floor((sr * fa + dr * k) * inv + 0.5) + floor((sg * fa + dg * k) * inv + 0.5) * 256
+ floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
end
end
if v >= 0 then
writeu32(dbuf, o, v)
elseif key >= 0 then
v = d -- unchanged
end
if key >= 0 then
GlyphKey[al], GlyphValue[al] = key, v
end
o += 4
end
end
@@ -318,39 +487,54 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local inv = 1 / area
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 ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32))
local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32))
local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32))
-- 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 ra, ga, ba, aa = ca % 256, floor(ca / 256) % 256, floor(ca / 65536) % 256, floor(ca / 16777216) % 256
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 cc ~= ca then rc, gc, bc, ac = cc % 256, floor(cc / 256) % 256, floor(cc / 65536) % 256, floor(cc / 16777216) % 256 end
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)
local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc)
if t and not textured then -- constant uv (atlas white pixel): fold the texel into the vertex colours
local tr, tg, tb, ta = SampleTexture(t, ua, vva)
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255
local tw0, th0 = t.Width, t.Height
local tx, ty = floor(ua * tw0), floor(vva * 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 -- (a white texel changes nothing: c * 255 / 255 is c)
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
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255
end
end
local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab
and aa == ac
if flat and aa <= 0 then return end
local f_opaque, f_packed, f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = false, 0, 0, 0, 0, 0, 0, 0
local f_pair: number | false = false
if flat then
f_opaque = aa >= 255
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)
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
if f_opaque then f_pair = PairF64(f_packed) end
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
end
local cconst = textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab
and aa == ac
if cconst and aa <= 0 then return end
local tw: number, th: number, tbuf: buffer = 0, 0, dbuf
local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255
local r255, g255, b255, a255 = 0, 0, 0, 0
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
if cconst then tw, th, tbuf = t.Width, t.Height, t.Buffer end
if textured then tw, th, tbuf = t.Width, t.Height, t.Buffer end
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
@@ -381,11 +565,36 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
yb -= 1
end
if yt > yb then continue end
local o = (yt * TargetWidth + x) * 4
local o = (yt * TargetWidth + x) * 4 + TargetBase
if flat then
for _ = yt, yb do
BlendPixel(dbuf, o, ra, ga, ba, aa)
o += stride
-- the row path's flat spans (BlendPixel's math, per-span constants, cached per destination value)
local o1 = o + (yb - yt) * stride
if f_opaque then
for oo = o, o1, stride do writeu32(dbuf, oo, f_packed) end
continue
end
local last_d, last_v = -1, 0
for oo = o, o1, stride 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 k = rshift(d, 24) * f_c1
local oa = f_sa + k
local inv2 = 1 / oa
last_v = floor((f_rs + dr * k) * inv2 + 0.5) + floor((f_gs + dg * k) * inv2 + 0.5) * 256
+ floor((f_bs + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(dbuf, oo, last_v)
end
end
continue
end
@@ -395,7 +604,32 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
(A2 * px + (B2 * py + C2)) * inv
local a = w0 * aa + w1 * ab + w2 * ac
if a > 0 then
BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, w0 * ba + w1 * bb + w2 * bc, a)
-- BlendPixel inlined (same math; a call per pixel costs more than the blend)
local r, g, b = w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, w0 * ba + w1 * bb + w2 * bc
if a >= 255 then
writeu32(dbuf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080)
else
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536
+ floor(a + 0.5) * 16777216)
else
local sa = a / 255
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
local ns = 1 - sa
writeu32(dbuf, o, floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256
+ floor(b * sa + db * ns + 0.5) * 65536 + 4278190080)
else
local k = rshift(d, 24) * ((1 - sa) / 255)
local oa = sa + k
local inv2 = 1 / oa
writeu32(dbuf, o, floor((r * sa + dr * k) * inv2 + 0.5)
+ floor((g * sa + dg * k) * inv2 + 0.5) * 256
+ floor((b * sa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
end
o += stride
end
@@ -424,6 +658,10 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
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
-- 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.
if xl > minx and xl <= xr then xl += 1 end
while xl <= xr do
local px = xl + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
@@ -432,6 +670,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end
xl += 1
end
if xr < maxx and xr > xl then xr -= 1 end
while xr > xl do
local px = xr + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
@@ -441,11 +680,19 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
xr -= 1
end
if xl > xr then continue end
local o = (y * TargetWidth + xl) * 4
local o = (y * TargetWidth + xl) * 4 + TargetBase
if flat then
local o1 = o + (xr - xl) * 4
if f_opaque then
for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end
if f_pair then
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
end
local last_d, last_v = -1, 0
@@ -521,15 +768,48 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local px = x + 0.5
local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv
local a = w0 * aa + w1 * ab + w2 * ac
local r, g, b = 0, 0, 0
if textured then
local r = w0 * ra + w1 * rb + w2 * rc
local g = w0 * ga + w1 * gb + w2 * gc
local b = w0 * ba + w1 * bb + w2 * bc
local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc)
BlendPixel(dbuf, o, r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255)
r = w0 * ra + w1 * rb + w2 * rc
g = w0 * ga + w1 * gb + w2 * gc
b = w0 * ba + w1 * bb + w2 * bc
-- SampleTexture inlined
local tx, ty = floor((w0 * ua + w1 * ub + w2 * uc) * tw), floor((w0 * vva + w1 * vvb + w2 * vvc) * th)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local to = (ty * tw + tx) * 4
r, g, b, a = r * readu8(tbuf, to) / 255, g * readu8(tbuf, to + 1) / 255, b * readu8(tbuf, to + 2) / 255,
a * readu8(tbuf, to + 3) / 255
elseif a > 0 then
BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc,
w0 * ba + w1 * bb + w2 * bc, a)
r, g, b = w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, w0 * ba + w1 * bb + w2 * bc
else
o += 4
continue
end
-- BlendPixel inlined (same math; a call per pixel costs more than the blend)
if a >= 255 then
writeu32(dbuf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080)
elseif not (a <= 0) then
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536
+ floor(a + 0.5) * 16777216)
else
local sa = a / 255
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
local ns = 1 - sa
writeu32(dbuf, o, floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256
+ floor(b * sa + db * ns + 0.5) * 65536 + 4278190080)
else
local k = rshift(d, 24) * ((1 - sa) / 255)
local oa = sa + k
local inv2 = 1 / oa
writeu32(dbuf, o, floor((r * sa + dr * k) * inv2 + 0.5)
+ floor((g * sa + dg * k) * inv2 + 0.5) * 256
+ floor((b * sa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
o += 4
end
@@ -552,6 +832,12 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
DrawTriangle(dbuf, vbuf, va, vc, vd, t, cx0, cy0, cx1, cy1, ox, oy)
return
end
local minx, maxx = max(floor(min(x0, x1, x2, x3)), cx0), min(ceil(max(x0, x1, x2, x3)), cx1 - 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
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
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)
-- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P
local px_, py_, qx_, qy_ = x1, y1, x3, y3 -- b, d
@@ -581,13 +867,16 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
WA, WB, WC = WA * winv, WB * winv, WC * winv
local du, dv = uc - ua, vvc - vva
local minx, maxx = max(floor(min(x0, x1, x2, x3)), cx0), min(ceil(max(x0, x1, x2, x3)), cx1 - 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
local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32))
if aa <= 0 then return end
Shrink(minx, miny, maxx + 1, maxy + 1)
local tw: number, th: number, tbuf: buffer = t.Width, t.Height, t.Buffer
-- v constant across the line (ImGui's line texture: u across, one row per width): the texel row is fixed
-- (vva + w * 0 is vva)
local trow = -1
if dv == 0 then
local ty = floor(vva * th)
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
trow = ty * tw * 4
end
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
for y = miny, maxy do
@@ -598,6 +887,7 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
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
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)
while xl <= xr do
local px = xl + 0.5
local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3
@@ -607,6 +897,7 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end
xl += 1
end
if xr < maxx and xr > xl then xr -= 1 end
while xr > xl do
local px = xr + 0.5
local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3
@@ -617,14 +908,20 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
xr -= 1
end
if xl > xr then continue end
local o = (y * TargetWidth + xl) * 4
local o = (y * TargetWidth + xl) * 4 + TargetBase
local wrow = WB * py + WC
for x = xl, xr do
local w = WA * (x + 0.5) + wrow
local tx, ty = floor((ua + w * du) * tw), floor((vva + w * dv) * th)
local tx = floor((ua + w * du) * tw)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local tv = readu32(tbuf, (ty * tw + tx) * 4)
local tv
if trow >= 0 then
tv = readu32(tbuf, trow + tx * 4)
else
local ty = floor((vva + w * dv) * th)
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
tv = readu32(tbuf, (ty * tw + tx) * 4)
end
if tv ~= last_tv then
last_tv = tv
sa = rshift(tv, 24) * a255
@@ -690,7 +987,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1
local opaque = aa >= 255 and ab >= 255
local prev_o = 0
for y = py0, py1 - 1 do
local o = (y * TargetWidth + px0) * 4
local o = (y * TargetWidth + px0) * 4 + TargetBase
if y > py0 and (opaque or RowRepeats(o, len, true))
or (y == py0 and not opaque and RowRepeats(o, len, false)) then
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
@@ -699,7 +996,34 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1
for x = px0, px1 - 1 do
local f = (x + 0.5 - x0) * inv
local nf = 1 - f
BlendPixel(TargetBuffer, oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f)
local r, g, b, a = ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f
-- BlendPixel inlined (same math)
if a >= 255 then
writeu32(TargetBuffer, oo, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536
+ 4278190080)
elseif not (a <= 0) then
local d = readu32(TargetBuffer, oo)
if d < 16777216 then
writeu32(TargetBuffer, oo, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536
+ floor(a + 0.5) * 16777216)
else
local sa = a / 255
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
local ns = 1 - sa
writeu32(TargetBuffer, oo, floor(r * sa + dr * ns + 0.5)
+ floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536
+ 4278190080)
else
local k = rshift(d, 24) * ((1 - sa) / 255)
local oa = sa + k
local inv2 = 1 / oa
writeu32(TargetBuffer, oo, floor((r * sa + dr * k) * inv2 + 0.5)
+ floor((g * sa + dg * k) * inv2 + 0.5) * 256
+ floor((b * sa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
oo = oo + 4
end
end
@@ -708,26 +1032,20 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1
end
end
function M.SetTarget(buf: buffer, width: number)
TargetBuffer, TargetWidth = buf, width
UX1 = UX0
-- x0 y0: target pixel stored at buf's byte 0 (a sub-rectangle target: width = its width)
function M.SetTarget(buf: buffer, width: number, x0: number?, y0: number?)
TargetBuffer, TargetWidth, TargetBase = buf, width, -((y0 or 0) * width + (x0 or 0)) * 4
end
@native
function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number)
local rw = rx1 - rx0
UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0
for y = ry0, ry1 - 1 do RowX0[y], RowX1[y], RowV[y] = rx0, rx1, 0 end
PX1 = PX0
if rw == TargetWidth then
buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4)
buffer.fill(TargetBuffer, (ry0 * TargetWidth + rx0) * 4 + TargetBase, 0, (ry1 - ry0) * TargetWidth * 4)
else
for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end
end
end
@native
function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number)
for y = 0, rh - 1 do
buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4)
for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4 + TargetBase, 0, rw * 4) end
end
end
@@ -754,13 +1072,12 @@ local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, v
end
M.DrawPrim = DrawPrim
-- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback)
local Scratch = buffer.create(TILE * TILE * 4)
-- Packed tile jobs -> one exact-size buffer per rect (rasterized straight into it), in job order (worker + main-thread
-- fallback)
@native
function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect
local ClearRect, SetTarget = M.ClearRect, M.SetTarget
local REC_A, REC_B, REC_C, REC_D = M.REC_A, M.REC_B, M.REC_C, M.REC_D
M.SetTarget(Scratch, TILE)
local out, no = {}, 0
local o = 0
while o < tlen do
@@ -772,6 +1089,9 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
for r = 0, nr - 1 do
local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4),
readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12)
local rw, rh = rx1 - rx0, ry1 - ry0
local sub = buffer.create(rw * rh * 4)
SetTarget(sub, rw, rx0, ry0)
ClearRect(rx0, ry0, rx1, ry1)
for k = 0, count - 1 do
local q = readi32(T, po + k * 4)
@@ -785,9 +1105,6 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
if tid >= 0 then t = textures[tid] end
DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1)
end
local rw, rh = rx1 - rx0, ry1 - ry0
local sub = buffer.create(rw * rh * 4)
CopySubRect(sub, rx0, ry0, rw, rh)
no += 1
out[no] = sub
end
@@ -795,4 +1112,46 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
return out
end
-- An Actor's texture copies (worker.luau; parallel.lua's Sync mode emulates it): drop the destroyed ids, apply the
-- updates parallel.lua's Flush sent. { id, buf, w, h, fill }: whole texture, rows past buf are all fill;
-- { id, false, w, h, offset, patch }: rows; { id, false, w, h, rects, patch }: x, y, w, h quadruples, rows packed.
function M.ApplyTextures(textures, updates, dropped)
for _, id in dropped or {} do
textures[id] = nil
end
for _, u in updates do
if u[2] then
local b, w, h, fill = u[2], u[3], u[4], u[5]
local n, total = buffer.len(b), w * h * 4
if n < total then
local full = buffer.create(total)
buffer.copy(full, 0, b)
if fill ~= 0 then
buffer.writeu32(full, n, fill)
local k = 4
while k < total - n do
local c = math.min(k, total - n - k)
buffer.copy(full, n + k, full, n, c)
k += c
end
end
b = full
end
textures[u[1]] = { Buffer = b, Width = w, Height = h }
elseif type(u[5]) == "table" then
local t, rects, patch = textures[u[1]], u[5], u[6]
local dst, w, o = t.Buffer, t.Width, 0
for i = 1, #rects, 4 do
local x, y, rw, rh = rects[i], rects[i + 1], rects[i + 2], rects[i + 3]
for yy = y, y + rh - 1 do
buffer.copy(dst, (yy * w + x) * 4, patch, o, rw * 4)
o += rw * 4
end
end
else
buffer.copy(textures[u[1]].Buffer, u[5], u[6])
end
end
end
return M
+381 -175
View File
@@ -6,14 +6,14 @@ local Overlays = IM_INCLUDE("roblox/overlays.lua")
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
local readu32, readf64 = buffer.readu32, buffer.readf64
local SetTarget, ClearRect, DrawPrim, CopySubRect = Raster.SetTarget, Raster.ClearRect, Raster.DrawPrim,
Raster.CopySubRect
local SetTarget, ClearRect, DrawPrim = Raster.SetTarget, Raster.ClearRect, Raster.DrawPrim
local TILE = Raster.TILE
local TILE_SIZE = Vector2.new(TILE, TILE)
local EditableImages, PB, PE, GetBackendData, UpdateTexture = Textures.EditableImages, Textures.PB, Textures.PE,
Textures.GetBackendData, Textures.UpdateTexture
local GetLayer, HideLayer, GetTile, DestroyLayerSet, Snapshot, CompareDrawList, ShiftLayer = Layers.GetLayer,
Layers.HideLayer, Layers.GetTile, Layers.DestroyLayerSet, Layers.Snapshot, Layers.CompareDrawList, Layers.ShiftLayer
local ShiftSnapshot = Layers.ShiftSnapshot
local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = Layers.CmdUnclipped, Layers.CmdKind,
Layers.CmdBoundsX0, Layers.CmdBoundsY0, Layers.CmdBoundsX1, Layers.CmdBoundsY1
local CLIP_PAD = Layers.CLIP_PAD
@@ -31,8 +31,12 @@ local MAX_DEFER_FRAMES = 8 -- a changed tile is redrawn at the latest this many
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = {}, {}, {}, {}, {}, {}
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = {}, {}, {}, {}
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = {}, {}, {}, {}
local PrimTexId, PrimVtxBuffer, PrimKind = {}, {}, {}
local PrimTexId, PrimVtxBuffer = {}, {}
-- flat rect (one colour, one uv or untextured): HashTiles hashes its clipped rect per tile
local PrimFlat = {}
-- 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 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.PrimTexture, M.PrimGradient = PrimTexture, PrimGradient
M.PrimClipX0, M.PrimClipY0, M.PrimClipX1, M.PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1
@@ -67,16 +71,13 @@ function EditableImages.AddRect(n: number, a: number, b: number, c: number, d: n
return n
end
@native
local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: number, oy: number)
local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy
local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24)
local c = readu32(vbuf, v + 32)
-- one % per hash: h < 2^31, so h * 48271 + the 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
h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2
return h1, h2
end
-- Primitives with a vertex CompareDrawList found drifted (DriftSet[vertex offset // VTX_STRIDE + 1], current draw list):
-- 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
-- HashTiles scratch, per touched tile (slot = its index in layer.Touched): tile key -> slot, its list, count, hashes
local KeySlot, SlotCount, SlotHash1, SlotHash2 = {}, {}, {}, {}
local SlotList, SlotListHash1, SlotListHash2, SlotListFlat = {}, {}, {}, {}
@native
local function HashTiles(layer, plist, np, lx0, ly0, ox, oy)
@@ -85,9 +86,16 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy)
local TileListHash1, TileListHash2, TileListFlat = layer.TileListHash1, layer.TileListHash2, layer.TileListFlat
for k = 1, layer.TouchedCount do TileCounts[Touched[k]] = 0 end
local TouchedCount = 0
local CurKey, CurCount, CurHash1, CurHash2, CurList, CurListHash1, CurListHash2, CurListFlat =
nil, 0, 0, 0, nil, nil, nil, nil
local CurKey, CurSlot, CurCount, CurHash1, CurHash2, CurList, CurListHash1, CurListHash2, CurListFlat =
-1, 0, 0, 0, 0, nil, nil, nil, nil
local TileXs, TileYs = layer.TileX, layer.TileY
-- upvalues as locals: cheaper in the hot loop
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1
local PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat =
PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat
local KeySlot, SlotCount, SlotHash1, SlotHash2 = KeySlot, SlotCount, SlotHash1, SlotHash2
local SlotList, SlotListHash1, SlotListHash2, SlotListFlat = SlotList, SlotListHash1, SlotListHash2, SlotListFlat
local TILE = TILE
for pi = 1, np do
local p = plist[pi]
local tex_id = PrimTexId[p]
@@ -97,92 +105,118 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy)
local vbuf = PrimVtxBuffer[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
local FlatRect, RectColor, RectUV = false, 0, 0
if vd and not PrimGradient[p] then
local u0, v0 = readf64(vbuf, va + 16), readf64(vbuf, va + 24)
local vc = PrimC[p]
if not PrimTexture[p] or (u0 == readf64(vbuf, vc + 16) and v0 == readf64(vbuf, vc + 24)) then
FlatRect, RectColor, RectUV = true, readu32(vbuf, va + 32), u0 * 8192 + v0
end
local FlatRect, RectColor, RectUV = PrimFlat[p], 0, 0
if FlatRect then
RectColor, RectUV = readu32(vbuf, va + 32), readf64(vbuf, va + 16) * 8192 + readf64(vbuf, va + 24)
end
local h1, h2 = 0, 0
local FlatSig = -1
if FlatRect then FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1 end
if not FlatRect then
if FlatRect then
FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1
else
h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1
h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2
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);
-- line quad (any shape) a, c, b, d. The kind is mixed in after the second vertex.
local gk, v2, v3, nv = PrimGradient[p], PrimC[p], PrimB[p], 3
if vd then
-- axis aligned quad: CollectPrims checked that TR/BL follow from TL/BR (+ kind)
h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay)
h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay)
local gk = PrimGradient[p]
if gk then
nv = gk == 3 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
-- inlined (a call per vertex costs more than the hash): one % per hash, h < 2^31, so h * 48271 + the
-- terms (|x|, |y| < 2^15, uv < 2^14, c < 2^32) stays below 2^53
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
if k == 2 and gk then
h1 = (h1 * 48271 + gk) % P1
h2 = (h2 * 16807 + gk * 3) % P2
end
if gk == 3 then -- line quad: any shape
h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay)
h1, h2 = HashVertex(h1, h2, vbuf, vd, vax, vay)
end
else
h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay)
h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay)
h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay)
end
if DriftOn and (DriftSet[va // VTX_STRIDE + 1] or DriftSet[PrimB[p] // VTX_STRIDE + 1]
or DriftSet[PrimC[p] // VTX_STRIDE + 1] or (vd and DriftSet[vd // VTX_STRIDE + 1])) then
h1 = (h1 + DriftMark1) % P1
h2 = (h2 + DriftMark2) % P2
end
end
for ty = floor((PrimBoundsY0[p] - ly0) / TILE), floor((PrimBoundsY1[p] - 1 - ly0) / TILE) do
for tx = floor((PrimBoundsX0[p] - lx0) / TILE), floor((PrimBoundsX1[p] - 1 - lx0) / TILE) do
if FlatRect then
local tx0, ty0 = tx * TILE, ty * TILE
local ix0, iy0 = max(cx0 - tx0, 0), max(cy0 - ty0, 0)
local ix1, iy1 = min(cx1 - tx0, TILE), min(cy1 - ty0, TILE)
local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1
h1 = ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1
h2 = ((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2
-- the tiles it touches, row by row (one loop, no nested for: most primitives touch one tile; never empty)
local tx0, tx1, ty1 = cx0 // TILE, (cx1 - 1) // TILE, (cy1 - 1) // TILE
local tx, ty = tx0, cy0 // TILE
while true do
if FlatRect then
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
h1 = ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1
h2 = ((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2
end
-- unique for |tx|, |ty| < 32768 (content tiles go negative)
local key = (ty + 32768) * 65536 + tx + 32768
if key ~= CurKey then
-- consecutive primitives often alternate between tiles: the tile's state is in slot arrays
if CurSlot > 0 then
SlotCount[CurSlot], SlotHash1[CurSlot], SlotHash2[CurSlot] = CurCount, CurHash1, CurHash2
end
-- unique for |tx|, |ty| < 32768 (content tiles go negative)
local key = (ty + 32768) * 65536 + tx + 32768
if key ~= CurKey then
if CurKey then
TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2
end
CurKey = key
CurCount = TileCounts[key]
if not CurCount or CurCount == 0 then
CurCount, CurHash1, CurHash2 = 0, 0, 0
if not TileLists[key] then
local ListPool = EditableImages.ListPool
local m = #ListPool
if m >= 4 then
TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] =
ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m]
ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] = nil, nil, nil, nil
else
TileLists[key] = {}
TileListHash1[key] = {}
TileListHash2[key] = {}
TileListFlat[key] = {}
end
CurKey = key
local slot = KeySlot[key]
if slot then
CurCount, CurHash1, CurHash2 = SlotCount[slot], SlotHash1[slot], SlotHash2[slot]
else
if not TileLists[key] then
local ListPool = EditableImages.ListPool
local m = #ListPool
if m >= 4 then
TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] =
ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m]
ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] = nil, nil, nil, nil
else
TileLists[key] = {}
TileListHash1[key] = {}
TileListHash2[key] = {}
TileListFlat[key] = {}
end
TouchedCount = TouchedCount + 1
Touched[TouchedCount] = key
TileXs[key], TileYs[key] = tx, ty
else
CurHash1, CurHash2 = TileHash1[key], TileHash2[key]
end
CurList, CurListHash1, CurListHash2, CurListFlat =
TouchedCount = TouchedCount + 1
slot = TouchedCount
KeySlot[key] = slot
Touched[slot] = key
TileXs[key], TileYs[key] = tx, ty
SlotList[slot], SlotListHash1[slot], SlotListHash2[slot], SlotListFlat[slot] =
TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key]
CurCount, CurHash1, CurHash2 = 0, 0, 0
end
CurCount += 1
CurList[CurCount], CurListHash1[CurCount], CurListHash2[CurCount], CurListFlat[CurCount] =
p, h1, h2, FlatSig
CurHash1 = (CurHash1 * 48271 + h1) % P1
CurHash2 = (CurHash2 * 16807 + h2 + CurCount) % P2
CurSlot = slot
CurList, CurListHash1, CurListHash2, CurListFlat =
SlotList[slot], SlotListHash1[slot], SlotListHash2[slot], SlotListFlat[slot]
end
CurCount += 1
CurList[CurCount], CurListHash1[CurCount], CurListHash2[CurCount], CurListFlat[CurCount] =
p, h1, h2, FlatSig
CurHash1 = (CurHash1 * 48271 + h1) % P1
CurHash2 = (CurHash2 * 16807 + h2 + CurCount) % P2
if tx < tx1 then
tx += 1
elseif ty < ty1 then
tx, ty = tx0, ty + 1
else
break
end
end
end
if CurKey then TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 end
if CurSlot > 0 then SlotCount[CurSlot], SlotHash1[CurSlot], SlotHash2[CurSlot] = CurCount, CurHash1, CurHash2 end
for slot = 1, TouchedCount do
local key = Touched[slot]
TileCounts[key], TileHash1[key], TileHash2[key] = SlotCount[slot], SlotHash1[slot], SlotHash2[slot]
KeySlot[key] = nil
end
layer.TouchedCount = TouchedCount
return TouchedCount
end
@@ -214,6 +248,7 @@ local function PlaceLayer(layer, scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1,
end
end
@native
local function SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1)
local TileCounts, Touched = layer.TileCounts, layer.Touched
-- content layer: only tiles inside its clip frame are kept, so scrolling holds the visible tiles + a few spares
@@ -247,6 +282,9 @@ local function SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, c
end
end
-- the new primitive bounds in the tile (clipped to it); swapped with the tile's Drawn* after a redraw
local NewX0, NewY0, NewX1, NewY1 = {}, {}, {}, {}
@native
local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1)
local qx0, qy0, qx1, qy1 = tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1
@@ -254,17 +292,20 @@ local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0,
local DrawnHash1, DrawnHash2, DrawnX0, DrawnY0, DrawnX1, DrawnY1, DrawnCount =
tile.DrawnHash1, tile.DrawnHash2, tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1,
tile.DrawnCount
local NX0, NY0, NX1, NY1 = NewX0, NewY0, NewX1, NewY1
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1
-- content bounds = the union of the clipped primitive bounds (clipping to the tile commutes with min / max)
local nx0, ny0, nx1, ny1 = TILE, TILE, 0, 0
for k = 1, count do
local p = list[k]
local a, b = PrimBoundsX0[p] - x0, PrimBoundsY0[p] - y0
local c, d = PrimBoundsX1[p] - x0, PrimBoundsY1[p] - y0
local a, b = max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0)
local c, d = min(PrimBoundsX1[p] - x0, TILE), min(PrimBoundsY1[p] - y0, TILE)
NX0[k], NY0[k], NX1[k], NY1[k] = a, b, c, d
if a < nx0 then nx0 = a end
if b < ny0 then ny0 = b end
if c > nx1 then nx1 = c end
if d > ny1 then ny1 = d end
end
nx0, ny0, nx1, ny1 = max(nx0, 0), max(ny0, 0), min(nx1, TILE), min(ny1, TILE)
local DX0, DY0, DX1, DY1, AddRect = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1,
EditableImages.DY1, EditableImages.AddRect
local DirtyCount = 0
@@ -285,11 +326,13 @@ local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0,
local of, lf = tile.DrawnFlat, layer.TileListFlat[key]
local paired = DrawnCount - j - i == count - j - i
for k = i, count - j do
local p = list[k]
local a, b, c, d = max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0),
min(PrimBoundsX1[p] - x0, TILE), min(PrimBoundsY1[p] - y0, TILE)
local a, b, c, d = NX0[k], NY0[k], NX1[k], NY1[k]
local oa, ob, oc, od = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k]
if paired and lf[k] >= 0 and lf[k] == of[k] then
if paired and DrawnHash1[k] == ListHash1[k] and DrawnHash2[k] == ListHash2[k] then
-- same primitive at the same place in both lists: every pixel it covers is either in a changed one's
-- rect or drawn by the same primitives in the same order
continue
elseif paired and lf[k] >= 0 and lf[k] == of[k] then
-- same flat rect, new bounds: only the strips between the old and new edges can differ
local uy0, uy1 = min(b, ob), max(d, od)
local ux0, ux1 = min(a, oa), max(c, oc)
@@ -298,12 +341,21 @@ local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0,
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
DirtyCount = AddRect(DirtyCount, a, b, c, d)
if k <= DrawnCount - j then DirtyCount = AddRect(DirtyCount, oa, ob, oc, od) end
-- (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
DirtyCount = AddRect(DirtyCount, DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k])
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
-- clip D to V, then add the exposed part that isn't valid. cut: part of D inside the valid rect was clipped away
@@ -340,14 +392,12 @@ local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0,
end
tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 = qx0, qy0, qx1, qy1
tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1 = nx0, ny0, nx1, ny1
local DrawnFlat, ListFlat = tile.DrawnFlat, layer.TileListFlat[key]
for k = 1, count do
local p = list[k]
DrawnHash1[k], DrawnHash2[k], DrawnFlat[k] = ListHash1[k], ListHash2[k], ListFlat[k]
DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] =
max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), min(PrimBoundsX1[p] - x0, TILE),
min(PrimBoundsY1[p] - y0, TILE)
end
-- the drawn state is now the tile's list: swap tables instead of copying (HashTiles rewrites the layer's lists)
tile.DrawnHash1, layer.TileListHash1[key] = ListHash1, DrawnHash1
tile.DrawnHash2, layer.TileListHash2[key] = ListHash2, DrawnHash2
tile.DrawnFlat, layer.TileListFlat[key] = layer.TileListFlat[key], tile.DrawnFlat
tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1 = NX0, NY0, NX1, NY1
NewX0, NewY0, NewX1, NewY1 = DrawnX0, DrawnY0, DrawnX1, DrawnY1
tile.DrawnCount = count
return RectCount
end
@@ -357,26 +407,26 @@ local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1)
ClearRect(rx0, ry0, rx1, ry1)
for k = 1, count do
local p = list[k]
local cx0, cy0 = max(PrimClipX0[p] - x0, rx0), max(PrimClipY0[p] - y0, ry0)
local cx1, cy1 = min(PrimClipX1[p] - x0, rx1), min(PrimClipY1[p] - y0, ry1)
if cx0 >= cx1 or cy0 >= cy1 or PrimBoundsX0[p] - x0 >= rx1 or PrimBoundsY0[p] - y0 >= ry1
or PrimBoundsX1[p] - x0 <= rx0 or PrimBoundsY1[p] - y0 <= ry0 then
-- (bounds first: most of a tile's primitives miss a small rect)
if PrimBoundsX0[p] - x0 >= rx1 or PrimBoundsY0[p] - y0 >= ry1 or PrimBoundsX1[p] - x0 <= rx0
or PrimBoundsY1[p] - y0 <= ry0 then
continue
end
local cx0, cy0 = max(PrimClipX0[p] - x0, rx0), max(PrimClipY0[p] - y0, ry0)
local cx1, cy1 = min(PrimClipX1[p] - x0, rx1), min(PrimClipY1[p] - y0, ry1)
if cx0 >= cx1 or cy0 >= cy1 then continue end
local kind, gk = 0, PrimGradient[p]
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)
end
end
-- WritePixelsBuffer needs the exact size: partial upload buffers are reused by size
-- WritePixelsBuffer needs the exact size: a rect is rasterized straight into an upload buffer of its size (reused by
-- size; the whole tile: TileBuffer). One small buffer stays in cache, unlike a 64 KB buffer per tile.
local TileBuffer = buffer.create(TILE * TILE * 4)
local SubBuffers, SubBufferCount = {}, 0
local function UploadRect(img, buf, rx0, ry0, rx1, ry1)
local rw, rh = rx1 - rx0, ry1 - ry0
if rw == TILE and rh == TILE then
img:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf)
return
end
local function RectBuffer(rw, rh)
if rw == TILE and rh == TILE then return TileBuffer end
local sk = rw * 1024 + rh
local sub = SubBuffers[sk]
if not sub then
@@ -388,8 +438,7 @@ local function UploadRect(img, buf, rx0, ry0, rx1, ry1)
SubBuffers[sk] = sub
SubBufferCount += 1
end
CopySubRect(sub, rx0, ry0, rw, rh)
img:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), sub)
return sub
end
local function RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1)
@@ -407,23 +456,30 @@ local function RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy,
Parallel.Tile(tile.Image, list, count, x0, y0, tox, toy, RectCount)
return
end
SetTarget(tile.Buffer, TILE)
local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1
for r = 1, RectCount do
local rx0, ry0, rx1, ry1 = DX0[r], DY0[r], DX1[r], DY1[r]
local rw, rh = rx1 - rx0, ry1 - ry0
local buf = RectBuffer(rw, rh)
SetTarget(buf, rw, rx0, ry0)
RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1)
PB("ImGui upload")
local t_up = Timing and os.clock()
if Timing then
Timing.PixelsRasterized += (rx1 - rx0) * (ry1 - ry0)
Timing.PixelsRasterized += rw * rh
Timing.Uploads += 1
end
UploadRect(tile.Image, tile.Buffer, rx0, ry0, rx1, ry1)
if buf == TileBuffer then
tile.Image:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf)
else
tile.Image:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), buf)
end
if Timing then Timing.Upload += os.clock() - t_up end
PE()
end
end
@native
local function DrawLayer(BackendData, layer, plist, np, lx0, ly0, ox, oy, force, z, clip_x0, clip_y0, clip_x1, clip_y1)
PB("ImGui tile hash")
if EditableImages.StageTiming then EditableImages.BeginStage() end
@@ -533,18 +589,12 @@ local function ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox,
end
end
end
if same == 2 then
Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
set.SnapExtentX0 += sdx
set.SnapExtentY0 += sdy
set.SnapExtentX1 += sdx
set.SnapExtentY1 += sdy
end
if same == 2 then ShiftSnapshot(set, draw_list, sdx, sdy) end
set.LastUsed = BackendData.FrameNo
return PlaceOverlays(BackendData, draw_list, z, ox, oy)
end
-- Collects primitives into Prim* (from n + 1) and commands into Cmd*; returns n, LimitFree and the extents
-- Collects primitives into Prim* (from n + 1), LayerPrims* and commands into Cmd*; returns n, LimitFree and the extents
@native
local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1)
local vbuf, idx = draw_list.VtxBuffer.Buf, draw_list.IdxBuffer.Data
@@ -558,7 +608,15 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
if a < LimitX0 or b < LimitY0 or c > LimitX1 or d > LimitY1 then LimitFree = false end
ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d)
end
-- upvalues as locals: cheaper in the hot loop
local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat =
PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat
local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1
local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1
local LayerPrims1, LayerPrims2, LayerPrims3 = LayerPrims1, LayerPrims2, LayerPrims3
local ci = 0
local c1, c2, c3 = 0, 0, 0
local k1x, k1y, k3x, k3y = math.huge, math.huge, math.huge, math.huge
for _, pcmd in draw_list.CmdBuffer:iter() do
ci += 1
CmdUnclipped[ci], CmdKind[ci] = false, 0
@@ -604,33 +662,23 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
local pbx, pby = readf64(vbuf, vb), readf64(vbuf, vb + 8)
local pcx, pcy = readf64(vbuf, vc), readf64(vbuf, vc + 8)
local bx0, by0, bx1, by1
local flat = false
if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then
local d = (vo + idx[i + 5] - 1) * VTX_STRIDE
local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8)
local col = readu32(vbuf, va + 32)
if t and readu32(vbuf, vb + 32) == col and readu32(vbuf, vc + 32) == col
and readu32(vbuf, d + 32) == col then
-- textured line quad (ImPlot PrimLine): uv a = b, c = d, u a ~= u c (else a textured rect may match)
local tax, tay, tcx, tcy = readf64(vbuf, va + 16), readf64(vbuf, va + 24),
readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
if tax ~= tcx and readf64(vbuf, vb + 16) == tax
and readf64(vbuf, vb + 24) == tay and readf64(vbuf, d + 16) == tcx
and readf64(vbuf, d + 24) == tcy then
vd, gk = d, 3
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
if not vd and pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then
local col, colb, colc, cold = readu32(vbuf, va + 32), readu32(vbuf, vb + 32),
readu32(vbuf, vc + 32), readu32(vbuf, d + 32)
local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24)
local colb, colc, cold = readu32(vbuf, vb + 32), readu32(vbuf, vc + 32), readu32(vbuf, d + 32)
local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24)
local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
-- axis aligned rect, then textured line quad: never both (a rect with one colour has u b = u c,
-- a line quad u a = u b ~= u c), so the order doesn't change the result
if pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then
local tbx, tby = readf64(vbuf, vb + 16), readf64(vbuf, vb + 24)
local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24)
local tdx, tdy = readf64(vbuf, d + 16), readf64(vbuf, d + 24)
if colb == col and colc == col and cold == col then
if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then vd = d end
if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then
vd, flat = d, not t or (tax == tcx and tay == tcy)
end
elseif tax == tbx and tax == tcx and tax == tdx and tay == tby and tay == tcy
and tay == tdy then
if colb == col and cold == colc then
@@ -646,6 +694,15 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
bx1, by1 = ceil(pcx - ox - 0.5), ceil(pcy - oy - 0.5)
end
end
-- textured line quad (ImPlot PrimLine): uv a = b, c = d, u a ~= u c
if not vd and t and colb == col and colc == col and cold == col and tax ~= tcx
and readf64(vbuf, vb + 16) == tax and readf64(vbuf, vb + 24) == tay
and readf64(vbuf, d + 16) == tcx and readf64(vbuf, d + 24) == tcy then
vd, gk = d, 3
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
if vd then
i = i + 6
@@ -654,16 +711,10 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
bx1, by1 = ceil(max(pax, pbx, pcx) - ox) + 1, ceil(max(pay, pby, pcy) - oy) + 1
i = i + 3
end
if bx0 < cx0 or by0 < cy0 or bx1 > cx1 or by1 > cy1 then CmdFree = false end
if bx0 < cex0 then cex0 = bx0 end
if by0 < cey0 then cey0 = by0 end
if bx1 > cex1 then cex1 = bx1 end
if by1 > cey1 then cey1 = by1 end
if bx0 < ex0 then ex0 = bx0 end
if by0 < ey0 then ey0 = by0 end
if bx1 > ex1 then ex1 = bx1 end
if by1 > ey1 then ey1 = by1 end
if bx0 < LimitX0 or by0 < LimitY0 or bx1 > LimitX1 or by1 > LimitY1 then LimitFree = false end
if bx0 < cx0 then bx0 = cx0 end
if by0 < cy0 then by0 = cy0 end
if bx1 > cx1 then bx1 = cx1 end
@@ -674,41 +725,43 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
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
PrimKind[n] = kind
PrimFlat[n] = flat
if kind == 2 then
c2 += 1
LayerPrims2[c2] = n
elseif kind == 1 then
c1 += 1
LayerPrims1[c1] = n
if bx0 < k1x then k1x = bx0 end
if by0 < k1y then k1y = by0 end
else
c3 += 1
LayerPrims3[c3] = n
if bx0 < k3x then k3x = bx0 end
if by0 < k3y then k3y = by0 end
end
end
end
-- per command, from the bounds of all its primitives: one clipped, one past the limits, the extents
if cex0 < cx0 or cey0 < cy0 or cex1 > cx1 or cey1 > cy1 then CmdFree = false end
if cex0 < LimitX0 or cey0 < LimitY0 or cex1 > LimitX1 or cey1 > LimitY1 then LimitFree = false end
if cex0 < ex0 then ex0 = cex0 end
if cey0 < ey0 then ey0 = cey0 end
if cex1 > ex1 then ex1 = cex1 end
if cey1 > ey1 then ey1 = cey1 end
end
if cex0 > cex1 then cex0, cey0, cex1, cey1 = 0, 0, 0, 0 end
CmdUnclipped[ci] = CmdFree
CmdBoundsX0[ci], CmdBoundsY0[ci], CmdBoundsX1[ci], CmdBoundsY1[ci] = cex0, cey0, cex1, cey1
end
end
Kind1Count, Kind2Count, Kind3Count, Kind1X, Kind1Y, Kind3X, Kind3Y = c1, c2, c3, k1x, k1y, k3x, k3y
return n, LimitFree, ex0, ey0, ex1, ey1
end
@native
local function DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1)
local function DrawLists(BackendData, draw_list, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1)
local set = BackendData.Layers[draw_list]
local ListDeferred = false
local Kind1Count, Kind2Count, Kind3Count = 0, 0, 0
local Kind1X, Kind1Y, Kind3X, Kind3Y = math.huge, math.huge, math.huge, math.huge
for p = first, n do
local k = PrimKind[p]
if k == 1 then
Kind1Count += 1
LayerPrims1[Kind1Count] = p
if PrimBoundsX0[p] < Kind1X then Kind1X = PrimBoundsX0[p] end
if PrimBoundsY0[p] < Kind1Y then Kind1Y = PrimBoundsY0[p] end
elseif k == 2 then
Kind2Count += 1
LayerPrims2[Kind2Count] = p
else
Kind3Count += 1
LayerPrims3[Kind3Count] = p
if PrimBoundsX0[p] < Kind3X then Kind3X = PrimBoundsX0[p] end
if PrimBoundsY0[p] < Kind3Y then Kind3Y = PrimBoundsY0[p] end
end
end
if Kind1Count > 0 then
z += 1
if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 1), LayerPrims1, Kind1Count, Kind1X, Kind1Y, ox,
@@ -739,6 +792,132 @@ local function DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, Lim
return z, ListDeferred
end
-- The layer origin of each kind (DrawLists' DrawLayer arguments), from the last CollectPrims
local function LayerOrigin(draw_list, kind, ox, oy)
if kind == 1 then return Kind1X, Kind1Y end
if kind == 3 then return Kind3X, Kind3Y end
return floor(draw_list._ScrollOriginX - ox), floor(draw_list._ScrollOriginY - oy)
end
local PatchLayers, PatchKeys, PatchPrim = {}, {}, {}
-- 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)
-- 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).
@native
local function PatchDrawList(BackendData, set, draw_list, n0, n, dx, dy, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1)
table.clear(PatchPrim)
local SigA, SigD = set.PrimSigA, set.PrimSigD
if not SigA or set.PrimN ~= n - n0 then return false end
for m = 1, n - n0 do
local p = n0 + m
if PrimA[p] ~= SigA[m] or PrimD[p] ~= SigD[m] then return false end
end
local np = 0
for kind = 1, 3 do
local layer = set[kind]
local count = kind == 1 and Kind1Count or kind == 2 and Kind2Count or Kind3Count
if count == 0 then
if layer and layer.Visible then return false end
continue
end
if not (layer and layer.Visible and layer.X) then return false end
local lx0, ly0 = LayerOrigin(draw_list, kind, ox, oy)
if lx0 ~= layer.X + dx or ly0 ~= layer.Y + dy then return false end
if layer.Root ~= layer.Frame then
local ccx0 = draw_list._ContentClipX0
if not ccx0 or not layer.ClipX0 then return false end
if max(floor(ccx0 - ox), LimitX0) ~= layer.ClipX0 + dx
or max(floor(draw_list._ContentClipY0 - oy), LimitY0) ~= layer.ClipY0 + dy
or min(floor(draw_list._ContentClipX1 - ox), LimitX1) ~= layer.ClipX1 + dx
or min(floor(draw_list._ContentClipY1 - oy), LimitY1) ~= layer.ClipY1 + dy then
return false
end
end
-- the tiles of the primitives with a drifted vertex (flat rects: drawn from their bounds only, unchanged)
local plist = kind == 1 and LayerPrims1 or kind == 2 and LayerPrims2 or LayerPrims3
local TileCounts, Tiles = layer.TileCounts, layer.Tiles
for m = 1, count do
local p = plist[m]
local vd = PrimD[p]
if PrimFlat[p]
or not (DriftSet[PrimA[p] // VTX_STRIDE + 1] or DriftSet[PrimB[p] // VTX_STRIDE + 1]
or DriftSet[PrimC[p] // VTX_STRIDE + 1] or (vd and DriftSet[vd // VTX_STRIDE + 1])) then
continue
end
PatchPrim[p] = true
local cx0, cy0, cx1, cy1 = PrimBoundsX0[p] - lx0, PrimBoundsY0[p] - ly0, PrimBoundsX1[p] - lx0,
PrimBoundsY1[p] - ly0
for ty = cy0 // TILE, (cy1 - 1) // TILE do
for tx = cx0 // TILE, (cx1 - 1) // TILE do
local key = (ty + 32768) * 65536 + tx + 32768
local c, tile = TileCounts[key], Tiles[key]
if not c or c == 0 or not tile then continue end -- not drawn (outside the content clip)
if tile.DrawnCount ~= c or tile.Hash1 ~= layer.TileHash1[key] or tile.Hash2 ~= layer.TileHash2[key]
or (tile.Deferred or 0) > 0 then
return false
end
np += 1
PatchLayers[np], PatchKeys[np] = kind, key
end
end
end
end
-- the lists: this frame's primitive indices
local delta = n0 - set.PrimBase
set.PrimBase = n0
for kind = 1, 3 do
local layer = set[kind]
if delta == 0 or not (layer and layer.Visible) then continue end
local TileCounts, TileLists, Touched = layer.TileCounts, layer.TileLists, layer.Touched
for kk = 1, layer.TouchedCount do
local key = Touched[kk]
local c = TileCounts[key]
if c and c > 0 then
local list = TileLists[key]
for k = 1, c do list[k] += delta end
end
end
end
-- the patched tiles: their drawn entries, the drifted primitives' hashes changed, redrawn
local FrameNo = BackendData.FrameNo
for i = 1, np do
local kind, key = PatchLayers[i], PatchKeys[i]
local layer = set[kind]
local tile = layer.Tiles[key]
if tile.Used == FrameNo then continue end -- (done: a tile of several drifted primitives)
tile.Used = FrameNo
local count = layer.TileCounts[key]
local list, LH1, LH2 = layer.TileLists[key], layer.TileListHash1[key], layer.TileListHash2[key]
table.move(tile.DrawnHash1, 1, count, 1, LH1)
table.move(tile.DrawnHash2, 1, count, 1, LH2)
table.move(tile.DrawnFlat, 1, count, 1, layer.TileListFlat[key])
local h1, h2 = 0, 0
for k = 1, count do
if PatchPrim[list[k]] then
LH1[k], LH2[k] = (LH1[k] + DriftMark1) % P1, (LH2[k] + DriftMark2) % P2
end
h1 = (h1 * 48271 + LH1[k]) % P1
h2 = (h2 * 16807 + LH2[k] + k) % P2
end
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 vx0, vy0, vx1, vy1 = 0, 0, TILE, TILE
if layer.Root ~= layer.Frame then
vx0, vy0 = max(layer.ClipX0 + dx - x0, 0), max(layer.ClipY0 + dy - y0, 0)
vx1, vy1 = min(layer.ClipX1 + dx - x0, TILE), min(layer.ClipY1 + dy - y0, TILE)
end
local exposed = vx0 < tile.ValidX0 or vy0 < tile.ValidY0 or vx1 > tile.ValidX1 or vy1 > tile.ValidY1
RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, false, exposed, vx0, vy0, vx1, vy1)
end
table.clear(PatchPrim)
return true
end
-- Overlay frames are only hidden (the user owns them); unused layers hidden, long unused ones freed
local function SweepLayers(BackendData, FrameNo)
for frame, shown in pairs(BackendData.OverlayShown) do
@@ -803,7 +982,7 @@ function M.RenderDrawData(draw_data)
local set = BackendData.Layers[draw_list]
local same, sdx, sdy = 0, 0, 0
if not force then same, sdx, sdy = CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) end
if same ~= 0 then
if same == 1 or same == 2 then
z = ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight)
if EditableImages.StageTiming then EditableImages.EndStage("Compare") end
PE()
@@ -814,16 +993,39 @@ function M.RenderDrawData(draw_data)
PB("ImGui collect")
if EditableImages.StageTiming then EditableImages.BeginStage() end
local first = n + 1
local LimitFree, ex0, ey0, ex1, ey1
local n0 = n
n, LimitFree, ex0, ey0, ex1, ey1 = CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1,
LimitY1)
if EditableImages.StageTiming then EditableImages.EndStage("Collect") end
PE()
local nd = Layers.DriftCount
if nd > 0 then
local Drift = Layers.Drift
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
end
if same == 3 then
PB("ImGui drift patch")
if EditableImages.StageTiming then EditableImages.BeginStage() end
local patched = PatchDrawList(BackendData, set, draw_list, n0, n, sdx, sdy, ox, oy, LimitX0, LimitY0,
LimitX1, LimitY1)
if EditableImages.StageTiming then EditableImages.EndStage("Raster") end
PE()
if patched then
for k = 1, nd do DriftSet[Layers.Drift[k] // VTX_STRIDE + 1] = false end
DriftOn = false
z = ReuseDrawList(BackendData, set, draw_list, 2, sdx, sdy, z, ox, oy, ScreenWidth, ScreenHeight)
continue
end
end
local ListDeferred
z, ListDeferred = DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1,
LimitY1)
z, ListDeferred = DrawLists(BackendData, draw_list, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1)
if nd > 0 then
for k = 1, nd do DriftSet[Layers.Drift[k] // VTX_STRIDE + 1] = false end
DriftOn = false
end
set = BackendData.Layers[draw_list]
-- deferred tiles: not "unchanged" next frame, so they get redrawn
if set then
@@ -832,6 +1034,10 @@ function M.RenderDrawData(draw_data)
Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight)
set.SnapLimitFree = LimitFree
set.SnapExtentX0, set.SnapExtentY0, set.SnapExtentX1, set.SnapExtentY1 = ex0, ey0, ex1, ey1
-- the primitive sequence the tile lists were built from (PatchDrawList)
set.PrimBase, set.PrimN = n0, n - n0
set.PrimSigA = table.move(PrimA, n0 + 1, n, 1, set.PrimSigA or {})
set.PrimSigD = table.move(PrimD, n0 + 1, n, 1, set.PrimSigD or {})
end
end
if ListDeferred then AnyDeferred = true end
+65 -31
View File
@@ -7,7 +7,8 @@ local TILE = Raster.TILE
local M = {}
-- One table, not locals: shared by every context and module. FreeTile is set by layers.lua (Evict needs it).
-- One table, not locals: shared by every context and module. FreeTile is set by layers.lua (Evict needs it),
-- TextureDropped(id, record) by parallel.lua (Actors free their copies).
local EditableImages = {
Cap = 64 * 1024 * 1024, Bytes = 0, Count = 0, ImageBytes = setmetatable({}, { __mode = "k" }),
Pool = {}, PoolMax = 16,
@@ -39,33 +40,45 @@ function M.GetBackendData()
return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil
end
-- n pixels from the byte table src (1-based index s) to dst (byte offset d). Typed + unrolled by 4: the native code
-- skips the generic table/buffer checks (~40% faster than the plain loop).
@native
local function CopyTexturePixels(tex, dst, x, y, w, h, dst_zero)
local bpp, tex_w = tex.BytesPerPixel, tex.Width
if x == 0 and w == tex_w and bpp == 4 then -- whole rows: one flat loop; dst_zero: skip writing zero pixels
local function CopyRGBA(src: { number }, s: number, dst: buffer, d: number, n: number)
for _ = 1, n // 4 do
writeu32(dst, d, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216)
writeu32(dst, d + 4, src[s + 4] + src[s + 5] * 256 + src[s + 6] * 65536 + src[s + 7] * 16777216)
writeu32(dst, d + 8, src[s + 8] + src[s + 9] * 256 + src[s + 10] * 65536 + src[s + 11] * 16777216)
writeu32(dst, d + 12, src[s + 12] + src[s + 13] * 256 + src[s + 14] * 65536 + src[s + 15] * 16777216)
s += 16
d += 16
end
for _ = 1, n % 4 do
writeu32(dst, d, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216)
s += 4
d += 4
end
end
@native
local function CopyAlpha8(src: { number }, s: number, dst: buffer, d: number, n: number) -- white with alpha
for _ = 1, n do
writeu32(dst, d, 16777215 + src[s] * 16777216)
s += 1
d += 4
end
end
local function CopyTexturePixels(tex, dst, x, y, w, h)
local tex_w = tex.Width
local copy = tex.BytesPerPixel == 4 and CopyRGBA or CopyAlpha8
if x == 0 and w == tex_w then -- whole rows: one flat run
local src, s = tex:GetPixelsAt(0, y)
local d = y * tex_w * 4
for _ = 1, w * h do
local v = src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216
if v ~= 0 or not dst_zero then writeu32(dst, d, v) end
s += 4
d += 4
end
copy(src, s, dst, y * tex_w * 4, w * h)
return
end
for row = 0, h - 1 do
local src, src_base = tex:GetPixelsAt(x, y + row)
local dst_off = ((y + row) * tex_w + x) * 4
if bpp == 4 then
for i = 0, w - 1 do
local s = src_base + i * 4
writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216)
end
else -- Alpha8: white with alpha
for i = 0, w - 1 do
writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216)
end
end
local src, s = tex:GetPixelsAt(x, y + row)
copy(src, s, dst, ((y + row) * tex_w + x) * 4, w)
end
end
@@ -73,9 +86,18 @@ end
local Records = {}
M.Records = Records
-- The buffer of the last destroyed atlas texture record: the next one of the same size (an atlas repack: same size
-- every time) reuses it. buffer.create of an atlas is slow in Studio (~0.2-1.8 ms for 512 KB, spiky).
local SpareBuffer: buffer? = nil
local function CreateTextureRecord(tex)
local w, h = tex.Width, tex.Height
local b = buffer.create(w * h * 4)
local b, reused = SpareBuffer, false
if b and buffer.len(b) == w * h * 4 then
SpareBuffer, reused = nil, true
else
b = buffer.create(w * h * 4)
end
-- The current font atlas texture: pixels outside the packed rects (MaxRectBounds) and the queued uploads (UsedRect)
-- are still zero (repack's BlockCopy doesn't queue, but every copied rect is packed). Fill them with what zero
-- converts to, convert only the used corner. A fresh/grown atlas is mostly empty. Any other texture: everything.
@@ -87,7 +109,9 @@ local function CreateTextureRecord(tex)
ch = math.min(h, math.max(u.y + u.h, m.y))
end
if cw < w or ch < h then
if tex.BytesPerPixel ~= 4 then -- Alpha8 zero -> 0x00FFFFFF; RGBA zero -> 0 (buffer.create's fill)
if tex.BytesPerPixel == 4 then
if reused then buffer.fill(b, 0, 0) end
else -- Alpha8 zero -> 0x00FFFFFF; RGBA zero -> 0 (buffer.create's fill)
local n, total = 4, w * h * 4
writeu32(b, 0, 16777215)
while n < total do
@@ -96,9 +120,9 @@ local function CreateTextureRecord(tex)
n += c
end
end
CopyTexturePixels(tex, b, 0, 0, cw, ch, tex.BytesPerPixel == 4)
CopyTexturePixels(tex, b, 0, 0, cw, ch)
else
CopyTexturePixels(tex, b, 0, 0, w, h, true)
CopyTexturePixels(tex, b, 0, 0, w, h)
end
-- rows FillRow.. hold only Fill (what zero converts to): parallel.lua sends Actors the rows above it
local t = { Buffer = b, Width = w, Height = h, FillRow = ch, Fill = tex.BytesPerPixel ~= 4 and 16777215 or 0 }
@@ -119,22 +143,30 @@ function M.UpdateTexture(tex)
return
end
local y0, y1 = math.huge, -1
local rects, n = {}, 0
for _, r in tex.Updates:iter() do
CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h)
if r.y < y0 then y0 = r.y end
if r.y + r.h > y1 then y1 = r.y + r.h end
rects[n + 1], rects[n + 2], rects[n + 3], rects[n + 4] = r.x, r.y, r.w, r.h
n += 4
end
-- parallel workers hold copies, patched when this changes: Log[V] = changed rows (only the last 16 kept)
-- parallel workers hold copies, patched when this changes: Log[V] = changed rows + the rects (x, y, w, h
-- quadruples) (only the last 16 kept)
if t.FillRow and y1 > t.FillRow then t.FillRow = y1 end
local v = (t.V or 0) + 1
t.V = v
t.Log = t.Log or {}
t.Log[v] = y1 > y0 and { y0, y1 } or { 0, 0 }
t.Log[v] = y1 > y0 and { y0, y1, rects } or { 0, 0 }
t.Log[v - 16] = nil
tex:SetStatus(ImTextureStatus.OK)
elseif tex.Status == ImTextureStatus.WantDestroy then
if tex.BackendUserData then
Records[tex.BackendUserData] = nil
local id = tex.BackendUserData
local rec = Records[id]
if EditableImages.TextureDropped then EditableImages.TextureDropped(id, rec) end
if rec and rec.FillRow then SpareBuffer = rec.Buffer end -- (FillRow: a buffer CreateTextureRecord made)
Records[id] = nil
tex.BackendUserData = nil
end
tex:SetTexID(ImTextureID_Invalid)
@@ -150,7 +182,9 @@ function ImGui_ImplRoblox_CreateTexture(pixels, w, h)
end
function ImGui_ImplRoblox_DestroyTexture(tex_ref)
Records[tex_ref._TexID] = nil
local id = tex_ref._TexID
if EditableImages.TextureDropped then EditableImages.TextureDropped(id, Records[id]) end
Records[id] = nil
end
-- Every EditableImage goes through Create/Destroy, counted against Cap. Over the cap (or CreateEditableImage failing):
+3 -25
View File
@@ -8,31 +8,9 @@ local Raster = require(script.Parent:WaitForChild("Raster"))
local Done = Actor:WaitForChild("Done")
local Textures = {}
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength)
for _, Texture in TexUpdates do
if Texture[2] then
local B, W, H, Fill = Texture[2], Texture[3], Texture[4], Texture[5]
local n, total = buffer.len(B), W * H * 4
if n < total then -- the rows below were left out: all Fill (parallel.lua fullCopy)
local Full = buffer.create(total)
buffer.copy(Full, 0, B)
if Fill ~= 0 then
buffer.writeu32(Full, n, Fill)
local k = 4
while k < total - n do
local c = math.min(k, total - n - k)
buffer.copy(Full, n + k, Full, n, c)
k += c
end
end
B = Full
end
Textures[Texture[1]] = { Buffer = B, Width = W, Height = H }
else -- rows changed since the copy this Actor has
local T = Textures[Texture[1]]
buffer.copy(T.Buffer, Texture[5], Texture[6])
end
end
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength, Dropped)
-- this Actor's texture copies: destroyed ids dropped, changed rows/rects patched (parallel.lua Flush)
Raster.ApplyTextures(Textures, TexUpdates, Dropped)
local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures)
task.synchronize()
Done:Fire(Id, Results)
+1 -1
View File
@@ -1 +1 @@
[[46, "imgui.lua"], [22688, "imgui_demo.lua"], [34545, "imgui_draw.lua"], [42896, "imgui_h.lua"], [45899, "roblox/raster.lua"], [46699, "roblox/textures.lua"], [46916, "roblox/layers.lua"], [47253, "roblox/overlays.lua"], [47334, "roblox/render.lua"], [48201, "roblox/parallel.lua"], [48648, "imgui_impl_roblox.lua"], [49149, "imgui_impl_roblox_fonts.lua"], [55552, "imgui_internal.lua"], [59520, "imgui_tables.lua"], [64612, "imgui_widgets.lua"], [76880, "imstb_rectpack.lua"], [77557, "imstb_textedit.lua"], [79099, "imstb_truetype.lua"], [82040, "imstd_minstdio.lua"]]
[[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"]]
+8353 -6925
View File
File diff suppressed because it is too large. Load diff
+506 -169
View File
@@ -11,7 +11,7 @@ local Raster = (function()
-- Target: RGBA8 row-major (ImU32 is already R | G<<8 | B<<16 | A<<24), non-premultiplied "over" onto transparent.
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
local readu8, readu32, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu32
local readf64 = buffer.readf64
local readf64, writef64 = buffer.readf64, buffer.writef64
local band, rshift = bit32.band, bit32.rshift
local readi32 = buffer.readi32
@@ -26,7 +26,22 @@ local M = {
}
local TILE = M.TILE
local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0
-- Pixel (x, y) of the target is at byte (y * TargetWidth + x) * 4 + TargetBase: a target can be a sub-rectangle of the
-- tile (raster straight into the upload buffer)
local TargetBuffer: buffer, TargetWidth, TargetBase = buffer.create(0), 0, 0
-- Solid spans are written two pixels per writef64 (a write costs about the same at either width): the f64 whose bytes
-- are the pixel twice. Only for a normal double (exponent field not 0 or all ones), which every load and store keeps
-- bit for bit; else PairF64 returns false and spans are written per pixel.
local PairScratch = buffer.create(8)
@native
local function PairF64(v: number): number | false
local e = band(rshift(v, 20), 2047)
if e == 0 or e == 2047 then return false end
writeu32(PairScratch, 0, v)
writeu32(PairScratch, 4, v)
return readf64(PairScratch, 0)
end
local PrevRow = buffer.create(1024)
-- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else
@@ -48,33 +63,50 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean
return false
end
local RectColumns = table.create(256, 0)
-- DrawRect's per-alpha blend cache: GlyphKey[alpha] = GlyphGen + destination value -> GlyphValue[alpha]. GlyphGen
-- (a multiple of 2^32) changes with the vertex colour.
local GlyphKey, GlyphValue = table.create(256, -1), table.create(256, 0)
GlyphKey[0], GlyphValue[0] = -1, 0
local GlyphCol, GlyphGen = -1, 0
-- Uniform region: [UX0, UX1) x [UY0, UY1) of the target holds only the pixel value UV (empty when UX0 >= UX1).
-- Set by ClearRect and by solid rects; shrunk by everything drawn over it. A solid rect inside it blends one pixel and
-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel.
local UX0, UY0, UX1, UY1, UV = 0, 0, 0, 0, 0
-- Uniform rows: [RowX0[y], RowX1[y]) of target row y holds only the pixel value RowV[y] (empty when RowX0 >= RowX1).
-- Set by ClearRect and by solid spans; shrunk by everything drawn over it. A solid span inside it blends one pixel and
-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. Only the rows of the last
-- ClearRect are valid: drawing must stay inside it (callers clip every primitive to the cleared rect).
local RowX0, RowX1, RowV = table.create(TILE, 0), table.create(TILE, 0), table.create(TILE, 0)
RowX0[0], RowX1[0], RowV[0] = 0, 0, 0
-- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece outside it
-- Drawing changed [x0, x1) x [y0, y1): keep the larger uniform piece of each row outside it
@native
local function Shrink(x0: number, y0: number, x1: number, y1: number)
if x0 >= UX1 or x1 <= UX0 or y0 >= UY1 or y1 <= UY0 or UX0 >= UX1 then return end
local h, w = UY1 - UY0, UX1 - UX0
local left, right, top, bottom = (x0 - UX0) * h, (UX1 - x1) * h, (y0 - UY0) * w, (UY1 - y1) * w
local best = max(left, right, top, bottom)
if best <= 0 then
UX1 = UX0
elseif best == left then
UX1 = x0
elseif best == right then
UX0 = x1
elseif best == top then
UY1 = y0
else
UY0 = y1
local function ApplyDamage(x0: number, y0: number, x1: number, y1: number)
for y = y0, y1 - 1 do
local a, b = RowX0[y], RowX1[y]
if x0 < b and x1 > a then
if x0 - a >= b - x1 then RowX1[y] = x0 else RowX0[y] = x1 end
end
end
end
-- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync.
-- Only FillSpan reads the uniform rows: damage is collected into one pending rect (nearby rects merged: a text line's
-- glyphs, a shape's triangles) and applied when FillSpan runs. Over-shrinking only loses uniform pixels.
local PX0, PY0, PX1, PY1 = 0, 0, 0, 0 -- pending damage (none when PX0 >= PX1)
@native
local function Shrink(x0: number, y0: number, x1: number, y1: number)
if PX0 >= PX1 then
PX0, PY0, PX1, PY1 = x0, y0, x1, y1
return
end
local ux0, uy0, ux1, uy1 = min(x0, PX0), min(y0, PY0), max(x1, PX1), max(y1, PY1)
if (ux1 - ux0) * (uy1 - uy0) <= ((x1 - x0) * (y1 - y0) + (PX1 - PX0) * (PY1 - PY0)) * 1.25 + 256 then
PX0, PY0, PX1, PY1 = ux0, uy0, ux1, uy1
return
end
ApplyDamage(PX0, PY0, PX1, PY1)
PX0, PY0, PX1, PY1 = x0, y0, x1, y1
end
-- The blend, for reference: every rasterizer loop inlines this math (a call per pixel costs more than the blend), the
-- span paths with per-span constants: keep them in sync. Not called.
@native
local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number)
if a >= 255 then
@@ -104,57 +136,177 @@ local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number,
end
end
-- Wide spans (>= 32 px) over non-uniform rows: rows usually blend over identical rows, so a row whose destination
-- repeats the previous one's copies its result
@native
local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number,
b: number, a: number)
if a <= 0 then return end
local w4 = (x1 - x0 - 1) * 4
if x0 >= UX0 and y0 >= UY0 and x1 <= UX1 and y1 <= UY1 and a < 255 then
-- over one value: FillSpan's per-pixel result for d = UV, then fill
local d, v = UV, 0
if d < 16777216 then
v = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216
else
local sa = a / 255
local ns = 1 - sa
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
v = floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256
+ floor(b * sa + db * ns + 0.5) * 65536 + 4278190080
else
local k = rshift(d, 24) * (ns / 255)
local oa = sa + k
local inv = 1 / oa
v = floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256
+ floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
end
local first = (y0 * TargetWidth + x0) * 4
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, v) end
for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end
UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, v
return
if PX0 < PX1 then
ApplyDamage(PX0, PY0, PX1, PY1)
PX1 = PX0
end
local w4 = (x1 - x0 - 1) * 4
local span = x1 - x0
if a >= 255 then
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local first = (y0 * TargetWidth + x0) * 4
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end
for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end
-- now uniform: keep whichever region is larger
local area = (x1 - x0) * (y1 - y0)
Shrink(x0, y0, x1, y1)
if area > (UX1 - UX0) * (UY1 - UY0) or UX0 >= UX1 then UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, packed end
local first = (y0 * TargetWidth + x0) * 4 + TargetBase
local pair = span >= 16 and PairF64(packed)
if pair then
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)
local y = y0
while y < y1 do
local ra, rb = RowX0[y], RowX1[y]
local na, nb = ra, rb
if x0 < rb and x1 > ra then
if x0 - ra >= rb - x1 then nb = x0 else na = x1 end
end
if span > nb - na then
repeat
RowX0[y], RowX1[y], RowV[y] = x0, x1, packed
y += 1
until y >= y1 or RowX0[y] ~= ra or RowX1[y] ~= rb
else
repeat
RowX0[y], RowX1[y] = na, nb
y += 1
until y >= y1 or RowX0[y] ~= ra or RowX1[y] ~= rb
end
end
return
end
Shrink(x0, y0, x1, y1)
local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216
local sa = a / 255
local ns = 1 - sa
local c1 = ns / 255
local rs, gs, bs = r * sa, g * sa, b * sa
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
for y = y0, y1 - 1 do
local o0 = (y * TargetWidth + x0) * 4
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 y = y0
while y < y1 do
local o0 = (y * TargetWidth + x0) * 4 + TargetBase
local ra, rb = RowX0[y], RowX1[y]
if x0 >= ra and x1 <= rb then
-- over one value: the per-pixel result for d = RowV[y], then fill; following rows with the same uniform
-- piece get the same result
local d = RowV[y]
if d ~= last_d then
last_d = d
if d < 16777216 then
last_v = packed0
else
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
end
end
local v = last_v
if v == prev_v and span > 8 then -- (a call: slower than a few writes)
buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4)
else
local pair = 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
local na, nb, nv = ra, rb, d
if span >= x0 - ra and span >= rb - x1 then
na, nb, nv = x0, x1, v
elseif x0 - ra >= rb - x1 then
nb = x0
else
na = x1
end
RowX0[y], RowX1[y], RowV[y] = na, nb, nv
y += 1
local stride = TargetWidth * 4
local o = o0
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
y += 1
end
prev_o, prev_v, has_prev = o, v, false
continue
end
if x0 < rb and x1 > ra then
if x0 - ra >= rb - x1 then RowX1[y] = x0 else RowX0[y] = x1 end
end
if wide then
local repeats = RowRepeats(o0, w4 + 4, has_prev)
has_prev = true
if repeats then
buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4)
prev_o, prev_v = o0, -1
y += 1
continue
end
end
prev_o, prev_v = o0, -1
if black then
-- (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
local d = readu32(TargetBuffer, o)
if d ~= last_d then
last_d = d
if d >= 4278190080 then
last_v = 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
elseif d < 16777216 then
last_v = packed0
else
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
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
end
writeu32(TargetBuffer, o, last_v)
end
y += 1
continue
end
for o = o0, o0 + w4, 4 do
local d = readu32(TargetBuffer, o)
if d == last_d then
@@ -177,6 +329,7 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
writeu32(TargetBuffer, o, last_v)
end
end
y += 1
end
end
@@ -211,23 +364,7 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
end
if a <= 0 then return end
if a >= 255 or px1 - px0 < 32 or (px0 >= UX0 and py0 >= UY0 and px1 <= UX1 and py1 <= UY1) then
FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a)
return
end
-- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result
Shrink(px0, py0, px1, py1)
local len = (px1 - px0) * 4
local prev_o = 0
for y = py0, py1 - 1 do
local o = (y * TargetWidth + px0) * 4
if RowRepeats(o, len, y > py0) then
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
else
FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a)
end
prev_o = o
end
FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a)
return
end
@@ -239,18 +376,31 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
local cols = RectColumns
local ident = col == 4294967295
local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0
local step = true
for c = 1, ncol do
local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
cols[c] = tx * 4
if c > 1 and tx * 4 ~= cols[c - 1] + 4 then step = false end
end
-- white translucent texels (font atlas): blend result cached per alpha for one destination value and colour
if col ~= GlyphCol then
GlyphCol = col
GlyphGen += 4294967296
if GlyphGen >= 4503599627370496 then -- 2^52: keys must stay exact
GlyphGen = 4294967296
for k = 0, 255 do GlyphKey[k] = -1 end
end
end
local gen = GlyphGen
for y = py0, py1 - 1 do
local ty = floor((v0 + (y + 0.5 - y0) * dv) * th)
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local trow4 = ty * tw * 4
local o = (y * TargetWidth + px0) * 4
local o = (y * TargetWidth + px0) * 4 + TargetBase
local tb0 = trow4 + cols[1] - 4
for c = 1, ncol do
local tv = readu32(tbuf, trow4 + cols[c])
local tv = readu32(tbuf, step and tb0 + c * 4 or trow4 + cols[c])
if tv < 16777216 then
o += 4
continue
@@ -260,6 +410,17 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
o += 4
continue
end
local d, key, al = 0, -1, 0
if tv % 16777216 == 16777215 then
al = rshift(tv, 24)
d = readu32(dbuf, o)
key = gen + d
if GlyphKey[al] == key then
writeu32(dbuf, o, GlyphValue[al])
o += 4
continue
end
end
-- BlendPixel inlined (same math)
if tv ~= last_tv then
last_tv = tv
@@ -270,27 +431,35 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
fn = 1 - fa
fk = (1 - fa) / 255
end
local v = -1
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
v = s_opaque + 4278190080
elseif sa > 0 then
local d = readu32(dbuf, o)
if key < 0 then d = readu32(dbuf, o) end
if d < 16777216 then
writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216)
v = s_opaque + floor(sa + 0.5) * 16777216
else
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256
+ floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080)
v = floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256
+ floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080
else
local k = rshift(d, 24) * fk
local oa = fa + k
local inv = 1 / oa
writeu32(dbuf, o, floor((sr * fa + dr * k) * inv + 0.5)
+ floor((sg * fa + dg * k) * inv + 0.5) * 256
+ floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
v = floor((sr * fa + dr * k) * inv + 0.5) + floor((sg * fa + dg * k) * inv + 0.5) * 256
+ floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
end
end
if v >= 0 then
writeu32(dbuf, o, v)
elseif key >= 0 then
v = d -- unchanged
end
if key >= 0 then
GlyphKey[al], GlyphValue[al] = key, v
end
o += 4
end
end
@@ -327,39 +496,54 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local inv = 1 / area
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 ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32))
local rb, gb, bb, ab = UnpackColor(readu32(vbuf, vb + 32))
local rc, gc, bc, ac = UnpackColor(readu32(vbuf, vc + 32))
-- 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 ra, ga, ba, aa = ca % 256, floor(ca / 256) % 256, floor(ca / 65536) % 256, floor(ca / 16777216) % 256
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 cc ~= ca then rc, gc, bc, ac = cc % 256, floor(cc / 256) % 256, floor(cc / 65536) % 256, floor(cc / 16777216) % 256 end
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)
local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc)
if t and not textured then -- constant uv (atlas white pixel): fold the texel into the vertex colours
local tr, tg, tb, ta = SampleTexture(t, ua, vva)
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255
local tw0, th0 = t.Width, t.Height
local tx, ty = floor(ua * tw0), floor(vva * 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 -- (a white texel changes nothing: c * 255 / 255 is c)
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
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255
end
end
local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab
and aa == ac
if flat and aa <= 0 then return end
local f_opaque, f_packed, f_sa, f_ns, f_c1, f_rs, f_gs, f_bs = false, 0, 0, 0, 0, 0, 0, 0
local f_pair: number | false = false
if flat then
f_opaque = aa >= 255
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)
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
if f_opaque then f_pair = PairF64(f_packed) end
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
end
local cconst = textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab
and aa == ac
if cconst and aa <= 0 then return end
local tw: number, th: number, tbuf: buffer = 0, 0, dbuf
local r255, g255, b255, a255 = ra / 255, ga / 255, ba / 255, aa / 255
local r255, g255, b255, a255 = 0, 0, 0, 0
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
if cconst then tw, th, tbuf = t.Width, t.Height, t.Buffer end
if textured then tw, th, tbuf = t.Width, t.Height, t.Buffer end
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
@@ -390,11 +574,36 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
yb -= 1
end
if yt > yb then continue end
local o = (yt * TargetWidth + x) * 4
local o = (yt * TargetWidth + x) * 4 + TargetBase
if flat then
for _ = yt, yb do
BlendPixel(dbuf, o, ra, ga, ba, aa)
o += stride
-- the row path's flat spans (BlendPixel's math, per-span constants, cached per destination value)
local o1 = o + (yb - yt) * stride
if f_opaque then
for oo = o, o1, stride do writeu32(dbuf, oo, f_packed) end
continue
end
local last_d, last_v = -1, 0
for oo = o, o1, stride 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 k = rshift(d, 24) * f_c1
local oa = f_sa + k
local inv2 = 1 / oa
last_v = floor((f_rs + dr * k) * inv2 + 0.5) + floor((f_gs + dg * k) * inv2 + 0.5) * 256
+ floor((f_bs + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(dbuf, oo, last_v)
end
end
continue
end
@@ -404,7 +613,32 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
(A2 * px + (B2 * py + C2)) * inv
local a = w0 * aa + w1 * ab + w2 * ac
if a > 0 then
BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, w0 * ba + w1 * bb + w2 * bc, a)
-- BlendPixel inlined (same math; a call per pixel costs more than the blend)
local r, g, b = w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, w0 * ba + w1 * bb + w2 * bc
if a >= 255 then
writeu32(dbuf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080)
else
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536
+ floor(a + 0.5) * 16777216)
else
local sa = a / 255
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
local ns = 1 - sa
writeu32(dbuf, o, floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256
+ floor(b * sa + db * ns + 0.5) * 65536 + 4278190080)
else
local k = rshift(d, 24) * ((1 - sa) / 255)
local oa = sa + k
local inv2 = 1 / oa
writeu32(dbuf, o, floor((r * sa + dr * k) * inv2 + 0.5)
+ floor((g * sa + dg * k) * inv2 + 0.5) * 256
+ floor((b * sa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
end
o += stride
end
@@ -433,6 +667,10 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
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
-- 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.
if xl > minx and xl <= xr then xl += 1 end
while xl <= xr do
local px = xl + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
@@ -441,6 +679,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end
xl += 1
end
if xr < maxx and xr > xl then xr -= 1 end
while xr > xl do
local px = xr + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
@@ -450,11 +689,19 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
xr -= 1
end
if xl > xr then continue end
local o = (y * TargetWidth + xl) * 4
local o = (y * TargetWidth + xl) * 4 + TargetBase
if flat then
local o1 = o + (xr - xl) * 4
if f_opaque then
for oo = o, o1, 4 do writeu32(dbuf, oo, f_packed) end
if f_pair then
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
end
local last_d, last_v = -1, 0
@@ -530,15 +777,48 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local px = x + 0.5
local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv
local a = w0 * aa + w1 * ab + w2 * ac
local r, g, b = 0, 0, 0
if textured then
local r = w0 * ra + w1 * rb + w2 * rc
local g = w0 * ga + w1 * gb + w2 * gc
local b = w0 * ba + w1 * bb + w2 * bc
local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc)
BlendPixel(dbuf, o, r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255)
r = w0 * ra + w1 * rb + w2 * rc
g = w0 * ga + w1 * gb + w2 * gc
b = w0 * ba + w1 * bb + w2 * bc
-- SampleTexture inlined
local tx, ty = floor((w0 * ua + w1 * ub + w2 * uc) * tw), floor((w0 * vva + w1 * vvb + w2 * vvc) * th)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local to = (ty * tw + tx) * 4
r, g, b, a = r * readu8(tbuf, to) / 255, g * readu8(tbuf, to + 1) / 255, b * readu8(tbuf, to + 2) / 255,
a * readu8(tbuf, to + 3) / 255
elseif a > 0 then
BlendPixel(dbuf, o, w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc,
w0 * ba + w1 * bb + w2 * bc, a)
r, g, b = w0 * ra + w1 * rb + w2 * rc, w0 * ga + w1 * gb + w2 * gc, w0 * ba + w1 * bb + w2 * bc
else
o += 4
continue
end
-- BlendPixel inlined (same math; a call per pixel costs more than the blend)
if a >= 255 then
writeu32(dbuf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080)
elseif not (a <= 0) then
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536
+ floor(a + 0.5) * 16777216)
else
local sa = a / 255
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
local ns = 1 - sa
writeu32(dbuf, o, floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256
+ floor(b * sa + db * ns + 0.5) * 65536 + 4278190080)
else
local k = rshift(d, 24) * ((1 - sa) / 255)
local oa = sa + k
local inv2 = 1 / oa
writeu32(dbuf, o, floor((r * sa + dr * k) * inv2 + 0.5)
+ floor((g * sa + dg * k) * inv2 + 0.5) * 256
+ floor((b * sa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
o += 4
end
@@ -561,6 +841,12 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
DrawTriangle(dbuf, vbuf, va, vc, vd, t, cx0, cy0, cx1, cy1, ox, oy)
return
end
local minx, maxx = max(floor(min(x0, x1, x2, x3)), cx0), min(ceil(max(x0, x1, x2, x3)), cx1 - 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
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
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)
-- outer edges P -> Q (quad order, counter-clockwise like DrawTriangle's swap): A = yP - yQ, B = xQ - xP, C from P
local px_, py_, qx_, qy_ = x1, y1, x3, y3 -- b, d
@@ -590,13 +876,16 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
WA, WB, WC = WA * winv, WB * winv, WC * winv
local du, dv = uc - ua, vvc - vva
local minx, maxx = max(floor(min(x0, x1, x2, x3)), cx0), min(ceil(max(x0, x1, x2, x3)), cx1 - 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
local ra, ga, ba, aa = UnpackColor(readu32(vbuf, va + 32))
if aa <= 0 then return end
Shrink(minx, miny, maxx + 1, maxy + 1)
local tw: number, th: number, tbuf: buffer = t.Width, t.Height, t.Buffer
-- v constant across the line (ImGui's line texture: u across, one row per width): the texel row is fixed
-- (vva + w * 0 is vva)
local trow = -1
if dv == 0 then
local ty = floor(vva * th)
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
trow = ty * tw * 4
end
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
for y = miny, maxy do
@@ -607,6 +896,7 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
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
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)
while xl <= xr do
local px = xl + 0.5
local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3
@@ -616,6 +906,7 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end
xl += 1
end
if xr < maxx and xr > xl then xr -= 1 end
while xr > xl do
local px = xr + 0.5
local w0, w1, w2, w3 = A0 * px + e0, A1 * px + e1, A2 * px + e2, A3 * px + e3
@@ -626,14 +917,20 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number,
xr -= 1
end
if xl > xr then continue end
local o = (y * TargetWidth + xl) * 4
local o = (y * TargetWidth + xl) * 4 + TargetBase
local wrow = WB * py + WC
for x = xl, xr do
local w = WA * (x + 0.5) + wrow
local tx, ty = floor((ua + w * du) * tw), floor((vva + w * dv) * th)
local tx = floor((ua + w * du) * tw)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local tv = readu32(tbuf, (ty * tw + tx) * 4)
local tv
if trow >= 0 then
tv = readu32(tbuf, trow + tx * 4)
else
local ty = floor((vva + w * dv) * th)
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
tv = readu32(tbuf, (ty * tw + tx) * 4)
end
if tv ~= last_tv then
last_tv = tv
sa = rshift(tv, 24) * a255
@@ -699,7 +996,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1
local opaque = aa >= 255 and ab >= 255
local prev_o = 0
for y = py0, py1 - 1 do
local o = (y * TargetWidth + px0) * 4
local o = (y * TargetWidth + px0) * 4 + TargetBase
if y > py0 and (opaque or RowRepeats(o, len, true))
or (y == py0 and not opaque and RowRepeats(o, len, false)) then
buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len)
@@ -708,7 +1005,34 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1
for x = px0, px1 - 1 do
local f = (x + 0.5 - x0) * inv
local nf = 1 - f
BlendPixel(TargetBuffer, oo, ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f)
local r, g, b, a = ra * nf + rb * f, ga * nf + gb * f, ba * nf + bb * f, aa * nf + ab * f
-- BlendPixel inlined (same math)
if a >= 255 then
writeu32(TargetBuffer, oo, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536
+ 4278190080)
elseif not (a <= 0) then
local d = readu32(TargetBuffer, oo)
if d < 16777216 then
writeu32(TargetBuffer, oo, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536
+ floor(a + 0.5) * 16777216)
else
local sa = a / 255
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if d >= 4278190080 then
local ns = 1 - sa
writeu32(TargetBuffer, oo, floor(r * sa + dr * ns + 0.5)
+ floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536
+ 4278190080)
else
local k = rshift(d, 24) * ((1 - sa) / 255)
local oa = sa + k
local inv2 = 1 / oa
writeu32(TargetBuffer, oo, floor((r * sa + dr * k) * inv2 + 0.5)
+ floor((g * sa + dg * k) * inv2 + 0.5) * 256
+ floor((b * sa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
oo = oo + 4
end
end
@@ -717,26 +1041,20 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1
end
end
function M.SetTarget(buf: buffer, width: number)
TargetBuffer, TargetWidth = buf, width
UX1 = UX0
-- x0 y0: target pixel stored at buf's byte 0 (a sub-rectangle target: width = its width)
function M.SetTarget(buf: buffer, width: number, x0: number?, y0: number?)
TargetBuffer, TargetWidth, TargetBase = buf, width, -((y0 or 0) * width + (x0 or 0)) * 4
end
@native
function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number)
local rw = rx1 - rx0
UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0
for y = ry0, ry1 - 1 do RowX0[y], RowX1[y], RowV[y] = rx0, rx1, 0 end
PX1 = PX0
if rw == TargetWidth then
buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4)
buffer.fill(TargetBuffer, (ry0 * TargetWidth + rx0) * 4 + TargetBase, 0, (ry1 - ry0) * TargetWidth * 4)
else
for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end
end
end
@native
function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number)
for y = 0, rh - 1 do
buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4)
for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4 + TargetBase, 0, rw * 4) end
end
end
@@ -763,13 +1081,12 @@ local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, v
end
M.DrawPrim = DrawPrim
-- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback)
local Scratch = buffer.create(TILE * TILE * 4)
-- Packed tile jobs -> one exact-size buffer per rect (rasterized straight into it), in job order (worker + main-thread
-- fallback)
@native
function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect
local ClearRect, SetTarget = M.ClearRect, M.SetTarget
local REC_A, REC_B, REC_C, REC_D = M.REC_A, M.REC_B, M.REC_C, M.REC_D
M.SetTarget(Scratch, TILE)
local out, no = {}, 0
local o = 0
while o < tlen do
@@ -781,6 +1098,9 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
for r = 0, nr - 1 do
local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4),
readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12)
local rw, rh = rx1 - rx0, ry1 - ry0
local sub = buffer.create(rw * rh * 4)
SetTarget(sub, rw, rx0, ry0)
ClearRect(rx0, ry0, rx1, ry1)
for k = 0, count - 1 do
local q = readi32(T, po + k * 4)
@@ -794,9 +1114,6 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
if tid >= 0 then t = textures[tid] end
DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1)
end
local rw, rh = rx1 - rx0, ry1 - ry0
local sub = buffer.create(rw * rh * 4)
CopySubRect(sub, rx0, ry0, rw, rh)
no += 1
out[no] = sub
end
@@ -804,36 +1121,56 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
return out
end
-- An Actor's texture copies (worker.luau; parallel.lua's Sync mode emulates it): drop the destroyed ids, apply the
-- updates parallel.lua's Flush sent. { id, buf, w, h, fill }: whole texture, rows past buf are all fill;
-- { id, false, w, h, offset, patch }: rows; { id, false, w, h, rects, patch }: x, y, w, h quadruples, rows packed.
function M.ApplyTextures(textures, updates, dropped)
for _, id in dropped or {} do
textures[id] = nil
end
for _, u in updates do
if u[2] then
local b, w, h, fill = u[2], u[3], u[4], u[5]
local n, total = buffer.len(b), w * h * 4
if n < total then
local full = buffer.create(total)
buffer.copy(full, 0, b)
if fill ~= 0 then
buffer.writeu32(full, n, fill)
local k = 4
while k < total - n do
local c = math.min(k, total - n - k)
buffer.copy(full, n + k, full, n, c)
k += c
end
end
b = full
end
textures[u[1]] = { Buffer = b, Width = w, Height = h }
elseif type(u[5]) == "table" then
local t, rects, patch = textures[u[1]], u[5], u[6]
local dst, w, o = t.Buffer, t.Width, 0
for i = 1, #rects, 4 do
local x, y, rw, rh = rects[i], rects[i + 1], rects[i + 2], rects[i + 3]
for yy = y, y + rh - 1 do
buffer.copy(dst, (yy * w + x) * 4, patch, o, rw * 4)
o += rw * 4
end
end
else
buffer.copy(textures[u[1]].Buffer, u[5], u[6])
end
end
end
return M
end)()
local Done = Actor:WaitForChild("Done")
local Textures = {}
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength)
for _, Texture in TexUpdates do
if Texture[2] then
local B, W, H, Fill = Texture[2], Texture[3], Texture[4], Texture[5]
local n, total = buffer.len(B), W * H * 4
if n < total then -- the rows below were left out: all Fill (parallel.lua fullCopy)
local Full = buffer.create(total)
buffer.copy(Full, 0, B)
if Fill ~= 0 then
buffer.writeu32(Full, n, Fill)
local k = 4
while k < total - n do
local c = math.min(k, total - n - k)
buffer.copy(Full, n + k, Full, n, c)
k += c
end
end
B = Full
end
Textures[Texture[1]] = { Buffer = B, Width = W, Height = H }
else -- rows changed since the copy this Actor has
local T = Textures[Texture[1]]
buffer.copy(T.Buffer, Texture[5], Texture[6])
end
end
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength, Dropped)
-- this Actor's texture copies: destroyed ids dropped, changed rows/rects patched (parallel.lua Flush)
Raster.ApplyTextures(Textures, TexUpdates, Dropped)
local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures)
task.synchronize()
Done:Fire(Id, Results)
+1 -1
View File
@@ -1 +1 @@
[[183, "imgui.lua"], [22825, "imgui_demo.lua"], [34682, "imgui_draw.lua"], [43033, "imgui_h.lua"], [46034, "imgui_impl_love.lua"], [46578, "imgui_internal.lua"], [50546, "imgui_tables.lua"], [55638, "imgui_widgets.lua"], [67906, "imstb_rectpack.lua"], [68583, "imstb_textedit.lua"], [70125, "imstb_truetype.lua"], [73066, "imstd_minstdio.lua"]]
[[183, "imgui.lua"], [22933, "imgui_demo.lua"], [34790, "imgui_draw.lua"], [43214, "imgui_h.lua"], [46222, "imgui_impl_love.lua"], [46784, "imgui_internal.lua"], [50756, "imgui_tables.lua"], [55878, "imgui_widgets.lua"], [68266, "imstb_rectpack.lua"], [68943, "imstb_textedit.lua"], [70485, "imstb_truetype.lua"], [73446, "imstd_minstdio.lua"]]
+626 -244
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -18,6 +18,10 @@ there, but keep this port's existing data structures and conventions. Read the s
`return M`; `bundle.py` inlines them into the `imgui_impl_roblox.lua` function (one `do ... end` each, in dependency
order, `X` a local of that function). Use one name per module everywhere; no circular includes (late-bind a field on
a shared table instead, e.g. `EditableImages.FreeTile`).
- Roblox/Luau-specific replacements of hot library internals go in `backends/roblox/patches.lua` (installed when the
backend loads, one switch per patch in `Enabled`), never in the library sources. They must stay exactly equivalent
(draw hashes, pixels) and hand uncommon cases back to the original; patch `MT.*` methods or globals looked up at
call time. When changing a patched library function, update or disable its patch.
- No `goto`, no `::labels::`, no `setfenv/getfenv`, no LuaJIT `bit`/`ffi`. Use `bit32`. For `continue` use
`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
+172 -64
View File
@@ -4592,7 +4592,7 @@ function ImGui.CollapseButton(id, pos, dock_node)
local g = ImGui.GetCurrentContext()
local window = g.CurrentWindow
local bb = ImRect(pos, pos + ImVec2(g.FontSize, g.FontSize))
local bb = ImRect(pos.x, pos.y, pos.x + g.FontSize, pos.y + g.FontSize) -- [Luau] scalar form: no temporary ImVec2
local is_clipped = not ImGui.ItemAdd(bb, id)
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, ImGuiButtonFlags.None)
if is_clipped then return pressed end
@@ -4939,6 +4939,7 @@ end
local hash_memo, hash_memo_n, HASH_MEMO_MAX = {}, 0, 16384
local ImHashStrRaw
@native
function ImHashStr(str, size, seed)
if seed == nil then seed = 0 end
if size == nil or size == #str then
@@ -6783,6 +6784,7 @@ function ImGui.SameLine(offset_from_start_x, spacing_w)
end
--- @param indent_w? float
@native
function ImGui.Indent(indent_w)
if indent_w == nil then indent_w = 0.0 end
@@ -6799,6 +6801,7 @@ function ImGui.Indent(indent_w)
end
--- @param indent_w? float
@native
function ImGui.Unindent(indent_w)
if indent_w == nil then indent_w = 0.0 end
@@ -6835,6 +6838,7 @@ function ImGui.PushItemWidth(item_width)
g.NextItemData.HasFlags = bit32.band(g.NextItemData.HasFlags, bit32.bnot(ImGuiNextItemDataFlags.HasWidth))
end
@native
function ImGui.PopItemWidth()
local g = GImGui
local window = g.CurrentWindow
@@ -7001,7 +7005,13 @@ function ImGui.BeginGroup()
local g = GImGui
local window = g.CurrentWindow
local group_data = ImGuiGroupData()
-- [Luau] C++ copies the ImGuiGroupData into the vector's storage: reuse the entry an EndGroup() left past Size
-- (every field is written below) instead of allocating 7 tables per group
local group_stack = g.GroupStack
local group_data = (group_stack.Size < group_stack.Capacity) and group_stack.Data[group_stack.Size + 1] or nil
if group_data == nil then
group_data = ImGuiGroupData()
end
group_data.WindowID = window.ID
ImVec2_Copy(group_data.BackupCursorPos, window.DC.CursorPos)
ImVec2_Copy(group_data.BackupCursorPosPrevLine, window.DC.CursorPosPrevLine)
@@ -7017,7 +7027,7 @@ function ImGui.BeginGroup()
group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive
group_data.EmitItem = true
g.GroupStack:push_back(group_data)
group_stack:push_back(group_data)
window.DC.GroupOffset.x = window.DC.CursorPos.x - window.Pos.x - window.DC.ColumnsOffset.x
ImVec1_Copy(window.DC.Indent, window.DC.GroupOffset)
@@ -7028,6 +7038,7 @@ function ImGui.BeginGroup()
end
end
local EndGroup_bb = ImRect() -- [Luau] scratch for EndGroup(), never escapes
@native
function ImGui.EndGroup()
local g = GImGui
@@ -7042,10 +7053,14 @@ function ImGui.EndGroup()
end
-- Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
local group_bb = ImRect(group_data.BackupCursorPos, ImMax(ImMax(window.DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos))
-- [Luau] scalar ImMax()es into a scratch rect (ItemAdd() and ImRect_Copy() below copy it)
local bcp, cmp, lmax = group_data.BackupCursorPos, window.DC.CursorMaxPos, g.LastItemData.Rect.Max
local group_bb = EndGroup_bb
group_bb.Min.x = bcp.x; group_bb.Min.y = bcp.y
group_bb.Max.x = math.max(math.max(cmp.x, lmax.x), bcp.x); group_bb.Max.y = math.max(math.max(cmp.y, lmax.y), bcp.y)
ImVec2_Copy(window.DC.CursorPos, group_data.BackupCursorPos)
ImVec2_Copy(window.DC.CursorPosPrevLine, group_data.BackupCursorPosPrevLine)
ImVec2_Copy(window.DC.CursorMaxPos, ImMax(group_data.BackupCursorMaxPos, group_bb.Max))
ImVec2_CopyV(window.DC.CursorMaxPos, math.max(group_data.BackupCursorMaxPos.x, group_bb.Max.x), math.max(group_data.BackupCursorMaxPos.y, group_bb.Max.y))
ImVec1_Copy(window.DC.Indent, group_data.BackupIndent)
ImVec1_Copy(window.DC.GroupOffset, group_data.BackupGroupOffset)
ImVec2_Copy(window.DC.CurrLineSize, group_data.BackupCurrLineSize)
@@ -7061,7 +7076,7 @@ function ImGui.EndGroup()
end
window.DC.CurrLineTextBaseOffset = ImMax(window.DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset) -- FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ImGui.ItemSize(group_bb:GetSize())
ImGui.ItemSize(group_bb) -- [Luau] == ItemSize(group_bb:GetSize()): ItemSize() takes the rect's size
ImGui.ItemAdd(group_bb, 0, nil, ImGuiItemFlags.NoTabStop)
-- If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
@@ -7133,12 +7148,14 @@ end
--- @param default_w float
--- @param default_h float
--- @return ImVec2
@native
function ImGui.CalcItemSize(size, default_w, default_h)
return ImVec2(ImGui._CalcItemSizeXY(size.x, size.y, default_w, default_h)) -- [Luau] 'size' is by value upstream: never written to
end
-- [Luau] scalar CalcItemSize(): callers that build 'size' themselves skip both ImVec2 allocations
--- @return float, float
@native
function ImGui._CalcItemSizeXY(size_x, size_y, default_w, default_h)
local avail_x, avail_y
if size_x < 0.0 or size_y < 0.0 then
@@ -7716,6 +7733,7 @@ end
-- Push a given id value ignoring the ID stack as a seed.
--- @param id ImGuiID
@native
function ImGui.PushOverrideID(id)
local g = GImGui
local window = g.CurrentWindow
@@ -8684,6 +8702,7 @@ end
--- @param ctx? ImGuiContext
--- @param key ImGuiKey
--- @return ImGuiKeyData, int
@native
function ImGui.GetKeyData(ctx, key)
if ctx == nil then ctx = GImGui end
@@ -8751,6 +8770,7 @@ end
-- Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey.A) (>= 1.87)
--- @param key ImGuiKey
--- @param owner_id? ImGuiID
@native
function ImGui.IsKeyDown(key, owner_id)
if owner_id == nil then owner_id = ImGuiKeyOwner_Any end
@@ -8985,13 +9005,15 @@ end
-- Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6
-- See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
--- @param rt ImGuiKeyRoutingTable
@native
function ImGui.UpdateKeyRoutingTable(rt)
local g = GImGui --[[@as ImGuiContext]]
rt.EntriesNext:resize(0)
local index, entries_next = rt.Index, rt.EntriesNext -- [Luau] cached field reads (same tables until the swap below)
for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do
local new_routing_start_idx = rt.EntriesNext.Size + 1
local new_routing_start_idx = entries_next.Size + 1
local routing_entry
local old_routing_idx = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1]
local old_routing_idx = index[key - ImGuiKey.NamedKey_BEGIN + 1]
while old_routing_idx ~= -1 do
repeat
routing_entry = rt.Entries[old_routing_idx]
@@ -9003,7 +9025,7 @@ function ImGui.UpdateKeyRoutingTable(rt)
break
end
rt.EntriesNext:push_back(routing_entry) -- Write alive ones into new buffer
entries_next:push_back(routing_entry) -- Write alive ones into new buffer
-- Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
-- This is the result of previous frame's SetShortcutRouting() call.
@@ -9021,9 +9043,9 @@ function ImGui.UpdateKeyRoutingTable(rt)
end
-- Rewrite linked-list
rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = (new_routing_start_idx <= rt.EntriesNext.Size and new_routing_start_idx or -1)
for n = new_routing_start_idx, rt.EntriesNext.Size do
rt.EntriesNext[n].NextEntryIndex = (n + 1 <= rt.EntriesNext.Size) and (n + 1) or -1
index[key - ImGuiKey.NamedKey_BEGIN + 1] = (new_routing_start_idx <= entries_next.Size and new_routing_start_idx or -1)
for n = new_routing_start_idx, entries_next.Size do
entries_next[n].NextEntryIndex = (n + 1 <= entries_next.Size) and (n + 1) or -1
end
end
rt.Entries:swap(rt.EntriesNext) -- Swap new and old indexes
@@ -9957,7 +9979,10 @@ local function CalcWindowSizeAfterConstraint(window, size_desired)
-- Minimum size
local size_min = CalcWindowMinSize(window)
return ImMax(new_size, size_min)
-- [Luau] ImMax(new_size, size_min) written into new_size (a local copy)
new_size.x = math.max(new_size.x, size_min.x)
new_size.y = math.max(new_size.y, size_min.y)
return new_size
end
--- @param window ImGuiWindow
@@ -10164,7 +10189,9 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c
-- We only clip interaction so we overwrite window.ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
local clip_with_viewport_rect = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasMouseHoveredViewport) == 0 or g.IO.MouseHoveredViewport ~= window.ViewportId or bit32.band(window.Viewport.Flags, ImGuiViewportFlags.NoDecoration) == 0
if (clip_with_viewport_rect) then
ImRect_Copy(window.ClipRect, window.Viewport:GetMainRect())
-- [Luau] ImRect_Copy(window.ClipRect, window.Viewport:GetMainRect()) without the temporary ImRect
local vp, cr = window.Viewport, window.ClipRect
cr.Min.x = vp.Pos.x; cr.Min.y = vp.Pos.y; cr.Max.x = vp.Pos.x + vp.Size.x; cr.Max.y = vp.Pos.y + vp.Size.y
end
local clamp_rect = ImRect()
@@ -10369,6 +10396,7 @@ end
--- @param pos ImVec2
--- @param wrap_pos_x float
--- @return float
@native
function ImGui.CalcWrapWidthForPos(pos, wrap_pos_x)
if wrap_pos_x < 0.0 then
return 0.0
@@ -10403,12 +10431,18 @@ end
@native
function ImGui.FindRenderedTextEnd(text, text_end)
local text_display_end = 1
local text_len = #text
if not text_end then
text_end = text_len + 1
if type(text) == "string" then
-- [Luau] inline ImMemchr() for strings; string.len(): `#` on a string isn't a native fast path
if not text_end then
text_end = string.len(text) + 1
end
text_display_end = string.find(text, "##", 1, true) or text_end
else
if not text_end then
text_end = #text + 1
end
text_display_end = ImMemchr(text, "##", 1) or text_end
end
text_display_end = ImMemchr(text, "##", 1) or text_end
text_display_end = math.min(text_display_end, text_end) -- [Luau] scalar ImMin()
return text_display_end
@@ -10452,6 +10486,7 @@ end
--- @param text string
--- @param text_end int?
--- @param wrap_width float
@native
function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width)
local g = GImGui
local window = g.CurrentWindow
@@ -10530,6 +10565,7 @@ end
--- @param text_size_if_known? ImVec2
--- @param align? ImVec2
--- @param clip_rect? ImRect
@native
function ImGui.RenderTextClipped(pos_min, pos_max, text, text_end, text_size_if_known, align, clip_rect)
if not align then align = RenderTextClipped_align0 end
@@ -10795,12 +10831,15 @@ local function RenderWindowOuterSingleBorder(window, border_n, border_col, borde
window.DrawList:PathStroke(border_col, border_size)
end
local RenderWindowOuterBorders_max = ImVec2() -- [Luau] scratch, AddRect() only reads it
local function RenderWindowOuterBorders(window)
local g = GImGui
local border_size = window.WindowBorderSize
local border_col = ImGui.GetColorU32(ImGuiCol.Border)
if border_size > 0.0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoBackground) == 0) then
window.DrawList:AddRect(window.Pos, window.Pos + window.Size, border_col, window.WindowRounding, window.WindowBorderSize, 0)
local p_max = RenderWindowOuterBorders_max
p_max.x = window.Pos.x + window.Size.x; p_max.y = window.Pos.y + window.Size.y
window.DrawList:AddRect(window.Pos, p_max, border_col, window.WindowRounding, window.WindowBorderSize, 0)
elseif border_size > 0.0 then
if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then -- Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
RenderWindowOuterSingleBorder(window, 1, border_col, border_size)
@@ -10830,6 +10869,7 @@ end
--- @param handle_borders_and_resize_grips bool
--- @param resize_grip_col ImU32[]
--- @param resize_grip_draw_size float
local Begin_viewport_rect, Begin_visibility_rect = ImRect(), ImRect() -- [Luau] Begin() scratch, see there
-- [Luau] scratch for RenderWindowDecorations()/RenderWindowTitleBarContents(): callees only read or copy these
local WindowDecoScratch = { text_size = ImVec2(), layout_r = ImRect(), clip_r = ImRect(), bg_rect = ImRect(), p = ImVec2(), title_bar_rect = ImRect() }
@@ -11667,6 +11707,7 @@ function ImGui.SetLastItemDataForChildWindowItem(window, rect)
ImGui.SetLastItemData(window.ChildId, g.CurrentItemFlags, window.DC.ChildItemStatusFlags or 0, rect)
end
local EndChild_size, EndChild_bb = ImVec2(), ImRect()
function ImGui.EndChild()
local g = GImGui
local child_window = g.CurrentWindow
@@ -11675,11 +11716,14 @@ function ImGui.EndChild()
IM_ASSERT(bit32.band(child_window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0) -- Mismatched BeginChild()/EndChild() calls
g.WithinEndChildID = child_window.ID
local child_size = ImVec2(child_window.Size.x, child_window.Size.y)
local child_size_x, child_size_y = child_window.Size.x, child_window.Size.y -- [Luau] scalar copy
ImGui.End()
if child_window.BeginCount == 1 then
local parent_window = g.CurrentWindow
local bb = ImRect(parent_window.DC.CursorPos, parent_window.DC.CursorPos + child_size)
-- [Luau] scratch size/bb filled after End(): ItemSize()/ItemAdd() copy or read them, RenderNavCursor() reads bb
local child_size, bb, cursor = EndChild_size, EndChild_bb, parent_window.DC.CursorPos
child_size.x = child_size_x; child_size.y = child_size_y
bb.Min.x = cursor.x; bb.Min.y = cursor.y; bb.Max.x = cursor.x + child_size_x; bb.Max.y = cursor.y + child_size_y
ImGui.ItemSize(child_size)
local nav_flattened = bit32.band(child_window.ChildFlags, ImGuiChildFlags.NavFlattened) ~= 0
if (child_window.DC.NavLayersActiveMask ~= 0 or child_window.DC.NavWindowHasScrollY) and not nav_flattened then
@@ -12454,11 +12498,14 @@ function ImGui.Begin(name, open, flags)
if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and bit32.band(flags, ImGuiWindowFlags.NoCollapse) == 0 and not window.DockIsActive then
-- We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed),
-- so verify that we don't have items over the title bar.
local title_bar_rect = window:TitleBarRect()
if g.HoveredWindow == window and g.HoveredId == 0 and g.HoveredIdPreviousFrame == 0 and g.ActiveId == 0 and ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) then
if g.IO.MouseClickedCount[0] == 2 and ImGui.GetKeyOwner(ImGuiKey.MouseLeft) == ImGuiKeyOwner_NoOwner then
window.WantCollapseToggle = true
ImGui.SetKeyOwner(ImGuiKey.MouseLeft, window.MoveId) -- Claim input the same way ButtonBehavior() does. Prevent a same-frame move from triggering other items. (#9439)
-- [Luau] title bar rect only built when the cheaper tests pass
if g.HoveredWindow == window and g.HoveredId == 0 and g.HoveredIdPreviousFrame == 0 and g.ActiveId == 0 then
local title_bar_rect = window:TitleBarRect()
if ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) then
if g.IO.MouseClickedCount[0] == 2 and ImGui.GetKeyOwner(ImGuiKey.MouseLeft) == ImGuiKeyOwner_NoOwner then
window.WantCollapseToggle = true
ImGui.SetKeyOwner(ImGuiKey.MouseLeft, window.MoveId) -- Claim input the same way ButtonBehavior() does. Prevent a same-frame move from triggering other items. (#9439)
end
end
end
if window.WantCollapseToggle then
@@ -12477,14 +12524,13 @@ function ImGui.Begin(name, open, flags)
-- Outer Decoration Sizes
-- (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
local scrollbar_sizes_from_last_frame = ImVec2()
ImVec2_Copy(scrollbar_sizes_from_last_frame, window.ScrollbarSizes)
local scrollbar_sizes_from_last_frame_x, scrollbar_sizes_from_last_frame_y = window.ScrollbarSizes.x, window.ScrollbarSizes.y -- [Luau] scalar copy
window.DecoOuterSizeX1 = 0.0
window.DecoOuterSizeX2 = 0.0
window.DecoOuterSizeY1 = window.TitleBarHeight + window.MenuBarHeight
window.DecoOuterSizeY2 = 0.0
window.ScrollbarSizes = ImVec2(0.0, 0.0)
window.ScrollbarSizes.x = 0.0; window.ScrollbarSizes.y = 0.0 -- [Luau] in place
-- Calculate auto-fit size, handle automatic resize
-- - Using SetNextWindowSize() overrides ImGuiWindowFlags.AlwaysAutoResize, so it can be used on tooltips/popups, etc.
@@ -12504,8 +12550,12 @@ function ImGui.Begin(name, open, flags)
size_auto_fit_mask = bit32.bor(size_auto_fit_mask, bit32.lshift(1, ImGuiAxis.Y - 1))
end
local size_auto_fit = CalcWindowAutoFitSize(window, window.ContentSizeIdeal, size_auto_fit_mask)
local old_size = ImVec2(window.SizeFull.x, window.SizeFull.y)
-- [Luau] the auto-fit size is only read when an axis auto-fits: not computed otherwise (unless a size callback would see the call)
local size_auto_fit
if size_auto_fit_mask ~= 0 or (bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 and g.NextWindowData.SizeCallback) then
size_auto_fit = CalcWindowAutoFitSize(window, window.ContentSizeIdeal, size_auto_fit_mask)
end
local old_size_x, old_size_y = window.SizeFull.x, window.SizeFull.y -- [Luau] scalar copy
if size_auto_fit_x_always or size_auto_fit_x_current then
if size_auto_fit_x_always then
@@ -12532,7 +12582,7 @@ function ImGui.Begin(name, open, flags)
use_current_size_for_scrollbar_y = true
end
if old_size.x ~= window.SizeFull.x or old_size.y ~= window.SizeFull.y then
if old_size_x ~= window.SizeFull.x or old_size_y ~= window.SizeFull.y then
ImGui.MarkIniSettingsDirty(window)
end
end
@@ -12574,7 +12624,9 @@ function ImGui.Begin(name, open, flags)
-- Late create viewport if we don't fit within our current host viewport.
if window.ViewportAllowPlatformMonitorExtend >= 0 and not window.ViewportOwned and bit32.band(window.Viewport.Flags, ImGuiViewportFlags.IsMinimized) == 0 then
if not window.Viewport:GetMainRect():Contains(window:Rect()) then
-- [Luau] scalar version of: if not window.Viewport:GetMainRect():Contains(window:Rect()) then
local vp, wp, ws = window.Viewport, window.Pos, window.Size
if not (wp.x >= vp.Pos.x and wp.x + ws.x <= vp.Pos.x + vp.Size.x and wp.y >= vp.Pos.y and wp.y + ws.y <= vp.Pos.y + vp.Size.y) then
-- This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
-- local old_viewport = window.Viewport
window.Viewport = ImGui.AddUpdateViewport(window, window.ID, window.Pos, window.Size, ImGuiViewportFlags.NoFocusOnAppearing)
@@ -12592,10 +12644,19 @@ function ImGui.Begin(name, open, flags)
-- Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
-- When clamping to stay visible, we will enforce that window.Pos stays inside of visibility_rect.
local viewport_rect = window.Viewport:GetMainRect()
local viewport_work_rect = window.Viewport:GetWorkRect()
local visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding)
local visibility_rect = ImRect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding)
-- [Luau] scratch rects filled in place (only read, last read by PushClipRect() below; no nested Begin() in between), scalar padding
local viewport_rect = Begin_viewport_rect
do
local vp = window.Viewport
local r_min, r_max = viewport_rect.Min, viewport_rect.Max
r_min.x = vp.Pos.x; r_min.y = vp.Pos.y; r_max.x = vp.Pos.x + vp.Size.x; r_max.y = vp.Pos.y + vp.Size.y
end
local work_pos, work_size = window.Viewport.WorkPos, window.Viewport.WorkSize
local visibility_padding_x = ImMax(style.DisplayWindowPadding.x, style.DisplaySafeAreaPadding.x)
local visibility_padding_y = ImMax(style.DisplayWindowPadding.y, style.DisplaySafeAreaPadding.y)
local visibility_rect = Begin_visibility_rect
visibility_rect.Min.x = work_pos.x + visibility_padding_x; visibility_rect.Min.y = work_pos.y + visibility_padding_y
visibility_rect.Max.x = (work_pos.x + work_size.x) - visibility_padding_x; visibility_rect.Max.y = (work_pos.y + work_size.y) - visibility_padding_y
-- Clamp position/size so window stays visible within its viewport or monitor
-- Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
@@ -12693,18 +12754,24 @@ function ImGui.Begin(name, open, flags)
-- When reading the current size we need to read it after size constraints have been applied.
-- Intentionally use previous frame values for InnerRect and ScrollbarSizes.
-- And when we use window.DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
local avail_size_from_current_frame = ImVec2(window.SizeFull.x, window.SizeFull.y - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2))
local avail_size_from_last_frame = window.InnerRect:GetSize() + scrollbar_sizes_from_last_frame
local needed_size_from_last_frame = window_just_created and ImVec2(0, 0) or window.ContentSize + window.WindowPadding * 2.0
-- [Luau] scalar avail/needed sizes
local avail_size_from_current_frame_x, avail_size_from_current_frame_y = window.SizeFull.x, window.SizeFull.y - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2)
local inner_rect = window.InnerRect
local avail_size_from_last_frame_x = (inner_rect.Max.x - inner_rect.Min.x) + scrollbar_sizes_from_last_frame_x
local avail_size_from_last_frame_y = (inner_rect.Max.y - inner_rect.Min.y) + scrollbar_sizes_from_last_frame_y
local needed_size_from_last_frame_x, needed_size_from_last_frame_y = 0, 0
if not window_just_created then
needed_size_from_last_frame_x = window.ContentSize.x + window.WindowPadding.x * 2.0; needed_size_from_last_frame_y = window.ContentSize.y + window.WindowPadding.y * 2.0
end
local size_for_scrollbars_x = use_current_size_for_scrollbar_x and avail_size_from_current_frame.x or avail_size_from_last_frame.x
local size_for_scrollbars_y = use_current_size_for_scrollbar_y and avail_size_from_current_frame.y or avail_size_from_last_frame.y
local size_for_scrollbars_x = use_current_size_for_scrollbar_x and avail_size_from_current_frame_x or avail_size_from_last_frame_x
local size_for_scrollbars_y = use_current_size_for_scrollbar_y and avail_size_from_current_frame_y or avail_size_from_last_frame_y
local scrollbar_x_prev = window.ScrollbarX
-- local scrollbar_y_from_last_frame = window.ScrollbarY -- FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
window.ScrollbarY = (bit32.band(flags, ImGuiWindowFlags.AlwaysVerticalScrollbar) ~= 0) or ((needed_size_from_last_frame.y > size_for_scrollbars_y) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0))
window.ScrollbarX = (bit32.band(flags, ImGuiWindowFlags.AlwaysHorizontalScrollbar) ~= 0) or ((needed_size_from_last_frame.x > size_for_scrollbars_x - (window.ScrollbarY and style.ScrollbarSize or 0.0)) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0) and (bit32.band(flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0))
window.ScrollbarY = (bit32.band(flags, ImGuiWindowFlags.AlwaysVerticalScrollbar) ~= 0) or ((needed_size_from_last_frame_y > size_for_scrollbars_y) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0))
window.ScrollbarX = (bit32.band(flags, ImGuiWindowFlags.AlwaysHorizontalScrollbar) ~= 0) or ((needed_size_from_last_frame_x > size_for_scrollbars_x - (window.ScrollbarY and style.ScrollbarSize or 0.0)) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0) and (bit32.band(flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0))
-- Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488)
-- (Feedback loops of this sort can manifest in various situations, but combining horizontal + vertical scrollbar + using a clipper with varying width items is one frequent cause.
@@ -12725,10 +12792,10 @@ function ImGui.Begin(name, open, flags)
window.ScrollbarXStabilizeEnabled = scrollbar_x_stabilize
if window.ScrollbarX and not window.ScrollbarY then
window.ScrollbarY = (needed_size_from_last_frame.y > size_for_scrollbars_y - style.ScrollbarSize) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0)
window.ScrollbarY = (needed_size_from_last_frame_y > size_for_scrollbars_y - style.ScrollbarSize) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0)
end
window.ScrollbarSizes = ImVec2(window.ScrollbarY and style.ScrollbarSize or 0.0, window.ScrollbarX and style.ScrollbarSize or 0.0)
window.ScrollbarSizes.x = window.ScrollbarY and style.ScrollbarSize or 0.0; window.ScrollbarSizes.y = window.ScrollbarX and style.ScrollbarSize or 0.0 -- [Luau] in place
-- Amend the partially filled window.DecorationXXX values.
window.DecoOuterSizeX2 = window.DecoOuterSizeX2 + window.ScrollbarSizes.x
@@ -12750,9 +12817,11 @@ function ImGui.Begin(name, open, flags)
else
host_rect = viewport_rect
end
local outer_rect = window:Rect()
local title_bar_rect = window:TitleBarRect()
ImRect_Copy(window.OuterRectClipped, outer_rect)
do -- [Luau] ImRect_Copy(window.OuterRectClipped, window:Rect()) without the temporary ImRect
local r = window.OuterRectClipped
r.Min.x = window.Pos.x; r.Min.y = window.Pos.y; r.Max.x = window.Pos.x + window.Size.x; r.Max.y = window.Pos.y + window.Size.y
end
if window.DockIsActive then
window.OuterRectClipped.Min.y = window.OuterRectClipped.Min.y + window.TitleBarHeight
end
@@ -12827,7 +12896,9 @@ function ImGui.Begin(name, open, flags)
end
local previous_child_overlapping
if previous_child ~= nil then
previous_child_overlapping = previous_child:Rect():Overlaps(window:Rect())
-- [Luau] scalar previous_child:Rect():Overlaps(window:Rect())
local pp, ps, wp, ws = previous_child.Pos, previous_child.Size, window.Pos, window.Size
previous_child_overlapping = pp.x <= wp.x + ws.x and pp.x + ps.x >= wp.x and pp.y <= wp.y + ws.y and pp.y + ps.y >= wp.y
else
previous_child_overlapping = false
end
@@ -13540,6 +13611,7 @@ function ImGui.GetMergedModsFromKeys()
return mods
end
@native
function ImGui.UpdateKeyboardInputs()
local g = GImGui
local io = g.IO
@@ -13581,14 +13653,15 @@ function ImGui.UpdateKeyboardInputs()
end
-- Update keys
local keys_data, delta_time = io.KeysData, io.DeltaTime -- [Luau] cached field reads
for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do
local key_data = io.KeysData[key - ImGuiKey.NamedKey_BEGIN]
local key_data = keys_data[key - ImGuiKey.NamedKey_BEGIN]
key_data.DownDurationPrev = key_data.DownDuration
if key_data.Down then
if key_data.DownDuration < 0.0 then
key_data.DownDuration = 0.0
else
key_data.DownDuration = key_data.DownDuration + io.DeltaTime
key_data.DownDuration = key_data.DownDuration + delta_time
end
else
key_data.DownDuration = -1.0
@@ -13603,9 +13676,10 @@ function ImGui.UpdateKeyboardInputs()
end
-- Update keys/input owner (named keys only): one entry per key
local keys_owner_data = g.KeysOwnerData -- [Luau] cached field read
for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do
local key_data = io.KeysData[key - ImGuiKey.NamedKey_BEGIN]
local owner_data = g.KeysOwnerData[key - ImGuiKey.NamedKey_BEGIN]
local key_data = keys_data[key - ImGuiKey.NamedKey_BEGIN]
local owner_data = keys_owner_data[key - ImGuiKey.NamedKey_BEGIN]
owner_data.OwnerCurr = owner_data.OwnerNext
if not key_data.Down then -- Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
owner_data.OwnerNext = ImGuiKeyOwner_NoOwner
@@ -13979,6 +14053,7 @@ function ImGui.GetScale()
end
--- @return ImGuiWindow
@native
function ImGui.GetCurrentWindowRead()
local g = GImGui
return g.CurrentWindow
@@ -13987,9 +14062,9 @@ end
--- @return ImGuiWindow
@native
function ImGui.GetCurrentWindow()
local g = GImGui
g.CurrentWindow.WriteAccessed = true
return g.CurrentWindow
local window = GImGui.CurrentWindow -- [Luau] one read: CurrentWindow sits in a hash slot the inline cache can't predict
window.WriteAccessed = true
return window
end
-- Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
@@ -14688,7 +14763,8 @@ end
--- @return ImVec2
@native
function ImGui.CalcTextSize(text, text_end, hide_text_after_double_hash, wrap_width)
return ImGui.CalcTextSizeEx(text, 1, text_end, hide_text_after_double_hash, wrap_width)
local x, y = ImGui.CalcTextSizeXY(text, 1, text_end, hide_text_after_double_hash, wrap_width) -- [Luau] inline CalcTextSizeEx()
return ImVec2(x, y)
end
--- @param text ImString
@@ -15090,13 +15166,22 @@ end
-- FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
--- @param idx ImGuiCol
--- @param col ImU32|ImVec4
@native
function ImGui.PushStyleColor(idx, col)
local g = GImGui
local backup = ImGuiColorMod(idx, g.Style.Colors[idx])
-- [Luau] inline g.ColorStack:push_back(backup)
-- [Luau] inline g.ColorStack:push_back(backup); C++ copies the ImGuiColorMod into the vector's storage: reuse the
-- entry a PopStyleColor() left past Size instead of allocating one per push
local stack = g.ColorStack
local n = stack.Size + 1
if n > stack.Capacity then stack:push_back(backup) else stack.Data[n] = backup; stack.Size = n end
local backup = (n <= stack.Capacity) and stack.Data[n] or nil
if backup then
backup.Col = idx
ImVec4_Copy(backup.BackupValue, g.Style.Colors[idx])
stack.Size = n
else
backup = ImGuiColorMod(idx, g.Style.Colors[idx])
if n > stack.Capacity then stack:push_back(backup) else stack.Data[n] = backup; stack.Size = n end
end
if g.DebugFlashStyleColorIdx ~= idx then
if type(col) == "number" then
ImGui.ColorConvertU32ToFloat4(col, g.Style.Colors[idx])
@@ -15107,6 +15192,7 @@ function ImGui.PushStyleColor(idx, col)
end
--- @param count? int
@native
function ImGui.PopStyleColor(count)
if count == nil then count = 1 end
@@ -15181,6 +15267,25 @@ function ImGui.GetStyleVarInfo(idx)
return GStyleVarsInfo[idx + 1]
end
-- [Luau] g.StyleVarStack:push_back(ImGuiStyleMod(idx, v)); C++ copies the ImGuiStyleMod into the vector's storage:
-- reuse the entry a PopStyleVar() left past Size instead of allocating two tables per push
local function PushStyleMod(g, idx, v)
local stack = g.StyleVarStack
local n = stack.Size + 1
local mod = (n <= stack.Capacity) and stack.Data[n] or nil
if mod then
mod.VarIdx = idx
if type(v) == "number" then
mod.BackupVal[1] = v; mod.BackupVal[2] = nil
else -- ImVec2
mod.BackupVal[1] = v.x; mod.BackupVal[2] = v.y
end
stack.Size = n
else
stack:push_back(ImGuiStyleMod(idx, v))
end
end
--- @param idx ImGuiStyleVar
--- @param val float|ImVec2
function ImGui.PushStyleVar(idx, val)
@@ -15192,7 +15297,7 @@ function ImGui.PushStyleVar(idx, val)
IM_ASSERT_USER_ERROR_RET(var_info.DataType == ImGuiDataType.Float and var_info.Count == 2, "Calling PushStyleVar() with wrong type!")
end
local var = g.Style[var_info.Key]
g.StyleVarStack:push_back(ImGuiStyleMod(idx, var))
PushStyleMod(g, idx, var)
if type(val) == "number" then
g.Style[var_info.Key] = val
else -- [Port] copy into the style's own ImVec2: storing the caller's vector would alias it into the style forever
@@ -15207,7 +15312,7 @@ function ImGui.PushStyleVarX(idx, val_x)
local var_info = ImGui.GetStyleVarInfo(idx)
IM_ASSERT_USER_ERROR_RET(var_info.DataType == ImGuiDataType.Float and var_info.Count == 2, "Calling PushStyleVarX() with wrong type!")
local pvar = g.Style[var_info.Key]
g.StyleVarStack:push_back(ImGuiStyleMod(idx, pvar))
PushStyleMod(g, idx, pvar)
pvar.x = val_x
end
@@ -15218,7 +15323,7 @@ function ImGui.PushStyleVarY(idx, val_y)
local var_info = ImGui.GetStyleVarInfo(idx)
IM_ASSERT_USER_ERROR_RET(var_info.DataType == ImGuiDataType.Float and var_info.Count == 2, "Calling PushStyleVarY() with wrong type!")
local pvar = g.Style[var_info.Key]
g.StyleVarStack:push_back(ImGuiStyleMod(idx, pvar))
PushStyleMod(g, idx, pvar)
pvar.y = val_y
end
@@ -15248,6 +15353,7 @@ end
-- ATTENTION THIS IS IN LEGACY LOCAL SPACE.
--- @param wrap_local_pos_x float
@native
function ImGui.PushTextWrapPos(wrap_local_pos_x)
local g = GImGui
local window = g.CurrentWindow
@@ -15259,6 +15365,7 @@ function ImGui.PushTextWrapPos(wrap_local_pos_x)
dc.TextWrapPos = wrap_local_pos_x
end
@native
function ImGui.PopTextWrapPos()
local g = GImGui
local window = g.CurrentWindow
@@ -20896,6 +21003,7 @@ function ImGui.DebugNodeFontGlyph(font, glyph)
ImGui.Text("SourceIdx: %d", glyph.SourceIdx)
end
@native
function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask)
local draw_list = ImGui.GetWindowDrawList()
local glyph_col = ImGui.GetColorU32(ImGuiCol.Text)
+99 -26
View File
@@ -349,6 +349,7 @@ end
--- @param gradient_p1 ImVec2
--- @param col0 ImU32
--- @param col1 ImU32
@native
function ImGui.ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col0, col1)
local gradient_extent = gradient_p1 - gradient_p0
local gradient_inv_length2 = 1.0 / ImLengthSqr(gradient_extent)
@@ -637,6 +638,10 @@ function MT.ImFontAtlas:ClearFonts()
end
end
-- [Luau] Pixels of the last atlas texture removed after the backend destroyed it: the next ImTextureData:Create() of
-- the same byte size (atlas repack: same size every time) zero-fills and reuses it instead of allocating a new table
local RecycledTexPixels, RecycledTexPixelsSize = nil, 0
--- @param tex ImTextureData
function ImTextureDataUpdateNewFrame(tex)
local remove_from_list = false
@@ -709,6 +714,9 @@ function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures)
if remove_from_list then
IM_ASSERT(atlas.TexData ~= tex)
if tex.Pixels ~= nil then
RecycledTexPixels, RecycledTexPixelsSize = tex.Pixels, tex.Width * tex.Height * tex.BytesPerPixel
end
tex:DestroyPixels()
atlas.TexList:erase(tex_n)
tex_n = tex_n - 1
@@ -1025,6 +1033,10 @@ function ImFontAtlasRemoveDrawListSharedData(atlas, data)
atlas.DrawListSharedDatas:find_erase(data)
end
-- [Luau] RectsIndex index of the entry the repack loop is re-adding: ImFontAtlasPackReuseRectEntry() checks it before
-- searching RectsIndex (index_from_ptr is a linear search: O(n^2) per repack otherwise)
local ImFontAtlasPackReuseIndexHint = nil
--- @param atlas ImFontAtlas
--- @param w int
--- @param h int
@@ -1052,7 +1064,7 @@ local function ImFontAtlasTextureRepack(atlas, w, h)
local old_index = builder.RectsIndex:copy()
old_rects:swap(builder.Rects)
for _, index_entry in builder.RectsIndex:iter() do
for index_n, index_entry in builder.RectsIndex:iter() do
repeat
if index_entry.IsUsed == false then
break
@@ -1063,7 +1075,9 @@ local function ImFontAtlasTextureRepack(atlas, w, h)
break
end
ImFontAtlasPackReuseIndexHint = index_n - 1
local new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, index_entry)
ImFontAtlasPackReuseIndexHint = nil
if new_r_id == ImFontAtlasRectId_Invalid then
-- Undo, grow texture and try repacking again.
-- FIXME-NEWATLAS-TESTS: This is a very rarely exercised path! It needs to be automatically tested properly.
@@ -1078,7 +1092,7 @@ local function ImFontAtlasTextureRepack(atlas, w, h)
return
end
IM_ASSERT(ImFontAtlasRectId_GetIndex(new_r_id) == builder.RectsIndex:index_from_ptr(index_entry))
IM_ASSERT(ImFontAtlasRectId_GetIndex(new_r_id) == index_n - 1) -- [Luau] == RectsIndex:index_from_ptr(index_entry)
local new_r = ImFontAtlasPackGetRect(atlas, new_r_id)
ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r.x, new_r.y, new_r.w, new_r.h)
@@ -1193,7 +1207,10 @@ end
local function ImFontAtlasPackReuseRectEntry(atlas, index_entry)
IM_ASSERT(index_entry.IsUsed)
index_entry.TargetIndex = atlas.Builder.Rects.Size - 1
local index_idx = atlas.Builder.RectsIndex:index_from_ptr(index_entry)
local index_idx = ImFontAtlasPackReuseIndexHint
if index_idx == nil or atlas.Builder.RectsIndex.Data[index_idx + 1] ~= index_entry then
index_idx = atlas.Builder.RectsIndex:index_from_ptr(index_entry)
end
return ImFontAtlasRectId_Make(index_idx, index_entry.Generation)
end
@@ -2705,7 +2722,18 @@ function MT.ImTextureData:Create(format, w, h)
self.BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format)
self.UseColors = false
local n = self.Width * self.Height * self.BytesPerPixel
if table.create then
if RecycledTexPixels ~= nil and RecycledTexPixelsSize == n then
-- [Luau] same contents as memset: zero the first block, then double it with table.move (native copies)
local p, k = RecycledTexPixels, math.min(n, 4096)
RecycledTexPixels, RecycledTexPixelsSize = nil, 0
for i = 1, k do p[i] = 0 end
while k < n do
local c = math.min(k, n - k)
table.move(p, 1, c, k + 1)
k = k + c
end
self.Pixels = p
elseif table.create then
self.Pixels = table.create(n, 0) -- [Luau] native zero fill, same contents as memset
else
self.Pixels = {}
@@ -2807,6 +2835,7 @@ end
-- Find glyph, load if necessary, return fallback if missing
--- @param c ImWchar
--- @return ImFontGlyph?
@native
function MT.ImFontBaked:FindGlyph(c)
if c < self.IndexLookup.Size then
local i = self.IndexLookup.Data[c + 1]
@@ -3011,6 +3040,7 @@ end
--- @param size float
--- @param density float?
--- @return ImFontBaked?
@native
function MT.ImFont:GetFontBaked(size, density)
if not density then density = -1.0 end
@@ -3292,7 +3322,10 @@ local ImFontCalcWordWrapPositionEx_Uncached
local WRAP_MEMO_MAX = 4096
function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_width, flags)
local baked = font:GetFontBaked(size)
local baked = font.LastBaked -- [Luau] inline font:GetFontBaked(size) fast path
if not (baked and baked.Size == math.floor(size + 0.5) and baked.RasterizerDensity == font.CurrentRasterizerDensity) then
baked = font:GetFontBaked(size)
end
if type(text) ~= "string" then
return ImFontCalcWordWrapPositionEx_Uncached(baked, size, text, pos, text_end, wrap_width, flags)
end
@@ -3481,11 +3514,14 @@ function ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begi
-- Advances of a baked font never change once loaded, so entries stay valid.
local cache_key = nil
local wrap_cache = nil
local text_len1 = text_is_str and #text + 1 or -1
local text_len1 = text_is_str and string.len(text) + 1 or -1 -- [Luau] string.len(): `#` on a string isn't a native fast path
local baked = font.LastBaked -- [Luau] inline font:GetFontBaked(size) fast path (same baked as the calls below in upstream)
if not (baked and baked.Size == math.floor(size + 0.5) and baked.RasterizerDensity == font.CurrentRasterizerDensity) then
baked = font:GetFontBaked(size)
end
local cacheable = text_is_str and text_begin == 1 and out_offset == nil and max_width >= FLT_MAX
and (text_end == nil or text_end == text_len1) and (text_end_display == nil or text_end_display == text_len1) and (flags == nil or bit32.band(flags, ImDrawTextFlags.StopOnNewLine) == 0)
if cacheable and wrap_width <= 0.0 then
local baked = font:GetFontBaked(size)
local cache = baked._TextSizeCache
if cache == nil or baked._TextSizeCacheN >= TEXT_SIZE_CACHE_MAX then
cache = {}; baked._TextSizeCache = cache; baked._TextSizeCacheN = 0
@@ -3497,7 +3533,6 @@ function ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begi
cache_key = text
elseif cacheable and wrap_width > 0.0 then
-- [Luau] same for wrapped text (TextWrapped() measures every line every frame): exact results per (size, wrap width, text)
local baked = font:GetFontBaked(size)
local cache = baked._TextSizeCache
if cache == nil or baked._TextSizeCacheN >= TEXT_SIZE_CACHE_MAX then
cache = {}; baked._TextSizeCache = cache; baked._TextSizeCacheN = 0
@@ -3519,7 +3554,6 @@ function ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begi
text_end_display = text_end
end
local baked = font:GetFontBaked(size)
local line_height = size
local scale = line_height / baked.Size
@@ -4288,7 +4322,12 @@ function MT.ImDrawList:_ResetForNewFrame()
self.Flags = self._Data.InitialDrawFlags
IM_ASSERT(bit32.band(self.Flags, bit32.bnot(ImDrawFlags.AllowInFrameScope_)) == 0)
self._CmdHeader = ImDrawCmdHeader() -- memset(&_CmdHeader, 0, sizeof(_CmdHeader))
-- memset(&_CmdHeader, 0, sizeof(_CmdHeader)) -- [Luau] in place, no new table per frame
local header = self._CmdHeader
local hcr = header.ClipRect
hcr.x = 0; hcr.y = 0; hcr.z = 0; hcr.w = 0
header.TexRef = nil
header.VtxOffset = 0
self._VtxCurrentIdx = 1
self._VtxWritePtr = 1
@@ -4299,7 +4338,7 @@ function MT.ImDrawList:_ResetForNewFrame()
self._DrawFlagsStack.Size = 0 -- [Port] _DrawFlagsStack.clear() (ImSmallStack_)
self._Path:resize(0)
self.CmdBuffer:push_back(ImDrawCmd())
self:AddDrawCmd() -- [Luau] C++ push_back(ImDrawCmd()): same zeroed command (the header was just zeroed), reuses last frame's object
-- Caller needs to bet _SetPixelDensity() as well.
end
@@ -4345,18 +4384,33 @@ function MT.ImDrawList:CloneOutput()
return dst
end
@native
function MT.ImDrawList:AddDrawCmd()
local draw_cmd = ImDrawCmd()
ImVec4_Copy(draw_cmd.ClipRect, self._CmdHeader.ClipRect) -- Same as calling ImDrawCmd_HeaderCopy()
draw_cmd.TexRef = self._CmdHeader.TexRef
draw_cmd.VtxOffset = self._CmdHeader.VtxOffset
draw_cmd.IdxOffset = self.IdxBuffer.Size
IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z and draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w)
-- [Luau] inline self.CmdBuffer:push_back(draw_cmd)
-- [Luau] C++ constructs the command in the vector's storage, which keeps last frame's memory: reuse the command
-- object left past Size by resize(0)/pop_back() (Merge() takes channel commands out of their slots, nothing else
-- shares them) instead of allocating 3 tables per command per frame
local cmd_buffer = self.CmdBuffer
local n = cmd_buffer.Size + 1
local draw_cmd = (n <= cmd_buffer.Capacity) and cmd_buffer.Data[n] or nil
if draw_cmd then
draw_cmd.ElemCount = 0
draw_cmd.UserCallback = nil
draw_cmd.UserCallbackData = nil
draw_cmd.UserCallbackDataSize = 0
draw_cmd.UserCallbackDataOffset = 0
else
draw_cmd = ImDrawCmd()
end
local header = self._CmdHeader
local dcr, hcr = draw_cmd.ClipRect, header.ClipRect
dcr.x = hcr.x; dcr.y = hcr.y; dcr.z = hcr.z; dcr.w = hcr.w -- Same as calling ImDrawCmd_HeaderCopy()
draw_cmd.TexRef = header.TexRef
draw_cmd.VtxOffset = header.VtxOffset
draw_cmd.IdxOffset = self.IdxBuffer.Size
IM_ASSERT(dcr.x <= dcr.z and dcr.y <= dcr.w)
-- [Luau] inline self.CmdBuffer:push_back(draw_cmd)
if n > cmd_buffer.Capacity then cmd_buffer:push_back(draw_cmd) else cmd_buffer.Data[n] = draw_cmd; cmd_buffer.Size = n end
end
@@ -4475,6 +4529,7 @@ end
-- Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack.
-- The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only.
@native
function MT.ImDrawList:_OnChangedClipRect()
-- If current command is used with different settings we need to add a new command
IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0)
@@ -4637,7 +4692,11 @@ function MT.ImDrawListSplitter:Merge(draw_list)
-- Merge previous channel last draw command with current channel first draw command if matching.
last_cmd.ElemCount = last_cmd.ElemCount + next_cmd.ElemCount
idx_offset = idx_offset + next_cmd.ElemCount
cmds:erase(1) -- FIXME-OPT: Improve for multiple merges.
-- [Luau] cmds:erase(1), keeping the erased command object past Size for AddDrawCmd() to reuse
local d = cmds.Data
for k = 1, cmds.Size - 1 do d[k] = d[k + 1] end
d[cmds.Size] = next_cmd
cmds.Size = cmds.Size - 1 -- FIXME-OPT: Improve for multiple merges.
end
end
if cmds.Size > 0 then
@@ -4664,8 +4723,9 @@ function MT.ImDrawListSplitter:Merge(draw_list)
if ch._CmdBuffer.Size > 0 then
local src_cmds = ch._CmdBuffer.Data
for n = 1, ch._CmdBuffer.Size do
dst_cmds[cmd_write] = src_cmds[n]
src_cmds[n] = nil -- [Port] ownership moved to the draw list
-- [Port] ownership moved to the draw list; [Luau] the unused command object that was in the draw list's
-- slot goes to the channel's slot instead of nil (AddDrawCmd() reuses it: each object stays in one slot)
dst_cmds[cmd_write], src_cmds[n] = src_cmds[n], dst_cmds[cmd_write]
cmd_write = cmd_write + 1
end
end
@@ -4732,7 +4792,7 @@ function MT.ImDrawListSplitter:SetCurrentChannel(draw_list, idx)
curr_cmd.TexRef = header.TexRef
curr_cmd.VtxOffset = header.VtxOffset
elseif ccr.x ~= hcr.x or ccr.y ~= hcr.y or ccr.z ~= hcr.z or ccr.w ~= hcr.w
or curr_cmd.TexRef._TexData ~= header.TexRef._TexData or curr_cmd.TexRef._TexID ~= header.TexRef._TexID
or (curr_cmd.TexRef ~= header.TexRef and (curr_cmd.TexRef._TexData ~= header.TexRef._TexData or curr_cmd.TexRef._TexID ~= header.TexRef._TexID))
or curr_cmd.VtxOffset ~= header.VtxOffset then
draw_list:AddDrawCmd()
end
@@ -4834,6 +4894,7 @@ end
MT.ImDrawList.PrimReserve = PrimReserve
-- Release the number of reserved vertices/indices from the end of the last reservation made with PrimReserve().
@native
function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count)
IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0)
@@ -4890,6 +4951,7 @@ end
--- @param uv_a ImVec2
--- @param uv_c ImVec2
--- @param col any
@native
function MT.ImDrawList:PrimRectUV(a, c, uv_a, uv_c, col)
local idx = self._VtxCurrentIdx
local idx_data = self.IdxBuffer.Data; local vtx_data = self.VtxBuffer.Buf
@@ -7002,6 +7064,7 @@ function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius)
end
-- Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui.PushClipRect() to affect logic (hit-testing and widget culling)
@native
function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect)
-- [Luau] reuse the stack slot's ImVec4 left from earlier frames (each slot stays uniquely owned by the stack)
local stack = self._ClipRectStack
@@ -7036,6 +7099,7 @@ function MT.ImDrawList:PushClipRectFullScreen()
self:PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.z, cr.w))
end
@native
function MT.ImDrawList:PopClipRect()
local stack = self._ClipRectStack
IM_ASSERT(stack.Size > 0)
@@ -7178,6 +7242,7 @@ end
--- @param a_min float
--- @param a_max float
--- @param num_segments int
@native
function MT.ImDrawList:_PathArcToN(center, radius, a_min, a_max, num_segments)
if not (radius >= 0.25 * self._FringeScale) then -- [Port] !IM_HAS_ROUNDING(radius)
self._Path:push_back(center)
@@ -7288,7 +7353,10 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b
local line_height = size
local baked = self:GetFontBaked(size)
local baked = self.LastBaked -- [Luau] inline self:GetFontBaked(size) fast path
if not (baked and baked.Size == math.floor(size + 0.5) and baked.RasterizerDensity == self.CurrentRasterizerDensity) then
baked = self:GetFontBaked(size)
end
local scale = size / baked.Size
local origin_x = x
@@ -7692,6 +7760,8 @@ function ImGui.CalcRoundingFlagsForRectInRect(r_in, r_outer, threshold)
return flags
end
local Checkerboard_cell_min, Checkerboard_cell_max = ImVec2(), ImVec2()
-- Helper for ColorPicker4()
-- NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
-- Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether.
@@ -7704,6 +7774,7 @@ end
--- @param grid_off ImVec2
--- @param rounding? float
--- @param flags? ImDrawFlags
@native
function ImGui.RenderColorRectWithAlphaCheckerboard(draw_list, p_min, p_max, col, alpha, grid_step, grid_off, rounding, flags)
if rounding == nil then rounding = 0.0 end
if flags == nil then flags = 0 end
@@ -7754,7 +7825,9 @@ function ImGui.RenderColorRectWithAlphaCheckerboard(draw_list, p_min, p_max, col
end
local col_bg
if dual_layer then col_bg = col_bg2 elseif (yi + xi) % 2 == 1 then col_bg = col_bg2 else col_bg = col_bg1 end
draw_list:AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg, rounding, cell_flags)
local cell_min, cell_max = Checkerboard_cell_min, Checkerboard_cell_max -- [Luau] scratch: AddRectFilled() only reads them
cell_min.x = x1; cell_min.y = y1; cell_max.x = x2; cell_max.y = y2
draw_list:AddRectFilled(cell_min, cell_max, col_bg, rounding, cell_flags)
end
x = x + x_step
xi = xi + 1
+8 -1
View File
@@ -148,6 +148,7 @@ function ImGui.GetMetatables() return MT end
--- @param _EXPR any
--- @param _MSG string?
@native
function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end
IM_ASSERT_PARANOID = IM_ASSERT
@@ -395,12 +396,14 @@ local IM_VECTOR = {}
--- @param t ImVector
--- @param k string|int
--- @return any
IM_VECTOR.__index = function(t, k)
@native
local function IM_VECTOR_index(t, k)
local m = IM_VECTOR[k] -- [Port] methods first (hot path)
if m ~= nil then return m end
if k == "Data" then return nil end -- [Port] Data has already been discarded
return t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- [Port] if the mt access turns out nil, the k must be int index into Data
end
IM_VECTOR.__index = IM_VECTOR_index
--- @param t ImVector
--- @param k int
@@ -422,14 +425,18 @@ local function _grow_capacity(v, sz) local new_capacity = (v.Capacity ~= 0) and
--- @nodiscard
function ImVector(T, COPY_FUNC) return setmetatable({Data = nil, Size = 0, Capacity = 0, _Constructor = T or _default_constructor, _CopyFunc = COPY_FUNC or _default_copyfunc}, IM_VECTOR) end
@native
function IM_VECTOR:push_back(value) if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; self._CopyFunc(self.Data, self.Size + 1, value); self.Size = self.Size + 1; return value end
@native
function IM_VECTOR:pop_back() IM_ASSERT(self.Size > 0); self.Size = self.Size - 1; end
function IM_VECTOR:push_front(value) if self.Size == 0 then self:push_back(value) else self:insert(1, value) end end
function IM_VECTOR:clear() if self.Data then self.Size = 0; self.Capacity = 0; IM_FREE(self, "Data"); self.Data = nil end end
function IM_VECTOR:clear_delete() for i = 1, self.Size do self.Data[i] = nil end self.Size = 0 end
function IM_VECTOR:empty() return self.Size == 0 end
@native
function IM_VECTOR:back() IM_ASSERT(self.Size > 0) return self.Data[self.Size] end
function IM_VECTOR:erase(i) IM_ASSERT(i >= 1 and i <= self.Size) local removed = (table.remove(self.Data, i)) ~= nil self.Size = self.Size - 1 return removed end
@native
local function _iter(v, i) i = i + 1 if i <= v.Size then return i, v.Data[i] end end
function IM_VECTOR:iter() return _iter, self, 0 end
function IM_VECTOR:find_index(value) for i = 1, self.Size do if self.Data[i] == value then return i end end return nil end
+5 -1
View File
@@ -537,6 +537,7 @@ IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT = ((IM_DRAWLIST_TEX_LINES_DETAILED_WI
-- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling.
-- [Port] Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert.
function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error
@native
function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end
-- Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam.
@@ -577,6 +578,7 @@ ImGuiKeyOwner_NoOwner = 4294967295 -- Require key to have no owner.
function ImGui.MouseButtonToKey(button) IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) return ImGuiKey.MouseLeft + button end
--- @param key ImGuiKey
@native
function ImGui.IsNamedKey(key)
return key >= ImGuiKey.NamedKey_BEGIN and key < ImGuiKey.NamedKey_END
end
@@ -1449,6 +1451,7 @@ MT.ImGuiNextItemData = {}
MT.ImGuiNextItemData.__index = MT.ImGuiNextItemData
-- Also cleared manually by ItemAdd()!
@native
function MT.ImGuiNextItemData:ClearFlags()
self.HasFlags = ImGuiNextItemDataFlags.None
self.ItemFlagsSet = ImGuiItemFlags.None
@@ -1498,6 +1501,7 @@ end
MT.ImGuiNextWindowData = {}
MT.ImGuiNextWindowData.__index = MT.ImGuiNextWindowData
@native
function MT.ImGuiNextWindowData:ClearFlags()
self.HasFlags = ImGuiNextWindowDataFlags.None
end
@@ -2990,7 +2994,7 @@ end
--- @return ImRect
--- @nodiscard
function MT.ImGuiWindow:TitleBarRect()
return ImRect(self.Pos, ImVec2(self.Pos.x + self.SizeFull.x, self.Pos.y + self.TitleBarHeight))
return ImRect(self.Pos.x, self.Pos.y, self.Pos.x + self.SizeFull.x, self.Pos.y + self.TitleBarHeight) -- [Luau] scalar form: no temporary ImVec2
end
--- @return ImRect
+39 -9
View File
@@ -355,6 +355,8 @@ end
ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge)
local function Rect(r) return ImRect(r.Min.x, r.Min.y, r.Max.x, r.Max.y) end
-- [Luau] scratch rects for TableUpdateLayout()/TableMergeDrawChannels() locals that never escape
local TableUpdateLayout_work_rect, TableUpdateLayout_host_clip_rect, TableUpdateLayout_mouse_hit_rect, TableMergeDrawChannels_merge_clip_rect = ImRect(), ImRect(), ImRect(), ImRect()
local function V2(v) return ImVec2(v.x, v.y) end
-------------------------------------------------------------------------------
@@ -429,6 +431,7 @@ end
--- @param table_ ImGuiTable
--- @param instance_no int
@native
function ImGui.TableGetInstanceData(table_, instance_no)
if instance_no == 0 then
return table_.InstanceDataFirst
@@ -451,9 +454,10 @@ function ImGui.BeginTable(str_id, columns_count, flags, outer_size, inner_width)
return ImGui.BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width)
end
local BeginTableEx_outer_size_default = ImVec2(0.0, 0.0) -- [Luau] shared read-only default (only read below)
function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_width)
if flags == nil then flags = 0 end
if outer_size == nil then outer_size = ImVec2(0.0, 0.0) end
if outer_size == nil then outer_size = BeginTableEx_outer_size_default end
if inner_width == nil then inner_width = 0.0 end
local g = GImGui
@@ -477,8 +481,10 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi
-- - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[].
local use_child_window = band(flags, bor(ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY)) ~= 0
local avail_size = ImGui.GetContentRegionAvail()
local actual_outer_size = ImTrunc(ImGui.CalcItemSize(outer_size, mathMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window and mathMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) or 0.0))
local outer_rect = ImRect(outer_window.DC.CursorPos, outer_window.DC.CursorPos + actual_outer_size)
local actual_outer_size_x, actual_outer_size_y = ImGui._CalcItemSizeXY(outer_size.x, outer_size.y, mathMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window and mathMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) or 0.0)
actual_outer_size_x, actual_outer_size_y = ImTrunc(actual_outer_size_x), ImTrunc(actual_outer_size_y) -- [Luau] scalar ImTrunc(CalcItemSize(...))
local outer_cursor = outer_window.DC.CursorPos
local outer_rect = ImRect(outer_cursor.x, outer_cursor.y, outer_cursor.x + actual_outer_size_x, outer_cursor.y + actual_outer_size_y) -- [Luau] scalar form: no temporary ImVec2
local outer_window_is_measuring_size = (outer_window.AutoFitFramesX > 0) or (outer_window.AutoFitFramesY > 0) -- Doesn't apply to AlwaysAutoResize windows!
if use_child_window and ImGui.IsClippedEx(outer_rect, 0) and not outer_window_is_measuring_size then
ImGui.ItemSize(outer_rect)
@@ -1230,7 +1236,7 @@ function ImGui.TableUpdateLayout(table_)
table_.ColumnsStretchSumWeights = stretch_sum_weights
-- [Part 4] Apply final widths based on requested widths
local work_rect = Rect(table_.WorkRect)
local work_rect = TableUpdateLayout_work_rect; ImRect_Copy(work_rect, table_.WorkRect) -- [Luau] scratch copy
local width_spacings = (table_.OuterPaddingX * 2.0) + (table_.CellSpacingX1 + table_.CellSpacingX2) * (table_.ColumnsEnabledCount - 1)
local width_removed = (table_.HasScrollbarYPrev and not table_.InnerWindow.ScrollbarY) and g.Style.ScrollbarSize or 0.0 -- To synchronize decoration width of synced tables with mismatching scrollbar state (#5920)
local width_avail = mathMax(1.0, ((band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 and table_.InnerWidth == 0.0) and table_.InnerClipRect:GetWidth() or work_rect:GetWidth()) - width_removed)
@@ -1286,7 +1292,8 @@ function ImGui.TableUpdateLayout(table_)
table_instance.HoveredRowLast = table_instance.HoveredRowNext
table_instance.HoveredRowNext = -1
table_.HoveredColumnBody = -1; table_.HoveredColumnBorder = -1
local mouse_hit_rect = ImRect(table_.OuterRect.Min.x, table_.OuterRect.Min.y, table_.OuterRect.Max.x, mathMax(table_.OuterRect.Max.y, table_.OuterRect.Min.y + table_instance.LastOuterHeight))
local mouse_hit_rect = TableUpdateLayout_mouse_hit_rect -- [Luau] scratch, ItemHoverable() only reads it
mouse_hit_rect.Min.x, mouse_hit_rect.Min.y, mouse_hit_rect.Max.x, mouse_hit_rect.Max.y = table_.OuterRect.Min.x, table_.OuterRect.Min.y, table_.OuterRect.Max.x, mathMax(table_.OuterRect.Max.y, table_.OuterRect.Min.y + table_instance.LastOuterHeight)
local backup_active_id = g.ActiveId
g.ActiveId = 0
local is_hovering_table = ImGui.ItemHoverable(mouse_hit_rect, 0, ImGuiItemFlags.None)
@@ -1305,7 +1312,7 @@ function ImGui.TableUpdateLayout(table_)
local has_at_least_one_column_requesting_output = false
local offset_x_frozen = (table_.FreezeColumnsCount > 0)
local offset_x = ((table_.FreezeColumnsCount > 0) and table_.OuterRect.Min.x or work_rect.Min.x) + table_.OuterPaddingX - table_.CellSpacingX1
local host_clip_rect = Rect(table_.InnerClipRect)
local host_clip_rect = TableUpdateLayout_host_clip_rect; ImRect_Copy(host_clip_rect, table_.InnerClipRect) -- [Luau] scratch copy
--host_clip_rect.Max.x += table.CellPaddingX + table.CellSpacingX2
BitArrayClearAll(table_.VisibleMaskByIndex)
for order_n = 0, columns_count - 1 do
@@ -1560,6 +1567,8 @@ function ImGui.TableApplyExternalUnclipRect(table_, rect)
end
end
local TableUpdateBorders_hit_rect = ImRect()
-- Process hit-testing on resizing borders. Actual size change will be applied in EndTable()
-- - Set table.HoveredColumnBorder with a short delay/timer to reduce visual feedback noise.
function ImGui.TableUpdateBorders(table_)
@@ -1599,7 +1608,8 @@ function ImGui.TableUpdateBorders(table_)
end
local column_id = ImGui.TableGetColumnResizeID(table_, column_n, table_.InstanceCurrent)
local hit_rect = ImRect(column.MaxX - hit_half_width, hit_y1, column.MaxX + hit_half_width, border_y2_hit)
local hit_rect = TableUpdateBorders_hit_rect -- [Luau] scratch: ItemAdd() copies it, ButtonBehavior() reads it
hit_rect.Min.x = column.MaxX - hit_half_width; hit_rect.Min.y = hit_y1; hit_rect.Max.x = column.MaxX + hit_half_width; hit_rect.Max.y = border_y2_hit
ImGui.ItemAdd(hit_rect, column_id, nil, ImGuiItemFlags.NoNav)
--ImGui.GetForegroundDrawList():AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100))
@@ -2259,6 +2269,7 @@ end
-- [Public] Starts into the first cell of a new row
--- @param row_flags? ImGuiTableRowFlags
--- @param row_min_height? float
@native
function ImGui.TableNextRow(row_flags, row_min_height)
if row_flags == nil then row_flags = 0 end
if row_min_height == nil then row_min_height = 0.0 end
@@ -2288,6 +2299,7 @@ function ImGui.TableNextRow(row_flags, row_min_height)
end
-- [Internal] Only called by TableNextRow()
@native
function ImGui.TableBeginRow(table_)
local window = table_.InnerWindow
IM_ASSERT(not table_.IsInsideRow)
@@ -2332,6 +2344,7 @@ end
local TableEndRow_RowMin, TableEndRow_RowMax = ImVec2(), ImVec2()
-- [Internal] Called by TableNextRow()
@native
function ImGui.TableEndRow(table_)
local g = GImGui
local window = g.CurrentWindow
@@ -2509,6 +2522,7 @@ function ImGui.TableGetColumnIndex()
end
-- [Public] Append into a specific column
@native
function ImGui.TableSetColumnIndex(column_n)
local g = GImGui
local table_ = g.CurrentTable
@@ -2610,7 +2624,21 @@ function ImGui.TableBeginCell(table_, column_n)
--IM_ASSERT(table.DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP)
else
-- FIXME-TABLE: Could avoid this if draw channel is dummy channel?
ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect)
-- [Luau] inline ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect)
local cr = column.ClipRect
local x1, y1, x2, y2 = cr.Min.x, cr.Min.y, cr.Max.x, cr.Max.y
local wcr = window.ClipRect
wcr.Min.x = x1; wcr.Min.y = y1; wcr.Max.x = x2; wcr.Max.y = y2
local draw_list = window.DrawList
local hcr = draw_list._CmdHeader.ClipRect
hcr.x = x1; hcr.y = y1; hcr.z = x2; hcr.w = y2
local stack = draw_list._ClipRectStack
local top = stack.Data[stack.Size]
if top ~= nil then
top.x = x1; top.y = y1; top.z = x2; top.w = y2
else
stack.Data[stack.Size] = ImVec4(x1, y1, x2, y2)
end
local channel = column.DrawChannelCurrent
if splitter._Current ~= channel then
splitter:SetCurrentChannel(window.DrawList, channel)
@@ -2669,6 +2697,7 @@ end
-------------------------------------------------------------------------------
-- Maximum column content width given current layout. Use column.MinX so this value differs on a per-column basis.
@native
function ImGui.TableCalcMaxColumnWidth(table_, column_n)
local column = table_.Columns[column_n]
local max_width = FLT_MAX
@@ -2696,6 +2725,7 @@ function ImGui.TableCalcMaxColumnWidth(table_, column_n)
end
-- Note this is meant to be stored in column.WidthAuto, please generally use the WidthAuto field
@native
function ImGui.TableGetColumnWidthAuto(table_, column)
local content_width_body = mathMax(column.ContentMaxXFrozen, column.ContentMaxXUnfrozen) - column.WorkMinX
local content_width_headers = column.ContentMaxXHeadersIdeal - column.WorkMinX
@@ -3112,7 +3142,7 @@ function ImGui.TableMergeDrawChannels(table_)
local merge_channels_count = merge_groups[merge_group_n].ChannelsCount
if merge_channels_count ~= 0 then
local merge_group = merge_groups[merge_group_n]
local merge_clip_rect = Rect(merge_group.ClipRect)
local merge_clip_rect = TableMergeDrawChannels_merge_clip_rect; ImRect_Copy(merge_clip_rect, merge_group.ClipRect) -- [Luau] scratch copy
-- Extend outer-most clip limits to match those of host, so draw calls can be merged even if
-- outer-most columns have some outer padding offsetting them from their parent ClipRect.
+236 -116
View File
@@ -99,7 +99,7 @@ function ImGui.TextEx(text, text_end, flags)
-- Calculate length
if text_end == nil then
text_end = #text + 1
text_end = (type(text) == "string" and string.len(text) or #text) + 1 -- [Luau] `#` on a string isn't a native fast path
end
local dc = window.DC
@@ -110,7 +110,12 @@ function ImGui.TextEx(text, text_end, flags)
-- [Luau] scalar text_pos, scratch bb (ItemAdd() copies it, RenderTextWrapped() only reads it)
local text_pos_x, text_pos_y = dc.CursorPos.x, dc.CursorPos.y + dc.CurrLineTextBaseOffset
local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(dc.CursorPos, wrap_pos_x) or 0.0
local text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false, wrap_width)
-- [Luau] inline ImGui.CalcTextSizeXY(text, 1, text_end, false, wrap_width)
local text_size_x, text_size_y = 0.0, g.FontSize
if text ~= "" and text_end > 1 then
text_size_x, text_size_y = ImFontCalcTextSizeXY(g.Font, text_size_y, FLT_MAX, wrap_width, text, 1, text_end, text_end, nil, ImDrawTextFlags.None)
text_size_x = math.ceil(text_size_x) -- Round (see CalcTextSize())
end
local bb = TextEx_bb
local bb_min, bb_max = bb.Min, bb.Max
@@ -226,7 +231,13 @@ end
@native
function ImGui.Text(fmt, ...)
if select('#', ...) > 0 then
ImGui.TextV(fmt, ...)
-- [Luau] inline ImGui.TextV(fmt, ...) (saves a vararg call per Text())
local window = GImGui.CurrentWindow -- [Luau] inline GetCurrentWindow()
window.WriteAccessed = true
if window.SkipItems then
return
end
ImGui.TextEx(ImFormatString(fmt, ...), nil, ImGuiTextFlags.NoWidthForLargeClippedText)
else
ImGui.TextEx(fmt)
end
@@ -243,6 +254,7 @@ end
--- @param fmt string
--- @param ... any
@native
function ImGui.TextDisabled(fmt, ...)
local g = GImGui
ImGui.PushStyleColor(ImGuiCol.Text, g.Style.Colors[ImGuiCol.TextDisabled])
@@ -252,6 +264,7 @@ end
--- @param fmt string
--- @param ... any
@native
function ImGui.TextWrapped(fmt, ...)
local g = GImGui
local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0) -- Keep existing wrap position if one is already set
@@ -307,6 +320,8 @@ end
--- @param label string
--- @param fmt string
--- @param ... any
-- [Luau] scratch for LabelText(): only read by its callees (ItemAdd() copies total_bb), never escape
local LabelText_value_size, LabelText_value_bb, LabelText_total_bb, LabelText_pos = ImVec2(), ImRect(), ImRect(), ImVec2()
function ImGui.LabelText(label, fmt, ...)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
@@ -319,23 +334,30 @@ function ImGui.LabelText(label, fmt, ...)
local value_text = ImFormatString(fmt, ...)
local value_text_end = #value_text + 1
local value_size = ImGui.CalcTextSize(value_text, value_text_end, false)
local value_size = LabelText_value_size
value_size.x, value_size.y = ImGui.CalcTextSizeXY(value_text, 1, value_text_end, false)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local value_bb = ImRect(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2))
local total_bb = ImRect(pos, pos + ImVec2(w + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0), ImMax(value_size.y, label_size.y) + style.FramePadding.y * 2))
local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- [Luau] scalar pos
local value_bb = LabelText_value_bb
value_bb.Min.x, value_bb.Min.y, value_bb.Max.x, value_bb.Max.y = pos_x, pos_y, pos_x + w, pos_y + (value_size.y + style.FramePadding.y * 2)
local total_bb = LabelText_total_bb
total_bb.Min.x, total_bb.Min.y = pos_x, pos_y
total_bb.Max.x = pos_x + (w + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0))
total_bb.Max.y = pos_y + (ImMax(value_size.y, label_size_y) + style.FramePadding.y * 2)
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, 0) then
return
end
-- Render
ImGui.RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text, value_text_end, value_size, ImVec2(0.0, 0.0))
if label_size.x > 0.0 then
ImGui.RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
local text_pos = LabelText_pos
text_pos.x, text_pos.y = value_bb.Min.x + style.FramePadding.x, value_bb.Min.y + style.FramePadding.y
ImGui.RenderTextClipped(text_pos, value_bb.Max, value_text, value_text_end, value_size, LAYOUT_ZERO_SIZE)
if label_size_x > 0.0 then
text_pos.x, text_pos.y = value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y
ImGui.RenderText(text_pos, label, 1, label_end, false)
end
end
@@ -822,6 +844,7 @@ end
--- @param label string
--- @param size_arg? ImVec2
--- @return bool
@native
function ImGui.Button(label, size_arg)
return ImGui.ButtonEx(label, size_arg, ImGuiButtonFlags.None)
end
@@ -833,7 +856,7 @@ function ImGui.SmallButton(label)
local g = GImGui
local backup_padding_y = g.Style.FramePadding.y
g.Style.FramePadding.y = 0.0
local pressed = ImGui.ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags.AlignTextBaseLine)
local pressed = ImGui.ButtonEx(label, LAYOUT_ZERO_SIZE, ImGuiButtonFlags.AlignTextBaseLine) -- [Luau] shared read-only ImVec2(0, 0)
g.Style.FramePadding.y = backup_padding_y
return pressed
end
@@ -843,6 +866,7 @@ end
--- @param str_id string
--- @param size_arg ImVec2
--- @param flags? ImGuiButtonFlags
local InvisibleButton_size, InvisibleButton_bb = ImVec2(), ImRect() -- [Luau] scratch for InvisibleButton(): only read by callees, never escape
function ImGui.InvisibleButton(str_id, size_arg, flags)
if flags == nil then flags = 0 end
@@ -852,10 +876,13 @@ function ImGui.InvisibleButton(str_id, size_arg, flags)
end
-- Ensure zero-size fits to contents
local size = ImVec2(ImGui._CalcItemSizeXY(size_arg.x ~= 0.0 and size_arg.x or -FLT_MIN, size_arg.y ~= 0.0 and size_arg.y or -FLT_MIN, 0.0, 0.0))
local size = InvisibleButton_size
size.x, size.y = ImGui._CalcItemSizeXY(size_arg.x ~= 0.0 and size_arg.x or -FLT_MIN, size_arg.y ~= 0.0 and size_arg.y or -FLT_MIN, 0.0, 0.0)
local id = window:GetID(str_id)
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + size)
local cursor = window.DC.CursorPos
local bb = InvisibleButton_bb
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = cursor.x, cursor.y, cursor.x + size.x, cursor.y + size.y
ImGui.ItemSize(size)
local item_flags = (bit32.band(flags, ImGuiButtonFlags.EnableNav) ~= 0) and ImGuiItemFlags.None or ImGuiItemFlags.NoNav
@@ -874,6 +901,7 @@ end
--- @param dir ImGuiDir
--- @param size ImVec2
--- @param flags? ImGuiButtonFlags
local ArrowButton_bb, ArrowButton_pos, ArrowButton_size = ImRect(), ImVec2(), ImVec2() -- [Luau] scratch for ArrowButton[Ex](): only read by callees, never escape
function ImGui.ArrowButtonEx(str_id, dir, size, flags)
if flags == nil then flags = 0 end
@@ -884,7 +912,9 @@ function ImGui.ArrowButtonEx(str_id, dir, size, flags)
local g = GImGui
local id = window:GetID(str_id)
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + size)
local cursor = window.DC.CursorPos
local bb = ArrowButton_bb
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = cursor.x, cursor.y, cursor.x + size.x, cursor.y + size.y
local default_size = ImGui.GetFrameHeight()
ImGui.ItemSize(size, (size.y >= default_size) and g.Style.FramePadding.y or -1.0)
if not ImGui.ItemAdd(bb, id) then
@@ -898,7 +928,9 @@ function ImGui.ArrowButtonEx(str_id, dir, size, flags)
local text_col = ImGui.GetColorU32(ImGuiCol.Text)
ImGui.RenderNavCursor(bb, id)
ImGui.RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding)
ImGui.RenderArrow(window.DrawList, bb.Min + ImVec2(ImMax(0.0, (size.x - g.FontSize) * 0.5), ImMax(0.0, (size.y - g.FontSize) * 0.5)), text_col, dir)
local pos = ArrowButton_pos
pos.x, pos.y = bb.Min.x + ImMax(0.0, (size.x - g.FontSize) * 0.5), bb.Min.y + ImMax(0.0, (size.y - g.FontSize) * 0.5)
ImGui.RenderArrow(window.DrawList, pos, text_col, dir)
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags)
return pressed
@@ -908,7 +940,8 @@ end
--- @param dir ImGuiDir
function ImGui.ArrowButton(str_id, dir)
local sz = ImGui.GetFrameHeight()
return ImGui.ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags.None)
local size = ArrowButton_size; size.x = sz; size.y = sz -- [Luau] scratch, ArrowButtonEx() only reads it
return ImGui.ArrowButtonEx(str_id, dir, size, ImGuiButtonFlags.None)
end
-- Button to close a window
@@ -1311,7 +1344,7 @@ end
--- @param v bool
--- @return bool is_pressed
--- @return bool is_checked # The updated `v` passed in
local Checkbox_total_bb, Checkbox_check_bb, Checkbox_label_pos = ImRect(), ImRect(), ImVec2() -- [Luau] scratch, only read by callees
local Checkbox_total_bb, Checkbox_check_bb, Checkbox_label_pos, Checkbox_mark_pos = ImRect(), ImRect(), ImVec2(), ImVec2() -- [Luau] scratch, only read by callees
@native
function ImGui.Checkbox(label, v)
@@ -1386,7 +1419,9 @@ function ImGui.Checkbox(label, v)
window.DrawList:AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding)
elseif v then
local pad = ImMax(1.0, IM_TRUNC(square_sz / 6.0))
ImGui.RenderCheckMark(window.DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0)
local mark_pos = Checkbox_mark_pos -- [Luau] check_bb.Min + ImVec2(pad, pad) into scratch
mark_pos.x, mark_pos.y = check_bb.Min.x + pad, check_bb.Min.y + pad
ImGui.RenderCheckMark(window.DrawList, mark_pos, check_col, square_sz - pad * 2.0)
end
end
@@ -1435,6 +1470,8 @@ ImGui.CheckboxFlagsT = ImGui.CheckboxFlags
--- @param label string
--- @param active bool
--- @return bool is_pressed
-- [Luau] scratch for RadioButtonEx(): only read by its callees (ItemAdd() copies total_bb), never escape
local RadioButton_total_bb, RadioButton_center, RadioButton_label_pos = ImRect(), ImVec2(), ImVec2()
function ImGui.RadioButtonEx(label, active)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
@@ -1445,20 +1482,21 @@ function ImGui.RadioButtonEx(label, active)
local style = g.Style
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size
local square_sz = g.FontSize + style.FramePadding.y * 2.0 -- [Luau] inline GetFrameHeight()
local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- [Luau] scalar pos, no temporary ImVec2
local check_bb = ImRect(pos_x, pos_y, pos_x + square_sz, pos_y + square_sz)
local total_bb = ImRect(pos_x, pos_y, pos_x + (square_sz + (label_size.x > 0.0 and style.ItemInnerSpacing.x + label_size.x or 0.0)), pos_y + (label_size.y + style.FramePadding.y * 2.0))
local check_bb_min_x, check_bb_min_y, check_bb_max_x, check_bb_max_y = pos_x, pos_y, pos_x + square_sz, pos_y + square_sz -- [Luau] scalar check_bb
local total_bb = RadioButton_total_bb
total_bb.Min.x, total_bb.Min.y, total_bb.Max.x, total_bb.Max.y = pos_x, pos_y, pos_x + (square_sz + (label_size_x > 0.0 and style.ItemInnerSpacing.x + label_size_x or 0.0)), pos_y + (label_size_y + style.FramePadding.y * 2.0)
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, id) then
return false
end
local center = check_bb:GetCenter()
center.x = IM_ROUND(center.x)
center.y = IM_ROUND(center.y)
local center = RadioButton_center -- [Luau] check_bb:GetCenter() into scratch
center.x = IM_ROUND((check_bb_min_x + check_bb_max_x) * 0.5)
center.y = IM_ROUND((check_bb_min_y + check_bb_max_y) * 0.5)
local radius = (square_sz - 1.0) * 0.5
local pressed, hovered, held = ImGui.ButtonBehavior(total_bb, id)
@@ -1487,11 +1525,12 @@ function ImGui.RadioButtonEx(label, active)
window.DrawList:AddCircle(center + ImVec2(1, 1), radius, ImGui.GetColorU32(ImGuiCol.BorderShadow), num_segment, style.FrameBorderSize)
window.DrawList:AddCircle(center, radius, ImGui.GetColorU32(ImGuiCol.Border), num_segment, style.FrameBorderSize)
end
local label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y)
local label_pos = RadioButton_label_pos
label_pos.x, label_pos.y = check_bb_max_x + style.ItemInnerSpacing.x, check_bb_min_y + style.FramePadding.y
if g.LogEnabled then
ImGui.LogRenderedText(label_pos, active and "(x)" or "( )")
end
if label_size.x > 0.0 then
if label_size_x > 0.0 then
ImGui.RenderText(label_pos, label, 1, label_end, false)
end
@@ -1516,8 +1555,10 @@ end
--- @param fraction float
--- @param size_arg? ImVec2
--- @param overlay? string
local ProgressBar_size_arg_default = ImVec2(-FLT_MIN, 0) -- [Luau] shared read-only default (CalcItemSize() only reads it)
local ProgressBar_size, ProgressBar_overlay_pos, ProgressBar_overlay_align = ImVec2(), ImVec2(), ImVec2(0.0, 0.5) -- [Luau] scratch / shared read-only, only read by RenderTextClipped()
function ImGui.ProgressBar(fraction, size_arg, overlay)
if size_arg == nil then size_arg = ImVec2(-FLT_MIN, 0) end
if size_arg == nil then size_arg = ProgressBar_size_arg_default end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
@@ -1527,10 +1568,10 @@ function ImGui.ProgressBar(fraction, size_arg, overlay)
local g = GImGui
local style = g.Style
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local size = ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0)
local bb = ImRect(pos, pos + size)
local pos = window.DC.CursorPos -- [Luau] only read before ItemSize() moves the cursor
local size_x, size_y = ImGui._CalcItemSizeXY(size_arg.x, size_arg.y, ImGui.CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0) -- [Luau] scalar size
local bb = ImRect(pos.x, pos.y, pos.x + size_x, pos.y + size_y)
local size = ProgressBar_size; size.x = size_x; size.y = size_y -- [Luau] scratch, ItemSize() only reads it
ImGui.ItemSize(size, style.FramePadding.y)
if not ImGui.ItemAdd(bb, 0) then
return
@@ -1556,7 +1597,7 @@ function ImGui.ProgressBar(fraction, size_arg, overlay)
-- Render
ImGui.RenderFrame(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), true, style.FrameRounding)
bb:Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize))
bb:Expand(-style.FrameBorderSize) -- [Luau] == Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize))
local fill_x0 = ImLerp(bb.Min.x, bb.Max.x, fill_n0)
local fill_x1 = ImLerp(bb.Min.x, bb.Max.x, fill_n1)
@@ -1574,11 +1615,14 @@ function ImGui.ProgressBar(fraction, size_arg, overlay)
local overlay_size = ImGui.CalcTextSize(overlay, nil)
if overlay_size.x > 0.0 then
local text_x = is_indeterminate and ((bb.Min.x + bb.Max.x - overlay_size.x) * 0.5) or (fill_x1 + style.ItemSpacing.x)
ImGui.RenderTextClipped(ImVec2(ImClamp(text_x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, nil, overlay_size, ImVec2(0.0, 0.5), bb)
local overlay_pos = ProgressBar_overlay_pos
overlay_pos.x, overlay_pos.y = ImClamp(text_x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y
ImGui.RenderTextClipped(overlay_pos, bb.Max, overlay, nil, overlay_size, ProgressBar_overlay_align, bb)
end
end
end
local Bullet_bb, Bullet_pos = ImRect(), ImVec2() -- [Luau] scratch for Bullet(): only read by its callees (ItemAdd() copies bb), never escape
function ImGui.Bullet()
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
@@ -1588,7 +1632,9 @@ function ImGui.Bullet()
local g = GImGui
local style = g.Style
local line_height = ImMax(ImMin(window.DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), g.FontSize)
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(g.FontSize, line_height))
local cursor = window.DC.CursorPos
local bb = Bullet_bb
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = cursor.x, cursor.y, cursor.x + g.FontSize, cursor.y + line_height
ImGui.ItemSize(bb)
if not ImGui.ItemAdd(bb, 0) then
ImGui.SameLine(0, style.FramePadding.x * 2)
@@ -1597,7 +1643,9 @@ function ImGui.Bullet()
-- Render and stay on same line
local text_col = ImGui.GetColorU32(ImGuiCol.Text)
ImGui.RenderBullet(window.DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5, line_height * 0.5), text_col)
local pos = Bullet_pos
pos.x, pos.y = bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + line_height * 0.5
ImGui.RenderBullet(window.DrawList, pos, text_col)
ImGui.SameLine(0, style.FramePadding.x * 2.0)
end
@@ -1695,6 +1743,7 @@ end
-------------------------------------------------------------------------------
local LayoutHelpers_size = ImVec2() -- [Luau] scratch for ItemSize() arguments
local LayoutHelpers_bb = ImRect() -- [Luau] scratch for ItemAdd() arguments (ItemAdd() copies it)
function ImGui.Spacing()
local window = ImGui.GetCurrentWindow()
@@ -1712,7 +1761,8 @@ function ImGui.Dummy(size)
end
local cursor = window.DC.CursorPos
local bb = ImRect(cursor.x, cursor.y, cursor.x + size.x, cursor.y + size.y) -- [Luau] no temporary ImVec2
local bb = LayoutHelpers_bb -- [Luau] scratch, no temporary ImVec2
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = cursor.x, cursor.y, cursor.x + size.x, cursor.y + size.y
ImGui.ItemSize(size)
ImGui.ItemAdd(bb, 0)
end
@@ -1729,9 +1779,10 @@ function ImGui.NewLine()
window.DC.IsSameLine = false
if window.DC.CurrLineSize.y > 0.0 then -- In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
ImGui.ItemSize(ImVec2(0, 0))
ImGui.ItemSize(LAYOUT_ZERO_SIZE)
else
ImGui.ItemSize(ImVec2(0.0, g.FontSize))
local size = LayoutHelpers_size; size.x = 0.0; size.y = g.FontSize -- [Luau] scratch
ImGui.ItemSize(size)
end
window.DC.LayoutType = backup_layout_type
@@ -1753,6 +1804,7 @@ end
-- Note how thickness == 1.0f is handled specifically as not moving CursorPos by 'thickness', but other values are.
--- @param flags ImGuiSeparatorFlags
--- @param thickness float
local SeparatorEx_bb = ImRect() -- [Luau] scratch for SeparatorEx(): only read by its callees (ItemAdd() copies it), never escapes
function ImGui.SeparatorEx(flags, thickness)
if thickness == nil then thickness = 1.0 end
@@ -1769,7 +1821,8 @@ function ImGui.SeparatorEx(flags, thickness)
-- Vertical separator, for menu bars (use current line height).
local y1 = window.DC.CursorPos.y
local y2 = window.DC.CursorPos.y + window.DC.CurrLineSize.y
local bb = ImRect(window.DC.CursorPos.x, y1, window.DC.CursorPos.x + thickness, y2) -- [Luau] no temporary ImVec2
local bb = SeparatorEx_bb -- [Luau] scratch, no temporary ImVec2
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = window.DC.CursorPos.x, y1, window.DC.CursorPos.x + thickness, y2
local item_size = LayoutHelpers_size; item_size.x = thickness; item_size.y = 0.0
ImGui.ItemSize(item_size)
if not ImGui.ItemAdd(bb, 0) then
@@ -1803,7 +1856,8 @@ function ImGui.SeparatorEx(flags, thickness)
-- This was mostly chosen to allow backward compatibility with user's code assuming zero-height when calculating height for layout (e.g. bottom alignment of a status bar).
-- In order to handle scaling we need to scale separator thickness and it would not makes sense to have a disparity depending on height.
----float thickness_for_layout = (thickness == 1.0f) ? 0.0f : thickness; // FIXME: See 1.70/1.71 Separator() change: makes legacy 1-px separator not affect layout yet. Should change.
local bb = ImRect(x1, window.DC.CursorPos.y, x2, window.DC.CursorPos.y + thickness) -- [Luau] no temporary ImVec2
local bb = SeparatorEx_bb -- [Luau] scratch, no temporary ImVec2
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = x1, window.DC.CursorPos.y, x2, window.DC.CursorPos.y + thickness
local item_size = LayoutHelpers_size; item_size.x = 0.0; item_size.y = thickness
ImGui.ItemSize(item_size)
@@ -1849,19 +1903,25 @@ end
--- @param label string
--- @param label_end? int
--- @param extra_w float
local SeparatorTextEx_label_size, SeparatorTextEx_min_size, SeparatorTextEx_bb, SeparatorTextEx_label_pos, SeparatorTextEx_clip_max = ImVec2(), ImVec2(), ImRect(), ImVec2(), ImVec2()
function ImGui.SeparatorTextEx(id, label, label_end, extra_w)
local g = GImGui
local window = g.CurrentWindow
local style = g.Style
local label_size = ImGui.CalcTextSize(label, label_end, false)
local pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y)
-- [Luau] scratch vectors/rect (callees only read them or copy them), scalar pos
local label_size = SeparatorTextEx_label_size
label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false)
local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y
local padding = style.SeparatorTextPadding
local separator_thickness = style.SeparatorTextBorderSize
local min_size = ImVec2(label_size.x + extra_w + padding.x * 2.0, ImMax(label_size.y + padding.y * 2.0, separator_thickness))
local min_size = SeparatorTextEx_min_size
min_size.x = label_size.x + extra_w + padding.x * 2.0; min_size.y = ImMax(label_size.y + padding.y * 2.0, separator_thickness)
local bb = ImRect(pos, ImVec2(window.WorkRect.Max.x, pos.y + min_size.y))
local bb = SeparatorTextEx_bb
bb.Min.x = pos_x; bb.Min.y = pos_y; bb.Max.x = window.WorkRect.Max.x; bb.Max.y = pos_y + min_size.y
local text_baseline_y = ImTrunc((bb:GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.999) --ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f))
ImGui.ItemSize(min_size, text_baseline_y)
@@ -1869,12 +1929,13 @@ function ImGui.SeparatorTextEx(id, label, label_end, extra_w)
return
end
local sep1_x1 = pos.x
local sep1_x1 = pos_x
local sep2_x2 = bb.Max.x
local seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5) + 1.0
local label_avail_w = ImMax(0.0, sep2_x2 - sep1_x1 - padding.x * 2.0)
local label_pos = ImVec2(pos.x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y) -- FIXME-ALIGN
local label_pos = SeparatorTextEx_label_pos
label_pos.x = pos_x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x); label_pos.y = pos_y + text_baseline_y -- FIXME-ALIGN
-- This allows using SameLine() to position something in the 'extra_w'
window.DC.CursorPosPrevLine.x = label_pos.x + label_size.x
@@ -1897,7 +1958,9 @@ function ImGui.SeparatorTextEx(id, label, label_end, extra_w)
ImGui.LogSetNextTextDecoration("---", nil)
end
ImGui.RenderTextEllipsis(window.DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, label_size)
local clip_max = SeparatorTextEx_clip_max
clip_max.x = bb.Max.x; clip_max.y = bb.Max.y + style.ItemSpacing.y
ImGui.RenderTextEllipsis(window.DrawList, label_pos, clip_max, bb.Max.x, label, label_end, label_size)
else
if g.LogEnabled then
ImGui.LogText("---")
@@ -1950,6 +2013,8 @@ end
--- @param label string
--- @param preview_value? string
--- @param flags? ImGuiComboFlags
-- [Luau] scratch for BeginCombo(): only read by its callees (ItemAdd() copies them), never escape
local BeginCombo_bb, BeginCombo_total_bb, BeginCombo_p0, BeginCombo_p1 = ImRect(), ImRect(), ImVec2(), ImVec2()
function ImGui.BeginCombo(label, preview_value, flags)
if flags == nil then flags = 0 end
@@ -1977,7 +2042,7 @@ function ImGui.BeginCombo(label, preview_value, flags)
end
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size
local preview_width
if ((bit32.band(flags, ImGuiComboFlags.WidthFitPreview) ~= 0) and (preview_value ~= nil)) then
@@ -1995,9 +2060,12 @@ function ImGui.BeginCombo(label, preview_value, flags)
w = ImGui.CalcItemWidth()
end
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0))
local label_offset = (label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0
local total_bb = ImRect(bb.Min, bb.Max + ImVec2(label_offset, 0.0))
local cursor = window.DC.CursorPos
local bb = BeginCombo_bb
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0)
local label_offset = (label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0
local total_bb = BeginCombo_total_bb
total_bb.Min.x, total_bb.Min.y, total_bb.Max.x, total_bb.Max.y = bb.Min.x, bb.Min.y, bb.Max.x + label_offset, bb.Max.y + 0.0
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, id, bb) then
@@ -2020,27 +2088,34 @@ function ImGui.BeginCombo(label, preview_value, flags)
ImGui.RenderNavCursor(bb, id)
if bit32.band(flags, ImGuiComboFlags.NoPreview) == 0 then
window.DrawList:AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (bit32.band(flags, ImGuiComboFlags.NoArrowButton) ~= 0) and ImDrawFlags.RoundAll or ImDrawFlags.RoundLeft)
local p1 = BeginCombo_p1
p1.x, p1.y = value_x2, bb.Max.y
window.DrawList:AddRectFilled(bb.Min, p1, frame_col, style.FrameRounding, (bit32.band(flags, ImGuiComboFlags.NoArrowButton) ~= 0) and ImDrawFlags.RoundAll or ImDrawFlags.RoundLeft)
end
if bit32.band(flags, ImGuiComboFlags.NoArrowButton) == 0 then
local bg_col = ImGui.GetColorU32((popup_open or hovered) and ImGuiCol.ButtonHovered or ImGuiCol.Button)
local text_col = ImGui.GetColorU32(ImGuiCol.Text)
window.DrawList:AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) and ImDrawFlags.RoundAll or ImDrawFlags.RoundRight)
local p0 = BeginCombo_p0
p0.x, p0.y = value_x2, bb.Min.y
window.DrawList:AddRectFilled(p0, bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) and ImDrawFlags.RoundAll or ImDrawFlags.RoundRight)
if value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x then
ImGui.RenderArrow(window.DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir.Down, 1.0)
p0.x, p0.y = value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y
ImGui.RenderArrow(window.DrawList, p0, text_col, ImGuiDir.Down, 1.0)
end
end
ImGui.RenderFrameBorder(bb.Min, bb.Max, style.FrameRounding)
-- Store geometry for BeginComboPreview() - only necessary when visible.
-- [Luau] written in place (C++ assigns the struct)
local preview_rect = g.ComboPreviewData.PreviewRect
if bit32.band(flags, ImGuiComboFlags.NoPreview) ~= 0 then
g.ComboPreviewData.PreviewRect = ImRect()
preview_rect.Min.x, preview_rect.Min.y, preview_rect.Max.x, preview_rect.Max.y = 0, 0, 0, 0
else
g.ComboPreviewData.PreviewRect = ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y)
preview_rect.Min.x, preview_rect.Min.y, preview_rect.Max.x, preview_rect.Max.y = bb.Min.x, bb.Min.y, value_x2, bb.Max.y
end
-- Render preview and label
@@ -2048,11 +2123,16 @@ function ImGui.BeginCombo(label, preview_value, flags)
if g.LogEnabled then
ImGui.LogSetNextTextDecoration("{", "}")
end
ImGui.RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, nil, nil)
local p0, p1 = BeginCombo_p0, BeginCombo_p1
p0.x, p0.y = bb.Min.x + style.FramePadding.x, bb.Min.y + style.FramePadding.y
p1.x, p1.y = value_x2, bb.Max.y
ImGui.RenderTextClipped(p0, p1, preview_value, nil, nil)
end
if label_size.x > 0 then
ImGui.RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
if label_size_x > 0 then
local p0 = BeginCombo_p0
p0.x, p0.y = bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y
ImGui.RenderText(p0, label, 1, label_end, false)
end
if not popup_open then
@@ -3001,6 +3081,7 @@ end
--- @param step_fast? number
--- @param format? string
--- @param flags? ImGuiInputTextFlags
local InputScalar_button_size = ImVec2() -- [Luau] scratch for the step buttons' size (ButtonEx() only reads it)
function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flags)
if flags == nil then flags = 0 end
@@ -3070,8 +3151,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag
-- Step buttons
if has_step_buttons then
local backup_frame_padding = ImVec2()
ImVec2_Copy(backup_frame_padding, style.FramePadding)
local backup_frame_padding_x, backup_frame_padding_y = style.FramePadding.x, style.FramePadding.y -- [Luau] scalar backup
style.FramePadding.x = style.FramePadding.y
if bit32.band(flags, ImGuiInputTextFlags.ReadOnly) ~= 0 then
ImGui.BeginDisabled()
@@ -3079,13 +3159,14 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag
ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true)
ImGui.SameLine(0, style.ItemInnerSpacing.x)
--- @cast step number
if ImGui.ButtonEx("-", ImVec2(button_size, button_size)) then
local step_button_size = InputScalar_button_size; step_button_size.x = button_size; step_button_size.y = button_size
if ImGui.ButtonEx("-", step_button_size) then
data = ImGui.DataTypeApplyOp(data_type, 45, data, ((g.IO.KeyCtrl and step_fast) and step_fast or step))
value_changed = true
ret = true
end
ImGui.SameLine(0, style.ItemInnerSpacing.x)
if ImGui.ButtonEx("+", ImVec2(button_size, button_size)) then
if ImGui.ButtonEx("+", step_button_size) then
data = ImGui.DataTypeApplyOp(data_type, 43, data, ((g.IO.KeyCtrl and step_fast) and step_fast or step))
value_changed = true
ret = true
@@ -3099,7 +3180,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag
ImGui.SameLine(0, style.ItemInnerSpacing.x)
ImGui.TextEx(label, label_end)
end
ImVec2_Copy(style.FramePadding, backup_frame_padding)
ImVec2_CopyV(style.FramePadding, backup_frame_padding_x, backup_frame_padding_y)
ImGui.PopID()
ImGui.EndGroup()
@@ -3991,6 +4072,7 @@ end
--- @param out_grab_bb ImRect
--- @return T v # updated `v` passed in
--- @return bool value_changed
@native
function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_max, format, flags, out_grab_bb)
local g = GImGui
local style = g.Style
@@ -4161,6 +4243,7 @@ end
--- @param out_grab_bb ImRect
--- @return T v
--- @return bool value_changed
@native
function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out_grab_bb)
-- Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert.
IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.")
@@ -4244,6 +4327,7 @@ end
--- @param max T
--- @param format? string
--- @param flags? ImGuiSliderFlags
@native
function ImGui.SliderScalar(label, data_type, data, min, max, format, flags)
if flags == nil then flags = 0 end
@@ -4444,6 +4528,7 @@ end
--- @param v_max float
--- @param format? string
--- @param flags? ImGuiSliderFlags
@native
function ImGui.SliderFloat(label, v, v_min, v_max, format, flags)
if format == nil then format = "%.3f" end
if flags == nil then flags = 0 end
@@ -4629,7 +4714,7 @@ function ImGui.InputText(label, buf, buf_size, flags, callback, user_data)
if flags == nil then flags = 0 end
IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) -- call InputTextMultiline()
return ImGui.InputTextEx(label, nil, buf, buf_size, ImVec2(0, 0), flags, callback, user_data)
return ImGui.InputTextEx(label, nil, buf, buf_size, LAYOUT_ZERO_SIZE, flags, callback, user_data) -- [Luau] shared read-only ImVec2(0, 0)
end
-- [Luau] InputText edits a byte table in place (C++ char buf[N]). Helpers to make/read one:
@@ -5424,6 +5509,7 @@ end
--- @param flags ImGuiInputTextFlags
--- @param callback? ImGuiInputTextCallback
--- @param callback_user_data any
local InputTextEx_frame_bb, InputTextEx_total_bb = ImRect(), ImRect() -- [Luau] scratch, see InputTextEx()
local HintBufCache = setmetatable({}, { __mode = "k" })
local function HintToBuf(hint)
local t = HintBufCache[hint]
@@ -5462,17 +5548,20 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
end
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local frame_size = ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), (is_multiline and g.FontSize * 8.0 or label_size.y) + style.FramePadding.y * 2.0) -- Arbitrary default of 8 lines high for multi-line
local total_size = ImVec2(frame_size.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0), frame_size.y)
local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size, frame_size, inner_size
local frame_size_x, frame_size_y = ImGui._CalcItemSizeXY(size_arg.x, size_arg.y, ImGui.CalcItemWidth(), (is_multiline and g.FontSize * 8.0 or label_size_y) + style.FramePadding.y * 2.0) -- Arbitrary default of 8 lines high for multi-line
local total_size_x, total_size_y = frame_size_x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0), frame_size_y -- [Luau] scalar total_size
local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + frame_size)
local total_bb = ImRect(frame_bb.Min, frame_bb.Min + total_size)
-- [Luau] total_bb is a scratch rect (only ItemSize()/ItemAdd() read it); a single-line field's frame_bb too until ItemAdd() accepts it (clipped fields allocate nothing)
local cursor = window.DC.CursorPos
local frame_bb = is_multiline and ImRect() or InputTextEx_frame_bb
frame_bb.Min.x = cursor.x; frame_bb.Min.y = cursor.y; frame_bb.Max.x = cursor.x + frame_size_x; frame_bb.Max.y = cursor.y + frame_size_y
local total_bb = InputTextEx_total_bb
total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y; total_bb.Max.x = frame_bb.Min.x + total_size_x; total_bb.Max.y = frame_bb.Min.y + total_size_y
local draw_window = window
local inner_size = ImVec2()
ImVec2_Copy(inner_size, frame_size)
local item_data_backup = ImGuiLastItemData()
local inner_size_x, inner_size_y = frame_size_x, frame_size_y
local item_data_backup = is_multiline and ImGuiLastItemData() or nil -- [Luau] only used by the multi-line path
if is_multiline then
local backup_pos = ImVec2()
ImVec2_Copy(backup_pos, window.DC.CursorPos)
@@ -5513,7 +5602,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
draw_window = g.CurrentWindow -- Child window
draw_window.DC.NavLayersActiveMaskNext = bit32.bor(draw_window.DC.NavLayersActiveMaskNext, bit32.lshift(1, draw_window.DC.NavLayerCurrent)) -- This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it.
ImVec2_Copy(draw_window.DC.CursorPos, draw_window.DC.CursorPos + style.FramePadding)
inner_size.x = inner_size.x - draw_window.ScrollbarSizes.x
inner_size_x = inner_size_x - draw_window.ScrollbarSizes.x
-- FIXME: Could this be a ImGuiChildFlags to affect the SetLastItemDataForWindow() call?
g.LastItemData.ID = id
@@ -5528,6 +5617,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
return false
end
end
frame_bb = ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y) -- [Luau] own copy of the scratch from here on
end
-- Ensure mouse cursor is set even after switching to keyboard/gamepad mode. May generalize further? (#6417)
@@ -5627,7 +5717,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
-- Find initial scroll position for right alignment
ImVec2_Copy(state.Scroll, ImVec2(0.0, 0.0))
if bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 then
state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size.x + style.FramePadding.x * 2.0) -- [Port] FIXME: no table.concat here
state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size_x + style.FramePadding.x * 2.0) -- [Port] FIXME: no table.concat here
end
-- Recycle existing cursor/selection/undo stack but clamp position
@@ -5866,7 +5956,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
IM_ASSERT(state ~= nil)
--- @cast state ImGuiInputTextState
local row_count_per_page = ImMax(ImTrunc((inner_size.y - style.FramePadding.y) / g.FontSize), 1)
local row_count_per_page = ImMax(ImTrunc((inner_size_y - style.FramePadding.y) / g.FontSize), 1)
state.Stb.row_count_per_page = row_count_per_page
local k_mask = (io.KeyShift and STB_TEXTEDIT_K_SHIFT or 0)
@@ -6220,7 +6310,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
local draw_pos = ImVec2()
ImVec2_Copy(draw_pos, is_multiline and draw_window.DC.CursorPos or (frame_bb.Min + style.FramePadding))
local clip_rect = ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y) -- Not using frame_bb.Max because we have adjusted size
local clip_rect = ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size_x, frame_bb.Min.y + inner_size_y) -- Not using frame_bb.Max because we have adjusted size
if is_multiline then
clip_rect:ClipWith(draw_window.ClipRect)
end
@@ -6309,8 +6399,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
if render_cursor and state.CursorFollow then
-- Horizontal scroll in chunks of quarter width
if bit32.band(flags, ImGuiInputTextFlags.NoHorizontalScroll) == 0 then
local scroll_increment_x = inner_size.x * 0.25
local visible_width = inner_size.x - style.FramePadding.x
local scroll_increment_x = inner_size_x * 0.25
local visible_width = inner_size_x - style.FramePadding.x
if cursor_offset.x < state.Scroll.x then
state.Scroll.x = IM_TRUNC(ImMax(0.0, cursor_offset.x - scroll_increment_x))
elseif cursor_offset.x - visible_width >= state.Scroll.x then
@@ -6325,21 +6415,21 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
-- Test if cursor is vertically visible
if cursor_offset.y - g.FontSize < scroll_y then
new_scroll_y = ImMax(0.0, cursor_offset.y - g.FontSize)
elseif cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0) >= scroll_y then
new_scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0
elseif cursor_offset.y - (inner_size_y - style.FramePadding.y * 2.0) >= scroll_y then
new_scroll_y = cursor_offset.y - inner_size_y + style.FramePadding.y * 2.0
end
end
state.CursorFollow = false
end
if state.CursorCenterY then
if is_multiline then
new_scroll_y = cursor_offset.y - g.FontSize - (inner_size.y * 0.5 - style.FramePadding.y)
new_scroll_y = cursor_offset.y - g.FontSize - (inner_size_y * 0.5 - style.FramePadding.y)
end
state.CursorCenterY = false
render_cursor = false
end
if new_scroll_y ~= scroll_y then
local scroll_max_y = ImMax((text_size_y + style.FramePadding.y * 2.0) - inner_size.y, 0.0)
local scroll_max_y = ImMax((text_size_y + style.FramePadding.y * 2.0) - inner_size_y, 0.0)
scroll_y = ImClamp(new_scroll_y, 0.0, scroll_max_y)
draw_pos.y = draw_pos.y + (draw_window.Scroll.y - scroll_y) -- Manipulate cursor pos immediately avoid a frame of lag
draw_window.Scroll.y = scroll_y
@@ -6470,7 +6560,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
ImGui.LogRenderedText(draw_pos, ImGui._ByteArrayToString(buf_display, 1, buf_display_end))
end
if label_size.x > 0.0 then
if label_size_x > 0.0 then
ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
end
@@ -6499,7 +6589,7 @@ function ImGui.InputTextWithHint(label, hint, buf, buf_size, flags, callback, us
if flags == nil then flags = 0 end
IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) -- call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint.
return ImGui.InputTextEx(label, hint, buf, buf_size, ImVec2(0, 0), flags, callback, user_data)
return ImGui.InputTextEx(label, hint, buf, buf_size, LAYOUT_ZERO_SIZE, flags, callback, user_data) -- [Luau] shared read-only ImVec2(0, 0)
end
-- [Luau] stb positions/undo indices are 1-based in this port (displayed as-is)
@@ -7759,6 +7849,7 @@ end
--- @param storage_id ImGuiID
--- @param is_open bool
@native
function ImGui.TreeNodeSetOpen(storage_id, is_open)
local g = GImGui
local storage = g.CurrentWindow.DC.StateStorage
@@ -7767,6 +7858,7 @@ end
--- @param storage_id ImGuiID
--- @param flags ImGuiTreeNodeFlags
@native
function ImGui.TreeNodeUpdateNextOpen(storage_id, flags)
-- Leaf node always open a new tree/id scope. If you never use it, add ImGuiTreeNodeFlags.NoTreePushOnOpen.
if bit32.band(flags, ImGuiTreeNodeFlags.Leaf) ~= 0 then
@@ -8222,6 +8314,7 @@ function ImGui.TreePush(str_id)
end
--- @param id ImGuiID
@native
function ImGui.TreePushOverrideID(id)
local g = GImGui
local window = g.CurrentWindow
@@ -8230,6 +8323,7 @@ function ImGui.TreePushOverrideID(id)
ImGui.PushOverrideID(id)
end
@native
function ImGui.TreePop()
local g = GImGui
local window = g.CurrentWindow
@@ -8266,6 +8360,7 @@ end
-- Set next TreeNode/CollapsingHeader open state.
--- @param is_open bool
--- @param cond? ImGuiCond
@native
function ImGui.SetNextItemOpen(is_open, cond)
if cond == nil then cond = 0 end
@@ -8361,6 +8456,8 @@ end
--- @param size_arg? any
--- @return bool is_pressed
--- @return bool is_selected # Updated `selected`
-- [Luau] scratch for Selectable(): only read by its callees (ItemAdd() copies bb), never escape
local Selectable_label_size, Selectable_size, Selectable_pos, Selectable_pos_max, Selectable_bb = ImVec2(), ImVec2(), ImVec2(), ImVec2(), ImRect()
@native
function ImGui.Selectable(label, selected, flags, size_arg)
if selected == nil then selected = false end
@@ -8378,10 +8475,13 @@ function ImGui.Selectable(label, selected, flags, size_arg)
-- Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle.
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local size = ImVec2((size_arg.x ~= 0.0) and size_arg.x or label_size.x, (size_arg.y ~= 0.0) and size_arg.y or label_size.y)
local label_size = Selectable_label_size
label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false)
local size = Selectable_size
size.x = (size_arg.x ~= 0.0) and size_arg.x or label_size.x
size.y = (size_arg.y ~= 0.0) and size_arg.y or label_size.y
local pos = ImVec2()
local pos = Selectable_pos
ImVec2_Copy(pos, window.DC.CursorPos)
pos.y = pos.y + window.DC.CurrLineTextBaseOffset
@@ -8398,7 +8498,8 @@ function ImGui.Selectable(label, selected, flags, size_arg)
-- Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
-- FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos.
local bb = ImRect(min_x, pos.y, min_x + size.x, pos.y + size.y)
local bb = Selectable_bb
bb.Min.x = min_x; bb.Min.y = pos.y; bb.Max.x = min_x + size.x; bb.Max.y = pos.y + size.y
if bit32.band(flags, ImGuiSelectableFlags.NoPadWithHalfSpacing) == 0 then
local spacing_x = span_all_columns and 0.0 or style.ItemSpacing.x
local spacing_y = style.ItemSpacing.y
@@ -8555,7 +8656,9 @@ function ImGui.Selectable(label, selected, flags, size_arg)
-- Text stays at the submission position. Alignment/clipping extents ignore SpanAllColumns.
if is_visible then
ImGui.RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window.WorkRect.Max.x), pos.y + size.y), label, label_end, label_size, style.SelectableTextAlign, bb)
local pos_max = Selectable_pos_max
pos_max.x = ImMin(pos.x + size.x, window.WorkRect.Max.x); pos_max.y = pos.y + size.y
ImGui.RenderTextClipped(pos, pos_max, label, label_end, label_size, style.SelectableTextAlign, bb)
end
-- Automatically close popups
@@ -10030,6 +10133,8 @@ end
-- Consider using ImPlot (https://github.com/epezent/implot) which is much better!
-------------------------------------------------------------------------------
local PlotEx_pos0, PlotEx_pos1 = ImVec2(), ImVec2() -- [Luau] scratch line/bar corners
--- @param plot_type ImGuiPlotType
--- @param label string
--- @param values_getter fun(data?: table, idx: int): float
@@ -10041,6 +10146,7 @@ end
--- @param scale_max float
--- @param size_arg ImVec2
--- @return int
@native
function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, size_arg)
local g = GImGui
local window = ImGui.GetCurrentWindow()
@@ -10055,9 +10161,10 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value
local label_size = ImGui.CalcTextSize(label, label_end, false)
local frame_size = ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0)
local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + frame_size)
local inner_bb = ImRect(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding)
local total_bb = ImRect(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0 and style.ItemInnerSpacing.x + label_size.x or 0.0, 0))
local cursor, pad = window.DC.CursorPos, style.FramePadding -- [Luau] scalar forms: no temporary ImVec2s
local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + frame_size.x, cursor.y + frame_size.y)
local inner_bb = ImRect(frame_bb.Min.x + pad.x, frame_bb.Min.y + pad.y, frame_bb.Max.x - pad.x, frame_bb.Max.y - pad.y)
local total_bb = ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x + (label_size.x > 0.0 and style.ItemInnerSpacing.x + label_size.x or 0.0), frame_bb.Max.y + 0)
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, id, frame_bb, ImGuiItemFlags.NoNav) then
return -1
@@ -10113,39 +10220,43 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value
local v0 = values_getter(data, (0 + values_offset) % values_count + 1)
local t0 = 0.0
local tp0 = ImVec2(t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale)) -- Point in the normalized space of our target rectangle
local tp0_x, tp0_y = t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale) -- Point in the normalized space of our target rectangle -- [Luau] scalar tp0/tp1
local histogram_zero_line_t = (scale_min * scale_max < 0.0) and (1 + scale_min * inv_scale) or (scale_min < 0.0 and 0.0 or 1.0) -- Where does the zero line stands
local col_base = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLines or ImGuiCol.PlotHistogram)
local col_hovered = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLinesHovered or ImGuiCol.PlotHistogramHovered)
local inner_min_x, inner_min_y, inner_max_x, inner_max_y = inner_bb.Min.x, inner_bb.Min.y, inner_bb.Max.x, inner_bb.Max.y
local draw_list = window.DrawList
for _ = 0, res_w - 1 do
local t1 = t0 + t_step
local v1_idx = math.floor(t0 * item_count + 0.5) + 1
IM_ASSERT(v1_idx >= 1 and v1_idx <= values_count)
local v1 = values_getter(data, (v1_idx - 1 + values_offset + 1) % values_count + 1)
local tp1 = ImVec2(t1, 1.0 - ImSaturate((v1 - scale_min) * inv_scale))
local tp1_x, tp1_y = t1, 1.0 - ImSaturate((v1 - scale_min) * inv_scale)
-- NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
local pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0)
local pos1
-- [Luau] ImLerp() on scalars into scratch vectors, only read by AddLine()/AddRectFilled()
local pos0, pos1 = PlotEx_pos0, PlotEx_pos1
pos0.x = inner_min_x + (inner_max_x - inner_min_x) * tp0_x; pos0.y = inner_min_y + (inner_max_y - inner_min_y) * tp0_y
pos1.x = inner_min_x + (inner_max_x - inner_min_x) * tp1_x
if plot_type == ImGuiPlotType.Lines then
pos1 = ImLerp(inner_bb.Min, inner_bb.Max, tp1)
pos1.y = inner_min_y + (inner_max_y - inner_min_y) * tp1_y
else
pos1 = ImLerp(inner_bb.Min, inner_bb.Max, ImVec2(tp1.x, histogram_zero_line_t))
pos1.y = inner_min_y + (inner_max_y - inner_min_y) * histogram_zero_line_t
end
if plot_type == ImGuiPlotType.Lines then
window.DrawList:AddLine(pos0, pos1, idx_hovered == v1_idx and col_hovered or col_base)
draw_list:AddLine(pos0, pos1, idx_hovered == v1_idx and col_hovered or col_base)
elseif plot_type == ImGuiPlotType.Histogram then
if pos1.x >= pos0.x + 2.0 then
pos1.x = pos1.x - 1.0
end
window.DrawList:AddRectFilled(pos0, pos1, idx_hovered == v1_idx and col_hovered or col_base)
draw_list:AddRectFilled(pos0, pos1, idx_hovered == v1_idx and col_hovered or col_base)
end
t0 = t1
tp0 = tp1
tp0_x, tp0_y = tp1_x, tp1_y
end
end
@@ -10766,6 +10877,8 @@ end
--- @param shortcut? string
--- @param selected? bool
--- @param enabled? bool
-- [Luau] scratch for MenuItemEx(): only read by its callees (Selectable() only reads size_arg), never escape
local MenuItem_text_pos, MenuItem_size, MenuItem_p = ImVec2(), ImVec2(), ImVec2()
function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled)
if selected == nil then selected = false end
if enabled == nil then enabled = true end
@@ -10777,10 +10890,9 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled)
local g = GImGui
local style = g.Style
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- [Luau] scalar pos
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local label_size_x, label_size_y = ImGui.CalcTextSizeXY(label, 1, label_end, false) -- [Luau] scalar label_size
-- See BeginMenuEx() for comments about this.
local menuset_is_open = IsRootOfOpenMenuSet()
@@ -10806,9 +10918,11 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled)
-- Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
-- Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark.
window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5)
local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset)
local text_pos = MenuItem_text_pos
text_pos.x, text_pos.y = window.DC.CursorPos.x + offsets.OffsetLabel, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset
ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0)
pressed = ImGui.Selectable("", selected, selectable_flags, ImVec2(label_size.x, 0.0))
local size = MenuItem_size; size.x = label_size_x; size.y = 0.0
pressed = ImGui.Selectable("", selected, selectable_flags, size)
ImGui.PopStyleVar()
if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 then
ImGui.RenderText(text_pos, label, 1, label_end, false)
@@ -10827,25 +10941,31 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled)
shortcut_w = ImGui.CalcTextSize(shortcut, nil).x
end
local checkmark_w = IM_TRUNC(g.FontSize * 1.20) -- FIXME: Always accounted for, even in a menu with none, because 'selected' has no neutral setting.
local min_w = offsets:DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w) -- Feedback for next frame
local min_w = offsets:DeclColumns(icon_w, label_size_x, shortcut_w, checkmark_w) -- Feedback for next frame
local stretch_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w)
local text_pos = ImVec2(pos.x, pos.y + window.DC.CurrLineTextBaseOffset)
pressed = ImGui.Selectable("", false, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y))
local text_pos_x, text_pos_y = pos_x, pos_y + window.DC.CurrLineTextBaseOffset -- [Luau] scalar text_pos
local size = MenuItem_size; size.x = min_w; size.y = label_size_y
pressed = ImGui.Selectable("", false, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), size)
if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 then
ImGui.RenderText(text_pos + ImVec2(offsets.OffsetLabel, 0.0), label, 1, label_end, false)
local p = MenuItem_p -- [Luau] text_pos + ImVec2(...) into scratch (RenderText()/RenderCheckMark() only read it)
p.x, p.y = text_pos_x + offsets.OffsetLabel, text_pos_y + 0.0
ImGui.RenderText(p, label, 1, label_end, false)
if icon_w > 0.0 then
--- @cast icon string
ImGui.RenderText(text_pos + ImVec2(offsets.OffsetIcon, 0.0), icon)
p.x, p.y = text_pos_x + offsets.OffsetIcon, text_pos_y + 0.0
ImGui.RenderText(p, icon)
end
if shortcut_w > 0.0 then
ImGui.PushStyleColor(ImGuiCol.Text, style.Colors[ImGuiCol.TextDisabled])
ImGui.LogSetNextTextDecoration("(", ")")
--- @cast shortcut string
ImGui.RenderText(text_pos + ImVec2(offsets.OffsetShortcut + stretch_w, 0.0), shortcut, nil, nil, false)
p.x, p.y = text_pos_x + (offsets.OffsetShortcut + stretch_w), text_pos_y + 0.0
ImGui.RenderText(p, shortcut, nil, nil, false)
ImGui.PopStyleColor()
end
if selected then
ImGui.RenderCheckMark(window.DrawList, text_pos + ImVec2(offsets.OffsetMark + stretch_w + g.FontSize * 0.40, g.FontSize * 0.134 * 0.5), ImGui.GetColorU32(ImGuiCol.Text), g.FontSize * 0.866)
p.x, p.y = text_pos_x + (offsets.OffsetMark + stretch_w + g.FontSize * 0.40), text_pos_y + g.FontSize * 0.134 * 0.5
ImGui.RenderCheckMark(window.DrawList, p, ImGui.GetColorU32(ImGuiCol.Text), g.FontSize * 0.866)
end
end
end
+46 -26
View File
@@ -213,7 +213,8 @@ local STBTT_fabs = math.abs
local STBTT_ifloor = math.floor
local STBTT_iceil = math.ceil
local trunc = function(x)
@native
local function trunc(x)
if x >= 0 then
return math.floor(x)
else
@@ -2066,11 +2067,25 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t
if e.fdx == 0 then
local x0 = e.fx
if x0 < len then
if x0 >= 0 then
stbtt__handle_clipped_edge(scanline, trunc(x0), e, x0, y_top, x0, y_bottom)
stbtt__handle_clipped_edge(scanline_fill, trunc(x0) + 1, e, x0, y_top, x0, y_bottom)
else
stbtt__handle_clipped_edge(scanline_fill, 0, e, x0, y_top, x0, y_bottom)
-- [Luau] the stbtt__handle_clipped_edge() calls, inlined (every edge of pixel fonts like ProggyClean is
-- vertical): x0 == x1, so clipping to sy/ey keeps x, and the same arithmetic gives the same results
local y0, y1 = y_top, y_bottom
local sy, ey = e.sy, e.ey
if y0 <= ey and y1 >= sy then
if y0 < sy then y0 = sy end
if y1 > ey then y1 = ey end
local height = e.direction * (y1 - y0)
if x0 >= 0 then
local x = math.floor(x0) -- trunc(x0)
if x0 <= x then
scanline[x] = scanline[x] + height
else
scanline[x] = scanline[x] + height * (1 - ((x0 - x) + (x0 - x)) / 2)
end
scanline_fill[x + 1] = scanline_fill[x + 1] + height
else
scanline_fill[0] = scanline_fill[0] + height
end
end
end
else
@@ -2615,9 +2630,12 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
local n = 0
local start = 0
-- [Luau] vertex types and the current vertex in locals, stbtt__add_point() inlined (same values)
local VTX_MOVE, VTX_LINE, VTX_CURVE, VTX_CUBIC = STBTT_VTX.MOVE, STBTT_VTX.LINE, STBTT_VTX.CURVE, STBTT_VTX.CUBIC
-- count how many "moves" there are to get the contour count
for i = 1, num_verts do
if vertices[i].type == STBTT_VTX.MOVE then
if vertices[i].type == VTX_MOVE then
n = n + 1
end
end
@@ -2637,7 +2655,9 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
num_points = 0
n = -1
for i = 1, num_verts do
if vertices[i].type == STBTT_VTX.MOVE then
local v = vertices[i]
local vtype = v.type
if vtype == VTX_MOVE then
-- start the next contour
if n >= 0 then
contour_lengths[n + 1] = num_points - start
@@ -2645,30 +2665,30 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
n = n + 1
start = num_points
x = vertices[i].x
y = vertices[i].y
stbtt__add_point(points, num_points, x, y)
x = v.x
y = v.y
num_points = num_points + 1
elseif vertices[i].type == STBTT_VTX.LINE then
x = vertices[i].x
y = vertices[i].y
stbtt__add_point(points, num_points, x, y)
if points then local pt = points[num_points]; pt.x = x; pt.y = y end -- stbtt__add_point()
elseif vtype == VTX_LINE then
x = v.x
y = v.y
num_points = num_points + 1
elseif vertices[i].type == STBTT_VTX.CURVE then
if points then local pt = points[num_points]; pt.x = x; pt.y = y end -- stbtt__add_point()
elseif vtype == VTX_CURVE then
num_points = stbtt__tesselate_curve(points, num_points, x, y,
vertices[i].cx, vertices[i].cy,
vertices[i].x, vertices[i].y,
v.cx, v.cy,
v.x, v.y,
objspace_flatness_squared, 0)
x = vertices[i].x
y = vertices[i].y
elseif vertices[i].type == STBTT_VTX.CUBIC then
x = v.x
y = v.y
elseif vtype == VTX_CUBIC then
num_points = stbtt__tesselate_cubic(points, num_points, x, y,
vertices[i].cx, vertices[i].cy,
vertices[i].cx1, vertices[i].cy1,
vertices[i].x, vertices[i].y,
v.cx, v.cy,
v.cx1, v.cy1,
v.x, v.y,
objspace_flatness_squared, 0)
x = vertices[i].x
y = vertices[i].y
x = v.x
y = v.y
end
end
contour_lengths[n + 1] = num_points - start
+85 -8
View File
@@ -23,6 +23,14 @@
# C `--@hoist` functions in the sources (pure numeric helpers: ImMin, ImMax, ImClamp, ...) are moved to the bundle top
# as `local function`s (their source lines become blank) so Luau -O2 can inline them everywhere.
# E statement-form `IM_ASSERT(...)` becomes `assert(...)` (fast builtin); expression uses are left alone.
# L (Roblox) library-internal `ImGui.Foo` reads inside function bodies become `ImGui_Foo`, a local of the file's
# __FILES function or of a wrapper around it (the file's most used names, within the 200 locals / upvalues
# limits; the rest stays ImGui.Foo). Luau's inline cache only
# remembers hash slots < 256 and ImGui has ~1000 keys: most ImGui.Foo lookups missed it. Each file registers a
# binder (`ImGui_Foo = ImGui.Foo`, ...) that IM_INCLUDE runs after every file it loads, so they are set before
# any user code runs. Only names assigned exactly once, at load time, are localized (checked here); ImGui.Foo
# stays set (public table unchanged). An app that replaces ImGui.Foo no longer intercepts the library's own
# calls, except for the names in L_PATCHABLE (hooked by tests/apps: those stay table lookups).
import os, re, sys, json, shutil, subprocess, tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
@@ -35,7 +43,7 @@ LOVE = False
if "--target" in sys.argv:
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"]
OPT = {x: os.environ.get("IMGUI_BUNDLE_NOOPT") != "1" and os.environ.get("IMGUI_BUNDLE_NO_" + x) != "1" for x in "ABCE"}
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
# per function (margin left for nested functions that also capture file locals)
MAX_LOCALS, MAX_UPVALUES = 160, (45 if LOVE else 150)
@@ -178,11 +186,11 @@ if OPT["E"]:
# ---- B: enum / constant folding ----
LUAU = shutil.which("luau") or (sorted(__import__("glob").glob("/nix/store/*-luau-*/bin/luau")) or ["luau"])[-1]
def header():
return ["local __FILES, __LOADED = {}, {}",
def header(bind=False):
return ["local __FILES, __LOADED%s = {}, {}%s" % ((", __BIND", ", {}") if bind else ("", "")),
"function IM_INCLUDE(name)",
" local r = __LOADED[name]",
" if r == nil then r = __FILES[name](); if r == nil then r = true end; __LOADED[name] = r end",
" if r == nil then r = __FILES[name](); if r == nil then r = true end; __LOADED[name] = r%s end" % ("; for i = 1, #__BIND do __BIND[i]() end" if bind else ""),
" return r",
"end", ""]
@@ -278,17 +286,86 @@ if OPT["A"]:
hot.append(n)
taken = [c + (n in u) for c, u in zip(taken, used)]
# ---- L: ImGui.Foo reads in function bodies -> per-file locals ----
# (L only rewrites `ImGui.Foo` reads: MT.* methods and other globals, e.g. what backends/roblox/patches.lua replaces at
# load time - MT.ImFont.RenderText, MT.ImDrawList.AddText, ImFontCalcTextSizeXY - are never copied. Assignments in
# backend modules count too: a name set in two places is not localized.)
L_PATCHABLE = re.compile(r"(Begin|End|TreeNode\w*|CollapsingHeader|ItemAdd|ItemHoverable|ItemSize|BeginTabItem|ShowDemoWindow)$")
L_LOCALS, L_UPVALUES = 200 - 20 - 10, 200 - 5 # Luau limits per function, minus the registers check's 20, minus margin
localized = {} # __FILES function -> ([Foo, ...] in a wrapper function, [Foo, ...] in the function itself)
def imgui_read(toks, d, i, ok):
"""toks[i] starts an `ImGui.Foo` read (Foo in ok) inside a function body"""
return toks[i][1] == "ImGui" and d[i] > 0 and isref(toks, i) and toks[i - 1][1] != "function" and nexttext(toks, i) == "." and toks[i + 2][1] in ok and nexttext(toks, i + 2) != "="
def nlocal(toks, i):
"""names declared by the `local` at toks[i]"""
if nexttext(toks, i) == "function": return 1
n, j = 1, i + 2
while nexttext(toks, j - 1) == "," : n += 1; j += 2
return n
if OPT["L"] and not LOVE:
lexed = {f: lex(s) for f, s in FILES.items()}
sets, idents = {}, set()
for f, toks in lexed.items():
d = fdepths(toks)
idents.update(t for k, t, _ in toks if k == "name")
for i, (k, t, p) in enumerate(toks):
if t != "ImGui" or not isref(toks, i): continue
nx = nexttext(toks, i)
if nx != ".":
assert nx == "=" and d[i] == 0 and nexttext(toks, i + 1) == "{", "L: %s: ImGui used as a value (%r): can't prove single assignment of its fields" % (f, nx)
continue
key, after = toks[i + 2][1], nexttext(toks, i + 2)
j = i + 3 # `ImGui.Foo, x = ...` (multiple assignment)? walk a target list
while after == "," and j < len(toks) and (toks[j][0] == "name" or toks[j][1] in (".", ",")): j += 1
if i > 0 and toks[i - 1][1] == "function": sets.setdefault(key, []).append((f, d[i - 1]))
elif after == "=" or (after == "," and j < len(toks) and toks[j][1] == "="): sets.setdefault(key, []).append((f, d[i]))
ok = {n for n, w in sets.items() if len(w) == 1 and w[0][1] == 0 and not L_PATCHABLE.match(n)}
clash = {"ImGui_" + n for n in ok} & idents
assert not clash, "L: local names clash with source identifiers: %s" % sorted(clash)
# where the locals go (most used names first): the __FILES function itself (room left next to its own top-level
# locals) and, when that's not enough, a wrapper function around it first (`(function() local ImGui_Foo, ...
# return function() <file> end end)()`: they are upvalues of the file function, next to the bundle-level A/C locals).
# The rest stays ImGui.Foo (small tables `ImGui__1.Foo` for them, always cache hits, measured no faster).
upvals = set(hot + hoisted_names + re.findall(r"\w+", HOIST_DEPS.split("=")[0]))
count, nlocals, nupvals = {}, {}, {}
for f, toks in lexed.items():
fn, d = GROUP.get(f, f), fdepths(toks)
nlocals[fn] = nlocals.get(fn, 0) + sum(nlocal(toks, i) for i in range(len(toks)) if toks[i][1] == "local" and d[i] == 0)
nupvals.setdefault(fn, set()).update(t for i, (k, t, _) in enumerate(toks) if t in upvals and isref(toks, i))
if "ImGui" in declared(toks): count[fn] = None
if count.get(fn, {}) is None: continue
c = count.setdefault(fn, {})
for i in range(len(toks)):
if imgui_read(toks, d, i, ok): c[toks[i + 2][1]] = c.get(toks[i + 2][1], 0) + 1
if BACKEND in nlocals: nlocals[BACKEND] += len(MODULES)
for fn, c in count.items():
c = sorted(c or (), key=lambda n: (-c[n], n))
inner = max(0, L_LOCALS - nlocals[fn])
outer = 0 if fn == BACKEND or len(c) <= inner else min(L_LOCALS, L_UPVALUES - len(nupvals[fn])) # (registers check: the backend's function line stays plain)
if c: localized[fn] = (sorted(c[:outer]), sorted(c[outer:outer + inner]))
for f, toks in lexed.items():
sel = set().union(*localized.get(GROUP.get(f, f), ()))
if not sel: continue
d = fdepths(toks)
FILES[f] = apply(FILES[f], [(toks[i][2], toks[i + 2][2] + len(toks[i + 2][1]), "ImGui_" + toks[i + 2][1]) for i in range(len(toks)) if imgui_read(toks, d, i, sel)])
out = ["--!optimize 2", "-- GENERATED by tools/bundle.py from *.lua, backends/, fonts/ - do not edit", ""]
if LOVE:
out = ["-- GENERATED by tools/bundle.py --target love - do not edit", re.search(r"--@compat-begin\n(.*?)--@compat-end", open(os.path.join(BACKEND_DIR, BACKEND)).read(), re.S).group(1), ""]
if hot: out.append("local " + ", ".join(hot))
if hoisted: out += [HOIST_DEPS] + hoisted
out += header()
out += header(bool(localized))
linemap = [] # (first bundle line, file) for error -> source mapping (tools/test/run.py)
def nextline(): return sum(x.count("\n") + 1 for x in out) + 1
for name, src in sorted(FILES.items()):
if name in GROUP: continue
out.append("__FILES[%r] = function()" % name)
outer, inner = localized.get(name, ((), ()))
out.append("__FILES[%r] = %sfunction()" % (name, "(" if outer else ""))
for ns in (outer, inner): # declared + bound (now and after every IM_INCLUDE: load-time calls into other files)
if not ns: continue
out.append("local " + ", ".join("ImGui_" + n for n in ns))
out.append("__BIND[#__BIND + 1] = function() if ImGui then " + " ".join("ImGui_%s = ImGui.%s" % (n, n) for n in ns) + " end end; __BIND[#__BIND]()")
if ns is outer: out.append("return function()")
if name == BACKEND and MODULES:
out.append("local " + ", ".join(EXPORT[k] for k in MODULES))
for k in MODULES:
@@ -299,7 +376,7 @@ for name, src in sorted(FILES.items()):
src = INCLUDE.sub("", src)
linemap.append((nextline(), name))
out.append(src.rstrip("\n"))
out.append("end")
out.append("end end)()" if outer else "end")
out.append("")
for name in ENTRY:
out.append("IM_INCLUDE(%r)" % name)
@@ -324,4 +401,4 @@ if not LOVE:
open(os.path.join(OUT, "ImGuiWorker.client.luau"), "w").write(
"--!optimize 2\n-- GENERATED by tools/bundle.py from backends/roblox/worker.luau + raster.lua - do not edit\n"
+ worker[:req.start()] + "local Raster = (function()\n" + raster + "\nend)()" + worker[req.end():])
print("wrote build/%s (%d files, %d exports)" % (NAME, len(FILES), len(names)))
print("wrote build/%s (%d files, %d exports%s)" % (NAME, len(FILES), len(names), ", %d ImGui.* localized" % sum(len(a) + len(b) for a, b in localized.values()) if localized else ""))
+112
View File
@@ -0,0 +1,112 @@
-- Benchmark scenes shared by the Studio bench (slopgame place, ReplicatedStorage.Shared.BenchScenes) and the headless
-- tools/test/scripts/t_stress2.luau. Deterministic: everything animates from the frame number f, never from time.
-- return function(G, ImPlot?) -> { plots = fn(f), colorpicker = fn(f), implot = fn(f) (if ImPlot), demo_all = fn(f) }
return function(G, ImPlot)
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
local Cond = G.ImGuiCond
local S = { values = table.create(90, 0), col1 = ImVec4(0.4, 0.7, 0.2, 0.5), col2 = ImVec4(0.9, 0.3, 0.6, 0.8),
edits = { ImVec4(1, 0, 0, 1), ImVec4(0, 1, 0, 0.5), ImVec4(0, 0, 1, 1), ImVec4(1, 1, 0, 0.25) } }
local scenes = {}
local function Place(name, x, y, w, h)
ImGui.SetNextWindowPos(ImVec2(x, y), Cond.Always)
ImGui.SetNextWindowSize(ImVec2(w, h), Cond.Always)
return ImGui.Begin(name)
end
-- PlotLines + PlotHistogram over a 90-sample ring buffer, one new sample per frame (demo "Plots Widgets" pattern)
function scenes.plots(f)
local v = S.values
local off = f % 90
v[off + 1] = math.sin(f * 0.13) * 0.7 + math.sin(f * 0.031) * 0.3
Place("Plots", 60, 60, 520, 640)
ImGui.PlotLines("Lines", v, nil, 90, off, "avg", -1.0, 1.0, ImVec2(0, 120))
ImGui.PlotHistogram("Histogram", v, nil, 90, off, nil, -1.0, 1.0, ImVec2(0, 120))
ImGui.PlotLines("Lines small", v, nil, 90, off, nil, -1.0, 1.0, ImVec2(0, 60))
ImGui.PlotHistogram("Histogram small", v, nil, 90, off, nil, -1.0, 1.0, ImVec2(0, 60))
ImGui.End()
end
-- ColorPicker4 with hue bar and with hue wheel (+ alpha bars), colour animated every frame, plus ColorEdit4s
function scenes.colorpicker(f)
local h = (f * 0.005) % 1
local r, g, b = ImGui.ColorConvertHSVtoRGB(h, 0.7, 0.9)
S.col1.x, S.col1.y, S.col1.z = r, g, b
r, g, b = ImGui.ColorConvertHSVtoRGB((h + 0.5) % 1, 0.5, 0.8)
S.col2.x, S.col2.y, S.col2.z = r, g, b
local F = G.ImGuiColorEditFlags
Place("Colors", 60, 60, 520, 640)
ImGui.ColorPicker4("bar", S.col1, bit32.bor(F.PickerHueBar, F.AlphaBar))
ImGui.ColorPicker4("wheel", S.col2, bit32.bor(F.PickerHueWheel, F.AlphaBar))
for i, c in S.edits do ImGui.ColorEdit4("edit " .. i, c) end
ImGui.End()
end
if ImPlot then
local xs, ys, sx, sy, bars, xs101, y1, y2, heat = {}, {}, {}, {}, {}, {}, {}, {}, {}
for i = 1, 1001 do xs[i] = (i - 1) * 0.001 end
for i = 1, 100 do
sx[i] = ((i * 7919) % 1000) / 1000
sy[i] = ((i * 104729) % 1000) / 1000
end
for i = 1, 101 do xs101[i] = i - 1 end
-- line (1001 pts, animated), scatter (100 pts), bars (10, animated), shaded (2x101, animated), heatmap (10x10, animated)
function scenes.implot(f)
for i = 1, 1001 do ys[i] = 0.5 + 0.5 * math.sin(50 * (xs[i] + f * 0.002)) end
for i = 1, 10 do bars[i] = 5 + 4 * math.sin(f * 0.05 + i) end
for i = 1, 101 do
y1[i] = 250 + 100 * math.sin((i + f) * 0.07)
y2[i] = 200 + 80 * math.cos((i + f) * 0.05)
end
for i = 1, 100 do heat[i] = 0.5 + 0.5 * math.sin(i * 0.37 + f * 0.04) end
Place("ImPlot", 60, 60, 620, 900)
local sz = ImVec2(-1, 200)
if ImPlot.BeginPlot("Line", sz) then
ImPlot.SetupAxesLimits(0, 1, 0, 1, Cond.Always)
ImPlot.PlotLine("f(x)", xs, ys, 1001)
ImPlot.EndPlot()
end
if ImPlot.BeginPlot("Scatter + Bars", sz) then
ImPlot.SetupAxesLimits(0, 10, 0, 10, Cond.Always)
ImPlot.PlotBars("bars", bars, 10, 0.7, 0)
local sxx, syy = {}, {}
for i = 1, 100 do sxx[i], syy[i] = sx[i] * 10, sy[i] * 10 end
ImPlot.PlotScatter("pts", sxx, syy, 100)
ImPlot.EndPlot()
end
if ImPlot.BeginPlot("Shaded", sz) then
ImPlot.SetupAxesLimits(0, 100, 0, 500, Cond.Always)
ImPlot.PlotShaded("a", xs101, y1, 101, 0)
ImPlot.PlotShaded("b", xs101, y2, 101, 0)
ImPlot.PlotLine("a", xs101, y1, 101)
ImPlot.PlotLine("b", xs101, y2, 101)
ImPlot.EndPlot()
end
if ImPlot.BeginPlot("##Heatmap", ImVec2(220, 220)) then
ImPlot.PlotHeatmap("heat", heat, 10, 10, 0, 1, "%.1f")
ImPlot.EndPlot()
end
ImGui.End()
end
end
-- the whole demo window, every CollapsingHeader / TreeNode forced open, static
local realCH, realTN, forcing = ImGui.CollapsingHeader, ImGui.TreeNode, false
ImGui.CollapsingHeader = function(label, ...)
if forcing then ImGui.SetNextItemOpen(true, Cond.Always) end
return realCH(label, ...)
end
ImGui.TreeNode = function(label, ...)
if forcing then ImGui.SetNextItemOpen(true, Cond.Always) end
return realTN(label, ...)
end
function scenes.demo_all(f)
ImGui.SetNextWindowPos(ImVec2(60, 40), Cond.Always)
ImGui.SetNextWindowSize(ImVec2(620, 900), Cond.Always)
forcing = true
ImGui.ShowDemoWindow()
forcing = false
end
return scenes
end
+3 -1
View File
@@ -39,9 +39,11 @@ CHECKS=(
"demo_open|DRAWHASH|$R --main tools/test/scripts/t_drawhash.luau --frames 150 --open"
"demo_random|^|python3 tools/test/run.py --roblox --timeout 600 --frames 400 --open"
"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"
"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"
"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"
"parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 500"
"parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 620"
"pool_ctx|POOLCTX OK|$R --main tools/test/scripts/t_pool_ctx.luau --frames 60"
"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"
+2
View File
@@ -5,6 +5,8 @@
# demo = t_drawhash with Widgets,Basic / whole demo open: changes with any demo edit
cd "$(dirname "$0")/../.."
export PATH="$PATH:/nix/store/2m2ja613nndihc8qm10f2rhq6znp1nh4-luau-0.734/bin:/nix/store/4qxq4arv32ly13kl3g0m5q80gm3a35xr-luajit-2.1.1741730670/bin"
command -v luau >/dev/null || { l=$(ls -d /nix/store/*-luau-*/bin 2>/dev/null | tail -1); [ -n "$l" ] && export PATH="$PATH:$l"; }
command -v luajit >/dev/null || { l=$(ls -d /nix/store/*-luajit-2*/bin 2>/dev/null | grep -v -- -env | tail -1); [ -n "$l" ] && export PATH="$PATH:$l"; }
REV=${1:-HEAD}
hashes() { # $1 = repo dir
( cd "$1"
+102
View File
@@ -0,0 +1,102 @@
-- Moving-window pixel oracle (like t_pixels): a window with circles, rounded rects, bullets and curves moves by whole
-- pixels (some frames by half a pixel), "PIX <frame> <hash>" every 4 frames. Trig-generated vertices drift by an ulp
-- off the exact shift: the backend must still redraw what they touch. 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, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
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 col = ImVec4(0.4, 0.7, 0.2, 0.5)
local buf = ImGui.NewTextBuffer("type here", 128)
local slider = 0.3
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 = ImVec2(40, 40)
local radio = 1
game:GetService("RunService").Stepped:Connect(function()
frame += 1
if frame > 240 then return end
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(1200, 740)
if frame > 4 then
if frame < 120 then pos = ImVec2(pos.x + 3, pos.y + 2) else pos = ImVec2(pos.x - 5, pos.y - 1) end
if frame % 37 == 0 then pos = ImVec2(pos.x + 0.5, pos.y) end -- fractional: full path
end
ImGui.NewFrame()
ImGui.SetNextWindowPos(pos, G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(420, 460), G.ImGuiCond.Always)
ImGui.Begin("Stress")
for i = 1, 6 do ImGui.Button("Button " .. i); ImGui.SameLine(); slider = ImGui.SliderFloat("##s" .. i, slider, 0, 1) end
for i = 1, 4 do if ImGui.RadioButton("r" .. i, radio == i) then radio = i end; ImGui.SameLine() end
ImGui.NewLine()
ImGui.Checkbox("check", true)
ImGui.Bullet(); ImGui.Text("bullet")
if ImGui.TreeNode("tree") then ImGui.Text("inside"); ImGui.TreePop() end
ImGui.ColorButton("cb", col)
local dl = ImGui.GetWindowDrawList()
local p = ImGui.GetCursorScreenPos()
dl:AddCircleFilled(ImVec2(p.x + 40, p.y + 40), 33.3, 0xFF3080F0)
dl:AddCircle(ImVec2(p.x + 120, p.y + 40), 27.7, 0xFFF08030, 0, 2.5)
dl:AddRectFilled(ImVec2(p.x + 170, p.y + 10), ImVec2(p.x + 260, p.y + 70), 0x8040F040, 12.3)
dl:AddBezierCubic(ImVec2(p.x, p.y + 90), ImVec2(p.x + 90, p.y + 60), ImVec2(p.x + 180, p.y + 140), ImVec2(p.x + 300, p.y + 90), 0xFFFFFFFF, 1.7)
ImGui.Dummy(ImVec2(300, 150))
for i = 1, 40 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog.", i) end
ImGui.End()
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if frame % 4 == 0 then
print("PIX", frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
end
if frame == 240 then print("MOVEPIX DONE") end
end)
+9 -1
View File
@@ -4,7 +4,7 @@
-- PreSimulation -> PostSimulation), open with SyncDrop (half the worker results lost -> Finish falls back), and closed
-- (late RenderDrawData: rasterized + uploaded at once). The composites of A and B must match at every checkpoint.
-- Prints the executor's main-thread pack cost per frame next to A's inline raster + upload cost.
-- run: python3 tools/test/run.py --main tools/test/scripts/t_parallel.luau --frames 900 --quiet --roblox
-- run: python3 tools/test/run.py --main tools/test/scripts/t_parallel.luau --frames 900 --quiet --roblox (5 scenarios: >= 600)
local RS = game:GetService("ReplicatedStorage")
local G = require(RS:WaitForChild("ImGui"))
local ImGui, ImVec2 = G.ImGui, G.ImVec2
@@ -85,6 +85,14 @@ local SCEN = {
ImGui.Text("frame %d", f)
ImGui.End()
end },
{ "fonts", function(f) -- a new font size every frame: glyph uploads, atlas grow/repack (Actor texture patches)
ImGui.SetNextWindowPos(ImVec2(40, 30), G.ImGuiCond.Always); ImGui.SetNextWindowSize(ImVec2(620, 600), G.ImGuiCond.Always)
ImGui.Begin("Fonts")
ImGui.PushFont(nil, 12 + (f * 0.25) % 40)
for i = 1, 12 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog, %d times.", i, f) end
ImGui.PopFont()
ImGui.End()
end },
}
local ctx, gui = {}, {}
+88
View File
@@ -0,0 +1,88 @@
-- Pixel oracle for the bench scenes (tools/test/bench_scenes.luau: plots, colorpicker, implot if ImPlot is given,
-- demo_all), animated: composites the ScreenGui (like t_pixels) every few frames and prints "PIX <scene> <frame> <hash>".
-- Run with RUN_FLAGS="ARG_FORCE=true" for a full redraw every frame: incremental output must match it exactly (and match
-- the previous backend version).
-- python3 tools/test/run.py --main tools/test/scripts/t_scene_pixels.luau --frames 200 --quiet --roblox \
-- --module BenchScenes=tools/test/bench_scenes.luau [--module ImPlot=extensions/implot-luau/ImPlot.lua]
local RS = game:GetService("ReplicatedStorage")
local G = require(RS:WaitForChild("ImGui"))
local ImGui = G.ImGui
local ImPlot = RS:FindFirstChild("ImPlot") and require(RS.ImPlot)(G)
ImGui.CreateContext()
if ImPlot then ImPlot.CreateContext() end
G.ImGui_ImplRoblox.Init()
G.ImGui_ImplRoblox.SetRenderRate(0)
local io = ImGui.GetIO()
local W, H = 1280, 760
local scenes = require(RS:WaitForChild("BenchScenes"))(G, ImPlot)
local ORDER = {}
for _, name in { "plots", "colorpicker", "implot", "demo_all" } do
if scenes[name] then table.insert(ORDER, name) end
end
local FRAMES, EVERY = 40, 8
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
game:GetService("RunService").Stepped:Connect(function()
frame += 1
local si = (frame - 1) // FRAMES + 1
local name = ORDER[si]
if not name then return end
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(-1000, -1000)
ImGui.NewFrame()
scenes[name](frame)
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if frame % EVERY == 0 then
print("PIX", name, frame, composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui")))
end
if frame == #ORDER * FRAMES then print("SCENEPIX DONE") end
end)
+72
View File
@@ -0,0 +1,72 @@
-- Library CPU cost of the Studio bench's scene (demo window + "Stress" window: 20 buttons/sliders, a 60x6 table,
-- 80 TextWrapped lines), mouse sweeping over it. Prints the median ImGui.NewFrame..Render time (real clock, backend
-- excluded) and a checksum of the draw data. Use with --roblox (only @native functions native, like Studio); the machine
-- is often busy, so compare runs interleaved and look at the lower quartile (lowq-mean).
-- RUN_FLAGS="ARG_MODE='scroll'" python3 tools/test/run.py --main tools/test/scripts/t_stress.luau --frames 800 --quiet --roblox
-- ARG_MODE: "hover" (default), "idle" (mouse outside, like the bench's idle), "scroll", "resize", "fonts".
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)
local io = ImGui.GetIO()
local MODE = type(ARG_MODE) == "string" and ARG_MODE or "hover"
local clock = os.realclock or os.clock
local S = { fsize = 13, scroll = 0, pos = ImVec2(60, 60), size = ImVec2(520, 640), slider = 0.5, check = true }
local function StressWindow()
ImGui.SetNextWindowPos(S.pos, G.ImGuiCond.Always)
ImGui.SetNextWindowSize(S.size, G.ImGuiCond.Always)
ImGui.PushFont(nil, S.fsize)
ImGui.Begin("Stress")
ImGui.SetScrollY(S.scroll)
for i = 1, 20 do
if ImGui.Button("Button " .. i) then end
ImGui.SameLine()
S.slider = ImGui.SliderFloat("##s" .. i, S.slider, 0, 1)
end
_, S.check = ImGui.Checkbox("Checkbox", S.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, 80 do ImGui.TextWrapped("Line %d: the quick brown fox jumps over the lazy dog, again and again and again.", i) end
ImGui.PopFont()
ImGui.End()
end
local frame, h, times = 0, 0, {}
local function mix(v) h = (h * 31 + math.floor(v * 64 + 0.5)) % 2147483647 end
game:GetService("RunService").Stepped:Connect(function()
frame += 1
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
if MODE == "idle" then io:AddMousePosEvent(-1000, -1000) else io:AddMousePosEvent(70 + (frame * 7) % 480, 80 + (frame * 13) % 560) end
if MODE == "scroll" then S.scroll = (S.scroll + 6) % 2400 end
if MODE == "resize" then S.size = ImVec2(420 + (frame * 3) % 300, 500 + (frame * 2) % 200) end
if MODE == "fonts" then S.fsize = 12 + (frame * 0.25) % 40 end
local t0 = clock()
ImGui.NewFrame()
ImGui.SetNextWindowPos(ImVec2(620, 40), G.ImGuiCond.Once)
ImGui.ShowDemoWindow()
StressWindow()
ImGui.Render()
if frame > 20 then table.insert(times, clock() - t0) end
for _, dl in ImGui.GetDrawData().CmdLists:iter() do
local vb, id = dl.VtxBuffer.Buf, dl.IdxBuffer.Data
for i = 1, dl.VtxBuffer.Size do local o = (i - 1) * 36; mix(buffer.readf64(vb, o)); mix(buffer.readf64(vb, o + 8)); mix(buffer.readf64(vb, o + 16) * 4096); mix(buffer.readf64(vb, o + 24) * 4096); mix(buffer.readu32(vb, o + 32) / 64) end
for i = 1, dl.IdxBuffer.Size do mix(id[i]) end
for _, c in dl.CmdBuffer:iter() do mix(c.ClipRect.x); mix(c.ClipRect.y); mix(c.ClipRect.z); mix(c.ClipRect.w); mix(c.ElemCount) end
end
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if frame == ARG_FRAMES - 1 then
table.sort(times)
local lo = 0
for i = 1, #times // 4 do lo += times[i] end
print(string.format("STRESS %s med %.3f ms p25 %.3f ms lowq-mean %.3f ms", MODE, times[#times // 2 + 1] * 1000, times[#times // 4] * 1000, lo / (#times // 4) * 1000))
print("STRESSHASH", h)
end
end)
+55
View File
@@ -0,0 +1,55 @@
-- Headless twin of the Studio bench's round-3 scenes (tools/test/bench_scenes.luau): plots, colorpicker, implot,
-- demo_all. Prints the median / lower-quartile library time (NewFrame..Render) and backend time (RenderDrawData), and a
-- checksum of the draw data (must not change with internal optimizations).
-- RUN_FLAGS="ARG_MODE='plots'" python3 tools/test/run.py --main tools/test/scripts/t_stress2.luau --frames 400 --quiet --roblox \
-- --module BenchScenes=tools/test/bench_scenes.luau [--module ImPlot=../implot-luau/ImPlot.lua]
local RS = game:GetService("ReplicatedStorage")
local G = require(RS:WaitForChild("ImGui"))
local ImGui = G.ImGui
local ImPlot = RS:FindFirstChild("ImPlot") and require(RS.ImPlot)(G)
ImGui.CreateContext()
if ImPlot then ImPlot.CreateContext() end
G.ImGui_ImplRoblox.Init()
G.ImGui_ImplRoblox.SetRenderRate(0)
local io = ImGui.GetIO()
local MODE = type(ARG_MODE) == "string" and ARG_MODE or "plots"
local scene = require(RS:WaitForChild("BenchScenes"))(G, ImPlot)[MODE]
assert(scene, "unknown or unavailable scene " .. MODE)
local clock = os.realclock or os.clock
local frame, h, lib, be = 0, 0, {}, {}
local function mix(v) h = (h * 31 + math.floor(v * 64 + 0.5)) % 2147483647 end
local function stats(t)
table.sort(t)
local lo = 0
for i = 1, #t // 4 do lo += t[i] end
return t[#t // 2 + 1] * 1000, lo / (#t // 4) * 1000
end
game:GetService("RunService").Stepped:Connect(function()
frame += 1
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
io:AddMousePosEvent(-1000, -1000)
local t0 = clock()
ImGui.NewFrame()
scene(frame)
ImGui.Render()
local t1 = clock()
local dd = ImGui.GetDrawData()
for _, dl in dd.CmdLists:iter() do
local vb, id = dl.VtxBuffer.Buf, dl.IdxBuffer.Data
for i = 1, dl.VtxBuffer.Size do local o = (i - 1) * 36; mix(buffer.readf64(vb, o)); mix(buffer.readf64(vb, o + 8)); mix(buffer.readf64(vb, o + 16) * 4096); mix(buffer.readf64(vb, o + 24) * 4096); mix(buffer.readu32(vb, o + 32) / 64) end
for i = 1, dl.IdxBuffer.Size do mix(id[i]) end
for _, c in dl.CmdBuffer:iter() do mix(c.ClipRect.x); mix(c.ClipRect.y); mix(c.ClipRect.z); mix(c.ClipRect.w); mix(c.ElemCount) end
end
local t2 = clock()
G.ImGui_ImplRoblox.RenderDrawData(dd)
local t3 = clock()
if frame > 20 then table.insert(lib, t1 - t0); table.insert(be, t3 - t2) end
if frame == ARG_FRAMES - 1 then
local lm, ll = stats(lib)
local bm, bl = stats(be)
print(string.format("STRESS2 %s lib med %.3f lowq %.3f ms | backend med %.3f lowq %.3f ms", MODE, lm, ll, bm, bl))
print("STRESS2HASH", MODE, h)
end
end)
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "4dbug/imgui-luau"
version = "0.4.2"
version = "0.4.3"
registry = "https://github.com/UpliftGames/wally-index"
realm = "shared"
license = "MIT"