2 Commits
Author SHA1 Message Date
4DBug dd9a5ef219 0.4.2
Build & Release / build (push) Canceled after 0s
- Less garbage per frame: scalar text/label sizes, scratch rects/points, reused clip-stack ImVec4 and window stack entries (160 -> 56 KB/frame on demo+stress, draw hashes unchanged)
- Faster glyph baking: @native rasterizer/rect packer/pixel loops, glyph shape cache, comparator-free edge sort, inline scanline conversion, table.create zero-fill; fix leaked global 'step'
- Textures: new atlases convert only the packed corner, flat row conversion skipping zero pixels
- Raster: uniform-region tracking, direct opaque glyph texels, inlined BlendPixel with per-texel cache
- Raster: textured line quads drawn as one quad, u32 texel reads for constant-colour triangles, column walk for tall narrow triangles (plot bench Raster 4.16 -> 3.21 ms, HashVertex 0.64 -> 0.55 ms, pixels unchanged)
- Parallel: send Actors only changed atlas rows / rows above FillRow (full-copy 1283 -> 619 MB on fontbench x4 Actors); dispatch small and text-heavy frames (MinTiles 1, MinPixels 2048, MaxBytesPerPixel 0)
- Stage timing: Textures and Flush stages; parallel stats explain serial flushes
- extensions/: submodules for imcurveedit-luau, imgradient-luau, imgui-memory-editor-luau, imsequencer-luau; all 9 submodule URLs and README links now on GitHub
- new examples: example_love_extensions, example_roblox_extensions
2026-10-17 13:18:53 -05:00
4DBug 9b1052beed 0.4.1
Build & Release / build (push) Canceled after 0s
- TextProxy works for any widget that sets PlatformImeData.WantTextInput (+ SelectedText)
- TextProxy: key-code fallback waits for the TextBox (fixes doubled typing); no stuck Ctrl after paste
- Raster: reversed rects (min > max) draw like upstream (fixes ImNodes/ImPlot box select)
- test harness: --module NAME=path loads extra ModuleScripts
- new tests: t_textproxy_custom, t_rect_flip
- extensions/: submodules for imguicolortextedit-luau, imguizmo-luau, implot-luau, implot3d-luau, imnodes-luau
2026-10-17 07:31:40 -05:00
41 changed files with 4080 additions and 503 deletions

No files matched your search

+19 -3
View File
@@ -116,7 +116,7 @@ The Style Editor (`ImGui.ShowStyleEditor()`) and the Metrics/Debugger (`ImGui.Sh
### Getting Started & Integration (Roblox) ### Getting Started & Integration (Roblox)
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/[email protected].0"` 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].2"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source:
1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped. 1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped.
2. Sync with [Rojo](https://rojo.space): [`default.project.json`](/default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`. 2. Sync with [Rojo](https://rojo.space): [`default.project.json`](/default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`.
@@ -184,7 +184,7 @@ Rojo layout (as in [`default.project.json`](/default.project.json)):
``` ```
```lua ```lua
ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Worker ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, Worker
RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below) RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below)
ImGui_ImplRoblox.NewFrame() ImGui_ImplRoblox.NewFrame()
@@ -198,7 +198,7 @@ end)
``` ```
**Frame ordering.** A Roblox frame runs `PreRender` (`RenderStepped`), `PreAnimation`, `PreSimulation` (`Stepped`), `PostSimulation` (`Heartbeat`). What the scripts changed up to the end of `PostSimulation` of frame N is drawn by the render that follows the next `PreRender` (N+1), together with whatever `PreRender` N+1 changes. So `RenderDrawData` in `PreSimulation` (layer `Position`/`ZIndex`/`Visible` changes) plus `Finish` in `PostSimulation` (the pixels) land in the same render: no frame shows moved layers with old pixels. Actor work requested in `PreSimulation` runs in that frame's parallel phases, and the results are back before `PostSimulation`. **Frame ordering.** A Roblox frame runs `PreRender` (`RenderStepped`), `PreAnimation`, `PreSimulation` (`Stepped`), `PostSimulation` (`Heartbeat`). What the scripts changed up to the end of `PostSimulation` of frame N is drawn by the render that follows the next `PreRender` (N+1), together with whatever `PreRender` N+1 changes. So `RenderDrawData` in `PreSimulation` (layer `Position`/`ZIndex`/`Visible` changes) plus `Finish` in `PostSimulation` (the pixels) land in the same render: no frame shows moved layers with old pixels. Actor work requested in `PreSimulation` runs in that frame's parallel phases, and the results are back before `PostSimulation`.
- The executor only dispatches between `PreAnimation` and its `Finish`. A `RenderDrawData` anywhere else (`RenderStepped`/`PreRender`, after `Finish`, with too little work: fewer than `MinTiles` tiles or `MinPixels` dirty pixels, or with dense primitives: more than `MaxBytesPerPixel` packed payload bytes per dirty pixel, e.g. text-heavy frames, where packing costs more than rasterizing; `0` = no limit) is rasterized and uploaded on the main thread right away, like without the executor. That is always correct, just not parallel. - The executor only dispatches between `PreAnimation` and its `Finish`. A `RenderDrawData` anywhere else (`RenderStepped`/`PreRender`, after `Finish`, with too little work: fewer than `MinTiles` tiles or `MinPixels` dirty pixels, or with dense primitives: more than `MaxBytesPerPixel` packed payload bytes per dirty pixel, `0` = no limit, the default: measured in Studio, packing text-heavy frames costs under 0.1 ms) is rasterized and uploaded on the main thread right away, like without the executor. That is always correct, just not parallel.
- Minimal example: [examples/example_roblox_parallel/main.client.luau](/examples/example_roblox_parallel/main.client.luau) (the demo window, 2 Actors; map it instead of `examples/example_roblox` in `default.project.json`). - Minimal example: [examples/example_roblox_parallel/main.client.luau](/examples/example_roblox_parallel/main.client.luau) (the demo window, 2 Actors; map it instead of `examples/example_roblox` in `default.project.json`).
- If your frame ends elsewhere, call `ImGui_ImplRoblox.FinishParallel()` yourself. It must run before the next render, and after the parallel phase if you want the workers' results. - If your frame ends elsewhere, call `ImGui_ImplRoblox.FinishParallel()` yourself. It must run before the next render, and after the parallel phase if you want the workers' results.
- `ImGui_ImplRoblox.GetParallelStats()`: `ParallelFlushes`, `SerialFlushes`, `Tiles`, `Fallbacks` (worker results missing at `Finish`), `Late`, `Pack`/`Flush`/`Finish` (main-thread seconds, cumulative). `ImGui_ImplRoblox.GetParallelConfig()` returns the live config table (thresholds can be changed at any time; a new `Actors` count needs another `EnableParallel()`). - `ImGui_ImplRoblox.GetParallelStats()`: `ParallelFlushes`, `SerialFlushes`, `Tiles`, `Fallbacks` (worker results missing at `Finish`), `Late`, `Pack`/`Flush`/`Finish` (main-thread seconds, cumulative). `ImGui_ImplRoblox.GetParallelConfig()` returns the live config table (thresholds can be changed at any time; a new `Actors` count needs another `EnableParallel()`).
@@ -312,6 +312,22 @@ python3 tools/test/run.py --main tools/test/scripts/t_tables.luau --frames 120 -
See [docs/PORTING.md](/docs/PORTING.md) for the porting rules. See [docs/PORTING.md](/docs/PORTING.md) for the porting rules.
### Extensions (work in progress)
Separate repos, included as submodules under `extensions/` (clone with `--recursive`):
- [imcurveedit-luau](https://github.com/4DBug/imcurveedit-luau): ImCurveEdit (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a curve editor.
- [imgradient-luau](https://github.com/4DBug/imgradient-luau): ImGradient (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a gradient editor.
- [imguicolortextedit-luau](https://github.com/4DBug/imguicolortextedit-luau): [ImGuiColorTextEdit](https://github.com/goossens/ImGuiColorTextEdit) (goossens fork), a syntax-highlighting text editor.
- [imguizmo-luau](https://github.com/4DBug/imguizmo-luau): [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), 3D gizmos with Roblox Camera/CFrame helpers.
- [imgui-memory-editor-luau](https://github.com/4DBug/imgui-memory-editor-luau): [imgui_memory_editor](https://github.com/ocornut/imgui_club) (imgui_club), a hex editor for Roblox `buffer`s, LÖVE `ByteData` and byte tables.
- [implot-luau](https://github.com/4DBug/implot-luau): [ImPlot](https://github.com/epezent/implot), 2D plotting.
- [implot3d-luau](https://github.com/4DBug/implot3d-luau): [ImPlot3D](https://github.com/brenocq/implot3d), 3D plotting.
- [imnodes-luau](https://github.com/4DBug/imnodes-luau): [imnodes](https://github.com/Nelarius/imnodes), a node editor.
- [imsequencer-luau](https://github.com/4DBug/imsequencer-luau): ImSequencer (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a timeline/sequencer.
Usage: `local ImPlot = require(ImPlotModule)(require(ImGuiModule))`.
### Not ported yet ### Not ported yet
Multi-select / box-select, typing-select, the Assets Browser example, the Item Picker and a few smaller items. The full list is in [docs/TODO.txt](/docs/TODO.txt). Multi-select / box-select, typing-select, the Assets Browser example, the Item Picker and a few smaller items. The full list is in [docs/TODO.txt](/docs/TODO.txt).
+27
View File
@@ -0,0 +1,27 @@
[submodule "extensions/imguicolortextedit-luau"]
path = extensions/imguicolortextedit-luau
url = https://github.com/4DBug/imguicolortextedit-luau.git
[submodule "extensions/imguizmo-luau"]
path = extensions/imguizmo-luau
url = https://github.com/4DBug/imguizmo-luau.git
[submodule "extensions/implot-luau"]
path = extensions/implot-luau
url = https://github.com/4DBug/implot-luau.git
[submodule "extensions/imnodes-luau"]
path = extensions/imnodes-luau
url = https://github.com/4DBug/imnodes-luau.git
[submodule "extensions/implot3d-luau"]
path = extensions/implot3d-luau
url = https://github.com/4DBug/implot3d-luau.git
[submodule "extensions/imcurveedit-luau"]
path = extensions/imcurveedit-luau
url = https://github.com/4DBug/imcurveedit-luau.git
[submodule "extensions/imgradient-luau"]
path = extensions/imgradient-luau
url = https://github.com/4DBug/imgradient-luau.git
[submodule "extensions/imgui-memory-editor-luau"]
path = extensions/imgui-memory-editor-luau
url = https://github.com/4DBug/imgui-memory-editor-luau.git
[submodule "extensions/imsequencer-luau"]
path = extensions/imsequencer-luau
url = https://github.com/4DBug/imsequencer-luau.git
+19 -3
View File
@@ -113,7 +113,7 @@ The Style Editor (`ImGui.ShowStyleEditor()`) and the Metrics/Debugger (`ImGui.Sh
### Getting Started & Integration (Roblox) ### Getting Started & Integration (Roblox)
With [Wally](https://wally.run) ([4dbug/imgui-luau](https://wally.run/package/4dbug/imgui-luau)): add `ImGui = "4dbug/[email protected].0"` 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].2"` under `[dependencies]` in your `wally.toml`, run `wally install`, then `require(ReplicatedStorage.Packages.ImGui)`. Or from source:
1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped. 1. Build the module: `python3 tools/bundle.py` writes `build/ImGui.luau` (`--no-demo` leaves the demo out) and `build/ImGuiTyped.luau`, a small typed entry module (Luau types for the public `ImGui.*` API, `ImVec2`/`ImVec4` and the flag enums) that requires `build/ImGui.luau` as its child `Impl`. The Wally package and the Rojo projects use that layout, so you get autocomplete and type errors in `--!strict` scripts. The single-file `ImGui.luau` also works on its own, just untyped.
2. Sync with [Rojo](https://rojo.space): [`default.project.json`](default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`. 2. Sync with [Rojo](https://rojo.space): [`default.project.json`](default.project.json) puts the module in `ReplicatedStorage.ImGui` and the example LocalScript in `StarterPlayerScripts`.
@@ -181,7 +181,7 @@ Rojo layout (as in [`default.project.json`](default.project.json)):
``` ```
```lua ```lua
ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Worker ImGui_ImplRoblox.EnableParallel({ Actors = 4 }) -- also: MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, Worker
RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below) RunService.PreSimulation:Connect(function() -- NOT RenderStepped (see below)
ImGui_ImplRoblox.NewFrame() ImGui_ImplRoblox.NewFrame()
@@ -195,7 +195,7 @@ end)
``` ```
**Frame ordering.** A Roblox frame runs `PreRender` (`RenderStepped`), `PreAnimation`, `PreSimulation` (`Stepped`), `PostSimulation` (`Heartbeat`). What the scripts changed up to the end of `PostSimulation` of frame N is drawn by the render that follows the next `PreRender` (N+1), together with whatever `PreRender` N+1 changes. So `RenderDrawData` in `PreSimulation` (layer `Position`/`ZIndex`/`Visible` changes) plus `Finish` in `PostSimulation` (the pixels) land in the same render: no frame shows moved layers with old pixels. Actor work requested in `PreSimulation` runs in that frame's parallel phases, and the results are back before `PostSimulation`. **Frame ordering.** A Roblox frame runs `PreRender` (`RenderStepped`), `PreAnimation`, `PreSimulation` (`Stepped`), `PostSimulation` (`Heartbeat`). What the scripts changed up to the end of `PostSimulation` of frame N is drawn by the render that follows the next `PreRender` (N+1), together with whatever `PreRender` N+1 changes. So `RenderDrawData` in `PreSimulation` (layer `Position`/`ZIndex`/`Visible` changes) plus `Finish` in `PostSimulation` (the pixels) land in the same render: no frame shows moved layers with old pixels. Actor work requested in `PreSimulation` runs in that frame's parallel phases, and the results are back before `PostSimulation`.
- The executor only dispatches between `PreAnimation` and its `Finish`. A `RenderDrawData` anywhere else (`RenderStepped`/`PreRender`, after `Finish`, with too little work: fewer than `MinTiles` tiles or `MinPixels` dirty pixels, or with dense primitives: more than `MaxBytesPerPixel` packed payload bytes per dirty pixel, e.g. text-heavy frames, where packing costs more than rasterizing; `0` = no limit) is rasterized and uploaded on the main thread right away, like without the executor. That is always correct, just not parallel. - The executor only dispatches between `PreAnimation` and its `Finish`. A `RenderDrawData` anywhere else (`RenderStepped`/`PreRender`, after `Finish`, with too little work: fewer than `MinTiles` tiles or `MinPixels` dirty pixels, or with dense primitives: more than `MaxBytesPerPixel` packed payload bytes per dirty pixel, `0` = no limit, the default: measured in Studio, packing text-heavy frames costs under 0.1 ms) is rasterized and uploaded on the main thread right away, like without the executor. That is always correct, just not parallel.
- Minimal example: [examples/example_roblox_parallel/main.client.luau](examples/example_roblox_parallel/main.client.luau) (the demo window, 2 Actors; map it instead of `examples/example_roblox` in `default.project.json`). - Minimal example: [examples/example_roblox_parallel/main.client.luau](examples/example_roblox_parallel/main.client.luau) (the demo window, 2 Actors; map it instead of `examples/example_roblox` in `default.project.json`).
- If your frame ends elsewhere, call `ImGui_ImplRoblox.FinishParallel()` yourself. It must run before the next render, and after the parallel phase if you want the workers' results. - If your frame ends elsewhere, call `ImGui_ImplRoblox.FinishParallel()` yourself. It must run before the next render, and after the parallel phase if you want the workers' results.
- `ImGui_ImplRoblox.GetParallelStats()`: `ParallelFlushes`, `SerialFlushes`, `Tiles`, `Fallbacks` (worker results missing at `Finish`), `Late`, `Pack`/`Flush`/`Finish` (main-thread seconds, cumulative). `ImGui_ImplRoblox.GetParallelConfig()` returns the live config table (thresholds can be changed at any time; a new `Actors` count needs another `EnableParallel()`). - `ImGui_ImplRoblox.GetParallelStats()`: `ParallelFlushes`, `SerialFlushes`, `Tiles`, `Fallbacks` (worker results missing at `Finish`), `Late`, `Pack`/`Flush`/`Finish` (main-thread seconds, cumulative). `ImGui_ImplRoblox.GetParallelConfig()` returns the live config table (thresholds can be changed at any time; a new `Actors` count needs another `EnableParallel()`).
@@ -309,6 +309,22 @@ python3 tools/test/run.py --main tools/test/scripts/t_tables.luau --frames 120 -
See [docs/PORTING.md](docs/PORTING.md) for the porting rules. See [docs/PORTING.md](docs/PORTING.md) for the porting rules.
### Extensions (work in progress)
Separate repos, included as submodules under `extensions/` (clone with `--recursive`):
- [imcurveedit-luau](https://github.com/4DBug/imcurveedit-luau): ImCurveEdit (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a curve editor.
- [imgradient-luau](https://github.com/4DBug/imgradient-luau): ImGradient (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a gradient editor.
- [imguicolortextedit-luau](https://github.com/4DBug/imguicolortextedit-luau): [ImGuiColorTextEdit](https://github.com/goossens/ImGuiColorTextEdit) (goossens fork), a syntax-highlighting text editor.
- [imguizmo-luau](https://github.com/4DBug/imguizmo-luau): [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), 3D gizmos with Roblox Camera/CFrame helpers.
- [imgui-memory-editor-luau](https://github.com/4DBug/imgui-memory-editor-luau): [imgui_memory_editor](https://github.com/ocornut/imgui_club) (imgui_club), a hex editor for Roblox `buffer`s, LÖVE `ByteData` and byte tables.
- [implot-luau](https://github.com/4DBug/implot-luau): [ImPlot](https://github.com/epezent/implot), 2D plotting.
- [implot3d-luau](https://github.com/4DBug/implot3d-luau): [ImPlot3D](https://github.com/brenocq/implot3d), 3D plotting.
- [imnodes-luau](https://github.com/4DBug/imnodes-luau): [imnodes](https://github.com/Nelarius/imnodes), a node editor.
- [imsequencer-luau](https://github.com/4DBug/imsequencer-luau): ImSequencer (from [ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo)), a timeline/sequencer.
Usage: `local ImPlot = require(ImPlotModule)(require(ImGuiModule))`.
### Not ported yet ### Not ported yet
Multi-select / box-select, typing-select, the Assets Browser example, the Item Picker and a few smaller items. The full list is in [docs/TODO.txt](docs/TODO.txt). Multi-select / box-select, typing-select, the Assets Browser example, the Item Picker and a few smaller items. The full list is in [docs/TODO.txt](docs/TODO.txt).
+31 -17
View File
@@ -251,9 +251,13 @@ function ImGui_ImplRoblox_SetTextProxy(enabled)
BackendData.ProxyLostId = nil BackendData.ProxyLostId = nil
return return
end end
BackendData.ProxyLostId = BackendData.ProxyActiveId BackendData.ProxyLostId = BackendData.ProxyActiveId -- don't recapture for the same field
local g = ImGui.GetCurrentContext() local g = ImGui.GetCurrentContext()
if g and g.ActiveId ~= 0 and g.ActiveId == BackendData.ProxyActiveId then ImGui.ClearActiveID() end if g and g.ActiveId ~= 0 and g.ActiveId == BackendData.ProxyActiveId then
ImGui.ClearActiveID()
-- the key falls back to the focused window next: the "don't recapture" covers it too
if g.NavWindow then BackendData.ProxyActiveId = g.NavWindow.ID; BackendData.ProxyLostId = g.NavWindow.ID end
end
end) end)
end end
@@ -307,14 +311,18 @@ function ImGui_ImplRoblox_NewFrame()
local proxy = BackendData.Proxy local proxy = BackendData.Proxy
local g = ImGui.GetCurrentContext() local g = ImGui.GetCurrentContext()
local focused_box = proxy and UserInputService:GetFocusedTextBox() local focused_box = proxy and UserInputService:GetFocusedTextBox()
-- key: the active item (InputText), else the focused window (custom widgets setting PlatformImeData.WantTextInput)
local proxy_key = g.ActiveId
if proxy_key == 0 and g.NavWindow then proxy_key = g.NavWindow.ID end
if proxy_key ~= BackendData.ProxyActiveId then BackendData.ProxyLostId = nil end -- (a "don't recapture" never outlives its field)
if not proxy then if not proxy then
elseif io.WantTextInput and g.ActiveId ~= 0 then elseif io.WantTextInput and proxy_key ~= 0 then
if g.ActiveId ~= BackendData.ProxyActiveId or g.ActiveIdIsJustActivated or g.IO.MouseClicked[0] then if proxy_key ~= BackendData.ProxyActiveId or (g.ActiveId ~= 0 and g.ActiveIdIsJustActivated) or g.IO.MouseClicked[0] then
BackendData.ProxyActiveId = g.ActiveId BackendData.ProxyActiveId = proxy_key
BackendData.ProxyLostId = nil BackendData.ProxyLostId = nil
end end
local mouse_up = not (io.MouseDown[0] or io.MouseDown[1] or io.MouseDown[2]) local mouse_up = not (io.MouseDown[0] or io.MouseDown[1] or io.MouseDown[2])
if focused_box ~= proxy and mouse_up and BackendData.ProxyLostId ~= g.ActiveId if focused_box ~= proxy and mouse_up and BackendData.ProxyLostId ~= proxy_key and proxy.Parent
and (focused_box == nil or not focused_box:IsDescendantOf(game)) then and (focused_box == nil or not focused_box:IsDescendantOf(game)) then
-- what it already holds is not new input (else re-typing it would collapse imgui's selection) -- what it already holds is not new input (else re-typing it would collapse imgui's selection)
BackendData.ProxyText = proxy.Text BackendData.ProxyText = proxy.Text
@@ -352,17 +360,15 @@ function ImGui_ImplRoblox_NewFrame()
for _, cp in utf8.codes(text:sub(#prev + 1)) do io:AddInputCharacter(cp) end for _, cp in utf8.codes(text:sub(#prev + 1)) do io:AddInputCharacter(cp) end
end end
end end
if ctrl then io:AddKeyEvent(ImGuiMod_Ctrl, true) end -- re-press only if still physically held: the text can arrive after Ctrl's InputEnded, and re-pressing
-- then left Ctrl stuck down in imgui (typing ignored, shortcuts broken until Ctrl was pressed again)
if ctrl and (UserInputService:IsKeyDown(Enum.KeyCode.LeftControl) or UserInputService:IsKeyDown(Enum.KeyCode.RightControl)) then
io:AddKeyEvent(ImGuiMod_Ctrl, true)
end
used_proxy_text = true used_proxy_text = true
BackendData.ProxyText = nil BackendData.ProxyText = nil
end end
local st = g.InputTextState local sel = g.PlatformImeData.SelectedText or "" -- (last frame's widget selection: ImGui.NewFrame() not run yet)
local sel = ""
if st and st.ID ~= 0 and st.ID == g.ActiveId and st.Stb and st:HasSelection() then
local a, b = math.min(st.Stb.select_start, st.Stb.select_end),
math.max(st.Stb.select_start, st.Stb.select_end)
sel = ImGui._ByteArrayToString(st.TextA.Data, a, b) -- stb positions are 1-based in this port
end
if sel ~= BackendData.ProxyText then if sel ~= BackendData.ProxyText then
proxy.Text = sel proxy.Text = sel
BackendData.ProxyLastRaw = nil BackendData.ProxyLastRaw = nil
@@ -377,9 +383,17 @@ function ImGui_ImplRoblox_NewFrame()
BackendData.DeleteKeySeen = false BackendData.DeleteKeySeen = false
local pending = BackendData.PendingChars local pending = BackendData.PendingChars
if #pending > 0 then if used_proxy_text then
if not used_proxy_text then for _, c in ipairs(pending) do io:AddInputCharacter(c) end end table.clear(pending) -- the proxy delivered the text: the key-code copies would double it
table.clear(pending) BackendData.PendingAge = 0
elseif #pending > 0 then
-- the TextBox's Text can update a frame or two after InputBegan: wait before falling back to key codes
BackendData.PendingAge = (BackendData.PendingAge or 0) + 1
if not ProxyFocused or BackendData.PendingAge > 3 then
for _, c in ipairs(pending) do io:AddInputCharacter(c) end
table.clear(pending)
BackendData.PendingAge = 0
end
end end
-- Tiles Active while over imgui, so Roblox stops passing clicks/wheel to the game (camera zoom etc.) -- Tiles Active while over imgui, so Roblox stops passing clicks/wheel to the game (camera zoom etc.)
+54 -6
View File
@@ -17,15 +17,18 @@ local PrimTexId, PrimVtxBuffer = Render.PrimTexId, Render.PrimVtxBuffer
local M = Render.Parallel local M = Render.Parallel
local writei32, writef64, copy = buffer.writei32, buffer.writef64, buffer.copy local writei32, writef64, copy = buffer.writei32, buffer.writef64, buffer.copy
local RasterJobs = Raster.RasterJobs local RasterJobs = Raster.RasterJobs
local VTX, REC, REC_A, REC_B, REC_C, JOB = Raster.VTX, Raster.REC, Raster.REC_A, Raster.REC_B, Raster.REC_C, Raster.JOB local VTX, REC, REC_A, REC_B, REC_C, REC_D, JOB = Raster.VTX, Raster.REC, Raster.REC_A, Raster.REC_B, Raster.REC_C,
Raster.REC_D, Raster.JOB
assert(VTX == VTX_STRIDE, "raster.lua: vertex layout differs from ImDrawVert") assert(VTX == VTX_STRIDE, "raster.lua: vertex layout differs from ImDrawVert")
-- Sync / SyncDrop / Inline: test hooks (inline "workers"; drop half their results; bypass the executor) -- Sync / SyncDrop / Inline: test hooks (inline "workers"; drop half their results; bypass the executor)
M.Config = { Actors = 4, MinTiles = 4, MinPixels = 16384, MaxBytesPerPixel = 3, Sync = false, SyncDrop = false, M.Config = { Actors = 4, MinTiles = 1, MinPixels = 2048, MaxBytesPerPixel = 0, Sync = false, SyncDrop = false,
Inline = false, Worker = nil } Inline = false, Worker = nil }
M.Stats = { M.Stats = {
ParallelFlushes = 0, SerialFlushes = 0, Tiles = 0, Fallbacks = 0, Late = 0, Pack = 0, Flush = 0, Finish = 0, ParallelFlushes = 0, SerialFlushes = 0, Tiles = 0, Fallbacks = 0, Late = 0, Pack = 0, Flush = 0, Finish = 0,
SendBytes = 0, TexSends = 0, TexBytes = 0, Rects = 0, Recv = 0, RecvBytes = 0, SendBytes = 0, TexSends = 0, TexBytes = 0, Rects = 0, Recv = 0, RecvBytes = 0,
-- why a flush stayed serial: dispatch window closed / Actors not ready / below MinTiles or MinPixels / over MaxBytesPerPixel
SerialClosed = 0, SerialNotReady = 0, SerialSmall = 0, SerialBytes = 0,
} }
local Stats = M.Stats local Stats = M.Stats
@@ -160,9 +163,10 @@ function M.Tile(img, list, count: number, x0: number, y0: number, tox: number, t
local vb = PrimVtxBuffer[p] local vb = PrimVtxBuffer[p]
copy(P, pn + REC_A, vb, PrimA[p], VTX) copy(P, pn + REC_A, vb, PrimA[p], VTX)
copy(P, pn + REC_C, vb, PrimC[p], VTX) copy(P, pn + REC_C, vb, PrimC[p], VTX)
if not d then if not d or gk == 3 then
copy(P, pn + REC_B, vb, PrimB[p], VTX) copy(P, pn + REC_B, vb, PrimB[p], VTX)
end end
if gk == 3 then copy(P, pn + REC_D, vb, d, VTX) end
pn += REC pn += REC
end end
writei32(T, to, poff[p]) writei32(T, to, poff[p])
@@ -232,6 +236,21 @@ function M.Finish()
Stats.Finish += os.clock() - t0 Stats.Finish += os.clock() - t0
end end
-- A whole texture for an Actor without a copy (new id: grow/repack): only the rows above FillRow, the Actor fills the
-- rest with Fill (a new atlas is mostly empty). Built once per version, shared by every Actor's SendMessage.
local function fullCopy(rec, v: number): buffer
if rec.HeadV ~= v then
local src, len = rec.Buffer, (rec.FillRow or rec.Height) * rec.Width * 4
local head = src
if len < buffer.len(src) then
head = buffer.create(len)
copy(head, 0, src, 0, len)
end
rec.Head, rec.HeadV = head, v
end
return rec.Head
end
function M.Flush() function M.Flush()
local n = jobs.N local n = jobs.N
if n == 0 then if n == 0 then
@@ -249,6 +268,11 @@ function M.Flush()
bytes += Pn[a] + Tn[a] bytes += Pn[a] + Tn[a]
end end
par = bytes <= cfg.MaxBytesPerPixel * jobs.Px par = bytes <= cfg.MaxBytesPerPixel * jobs.Px
if not par then Stats.SerialBytes += 1 end
elseif not par then
if not open then Stats.SerialClosed += 1
elseif not (cfg.Sync or ready) then Stats.SerialNotReady += 1
else Stats.SerialSmall += 1 end
end end
batch_no += 1 batch_no += 1
local b = jobs local b = jobs
@@ -272,14 +296,38 @@ function M.Flush()
local tex, s = NO_TEX, sent[a] local tex, s = NO_TEX, sent[a]
for rec, id in used[a] do for rec, id in used[a] do
local v = rec.V or 0 local v = rec.V or 0
if s[rec] ~= v then local had = s[rec]
if had ~= v then
if tex == NO_TEX then if tex == NO_TEX then
tex = {} tex = {}
end end
s[rec] = v s[rec] = v
tex[#tex + 1] = { id, rec.Buffer, rec.Width, rec.Height } -- the Actor has version `had`: send only the rows changed since then when the log covers them
local y0, y1, log = math.huge, -1, rec.Log
if had and log then
for k = had + 1, v do
local e = log[k]
if not e then y0 = nil; break end
if e[2] > e[1] then
if e[1] < y0 then y0 = e[1] end
if e[2] > y1 then y1 = e[2] end
end
end
else
y0 = nil
end
if y0 == nil then
local buf = fullCopy(rec, v)
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 }
Stats.TexBytes += buffer.len(patch)
end
Stats.TexSends += 1 Stats.TexSends += 1
Stats.TexBytes += buffer.len(rec.Buffer)
end end
end end
Stats.SendBytes += Pn[a] + tl Stats.SendBytes += Pn[a] + tl
+342 -18
View File
@@ -9,11 +9,11 @@ local readi32 = buffer.readi32
local M = { local M = {
TILE = 128, TILE = 128,
-- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs. -- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs.
-- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2), tex id (-1: none), clip x0 y0 x1 y1, -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad), tex id (-1: none),
-- bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64, col u32): a at REC_A, -- clip x0 y0 x1 y1, bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64,
-- c at REC_C, b at REC_B. -- col u32): a at REC_A, c at REC_C, b at REC_B, d at REC_D.
-- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32). -- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32).
VTX = 36, REC = 148, REC_A = 40, REC_C = 76, REC_B = 112, JOB = 32, VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32,
} }
local TILE = M.TILE local TILE = M.TILE
@@ -40,6 +40,31 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean
end end
local RectColumns = table.create(256, 0) local RectColumns = table.create(256, 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
-- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece 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
end
end
-- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync. -- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync.
@native @native
local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number) local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number)
@@ -75,13 +100,44 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
b: number, a: number) b: number, a: number)
if a <= 0 then return end if a <= 0 then return end
local w4 = (x1 - x0 - 1) * 4 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
end
if a >= 255 then if a >= 255 then
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local first = (y0 * TargetWidth + x0) * 4 local first = (y0 * TargetWidth + x0) * 4
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end 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 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
return return
end 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 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 sa = a / 255
local ns = 1 - sa local ns = 1 - sa
@@ -146,11 +202,12 @@ 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 r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
end end
if a <= 0 then return end if a <= 0 then return end
if a >= 255 or px1 - px0 < 32 then 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) FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a)
return return
end end
-- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result -- 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 len = (px1 - px0) * 4
local prev_o = 0 local prev_o = 0
for y = py0, py1 - 1 do for y = py0, py1 - 1 do
@@ -165,11 +222,14 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
return return
end end
Shrink(px0, py0, px1, py1)
local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0) local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0)
local tw: number, th: number, tbuf: buffer, dbuf: buffer = t.Width, t.Height, t.Buffer, TargetBuffer local tw: number, th: number, tbuf: buffer, dbuf: buffer = t.Width, t.Height, t.Buffer, TargetBuffer
local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255 local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255
local ncol = px1 - px0 local ncol = px1 - px0
local cols = RectColumns 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
for c = 1, ncol do for c = 1, ncol do
local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) 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 if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
@@ -182,17 +242,47 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
local o = (y * TargetWidth + px0) * 4 local o = (y * TargetWidth + px0) * 4
for c = 1, ncol do for c = 1, ncol do
local tv = readu32(tbuf, trow4 + cols[c]) local tv = readu32(tbuf, trow4 + cols[c])
if tv >= 16777216 then if tv < 16777216 then
local sa = rshift(tv, 24) * a255 o += 4
local sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, continue
band(rshift(tv, 16), 255) * b255 end
if sa >= 255 then if ident and tv >= 4278190080 then -- white opaque vertex colour: an opaque texel is the result
writeu32(dbuf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + 4278190080) writeu32(dbuf, o, tv)
o += 4
continue
end
-- BlendPixel inlined (same math)
if tv ~= last_tv then
last_tv = tv
sa = rshift(tv, 24) * a255
sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255
s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536
fa = sa / 255
fn = 1 - fa
fk = (1 - fa) / 255
end
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
elseif sa > 0 then
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216)
else else
BlendPixel(dbuf, o, sr, sg, sb, sa) 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)
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)
end
end end
end end
o = o + 4 o += 4
end end
end end
end end
@@ -214,6 +304,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1) local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1)
local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1) local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1)
if minx > maxx or miny > maxy then return end if minx > maxx or miny > maxy then return end
Shrink(minx, miny, maxx + 1, maxy + 1)
local A0, B0 = y1 - y2, x2 - x1 local A0, B0 = y1 - y2, x2 - x1
local C0 = -(A0 * x1 + B0 * y1) local C0 = -(A0 * x1 + B0 * y1)
@@ -253,6 +344,64 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
f_c1 = f_ns / 255 f_c1 = f_ns / 255
f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa 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 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 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
-- pixel blended once, so the order does not matter): no empty-row passes
local m0, m1, m2 = B0 ~= 0 and -1 / B0 or 0, B1 ~= 0 and -1 / B1 or 0, B2 ~= 0 and -1 / B2 or 0
local stride = TargetWidth * 4
for x = minx, maxx do
local px = x + 0.5
local yt, yb = miny, maxy
local f0, f1, f2 = A0 * px + C0, A1 * px + C1, A2 * px + C2
if B0 > 0 then yt = max(yt, floor(f0 * m0 - 0.500001)) elseif B0 < 0 then yb = min(yb, ceil(f0 * m0 - 0.499999)) end
if B1 > 0 then yt = max(yt, floor(f1 * m1 - 0.500001)) elseif B1 < 0 then yb = min(yb, ceil(f1 * m1 - 0.499999)) end
if B2 > 0 then yt = max(yt, floor(f2 * m2 - 0.500001)) elseif B2 < 0 then yb = min(yb, ceil(f2 * m2 - 0.499999)) end
while yt <= yb do
local py = yt + 0.5
local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2)
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
yt += 1
end
while yb > yt do
local py = yb + 0.5
local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2)
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
yb -= 1
end
if yt > yb then continue end
local o = (yt * TargetWidth + x) * 4
if flat then
for _ = yt, yb do
BlendPixel(dbuf, o, ra, ga, ba, aa)
o += stride
end
continue
end
for y = yt, yb do
local py = y + 0.5
local w0, w1, w2 = (A0 * px + (B0 * py + C0)) * inv, (A1 * px + (B1 * py + C1)) * inv,
(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)
end
o += stride
end
end
return
end
for y = miny, maxy do for y = miny, maxy do
local py = y + 0.5 local py = y + 0.5
@@ -324,6 +473,50 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end end
continue continue
end end
if cconst then
-- constant vertex colour, varying uv (AA line textures): texel read as u32, blend cached per texel value
for x = xl, xr do
local px = x + 0.5
local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv
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 tv = readu32(tbuf, (ty * tw + tx) * 4)
if tv ~= last_tv then
last_tv = tv
sa = rshift(tv, 24) * a255
sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255
s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536
fa = sa / 255
fn = 1 - fa
fk = (1 - fa) / 255
end
-- BlendPixel inlined (same math)
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
elseif sa > 0 then
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, 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)
else
local k = rshift(d, 24) * fk
local oa = fa + k
local inv2 = 1 / oa
writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5)
+ floor((sg * fa + dg * k) * inv2 + 0.5) * 256
+ floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
o += 4
end
continue
end
for x = xl, xr do for x = xl, xr do
local px = x + 0.5 local px = x + 0.5
local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv
@@ -343,6 +536,131 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end end
end end
-- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as
-- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad.
@native
local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, vd: number, t,
cx0: number, cy0: number, cx1: number, cy1: number, ox: number, oy: number)
local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy
local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy
local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy
local x3, y3 = readf64(vbuf, vd) - ox, readf64(vbuf, vd + 8) - oy
local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)
local area2 = (x2 - x0) * (y3 - y0) - (y2 - y0) * (x3 - x0)
if area == 0 or area2 == 0 or (area < 0) ~= (area2 < 0) then -- degenerate or not convex: the two triangles
DrawTriangle(dbuf, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy)
DrawTriangle(dbuf, vbuf, va, vc, vd, t, cx0, cy0, cx1, cy1, ox, oy)
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
if area < 0 then
px_, py_, qx_, qy_ = x3, y3, x1, y1
area = -area
end
-- order a -> p -> c -> q
local A0, B0 = y0 - py_, px_ - x0
local C0 = -(A0 * x0 + B0 * y0)
local A1, B1 = py_ - y2, x2 - px_
local C1 = -(A1 * px_ + B1 * py_)
local A2, B2 = y2 - qy_, qx_ - x2
local C2 = -(A2 * x2 + B2 * y2)
local A3, B3 = qy_ - y0, x0 - qx_
local C3 = -(A3 * qx_ + B3 * qy_)
local tl0 = A0 > 0 or (A0 == 0 and B0 > 0)
local tl1 = A1 > 0 or (A1 == 0 and B1 > 0)
local tl2 = A2 > 0 or (A2 == 0 and B2 > 0)
local tl3 = A3 > 0 or (A3 == 0 and B3 > 0)
local n0, n1, n2, n3 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0,
A3 ~= 0 and -1 / A3 or 0
-- weight of c in triangle a b c: edge a -> b over its area (same sign whichever side b is on)
local WA, WB = y0 - y1, x1 - x0
local WC = -(WA * x0 + WB * y0)
local winv = 1 / ((x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0))
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
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
local py = y + 0.5
local xl, xr = minx, maxx
local e0, e1, e2, e3 = B0 * py + C0, B1 * py + C1, B2 * py + C2, B3 * py + C3
if A0 > 0 then xl = max(xl, floor(e0 * n0 - 0.500001)) elseif A0 < 0 then xr = min(xr, ceil(e0 * n0 - 0.499999)) end
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
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
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2))
and (w3 > 0 or (w3 == 0 and tl3)) then
break
end
xl += 1
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
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2))
and (w3 > 0 or (w3 == 0 and tl3)) then
break
end
xr -= 1
end
if xl > xr then continue end
local o = (y * TargetWidth + xl) * 4
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)
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)
if tv ~= last_tv then
last_tv = tv
sa = rshift(tv, 24) * a255
sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255
s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536
fa = sa / 255
fn = 1 - fa
fk = (1 - fa) / 255
end
-- BlendPixel inlined (same math)
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
elseif sa > 0 then
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, 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)
else
local k = rshift(d, 24) * fk
local oa = fa + k
local inv2 = 1 / oa
writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5)
+ floor((sg * fa + dg * k) * inv2 + 0.5) * 256
+ floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
o += 4
end
end
end
-- Linear gradient quad, constant uv. kind 1: along y (ca top, cb bottom), 2: along x. Same pixels as the triangles. -- Linear gradient quad, constant uv. kind 1: along y (ca top, cb bottom), 2: along x. Same pixels as the triangles.
@native @native
local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, ca: number, local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, ca: number,
@@ -350,6 +668,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1
local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0)
local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1)
if px0 >= px1 or py0 >= py1 then return end if px0 >= px1 or py0 >= py1 then return end
Shrink(px0, py0, px1, py1)
local ra, ga, ba, aa = UnpackColor(ca) local ra, ga, ba, aa = UnpackColor(ca)
local rb, gb, bb, ab = UnpackColor(cb) local rb, gb, bb, ab = UnpackColor(cb)
if t then if t then
@@ -391,11 +710,13 @@ end
function M.SetTarget(buf: buffer, width: number) function M.SetTarget(buf: buffer, width: number)
TargetBuffer, TargetWidth = buf, width TargetBuffer, TargetWidth = buf, width
UX1 = UX0
end end
@native @native
function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number)
local rw = rx1 - rx0 local rw = rx1 - rx0
UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0
if rw == TargetWidth then if rw == TargetWidth then
buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4)
else else
@@ -410,13 +731,16 @@ function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: nu
end end
end end
-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2 -- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd)
@native @native
local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, tox: number, toy: number, local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: number, tox: number,
cx0: number, cy0: number, cx1: number, cy1: number) toy: number, cx0: number, cy0: number, cx1: number, cy1: number)
if kind == 0 then if kind == 0 then
DrawTriangle(TargetBuffer, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, tox, toy) DrawTriangle(TargetBuffer, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, tox, toy)
return return
elseif kind == 4 then
DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, t, cx0, cy0, cx1, cy1, tox, toy)
return
end end
local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox,
readf64(vbuf, vc + 8) - toy readf64(vbuf, vc + 8) - toy
@@ -435,7 +759,7 @@ local Scratch = buffer.create(TILE * TILE * 4)
@native @native
function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect
local REC_A, REC_B, REC_C = M.REC_A, M.REC_B, M.REC_C 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) M.SetTarget(Scratch, TILE)
local out, no = {}, 0 local out, no = {}, 0
local o = 0 local o = 0
@@ -459,7 +783,7 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
end end
local tid, t = readi32(P, q + 4), nil local tid, t = readi32(P, q + 4), nil
if tid >= 0 then t = textures[tid] end if tid >= 0 then t = textures[tid] end
DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, tox, toy, cx0, cy0, cx1, cy1) 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 end
local rw, rh = rx1 - rx0, ry1 - ry0 local rw, rh = rx1 - rx0, ry1 - ry0
local sub = buffer.create(rw * rh * 4) local sub = buffer.create(rw * rh * 4)
+30 -8
View File
@@ -72,10 +72,9 @@ local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: n
local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy
local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24) local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24)
local c = readu32(vbuf, v + 32) local c = readu32(vbuf, v + 32)
h1 = (h1 * 48271 + x * 4096 + y) % P1 -- 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 + uv * 4096 + c) % P1 h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1
h2 = (h2 * 16807 + y * 4093 + x) % P2 h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2
h2 = (h2 * 16807 + uv * 65521 + c * 3) % P2
return h1, h2 return h1, h2
end end
@@ -122,6 +121,10 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy)
h1 = (h1 * 48271 + gk) % P1 h1 = (h1 * 48271 + gk) % P1
h2 = (h2 * 16807 + gk * 3) % P2 h2 = (h2 * 16807 + gk * 3) % P2
end 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 else
h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) 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, PrimB[p], vax, vay)
@@ -362,7 +365,7 @@ local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1)
end end
local kind, gk = 0, PrimGradient[p] local kind, gk = 0, PrimGradient[p]
if PrimD[p] then kind = gk and gk + 1 or 1 end if PrimD[p] then kind = gk and gk + 1 or 1 end
DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], tox, toy, cx0, cy0, cx1, cy1) DrawPrim(kind, PrimTexture[p], PrimVtxBuffer[p], PrimA[p], PrimB[p], PrimC[p], PrimD[p] or 0, tox, toy, cx0, cy0, cx1, cy1)
end end
end end
@@ -604,7 +607,22 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0,
if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then 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 d = (vo + idx[i + 5] - 1) * VTX_STRIDE
local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8) local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8)
if pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then 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), local col, colb, colc, cold = readu32(vbuf, va + 32), readu32(vbuf, vb + 32),
readu32(vbuf, vc + 32), readu32(vbuf, d + 32) readu32(vbuf, vc + 32), readu32(vbuf, d + 32)
local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24) local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24)
@@ -748,14 +766,16 @@ function M.RenderDrawData(draw_data)
PB("ImGui RenderDrawData") PB("ImGui RenderDrawData")
BackendData.FrameStartTime = os.clock() BackendData.FrameStartTime = os.clock()
if EditableImages.StageTiming then if EditableImages.StageTiming then
EditableImages.StageFrame = { Compare = 0, Collect = 0, Hash = 0, Raster = 0, Upload = 0, Other = 0, Total = 0, EditableImages.StageFrame = { Compare = 0, Collect = 0, Hash = 0, Raster = 0, Upload = 0, Textures = 0, Flush = 0, Other = 0, Total = 0,
TilesRasterized = 0, PixelsRasterized = 0, Uploads = 0, TilesCreated = 0, TilesFreed = 0 } end TilesRasterized = 0, PixelsRasterized = 0, Uploads = 0, TilesCreated = 0, TilesFreed = 0 } end
BackendData.FrameTiles = 0 BackendData.FrameTiles = 0
-- the first dirty tile of a frame is always redrawn (progress), the rest within the budget -- the first dirty tile of a frame is always redrawn (progress), the rest within the budget
BackendData.RedrawStarted = false BackendData.RedrawStarted = false
BackendData.Stale = nil BackendData.Stale = nil
if EditableImages.StageTiming then EditableImages.BeginStage() end
UpdateTextures(draw_data) UpdateTextures(draw_data)
if EditableImages.StageTiming then EditableImages.EndStage("Textures") end
if not RenderRateAllows(BackendData, draw_data) then if not RenderRateAllows(BackendData, draw_data) then
PE() PE()
return return
@@ -828,13 +848,15 @@ function M.RenderDrawData(draw_data)
BackendData.StaleHeartbeat = BackendData.HeartbeatCount BackendData.StaleHeartbeat = BackendData.HeartbeatCount
end end
if Parallel.Active then if Parallel.Active then
if EditableImages.StageTiming then EditableImages.BeginStage() end
Parallel.Flush() Parallel.Flush()
if EditableImages.StageTiming then EditableImages.EndStage("Flush") end
end end
if EditableImages.StageTiming and EditableImages.StageFrame then if EditableImages.StageTiming and EditableImages.StageFrame then
local f = EditableImages.StageFrame local f = EditableImages.StageFrame
f.Raster -= f.Upload f.Raster -= f.Upload
f.Total = os.clock() - BackendData.FrameStartTime f.Total = os.clock() - BackendData.FrameStartTime
f.Other = f.Total - f.Compare - f.Collect - f.Hash - f.Raster - f.Upload f.Other = f.Total - f.Compare - f.Collect - f.Hash - f.Raster - f.Upload - f.Textures - f.Flush
BackendData.FrameStats = f BackendData.FrameStats = f
end end
PE() PE()
+50 -4
View File
@@ -40,8 +40,19 @@ function M.GetBackendData()
end end
@native @native
local function CopyTexturePixels(tex, dst, x, y, w, h) local function CopyTexturePixels(tex, dst, x, y, w, h, dst_zero)
local bpp, tex_w = tex.BytesPerPixel, tex.Width 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 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
return
end
for row = 0, h - 1 do for row = 0, h - 1 do
local src, src_base = tex:GetPixelsAt(x, y + row) local src, src_base = tex:GetPixelsAt(x, y + row)
local dst_off = ((y + row) * tex_w + x) * 4 local dst_off = ((y + row) * tex_w + x) * 4
@@ -63,8 +74,34 @@ local Records = {}
M.Records = Records M.Records = Records
local function CreateTextureRecord(tex) local function CreateTextureRecord(tex)
local t = { Buffer = buffer.create(tex.Width * tex.Height * 4), Width = tex.Width, Height = tex.Height } local w, h = tex.Width, tex.Height
CopyTexturePixels(tex, t.Buffer, 0, 0, tex.Width, tex.Height) local b = buffer.create(w * h * 4)
-- 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.
local atlas = ImGui.GetCurrentContext() and ImGui.GetIO().Fonts
local cw, ch = w, h
if atlas and atlas.TexData == tex and atlas.Builder then
local u, m = tex.UsedRect, atlas.Builder.MaxRectBounds
cw = math.min(w, math.max(u.x + u.w, m.x))
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)
local n, total = 4, w * h * 4
writeu32(b, 0, 16777215)
while n < total do
local c = math.min(n, total - n)
buffer.copy(b, n, b, 0, c)
n += c
end
end
CopyTexturePixels(tex, b, 0, 0, cw, ch, tex.BytesPerPixel == 4)
else
CopyTexturePixels(tex, b, 0, 0, w, h, true)
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 }
EditableImages.LastTextureId += 1 EditableImages.LastTextureId += 1
Records[EditableImages.LastTextureId] = t Records[EditableImages.LastTextureId] = t
tex.BackendUserData = EditableImages.LastTextureId tex.BackendUserData = EditableImages.LastTextureId
@@ -81,10 +118,19 @@ function M.UpdateTexture(tex)
CreateTextureRecord(tex) CreateTextureRecord(tex)
return return
end end
local y0, y1 = math.huge, -1
for _, r in tex.Updates:iter() do for _, r in tex.Updates:iter() do
CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h) 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
end end
t.V = (t.V or 0) + 1 -- parallel workers hold copies, resent when this changes -- parallel workers hold copies, patched when this changes: Log[V] = changed rows (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 - 16] = nil
tex:SetStatus(ImTextureStatus.OK) tex:SetStatus(ImTextureStatus.OK)
elseif tex.Status == ImTextureStatus.WantDestroy then elseif tex.Status == ImTextureStatus.WantDestroy then
if tex.BackendUserData then if tex.BackendUserData then
+22 -1
View File
@@ -10,7 +10,28 @@ local Textures = {}
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength) Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength)
for _, Texture in TexUpdates do for _, Texture in TexUpdates do
Textures[Texture[1]] = { Buffer = Texture[2], Width = Texture[3], Height = Texture[4] } 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 end
local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures) local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures)
task.synchronize() task.synchronize()
+1 -1
View File
@@ -1 +1 @@
[[46, "imgui.lua"], [22647, "imgui_demo.lua"], [34504, "imgui_draw.lua"], [42828, "imgui_h.lua"], [45827, "roblox/raster.lua"], [46303, "roblox/textures.lua"], [46474, "roblox/layers.lua"], [46811, "roblox/overlays.lua"], [46892, "roblox/render.lua"], [47737, "roblox/parallel.lua"], [48136, "imgui_impl_roblox.lua"], [48623, "imgui_impl_roblox_fonts.lua"], [55026, "imgui_internal.lua"], [58992, "imgui_tables.lua"], [64084, "imgui_widgets.lua"], [76318, "imstb_rectpack.lua"], [76982, "imstb_textedit.lua"], [78524, "imstb_truetype.lua"], [81312, "imstd_minstdio.lua"]] [[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"]]
+905 -175
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -70,6 +70,7 @@ export type ImGuiAPI = {
CalcRoundingFlagsForRectInRect: (...any) -> ...any, CalcRoundingFlagsForRectInRect: (...any) -> ...any,
CalcTextSize: (text: string, text_end: string?, hide_text_after_double_hash: boolean?, wrap_width: number?) -> ImVec2, CalcTextSize: (text: string, text_end: string?, hide_text_after_double_hash: boolean?, wrap_width: number?) -> ImVec2,
CalcTextSizeEx: (...any) -> ...any, CalcTextSizeEx: (...any) -> ...any,
CalcTextSizeXY: (...any) -> ...any,
CalcTypematicRepeatAmount: (...any) -> ...any, CalcTypematicRepeatAmount: (...any) -> ...any,
CalcWindowNextAutoFitSize: (...any) -> ...any, CalcWindowNextAutoFitSize: (...any) -> ...any,
CalcWrapWidthForPos: (...any) -> ...any, CalcWrapWidthForPos: (...any) -> ...any,
+364 -19
View File
@@ -18,11 +18,11 @@ local readi32 = buffer.readi32
local M = { local M = {
TILE = 128, TILE = 128,
-- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs. -- Packed jobs (parallel executor -> worker), per Actor and flush: P = primitive records, T = tile jobs.
-- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2), tex id (-1: none), clip x0 y0 x1 y1, -- P record (REC bytes): kind (0 triangle, 1 rect, 2/3 gradient kind 1/2, 4 line quad), tex id (-1: none),
-- bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64, col u32): a at REC_A, -- clip x0 y0 x1 y1, bounds x0 y0 x1 y1 (screen pixels, i32), then raw vertices (VTX bytes: x y u v f64,
-- c at REC_C, b at REC_B. -- col u32): a at REC_A, c at REC_C, b at REC_B, d at REC_D.
-- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32). -- T job: tox toy (f64), x0 y0 nr count (i32), nr x rect x0 y0 x1 y1 (i32, tile pixels), count x P offset (i32).
VTX = 36, REC = 148, REC_A = 40, REC_C = 76, REC_B = 112, JOB = 32, VTX = 36, REC = 184, REC_A = 40, REC_C = 76, REC_B = 112, REC_D = 148, JOB = 32,
} }
local TILE = M.TILE local TILE = M.TILE
@@ -49,6 +49,31 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean
end end
local RectColumns = table.create(256, 0) local RectColumns = table.create(256, 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
-- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece 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
end
end
-- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync. -- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync.
@native @native
local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number) local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, b: number, a: number)
@@ -84,13 +109,44 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number
b: number, a: number) b: number, a: number)
if a <= 0 then return end if a <= 0 then return end
local w4 = (x1 - x0 - 1) * 4 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
end
if a >= 255 then if a >= 255 then
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
local first = (y0 * TargetWidth + x0) * 4 local first = (y0 * TargetWidth + x0) * 4
for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end 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 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
return return
end 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 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 sa = a / 255
local ns = 1 - sa local ns = 1 - sa
@@ -155,11 +211,12 @@ 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 r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
end end
if a <= 0 then return end if a <= 0 then return end
if a >= 255 or px1 - px0 < 32 then 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) FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a)
return return
end end
-- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result -- 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 len = (px1 - px0) * 4
local prev_o = 0 local prev_o = 0
for y = py0, py1 - 1 do for y = py0, py1 - 1 do
@@ -174,11 +231,14 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
return return
end end
Shrink(px0, py0, px1, py1)
local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0) local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0)
local tw: number, th: number, tbuf: buffer, dbuf: buffer = t.Width, t.Height, t.Buffer, TargetBuffer local tw: number, th: number, tbuf: buffer, dbuf: buffer = t.Width, t.Height, t.Buffer, TargetBuffer
local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255 local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255
local ncol = px1 - px0 local ncol = px1 - px0
local cols = RectColumns 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
for c = 1, ncol do for c = 1, ncol do
local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) 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 if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
@@ -191,17 +251,47 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number
local o = (y * TargetWidth + px0) * 4 local o = (y * TargetWidth + px0) * 4
for c = 1, ncol do for c = 1, ncol do
local tv = readu32(tbuf, trow4 + cols[c]) local tv = readu32(tbuf, trow4 + cols[c])
if tv >= 16777216 then if tv < 16777216 then
local sa = rshift(tv, 24) * a255 o += 4
local sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, continue
band(rshift(tv, 16), 255) * b255 end
if sa >= 255 then if ident and tv >= 4278190080 then -- white opaque vertex colour: an opaque texel is the result
writeu32(dbuf, o, floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536 + 4278190080) writeu32(dbuf, o, tv)
o += 4
continue
end
-- BlendPixel inlined (same math)
if tv ~= last_tv then
last_tv = tv
sa = rshift(tv, 24) * a255
sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255
s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536
fa = sa / 255
fn = 1 - fa
fk = (1 - fa) / 255
end
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
elseif sa > 0 then
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216)
else else
BlendPixel(dbuf, o, sr, sg, sb, sa) 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)
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)
end
end end
end end
o = o + 4 o += 4
end end
end end
end end
@@ -223,6 +313,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1) local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1)
local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1) local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1)
if minx > maxx or miny > maxy then return end if minx > maxx or miny > maxy then return end
Shrink(minx, miny, maxx + 1, maxy + 1)
local A0, B0 = y1 - y2, x2 - x1 local A0, B0 = y1 - y2, x2 - x1
local C0 = -(A0 * x1 + B0 * y1) local C0 = -(A0 * x1 + B0 * y1)
@@ -262,6 +353,64 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
f_c1 = f_ns / 255 f_c1 = f_ns / 255
f_rs, f_gs, f_bs = ra * f_sa, ga * f_sa, ba * f_sa 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 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 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
-- pixel blended once, so the order does not matter): no empty-row passes
local m0, m1, m2 = B0 ~= 0 and -1 / B0 or 0, B1 ~= 0 and -1 / B1 or 0, B2 ~= 0 and -1 / B2 or 0
local stride = TargetWidth * 4
for x = minx, maxx do
local px = x + 0.5
local yt, yb = miny, maxy
local f0, f1, f2 = A0 * px + C0, A1 * px + C1, A2 * px + C2
if B0 > 0 then yt = max(yt, floor(f0 * m0 - 0.500001)) elseif B0 < 0 then yb = min(yb, ceil(f0 * m0 - 0.499999)) end
if B1 > 0 then yt = max(yt, floor(f1 * m1 - 0.500001)) elseif B1 < 0 then yb = min(yb, ceil(f1 * m1 - 0.499999)) end
if B2 > 0 then yt = max(yt, floor(f2 * m2 - 0.500001)) elseif B2 < 0 then yb = min(yb, ceil(f2 * m2 - 0.499999)) end
while yt <= yb do
local py = yt + 0.5
local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2)
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
yt += 1
end
while yb > yt do
local py = yb + 0.5
local w0, w1, w2 = A0 * px + (B0 * py + C0), A1 * px + (B1 * py + C1), A2 * px + (B2 * py + C2)
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2)) then
break
end
yb -= 1
end
if yt > yb then continue end
local o = (yt * TargetWidth + x) * 4
if flat then
for _ = yt, yb do
BlendPixel(dbuf, o, ra, ga, ba, aa)
o += stride
end
continue
end
for y = yt, yb do
local py = y + 0.5
local w0, w1, w2 = (A0 * px + (B0 * py + C0)) * inv, (A1 * px + (B1 * py + C1)) * inv,
(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)
end
o += stride
end
end
return
end
for y = miny, maxy do for y = miny, maxy do
local py = y + 0.5 local py = y + 0.5
@@ -333,6 +482,50 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end end
continue continue
end end
if cconst then
-- constant vertex colour, varying uv (AA line textures): texel read as u32, blend cached per texel value
for x = xl, xr do
local px = x + 0.5
local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv
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 tv = readu32(tbuf, (ty * tw + tx) * 4)
if tv ~= last_tv then
last_tv = tv
sa = rshift(tv, 24) * a255
sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255
s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536
fa = sa / 255
fn = 1 - fa
fk = (1 - fa) / 255
end
-- BlendPixel inlined (same math)
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
elseif sa > 0 then
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, 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)
else
local k = rshift(d, 24) * fk
local oa = fa + k
local inv2 = 1 / oa
writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5)
+ floor((sg * fa + dg * k) * inv2 + 0.5) * 256
+ floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
o += 4
end
continue
end
for x = xl, xr do for x = xl, xr do
local px = x + 0.5 local px = x + 0.5
local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv local w0, w1, w2 = (A0 * px + e0) * inv, (A1 * px + e1) * inv, (A2 * px + e2) * inv
@@ -352,6 +545,131 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number,
end end
end end
-- Textured line quad (triangles a b c + a c d, one colour, uv a = b and c = d: ImPlot PrimLine). Same edge functions as
-- the two DrawTriangle calls (so the same pixels), uv from triangle a b c's barycentrics over the whole quad.
@native
local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number, vc: number, vd: number, t,
cx0: number, cy0: number, cx1: number, cy1: number, ox: number, oy: number)
local x0, y0 = readf64(vbuf, va) - ox, readf64(vbuf, va + 8) - oy
local x1, y1 = readf64(vbuf, vb) - ox, readf64(vbuf, vb + 8) - oy
local x2, y2 = readf64(vbuf, vc) - ox, readf64(vbuf, vc + 8) - oy
local x3, y3 = readf64(vbuf, vd) - ox, readf64(vbuf, vd + 8) - oy
local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)
local area2 = (x2 - x0) * (y3 - y0) - (y2 - y0) * (x3 - x0)
if area == 0 or area2 == 0 or (area < 0) ~= (area2 < 0) then -- degenerate or not convex: the two triangles
DrawTriangle(dbuf, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy)
DrawTriangle(dbuf, vbuf, va, vc, vd, t, cx0, cy0, cx1, cy1, ox, oy)
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
if area < 0 then
px_, py_, qx_, qy_ = x3, y3, x1, y1
area = -area
end
-- order a -> p -> c -> q
local A0, B0 = y0 - py_, px_ - x0
local C0 = -(A0 * x0 + B0 * y0)
local A1, B1 = py_ - y2, x2 - px_
local C1 = -(A1 * px_ + B1 * py_)
local A2, B2 = y2 - qy_, qx_ - x2
local C2 = -(A2 * x2 + B2 * y2)
local A3, B3 = qy_ - y0, x0 - qx_
local C3 = -(A3 * qx_ + B3 * qy_)
local tl0 = A0 > 0 or (A0 == 0 and B0 > 0)
local tl1 = A1 > 0 or (A1 == 0 and B1 > 0)
local tl2 = A2 > 0 or (A2 == 0 and B2 > 0)
local tl3 = A3 > 0 or (A3 == 0 and B3 > 0)
local n0, n1, n2, n3 = A0 ~= 0 and -1 / A0 or 0, A1 ~= 0 and -1 / A1 or 0, A2 ~= 0 and -1 / A2 or 0,
A3 ~= 0 and -1 / A3 or 0
-- weight of c in triangle a b c: edge a -> b over its area (same sign whichever side b is on)
local WA, WB = y0 - y1, x1 - x0
local WC = -(WA * x0 + WB * y0)
local winv = 1 / ((x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0))
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
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
local py = y + 0.5
local xl, xr = minx, maxx
local e0, e1, e2, e3 = B0 * py + C0, B1 * py + C1, B2 * py + C2, B3 * py + C3
if A0 > 0 then xl = max(xl, floor(e0 * n0 - 0.500001)) elseif A0 < 0 then xr = min(xr, ceil(e0 * n0 - 0.499999)) end
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
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
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2))
and (w3 > 0 or (w3 == 0 and tl3)) then
break
end
xl += 1
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
if (w0 > 0 or (w0 == 0 and tl0)) and (w1 > 0 or (w1 == 0 and tl1)) and (w2 > 0 or (w2 == 0 and tl2))
and (w3 > 0 or (w3 == 0 and tl3)) then
break
end
xr -= 1
end
if xl > xr then continue end
local o = (y * TargetWidth + xl) * 4
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)
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)
if tv ~= last_tv then
last_tv = tv
sa = rshift(tv, 24) * a255
sr, sg, sb = band(tv, 255) * r255, band(rshift(tv, 8), 255) * g255, band(rshift(tv, 16), 255) * b255
s_opaque = floor(sr + 0.5) + floor(sg + 0.5) * 256 + floor(sb + 0.5) * 65536
fa = sa / 255
fn = 1 - fa
fk = (1 - fa) / 255
end
-- BlendPixel inlined (same math)
if sa >= 255 then
writeu32(dbuf, o, s_opaque + 4278190080)
elseif sa > 0 then
local d = readu32(dbuf, o)
if d < 16777216 then
writeu32(dbuf, o, 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)
else
local k = rshift(d, 24) * fk
local oa = fa + k
local inv2 = 1 / oa
writeu32(dbuf, o, floor((sr * fa + dr * k) * inv2 + 0.5)
+ floor((sg * fa + dg * k) * inv2 + 0.5) * 256
+ floor((sb * fa + db * k) * inv2 + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216)
end
end
end
o += 4
end
end
end
-- Linear gradient quad, constant uv. kind 1: along y (ca top, cb bottom), 2: along x. Same pixels as the triangles. -- Linear gradient quad, constant uv. kind 1: along y (ca top, cb bottom), 2: along x. Same pixels as the triangles.
@native @native
local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, ca: number, local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1: number, y1: number, ca: number,
@@ -359,6 +677,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1
local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0) local px0, py0 = max(ceil(x0 - 0.5), cx0), max(ceil(y0 - 0.5), cy0)
local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1) local px1, py1 = min(ceil(x1 - 0.5), cx1), min(ceil(y1 - 0.5), cy1)
if px0 >= px1 or py0 >= py1 then return end if px0 >= px1 or py0 >= py1 then return end
Shrink(px0, py0, px1, py1)
local ra, ga, ba, aa = UnpackColor(ca) local ra, ga, ba, aa = UnpackColor(ca)
local rb, gb, bb, ab = UnpackColor(cb) local rb, gb, bb, ab = UnpackColor(cb)
if t then if t then
@@ -400,11 +719,13 @@ end
function M.SetTarget(buf: buffer, width: number) function M.SetTarget(buf: buffer, width: number)
TargetBuffer, TargetWidth = buf, width TargetBuffer, TargetWidth = buf, width
UX1 = UX0
end end
@native @native
function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number)
local rw = rx1 - rx0 local rw = rx1 - rx0
UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0
if rw == TargetWidth then if rw == TargetWidth then
buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4)
else else
@@ -419,13 +740,16 @@ function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: nu
end end
end end
-- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2 -- kind: 0 triangle (va vb vc), 1 rect (TL va, BR vc), 2/3 gradient kind 1/2, 4 line quad (va vb vc vd)
@native @native
local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, tox: number, toy: number, local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, vc: number, vd: number, tox: number,
cx0: number, cy0: number, cx1: number, cy1: number) toy: number, cx0: number, cy0: number, cx1: number, cy1: number)
if kind == 0 then if kind == 0 then
DrawTriangle(TargetBuffer, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, tox, toy) DrawTriangle(TargetBuffer, vbuf, va, vb, vc, t, cx0, cy0, cx1, cy1, tox, toy)
return return
elseif kind == 4 then
DrawLineQuad(TargetBuffer, vbuf, va, vb, vc, vd, t, cx0, cy0, cx1, cy1, tox, toy)
return
end end
local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox, local ax, ay, cx, cy = readf64(vbuf, va) - tox, readf64(vbuf, va + 8) - toy, readf64(vbuf, vc) - tox,
readf64(vbuf, vc + 8) - toy readf64(vbuf, vc + 8) - toy
@@ -444,7 +768,7 @@ local Scratch = buffer.create(TILE * TILE * 4)
@native @native
function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect
local REC_A, REC_B, REC_C = M.REC_A, M.REC_B, M.REC_C 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) M.SetTarget(Scratch, TILE)
local out, no = {}, 0 local out, no = {}, 0
local o = 0 local o = 0
@@ -468,7 +792,7 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer }
end end
local tid, t = readi32(P, q + 4), nil local tid, t = readi32(P, q + 4), nil
if tid >= 0 then t = textures[tid] end if tid >= 0 then t = textures[tid] end
DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, tox, toy, cx0, cy0, cx1, cy1) 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 end
local rw, rh = rx1 - rx0, ry1 - ry0 local rw, rh = rx1 - rx0, ry1 - ry0
local sub = buffer.create(rw * rh * 4) local sub = buffer.create(rw * rh * 4)
@@ -487,7 +811,28 @@ local Textures = {}
Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength) Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength)
for _, Texture in TexUpdates do for _, Texture in TexUpdates do
Textures[Texture[1]] = { Buffer = Texture[2], Width = Texture[3], Height = Texture[4] } 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 end
local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures) local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures)
task.synchronize() task.synchronize()
+1 -1
View File
@@ -1 +1 @@
[[183, "imgui.lua"], [22784, "imgui_demo.lua"], [34641, "imgui_draw.lua"], [42965, "imgui_h.lua"], [45962, "imgui_impl_love.lua"], [46506, "imgui_internal.lua"], [50472, "imgui_tables.lua"], [55564, "imgui_widgets.lua"], [67798, "imstb_rectpack.lua"], [68462, "imstb_textedit.lua"], [70004, "imstb_truetype.lua"], [72792, "imstd_minstdio.lua"]] [[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"]]
+399 -123
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,5 @@
function love.conf(t)
t.window.title = "Dear ImGui - LÖVE extensions example"
t.window.width, t.window.height = 1280, 800
t.window.resizable = true
end
+619
View File
@@ -0,0 +1,619 @@
-- Dear ImGui extensions on LÖVE: python3 tools/bundle.py --target love then love examples/example_love_extensions
local ROOT = love.filesystem.getSource() .. "/../../" -- repo root (build/, fonts/, extensions/)
local f = assert(io.open(ROOT .. "build/imgui_love.lua", "rb"), "run: python3 tools/bundle.py --target love")
local G = assert(loadstring(f:read("*a"), "@imgui_love.lua"))(); f:close()
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
local _
-- Each extension repo ships a LÖVE/LuaJIT build in its love/ folder (regenerate with <repo>/tools/love.sh)
local function LoadExt(repo, name)
return assert(loadfile(ROOT .. "extensions/" .. repo .. "/love/" .. name))()
end
-- catppuccin mocha mauve https://catppuccin.com/palette
local Crust, Mantle, Base = 0x11111b, 0x181825, 0x1e1e2e
local Surface0, Surface1, Surface2 = 0x313244, 0x45475a, 0x585b70
local Overlay0, Overlay2, Text = 0x6c7086, 0x9399b2, 0xcdd6f4
local Mauve, Lavender = 0xcba6f7, 0xb4befe
local Red, Peach, Yellow, Green, Blue, Pink = 0xf38ba8, 0xfab387, 0xf9e2af, 0xa6e3a1, 0x89b4fa, 0xf5c2e7
local function Col32(Value, Alpha)
return G.IM_COL32(bit32.extract(Value, 16, 8), bit32.extract(Value, 8, 8), bit32.extract(Value, 0, 8),
math.floor((Alpha or 1.0) * 255 + 0.5))
end
local function StyleColorsCatppuccinMocha(Style)
local function Hex(Value, Alpha)
return ImVec4(bit32.extract(Value, 16, 8) / 255, bit32.extract(Value, 8, 8) / 255, bit32.extract(Value, 0, 8) / 255, Alpha or 1.0)
end
local Entries = {
{ "Text", Text }, { "TextDisabled", Overlay0 },
{ "WindowBg", Base }, { "ChildBg", Base, 0.0 }, { "PopupBg", Mantle, 0.98 }, { "Border", Surface1 }, { "BorderShadow", Crust, 0.0 },
{ "FrameBg", Surface0 }, { "FrameBgHovered", Surface1 }, { "FrameBgActive", Surface2 },
{ "TitleBg", Mantle }, { "TitleBgActive", Crust }, { "TitleBgCollapsed", Mantle, 0.75 }, { "MenuBarBg", Mantle },
{ "ScrollbarBg", Mantle }, { "ScrollbarGrab", Surface1 }, { "ScrollbarGrabHovered", Surface2 }, { "ScrollbarGrabActive", Overlay0 },
{ "CheckMark", Mauve }, { "CheckboxSelectedBg", Surface0 }, { "SliderGrab", Mauve, 0.8 }, { "SliderGrabActive", Mauve },
{ "Button", Surface0 }, { "ButtonHovered", Surface1 }, { "ButtonActive", Mauve, 0.6 },
{ "Header", Surface0 }, { "HeaderHovered", Surface1 }, { "HeaderActive", Mauve, 0.5 },
{ "Separator", Surface1 }, { "SeparatorHovered", Mauve, 0.7 }, { "SeparatorActive", Mauve },
{ "ResizeGrip", Mauve, 0.2 }, { "ResizeGripHovered", Mauve, 0.6 }, { "ResizeGripActive", Mauve, 0.9 },
{ "InputTextCursor", Text },
{ "Tab", Surface0 }, { "TabHovered", Surface2 }, { "TabSelected", Surface1 }, { "TabSelectedOverline", Mauve },
{ "TabDimmed", Mantle }, { "TabDimmedSelected", Surface0 }, { "TabDimmedSelectedOverline", Overlay0 },
{ "DockingPreview", Mauve, 0.7 }, { "DockingEmptyBg", Crust },
{ "PlotLines", Overlay2 }, { "PlotLinesHovered", Mauve }, { "PlotHistogram", Mauve, 0.8 }, { "PlotHistogramHovered", Lavender },
{ "TableHeaderBg", Surface0 }, { "TableBorderStrong", Surface1 }, { "TableBorderLight", Surface0 }, { "TableRowBg", Base, 0.0 }, { "TableRowBgAlt", Surface0, 0.3 },
{ "TextLink", Mauve }, { "TextSelectedBg", Mauve, 0.35 }, { "TreeLines", Surface2 }, { "DragDropTarget", Mauve, 0.9 },
{ "NavCursor", Lavender }, { "NavWindowingHighlight", Lavender, 0.7 }, { "NavWindowingDimBg", Crust, 0.5 }, { "ModalWindowDimBg", Crust, 0.6 },
}
for _, E in ipairs(Entries) do
Style.Colors[G.ImGuiCol[E[1]]] = Hex(E[2], E[3])
end
end
local Demos = {}
local CurveLabels = { "Translation", "Rotation", "Scale" }
local function NewRampEdit(ImCurveEdit, Min, Max)
local R = {
mPts = {
{ ImVec2(-10, 0), ImVec2(20, 0.6), ImVec2(25, 0.2), ImVec2(70, 0.4), ImVec2(120, 1) },
{ ImVec2(-50, 0.2), ImVec2(33, 0.7), ImVec2(80, 0.2), ImVec2(82, 0.8) },
{ ImVec2(40, 0), ImVec2(60, 0.1), ImVec2(90, 0.82), ImVec2(150, 0.24), ImVec2(200, 0.34), ImVec2(250, 0.12) },
},
mbVisible = { true, true, true }, mMin = Min, mMax = Max,
}
function R:GetCurveCount() return 3 end
function R:IsVisible(c) return self.mbVisible[c] end
function R:GetPointCount(c) return #self.mPts[c] end
function R:GetCurveColor(c) return ({ 0xFF0000FF, 0xFF00FF00, 0xFFFF0000 })[c] end
function R:GetPoints(c) return self.mPts[c] end
function R:GetCurveType() return ImCurveEdit.CurveSmooth end
function R:SortValues(c) table.sort(self.mPts[c], function(a, b) return a.x < b.x end) end
function R:EditPoint(c, p, value)
self.mPts[c][p] = ImVec2(value.x, value.y)
self:SortValues(c)
for i, pt in ipairs(self.mPts[c]) do if pt.x == value.x then return i end end
return p
end
function R:AddPoint(c, value)
if #self.mPts[c] >= 8 then return end
table.insert(self.mPts[c], value)
self:SortValues(c)
end
function R:GetMax() return self.mMax end
function R:GetMin() return self.mMin end
function R:GetBackgroundColor() return 0 end
return R
end
-- ImCurveEdit
do
local D = { Name = "ImCurveEdit" }
local ImCurveEdit, RampEdit, Selected
function D.Init()
ImCurveEdit = LoadExt("imcurveedit-luau", "ImCurveEdit.lua")(G)
RampEdit, Selected = NewRampEdit(ImCurveEdit, ImVec2(-100, 0), ImVec2(300, 1)), {}
end
function D.Draw()
ImGui.SetNextWindowSize(ImVec2(700, 400), G.ImGuiCond.FirstUseEver)
D.Show = ImGui.Begin("ImCurveEdit", D.Show)
for i = 1, 3 do
_, RampEdit.mbVisible[i] = ImGui.Checkbox(CurveLabels[i], RampEdit.mbVisible[i])
ImGui.SameLine()
end
ImGui.Text("selected: %d", #Selected)
local Avail = ImGui.GetContentRegionAvail()
_, Selected = ImCurveEdit.Edit(RampEdit, ImVec2(Avail.x, Avail.y), 137, nil, Selected)
ImGui.End()
end
table.insert(Demos, D)
end
-- ImGradient
do
local D = { Name = "ImGradient" }
local ImGradient, Gradient, Selection = nil, nil, -1
local Size = ImVec2(400, 24)
function D.Init()
ImGradient = LoadExt("imgradient-luau", "ImGradient.lua")(G)
Gradient = { Points = { ImVec4(1, 0.2, 0.2, 0), ImVec4(1, 0.9, 0.2, 0.4), ImVec4(0.2, 0.4, 1, 1) } }
function Gradient:GetPointCount() return #self.Points end
function Gradient:GetPoints() return self.Points end
function Gradient:EditPoint(i, v) self.Points[i] = v; return i end
function Gradient:AddPoint(v) table.insert(self.Points, v) end
function Gradient:Sorted()
local s = table.clone(self.Points)
table.sort(s, function(a, b) return a.w < b.w end)
return s
end
end
function D.Draw()
D.Show = ImGui.Begin("ImGradient", D.Show)
local Pos = ImGui.GetCursorScreenPos()
local Dl, S = ImGui.GetWindowDrawList(), Gradient:Sorted()
local X0 = Pos.x
for i = 0, #S do
local a, b = S[math.max(i, 1)], S[math.min(i + 1, #S)]
local X1 = Pos.x + Size.x * (i < #S and b.w or 1)
local Ca = ImGui.ColorConvertFloat4ToU32(ImVec4(a.x, a.y, a.z, 1))
local Cb = ImGui.ColorConvertFloat4ToU32(ImVec4(b.x, b.y, b.z, 1))
if X1 > X0 then Dl:AddRectFilledMultiColor(ImVec2(X0, Pos.y), ImVec2(X1, Pos.y + Size.y), Ca, Cb, Cb, Ca) end
X0 = X1
end
_, Selection = ImGradient.Edit(Gradient, Size, Selection)
ImGui.Text("points: %d selection: %d", #Gradient.Points, Selection)
local P = Gradient.Points[Selection]
if P then
local Col = ImVec4(P.x, P.y, P.z, 1)
if ImGui.ColorEdit3("color", Col) then Gradient:EditPoint(Selection, ImVec4(Col.x, Col.y, Col.z, P.w)) end
if ImGui.Button("Delete point") and #Gradient.Points > 2 then table.remove(Gradient.Points, Selection); Selection = -1 end
end
ImGui.End()
end
table.insert(Demos, D)
end
-- ImSequencer
do
local D = { Name = "ImSequencer" }
local ImSequencer, ImCurveEdit, RampEdit, MySequence, Options
local TypeNames = { "Camera", "Music", "ScreenEffect", "FadeIn", "Animation" }
local SelectedEntry, FirstFrame, Expanded, CurrentFrame = -1, 0, true, 100
function D.Init()
ImSequencer = LoadExt("imsequencer-luau", "ImSequencer.lua")(G)
ImCurveEdit = LoadExt("imcurveedit-luau", "ImCurveEdit.lua")(G)
RampEdit = NewRampEdit(ImCurveEdit, ImVec2(0, 0), ImVec2(1, 1))
local function Item(t, s, e, x) return { mType = t, mFrameStart = s, mFrameEnd = e, mExpanded = x } end
MySequence = { mFrameMin = -100, mFrameMax = 1000 }
MySequence.myItems = { Item(1, 10, 30, false), Item(2, 20, 30, true), Item(4, 12, 60, false), Item(3, 61, 90, false), Item(5, 90, 99, false) }
function MySequence:GetFrameMin() return self.mFrameMin end
function MySequence:GetFrameMax() return self.mFrameMax end
function MySequence:GetItemCount() return #self.myItems end
function MySequence:GetItemTypeCount() return #TypeNames end
function MySequence:GetItemTypeName(t) return TypeNames[t] end
function MySequence:GetItemLabel(i) return string.format("[%02d] %s", i - 1, TypeNames[self.myItems[i].mType]) end
function MySequence:Get(i)
local it = self.myItems[i]
return it.mFrameStart, it.mFrameEnd, it.mType, 0xFFAA8080
end
function MySequence:Set(i, s, e) local it = self.myItems[i]; it.mFrameStart, it.mFrameEnd = s, e end
function MySequence:Add(t) table.insert(self.myItems, Item(t, 0, 10, false)) end
function MySequence:Del(i) table.remove(self.myItems, i) end
function MySequence:Duplicate(i) table.insert(self.myItems, table.clone(self.myItems[i])) end
function MySequence:GetCustomHeight(i) return self.myItems[i].mExpanded and 300 or 0 end
function MySequence:DoubleClick(i)
if self.myItems[i].mExpanded then self.myItems[i].mExpanded = false; return end
for _, it in ipairs(self.myItems) do it.mExpanded = false end
self.myItems[i].mExpanded = true
end
function MySequence:CustomDraw(i, dl, rc, legendRect, clippingRect, legendClippingRect)
RampEdit.mMax = ImVec2(self.mFrameMax, 1)
RampEdit.mMin = ImVec2(self.mFrameMin, 0)
dl:PushClipRect(legendClippingRect.Min, legendClippingRect.Max, true)
for c = 1, 3 do
local pta = ImVec2(legendRect.Min.x + 30, legendRect.Min.y + (c - 1) * 14)
local ptb = ImVec2(legendRect.Max.x, legendRect.Min.y + c * 14)
dl:AddText(pta, RampEdit.mbVisible[c] and 0xFFFFFFFF or 0x80FFFFFF, CurveLabels[c])
if G.ImRect(pta, ptb):Contains(ImGui.GetMousePos()) and ImGui.IsMouseClicked(0) then
RampEdit.mbVisible[c] = not RampEdit.mbVisible[c]
end
end
dl:PopClipRect()
ImGui.SetCursorScreenPos(rc.Min)
ImCurveEdit.Edit(RampEdit, ImVec2(rc.Max.x - rc.Min.x, rc.Max.y - rc.Min.y), 137 + i, clippingRect)
end
function MySequence:CustomDrawCompact(i, dl, rc, clippingRect)
RampEdit.mMax = ImVec2(self.mFrameMax, 1)
RampEdit.mMin = ImVec2(self.mFrameMin, 0)
dl:PushClipRect(clippingRect.Min, clippingRect.Max, true)
local it = self.myItems[i]
for c = 1, 3 do
for _, pt in ipairs(RampEdit.mPts[c]) do
local p = pt.x
if p >= it.mFrameStart and p <= it.mFrameEnd then
local x = rc.Min.x + (rc.Max.x - rc.Min.x) * (p - self.mFrameMin) / (self.mFrameMax - self.mFrameMin)
dl:AddLine(ImVec2(x, rc.Min.y + 6), ImVec2(x, rc.Max.y - 4), 0xAA000000, 4)
end
end
end
dl:PopClipRect()
end
local S = ImSequencer
Options = bit32.bor(S.SEQUENCER_EDIT_STARTEND, S.SEQUENCER_ADD, S.SEQUENCER_DEL, S.SEQUENCER_COPYPASTE, S.SEQUENCER_CHANGE_FRAME)
end
function D.Draw()
ImGui.SetNextWindowSize(ImVec2(900, 600), G.ImGuiCond.FirstUseEver)
D.Show = ImGui.Begin("ImSequencer", D.Show)
ImGui.PushItemWidth(130)
MySequence.mFrameMin = ImGui.InputInt("Frame Min", MySequence.mFrameMin)
ImGui.SameLine()
CurrentFrame = ImGui.InputInt("Frame ", CurrentFrame)
ImGui.SameLine()
MySequence.mFrameMax = ImGui.InputInt("Frame Max", MySequence.mFrameMax)
ImGui.PopItemWidth()
_, CurrentFrame, Expanded, SelectedEntry, FirstFrame = ImSequencer.Sequencer(MySequence, CurrentFrame, Expanded, SelectedEntry, FirstFrame, Options)
if SelectedEntry ~= -1 then
ImGui.Text("I am a %s, please edit me", TypeNames[MySequence.myItems[SelectedEntry].mType])
end
ImGui.End()
end
table.insert(Demos, D)
end
-- imgui_memory_editor
do
local D = { Name = "Memory Editor" }
local ffi = require("ffi")
local Data, Ptr, MemEdit, MemEdit2, Frame = nil, nil, nil, nil, 0
function D.Init()
local MemoryEditor = LoadExt("imgui-memory-editor-luau", "MemoryEditor.lua")(G)
Data = love.data.newByteData(0x400)
Ptr = ffi.cast("uint8_t*", Data:getFFIPointer())
ffi.cast("float*", Ptr + 0x10)[0] = math.pi
ffi.copy(Ptr + 0x20, "Hello from a LOVE ByteData!")
for i = 0x40, 0x3FF do Ptr[i] = (i * 37) % 256 end
MemEdit = MemoryEditor.new()
MemEdit.OptShowDataPreview = true
MemEdit2 = MemoryEditor.new()
MemEdit2.HighlightFn = function(_, off) return Ptr[off] % 2 == 0 end
end
function D.Draw()
Frame = Frame + 1
ffi.cast("uint32_t*", Ptr)[0] = Frame
MemEdit:DrawWindow("Memory Editor", Data)
local Open, Visible = ImGui.Begin("Memory Editor (DrawContents)", D.Show)
D.Show = Open
if Visible then
ImGui.Text("frame = %d (the u32 at 0x00)", Frame)
MemEdit2:DrawContents(Data, 0x80, 0x1000)
end
ImGui.End()
end
table.insert(Demos, D)
end
-- ImGuizmo (fixed camera, one cube; matrices are column-major float[16] like upstream)
do
local D = { Name = "ImGuizmo" }
local ImGuizmo, OP, MODE
local Operation, Mode
local UseSnap, ShowGrid = false, true
local Snap = { 1, 1, 1 }
local AngleSnap, ScaleSnap = 15, 0.1
local BoundSizing, BoundSizingSnap = false, false
local Bounds = { -0.5, -0.5, -0.5, 0.5, 0.5, 0.5 }
local BoundsSnap = { 0.1, 0.1, 0.1 }
local Identity = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
local Object = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
local View
local function Cross(a, b) return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } end
local function Norm(a) local l = math.sqrt(a[1] ^ 2 + a[2] ^ 2 + a[3] ^ 2); return { a[1] / l, a[2] / l, a[3] / l } end
local function Dot(a, b) return a[1] * b[1] + a[2] * b[2] + a[3] * b[3] end
-- upstream example's LookAt / Perspective
local function LookAt(eye, at, up)
local z = Norm({ eye[1] - at[1], eye[2] - at[2], eye[3] - at[3] })
local x = Norm(Cross(up, z))
local y = Norm(Cross(z, x))
return { x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, x[3], y[3], z[3], 0, -Dot(x, eye), -Dot(y, eye), -Dot(z, eye), 1 }
end
local function Perspective(fovy, aspect, n, fa)
local ymax = n * math.tan(fovy * math.pi / 360)
local xmax = ymax * aspect
local t2, w, h, d = 2 * n, 2 * xmax, 2 * ymax, fa - n
return { t2 / w, 0, 0, 0, 0, t2 / h, 0, 0, 0, 0, (-fa - n) / d, -1, 0, 0, (-t2 * fa) / d, 0 }
end
function D.Init()
ImGuizmo = LoadExt("imguizmo-luau", "ImGuizmo.lua")(G)
OP, MODE = ImGuizmo.OPERATION, ImGuizmo.MODE
Operation, Mode = OP.TRANSLATE, MODE.WORLD
View = LookAt({ 6, 5, 8 }, { 0, 0, 0 }, { 0, 1, 0 })
end
local function EditTransform(Matrix)
local K = G.ImGuiKey
if ImGui.IsKeyPressed(K.T) then Operation = OP.TRANSLATE end
if ImGui.IsKeyPressed(K.E) then Operation = OP.ROTATE end
if ImGui.IsKeyPressed(K.R) then Operation = OP.SCALE end
_, Operation = ImGui.RadioButton("Translate", Operation, OP.TRANSLATE); ImGui.SameLine()
_, Operation = ImGui.RadioButton("Rotate", Operation, OP.ROTATE); ImGui.SameLine()
_, Operation = ImGui.RadioButton("Scale", Operation, OP.SCALE); ImGui.SameLine()
_, Operation = ImGui.RadioButton("Universal", Operation, OP.UNIVERSAL)
local Tr, Rt, Sc = {}, {}, {}
ImGuizmo.DecomposeMatrixToComponents(Matrix, Tr, Rt, Sc)
local Edited = ImGui.DragFloat3("Tr", Tr, 0.1)
Edited = ImGui.DragFloat3("Rt", Rt, 1) or Edited
Edited = ImGui.DragFloat3("Sc", Sc, 0.01) or Edited
if Edited then ImGuizmo.RecomposeMatrixFromComponents(Tr, Rt, Sc, Matrix) end
if Operation ~= OP.SCALE then
_, Mode = ImGui.RadioButton("Local", Mode, MODE.LOCAL); ImGui.SameLine()
_, Mode = ImGui.RadioButton("World", Mode, MODE.WORLD)
end
_, UseSnap = ImGui.Checkbox("Snap", UseSnap); ImGui.SameLine()
if Operation == OP.ROTATE then
AngleSnap = ImGui.DragFloat("Angle Snap", AngleSnap, 1)
elseif Operation == OP.SCALE then
ScaleSnap = ImGui.DragFloat("Scale Snap", ScaleSnap, 0.01)
else
ImGui.DragFloat3("Snap Value", Snap, 0.1)
end
if Operation == OP.SCALE then
_, BoundSizing = ImGui.Checkbox("Bound Sizing", BoundSizing)
if BoundSizing then
ImGui.PushID(3)
_, BoundSizingSnap = ImGui.Checkbox("Bound Snap", BoundSizingSnap); ImGui.SameLine()
ImGui.DragFloat3("Snap", BoundsSnap, 0.01)
ImGui.PopID()
end
end
_, ShowGrid = ImGui.Checkbox("Show Grid", ShowGrid)
local SnapArg
if UseSnap then
if Operation == OP.ROTATE then SnapArg = { AngleSnap, AngleSnap, AngleSnap }
elseif Operation == OP.SCALE then SnapArg = { ScaleSnap, ScaleSnap, ScaleSnap }
else SnapArg = Snap end
end
return SnapArg
end
function D.Draw()
ImGuizmo.BeginFrame()
local W, H = love.graphics.getDimensions()
local Proj = Perspective(45, W / H, 0.1, 100)
ImGuizmo.SetDrawlist(ImGui.GetBackgroundDrawList())
ImGuizmo.SetRect(0, 0, W, H)
D.Show = ImGui.Begin("ImGuizmo", D.Show)
local SnapArg = EditTransform(Object)
ImGui.End()
if ShowGrid then ImGuizmo.DrawGrid(View, Proj, Identity, 10) end
ImGuizmo.DrawCubes(View, Proj, Object, 1)
-- Bound Sizing replaces the scale gizmo (BOUNDS draws only the bounds box)
local UseBounds = BoundSizing and Operation == OP.SCALE
ImGuizmo.Manipulate(View, Proj, UseBounds and OP.BOUNDS or Operation, Mode, Object, nil, SnapArg,
UseBounds and Bounds or nil, UseBounds and BoundSizingSnap and BoundsSnap or nil)
ImGuizmo.ViewManipulate(View, 10, ImVec2(W - 128, 0), ImVec2(128, 128), 0x10101010)
end
table.insert(Demos, D)
end
-- ImNodes (Logic Simulator)
do
local D = { Name = "ImNodes" }
local UI
function D.Init()
local ImNodes = LoadExt("imnodes-luau", "ImNodes.lua")(G)
local LogicSim = LoadExt("imnodes-luau", "LogicSim.lua")(G, ImNodes)
UI = LoadExt("imnodes-luau", "LogicUI.lua")(G, ImNodes, LogicSim)
ImNodes.CreateContext()
ImNodes.PushAttributeFlag(ImNodes.ImNodesAttributeFlags.EnableLinkDetachWithDragClick)
local NodesIO = ImNodes.GetIO()
local KeyCtrl = function() return ImGui.GetIO().KeyCtrl end
NodesIO.LinkDetachWithModifierClick.Modifier = KeyCtrl
NodesIO.MultipleSelectModifier.Modifier = KeyCtrl
local NodesStyle = ImNodes.GetStyle()
NodesStyle.Flags = bit32.bor(NodesStyle.Flags, ImNodes.ImNodesStyleFlags.GridLinesPrimary)
-- catppuccin mocha
local Col, C = ImNodes.ImNodesCol, NodesStyle.Colors
C[Col.NodeBackground] = Col32(Surface0)
C[Col.NodeBackgroundHovered] = Col32(Surface1)
C[Col.NodeBackgroundSelected] = Col32(Surface1)
C[Col.NodeOutline] = Col32(Surface2)
C[Col.TitleBar] = Col32(Mantle)
C[Col.TitleBarHovered] = Col32(Surface1)
C[Col.TitleBarSelected] = Col32(Mauve, 0.6)
C[Col.Link] = Col32(Mauve, 0.8)
C[Col.LinkHovered] = Col32(Lavender)
C[Col.LinkSelected] = Col32(Lavender)
C[Col.Pin] = Col32(Mauve, 0.7)
C[Col.PinHovered] = Col32(Lavender)
C[Col.BoxSelector] = Col32(Mauve, 0.12)
C[Col.BoxSelectorOutline] = Col32(Mauve, 0.6)
C[Col.GridBackground] = Col32(Crust)
C[Col.GridLine] = Col32(Surface0, 0.6)
C[Col.GridLinePrimary] = Col32(Surface1, 0.8)
C[Col.MiniMapBackground] = Col32(Mantle, 0.6)
C[Col.MiniMapBackgroundHovered] = Col32(Mantle, 0.8)
C[Col.MiniMapOutline] = Col32(Surface1, 0.6)
C[Col.MiniMapOutlineHovered] = Col32(Surface2)
C[Col.MiniMapNodeBackground] = Col32(Surface1, 0.6)
C[Col.MiniMapNodeBackgroundHovered] = Col32(Surface2)
C[Col.MiniMapNodeBackgroundSelected] = Col32(Mauve, 0.6)
C[Col.MiniMapNodeOutline] = Col32(Overlay0, 0.6)
C[Col.MiniMapLink] = C[Col.Link]
C[Col.MiniMapLinkSelected] = C[Col.LinkSelected]
C[Col.MiniMapCanvas] = Col32(Text, 0.1)
C[Col.MiniMapCanvasOutline] = Col32(Text, 0.6)
end
function D.Draw() UI.Draw() end
table.insert(Demos, D)
end
-- ImPlot
do
local D = { Name = "ImPlot" }
local ImPlot
function D.Init()
ImPlot = LoadExt("implot-luau", "ImPlot.lua")(G)
LoadExt("implot-luau", "ImPlotDemo.lua")(G, ImPlot)
ImPlot.CreateContext()
end
function D.Draw() ImPlot.ShowDemoWindow() end
table.insert(Demos, D)
end
-- ImPlot3D
do
local D = { Name = "ImPlot3D" }
local ImPlot3D
function D.Init()
ImPlot3D = LoadExt("implot3d-luau", "ImPlot3D.lua")(G)
LoadExt("implot3d-luau", "ImPlot3DDemo.lua")(G, ImPlot3D)
ImPlot3D.CreateContext()
end
function D.Draw() ImPlot3D.ShowDemoWindow() end
table.insert(Demos, D)
end
-- ImGuiColorTextEdit
do
local D = { Name = "ImGuiColorTextEdit" }
local TextEditor, Editor, SavedUndoIndex
local SampleCode = [==[
-- Sample Lua code
local function Greet(name)
return "Hello, " .. name .. "!"
end
for i = 1, 10 do
if i % 2 == 0 then
print(Greet("Player" .. i), 3.14 * i, 0xFF)
end
end
--[[ block
comment ]]
local t = { a = 1, b = "two", [3] = true, nil }
]==]
-- catppuccin mocha, in TextEditor.Color order
local CatppuccinPalette = {
Col32(Text), Col32(Mauve), Col32(Yellow), Col32(Peach), Col32(Green), Col32(Overlay2), Col32(Pink), Col32(Text),
Col32(Blue), Col32(Overlay0), Col32(Base), Col32(Text), Col32(Surface2), Col32(Surface1), Col32(Surface0), Col32(Overlay0),
Col32(Yellow), Col32(Blue), Col32(Mauve), Col32(Red), Col32(Overlay0), Col32(Lavender), Col32(Text, 0.03), Col32(Text, 0.06),
}
function D.Init()
TextEditor = LoadExt("imguicolortextedit-luau", "TextEditor.lua")(G)
Editor = TextEditor.new()
Editor:SetPalette(CatppuccinPalette)
Editor:SetLanguage(TextEditor.Language.Lua())
Editor:SetText(SampleCode)
SavedUndoIndex = Editor:GetUndoIndex()
end
function D.Draw()
ImGui.SetNextWindowSize(ImVec2(800, 600), G.ImGuiCond.FirstUseEver)
D.Show = ImGui.Begin("Text Editor Demo", D.Show, G.ImGuiWindowFlags.MenuBar)
if ImGui.BeginMenuBar() then
if ImGui.BeginMenu("File") then
if ImGui.MenuItem("Save") then SavedUndoIndex = Editor:GetUndoIndex() end -- stub: nowhere to save to
ImGui.EndMenu()
end
if ImGui.BeginMenu("Edit") then
local ReadOnly = Editor:IsReadOnlyEnabled()
if ImGui.MenuItem("Read-only mode", nil, ReadOnly) then Editor:SetReadOnlyEnabled(not ReadOnly) end
ImGui.Separator()
if ImGui.MenuItem("Undo", "Ctrl-Z", nil, Editor:CanUndo()) then Editor:Undo() end
if ImGui.MenuItem("Redo", "Ctrl-Y", nil, Editor:CanRedo()) then Editor:Redo() end
ImGui.Separator()
local HasSelection = Editor:AnyCursorHasSelection()
if ImGui.MenuItem("Copy", "Ctrl-C", nil, HasSelection) then Editor:Copy() end
if ImGui.MenuItem("Cut", "Ctrl-X", nil, not ReadOnly and HasSelection) then Editor:Cut() end
if ImGui.MenuItem("Delete", "Del", nil, not ReadOnly and HasSelection) then Editor:ReplaceTextInAllCursors("") end
if ImGui.MenuItem("Paste", "Ctrl-V", nil, not ReadOnly) then Editor:Paste() end
ImGui.Separator()
if ImGui.MenuItem("Select all", "Ctrl-A") then Editor:SelectAll() end
ImGui.EndMenu()
end
if ImGui.BeginMenu("View") then
if ImGui.MenuItem("Catppuccin palette") then Editor:SetPalette(CatppuccinPalette) end
if ImGui.MenuItem("Dark palette") then Editor:SetPalette(TextEditor.GetDarkPalette()) end
if ImGui.MenuItem("Light palette") then Editor:SetPalette(TextEditor.GetLightPalette()) end
ImGui.EndMenu()
end
ImGui.EndMenuBar()
end
local Pos = Editor:GetMainCursorPosition()
ImGui.Text(string.format("%d/%d | %d lines | %s | %s | %s",
Pos.line + 1, Pos.index + 1, Editor:GetLineCount(),
Editor:IsOverwriteEnabled() and "Ovr" or "Ins",
Editor:GetUndoIndex() ~= SavedUndoIndex and "*" or " ",
Editor:GetLanguageName()))
Editor:Render("TextEditor")
ImGui.End()
end
table.insert(Demos, D)
end
local ShowImGuiDemo = true
local function ShowExtensionsWindow()
ImGui.Begin("Extensions")
_, ShowImGuiDemo = ImGui.Checkbox("Dear ImGui Demo", ShowImGuiDemo)
local Fr = ImGui.GetIO().Framerate
ImGui.SameLine(); ImGui.TextDisabled("%.1f FPS", Fr)
ImGui.Separator()
for _, D in ipairs(Demos) do
local Changed
Changed, D.Show = ImGui.Checkbox(D.Name, D.Show or false)
if Changed and D.Show and not D.Ready then
local Ok, Err = pcall(D.Init)
D.Ready, D.Error = Ok, (not Ok) and tostring(Err) or nil
D.Show = Ok
end
if D.Error then
ImGui.SameLine()
ImGui.TextDisabled("(failed)")
if ImGui.BeginItemTooltip() then
ImGui.TextUnformatted(D.Error)
ImGui.EndTooltip()
end
end
end
ImGui.End()
end
function love.load()
ImGui.CreateContext()
local io = ImGui.GetIO()
io.ConfigFlags = bit32.bor(io.ConfigFlags, G.ImGuiConfigFlags.NavEnableKeyboard, G.ImGuiConfigFlags.DockingEnable)
io.IniFilename = nil
G.ImGui_ImplLove.Init({ root = ROOT })
StyleColorsCatppuccinMocha(ImGui.GetStyle())
io.Fonts:AddFontDefault()
for _, Name in ipairs({ "Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyTiny", "Roboto-Medium" }) do
io.Fonts:AddFontFromFileTTF("fonts/" .. Name .. ".ttf", 13.0)
end
end
function love.update(dt)
G.ImGui_ImplLove.NewFrame()
ImGui.NewFrame()
ImGui.DockSpaceOverViewport(0, nil, G.ImGuiDockNodeFlags.PassthruCentralNode)
if ShowImGuiDemo then ShowImGuiDemo = ImGui.ShowDemoWindow(ShowImGuiDemo) end
ShowExtensionsWindow()
for _, D in ipairs(Demos) do
if D.Show then
-- a throwing demo would skip Render and break every later frame: unwind its stacks and turn it off
local State = G.ImGuiErrorRecoveryState()
ImGui.ErrorRecoveryStoreState(State)
local Ok, Err = pcall(D.Draw)
if not Ok then
ImGui.ErrorRecoveryTryToRecoverState(State)
D.Show, D.Error = false, tostring(Err)
print(D.Name .. " demo error: " .. D.Error)
end
end
end
ImGui.Render()
end
function love.draw()
local c = 0x1e1e2e
love.graphics.clear(bit32.extract(c, 16, 8) / 255, bit32.extract(c, 8, 8) / 255, bit32.extract(c, 0, 8) / 255, 1)
G.ImGui_ImplLove.RenderDrawData(ImGui.GetDrawData())
end
function love.mousemoved(x, y) G.ImGui_ImplLove.MouseMoved(x, y) end
function love.mousepressed(x, y, b) G.ImGui_ImplLove.MousePressed(x, y, b) end
function love.mousereleased(x, y, b) G.ImGui_ImplLove.MouseReleased(x, y, b) end
function love.wheelmoved(x, y) G.ImGui_ImplLove.WheelMoved(x, y) end
function love.keypressed(k) G.ImGui_ImplLove.KeyPressed(k) end
function love.keyreleased(k) G.ImGui_ImplLove.KeyReleased(k) end
function love.textinput(t) G.ImGui_ImplLove.TextInput(t) end
function love.focus(f) G.ImGui_ImplLove.Focus(f) end
@@ -0,0 +1,656 @@
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local ImGuiModule = ReplicatedStorage:WaitForChild("ImGui")
local G = require(ImGuiModule)
local ImGui, ImGui_ImplRoblox = G.ImGui, G.ImGui_ImplRoblox
ImGui.CreateContext()
local IO = ImGui.GetIO()
IO.ConfigFlags = bit32.bor(IO.ConfigFlags, G.ImGuiConfigFlags.NavEnableKeyboard, G.ImGuiConfigFlags.DockingEnable)
-- catppuccin mocha mauve https://catppuccin.com/palette
local Crust, Mantle, Base = 0x11111b, 0x181825, 0x1e1e2e
local Surface0, Surface1, Surface2 = 0x313244, 0x45475a, 0x585b70
local Overlay0, Overlay2, Text = 0x6c7086, 0x9399b2, 0xcdd6f4
local Mauve, Lavender = 0xcba6f7, 0xb4befe
local Red, Peach, Yellow, Green, Blue, Pink = 0xf38ba8, 0xfab387, 0xf9e2af, 0xa6e3a1, 0x89b4fa, 0xf5c2e7
-- IM_COL32 from a 0xRRGGBB hex and 0..1 alpha
local function Col32(Value, Alpha)
return G.IM_COL32(
bit32.extract(Value, 16, 8),
bit32.extract(Value, 8, 8),
bit32.extract(Value, 0, 8),
math.floor((Alpha or 1.0) * 255 + 0.5)
)
end
local function StyleColorsCatppuccinMocha(Style)
local function Hex(Value, Alpha)
return G.ImVec4(
bit32.extract(Value, 16, 8) / 255,
bit32.extract(Value, 8, 8) / 255,
bit32.extract(Value, 0, 8) / 255,
Alpha or 1.0
)
end
local Entries = {
{ "Text", Text },
{ "TextDisabled", Overlay0 },
{ "WindowBg", Base },
{ "ChildBg", Base, 0.0 },
{ "PopupBg", Mantle, 0.98 },
{ "Border", Surface1 },
{ "BorderShadow", Crust, 0.0 },
{ "FrameBg", Surface0 },
{ "FrameBgHovered", Surface1 },
{ "FrameBgActive", Surface2 },
{ "TitleBg", Mantle },
{ "TitleBgActive", Crust },
{ "TitleBgCollapsed", Mantle, 0.75 },
{ "MenuBarBg", Mantle },
{ "ScrollbarBg", Mantle },
{ "ScrollbarGrab", Surface1 },
{ "ScrollbarGrabHovered", Surface2 },
{ "ScrollbarGrabActive", Overlay0 },
{ "CheckMark", Mauve },
{ "CheckboxSelectedBg", Surface0 },
{ "SliderGrab", Mauve, 0.8 },
{ "SliderGrabActive", Mauve },
{ "Button", Surface0 },
{ "ButtonHovered", Surface1 },
{ "ButtonActive", Mauve, 0.6 },
{ "Header", Surface0 },
{ "HeaderHovered", Surface1 },
{ "HeaderActive", Mauve, 0.5 },
{ "Separator", Surface1 },
{ "SeparatorHovered", Mauve, 0.7 },
{ "SeparatorActive", Mauve },
{ "ResizeGrip", Mauve, 0.2 },
{ "ResizeGripHovered", Mauve, 0.6 },
{ "ResizeGripActive", Mauve, 0.9 },
{ "InputTextCursor", Text },
{ "Tab", Surface0 },
{ "TabHovered", Surface2 },
{ "TabSelected", Surface1 },
{ "TabSelectedOverline", Mauve },
{ "TabDimmed", Mantle },
{ "TabDimmedSelected", Surface0 },
{ "TabDimmedSelectedOverline", Overlay0 },
{ "DockingPreview", Mauve, 0.7 },
{ "DockingEmptyBg", Crust },
{ "PlotLines", Overlay2 },
{ "PlotLinesHovered", Mauve },
{ "PlotHistogram", Mauve, 0.8 },
{ "PlotHistogramHovered", Lavender },
{ "TableHeaderBg", Surface0 },
{ "TableBorderStrong", Surface1 },
{ "TableBorderLight", Surface0 },
{ "TableRowBg", Base, 0.0 },
{ "TableRowBgAlt", Surface0, 0.3 },
{ "TextLink", Mauve },
{ "TextSelectedBg", Mauve, 0.35 },
{ "TreeLines", Surface2 },
{ "DragDropTarget", Mauve, 0.9 },
{ "NavCursor", Lavender },
{ "NavWindowingHighlight", Lavender, 0.7 },
{ "NavWindowingDimBg", Crust, 0.5 },
{ "ModalWindowDimBg", Crust, 0.6 },
}
for _, Entry in ipairs(Entries) do
local Name, Color, Alpha = Entry[1], Entry[2], Entry[3]
Style.Colors[G.ImGuiCol[Name]] = Hex(Color, Alpha)
end
end
StyleColorsCatppuccinMocha(ImGui.GetStyle())
IO.Fonts:AddFontDefault()
for _, Name in { "Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyTiny", "Roboto-Medium" } do
IO.Fonts:AddFontFromFileTTF("fonts/" .. Name .. ".ttf", 13.0)
end
ImGui_ImplRoblox.Init()
ImGui_ImplRoblox.SetTextProxy(true) -- OS copy/paste for ImGuiColorTextEdit
local RenderRate = 60 -- UI redraws per second (0 = every frame)
ImGui_ImplRoblox.SetRenderRate(RenderRate)
ImGui_ImplRoblox.EnableParallel({ Actors = 4 })
-- Game FPS and ImGui render FPS, sampled every 0.5 s
local GameFps, RenderFps, Frames, Renders, Since = 0, 0, 0, nil, os.clock()
RunService.RenderStepped:Connect(function()
Frames += 1
local Now = os.clock()
local Dt = Now - Since
if Dt >= 0.5 then
GameFps = Frames / Dt
local R = ImGui_ImplRoblox.GetStats().Renders
RenderFps = (R and Renders) and (R - Renders) / Dt or 0
Frames, Renders, Since = 0, R, Now
end
end)
local function Help(Desc)
ImGui.SameLine()
ImGui.TextDisabled("(?)")
if ImGui.BeginItemTooltip() then
ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0)
ImGui.TextUnformatted(Desc)
ImGui.PopTextWrapPos()
ImGui.EndTooltip()
end
end
local Enabled, Timing = true, false
local function ShowParallelWindow()
local C, S = ImGui_ImplRoblox.GetParallelConfig(), ImGui_ImplRoblox.GetParallelStats()
ImGui.Begin("Parallel")
local Fr = IO.Framerate
ImGui.Text("Game %.1f FPS (%.2f ms)", GameFps, GameFps > 0 and 1000 / GameFps or 0)
Help("Frames Roblox actually renders per second (counted from RenderStepped).")
ImGui.Text("ImGui Logic %.1f FPS (%.2f ms)", Fr, Fr > 0 and 1000 / Fr or 0)
Help("How often ImGui logic runs NewFrame..Render (io.Framerate, 60-frame average). Runs every game frame so input stays responsive.")
ImGui.Text("ImGui Render %.1f FPS", RenderFps)
Help("How often the backend actually redraws the UI (capped by Render rate). Frames in between reuse the last drawn UI.")
local Rate, RateChanged = ImGui.SliderInt("Render rate", RenderRate, 0, 240, RenderRate == 0 and "every frame" or "%d Hz")
Help("Max UI redraws per second (SetRenderRate). 0 = redraw every game frame.")
if RateChanged then
RenderRate = Rate
ImGui_ImplRoblox.SetRenderRate(Rate)
end
ImGui.Separator()
local Changed
Changed, Enabled = ImGui.Checkbox("Enabled", Enabled)
Help("Rasterize dirty tiles on Actors (parallel Luau). Off = everything is rasterized on the main thread.")
if Changed then
if Enabled then
ImGui_ImplRoblox.EnableParallel()
else
ImGui_ImplRoblox.DisableParallel()
end
end
local Actors = C.Actors
Actors, Changed = ImGui.SliderInt("Actors", Actors, 1, 16)
Help("Number of worker Actors. Changing it finishes the pending frame and replaces the Actors. More than your CPU core count won't help.")
if Changed then
C.Actors = Actors
if Enabled then
ImGui_ImplRoblox.EnableParallel()
end
end
C.MinTiles = ImGui.SliderInt("MinTiles", C.MinTiles, 0, 64)
Help("A frame with fewer dirty tiles than this is rasterized on the main thread (dispatch overhead isn't worth it).")
C.MinPixels = ImGui.SliderInt("MinPixels", C.MinPixels, 0, 262144)
Help("A frame with fewer dirty pixels than this is rasterized on the main thread.")
C.MaxBytesPerPixel = ImGui.SliderFloat("MaxBytesPerPixel", C.MaxBytesPerPixel, 0, 16)
Help("If the packed data sent to Actors exceeds this many bytes per dirty pixel (e.g. lots of small text), the frame stays on the main thread, since copying would cost more than it saves. 0 = no limit.")
local B = ImGui_ImplRoblox.GetStats()
ImGui.Separator()
ImGui.Text("Flushes parallel %d serial %d", S.ParallelFlushes, S.SerialFlushes)
Help("Frames whose dirty tiles went to Actors vs. were rasterized on the main thread (below thresholds, or ImGui ran too late in the frame).")
ImGui.Text("Fallbacks %d Late %d", S.Fallbacks, S.Late)
Help("Fallbacks: Actor batches not finished in time, rasterized on the main thread so the frame is never partial. Late: results that arrived after that and were discarded. Both should stay at 0.")
ImGui.Text("Tiles %d EditableImage %.1f MB", B.Tiles, B.EditableImageBytes / 1048576)
Help("Live 128x128 raster tiles and EditableImage memory used by the backend (hard-capped).")
Changed, Timing = ImGui.Checkbox("Stage timing", Timing)
Help("Per-stage main-thread time of the last rendered frame. With parallel on, Raster is only the packing for Actors.")
if Changed then
ImGui_ImplRoblox.SetStageTiming(Timing)
end
if Timing and B.Frame then
for _, K in { "Compare", "Collect", "Hash", "Raster", "Upload", "Other", "Total" } do
ImGui.Text("%-8s %.3f ms", K, (B.Frame[K] or 0) * 1000)
end
end
ImGui.End()
end
-- Extension demos (code from extensions/*/examples/roblox). Each is required/initialized on first enable.
local RS = ReplicatedStorage
local ImVec2 = G.ImVec2
local _
local Demos = {}
-- imgui_memory_editor
do
local D = { Name = "Memory Editor" }
local Data, MemEdit, MemEdit2, Frame = nil, nil, nil, 0
function D.Init()
local MemoryEditor = require(RS:WaitForChild("MemoryEditor"))(G)
Data = buffer.create(0x400)
buffer.writef32(Data, 0x10, math.pi)
buffer.writestring(Data, 0x20, "Hello from a Roblox buffer!")
for i = 0x40, 0x3FF do buffer.writeu8(Data, i, (i * 37) % 256) end
MemEdit = MemoryEditor.new()
MemEdit.OptShowDataPreview = true
MemEdit2 = MemoryEditor.new()
MemEdit2.HighlightFn = function(mem, off) return buffer.readu8(mem, off) % 2 == 0 end
end
function D.Draw()
Frame += 1
buffer.writeu32(Data, 0x00, Frame)
MemEdit:DrawWindow("Memory Editor", Data)
local Open, Visible = ImGui.Begin("Memory Editor (DrawContents)", D.Show)
D.Show = Open
if Visible then
ImGui.Text("frame = %d (the u32 at 0x00)", Frame)
MemEdit2:DrawContents(Data, 0x80, 0x1000)
end
ImGui.End()
end
table.insert(Demos, D)
end
-- ImGuizmo
do
local D = { Name = "ImGuizmo" }
local ImGuizmo, OP, MODE, Roblox, Part
local Operation, Mode
local UseSnap, ShowGrid = false, false
local Snap = { 1, 1, 1 }
local AngleSnap, ScaleSnap = 15, 0.1
local BoundSizing, BoundSizingSnap = false, false
local Bounds = { -0.5, -0.5, -0.5, 0.5, 0.5, 0.5 }
local BoundsSnap = { 0.1, 0.1, 0.1 }
local Identity = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
local Camera = workspace.CurrentCamera
function D.Init()
ImGuizmo = require(RS:WaitForChild("ImGuizmo"))(G)
OP, MODE, Roblox = ImGuizmo.OPERATION, ImGuizmo.MODE, ImGuizmo.Roblox
Operation, Mode = OP.TRANSLATE, MODE.WORLD
Part = workspace:FindFirstChild("GizmoPart")
if not Part then
Part = Instance.new("Part")
Part.Name = "GizmoPart"
Part.Anchored = true
Part.Size = Vector3.new(4, 4, 4)
Part.CFrame = CFrame.new(0, 5, 0)
Part.Parent = workspace
end
end
local function EditTransform(Matrix)
local ImGuiKey = G.ImGuiKey
if ImGui.IsKeyPressed(ImGuiKey.T) then Operation = OP.TRANSLATE end
if ImGui.IsKeyPressed(ImGuiKey.E) then Operation = OP.ROTATE end
if ImGui.IsKeyPressed(ImGuiKey.R) then Operation = OP.SCALE end
_, Operation = ImGui.RadioButton("Translate", Operation, OP.TRANSLATE)
ImGui.SameLine()
_, Operation = ImGui.RadioButton("Rotate", Operation, OP.ROTATE)
ImGui.SameLine()
_, Operation = ImGui.RadioButton("Scale", Operation, OP.SCALE)
ImGui.SameLine()
_, Operation = ImGui.RadioButton("Universal", Operation, OP.UNIVERSAL)
local Tr, Rt, Sc = {}, {}, {}
ImGuizmo.DecomposeMatrixToComponents(Matrix, Tr, Rt, Sc)
local Edited = ImGui.DragFloat3("Tr", Tr, 0.1)
Edited = ImGui.DragFloat3("Rt", Rt, 1) or Edited
Edited = ImGui.DragFloat3("Sc", Sc, 0.01) or Edited
if Edited then ImGuizmo.RecomposeMatrixFromComponents(Tr, Rt, Sc, Matrix) end
if Operation ~= OP.SCALE then
_, Mode = ImGui.RadioButton("Local", Mode, MODE.LOCAL)
ImGui.SameLine()
_, Mode = ImGui.RadioButton("World", Mode, MODE.WORLD)
end
_, UseSnap = ImGui.Checkbox("Snap", UseSnap)
ImGui.SameLine()
if Operation == OP.ROTATE then
AngleSnap = ImGui.DragFloat("Angle Snap", AngleSnap, 1)
elseif Operation == OP.SCALE then
ScaleSnap = ImGui.DragFloat("Scale Snap", ScaleSnap, 0.01)
else
ImGui.DragFloat3("Snap Value", Snap, 0.1)
end
if Operation == OP.SCALE then
_, BoundSizing = ImGui.Checkbox("Bound Sizing", BoundSizing)
end
if Operation == OP.SCALE and BoundSizing then
ImGui.PushID(3)
_, BoundSizingSnap = ImGui.Checkbox("Bound Snap", BoundSizingSnap)
ImGui.SameLine()
ImGui.DragFloat3("Snap", BoundsSnap, 0.01)
ImGui.PopID()
end
_, ShowGrid = ImGui.Checkbox("Show Grid", ShowGrid)
local SnapArg = nil
if UseSnap then
if Operation == OP.ROTATE then
SnapArg = { AngleSnap, AngleSnap, AngleSnap }
elseif Operation == OP.SCALE then
SnapArg = { ScaleSnap, ScaleSnap, ScaleSnap }
else
SnapArg = Snap
end
end
return Edited, SnapArg
end
function D.Draw()
ImGuizmo.BeginFrame()
local Viewport = Camera.ViewportSize
ImGuizmo.SetDrawlist(ImGui.GetForegroundDrawList())
ImGuizmo.SetRect(0, 0, Viewport.X, Viewport.Y)
local View = Roblox.ViewFromCamera(Camera)
local Proj = Roblox.ProjFromCamera(Camera)
-- Part.Size is baked into the basis so SCALE / bounds edit it
local Matrix = Roblox.MatrixFromCFrame(Part.CFrame)
local Size = Part.Size
for I = 1, 3 do
Matrix[I] *= Size.X
Matrix[4 + I] *= Size.Y
Matrix[8 + I] *= Size.Z
end
D.Show = ImGui.Begin("ImGuizmo", D.Show)
local Edited, SnapArg = EditTransform(Matrix)
ImGui.End()
if ShowGrid then ImGuizmo.DrawGrid(View, Proj, Identity, 10) end
-- Bound Sizing replaces the scale gizmo (BOUNDS draws only the bounds box)
local UseBounds = BoundSizing and Operation == OP.SCALE
local Moved = ImGuizmo.Manipulate(View, Proj, UseBounds and OP.BOUNDS or Operation, Mode, Matrix, nil, SnapArg,
UseBounds and Bounds or nil, UseBounds and BoundSizingSnap and BoundsSnap or nil)
if Edited or Moved then
local NewCFrame, NewSize = Roblox.CFrameFromMatrix(Matrix)
Part.CFrame = NewCFrame
Part.Size = NewSize
end
-- ViewManipulate edits View in place; the camera is its inverse
ImGuizmo.ViewManipulate(View, 10, ImVec2(Viewport.X - 128, 0), ImVec2(128, 128), 0x10101010)
if ImGuizmo.IsUsingViewManipulate() then
Camera.CameraType = Enum.CameraType.Scriptable
Camera.CFrame = Roblox.CFrameFromMatrix(View):Inverse()
end
end
table.insert(Demos, D)
end
-- ImNodes (Logic Simulator)
do
local D = { Name = "ImNodes" }
local UI
function D.Init()
local ImNodes = require(RS:WaitForChild("ImNodes"))(G)
local Logic = RS:WaitForChild("Logic")
local LogicSim = require(Logic:WaitForChild("Simulation"))(G, ImNodes)
UI = require(Logic:WaitForChild("UI"))(G, ImNodes, LogicSim)
ImNodes.CreateContext()
ImNodes.PushAttributeFlag(ImNodes.ImNodesAttributeFlags.EnableLinkDetachWithDragClick)
local NodesIO = ImNodes.GetIO()
local KeyCtrl = function()
return ImGui.GetIO().KeyCtrl
end
NodesIO.LinkDetachWithModifierClick.Modifier = KeyCtrl
NodesIO.MultipleSelectModifier.Modifier = KeyCtrl
local NodesStyle = ImNodes.GetStyle()
NodesStyle.Flags = bit32.bor(NodesStyle.Flags, ImNodes.ImNodesStyleFlags.GridLinesPrimary)
-- catppuccin mocha
local Col, C = ImNodes.ImNodesCol, NodesStyle.Colors
C[Col.NodeBackground] = Col32(Surface0)
C[Col.NodeBackgroundHovered] = Col32(Surface1)
C[Col.NodeBackgroundSelected] = Col32(Surface1)
C[Col.NodeOutline] = Col32(Surface2)
C[Col.TitleBar] = Col32(Mantle)
C[Col.TitleBarHovered] = Col32(Surface1)
C[Col.TitleBarSelected] = Col32(Mauve, 0.6)
C[Col.Link] = Col32(Mauve, 0.8)
C[Col.LinkHovered] = Col32(Lavender)
C[Col.LinkSelected] = Col32(Lavender)
C[Col.Pin] = Col32(Mauve, 0.7)
C[Col.PinHovered] = Col32(Lavender)
C[Col.BoxSelector] = Col32(Mauve, 0.12)
C[Col.BoxSelectorOutline] = Col32(Mauve, 0.6)
C[Col.GridBackground] = Col32(Crust)
C[Col.GridLine] = Col32(Surface0, 0.6)
C[Col.GridLinePrimary] = Col32(Surface1, 0.8)
C[Col.MiniMapBackground] = Col32(Mantle, 0.6)
C[Col.MiniMapBackgroundHovered] = Col32(Mantle, 0.8)
C[Col.MiniMapOutline] = Col32(Surface1, 0.6)
C[Col.MiniMapOutlineHovered] = Col32(Surface2)
C[Col.MiniMapNodeBackground] = Col32(Surface1, 0.6)
C[Col.MiniMapNodeBackgroundHovered] = Col32(Surface2)
C[Col.MiniMapNodeBackgroundSelected] = Col32(Mauve, 0.6)
C[Col.MiniMapNodeOutline] = Col32(Overlay0, 0.6)
C[Col.MiniMapLink] = C[Col.Link]
C[Col.MiniMapLinkSelected] = C[Col.LinkSelected]
C[Col.MiniMapCanvas] = Col32(Text, 0.1)
C[Col.MiniMapCanvasOutline] = Col32(Text, 0.6)
end
function D.Draw()
UI.Draw()
end
table.insert(Demos, D)
end
-- ImPlot
do
local D = { Name = "ImPlot" }
local ImPlot
function D.Init()
local Module = RS:WaitForChild("ImPlot")
ImPlot = require(Module)(G)
require(Module:WaitForChild("ImPlotDemo"))(G, ImPlot)
ImPlot.CreateContext()
end
function D.Draw()
ImPlot.ShowDemoWindow()
end
table.insert(Demos, D)
end
-- ImPlot3D
do
local D = { Name = "ImPlot3D" }
local ImPlot3D
function D.Init()
local Module = RS:WaitForChild("ImPlot3D")
ImPlot3D = require(Module)(G)
require(Module:WaitForChild("ImPlot3DDemo"))(G, ImPlot3D)
ImPlot3D.CreateContext()
end
function D.Draw()
ImPlot3D.ShowDemoWindow()
end
table.insert(Demos, D)
end
-- ImGuiColorTextEdit
do
local D = { Name = "ImGuiColorTextEdit" }
local Editor, SavedUndoIndex
local SampleCode = [==[
-- Sample Lua code
local Players = game:GetService("Players")
local function Greet(name: string): string
return "Hello, " .. name .. "!"
end
for i = 1, 10 do
if i % 2 == 0 then
print(Greet("Player" .. i), 3.14 * i, 0xFF)
end
end
--[[ block
comment ]]
local t = { a = 1, b = "two", [3] = true, nil }
]==]
local TextEditor
-- catppuccin mocha, in TextEditor.Color order
local CatppuccinPalette = {
Col32(Text), -- text
Col32(Mauve), -- keyword
Col32(Yellow), -- declaration
Col32(Peach), -- number
Col32(Green), -- string
Col32(Overlay2), -- punctuation
Col32(Pink), -- preprocessor
Col32(Text), -- identifier
Col32(Blue), -- known identifier
Col32(Overlay0), -- comment
Col32(Base), -- background
Col32(Text), -- cursor
Col32(Surface2), -- selection
Col32(Surface1), -- whitespace
Col32(Surface0), -- matchingBracketBackground
Col32(Overlay0), -- matchingBracketActive
Col32(Yellow), -- matchingBracketLevel1
Col32(Blue), -- matchingBracketLevel2
Col32(Mauve), -- matchingBracketLevel3
Col32(Red), -- matchingBracketError
Col32(Overlay0), -- line number
Col32(Lavender), -- current line number
Col32(Text, 0.03), -- current line highlight
Col32(Text, 0.06), -- current line highlight border
}
function D.Init()
TextEditor = require(RS:WaitForChild("TextEditor"))(G)
Editor = TextEditor.new()
Editor:SetPalette(CatppuccinPalette)
Editor:SetLanguage(TextEditor.Language.Lua())
Editor:SetText(SampleCode)
SavedUndoIndex = Editor:GetUndoIndex()
end
function D.Draw()
ImGui.SetNextWindowSize(ImVec2(800, 600), G.ImGuiCond.FirstUseEver)
D.Show = ImGui.Begin("Text Editor Demo", D.Show, G.ImGuiWindowFlags.MenuBar)
if ImGui.BeginMenuBar() then
if ImGui.BeginMenu("File") then
if ImGui.MenuItem("Save") then
SavedUndoIndex = Editor:GetUndoIndex() -- stub: nowhere to save to
end
ImGui.EndMenu()
end
if ImGui.BeginMenu("Edit") then
local ReadOnly = Editor:IsReadOnlyEnabled()
if ImGui.MenuItem("Read-only mode", nil, ReadOnly) then
Editor:SetReadOnlyEnabled(not ReadOnly)
end
ImGui.Separator()
if ImGui.MenuItem("Undo", "Ctrl-Z", nil, Editor:CanUndo()) then Editor:Undo() end
if ImGui.MenuItem("Redo", "Ctrl-Y", nil, Editor:CanRedo()) then Editor:Redo() end
ImGui.Separator()
local HasSelection = Editor:AnyCursorHasSelection()
if ImGui.MenuItem("Copy", "Ctrl-C", nil, HasSelection) then Editor:Copy() end
if ImGui.MenuItem("Cut", "Ctrl-X", nil, not ReadOnly and HasSelection) then Editor:Cut() end
if ImGui.MenuItem("Delete", "Del", nil, not ReadOnly and HasSelection) then
Editor:ReplaceTextInAllCursors("")
end
if ImGui.MenuItem("Paste", "Ctrl-V", nil, not ReadOnly) then Editor:Paste() end
ImGui.Separator()
if ImGui.MenuItem("Select all", "Ctrl-A") then Editor:SelectAll() end
ImGui.EndMenu()
end
if ImGui.BeginMenu("View") then
if ImGui.MenuItem("Catppuccin palette") then Editor:SetPalette(CatppuccinPalette) end
if ImGui.MenuItem("Dark palette") then Editor:SetPalette(TextEditor.GetDarkPalette()) end
if ImGui.MenuItem("Light palette") then Editor:SetPalette(TextEditor.GetLightPalette()) end
ImGui.EndMenu()
end
ImGui.EndMenuBar()
end
local Pos = Editor:GetMainCursorPosition()
ImGui.Text(string.format("%d/%d | %d lines | %s | %s | %s",
Pos.line + 1, Pos.index + 1, Editor:GetLineCount(),
Editor:IsOverwriteEnabled() and "Ovr" or "Ins",
Editor:GetUndoIndex() ~= SavedUndoIndex and "*" or " ",
Editor:GetLanguageName()))
Editor:Render("TextEditor")
ImGui.End()
end
table.insert(Demos, D)
end
local ShowImGuiDemo = true
local function ShowExtensionsWindow()
ImGui.Begin("Extensions")
_, ShowImGuiDemo = ImGui.Checkbox("Dear ImGui Demo", ShowImGuiDemo)
ImGui.Separator()
for _, D in Demos do
local Changed
Changed, D.Show = ImGui.Checkbox(D.Name, D.Show or false)
if Changed and D.Show and not D.Ready then
local Ok, Err = pcall(D.Init)
D.Ready, D.Error = Ok, not Ok and tostring(Err) or nil
D.Show = Ok
end
if D.Error then
ImGui.SameLine()
ImGui.TextDisabled("(failed)")
if ImGui.BeginItemTooltip() then
ImGui.TextUnformatted(D.Error)
ImGui.EndTooltip()
end
end
end
ImGui.End()
end
-- PreSimulation, not RenderStepped: the parallel Finish runs in PostSimulation
RunService.PreSimulation:Connect(function()
ImGui_ImplRoblox.NewFrame()
ImGui.NewFrame()
ImGui.DockSpaceOverViewport(0, nil, G.ImGuiDockNodeFlags.PassthruCentralNode)
if ShowImGuiDemo then
ImGui.ShowDemoWindow()
end
ShowParallelWindow()
ShowExtensionsWindow()
for _, D in Demos do
if D.Show then
-- a throwing demo would skip Render and break every later frame: unwind its Begin/Push stacks and turn it off
local State = G.ImGuiErrorRecoveryState()
ImGui.ErrorRecoveryStoreState(State)
local Ok, Err = pcall(D.Draw)
if not Ok then
ImGui.ErrorRecoveryTryToRecoverState(State)
D.Show, D.Error = false, tostring(Err)
warn(D.Name .. " demo error: " .. D.Error)
end
end
end
ImGui.Render()
ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
end)
script.Destroying:Connect(function()
ImGui_ImplRoblox.DisableParallel()
ImGui_ImplRoblox.Shutdown()
ImGui.DestroyContext()
end)
+82 -41
View File
@@ -4872,26 +4872,33 @@ local ImGuiResizeBorderDef = {
--- @param thickness float --- @param thickness float
--- @return ImRect --- @return ImRect
--- @nodiscard --- @nodiscard
local function GetResizeBorderRect(window, border_n, perp_padding, thickness) -- [Luau] out: optional ImRect written in place (no allocation)
local rect = window:Rect() local function GetResizeBorderRect(window, border_n, perp_padding, thickness, out)
local x0, y0 = window.Pos.x, window.Pos.y
local x1, y1 = x0 + window.Size.x, y0 + window.Size.y
if thickness == 0.0 then if thickness == 0.0 then
ImVec2_CopyV(rect.Max, rect.Max.x - 1, rect.Max.y - 1) x1, y1 = x1 - 1, y1 - 1
end end
local a, b, c, d
if border_n == ImGuiDir.Left then if border_n == ImGuiDir.Left then
return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding) a, b, c, d = x0 - thickness, y0 + perp_padding, x0 + thickness, y1 - perp_padding
elseif border_n == ImGuiDir.Right then
a, b, c, d = x1 - thickness, y0 + perp_padding, x1 + thickness, y1 - perp_padding
elseif border_n == ImGuiDir.Up then
a, b, c, d = x0 + perp_padding, y0 - thickness, x1 - perp_padding, y0 + thickness
elseif border_n == ImGuiDir.Down then
a, b, c, d = x0 + perp_padding, y1 - thickness, x1 - perp_padding, y1 + thickness
else
IM_ASSERT(false)
a, b, c, d = 0, 0, 0, 0
end end
if border_n == ImGuiDir.Right then if out then
return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding) out.Min.x, out.Min.y, out.Max.x, out.Max.y = a, b, c, d
return out
end end
if border_n == ImGuiDir.Up then return ImRect(a, b, c, d)
return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness)
end
if border_n == ImGuiDir.Down then
return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness)
end
IM_ASSERT(false)
return ImRect()
end end
local UpdateWindowManualResize_rect = ImRect() -- [Luau] scratch grip/border rect: ItemAdd() copies, ButtonBehavior() reads
-- Known size hash -- Known size hash
-- It is ok to call ImHashData on a string with known length but the ### operator won't be supported. -- It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
@@ -10173,10 +10180,12 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c
local corner_pos = def.CornerPosN local corner_pos = def.CornerPosN
local inner_dir = def.InnerDir local inner_dir = def.InnerDir
local corner = ImVec2(window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y) local corner_x, corner_y = window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y
-- Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window -- Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
local resize_rect = ImRect(corner - inner_dir * grip_hover_outer_size, corner + inner_dir * grip_hover_inner_size) local resize_rect = UpdateWindowManualResize_rect -- [Luau] scratch, scalar math
resize_rect.Min.x, resize_rect.Min.y = corner_x - inner_dir.x * grip_hover_outer_size, corner_y - inner_dir.y * grip_hover_outer_size
resize_rect.Max.x, resize_rect.Max.y = corner_x + inner_dir.x * grip_hover_inner_size, corner_y + inner_dir.y * grip_hover_inner_size
if resize_rect.Min.x > resize_rect.Max.x then resize_rect.Min.x, resize_rect.Max.x = resize_rect.Max.x, resize_rect.Min.x end if resize_rect.Min.x > resize_rect.Max.x then resize_rect.Min.x, resize_rect.Max.x = resize_rect.Max.x, resize_rect.Min.x end
if resize_rect.Min.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end if resize_rect.Min.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end
@@ -10249,7 +10258,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c
axis = ImGuiAxis.Y axis = ImGuiAxis.Y
end end
local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding) local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding, UpdateWindowManualResize_rect)
local border_id = window:GetID(border_n + 4) -- == GetWindowResizeBorderID() local border_id = window:GetID(border_n + 4) -- == GetWindowResizeBorderID()
ImGui.ItemAdd(border_rect, border_id, nil, ImGuiItemFlags.NoNav) ImGui.ItemAdd(border_rect, border_id, nil, ImGuiItemFlags.NoNav)
local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus)) local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus))
@@ -10278,7 +10287,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c
-- FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! -- FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
local just_scrolled_manually_while_resizing = (g.WheelingWindow ~= nil and g.WheelingWindowScrolledFrame == g.FrameCount and ImGui.IsWindowChildOf(window, g.WheelingWindow, false, true)) local just_scrolled_manually_while_resizing = (g.WheelingWindow ~= nil and g.WheelingWindowScrolledFrame == g.FrameCount and ImGui.IsWindowChildOf(window, g.WheelingWindow, false, true))
if g.ActiveIdIsJustActivated or just_scrolled_manually_while_resizing then if g.ActiveIdIsJustActivated or just_scrolled_manually_while_resizing then
g.WindowResizeBorderExpectedRect = border_rect g.WindowResizeBorderExpectedRect = ImRect(border_rect.Min, border_rect.Max) -- [Luau] copy: border_rect is scratch
g.WindowResizeRelativeMode = false g.WindowResizeRelativeMode = false
end end
@@ -10486,18 +10495,23 @@ function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin
local pos = RenderTextClippedEx_pos local pos = RenderTextClippedEx_pos
pos.x = pos_min.x; pos.y = pos_min.y pos.x = pos_min.x; pos.y = pos_min.y
local text_size = text_size_if_known or ImGui.CalcTextSize(text, text_display_end, false, 0.0) local text_size_x, text_size_y -- [Luau] scalar text_size
if text_size_if_known then
text_size_x, text_size_y = text_size_if_known.x, text_size_if_known.y
else
text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_display_end, false, 0.0)
end
local clip_min = clip_rect and clip_rect.Min or pos_min local clip_min = clip_rect and clip_rect.Min or pos_min
local clip_max = clip_rect and clip_rect.Max or pos_max local clip_max = clip_rect and clip_rect.Max or pos_max
local need_clipping = (pos.x + text_size.x >= clip_max.x) or (pos.y + text_size.y >= clip_max.y) local need_clipping = (pos.x + text_size_x >= clip_max.x) or (pos.y + text_size_y >= clip_max.y)
if (clip_rect) then -- If we had no explicit clipping rectangle then pos==clip_min if (clip_rect) then -- If we had no explicit clipping rectangle then pos==clip_min
need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y)) need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y))
end end
-- Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. -- Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0.0) then pos.x = math.max(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x) end if (align.x > 0.0) then pos.x = math.max(pos.x, pos.x + (pos_max.x - pos.x - text_size_x) * align.x) end
if (align.y > 0.0) then pos.y = math.max(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y) end if (align.y > 0.0) then pos.y = math.max(pos.y, pos.y + (pos_max.y - pos.y - text_size_y) * align.y) end
-- Render -- Render
if (need_clipping) then if (need_clipping) then
@@ -10816,6 +10830,9 @@ end
--- @param handle_borders_and_resize_grips bool --- @param handle_borders_and_resize_grips bool
--- @param resize_grip_col ImU32[] --- @param resize_grip_col ImU32[]
--- @param resize_grip_draw_size float --- @param resize_grip_draw_size float
-- [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() }
local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_col, resize_grip_draw_size) local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_col, resize_grip_draw_size)
local g = GImGui local g = GImGui
local style = g.Style local style = g.Style
@@ -10856,7 +10873,8 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high
if bit32.band(flags, ImGuiWindowFlags.DockNodeHost) ~= 0 then bg_col = 0 end if bit32.band(flags, ImGuiWindowFlags.DockNodeHost) ~= 0 then bg_col = 0 end
if bit32.band(bg_col, IM_COL32_A_MASK) ~= 0 then if bit32.band(bg_col, IM_COL32_A_MASK) ~= 0 then
local bg_rect = ImRect(window.Pos + ImVec2(0, window.TitleBarHeight), window.Pos + window.Size) local bg_rect = WindowDecoScratch.bg_rect -- [Luau] scalar, no temporaries
bg_rect.Min.x, bg_rect.Min.y, bg_rect.Max.x, bg_rect.Max.y = window.Pos.x + 0, window.Pos.y + window.TitleBarHeight, window.Pos.x + window.Size.x, window.Pos.y + window.Size.y
local bg_rounding_flags local bg_rounding_flags
if window.DockIsActive then if window.DockIsActive then
bg_rounding_flags = ImGui.CalcRoundingFlagsForRectInRect(bg_rect, window.DockNode.HostWindow:Rect(), 0.0) bg_rounding_flags = ImGui.CalcRoundingFlagsForRectInRect(bg_rect, window.DockNode.HostWindow:Rect(), 0.0)
@@ -10928,11 +10946,20 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high
end end
local grip = ImGuiResizeGripDef[resize_grip_n] local grip = ImGuiResizeGripDef[resize_grip_n]
local corner = ImLerp(window.Pos, window.Pos + window.Size, grip.CornerPosN) -- [Luau] scalar corner/points, one scratch ImVec2 (the path copies points)
local pos, cpn, dir = window.Pos, grip.CornerPosN, grip.InnerDir
local corner_x = pos.x + ((pos.x + window.Size.x) - pos.x) * cpn.x
local corner_y = pos.y + ((pos.y + window.Size.y) - pos.y) * cpn.y
local border_inner = IM_ROUND(window_border_size * 0.5) local border_inner = IM_ROUND(window_border_size * 0.5)
window.DrawList:PathLineTo(corner + grip.InnerDir * ((resize_grip_n % 2 == 0) and ImVec2(border_inner, resize_grip_draw_size) or ImVec2(resize_grip_draw_size, border_inner))) local a, b = border_inner, resize_grip_draw_size
window.DrawList:PathLineTo(corner + grip.InnerDir * ((resize_grip_n % 2 == 0) and ImVec2(resize_grip_draw_size, border_inner) or ImVec2(border_inner, resize_grip_draw_size))) if resize_grip_n % 2 ~= 0 then a, b = b, a end
window.DrawList:PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + border_inner), corner.y + grip.InnerDir.y * (window_rounding + border_inner)), window_rounding, grip.AngleMin12, grip.AngleMax12) local p = WindowDecoScratch.p
p.x, p.y = corner_x + dir.x * a, corner_y + dir.y * b
window.DrawList:PathLineTo(p)
p.x, p.y = corner_x + dir.x * b, corner_y + dir.y * a
window.DrawList:PathLineTo(p)
p.x, p.y = corner_x + dir.x * (window_rounding + border_inner), corner_y + dir.y * (window_rounding + border_inner)
window.DrawList:PathArcToFast(p, window_rounding, grip.AngleMin12, grip.AngleMax12)
window.DrawList:PathFillConvex(col) window.DrawList:PathFillConvex(col)
until true until true
@@ -10949,6 +10976,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high
end end
ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders
-- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. -- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
-- Render title text, collapse button, close button -- Render title text, collapse button, close button
-- [Port] Returns the updated 'open' value (nil when there is no close button) -- [Port] Returns the updated 'open' value (nil when there is no close button)
@@ -11014,7 +11042,9 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open)
-- Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) -- Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
-- FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. -- FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
local marker_size_x = (bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0) and (button_sz * 0.80) or 0.0 local marker_size_x = (bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0) and (button_sz * 0.80) or 0.0
local text_size = ImGui.CalcTextSize(name, nil, true) + ImVec2(marker_size_x, 0.0) local text_size = WindowDecoScratch.text_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known)
local text_size_x, text_size_y = ImGui.CalcTextSizeXY(name, 1, nil, true)
text_size.x = text_size_x + marker_size_x; text_size.y = text_size_y + 0.0
-- As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, -- As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
-- while uncentered title text will still reach edges correctly. -- while uncentered title text will still reach edges correctly.
@@ -11031,8 +11061,9 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open)
pad_r = ImMax(pad_r, pad_extend * centerness) pad_r = ImMax(pad_r, pad_extend * centerness)
end end
local layout_r = ImRect(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y) local layout_r, clip_r = WindowDecoScratch.layout_r, WindowDecoScratch.clip_r -- [Luau] scratch, only read by callees
local clip_r = ImRect(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y) layout_r.Min.x, layout_r.Min.y, layout_r.Max.x, layout_r.Max.y = title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y
clip_r.Min.x, clip_r.Min.y, clip_r.Max.x, clip_r.Max.y = layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y
if bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0 then if bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0 then
local marker_pos = ImVec2() local marker_pos = ImVec2()
@@ -12169,13 +12200,17 @@ function ImGui.Begin(name, open, flags)
-- Add to stack -- Add to stack
g.CurrentWindow = window g.CurrentWindow = window
g.CurrentWindowStack:resize(g.CurrentWindowStack.Size + 1) g.CurrentWindowStack:resize(g.CurrentWindowStack.Size + 1)
g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = ImGuiWindowStackData() -- [Luau] reuse the slot's table left by pop_back() (C++ reuses the vector storage); every field is set below
local window_stack_data = g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] local window_stack_data = g.CurrentWindowStack.Data[g.CurrentWindowStack.Size]
if type(window_stack_data) ~= "table" or window_stack_data.ParentLastItemDataBackup == nil then
window_stack_data = ImGuiWindowStackData()
g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = window_stack_data
end
window_stack_data.Window = window window_stack_data.Window = window
ImGuiLastItemData_Copy(window_stack_data.ParentLastItemDataBackup, g.LastItemData) ImGuiLastItemData_Copy(window_stack_data.ParentLastItemDataBackup, g.LastItemData)
window_stack_data.DisabledOverrideReenable = (bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) and (bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0) window_stack_data.DisabledOverrideReenable = (bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) and (bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0)
window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0 window_stack_data.DisabledOverrideReenableAlphaBackup = 0.0
window_stack_data.StackSizesInBegin = ImGuiErrorRecoveryState() window_stack_data.StackSizesInBegin = window_stack_data.StackSizesInBegin or ImGuiErrorRecoveryState() -- [Luau] reused, all fields stored
ImGui.ErrorRecoveryStoreState(window_stack_data.StackSizesInBegin) ImGui.ErrorRecoveryStoreState(window_stack_data.StackSizesInBegin)
g.StackSizesInBeginForCurrentWindow = window_stack_data.StackSizesInBegin g.StackSizesInBeginForCurrentWindow = window_stack_data.StackSizesInBegin
if bit32.band(flags, ImGuiWindowFlags.ChildMenu) ~= 0 then if bit32.band(flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
@@ -12956,7 +12991,9 @@ function ImGui.Begin(name, open, flags)
-- Title bar -- Title bar
if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then
open = RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window.WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window.WindowBorderSize, title_bar_rect.Max.y), name, open) local r = WindowDecoScratch.title_bar_rect -- [Luau] scratch, only read
r.Min.x, r.Min.y, r.Max.x, r.Max.y = title_bar_rect.Min.x + window.WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window.WindowBorderSize, title_bar_rect.Max.y
open = RenderWindowTitleBarContents(window, r, name, open)
elseif bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and window.DockIsActive then elseif bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and window.DockIsActive then
ImGui.LogText("%s\n", string.sub(window.Name, 1, ImGui.FindRenderedTextEnd(window.Name) - 1)) ImGui.LogText("%s\n", string.sub(window.Name, 1, ImGui.FindRenderedTextEnd(window.Name) - 1))
end end
@@ -14373,6 +14410,7 @@ function ImGui.NewFrame()
ImGuiPlatformImeData_Copy(g.PlatformImeDataPrev, g.PlatformImeData) ImGuiPlatformImeData_Copy(g.PlatformImeDataPrev, g.PlatformImeData)
g.PlatformImeData.WantVisible = false g.PlatformImeData.WantVisible = false
g.PlatformImeData.WantTextInput = false g.PlatformImeData.WantTextInput = false
g.PlatformImeData.SelectedText = "" -- [Port]
-- Mouse wheel scrolling, scale -- Mouse wheel scrolling, scale
ImGui.UpdateMouseWheel() ImGui.UpdateMouseWheel()
@@ -14659,10 +14697,10 @@ end
--- @param hide_text_after_double_hash? bool --- @param hide_text_after_double_hash? bool
--- @param wrap_width? float --- @param wrap_width? float
--- @return ImVec2 --- @return ImVec2
-- [Luau] scalar CalcTextSizeEx(): returns x, y without allocating an ImVec2 (hot widget paths)
@native @native
function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double_hash, wrap_width) function ImGui.CalcTextSizeXY(text, text_begin, text_end, hide_text_after_double_hash, wrap_width)
if hide_text_after_double_hash == nil then hide_text_after_double_hash = false end if wrap_width == nil then wrap_width = -1.0 end
if wrap_width == nil then wrap_width = -1.0 end
local g = GImGui local g = GImGui
@@ -14673,19 +14711,22 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double
text_display_end = text_end text_display_end = text_end
end end
local font = g.Font
local font_size = g.FontSize local font_size = g.FontSize
if text == "" or (text_end and text_end <= text_begin) then if text == "" or (text_end and text_end <= text_begin) then
return ImVec2(0.0, font_size) return 0.0, font_size
end end
local text_size = ImFontCalcTextSizeEx(font, font_size, FLT_MAX, wrap_width, text, text_begin, text_display_end, text_display_end, nil, ImDrawTextFlags.None) -- [Luau] inline font:CalcTextSizeA() local x, y = ImFontCalcTextSizeXY(g.Font, font_size, FLT_MAX, wrap_width, text, text_begin, text_display_end, text_display_end, nil, ImDrawTextFlags.None) -- [Luau] inline font:CalcTextSizeA()
-- Round -- Round
-- (see 7b0bf230, 4622fa4b6, #791 for details about this.) -- (see 7b0bf230, 4622fa4b6, #791 for details about this.)
-- FIXME: Add a way to disable this. -- FIXME: Add a way to disable this.
text_size.x = math.ceil(text_size.x) -- [Luau] == ImCeilFast() for all finite values, builtin return math.ceil(x), y -- [Luau] == ImCeilFast() for all finite values, builtin
end
return text_size @native
function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double_hash, wrap_width)
local x, y = ImGui.CalcTextSizeXY(text, text_begin, text_end, hide_text_after_double_hash, wrap_width)
return ImVec2(x, y)
end end
-- Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() -- Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
+50 -23
View File
@@ -49,6 +49,7 @@ end
--- @param buf char[] # 1-based --- @param buf char[] # 1-based
--- @param base int # 1-based start index --- @param base int # 1-based start index
--- @param u32 ImU32 --- @param u32 ImU32
@native
local function write_u32(buf, base, u32) local function write_u32(buf, base, u32)
buf[base + 0] = bit32.band(u32, 0xFF) buf[base + 0] = bit32.band(u32, 0xFF)
buf[base + 1] = bit32.band(bit32.rshift(u32, 8), 0xFF) buf[base + 1] = bit32.band(bit32.rshift(u32, 8), 0xFF)
@@ -778,6 +779,7 @@ end
--- @param dst_pitch int --- @param dst_pitch int
--- @param w int --- @param w int
--- @param h int --- @param h int
@native
function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixels, dst_pixels_base, dst_fmt, dst_pitch, w, h) function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixels, dst_pixels_base, dst_fmt, dst_pitch, w, h)
IM_ASSERT(src_pixels ~= nil and dst_pixels ~= nil) IM_ASSERT(src_pixels ~= nil and dst_pixels ~= nil)
local src_pixels_base = 1 local src_pixels_base = 1
@@ -795,7 +797,8 @@ function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixe
local alpha = src_pixels[src_pixels_base + 0] local alpha = src_pixels[src_pixels_base + 0]
src_pixels_base = src_pixels_base + 1 src_pixels_base = src_pixels_base + 1
write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha)) -- [Luau] inline write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha))
dst_pixels[dst_pixels_base] = 255; dst_pixels[dst_pixels_base + 1] = 255; dst_pixels[dst_pixels_base + 2] = 255; dst_pixels[dst_pixels_base + 3] = alpha
dst_pixels_base = dst_pixels_base + 4 dst_pixels_base = dst_pixels_base + 4
end end
@@ -2701,8 +2704,13 @@ function MT.ImTextureData:Create(format, w, h)
self.Height = h self.Height = h
self.BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format) self.BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format)
self.UseColors = false self.UseColors = false
self.Pixels = {} local n = self.Width * self.Height * self.BytesPerPixel
ImStd.memset(self.Pixels, 0, self.Width * self.Height * self.BytesPerPixel) if table.create then
self.Pixels = table.create(n, 0) -- [Luau] native zero fill, same contents as memset
else
self.Pixels = {}
ImStd.memset(self.Pixels, 0, n)
end
self.UsedRect.x = 0 self.UsedRect.x = 0
self.UsedRect.y = 0 self.UsedRect.y = 0
self.UsedRect.w = 0 self.UsedRect.w = 0
@@ -3466,7 +3474,8 @@ end
local TEXT_SIZE_CACHE_MAX = 4096 local TEXT_SIZE_CACHE_MAX = 4096
@native @native
function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags) -- [Luau] scalar core of ImFontCalcTextSizeEx(): returns size.x, size.y, remaining (no ImVec2 allocated)
function ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags)
local text_is_str = type(text) == "string" local text_is_str = type(text) == "string"
-- [Luau] cache for the common case (whole string, single pass, no wrap/limit): per baked font, text -> unscaled width, line count. -- [Luau] cache for the common case (whole string, single pass, no wrap/limit): per baked font, text -> unscaled width, line count.
-- Advances of a baked font never change once loaded, so entries stay valid. -- Advances of a baked font never change once loaded, so entries stay valid.
@@ -3483,7 +3492,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi
end end
local e = cache[text] local e = cache[text]
if e then if e then
return ImVec2(e[1] * (size / baked.Size), e[2] * size), text_len1 return e[1] * (size / baked.Size), e[2] * size, text_len1
end end
cache_key = text cache_key = text
elseif cacheable and wrap_width > 0.0 then elseif cacheable and wrap_width > 0.0 then
@@ -3499,7 +3508,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi
if by_wrap == nil then by_wrap = {}; by_size[wrap_width] = by_wrap end if by_wrap == nil then by_wrap = {}; by_size[wrap_width] = by_wrap end
local e = by_wrap[text] local e = by_wrap[text]
if e then if e then
return ImVec2(e[1], e[2]), e[3] return e[1], e[2], e[3]
end end
wrap_cache = by_wrap wrap_cache = by_wrap
end end
@@ -3514,7 +3523,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi
local line_height = size local line_height = size
local scale = line_height / baked.Size local scale = line_height / baked.Size
local text_size = ImVec2() local tx, ty = 0.0, 0.0
local line_width = 0.0 local line_width = 0.0
local word_wrap_enabled = (wrap_width > 0.0) local word_wrap_enabled = (wrap_width > 0.0)
@@ -3534,10 +3543,10 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi
end end
if s >= word_wrap_eol then if s >= word_wrap_eol then
if text_size.x < line_width then if tx < line_width then
text_size.x = line_width tx = line_width
end end
text_size.y = text_size.y + line_height ty = ty + line_height
line_width = 0.0 line_width = 0.0
s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks
if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then
@@ -3562,8 +3571,8 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi
end end
if c == 10 then -- '\n' if c == 10 then -- '\n'
text_size.x = ImMax(text_size.x, line_width) if tx < line_width then tx = line_width end
text_size.y = text_size.y + line_height ty = ty + line_height
line_width = 0.0 line_width = 0.0
if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then
stop = true; break stop = true; break
@@ -3595,30 +3604,36 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi
if stop then break end if stop then break end
end end
if (text_size.x < line_width) then if (tx < line_width) then
text_size.x = line_width tx = line_width
end end
if out_offset then -- offset allow for the possibility of sitting after a trailing \n if out_offset then -- offset allow for the possibility of sitting after a trailing \n
out_offset.x = line_width out_offset.x = line_width
out_offset.y = text_size.y + line_height out_offset.y = ty + line_height
end end
if (line_width > 0 or text_size.y == 0.0) then -- whereas size.y will ignore the trailing \n if (line_width > 0 or ty == 0.0) then -- whereas size.y will ignore the trailing \n
text_size.y = text_size.y + line_height ty = ty + line_height
end end
local out_remaining = s local out_remaining = s
if cache_key then if cache_key then
baked._TextSizeCache[cache_key] = { text_size.x / scale, text_size.y / line_height } baked._TextSizeCache[cache_key] = { tx / scale, ty / line_height }
baked._TextSizeCacheN = baked._TextSizeCacheN + 1 baked._TextSizeCacheN = baked._TextSizeCacheN + 1
elseif wrap_cache then elseif wrap_cache then
wrap_cache[text] = { text_size.x, text_size.y, out_remaining } wrap_cache[text] = { tx, ty, out_remaining }
baked._TextSizeCacheN = baked._TextSizeCacheN + 1 baked._TextSizeCacheN = baked._TextSizeCacheN + 1
end end
return text_size, out_remaining return tx, ty, out_remaining
end
-- ImVec2 version (upstream signature)
function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags)
local x, y, remaining = ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags)
return ImVec2(x, y), remaining
end end
--- @param size float --- @param size float
@@ -6145,6 +6160,10 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags)
return return
end end
-- [Port] reversed corners (min > max, e.g. a box selection dragged up/left): upstream's min_dim checks drop them, older ImGui drew them
if p_min.x > p_max.x or p_min.y > p_max.y then
p_min, p_max = ImVec2(ImMin(p_min.x, p_max.x), ImMin(p_min.y, p_max.y)), ImVec2(ImMax(p_min.x, p_max.x), ImMax(p_min.y, p_max.y))
end
flags = bit32.bor(flags, self.Flags) flags = bit32.bor(flags, self.Flags)
local stroke_pos = _GetStrokePos(flags, ImDrawFlags.StrokeInside) local stroke_pos = _GetStrokePos(flags, ImDrawFlags.StrokeInside)
if stroke_pos == ImDrawFlags.StrokeLegacy then if stroke_pos == ImDrawFlags.StrokeLegacy then
@@ -6362,6 +6381,8 @@ function MT.ImDrawList:AddRectFilled(p_min, p_max, col, rounding, flags)
end end
local ax, ay, bx, by = p_min.x, p_min.y, p_max.x, p_max.y local ax, ay, bx, by = p_min.x, p_min.y, p_max.x, p_max.y
if ax > bx then ax, bx = bx, ax end -- [Port] reversed corners: see AddRect
if ay > by then ay, by = by, ay end
local width = bx - ax local width = bx - ax
local height = by - ay local height = by - ay
local min_dim = ImMin(width, height) local min_dim = ImMin(width, height)
@@ -6982,7 +7003,15 @@ 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) -- 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)
function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect) function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect)
local cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) -- [Luau] reuse the stack slot's ImVec4 left from earlier frames (each slot stays uniquely owned by the stack)
local stack = self._ClipRectStack
local n = stack.Size + 1
local cr = n <= stack.Capacity and stack.Data[n] or nil
if cr then
cr.x = cr_min.x; cr.y = cr_min.y; cr.z = cr_max.x; cr.w = cr_max.y
else
cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y)
end
if intersect_with_current_clip_rect then if intersect_with_current_clip_rect then
local current = self._CmdHeader.ClipRect local current = self._CmdHeader.ClipRect
@@ -6997,8 +7026,6 @@ function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_
cr.w = math.max(cr.y, cr.w) cr.w = math.max(cr.y, cr.w)
-- [Luau] inline self._ClipRectStack:push_back(cr) -- [Luau] inline self._ClipRectStack:push_back(cr)
local stack = self._ClipRectStack
local n = stack.Size + 1
if n > stack.Capacity then stack:push_back(cr) else stack.Data[n] = cr; stack.Size = n end if n > stack.Capacity then stack:push_back(cr) else stack.Data[n] = cr; stack.Size = n end
ImVec4_Copy(self._CmdHeader.ClipRect, cr) ImVec4_Copy(self._CmdHeader.ClipRect, cr)
self:_OnChangedClipRect() self:_OnChangedClipRect()
+6 -2
View File
@@ -1438,6 +1438,7 @@ end
--- @field InputPos ImVec2 --- @field InputPos ImVec2
--- @field InputLineHeight float --- @field InputLineHeight float
--- @field ViewportId ImGuiID --- @field ViewportId ImGuiID
--- @field SelectedText string
--- @return ImGuiPlatformImeData --- @return ImGuiPlatformImeData
--- @nodiscard --- @nodiscard
@@ -1447,7 +1448,8 @@ function ImGuiPlatformImeData()
WantTextInput = false, -- A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. WantTextInput = false, -- A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput.
InputPos = ImVec2(), -- Position of input cursor (for IME). InputPos = ImVec2(), -- Position of input cursor (for IME).
InputLineHeight = 0.0, -- Line height (for IME). InputLineHeight = 0.0, -- Line height (for IME).
ViewportId = 0 -- ID of platform window/viewport. ViewportId = 0, -- ID of platform window/viewport.
SelectedText = "" -- [Port] Text currently selected in the widget wanting text input (backends may mirror it, e.g. for native copy).
} }
end end
@@ -1459,6 +1461,7 @@ function ImGuiPlatformImeData_Copy(dest, src)
ImVec2_Copy(dest.InputPos, src.InputPos) ImVec2_Copy(dest.InputPos, src.InputPos)
dest.InputLineHeight = src.InputLineHeight dest.InputLineHeight = src.InputLineHeight
dest.ViewportId = src.ViewportId dest.ViewportId = src.ViewportId
dest.SelectedText = src.SelectedText -- [Port]
end end
--- @param data1 ImGuiPlatformImeData --- @param data1 ImGuiPlatformImeData
@@ -1468,7 +1471,8 @@ function ImGuiPlatformImeData_Compare(data1, data2)
data1.WantTextInput ~= data2.WantTextInput or data1.WantTextInput ~= data2.WantTextInput or
data1.InputPos ~= data2.InputPos or data1.InputPos ~= data2.InputPos or
data1.InputLineHeight ~= data2.InputLineHeight or data1.InputLineHeight ~= data2.InputLineHeight or
data1.ViewportId ~= data2.ViewportId then data1.ViewportId ~= data2.ViewportId or
data1.SelectedText ~= data2.SelectedText then
return false return false
end end
+3 -1
View File
@@ -319,13 +319,15 @@ end
--- @param s table # 1-based --- @param s table # 1-based
--- @param c any --- @param c any
--- @param n int --- @param n int
@native
function ImStd.memset(s, c, n) function ImStd.memset(s, c, n)
for i = 1, n do s[i] = c end for i = 1, n do s[i] = c end
end end
do do
local _memmove = function(dest, dest_start, src, src_start, count) @native
local function _memmove(dest, dest_start, src, src_start, count)
if count <= 0 then return end if count <= 0 then return end
local c = (dest == src and dest_start >= src_start) local c = (dest == src and dest_start >= src_start)
+72 -38
View File
@@ -110,13 +110,13 @@ function ImGui.TextEx(text, text_end, flags)
-- [Luau] scalar text_pos, scratch bb (ItemAdd() copies it, RenderTextWrapped() only reads it) -- [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 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 wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(dc.CursorPos, wrap_pos_x) or 0.0
local text_size = ImGui.CalcTextSizeEx(text, 1, text_end, false, wrap_width) local text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false, wrap_width)
local bb = TextEx_bb local bb = TextEx_bb
local bb_min, bb_max = bb.Min, bb.Max local bb_min, bb_max = bb.Min, bb.Max
bb_min.x = text_pos_x; bb_min.y = text_pos_y bb_min.x = text_pos_x; bb_min.y = text_pos_y
bb_max.x = text_pos_x + text_size.x; bb_max.y = text_pos_y + text_size.y bb_max.x = text_pos_x + text_size_x; bb_max.y = text_pos_y + text_size_y
ImGui.ItemSize(text_size, 0.0) ImGui.ItemSize(bb, 0.0) -- [Luau] the bb's size == text_size
if not ImGui.ItemAdd(bb, 0) then if not ImGui.ItemAdd(bb, 0) then
return return
end end
@@ -342,6 +342,8 @@ end
-- Text with a little bullet aligned to the typical tree node. -- Text with a little bullet aligned to the typical tree node.
--- @param fmt string --- @param fmt string
--- @param ... any --- @param ... any
local BulletText_bb, BulletText_pos, BulletText_size = ImRect(), ImVec2(), ImVec2() -- [Luau] scratch, only read by callees
function ImGui.BulletText(fmt, ...) function ImGui.BulletText(fmt, ...)
local window = ImGui.GetCurrentWindow() local window = ImGui.GetCurrentWindow()
if window.SkipItems then if window.SkipItems then
@@ -353,20 +355,26 @@ function ImGui.BulletText(fmt, ...)
local text = ImFormatString(fmt, ...) local text = ImFormatString(fmt, ...)
local text_end = #text + 1 local text_end = #text + 1
local label_size = ImGui.CalcTextSize(text, text_end, false) local label_size_x, label_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false) -- [Luau] scalar label_size/total_size
local total_size = ImVec2(g.FontSize + ((label_size.x > 0.0) and (label_size.x + style.FramePadding.x * 2) or 0.0), label_size.y) -- Empty text doesn't add padding local total_size_x = g.FontSize + ((label_size_x > 0.0) and (label_size_x + style.FramePadding.x * 2) or 0.0) -- Empty text doesn't add padding
-- [Luau] scalar pos, no temporary ImVec2 -- [Luau] scalar pos, no temporary ImVec2
local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset
local bb = BulletText_bb
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = pos_x, pos_y, pos_x + total_size_x, pos_y + label_size_y
local total_size = BulletText_size
total_size.x, total_size.y = total_size_x, label_size_y
ImGui.ItemSize(total_size, 0.0) ImGui.ItemSize(total_size, 0.0)
local bb = ImRect(pos_x, pos_y, pos_x + total_size.x, pos_y + total_size.y)
if not ImGui.ItemAdd(bb, 0) then if not ImGui.ItemAdd(bb, 0) then
return return
end end
-- Render -- Render
local text_col = ImGui.GetColorU32(ImGuiCol.Text) local text_col = ImGui.GetColorU32(ImGuiCol.Text)
ImGui.RenderBullet(window.DrawList, ImVec2(bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + g.FontSize * 0.5), text_col) local p = BulletText_pos
ImGui.RenderText(ImVec2(bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0), text, 1, text_end, false) p.x, p.y = bb.Min.x + (style.FramePadding.x + g.FontSize * 0.5), bb.Min.y + g.FontSize * 0.5
ImGui.RenderBullet(window.DrawList, p, text_col)
p.x, p.y = bb.Min.x + (g.FontSize + style.FramePadding.x * 2), bb.Min.y + 0.0
ImGui.RenderText(p, text, 1, text_end, false)
end end
-- [Port] va_list variants: identical to the varargs versions in Lua -- [Port] va_list variants: identical to the varargs versions in Lua
@@ -744,6 +752,7 @@ end
--- @param size_arg? ImVec2 --- @param size_arg? ImVec2
--- @param flags? ImGuiButtonFlags --- @param flags? ImGuiButtonFlags
--- @return bool --- @return bool
local ButtonEx_bb, ButtonEx_label_size, ButtonEx_size = ImRect(), ImVec2(), ImVec2()
local ButtonEx_text_min, ButtonEx_text_max = ImVec2(), ImVec2() local ButtonEx_text_min, ButtonEx_text_max = ImVec2(), ImVec2()
@native @native
@@ -760,7 +769,8 @@ function ImGui.ButtonEx(label, size_arg, flags)
local style = g.Style local style = g.Style
local id = window:GetID(label) local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label) local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false) local label_size = ButtonEx_label_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known)
label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false)
-- [Luau] scalar pos, no temporary ImVec2 -- [Luau] scalar pos, no temporary ImVec2
local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y local pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y
@@ -768,9 +778,11 @@ function ImGui.ButtonEx(label, size_arg, flags)
if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and frame_padding.y < window.DC.CurrLineTextBaseOffset then -- Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and frame_padding.y < window.DC.CurrLineTextBaseOffset then -- Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
pos_y = pos_y + window.DC.CurrLineTextBaseOffset - frame_padding.y pos_y = pos_y + window.DC.CurrLineTextBaseOffset - frame_padding.y
end end
local size = ImGui.CalcItemSize(size_arg, label_size.x + frame_padding.x * 2.0, label_size.y + frame_padding.y * 2.0) local size = ButtonEx_size -- [Luau] scratch + scalar CalcItemSize(): ItemSize() only reads it
size.x, size.y = ImGui._CalcItemSizeXY(size_arg.x, size_arg.y, label_size.x + frame_padding.x * 2.0, label_size.y + frame_padding.y * 2.0)
local bb = ImRect(pos_x, pos_y, pos_x + size.x, pos_y + size.y) local bb = ButtonEx_bb -- [Luau] scratch: ItemAdd() copies it, ButtonBehavior()/Render*() only read it
bb.Min.x, bb.Min.y, bb.Max.x, bb.Max.y = pos_x, pos_y, pos_x + size.x, pos_y + size.y
ImGui.ItemSize(size, frame_padding.y) ImGui.ItemSize(size, frame_padding.y)
if not ImGui.ItemAdd(bb, id) then if not ImGui.ItemAdd(bb, id) then
return false return false
@@ -1299,6 +1311,8 @@ end
--- @param v bool --- @param v bool
--- @return bool is_pressed --- @return bool is_pressed
--- @return bool is_checked # The updated `v` passed in --- @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
@native @native
function ImGui.Checkbox(label, v) function ImGui.Checkbox(label, v)
local window = ImGui.GetCurrentWindow() local window = ImGui.GetCurrentWindow()
@@ -1310,18 +1324,19 @@ function ImGui.Checkbox(label, v)
local style = g.Style local style = g.Style
local id = window:GetID(label) local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(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 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 pos_x, pos_y = window.DC.CursorPos.x, window.DC.CursorPos.y -- [Luau] scalar pos, no temporary ImVec2
local total_width local total_width
if label_size.x > 0.0 then if label_size_x > 0.0 then
total_width = square_sz + style.ItemInnerSpacing.x + label_size.x total_width = square_sz + style.ItemInnerSpacing.x + label_size_x
else else
total_width = square_sz total_width = square_sz
end end
local total_bb = ImRect(pos_x, pos_y, pos_x + total_width, pos_y + (label_size.y + style.FramePadding.y * 2.0)) local total_bb = Checkbox_total_bb
total_bb.Min.x, total_bb.Min.y, total_bb.Max.x, total_bb.Max.y = pos_x, pos_y, pos_x + total_width, pos_y + (label_size_y + style.FramePadding.y * 2.0)
ImGui.ItemSize(total_bb, style.FramePadding.y) ImGui.ItemSize(total_bb, style.FramePadding.y)
local is_visible = ImGui.ItemAdd(total_bb, id) local is_visible = ImGui.ItemAdd(total_bb, id)
local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0) local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0)
@@ -1353,7 +1368,8 @@ function ImGui.Checkbox(label, v)
ImGui.MarkItemEdited(id) ImGui.MarkItemEdited(id)
end end
local check_bb = ImRect(pos_x, pos_y, pos_x + square_sz, pos_y + square_sz) local check_bb = Checkbox_check_bb
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
local mixed_value = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.MixedValue) ~= 0) local mixed_value = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.MixedValue) ~= 0)
if is_visible then if is_visible then
ImGui.RenderNavCursor(total_bb, id) ImGui.RenderNavCursor(total_bb, id)
@@ -1378,8 +1394,9 @@ function ImGui.Checkbox(label, v)
ImGui.LogRenderedText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), mixed_value and "[~]" or (v and "[x]" or "[ ]")) -- label_pos ImGui.LogRenderedText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), mixed_value and "[~]" or (v and "[x]" or "[ ]")) -- label_pos
end end
if is_visible and label_size.x > 0.0 then if is_visible and label_size_x > 0.0 then
local label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y) -- [Luau] only built when used local label_pos = Checkbox_label_pos
label_pos.x, label_pos.y = check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y
ImGui.RenderText(label_pos, label, 1, label_end, false) ImGui.RenderText(label_pos, label, 1, label_end, false)
end end
@@ -3502,7 +3519,8 @@ end
-- [Luau] memo of string.format(format, value) for drag/slider value text (same values are redrawn every frame). -- [Luau] memo of string.format(format, value) for drag/slider value text (same values are redrawn every frame).
local fmt_memo, fmt_memo_n = {}, 0 local fmt_memo, fmt_memo_n = {}, 0
local SliderScalar_total_bb, SliderScalar_grab_bb = ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape local SliderScalar_total_bb, SliderScalar_grab_bb, SliderScalar_frame_bb = ImRect(), ImRect(), ImRect() -- [Luau] scratch for SliderScalar()/DragScalar(), never escape
local SliderScalar_label_pos = ImVec2()
local DRAG_TEXT_ALIGN = ImVec2(0.5, 0.5) local DRAG_TEXT_ALIGN = ImVec2(0.5, 0.5)
function FormatCached(format, v) function FormatCached(format, v)
local m = fmt_memo[format] local m = fmt_memo[format]
@@ -3533,12 +3551,13 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla
local color_marker = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasColorMarker) ~= 0) and g.NextItemData.ColorMarker or 0 local color_marker = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasColorMarker) ~= 0) and g.NextItemData.ColorMarker or 0
local label_end = ImGui.FindRenderedTextEnd(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 cursor = window.DC.CursorPos local cursor = window.DC.CursorPos
local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size.y + style.FramePadding.y * 2.0)) -- [Luau] no temporary ImVec2 local frame_bb = SliderScalar_frame_bb -- [Luau] scratch: callees only read it
frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0)
local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it
total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y
total_bb.Max.x = frame_bb.Max.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0); total_bb.Max.y = frame_bb.Max.y + 0.0 total_bb.Max.x = frame_bb.Max.x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0); total_bb.Max.y = frame_bb.Max.y + 0.0
local temp_input_allowed = (bit32.band(flags, ImGuiSliderFlags.NoInput) == 0) local temp_input_allowed = (bit32.band(flags, ImGuiSliderFlags.NoInput) == 0)
ImGui.ItemSize(total_bb, style.FramePadding.y) ImGui.ItemSize(total_bb, style.FramePadding.y)
@@ -3626,8 +3645,10 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla
ImGui.PopStyleColor() ImGui.PopStyleColor()
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) local label_pos = SliderScalar_label_pos
label_pos.x, label_pos.y = frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y
ImGui.RenderText(label_pos, label, 1, label_end, false)
end end
return data, value_changed return data, value_changed
@@ -4238,10 +4259,11 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags)
local color_marker = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasColorMarker) ~= 0) and g.NextItemData.ColorMarker or 0 local color_marker = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasColorMarker) ~= 0) and g.NextItemData.ColorMarker or 0
local label_end = ImGui.FindRenderedTextEnd(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 cursor = window.DC.CursorPos local cursor = window.DC.CursorPos
local frame_bb = ImRect(cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size.y + style.FramePadding.y * 2.0)) -- [Luau] no temporary ImVec2 local frame_bb = SliderScalar_frame_bb -- [Luau] scratch: callees only read it
local total_bb_x = frame_bb.Max.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0) frame_bb.Min.x, frame_bb.Min.y, frame_bb.Max.x, frame_bb.Max.y = cursor.x, cursor.y, cursor.x + w, cursor.y + (label_size_y + style.FramePadding.y * 2.0)
local total_bb_x = frame_bb.Max.x + ((label_size_x > 0.0) and (style.ItemInnerSpacing.x + label_size_x) or 0.0)
local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it local total_bb = SliderScalar_total_bb -- [Luau] scratch: ItemSize()/ItemAdd() only read it
total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y; total_bb.Max.x = total_bb_x; total_bb.Max.y = frame_bb.Max.y total_bb.Min.x = frame_bb.Min.x; total_bb.Min.y = frame_bb.Min.y; total_bb.Max.x = total_bb_x; total_bb.Max.y = frame_bb.Max.y
@@ -4327,8 +4349,10 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags)
ImGui.PopStyleColor() ImGui.PopStyleColor()
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) local label_pos = SliderScalar_label_pos
label_pos.x, label_pos.y = frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y
ImGui.RenderText(label_pos, label, 1, label_end, false)
end end
-- IMGUI_TEST_ENGINE_ITEM_INFO() -- IMGUI_TEST_ENGINE_ITEM_INFO()
@@ -6408,6 +6432,10 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback
ImVec2_Copy(ime_data.InputPos, ImVec2(cursor_screen_pos.x - 1.0, cursor_screen_pos.y - g.FontSize)) ImVec2_Copy(ime_data.InputPos, ImVec2(cursor_screen_pos.x - 1.0, cursor_screen_pos.y - g.FontSize))
ime_data.InputLineHeight = g.FontSize ime_data.InputLineHeight = g.FontSize
ime_data.ViewportId = window.Viewport.ID ime_data.ViewportId = window.Viewport.ID
-- [Port] selection for backends (stb positions are 1-based in this port)
if state.Stb and state:HasSelection() then
ime_data.SelectedText = ImGui._ByteArrayToString(state.TextA.Data, ImMin(state.Stb.select_start, state.Stb.select_end), ImMax(state.Stb.select_start, state.Stb.select_end))
end
end end
end end
@@ -7808,6 +7836,10 @@ end
--- @param flags ImGuiTreeNodeFlags --- @param flags ImGuiTreeNodeFlags
--- @param label string --- @param label string
--- @param label_end? int --- @param label_end? int
local TreeNode_frame_bb, TreeNode_interact_bb = ImRect(), ImRect() -- [Luau] scratch for TreeNodeBehavior(), never escape
local TreeNode_label_size, TreeNode_text_pos, TreeNode_tmp = ImVec2(), ImVec2(), ImVec2()
local function TreeNode_tmp_pos(x, y) local v = TreeNode_tmp; v.x = x; v.y = y; return v end -- [Luau] scratch pos for Render*() args
@native @native
function ImGui.TreeNodeBehavior(id, flags, label, label_end) function ImGui.TreeNodeBehavior(id, flags, label, label_end)
local window = ImGui.GetCurrentWindow() local window = ImGui.GetCurrentWindow()
@@ -7832,7 +7864,8 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end)
if label_end == nil then if label_end == nil then
label_end = ImGui.FindRenderedTextEnd(label) label_end = ImGui.FindRenderedTextEnd(label)
end end
local label_size = ImGui.CalcTextSize(label, label_end, false) local label_size = TreeNode_label_size -- [Luau] scratch: only read below (RenderTextClipped text_size_if_known)
label_size.x, label_size.y = ImGui.CalcTextSizeXY(label, 1, label_end, false)
local text_offset_x = g.FontSize + (display_frame and (padding_x * 3) or (padding_x * 2)) -- Collapsing arrow width + Spacing local text_offset_x = g.FontSize + (display_frame and (padding_x * 3) or (padding_x * 2)) -- Collapsing arrow width + Spacing
local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset -- Latch before ItemSize changes it local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset -- Latch before ItemSize changes it
@@ -7841,7 +7874,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end)
local frame_height = label_size.y + padding_y * 2 local frame_height = label_size.y + padding_y * 2
local span_all_columns = bit32.band(flags, ImGuiTreeNodeFlags.SpanAllColumns) ~= 0 and (g.CurrentTable ~= nil) local span_all_columns = bit32.band(flags, ImGuiTreeNodeFlags.SpanAllColumns) ~= 0 and (g.CurrentTable ~= nil)
local span_all_columns_label = bit32.band(flags, ImGuiTreeNodeFlags.LabelSpanAllColumns) ~= 0 and (g.CurrentTable ~= nil) local span_all_columns_label = bit32.band(flags, ImGuiTreeNodeFlags.LabelSpanAllColumns) ~= 0 and (g.CurrentTable ~= nil)
local frame_bb = ImRect() local frame_bb = TreeNode_frame_bb -- [Luau] scratch, fully written here; callees copy or only read it
frame_bb.Min.x = span_all_columns and window.ParentWorkRect.Min.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanFullWidth) ~= 0 and window.WorkRect.Min.x or window.DC.CursorPos.x) frame_bb.Min.x = span_all_columns and window.ParentWorkRect.Min.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanFullWidth) ~= 0 and window.WorkRect.Min.x or window.DC.CursorPos.x)
frame_bb.Min.y = window.DC.CursorPos.y + (text_offset_y - padding_y) frame_bb.Min.y = window.DC.CursorPos.y + (text_offset_y - padding_y)
frame_bb.Max.x = span_all_columns and window.ParentWorkRect.Max.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanLabelWidth) ~= 0 and window.DC.CursorPos.x + text_width + padding_x or window.WorkRect.Max.x) frame_bb.Max.x = span_all_columns and window.ParentWorkRect.Max.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanLabelWidth) ~= 0 and window.DC.CursorPos.x + text_width + padding_x or window.WorkRect.Max.x)
@@ -7852,12 +7885,13 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end)
frame_bb.Max.x = frame_bb.Max.x + outer_extend frame_bb.Max.x = frame_bb.Max.x + outer_extend
end end
local text_pos = ImVec2(window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y) local text_pos = TreeNode_text_pos -- [Luau] scratch
text_pos.x, text_pos.y = window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y
local item_size = LayoutHelpers_size; item_size.x = text_width; item_size.y = frame_height -- [Luau] scratch, ItemSize() only reads it local item_size = LayoutHelpers_size; item_size.x = text_width; item_size.y = frame_height -- [Luau] scratch, ItemSize() only reads it
ImGui.ItemSize(item_size, padding_y) ImGui.ItemSize(item_size, padding_y)
-- For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing -- For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
local interact_bb = ImRect() local interact_bb = TreeNode_interact_bb -- [Luau] scratch, ItemAdd()/ButtonBehavior()/SetNavID() copy or only read it
ImRect_Copy(interact_bb, frame_bb) ImRect_Copy(interact_bb, frame_bb)
if bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.SpanAvailWidth, ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.SpanLabelWidth, ImGuiTreeNodeFlags.SpanAllColumns)) == 0 then if bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.SpanAvailWidth, ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.SpanLabelWidth, ImGuiTreeNodeFlags.SpanAllColumns)) == 0 then
interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0 and (style.ItemSpacing.x * 2.0) or 0.0) interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0 and (style.ItemSpacing.x * 2.0) or 0.0)
@@ -8051,9 +8085,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end)
ImGui.TablePopBackgroundChannel() ImGui.TablePopBackgroundChannel()
end end
if bit32.band(flags, ImGuiTreeNodeFlags.Bullet) ~= 0 then if bit32.band(flags, ImGuiTreeNodeFlags.Bullet) ~= 0 then
ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) ImGui.RenderBullet(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col)
elseif not is_leaf then elseif not is_leaf then
ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 1.0) ImGui.RenderArrow(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 1.0)
else -- Leaf without bullet, left-adjusted text else -- Leaf without bullet, left-adjusted text
text_pos.x = text_pos.x - (text_offset_x - padding_x) text_pos.x = text_pos.x - (text_offset_x - padding_x)
end end
@@ -8074,9 +8108,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end)
ImGui.TablePopBackgroundChannel() ImGui.TablePopBackgroundChannel()
end end
if bit32.band(flags, ImGuiTreeNodeFlags.Bullet) ~= 0 then if bit32.band(flags, ImGuiTreeNodeFlags.Bullet) ~= 0 then
ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.5, text_pos.y + g.FontSize * 0.5), text_col) ImGui.RenderBullet(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x * 0.5, text_pos.y + g.FontSize * 0.5), text_col)
elseif not is_leaf then elseif not is_leaf then
ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.15), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 0.70) ImGui.RenderArrow(window.DrawList, TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.15), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 0.70)
end end
if g.LogEnabled then if g.LogEnabled then
ImGui.LogSetNextTextDecoration(">", nil) ImGui.LogSetNextTextDecoration(">", nil)
@@ -8084,7 +8118,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end)
end end
if draw_tree_lines then if draw_tree_lines then
ImGui.TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.5)) ImGui.TreeNodeDrawLineToChildNode(TreeNode_tmp_pos(text_pos.x - text_offset_x + padding_x, text_pos.y + g.FontSize * 0.5))
end end
-- Label -- Label
+13
View File
@@ -105,6 +105,7 @@ local STBRP__PREV_LINK_TYPE = {
--- @return stbrp_rect --- @return stbrp_rect
--- @nodiscard --- @nodiscard
@native
local function stbrp_rect() local function stbrp_rect()
return { return {
-- reserved for your use: -- reserved for your use:
@@ -128,6 +129,7 @@ end
--- @return stbrp_node --- @return stbrp_node
--- @nodiscard --- @nodiscard
@native
local function stbrp_node() local function stbrp_node()
return { return {
x = 0, x = 0,
@@ -149,6 +151,7 @@ end
--- @return stbrp_context --- @return stbrp_context
--- @nodiscard --- @nodiscard
@native
local function stbrp_context() local function stbrp_context()
return { return {
width = 0, width = 0,
@@ -171,6 +174,7 @@ end
--- @field prev_link_type? int --- @field prev_link_type? int
--- @return stbrp__findresult --- @return stbrp__findresult
@native
local function stbrp__findresult() local function stbrp__findresult()
return { return {
x = 0, x = 0,
@@ -191,6 +195,7 @@ end
-- If you call init again, this will be reset to the default. -- If you call init again, this will be reset to the default.
--- @param context stbrp_context --- @param context stbrp_context
--- @param heuristic int --- @param heuristic int
@native
local function stbrp_setup_heuristic(context, heuristic) local function stbrp_setup_heuristic(context, heuristic)
if context.init_mode == STBRP__INIT_skyline then if context.init_mode == STBRP__INIT_skyline then
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight or heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight) STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight or heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight)
@@ -205,6 +210,7 @@ end
-- If you call init again, this will be reset to the default (false). -- If you call init again, this will be reset to the default (false).
--- @param context stbrp_context --- @param context stbrp_context
--- @param allow_out_of_mem boolean --- @param allow_out_of_mem boolean
@native
local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem) local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem)
if allow_out_of_mem then if allow_out_of_mem then
-- if it's ok to run out of memory, then don't bother aligning them; -- if it's ok to run out of memory, then don't bother aligning them;
@@ -248,6 +254,7 @@ end
--- @param height int --- @param height int
--- @param nodes stbrp_node[] --- @param nodes stbrp_node[]
--- @param num_nodes int --- @param num_nodes int
@native
function stbrp_init_target(context, width, height, nodes, num_nodes) function stbrp_init_target(context, width, height, nodes, num_nodes)
for i = 1, num_nodes - 1 do for i = 1, num_nodes - 1 do
nodes[i].next = nodes[i + 1] nodes[i].next = nodes[i + 1]
@@ -278,6 +285,7 @@ end
--- @param x0 int --- @param x0 int
--- @param width int --- @param width int
--- @return int, int --- @return int, int
@native
local function stbrp__skyline_find_min_y(c, first, x0, width) local function stbrp__skyline_find_min_y(c, first, x0, width)
local node = first local node = first
local x1 = x0 + width local x1 = x0 + width
@@ -325,6 +333,7 @@ end
--- @param width int --- @param width int
--- @param height int --- @param height int
--- @return stbrp__findresult --- @return stbrp__findresult
@native
local function stbrp__skyline_find_best_pos(c, width, height) local function stbrp__skyline_find_best_pos(c, width, height)
local best_waste = bit32.lshift(1, 30) local best_waste = bit32.lshift(1, 30)
local best_x = 0 local best_x = 0
@@ -454,6 +463,7 @@ end
--- @param width int --- @param width int
--- @param height int --- @param height int
--- @return stbrp__findresult --- @return stbrp__findresult
@native
local function stbrp__skyline_pack_rectangle(context, width, height) local function stbrp__skyline_pack_rectangle(context, width, height)
-- find best position according to heuristic -- find best position according to heuristic
local res = stbrp__skyline_find_best_pos(context, width, height) local res = stbrp__skyline_find_best_pos(context, width, height)
@@ -522,6 +532,7 @@ end
--- @param b stbrp_rect --- @param b stbrp_rect
--- @return bool --- @return bool
--- @package --- @package
@native
local function rect_height_compare(a, b) local function rect_height_compare(a, b)
if a.h > b.h then if a.h > b.h then
return true return true
@@ -536,6 +547,7 @@ end
--- @param b stbrp_rect --- @param b stbrp_rect
--- @return bool --- @return bool
--- @package --- @package
@native
local function rect_original_order(a, b) local function rect_original_order(a, b)
return a.was_packed < b.was_packed return a.was_packed < b.was_packed
end end
@@ -567,6 +579,7 @@ end
--- @param rects stbrp_rect[] --- @param rects stbrp_rect[]
--- @param num_rects int --- @param num_rects int
--- @return int --- @return int
@native
local function stbrp_pack_rects(context, rects, num_rects) local function stbrp_pack_rects(context, rects, num_rects)
local all_rects_packed = 1 local all_rects_packed = 1
+170 -17
View File
@@ -168,7 +168,7 @@ local stbtt_MakeGlyphBitmapSubpixelPrefilter
local stbtt_GetFontVMetrics local stbtt_GetFontVMetrics
local stbtt__GetGlyphInfoT2 local stbtt__GetGlyphInfoT2
local stbtt__GetGlyphShapeT2 local stbtt__GetGlyphShapeT2
local stbtt_GetGlyphShape local stbtt_GetGlyphShape, stbtt_GetGlyphShapeUncached
local stbtt_GetGlyphBitmapBox local stbtt_GetGlyphBitmapBox
local stbtt_GetGlyphBitmapBoxSubpixel local stbtt_GetGlyphBitmapBoxSubpixel
local stbtt_GetGlyphHMetrics local stbtt_GetGlyphHMetrics
@@ -221,6 +221,7 @@ local trunc = function(x)
end end
end end
@native
local function STBTT__NOTUSED(_) return end local function STBTT__NOTUSED(_) return end
--- @alias stbtt_int32 int --- @alias stbtt_int32 int
@@ -243,6 +244,7 @@ local unsigned_char = stbtt_uint8
--- @param initial_offset? int --- @param initial_offset? int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__buf(initial_offset) local function stbtt__buf(initial_offset)
return { return {
data = nil, data = nil,
@@ -277,6 +279,7 @@ end
--- @field fdselect stbtt__buf # map from glyph to fontdict --- @field fdselect stbtt__buf # map from glyph to fontdict
--- @return stbtt_fontinfo --- @return stbtt_fontinfo
@native
function stbtt_fontinfo() function stbtt_fontinfo()
return { return {
data = nil, data = nil,
@@ -317,6 +320,7 @@ end
--- @return stbtt_vertex --- @return stbtt_vertex
--- @nodiscard --- @nodiscard
@native
local function stbtt_vertex() local function stbtt_vertex()
return { return {
x = nil, x = nil,
@@ -346,6 +350,7 @@ end
--- @return stbtt__csctx --- @return stbtt__csctx
--- @nodiscard --- @nodiscard
@native
local function stbtt__csctx() local function stbtt__csctx()
return { return {
bounds = false, bounds = false,
@@ -367,6 +372,7 @@ end
--- @param bounds bool --- @param bounds bool
--- @return stbtt__csctx --- @return stbtt__csctx
--- @nodiscard --- @nodiscard
@native
local function STBTT__CSCTX_INIT(bounds) local function STBTT__CSCTX_INIT(bounds)
local this = stbtt__csctx() local this = stbtt__csctx()
@@ -400,6 +406,7 @@ end
--- @return stbtt__edge --- @return stbtt__edge
--- @nodiscard --- @nodiscard
@native
local function stbtt__edge() local function stbtt__edge()
return { return {
x0 = nil, x0 = nil,
@@ -414,6 +421,7 @@ end
--- @return stbtt__active_edge --- @return stbtt__active_edge
--- @nodiscard --- @nodiscard
@native
local function stbtt__active_edge() local function stbtt__active_edge()
return { return {
next = nil, next = nil,
@@ -428,8 +436,15 @@ end
--- @return stbtt__active_edge --- @return stbtt__active_edge
--- @nodiscard --- @nodiscard
local active_pool, active_pool_n = {}, 0 -- [Luau] reused per stbtt__rasterize_sorted_edges() call (C: stbtt__hheap)
@native
local function stbtt__new_active(e, off_x, start_point) local function stbtt__new_active(e, off_x, start_point)
local z = stbtt__active_edge() active_pool_n = active_pool_n + 1
local z = active_pool[active_pool_n]
if z == nil then
z = stbtt__active_edge()
active_pool[active_pool_n] = z
end
local dxdy = (e.x1 - e.x0) / (e.y1 - e.y0) local dxdy = (e.x1 - e.x0) / (e.y1 - e.y0)
z.fdx = dxdy z.fdx = dxdy
@@ -453,6 +468,7 @@ end
--- @return stbtt__bitmap --- @return stbtt__bitmap
--- @nodiscard --- @nodiscard
@native
local function stbtt__bitmap() local function stbtt__bitmap()
return { return {
w = nil, w = nil,
@@ -468,6 +484,7 @@ end
--- @return stbtt__point --- @return stbtt__point
--- @nodiscard --- @nodiscard
@native
local function stbtt__point() return { x = nil, y = nil } end local function stbtt__point() return { x = nil, y = nil } end
---------------------------------------------- ----------------------------------------------
@@ -478,6 +495,7 @@ local function stbtt__point() return { x = nil, y = nil } end
--- ---
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__buf_get8(b) local function stbtt__buf_get8(b)
if b.cursor >= b.size then return 0 end if b.cursor >= b.size then return 0 end
local result = b.data[b.offset + b.cursor + 1] local result = b.data[b.offset + b.cursor + 1]
@@ -486,6 +504,7 @@ local function stbtt__buf_get8(b)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__buf_peek8(b) local function stbtt__buf_peek8(b)
if b.cursor >= b.size then return 0 end if b.cursor >= b.size then return 0 end
return b.data[b.offset + b.cursor + 1] return b.data[b.offset + b.cursor + 1]
@@ -493,6 +512,7 @@ end
--- @param b stbtt__buf --- @param b stbtt__buf
--- @param o int --- @param o int
@native
local function stbtt__buf_seek(b, o) local function stbtt__buf_seek(b, o)
STBTT_assert(not (o > b.size or o < 0)) STBTT_assert(not (o > b.size or o < 0))
if o > b.size or o < 0 then if o > b.size or o < 0 then
@@ -504,10 +524,12 @@ end
--- @param b stbtt__buf --- @param b stbtt__buf
--- @param o int --- @param o int
@native
local function stbtt__buf_skip(b, o) local function stbtt__buf_skip(b, o)
stbtt__buf_seek(b, b.cursor + o) stbtt__buf_seek(b, b.cursor + o)
end end
@native
local function stbtt__buf_get(b, n) local function stbtt__buf_get(b, n)
local v = 0 local v = 0
STBTT_assert(n >= 1 and n <= 4) STBTT_assert(n >= 1 and n <= 4)
@@ -522,6 +544,7 @@ end
--- @param offset? int --- @param offset? int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__new_buf(p, size, offset) local function stbtt__new_buf(p, size, offset)
local r = stbtt__buf(offset) local r = stbtt__buf(offset)
STBTT_assert(size < 0x40000000) STBTT_assert(size < 0x40000000)
@@ -532,8 +555,10 @@ local function stbtt__new_buf(p, size, offset)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__buf_get16(b) return stbtt__buf_get(b, 2) end local function stbtt__buf_get16(b) return stbtt__buf_get(b, 2) end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end
--- @param b stbtt__buf --- @param b stbtt__buf
@@ -541,6 +566,7 @@ local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end
--- @param s int --- @param s int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__buf_range(b, o, s) local function stbtt__buf_range(b, o, s)
local r = stbtt__new_buf(nil, 0) local r = stbtt__new_buf(nil, 0)
if (o < 0 or s < 0 or o > b.size or s > (b.size - o)) then if (o < 0 or s < 0 or o > b.size or s > (b.size - o)) then
@@ -553,6 +579,7 @@ local function stbtt__buf_range(b, o, s)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__cff_get_index(b) local function stbtt__cff_get_index(b)
local count, start, offsize local count, start, offsize
start = b.cursor start = b.cursor
@@ -567,6 +594,7 @@ local function stbtt__cff_get_index(b)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__cff_int(b) local function stbtt__cff_int(b)
local b0 = stbtt__buf_get8(b) local b0 = stbtt__buf_get8(b)
if b0 >= 32 and b0 <= 246 then return b0 - 139 if b0 >= 32 and b0 <= 246 then return b0 - 139
@@ -580,6 +608,7 @@ local function stbtt__cff_int(b)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__cff_skip_operand(b) local function stbtt__cff_skip_operand(b)
local v local v
local b0 = stbtt__buf_peek8(b) local b0 = stbtt__buf_peek8(b)
@@ -601,6 +630,7 @@ end
--- @param key int --- @param key int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__dict_get(b, key) local function stbtt__dict_get(b, key)
stbtt__buf_seek(b, 0) stbtt__buf_seek(b, 0)
while b.cursor < b.size do while b.cursor < b.size do
@@ -622,6 +652,7 @@ end
--- @param outcount int --- @param outcount int
--- @return int[] --- @return int[]
--- @nodiscard --- @nodiscard
@native
local function stbtt__dict_get_ints(b, key, outcount) local function stbtt__dict_get_ints(b, key, outcount)
local operands = stbtt__dict_get(b, key) local operands = stbtt__dict_get(b, key)
local out = {} local out = {}
@@ -633,6 +664,7 @@ local function stbtt__dict_get_ints(b, key, outcount)
end end
--- @param b stbtt__buf --- @param b stbtt__buf
@native
local function stbtt__cff_index_count(b) local function stbtt__cff_index_count(b)
stbtt__buf_seek(b, 0) stbtt__buf_seek(b, 0)
return stbtt__buf_get16(b) return stbtt__buf_get16(b)
@@ -642,6 +674,7 @@ end
--- @param i int --- @param i int
--- @return stbtt__buf --- @return stbtt__buf
--- @nodiscard --- @nodiscard
@native
local function stbtt__cff_index_get(b, i) local function stbtt__cff_index_get(b, i)
local count, offsize, start, _end local count, offsize, start, _end
stbtt__buf_seek(b, 0) stbtt__buf_seek(b, 0)
@@ -685,17 +718,26 @@ end
--- stbtt_GetNumberOfFonts_internal --- stbtt_GetNumberOfFonts_internal
--- stbtt__get_svg --- stbtt__get_svg
@native
local function ttUSHORT(p, offset) return stbtt_uint16(p[offset + 1] * 256 + p[offset + 2]) end local function ttUSHORT(p, offset) return stbtt_uint16(p[offset + 1] * 256 + p[offset + 2]) end
@native
local function ttSHORT(p, offset) return stbtt_int16(p[offset + 1] * 256 + p[offset + 2]) end local function ttSHORT(p, offset) return stbtt_int16(p[offset + 1] * 256 + p[offset + 2]) end
@native
local function ttULONG(p, offset) return stbtt_uint32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end local function ttULONG(p, offset) return stbtt_uint32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end
@native
local function ttLONG(p, offset) return stbtt_int32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end local function ttLONG(p, offset) return stbtt_int32(bit32.lshift(p[offset + 1], 24) + bit32.lshift(p[offset + 2], 16) + bit32.lshift(p[offset + 3], 8) + p[offset + 4]) end
@native
local function ttBYTE(p, offset) return stbtt_uint8(p[offset + 1]) end local function ttBYTE(p, offset) return stbtt_uint8(p[offset + 1]) end
@native
local function ttCHAR(p, offset) return stbtt_int8(p[offset + 1]) end local function ttCHAR(p, offset) return stbtt_int8(p[offset + 1]) end
@native
local function stbtt_tag4(p, c0, c1, c2, c3, offset) offset = offset or 0; return p[offset + 1] == c0 and p[offset + 2] == c1 and p[offset + 3] == c2 and p[offset + 4] == c3 end local function stbtt_tag4(p, c0, c1, c2, c3, offset) offset = offset or 0; return p[offset + 1] == c0 and p[offset + 2] == c1 and p[offset + 3] == c2 and p[offset + 4] == c3 end
@native
local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end local function stbtt_tag(p, str, offset) local c0, c1, c2, c3 = string.byte(str, 1, 4); return stbtt_tag4(p, c0, c1, c2, c3, offset) end
@native
local function stbtt__isfont(font) local function stbtt__isfont(font)
-- check the version number -- check the version number
if stbtt_tag4(font, 49, 0, 0, 0) then return true end -- TrueType 1 if stbtt_tag4(font, 49, 0, 0, 0) then return true end -- TrueType 1
@@ -707,6 +749,7 @@ local function stbtt__isfont(font)
end end
-- @OPTIMIZE: binary search -- @OPTIMIZE: binary search
@native
local function stbtt__find_table(data, font_start, tag) local function stbtt__find_table(data, font_start, tag)
local num_tables = ttUSHORT(data, font_start + 4) local num_tables = ttUSHORT(data, font_start + 4)
local tabledir = font_start + 12 local tabledir = font_start + 12
@@ -719,6 +762,7 @@ local function stbtt__find_table(data, font_start, tag)
return 0 return 0
end end
@native
local function stbtt_GetFontOffsetForIndex_internal(font_collection, index) local function stbtt_GetFontOffsetForIndex_internal(font_collection, index)
-- if it's just a font, there's only one valid index -- if it's just a font, there's only one valid index
if stbtt__isfont(font_collection) then if stbtt__isfont(font_collection) then
@@ -742,6 +786,7 @@ end
--- @param cff stbtt__buf --- @param cff stbtt__buf
--- @param fontdict stbtt__buf --- @param fontdict stbtt__buf
@native
local function stbtt__get_subrs(cff, fontdict) local function stbtt__get_subrs(cff, fontdict)
local private_loc = stbtt__dict_get_ints(fontdict, 18, 2) local private_loc = stbtt__dict_get_ints(fontdict, 18, 2)
if (private_loc[2] == 0 or private_loc[1] == 0) then if (private_loc[2] == 0 or private_loc[1] == 0) then
@@ -757,6 +802,7 @@ local function stbtt__get_subrs(cff, fontdict)
end end
--- @return bool --- @return bool
@native
local function stbtt_InitFont_internal(info, data, fontstart) local function stbtt_InitFont_internal(info, data, fontstart)
local cmap local cmap
local numTables local numTables
@@ -884,6 +930,7 @@ end
-- Returns 0 if the character codepoint is not defined in the font. -- Returns 0 if the character codepoint is not defined in the font.
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param unicode_codepoint int --- @param unicode_codepoint int
@native
function stbtt_FindGlyphIndex(info, unicode_codepoint) function stbtt_FindGlyphIndex(info, unicode_codepoint)
local data = info.data local data = info.data
local index_map = info.index_map local index_map = info.index_map
@@ -989,6 +1036,7 @@ end
--- @param y stbtt_int32 --- @param y stbtt_int32
--- @param cx stbtt_int32 --- @param cx stbtt_int32
--- @param cy stbtt_int32 --- @param cy stbtt_int32
@native
local function stbtt_setvertex(v, vtx_type, x, y, cx, cy) local function stbtt_setvertex(v, vtx_type, x, y, cx, cy)
v.type = vtx_type v.type = vtx_type
v.x = (stbtt_int16)(x) v.x = (stbtt_int16)(x)
@@ -997,6 +1045,7 @@ local function stbtt_setvertex(v, vtx_type, x, y, cx, cy)
v.cy = (stbtt_int16)(cy) v.cy = (stbtt_int16)(cy)
end end
@native
local function stbtt__GetGlyfOffset(info, glyph_index) local function stbtt__GetGlyfOffset(info, glyph_index)
STBTT_assert(info.cff.size == 0) STBTT_assert(info.cff.size == 0)
@@ -1017,6 +1066,7 @@ end
-- Gets the bounding box of the visible part of the glyph, in unscaled coordinates -- Gets the bounding box of the visible part of the glyph, in unscaled coordinates
--- @return integer, integer?, integer?, integer?, integer? --- @return integer, integer?, integer?, integer?, integer?
@native
local function stbtt_GetGlyphBox(info, glyph_index) local function stbtt_GetGlyphBox(info, glyph_index)
local n, x0, y0, x1, y1 local n, x0, y0, x1, y1
@@ -1045,6 +1095,7 @@ end
--- @param scy stbtt_int32 --- @param scy stbtt_int32
--- @param cx stbtt_int32 --- @param cx stbtt_int32
--- @param cy stbtt_int32 --- @param cy stbtt_int32
@native
local function stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy) local function stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy)
if start_off then if start_off then
if was_off then if was_off then
@@ -1069,6 +1120,7 @@ end
--- @param glyph_index int --- @param glyph_index int
--- @return int num_vertices --- @return int num_vertices
--- @return stbtt_vertex[]? vertices --- @return stbtt_vertex[]? vertices
@native
local function stbtt__GetGlyphShapeTT(info, glyph_index) local function stbtt__GetGlyphShapeTT(info, glyph_index)
local data = info.data local data = info.data
local num_vertices local num_vertices
@@ -1288,7 +1340,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index)
n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4]) n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4])
-- Get indexed glyph. -- Get indexed glyph.
comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx) comp_num_vertices, comp_verts = stbtt_GetGlyphShapeUncached(info, gidx) -- [Luau] transformed in place below: must be a fresh copy
if comp_num_vertices > 0 then if comp_num_vertices > 0 then
-- Transform vertices. -- Transform vertices.
for i = 1, comp_num_vertices do for i = 1, comp_num_vertices do
@@ -1326,6 +1378,7 @@ end
--- @param c stbtt__csctx --- @param c stbtt__csctx
--- @param x stbtt_int32 --- @param x stbtt_int32
--- @param y stbtt_int32 --- @param y stbtt_int32
@native
local function stbtt__track_vertex(c, x, y) local function stbtt__track_vertex(c, x, y)
if x > c.max_x or not c.started then c.max_x = x end if x > c.max_x or not c.started then c.max_x = x end
if y > c.max_y or not c.started then c.max_y = y end if y > c.max_y or not c.started then c.max_y = y end
@@ -1342,6 +1395,7 @@ end
--- @param cy stbtt_int32 --- @param cy stbtt_int32
--- @param cx1 stbtt_int32 --- @param cx1 stbtt_int32
--- @param cy1 stbtt_int32 --- @param cy1 stbtt_int32
@native
local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1) local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1)
if c.bounds then if c.bounds then
stbtt__track_vertex(c, x, y) stbtt__track_vertex(c, x, y)
@@ -1357,6 +1411,7 @@ local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1)
end end
--- @param ctx stbtt__csctx --- @param ctx stbtt__csctx
@native
local function stbtt__csctx_close_shape(ctx) local function stbtt__csctx_close_shape(ctx)
if ctx.first_x ~= ctx.x or ctx.first_y ~= ctx.y then if ctx.first_x ~= ctx.x or ctx.first_y ~= ctx.y then
stbtt__csctx_v(ctx, STBTT_VTX.LINE, trunc(ctx.first_x), trunc(ctx.first_y), 0, 0, 0, 0) stbtt__csctx_v(ctx, STBTT_VTX.LINE, trunc(ctx.first_x), trunc(ctx.first_y), 0, 0, 0, 0)
@@ -1366,6 +1421,7 @@ end
--- @param ctx stbtt__csctx --- @param ctx stbtt__csctx
--- @param dx float --- @param dx float
--- @param dy float --- @param dy float
@native
local function stbtt__csctx_rmove_to(ctx, dx, dy) local function stbtt__csctx_rmove_to(ctx, dx, dy)
stbtt__csctx_close_shape(ctx) stbtt__csctx_close_shape(ctx)
ctx.x = ctx.x + dx ctx.x = ctx.x + dx
@@ -1378,6 +1434,7 @@ end
--- @param ctx stbtt__csctx --- @param ctx stbtt__csctx
--- @param dx float --- @param dx float
--- @param dy float --- @param dy float
@native
local function stbtt__csctx_rline_to(ctx, dx, dy) local function stbtt__csctx_rline_to(ctx, dx, dy)
ctx.x = ctx.x + dx ctx.x = ctx.x + dx
ctx.y = ctx.y + dy ctx.y = ctx.y + dy
@@ -1391,6 +1448,7 @@ end
--- @param dy2 float --- @param dy2 float
--- @param dx3 float --- @param dx3 float
--- @param dy3 float --- @param dy3 float
@native
local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3) local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3)
local cx1 = ctx.x + dx1 local cx1 = ctx.x + dx1
local cy1 = ctx.y + dy1 local cy1 = ctx.y + dy1
@@ -1401,6 +1459,7 @@ local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3)
stbtt__csctx_v(ctx, STBTT_VTX.CUBIC, trunc(ctx.x), trunc(ctx.y), trunc(cx1), trunc(cy1), trunc(cx2), trunc(cy2)) stbtt__csctx_v(ctx, STBTT_VTX.CUBIC, trunc(ctx.x), trunc(ctx.y), trunc(cx1), trunc(cy1), trunc(cx2), trunc(cy2))
end end
@native
local function stbtt__get_subr(idx, n) local function stbtt__get_subr(idx, n)
local count = stbtt__cff_index_count(idx) local count = stbtt__cff_index_count(idx)
local bias = 107 local bias = 107
@@ -1416,6 +1475,7 @@ local function stbtt__get_subr(idx, n)
return stbtt__cff_index_get(idx, n) return stbtt__cff_index_get(idx, n)
end end
@native
local function stbtt__cid_get_glyph_subrs(info, glyph_index) local function stbtt__cid_get_glyph_subrs(info, glyph_index)
local fdselect = info.fdselect local fdselect = info.fdselect
local fdselector = -1 local fdselector = -1
@@ -1446,6 +1506,7 @@ end
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param glyph_index int --- @param glyph_index int
--- @param c stbtt__csctx --- @param c stbtt__csctx
@native
local function stbtt__run_charstring(info, glyph_index, c) local function stbtt__run_charstring(info, glyph_index, c)
local in_header = true local in_header = true
local maskbits = 0 local maskbits = 0
@@ -1719,6 +1780,7 @@ end
--- @param glyph_index int --- @param glyph_index int
--- @return int num_vertices --- @return int num_vertices
--- @return stbtt_vertex[]? vertices --- @return stbtt_vertex[]? vertices
@native
function stbtt__GetGlyphShapeT2(info, glyph_index) function stbtt__GetGlyphShapeT2(info, glyph_index)
-- runs the charstring twice, once to count and once to output (to avoid realloc) -- runs the charstring twice, once to count and once to output (to avoid realloc)
local vertices = nil local vertices = nil
@@ -1744,6 +1806,7 @@ end
--- @return int y0 --- @return int y0
--- @return int x1 --- @return int x1
--- @return int y1 --- @return int y1
@native
function stbtt__GetGlyphInfoT2(info, glyph_index) function stbtt__GetGlyphInfoT2(info, glyph_index)
local c = STBTT__CSCTX_INIT(true) local c = STBTT__CSCTX_INIT(true)
local r = stbtt__run_charstring(info, glyph_index, c) local r = stbtt__run_charstring(info, glyph_index, c)
@@ -1765,7 +1828,8 @@ end
-- its x,y, using cx,cy as the bezier control point. -- its x,y, using cx,cy as the bezier control point.
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param glyph_index int --- @param glyph_index int
function stbtt_GetGlyphShape(info, glyph_index) @native
function stbtt_GetGlyphShapeUncached(info, glyph_index)
if info.cff.size == 0 then if info.cff.size == 0 then
return stbtt__GetGlyphShapeTT(info, glyph_index) return stbtt__GetGlyphShapeTT(info, glyph_index)
else else
@@ -1773,11 +1837,32 @@ function stbtt_GetGlyphShape(info, glyph_index)
end end
end end
@native
function stbtt_GetGlyphShape(info, glyph_index)
-- [Luau] shapes don't depend on the size: cache them per font (baking a new size re-used to re-parse every glyph).
-- Callers only read the vertices (stbtt_FreeShape is a no-op).
local cache = info._ShapeCache
if cache == nil then cache = {}; info._ShapeCache = cache end
local e = cache[glyph_index]
if e == nil then
local n, v
if info.cff.size == 0 then
n, v = stbtt__GetGlyphShapeTT(info, glyph_index)
else
n, v = stbtt__GetGlyphShapeT2(info, glyph_index)
end
e = { n, v }
cache[glyph_index] = e
end
return e[1], e[2]
end
-- leftSideBearing is the offset from the current horizontal position to the left edge of the character -- leftSideBearing is the offset from the current horizontal position to the left edge of the character
-- advanceWidth is the offset from the current horizontal position to the next horizontal position -- advanceWidth is the offset from the current horizontal position to the next horizontal position
-- these are expressed in unscaled coordinates -- these are expressed in unscaled coordinates
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param glyph_index int --- @param glyph_index int
@native
function stbtt_GetGlyphHMetrics(info, glyph_index) function stbtt_GetGlyphHMetrics(info, glyph_index)
local numOfLongHorMetrics = ttUSHORT(info.data, info.hhea + 34) local numOfLongHorMetrics = ttUSHORT(info.data, info.hhea + 34)
@@ -1800,6 +1885,7 @@ end
-- these are expressed in unscaled coordinates, so you must multiply by -- these are expressed in unscaled coordinates, so you must multiply by
-- the scale factor for a given size -- the scale factor for a given size
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
@native
function stbtt_GetFontVMetrics(info) function stbtt_GetFontVMetrics(info)
local ascent = ttSHORT(info.data, info.hhea + 4) local ascent = ttSHORT(info.data, info.hhea + 4)
local descent = ttSHORT(info.data, info.hhea + 6) local descent = ttSHORT(info.data, info.hhea + 6)
@@ -1816,6 +1902,7 @@ end
-- so if you prefer to measure height by the ascent only, use a similar calculation. -- so if you prefer to measure height by the ascent only, use a similar calculation.
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param height float --- @param height float
@native
function stbtt_ScaleForPixelHeight(info, height) function stbtt_ScaleForPixelHeight(info, height)
local fheight = ttSHORT(info.data, info.hhea + 4) - ttSHORT(info.data, info.hhea + 6) local fheight = ttSHORT(info.data, info.hhea + 4) - ttSHORT(info.data, info.hhea + 6)
return height / fheight return height / fheight
@@ -1836,6 +1923,7 @@ end
--- @param scale_y float --- @param scale_y float
--- @param shift_x float --- @param shift_x float
--- @param shift_y float --- @param shift_y float
@native
function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, shift_y) function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, shift_y)
local n, x0, y0, x1, y1 = stbtt_GetGlyphBox(font, glyph) local n, x0, y0, x1, y1 = stbtt_GetGlyphBox(font, glyph)
@@ -1866,6 +1954,7 @@ end
--- @param glyph int --- @param glyph int
--- @param scale_x float --- @param scale_x float
--- @param scale_y float --- @param scale_y float
@native
function stbtt_GetGlyphBitmapBox(font, glyph, scale_x, scale_y) function stbtt_GetGlyphBitmapBox(font, glyph, scale_x, scale_y)
return stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0, 0.0) return stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0, 0.0)
end end
@@ -1893,6 +1982,7 @@ end
--- @param y0 float --- @param y0 float
--- @param x1 float --- @param x1 float
--- @param y1 float --- @param y1 float
@native
local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1) local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1)
if y0 == y1 then return end if y0 == y1 then return end
STBTT_assert(y0 < y1) STBTT_assert(y0 < y1)
@@ -1934,6 +2024,7 @@ end
--- @param height float --- @param height float
--- @param top_width float --- @param top_width float
--- @param bottom_width float --- @param bottom_width float
@native
local function stbtt__sized_trapezoid_area(height, top_width, bottom_width) local function stbtt__sized_trapezoid_area(height, top_width, bottom_width)
STBTT_assert(top_width >= 0) STBTT_assert(top_width >= 0)
STBTT_assert(bottom_width >= 0) STBTT_assert(bottom_width >= 0)
@@ -1945,12 +2036,14 @@ end
--- @param tx1 float --- @param tx1 float
--- @param bx0 float --- @param bx0 float
--- @param bx1 float --- @param bx1 float
@native
local function stbtt__position_trapezoid_area(height, tx0, tx1, bx0, bx1) local function stbtt__position_trapezoid_area(height, tx0, tx1, bx0, bx1)
return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0) return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0)
end end
--- @param height float --- @param height float
--- @param width float --- @param width float
@native
local function stbtt__sized_triangle_area(height, width) local function stbtt__sized_triangle_area(height, width)
return height * width / 2 return height * width / 2
end end
@@ -1960,6 +2053,7 @@ end
--- @param len int --- @param len int
--- @param e stbtt__active_edge --- @param e stbtt__active_edge
--- @param y_top float --- @param y_top float
@native
local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_top) local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_top)
local y_bottom = y_top + 1 local y_bottom = y_top + 1
@@ -2182,11 +2276,14 @@ end
--- @param vsubsample int --- @param vsubsample int
--- @param off_x int --- @param off_x int
--- @param off_y int --- @param off_y int
local rasterize_scanline, rasterize_scanline2 = {}, {} -- [Luau] reused: fully cleared per scanline below
@native
local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y)
local active = nil local active = nil
local scanline = {} -- [Port] size = result.w, 0-based active_pool_n = 0 -- every active edge of the previous call is dead
local scanline2 = {} -- [Port] size = result.w + 1, 0-based local scanline = rasterize_scanline -- [Port] size = result.w, 0-based
local scanline2 = rasterize_scanline2 -- [Port] size = result.w + 1, 0-based
STBTT__NOTUSED(vsubsample) STBTT__NOTUSED(vsubsample)
@@ -2244,20 +2341,18 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of
do do
local sum = 0 local sum = 0
local pixels, base = result.pixels, j * result.stride + 1
for i = 0, result.w - 1 do for i = 0, result.w - 1 do
local k
local m
sum = sum + scanline2[i] sum = sum + scanline2[i]
k = scanline[i] + sum -- [Luau] k >= 0: trunc == floor, and m is already 0..255 (unsigned_char() is a no-op)
k = STBTT_fabs(k) * 255 + 0.5 local m = math.floor(math.abs(scanline[i] + sum) * 255 + 0.5)
m = trunc(k)
if m > 255 then m = 255 end if m > 255 then m = 255 end
result.pixels[j * result.stride + i + 1] = unsigned_char(m) pixels[base + i] = m
end end
end end
-- advance all the edges -- advance all the edges
step = active local step = active
while step do while step do
step.fx = step.fx + step.fdx -- advance to position for current scanline step.fx = step.fx + step.fdx -- advance to position for current scanline
step = step.next -- advance through list step = step.next -- advance through list
@@ -2277,10 +2372,47 @@ local STBTT__COMPARE = function(a, b)
end end
--- @param p stbtt__edge[] --- @param p stbtt__edge[]
@native
local function stbtt__sort_edges(p) local function stbtt__sort_edges(p)
STBTT_sort(p, STBTT__COMPARE) STBTT_sort(p, STBTT__COMPARE)
end end
-- [Luau] sorts p[lo..hi] by y0 without a comparator callback (like upstream's stbtt__sort_edges_quicksort + ins_sort)
@native
local function stbtt__sort_edges_range(p, lo, hi)
while hi - lo > 12 do
-- median of three -> p[lo]
local m = math.floor((lo + hi) / 2)
local a, b, c = p[lo], p[m], p[hi]
if b.y0 < a.y0 then a, b = b, a end
if c.y0 < b.y0 then b, c = c, b; if b.y0 < a.y0 then a, b = b, a end end
p[lo], p[m], p[hi] = b, a, c
local pivot = p[lo].y0
local i, j = lo + 1, hi
while true do
while p[i].y0 < pivot do i = i + 1 end
while pivot < p[j].y0 do j = j - 1 end
if i >= j then break end
p[i], p[j] = p[j], p[i]
i = i + 1; j = j - 1
end
p[lo], p[j] = p[j], p[lo]
-- recurse into the smaller side, loop on the larger
if j - lo < hi - j then
stbtt__sort_edges_range(p, lo, j - 1); lo = j + 1
else
stbtt__sort_edges_range(p, j + 1, hi); hi = j - 1
end
end
for i = lo + 1, hi do
local t = p[i]
local y = t.y0
local j = i - 1
while j >= lo and p[j].y0 > y do p[j + 1] = p[j]; j = j - 1 end
p[j + 1] = t
end
end
--- @param result stbtt__bitmap --- @param result stbtt__bitmap
--- @param pts stbtt__point[] --- @param pts stbtt__point[]
--- @param wcount int[] --- @param wcount int[]
@@ -2292,6 +2424,8 @@ end
--- @param off_x int --- @param off_x int
--- @param off_y int --- @param off_y int
--- @param invert bool --- @param invert bool
local rasterize_edges = {}
@native
local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert) local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert)
local y_scale_inv = (invert) and -scale_y or scale_y local y_scale_inv = (invert) and -scale_y or scale_y
local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2 local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2
@@ -2303,7 +2437,13 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y,
n = n + wcount[i] n = n + wcount[i]
end end
local e = {} for i = 1, n + 1 do e[i] = stbtt__edge() end -- add an extra one as a sentinel -- [Luau] edges reused across calls; unused entries are sentinels (y0 = nil) like the unfilled ones upstream
local e = rasterize_edges
for i = 1, n + 1 do
local ed = e[i]
if ed == nil then e[i] = stbtt__edge() else ed.y0 = nil; ed.invert = false end
end
for i = n + 2, #e do e[i].y0 = nil end
n = 0 n = 0
local m = 0 local m = 0
@@ -2347,7 +2487,7 @@ local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y,
end end
-- now sort the edges by their highest point (should snap to integer, and then by x) -- now sort the edges by their highest point (should snap to integer, and then by x)
stbtt__sort_edges(e) stbtt__sort_edges_range(e, 1, n) -- [Luau] e[n + 1..] are y0 == nil sentinels, already last
-- now, traverse the scanlines and find the intersections on each scanline, use xor winding rule -- now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y) stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y)
@@ -2357,6 +2497,7 @@ end
--- @param n int --- @param n int
--- @param x float --- @param x float
--- @param y float --- @param y float
@native
local function stbtt__add_point(points, n, x, y) local function stbtt__add_point(points, n, x, y)
if points == nil then return end -- during first pass, it's unallocated if points == nil then return end -- during first pass, it's unallocated
points[n + 1].x = x points[n + 1].x = x
@@ -2375,6 +2516,7 @@ end
--- @param objspace_flatness_squared float --- @param objspace_flatness_squared float
--- @param n int --- @param n int
--- @return int num_points # updated num_points passed in --- @return int num_points # updated num_points passed in
@native
local function stbtt__tesselate_curve(points, num_points, x0, y0, x1, y1, x2, y2, objspace_flatness_squared, n) local function stbtt__tesselate_curve(points, num_points, x0, y0, x1, y1, x2, y2, objspace_flatness_squared, n)
-- midpoint -- midpoint
local mx = (x0 + 2 * x1 + x2) / 4 local mx = (x0 + 2 * x1 + x2) / 4
@@ -2411,6 +2553,7 @@ end
--- @param objspace_flatness_squared float --- @param objspace_flatness_squared float
--- @param n int --- @param n int
--- @return int num_points # updated num_points passed in --- @return int num_points # updated num_points passed in
@native
local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n) local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n)
-- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough -- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough
local dx0 = x1 - x0 local dx0 = x1 - x0
@@ -2462,6 +2605,8 @@ end
--- @return stbtt__point[]? points --- @return stbtt__point[]? points
--- @return int? num_contours --- @return int? num_contours
--- @return int[]? contour_lengths --- @return int[]? contour_lengths
local flatten_points = {}
@native
local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
local points = nil local points = nil
local num_points = 0 local num_points = 0
@@ -2486,8 +2631,8 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
for pass = 0, 1 do for pass = 0, 1 do
local x, y = 0, 0 local x, y = 0, 0
if pass == 1 then if pass == 1 then
points = {} points = flatten_points -- [Luau] reused across calls (only [1..num_points] is read)
for i = 1, num_points do points[i] = stbtt__point() end for i = #points + 1, num_points do points[i] = stbtt__point() end
end end
num_points = 0 num_points = 0
n = -1 n = -1
@@ -2544,6 +2689,7 @@ end
--- @param x_off int --- @param x_off int
--- @param y_off int --- @param y_off int
--- @param invert bool --- @param invert bool
@native
local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert) local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert)
local scale = (scale_x > scale_y) and scale_y or scale_x local scale = (scale_x > scale_y) and scale_y or scale_x
@@ -2571,6 +2717,7 @@ end
--- @param shift_x float --- @param shift_x float
--- @param shift_y float --- @param shift_y float
--- @param glyph int --- @param glyph int
@native
local function stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, glyph) local function stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, glyph)
local num_verts, vertices = stbtt_GetGlyphShape(info, glyph) local num_verts, vertices = stbtt_GetGlyphShape(info, glyph)
local gbm = stbtt__bitmap() local gbm = stbtt__bitmap()
@@ -2624,6 +2771,7 @@ local STBTT__OVER_MASK = STBTT_MAX_OVERSAMPLE - 1
--- @param h int --- @param h int
--- @param stride_in_bytes int --- @param stride_in_bytes int
--- @param kernel_width unsigned_int --- @param kernel_width unsigned_int
@native
local function stbtt__h_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local function stbtt__h_prefilter(pixels, w, h, stride_in_bytes, kernel_width)
local buffer = {} local buffer = {}
local safe_w = w - kernel_width local safe_w = w - kernel_width
@@ -2653,6 +2801,7 @@ end
--- @param h int --- @param h int
--- @param stride_in_bytes int --- @param stride_in_bytes int
--- @param kernel_width unsigned_int --- @param kernel_width unsigned_int
@native
local function stbtt__v_prefilter(pixels, w, h, stride_in_bytes, kernel_width) local function stbtt__v_prefilter(pixels, w, h, stride_in_bytes, kernel_width)
local buffer = {} local buffer = {}
local safe_h = h - kernel_width local safe_h = h - kernel_width
@@ -2679,6 +2828,7 @@ end
--- @param oversample int --- @param oversample int
--- @return float --- @return float
@native
local function stbtt__oversample_shift(oversample) local function stbtt__oversample_shift(oversample)
if oversample == 0 then if oversample == 0 then
return 0.0 return 0.0
@@ -2705,6 +2855,7 @@ end
--- @param prefilter_x int --- @param prefilter_x int
--- @param prefilter_y int --- @param prefilter_y int
--- @param glyph int --- @param glyph int
@native
function stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, prefilter_x, prefilter_y, glyph) function stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, prefilter_x, prefilter_y, glyph)
stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph) stbtt_MakeGlyphBitmapSubpixel(info, output, out_w - (prefilter_x - 1), out_h - (prefilter_y - 1), out_stride, scale_x, scale_y, shift_x, shift_y, glyph)
@@ -2758,6 +2909,7 @@ end
-- return '0' for index 0, and -1 for all other indices. -- return '0' for index 0, and -1 for all other indices.
--- @param data table --- @param data table
--- @param index int --- @param index int
@native
function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end
-- Given an offset into the file that defines a font, this function builds -- Given an offset into the file that defines a font, this function builds
@@ -2768,6 +2920,7 @@ function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForI
--- @param info stbtt_fontinfo --- @param info stbtt_fontinfo
--- @param data table --- @param data table
--- @param offset int --- @param offset int
@native
function stbtt_InitFont(info, data, offset) return stbtt_InitFont_internal(info, data, offset) end function stbtt_InitFont(info, data, offset) return stbtt_InitFont_internal(info, data, offset) end
return { return {
+2
View File
@@ -31,6 +31,7 @@ CHECKS=(
"passthru|PASSTHRU OK|$R --main tools/test/scripts/t_passthru.luau --frames 40" "passthru|PASSTHRU OK|$R --main tools/test/scripts/t_passthru.luau --frames 40"
"fonts|FONTS OK|$R --main tools/test/scripts/t_fonts.luau --frames 8" "fonts|FONTS OK|$R --main tools/test/scripts/t_fonts.luau --frames 8"
"textproxy|PROXY OK|$R --main tools/test/scripts/t_textproxy.luau --frames 30" "textproxy|PROXY OK|$R --main tools/test/scripts/t_textproxy.luau --frames 30"
"textproxy_custom|CUSTOM PROXY OK|$R --main tools/test/scripts/t_textproxy_custom.luau --frames 15"
"style_editor|SE OK|$R --main tools/test/scripts/t_style_editor.luau --frames 20" "style_editor|SE OK|$R --main tools/test/scripts/t_style_editor.luau --frames 20"
"style_leak|STYLE OK|$R --main tools/test/scripts/t_style_leak.luau --frames 60 --open" "style_leak|STYLE OK|$R --main tools/test/scripts/t_style_leak.luau --frames 60 --open"
"apps|APPS OK|$R --main tools/test/scripts/t_apps.luau --frames 120 --open" "apps|APPS OK|$R --main tools/test/scripts/t_apps.luau --frames 120 --open"
@@ -38,6 +39,7 @@ CHECKS=(
"demo_open|DRAWHASH|$R --main tools/test/scripts/t_drawhash.luau --frames 150 --open" "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" "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" "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"
"rect_flip|RECTFLIP OK|$R --main tools/test/scripts/t_rect_flip.luau --frames 30"
"tile_bound|TILEBOUND OK|$R --main tools/test/scripts/t_tile_bound.luau --frames 200" "tile_bound|TILEBOUND OK|$R --main tools/test/scripts/t_tile_bound.luau --frames 200"
"parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 500" "parallel|PARALLEL OK|$R --main tools/test/scripts/t_parallel.luau --frames 500"
"pool_ctx|POOLCTX OK|$R --main tools/test/scripts/t_pool_ctx.luau --frames 60" "pool_ctx|POOLCTX OK|$R --main tools/test/scripts/t_pool_ctx.luau --frames 60"
+1
View File
@@ -192,6 +192,7 @@ ROBLOX = setmetatable({
}, { __index = realG }) }, { __index = realG })
local mod = newInst("ModuleScript", "ImGui", ReplicatedStorage); rawset(mod, "_src", "ImGui.luau") local mod = newInst("ModuleScript", "ImGui", ReplicatedStorage); rawset(mod, "_src", "ImGui.luau")
for _, name in EXTRA_MODULES or {} do rawset(newInst("ModuleScript", name, ReplicatedStorage), "_src", name) end
-- Run main.lua as a LocalScript -- Run main.lua as a LocalScript
local main = loadAsScript("main.client.luau", newInst("LocalScript", "main")) local main = loadAsScript("main.client.luau", newInst("LocalScript", "main"))
main() main()
+5
View File
@@ -24,6 +24,10 @@ def build_run(args, flags):
out.append("SOURCE_FNS[%r] = function(%s)\n%s\nend" % (key, G, s)) out.append("SOURCE_FNS[%r] = function(%s)\n%s\nend" % (key, G, s))
add("ImGui.luau", os.path.join(TMP, "ImGui.luau")) add("ImGui.luau", os.path.join(TMP, "ImGui.luau"))
add("main.client.luau", args.main) add("main.client.luau", args.main)
for m in args.module: # [extensions] NAME=path -> ReplicatedStorage.NAME ModuleScript
name, path = m.split("=", 1)
add(name, path)
out.append("EXTRA_MODULES = {%s}" % ",".join(repr(m.split("=", 1)[0]) for m in args.module))
out.append(open(os.path.join(HERE, "roblox_mock.luau")).read()) out.append(open(os.path.join(HERE, "roblox_mock.luau")).read())
global OFFSET, LAST_LINE, STRIPPED global OFFSET, LAST_LINE, STRIPPED
bundle = open(os.path.join(TMP, "ImGui.luau")).read() bundle = open(os.path.join(TMP, "ImGui.luau")).read()
@@ -66,6 +70,7 @@ def main():
ap.add_argument("--profile", action="store_true", help="sampling profile (no codegen) -> profile.out; see tools/test/prof.py") ap.add_argument("--profile", action="store_true", help="sampling profile (no codegen) -> profile.out; see tools/test/prof.py")
ap.add_argument("--open", action="store_true", help="force all CollapsingHeader/TreeNode open") ap.add_argument("--open", action="store_true", help="force all CollapsingHeader/TreeNode open")
ap.add_argument("--timeout", type=int, default=120) ap.add_argument("--timeout", type=int, default=120)
ap.add_argument("--module", action="append", default=[], help="NAME=path: extra ModuleScript in ReplicatedStorage (extension repos)")
ap.add_argument("--quiet", action="store_true", help="no random input (scripted tests drive io themselves)") ap.add_argument("--quiet", action="store_true", help="no random input (scripted tests drive io themselves)")
args = ap.parse_args() args = ap.parse_args()
+89
View File
@@ -0,0 +1,89 @@
-- Reversed rects (min > max, e.g. box-select dragged up/left) must draw like upstream's GPU path:
-- AddRectFilled + AddRect from each of the 4 drag directions composite to identical, non-blank pixels.
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 W, H = 1280, 760
local function composite(gui)
local screen = buffer.create(W * H * 3)
local function walk(inst, ox, oy, kx0, ky0, kx1, ky1)
local kids = inst:GetChildren()
table.sort(kids, function(a, b) return (a.ZIndex or 1) < (b.ZIndex or 1) end)
for _, c in ipairs(kids) do
if c.Visible ~= false then
local x, y = ox + (c.Position and c.Position.X or 0), oy + (c.Position and c.Position.Y or 0)
local cx0, cy0, cx1, cy1 = kx0, ky0, kx1, ky1
if c.ClipsDescendants then
cx0, cy0 = math.max(cx0, x), math.max(cy0, y)
cx1, cy1 = math.min(cx1, x + c.Size.X), math.min(cy1, y + c.Size.Y)
end
if c.ClassName == "ImageLabel" then
local img = c.ImageContent.Object
local px, sz = img.Pixels, img.Size.X
for ty = 0, sz - 1 do
local sy = y + ty
if sy >= cy0 and sy < cy1 then
for tx = 0, sz - 1 do
local sx = x + tx
if sx >= cx0 and sx < cx1 then
local o = (ty * sz + tx) * 4
local a = buffer.readu8(px, o + 3)
if a > 0 then
local d = (sy * W + sx) * 3
local fa = a / 255
for ch = 0, 2 do
local v = buffer.readu8(px, o + ch) * fa + buffer.readu8(screen, d + ch) * (1 - fa)
buffer.writeu8(screen, d + ch, math.floor(v + 0.5))
end
end
end
end
end
end
end
walk(c, x, y, cx0, cy0, cx1, cy1)
end
end
end
walk(gui, 0, 0, 0, 0, W, H)
local h = 0
for i = 0, W * H * 3 - 4, 4 do h = (h * 31 + buffer.readu32(screen, i)) % 2147483647 end
return h
end
local A, B = ImVec2(200, 150), ImVec2(520, 400) -- drag start/end, down-right
local DIRS = { "none", "dr", "ul", "ur", "dl" }
local CORNERS = {
dr = { A, B }, ul = { B, A },
ur = { ImVec2(A.x, B.y), ImVec2(B.x, A.y) }, dl = { ImVec2(B.x, A.y), ImVec2(A.x, B.y) },
}
local di, pf, res = 1, 0, {}
game:GetService("RunService").Stepped:Connect(function()
local d = DIRS[di]
if not d then return end
pf += 1
G.ImGui_ImplRoblox.NewFrame()
io.DeltaTime = 1 / 60
ImGui.NewFrame()
local c = CORNERS[d]
if c then
local dl = ImGui.GetForegroundDrawList()
dl:AddRectFilled(c[1], c[2], 0x6496FF32)
dl:AddRect(c[1], c[2], 0xFFFF9664, 0, 2)
dl:AddRectFilled(c[1], c[2], 0xFF00FF00, 12) -- rounded too
end
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if pf == 4 then
res[d] = composite(game:GetService("Players").LocalPlayer.PlayerGui:FindFirstChild("ImGui"))
print("RECT", d, res[d])
di += 1; pf = 0
if not DIRS[di] then
local ok = res.dr ~= res.none and res.ul == res.dr and res.ur == res.dr and res.dl == res.dr
print(ok and "RECTFLIP OK" or "RECTFLIP MISMATCH")
end
end
end)
+1 -1
View File
@@ -64,7 +64,7 @@ game:GetService("RunService").Stepped:Connect(function()
assert(st.TextLen == 0, "backspace should delete imgui's whole selection, len " .. st.TextLen) assert(st.TextLen == 0, "backspace should delete imgui's whole selection, len " .. st.TextLen)
print("BACKSPACE OK") print("BACKSPACE OK")
end end
if f == 27 then if f == 30 then -- (key-code fallback waits a few frames for the TextBox first)
local st = ImGui.GetCurrentContext().InputTextState local st = ImGui.GetCurrentContext().InputTextState
local got = G.ImGui._ByteArrayToString(st.TextA.Data, 1, st.TextLen + 1) local got = G.ImGui._ByteArrayToString(st.TextA.Data, 1, st.TextLen + 1)
assert(got:find("z"), "key fallback while proxy focused: " .. got) assert(got:find("z"), "key fallback while proxy focused: " .. got)
@@ -0,0 +1,31 @@
-- Text proxy for a custom widget (no ActiveId): it sets PlatformImeData.WantTextInput/SelectedText while its window is focused.
local G = require(game:GetService("ReplicatedStorage"):WaitForChild("ImGui"))
local ImGui, ImVec2 = G.ImGui, G.ImVec2
local UIS = game:GetService("UserInputService")
ImGui.CreateContext(); G.ImGui_ImplRoblox.Init(); G.ImGui_ImplRoblox.SetTextProxy(true)
local io = ImGui.GetIO()
local got, proxy, f = "", nil, 0
game:GetService("RunService").Stepped:Connect(function()
f += 1
G.ImGui_ImplRoblox.NewFrame()
proxy = proxy or game:GetService("Players").LocalPlayer.PlayerGui.ImGui.TextProxy
if f == 3 then io:AddMousePosEvent(60, 45); io:AddMouseButtonEvent(0, true) end
if f == 4 then io:AddMouseButtonEvent(0, false) end
if f == 8 then assert(UIS:GetFocusedTextBox() == proxy, "proxy focused"); proxy.Text = "x" end
ImGui.NewFrame()
ImGui.SetNextWindowPos(ImVec2(10, 10)); ImGui.SetNextWindowSize(ImVec2(300, 100))
ImGui.Begin("Editor")
if ImGui.IsWindowFocused() then
local ime = ImGui.GetCurrentContext().PlatformImeData
ime.WantTextInput = true; ime.SelectedText = "abc"
local q = io.InputQueueCharacters
for i = 1, q.Size do got ..= utf8.char(q.Data[i]) end
end
ImGui.End()
ImGui.Render(); G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
if f == 12 then
assert(got == "x", "widget got: " .. got)
assert(proxy.Text == "abc", "mirror: " .. proxy.Text)
print("CUSTOM PROXY OK")
end
end)
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "4dbug/imgui-luau" name = "4dbug/imgui-luau"
version = "0.4.0" version = "0.4.2"
registry = "https://github.com/UpliftGames/wally-index" registry = "https://github.com/UpliftGames/wally-index"
realm = "shared" realm = "shared"
license = "MIT" license = "MIT"