Files
imgui-luau/tools/test/run.luau
T

36491 lines
1.5 MiB
Plaintext

--!native
--!optimize 2
ARG_FRAMES=200; ARG_BIG=false; ARG_OPEN=true;
local SOURCE_FNS = {}
SOURCE_FNS['ImGui.luau'] = function(game, workspace, Instance, Enum, Vector2, Vector3, UDim2, Color3, Content, warn, require, script, os)
-- GENERATED by tools/bundle.py from imgui/*.lua - do not edit
local __FILES, __LOADED = {}, {}
function IM_INCLUDE(name)
local r = __LOADED[name]
if r == nil then r = __FILES[name](); if r == nil then r = true end; __LOADED[name] = r end
return r
end
__FILES['imgui.lua'] = function()
--- ImGui Sincerely WIP
-- (Core Code)
--- Flags:
-- IMGUI_DISABLE_OBSOLETE_FUNCTIONS = true -- This flag is not implemented
-- NOTE: you must implement ImStd.ImFileOpen if you are not in GMod
IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS = true -- Don't implement ImStd.ImFileOpen/ImStd.ImFileClose/ImStd.ImFileRead/ImFileWrite so you can implement them yourself
IMGUI_DISABLE_DEBUG_TOOLS = false -- Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty
--- @type ImGuiContext?
local GImGui = nil
ImGui = {}
ImStd = {} -- Contains functions that originally don't belong to cpp namespaces
-- IM_INCLUDE(name) is provided by the bundle (see tools/bundle.py): runs the bundled file once, returns its result.
function ImGui._GetTypeFunc() return type end
local function LUA_TableConstructorWrapper(T, size, userdata)
local p = {}
for i = 1, size do p[i] = T() end
return p
end
local GImAllocatorAllocFunc = LUA_TableConstructorWrapper
local GImAllocatorFreeFunc = function(p0, p1, p2) end
local GImAllocatorUserData = nil
--- @param constructor function
--- @param size int
function ImGui.MemAlloc(constructor, size)
local p = GImAllocatorAllocFunc(constructor, size, GImAllocatorUserData)
local ctx = GImGui
if ctx then
ImGui.DebugAllocHook(ctx.DebugAllocInfo, ctx.FrameCount, p, size)
end
return p
end
-- This does not set `owner[field]` to nil!
--- @param owner table
--- @param field string|int
function ImGui.MemFree(owner, field)
if owner ~= nil then
local ctx = GImGui
if ctx then
ImGui.DebugAllocHook(ctx.DebugAllocInfo, ctx.FrameCount, owner, -1)
end
end
return GImAllocatorFreeFunc(owner, field, GImAllocatorUserData)
end
--- @param info ImGuiDebugAllocInfo
--- @param frame_count int
--- @param ptr table
--- @param size size_t
function ImGui.DebugAllocHook(info, frame_count, ptr, size)
local entry = info.LastEntriesBuf[info.LastEntriesIdx]
if entry.FrameCount ~= frame_count then
info.LastEntriesIdx = info.LastEntriesIdx % (#info.LastEntriesBuf) + 1
entry = info.LastEntriesBuf[info.LastEntriesIdx]
entry.FrameCount = frame_count
entry.AllocCount = 0
entry.FreeCount = 0
end
if size ~= -1 then
-- print(string.format("[%05d] MemAlloc(%d) -> %p", frame_count, size, ptr))
entry.AllocCount = entry.AllocCount + 1
info.TotalAllocCount = info.TotalAllocCount + 1
else
-- print(string.format("[%05d] MemFree(%p)", frame_count, ptr))
entry.FreeCount = entry.FreeCount + 1
info.TotalFreeCount = info.TotalFreeCount + 1
end
end
IM_INCLUDE"imgui_h.lua"
IM_INCLUDE"imgui_internal.lua"
IM_INCLUDE"imgui_draw.lua"
IM_INCLUDE"imgui_widgets.lua"
IM_INCLUDE"imgui_tables.lua"
local IMGUI_DEBUG_NAV_SCORING = false
local IMGUI_DEBUG_NAV_RECTS = false
local FONT_DEFAULT_SIZE_BASE = 20
local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04
local WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70
local TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10) -- Multiplied by g.Style.MouseCursorScale
local TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20) -- Multiplied by g.Style.MouseCursorScale
local TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5, 1.0) -- Multiplied by g.Style.MouseCursorScale
local IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111
local string = string
ImFormatString = string.format -- TODO: an simplified version that operates on byte tables directly?
--- @module "imstd_minstdio"
ImStd.sscanf = IM_INCLUDE"imstd_minstdio.lua"
local math = math
local bit32 = bit32
---------------------------------------------------------------------------------------
-- [SECTION] MISC HELPERS/UTILITIES (File functions)
---------------------------------------------------------------------------------------
--- This closes the _file.
--- @param _file any # File object
function IM_FILE_CLOSE(_file) end
--- This returns the size of _file in bytes.
--- @param _file any # File object
--- @return int
function IM_FILE_SIZE(_file) return -1 end
--- This writes _str into _file.
--- @param _file any # File object
--- @param _str string
function IM_FILE_WRITE(_file, _str) end
--- This reads the specified _count of chars and returns them as a binary string.
--- @param _file any # File object
--- @param _count int
--- @return string
function IM_FILE_READ(_file, _count) return "" end
--- This opens the file at _filename in _mode and returns the File object.
--- @param _filename string
--- @param _mode string # e.g. "rb"
--- @return any
function ImStd.ImFileOpen(_filename, _mode) end
--- [GMod] Platform specific
if gmod then
IM_FILE_CLOSE = FindMetaTable("File").Close --- @type function
IM_FILE_SIZE = FindMetaTable("File").Size --- @type function
IM_FILE_WRITE = FindMetaTable("File").Write --- @type function
IM_FILE_READ = FindMetaTable("File").Read --- @type function
end
if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then
--- [GMod] Another Platform specific
if gmod then
function ImStd.ImFileOpen(filename, mode) return file.Open(filename, mode, "GAME") end
end
function ImStd.ImFileClose(f) IM_FILE_CLOSE(f) end
function ImStd.ImFileGetSize(f) return IM_FILE_SIZE(f) end
--- @param f any # File object
--- @param data table # 1-based table to store result data
--- @param count int # Amount of bytes to read from `f`
function ImStd.ImFileRead(f, data, count)
local CHUNK_SIZE = 8000 -- We don't read byte by byte
local offset = 0
while offset < count do
local read_size = math.min(CHUNK_SIZE, count - offset)
local str = IM_FILE_READ(f, read_size)
local bytes = {string.byte(str, 1, read_size)}
for i = 1, read_size do
data[offset + i] = bytes[i]
end
offset = offset + read_size
end
end
--- @param filename string
--- @param mode string
--- @return table?, integer?
function ImStd.ImFileLoadToMemory(filename, mode)
local f = ImStd.ImFileOpen(filename, mode)
if not f then return end
local file_size = ImStd.ImFileGetSize(f)
if file_size <= 0 then
ImStd.ImFileClose(f)
return
end
local file_data = {}
ImStd.ImFileRead(f, file_data, file_size)
if #file_data == 0 then
ImStd.ImFileClose(f)
return
end
ImStd.ImFileClose(f)
return file_data, file_size
end
end
--- Forward Declarations
local CalcNextScrollFromScrollTargetAndClamp
local MT = ImGui.GetMetatables()
--- @param scale_factor float
function MT.ImGuiStyle:ScaleAllSizes(scale_factor)
self._MainScale = self._MainScale * scale_factor
self.WindowPadding = ImTrunc(self.WindowPadding * scale_factor)
self.WindowRounding = ImTrunc(self.WindowRounding * scale_factor)
self.WindowBorderSize = ImTrunc(self.WindowBorderSize * scale_factor)
self.WindowMinSize = ImTrunc(self.WindowMinSize * scale_factor)
self.WindowBorderHoverPadding = ImTrunc(self.WindowBorderHoverPadding * scale_factor)
self.ChildRounding = ImTrunc(self.ChildRounding * scale_factor)
self.ChildBorderSize = ImTrunc(self.ChildBorderSize * scale_factor)
self.PopupRounding = ImTrunc(self.PopupRounding * scale_factor)
self.PopupBorderSize = ImTrunc(self.PopupBorderSize * scale_factor)
self.FramePadding = ImTrunc(self.FramePadding * scale_factor)
self.FrameBorderSize = ImTrunc(self.FrameBorderSize * scale_factor)
self.FrameRounding = ImTrunc(self.FrameRounding * scale_factor)
self.ItemSpacing = ImTrunc(self.ItemSpacing * scale_factor)
self.ItemInnerSpacing = ImTrunc(self.ItemInnerSpacing * scale_factor)
self.CellPadding = ImTrunc(self.CellPadding * scale_factor)
self.TouchExtraPadding = ImTrunc(self.TouchExtraPadding * scale_factor)
self.IndentSpacing = ImTrunc(self.IndentSpacing * scale_factor)
self.ColumnsMinSpacing = ImTrunc(self.ColumnsMinSpacing * scale_factor)
self.ScrollbarSize = ImTrunc(self.ScrollbarSize * scale_factor)
self.ScrollbarRounding = ImTrunc(self.ScrollbarRounding * scale_factor)
self.ScrollbarPadding = ImTrunc(self.ScrollbarPadding * scale_factor)
self.GrabMinSize = ImTrunc(self.GrabMinSize * scale_factor)
self.GrabRounding = ImTrunc(self.GrabRounding * scale_factor)
self.LogSliderDeadzone = ImTrunc(self.LogSliderDeadzone * scale_factor)
self.ImageRounding = ImTrunc(self.ImageRounding * scale_factor)
self.ImageBorderSize = ImTrunc(self.ImageBorderSize * scale_factor)
self.TabRounding = ImTrunc(self.TabRounding * scale_factor)
self.TabBorderSize = ImTrunc(self.TabBorderSize * scale_factor)
self.TabMinWidthBase = ImTrunc(self.TabMinWidthBase * scale_factor)
self.TabMinWidthShrink = ImTrunc(self.TabMinWidthShrink * scale_factor)
self.TabCloseButtonMinWidthSelected = (self.TabCloseButtonMinWidthSelected > 0.0 and self.TabCloseButtonMinWidthSelected ~= FLT_MAX) and ImTrunc(self.TabCloseButtonMinWidthSelected * scale_factor) or self.TabCloseButtonMinWidthSelected
self.TabCloseButtonMinWidthUnselected = (self.TabCloseButtonMinWidthUnselected > 0.0 and self.TabCloseButtonMinWidthUnselected ~= FLT_MAX) and ImTrunc(self.TabCloseButtonMinWidthUnselected * scale_factor) or self.TabCloseButtonMinWidthUnselected
self.TabBarBorderSize = ImTrunc(self.TabBarBorderSize * scale_factor)
self.TabBarOverlineSize = ImTrunc(self.TabBarOverlineSize * scale_factor)
self.TreeLinesSize = ImTrunc(self.TreeLinesSize * scale_factor)
self.TreeLinesRounding = ImTrunc(self.TreeLinesRounding * scale_factor)
self.MenuItemRounding = ImTrunc(self.MenuItemRounding * scale_factor)
self.SelectableRounding = ImTrunc(self.SelectableRounding * scale_factor)
self.DragDropTargetRounding = ImTrunc(self.DragDropTargetRounding * scale_factor)
self.DragDropTargetBorderSize = ImTrunc(self.DragDropTargetBorderSize * scale_factor)
self.DragDropTargetPadding = ImTrunc(self.DragDropTargetPadding * scale_factor)
self.ColorMarkerSize = ImTrunc(self.ColorMarkerSize * scale_factor)
self.InputTextCursorSize = ImTrunc(self.InputTextCursorSize * scale_factor)
self.SeparatorSize = ImTrunc(self.SeparatorSize * scale_factor)
self.SeparatorTextBorderSize = ImTrunc(self.SeparatorTextBorderSize * scale_factor)
self.SeparatorTextPadding = ImTrunc(self.SeparatorTextPadding * scale_factor)
self.DockingSeparatorSize = ImTrunc(self.DockingSeparatorSize * scale_factor)
self.DisplayWindowPadding = ImTrunc(self.DisplayWindowPadding * scale_factor)
self.DisplaySafeAreaPadding = ImTrunc(self.DisplaySafeAreaPadding * scale_factor)
self.MouseCursorScale = ImTrunc(self.MouseCursorScale * scale_factor)
end
local ImGuiResizeGripDef = {
{CornerPosN = ImVec2(1, 1), InnerDir = ImVec2(-1, -1), AngleMin12 = 0, AngleMax12 = 3}, -- Bottom right grip
{CornerPosN = ImVec2(0, 1), InnerDir = ImVec2( 1, -1), AngleMin12 = 3, AngleMax12 = 6} -- Bottom left
}
--- [1] Left, [2] Right, [3] Up, [4] Down
local ImGuiResizeBorderDef = {
{InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00},
{InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00},
{InnerDir = ImVec2( 0, 1), SegmentN1 = ImVec2( 0, 0), SegmentN2 = ImVec2( 1, 0), OuterAngle = IM_PI * 1.50},
{InnerDir = ImVec2( 0, -1), SegmentN1 = ImVec2( 1, 1), SegmentN2 = ImVec2( 0, 1), OuterAngle = IM_PI * 0.50}
}
--- @param window ImGuiWindow
--- @param border_n int
--- @param perp_padding float
--- @param thickness float
--- @return ImRect
--- @nodiscard
local function GetResizeBorderRect(window, border_n, perp_padding, thickness)
local rect = window:Rect()
if thickness == 0.0 then
ImVec2_CopyV(rect.Max, rect.Max.x - 1, rect.Max.y - 1)
end
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)
end
if border_n == ImGuiDir.Right then
return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding)
end
if border_n == ImGuiDir.Up then
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
--- @param data table|number
--- @param size int? # size = -1 to indicate that `data` is a single number
--- @param seed int?
--- @return int
function ImHashData(data, size, seed)
seed = seed or 0
local FNV_OFFSET_BASIS = 0x811C9DC5
local FNV_PRIME = 0x01000193
local hash = bit32.bxor(FNV_OFFSET_BASIS, seed)
if size == -1 then --- @cast data number
hash = bit32.bxor(hash, data)
hash = bit32.band(hash * FNV_PRIME, 0xFFFFFFFF)
else
size = size or #data
for i = 1, size do
hash = bit32.bxor(hash, data[i])
hash = bit32.band(hash * FNV_PRIME, 0xFFFFFFFF)
end
end
return hash
end
-- Use FNV1a, as one ImGui FIXME suggested
--- @param str string
--- @param size int?
--- @param seed int?
--- @return int
function ImHashStr(str, size, seed)
if size == nil then size = #str end
if seed == nil then seed = 0 end
if str == "" or size == 0 then
return seed -- need to match cpp code edge case behavior while using FNV ourselves
end
local FNV_OFFSET_BASIS = 0x811C9DC5
local FNV_PRIME = 0x01000193
local hash = bit32.bxor(FNV_OFFSET_BASIS, seed)
local i = 1
local c
while i <= size do
c = string.byte(str, i)
-- `###` to reset back to initial hash value
if c == 35 and string.byte(str, i + 1) == 35 and string.byte(str, i + 2) == 35 then
hash = bit32.bxor(FNV_OFFSET_BASIS, seed)
i = i + 2
else
hash = bit32.bxor(hash, c)
hash = bit32.band(hash * FNV_PRIME, 0xFFFFFFFF)
end
i = i + 1
end
return hash
end
do --[[CharFromUtf8]]
local lengths = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0}
local masks = {0x00, 0x7f, 0x1f, 0x0f, 0x07}
local mins = {0x400000, 0, 0x80, 0x800, 0x10000}
local shiftc = {0, 18, 12, 6, 0}
local shifte = {0, 6, 4, 2, 0}
local s = {0, 0, 0, 0}
--- @param in_text ImString
--- @param pos int
--- @param in_text_end int
--- @return int wanted
--- @return unsigned_int out_char
function ImStd.ImTextCharFromUtf8(in_text, pos, in_text_end)
local len = lengths[bit32.rshift(ImStrByte(in_text, pos), 3) + 1]
local wanted = len > 0 and len or 1
if in_text_end == nil then
in_text_end = pos + wanted
end
s[1] = (pos < in_text_end) and ImStrByte(in_text, pos) or 0
s[2] = (pos + 1 < in_text_end) and ImStrByte(in_text, pos + 1) or 0
s[3] = (pos + 2 < in_text_end) and ImStrByte(in_text, pos + 2) or 0
s[4] = (pos + 3 < in_text_end) and ImStrByte(in_text, pos + 3) or 0
local out_char
out_char = bit32.lshift(bit32.band(s[1], masks[len + 1]), 18)
out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[2], 0x3f), 12))
out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[3], 0x3f), 6))
out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[4], 0x3f), 0))
out_char = bit32.rshift(out_char, shiftc[len + 1])
local e = 0
e = bit32.lshift((out_char < mins[len + 1]) and 1 or 0, 6)
e = bit32.bor(e, bit32.lshift((bit32.rshift(out_char, 11) == 0x1b) and 1 or 0, 7))
e = bit32.bor(e, bit32.lshift((out_char > IM_UNICODE_CODEPOINT_MAX) and 1 or 0, 8))
e = bit32.bor(e, bit32.rshift(bit32.band(s[2], 0xc0), 2))
e = bit32.bor(e, bit32.rshift(bit32.band(s[3], 0xc0), 4))
e = bit32.bor(e, bit32.rshift(s[4], 6))
e = bit32.bxor(e, 0x2a)
e = bit32.rshift(e, shifte[len + 1])
if e ~= 0 then
wanted = ImMin(wanted, (s[1] ~= 0 and 1 or 0) + (s[2] ~= 0 and 1 or 0) + (s[3] ~= 0 and 1 or 0) + (s[4] ~= 0 and 1 or 0))
out_char = IM_UNICODE_CODEPOINT_INVALID
end
return wanted, out_char
end
end
--- @param buf char[]
--- @param buf_size int
--- @param c unsigned_int
local function ImTextCharToUtf8_inline(buf, buf_size, c)
if c < 0x80 then
buf[1] = c
return 1
end
if c < 0x800 then
if buf_size < 2 then
return 0
end
buf[1] = (0xc0 + bit32.rshift(c, 6))
buf[2] = (0x80 + bit32.band(c, 0x3f))
return 2
end
if c < 0x10000 then
if buf_size < 3 then
return 0
end
buf[1] = (0xe0 + bit32.rshift(c, 12))
buf[2] = (0x80 + bit32.band(bit32.rshift(c, 6), 0x3f))
buf[3] = (0x80 + bit32.band(c, 0x3f))
return 3
end
if c <= 0x10FFFF then
if buf_size < 4 then
return 0
end
buf[1] = (0xf0 + bit32.rshift(c, 18))
buf[2] = (0x80 + bit32.band(bit32.rshift(c, 12), 0x3f))
buf[3] = (0x80 + bit32.band(bit32.rshift(c, 6), 0x3f))
buf[4] = (0x80 + bit32.band(c, 0x3f))
return 4
end
-- Invalid code point, the max unicode is 0x10FFFF
return 0
end
--- @param out_buf [char, char, char, char, char]
--- @param c unsigned_int
function ImStd.ImTextCharToUtf8(out_buf, c)
local count = ImTextCharToUtf8_inline(out_buf, 5, c)
out_buf[count + 1] = 0
return count
end
--- @param in_text ImString
--- @param pos int
--- @param in_text_end int
--- @return int
function ImStd.ImTextCountUtf8BytesFromChar(in_text, pos, in_text_end)
local bytes, unused = ImStd.ImTextCharFromUtf8(in_text, pos, in_text_end)
return bytes
end
--- @param text ImString
--- @param in_text_start int
--- @param in_p int
function ImStd.ImTextFindPreviousUtf8Codepoint(text, in_text_start, in_p)
while in_p > in_text_start do
in_p = in_p - 1
if bit32.band(ImStrByte(text, in_p), 0xC0) ~= 0x80 then
return in_p
end
end
return in_text_start
end
--- @param text ImString
--- @param in_text_start int
--- @param in_text_end int
--- @param in_p int
--- @return int
function ImStd.ImTextFindValidUtf8CodepointEnd(text, in_text_start, in_text_end, in_p)
if in_text_start == in_p then
return in_text_start
end
local prev = ImStd.ImTextFindPreviousUtf8Codepoint(text, in_text_start, in_p)
local prev_c_len, prev_c = ImStd.ImTextCharFromUtf8(text, prev, in_text_end)
-- Check if the previous character is valid and fits within the range
if prev_c ~= IM_UNICODE_CODEPOINT_INVALID and prev_c_len <= (in_p - prev) then
return in_p
end
return prev
end
--- @param a ImVec2
--- @param b ImVec2
--- @param p ImVec2
--- @return ImVec2
--- @nodiscard
function ImStd.ImLineClosestPoint(a, b, p)
local ap = p - a
local ab_dir = b - a
local dot = ap.x * ab_dir.x + ap.y * ab_dir.y
if dot < 0.0 then
return a
end
local ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y
if dot > ab_len_sqr then
return b
end
return a + ab_dir * (dot / ab_len_sqr)
end
--- @param a ImVec2
--- @param b ImVec2
--- @param c ImVec2
--- @param p ImVec2
function ImStd.ImTriangleContainsPoint(a, b, c, p)
local b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0
local b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0
local b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0
return (b1 == b2) and (b2 == b3)
end
--- @param a ImVec2
--- @param b ImVec2
--- @param c ImVec2
--- @param p ImVec2
--- @return float, float, float
function ImStd.ImTriangleBarycentricCoords(a, b, c, p)
local v0 = b - a
local v1 = c - a
local v2 = p - a
local denom = v0.x * v1.y - v1.x * v0.y
local out_v = (v2.x * v1.y - v1.x * v2.y) / denom
local out_w = (v0.x * v2.y - v2.x * v0.y) / denom
local out_u = 1.0 - out_v - out_w
return out_u, out_v, out_w
end
--- @param a ImVec2
--- @param b ImVec2
--- @param c ImVec2
--- @param p ImVec2
--- @return ImVec2
--- @nodiscard
function ImStd.ImTriangleClosestPoint(a, b, c, p)
local proj_ab = ImStd.ImLineClosestPoint(a, b, p)
local proj_bc = ImStd.ImLineClosestPoint(b, c, p)
local proj_ca = ImStd.ImLineClosestPoint(c, a, p)
local dist2_ab = ImLengthSqr(p - proj_ab)
local dist2_bc = ImLengthSqr(p - proj_bc)
local dist2_ca = ImLengthSqr(p - proj_ca)
local m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca))
if m == dist2_ab then
return proj_ab
elseif m == dist2_bc then
return proj_bc
else
return proj_ca
end
end
--- @param dst char[]
--- @param dst_pos int
--- @param src char[]
--- @param src_pos int
--- @param count size_t
function ImStd.ImStrncpy(dst, dst_pos, src, src_pos, count)
if count < 1 then
return
end
if count > 1 then
ImStd.memmove(dst, dst_pos, src, src_pos, count - 1)
end
dst[dst_pos + (count - 1)] = 0
end
--- @param str char[]
--- @param mid_line int
--- @param begin int
function ImStd.ImStrbol(str, mid_line, begin)
IM_ASSERT_PARANOID(mid_line >= begin and mid_line <= #str)
while mid_line > begin and str[mid_line - 1] ~= 10 do
mid_line = mid_line - 1
end
return mid_line
end
--- @param buf char[]
function ImStd.ImStrTrimBlanks(buf)
local p = 1 -- buf_begin
while buf[p] == 32 or buf[p] == 9 do
p = p + 1
end
local p_start = p
while buf[p] ~= 0 do
p = p + 1
end
while p > p_start and (buf[p - 1] == 32 or buf[p - 1] == 9) do
p = p - 1
end
if p_start > 1 then
ImStd.memmove(buf, 1, buf, p_start, p - p_start)
end
buf[p - p_start + 1] = 0
end
function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling)
local g = GImGui
local window = g.CurrentWindow
g.Style.FontSizeBase = g.FontSizeBase
-- if (window ~= nil and window.SkipItems) then
-- local table = g.CurrentTable
-- if (table == nil or (table.CurrentColumn ~= -1 and table.Columns[table.CurrentColumn].IsSkipItems == false)) then
-- return
-- end
-- end
local final_size = (restore_font_size_after_scaling > 0.0) and restore_font_size_after_scaling or 0.0
if final_size == 0.0 then
final_size = g.FontSizeBase
final_size = final_size * g.Style.FontScaleMain
final_size = final_size * g.Style.FontScaleDpi
if window ~= nil then
final_size = final_size * window.FontWindowScale
end
end
final_size = ImGui.GetRoundedFontSize(final_size)
final_size = ImClamp(final_size, 4.0, IMGUI_FONT_SIZE_MAX)
if (g.Font ~= nil and bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0) then
g.Font.CurrentRasterizerDensity = g.FontRasterizerDensity
end
g.FontSize = final_size
g.FontBaked = (g.Font ~= nil and window ~= nil) and g.Font:GetFontBaked(final_size) or nil
g.FontBakedScale = (g.FontBaked ~= nil) and (g.FontSize / g.FontBaked.Size) or 0.0
g.DrawListSharedData.FontSize = g.FontSize
g.DrawListSharedData.FontScale = g.FontBakedScale
end
function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_scaling)
local g = GImGui
g.Font = font
g.FontSizeBase = font_size_before_scaling
ImGui.UpdateCurrentFontSize(font_size_after_scaling)
if font ~= nil then
IM_ASSERT(font and font:IsLoaded())
local atlas = font.OwnerAtlas
g.DrawListSharedData.FontAtlas = atlas
g.DrawListSharedData.Font = font
ImFontAtlasUpdateDrawListsSharedData(atlas)
if (g.CurrentWindow ~= nil) then
g.CurrentWindow.DrawList:_SetTexture(atlas.TexRef)
end
end
end
function ImGui.PushFont(font, font_size_base)
local g = GImGui
if font == nil then
font = g.Font
end
IM_ASSERT(font ~= nil)
IM_ASSERT(font_size_base >= 0.0)
g.FontStack:push_back(ImFontStackData(font, g.FontSizeBase, g.FontSize))
if font_size_base == 0.0 then
font_size_base = g.FontSizeBase
end
ImGui.SetCurrentFont(font, font_size_base, 0.0)
end
function ImGui.PopFont()
local g = GImGui
if (g.FontStack.Size <= 0) then
IM_ASSERT_USER_ERROR(0, "Calling PopFont() too many times!")
return
end
local font_stack_data = g.FontStack:back()
ImGui.SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, font_stack_data.FontSizeAfterScaling)
g.FontStack:pop_back()
end
function ImGui.UpdateTexturesNewFrame()
local g = GImGui
local has_textures = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0
for _, atlas in g.FontAtlases:iter() do
if (atlas.OwnerContext == g) then
ImFontAtlasUpdateNewFrame(atlas, g.FrameCount, has_textures)
else
IM_ASSERT(atlas.Builder ~= nil and atlas.Builder.FrameCount ~= -1)
IM_ASSERT(atlas.RendererHasTextures == has_textures)
end
end
for _, tex in g.UserTextures:iter() do
ImTextureDataUpdateNewFrame(tex)
end
end
function ImGui.UpdateTexturesEndFrame()
local g = GImGui
g.PlatformIO.Textures:resize(0)
for _, atlas in g.FontAtlases:iter() do
for _, tex in atlas.TexList:iter() do
tex.RefCount = atlas.RefCount
g.PlatformIO.Textures:push_back(tex)
end
end
for _, tex in g.UserTextures:iter() do
g.PlatformIO.Textures:push_back(tex)
end
end
function ImGui.UpdateFontsNewFrame()
local g = GImGui
if (bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) == 0) then
for _, atlas in g.FontAtlases:iter() do
atlas.Locked = true
end
end
if (g.Style._NextFrameFontSizeBase ~= 0.0) then
g.Style.FontSizeBase = g.Style._NextFrameFontSizeBase
g.Style._NextFrameFontSizeBase = 0.0
end
local font = ImGui.GetDefaultFont()
if g.Style.FontSizeBase <= 0.0 then
g.Style.FontSizeBase = ((font.LegacySize > 0.0) and font.LegacySize or FONT_DEFAULT_SIZE_BASE)
end
g.Font = font
g.FontSizeBase = g.Style.FontSizeBase
g.FontSize = 0.0
local font_stack_data = ImFontStackData(font, g.Style.FontSizeBase, g.Style.FontSizeBase)
ImGui.SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0)
g.FontStack:push_back(font_stack_data)
IM_ASSERT(g.Font:IsLoaded())
end
function ImGui.UpdateFontsEndFrame()
ImGui.PopFont()
end
--- @return ImFont
function ImGui.GetDefaultFont()
local g = GImGui
local atlas = g.IO.Fonts
if (atlas.Builder == nil or atlas.Fonts.Size == 0) then
ImFontAtlasBuildMain(atlas)
end
return g.IO.FontDefault and g.IO.FontDefault or atlas.Fonts[1]
end
--- @param atlas ImFontAtlas
function ImGui.RegisterFontAtlas(atlas)
local g = GImGui
if (g.FontAtlases.Size == 0) then
IM_ASSERT(atlas == g.IO.Fonts)
end
atlas.RefCount = atlas.RefCount + 1
g.FontAtlases:push_back(atlas)
ImFontAtlasAddDrawListSharedData(atlas, g.DrawListSharedData)
for _, tex in atlas.TexList:iter() do
tex.RefCount = atlas.RefCount
end
end
--- @param atlas ImFontAtlas
function ImGui.UnregisterFontAtlas(atlas)
local g = GImGui
IM_ASSERT(atlas.RefCount > 0)
ImFontAtlasRemoveDrawListSharedData(atlas, g.DrawListSharedData)
g.FontAtlases:find_erase(atlas)
atlas.RefCount = atlas.RefCount - 1
for _, tex in atlas.TexList:iter() do
tex.RefCount = atlas.RefCount
end
end
function ImGui.GetCurrentContext()
return GImGui
end
--- @param ctx ImGuiContext?
function ImGui.SetCurrentContext(ctx)
GImGui = ctx
ImGui._SetCurrentContext_Internal(ctx)
ImGui._SetCurrentContext_Widgets(ctx)
ImGui._SetCurrentContext_Tables(ctx)
end
--- @param alloc_func ImGuiMemAllocFunc
--- @param free_func ImGuiMemFreeFunc
--- @param user_data any
function ImGui.SetAllocatorFunctions(alloc_func, free_func, user_data)
GImAllocatorAllocFunc = alloc_func
GImAllocatorFreeFunc = free_func
GImAllocatorUserData = user_data
end
--- @param key ImGuiLocKey
--- @param text string
--- @return ImGuiLocEntry
--- @nodiscard
--- @package
local function ImGuiLocEntry(key, text)
return { Key = key, Text = text }
end
local GLocalizationEntriesEnUS = {
ImGuiLocEntry(ImGuiLocKey.VersionStr, "ImGui Sincerely WIP"),
ImGuiLocEntry(ImGuiLocKey.TableSizeOne, "Size column to fit###SizeOne"),
ImGuiLocEntry(ImGuiLocKey.TableSizeAllFit, "Size all columns to fit###SizeAll"),
ImGuiLocEntry(ImGuiLocKey.TableSizeAllDefault, "Size all columns to default###SizeAll"),
ImGuiLocEntry(ImGuiLocKey.TableReset, "Reset"),
ImGuiLocEntry(ImGuiLocKey.TableResetOrder, "Reset order###ResetOrder"),
ImGuiLocEntry(ImGuiLocKey.TableResetVisibility, "Reset visibility###ResetVisibility"),
ImGuiLocEntry(ImGuiLocKey.WindowingMainMenuBar, "(Main menu bar)"),
ImGuiLocEntry(ImGuiLocKey.WindowingPopup, "(Popup)"),
ImGuiLocEntry(ImGuiLocKey.WindowingUntitled, "(Untitled)"),
ImGuiLocEntry(ImGuiLocKey.OpenLink_s, "Open '%s'"),
ImGuiLocEntry(ImGuiLocKey.CopyLink, "Copy Link###CopyLink"),
ImGuiLocEntry(ImGuiLocKey.DockingHideTabBar, "Hide tab bar###HideTabBar"),
ImGuiLocEntry(ImGuiLocKey.DockingHoldShiftToDock, "Hold SHIFT to enable Docking window."),
ImGuiLocEntry(ImGuiLocKey.DockingDragToUndockOrMoveNode, "Click and drag to move or undock whole node."),
}
function ImGui.Initialize()
local g = GImGui
IM_ASSERT(not g.Initialized and not g.SettingsLoaded)
ImGui.LocalizeRegisterEntries(GLocalizationEntriesEnUS, #GLocalizationEntriesEnUS)
local viewport = ImGuiViewportP()
viewport.ID = IMGUI_VIEWPORT_DEFAULT_ID
viewport.Idx = 1
viewport.PlatformWindowCreated = true
viewport.Flags = ImGuiViewportFlags.OwnedByApp
g.Viewports:push_back(viewport)
g.ViewportCreatedCount = g.ViewportCreatedCount + 1
g.PlatformIO.Viewports:push_back(g.Viewports.Data[1])
for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do
if (key >= ImGuiKey.K0 and key <= ImGuiKey.K9) or (key >= ImGuiKey.A and key <= ImGuiKey.Z) or (key >= ImGuiKey.Keypad0 and key <= ImGuiKey.Keypad9)
or key == ImGuiKey.Tab or key == ImGuiKey.Space or key == ImGuiKey.Apostrophe or key == ImGuiKey.Comma or key == ImGuiKey.Minus or key == ImGuiKey.Period
or key == ImGuiKey.Slash or key == ImGuiKey.Semicolon or key == ImGuiKey.Equal or key == ImGuiKey.LeftBracket or key == ImGuiKey.RightBracket or key == ImGuiKey.GraveAccent
or key == ImGuiKey.KeypadDecimal or key == ImGuiKey.KeypadDivide or key == ImGuiKey.KeypadMultiply or key == ImGuiKey.KeypadSubtract or key == ImGuiKey.KeypadAdd or key == ImGuiKey.KeypadEqual then
g.KeysMayBeCharInput:SetBit(key + 1)
end
end
local atlas = g.IO.Fonts
g.DrawListSharedData.Context = g
ImGui.RegisterFontAtlas(atlas)
g.Initialized = true
end
--- @param shared_font_atlas? ImFontAtlas
function ImGui.CreateContext(shared_font_atlas)
local prev_ctx = ImGui.GetCurrentContext()
local ctx = ImGuiContext(shared_font_atlas)
ImGui.SetCurrentContext(ctx)
ImGui.Initialize()
if prev_ctx ~= nil then
ImGui.SetCurrentContext(prev_ctx) -- Restore previous context if any, else keep new one
end
return ctx
end
--- @param ctx? ImGuiContext
function ImGui.DestroyContext(ctx)
local prev_ctx = ImGui.GetCurrentContext()
if ctx == nil then
ctx = prev_ctx
end
ImGui.SetCurrentContext(ctx)
ImGui.Shutdown()
ImGui.SetCurrentContext((prev_ctx ~= ctx) and prev_ctx or nil)
end
--- @param window ImGuiWindow
--- @return any
function ImGui.FindWindowSettingsByWindow(window)
local g = GImGui
if window.SettingsOffset ~= -1 then
return g.SettingsWindows[window.SettingsOffset + 1]
end
return ImGui.FindWindowSettingsByID(window.ID)
end
--- @param id ImGuiID
--- @return any
function ImGui.FindWindowSettingsByID(id)
local g = GImGui
for _, settings in g.SettingsWindows:iter() do
if settings.ID == id and not settings.WantDelete then
return settings
end
end
return nil
end
--- @param window ImGuiWindow
--- @return ImGuiWindow?
function ImGui.FindFrontMostVisibleChildWindow(window)
for n = window.DC.ChildWindows.Size, 1, -1 do
if ImGui.IsWindowActiveAndVisible(window.DC.ChildWindows.Data[n]) then
return ImGui.FindFrontMostVisibleChildWindow(window.DC.ChildWindows.Data[n])
end
end
return window
end
--- @param window ImGuiWindow
--- @param cond ImGuiCond
--- @param allow bool
local function SetWindowConditionAllowFlags(window, cond, allow)
if allow then
window.SetWindowPosAllowFlags = bit32.bor(window.SetWindowPosAllowFlags, cond)
window.SetWindowSizeAllowFlags = bit32.bor(window.SetWindowSizeAllowFlags, cond)
window.SetWindowCollapsedAllowFlags = bit32.bor(window.SetWindowCollapsedAllowFlags, cond)
else
window.SetWindowPosAllowFlags = bit32.band(window.SetWindowPosAllowFlags, bit32.bnot(cond))
window.SetWindowSizeAllowFlags = bit32.band(window.SetWindowSizeAllowFlags, bit32.bnot(cond))
window.SetWindowCollapsedAllowFlags = bit32.band(window.SetWindowCollapsedAllowFlags, bit32.bnot(cond))
end
end
--- @param window ImGuiWindow
--- @param settings ImGuiWindowSettings
local function ApplyWindowSettings(window, settings)
if settings ~= nil then
local main_viewport = ImGui.GetMainViewport()
ImVec2_Copy(window.ViewportPos, main_viewport.Pos)
if (settings.ViewportId ~= 0) then
window.ViewportId = settings.ViewportId
ImVec2_Copy(window.ViewportPos, settings.ViewportPos)
end
window.Pos = ImTrunc(ImVec2(settings.Pos.x + window.ViewportPos.x, settings.Pos.y + window.ViewportPos.y))
if settings.Size.x > 0 and settings.Size.y > 0 then
local size = ImVec2(ImTrunc(settings.Size.x), ImTrunc(settings.Size.y))
ImVec2_Copy(window.Size, size)
ImVec2_Copy(window.SizeFull, size)
window.AutoFitFramesX = 0; window.AutoFitFramesY = 0
end
window.Collapsed = settings.Collapsed
-- window.DockId = settings.DockId
-- window.DockOrder = settings.DockOrder
SetWindowConditionAllowFlags(window, ImGuiCond.FirstUseEver, false)
end
-- So first call to CalcWindowContentSizes() doesn't return crazy values
ImVec2_Copy(window.DC.CursorStartPos, window.Pos)
ImVec2_Copy(window.DC.CursorMaxPos, window.Pos)
ImVec2_Copy(window.DC.IdealMaxPos, window.Pos)
if (bit32.band(window.Flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0) then
window.AutoFitFramesX = 2; window.AutoFitFramesY = 2
window.AutoFitOnlyGrows = false
else
window.AutoFitFramesX = (window.Size.x <= 0.0) and 2 or 0
window.AutoFitFramesY = (window.Size.y <= 0.0) and 2 or 0
window.AutoFitOnlyGrows = (window.AutoFitFramesX > 0) or (window.AutoFitFramesY > 0)
end
end
--- @param window ImGuiWindow
--- @param settings ImGuiWindowSettings
local function InitOrLoadWindowSettings(window, settings)
-- Initial window state with e.g. default/arbitrary window position
-- Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
local main_viewport = ImGui.GetMainViewport()
ImVec2_Copy(window.Pos, main_viewport.Pos + ImVec2(60, 60))
ImVec2_Copy(window.Size, ImVec2(0, 0))
ImVec2_Copy(window.SizeFull, ImVec2(0, 0))
ImVec2_Copy(window.ViewportPos, main_viewport.Pos)
window.SetWindowPosAllowFlags = bit32.bor(ImGuiCond.Always, ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing)
window.SetWindowSizeAllowFlags = window.SetWindowPosAllowFlags
window.SetWindowCollapsedAllowFlags = window.SetWindowPosAllowFlags
-- window.SetWindowDockAllowFlags = window.SetWindowPosAllowFlags
ApplyWindowSettings(window, settings)
if settings ~= nil then
-- TODO: settings.LastUsedDate = g.SessionDate
end
end
--- @param name string
--- @param flags ImGuiWindowFlags
--- @return ImGuiWindow
local function CreateNewWindow(name, flags)
local g = GImGui
local window_id = ImHashStr(name)
local window = ImGuiWindow(g, name)
window.ID = window_id
window.Flags = flags
g.WindowsById[window_id] = window
local settings = nil
if bit32.band(window.Flags, ImGuiWindowFlags.NoSavedSettings) == 0 then
settings = ImGui.FindWindowSettingsByWindow(window)
if settings ~= nil then
window.SettingsOffset = g.SettingsWindows:index_from_ptr(settings)
end
end
InitOrLoadWindowSettings(window, settings)
if bit32.band(flags, ImGuiWindowFlags.NoBringToFrontOnFocus) ~= 0 then
g.Windows:push_front(window)
else
g.Windows:push_back(window)
end
return window
end
--- @param window ImGuiWindow
--- @return ImGuiWindow?
local function GetWindowForTitleDisplay(window)
if window.DockNodeAsHost then
return window.DockNodeAsHost.VisibleWindow
else
return window
end
end
--- @param id ImGuiID
function ImGui.KeepAliveID(id)
local g = GImGui
if g.ActiveId == id then
g.ActiveIdIsAlive = id
end
if g.DeactivatedItemData.ID == id then
g.DeactivatedItemData.IsAlive = true
end
end
--- @param r_min ImVec2
--- @param r_max ImVec2
--- @param clip? bool
function ImGui.IsMouseHoveringRect(r_min, r_max, clip)
if clip == nil then clip = true end
local g = GImGui
local rect_clipped = ImRect(r_min, r_max)
if clip then
rect_clipped:ClipWith(g.CurrentWindow.ClipRect)
end
if not rect_clipped:ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding) then
return false
end
if (not g.MouseViewport:GetMainRect():Overlaps(rect_clipped)) then
return false
end
return true
end
-- Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
-- [Internal] This doesn't test if the button is pressed
--- @param button ImGuiMouseButton
--- @param lock_threshold? float
function ImGui.IsMouseDragPastThreshold(button, lock_threshold)
if lock_threshold == nil then lock_threshold = -1.0 end
local g = GImGui
IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown)
if lock_threshold < 0.0 then
lock_threshold = g.IO.MouseDragThreshold
end
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold
end
--- @param button ImGuiMouseButton
--- @param lock_threshold? float
function ImGui.IsMouseDragging(button, lock_threshold)
if lock_threshold == nil then lock_threshold = -1.0 end
local g = GImGui
IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown)
if not g.IO.MouseDown[button] then
return false
end
return ImGui.IsMouseDragPastThreshold(button, lock_threshold)
end
--- @param pos ImVec2
function ImGui.TeleportMousePos(pos)
local g = GImGui
ImVec2_Copy(g.IO.MousePos, pos)
ImVec2_Copy(g.IO.MousePosPrev, pos)
ImVec2_CopyV(g.IO.MouseDelta, 0.0, 0.0)
g.IO.WantSetMousePos = true
-- IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y)
end
--- @param id ImGuiID
function ImGui.ItemHandleShortcut(id)
local g = GImGui
local flags = g.NextItemData.ShortcutFlags
IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetNextItemShortcut)) == 0)
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 then
return
end
if bit32.band(flags, ImGuiInputFlags.Tooltip) ~= 0 then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasShortcut)
g.LastItemData.Shortcut = g.NextItemData.Shortcut
end
if not ImGui.Shortcut(g.NextItemData.Shortcut, bit32.band(flags, ImGuiInputFlags.SupportedByShortcut), id) or g.NavActivateId ~= 0 then
return
end
g.NavActivateId = id
g.NavActivateFlags = bit32.bor(ImGuiActivateFlags.PreferInput, ImGuiActivateFlags.FromShortcut)
g.NavActivateDownId = id
g.NavActivatePressedId = id
ImGui.NavHighlightActivated(id)
end
--- @param bb ImRect
--- @param id ImGuiID
--- @param nav_bb_arg? ImRect
--- @param extra_flags? ImGuiItemFlags
function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags)
if extra_flags == nil then extra_flags = 0 end
local g = GImGui
local window = g.CurrentWindow
g.LastItemData.ID = id
ImRect_Copy(g.LastItemData.Rect, bb)
ImRect_Copy(g.LastItemData.NavRect, nav_bb_arg and nav_bb_arg or bb)
g.LastItemData.ItemFlags = bit32.bor(g.CurrentItemFlags, g.NextItemData.ItemFlagsSet, extra_flags)
g.LastItemData.StatusFlags = ImGuiItemStatusFlags.None
if id ~= 0 then
ImGui.KeepAliveID(id)
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoNav) == 0 then
window.DC.NavLayersActiveMaskNext = bit32.bor(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, window.DC.NavLayerCurrent))
if g.NavId == id or g.NavAnyRequest then
if g.NavWindow.RootWindowForNav == window.RootWindowForNav then
if window == g.NavWindow or bit32.band(bit32.bor(window.ChildFlags, g.NavWindow.ChildFlags), ImGuiChildFlags.NavFlattened) ~= 0 then
ImGui.NavProcessItem()
end
end
end
end
if bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasShortcut) ~= 0 then
ImGui.ItemHandleShortcut(id)
end
end
g.NextItemData.HasFlags = ImGuiNextItemDataFlags.None
g.NextItemData.ItemFlagsSet = ImGuiItemFlags.None
local is_rect_visible = bb:Overlaps(window.ClipRect)
if not is_rect_visible then
if id == 0 or not (id == g.ActiveId or id == g.ActiveIdPreviousFrame or id == g.NavId or id == g.NavActivateId or g.ItemUnclipByLog) then
return false
end
end
if id ~= 0 and g.DeactivatedItemData.ID == id then
g.DeactivatedItemData.ElapseFrame = g.FrameCount
end
if is_rect_visible then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible)
end
if ImGui.IsMouseHoveringRect(bb.Min, bb.Max) then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect)
end
return true
end
--- @param size_or_bb ImVec2|ImRect
--- @param text_baseline_y? float
function ImGui.ItemSize(size_or_bb, text_baseline_y)
if text_baseline_y == nil then text_baseline_y = -1.0 end
local size
if size_or_bb.Min then
--- @cast size_or_bb ImRect
size = size_or_bb:GetSize()
else
--- @cast size_or_bb ImVec2
size = size_or_bb
end
local g = GImGui
local window = g.CurrentWindow
if window.SkipItems then
return
end
local offset_to_match_baseline_y
if text_baseline_y >= 0 then
offset_to_match_baseline_y = ImMax(0, window.DC.CurrLineTextBaseOffset - text_baseline_y)
else
offset_to_match_baseline_y = 0
end
local line_y1
if window.DC.IsSameLine then
line_y1 = window.DC.CursorPosPrevLine.y
else
line_y1 = window.DC.CursorPos.y
end
local line_height = ImMax(window.DC.CurrLineSize.y, window.DC.CursorPos.y - line_y1 + size.y + offset_to_match_baseline_y)
window.DC.CursorPosPrevLine.x = window.DC.CursorPos.x + size.x
window.DC.CursorPosPrevLine.y = line_y1
window.DC.CursorPos.x = IM_TRUNC(window.Pos.x + window.DC.Indent.x + window.DC.ColumnsOffset.x)
window.DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y)
window.DC.CursorMaxPos.x = ImMax(window.DC.CursorMaxPos.x, window.DC.CursorPosPrevLine.x)
window.DC.CursorMaxPos.y = ImMax(window.DC.CursorMaxPos.y, window.DC.CursorPos.y - g.Style.ItemSpacing.y)
window.DC.PrevLineSize.y = line_height
window.DC.CurrLineSize.y = 0
window.DC.PrevLineTextBaseOffset = ImMax(window.DC.CurrLineTextBaseOffset, text_baseline_y)
window.DC.CurrLineTextBaseOffset = 0
window.DC.IsSetPos = false
window.DC.IsSameLine = false
--- Horizontal layout mode
if (window.DC.LayoutType == ImGuiLayoutType.Horizontal) then
ImGui.SameLine()
end
end
--- @param offset_from_start_x float?
--- @param spacing_w float?
function ImGui.SameLine(offset_from_start_x, spacing_w)
if offset_from_start_x == nil then offset_from_start_x = 0.0 end
if spacing_w == nil then spacing_w = -1.0 end
local g = GImGui
local window = g.CurrentWindow
if window.SkipItems then
return
end
if offset_from_start_x ~= 0.0 then
if spacing_w < 0.0 then spacing_w = 0.0 end
window.DC.CursorPos.x = window.Pos.x - window.Scroll.x + offset_from_start_x + spacing_w + window.DC.GroupOffset.x + window.DC.ColumnsOffset.x
window.DC.CursorPos.y = window.DC.CursorPosPrevLine.y
else
if spacing_w < 0.0 then spacing_w = g.Style.ItemSpacing.x end
window.DC.CursorPos.x = window.DC.CursorPosPrevLine.x + spacing_w
window.DC.CursorPos.y = window.DC.CursorPosPrevLine.y
end
ImVec2_Copy(window.DC.CurrLineSize, window.DC.PrevLineSize)
window.DC.CurrLineTextBaseOffset = window.DC.PrevLineTextBaseOffset
window.DC.IsSameLine = true
end
--- @param indent_w? float
function ImGui.Indent(indent_w)
if indent_w == nil then indent_w = 0.0 end
local g = GImGui
local window = ImGui.GetCurrentWindow()
if indent_w ~= 0.0 then
window.DC.Indent.x = window.DC.Indent.x + indent_w
else
window.DC.Indent.x = window.DC.Indent.x + g.Style.IndentSpacing
end
window.DC.CursorPos.x = window.Pos.x + window.DC.Indent.x + window.DC.ColumnsOffset.x
end
--- @param indent_w? float
function ImGui.Unindent(indent_w)
if indent_w == nil then indent_w = 0.0 end
local g = GImGui
local window = ImGui.GetCurrentWindow()
if indent_w ~= 0.0 then
window.DC.Indent.x = window.DC.Indent.x - indent_w
else
window.DC.Indent.x = window.DC.Indent.x - g.Style.IndentSpacing
end
window.DC.CursorPos.x = window.Pos.x + window.DC.Indent.x + window.DC.ColumnsOffset.x
end
-- Affect large frame+labels widgets only
--- @param item_width float
function ImGui.SetNextItemWidth(item_width)
local g = GImGui
g.NextItemData.HasFlags = bit32.bor(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasWidth)
g.NextItemData.Width = item_width
end
--- @param item_width float
function ImGui.PushItemWidth(item_width)
local g = GImGui
local window = g.CurrentWindow
window.DC.ItemWidthStack:push_back(window.DC.ItemWidth)
window.DC.ItemWidth = (item_width == 0.0) and window.DC.ItemWidthDefault or item_width
g.NextItemData.HasFlags = bit32.band(g.NextItemData.HasFlags, bit32.bnot(ImGuiNextItemDataFlags.HasWidth))
end
function ImGui.PopItemWidth()
local g = GImGui
local window = g.CurrentWindow
if window.DC.ItemWidthStack.Size <= 0 then
IM_ASSERT_USER_ERROR(false, "Calling PopItemWidth() too many times!")
return
end
window.DC.ItemWidth = window.DC.ItemWidthStack:back()
window.DC.ItemWidthStack:pop_back()
end
--- @param components int
--- @param w_full float
function ImGui.PushMultiItemsWidths(components, w_full)
local g = GImGui
local window = g.CurrentWindow
IM_ASSERT(components > 0)
local style = g.Style
window.DC.ItemWidthStack:push_back(window.DC.ItemWidth)
local w_items = w_full - style.ItemInnerSpacing.x * (components - 1)
local prev_split = w_items
for i = components - 1, 1, -1 do
local next_split = IM_TRUNC(w_items * i / components)
window.DC.ItemWidthStack:push_back(ImMax(prev_split - next_split, 1.0))
prev_split = next_split
end
window.DC.ItemWidth = ImMax(prev_split, 1.0)
g.NextItemData.HasFlags = bit32.band(g.NextItemData.HasFlags, bit32.bnot(ImGuiNextItemDataFlags.HasWidth))
end
--- @return float
function ImGui.GetFrameHeight()
local g = GImGui
return g.FontSize + g.Style.FramePadding.y * 2.0
end
--- @return ImVec2
--- @nodiscard
function ImGui.GetContentRegionAvail()
local g = GImGui
local window = g.CurrentWindow
local mx
if window.DC.CurrentColumns or g.CurrentTable then
mx = window.WorkRect.Max
else
mx = window.ContentRegionRect.Max
end
return ImVec2(mx.x - window.DC.CursorPos.x, mx.y - window.DC.CursorPos.y)
end
--- @return ImVec2
--- @nodiscard
function ImGui.GetCursorScreenPos()
local window = ImGui.GetCurrentWindowRead()
local ret = ImVec2()
ImVec2_Copy(ret, window.DC.CursorPos)
return ret
end
--- @param pos ImVec2
function ImGui.SetCursorScreenPos(pos)
local window = ImGui.GetCurrentWindow()
ImVec2_Copy(window.DC.CursorPos, pos)
window.DC.IsSetPos = true
end
-- Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
-- Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
-- FIXME-OPT: Could we safely early out on ->SkipItems?
function ImGui.BeginGroup()
local g = GImGui
local window = g.CurrentWindow
local group_data = ImGuiGroupData()
group_data.WindowID = window.ID
ImVec2_Copy(group_data.BackupCursorPos, window.DC.CursorPos)
ImVec2_Copy(group_data.BackupCursorPosPrevLine, window.DC.CursorPosPrevLine)
ImVec2_Copy(group_data.BackupCursorMaxPos, window.DC.CursorMaxPos)
ImVec1_Copy(group_data.BackupIndent, window.DC.Indent)
ImVec1_Copy(group_data.BackupGroupOffset, window.DC.GroupOffset)
ImVec2_Copy(group_data.BackupCurrLineSize, window.DC.CurrLineSize)
group_data.BackupCurrLineTextBaseOffset = window.DC.CurrLineTextBaseOffset
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive
group_data.BackupHoveredIdIsAlive = (g.HoveredId ~= 0)
group_data.BackupIsSameLine = window.DC.IsSameLine
group_data.BackupAnyIdHasBeenEditedThisFrame = g.AnyIdHasBeenEditedThisFrame
group_data.BackupDeactivatedIdIsAlive = g.DeactivatedItemData.IsAlive
group_data.EmitItem = true
g.GroupStack:push_back(group_data)
window.DC.GroupOffset.x = window.DC.CursorPos.x - window.Pos.x - window.DC.ColumnsOffset.x
ImVec1_Copy(window.DC.Indent, window.DC.GroupOffset)
ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos)
ImVec2_CopyV(window.DC.CurrLineSize, 0.0, 0.0)
if (g.LogEnabled) then
g.LogLinePosY = -FLT_MAX
end
end
function ImGui.EndGroup()
local g = GImGui
local window = g.CurrentWindow
IM_ASSERT(g.GroupStack.Size > 0) -- Mismatched BeginGroup()/EndGroup() calls
local group_data = g.GroupStack:back()
IM_ASSERT(group_data.WindowID == window.ID) -- EndGroup() in wrong window?
if (window.DC.IsSetPos) then
-- TODO: ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
end
local group_bb = ImRect(group_data.BackupCursorPos, ImMax(ImMax(window.DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos))
ImVec2_Copy(window.DC.CursorPos, group_data.BackupCursorPos)
ImVec2_Copy(window.DC.CursorPosPrevLine, group_data.BackupCursorPosPrevLine)
ImVec2_Copy(window.DC.CursorMaxPos, ImMax(group_data.BackupCursorMaxPos, group_bb.Max))
ImVec1_Copy(window.DC.Indent, group_data.BackupIndent)
ImVec1_Copy(window.DC.GroupOffset, group_data.BackupGroupOffset)
ImVec2_Copy(window.DC.CurrLineSize, group_data.BackupCurrLineSize)
window.DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset
window.DC.IsSameLine = group_data.BackupIsSameLine
if (g.LogEnabled) then
g.LogLinePosY = -FLT_MAX -- To enforce a carriage return
end
if (not group_data.EmitItem) then
g.GroupStack:pop_back()
return
end
window.DC.CurrLineTextBaseOffset = ImMax(window.DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset) -- FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now
ImGui.ItemSize(group_bb:GetSize())
ImGui.ItemAdd(group_bb, 0, nil, ImGuiItemFlags.NoTabStop)
-- If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
-- It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
-- Also if you grep for LastItemId you'll notice it is only used in that context.
-- (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
local group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive ~= g.ActiveId) and (g.ActiveIdIsAlive == g.ActiveId) and g.ActiveId
local group_contains_deactivated_id = (group_data.BackupDeactivatedIdIsAlive == false) and (g.DeactivatedItemData.IsAlive == true)
if group_contains_curr_active_id then
g.LastItemData.ID = g.ActiveId
elseif group_contains_deactivated_id then
g.LastItemData.ID = g.DeactivatedItemData.ID
end
ImRect_Copy(g.LastItemData.Rect, group_bb)
-- Forward Hovered flag
local group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) and g.HoveredId ~= 0
if group_contains_curr_hovered_id then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow)
end
-- Forward Edited flag
if g.AnyIdHasBeenEditedThisFrame and not group_data.BackupAnyIdHasBeenEditedThisFrame then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Edited)
end
-- Forward Deactivated flag
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasDeactivated)
if group_contains_deactivated_id then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Deactivated)
end
g.GroupStack:pop_back()
if g.DebugShowGroupRects then
window.DrawList:AddRect(group_bb.Min, group_bb.Max, IM_COL32(255, 0, 255, 255)) -- [Debug]
end
end
function ImGui.CalcItemWidth()
local g = GImGui
local window = g.CurrentWindow
local w
if bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasWidth) ~= 0 then
w = g.NextItemData.Width
else
w = window.DC.ItemWidth
end
if w < 0.0 then
local region_avail_x = ImGui.GetContentRegionAvail().x
w = ImMax(1.0, region_avail_x + w)
end
w = IM_TRUNC(w)
return w
end
--- @param size ImVec2
--- @param default_w float
--- @param default_h float
--- @return ImVec2
function ImGui.CalcItemSize(size, default_w, default_h)
local avail
if size.x < 0.0 or size.y < 0.0 then
avail = ImGui.GetContentRegionAvail()
end
if size.x == 0.0 then
size.x = default_w
elseif size.x < 0.0 then
size.x = ImMax(4.0, avail.x + size.x) -- size.x is negative here so we are subtracting
end
if size.y == 0.0 then
size.y = default_h
elseif size.y < 0.0 then
size.y = ImMax(4.0, avail.y + size.y) -- size.y is negative here so we are subtracting
end
return size
end
function ImGui.GetTextLineHeight()
local g = GImGui
return g.FontSize
end
function ImGui.IsItemActive()
local g = GImGui
if g.ActiveId ~= 0 then
return g.ActiveId == g.LastItemData.ID
end
return false
end
function ImGui.IsItemFocused()
local g = GImGui
if g.NavId ~= g.LastItemData.ID or g.NavId == 0 then
return false
end
local window = g.CurrentWindow
if g.LastItemData.ID == window.ID and window.WriteAccessed then
return false
end
return true
end
function ImGui.IsItemDeactivated()
local g = GImGui
if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasDeactivated) ~= 0 then
return bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Deactivated) ~= 0
end
return g.DeactivatedItemData.ID == g.LastItemData.ID and g.LastItemData.ID ~= 0 and g.DeactivatedItemData.ElapseFrame >= g.FrameCount
end
function ImGui.IsItemDeactivatedAfterEdit()
local g = GImGui
return ImGui.IsItemDeactivated() and g.DeactivatedItemData.HasBeenEditedBefore
end
---------------------------------------------------------------------------------------
-- [SECTION] WINDOW FOCUS
---------------------------------------------------------------------------------------
--- @param window? ImGuiWindow
--- @param flags? ImGuiFocusRequestFlags
function ImGui.FocusWindow(window, flags)
if flags == nil then flags = 0 end
local g = GImGui
if bit32.band(flags, ImGuiFocusRequestFlags.UnlessBelowModal) ~= 0 and g.NavWindow ~= window then
local blocking_modal = ImGui.FindBlockingModal(window)
if blocking_modal then
-- IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".", window ? window->Name : "<NULL>", blocking_modal->Name)
if window and window == window.RootWindow and bit32.band(window.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then
ImGui.BringWindowToDisplayBehind(window, blocking_modal)
end
ImGui.ClosePopupsOverWindow(ImGui.GetTopMostPopupModal(), false)
return
end
end
if bit32.band(flags, ImGuiFocusRequestFlags.RestoreFocusedChild) ~= 0 and window ~= nil then
window = ImGui.NavRestoreLastChildNavWindow(window)
end
if g.NavWindow ~= window then
ImGui.SetNavWindow(window)
if window and g.NavHighlightItemUnderNav then
g.NavMousePosDirty = true
end
g.NavId = window and window.NavLastIds[0] or 0
g.NavLayer = ImGuiNavLayer.Main
ImGui.SetNavFocusScope(window and window.NavRootFocusScopeId or 0)
g.NavIdIsAlive = false
g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid
-- Close popups if any
ImGui.ClosePopupsOverWindow(window, false)
end
IM_ASSERT(window == nil or window.RootWindowDockTree ~= nil)
local focus_front_window = window and window.RootWindow or nil
local display_front_window = window and window.RootWindowDockTree or nil
local dock_node = window and window.DockNode or nil
local active_id_window_is_dock_node_host = g.ActiveIdWindow and dock_node and dock_node.HostWindow == g.ActiveIdWindow
if g.ActiveId ~= 0 and g.ActiveIdWindow and g.ActiveIdWindow.RootWindow ~= focus_front_window then
if not g.ActiveIdNoClearOnFocusLoss and not active_id_window_is_dock_node_host then
ImGui.ClearActiveID()
end
end
if not window then
return
end
window.LastFrameJustFocused = g.FrameCount
ImGui.BringWindowToFocusFront(focus_front_window)
if bit32.band(bit32.bor(window.Flags, focus_front_window.Flags, display_front_window.Flags), ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then
ImGui.BringWindowToDisplayFront(display_front_window)
end
end
--- @param window ImGuiWindow
--- @return int
function ImGui.FindWindowFocusIndex(window)
local g = GImGui
-- IM_UNUSED(g)
local order = window.FocusOrder
IM_ASSERT(window.RootWindow == window) -- No child window (not testing _ChildWindow because of docking)
IM_ASSERT(g.WindowsFocusOrder.Data[order] == window)
return order
end
--- @param window ImGuiWindow
--- @return bool
function ImGui.IsWindowNavFocusable(window)
return window.WasActive and window == window.RootWindow and bit32.band(window.Flags, ImGuiWindowFlags.NoNavFocus) == 0
end
--- @param i_start int
--- @param i_stop int
--- @param dir int
--- @return ImGuiWindow?
function ImGui.FindWindowNavFocusable(i_start, i_stop, dir)
local g = GImGui
local i = i_start
while i >= 1 and i <= g.WindowsFocusOrder.Size and i ~= i_stop do
local window = g.WindowsFocusOrder.Data[i]
if ImGui.IsWindowNavFocusable(window) then
return window
end
i = i + dir
end
return nil
end
function ImGui.UpdateWindowInFocusOrderList(window, just_created, new_flags)
local g = GImGui
local new_is_explicit_child = (bit32.band(new_flags, ImGuiWindowFlags.ChildWindow) ~= 0) and ((bit32.band(new_flags, ImGuiWindowFlags.Popup) == 0) or (bit32.band(new_flags, ImGuiWindowFlags.ChildMenu) ~= 0))
local child_flag_changed = (new_is_explicit_child ~= window.IsExplicitChild)
if (just_created or child_flag_changed) and not new_is_explicit_child then
IM_ASSERT(not g.WindowsFocusOrder:contains(window))
g.WindowsFocusOrder:push_back(window)
window.FocusOrder = g.WindowsFocusOrder.Size
elseif not just_created and child_flag_changed and new_is_explicit_child then
IM_ASSERT(g.WindowsFocusOrder.Data[window.FocusOrder] == window)
for n = window.FocusOrder + 1, g.WindowsFocusOrder.Size do
g.WindowsFocusOrder.Data[n].FocusOrder = g.WindowsFocusOrder.Data[n].FocusOrder - 1
end
g.WindowsFocusOrder:erase(window.FocusOrder)
window.FocusOrder = -1
end
window.IsExplicitChild = new_is_explicit_child
end
--- @param window? ImGuiWindow
function ImGui.BringWindowToFocusFront(window)
local g = GImGui
IM_ASSERT(window == window.RootWindow)
local cur_order = window.FocusOrder
IM_ASSERT(g.WindowsFocusOrder.Data[cur_order] == window)
if g.WindowsFocusOrder:back() == window then
return
end
local new_order = g.WindowsFocusOrder.Size
for n = cur_order, new_order - 1 do
g.WindowsFocusOrder.Data[n] = g.WindowsFocusOrder.Data[n + 1]
g.WindowsFocusOrder.Data[n].FocusOrder = g.WindowsFocusOrder.Data[n].FocusOrder - 1
IM_ASSERT(g.WindowsFocusOrder.Data[n].FocusOrder == n)
end
g.WindowsFocusOrder.Data[new_order] = window
window.FocusOrder = new_order
end
--- @param window? ImGuiWindow
function ImGui.BringWindowToDisplayFront(window)
local g = GImGui
local current_front_window = g.Windows:back()
if current_front_window == window or current_front_window.RootWindowDockTree == window then
return
end
for i, this_window in g.Windows:iter() do
if this_window == window then
g.Windows:erase(i)
break
end
end
g.Windows:push_back(window)
end
--- @param window ImGuiWindow
--- @param behind_window ImGuiWindow
function ImGui.BringWindowToDisplayBehind(window, behind_window)
IM_ASSERT(window ~= nil and behind_window ~= nil)
local g = GImGui
window = window.RootWindow
behind_window = behind_window.RootWindow
-- TODO:
end
--- @param under_this_window? ImGuiWindow
--- @param ignore_window? ImGuiWindow
--- @param filter_viewport? ImGuiViewport
--- @param flags ImGuiFocusRequestFlags
function ImGui.FocusTopMostWindowUnderOne(under_this_window, ignore_window, filter_viewport, flags)
local g = GImGui
local start_idx = g.WindowsFocusOrder.Size
if under_this_window ~= nil then
-- Aim at root window behind us, if we are in a child window that's our own root (see #4640)
local offset = -1
while bit32.band(under_this_window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 do
under_this_window = under_this_window.ParentWindow
offset = 0
end
--- @cast under_this_window ImGuiWindow
start_idx = ImGui.FindWindowFocusIndex(under_this_window) + offset
end
for i = start_idx, 1, -1 do
repeat
local window = g.WindowsFocusOrder.Data[i]
if window == ignore_window or not window.WasActive then
break
end
if filter_viewport ~= nil and window.Viewport ~= filter_viewport then
break
end
if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs)) ~= bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs) then
ImGui.FocusWindow(window, flags)
return
end
until true
end
ImGui.FocusWindow(nil, flags)
end
--- @param id ImGuiID
--- @param window ImGuiWindow
function ImGui.SetFocusID(id, window)
local g = GImGui
IM_ASSERT(id ~= 0)
if g.NavWindow ~= window then
ImGui.SetNavWindow(window)
end
local nav_layer = window.DC.NavLayerCurrent
g.NavId = id
g.NavLayer = nav_layer
ImGui.SetNavFocusScope(g.CurrentFocusScopeId)
window.NavLastIds[nav_layer] = id
if g.LastItemData.ID == id then
ImRect_Copy(window.NavRectRel[nav_layer], ImGui.WindowRectAbsToRel(window, g.LastItemData.NavRect))
end
g.NavIdItemFlags = (g.LastItemData.ID == id) and g.LastItemData.ItemFlags or ImGuiItemFlags.None
if id == g.ActiveIdIsAlive then
g.NavIdIsAlive = true
end
if g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then
g.NavHighlightItemUnderNav = true
elseif g.IO.ConfigNavCursorVisibleAuto then
g.NavCursorVisible = false
end
ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X)
ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y)
end
function ImGui.StopMouseMovingWindow()
local g = GImGui
local window = g.MovingWindow
if window and window.Viewport then
if bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) ~= 0 then
ImGui.UpdateTryMergeWindowIntoHostViewport(window.RootWindowDockTree, g.MouseViewport)
end
if (not ImGui.IsDragDropPayloadBeingAccepted()) then
g.MouseViewport = window.Viewport
end
local window_can_use_inputs = bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0
if window_can_use_inputs then
window.Viewport.Flags = bit32.band(window.Viewport.Flags, bit32.bnot(ImGuiViewportFlags.NoInputs))
end
end
g.MovingWindow = nil
end
--- @param id ImGuiID
--- @param window? ImGuiWindow
function ImGui.SetActiveID(id, window)
local g = GImGui
if g.ActiveId ~= 0 then
local deactivated_data = g.DeactivatedItemData
deactivated_data.ID = g.ActiveId
deactivated_data.ElapseFrame = (g.LastItemData.ID == g.ActiveId) and g.FrameCount or g.FrameCount + 1 -- FIXME: OK to use LastItemData?
deactivated_data.HasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore
deactivated_data.IsAlive = (g.ActiveIdIsAlive == g.ActiveId)
if g.InputTextState.ID == g.ActiveId then
ImGui.InputTextDeactivateHook(g.ActiveId)
end
if g.MovingWindow and (g.ActiveId == g.MovingWindow.MoveId) then
print("SetActiveID() cancel MovingWindow")
ImGui.StopMouseMovingWindow()
end
end
g.ActiveIdIsJustActivated = (g.ActiveId ~= id)
if (g.ActiveIdIsJustActivated) then
-- IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() 0x%08X in \"%s\"%*s(previously 0x%08X in \"%s\")\n", id, window ? window->Name : "",
-- ImMax(0, 20 - (int)(window ? strlen(window->Name) : 0)), "", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "");
g.ActiveIdTimer = 0.0
g.ActiveIdHasBeenPressedBefore = false
g.ActiveIdHasBeenEditedBefore = false
g.ActiveIdMouseButton = -1
if id ~= 0 then
g.LastActiveId = id
g.LastActiveIdTimer = 0.0
end
end
g.ActiveId = id
g.ActiveIdAllowOverlap = false
g.ActiveIdNoClearOnFocusLoss = false
g.ActiveIdWindow = window
g.ActiveIdHasBeenEditedThisFrame = false
g.ActiveIdFromShortcut = false
g.ActiveIdDisabledId = 0
if id ~= 0 then
g.ActiveIdIsAlive = id
if g.NavActivateId == id or g.NavJustMovedToId == id then
g.ActiveIdSource = g.NavInputSource
else
g.ActiveIdSource = ImGuiInputSource.Mouse
end
IM_ASSERT(g.ActiveIdSource ~= ImGuiInputSource.None)
end
g.ActiveIdUsingNavDirMask = 0x00
g.ActiveIdUsingAllKeyboardKeys = false
end
function ImGui.ClearActiveID()
ImGui.SetActiveID(0, nil)
end
--- @param str_id string|int
function ImGui.PushID(str_id)
local g = GImGui
local window = g.CurrentWindow
local id = window:GetID(str_id)
window.IDStack:push_back(id)
end
--- @param id ImGuiID
function ImGui.PushOverrideID(id)
local g = GImGui
local window = g.CurrentWindow
-- TODO: DebugHookIdInfo()
window.IDStack:push_back(id)
end
function ImGui.PopID()
local window = GImGui.CurrentWindow
IM_ASSERT_USER_ERROR_RET(window.IDStack.Size > 1, "Calling PopID() too many times!")
window.IDStack:pop_back()
end
--- @param id string|int
--- @return ImGuiID
function MT.ImGuiWindow:GetID(id)
local seed = self.IDStack:back()
if type(id) == "string" then
return ImHashStr(id, nil, seed)
else --- @cast id int
return ImHashData(id, -1, seed)
end
end
-- This is only used in rare/specific situations to manufacture an ID out of nowhere
-- FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those?
--- @param p_abs ImVec2
--- @return ImGuiID
function MT.ImGuiWindow:GetIDFromPos(p_abs)
local seed = self.IDStack:back()
local p_rel = ImGui.WindowPosAbsToRel(self, p_abs)
return ImHashData(p_rel, 2, seed)
end
--- @param id ImGuiID
function ImGui.SetHoveredID(id)
local g = GImGui
g.HoveredId = id
g.HoveredIdAllowOverlap = false
if id ~= 0 and g.HoveredIdPreviousFrame ~= id then
g.HoveredIdTimer = 0.0
g.HoveredIdNotActiveTimer = 0.0
end
end
--- @param flags ImGuiHoveredFlags
--- @return float
local function CalcDelayFromHoveredFlags(flags)
local g = GImGui
if bit32.band(flags, ImGuiHoveredFlags.DelayNormal) ~= 0 then
return g.Style.HoverDelayNormal
end
if bit32.band(flags, ImGuiHoveredFlags.DelayShort) ~= 0 then
return g.Style.HoverDelayShort
end
return 0.0
end
--- @param user_flags ImGuiHoveredFlags
--- @param shared_flags ImGuiHoveredFlags
local function ApplyHoverFlagsForTooltip(user_flags, shared_flags)
if bit32.band(user_flags, bit32.bor(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal)) ~= 0 then
shared_flags = bit32.band(shared_flags, bit32.bnot(bit32.bor(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal)))
end
return bit32.bor(user_flags, shared_flags)
end
--- @param id ImGuiID
function ImGui.MarkItemEdited(id)
-- This marking is to be able to provide info for IsItemDeactivatedAfterEdit().
-- ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
local g = GImGui
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal)
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) ~= 0 then
return
end
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Edited)
if g.ActiveId == id or g.ActiveId == 0 then
-- FIXME: Can't we fully rely on LastItemData yet?
g.AnyIdHasBeenEditedThisFrame = true
g.ActiveIdHasBeenEditedThisFrame = true
g.ActiveIdHasBeenEditedBefore = true
end
if g.DeactivatedItemData.ID == id then
g.DeactivatedItemData.HasBeenEditedBefore = true
end
-- We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
-- We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
-- FIXME: This assert is getting a bit meaningless over time. It helped detect some unusual use cases but eventually it is becoming an unnecessary restriction.
IM_ASSERT(g.DragDropActive or g.ActiveId == id or g.ActiveId == 0 or g.DeactivatedItemData.ID == id or g.ActiveIdPreviousFrame == id or g.NavJustMovedToId or (g.CurrentMultiSelect ~= nil and g.BoxSelectState.IsActive))
-- IM_ASSERT(g.CurrentWindow.DC.LastItemId == id)
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Edited)
end
--- @param window ImGuiWindow
--- @param flags ImGuiHoveredFlags
function ImGui.IsWindowContentHoverable(window, flags)
-- An active popup disable hovering on other windows (apart from its own children)
-- FIXME-OPT: This could be cached/stored within the window.
local g = GImGui
if g.NavWindow then
local focused_root_window = g.NavWindow.RootWindowDockTree
if focused_root_window.WasActive and focused_root_window ~= window.RootWindowDockTree then
-- For the purpose of those flags we differentiate "standard popup" from "modal popup"
-- NB: The 'else' is important because Modal windows are also Popups.
local want_inhibit = false
if bit32.band(focused_root_window.Flags, ImGuiWindowFlags.Modal) ~= 0 then
want_inhibit = true
elseif (bit32.band(focused_root_window.Flags, ImGuiWindowFlags.Popup) ~= 0) and (bit32.band(flags, ImGuiHoveredFlags.AllowWhenBlockedByPopup) == 0) then
want_inhibit = true
end
-- Inhibit hover unless the window is within the stack of our modal/popup
if want_inhibit then
if not ImGui.IsWindowWithinBeginStackOf(window.RootWindow, focused_root_window) then
return false
end
end
end
end
-- Filter by viewport
if (window.Viewport ~= g.MouseViewport) then
if (g.MovingWindow == nil or window.RootWindowDockTree ~= g.MovingWindow.RootWindowDockTree) then
return false
end
end
return true
end
--- @param flags? ImGuiHoveredFlags
function ImGui.IsItemHovered(flags)
if flags == nil then flags = 0 end
local g = GImGui
local window = g.CurrentWindow
IM_ASSERT_USER_ERROR(bit32.band(flags, bit32.bnot(ImGuiHoveredFlags.AllowedMaskForIsItemHovered)) == 0, "Invalid flags for IsItemHovered()!")
if g.NavHighlightItemUnderNav and g.NavCursorVisible and bit32.band(flags, ImGuiHoveredFlags.NoNavOverride) == 0 then
if not ImGui.IsItemFocused() then
return false
end
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 and bit32.band(flags, ImGuiHoveredFlags.AllowWhenDisabled) == 0 then
return false
end
if bit32.band(flags, ImGuiHoveredFlags.ForTooltip) ~= 0 then
flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav)
end
else
local status_flags = g.LastItemData.StatusFlags
if bit32.band(status_flags, ImGuiItemStatusFlags.HoveredRect) == 0 then
return false
end
if bit32.band(flags, ImGuiHoveredFlags.ForTooltip) ~= 0 then
flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse)
end
if g.HoveredWindow ~= window and bit32.band(status_flags, ImGuiItemStatusFlags.HoveredWindow) == 0 then
if bit32.band(flags, ImGuiHoveredFlags.AllowWhenOverlappedByWindow) == 0 then
return false
end
end
local id = g.LastItemData.ID
if bit32.band(flags, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) == 0 then
if g.ActiveId ~= 0 and g.ActiveId ~= id and not g.ActiveIdAllowOverlap and not g.ActiveIdFromShortcut then
local cancel_is_hovered = true
if g.ActiveId == window.MoveId and (id == 0 or g.ActiveIdDisabledId == id) then
cancel_is_hovered = false
end
if g.ActiveId == window.TabId then
cancel_is_hovered = false
end
if cancel_is_hovered then
return false
end
end
end
if not ImGui.IsWindowContentHoverable(window, flags) and bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoWindowHoverableCheck) == 0 then
return false
end
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 and bit32.band(flags, ImGuiHoveredFlags.AllowWhenDisabled) == 0 then
return false
end
if id == window.MoveId and window.WriteAccessed then
return false
end
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowOverlap) ~= 0 and id ~= 0 then
if bit32.band(flags, ImGuiHoveredFlags.AllowWhenOverlappedByItem) == 0 then
if g.HoveredIdPreviousFrame ~= g.LastItemData.ID then
return false
end
end
end
end
local delay = CalcDelayFromHoveredFlags(flags)
if delay > 0.0 or bit32.band(flags, ImGuiHoveredFlags.Stationary) ~= 0 then
local hover_delay_id
if g.LastItemData.ID ~= 0 then
hover_delay_id = g.LastItemData.ID
else
hover_delay_id = window:GetIDFromPos(g.LastItemData.Rect.Min)
end
if bit32.band(flags, ImGuiHoveredFlags.NoSharedDelay) ~= 0 and g.HoverItemDelayIdPreviousFrame ~= hover_delay_id then
g.HoverItemDelayTimer = 0.0
end
g.HoverItemDelayId = hover_delay_id
if bit32.band(flags, ImGuiHoveredFlags.Stationary) ~= 0 and g.HoverItemUnlockedStationaryId ~= hover_delay_id then
return false
end
if g.HoverItemDelayTimer < delay then
return false
end
end
return true
end
--- @param bb ImRect
--- @param id ImGuiID
--- @param item_flags ImGuiItemFlags
function ImGui.ItemHoverable(bb, id, item_flags)
local g = GImGui
local window = g.CurrentWindow
if not IMGUI_DISABLE_DEBUG_TOOLS then
if id ~= 0 and g.HoveredIdPreviousFrame == id and bit32.band(item_flags, ImGuiItemFlags.AllowDuplicateId) == 0 then
g.HoveredIdPreviousFrameItemCount = g.HoveredIdPreviousFrameItemCount + 1
if g.DebugDrawIdConflictsId == id then
window.DrawList:AddRect(bb.Min - ImVec2(1, 1), bb.Max + ImVec2(1, 1), IM_COL32(255, 0, 0, 255), 0.0, 2.0, ImDrawFlags.None)
end
end
end
if g.HoveredWindow ~= window then
return false
end
if not ImGui.IsMouseHoveringRect(bb.Min, bb.Max) then
return false
end
if g.HoveredId ~= 0 and g.HoveredId ~= id and not g.HoveredIdAllowOverlap then
return false
end
if g.ActiveId ~= 0 and g.ActiveId ~= id and not g.ActiveIdAllowOverlap then
if not g.ActiveIdFromShortcut then
return false
end
end
if (bit32.band(item_flags, ImGuiItemFlags.NoWindowHoverableCheck) == 0) and not ImGui.IsWindowContentHoverable(window, ImGuiHoveredFlags.None) then
g.HoveredIdIsDisabled = true
return false
end
if id ~= 0 then
if g.DragDropActive and g.DragDropPayload.SourceId == id and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoDisableHover) == 0) then
return false
end
ImGui.SetHoveredID(id)
if bit32.band(item_flags, ImGuiItemFlags.AllowOverlap) ~= 0 then
g.HoveredIdAllowOverlap = true
if g.HoveredIdPreviousFrame ~= id then
return false
end
end
if id == g.LastItemData.ID and (bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasShortcut) ~= 0) and g.ActiveId ~= id then
if ImGui.IsItemHovered(bit32.bor(ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.DelayNormal)) then
ImGui.SetTooltip("%s", ImGui.GetKeyChordName(g.LastItemData.Shortcut))
end
end
end
if bit32.band(item_flags, ImGuiItemFlags.Disabled) ~= 0 then
-- Release active id if turning disabled
if g.ActiveId == id and id ~= 0 then
ImGui.ClearActiveID()
end
g.HoveredIdIsDisabled = true
return false
end
if g.NavHighlightItemUnderNav and (bit32.band(item_flags, ImGuiItemFlags.NoNavDisableMouseHover) == 0) then
return false
end
return true
end
--- @param bb ImRect
--- @param id ImGuiID
--- @return bool
function ImGui.IsClippedEx(bb, id)
local g = GImGui
local window = g.CurrentWindow
if not bb:Overlaps(window.ClipRect) then
if id == 0 or (id ~= g.ActiveId and id ~= g.ActiveIdPreviousFrame and id ~= g.NavId and id ~= g.NavActivateId) then
if not g.ItemUnclipByLog then
return true
end
end
end
return false
end
--- @param item_id ImGuiID
--- @param item_flags ImGuiItemFlags
--- @param status_flags ImGuiItemStatusFlags
--- @param item_rect ImRect
function ImGui.SetLastItemData(item_id, item_flags, status_flags, item_rect)
local g = GImGui
g.LastItemData.ID = item_id
g.LastItemData.ItemFlags = item_flags
g.LastItemData.StatusFlags = status_flags
ImRect_Copy(g.LastItemData.Rect, item_rect)
ImRect_Copy(g.LastItemData.NavRect, item_rect)
end
--- @param window ImGuiWindow
--- @param rect ImRect
function ImGui.SetLastItemDataForWindow(window, rect)
local g = GImGui
if window.DockIsActive then
ImGui.SetLastItemData(window.MoveId, g.CurrentItemFlags, window.DC.DockTabItemStatusFlags, window.DC.DockTabItemRect)
else
ImGui.SetLastItemData(window.MoveId, g.CurrentItemFlags, window.DC.WindowItemStatusFlags, rect)
end
end
--- @param c unsigned_int
function MT.ImGuiIO:AddInputCharacter(c)
IM_ASSERT(self.Ctx ~= nil)
local g = self.Ctx
if c == 0 or not self.AppAcceptingEvents then
return
end
local e = ImGuiInputEvent()
e.Type = ImGuiInputEventType.Text
e.Source = ImGuiInputSource.Keyboard
e.EventId = g.InputEventsNextEventId
g.InputEventsNextEventId = g.InputEventsNextEventId + 1
e.Text = ImGuiInputEventText()
e.Text.Char = c
g.InputEventsQueue:push_back(e)
end
--- @param c ImWchar16
function MT.ImGuiIO:AddInputCharacterUTF16(c)
if (c == 0 and self.InputQueueSurrogate == 0) or not self.AppAcceptingEvents then
return
end
if bit32.band(c, 0xFC00) == 0xD800 then -- High surrogate, must save
if self.InputQueueSurrogate ~= 0 then
self:AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID)
end
self.InputQueueSurrogate = c
return
end
local cp = c
if self.InputQueueSurrogate ~= 0 then
if bit32.band(c, 0xFC00) ~= 0xDC00 then -- Invalid low surrogate
self:AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID)
else
-- #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
cp = IM_UNICODE_CODEPOINT_INVALID
-- #endif
end
self.InputQueueSurrogate = 0
end
self:AddInputCharacter(cp)
end
function MT.ImGuiIO:ClearEventsQueue()
IM_ASSERT(self.Ctx ~= nil)
local g = GImGui
g.InputEventsQueue:clear()
end
function MT.ImGuiIO:ClearInputKeys()
local g = self.Ctx
for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do
if not ImGui.IsMouseKey(key) then
local key_data = g.IO.KeysData[key - ImGuiKey.NamedKey_BEGIN]
key_data.Down = false
key_data.DownDuration = -1.0
key_data.DownDurationPrev = -1.0
end
end
self.KeyCtrl = false
self.KeyShift = false
self.KeyAlt = false
self.KeySuper = false
self.KeyMods = ImGuiMod_None
self.InputQueueCharacters:resize(0)
end
function MT.ImGuiIO:ClearInputMouse()
for key = ImGuiKey_Mouse_BEGIN, ImGuiKey_Mouse_END - 1 do
local key_data = self.KeysData[key - ImGuiKey.NamedKey_BEGIN]
if key_data then
key_data.Down = false
key_data.DownDuration = -1.0
key_data.DownDurationPrev = -1.0
end
end
self.MousePos = ImVec2(-FLT_MAX, -FLT_MAX)
for n = 0, 2 do -- IM_COUNTOF(MouseDown)
self.MouseDown[n] = false
self.MouseDownDuration[n] = -1.0
self.MouseDownDurationPrev[n] = -1.0
end
self.MouseWheel = 0
self.MouseWheelH = 0
end
--- @param ctx ImGuiContext
--- @param type ImGuiInputEventType
--- @param arg? int
--- @return ImGuiInputEvent?
function MT.ImGuiIO:FindLatestInputEvent(ctx, type, arg)
if arg == nil then arg = -1 end
local g = ctx
for n = g.InputEventsQueue.Size, 1, -1 do
local e = g.InputEventsQueue.Data[n]
if e.Type ~= type then
elseif type == ImGuiInputEventType.Key and e.Key.Key ~= arg then
elseif type == ImGuiInputEventType.MouseButton and e.MouseButton.Button ~= arg then
else
return e
end
end
return nil
end
--- @param key ImGuiKey
--- @param down bool
--- @param analog_value float
function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value)
IM_ASSERT(self.Ctx ~= nil)
if key == ImGuiKey.None or not self.AppAcceptingEvents then
return
end
local g = self.Ctx
IM_ASSERT(ImGui.IsNamedKeyOrMod(key))
IM_ASSERT(ImGui.IsAliasKey(key) == false)
-- MacOS: swap Cmd(Super) and Ctrl
if (g.IO.ConfigMacOSXBehaviors) then
if (key == ImGuiMod_Super) then key = ImGuiMod_Ctrl
elseif (key == ImGuiMod_Ctrl) then key = ImGuiMod_Super
elseif (key == ImGuiKey.LeftSuper) then key = ImGuiKey.LeftCtrl
elseif (key == ImGuiKey.RightSuper) then key = ImGuiKey.RightCtrl
elseif (key == ImGuiKey.LeftCtrl) then key = ImGuiKey.LeftSuper
elseif (key == ImGuiKey.RightCtrl) then key = ImGuiKey.RightSuper
end
end
local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Key, key)
local key_data = ImGui.GetKeyData(g, key)
local latest_key_down = latest_event and latest_event.Key.Down or key_data.Down
local latest_key_analog = latest_event and latest_event.Key.AnalogValue or key_data.AnalogValue
if latest_key_down == down and latest_key_analog == analog_value then
return
end
local e = ImGuiInputEvent()
e.Type = ImGuiInputEventType.Key
e.Source = ImGui.IsGamepadKey(key) and ImGuiInputSource.Gamepad or ImGuiInputSource.Keyboard
e.EventId = g.InputEventsNextEventId
g.InputEventsNextEventId = g.InputEventsNextEventId + 1
e.Key = ImGuiInputEventKey()
e.Key.Key = key
e.Key.Down = down
e.Key.AnalogValue = analog_value
g.InputEventsQueue:push_back(e)
end
--- @param key ImGuiKey
--- @param down bool
function MT.ImGuiIO:AddKeyEvent(key, down)
if not self.AppAcceptingEvents then
return
end
self:AddKeyAnalogEvent(key, down, (down and 1.0 or 0.0))
end
--- @param accepting_events bool
function MT.ImGuiIO:SetAppAcceptingEvents(accepting_events)
self.AppAcceptingEvents = accepting_events
end
--- @param source ImGuiMouseSource
function MT.ImGuiIO:AddMouseSourceEvent(source)
IM_ASSERT(self.Ctx ~= nil)
local g = self.Ctx
g.InputEventsNextMouseSource = source
end
--- @param viewport_id ImGuiID
function MT.ImGuiIO:AddMouseViewportEvent(viewport_id)
IM_ASSERT(self.Ctx ~= nil)
local g = self.Ctx
-- IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags.HasMouseHoveredViewport);
if (not self.AppAcceptingEvents) then
return
end
-- Filter duplicate
local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MouseViewport)
local latest_viewport_id
if latest_event then
latest_viewport_id = latest_event.MouseViewport.HoveredViewportID
else
latest_viewport_id = g.IO.MouseHoveredViewport
end
if (latest_viewport_id == viewport_id) then
return
end
local e = ImGuiInputEvent()
e.Type = ImGuiInputEventType.MouseViewport
e.Source = ImGuiInputSource.Mouse
e.MouseViewport = ImGuiInputEventMouseViewport()
e.MouseViewport.HoveredViewportID = viewport_id
g.InputEventsQueue:push_back(e)
end
--- @param focused bool
function MT.ImGuiIO:AddFocusEvent(focused)
IM_ASSERT(self.Ctx ~= nil)
local g = self.Ctx
local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Focus)
local latest_focused = latest_event and latest_event.AppFocused.Focused or (not g.IO.AppFocusLost)
if latest_focused == focused or (self.ConfigDebugIgnoreFocusLoss and not focused) then
return
end
local e = ImGuiInputEvent()
e.Type = ImGuiInputEventType.Focus
e.EventId = g.InputEventsNextEventId
g.InputEventsNextEventId = g.InputEventsNextEventId + 1
e.AppFocused = ImGuiInputEventAppFocused()
e.AppFocused.Focused = focused
g.InputEventsQueue:push_back(e)
end
--- @param x float
--- @param y float
function MT.ImGuiIO:AddMousePosEvent(x, y)
IM_ASSERT(self.Ctx ~= nil)
if not self.AppAcceptingEvents then
return
end
local g = self.Ctx
local x_val = x
if x > -FLT_MAX then
x_val = ImFloor(x)
end
local y_val = y
if y > -FLT_MAX then
y_val = ImFloor(y)
end
local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MousePos)
local latest_pos = latest_event and ImVec2(latest_event.MousePos.PosX, latest_event.MousePos.PosY) or self.MousePos
if latest_pos.x == x_val and latest_pos.y == y_val then
return
end
local e = ImGuiInputEvent()
e.Type = ImGuiInputEventType.MousePos
e.Source = ImGuiInputSource.Mouse
e.EventId = g.InputEventsNextEventId
g.InputEventsNextEventId = g.InputEventsNextEventId + 1
e.MousePos = ImGuiInputEventMousePos()
e.MousePos.PosX = x_val
e.MousePos.PosY = y_val
e.MousePos.MouseSource = g.InputEventsNextMouseSource
g.InputEventsQueue:push_back(e)
end
--- @param mouse_button ImGuiMouseButton
--- @param down bool
function MT.ImGuiIO:AddMouseButtonEvent(mouse_button, down)
IM_ASSERT(self.Ctx ~= nil)
local g = self.Ctx
IM_ASSERT(mouse_button >= 0 and mouse_button < ImGuiMouseButton.COUNT)
if not self.AppAcceptingEvents then
return
end
-- On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
if self.ConfigMacOSXBehaviors and mouse_button == 0 and g.IO.MouseCtrlLeftAsRightClick then
-- Order of both statements matters: this event will still release mouse button 1
mouse_button = 1
if not down then
self.MouseCtrlLeftAsRightClick = false
end
end
local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MouseButton, mouse_button)
local latest_button_down = latest_event and latest_event.MouseButton.Down or self.MouseDown[mouse_button]
if latest_button_down == down then
return
end
-- On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
-- - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
-- - At this point we want from !down to down, so this is handling the initial press.
if self.ConfigMacOSXBehaviors and mouse_button == 0 and down then
local latest_super_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Key, ImGuiMod_Super)
if latest_super_event and latest_super_event.Key.Down or self.KeySuper then
-- IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n")
self.MouseCtrlLeftAsRightClick = true
self:AddMouseButtonEvent(1, true) -- This is just quicker to write that passing through, as we need to filter duplicate again.
return
end
end
local e = ImGuiInputEvent()
e.Type = ImGuiInputEventType.MouseButton
e.Source = ImGuiInputSource.Mouse
e.EventId = g.InputEventsNextEventId
g.InputEventsNextEventId = g.InputEventsNextEventId + 1
e.MouseButton = ImGuiInputEventMouseButton()
e.MouseButton.Button = mouse_button
e.MouseButton.Down = down
e.MouseButton.MouseSource = g.InputEventsNextMouseSource
g.InputEventsQueue:push_back(e)
end
--- @param wheel_x float
--- @param wheel_y float
function MT.ImGuiIO:AddMouseWheelEvent(wheel_x, wheel_y)
IM_ASSERT(self.Ctx ~= nil)
local g = self.Ctx
if not self.AppAcceptingEvents or (wheel_x == 0 and wheel_y == 0) then
return
end
local e = ImGuiInputEvent()
e.Type = ImGuiInputEventType.MouseWheel
e.Source = ImGuiInputSource.Mouse
e.EventId = g.InputEventsNextEventId
g.InputEventsNextEventId = g.InputEventsNextEventId + 1
e.MouseWheel = ImGuiInputEventMouseWheel()
e.MouseWheel.WheelX = wheel_x
e.MouseWheel.WheelY = wheel_y
e.MouseWheel.MouseSource = g.InputEventsNextMouseSource
g.InputEventsQueue:push_back(e)
end
--- @param key ImGuiKey
local function GetModForLRModKey(key)
if key == ImGuiKey.LeftCtrl or key == ImGuiKey.RightCtrl then
return ImGuiMod_Ctrl
end
if key == ImGuiKey.LeftShift or key == ImGuiKey.RightShift then
return ImGuiMod_Shift
end
if key == ImGuiKey.LeftAlt or key == ImGuiKey.RightAlt then
return ImGuiMod_Alt
end
if key == ImGuiKey.LeftSuper or key == ImGuiKey.RightSuper then
return ImGuiMod_Super
end
return ImGuiMod_None
end
--- @param key_chord ImGuiKeyChord
function ImGui.FixupKeyChord(key_chord)
local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_))
if ImGui.IsLRModKey(key) then
key_chord = bit32.bor(key_chord, GetModForLRModKey(key))
end
return key_chord
end
--- @param ctx? ImGuiContext
--- @param key ImGuiKey
--- @return ImGuiKeyData, int
function ImGui.GetKeyData(ctx, key)
if ctx == nil then ctx = GImGui end
if bit32.band(key, ImGuiMod_Mask_) ~= 0 then
key = ImGui.ConvertSingleModFlagToKey(key)
end
IM_ASSERT(ImGui.IsNamedKey(key), "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.")
local idx = key - ImGuiKey.NamedKey_BEGIN
return ctx.IO.KeysData[idx], idx
end
--- @param key_left ImGuiKey
--- @param key_right ImGuiKey
--- @param key_up ImGuiKey
--- @param key_down ImGuiKey
function ImGui.GetKeyMagnitude2d(key_left, key_right, key_up, key_down)
return ImVec2(
ImGui.GetKeyData(nil, key_right).AnalogValue - ImGui.GetKeyData(nil, key_left).AnalogValue,
ImGui.GetKeyData(nil, key_down).AnalogValue - ImGui.GetKeyData(nil, key_up).AnalogValue
)
end
--- @param key ImGuiKey
--- @param owner_id ImGuiID
function ImGui.TestKeyOwner(key, owner_id)
if not ImGui.IsNamedKeyOrMod(key) then
return true
end
local g = GImGui --- @cast g ImGuiContext
if g.ActiveIdUsingAllKeyboardKeys and owner_id ~= g.ActiveId and owner_id ~= ImGuiKeyOwner_Any then
if key >= ImGuiKey_Keyboard_BEGIN and key < ImGuiKey_Keyboard_END then
return false
end
end
local owner_data = ImGui.GetKeyOwnerData(g, key)
if owner_id == ImGuiKeyOwner_Any then
return not owner_data.LockThisFrame
end
if owner_data.OwnerCurr ~= owner_id then
if owner_data.LockThisFrame then
return false
end
if owner_data.OwnerCurr ~= ImGuiKeyOwner_NoOwner then
return false
end
end
return true
end
--- @param key ImGuiKey
--- @param owner_id? ImGuiID
function ImGui.IsKeyDown(key, owner_id)
if owner_id == nil then owner_id = ImGuiKeyOwner_Any end
local key_data = ImGui.GetKeyData(nil, key)
if not key_data.Down then
return false
end
if not ImGui.TestKeyOwner(key, owner_id) then
return false
end
return true
end
--- @param key ImGuiKey
--- @param is_repeat? bool
function ImGui.IsKeyPressed(key, is_repeat)
if is_repeat == nil then is_repeat = true end
return ImGui.IsKeyPressedEx(key, is_repeat and ImGuiInputFlags.Repeat or ImGuiInputFlags.None, ImGuiKeyOwner_Any)
end
--- @param key ImGuiKey
--- @param owner_id? ImGuiID
--- @return bool
function ImGui.IsKeyReleased(key, owner_id)
if owner_id == nil then owner_id = ImGuiKeyOwner_Any end
local key_data = ImGui.GetKeyData(nil, key)
if key_data.DownDurationPrev < 0.0 or key_data.Down then
return false
end
if not ImGui.TestKeyOwner(key, owner_id) then
return false
end
return true
end
--- @param key ImGuiKey
--- @param flags ImGuiInputFlags
--- @param owner_id? ImGuiID
function ImGui.IsKeyPressedEx(key, flags, owner_id)
if owner_id == nil then owner_id = 0 end
local g = GImGui
local key_data = ImGui.GetKeyData(g, key)
-- In theory this should already be encoded as (DownDuration < 0.0), but testing this facilitates eating mechanism (until we finish work on key ownership)
if not key_data.Down then
return false
end
local t = key_data.DownDuration
if t < 0.0 then
return false
end
IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByIsKeyPressed)) == 0) -- Passing flags not supported by this function!
if bit32.band(flags, bit32.bor(ImGuiInputFlags.RepeatRateMask_, ImGuiInputFlags.RepeatUntilMask_)) ~= 0 then -- Setting any _RepeatXXX option enables _Repeat
flags = bit32.bor(flags, ImGuiInputFlags.Repeat)
end
local pressed = (t == 0.0)
if not pressed and bit32.band(flags, ImGuiInputFlags.Repeat) ~= 0 then
local repeat_delay, repeat_rate = ImGui.GetTypematicRepeatRate(flags)
pressed = (t > repeat_delay) and (ImGui.GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0)
if pressed and bit32.band(flags, ImGuiInputFlags.RepeatUntilMask_) ~= 0 then
-- Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
-- Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
local key_pressed_time = g.Time - t + 0.00001
if bit32.band(flags, ImGuiInputFlags.RepeatUntilKeyModsChange) ~= 0 and g.LastKeyModsChangeTime > key_pressed_time then
pressed = false
end
if bit32.band(flags, ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone) ~= 0 and g.LastKeyModsChangeFromNoneTime > key_pressed_time then
pressed = false
end
if bit32.band(flags, ImGuiInputFlags.RepeatUntilOtherKeyPress) ~= 0 and g.LastKeyboardKeyPressTime > key_pressed_time then
pressed = false
end
end
end
if not pressed then
return false
end
if not ImGui.TestKeyOwner(key, owner_id) then
return false
end
return true
end
-- TODO:
function ImGui.GetKeyChordName(key_chord)
error("NOT IMPLEMENTED", 2)
end
--- @param t0 float
--- @param t1 float
--- @param repeat_delay float
--- @param repeat_rate float
function ImGui.CalcTypematicRepeatAmount(t0, t1, repeat_delay, repeat_rate)
if t1 == 0.0 then return 1 end
if t0 >= t1 then return 0 end
if repeat_rate <= 0.0 then
if t0 < repeat_delay and t1 >= repeat_delay then
return 1
else
return 0
end
end
local count_t0
if t0 < repeat_delay then
count_t0 = -1
else
count_t0 = math.floor((t0 - repeat_delay) / repeat_rate)
end
local count_t1
if t1 < repeat_delay then
count_t1 = -1
else
count_t1 = math.floor((t1 - repeat_delay) / repeat_rate)
end
return count_t1 - count_t0
end
--- @param flags ImGuiInputFlags
--- @return float repeat_delay
--- @return float repeat_rate
function ImGui.GetTypematicRepeatRate(flags)
local g = GImGui
flags = bit32.band(flags, ImGuiInputFlags.RepeatRateMask_)
if flags == ImGuiInputFlags.RepeatRateNavMove then repeat_delay = g.IO.KeyRepeatDelay * 0.72; repeat_rate = g.IO.KeyRepeatRate * 0.80; return repeat_delay, repeat_rate
elseif flags == ImGuiInputFlags.RepeatRateNavTweak then repeat_delay = g.IO.KeyRepeatDelay * 0.72; repeat_rate = g.IO.KeyRepeatRate * 0.30; return repeat_delay, repeat_rate
else repeat_delay = g.IO.KeyRepeatDelay * 1.00; repeat_rate = g.IO.KeyRepeatRate * 1.00; return repeat_delay, repeat_rate end
end
--- @param key ImGuiKey
--- @param repeat_delay float
--- @param repeat_rate float
function ImGui.GetKeyPressedAmount(key, repeat_delay, repeat_rate)
local g = GImGui
local key_data = ImGui.GetKeyData(g, key)
if not key_data.Down then -- In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
return 0
end
local t = key_data.DownDuration
return ImGui.CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate)
end
--- @param rt ImGuiKeyRoutingTable
function ImGui.UpdateKeyRoutingTable(rt)
local g = GImGui --[[@as ImGuiContext]]
rt.EntriesNext:resize(0)
for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do
local new_routing_start_idx = rt.EntriesNext.Size + 1
local routing_entry
local old_routing_idx = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1]
while old_routing_idx ~= -1 do
repeat
routing_entry = rt.Entries[old_routing_idx]
routing_entry.RoutingCurrScore = routing_entry.RoutingNextScore
routing_entry.RoutingCurr = routing_entry.RoutingNext
routing_entry.RoutingNext = ImGuiKeyOwner_NoOwner
routing_entry.RoutingNextScore = 0
if routing_entry.RoutingCurr == ImGuiKeyOwner_NoOwner then
break
end
rt.EntriesNext:push_back(routing_entry)
if routing_entry.Mods == g.IO.KeyMods then
local owner_data = ImGui.GetKeyOwnerData(g, key)
if owner_data.OwnerCurr == ImGuiKeyOwner_NoOwner then
owner_data.OwnerCurr = routing_entry.RoutingCurr
end
end
until true
old_routing_idx = routing_entry.NextEntryIndex
end
rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = (new_routing_start_idx <= rt.EntriesNext.Size and new_routing_start_idx or -1)
for n = new_routing_start_idx, rt.EntriesNext.Size do
rt.EntriesNext[n].NextEntryIndex = (n + 1 <= rt.EntriesNext.Size) and (n + 1) or -1
end
end
rt.Entries:swap(rt.EntriesNext)
end
-- owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope()
--- @param owner_id ImGuiID
local function GetRoutingIdFromOwnerId(owner_id)
local g = GImGui
return (owner_id ~= ImGuiKeyOwner_NoOwner and owner_id ~= ImGuiKeyOwner_Any) and owner_id or g.CurrentFocusScopeId
end
--- @param key_chord ImGuiKeyChord
--- @return ImGuiKeyRoutingData
function ImGui.GetShortcutRoutingData(key_chord)
local g = GImGui
local rt = g.KeysRoutingTable
local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_))
local mods = bit32.band(key_chord, ImGuiMod_Mask_)
if key == ImGuiKey.None then
key = ImGui.ConvertSingleModFlagToKey(mods)
end
IM_ASSERT(ImGui.IsNamedKey(key))
local routing_data
local idx = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1]
while idx ~= -1 do
routing_data = rt.Entries.Data[idx]
if routing_data.Mods == mods then
return routing_data
end
idx = routing_data.NextEntryIndex
end
local routing_data_idx = rt.Entries.Size + 1
rt.Entries:push_back(ImGuiKeyRoutingData())
routing_data = rt.Entries[routing_data_idx]
routing_data.Mods = mods
routing_data.NextEntryIndex = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1]
rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = routing_data_idx
return routing_data
end
--- @param focus_scope_id ImGuiID
--- @param owner_id ImGuiID
--- @param flags ImGuiInputFlags
local function CalcRoutingScore(focus_scope_id, owner_id, flags)
local g = GImGui
if bit32.band(flags, ImGuiInputFlags.RouteFocused) ~= 0 then
if owner_id ~= 0 and g.ActiveId == owner_id then
return 300
end
if focus_scope_id == 0 then
return 0
end
for index_in_focus_path = 1, g.NavFocusRoute.Size do
if g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id then
if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then
return 599 - (index_in_focus_path - 1)
else
return 199 - (index_in_focus_path - 1)
end
end
end
return 0
elseif bit32.band(flags, ImGuiInputFlags.RouteActive) ~= 0 then
if owner_id ~= 0 and g.ActiveId == owner_id then
return 300
end
return 0
elseif bit32.band(flags, ImGuiInputFlags.RouteGlobal) ~= 0 then
if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then
return 400
end
if owner_id ~= 0 and g.ActiveId == owner_id then
return 300
end
if bit32.band(flags, ImGuiInputFlags.RouteOverFocused) ~= 0 then
return 200
end
return 1
end
IM_ASSERT(false)
return 0
end
--- @param key_chord ImGuiKeyChord
local function IsKeyChordPotentiallyCharInput(key_chord)
local g = GImGui
local mods = bit32.band(key_chord, ImGuiMod_Mask_)
local ignore_char_inputs = ((bit32.band(mods, ImGuiMod_Ctrl) ~= 0) and (bit32.band(mods, ImGuiMod_Alt) == 0)) or (g.IO.ConfigMacOSXBehaviors and (bit32.band(mods, ImGuiMod_Ctrl) ~= 0))
if ignore_char_inputs then
return false
end
local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_))
if key == ImGuiKey.None then
return false
end
return g.KeysMayBeCharInput:TestBit(key + 1) -- TestBit requires 1-based index
end
--- @param key_chord ImGuiKeyChord
--- @param flags ImGuiInputFlags
--- @param owner_id ImGuiID
function ImGui.SetShortcutRouting(key_chord, flags, owner_id)
local g = GImGui
if bit32.band(flags, ImGuiInputFlags.RouteTypeMask_) == 0 then
flags = bit32.bor(flags, ImGuiInputFlags.RouteGlobal, ImGuiInputFlags.RouteOverFocused, ImGuiInputFlags.RouteOverActive) -- IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
else
IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiInputFlags.RouteTypeMask_))) -- Check that only 1 routing flag is used
end
IM_ASSERT(owner_id ~= ImGuiKeyOwner_Any and owner_id ~= ImGuiKeyOwner_NoOwner)
if bit32.band(flags, bit32.bor(ImGuiInputFlags.RouteOverFocused, ImGuiInputFlags.RouteUnlessBgFocused)) ~= 0 then
IM_ASSERT(bit32.band(flags, ImGuiInputFlags.RouteGlobal) ~= 0)
end
if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then
IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiInputFlags.RouteGlobal, ImGuiInputFlags.RouteFocused)) ~= 0)
end
key_chord = ImGui.FixupKeyChord(key_chord)
if g.DebugBreakInShortcutRouting == key_chord then
-- IM_DEBUG_BREAK()
end
if bit32.band(flags, ImGuiInputFlags.RouteUnlessBgFocused) ~= 0 then
if g.NavWindow == nil then
return false
end
end
if bit32.band(flags, ImGuiInputFlags.RouteAlways) ~= 0 then
-- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register", ImGui.GetKeyChordName(key_chord), flags, owner_id)
return true
end
if g.ActiveId ~= 0 and g.ActiveId ~= owner_id then
if bit32.band(flags, ImGuiInputFlags.RouteActive) ~= 0 then
return false
end
if g.IO.WantTextInput and IsKeyChordPotentiallyCharInput(key_chord) then
-- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input", ImGui.GetKeyChordName(key_chord), flags, owner_id)
return false
end
if bit32.band(flags, ImGuiInputFlags.RouteOverActive) == 0 and g.ActiveIdUsingAllKeyboardKeys then
local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_))
if key == ImGuiKey.None then
key = ImGui.ConvertSingleModFlagToKey(bit32.band(key_chord, ImGuiMod_Mask_))
end
if key >= ImGuiKey_Keyboard_BEGIN and key < ImGuiKey_Keyboard_END then
return false
end
end
end
local focus_scope_id = g.CurrentFocusScopeId
if bit32.band(flags, ImGuiInputFlags.RouteFromRootWindow) ~= 0 then
focus_scope_id = g.CurrentWindow.RootWindow.ID
end
local score = CalcRoutingScore(focus_scope_id, owner_id, flags)
-- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d", ImGui.GetKeyChordName(key_chord), flags, owner_id, score)
if score == 0 then
return false
end
local routing_data = ImGui.GetShortcutRoutingData(key_chord)
if score > routing_data.RoutingNextScore then
routing_data.RoutingNext = owner_id
routing_data.RoutingNextScore = score
end
if routing_data.RoutingCurr == owner_id then
-- IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route")
end
return routing_data.RoutingCurr == owner_id
end
--- @param mouse_pos? ImVec2
function ImGui.IsMousePosValid(mouse_pos)
local MOUSE_INVALID = -256000.0
local p
if mouse_pos then p = mouse_pos else p = GImGui.IO.MousePos end
return p.x >= MOUSE_INVALID and p.y >= MOUSE_INVALID
end
--- @return bool
function ImGui.IsAnyMouseDown()
local g = GImGui
for n = 0, 2 do -- IM_COUNTOF(g.IO.MouseDown) - 1
if g.IO.MouseDown[n] then
return true
end
end
return false
end
--- @param button ImGuiMouseButton
--- @param owner_id? ImGuiID
function ImGui.IsMouseDown(button, owner_id)
if owner_id == nil then owner_id = ImGuiKeyOwner_Any end
local g = GImGui
IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown)
return g.IO.MouseDown[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id)
end
--- @param button ImGuiMouseButton
--- @param is_repeat? bool
function ImGui.IsMouseClicked(button, is_repeat)
if is_repeat == nil then is_repeat = false end
return ImGui.IsMouseClickedEx(button, is_repeat and ImGuiInputFlags.Repeat or ImGuiInputFlags.None, ImGuiKeyOwner_Any)
end
--- @param button ImGuiMouseButton
--- @param flags ImGuiInputFlags
--- @param owner_id? ImGuiID
function ImGui.IsMouseClickedEx(button, flags, owner_id)
if owner_id == nil then owner_id = ImGuiKeyOwner_Any end
local g = GImGui
IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown)
if not g.IO.MouseDown[button] then
return false
end
local t = g.IO.MouseDownDuration[button]
if t < 0.0 then
return false
end
IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByIsMouseClicked)) == 0)
local is_repeat = (bit32.band(flags, ImGuiInputFlags.Repeat) ~= 0)
local pressed = (t == 0.0) or (is_repeat and t > g.IO.KeyRepeatDelay and ImGui.CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0)
if not pressed then
return false
end
if not ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) then
return false
end
return true
end
--- @param button ImGuiMouseButton
--- @param owner_id? ImGuiID
function ImGui.IsMouseReleased(button, owner_id)
if owner_id == nil then owner_id = ImGuiKeyOwner_Any end
local g = GImGui
IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown)
return g.IO.MouseReleased[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id)
end
do
local key_changed_mask = ImBitArray(ImGuiKey.NamedKey_COUNT)
--- @param trickle_fast_inputs bool
function ImGui.UpdateInputEvents(trickle_fast_inputs)
local g = GImGui
local io = g.IO
local trickle_interleaved_nonchar_keys_and_text = trickle_fast_inputs and g.WantTextInputNextFrame == 1
local mouse_moved = false
local mouse_wheeled = false
local key_changed = false
local key_changed_nonchar = false
local text_inputted = false
local mouse_button_changed = 0x00
key_changed_mask:ClearAllBits()
local event_n = 1
local stop_3231 = false
while event_n <= g.InputEventsQueue.Size do
repeat
local e = g.InputEventsQueue.Data[event_n]
if e.Type == ImGuiInputEventType.MousePos then
if g.IO.WantSetMousePos then
break
end
if trickle_fast_inputs and (mouse_button_changed ~= 0 or mouse_wheeled or key_changed or text_inputted) then
stop_3231 = true; break
end
local event_pos = ImVec2(e.MousePos.PosX, e.MousePos.PosY)
io.MousePos = event_pos
io.MouseSource = e.MousePos.MouseSource
mouse_moved = true
elseif e.Type == ImGuiInputEventType.MouseButton then
local button = e.MouseButton.Button
IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT)
if trickle_fast_inputs and ((bit32.band(mouse_button_changed, bit32.lshift(1, button)) ~= 0) or mouse_wheeled) then
stop_3231 = true; break
end
if trickle_fast_inputs and e.MouseButton.MouseSource == ImGuiMouseSource.TouchScreen and mouse_moved then
stop_3231 = true; break
end
io.MouseDown[button] = e.MouseButton.Down
io.MouseSource = e.MouseButton.MouseSource
mouse_button_changed = bit32.bor(mouse_button_changed, bit32.lshift(1, button))
elseif e.Type == ImGuiInputEventType.MouseWheel then
if trickle_fast_inputs and (mouse_moved or mouse_button_changed ~= 0) then
stop_3231 = true; break
end
io.MouseWheelH = io.MouseWheelH + e.MouseWheel.WheelX
io.MouseWheel = io.MouseWheel + e.MouseWheel.WheelY
io.MouseSource = e.MouseWheel.MouseSource
mouse_wheeled = true
elseif e.Type == ImGuiInputEventType.MouseViewport then
io.MouseHoveredViewport = e.MouseViewport.HoveredViewportID
elseif e.Type == ImGuiInputEventType.Key then
-- Trickling Rule: Stop processing queued events if we got multiple action on the same button
if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) ~= 0 then
break
end
local key = e.Key.Key
IM_ASSERT(key ~= ImGuiKey.None)
-- TODO: Also gets 0-based index here, consider making key_data storage 1-based
local key_data, key_data_index = ImGui.GetKeyData(g, key)
if trickle_fast_inputs and key_data.Down ~= e.Key.Down and (key_changed_mask:TestBit(key_data_index + 1) or mouse_button_changed ~= 0) then
stop_3231 = true; break
end
local key_is_potentially_for_char_input = IsKeyChordPotentiallyCharInput(bit32.bor(ImGui.GetMergedModsFromKeys(), key))
if trickle_interleaved_nonchar_keys_and_text and (text_inputted and not key_is_potentially_for_char_input) then
stop_3231 = true; break
end
if key_data.Down ~= e.Key.Down then
key_changed = true
key_changed_mask:SetBit(key_data_index + 1)
if trickle_interleaved_nonchar_keys_and_text and not key_is_potentially_for_char_input then
key_changed_nonchar = true
end
end
key_data.Down = e.Key.Down
key_data.AnalogValue = e.Key.AnalogValue
elseif e.Type == ImGuiInputEventType.Text then
if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) ~= 0 then
break
end
if trickle_fast_inputs and (mouse_button_changed ~= 0 or mouse_moved or mouse_wheeled) then
stop_3231 = true; break
end
if trickle_interleaved_nonchar_keys_and_text and key_changed_nonchar then
stop_3231 = true; break
end
local c = e.Text.Char
io.InputQueueCharacters:push_back((c <= IM_UNICODE_CODEPOINT_MAX) and c or IM_UNICODE_CODEPOINT_INVALID)
if trickle_interleaved_nonchar_keys_and_text then
text_inputted = true
end
elseif e.Type == ImGuiInputEventType.Focus then
local focus_lost = not e.AppFocused.Focused
io.AppFocusLost = focus_lost
else
IM_ASSERT(false, "Unknown event!")
end
until true
if stop_3231 then break end
event_n = event_n + 1
end
if event_n == g.InputEventsQueue.Size + 1 then
g.InputEventsQueue:resize(0)
else
for i = 1, event_n - 1 do
g.InputEventsQueue:erase(1)
end
end
if g.IO.AppFocusLost then
g.IO:ClearInputKeys()
g.IO:ClearInputMouse()
end
end
end
--- @param key ImGuiKey
--- @param owner_id ImGuiID
--- @param flags? ImGuiInputFlags
function ImGui.SetKeyOwner(key, owner_id, flags)
if flags == nil then flags = 0 end
local g = GImGui --- @cast g ImGuiContext
IM_ASSERT(ImGui.IsNamedKeyOrMod(key) and (owner_id ~= ImGuiKeyOwner_Any or (bit32.band(flags, bit32.bor(ImGuiInputFlags.LockThisFrame, ImGuiInputFlags.LockUntilRelease)) ~= 0)), "Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)")
IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetKeyOwner)) == 0, "Passing flags not supported by this function!")
local owner_data = ImGui.GetKeyOwnerData(g, key)
owner_data.OwnerCurr = owner_id
owner_data.OwnerNext = owner_id
owner_data.LockUntilRelease = (bit32.band(flags, ImGuiInputFlags.LockUntilRelease) ~= 0)
owner_data.LockThisFrame = (bit32.band(flags, ImGuiInputFlags.LockThisFrame) ~= 0) or owner_data.LockUntilRelease
end
-- Rarely used helper
--- @param key_chord ImGuiKeyChord
--- @param owner_id ImGuiID
--- @param flags? ImGuiInputFlags
function ImGui.SetKeyOwnersForKeyChord(key_chord, owner_id, flags)
if flags == nil then flags = 0 end
if bit32.band(key_chord, ImGuiMod_Ctrl) ~= 0 then
ImGui.SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags)
end
if bit32.band(key_chord, ImGuiMod_Shift) ~= 0 then
ImGui.SetKeyOwner(ImGuiMod_Shift, owner_id, flags)
end
if bit32.band(key_chord, ImGuiMod_Alt) ~= 0 then
ImGui.SetKeyOwner(ImGuiMod_Alt, owner_id, flags)
end
if bit32.band(key_chord, ImGuiMod_Super) ~= 0 then
ImGui.SetKeyOwner(ImGuiMod_Super, owner_id, flags)
end
if bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) ~= 0 then
ImGui.SetKeyOwner(bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)), owner_id, flags)
end
end
--- @param key ImGuiKey
--- @param flags? ImGuiInputFlags
function ImGui.SetItemKeyOwner(key, flags)
if flags == nil then flags = ImGuiInputFlags.None end
local g = GImGui
local id = g.LastItemData.ID
if id == 0 or (g.HoveredId ~= id and g.ActiveId ~= id) then
return false
end
if bit32.band(flags, ImGuiInputFlags.CondMask_) == 0 then
flags = bit32.bor(flags, ImGuiInputFlags.CondDefault_)
end
if (g.HoveredId == id and bit32.band(flags, ImGuiInputFlags.CondHovered) ~= 0) or (g.ActiveId == id and bit32.band(flags, ImGuiInputFlags.CondActive) ~= 0) then
IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetItemKeyOwner)) == 0)
if not ImGui.TestKeyOwner(key, id) then
return false
end
ImGui.SetKeyOwner(key, id, bit32.band(flags, bit32.bnot(ImGuiInputFlags.CondMask_)))
return true
end
return false
end
--- @param key_chord ImGuiKeyChord
--- @param flags ImGuiInputFlags
--- @param owner_id ImGuiID
function ImGui.IsKeyChordPressed(key_chord, flags, owner_id)
local g = GImGui
key_chord = ImGui.FixupKeyChord(key_chord)
local mods = bit32.band(key_chord, ImGuiMod_Mask_)
if g.IO.KeyMods ~= mods then
return false
end
-- Special storage location for mods
local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_))
if key == ImGuiKey.None then
key = ImGui.ConvertSingleModFlagToKey(mods)
end
if not ImGui.IsKeyPressedEx(key, bit32.band(flags, ImGuiInputFlags.RepeatMask_), owner_id) then
return false
end
return true
end
--- @param key_chord ImGuiKeyChord
--- @param flags? ImGuiInputFlags
function ImGui.SetNextItemShortcut(key_chord, flags)
if flags == nil then flags = 0 end
local g = GImGui
g.NextItemData.HasFlags = bit32.bor(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasShortcut)
g.NextItemData.Shortcut = key_chord
g.NextItemData.ShortcutFlags = flags
end
--- @param key_chord ImGuiKeyChord
--- @param flags ImGuiInputFlags
--- @param owner_id ImGuiID
function ImGui.Shortcut(key_chord, flags, owner_id)
local g = GImGui
-- IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)", ImGui.GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id)
-- When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
if bit32.band(flags, ImGuiInputFlags.RouteTypeMask_) == 0 then
flags = bit32.bor(flags, ImGuiInputFlags.RouteFocused)
end
-- Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
-- Effectively makes Shortcut() always input-owner aware.
if owner_id == ImGuiKeyOwner_Any or owner_id == ImGuiKeyOwner_NoOwner then
owner_id = GetRoutingIdFromOwnerId(owner_id)
end
if bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 then
return false
end
-- Submit route
if not ImGui.SetShortcutRouting(key_chord, flags, owner_id) then
return false
end
-- Default repeat behavior for Shortcut()
-- So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
if bit32.band(flags, ImGuiInputFlags.Repeat) ~= 0 and bit32.band(flags, ImGuiInputFlags.RepeatUntilMask_) == 0 then
flags = bit32.bor(flags, ImGuiInputFlags.RepeatUntilKeyModsChange)
end
if not ImGui.IsKeyChordPressed(key_chord, flags, owner_id) then
return false
end
-- Claim mods during the press
ImGui.SetKeyOwnersForKeyChord(bit32.band(key_chord, ImGuiMod_Mask_), owner_id)
IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByShortcut)) == 0) -- Passing flags not supported by this function!
return true
end
--- @param window ImGuiWindow
--- @return bool
function ImGui.IsWindowActiveAndVisible(window)
return window.Active and not window.Hidden
end
--- @param window ImGuiWindow
--- @nodiscard
local function CalcWindowMinSize(window)
local g = GImGui
local size_min = ImVec2()
if (bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0) and (bit32.band(window.Flags, ImGuiWindowFlags.Popup) == 0) then
if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then
size_min.x = g.Style.WindowMinSize.x
else
size_min.x = IMGUI_WINDOW_HARD_MIN_SIZE
end
if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 then
size_min.y = g.Style.WindowMinSize.y
else
size_min.y = IMGUI_WINDOW_HARD_MIN_SIZE
end
else
if bit32.band(window.Flags, ImGuiWindowFlags.AlwaysAutoResize) == 0 then
size_min.x = g.Style.WindowMinSize.x
else
size_min.x = IMGUI_WINDOW_HARD_MIN_SIZE
end
if bit32.band(window.Flags, ImGuiWindowFlags.AlwaysAutoResize) == 0 then
size_min.y = g.Style.WindowMinSize.y
else
size_min.y = IMGUI_WINDOW_HARD_MIN_SIZE
end
end
local window_for_height = window
size_min.y = ImMax(size_min.y, window_for_height.TitleBarHeight + window_for_height.MenuBarHeight + ImMax(0, g.Style.WindowRounding - 1))
return size_min
end
--- @param window ImGuiWindow
--- @param size_desired ImVec2
--- @return ImVec2
--- @nodiscard
local function CalcWindowSizeAfterConstraint(window, size_desired)
local g = GImGui
local new_size = ImVec2()
ImVec2_Copy(new_size, size_desired)
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 then
local cr = ImRect()
ImRect_Copy(cr, g.NextWindowData.SizeConstraintRect)
new_size.x = (cr.Min.x >= 0 and cr.Max.x >= 0) and ImClamp(new_size.x, cr.Min.x, cr.Max.x) or window.SizeFull.x
new_size.y = (cr.Min.y >= 0 and cr.Max.y >= 0) and ImClamp(new_size.y, cr.Min.y, cr.Max.y) or window.SizeFull.y
if g.NextWindowData.SizeCallback then
local data = {} -- TODO: ImGuiSizeCallbackData
data.UserData = g.NextWindowData.SizeCallbackUserData
data.Pos = ImVec2(window.Pos.x, window.Pos.y)
data.CurrentSize = ImVec2(window.SizeFull.x, window.SizeFull.y)
data.DesiredSize = ImVec2(new_size.x, new_size.y)
g.NextWindowData.SizeCallback(data)
new_size.x = data.DesiredSize.x
new_size.y = data.DesiredSize.y
end
new_size.x = IM_TRUNC(new_size.x)
new_size.y = IM_TRUNC(new_size.y)
end
local size_min = CalcWindowMinSize(window)
return ImMax(new_size, size_min)
end
--- @param window ImGuiWindow
--- @param content_size_current ImVec2
--- @param content_size_ideal ImVec2
local function CalcWindowContentSizes(window, content_size_current, content_size_ideal)
local preserve_old_content_sizes = false
if (window.Collapsed and window.AutoFitFramesX <= 0 and window.AutoFitFramesY <= 0) then
preserve_old_content_sizes = true
elseif (window.Hidden and window.HiddenFramesCannotSkipItems == 0 and window.HiddenFramesCanSkipItems > 0) then
preserve_old_content_sizes = true
end
if preserve_old_content_sizes then
content_size_current.x = window.ContentSize.x
content_size_current.y = window.ContentSize.y
content_size_ideal.x = window.ContentSizeIdeal.x
content_size_ideal.y = window.ContentSizeIdeal.y
return
end
if (window.ContentSizeExplicit.x ~= 0.0) then content_size_current.x = window.ContentSizeExplicit.x else content_size_current.x = ImTrunc64(window.DC.CursorMaxPos.x - window.DC.CursorStartPos.x) end
if (window.ContentSizeExplicit.y ~= 0.0) then content_size_current.y = window.ContentSizeExplicit.y else content_size_current.y = ImTrunc64(window.DC.CursorMaxPos.y - window.DC.CursorStartPos.y) end
if (window.ContentSizeExplicit.x ~= 0.0) then content_size_ideal.x = window.ContentSizeExplicit.x else content_size_ideal.x = ImTrunc64(ImMax(window.DC.CursorMaxPos.x, window.DC.IdealMaxPos.x) - window.DC.CursorStartPos.x) end
if (window.ContentSizeExplicit.y ~= 0.0) then content_size_ideal.y = window.ContentSizeExplicit.y else content_size_ideal.y = ImTrunc64(ImMax(window.DC.CursorMaxPos.y, window.DC.IdealMaxPos.y) - window.DC.CursorStartPos.y) end
end
--- @param window ImGuiWindow # The window to calculate auto-fit size for
--- @param size_contents ImVec2 # The content size
--- @param axis_mask int # The axis mask to determine which axes to auto-fit
--- @return ImVec2 # The auto-fit size
local function CalcWindowAutoFitSize(window, size_contents, axis_mask)
local g = GImGui
local style = g.Style
local decoration_w_without_scrollbars = window.DecoOuterSizeX1 + window.DecoOuterSizeX2 - window.ScrollbarSizes.x
local decoration_h_without_scrollbars = window.DecoOuterSizeY1 + window.DecoOuterSizeY2 - window.ScrollbarSizes.y
local size_pad = ImVec2(window.WindowPadding.x * 2, window.WindowPadding.y * 2)
local size_desired = ImVec2()
size_desired.x = (bit32.band(axis_mask, 1) ~= 0) and (size_contents.x + size_pad.x + decoration_w_without_scrollbars) or window.Size.x
size_desired.y = (bit32.band(axis_mask, 2) ~= 0) and (size_contents.y + size_pad.y + decoration_h_without_scrollbars) or window.Size.y
local size_max = ImVec2(FLT_MAX, FLT_MAX)
if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then
if not window.ViewportOwned then
size_max = ImGui.GetMainViewport().WorkSize - style.DisplaySafeAreaPadding * 2.0
end
local monitor_idx = window.ViewportAllowPlatformMonitorExtend
if monitor_idx >= 1 and monitor_idx <= g.PlatformIO.Monitors.Size then
size_max = g.PlatformIO.Monitors.Data[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0
end
end
if bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0 then
return ImMin(size_desired, size_max)
else
local size_min = CalcWindowMinSize(window)
local size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max)
local size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit)
local size_contents_for_scrollbar_x = (bit32.band(axis_mask, 1) ~= 0) and size_contents.x or window.ContentSize.x
local size_contents_for_scrollbar_y = (bit32.band(axis_mask, 2) ~= 0) and size_contents.y or window.ContentSize.y
local will_have_scrollbar_x = (size_auto_fit_after_constraint.x < size_contents_for_scrollbar_x + size_pad.x + decoration_w_without_scrollbars and bit32.band(window.Flags, ImGuiWindowFlags.NoScrollbar) == 0 and bit32.band(window.Flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysHorizontalScrollbar) ~= 0
local will_have_scrollbar_y = (size_auto_fit_after_constraint.y < size_contents_for_scrollbar_y + size_pad.y + decoration_h_without_scrollbars and bit32.band(window.Flags, ImGuiWindowFlags.NoScrollbar) == 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysVerticalScrollbar) ~= 0
if will_have_scrollbar_x then
size_auto_fit.y = size_auto_fit.y + style.ScrollbarSize
end
if will_have_scrollbar_y then
size_auto_fit.x = size_auto_fit.x + style.ScrollbarSize
end
return size_auto_fit
end
end
--- @param window ImGuiWindow
--- @return ImVec2
function ImGui.CalcWindowNextAutoFitSize(window)
local size_contents_current = ImVec2()
local size_contents_ideal = ImVec2()
CalcWindowContentSizes(window, size_contents_current, size_contents_ideal)
local size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal, -1)
local size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit)
return size_final
end
--- @param window ImGuiWindow
--- @return ImGuiCol
local function GetWindowBgColorIdx(window)
if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.Tooltip, ImGuiWindowFlags.Popup)) ~= 0 then
return ImGuiCol.PopupBg
elseif bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
return ImGuiCol.ChildBg
else
return ImGuiCol.WindowBg
end
end
--- @param window ImGuiWindow
--- @param corner_target_arg ImVec2
--- @param corner_norm ImVec2
--- @return ImVec2, ImVec2
--- @nodiscard
local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_norm)
local corner_target = ImVec2()
ImVec2_Copy(corner_target, corner_target_arg)
if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
local parent_window = window.ParentWindow
local parent_flags = parent_window.Flags
local limit_rect = ImRect()
ImRect_Copy(limit_rect, parent_window.InnerRect)
limit_rect:Expand(ImVec2(-ImMax(parent_window.WindowPadding.x, parent_window.WindowBorderSize), -ImMax(parent_window.WindowPadding.y, parent_window.WindowBorderSize)))
if (bit32.band(parent_flags, bit32.bor(ImGuiWindowFlags.HorizontalScrollbar, ImGuiWindowFlags.AlwaysHorizontalScrollbar)) == 0) or (bit32.band(parent_flags, ImGuiWindowFlags.NoScrollbar) ~= 0) then
corner_target.x = ImClamp(corner_target.x, limit_rect.Min.x, limit_rect.Max.x)
end
if bit32.band(parent_flags, ImGuiWindowFlags.NoScrollbar) ~= 0 then
corner_target.y = ImClamp(corner_target.y, limit_rect.Min.y, limit_rect.Max.y)
end
end
local pos_min = ImLerp(corner_target, window.Pos, corner_norm)
local pos_max = ImLerp(window.Pos + window.Size, corner_target, corner_norm)
local size_expected = pos_max - pos_min
local size_constrained = CalcWindowSizeAfterConstraint(window, size_expected)
local out_pos = pos_min
if corner_norm.x == 0.0 then
out_pos.x = out_pos.x - (size_constrained.x - size_expected.x)
end
if corner_norm.y == 0.0 then
out_pos.y = out_pos.y - (size_constrained.y - size_expected.y)
end
return out_pos, size_constrained
end
--- @param window ImGuiWindow
--- @param resize_grip_count int
--- @param resize_grip_col table
--- @param visibility_rect ImRect
--- @return int, int, int
local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_col, visibility_rect)
local g = GImGui
local flags = window.Flags
if (bit32.band(flags, ImGuiWindowFlags.NoResize) ~= 0 or window.AutoFitFramesX > 0 or window.AutoFitFramesY > 0) then
return 0, -1, -1
end
if (bit32.band(flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 and bit32.band(window.ChildFlags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0) then
return 0, -1, -1
end
if window.WasActive == false then
return 0, -1, -1
end
local border_hovered = -1
local border_held = -1
local ret_auto_fit_mask = 0x00
local grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35, g.Style.WindowRounding + 1.0 + g.FontSize * 0.2))
local grip_hover_inner_size = (resize_grip_count > 0) and IM_TRUNC(grip_draw_size * 0.75) or 0.0
local grip_hover_outer_size = g.WindowsBorderHoverPadding + 1
ImGui.PushID("#RESIZE")
local pos_target = ImVec2(FLT_MAX, FLT_MAX)
local size_target = ImVec2(FLT_MAX, FLT_MAX)
-- Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
-- - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
-- This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
-- - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
-- - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
-- We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
local clip_with_viewport_rect = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasMouseHoveredViewport) == 0 or g.IO.MouseHoveredViewport ~= window.ViewportId or bit32.band(window.Viewport.Flags, ImGuiViewportFlags.NoDecoration) == 0
if (clip_with_viewport_rect) then
ImRect_Copy(window.ClipRect, window.Viewport:GetMainRect())
end
local clamp_rect = ImRect()
ImRect_Copy(clamp_rect, visibility_rect)
local window_move_from_title_bar = (bit32.band(window.BgClickFlags, ImGuiWindowBgClickFlags.Move) == 0) and (bit32.band(window.Flags, ImGuiWindowFlags.NoTitleBar) == 0)
if window_move_from_title_bar then
clamp_rect.Min.y = clamp_rect.Min.y - window.TitleBarHeight
end
for resize_grip_n = 0, resize_grip_count - 1 do
local def = ImGuiResizeGripDef[resize_grip_n + 1]
local corner_pos = def.CornerPosN
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 resize_rect = ImRect(corner - inner_dir * grip_hover_outer_size, corner + inner_dir * 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.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end
local resize_grip_id = window:GetID(resize_grip_n)
ImGui.ItemAdd(resize_rect, resize_grip_id, nil, ImGuiItemFlags.NoNav)
local _, hovered, held = ImGui.ButtonBehavior(resize_rect, resize_grip_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus))
if hovered or held then
ImGui.SetMouseCursor((bit32.band(resize_grip_n, 1) ~= 0) and ImGuiMouseCursor.ResizeNESW or ImGuiMouseCursor.ResizeNWSE)
end
if held and g.IO.MouseDoubleClicked[0] then
local size_auto_fit = CalcWindowAutoFitSize(window, window.ContentSizeIdeal, -1)
size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit)
ret_auto_fit_mask = 0x03
ImGui.ClearActiveID()
elseif held then
local clamp_min = ImVec2((corner_pos.x == 1.0) and clamp_rect.Min.x or -FLT_MAX, (corner_pos.y == 1.0) and clamp_rect.Min.y or -FLT_MAX)
local clamp_max = ImVec2((corner_pos.x == 0.0) and clamp_rect.Max.x or FLT_MAX, (corner_pos.y == 0.0) and clamp_rect.Max.y or FLT_MAX)
local corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN)
corner_target = ImClamp(corner_target, clamp_min, clamp_max)
pos_target, size_target = CalcResizePosSizeFromAnyCorner(window, corner_target, corner_pos)
end
local resize_grip_visible = held or hovered or (resize_grip_n == 0 and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0)
if resize_grip_visible then
local color
if held then
color = ImGui.GetColorU32(ImGuiCol.ResizeGripActive)
else
if hovered then
color = ImGui.GetColorU32(ImGuiCol.ResizeGripHovered)
else
color = ImGui.GetColorU32(ImGuiCol.ResizeGrip)
end
end
resize_grip_col[resize_grip_n + 1] = color
end
end
local resize_border_mask = 0x00
if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
local mask_x = (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0) and 0x02 or 0
local mask_y = (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0) and 0x08 or 0
resize_border_mask = bit32.bor(mask_x, mask_y)
else
resize_border_mask = g.IO.ConfigWindowsResizeFromEdges and 0x0F or 0x00
end
for border_n = 0, 3 do
repeat
if bit32.band(resize_border_mask, bit32.lshift(1, border_n)) == 0 then
break
end
local def = ImGuiResizeBorderDef[border_n + 1]
local axis
if border_n == ImGuiDir.Left or border_n == ImGuiDir.Right then
axis = ImGuiAxis.X
else
axis = ImGuiAxis.Y
end
local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding)
local border_id = window:GetID(border_n + 4)
ImGui.ItemAdd(border_rect, border_id, nil, ImGuiItemFlags.NoNav)
local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus))
if hovered and g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER then
hovered = false
end
if hovered or held then
ImGui.SetMouseCursor((axis == ImGuiAxis.X) and ImGuiMouseCursor.ResizeEW or ImGuiMouseCursor.ResizeNS)
end
if held and g.IO.MouseDoubleClicked[0] then
-- Double-clicking bottom or right border auto-fit on this axis
-- FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
if border_n == 1 or border_n == 3 then -- Right and bottom border
local size_auto_fit = CalcWindowAutoFitSize(window, window.ContentSizeIdeal, bit32.lshift(1, axis - 1))
size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis]
ret_auto_fit_mask = bit32.bor(ret_auto_fit_mask, bit32.lshift(1, axis - 1))
hovered = false
held = false -- So border doesn't show highlighted at new position
end
ImGui.ClearActiveID()
elseif held then
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
g.WindowResizeBorderExpectedRect = border_rect
g.WindowResizeRelativeMode = false
end
if (bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0) and g.WindowResizeBorderExpectedRect ~= border_rect then
g.WindowResizeRelativeMode = true
end
local border_curr = window.Pos + ImMin(def.SegmentN1, def.SegmentN2) * window.Size
local border_target_rel_mode_for_axis
local border_target_abs_mode_for_axis
border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis]
border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding -- Match ButtonBehavior() padding above
-- Use absolute mode position
local border_target = ImVec2()
ImVec2_Copy(border_target, window.Pos)
border_target[axis] = border_target_abs_mode_for_axis
-- Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
local ignore_resize = false
if g.WindowResizeRelativeMode then
border_target[axis] = border_target_rel_mode_for_axis
if g.IO.MouseDelta[axis] == 0.0 or ((g.IO.MouseDelta[axis] > 0.0) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis)) then
ignore_resize = true
end
end
local clamp_min = ImVec2((border_n == ImGuiDir.Right) and clamp_rect.Min.x or -FLT_MAX, (border_n == ImGuiDir.Down or (border_n == ImGuiDir.Up and window_move_from_title_bar)) and clamp_rect.Min.y or -FLT_MAX)
local clamp_max = ImVec2((border_n == ImGuiDir.Left) and clamp_rect.Max.x or FLT_MAX, (border_n == ImGuiDir.Up) and clamp_rect.Max.y or FLT_MAX)
border_target = ImClamp(border_target, clamp_min, clamp_max)
if not ignore_resize then
pos_target, size_target = CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2))
end
end
if hovered then
border_hovered = border_n
end
if held then
border_held = border_n
end
until true
end
ImGui.PopID()
window.DC.NavLayerCurrent = ImGuiNavLayer.Main
if size_target.x ~= FLT_MAX and (window.Size.x ~= size_target.x or window.SizeFull.x ~= size_target.x) then
window.Size.x = size_target.x
window.SizeFull.x = size_target.x
end
if size_target.y ~= FLT_MAX and (window.Size.y ~= size_target.y or window.SizeFull.y ~= size_target.y) then
window.Size.y = size_target.y
window.SizeFull.y = size_target.y
end
if pos_target.x ~= FLT_MAX and window.Pos.x ~= ImFloor(pos_target.x) then
window.Pos.x = ImFloor(pos_target.x)
end
if pos_target.y ~= FLT_MAX and window.Pos.y ~= ImFloor(pos_target.y) then
window.Pos.y = ImFloor(pos_target.y)
end
if border_held ~= -1 then
g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding)
end
return ret_auto_fit_mask, border_hovered, border_held
end
--- @param pos ImVec2
--- @param wrap_pos_x float
--- @return float
function ImGui.CalcWrapWidthForPos(pos, wrap_pos_x)
if wrap_pos_x < 0.0 then
return 0.0
end
local g = GImGui
local window = g.CurrentWindow
if wrap_pos_x == 0.0 then
wrap_pos_x = window.WorkRect.Max.x
elseif wrap_pos_x > 0.0 then
wrap_pos_x = wrap_pos_x + window.Pos.x - window.Scroll.x
end
return ImMax(wrap_pos_x - pos.x, 1.0)
end
--- @param text ImString
--- @param text_end int?
--- @return int # Exclusive upper bound
function ImGui.FindRenderedTextEnd(text, text_end)
local text_display_end = 1
local text_len = #text
if not text_end then
text_end = text_len + 1
end
text_display_end = ImMemchr(text, "##", 1) or text_end
text_display_end = ImMin(text_display_end, text_end)
return text_display_end
end
--- @param pos ImVec2
--- @param text string
--- @param text_begin int?
--- @param text_end int?
--- @param hide_text_after_hash bool? # true by default
function ImGui.RenderText(pos, text, text_begin, text_end, hide_text_after_hash)
if text_begin == nil then text_begin = 1 end
if hide_text_after_hash == nil then hide_text_after_hash = true end
local g = GImGui
local window = g.CurrentWindow
-- Hide anything after a '##' string
local text_display_end
if hide_text_after_hash then
text_display_end = ImGui.FindRenderedTextEnd(text, text_end)
else
if text_end == nil then
text_end = #text + 1
end
text_display_end = text_end
end
if text ~= "" and text_display_end > 1 then
window.DrawList:AddText(g.Font, g.FontSize, pos, ImGui.GetColorU32(ImGuiCol.Text), text, text_begin, text_display_end, 0.0)
if g.LogEnabled then
-- ImGui.LogRenderedText(&pos, text, text_display_end);
end
end
end
--- @param pos ImVec2
--- @param text string
--- @param text_end int?
--- @param wrap_width float
function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width)
local g = GImGui
local window = g.CurrentWindow
if text_end == nil then
text_end = #text + 1
end
if text ~= "" then
window.DrawList:AddText(g.Font, g.FontSize, pos, ImGui.GetColorU32(ImGuiCol.Text), text, 1, text_end, wrap_width)
end
end
--- @param draw_list ImDrawList
--- @param pos_min ImVec2
--- @param pos_max ImVec2
--- @param text string
--- @param text_begin int
--- @param text_display_end int
--- @param text_size_if_known? ImVec2
--- @param align? ImVec2
--- @param clip_rect? ImRect
function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin, text_display_end, text_size_if_known, align, clip_rect)
if not align then align = ImVec2(0, 0) end
local pos = ImVec2()
ImVec2_Copy(pos, pos_min)
local text_size = text_size_if_known or ImGui.CalcTextSize(text, text_display_end, false, 0.0)
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 need_clipping = (pos.x + text_size.x >= clip_max.x) or (pos.y + text_size.y >= clip_max.y)
if (clip_rect) then
need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y))
end
if (align.x > 0.0) then pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x) end
if (align.y > 0.0) then pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y) end
local g = GImGui
if (need_clipping) then
local fine_clip_rect = ImVec4(clip_min.x, clip_min.y, clip_max.x, clip_max.y)
draw_list:AddText(nil, 0.0, pos, ImGui.GetColorU32(ImGuiCol.Text), text, text_begin, text_display_end, 0.0, fine_clip_rect)
else
draw_list:AddText(nil, 0.0, pos, ImGui.GetColorU32(ImGuiCol.Text), text, text_begin, text_display_end, 0.0, nil)
end
end
--- @param pos_min ImVec2
--- @param pos_max ImVec2
--- @param text string
--- @param text_end? int
--- @param text_size_if_known? ImVec2
--- @param align? ImVec2
--- @param clip_rect? ImRect
function ImGui.RenderTextClipped(pos_min, pos_max, text, text_end, text_size_if_known, align, clip_rect)
if not align then align = ImVec2(0, 0) end
local text_display_end = ImGui.FindRenderedTextEnd(text, text_end)
local text_len = text_display_end - 1
if text_len == 0 then
return
end
local g = GImGui
local window = g.CurrentWindow
ImGui.RenderTextClippedEx(window.DrawList, pos_min, pos_max, text, 1, text_display_end, text_size_if_known, align, clip_rect)
-- if (g.LogEnabled)
-- ImGui.LogRenderedText(&pos_min, text, text_display_end);
end
--- @param bb ImRect
--- @param id ImGuiID
--- @param flags? ImGuiNavRenderCursorFlags
--- @param rounding? float
function ImGui.RenderNavCursor(bb, id, flags, rounding)
if flags == nil then flags = ImGuiNavRenderCursorFlags.None end
if rounding == nil then rounding = -1.0 end
local g = GImGui
if id ~= g.NavId then
return
end
if not g.NavCursorVisible and bit32.band(flags, ImGuiNavRenderCursorFlags.AlwaysDraw) == 0 then
return
end
if id == g.LastItemData.ID and bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoNav) ~= 0 then
return
end
local window = g.CurrentWindow
if window.DC.NavHideHighlightOneFrame then
return
end
if rounding < 0.0 then
rounding = g.Style.FrameRounding
end
local display_rect = ImRect()
ImRect_Copy(display_rect, bb)
display_rect:ClipWith(window.ClipRect)
local scale_factor = ImGui.GetScale()
local thickness = ImTrunc(ImMax(2.0, 1.5 * scale_factor))
if bit32.band(flags, ImGuiNavRenderCursorFlags.Compact) ~= 0 then
window.DrawList:AddRect(display_rect.Min, display_rect.Max, ImGui.GetColorU32(ImGuiCol.NavCursor), rounding, thickness)
else
local distance = ImTrunc(3.0 + thickness * 0.5)
display_rect:Expand(ImVec2(distance, distance))
local fully_visible = window.ClipRect:Contains(display_rect)
if not fully_visible then
window.DrawList:PushClipRect(display_rect.Min, display_rect.Max)
end
window.DrawList:AddRect(display_rect.Min, display_rect.Max, ImGui.GetColorU32(ImGuiCol.NavCursor), rounding, thickness)
if not fully_visible then
window.DrawList:PopClipRect()
end
end
end
do --[[ImGui.RenderMouseCursor]]
local offset = ImVec2()
local size = ImVec2()
local uv_border = {ImVec2(), ImVec2()}
local uv_fill = {ImVec2(), ImVec2()}
--- @param base_pos ImVec2
--- @param base_scale float
--- @param mouse_cursor ImGuiMouseCursor
--- @param col_fill ImU32
--- @param col_border ImU32
--- @param col_shadow ImU32
function ImGui.RenderMouseCursor(base_pos, base_scale, mouse_cursor, col_fill, col_border, col_shadow)
local g = GImGui
if mouse_cursor <= ImGuiMouseCursor.None or mouse_cursor >= ImGuiMouseCursor.COUNT then -- We intentionally accept out of bound values
mouse_cursor = ImGuiMouseCursor.Arrow
end
local font_atlas = g.DrawListSharedData.FontAtlas
for _, viewport in g.Viewports:iter() do
repeat
if not ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, offset, size, uv_border, uv_fill) then
break
end
local pos = base_pos - offset
local scale = base_scale * viewport.DpiScale
if not viewport:GetMainRect():Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)) then
break
end
local draw_list = ImGui.GetForegroundDrawList(viewport)
local tex_ref = font_atlas.TexRef
draw_list:PushTexture(tex_ref);
draw_list:AddImage(tex_ref, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv_fill[1], uv_fill[2], col_shadow)
draw_list:AddImage(tex_ref, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv_fill[1], uv_fill[2], col_shadow)
draw_list:AddImage(tex_ref, pos, pos + size * scale, uv_fill[1], uv_fill[2], col_border)
draw_list:AddImage(tex_ref, pos, pos + size * scale, uv_border[1], uv_border[2], col_fill)
if mouse_cursor == ImGuiMouseCursor.Wait or mouse_cursor == ImGuiMouseCursor.Progress then
local a_min = ImFmod(g.Time * 5.0, 2.0 * IM_PI)
local a_max = a_min + IM_PI * 1.65
draw_list:PathArcTo(pos + ImVec2(14, -1) * scale, 6.0 * scale, a_min, a_max)
draw_list:PathStroke(col_fill, 3.0 * scale)
end
draw_list:PopTexture()
until true
end
end
end
--- Another overly complex function until we reorganize everything into a nice all-in-one helper.
--- This is made more complex because we have dissociated the layout rectangle (pos_min .. pos_max) from 'ellipsis_max_x' which may be beyond it.
--- This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
--- @param draw_list ImDrawList
--- @param pos_min ImVec2
--- @param pos_max ImVec2
--- @param ellipsis_max_x float
--- @param text string
--- @param text_end_full? int
--- @param text_size_if_known? ImVec2
function ImGui.RenderTextEllipsis(draw_list, pos_min, pos_max, ellipsis_max_x, text, text_end_full, text_size_if_known)
local g = GImGui
if text_end_full == nil then
text_end_full = ImGui.FindRenderedTextEnd(text)
end
local text_size
if text_size_if_known then
text_size = ImVec2()
ImVec2_Copy(text_size, text_size_if_known)
else
text_size = ImGui.CalcTextSize(text, text_end_full, false, 0.0)
end
-- draw_list:AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 6), IM_COL32(0, 0, 255, 255))
-- draw_list:AddLine(ImVec2(ellipsis_max_x, pos_min.y - 2), ImVec2(ellipsis_max_x, pos_max.y + 3), IM_COL32(0, 255, 0, 255))
-- FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
if text_size.x > pos_max.x - pos_min.x then
-- Hello wo...
-- | | |
-- min max ellipsis_max
-- <-> this is generally some padding value
local font = draw_list._Data.Font
local font_size = draw_list._Data.FontSize
local font_scale = draw_list._Data.FontScale
local text_end_ellipsis = nil
local baked = font:GetFontBaked(font_size)
local ellipsis_width = baked:GetCharAdvance(font.EllipsisChar) * font_scale
-- We can now claim the space between pos_max.x and ellipsis_max.x
local text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0)
local text_size_clipped
text_size_clipped, text_end_ellipsis = font:CalcTextSizeA(font_size, text_avail_width, 0.0, text, 1, text_end_full)
local text_size_clipped_x = text_size_clipped.x
-- Render text, render ellipsis
ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, 1, text_end_ellipsis, text_size, ImVec2(0.0, 0.0))
local cpu_fine_clip_rect = ImVec4(pos_min.x, pos_min.y, pos_max.x, pos_max.y)
local ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y))
font:RenderChar(draw_list, font_size, ellipsis_pos, ImGui.GetColorU32(ImGuiCol.Text), font.EllipsisChar, cpu_fine_clip_rect)
else
ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, 1, text_end_full, text_size, ImVec2(0.0, 0.0))
end
if g.LogEnabled then
ImGui.LogRenderedText(pos_min, text, text_end_full)
end
end
--- @param p_min ImVec2
--- @param p_max ImVec2
--- @param fill_col ImU32
--- @param borders? bool
--- @param rounding? float
function ImGui.RenderFrame(p_min, p_max, fill_col, borders, rounding)
if borders == nil then borders = true end
if rounding == nil then rounding = 0.0 end
local g = GImGui
local window = g.CurrentWindow
window.DrawList:AddRectFilled(p_min, p_max, fill_col, rounding)
local border_size = g.Style.FrameBorderSize
if borders and border_size > 0 then
window.DrawList:AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), ImGui.GetColorU32(ImGuiCol.BorderShadow), rounding, border_size, 0)
window.DrawList:AddRect(p_min, p_max, ImGui.GetColorU32(ImGuiCol.Border), rounding, border_size, 0)
end
end
--- @param p_min ImVec2
--- @param p_max ImVec2
--- @param rounding float
function ImGui.RenderFrameBorder(p_min, p_max, rounding)
local g = GImGui
local window = g.CurrentWindow
local border_size = g.Style.FrameBorderSize
if border_size > 0.0 then
window.DrawList:AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), ImGui.GetColorU32(ImGuiCol.BorderShadow), rounding, border_size, 0)
window.DrawList:AddRect(p_min, p_max, ImGui.GetColorU32(ImGuiCol.Border), rounding, border_size, 0)
end
end
--- @param bb ImRect
--- @param col ImU32
--- @param rounding float
function ImGui.RenderColorComponentMarker(bb, col, rounding)
if bb.Min.x + 1 >= bb.Max.x then
return
end
local g = GImGui
local window = g.CurrentWindow
ImGui.RenderRectFilledInRangeH(window.DrawList, bb, col, bb.Min.x, ImMin(bb.Min.x + g.Style.ColorMarkerSize, bb.Max.x), rounding)
end
--- @param window ImGuiWindow
--- @param border_n int
--- @param border_col ImU32
--- @param border_size float
local function RenderWindowOuterSingleBorder(window, border_n, border_col, border_size)
local def = ImGuiResizeBorderDef[border_n + 1]
local rounding = window.WindowRounding
local border_r = GetResizeBorderRect(window, border_n, rounding, 0.0)
window.DrawList:PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5, 0.5) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25, def.OuterAngle)
window.DrawList:PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5, 0.5) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25)
window.DrawList:PathStroke(border_col, border_size)
end
local function RenderWindowOuterBorders(window)
local g = GImGui
local border_size = window.WindowBorderSize
local border_col = ImGui.GetColorU32(ImGuiCol.Border)
if border_size > 0.0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoBackground) == 0) then
window.DrawList:AddRect(window.Pos, window.Pos + window.Size, border_col, window.WindowRounding, window.WindowBorderSize, 0)
elseif border_size > 0.0 then
if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then
RenderWindowOuterSingleBorder(window, 1, border_col, border_size)
end
if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 then
RenderWindowOuterSingleBorder(window, 3, border_col, border_size)
end
end
if window.ResizeBorderHovered ~= -1 or window.ResizeBorderHeld ~= -1 then
local border_n = (window.ResizeBorderHeld ~= -1) and window.ResizeBorderHeld or window.ResizeBorderHovered
local border_col_resizing = ImGui.GetColorU32((window.ResizeBorderHeld ~= -1) and ImGuiCol.SeparatorActive or ImGuiCol.SeparatorHovered)
RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0, window.WindowBorderSize))
end
if g.Style.FrameBorderSize > 0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoTitleBar) == 0) then
local y = window.Pos.y + window.TitleBarHeight - 1
window.DrawList:AddLineH(window.Pos.x + border_size * 0.5, window.Pos.x + window.Size.x - border_size * 0.5, y, border_col, g.Style.FrameBorderSize)
end
end
--- @param window ImGuiWindow
--- @param title_bar_rect ImRect
--- @param title_bar_is_highlight bool
--- @param handle_borders_and_resize_grips bool
--- @param resize_grip_col ImU32[]
--- @param resize_grip_draw_size float
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 style = g.Style
local flags = window.Flags
local window_rounding = window.WindowRounding
local window_border_size = window.WindowBorderSize
if window.Collapsed then
local backup_border_size = style.FrameBorderSize
g.Style.FrameBorderSize = window.WindowBorderSize
local title_bar_col = ImGui.GetColorU32((title_bar_is_highlight and g.NavCursorVisible) and ImGuiCol.TitleBgActive or ImGuiCol.TitleBgCollapsed)
ImGui.RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding)
g.Style.FrameBorderSize = backup_border_size
else
-- Window background
if bit32.band(flags, ImGuiWindowFlags.NoBackground) == 0 then
local bg_col = ImGui.GetColorU32(GetWindowBgColorIdx(window))
local override_alpha = false
local alpha = 1.0
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasBgAlpha) ~= 0 then
alpha = g.NextWindowData.BgAlphaVal
override_alpha = true
end
if override_alpha then
bg_col = bit32.band(bg_col, bit32.bnot(IM_COL32_A_MASK)) or bit32.lshift(IM_F32_TO_INT8_SAT(alpha), IM_COL32_A_SHIFT)
end
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_rounding_flags = (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and ImDrawFlags.RoundCornersAll or ImDrawFlags.RoundCornersBottom
local bg_draw_list = window.DrawList
bg_draw_list:AddRectFilled(bg_rect.Min, bg_rect.Max, bg_col, window_rounding, bg_rounding_flags)
end
end
-- Title bar
if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then
local title_bar_col = ImGui.GetColorU32(title_bar_is_highlight and ImGuiCol.TitleBgActive or ImGuiCol.TitleBg)
window.DrawList:AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags.RoundCornersTop)
end
-- Menu bar
if bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 then
local menu_bar_rect = window:MenuBarRect()
menu_bar_rect:ClipWith(window:Rect())
window.DrawList:AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, ImGui.GetColorU32(ImGuiCol.MenuBarBg), (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and window_rounding or 0.0, ImDrawFlags.RoundCornersTop)
if style.FrameBorderSize > 0.0 and menu_bar_rect.Max.y < window.Pos.y + window.Size.y then
window.DrawList:AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5, menu_bar_rect.Max.x - window_border_size * 0.5, menu_bar_rect.Max.y, ImGui.GetColorU32(ImGuiCol.Border), style.FrameBorderSize)
end
end
if window.ScrollbarX then
ImGui.Scrollbar(ImGuiAxis.X)
end
if window.ScrollbarY then
ImGui.Scrollbar(ImGuiAxis.Y)
end
-- Resize grip(s)
if handle_borders_and_resize_grips and (bit32.band(flags, ImGuiWindowFlags.NoResize) == 0) then
for resize_grip_n = 1, #ImGuiResizeGripDef do
repeat
local col = resize_grip_col[resize_grip_n]
if bit32.band(col, IM_COL32_A_MASK) == 0 then
break
end
local grip = ImGuiResizeGripDef[resize_grip_n]
local corner = ImLerp(window.Pos, window.Pos + window.Size, grip.CornerPosN)
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)))
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)))
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)
window.DrawList:PathFillConvex(col)
until true
end
end
if handle_borders_and_resize_grips then
RenderWindowOuterBorders(window)
end
end
window.DC.NavLayerCurrent = ImGuiNavLayer.Main
end
--- @param window ImGuiWindow
--- @param title_bar_rect ImRect
--- @param name string
--- @param open bool?
--- @return bool?
local function RenderWindowTitleBarContents(window, title_bar_rect, name, open)
local g = GImGui
local style = g.Style
local flags = window.Flags
local has_close_button = (open ~= nil)
local has_collapse_button = bit32.band(flags, ImGuiWindowFlags.NoCollapse) == 0 and (style.WindowMenuButtonPosition ~= ImGuiDir.None)
local item_flags_backup = g.CurrentItemFlags
g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.NoNavDefaultFocus)
window.DC.NavLayerCurrent = ImGuiNavLayer.Menu
local pad_l = g.Style.FramePadding.x
local pad_r = g.Style.FramePadding.x
local button_sz = g.FontSize
local close_button_pos
local collapse_button_pos
if has_close_button then
close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y)
pad_r = pad_r + button_sz + style.ItemInnerSpacing.x
end
if has_collapse_button and style.WindowMenuButtonPosition == ImGuiDir.Right then
collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y)
pad_r = pad_r + button_sz + style.ItemInnerSpacing.x
end
if has_collapse_button and style.WindowMenuButtonPosition == ImGuiDir.Left then
collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y)
pad_l = pad_l + button_sz + style.ItemInnerSpacing.x
end
if has_collapse_button then
if ImGui.CollapseButton(window:GetID("#COLLAPSE"), collapse_button_pos) then
window.Collapsed = not window.Collapsed
end
end
if has_close_button then
local backup_item_flags = g.CurrentItemFlags
g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.NoFocus)
if ImGui.CloseButton(window:GetID("#CLOSE"), close_button_pos) then
open = false
end
g.CurrentItemFlags = backup_item_flags
end
window.DC.NavLayerCurrent = ImGuiNavLayer.Main
g.CurrentItemFlags = item_flags_backup
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)
if (pad_l > style.FramePadding.x) then
pad_l = pad_l + g.Style.ItemInnerSpacing.x
end
if (pad_r > style.FramePadding.x) then
pad_r = pad_r + g.Style.ItemInnerSpacing.x
end
if (style.WindowTitleAlign.x > 0.0 and style.WindowTitleAlign.x < 1.0) then
local centerness = ImSaturate(1.0 - ImFabs(style.WindowTitleAlign.x - 0.5) * 2.0)
local pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect:GetWidth() - pad_l - pad_r - text_size.x)
pad_l = ImMax(pad_l, pad_extend * centerness)
pad_r = ImMax(pad_r, pad_extend * centerness)
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 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)
if bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0 then
local marker_pos = ImVec2()
marker_pos.x = ImClamp(layout_r.Min.x + (layout_r:GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x)
marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5
if marker_pos.x > layout_r.Min.x then
ImGui.RenderBullet(window.DrawList, marker_pos, ImGui.GetColorU32(ImGuiCol.UnsavedMarker))
clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - math.floor(marker_size_x * 0.5))
end
end
ImGui.RenderTextClipped(layout_r.Min, layout_r.Max, name, nil, text_size, style.WindowTitleAlign, clip_r)
return open
end
--- @param window ImGuiWindow
--- @param flags ImGuiWindowFlags
--- @param parent_window? ImGuiWindow
function ImGui.UpdateWindowParentAndRootLinks(window, flags, parent_window)
window.ParentWindow = parent_window
window.RootWindow = window
window.RootWindowPopupTree = window
window.RootWindowDockTree = window
window.RootWindowForTitleBarHighlight = window
window.RootWindowForNav = window
if parent_window and (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0) and (bit32.band(flags, ImGuiWindowFlags.Tooltip) == 0) then
window.RootWindowDockTree = parent_window.RootWindowDockTree
if not window.DockIsActive and (bit32.band(parent_window.Flags, ImGuiWindowFlags.DockNodeHost) == 0) then
window.RootWindow = parent_window.RootWindow
end
end
if parent_window and (bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0) then
window.RootWindowPopupTree = parent_window.RootWindowPopupTree
end
if parent_window and (bit32.band(flags, ImGuiWindowFlags.Modal) == 0) and (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0) then
window.RootWindowForTitleBarHighlight = parent_window.RootWindowForTitleBarHighlight
end
while bit32.band(window.RootWindowForNav.ChildFlags, ImGuiChildFlags.NavFlattened) ~= 0 do
IM_ASSERT(window.RootWindowForNav.ParentWindow ~= nil)
window.RootWindowForNav = window.RootWindowForNav.ParentWindow
end
end
-- [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
-- This is designed as a toy/test-bed for
--- @param window ImGuiWindow
function ImGui.UpdateWindowSkipRefresh(window)
local g = GImGui
window.SkipRefresh = false
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasRefreshPolicy) == 0 then
return
end
if bit32.band(g.NextWindowData.RefreshFlagsVal, ImGuiWindowRefreshFlags.TryToAvoidRefresh) ~= 0 then
-- FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
if window.Appearing then -- If currently appearing
return
end
if window.Hidden then -- If was hidden (previous frame)
return
end
if bit32.band(g.NextWindowData.RefreshFlagsVal, ImGuiWindowRefreshFlags.RefreshOnHover) ~= 0 and g.HoveredWindow then
if window.RootWindow == g.HoveredWindow.RootWindow or ImGui.IsWindowWithinBeginStackOf(g.HoveredWindow.RootWindow, window) then
return
end
end
if bit32.band(g.NextWindowData.RefreshFlagsVal, ImGuiWindowRefreshFlags.RefreshOnFocus) ~= 0 and g.NavWindow then
if window.RootWindow == g.NavWindow.RootWindow or ImGui.IsWindowWithinBeginStackOf(g.NavWindow.RootWindow, window) then
return
end
end
window.DrawList = nil
window.SkipRefresh = true
end
end
--- @param window ImGuiWindow
local function SetWindowActiveForSkipRefresh(window)
window.Active = true
for _, child in window.DC.ChildWindows:iter() do
if not child.Hidden then
child.Active = true
child.SkipRefresh = true
SetWindowActiveForSkipRefresh(child)
end
end
end
--- @param window ImGuiWindow?
local function SetCurrentWindow(window)
local g = GImGui
--- @diagnostic disable-next-line
g.CurrentWindow = window
if window then
if bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0 then
local viewport = window.Viewport
g.FontRasterizerDensity = (viewport.FramebufferScale.x ~= 0.0) and viewport.FramebufferScale.x or g.IO.DisplayFramebufferScale.x
end
local backup_skip_items = window.SkipItems
window.SkipItems = false
ImGui.UpdateCurrentFontSize(0.0)
window.SkipItems = backup_skip_items
ImGui.NavUpdateCurrentWindowIsScrollPushableX()
end
end
-- TODO:
function ImGui.GcCompactTransientMiscBuffers()
local g = GImGui
g.ItemFlagsStack:clear()
g.GroupStack:clear()
g.InputTextLineIndex:clear()
for _, atlas in g.FontAtlases:iter() do
atlas:CompactCache()
end
end
--- @param window ImGuiWindow
function ImGui.GcCompactTransientWindowBuffers(window)
window.MemoryCompacted = true
window.MemoryDrawListIdxCapacity = ImMin(math.floor(window.DrawList.IdxBuffer.Size * 1.05), window.DrawList.IdxBuffer.Capacity)
window.MemoryDrawListVtxCapacity = ImMin(math.floor(window.DrawList.VtxBuffer.Size * 1.05), window.DrawList.VtxBuffer.Capacity)
window.IDStack:clear()
window.DrawList:_ClearFreeMemory()
window.DC.ChildWindows:clear()
window.DC.ItemWidthStack:clear()
window.DC.TextWrapPosStack:clear()
end
--- @param window ImGuiWindow
function ImGui.GcAwakeTransientWindowBuffers(window)
window.MemoryCompacted = false
window.DrawList.IdxBuffer:reserve(window.MemoryDrawListIdxCapacity)
window.DrawList.VtxBuffer:reserve(window.MemoryDrawListVtxCapacity)
window.MemoryDrawListIdxCapacity = 0
window.MemoryDrawListVtxCapacity = 0
end
function ImGui.GetWindowWidth()
local window = GImGui.CurrentWindow
return window.Size.x
end
--- @param window ImGuiWindow
--- @param pos ImVec2
--- @param cond? ImGuiCond
function ImGui.SetWindowPos(window, pos, cond)
if cond == nil then cond = 0 end
if (cond ~= 0) and (bit32.band(window.SetWindowPosAllowFlags, cond) == 0) then
return
end
IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond))
window.SetWindowPosAllowFlags = bit32.band(window.SetWindowPosAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing)))
ImVec2_Copy(window.SetWindowPosVal, ImVec2(FLT_MAX, FLT_MAX))
local old_pos = ImVec2()
ImVec2_Copy(old_pos, window.Pos)
window.Pos.x = ImTrunc(pos.x)
window.Pos.y = ImTrunc(pos.y)
local offset = window.Pos - old_pos
if offset.x == 0 and offset.y == 0 then
return
end
ImVec2_Copy(window.DC.CursorPos, window.DC.CursorPos + offset)
ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorMaxPos + offset)
ImVec2_Copy(window.DC.IdealMaxPos, window.DC.IdealMaxPos + offset)
ImVec2_Copy(window.DC.CursorStartPos, window.DC.CursorStartPos + offset)
end
--- @param window ImGuiWindow
--- @param size ImVec2
--- @param cond? ImGuiCond
function ImGui.SetWindowSize(window, size, cond)
if cond == nil then cond = 0 end
if ((cond ~= 0) and bit32.band(window.SetWindowSizeAllowFlags, cond) == 0) then
return
end
IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond))
window.SetWindowSizeAllowFlags = bit32.band(window.SetWindowSizeAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing)))
if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or window.Appearing or bit32.band(window.ChildFlags, ImGuiChildFlags.AlwaysAutoResize) ~= 0 then
window.AutoFitFramesX = (size.x <= 0.0) and 2 or 0
end
if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or window.Appearing or bit32.band(window.ChildFlags, ImGuiChildFlags.AlwaysAutoResize) ~= 0 then
window.AutoFitFramesY = (size.y <= 0.0) and 2 or 0
end
-- local old_size = ImVec2()
-- ImVec2_Copy(old_size, window.SizeFull)
if size.x <= 0.0 then
window.AutoFitOnlyGrows = false
else
window.SizeFull.x = IM_TRUNC(size.x)
end
if size.y <= 0.0 then
window.AutoFitOnlyGrows = false
else
window.SizeFull.y = IM_TRUNC(size.y)
end
-- if old_size.x ~= window.SizeFull.x or old_size.y ~= window.SizeFull.y then
-- TODO: MarkIniSettingsDirty(window)
-- end
end
--- @param window ImGuiWindow
function ImGui.SetWindowHiddenAndSkipItemsForCurrentFrame(window)
window.Hidden = true
window.SkipItems = true
window.HiddenFramesCanSkipItems = 1
end
--- @param pos ImVec2
--- @param cond? ImGuiCond
--- @param pivot? ImVec2
function ImGui.SetNextWindowPos(pos, cond, pivot)
if cond == nil then cond = 0 end
if pivot == nil then pivot = ImVec2(0, 0) end
local g = GImGui
IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond))
g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos)
ImVec2_Copy(g.NextWindowData.PosVal, pos)
ImVec2_Copy(g.NextWindowData.PosPivotVal, pivot)
g.NextWindowData.PosCond = (cond ~= 0) and cond or ImGuiCond.Always
end
--- @param size ImVec2
--- @param cond? ImGuiCond
function ImGui.SetNextWindowSize(size, cond)
if cond == nil then cond = 0 end
local g = GImGui
IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond))
g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize)
ImVec2_Copy(g.NextWindowData.SizeVal, size)
g.NextWindowData.SizeCond = (cond ~= 0) and cond or ImGuiCond.Always
end
-- For each axis:
-- - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
-- - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
-- - See "Demo->Examples->Constrained-resizing window" for examples.
--- @param size_min ImVec2
--- @param size_max ImVec2
--- @param custom_callback? function
--- @param custom_callback_user_data? any
function ImGui.SetNextWindowSizeConstraints(size_min, size_max, custom_callback, custom_callback_user_data)
local g = GImGui
g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint)
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max)
g.NextWindowData.SizeCallback = custom_callback
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data
end
--- @param alpha float
function ImGui.SetNextWindowBgAlpha(alpha)
local g = GImGui
g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasBgAlpha)
g.NextWindowData.BgAlphaVal = alpha
end
function ImGui.GetWindowDrawList()
local window = ImGui.GetCurrentWindow()
return window.DrawList
end
function ImGui.GetFont()
return GImGui.Font
end
function ImGui.GetFontSize()
return GImGui.FontSize
end
--- @return ImVec2
function ImGui.GetFontTexUvWhitePixel()
return GImGui.DrawListSharedData.TexUvWhitePixel
end
-- This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
-- FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
function ImGui.SetActiveIdUsingAllKeyboardKeys()
local g = GImGui
IM_ASSERT(g.ActiveId ~= 0)
g.ActiveIdUsingNavDirMask = (bit32.lshift(1, ImGuiDir.COUNT) - 1)
g.ActiveIdUsingAllKeyboardKeys = true
ImGui.NavMoveRequestCancel()
end
--- @return ImVec2 # Ref
function ImGui.GetItemRectMin()
local g = GImGui
return g.LastItemData.Rect.Min
end
--- @return ImVec2 # Ref
function ImGui.GetItemRectMax()
local g = GImGui
return g.LastItemData.Rect.Max
end
--- @param name string
--- @param id ImGuiID
--- @param size_arg ImVec2
--- @param child_flags ImGuiChildFlags
--- @param window_flags ImGuiWindowFlags
function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags)
local g = GImGui
local parent_window = g.CurrentWindow
IM_ASSERT(id ~= 0)
-- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument
local ImGuiChildFlags_SupportedMask_ = bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY, ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize, ImGuiChildFlags.FrameStyle, ImGuiChildFlags.NavFlattened)
-- IM_UNUSED(ImGuiChildFlags_SupportedMask_)
IM_ASSERT(bit32.band(child_flags, bit32.bnot(ImGuiChildFlags_SupportedMask_)) == 0, "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?")
IM_ASSERT(bit32.band(window_flags, ImGuiWindowFlags.AlwaysAutoResize) == 0, "Cannot specify ImGuiWindowFlags.AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags.AlwaysAutoResize!")
if bit32.band(child_flags, ImGuiChildFlags.AlwaysAutoResize) ~= 0 then
IM_ASSERT(bit32.band(child_flags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0, "Cannot use ImGuiChildFlags.ResizeX or ImGuiChildFlags.ResizeY with ImGuiChildFlags.AlwaysAutoResize!")
IM_ASSERT(bit32.band(child_flags, bit32.bor(ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY)) ~= 0, "Must use ImGuiChildFlags.AutoResizeX or ImGuiChildFlags.AutoResizeY with ImGuiChildFlags.AlwaysAutoResize!")
end
if bit32.band(child_flags, ImGuiChildFlags.AutoResizeX) ~= 0 then
child_flags = bit32.band(child_flags, bit32.bnot(ImGuiChildFlags.ResizeX))
end
if bit32.band(child_flags, ImGuiChildFlags.AutoResizeY) ~= 0 then
child_flags = bit32.band(child_flags, bit32.bnot(ImGuiChildFlags.ResizeY))
end
-- Set window flags
window_flags = bit32.bor(window_flags, ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoTitleBar)
window_flags = bit32.bor(window_flags, bit32.band(parent_window.Flags, ImGuiWindowFlags.NoMove)) -- Inherit the NoMove flag
if bit32.band(child_flags, bit32.bor(ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize)) ~= 0 then
window_flags = bit32.bor(window_flags, ImGuiWindowFlags.AlwaysAutoResize)
end
if bit32.band(child_flags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0 then
window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings)
end
-- Special framed style
if bit32.band(child_flags, ImGuiChildFlags.FrameStyle) ~= 0 then
ImGui.PushStyleColor(ImGuiCol.ChildBg, g.Style.Colors[ImGuiCol.FrameBg])
ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, g.Style.FrameRounding)
ImGui.PushStyleVar(ImGuiStyleVar.ChildBorderSize, g.Style.FrameBorderSize)
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, g.Style.FramePadding)
child_flags = bit32.bor(child_flags, ImGuiChildFlags.Borders, ImGuiChildFlags.AlwaysUseWindowPadding)
window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoMove)
end
-- Forward size
-- Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags.ResizeXXX is set.
-- (the alternative would to store conditional flags per axis, which is possible but more code)
local size_avail = ImGui.GetContentRegionAvail()
local size_default = ImVec2((bit32.band(child_flags, ImGuiChildFlags.AutoResizeX) ~= 0) and 0.0 or size_avail.x, (bit32.band(child_flags, ImGuiChildFlags.AutoResizeY) ~= 0) and 0.0 or size_avail.y)
local size = ImGui.CalcItemSize(size_arg, size_default.x, size_default.y)
-- A SetNextWindowSize() call always has priority (#8020)
-- (since the code in Begin() never supported SizeVal==0.0f aka auto-resize via SetNextWindowSize() call, we don't support it here for now)
-- FIXME: We only support ImGuiCond_Always in this path. Supporting other paths would requires to obtain window pointer.
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ~= 0 and bit32.band(g.NextWindowData.SizeCond, ImGuiCond.Always) ~= 0 then
if g.NextWindowData.SizeVal.x > 0.0 then
size.x = g.NextWindowData.SizeVal.x
child_flags = bit32.band(child_flags, bit32.bnot(ImGuiChildFlags.ResizeX))
end
if g.NextWindowData.SizeVal.y > 0.0 then
size.y = g.NextWindowData.SizeVal.y
child_flags = bit32.band(child_flags, bit32.bnot(ImGuiChildFlags.ResizeY))
end
end
ImGui.SetNextWindowSize(size)
-- Forward child flags (we allow prior settings to merge but it'll only work for adding flags)
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasChildFlags) ~= 0 then
g.NextWindowData.ChildFlags = bit32.bor(g.NextWindowData.ChildFlags, child_flags)
else
g.NextWindowData.ChildFlags = child_flags
end
g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasChildFlags)
-- Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
-- FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
-- e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
local temp_window_name
if name then
temp_window_name = ImFormatString("%s/%s_%08X", parent_window.Name, name, id)
else
temp_window_name = ImFormatString("%s/%08X", parent_window.Name, id)
end
-- Set style
local backup_border_size = g.Style.ChildBorderSize
if bit32.band(child_flags, ImGuiChildFlags.Borders) == 0 then
g.Style.ChildBorderSize = 0.0
end
-- Begin into window
local _, ret = ImGui.Begin(temp_window_name, nil, window_flags)
-- Restore style
g.Style.ChildBorderSize = backup_border_size
if bit32.band(child_flags, ImGuiChildFlags.FrameStyle) ~= 0 then
ImGui.PopStyleVar(3)
ImGui.PopStyleColor()
end
local child_window = g.CurrentWindow
child_window.ChildId = id
-- Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
-- While this is not really documented/defined, it seems that the expected thing to do.
if child_window.BeginCount == 1 then
ImVec2_Copy(parent_window.DC.CursorPos, child_window.Pos)
end
-- Process navigation-in immediately so NavInit can run on first frame
-- Can enter a child if (A) it has navigable items or (B) it can be scrolled.
local temp_id_for_activation = ImHashStr("##Child", nil, id)
if g.ActiveId == temp_id_for_activation then
ImGui.ClearActiveID()
end
if g.NavActivateId == id and bit32.band(child_flags, ImGuiChildFlags.NavFlattened) == 0 and (child_window.DC.NavLayersActiveMask ~= 0 or child_window.DC.NavWindowHasScrollY) then
ImGui.FocusWindow(child_window)
ImGui.NavInitWindow(child_window, false)
ImGui.SetActiveID(temp_id_for_activation, child_window) -- Steal ActiveId with another arbitrary id so that key-press won't activate child item
g.ActiveIdSource = g.NavInputSource
end
return ret
end
--- @param window ImGuiWindow
local function StartMouseMovingWindow(window)
local g = GImGui
ImGui.FocusWindow(window)
ImGui.SetActiveID(window.MoveId, window)
if (g.IO.ConfigNavCursorVisibleAuto) then
g.NavCursorVisible = false
end
g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window.RootWindowDockTree.Pos
g.ActiveIdNoClearOnFocusLoss = true
ImGui.SetActiveIdUsingAllKeyboardKeys()
local can_move_window = true
if bit32.band(window.Flags, ImGuiWindowFlags.NoMove) ~= 0 or bit32.band(window.RootWindowDockTree.Flags, ImGuiWindowFlags.NoMove) ~= 0 then
can_move_window = false
end
if can_move_window then
g.MovingWindow = window
end
end
function ImGui.UpdateMouseMovingWindowNewFrame()
local g = GImGui
if g.MovingWindow then
ImGui.KeepAliveID(g.ActiveId)
IM_ASSERT(g.MovingWindow and g.MovingWindow.RootWindow)
local moving_window = g.MovingWindow.RootWindow
local window_disappeared = (not moving_window.WasActive and not moving_window.Active)
if g.IO.MouseDown[0] and ImGui.IsMousePosValid(g.IO.MousePos) and not window_disappeared then
local pos = g.IO.MousePos - g.ActiveIdClickOffset
if moving_window.Pos.x ~= pos.x or moving_window.Pos.y ~= pos.y then
ImGui.SetWindowPos(moving_window, pos, ImGuiCond.Always)
if moving_window.Viewport and moving_window.ViewportOwned then -- Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
ImVec2_Copy(moving_window.Viewport.Pos, pos)
moving_window.Viewport:UpdateWorkRect()
end
end
ImGui.FocusWindow(g.MovingWindow)
else
ImGui.StopMouseMovingWindow()
ImGui.ClearActiveID()
end
else
if (g.ActiveIdWindow and g.ActiveIdWindow.MoveId == g.ActiveId) then
ImGui.KeepAliveID(g.ActiveId)
if not g.IO.MouseDown[0] then
ImGui.ClearActiveID()
end
end
end
end
function ImGui.GetDrawListSharedData()
return GImGui.DrawListSharedData
end
--- @param id ImGuiID
--- @param popup_flags ImGuiPopupFlags
function ImGui.IsPopupOpen(id, popup_flags)
local g = GImGui
if bit32.band(popup_flags, ImGuiPopupFlags.AnyPopupId) ~= 0 then
-- Return true if any popup is open at the current BeginPopup() level of the popup stack
-- This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
IM_ASSERT(id == 0)
if bit32.band(popup_flags, ImGuiPopupFlags.AnyPopupLevel) ~= 0 then
return g.OpenPopupStack.Size > 0
else
return g.OpenPopupStack.Size > g.BeginPopupStack.Size
end
else
if bit32.band(popup_flags, ImGuiPopupFlags.AnyPopupLevel) ~= 0 then
-- Return true if the popup is open anywhere in the popup stack
for n = 1, g.OpenPopupStack.Size do
if g.OpenPopupStack.Data[n].PopupId == id then
return true
end
end
return false
else
-- Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
return g.OpenPopupStack.Size > g.BeginPopupStack.Size and g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1].PopupId == id
end
end
end
--- @return ImGuiWindow?
function ImGui.GetTopMostPopupModal()
local g = GImGui
for n = g.OpenPopupStack.Size, 1, -1 do
local popup = g.OpenPopupStack.Data[n].Window
if popup then
if bit32.band(popup.Flags, ImGuiWindowFlags.Modal) ~= 0 then
return popup
end
end
end
return nil
end
function ImGui.UpdateMouseMovingWindowEndFrame()
local g = GImGui
if g.ActiveId ~= 0 or (g.HoveredId ~= 0 and not g.HoveredIdIsDisabled) then
return
end
if g.NavWindow and g.NavWindow.Appearing then
return
end
local hovered_window = g.HoveredWindow
if ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) then
local hovered_root
if hovered_window then
hovered_root = hovered_window.RootWindow
else
hovered_root = nil
end
local is_closed_popup = hovered_root and (bit32.band(hovered_root.Flags, ImGuiWindowFlags.Popup) ~= 0) and not ImGui.IsPopupOpen(hovered_root.PopupId, ImGuiPopupFlags.AnyPopupLevel)
local is_queued_focus_request = g.NavMoveSubmitted and (bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.FocusApi) ~= 0)
if hovered_window ~= nil and not is_closed_popup and not is_queued_focus_request then
StartMouseMovingWindow(hovered_window)
-- Cancel moving if clicked outside of title bar
if bit32.band(hovered_window.BgClickFlags, ImGuiWindowBgClickFlags.Move) == 0 then -- set by io.ConfigWindowsMoveFromTitleBarOnly
if bit32.band(hovered_root.Flags, ImGuiWindowFlags.NoTitleBar) == 0 then
if not hovered_root:TitleBarRect():Contains(g.IO.MouseClickedPos[0]) then
g.MovingWindow = nil
end
end
end
-- Cancel moving if clicked over an item which was disabled or inhibited by popups
-- (when g.HoveredIdIsDisabled == true && g.HoveredId == 0 we are inhibited by popups, when g.HoveredIdIsDisabled == true && g.HoveredId != 0 we are over a disabled item)
if g.HoveredIdIsDisabled then
g.MovingWindow = nil
g.ActiveIdDisabledId = g.HoveredId
end
elseif hovered_window == nil and g.NavWindow ~= nil then
ImGui.FocusWindow(nil, ImGuiFocusRequestFlags.UnlessBelowModal)
end
end
-- With right mouse button we close popups without changing focus based on where the mouse is aimed
-- Instead, focus will be restored to the window under the bottom-most closed popup.
-- (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
if g.HoveredId == 0 and ImGui.IsMouseClickedEx(1, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) then
-- Find the top-most window between HoveredWindow and the top-most Modal Window.
-- This is where we can trim the popup stack.
local modal = ImGui.GetTopMostPopupModal()
local hovered_window_above_modal = hovered_window and (modal == nil or ImGui.IsWindowAbove(hovered_window, modal))
ImGui.ClosePopupsOverWindow(hovered_window_above_modal and hovered_window or modal, true)
end
end
--- @param window ImGuiWindow
--- @param delta ImVec2
function ImGui.TranslateWindow(window, delta)
ImVec2_Copy(window.Pos, window.Pos + delta)
window.ClipRect:Translate(delta)
window.OuterRectClipped:Translate(delta)
window.InnerRect:Translate(delta)
ImVec2_Copy(window.DC.CursorPos, window.DC.CursorPos + delta)
ImVec2_Copy(window.DC.CursorStartPos, window.DC.CursorStartPos + delta)
ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorMaxPos + delta)
ImVec2_Copy(window.DC.IdealMaxPos, window.DC.IdealMaxPos + delta)
end
--- ImGui::FindWindowByID
function ImGui.FindWindowByID(id)
local g = GImGui
if not g then return end
return g.WindowsById[id]
end
--- @param name string
--- @return ImGuiWindow?
function ImGui.FindWindowByName(name)
local id = ImHashStr(name)
return ImGui.FindWindowByID(id)
end
--- Push a new Dear ImGui window to add widgets to.
--- - Passing a non-nil `open` displays a close button on the upper-right corner of the window
--- @param name string
--- @param open? bool
--- @param flags? ImGuiWindowFlags
--- @return bool is_open # The updated `open` passed in
--- @return bool no_skip_items # You always need to call `ImGui.End()` even if false is returned
function ImGui.Begin(name, open, flags)
if flags == nil then flags = 0 end
local g = GImGui
local style = g.Style
IM_ASSERT(name ~= nil and name ~= "")
IM_ASSERT(g.WithinFrameScope)
IM_ASSERT(g.FrameCountEnded ~= g.FrameCount)
local window = ImGui.FindWindowByName(name)
local window_just_created = (window == nil)
if window_just_created then
window = CreateNewWindow(name, flags) --- @cast window ImGuiWindow
end
local current_frame = g.FrameCount
local first_begin_of_the_frame = (window.LastFrameActive ~= current_frame)
window.IsFallbackWindow = (g.CurrentWindowStack.Size == 0 and g.WithinFrameScopeWithImplicitWindow)
local window_just_activated_by_user = (window.LastFrameActive < (current_frame - 1))
if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then
local popup_ref = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1]
window_just_activated_by_user = window_just_activated_by_user or (window.PopupId ~= popup_ref.PopupId) -- We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user = window_just_activated_by_user or (window ~= popup_ref.Window)
end
window.Appearing = window_just_activated_by_user
if (window.Appearing) then
SetWindowConditionAllowFlags(window, ImGuiCond.Appearing, true)
end
-- Update Flags, LastFrameActive, BeginOrderXXX fields
local window_was_appearing = window.Appearing
if first_begin_of_the_frame then
ImGui.UpdateWindowInFocusOrderList(window, window_just_created, flags)
window.Appearing = window_just_activated_by_user
if (window.Appearing) then
SetWindowConditionAllowFlags(window, ImGuiCond.Appearing, true)
end
window.FlagsPreviousFrame = window.Flags
window.Flags = flags
window.ChildFlags = (bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasChildFlags) ~= 0) and g.NextWindowData.ChildFlags or 0
window.LastFrameActive = current_frame
window.LastTimeActive = g.Time
window.BeginOrderWithinParent = 0
window.BeginOrderWithinContext = g.WindowsActiveCount
g.WindowsActiveCount = g.WindowsActiveCount + 1
else
flags = window.Flags
end
local parent_window_in_stack
if g.CurrentWindowStack:empty() then
parent_window_in_stack = nil
else
parent_window_in_stack = g.CurrentWindowStack:back().Window
end
local parent_window
if first_begin_of_the_frame then
if (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0) then
parent_window = parent_window_in_stack
else
parent_window = nil
end
else
parent_window = window.ParentWindow
end
if window.IDStack.Size == 0 then
window.IDStack:push_back(window.ID)
end
-- Add to stack
g.CurrentWindow = window
g.CurrentWindowStack:resize(g.CurrentWindowStack.Size + 1)
g.CurrentWindowStack.Data[g.CurrentWindowStack.Size] = ImGuiWindowStackData()
local window_stack_data = g.CurrentWindowStack.Data[g.CurrentWindowStack.Size]
window_stack_data.Window = window
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.DisabledOverrideReenableAlphaBackup = 0.0
-- g.StackSizesInBeginForCurrentWindow = window_stack_data.StackSizesInBegin
if bit32.band(flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
g.BeginMenuDepth = g.BeginMenuDepth + 1
end
if first_begin_of_the_frame then
ImGui.UpdateWindowParentAndRootLinks(window, flags, parent_window)
window.ParentWindowInBeginStack = parent_window_in_stack
if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
window.ParentWindowForFocusRoute = parent_window_in_stack
else
window.ParentWindowForFocusRoute = nil
end
if parent_window then
window.FontWindowScaleParents = parent_window.FontWindowScaleParents * parent_window.FontWindowScale
else
window.FontWindowScaleParents = 1.0
end
end
ImGui.PushFocusScope((bit32.band(window.ChildFlags, ImGuiChildFlags.NavFlattened) ~= 0) and g.CurrentFocusScopeId or window.ID)
window.NavRootFocusScopeId = g.CurrentFocusScopeId
-- Add to popup stacks: update OpenPopupStack data, push to BeginPopupStack
if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then
local popup_ref = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1]
popup_ref.Window = window
popup_ref.ParentNavLayer = parent_window_in_stack.DC.NavLayerCurrent
g.BeginPopupStack:push_back(popup_ref)
window.PopupId = popup_ref.PopupId
end
local window_pos_set_by_api = false
local window_size_x_set_by_api = false
local window_size_y_set_by_api = false
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ~= 0 then
window_pos_set_by_api = (bit32.band(window.SetWindowPosAllowFlags, g.NextWindowData.PosCond) ~= 0)
if window_pos_set_by_api and ImLengthSqr(g.NextWindowData.PosPivotVal) > 1e-5 then
-- FIXME: Look into removing the branch so everything can go through this same code path for consistency.
ImVec2_Copy(window.SetWindowPosVal, g.NextWindowData.PosVal)
ImVec2_Copy(window.SetWindowPosPivot, g.NextWindowData.PosPivotVal)
window.SetWindowPosAllowFlags = bit32.band(window.SetWindowPosAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing)))
else
ImGui.SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond)
end
end
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ~= 0 then
window_size_x_set_by_api = (bit32.band(window.SetWindowSizeAllowFlags, g.NextWindowData.SizeCond) ~= 0) and (g.NextWindowData.SizeVal.x > 0.0)
window_size_y_set_by_api = (bit32.band(window.SetWindowSizeAllowFlags, g.NextWindowData.SizeCond) ~= 0) and (g.NextWindowData.SizeVal.y > 0.0)
if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then
g.NextWindowData.SizeVal.x = window.SizeFull.x
end
if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then
g.NextWindowData.SizeVal.y = window.SizeFull.y
end
ImGui.SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
end
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasScroll) ~= 0 then
if g.NextWindowData.ScrollVal.x >= 0.0 then
window.ScrollTarget.x = g.NextWindowData.ScrollVal.x
window.ScrollTargetCenterRatio.x = 0.0
end
if g.NextWindowData.ScrollVal.y >= 0.0 then
window.ScrollTarget.y = g.NextWindowData.ScrollVal.y
window.ScrollTargetCenterRatio.y = 0.0
end
end
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasContentSize) ~= 0 then
ImVec2_Copy(window.ContentSizeExplicit, g.NextWindowData.ContentSizeVal)
elseif first_begin_of_the_frame then
window.ContentSizeExplicit = ImVec2(0.0, 0.0)
end
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasWindowClass) ~= 0 then
window.WindowClass = g.NextWindowData.WindowClass
end
-- [EXPERIMENTAL] Skip Refresh mode
ImGui.UpdateWindowSkipRefresh(window)
if window_stack_data.DisabledOverrideReenable and window.RootWindow == window then
ImGui.BeginDisabledOverrideReenable()
end
g.CurrentWindow = nil
if first_begin_of_the_frame and not window.SkipRefresh then
local window_is_child_tooltip = (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0)
local window_just_appearing_after_hidden_for_resize = (window.HiddenFramesCannotSkipItems > 0)
window.Active = true
window.HasCloseButton = (open ~= nil)
ImRect_CopyFromV4(window.ClipRect, ImVec4(-FLT_MAX, -FLT_MAX, FLT_MAX, FLT_MAX))
window.IDStack:resize(1)
window.DrawList:_ResetForNewFrame()
if window.MemoryCompacted then
ImGui.GcAwakeTransientWindowBuffers(window)
end
-- UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
-- Update contents size from last frame for auto-fitting (or use explicit size)
CalcWindowContentSizes(window, window.ContentSize, window.ContentSizeIdeal)
if window.HiddenFramesCanSkipItems > 0 then
window.HiddenFramesCanSkipItems = window.HiddenFramesCanSkipItems - 1
end
if window.HiddenFramesCannotSkipItems > 0 then
window.HiddenFramesCannotSkipItems = window.HiddenFramesCannotSkipItems - 1
end
if window.HiddenFramesForRenderOnly > 0 then
window.HiddenFramesForRenderOnly = window.HiddenFramesForRenderOnly - 1
end
-- Hide new windows for one frame until they calculate their size
if window_just_created then
window.HiddenFramesCannotSkipItems = 1
end
-- Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
-- We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if window_just_activated_by_user and bit32.band(flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0 then
window.HiddenFramesCannotSkipItems = 1
if bit32.band(flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 then
if not window_size_x_set_by_api then
window.SizeFull.x = 0.0
window.Size.x = 0.0
end
if not window_size_y_set_by_api then
window.SizeFull.y = 0.0
window.Size.y = 0.0
end
ImVec2_Copy(window.ContentSize, ImVec2(0.0, 0.0))
ImVec2_Copy(window.ContentSizeIdeal, ImVec2(0.0, 0.0))
end
end
-- SELECT VIEWPORT
ImGui.WindowSelectViewport(window)
ImGui.SetCurrentViewport(window, window.Viewport)
SetCurrentWindow(window)
flags = window.Flags
if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
window.WindowBorderSize = style.ChildBorderSize
else
window.WindowBorderSize = (bit32.band(flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Modal) == 0) and style.PopupBorderSize or style.WindowBorderSize
end
window.WindowPadding = style.WindowPadding
if (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0) and (bit32.band(flags, ImGuiWindowFlags.Popup) == 0) and (bit32.band(window.ChildFlags, ImGuiChildFlags.AlwaysUseWindowPadding) == 0) and window.WindowBorderSize == 0.0 then
if bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 then
window.WindowPadding = ImVec2(0.0, style.WindowPadding.y)
else
window.WindowPadding = ImVec2(0.0, 0.0)
end
end
-- Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
window.DC.MenuBarOffset.x = ImMax(ImMax(window.WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x)
window.DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y
if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0 then
window.TitleBarHeight = 0.0
else
window.TitleBarHeight = g.FontSize + g.Style.FramePadding.y * 2.0
end
if bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 then
window.MenuBarHeight = window.DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0
else
window.MenuBarHeight = 0.0
end
window.TitleBarHeight = (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and 0 or g.FontSize + g.Style.FramePadding.y * 2
window.FontRefSize = g.FontSize -- Lock this to discourage calling window:CalcFontSize() outside of current window.
local use_current_size_for_scrollbar_x = window_just_created
local use_current_size_for_scrollbar_y = window_just_created
if window_size_x_set_by_api and window.ContentSizeExplicit.x ~= 0.0 then
use_current_size_for_scrollbar_x = true
end
if window_size_y_set_by_api and window.ContentSizeExplicit.y ~= 0.0 then
use_current_size_for_scrollbar_y = true
end
-- TODO: Collapse window by double-clicking on title bar
local scrollbar_sizes_from_last_frame = ImVec2()
ImVec2_Copy(scrollbar_sizes_from_last_frame, window.ScrollbarSizes)
window.DecoOuterSizeX1 = 0.0
window.DecoOuterSizeX2 = 0.0
window.DecoOuterSizeY1 = window.TitleBarHeight + window.MenuBarHeight
window.DecoOuterSizeY2 = 0.0
window.ScrollbarSizes = ImVec2(0.0, 0.0)
-- Calculate auto-fit size, handle automatic resize
-- - Using SetNextWindowSize() overrides ImGuiWindowFlags.AlwaysAutoResize, so it can be used on tooltips/popups, etc.
-- - We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags.AlwaysAutoResize when collapsed.
-- - Auto-fit may only grow window during the first few frames.
do
local size_auto_fit_x_always = not window_size_x_set_by_api and (bit32.band(flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0) and not window.Collapsed
local size_auto_fit_y_always = not window_size_y_set_by_api and (bit32.band(flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0) and not window.Collapsed
local size_auto_fit_x_current = not window_size_x_set_by_api and (window.AutoFitFramesX > 0)
local size_auto_fit_y_current = not window_size_y_set_by_api and (window.AutoFitFramesY > 0)
local size_auto_fit_mask = 0
if size_auto_fit_x_always or size_auto_fit_x_current then
size_auto_fit_mask = bit32.bor(size_auto_fit_mask, bit32.lshift(1, ImGuiAxis.X - 1))
end
if size_auto_fit_y_always or size_auto_fit_y_current then
size_auto_fit_mask = bit32.bor(size_auto_fit_mask, bit32.lshift(1, ImGuiAxis.Y - 1))
end
local size_auto_fit = CalcWindowAutoFitSize(window, window.ContentSizeIdeal, size_auto_fit_mask)
local old_size = ImVec2(window.SizeFull.x, window.SizeFull.y)
if size_auto_fit_x_always or size_auto_fit_x_current then
if size_auto_fit_x_always then
window.SizeFull.x = size_auto_fit.x
else
if window.AutoFitOnlyGrows then
window.SizeFull.x = ImMax(window.SizeFull.x, size_auto_fit.x)
else
window.SizeFull.x = size_auto_fit.x
end
end
use_current_size_for_scrollbar_x = true
end
if size_auto_fit_y_always or size_auto_fit_y_current then
if size_auto_fit_y_always then
window.SizeFull.y = size_auto_fit.y
else
if window.AutoFitOnlyGrows then
window.SizeFull.y = ImMax(window.SizeFull.y, size_auto_fit.y)
else
window.SizeFull.y = size_auto_fit.y
end
end
use_current_size_for_scrollbar_y = true
end
if old_size.x ~= window.SizeFull.x or old_size.y ~= window.SizeFull.y then
-- ImGui.MarkIniSettingsDirty(window)
end
end
ImVec2_Copy(window.SizeFull, CalcWindowSizeAfterConstraint(window, window.SizeFull))
ImVec2_Copy(window.Size, (window.Collapsed and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0) and window:TitleBarRect():GetSize() or window.SizeFull)
-- POSITION
-- Popup latch its initial position, will position itself when it appears next frame
if window_just_activated_by_user then
window.AutoPosLastDirection = ImGuiDir.None
if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Modal) == 0 and not window_pos_set_by_api then -- FIXME: BeginPopup() could use SetNextWindowPos()
ImVec2_Copy(window.Pos, g.BeginPopupStack:back().OpenPopupPos)
end
end
if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
IM_ASSERT(parent_window and parent_window.Active)
window.BeginOrderWithinParent = parent_window.DC.ChildWindows.Size
parent_window.DC.ChildWindows:push_back(window)
if (bit32.band(flags, ImGuiWindowFlags.Popup) == 0) and not window_pos_set_by_api and not window_is_child_tooltip then
ImVec2_Copy(window.Pos, parent_window.DC.CursorPos)
end
end
local window_pos_with_pivot = (window.SetWindowPosVal.x ~= FLT_MAX and window.HiddenFramesCannotSkipItems == 0)
if window_pos_with_pivot then
ImGui.SetWindowPos(window, window.SetWindowPosVal - window.Size * window.SetWindowPosPivot, 0) -- Position given a pivot (e.g. for centering)
elseif (bit32.band(flags, ImGuiWindowFlags.ChildMenu) ~= 0) then
ImVec2_Copy(window.Pos, ImGui.FindBestWindowPosForPopup(window))
elseif (bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0) and not window_pos_set_by_api and window_just_appearing_after_hidden_for_resize then
ImVec2_Copy(window.Pos, ImGui.FindBestWindowPosForPopup(window))
elseif (bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) and not window_pos_set_by_api and not window_is_child_tooltip then
ImVec2_Copy(window.Pos, ImGui.FindBestWindowPosForPopup(window))
end
-- Late create viewport if we don't fit within our current host viewport.
if window.ViewportAllowPlatformMonitorExtend >= 0 and not window.ViewportOwned and bit32.band(window.Viewport.Flags, ImGuiViewportFlags.IsMinimized) == 0 then
if not window.Viewport:GetMainRect():Contains(window:Rect()) then
-- This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
-- local old_viewport = window.Viewport
window.Viewport = ImGui.AddUpdateViewport(window, window.ID, window.Pos, window.Size, ImGuiViewportFlags.NoFocusOnAppearing)
-- FIXME-DPI
-- IM_ASSERT(old_viewport.DpiScale == window.Viewport.DpiScale) -- FIXME-DPI: Something went wrong
ImGui.SetCurrentViewport(window, window.Viewport)
SetCurrentWindow(window)
end
end
if window.ViewportOwned then
ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack)
end
local viewport_rect = window.Viewport:GetMainRect()
local viewport_work_rect = window.Viewport:GetWorkRect()
local visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding)
local visibility_rect = ImRect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding)
window.Pos.x = ImTrunc(window.Pos.x) window.Pos.y = ImTrunc(window.Pos.y)
local want_focus = false
if (window_just_activated_by_user and bit32.band(flags, ImGuiWindowFlags.NoFocusOnAppearing) == 0) then
if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then
want_focus = true
elseif (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Tooltip)) == 0)then
want_focus = true
end
end
if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
window.WindowRounding = style.ChildRounding
else
if (bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Modal) == 0) then
window.WindowRounding = style.PopupRounding
else
window.WindowRounding = style.WindowRounding
end
end
local handle_borders_and_resize_grips = true
if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and window.ParentWindow.SkipItems then
handle_borders_and_resize_grips = false
end
local border_hovered, border_held = -1, -1
local resize_grip_col = {0, 0, 0, 0}
local resize_grip_count
if (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0) and (bit32.band(flags, ImGuiWindowFlags.Popup) == 0) then
if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0) and (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0) then
resize_grip_count = 1
else
resize_grip_count = 0
end
else
resize_grip_count = g.IO.ConfigWindowsResizeFromEdges and 2 or 1 -- Allow resize from lower-left if we have the mouse cursor feedback for it.
end
local resize_grip_draw_size = ImTrunc(ImMax(g.FontSize * 1.10, g.Style.WindowRounding + 1.0 + g.FontSize * 0.2))
if handle_borders_and_resize_grips and not window.Collapsed then
local auto_fit_mask
auto_fit_mask, border_hovered, border_held = UpdateWindowManualResize(window, resize_grip_count, resize_grip_col, visibility_rect)
if auto_fit_mask ~= 0 then
if bit32.band(auto_fit_mask, bit32.lshift(1, ImGuiAxis.X - 1)) ~= 0 then
use_current_size_for_scrollbar_x = true
end
if bit32.band(auto_fit_mask, bit32.lshift(1, ImGuiAxis.Y - 1)) ~= 0 then
use_current_size_for_scrollbar_y = true
end
end
end
window.ResizeBorderHovered = border_hovered
window.ResizeBorderHeld = border_held
-- Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
if window.ViewportOwned then
if not window.Viewport.PlatformRequestMove then
ImVec2_Copy(window.Viewport.Pos, window.Pos)
end
if not window.Viewport.PlatformRequestResize then
ImVec2_Copy(window.Viewport.Size, window.Size)
end
window.Viewport:UpdateWorkRect()
viewport_rect = window.Viewport:GetMainRect()
end
-- Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
ImVec2_Copy(window.ViewportPos, window.Viewport.Pos)
--- SCROLLBAR VISIBILITY
-- Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size)
if not window.Collapsed then
-- When reading the current size we need to read it after size constraints have been applied.
-- Intentionally use previous frame values for InnerRect and ScrollbarSizes.
-- And when we use window.DecoOuterSizeY1 here it doesn't have ScrollbarSizes.y applied yet.
local avail_size_from_current_frame = ImVec2(window.SizeFull.x, window.SizeFull.y - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2))
local avail_size_from_last_frame = window.InnerRect:GetSize() + scrollbar_sizes_from_last_frame
local needed_size_from_last_frame = window_just_created and ImVec2(0, 0) or window.ContentSize + window.WindowPadding * 2.0
local size_for_scrollbars_x = use_current_size_for_scrollbar_x and avail_size_from_current_frame.x or avail_size_from_last_frame.x
local size_for_scrollbars_y = use_current_size_for_scrollbar_y and avail_size_from_current_frame.y or avail_size_from_last_frame.y
local scrollbar_x_prev = window.ScrollbarX
-- local scrollbar_y_from_last_frame = window.ScrollbarY -- FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
window.ScrollbarY = (bit32.band(flags, ImGuiWindowFlags.AlwaysVerticalScrollbar) ~= 0) or ((needed_size_from_last_frame.y > size_for_scrollbars_y) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0))
window.ScrollbarX = (bit32.band(flags, ImGuiWindowFlags.AlwaysHorizontalScrollbar) ~= 0) or ((needed_size_from_last_frame.x > size_for_scrollbars_x - (window.ScrollbarY and style.ScrollbarSize or 0.0)) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0) and (bit32.band(flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0))
-- Track when ScrollbarX visibility keeps toggling, which is a sign of a feedback loop, and stabilize by enforcing visibility (#3285, #8488)
-- (Feedback loops of this sort can manifest in various situations, but combining horizontal + vertical scrollbar + using a clipper with varying width items is one frequent cause.
-- The better solution is to, either (1) enforce visibility by using ImGuiWindowFlags.AlwaysHorizontalScrollbar or (2) declare stable contents width with SetNextWindowContentSize(), if you can compute it)
window.ScrollbarXStabilizeToggledHistory = bit32.lshift(window.ScrollbarXStabilizeToggledHistory, 1)
if scrollbar_x_prev ~= window.ScrollbarX then
window.ScrollbarXStabilizeToggledHistory = bit32.bor(window.ScrollbarXStabilizeToggledHistory, 0x01)
end
local scrollbar_x_stabilize = (window.ScrollbarXStabilizeToggledHistory ~= 0) and ImCountSetBits(window.ScrollbarXStabilizeToggledHistory) >= 4 -- 4 == half of bits in our U8 history.
if scrollbar_x_stabilize then
window.ScrollbarX = true
end
-- if scrollbar_x_stabilize and not window.ScrollbarXStabilizeEnabled then
-- IMGUI_DEBUG_LOG("[scroll] Stabilize ScrollbarX for Window '%s'\n", window.Name)
-- end
window.ScrollbarXStabilizeEnabled = scrollbar_x_stabilize
if window.ScrollbarX and not window.ScrollbarY then
window.ScrollbarY = (needed_size_from_last_frame.y > size_for_scrollbars_y - style.ScrollbarSize) and not (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) ~= 0)
end
window.ScrollbarSizes = ImVec2(window.ScrollbarY and style.ScrollbarSize or 0.0, window.ScrollbarX and style.ScrollbarSize or 0.0)
-- Amend the partially filled window.DecoOuterSizeX2 values.
window.DecoOuterSizeX2 = window.DecoOuterSizeX2 + window.ScrollbarSizes.x
window.DecoOuterSizeY2 = window.DecoOuterSizeY2 + window.ScrollbarSizes.y
end
local host_rect
if (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Popup) == 0 and not window_is_child_tooltip) then
host_rect = parent_window.ClipRect
else
host_rect = viewport_rect
end
local outer_rect = window:Rect()
local title_bar_rect = window:TitleBarRect()
ImRect_Copy(window.OuterRectClipped, outer_rect)
window.OuterRectClipped:ClipWith(host_rect)
window.InnerRect.Min.x = window.Pos.x + window.DecoOuterSizeX1
window.InnerRect.Min.y = window.Pos.y + window.DecoOuterSizeY1
window.InnerRect.Max.x = window.Pos.x + window.Size.x - window.DecoOuterSizeX2
window.InnerRect.Max.y = window.Pos.y + window.Size.y - window.DecoOuterSizeY2
local top_border_size = ((bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 or bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0) and style.FrameBorderSize or window.WindowBorderSize)
window.InnerClipRect.Min.x = ImFloor(0.5 + window.InnerRect.Min.x + window.WindowBorderSize * 0.5)
window.InnerClipRect.Min.y = ImFloor(0.5 + window.InnerRect.Min.y + top_border_size * 0.5)
window.InnerClipRect.Max.x = ImFloor(window.InnerRect.Max.x - window.WindowBorderSize * 0.5)
window.InnerClipRect.Max.y = ImFloor(window.InnerRect.Max.y - window.WindowBorderSize * 0.5)
window.InnerClipRect:ClipWithFull(host_rect)
--- Scrolling
-- Lock down maximum scrolling
-- The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
-- for right/bottom aligned items without creating a scrollbar.
window.ScrollMax.x = ImMax(0.0, window.ContentSize.x + window.WindowPadding.x * 2.0 - window.InnerRect:GetWidth())
window.ScrollMax.y = ImMax(0.0, window.ContentSize.y + window.WindowPadding.y * 2.0 - window.InnerRect:GetHeight())
-- Apply scrolling
ImVec2_Copy(window.Scroll, CalcNextScrollFromScrollTargetAndClamp(window))
ImVec2_CopyV(window.ScrollTarget, FLT_MAX, FLT_MAX)
window.DecoInnerSizeX1 = 0.0; window.DecoInnerSizeY1 = 0.0
IM_ASSERT(window.DrawList.CmdBuffer.Size == 1 and window.DrawList.CmdBuffer.Data[1].ElemCount == 0)
window.DrawList:PushTexture(g.Font.OwnerAtlas.TexRef)
ImGui.PushClipRect(host_rect.Min, host_rect.Max, false)
do
local render_decorations_in_parent = false
if (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0) and (bit32.band(flags, ImGuiWindowFlags.Popup) == 0) and not window_is_child_tooltip then
-- - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
-- - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
local previous_child
if parent_window.DC.ChildWindows.Size >= 2 then
previous_child = parent_window.DC.ChildWindows.Data[parent_window.DC.ChildWindows.Size - 1]
else
previous_child = nil
end
local previous_child_overlapping
if previous_child ~= nil then
previous_child_overlapping = previous_child:Rect():Overlaps(window:Rect())
else
previous_child_overlapping = false
end
local parent_is_empty = (parent_window.DrawList.VtxBuffer.Size == 0)
if (window.DrawList.CmdBuffer:back().ElemCount == 0 and not parent_is_empty and not previous_child_overlapping) then
render_decorations_in_parent = true
end
end
if render_decorations_in_parent then
window.DrawList = parent_window.DrawList
end
local title_bar_is_highlight = (g.NavWindow == window) -- TODO: proper cond, just simple highlight now
RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_col, resize_grip_draw_size)
if render_decorations_in_parent then
window.DrawList = window.DrawListInst
end
end
local allow_scrollbar_x = (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) == 0) and (bit32.band(flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0)
local allow_scrollbar_y = (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) == 0)
local work_rect_size_x
if window.ContentSizeExplicit.x ~= 0.0 then
work_rect_size_x = window.ContentSizeExplicit.x
else
local content_size_x = allow_scrollbar_x and (window.ContentSize and window.ContentSize.x or 0.0) or 0.0
local window_size_x = window.Size.x - window.WindowPadding.x * 2.0 - (window.DecoOuterSizeX1 + window.DecoOuterSizeX2)
work_rect_size_x = ImMax(content_size_x, window_size_x)
end
local work_rect_size_y
if window.ContentSizeExplicit.y ~= 0.0 then
work_rect_size_y = window.ContentSizeExplicit.y
else
local content_size_y = allow_scrollbar_y and (window.ContentSize and window.ContentSize.y or 0.0) or 0.0
local window_size_y = window.Size.y - window.WindowPadding.y * 2.0 - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2)
work_rect_size_y = ImMax(content_size_y, window_size_y)
end
window.WorkRect.Min.x = ImTrunc(window.InnerRect.Min.x - window.Scroll.x + ImMax(window.WindowPadding.x, window.WindowBorderSize))
window.WorkRect.Min.y = ImTrunc(window.InnerRect.Min.y - window.Scroll.y + ImMax(window.WindowPadding.y, window.WindowBorderSize))
window.WorkRect.Max.x = window.WorkRect.Min.x + work_rect_size_x
window.WorkRect.Max.y = window.WorkRect.Min.y + work_rect_size_y
window.ParentWorkRect = window.WorkRect
-- [LEGACY] Content Region
-- FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
-- Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
-- Used by:
-- - Mouse wheel scrolling + many other things
window.ContentRegionRect.Min.x = window.Pos.x - window.Scroll.x + window.WindowPadding.x + window.DecoOuterSizeX1
window.ContentRegionRect.Min.y = window.Pos.y - window.Scroll.y + window.WindowPadding.y + window.DecoOuterSizeY1
window.ContentRegionRect.Max.x = window.ContentRegionRect.Min.x + (window.ContentSizeExplicit.x ~= 0.0 and window.ContentSizeExplicit.x or (window.Size.x - window.WindowPadding.x * 2.0 - (window.DecoOuterSizeX1 + window.DecoOuterSizeX2)))
window.ContentRegionRect.Max.y = window.ContentRegionRect.Min.y + (window.ContentSizeExplicit.y ~= 0.0 and window.ContentSizeExplicit.y or (window.Size.y - window.WindowPadding.y * 2.0 - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2)))
-- Setup drawing context
-- (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window.DC.Indent.x = window.DecoOuterSizeX1 + window.WindowPadding.x - window.Scroll.x
window.DC.GroupOffset.x = 0.0
window.DC.ColumnsOffset.x = 0.0
-- Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
-- This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
local start_pos_highp_x = window.Pos.x + window.WindowPadding.x - window.Scroll.x + window.DecoOuterSizeX1 + window.DC.ColumnsOffset.x
local start_pos_highp_y = window.Pos.y + window.WindowPadding.y - window.Scroll.y + window.DecoOuterSizeY1
ImVec2_CopyV(window.DC.CursorStartPos, start_pos_highp_x, start_pos_highp_y)
ImVec2_CopyV(window.DC.CursorStartPosLossyness, start_pos_highp_x - window.DC.CursorStartPos.x, start_pos_highp_y - window.DC.CursorStartPos.y)
ImVec2_Copy(window.DC.CursorPos, window.DC.CursorStartPos)
ImVec2_Copy(window.DC.CursorPosPrevLine, window.DC.CursorPos)
ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorStartPos)
ImVec2_Copy(window.DC.IdealMaxPos, window.DC.CursorStartPos)
ImVec2_CopyV(window.DC.CurrLineSize, 0.0, 0.0)
ImVec2_CopyV(window.DC.PrevLineSize, 0.0, 0.0)
window.DC.CurrLineTextBaseOffset = 0.0
window.DC.PrevLineTextBaseOffset = 0.0
window.DC.IsSameLine = false
window.DC.IsSetPos = false
window.DC.NavLayerCurrent = ImGuiNavLayer.Main
window.DC.NavLayersActiveMask = window.DC.NavLayersActiveMaskNext
window.DC.NavLayersActiveMaskNext = 0x00
window.DC.NavIsScrollPushableX = true
window.DC.NavHideHighlightOneFrame = false
window.DC.NavWindowHasScrollY = window.ScrollMax.y > 0.0
window.DC.MenuBarAppending = false
window.DC.MenuColumns:Update(style.ItemSpacing.x, window_just_activated_by_user)
window.DC.TreeDepth = 0
window.DC.TreeHasStackDataDepthMask = 0x00
window.DC.TreeRecordsClippedNodesY2Mask = 0x00
window.DC.ChildWindows:resize(0)
window.DC.StateStorage = window.StateStorage
-- TODO: CurrentColumns
window.DC.LayoutType = ImGuiLayoutType.Vertical
window.DC.ParentLayoutType = (parent_window ~= nil) and parent_window.DC.LayoutType or ImGuiLayoutType.Vertical
-- Default item width. Make it proportional to window size if window can be manually resized.
-- (we cannot use AutoFitFramesX/AutoFitFramesY which is a temporary state)
local is_resizable_width
if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and not window.DockIsActive then
is_resizable_width = (window.Size.x > 0.0) and (bit32.band(window.ChildFlags, bit32.bor(ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AlwaysAutoResize)) == 0)
else
is_resizable_width = (window.Size.x > 0.0) and (bit32.band(flags, ImGuiWindowFlags.AlwaysAutoResize) == 0)
end
if is_resizable_width then
window.DC.ItemWidthDefault = ImTrunc(window.Size.x * 0.65)
else
window.DC.ItemWidthDefault = ImTrunc(g.FontSize * 16.0)
end
window.DC.ItemWidth = window.DC.ItemWidthDefault
window.DC.ItemWidthStack:resize(0)
window.DC.TextWrapPos = -1.0
window.DC.TextWrapPosStack:resize(0)
if window.AutoFitFramesX > 0 then
window.AutoFitFramesX = window.AutoFitFramesX - 1
end
if window.AutoFitFramesY > 0 then
window.AutoFitFramesY = window.AutoFitFramesY - 1
end
g.NextWindowData:ClearFlags()
if want_focus then
ImGui.FocusWindow(window, ImGuiFocusRequestFlags.UnlessBelowModal)
end
if want_focus and window == g.NavWindow then
ImGui.NavInitWindow(window, false)
end
if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 then
open = RenderWindowTitleBarContents(window, title_bar_rect, name, open)
end
if bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0 then
g.TooltipPreviousWindow = window
end
if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
window.BgClickFlags = parent_window.BgClickFlags
else
window.BgClickFlags = g.IO.ConfigWindowsMoveFromTitleBarOnly and ImGuiWindowBgClickFlags.None or ImGuiWindowBgClickFlags.Move
end
window.DC.WindowItemStatusFlags = ImGuiItemStatusFlags.None
if ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) then
window.DC.WindowItemStatusFlags = bit32.bor(window.DC.WindowItemStatusFlags, ImGuiItemStatusFlags.HoveredRect)
end
ImGui.SetLastItemDataForWindow(window, title_bar_rect)
else
if (window.SkipRefresh) then
SetWindowActiveForSkipRefresh(window)
end
ImGui.SetCurrentViewport(window, window.Viewport)
SetCurrentWindow(window)
g.NextWindowData:ClearFlags()
ImGui.SetLastItemDataForWindow(window, window:TitleBarRect())
end
if (not window.SkipRefresh) then
ImGui.PushClipRect(window.InnerClipRect.Min, window.InnerClipRect.Max, true)
end
window.WriteAccessed = false
window.BeginCount = window.BeginCount + 1
g.NextWindowData:ClearFlags()
if first_begin_of_the_frame and not window.SkipRefresh then
if (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0) and (bit32.band(flags, ImGuiWindowFlags.ChildMenu) == 0) then
-- Child window can be out of sight and have "negative" clip windows.
-- Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
IM_ASSERT((bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0))
local nav_request = (bit32.band(window.ChildFlags, ImGuiChildFlags.NavFlattened) ~= 0) and (g.NavAnyRequest and g.NavWindow and g.NavWindow.RootWindowForNav == window.RootWindowForNav)
if not g.LogEnabled and not nav_request then
if window.OuterRectClipped.Min.x >= window.OuterRectClipped.Max.x or window.OuterRectClipped.Min.y >= window.OuterRectClipped.Max.y then
if window.AutoFitFramesX > 0 or window.AutoFitFramesY > 0 then
window.HiddenFramesCannotSkipItems = 1
else
window.HiddenFramesCanSkipItems = 1
end
end
end
-- Hide along with parent or if parent is collapsed
if parent_window and (parent_window.Collapsed or parent_window.HiddenFramesCanSkipItems > 0) then
window.HiddenFramesCanSkipItems = 1
end
if parent_window and parent_window.HiddenFramesCannotSkipItems > 0 then
window.HiddenFramesCannotSkipItems = 1
end
end
if style.Alpha <= 0.0 then
window.HiddenFramesCanSkipItems = 1
end
local hidden_regular = (window.HiddenFramesCanSkipItems > 0) or (window.HiddenFramesCannotSkipItems > 0)
window.Hidden = hidden_regular or (window.HiddenFramesForRenderOnly > 0)
-- Disable inputs for requested number of frames
if window.DisableInputsFrames > 0 then
window.DisableInputsFrames = window.DisableInputsFrames - 1
window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.NoInputs)
end
-- Update the SkipItems flag, used to early out of all items functions (no layout required)
local skip_items = false
if window.Collapsed or not window.Active or hidden_regular then
if window.AutoFitFramesX <= 0 and window.AutoFitFramesY <= 0 and window.HiddenFramesCannotSkipItems <= 0 then
skip_items = true
end
end
window.SkipItems = skip_items
elseif first_begin_of_the_frame then
window.SkipItems = true
end
if open == nil then open = true end
return open, not window.SkipItems
end
function ImGui.End()
local g = GImGui
local window = g.CurrentWindow
if (g.CurrentWindowStack.Size <= 1 and g.WithinFrameScopeWithImplicitWindow) then
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!")
return
end
local window_stack_data = g.CurrentWindowStack:back()
if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then
IM_ASSERT_USER_ERROR(g.WithinEndPopupID == window.ID, "Must call EndPopup() and not End()!")
end
if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
IM_ASSERT_USER_ERROR(g.WithinEndChildID == window.ID, "Must call EndChild() and not End()!")
end
if not window.SkipRefresh then
ImGui.PopClipRect()
end
ImGui.PopFocusScope()
if window_stack_data.DisabledOverrideReenable and window.RootWindow == window then
ImGui.EndDisabledOverrideReenable()
end
if (window.SkipRefresh) then
IM_ASSERT(window.DrawList == nil)
window.DrawList = window.DrawListInst
end
-- Pop from window stack
ImGuiLastItemData_Copy(g.LastItemData, window_stack_data.ParentLastItemDataBackup)
if bit32.band(window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
g.BeginMenuDepth = g.BeginMenuDepth - 1
end
if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then
g.BeginPopupStack:pop_back()
end
g.CurrentWindowStack:pop_back()
-- LUA: No "Ternary Operator", since lua (... and (1) or (2)) will eval (1) and (2) no matter what
-- so something like `SetCurrentWindow((g.CurrentWindowStack.Size == 0) and nil or g.CurrentWindowStack:back().Window)` will error
if (g.CurrentWindowStack.Size == 0) then
SetCurrentWindow(nil)
else
SetCurrentWindow(g.CurrentWindowStack:back().Window)
end
if g.CurrentWindow then
ImGui.SetCurrentViewport(g.CurrentWindow, g.CurrentWindow.Viewport)
end
end
--- @param option ImGuiItemFlags
--- @param enabled bool
function ImGui.PushItemFlag(option, enabled)
local g = GImGui
local item_flags = g.CurrentItemFlags
IM_ASSERT(item_flags == g.ItemFlagsStack:back())
if enabled then
item_flags = bit32.bor(item_flags, option)
else
item_flags = bit32.band(item_flags, bit32.bnot(option))
end
g.CurrentItemFlags = item_flags
g.ItemFlagsStack:push_back(item_flags)
end
function ImGui.PopItemFlag()
local g = GImGui
IM_ASSERT_USER_ERROR_RET(g.ItemFlagsStack.Size > 1, "Calling PopItemFlag() too many times!")
g.ItemFlagsStack:pop_back()
g.CurrentItemFlags = g.ItemFlagsStack:back()
end
--- @param disabled? bool
function ImGui.BeginDisabled(disabled)
if disabled == nil then disabled = true end
local g = GImGui
local was_disabled = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0
if not was_disabled and disabled then
g.DisabledAlphaBackup = g.Style.Alpha
g.Style.Alpha = g.Style.Alpha * g.Style.DisabledAlpha
end
if was_disabled or disabled then
g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.Disabled)
end
g.ItemFlagsStack:push_back(g.CurrentItemFlags)
g.DisabledStackSize = g.DisabledStackSize + 1
end
function ImGui.EndDisabled()
local g = GImGui
IM_ASSERT_USER_ERROR_RET(g.DisabledStackSize > 0, "Calling EndDisabled() too many times!")
g.DisabledStackSize = g.DisabledStackSize - 1
local was_disabled = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0
g.ItemFlagsStack:pop_back()
g.CurrentItemFlags = g.ItemFlagsStack:back()
if was_disabled and bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) == 0 then
g.Style.Alpha = g.DisabledAlphaBackup
end
end
function ImGui.BeginDisabledOverrideReenable()
local g = GImGui
IM_ASSERT(bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0)
g.CurrentWindowStack.Data[g.CurrentWindowStack.Size].DisabledOverrideReenableAlphaBackup = g.Style.Alpha
g.Style.Alpha = g.DisabledAlphaBackup
g.CurrentItemFlags = bit32.band(g.CurrentItemFlags, bit32.bnot(ImGuiItemFlags.Disabled))
g.ItemFlagsStack:push_back(g.CurrentItemFlags)
g.DisabledStackSize = g.DisabledStackSize + 1
end
function ImGui.EndDisabledOverrideReenable()
local g = GImGui
IM_ASSERT(g.DisabledStackSize > 0)
g.DisabledStackSize = g.DisabledStackSize - 1
g.ItemFlagsStack:pop_back()
g.CurrentItemFlags = g.ItemFlagsStack:back()
g.Style.Alpha = g.CurrentWindowStack:back().DisabledOverrideReenableAlphaBackup
end
--- @param pos ImVec2
--- @param find_first_and_in_any_viewport bool
--- @return ImGuiWindow, ImGuiWindow?
local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport)
local g = GImGui
local hovered_window = nil
local hovered_window_under_moving_window = nil
-- Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
hovered_window = g.MovingWindow
local backup_moving_window_viewport = nil
if (find_first_and_in_any_viewport == false and g.MovingWindow) then
backup_moving_window_viewport = g.MovingWindow.Viewport
g.MovingWindow.Viewport = g.MouseViewport
if (bit32.band(g.MovingWindow.Flags, ImGuiWindowFlags.NoMouseInputs) == 0) then
hovered_window = g.MovingWindow
end
end
local padding_regular = g.Style.TouchExtraPadding
local padding_for_resize = ImMax(g.Style.TouchExtraPadding, ImVec2(g.Style.WindowBorderHoverPadding, g.Style.WindowBorderHoverPadding))
local window
local stop_6075 = false
for i = g.Windows.Size, 1, -1 do
repeat
window = g.Windows.Data[i]
if not window.WasActive or window.Hidden then
break
end
if bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) ~= 0 then
break
end
IM_ASSERT(window.Viewport)
if (window.Viewport ~= g.MouseViewport) then
break
end
local hit_padding
if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoResize, ImGuiWindowFlags.AlwaysAutoResize)) ~= 0 then
hit_padding = padding_regular
else
hit_padding = padding_for_resize
end
if not window.OuterRectClipped:ContainsWithPad(pos, hit_padding) then
break
end
if window.HitTestHoleSize.x ~= 0 then
-- TODO: hit test hole
end
if find_first_and_in_any_viewport then
hovered_window = window
stop_6075 = true; break
else
if hovered_window == nil then
hovered_window = window
end
if hovered_window_under_moving_window == nil and (not g.MovingWindow or window.RootWindowDockTree ~= g.MovingWindow.RootWindowDockTree) then
hovered_window_under_moving_window = window
end
if hovered_window and hovered_window_under_moving_window then
stop_6075 = true; break
end
end
until true
if stop_6075 then break end
end
if (find_first_and_in_any_viewport == false and g.MovingWindow) then
g.MovingWindow.Viewport = backup_moving_window_viewport
end
return hovered_window, hovered_window_under_moving_window
end
-- TODO:
function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos)
local g = GImGui
local io = g.IO
g.WindowsBorderHoverPadding = ImMax(ImMax(g.Style.TouchExtraPadding.x, g.Style.TouchExtraPadding.y), g.Style.WindowBorderHoverPadding)
local clear_hovered_windows = false
g.HoveredWindow, g.HoveredWindowUnderMovingWindow = FindHoveredWindowEx(mouse_pos, false)
IM_ASSERT(g.HoveredWindow == nil or g.HoveredWindow == g.MovingWindow or g.HoveredWindow.Viewport == g.MouseViewport)
g.HoveredWindowBeforeClear = g.HoveredWindow
local modal_window = ImGui.GetTopMostPopupModal()
if modal_window and g.HoveredWindow and not ImGui.IsWindowWithinBeginStackOf(g.HoveredWindow.RootWindow, modal_window) then
clear_hovered_windows = true
end
if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoMouse) ~= 0 then
clear_hovered_windows = true
end
local has_open_popup = (g.OpenPopupStack.Size > 0)
local has_open_modal = (modal_window ~= nil)
local mouse_earliest_down = -1
local mouse_any_down = false
for i = 0, 2 do -- IM_COUNTOF(io.MouseDown)
if io.MouseClicked[i] then
io.MouseDownOwned[i] = (g.HoveredWindow ~= nil) or has_open_popup
io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow ~= nil) or has_open_modal
end
mouse_any_down = mouse_any_down or io.MouseDown[i]
if (io.MouseDown[i] or io.MouseReleased[i]) then
if (mouse_earliest_down == -1 or (io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])) then
mouse_earliest_down = i
end
end
end
local mouse_avail = (mouse_earliest_down == -1) or io.MouseDownOwned[mouse_earliest_down]
local mouse_avail_unless_popup_close = (mouse_earliest_down == -1) or io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down]
local mouse_dragging_extern_payload = g.DragDropActive and bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceExtern) ~= 0
if not mouse_avail and not mouse_dragging_extern_payload then
clear_hovered_windows = true
end
if clear_hovered_windows then
g.HoveredWindow = nil
g.HoveredWindowUnderMovingWindow = nil
end
if (g.WantCaptureMouseNextFrame ~= -1) then
io.WantCaptureMouse = (g.WantCaptureMouseNextFrame ~= 0)
io.WantCaptureMouseUnlessPopupClose = io.WantCaptureMouse
else
io.WantCaptureMouse = (mouse_avail and (g.HoveredWindow ~= nil or mouse_any_down)) or has_open_popup
io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close and (g.HoveredWindow ~= nil or mouse_any_down)) or has_open_modal
end
io.WantCaptureKeyboard = false
if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) == 0 then
if (g.ActiveId ~= 0) or (modal_window ~= nil) then
io.WantCaptureKeyboard = true
elseif io.NavActive and bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 and io.ConfigNavCaptureKeyboard then
io.WantCaptureKeyboard = true
end
end
if g.WantCaptureKeyboardNextFrame ~= -1 then
io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame ~= 0)
end
io.WantTextInput = (g.WantTextInputNextFrame ~= -1) and (g.WantTextInputNextFrame ~= 0) or false
end
--- @param key ImGuiKey
--- @param v bool
--- @param analog_value float
function ImGui.UpdateAliasKey(key, v, analog_value)
IM_ASSERT(ImGui.IsAliasKey(key))
local key_data = ImGui.GetKeyData(nil, key)
key_data.Down = v
key_data.AnalogValue = analog_value
end
function ImGui.GetMergedModsFromKeys()
local g = GImGui
local mods = 0
if ImGui.GetKeyData(g, ImGuiMod_Ctrl).Down then mods = bit32.bor(mods, ImGuiMod_Ctrl) end
if ImGui.GetKeyData(g, ImGuiMod_Shift).Down then mods = bit32.bor(mods, ImGuiMod_Shift) end
if ImGui.GetKeyData(g, ImGuiMod_Alt).Down then mods = bit32.bor(mods, ImGuiMod_Alt) end
if ImGui.GetKeyData(g, ImGuiMod_Super).Down then mods = bit32.bor(mods, ImGuiMod_Super) end
return mods
end
function ImGui.UpdateKeyboardInputs()
local g = GImGui
local io = g.IO
if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) ~= 0 then
io:ClearInputKeys()
end
for n = 0, 2 do -- TODO: ImGuiMouseButton.COUNT - 1
ImGui.UpdateAliasKey(ImGui.MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] and 1.0 or 0.0)
end
ImGui.UpdateAliasKey(ImGuiKey.MouseWheelX, io.MouseWheelH ~= 0.0, io.MouseWheelH)
ImGui.UpdateAliasKey(ImGuiKey.MouseWheelY, io.MouseWheel ~= 0.0, io.MouseWheel)
-- Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values
local prev_key_mods = io.KeyMods
io.KeyMods = ImGui.GetMergedModsFromKeys()
io.KeyCtrl = bit32.band(io.KeyMods, ImGuiMod_Ctrl) ~= 0
io.KeyShift = bit32.band(io.KeyMods, ImGuiMod_Shift) ~= 0
io.KeyAlt = bit32.band(io.KeyMods, ImGuiMod_Alt) ~= 0
io.KeySuper = bit32.band(io.KeyMods, ImGuiMod_Super) ~= 0
if prev_key_mods ~= io.KeyMods then
g.LastKeyModsChangeTime = g.Time
end
if prev_key_mods ~= io.KeyMods and prev_key_mods == 0 then
g.LastKeyModsChangeFromNoneTime = g.Time
end
-- Clear gamepad data if disabled
if bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) == 0 then
for key = ImGuiKey_Gamepad_BEGIN, ImGuiKey_Gamepad_END - 1 do
io.KeysData[key - ImGuiKey.NamedKey_BEGIN].Down = false
io.KeysData[key - ImGuiKey.NamedKey_BEGIN].AnalogValue = 0.0
end
end
-- Update keys
for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do
local key_data = io.KeysData[key - ImGuiKey.NamedKey_BEGIN]
key_data.DownDurationPrev = key_data.DownDuration
if key_data.Down then
if key_data.DownDuration < 0.0 then
key_data.DownDuration = 0.0
else
key_data.DownDuration = key_data.DownDuration + io.DeltaTime
end
else
key_data.DownDuration = -1.0
end
if key_data.DownDuration == 0.0 then
if ImGui.IsKeyboardKey(key) then
g.LastKeyboardKeyPressTime = g.Time
elseif key == ImGuiKey.ReservedForModCtrl or key == ImGuiKey.ReservedForModShift or key == ImGuiKey.ReservedForModAlt or key == ImGuiKey.ReservedForModSuper then
g.LastKeyboardKeyPressTime = g.Time
end
end
end
-- Update keys/input owner (named keys only): one entry per key
for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do
local key_data = io.KeysData[key - ImGuiKey.NamedKey_BEGIN]
local owner_data = g.KeysOwnerData[key - ImGuiKey.NamedKey_BEGIN]
owner_data.OwnerCurr = owner_data.OwnerNext
if not key_data.Down then -- Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
owner_data.OwnerNext = ImGuiKeyOwner_NoOwner
end
owner_data.LockThisFrame = owner_data.LockUntilRelease and key_data.Down
owner_data.LockUntilRelease = owner_data.LockUntilRelease and key_data.Down -- Clear LockUntilRelease when key is not Down anymore
end
ImGui.UpdateKeyRoutingTable(g.KeysRoutingTable)
end
function ImGui.UpdateMouseInputs()
local g = GImGui
local io = g.IO
-- Mouse Wheel swapping flag
-- As a standard behavior holding Shift while using Vertical Mouse Wheel triggers Horizontal scroll instead
-- - We avoid doing it on OSX as it the OS input layer handles this already
io.MouseWheelRequestAxisSwap = io.KeyShift and not io.ConfigMacOSXBehaviors
-- Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (ImGui.IsMousePosValid(io.MousePos)) then
local x_val = ImFloor(io.MousePos.x)
local y_val = ImFloor(io.MousePos.y)
io.MousePos = ImVec2(x_val, y_val)
g.MouseLastValidPos = ImVec2(x_val, y_val)
end
-- If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
if (ImGui.IsMousePosValid(io.MousePos) and ImGui.IsMousePosValid(io.MousePosPrev)) then
io.MouseDelta = io.MousePos - io.MousePosPrev
else
io.MouseDelta = ImVec2(0.0, 0.0)
end
-- Update stationary timer
-- FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates
local mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource.Mouse) and 2.0 or 3.0
local mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold)
g.MouseStationaryTimer = mouse_stationary and (g.MouseStationaryTimer + io.DeltaTime) or 0.0
-- If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0 threshold but would need to reset in everywhere we set this to true.
if io.MouseDelta.x ~= 0.0 or io.MouseDelta.y ~= 0.0 then
g.NavHighlightItemUnderNav = false
end
for i = 0, 2 do -- IM_COUNTOF(io.MouseDown)
io.MouseClicked[i] = io.MouseDown[i] and (io.MouseDownDuration[i] < 0.0)
io.MouseClickedCount[i] = 0 -- Will be filled below
io.MouseReleased[i] = not io.MouseDown[i] and (io.MouseDownDuration[i] >= 0.0)
if (io.MouseReleased[i]) then
io.MouseReleasedTime[i] = g.Time
end
io.MouseDownDurationPrev[i] = io.MouseDownDuration[i]
if io.MouseDown[i] then
if io.MouseDownDuration[i] < 0.0 then
io.MouseDownDuration[i] = 0.0
else
io.MouseDownDuration[i] = io.MouseDownDuration[i] + io.DeltaTime
end
else
io.MouseDownDuration[i] = -1.0
end
if io.MouseClicked[i] then
local is_repeated_click = false
if (g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime then
local delta_from_click_pos
if ImGui.IsMousePosValid(io.MousePos) then
delta_from_click_pos = io.MousePos - io.MouseClickedPos[i]
else
delta_from_click_pos = ImVec2(0.0, 0.0)
end
if ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist then
is_repeated_click = true
end
end
if is_repeated_click then
io.MouseClickedLastCount[i] = io.MouseClickedLastCount[i] + 1
else
io.MouseClickedLastCount[i] = 1
end
io.MouseClickedTime[i] = g.Time
io.MouseClickedPos[i] = io.MousePos
io.MouseClickedCount[i] = io.MouseClickedLastCount[i]
ImVec2_Copy(io.MouseDragMaxDistanceAbs[i], ImVec2(0.0, 0.0))
io.MouseDragMaxDistanceSqr[i] = 0.0
elseif io.MouseDown[i] then
-- Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
local delta_from_click_pos
if ImGui.IsMousePosValid(io.MousePos) then
delta_from_click_pos = (io.MousePos - io.MouseClickedPos[i])
else
delta_from_click_pos = ImVec2(0.0, 0.0)
end
io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos))
io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, (delta_from_click_pos.x < 0.0) and -delta_from_click_pos.x or delta_from_click_pos.x)
io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, (delta_from_click_pos.y < 0.0) and -delta_from_click_pos.y or delta_from_click_pos.y)
end
io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2)
if (io.MouseClicked[i]) then
g.NavHighlightItemUnderNav = false
end
end
end
--- @param window? ImGuiWindow
--- @param wheel_amount float
local function LockWheelingWindow(window, wheel_amount)
local g = GImGui
if window then
g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER)
else
g.WheelingWindowReleaseTimer = 0.0
end
if (g.WheelingWindow == window) then
return
end
-- IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL")
g.WheelingWindow = window
ImVec2_Copy(g.WheelingWindowRefMousePos, g.IO.MousePos)
if window == nil then
g.WheelingWindowStartFrame = -1
g.WheelingAxisAvg = ImVec2(0.0, 0.0)
end
end
--- @param wheel ImVec2
--- @return ImGuiWindow?
local function FindBestWheelingWindow(wheel)
local g = GImGui
local windows = {nil, nil}
for axis = ImGuiAxis.X, ImGuiAxis.Y do
if wheel[axis] ~= 0.0 then
windows[axis] = g.HoveredWindow
local window = g.HoveredWindow
while bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 do
local has_scrolling = (window.ScrollMax[axis] ~= 0.0)
local inputs_disabled = (bit32.band(window.Flags, ImGuiWindowFlags.NoScrollWithMouse) ~= 0) and not (bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) ~= 0)
if has_scrolling and not inputs_disabled then
break -- select this window
end
windows[axis] = window.ParentWindow
window = window.ParentWindow
end
end
end
if windows[1] == nil and windows[2] == nil then
return nil
end
if (windows[1] == windows[2] or windows[1] == nil or windows[2] == nil) then
return windows[2] and windows[2] or windows[1]
end
if (g.WheelingWindowStartFrame == -1) then
g.WheelingWindowStartFrame = g.FrameCount
end
if ((g.WheelingWindowStartFrame == g.FrameCount and wheel.x ~= 0.0 and wheel.y ~= 0.0) or (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y)) then
ImVec2_Copy(g.WheelingWindowWheelRemainder, wheel)
return nil
end
return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) and windows[1] or windows[2]
end
function ImGui.UpdateMouseWheel()
local g = GImGui
if g.WheelingWindow ~= nil then
g.WheelingWindowReleaseTimer = g.WheelingWindowReleaseTimer - g.IO.DeltaTime
if ImGui.IsMousePosValid() and ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold then
g.WheelingWindowReleaseTimer = 0.0
end
if g.WheelingWindowReleaseTimer <= 0.0 then
LockWheelingWindow(nil, 0.0)
end
end
local mouse_window = g.WheelingWindow and g.WheelingWindow or g.HoveredWindow
if not mouse_window or mouse_window.Collapsed then
return
end
local owner_id = mouse_window.ID
local wheel = ImVec2()
wheel.x = ImGui.TestKeyOwner(ImGuiKey.MouseWheelX, owner_id) and g.IO.MouseWheelH or 0.0
wheel.y = ImGui.TestKeyOwner(ImGuiKey.MouseWheelY, owner_id) and g.IO.MouseWheel or 0.0
if g.WheelingWindow ~= nil then
ImGui.SetKeyOwner(ImGuiKey.MouseWheelX, owner_id)
ImGui.SetKeyOwner(ImGuiKey.MouseWheelY, owner_id)
end
-- Zoom / Scale window
-- FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned
if wheel.y ~= 0.0 and g.IO.KeyCtrl and g.IO.FontAllowUserScaling then
LockWheelingWindow(mouse_window, wheel.y)
local window = mouse_window
local new_font_scale = ImClamp(window.FontWindowScale + g.IO.MouseWheel * 0.10, 0.50, 2.50)
local scale = new_font_scale / window.FontWindowScale
window.FontWindowScale = new_font_scale
if window == window.RootWindow then
local offset = window.Size * (1.0 - scale) * (g.IO.MousePos - window.Pos) / window.Size
ImGui.SetWindowPos(window, window.Pos + offset, 0)
-- MarkIniSettingsDirty(window)
end
return
end
if g.IO.KeyCtrl then
return
end
-- Mouse wheel scrolling
if (g.IO.MouseWheelRequestAxisSwap) then
wheel = ImVec2(wheel.y, 0.0)
end
-- Maintain a rough average of moving magnitude on both axes
-- FIXME: should by based on wall clock time rather than frame-counter
g.WheelingAxisAvg.x = ImStd.ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30)
g.WheelingAxisAvg.y = ImStd.ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30)
-- In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now
wheel = wheel + g.WheelingWindowWheelRemainder
g.WheelingWindowWheelRemainder = ImVec2(0.0, 0.0)
if (wheel.x == 0.0 and wheel.y == 0.0) then
return
end
-- Mouse wheel scrolling: find target and apply
-- - don't renew lock if axis doesn't apply on the window.
-- - select a main axis when both axes are being moved.
local window
if g.WheelingWindow then
window = g.WheelingWindow
else
window = FindBestWheelingWindow(wheel)
end
if window then
if not (bit32.band(window.Flags, ImGuiWindowFlags.NoScrollWithMouse) ~= 0) and not (bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) ~= 0) then
local do_scroll = { wheel.x ~= 0.0 and window.ScrollMax.x ~= 0.0, wheel.y ~= 0.0 and window.ScrollMax.y ~= 0.0 }
if do_scroll[ImGuiAxis.X] and do_scroll[ImGuiAxis.Y] then
do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) and ImGuiAxis.Y or ImGuiAxis.X] = false
end
if do_scroll[ImGuiAxis.X] then
LockWheelingWindow(window, wheel.x)
local max_step = window.InnerRect:GetWidth() * 0.67
local scroll_step = ImTrunc(ImMin(2 * window.FontRefSize, max_step))
ImGui.SetScrollX(window, window.Scroll.x - wheel.x * scroll_step)
g.WheelingWindowScrolledFrame = g.FrameCount
end
if do_scroll[ImGuiAxis.Y] then
LockWheelingWindow(window, wheel.y)
local max_step = window.InnerRect:GetHeight() * 0.67
local scroll_step = ImTrunc(ImMin(5 * window.FontRefSize, max_step))
ImGui.SetScrollY(window, window.Scroll.y - wheel.y * scroll_step)
g.WheelingWindowScrolledFrame = g.FrameCount
end
end
end
end
local function SetupDrawListSharedData()
local g = GImGui
local virtual_space = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX)
for _, viewport in g.Viewports:iter() do
virtual_space:Add(viewport:GetMainRect())
end
g.DrawListSharedData.ClipRectFullscreen = virtual_space:ToVec4()
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol
g.DrawListSharedData:SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError)
g.DrawListSharedData.InitialFlags = ImDrawListFlags.None
if g.Style.AntiAliasedLines then
g.DrawListSharedData.InitialFlags = bit32.bor(g.DrawListSharedData.InitialFlags, ImDrawListFlags.AntiAliasedLines)
end
if g.Style.AntiAliasedLinesUseTex and not bit32.band(g.IO.Fonts.Flags, ImFontAtlasFlags.NoBakedLines) then
g.DrawListSharedData.InitialFlags = bit32.bor(g.DrawListSharedData.InitialFlags, ImDrawListFlags.AntiAliasedLinesUseTex)
end
if g.Style.AntiAliasedFill then
g.DrawListSharedData.InitialFlags = bit32.bor(g.DrawListSharedData.InitialFlags, ImDrawListFlags.AntiAliasedFill)
end
if bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasVtxOffset) then
g.DrawListSharedData.InitialFlags = bit32.bor(g.DrawListSharedData.InitialFlags, ImDrawListFlags.AllowVtxOffset)
end
g.DrawListSharedData.InitialFringeScale = 1.0
end
--- @param viewport ImGuiViewportP
local function InitViewportDrawData(viewport)
local g = GImGui
local draw_data = viewport.DrawDataP
viewport.DrawData = draw_data
viewport.DrawDataBuilder.Layers[1] = draw_data.CmdLists
viewport.DrawDataBuilder.Layers[2] = viewport.DrawDataBuilder.LayerData1
viewport.DrawDataBuilder.Layers[1]:resize(0)
viewport.DrawDataBuilder.Layers[2]:resize(0)
-- When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
-- and to allow applications/backends to easily skip rendering.
-- FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
-- This is because the work has been done already, and its wasted! We should fix that and add optimizations for
-- it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
local is_minimized = bit32.band(viewport.Flags, ImGuiViewportFlags.IsMinimized) ~= 0
draw_data.Valid = true
draw_data.FrameCount = g.FrameCount
draw_data.TotalVtxCount = 0
draw_data.TotalIdxCount = 0
draw_data.DisplayPos = viewport.Pos
if is_minimized then
draw_data.DisplaySize = ImVec2(0.0, 0.0)
else
ImVec2_Copy(draw_data.DisplaySize, viewport.Size)
end
if viewport.FramebufferScale.x ~= 0.0 then
draw_data.FramebufferScale = viewport.FramebufferScale
else
draw_data.FramebufferScale = g.IO.DisplayFramebufferScale
end
draw_data.OwnerViewport = viewport
draw_data.Textures = g.PlatformIO.Textures
end
-- FIXME-DPI:
function ImGui.GetScale()
local g = GImGui
return g.Style._MainScale
end
--- @return ImGuiWindow
function ImGui.GetCurrentWindowRead()
local g = GImGui
return g.CurrentWindow
end
--- @return ImGuiWindow
function ImGui.GetCurrentWindow()
local g = GImGui
g.CurrentWindow.WriteAccessed = true
return g.CurrentWindow
end
--- @param clip_rect_min ImVec2
--- @param clip_rect_max ImVec2
--- @param intersect_with_current_clip_rect? bool
function ImGui.PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect)
local window = ImGui.GetCurrentWindow()
window.DrawList:PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect)
ImRect_CopyFromV4(window.ClipRect, window.DrawList._ClipRectStack:back())
end
function ImGui.PopClipRect()
local window = ImGui.GetCurrentWindow()
window.DrawList:PopClipRect()
ImRect_CopyFromV4(window.ClipRect, window.DrawList._ClipRectStack:back())
end
--- @param viewport ImGuiViewportP
--- @param drawlist_no size_t # background(1), foreground(2)
--- @param drawlist_name string
--- @return ImDrawList
local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name)
local g = GImGui
IM_ASSERT(drawlist_no <= 2) -- IM_COUNTOF(viewport->BgFgDrawLists)
local draw_list = viewport.BgFgDrawLists[drawlist_no]
if draw_list == nil then
draw_list = ImDrawList(g.DrawListSharedData)
draw_list._OwnerName = drawlist_name
viewport.BgFgDrawLists[drawlist_no] = draw_list
end
if viewport.BgFgDrawListsLastTimeActive[drawlist_no] ~= g.Time then
draw_list:_ResetForNewFrame()
draw_list:PushTexture(g.IO.Fonts.TexRef)
draw_list:PushClipRect(viewport.Pos, viewport.Pos + viewport.Size, false)
viewport.BgFgDrawListsLastTimeActive[drawlist_no] = g.Time
end
return draw_list
end
--- @param viewport? ImGuiViewport
function ImGui.GetBackgroundDrawList(viewport)
local g = GImGui
if (viewport == nil) then
viewport = g.CurrentWindow.Viewport
end
--- @cast viewport ImGuiViewportP
return GetViewportBgFgDrawList(viewport, 1, "##Background")
end
--- @param viewport? ImGuiViewport
function ImGui.GetForegroundDrawList(viewport)
local g = GImGui
if (viewport == nil) then
viewport = g.CurrentWindow.Viewport
end
--- @cast viewport ImGuiViewportP
return GetViewportBgFgDrawList(viewport, 2, "##Foreground")
end
-- FIXME: Add a more explicit sort order in the window structure
--- @param lhs ImGuiWindow
--- @param rhs ImGuiWindow
local function ChildWindowComparer(lhs, rhs)
local a, b = lhs, rhs
local d = (bit32.band(a.Flags, ImGuiWindowFlags.Popup) ~= 0 and 1 or 0) - (bit32.band(b.Flags, ImGuiWindowFlags.Popup) ~= 0 and 1 or 0)
if d ~= 0 then
return (d < 0)
end
d = (bit32.band(a.Flags, ImGuiWindowFlags.Tooltip) ~= 0 and 1 or 0) - (bit32.band(b.Flags, ImGuiWindowFlags.Tooltip) ~= 0 and 1 or 0)
if d ~= 0 then
return (d < 0)
end
return (a.BeginOrderWithinParent - b.BeginOrderWithinParent < 0)
end
--- @param out_sorted_windows ImVector<ImGuiWindow>
--- @param window ImGuiWindow
local function AddWindowToSortBuffer(out_sorted_windows, window)
out_sorted_windows:push_back(window)
if window.Active then
local count = window.DC.ChildWindows.Size
ImStd.ImQsort(window.DC.ChildWindows.Data, count, ChildWindowComparer)
for i = 1, count do
local child = window.DC.ChildWindows[i]
if child.Active then
AddWindowToSortBuffer(out_sorted_windows, child)
end
end
end
end
local function AddWindowToDrawData(window, layer)
local g = GImGui
local viewport = window.Viewport
g.IO.MetricsRenderWindows = g.IO.MetricsRenderWindows + 1
-- TODO: splitter
ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[layer], window.DrawList)
for _, child in window.DC.ChildWindows:iter() do
if (ImGui.IsWindowActiveAndVisible(child)) then -- Clipped children may have been marked not active
AddWindowToDrawData(child, layer)
end
end
end
--- @param window ImGuiWindow
local function GetWindowDisplayLayer(window)
return (bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0) and 2 or 1
end
--- @param window ImGuiWindow
local function AddRootWindowToDrawData(window)
AddWindowToDrawData(window, GetWindowDisplayLayer(window))
end
--- @param builder ImDrawDataBuilder
local function FlattenDrawDataIntoSingleLayer(builder)
local n = builder.Layers[1].Size
local full_size = n
for i = 2, #builder.Layers do
full_size = full_size + builder.Layers[i].Size
end
builder.Layers[1]:resize(full_size)
for layer_n = 2, #builder.Layers do
local layer = builder.Layers[layer_n]
if not layer:empty() then
for i = 1, layer.Size do
builder.Layers[1].Data[n + i] = layer.Data[i]
end
n = n + layer.Size
layer:resize(0)
end
end
end
function ImGui.NewFrame()
IM_ASSERT(GImGui ~= nil, "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?")
local g = GImGui
g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame
g.ConfigFlagsCurrFrame = g.IO.ConfigFlags
g.Time = g.Time + g.IO.DeltaTime
g.FrameCount = g.FrameCount + 1
g.TooltipOverrideCount = 0
g.WindowsActiveCount = 0
g.MenusIdSubmittedThisFrame:resize(0)
-- FIXME: are lines below correct and necessary
g.FramerateSecPerFrameAccum = g.FramerateSecPerFrameAccum + (g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx])
g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % 60
g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, 60)
if g.FramerateSecPerFrameAccum > 0 then
g.IO.Framerate = (1.0 / (g.FramerateSecPerFrameAccum / g.FramerateSecPerFrameCount))
else
g.IO.Framerate = FLT_MAX
end
ImGui.UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue)
ImGui.UpdateViewportsNewFrame()
ImGui.UpdateTexturesNewFrame()
SetupDrawListSharedData()
ImGui.UpdateFontsNewFrame()
g.WithinFrameScope = true
-- Mark rendering data as invalid to prevent user who may have a handle on it to use it.
for _, viewport in g.Viewports:iter() do
viewport.DrawData = nil
viewport.DrawDataP.Valid = false
end
if g.DragDropActive and g.DragDropPayload.SourceId == g.ActiveId then
ImGui.KeepAliveID(g.DragDropPayload.SourceId)
end
if not g.IO.ConfigDebugHighlightIdConflicts or not g.IO.KeyCtrl then
g.DebugDrawIdConflictsId = 0
end
if g.IO.ConfigDebugHighlightIdConflicts and g.HoveredIdPreviousFrameItemCount > 1 then
g.DebugDrawIdConflictsId = g.HoveredIdPreviousFrame
end
-- Update HoveredId data
if not g.HoveredIdPreviousFrame then
g.HoveredIdTimer = 0.0
end
if not g.HoveredIdPreviousFrame or (g.HoveredId and g.ActiveId == g.HoveredId) then
g.HoveredIdNotActiveTimer = 0.0
end
if g.HoveredId then
g.HoveredIdTimer = g.HoveredIdTimer + g.IO.DeltaTime
end
if g.HoveredId and g.ActiveId ~= g.HoveredId then
g.HoveredIdNotActiveTimer = g.HoveredIdNotActiveTimer + g.IO.DeltaTime
end
g.HoveredIdPreviousFrame = g.HoveredId
g.HoveredIdPreviousFrameItemCount = 0
g.HoveredId = 0
g.HoveredIdAllowOverlap = false
g.HoveredIdIsDisabled = false
if (g.ActiveId ~= 0 and g.ActiveIdIsAlive ~= g.ActiveId and g.ActiveIdPreviousFrame == g.ActiveId) then
IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() 0x%08X because it isn't marked alive anymore!", g.ActiveId)
ImGui.ClearActiveID()
end
-- Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
if g.ActiveId then
g.ActiveIdTimer = g.ActiveIdTimer + g.IO.DeltaTime
end
if g.ActiveId and g.ActiveId == g.LastActiveId then
g.LastActiveIdWasSelected = g.ActiveIdWasSelected
g.LastActiveIdWasSoleSelected = g.ActiveIdWasSoleSelected
end
g.LastActiveIdTimer = g.LastActiveIdTimer + g.IO.DeltaTime
g.ActiveIdPreviousFrame = g.ActiveId
g.ActiveIdIsAlive = 0
g.AnyIdHasBeenEditedThisFrame = false
g.ActiveIdHasBeenEditedThisFrame = false
g.ActiveIdIsJustActivated = false
if g.TempInputId ~= 0 and g.ActiveId ~= g.TempInputId then
g.TempInputId = 0
end
if g.InputTextReactivateId ~= 0 and g.InputTextReactivateId ~= g.DeactivatedItemData.ID then
g.InputTextReactivateId = 0
end
if g.ActiveId == 0 then
g.ActiveIdUsingNavDirMask = 0x00
g.ActiveIdUsingAllKeyboardKeys = false
end
if g.DeactivatedItemData.ElapseFrame < g.FrameCount then
g.DeactivatedItemData.ID = 0
end
g.DeactivatedItemData.IsAlive = false
if g.InputTextDeactivatedState.ElapseFrame < g.FrameCount then
g.InputTextDeactivatedState.ID = 0
end
-- Record when we have been stationary as this state is preserved while over same item.
-- FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
-- To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
if g.HoverItemDelayId ~= 0 and g.MouseStationaryTimer >= g.Style.HoverStationaryDelay then
g.HoverItemUnlockedStationaryId = g.HoverItemDelayId
elseif g.HoverItemDelayId == 0 then
g.HoverItemUnlockedStationaryId = 0
end
if g.HoveredWindow ~= nil and g.MouseStationaryTimer >= g.Style.HoverStationaryDelay then
g.HoverWindowUnlockedStationaryId = g.HoveredWindow.ID
elseif g.HoveredWindow == nil then
g.HoverWindowUnlockedStationaryId = 0
end
-- Update hover delay for IsItemHovered() with delays and tooltips
g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId
if g.HoverItemDelayId ~= 0 then
g.HoverItemDelayTimer = g.HoverItemDelayTimer + g.IO.DeltaTime
g.HoverItemDelayClearTimer = 0.0
g.HoverItemDelayId = 0
elseif g.HoverItemDelayTimer > 0.0 then
-- This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
-- We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
g.HoverItemDelayClearTimer = g.HoverItemDelayClearTimer + g.IO.DeltaTime
if g.HoverItemDelayClearTimer >= ImMax(0.25, g.IO.DeltaTime * 2.0) then -- ~7 frames at 30 Hz + allow for low framerate
g.HoverItemDelayTimer = 0.0
g.HoverItemDelayClearTimer = 0.0 -- May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
end
end
ImGui.UpdateKeyboardInputs()
g.TooltipPreviousWindow = nil
ImGui.NavUpdate()
ImGui.UpdateMouseInputs()
IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size)
local gc_all = g.GcCompactAll or g.IO.ConfigMemoryCompactTimer < 0.0
local memory_compact_start_time = gc_all and FLT_MAX or (g.Time - g.IO.ConfigMemoryCompactTimer)
for _, window in g.Windows:iter() do
window.WasActive = window.Active
window.Active = false
window.WriteAccessed = false
window.BeginCountPreviousFrame = window.BeginCount
window.BeginCount = 0
if (not window.WasActive or gc_all) and not window.MemoryCompacted and window.LastTimeActive < memory_compact_start_time then
ImGui.GcCompactTransientWindowBuffers(window)
end
end
ImGui.UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos)
ImGui.UpdateMouseMovingWindowNewFrame()
g.MouseCursor = ImGuiMouseCursor.Arrow
g.WantCaptureMouseNextFrame = -1
g.WantCaptureKeyboardNextFrame = -1
g.WantTextInputNextFrame = -1
-- Platform IME data: reset for the frame
ImGuiPlatformImeData_Copy(g.PlatformImeDataPrev, g.PlatformImeData)
g.PlatformImeData.WantVisible = false
g.PlatformImeData.WantTextInput = false
ImGui.UpdateMouseWheel()
if g.GcCompactAll then
ImGui.GcCompactTransientMiscBuffers()
end
g.GcCompactAll = false
if (g.NavWindow and not g.NavWindow.WasActive) then
ImGui.FocusTopMostWindowUnderOne(nil, nil, nil, ImGuiFocusRequestFlags.RestoreFocusedChild)
end
g.CurrentWindowStack:resize(0)
g.BeginPopupStack:resize(0)
g.ItemFlagsStack:resize(0)
g.ItemFlagsStack:push_back(ImGuiItemFlags.Default_)
g.CurrentItemFlags = g.ItemFlagsStack:back()
g.GroupStack:resize(0)
g.WithinFrameScopeWithImplicitWindow = true
ImGui.SetNextWindowSize(ImVec2(400, 400), ImGuiCond.FirstUseEver)
ImGui.Begin("Debug##Default")
IM_ASSERT(g.CurrentWindow.IsFallbackWindow == true)
end
function ImGui.EndFrame()
local g = GImGui
IM_ASSERT(g.Initialized)
if g.FrameCountEnded == g.FrameCount then
return
end
IM_ASSERT_USER_ERROR(g.WithinFrameScope, "Forgot to call ImGui::NewFrame()?")
-- Notify Platform when our Input Method Editor cursor has moved
local ime_data = g.PlatformImeData
if g.PlatformIO.Platform_SetImeDataFn ~= nil and not ImGuiPlatformImeData_Compare(ime_data, g.PlatformImeDataPrev) then
local viewport = ImGui.FindViewportByID(ime_data.ViewportId)
if viewport == nil then
viewport = ImGui.GetMainViewport()
end
-- IMGUI_DEBUG_LOG_IO("[io] Calling Platform_SetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f) for Viewport 0x%08X", ime_data.WantVisible, ime_data.InputPos.x, ime_data.InputPos.y, viewport.ID)
g.PlatformIO.Platform_SetImeDataFn(g, viewport, ime_data)
end
g.WantTextInputNextFrame = ime_data.WantTextInput
g.WithinFrameScopeWithImplicitWindow = false
if (g.CurrentWindow and g.CurrentWindow.IsFallbackWindow and g.CurrentWindow.WriteAccessed == false) then
g.CurrentWindow.Active = false
end
ImGui.End()
ImGui.SetCurrentViewport(nil, nil)
-- Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
-- If you want to handle source item disappearing: instead of submitting your description tooltip
-- in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
-- (e.g. end of your item loop, or before EndFrame) by reading payload data.
-- In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
if g.DragDropActive and g.DragDropSourceFrameCount + 1 < g.FrameCount and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoPreviewTooltip) == 0) then
g.DragDropWithinSource = true
ImGui.SetTooltip("...")
g.DragDropWithinSource = false
end
g.WithinFrameScope = false
g.FrameCountEnded = g.FrameCount
ImGui.UpdateFontsEndFrame()
ImGui.UpdateMouseMovingWindowEndFrame()
ImGui.UpdateViewportsEndFrame()
g.WindowsTempSortBuffer:resize(0)
g.WindowsTempSortBuffer:reserve(g.Windows.Size)
for _, window in g.Windows:iter() do
repeat
if window.Active and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then -- if a child is active its parent will add it
break
end
AddWindowToSortBuffer(g.WindowsTempSortBuffer, window)
until true
end
IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size)
g.Windows:swap(g.WindowsTempSortBuffer)
g.IO.MetricsActiveWindows = g.WindowsActiveCount
ImGui.UpdateTexturesEndFrame()
for _, atlas in g.FontAtlases:iter() do
atlas.Locked = false
end
ImVec2_Copy(g.IO.MousePosPrev, g.IO.MousePos)
g.IO.AppFocusLost = false
g.IO.MouseWheel = 0.0
g.IO.MouseWheelH = 0.0
g.IO.InputQueueCharacters:resize(0)
end
-- TODO:
function ImGui.Render()
local g = GImGui
IM_ASSERT(g.Initialized)
if g.FrameCountEnded ~= g.FrameCount then
ImGui.EndFrame()
end
if g.FrameCountRendered == g.FrameCount then return end
g.FrameCountRendered = g.FrameCount
g.IO.MetricsRenderWindows = 0
for _, viewport in g.Viewports:iter() do
InitViewportDrawData(viewport)
if viewport.BgFgDrawLists[1] ~= nil and viewport.BgFgDrawListsLastTimeActive[1] == g.Time then
ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[1], ImGui.GetBackgroundDrawList(viewport))
end
end
-- TODO: RenderDimmedBackgrounds()
local windows_to_render_top_most = {nil, nil}
windows_to_render_top_most[1] = (g.NavWindowingTarget and (bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0)) and g.NavWindowingTarget.RootWindowDockTree or nil
windows_to_render_top_most[2] = g.NavWindowingTarget and g.NavWindowingListWindow or nil
for _, window in g.Windows:iter() do
if ImGui.IsWindowActiveAndVisible(window) and (bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0) and window ~= windows_to_render_top_most[1] and window ~= windows_to_render_top_most[2] then
AddRootWindowToDrawData(window)
end
end
for n = 1, 2 do
if windows_to_render_top_most[n] and ImGui.IsWindowActiveAndVisible(windows_to_render_top_most[n]) then -- NavWindowingTarget is always temporarily displayed as the top-most window
AddRootWindowToDrawData(windows_to_render_top_most[n])
end
end
-- Draw software mouse cursor if requested by io.MouseDrawCursor flag
if g.IO.MouseDrawCursor and g.MouseCursor ~= ImGuiMouseCursor.None then
ImGui.RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48))
end
g.IO.MetricsRenderVertices = 0
g.IO.MetricsRenderIndices = 0
for _, viewport in g.Viewports:iter() do
FlattenDrawDataIntoSingleLayer(viewport.DrawDataBuilder)
if viewport.BgFgDrawLists[2] ~= nil and viewport.BgFgDrawListsLastTimeActive[2] == g.Time then
ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[1], ImGui.GetForegroundDrawList(viewport))
end
local draw_data = viewport.DrawDataP
for _, draw_list in draw_data.CmdLists:iter() do
draw_list:_PopUnusedDrawCmd()
end
g.IO.MetricsRenderVertices = g.IO.MetricsRenderVertices + draw_data.TotalVtxCount
g.IO.MetricsRenderIndices = g.IO.MetricsRenderIndices + draw_data.TotalIdxCount
end
end
--- @param text ImString
--- @param text_end? int # Exclusive upper bound
--- @param hide_text_after_double_hash? bool
--- @param wrap_width? float
--- @return ImVec2
function ImGui.CalcTextSize(text, text_end, hide_text_after_double_hash, wrap_width)
return ImGui.CalcTextSizeEx(text, 1, text_end, hide_text_after_double_hash, wrap_width)
end
--- @param text ImString
--- @param text_begin int
--- @param text_end? int # Exclusive upper bound
--- @param hide_text_after_double_hash? bool
--- @param wrap_width? float
--- @return ImVec2
function ImGui.CalcTextSizeEx(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
local g = GImGui
local text_display_end
if hide_text_after_double_hash then
text_display_end = ImGui.FindRenderedTextEnd(text, text_end)
else
text_display_end = text_end
end
local font = g.Font
local font_size = g.FontSize
if text == "" or (text_end and text_end <= text_begin) then
return ImVec2(0.0, font_size)
end
local text_size = font:CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_begin, text_display_end, nil)
text_size.x = ImCeilFast(text_size.x)
return text_size
end
function ImGui.GetDrawData()
local g = GImGui
local viewport = g.Viewports[1]
return viewport.DrawDataP.Valid and viewport.DrawDataP or nil
end
function ImGui.GetTime()
return GImGui.Time
end
function ImGui.Shutdown()
local g = GImGui
IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == nil, "Forgot to shutdown Platform backend?")
IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == nil, "Forgot to shutdown Renderer backend?")
for _, viewport in g.Viewports:iter() do
-- IM_UNUSED(viewport)
IM_ASSERT_USER_ERROR(viewport.RendererUserData == nil and viewport.PlatformUserData == nil and viewport.PlatformHandle == nil, "Backend or app forgot to call DestroyPlatformWindows()?")
end
for _, atlas in g.FontAtlases:iter() do
ImGui.UnregisterFontAtlas(atlas)
if atlas.OwnerContext == g then
IM_ASSERT(atlas.RefCount == 0, "Destroying context owning a ImFontAtlas which is still used elsewhere!")
if atlas.RefCount == 0 then
atlas.Locked = false
end
end
end
g.DrawListSharedData.TempBuffer:clear()
if not g.Initialized then
return
end
-- TODO:
g.MenusIdSubmittedThisFrame:clear()
end
--- @return string?
function ImGui.GetClipboardText()
local g = GImGui
return g.PlatformIO.Platform_GetClipboardTextFn and g.PlatformIO.Platform_GetClipboardTextFn(g) or nil
end
--- @param text string
function ImGui.SetClipboardText(text)
local g = GImGui
if g.PlatformIO.Platform_SetClipboardTextFn ~= nil then
g.PlatformIO.Platform_SetClipboardTextFn(g, text)
end
end
function ImGui.GetIO() return GImGui.IO end
--- @return ImGuiPlatformIO
function ImGui.GetPlatformIO()
IM_ASSERT(GImGui ~= nil, "No current context. Did you call ImGui.CreateContext() and ImGui.SetCurrentContext()?")
return GImGui.PlatformIO
end
function ImGui.GetMouseCursor()
local g = GImGui
return g.MouseCursor
end
--- @param cursor_type ImGuiMouseCursor
function ImGui.SetMouseCursor(cursor_type)
local g = GImGui
g.MouseCursor = cursor_type
end
--- @param col_a ImU32
--- @param col_b ImU32
--- @return ImU32
function ImStd.ImAlphaBlendColors(col_a, col_b)
local t = bit32.band(bit32.rshift(col_b, IM_COL32_A_SHIFT), 0xFF) / 255.0
local r = ImLerp(bit32.band(bit32.rshift(col_a, IM_COL32_R_SHIFT), 0xFF), bit32.band(bit32.rshift(col_b, IM_COL32_R_SHIFT), 0xFF), t)
local g = ImLerp(bit32.band(bit32.rshift(col_a, IM_COL32_G_SHIFT), 0xFF), bit32.band(bit32.rshift(col_b, IM_COL32_G_SHIFT), 0xFF), t)
local b = ImLerp(bit32.band(bit32.rshift(col_a, IM_COL32_B_SHIFT), 0xFF), bit32.band(bit32.rshift(col_b, IM_COL32_B_SHIFT), 0xFF), t)
return IM_COL32(r, g, b, 0xFF)
end
--- @param in_col ImU32
--- @param out_col ImVec4?
--- @return ImVec4?
function ImGui.ColorConvertU32ToFloat4(in_col, out_col)
local s = 1.0 / 255.0
local r = bit32.band(bit32.rshift(in_col, IM_COL32_R_SHIFT), 0xFF) * s
local g = bit32.band(bit32.rshift(in_col, IM_COL32_G_SHIFT), 0xFF) * s
local b = bit32.band(bit32.rshift(in_col, IM_COL32_B_SHIFT), 0xFF) * s
local a = bit32.band(bit32.rshift(in_col, IM_COL32_A_SHIFT), 0xFF) * s
if out_col then
out_col[1] = r; out_col[2] = g; out_col[3] = b; out_col[4] = a
else
return ImVec4(r, g, b, a)
end
end
--- @param in_col ImVec4
--- @return ImU32
function ImGui.ColorConvertFloat4ToU32(in_col)
local out_col = 0
out_col = bit32.bor(out_col, bit32.lshift(IM_F32_TO_INT8_SAT(in_col.x), IM_COL32_R_SHIFT))
out_col = bit32.bor(out_col, bit32.lshift(IM_F32_TO_INT8_SAT(in_col.y), IM_COL32_G_SHIFT))
out_col = bit32.bor(out_col, bit32.lshift(IM_F32_TO_INT8_SAT(in_col.z), IM_COL32_B_SHIFT))
out_col = bit32.bor(out_col, bit32.lshift(IM_F32_TO_INT8_SAT(in_col.w), IM_COL32_A_SHIFT))
return out_col
end
--- @param r float
--- @param g float
--- @param b float
--- @return float, float, float
function ImGui.ColorConvertRGBtoHSV(r, g, b)
local K = 0.0
if g < b then
g, b = b, g
K = -1.0
end
if r < g then
r, g = g, r
K = -2.0 / 6.0 - K
end
local chroma = r - (g < b and g or b)
local out_h = ImFabs(K + (g - b) / (6.0 * chroma + 1e-20))
local out_s = chroma / (r + 1e-20)
local out_v = r
return out_h, out_s, out_v
end
--- @param h float
--- @param s float
--- @param v float
--- @return float, float, float
function ImGui.ColorConvertHSVtoRGB(h, s, v)
if s == 0.0 then
-- gray
return v, v, v
end
h = ImFmod(h, 1.0) / (60.0 / 360.0)
local i = math.floor(h)
local f = h - i
local p = v * (1.0 - s)
local q = v * (1.0 - s * f)
local t = v * (1.0 - s * (1.0 - f))
if i == 0 then
return v, t, p
elseif i == 1 then
return q, v, p
elseif i == 2 then
return p, v, t
elseif i == 3 then
return p, q, v
elseif i == 4 then
return t, p, v
else -- i == 5 or default
return v, p, q
end
end
--- @param clip_rect ImRect
--- @param pos ImVec2
--- @param items_height float
function ImGui.CalcClipRectVisibleItemsY(clip_rect, pos, items_height)
local visible_start = ImMax(ImTrunc((clip_rect.Min.y - pos.y) / items_height), 0)
local visible_end = ImMax(ImTrunc(ImCeil((clip_rect.Max.y - pos.y) / items_height)), visible_start)
return visible_start + 1, visible_end + 1
end
---------------------------------------------------------------------------------------
-- [SECTION] STYLING
---------------------------------------------------------------------------------------
function ImGui.GetStyle()
IM_ASSERT(GImGui ~= nil, "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?")
return GImGui.Style
end
do
local c = ImVec4()
--- @param col ImGuiCol|ImVec4|ImU32
--- @param alpha_mul? float
--- @param col_is_u32? bool # must be truthy if `col` is `ImU32`
--- @return ImU32
function ImGui.GetColorU32(col, alpha_mul, col_is_u32)
if alpha_mul == nil then alpha_mul = 1.0 end
local style = GImGui.Style
if not col_is_u32 then
--- @cast col ImVec4|ImGuiCol
if type(col) == "number" then
ImVec4_Copy(c, style.Colors[col])
c.w = c.w * style.Alpha * alpha_mul
else --- @cast col ImVec4
ImVec4_Copy(c, col)
c.w = c.w * style.Alpha
end
return ImGui.ColorConvertFloat4ToU32(c)
else
--- @cast col ImU32
alpha_mul = alpha_mul * style.Alpha
if alpha_mul >= 1.0 then
return col
end
local a = bit32.rshift(bit32.band(col, IM_COL32_A_MASK), IM_COL32_A_SHIFT)
a = math.floor(a * alpha_mul) -- We don't need to clamp 0..255 because alpha is in 0..1 range.
return bit32.bor(bit32.band(col, bit32.bnot(IM_COL32_A_MASK)), bit32.lshift(a, IM_COL32_A_SHIFT))
end
end
end
--- @param idx ImGuiCol
--- @param col ImU32|ImVec4
function ImGui.PushStyleColor(idx, col)
local g = GImGui
local backup = ImGuiColorMod(idx, g.Style.Colors[idx])
g.ColorStack:push_back(backup)
if g.DebugFlashStyleColorIdx ~= idx then
if type(col) == "number" then
ImGui.ColorConvertU32ToFloat4(col, g.Style.Colors[idx])
else --- @cast col ImVec4
ImVec4_Copy(g.Style.Colors[idx], col)
end
end
end
--- @param count? int
function ImGui.PopStyleColor(count)
if count == nil then count = 1 end
local g = GImGui
if g.ColorStack.Size < count then
IM_ASSERT_USER_ERROR(false, "Calling PopStyleColor() too many times!")
count = g.ColorStack.Size
end
while count > 0 do
local backup = g.ColorStack:back()
ImVec4_Copy(g.Style.Colors[backup.Col], backup.BackupValue)
g.ColorStack:pop_back()
count = count - 1
end
end
local GStyleVarsInfo = {
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "Alpha"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DisabledAlpha"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowPadding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowBorderSize"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowMinSize"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowTitleAlign"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildBorderSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupBorderSize"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "FramePadding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameBorderSize"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemSpacing"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemInnerSpacing"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "IndentSpacing"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "CellPadding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarPadding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabMinSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageBorderSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBorderSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthBase"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthShrink"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarBorderSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarOverlineSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TableAngledHeadersAngle"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "TableAngledHeadersTextAlign"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "MenuItemRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SelectableRounding"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DragDropTargetRounding"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ButtonTextAlign"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SelectableTextAlign"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorSize"),
ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorTextBorderSize"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextAlign"),
ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding")
}
--- @param idx ImGuiStyleVar
--- @return ImGuiStyleVarInfo
function ImGui.GetStyleVarInfo(idx)
IM_ASSERT(idx >= 0 and idx < ImGuiStyleVar.COUNT)
-- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT)
return GStyleVarsInfo[idx + 1]
end
--- @param idx ImGuiStyleVar
--- @param val float|ImVec2
function ImGui.PushStyleVar(idx, val)
local g = GImGui
local var_info = ImGui.GetStyleVarInfo(idx)
if type(val) == "number" then
IM_ASSERT_USER_ERROR_RET(var_info.DataType == ImGuiDataType.Float and var_info.Count == 1, "Calling PushStyleVar() with wrong type!")
else -- ImVec2
IM_ASSERT_USER_ERROR_RET(var_info.DataType == ImGuiDataType.Float and var_info.Count == 2, "Calling PushStyleVar() with wrong type!")
end
local var = g.Style[var_info.Key]
g.StyleVarStack:push_back(ImGuiStyleMod(idx, var))
g.Style[var_info.Key] = val
end
--- @param idx ImGuiStyleVar
--- @param val_x float
function ImGui.PushStyleVarX(idx, val_x)
local g = GImGui
local var_info = ImGui.GetStyleVarInfo(idx)
IM_ASSERT_USER_ERROR_RET(var_info.DataType == ImGuiDataType.Float and var_info.Count == 2, "Calling PushStyleVarX() with wrong type!")
local pvar = g.Style[var_info.Key]
g.StyleVarStack:push_back(ImGuiStyleMod(idx, pvar))
pvar.x = val_x
end
--- @param idx ImGuiStyleVar
--- @param val_y float
function ImGui.PushStyleVarY(idx, val_y)
local g = GImGui
local var_info = ImGui.GetStyleVarInfo(idx)
IM_ASSERT_USER_ERROR_RET(var_info.DataType == ImGuiDataType.Float and var_info.Count == 2, "Calling PushStyleVarY() with wrong type!")
local pvar = g.Style[var_info.Key]
g.StyleVarStack:push_back(ImGuiStyleMod(idx, pvar))
pvar.y = val_y
end
--- @param count? int
function ImGui.PopStyleVar(count)
if count == nil then count = 1 end
local g = GImGui
if g.StyleVarStack.Size < count then
IM_ASSERT_USER_ERROR(0, "Calling PopStyleVar() too many times!")
count = g.StyleVarStack.Size
end
while count > 0 do
local backup = g.StyleVarStack:back()
local var_info = ImGui.GetStyleVarInfo(backup.VarIdx)
local data = g.Style[var_info.Key]
if (var_info.DataType == ImGuiDataType.Float and var_info.Count == 1) then
g.Style[var_info.Key] = backup.BackupVal[1]
elseif (var_info.DataType == ImGuiDataType.Float and var_info.Count == 2) then
data.x = backup.BackupVal[1]; data.y = backup.BackupVal[2]
end
g.StyleVarStack:pop_back()
count = count - 1
end
end
--- @param wrap_local_pos_x float
function ImGui.PushTextWrapPos(wrap_local_pos_x) -- ATTENTION: THIS IS IN LEGACY LOCAL SPACE.
local g = GImGui
local window = g.CurrentWindow
window.DC.TextWrapPosStack:push_back(window.DC.TextWrapPos)
window.DC.TextWrapPos = wrap_local_pos_x
end
function ImGui.PopTextWrapPos()
local g = GImGui
local window = g.CurrentWindow
IM_ASSERT_USER_ERROR_RET(window.DC.TextWrapPosStack.Size > 0, "Calling PopTextWrapPos() too many times!")
window.DC.TextWrapPos = window.DC.TextWrapPosStack:back()
window.DC.TextWrapPosStack:pop_back()
end
--- @param window ImGuiWindow
--- @param popup_hierarchy bool
--- @param dock_hierarchy bool
local function GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy)
local last_window = nil
while last_window ~= window do
last_window = window
window = window.RootWindow
if popup_hierarchy then
window = window.RootWindowPopupTree
end
if dock_hierarchy then
window = window.RootWindowDockTree
end
end
return window
end
--- @param window ImGuiWindow
--- @param potential_parent ImGuiWindow
--- @param popup_hierarchy bool
--- @param dock_hierarchy bool
function ImGui.IsWindowChildOf(window, potential_parent, popup_hierarchy, dock_hierarchy)
local window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy)
if window_root == potential_parent then
return true
end
while window ~= nil do
if window == potential_parent then
return true
end
if window == window_root then -- end of chain
return false
end
window = window.ParentWindow
end
return false
end
--- @param window ImGuiWindow
function ImGui.IsWindowInBeginStack(window)
local g = GImGui
for n = g.CurrentWindowStack.Size, 1, -1 do
if g.CurrentWindowStack.Data[n].Window == window then
return true
end
end
return false
end
--- @param window ImGuiWindow
--- @param potential_parent ImGuiWindow
function ImGui.IsWindowWithinBeginStackOf(window, potential_parent)
if window.RootWindow == potential_parent then
return true
end
while window ~= nil do
if window == potential_parent then
return true
end
window = window.ParentWindowInBeginStack
end
return false
end
--- @param potential_above ImGuiWindow
--- @param potential_below ImGuiWindow
--- @return bool
function ImGui.IsWindowAbove(potential_above, potential_below)
local g = GImGui
-- It would be saner to ensure that display layer is always reflected in the g.Windows order, which would likely requires altering all manipulations of that array
local display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below)
if display_layer_delta ~= 0 then
return display_layer_delta > 0
end
for i = g.Windows.Size, 1, -1 do
local candidate_window = g.Windows.Data[i]
if candidate_window == potential_above then
return true
end
if candidate_window == potential_below then
return false
end
end
return false
end
--- @param window ImGuiWindow
--- @param scale float
local function ScaleWindow(window, scale)
local origin = window.Viewport.Pos
ImVec2_Copy(window.Pos, ImFloor((window.Pos - origin) * scale + origin))
ImVec2_Copy(window.Size, ImTrunc(window.Size * scale))
ImVec2_Copy(window.SizeFull, ImTrunc(window.SizeFull * scale))
ImVec2_Copy(window.ContentSize, ImTrunc(window.ContentSize * scale))
end
--- @param viewport ImGuiViewportP
--- @param scale float
function ImGui.ScaleWindowsInViewport(viewport, scale)
local g = GImGui
-- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X", viewport.ID)
if viewport.Window then
ScaleWindow(viewport.Window, scale)
else
for _, window in g.Windows:iter() do
if window.Viewport == viewport then
ScaleWindow(window, scale)
end
end
end
end
---------------------------------------------------------------------------------------
-- [SECTION] SCROLLING
---------------------------------------------------------------------------------------
--- @param target float
--- @param snap_min float
--- @param snap_max float
--- @param snap_threshold float
--- @param center_ratio float
local function CalcScrollEdgeSnap(target, snap_min, snap_max, snap_threshold, center_ratio)
if target <= snap_min + snap_threshold then
return ImLerp(snap_min, target, center_ratio)
end
if target >= snap_max - snap_threshold then
return ImLerp(target, snap_max, center_ratio)
end
return target
end
--- @param window ImGuiWindow
function CalcNextScrollFromScrollTargetAndClamp(window)
local scroll = ImVec2()
ImVec2_Copy(scroll, window.Scroll)
local decoration_size = ImVec2(window.DecoOuterSizeX1 + window.DecoInnerSizeX1 + window.DecoOuterSizeX2, window.DecoOuterSizeY1 + window.DecoInnerSizeY1 + window.DecoOuterSizeY2)
for axis = ImGuiAxis.X, ImGuiAxis.Y do
if window.ScrollTarget[axis] < FLT_MAX then
local center_ratio = window.ScrollTargetCenterRatio[axis]
local scroll_target = window.ScrollTarget[axis]
if window.ScrollTargetEdgeSnapDist[axis] > 0.0 then
local snap_min = 0.0
local snap_max = window.ScrollMax[axis] + window.SizeFull[axis] - decoration_size[axis]
scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window.ScrollTargetEdgeSnapDist[axis], center_ratio)
end
scroll[axis] = scroll_target - center_ratio * (window.SizeFull[axis] - decoration_size[axis])
end
scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0))
if not window.Collapsed and not window.SkipItems then
scroll[axis] = ImMin(scroll[axis], window.ScrollMax[axis])
end
end
return scroll
end
--- @param window ImGuiWindow
--- @param item_rect ImRect
--- @param flags? ImGuiScrollFlags
function ImGui.ScrollToRectEx(window, item_rect, flags)
if flags == nil then flags = 0 end
local g = GImGui
local scroll_rect = ImRect(window.InnerRect.Min - ImVec2(1, 1), window.InnerRect.Max + ImVec2(1, 1))
scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window.DecoInnerSizeX1, scroll_rect.Max.x)
scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window.DecoInnerSizeY1, scroll_rect.Max.y)
IM_ASSERT(bit32.band(flags, ImGuiScrollFlags.MaskX_) == 0 or ImIsPowerOfTwo(bit32.band(flags, ImGuiScrollFlags.MaskX_)))
IM_ASSERT(bit32.band(flags, ImGuiScrollFlags.MaskY_) == 0 or ImIsPowerOfTwo(bit32.band(flags, ImGuiScrollFlags.MaskY_)))
local in_flags = flags
if bit32.band(flags, ImGuiScrollFlags.MaskX_) == 0 and window.ScrollbarX then
flags = bit32.bor(flags, ImGuiScrollFlags.KeepVisibleEdgeX)
end
if bit32.band(flags, ImGuiScrollFlags.MaskY_) == 0 then
flags = bit32.bor(flags, window.Appearing and ImGuiScrollFlags.AlwaysCenterY or ImGuiScrollFlags.KeepVisibleEdgeY)
end
local fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x and item_rect.Max.x <= scroll_rect.Max.x
local fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y and item_rect.Max.y <= scroll_rect.Max.y
local can_be_fully_visible_x = (item_rect:GetWidth() + g.Style.ItemSpacing.x * 2.0) <= scroll_rect:GetWidth() or (window.AutoFitFramesX > 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0
local can_be_fully_visible_y = (item_rect:GetHeight() + g.Style.ItemSpacing.y * 2.0) <= scroll_rect:GetHeight() or (window.AutoFitFramesY > 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0
if bit32.band(flags, ImGuiScrollFlags.KeepVisibleEdgeX) ~= 0 and not fully_visible_x then
if item_rect.Min.x < scroll_rect.Min.x or not can_be_fully_visible_x then
ImGui.SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window.Pos.x, 0.0)
elseif item_rect.Max.x >= scroll_rect.Max.x then
ImGui.SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window.Pos.x, 1.0)
end
elseif (bit32.band(flags, ImGuiScrollFlags.KeepVisibleCenterX) ~= 0 and not fully_visible_x) or bit32.band(flags, ImGuiScrollFlags.AlwaysCenterX) ~= 0 then
if can_be_fully_visible_x then
ImGui.SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5) - window.Pos.x, 0.5)
else
ImGui.SetScrollFromPosX(window, item_rect.Min.x - window.Pos.x, 0.0)
end
end
if bit32.band(flags, ImGuiScrollFlags.KeepVisibleEdgeY) ~= 0 and not fully_visible_y then
if item_rect.Min.y < scroll_rect.Min.y or not can_be_fully_visible_y then
ImGui.SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window.Pos.y, 0.0)
elseif item_rect.Max.y >= scroll_rect.Max.y then
ImGui.SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window.Pos.y, 1.0)
end
elseif (bit32.band(flags, ImGuiScrollFlags.KeepVisibleCenterY) ~= 0 and not fully_visible_y) or bit32.band(flags, ImGuiScrollFlags.AlwaysCenterY) ~= 0 then
if can_be_fully_visible_y then
ImGui.SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5) - window.Pos.y, 0.5)
else
ImGui.SetScrollFromPosY(window, item_rect.Min.y - window.Pos.y, 0.0)
end
end
local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window)
local delta_scroll = next_scroll - window.Scroll
if bit32.band(flags, ImGuiScrollFlags.NoScrollParent) == 0 and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
if bit32.band(in_flags, bit32.bor(ImGuiScrollFlags.AlwaysCenterX, ImGuiScrollFlags.KeepVisibleCenterX)) ~= 0 then
in_flags = bit32.bor(bit32.band(in_flags, bit32.bnot(ImGuiScrollFlags.MaskX_)), ImGuiScrollFlags.KeepVisibleEdgeX)
end
if bit32.band(in_flags, bit32.bor(ImGuiScrollFlags.AlwaysCenterY, ImGuiScrollFlags.KeepVisibleCenterY)) ~= 0 then
in_flags = bit32.bor(bit32.band(in_flags, bit32.bnot(ImGuiScrollFlags.MaskY_)), ImGuiScrollFlags.KeepVisibleEdgeY)
end
local parent_delta = ImGui.ScrollToRectEx(window.ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags)
delta_scroll = delta_scroll + parent_delta
end
return delta_scroll
end
--- @return float
function ImGui.GetScrollMaxY()
local window = GImGui.CurrentWindow
return window.ScrollMax.y
end
--- @param window ImGuiWindow
--- @param scroll_x float
function ImGui.SetScrollX(window, scroll_x)
window.ScrollTarget.x = scroll_x
window.ScrollTargetCenterRatio.x = 0.0
window.ScrollTargetEdgeSnapDist.x = 0.0
end
--- @param window ImGuiWindow
--- @param scroll_y float
function ImGui.SetScrollY(window, scroll_y)
window.ScrollTarget.y = scroll_y
window.ScrollTargetCenterRatio.y = 0.0
window.ScrollTargetEdgeSnapDist.y = 0.0
end
--- @param window ImGuiWindow
--- @param local_x float
--- @param center_x_ratio float
function ImGui.SetScrollFromPosX(window, local_x, center_x_ratio)
IM_ASSERT(center_x_ratio >= 0.0 and center_x_ratio <= 1.0)
window.ScrollTarget.x = IM_TRUNC(local_x - window.DecoOuterSizeX1 - window.DecoInnerSizeX1 + window.Scroll.x)
window.ScrollTargetCenterRatio.x = center_x_ratio
window.ScrollTargetEdgeSnapDist.x = 0.0
end
--- @param window ImGuiWindow
--- @param local_y float
--- @param center_y_ratio float
function ImGui.SetScrollFromPosY(window, local_y, center_y_ratio)
IM_ASSERT(center_y_ratio >= 0.0 and center_y_ratio <= 1.0)
window.ScrollTarget.y = IM_TRUNC(local_y - window.DecoOuterSizeY1 - window.DecoInnerSizeY1 + window.Scroll.y)
window.ScrollTargetCenterRatio.y = center_y_ratio
window.ScrollTargetEdgeSnapDist.y = 0.0
end
---------------------------------------------------------------------------------------
-- [SECTION] TOOLTIPS
---------------------------------------------------------------------------------------
--- @param tooltip_flags ImGuiTooltipFlags
--- @param extra_window_flags ImGuiWindowFlags
function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags)
local g = GImGui
local is_dragdrop_tooltip = g.DragDropWithinSource or g.DragDropWithinTarget
if is_dragdrop_tooltip then
local is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource.TouchScreen)
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) == 0 then
local tooltip_pos
if is_touchscreen then
tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_TOUCH * g.Style.MouseCursorScale
else
tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET_MOUSE * g.Style.MouseCursorScale
end
local tooltip_pivot = is_touchscreen and TOOLTIP_DEFAULT_PIVOT_TOUCH or ImVec2(0.0, 0.0)
ImGui.SetNextWindowPos(tooltip_pos, ImGuiCond.None, tooltip_pivot)
end
local bg_alpha = g.Style.Colors[ImGuiCol.PopupBg].w * 0.60
ImGui.SetNextWindowBgAlpha(bg_alpha)
tooltip_flags = bit32.bor(tooltip_flags, ImGuiTooltipFlags.OverridePrevious)
end
if (bit32.band(tooltip_flags, ImGuiTooltipFlags.OverridePrevious) ~= 0) and g.TooltipPreviousWindow ~= nil and g.TooltipPreviousWindow.Active and not ImGui.IsWindowInBeginStack(g.TooltipPreviousWindow) then
-- IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name)
ImGui.SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow)
g.TooltipOverrideCount = g.TooltipOverrideCount + 1
end
local window_name_template = is_dragdrop_tooltip and "##Tooltip_DragDrop_%02d" or "##Tooltip_%02d"
local window_name = ImFormatString(window_name_template, g.TooltipOverrideCount)
local flags = bit32.bor(ImGuiWindowFlags.Tooltip, ImGuiWindowFlags.NoInputs, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.AlwaysAutoResize)
ImGui.Begin(window_name, nil, bit32.bor(flags, extra_window_flags))
return true
end
function ImGui.BeginTooltip()
return ImGui.BeginTooltipEx(ImGuiTooltipFlags.None, ImGuiWindowFlags.None)
end
function ImGui.BeginItemTooltip()
if not ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip) then
return false
end
return ImGui.BeginTooltipEx(ImGuiTooltipFlags.None, ImGuiWindowFlags.None)
end
function ImGui.EndTooltip()
IM_ASSERT(bit32.band(ImGui.GetCurrentWindowRead().Flags, ImGuiWindowFlags.Tooltip) ~= 0) -- Mismatched BeginTooltip()/EndTooltip() calls
ImGui.End()
end
--- @param fmt string
--- @param ... any
function ImGui.SetTooltip(fmt, ...)
if not ImGui.BeginTooltipEx(ImGuiTooltipFlags.OverridePrevious, ImGuiWindowFlags.None) then
return
end
ImGui.TextV(fmt, ...)
ImGui.EndTooltip()
end
--- @param fmt string
--- @param ... any
function ImGui.SetItemTooltip(fmt, ...)
if ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip) then
ImGui.SetTooltip(fmt, ...)
end
end
---------------------------------------------------------------------------------------
-- [SECTION] POPUPS
---------------------------------------------------------------------------------------
--- @param window? ImGuiWindow
function ImGui.FindBlockingModal(window)
local g = GImGui
if g.OpenPopupStack.Size <= 0 then
return nil
end
for i = 1, g.OpenPopupStack.Size do
repeat
local popup_data = g.OpenPopupStack.Data[i]
local popup_window = popup_data.Window
if popup_window == nil or bit32.band(popup_window.Flags, ImGuiWindowFlags.Modal) == 0 then
break
end
if not popup_window.Active and not popup_window.WasActive then
break
end
if window == nil then
return popup_window
end
if ImGui.IsWindowWithinBeginStackOf(window, popup_window) then
break
end
do return popup_window end
until true
end
return nil
end
--- @param id ImGuiID|string
--- @param popup_flags? ImGuiPopupFlags
function ImGui.OpenPopup(id, popup_flags)
if popup_flags == nil then popup_flags = 0 end
if type(id) == "number" then
return ImGui.OpenPopupEx(id, popup_flags)
else --- @cast id string
local g = GImGui
local _id = g.CurrentWindow:GetID(id)
IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)", id, _id)
return ImGui.OpenPopupEx(_id, popup_flags)
end
end
--- @param id ImGuiID
--- @param popup_flags ImGuiPopupFlags
function ImGui.OpenPopupEx(id, popup_flags)
local g = GImGui
local parent_window = g.CurrentWindow
local current_stack_size = g.BeginPopupStack.Size
if bit32.band(popup_flags, ImGuiPopupFlags.NoOpenOverExistingPopup) ~= 0 then
if ImGui.IsPopupOpen(0, ImGuiPopupFlags.AnyPopupId) then
return false
end
end
local popup_ref = ImGuiPopupData()
popup_ref.PopupId = id
popup_ref.Window = nil
popup_ref.RestoreNavWindow = g.NavWindow -- When popup closes focus may be restored to NavWindow (depend on window type).
popup_ref.OpenFrameCount = g.FrameCount
popup_ref.OpenParentId = parent_window.IDStack:back()
ImVec2_Copy(popup_ref.OpenPopupPos, ImGui.NavCalcPreferredRefPos(ImGuiWindowFlags.Popup))
if ImGui.IsMousePosValid(g.IO.MousePos) then
ImVec2_Copy(popup_ref.OpenMousePos, g.IO.MousePos)
else
ImVec2_Copy(popup_ref.OpenMousePos, popup_ref.OpenPopupPos)
end
-- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)", id)
if g.OpenPopupStack.Size < current_stack_size + 1 then
g.OpenPopupStack:push_back(popup_ref)
return true
else
-- Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
-- However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
-- in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
-- Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags.NoReopen is not specified.
local keep_existing = false
if g.OpenPopupStack.Data[current_stack_size + 1].PopupId == id then
if (g.OpenPopupStack.Data[current_stack_size + 1].OpenFrameCount == g.FrameCount - 1) or (bit32.band(popup_flags, ImGuiPopupFlags.NoReopen) ~= 0) then
keep_existing = true
end
end
if keep_existing then
-- No reopen
g.OpenPopupStack.Data[current_stack_size + 1].OpenFrameCount = popup_ref.OpenFrameCount
else
-- Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
ImGui.ClosePopupToLevel(current_stack_size, true)
g.OpenPopupStack:push_back(popup_ref)
end
-- When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
-- This is equivalent to what ClosePopupToLevel() does.
-- if (g.OpenPopupStack[current_stack_size + 1].PopupId == id)
-- FocusWindow(parent_window);
return not keep_existing
end
end
-- When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
-- This function closes any popups that are over 'ref_window'.
--- @param ref_window? ImGuiWindow
--- @param restore_focus_to_window_under_popup bool
function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_popup)
local g = GImGui
if g.OpenPopupStack.Size == 0 then
return
end
-- Don't close our own child popup windows.
-- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d", ref_window and ref_window.Name or "<NULL>", restore_focus_to_window_under_popup)
local popup_count_to_keep = 0
if ref_window then
-- Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
local ref_window_is_descendent_of_popup
local stop_8041 = false
while popup_count_to_keep < g.OpenPopupStack.Size do
repeat
local popup = g.OpenPopupStack.Data[popup_count_to_keep + 1]
if not popup.Window then
break
end
IM_ASSERT(bit32.band(popup.Window.Flags, ImGuiWindowFlags.Popup) ~= 0)
-- Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
-- - Clicking/Focusing Window2 won't close Popup1:
-- Window -> Popup1 -> Window2(Ref)
-- - Clicking/focusing Popup1 will close Popup2 and Popup3:
-- Window -> Popup1(Ref) -> Popup2 -> Popup3
-- - Each popups may contain child windows, which is why we compare ->RootWindow!
-- Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
-- We step through every popup from bottom to top to validate their position relative to reference window.
ref_window_is_descendent_of_popup = false
for n = popup_count_to_keep, g.OpenPopupStack.Size - 1 do
local popup_window = g.OpenPopupStack.Data[n + 1].Window
if popup_window and ImGui.IsWindowWithinBeginStackOf(ref_window, popup_window) then
ref_window_is_descendent_of_popup = true
break
end
end
if not ref_window_is_descendent_of_popup then
stop_8041 = true; break
end
until true
if stop_8041 then break end
popup_count_to_keep = popup_count_to_keep + 1
end
end
if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below
-- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")", ref_window and ref_window.Name or "<NULL>")
ImGui.ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup)
end
end
--- @param remaining int # 0-based
--- @param restore_focus_to_window_under_popup bool
function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup)
local g = GImGui
-- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d", remaining, restore_focus_to_window_under_popup)
IM_ASSERT(remaining >= 0 and remaining < g.OpenPopupStack.Size)
-- if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then
-- for n = remaining + 1, g.OpenPopupStack.Size do
-- local popup = g.OpenPopupStack.Data[n]
-- IMGUI_DEBUG_LOG_POPUP("[popup] - Closing PopupID 0x%08X Window \"%s\"", popup.PopupId, popup.Window and popup.Window.Name or nil)
-- end
-- end
-- Trim open popup stack
-- FIXME: is it safer to full copy here?
local prev_popup = g.OpenPopupStack.Data[remaining + 1]
g.OpenPopupStack:resize(remaining)
-- Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
if restore_focus_to_window_under_popup and prev_popup.Window then
local popup_window = prev_popup.Window
local focus_window
if bit32.band(popup_window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
focus_window = popup_window.ParentWindow
else
focus_window = prev_popup.RestoreNavWindow
end
if focus_window and not focus_window.WasActive then
ImGui.FocusTopMostWindowUnderOne(popup_window, nil, nil, ImGuiFocusRequestFlags.RestoreFocusedChild) -- Fallback
else
local focus_flags = (g.NavLayer == ImGuiNavLayer.Main) and ImGuiFocusRequestFlags.RestoreFocusedChild or ImGuiFocusRequestFlags.None
ImGui.FocusWindow(focus_window, focus_flags)
end
end
end
-- Close the popup we have Begin-ed into
function ImGui.CloseCurrentPopup()
local g = GImGui
local popup_idx = g.BeginPopupStack.Size
if popup_idx < 1 or popup_idx > g.OpenPopupStack.Size or g.BeginPopupStack.Data[popup_idx].PopupId ~= g.OpenPopupStack.Data[popup_idx].PopupId then
return
end
-- Closing a menu closes its top-most parent popup (unless a modal)
while popup_idx > 1 do
local popup_window = g.OpenPopupStack.Data[popup_idx].Window
local parent_popup_window = g.OpenPopupStack.Data[popup_idx - 1].Window
local close_parent = false
if popup_window and bit32.band(popup_window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
if parent_popup_window and not (bit32.band(parent_popup_window.Flags, ImGuiWindowFlags.MenuBar) ~= 0) then
close_parent = true
end
end
if not close_parent then
break
end
popup_idx = popup_idx - 1
end
-- IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size, popup_idx)
ImGui.ClosePopupToLevel(popup_idx - 1, true)
-- A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
-- To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
-- Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
local window = g.NavWindow
if window then
window.DC.NavHideHighlightOneFrame = true
end
end
--- @param id ImGuiID
--- @param extra_window_flags ImGuiWindowFlags
function ImGui.BeginPopupEx(id, extra_window_flags)
local g = GImGui
if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then
g.NextWindowData:ClearFlags()
return false
end
IM_ASSERT(bit32.band(extra_window_flags, ImGuiWindowFlags.ChildMenu) == 0) -- Use BeginPopupMenuEx()
local name = ImFormatString("##Popup_%08x", id) -- No recycling, so we can close/open during the same frame
local is_open
_, is_open = ImGui.Begin(name, nil, bit32.bor(extra_window_flags, ImGuiWindowFlags.Popup, ImGuiWindowFlags.NoDocking))
if not is_open then -- NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
ImGui.EndPopup()
end
-- g.CurrentWindow.FocusRouteParentWindow = g.CurrentWindow.ParentWindowInBeginStack
return is_open
end
--- @param id ImGuiID
--- @param label any
--- @param extra_window_flags ImGuiWindowFlags
function ImGui.BeginPopupMenuEx(id, label, extra_window_flags)
local g = GImGui
if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then
g.NextWindowData:ClearFlags()
return false
end
if bit32.band(extra_window_flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(extra_window_flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 then
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasChildFlags) ~= 0 then
g.NextWindowData.ChildFlags = bit32.bor(g.NextWindowData.ChildFlags, ImGuiChildFlags.AlwaysAutoResize)
else
g.NextWindowData.ChildFlags = ImGuiChildFlags.AlwaysAutoResize
end
g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasChildFlags)
end
IM_ASSERT(bit32.band(extra_window_flags, ImGuiWindowFlags.ChildMenu) ~= 0)
local name = ImFormatString("%s###Menu_%02d", label, g.BeginMenuDepth)
local is_open
_, is_open = ImGui.Begin(name, nil, bit32.bor(extra_window_flags, ImGuiWindowFlags.Popup))
if not is_open then
ImGui.EndPopup()
end
return is_open
end
--- @param str_id string
--- @param flags? ImGuiWindowFlags
function ImGui.BeginPopup(str_id, flags)
if flags == nil then flags = 0 end
local g = GImGui
if g.OpenPopupStack.Size <= g.BeginPopupStack.Size then -- Early out for performance
g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values
return false
end
flags = bit32.bor(flags, ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings)
local id = g.CurrentWindow:GetID(str_id)
return ImGui.BeginPopupEx(id, flags)
end
function ImGui.EndPopup()
local g = GImGui
local window = g.CurrentWindow
IM_ASSERT_USER_ERROR_RET((bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0) and (g.BeginPopupStack.Size > 0), "Calling EndPopup() in wrong window!")
-- Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
if g.NavWindow == window then
ImGui.NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags.LoopY)
end
-- Child-popups don't need to be laid out
local backup_within_end_popup_id = g.WithinEndPopupID
local backup_within_end_child_id = g.WithinEndChildID
g.WithinEndPopupID = window.ID
if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
g.WithinEndChildID = window.ID
end
ImGui.End()
g.WithinEndPopupID = backup_within_end_popup_id
g.WithinEndChildID = backup_within_end_child_id
end
--- @param ref_pos ImVec2
--- @param size ImVec2
--- @param last_dir ImGuiDir
--- @param r_outer ImRect
--- @param r_avoid ImRect
--- @param policy ImGuiPopupPositionPolicy
--- @return ImVec2 # Best Window Pos For Popup
--- @return int # Updated last_dir
--- @nodiscard
function ImGui.FindBestWindowPosForPopupEx(ref_pos, size, last_dir, r_outer, r_avoid, policy)
local base_pos_clamped
-- Combo Box policy (we want a connecting edge)
if policy == ImGuiPopupPositionPolicy.ComboBox then
local dir_preferred_order = {ImGuiDir.Down, ImGuiDir.Right, ImGuiDir.Left, ImGuiDir.Up}
for n = (last_dir ~= ImGuiDir.None) and 0 or 1, ImGuiDir.COUNT do
repeat
local dir = (n == 0) and last_dir or dir_preferred_order[n]
if n ~= 0 and dir == last_dir then -- Already tried this direction?
break
end
local pos
if dir == ImGuiDir.Down then pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y) -- Below, Toward Right (default)
elseif dir == ImGuiDir.Right then pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y) -- Above, Toward Right
elseif dir == ImGuiDir.Left then pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y) -- Below, Toward Left
elseif dir == ImGuiDir.Up then pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y) -- Above, Toward Left
end
if not r_outer:Contains(ImRect(pos, pos + size)) then
break
end
last_dir = dir
do return pos, last_dir end
until true
end
end
-- Tooltip and Default popup policy
-- (Always first try the direction we used on the last frame, if any)
if policy == ImGuiPopupPositionPolicy.Tooltip or policy == ImGuiPopupPositionPolicy.Default then
local dir_preferred_order = {ImGuiDir.Right, ImGuiDir.Down, ImGuiDir.Up, ImGuiDir.Left}
for n = (last_dir ~= ImGuiDir.None) and 0 or 1, ImGuiDir.COUNT do
repeat
local dir = (n == 0) and last_dir or dir_preferred_order[n]
if n ~= 0 and dir == last_dir then
break
end
local avail_w = ((dir == ImGuiDir.Left) and r_avoid.Min.x or r_outer.Max.x) - ((dir == ImGuiDir.Right) and r_avoid.Max.x or r_outer.Min.x)
local avail_h = ((dir == ImGuiDir.Up) and r_avoid.Min.y or r_outer.Max.y) - ((dir == ImGuiDir.Down) and r_avoid.Max.y or r_outer.Min.y)
-- If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
if avail_w < size.x and (dir == ImGuiDir.Left or dir == ImGuiDir.Right) then
break
end
if avail_h < size.y and (dir == ImGuiDir.Up or dir == ImGuiDir.Down) then
break
end
base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size)
local pos = ImVec2()
pos.x = (dir == ImGuiDir.Left) and (r_avoid.Min.x - size.x) or ((dir == ImGuiDir.Right) and r_avoid.Max.x or base_pos_clamped.x)
pos.y = (dir == ImGuiDir.Up) and (r_avoid.Min.y - size.y) or ((dir == ImGuiDir.Down) and r_avoid.Max.y or base_pos_clamped.y)
-- Clamp top-left corner of popup
pos.x = ImMax(pos.x, r_outer.Min.x)
pos.y = ImMax(pos.y, r_outer.Min.y)
last_dir = dir
do return pos, last_dir end
until true
end
end
-- Fallback when not enough room:
last_dir = ImGuiDir.None
-- For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
if policy == ImGuiPopupPositionPolicy.Tooltip then
return ref_pos + ImVec2(2, 2), last_dir
end
-- Otherwise try to keep within display
local pos = ImVec2(ref_pos.x, ref_pos.y)
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x)
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y)
return pos, last_dir
end
--- @param window ImGuiWindow
--- @return ImRect
--- @nodiscard
function ImGui.GetPopupAllowedExtentRect(window)
local g = GImGui
local r_screen = ImRect()
if window.ViewportAllowPlatformMonitorExtend >= 1 then
-- Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
local monitor = g.PlatformIO.Monitors.Data[window.ViewportAllowPlatformMonitorExtend]
ImVec2_Copy(r_screen.Min, monitor.WorkPos)
ImVec2_Copy(r_screen.Max, monitor.WorkPos + monitor.WorkSize)
else
-- Use the full viewport area (not work area) for popups
r_screen = window.Viewport:GetMainRect()
end
local padding = g.Style.DisplaySafeAreaPadding
r_screen:Expand(ImVec2((r_screen:GetWidth() > padding.x * 2) and -padding.x or 0.0, (r_screen:GetHeight() > padding.y * 2) and -padding.y or 0.0))
return r_screen
end
--- @param window ImGuiWindow
--- @return ImVec2
--- @nodiscard
function ImGui.FindBestWindowPosForPopup(window)
local g = GImGui
local r_outer = ImGui.GetPopupAllowedExtentRect(window)
if bit32.band(window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
-- Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
-- This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
local parent_window = window.ParentWindow
local horizontal_overlap = g.Style.ItemInnerSpacing.x -- We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
local r_avoid
if parent_window.DC.MenuBarAppending then
r_avoid = ImRect(-FLT_MAX, parent_window.ClipRect.Min.y, FLT_MAX, parent_window.ClipRect.Max.y) -- Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
else
r_avoid = ImRect(parent_window.Pos.x + horizontal_overlap, -FLT_MAX, parent_window.Pos.x + parent_window.Size.x - horizontal_overlap - parent_window.ScrollbarSizes.x, FLT_MAX)
end
local pos
pos, window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(window.Pos, window.Size, window.AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy.Default)
return pos
end
if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then
local pos
pos, window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(window.Pos, window.Size, window.AutoPosLastDirection, r_outer, ImRect(window.Pos, window.Pos), ImGuiPopupPositionPolicy.Default) -- Ideally we'd disable r_avoid here
return pos
end
if bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0 then
-- Position tooltip (always follows mouse + clamp within outer boundaries)
-- FIXME:
-- - Too many paths. One problem is that FindBestWindowPosForPopupEx() doesn't allow passing a suggested position (so touch screen path doesn't use it by default).
-- - Drag and drop tooltips are not using this path either: BeginTooltipEx() manually sets their position.
-- - Require some tidying up. In theory we could handle both cases in same location, but requires a bit of shuffling
-- as drag and drop tooltips are calling SetNextWindowPos() leading to 'window_pos_set_by_api' being set in Begin().
IM_ASSERT(g.CurrentWindow == window)
local scale = g.Style.MouseCursorScale
local ref_pos = ImGui.NavCalcPreferredRefPos(ImGuiWindowFlags.Tooltip)
if g.IO.MouseSource == ImGuiMouseSource.TouchScreen and ImGui.NavCalcPreferredRefPosSource(ImGuiWindowFlags.Tooltip) == ImGuiInputSource.Mouse then
local tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_TOUCH * scale - TOOLTIP_DEFAULT_PIVOT_TOUCH * window.Size
if r_outer:Contains(ImRect(tooltip_pos, tooltip_pos + window.Size)) then
return tooltip_pos
end
end
local tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET_MOUSE * scale
local r_avoid
if g.NavCursorVisible and g.NavHighlightItemUnderNav and not g.IO.ConfigNavMoveSetMousePos then
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8)
else
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale) -- FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
end
local pos
pos, window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(tooltip_pos, window.Size, window.AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy.Tooltip)
return pos
end
IM_ASSERT(false)
return window.Pos
end
--- @param flags ImGuiPopupFlags
--- @return ImGuiMouseButton
function ImGui.GetMouseButtonFromPopupFlags(flags)
IM_ASSERT(bit32.band(flags, ImGuiPopupFlags.InvalidMask_) == 0)
if bit32.band(flags, ImGuiPopupFlags.MouseButtonMask_) ~= 0 then
return bit32.rshift(bit32.band(flags, ImGuiPopupFlags.MouseButtonMask_), ImGuiPopupFlags.MouseButtonShift_) - 1
end
return ImGuiMouseButton.Right -- Default == 1
end
--- @param popup_flags ImGuiPopupFlags
--- @param id ImGuiID
function ImGui.IsPopupOpenRequestForItem(popup_flags, id)
local g = GImGui
local mouse_button = ImGui.GetMouseButtonFromPopupFlags(popup_flags)
if ImGui.IsMouseReleased(mouse_button) and ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByPopup) then
return true
end
if g.NavOpenContextMenuItemId == id and (ImGui.IsItemFocused() or id == g.CurrentWindow.MoveId) then
return true
end
return false
end
--- @param str_id? string
--- @param popup_flags? ImGuiPopupFlags
function ImGui.OpenPopupOnItemClick(str_id, popup_flags)
if popup_flags == nil then popup_flags = 0 end
local g = GImGui
if ImGui.IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID) then
local window = g.CurrentWindow
local id
if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end
IM_ASSERT(id ~= 0)
return ImGui.OpenPopupEx(id, popup_flags)
end
return false
end
--- @param str_id? string
--- @param popup_flags? ImGuiPopupFlags
--- @return bool
function ImGui.BeginPopupContextItem(str_id, popup_flags)
if popup_flags == nil then popup_flags = 0 end
local g = GImGui
local window = g.CurrentWindow
if window.SkipItems then
return false
end
local id
if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end
IM_ASSERT(id ~= 0)
if ImGui.IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID) then
ImGui.OpenPopupEx(id, popup_flags)
end
return ImGui.BeginPopupEx(id, bit32.bor(ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings))
end
---------------------------------------------------------------------------------------
-- [SECTION] NAVIGATION
---------------------------------------------------------------------------------------
--- @param id ImGuiID
function ImGui.PushFocusScope(id)
local g = GImGui
local data = ImGuiFocusScopeData()
data.ID = id
data.WindowID = g.CurrentWindow.ID
g.FocusScopeStack:push_back(data)
g.CurrentFocusScopeId = id
end
function ImGui.PopFocusScope()
local g = GImGui
-- TODO: IM_ASSERT_USER_ERROR_RET(g.FocusScopeStack.Size > g.StackSizesInBeginForCurrentWindow.SizeOfFocusScopeStack, "Calling PopFocusScope() too many times!")
g.FocusScopeStack:pop_back()
if g.FocusScopeStack.Size > 0 then
g.CurrentFocusScopeId = g.FocusScopeStack:back().ID
else
g.CurrentFocusScopeId = 0
end
end
--- @param focus_scope_id ImGuiID
function ImGui.IsInNavFocusRoute(focus_scope_id)
local g = GImGui
if g.NavFocusScopeId == focus_scope_id then
return true
end
for _, focus_scope in g.NavFocusRoute:iter() do
if focus_scope.ID == focus_scope_id then
return true
end
end
return false
end
--- @param focus_scope_id ImGuiID
function ImGui.SetNavFocusScope(focus_scope_id)
local g = GImGui
g.NavFocusScopeId = focus_scope_id
g.NavFocusRoute:resize(0)
if focus_scope_id == 0 then
return
end
IM_ASSERT(g.NavWindow ~= nil)
if focus_scope_id == g.CurrentFocusScopeId then
for n = g.FocusScopeStack.Size, 1, -1 do
local data = g.FocusScopeStack.Data[n]
if data.WindowID ~= g.CurrentWindow.ID then
break
end
g.NavFocusRoute:push_back(data)
end
elseif focus_scope_id == g.NavWindow.NavRootFocusScopeId then
local data = ImGuiFocusScopeData()
data.ID = focus_scope_id
data.WindowID = g.NavWindow.ID
g.NavFocusRoute:push_back(data)
else
return
end
local window = g.NavWindow.ParentWindowForFocusRoute
while window ~= nil do
local data = ImGuiFocusScopeData()
data.ID = window.NavRootFocusScopeId
data.WindowID = window.ID
g.NavFocusRoute:push_back(data)
window = window.ParentWindowForFocusRoute
end
IM_ASSERT(g.NavFocusRoute.Size < 100)
end
function ImGui.SetItemDefaultFocus()
local g = GImGui
local window = g.CurrentWindow
if not window.Appearing then
return
end
if g.NavWindow ~= window.RootWindowForNav or (not g.NavInitRequest and g.NavInitResult.ID == 0) or g.NavLayer ~= window.DC.NavLayerCurrent then
return
end
g.NavInitRequest = false
ImGui.NavApplyItemToResult(g.NavInitResult)
ImGui.NavUpdateAnyRequestFlag()
if not window.ClipRect:Contains(g.LastItemData.Rect) then
ImGui.ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags.None)
end
end
function ImGui.SetNavCursorVisibleAfterMove()
local g = GImGui
if g.NavWindow and (bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) ~= 0) then
g.NavCursorVisible = false
elseif g.NavInputSource == ImGuiInputSource.Keyboard and (bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) == 0) then
g.NavCursorVisible = false
elseif g.NavInputSource == ImGuiInputSource.Gamepad and (bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) == 0) then
g.NavCursorVisible = false
elseif g.IO.ConfigNavCursorVisibleAuto then
g.NavCursorVisible = true
end
g.NavHighlightItemUnderNav = true
g.NavMousePosDirty = true
end
--- @param window? ImGuiWindow
function ImGui.SetNavWindow(window)
local g = GImGui
if g.NavWindow ~= window then
-- IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")", window and window.Name or "<NULL>")
g.NavWindow = window
g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid
end
g.NavInitRequest = false
g.NavMoveSubmitted = false
g.NavMoveScoringItems = false
ImGui.NavUpdateAnyRequestFlag()
end
--- @param axis ImGuiAxis
function ImGui.NavClearPreferredPosForAxis(axis)
local g = GImGui
g.NavWindow.RootWindowForNav.NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX
end
--- @param id ImGuiID
--- @param nav_layer ImGuiNavLayer
--- @param focus_scope_id ImGuiID
--- @param rect_rel ImRect
function ImGui.SetNavID(id, nav_layer, focus_scope_id, rect_rel)
local g = GImGui
IM_ASSERT(g.NavWindow ~= nil)
IM_ASSERT(nav_layer == ImGuiNavLayer.Main or nav_layer == ImGuiNavLayer.Menu)
g.NavId = id
g.NavLayer = nav_layer
ImGui.SetNavFocusScope(focus_scope_id)
g.NavWindow.NavLastIds[nav_layer] = id
ImRect_Copy(g.NavWindow.NavRectRel[nav_layer], rect_rel)
ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X)
ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y)
end
--- @param nav_window ImGuiWindow
function ImGui.NavSaveLastChildNavWindowIntoParent(nav_window)
local parent = nav_window
while parent and parent.RootWindow ~= parent and bit32.band(parent.Flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu)) == 0 do
parent = parent.ParentWindow
end
if parent and parent ~= nav_window then
parent.NavLastChildNavWindow = nav_window
end
end
--- @param window ImGuiWindow
function ImGui.NavRestoreLastChildNavWindow(window)
if window.NavLastChildNavWindow and window.NavLastChildNavWindow.WasActive then
return window.NavLastChildNavWindow
end
return window
end
--- @param layer ImGuiNavLayer
function ImGui.NavRestoreLayer(layer)
local g = GImGui
if layer == ImGuiNavLayer.Main then
local prev_nav_window = g.NavWindow
g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow)
g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid
end
local window = g.NavWindow
if window.NavLastIds[layer] ~= 0 then
ImGui.SetNavID(window.NavLastIds[layer], layer, 0, window.NavRectRel[layer])
else
g.NavLayer = layer
ImGui.NavInitWindow(window, true)
end
end
--- @param id ImGuiID
function ImGui.NavHighlightActivated(id)
local g = GImGui
g.NavHighlightActivatedId = id
g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER
end
function ImGui.NavUpdateAnyRequestFlag()
local g = GImGui
g.NavAnyRequest = g.NavMoveScoringItems or g.NavInitRequest or (IMGUI_DEBUG_NAV_SCORING and g.NavWindow ~= nil)
if g.NavAnyRequest then
IM_ASSERT(g.NavWindow ~= nil)
end
end
--- @param window ImGuiWindow
--- @param force_reinit bool
function ImGui.NavInitWindow(window, force_reinit)
local g = GImGui
IM_ASSERT(window == g.NavWindow)
if bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) ~= 0 then
g.NavId = 0
ImGui.SetNavFocusScope(window.NavRootFocusScopeId)
return
end
local init_for_nav = false
if window == window.RootWindow or bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 or window.NavLastIds[0] == 0 or force_reinit then
init_for_nav = true
end
-- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d", init_for_nav, window->Name, g.NavLayer)
if init_for_nav then
ImGui.SetNavID(0, g.NavLayer, window.NavRootFocusScopeId, ImRect())
g.NavInitRequest = true
g.NavInitRequestFromMove = false
g.NavInitResult.ID = 0
ImGui.NavUpdateAnyRequestFlag()
else
g.NavId = window.NavLastIds[0]
ImGui.SetNavFocusScope(window.NavRootFocusScopeId)
end
end
--- @param window_type ImGuiWindowFlags
--- @return ImGuiInputSource
function ImGui.NavCalcPreferredRefPosSource(window_type)
local g = GImGui
local window = g.NavWindow
local activated_shortcut = g.ActiveId ~= 0 and g.ActiveIdFromShortcut and g.ActiveId == g.LastItemData.ID
if (bit32.band(window_type, ImGuiWindowFlags.Popup) ~= 0) and activated_shortcut then
return ImGuiInputSource.Keyboard
end
if not g.NavCursorVisible or not g.NavHighlightItemUnderNav or not window then
return ImGuiInputSource.Mouse
else
return ImGuiInputSource.Keyboard -- or Nav in general
end
end
--- @param window_type ImGuiWindowFlags
--- @return ImVec2
--- @nodiscard
function ImGui.NavCalcPreferredRefPos(window_type)
local g = GImGui
local window = g.NavWindow
local source = ImGui.NavCalcPreferredRefPosSource(window_type)
if source == ImGuiInputSource.Mouse then
-- Mouse (we need a fallback in case the mouse becomes invalid after being used)
-- The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
-- In theory we could move that +1.0f offset in OpenPopupEx()
local p = ImGui.IsMousePosValid(g.IO.MousePos) and g.IO.MousePos or g.MouseLastValidPos
return ImVec2(p.x + 1.0, p.y)
else
-- When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
local activated_shortcut = g.ActiveId ~= 0 and g.ActiveIdFromShortcut and g.ActiveId == g.LastItemData.ID
local ref_rect = ImRect()
if activated_shortcut and (bit32.band(window_type, ImGuiWindowFlags.Popup) ~= 0) then
ImRect_Copy(ref_rect, g.LastItemData.NavRect)
elseif window ~= nil then
ImRect_Copy(ref_rect, ImGui.WindowRectRelToAbs(window, window.NavRectRel[g.NavLayer]))
end
-- Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
if window ~= nil and window.LastFrameActive ~= g.FrameCount and (window.ScrollTarget.x ~= FLT_MAX or window.ScrollTarget.y ~= FLT_MAX) then
local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window)
ref_rect:Translate(window.Scroll - next_scroll)
end
local pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect:GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect:GetHeight()))
if window ~= nil then
local viewport = window.Viewport
if viewport then
pos = ImClamp(pos, viewport.Pos, viewport.Pos + viewport.Size)
end
end
return ImTrunc(pos) -- ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
end
end
--- @param axis ImGuiAxis
--- @return float
function ImGui.GetNavTweakPressedAmount(axis)
local g = GImGui
local repeat_delay, repeat_rate = ImGui.GetTypematicRepeatRate(ImGuiInputFlags.RepeatRateNavTweak)
local key_less, key_more
if g.NavInputSource == ImGuiInputSource.Gamepad then
key_less = (axis == ImGuiAxis.X) and ImGuiKey.GamepadDpadLeft or ImGuiKey.GamepadDpadUp
key_more = (axis == ImGuiAxis.X) and ImGuiKey.GamepadDpadRight or ImGuiKey.GamepadDpadDown
else
key_less = (axis == ImGuiAxis.X) and ImGuiKey.LeftArrow or ImGuiKey.UpArrow
key_more = (axis == ImGuiAxis.X) and ImGuiKey.RightArrow or ImGuiKey.DownArrow
end
local amount = ImGui.GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - ImGui.GetKeyPressedAmount(key_less, repeat_delay, repeat_rate)
if amount ~= 0.0 and ImGui.IsKeyDown(key_less) and ImGui.IsKeyDown(key_more) then -- Cancel when opposite directions are held, regardless of repeat phase
amount = 0.0
end
return amount
end
do
local nav_gamepad_keys_to_change_source = { ImGuiKey.GamepadFaceRight, ImGuiKey.GamepadFaceLeft, ImGuiKey.GamepadFaceUp, ImGuiKey.GamepadFaceDown, ImGuiKey.GamepadDpadRight, ImGuiKey.GamepadDpadLeft, ImGuiKey.GamepadDpadUp, ImGuiKey.GamepadDpadDown }
local nav_keyboard_keys_to_change_source = { ImGuiKey.Space, ImGuiKey.Enter, ImGuiKey.Escape, ImGuiKey.RightArrow, ImGuiKey.LeftArrow, ImGuiKey.UpArrow, ImGuiKey.DownArrow }
--- @param focus_change_dir int
function ImGui.NavUpdateWindowingTarget(focus_change_dir)
local g = GImGui
IM_ASSERT(g.NavWindowingTarget)
if bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.Modal) ~= 0 then
return
end
local i_current = ImGui.FindWindowFocusIndex(g.NavWindowingTarget)
local window_target = ImGui.FindWindowNavFocusable(i_current + focus_change_dir, 0, focus_change_dir)
if window_target == nil then
window_target = ImGui.FindWindowNavFocusable((focus_change_dir < 0) and g.WindowsFocusOrder.Size or 1, i_current, focus_change_dir)
end
if window_target then
g.NavWindowingTarget = window_target
g.NavWindowingTargetAnim = window_target
ImVec2_CopyV(g.NavWindowingAccumDeltaPos, 0.0, 0.0)
ImVec2_CopyV(g.NavWindowingAccumDeltaSize, 0.0, 0.0)
end
g.NavWindowingToggleLayer = false
end
--- @param apply_focus_window ImGuiWindow
function ImGui.NavUpdateWindowingApplyFocus(apply_focus_window)
local g = GImGui
if g.NavWindow == nil or apply_focus_window ~= g.NavWindow.RootWindow then
local previous_viewport = g.NavWindow and g.NavWindow.Viewport or nil
ImGui.ClearActiveID()
ImGui.SetNavCursorVisibleAfterMove()
ImGui.ClosePopupsOverWindow(apply_focus_window, false)
ImGui.FocusWindow(apply_focus_window, ImGuiFocusRequestFlags.RestoreFocusedChild)
IM_ASSERT(g.NavWindow ~= nil)
apply_focus_window = g.NavWindow
if apply_focus_window.NavLastIds[ImGuiNavLayer.Main] == 0 then
ImGui.NavInitWindow(apply_focus_window, false)
end
if apply_focus_window.DC.NavLayersActiveMaskNext == bit32.lshift(1, ImGuiNavLayer.Menu) then
g.NavLayer = ImGuiNavLayer.Menu
end
if apply_focus_window.Viewport ~= previous_viewport and g.PlatformIO.Platform_SetWindowFocus then
g.PlatformIO.Platform_SetWindowFocus(apply_focus_window.Viewport)
end
end
g.NavWindowingTarget = nil
end
function ImGui.NavUpdateWindowing()
local g = GImGui
local io = g.IO
local apply_focus_window = nil
local apply_toggle_layer = false
local modal_window = ImGui.GetTopMostPopupModal()
local allow_windowing = (modal_window == nil)
if not allow_windowing then
g.NavWindowingTarget = nil
end
if g.NavWindowingTargetAnim and g.NavWindowingTarget == nil then
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0, 0.0)
if g.DimBgRatio <= 0.0 and g.NavWindowingHighlightAlpha <= 0.0 then
g.NavWindowingTargetAnim = nil
end
end
local owner_id = ImHashStr("##NavUpdateWindowing")
local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0
local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0
local keyboard_next_window = allow_windowing and g.ConfigNavWindowingKeyNext ~= 0 and ImGui.Shortcut(g.ConfigNavWindowingKeyNext, bit32.bor(ImGuiInputFlags.Repeat, ImGuiInputFlags.RouteAlways), owner_id)
local keyboard_prev_window = allow_windowing and g.ConfigNavWindowingKeyPrev ~= 0 and ImGui.Shortcut(g.ConfigNavWindowingKeyPrev, bit32.bor(ImGuiInputFlags.Repeat, ImGuiInputFlags.RouteAlways), owner_id)
local start_toggling_with_gamepad = nav_gamepad_active and g.NavWindowingTarget == nil and ImGui.Shortcut(ImGuiKey.NavGamepadMenu, ImGuiInputFlags.RouteAlways, owner_id)
local start_windowing_with_gamepad = allow_windowing and start_toggling_with_gamepad
local start_windowing_with_keyboard = allow_windowing and g.NavWindowingTarget == nil and (keyboard_next_window or keyboard_prev_window)
local just_started_windowing_from_null_focus = false
if start_toggling_with_gamepad then
g.NavWindowingToggleLayer = true
g.NavWindowingToggleKey = ImGuiKey.NavGamepadMenu
g.NavWindowingInputSource = ImGuiInputSource.Gamepad
g.NavInputSource = ImGuiInputSource.Gamepad
end
if start_windowing_with_gamepad or start_windowing_with_keyboard then
local window = (g.NavWindow and ImGui.IsWindowNavFocusable(g.NavWindow)) and g.NavWindow or ImGui.FindWindowNavFocusable(g.WindowsFocusOrder.Size, 0, -1)
if window then
if start_windowing_with_keyboard or g.ConfigNavWindowingWithGamepad then
g.NavWindowingTarget = window.RootWindow
g.NavWindowingTargetAnim = window.RootWindow
end
g.NavWindowingTimer = 0.0
g.NavWindowingHighlightAlpha = 0.0
ImVec2_CopyV(g.NavWindowingAccumDeltaPos, 0.0, 0.0)
ImVec2_CopyV(g.NavWindowingAccumDeltaSize, 0.0, 0.0)
g.NavWindowingInputSource = start_windowing_with_keyboard and ImGuiInputSource.Keyboard or ImGuiInputSource.Gamepad
g.NavInputSource = g.NavWindowingInputSource
if g.NavWindow == nil then
just_started_windowing_from_null_focus = true
end
if keyboard_next_window or keyboard_prev_window then
ImGui.SetKeyOwnersForKeyChord(bit32.band(bit32.bor(g.ConfigNavWindowingKeyNext, g.ConfigNavWindowingKeyPrev), ImGuiMod_Mask_), owner_id)
end
end
end
if (g.NavWindowingTarget or g.NavWindowingToggleLayer) and g.NavWindowingInputSource == ImGuiInputSource.Gamepad then
if g.NavWindowingTarget ~= nil then
g.NavWindowingTimer = g.NavWindowingTimer + io.DeltaTime
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05))
local focus_change_dir = (ImGui.IsKeyPressedEx(ImGuiKey.GamepadL1, ImGuiInputFlags.None, ImGuiKeyOwner_Any) and 1 or 0) - (ImGui.IsKeyPressedEx(ImGuiKey.GamepadR1, ImGuiInputFlags.None, ImGuiKeyOwner_Any) and 1 or 0)
if focus_change_dir ~= 0 and not just_started_windowing_from_null_focus then
ImGui.NavUpdateWindowingTarget(focus_change_dir)
g.NavWindowingHighlightAlpha = 1.0
end
end
if not ImGui.IsKeyDown(ImGuiKey.NavGamepadMenu) then
g.NavWindowingToggleLayer = g.NavWindowingToggleLayer and (g.NavWindowingHighlightAlpha < 1.0)
if g.NavWindowingToggleLayer and g.NavWindow then
apply_toggle_layer = true
elseif not g.NavWindowingToggleLayer then
apply_focus_window = g.NavWindowingTarget
end
g.NavWindowingTarget = nil
g.NavWindowingToggleLayer = false
end
end
if g.NavWindowingTarget and g.NavWindowingInputSource == ImGuiInputSource.Keyboard then
local shared_mods = bit32.band(
bit32.band((g.ConfigNavWindowingKeyNext ~= 0) and g.ConfigNavWindowingKeyNext or ImGuiMod_Mask_, (g.ConfigNavWindowingKeyPrev ~= 0) and g.ConfigNavWindowingKeyPrev or ImGuiMod_Mask_),
ImGuiMod_Mask_)
IM_ASSERT(shared_mods ~= 0)
g.NavWindowingTimer = g.NavWindowingTimer + io.DeltaTime
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05))
if (keyboard_next_window or keyboard_prev_window) and not just_started_windowing_from_null_focus then
ImGui.NavUpdateWindowingTarget(keyboard_next_window and -1 or 1)
elseif bit32.band(io.KeyMods, shared_mods) ~= shared_mods then
apply_focus_window = g.NavWindowingTarget
end
end
local windowing_toggle_keys = { ImGuiKey.LeftAlt, ImGuiKey.RightAlt }
local windowing_toggle_layer_start = false
if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then
for _, windowing_toggle_key in ipairs(windowing_toggle_keys) do
if nav_keyboard_active and ImGui.IsKeyPressedEx(windowing_toggle_key, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) then
windowing_toggle_layer_start = true
g.NavWindowingToggleLayer = true
g.NavWindowingToggleKey = windowing_toggle_key
g.NavWindowingInputSource = ImGuiInputSource.Keyboard
g.NavInputSource = ImGuiInputSource.Keyboard
break
end
end
end
if g.NavWindowingToggleLayer and g.NavWindowingInputSource == ImGuiInputSource.Keyboard then
if io.InputQueueCharacters.Size > 0 or io.KeyCtrl or io.KeyShift or io.KeySuper then
g.NavWindowingToggleLayer = false
elseif windowing_toggle_layer_start == false and g.LastKeyboardKeyPressTime == g.Time then
g.NavWindowingToggleLayer = false
elseif ImGui.TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false or ImGui.TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false then
g.NavWindowingToggleLayer = false
end
if ImGui.IsKeyReleased(g.NavWindowingToggleKey) and g.NavWindowingToggleLayer then
if g.ActiveId == 0 or g.ActiveIdAllowOverlap then
if ImGui.IsMousePosValid(io.MousePos) == ImGui.IsMousePosValid(io.MousePosPrev) then
apply_toggle_layer = true
end
end
end
if not ImGui.IsKeyDown(g.NavWindowingToggleKey) then
g.NavWindowingToggleLayer = false
end
end
if g.NavWindowingTarget and bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.NoMove) == 0 then
local nav_move_dir
if g.NavInputSource == ImGuiInputSource.Keyboard and not io.KeyShift then
nav_move_dir = ImGui.GetKeyMagnitude2d(ImGuiKey.LeftArrow, ImGuiKey.RightArrow, ImGuiKey.UpArrow, ImGuiKey.DownArrow)
end
if g.NavInputSource == ImGuiInputSource.Gamepad then
nav_move_dir = ImGui.GetKeyMagnitude2d(ImGuiKey.GamepadLStickLeft, ImGuiKey.GamepadLStickRight, ImGuiKey.GamepadLStickUp, ImGuiKey.GamepadLStickDown)
end
if nav_move_dir and (nav_move_dir.x ~= 0.0 or nav_move_dir.y ~= 0.0) then
local NAV_MOVE_SPEED = 800.0
local move_step = NAV_MOVE_SPEED * io.DeltaTime * ImGui.GetScale()
ImVec2_Copy(g.NavWindowingAccumDeltaPos, g.NavWindowingAccumDeltaPos + nav_move_dir * move_step)
g.NavHighlightItemUnderNav = true
local accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos)
if accum_floored.x ~= 0.0 or accum_floored.y ~= 0.0 then
local moving_window = g.NavWindowingTarget.RootWindowDockTree
ImGui.SetWindowPos(moving_window, moving_window.Pos + accum_floored, ImGuiCond.Always)
ImVec2_Copy(g.NavWindowingAccumDeltaPos, g.NavWindowingAccumDeltaPos - accum_floored)
end
end
end
if apply_focus_window then
ImGui.NavUpdateWindowingApplyFocus(apply_focus_window)
end
if apply_toggle_layer and g.NavWindow then
ImGui.ClearActiveID()
local new_nav_window = g.NavWindow
while new_nav_window.ParentWindow
and bit32.band(new_nav_window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) == 0
and bit32.band(new_nav_window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0
and bit32.band(new_nav_window.Flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu)) == 0 do
new_nav_window = new_nav_window.ParentWindow
end
if new_nav_window ~= g.NavWindow then
local old_nav_window = g.NavWindow
ImGui.FocusWindow(new_nav_window)
new_nav_window.NavLastChildNavWindow = old_nav_window
end
local new_nav_layer = (bit32.band(g.NavWindow.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) ~= 0) and bit32.bxor(g.NavLayer, 1) or ImGuiNavLayer.Main
if new_nav_layer ~= g.NavLayer then
local preserve_layer_1_nav_id = (new_nav_window.DockNodeAsHost ~= nil)
if new_nav_layer == ImGuiNavLayer.Menu and not preserve_layer_1_nav_id then
g.NavWindow.NavLastIds[new_nav_layer] = 0
end
ImGui.NavRestoreLayer(new_nav_layer)
ImGui.SetNavCursorVisibleAfterMove()
end
end
end
function ImGui.NavUpdateContextMenuRequest()
local g = GImGui
local io = g.IO
g.NavOpenContextMenuItemId = 0
g.NavOpenContextMenuWindowId = 0
local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0
local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0
if (not nav_keyboard_active and not nav_gamepad_active) or g.NavWindow == nil then
return
end
local request = false
request = request or (nav_keyboard_active and (ImGui.IsKeyReleased(ImGuiKey.Menu, ImGuiKeyOwner_NoOwner) or (ImGui.IsKeyPressedEx(ImGuiKey.F10, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) and io.KeyMods == ImGuiMod_Shift)))
request = request or (nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.NavGamepadContextMenu, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner))
if not request then
return
end
g.NavOpenContextMenuItemId = g.NavId
g.NavOpenContextMenuWindowId = g.NavWindow.ID
if g.NavId == g.NavWindow:GetID("#CLOSE") or g.NavId == g.NavWindow:GetID("#COLLAPSE") then
g.NavOpenContextMenuItemId = g.NavWindow.MoveId
end
g.NavInputSource = ImGuiInputSource.Keyboard
ImGui.SetNavCursorVisibleAfterMove()
end
--- @param move_dir ImGuiDir
--- @param clip_dir ImGuiDir
--- @param move_flags ImGuiNavMoveFlags
--- @param scroll_flags ImGuiScrollFlags
function ImGui.NavMoveRequestSubmit(move_dir, clip_dir, move_flags, scroll_flags)
local g = GImGui
IM_ASSERT(g.NavWindow ~= nil)
if bit32.band(move_flags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then
move_flags = bit32.bor(move_flags, ImGuiNavMoveFlags.AllowCurrentNavId)
end
g.NavMoveSubmitted = true; g.NavMoveScoringItems = true
g.NavMoveDir = move_dir
g.NavMoveDirForDebug = move_dir
g.NavMoveClipDir = clip_dir
g.NavMoveFlags = move_flags
g.NavMoveScrollFlags = scroll_flags
g.NavMoveForwardToNextFrame = false
g.NavMoveKeyMods = (bit32.band(move_flags, ImGuiNavMoveFlags.FocusApi) ~= 0) and 0 or g.IO.KeyMods
g.NavMoveResultLocal:Clear()
g.NavMoveResultLocalVisible:Clear()
g.NavMoveResultOther:Clear()
g.NavTabbingCounter = 0
g.NavTabbingResultFirst:Clear()
ImGui.NavUpdateAnyRequestFlag()
end
--- @param r ImRect
--- @param preferred_pos_rel ImVec2
--- @param move_dir ImGuiDir
--- @param move_flags ImGuiNavMoveFlags
function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags)
local g = GImGui
local rel_to_abs_offset = g.NavWindow.DC.CursorStartPos
if bit32.band(move_flags, ImGuiNavMoveFlags.Forwarded) == 0 then
if preferred_pos_rel.x == FLT_MAX then
preferred_pos_rel.x = ImMin(r.Min.x + 1.0, r.Max.x) - rel_to_abs_offset.x
end
if preferred_pos_rel.y == FLT_MAX then
preferred_pos_rel.y = r:GetCenter().y - rel_to_abs_offset.y
end
end
if (move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and preferred_pos_rel.x ~= FLT_MAX then
local new_x = preferred_pos_rel.x + rel_to_abs_offset.x
r.Min.x = new_x; r.Max.x = new_x
elseif (move_dir == ImGuiDir.Left or move_dir == ImGuiDir.Right) and preferred_pos_rel.y ~= FLT_MAX then
local new_y = preferred_pos_rel.y + rel_to_abs_offset.y
r.Min.y = new_y; r.Max.y = new_y
end
end
--- @return float
function ImGui.NavUpdatePageUpPageDown()
local g = GImGui
local window = g.NavWindow
if bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) ~= 0 or g.NavWindowingTarget ~= nil then
return 0.0
end
local page_up_held = ImGui.IsKeyDown(ImGuiKey.PageUp, ImGuiKeyOwner_NoOwner)
local page_down_held = ImGui.IsKeyDown(ImGuiKey.PageDown, ImGuiKeyOwner_NoOwner)
local home_pressed = ImGui.IsKeyPressedEx(ImGuiKey.Home, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner)
local end_pressed = ImGui.IsKeyPressedEx(ImGuiKey.End, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner)
if page_up_held == page_down_held and home_pressed == end_pressed then
return 0.0
end
if g.NavLayer ~= ImGuiNavLayer.Main then
ImGui.NavRestoreLayer(ImGuiNavLayer.Main)
end
if bit32.band(window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Main)) == 0 and window.DC.NavWindowHasScrollY then
if ImGui.IsKeyPressedEx(ImGuiKey.PageUp, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then
ImGui.SetScrollY(window, window.Scroll.y - window.InnerRect:GetHeight())
elseif ImGui.IsKeyPressedEx(ImGuiKey.PageDown, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then
ImGui.SetScrollY(window, window.Scroll.y + window.InnerRect:GetHeight())
elseif home_pressed then
ImGui.SetScrollY(window, 0.0)
elseif end_pressed then
ImGui.SetScrollY(window, window.ScrollMax.y)
end
else
local nav_rect_rel = window.NavRectRel[g.NavLayer]
local page_offset_y = ImMax(0.0, window.InnerRect:GetHeight() - window.FontRefSize * 1.0 + nav_rect_rel:GetHeight())
local nav_scoring_rect_offset_y = 0.0
if ImGui.IsKeyPressedEx(ImGuiKey.PageUp, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then
nav_scoring_rect_offset_y = -page_offset_y
g.NavMoveDir = ImGuiDir.Down
g.NavMoveClipDir = ImGuiDir.Up
g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove)
elseif ImGui.IsKeyPressedEx(ImGuiKey.PageDown, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then
nav_scoring_rect_offset_y = page_offset_y
g.NavMoveDir = ImGuiDir.Up
g.NavMoveClipDir = ImGuiDir.Down
g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove)
elseif home_pressed then
nav_rect_rel.Min.y = 0.0; nav_rect_rel.Max.y = 0.0
if nav_rect_rel:IsInverted() then
nav_rect_rel.Min.x = 0.0; nav_rect_rel.Max.x = 0.0
end
g.NavMoveDir = ImGuiDir.Down
g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.ScrollToEdgeY)
elseif end_pressed then
nav_rect_rel.Min.y = window.ContentSize.y; nav_rect_rel.Max.y = window.ContentSize.y
if nav_rect_rel:IsInverted() then
nav_rect_rel.Min.x = 0.0; nav_rect_rel.Max.x = 0.0
end
g.NavMoveDir = ImGuiDir.Up
g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.ScrollToEdgeY)
end
return nav_scoring_rect_offset_y
end
return 0.0
end
function ImGui.NavUpdateCreateMoveRequest()
local g = GImGui
local io = g.IO
local window = g.NavWindow
local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0
local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0
if g.NavMoveForwardToNextFrame and window ~= nil then
IM_ASSERT(g.NavMoveDir ~= ImGuiDir.None and g.NavMoveClipDir ~= ImGuiDir.None)
IM_ASSERT(bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) ~= 0)
else
g.NavMoveDir = ImGuiDir.None
g.NavMoveFlags = ImGuiNavMoveFlags.None
g.NavMoveScrollFlags = ImGuiScrollFlags.None
if window and not g.NavWindowingTarget and bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then
local repeat_mode = bit32.bor(ImGuiInputFlags.Repeat, ImGuiInputFlags.RepeatRateNavMove)
if not ImGui.IsActiveIdUsingNavDir(ImGuiDir.Left) and ((nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.GamepadDpadLeft, repeat_mode, ImGuiKeyOwner_NoOwner)) or (nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.LeftArrow, repeat_mode, ImGuiKeyOwner_NoOwner))) then g.NavMoveDir = ImGuiDir.Left end
if not ImGui.IsActiveIdUsingNavDir(ImGuiDir.Right) and ((nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) or (nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner))) then g.NavMoveDir = ImGuiDir.Right end
if not ImGui.IsActiveIdUsingNavDir(ImGuiDir.Up) and ((nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.GamepadDpadUp, repeat_mode, ImGuiKeyOwner_NoOwner)) or (nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.UpArrow, repeat_mode, ImGuiKeyOwner_NoOwner))) then g.NavMoveDir = ImGuiDir.Up end
if not ImGui.IsActiveIdUsingNavDir(ImGuiDir.Down) and ((nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.GamepadDpadDown, repeat_mode, ImGuiKeyOwner_NoOwner)) or (nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.DownArrow, repeat_mode, ImGuiKeyOwner_NoOwner))) then g.NavMoveDir = ImGuiDir.Down end
end
g.NavMoveClipDir = g.NavMoveDir
ImRect_Copy(g.NavScoringNoClipRect, ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX))
end
local scoring_page_offset_y = 0.0
if window and g.NavMoveDir == ImGuiDir.None and nav_keyboard_active then
scoring_page_offset_y = ImGui.NavUpdatePageUpPageDown()
end
g.NavMoveForwardToNextFrame = false
if g.NavMoveDir ~= ImGuiDir.None then
ImGui.NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags)
end
if g.NavMoveSubmitted and g.NavId == 0 then
g.NavInitRequest = true; g.NavInitRequestFromMove = true
g.NavInitResult.ID = 0
if g.IO.ConfigNavCursorVisibleAuto then
g.NavCursorVisible = true
end
end
if g.NavMoveSubmitted and g.NavInputSource == ImGuiInputSource.Gamepad and g.NavLayer == ImGuiNavLayer.Main and window ~= nil then
local clamp_x = bit32.band(g.NavMoveFlags, bit32.bor(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.WrapX)) == 0
local clamp_y = bit32.band(g.NavMoveFlags, bit32.bor(ImGuiNavMoveFlags.LoopY, ImGuiNavMoveFlags.WrapY)) == 0
local inner_rect_rel = ImGui.WindowRectAbsToRel(window, ImRect(ImVec2(window.InnerRect.Min.x - 1, window.InnerRect.Min.y - 1), ImVec2(window.InnerRect.Max.x + 1, window.InnerRect.Max.y + 1)))
local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window)
inner_rect_rel:Translate(ImVec2(next_scroll.x - window.Scroll.x, next_scroll.y - window.Scroll.y))
if (clamp_x or clamp_y) and not inner_rect_rel:Contains(window.NavRectRel[g.NavLayer]) then
local pad_x = ImMin(inner_rect_rel:GetWidth(), window.FontRefSize * 0.5)
local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5)
inner_rect_rel.Min.x = clamp_x and (inner_rect_rel.Min.x + pad_x) or -FLT_MAX
inner_rect_rel.Max.x = clamp_x and (inner_rect_rel.Max.x - pad_x) or FLT_MAX
inner_rect_rel.Min.y = clamp_y and (inner_rect_rel.Min.y + pad_y) or -FLT_MAX
inner_rect_rel.Max.y = clamp_y and (inner_rect_rel.Max.y - pad_y) or FLT_MAX
window.NavRectRel[g.NavLayer]:ClipWithFull(inner_rect_rel)
g.NavId = 0
end
end
local scoring_rect = ImRect()
if window ~= nil then
local nav_rect_rel = ImRect()
if not window.NavRectRel[g.NavLayer]:IsInverted() then
ImRect_Copy(nav_rect_rel, window.NavRectRel[g.NavLayer])
end
scoring_rect = ImGui.WindowRectRelToAbs(window, nav_rect_rel)
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsPageMove) ~= 0 then
if window.InnerRect:Contains(scoring_rect) then
g.NavMoveFlags = bit32.bor(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet)
end
ImRect_Copy(g.NavScoringNoClipRect, scoring_rect)
scoring_rect:TranslateY(scoring_page_offset_y)
g.NavScoringNoClipRect:Add(scoring_rect)
end
if g.NavMoveSubmitted then
ImGui.NavBiasScoringRect(scoring_rect, window.RootWindowForNav.NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags)
end
IM_ASSERT(not scoring_rect:IsInverted())
end
ImRect_Copy(g.NavScoringRect, scoring_rect)
end
function ImGui.NavUpdateCreateTabbingRequest()
local g = GImGui
local window = g.NavWindow
IM_ASSERT(g.NavMoveDir == ImGuiDir.None)
if window == nil or g.NavWindowingTarget ~= nil or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) ~= 0 or not g.ConfigNavEnableTabbing then
return
end
local tab_pressed = ImGui.IsKeyPressedEx(ImGuiKey.Tab, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) and not g.IO.KeyCtrl and not g.IO.KeyAlt
if not tab_pressed then
return
end
local nav_keyboard_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0
if nav_keyboard_active then
g.NavTabbingDir = g.IO.KeyShift and -1 or ((g.NavCursorVisible == false and g.ActiveId == 0) and 0 or 1)
else
g.NavTabbingDir = g.IO.KeyShift and -1 or ((g.ActiveId == 0) and 0 or 1)
end
local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.Activate)
local scroll_flags = window.Appearing and bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.AlwaysCenterY) or bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleEdgeY)
local clip_dir = (g.NavTabbingDir < 0) and ImGuiDir.Up or ImGuiDir.Down
ImGui.NavMoveRequestSubmit(ImGuiDir.None, clip_dir, move_flags, scroll_flags)
g.NavTabbingCounter = -1
end
function ImGui.NavUpdate()
local g = GImGui
local io = g.IO
io.WantSetMousePos = false
local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0
if nav_gamepad_active and g.NavInputSource ~= ImGuiInputSource.Gamepad then
for _, key in ipairs(nav_gamepad_keys_to_change_source) do
if ImGui.IsKeyDown(key) then
g.NavInputSource = ImGuiInputSource.Gamepad
end
end
end
local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0
if nav_keyboard_active and g.NavInputSource ~= ImGuiInputSource.Keyboard then
for _, key in ipairs(nav_keyboard_keys_to_change_source) do
if ImGui.IsKeyDown(key) then
g.NavInputSource = ImGuiInputSource.Keyboard
end
end
end
g.NavJustMovedToId = 0
g.NavJustMovedToFocusScopeId = 0
g.NavJustMovedFromFocusScopeId = 0
if g.NavInitResult.ID ~= 0 then
ImGui.NavInitRequestApplyResult()
end
g.NavInitRequest = false
g.NavInitRequestFromMove = false
g.NavInitResult.ID = 0
if g.NavMoveSubmitted then
ImGui.NavMoveRequestApplyResult()
end
g.NavTabbingCounter = 0
g.NavMoveSubmitted = false
g.NavMoveScoringItems = false
if g.NavCursorHideFrames > 0 then
g.NavCursorHideFrames = g.NavCursorHideFrames - 1
if g.NavCursorHideFrames == 0 then
g.NavCursorVisible = true
end
end
local set_mouse_pos = false
if g.NavMousePosDirty and g.NavIdIsAlive then
if g.NavCursorVisible and g.NavHighlightItemUnderNav and g.NavWindow then
set_mouse_pos = true
end
end
g.NavMousePosDirty = false
IM_ASSERT(g.NavLayer == ImGuiNavLayer.Main or g.NavLayer == ImGuiNavLayer.Menu)
if g.NavWindow then
ImGui.NavSaveLastChildNavWindowIntoParent(g.NavWindow)
end
if g.NavWindow and g.NavWindow.NavLastChildNavWindow ~= nil and g.NavLayer == ImGuiNavLayer.Main then
g.NavWindow.NavLastChildNavWindow = nil
end
ImGui.NavUpdateWindowing()
io.NavActive = (nav_keyboard_active or nav_gamepad_active) and g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0
io.NavVisible = (io.NavActive and g.NavId ~= 0 and g.NavCursorVisible) or (g.NavWindowingTarget ~= nil)
ImGui.NavUpdateCancelRequest()
ImGui.NavUpdateContextMenuRequest()
g.NavActivateId = 0
g.NavActivateDownId = 0
g.NavActivatePressedId = 0
g.NavActivateFlags = ImGuiActivateFlags.None
if g.NavId ~= 0 and g.NavCursorVisible and not g.NavWindowingTarget and g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then
local activate_down = (nav_keyboard_active and ImGui.IsKeyDown(ImGuiKey.Space, ImGuiKeyOwner_NoOwner)) or (nav_gamepad_active and ImGui.IsKeyDown(ImGuiKey.NavGamepadActivate, ImGuiKeyOwner_NoOwner))
local activate_pressed = activate_down and ((nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.Space, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner)) or (nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.NavGamepadActivate, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner)))
local input_pressed_keyboard = nav_keyboard_active and (ImGui.IsKeyPressedEx(ImGuiKey.Enter, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) or ImGui.IsKeyPressedEx(ImGuiKey.KeypadEnter, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner))
local input_pressed_gamepad = false
if activate_down and nav_gamepad_active and ImGui.IsKeyDown(ImGuiKey.NavGamepadActivate, ImGuiKeyOwner_NoOwner) and bit32.band(g.NavIdItemFlags, ImGuiItemFlags.Inputable) ~= 0 then
if ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate).DownDurationPrev < NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY and ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate).DownDuration >= NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY then
input_pressed_gamepad = true
end
end
if g.ActiveId == 0 and activate_pressed then
g.NavActivateId = g.NavId
g.NavActivateFlags = ImGuiActivateFlags.PreferTweak
end
if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (input_pressed_keyboard or input_pressed_gamepad) then
g.NavActivateId = g.NavId
g.NavActivateFlags = ImGuiActivateFlags.PreferInput
end
if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_down or input_pressed_keyboard or input_pressed_gamepad) then
g.NavActivateDownId = g.NavId
end
if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_pressed or input_pressed_keyboard or input_pressed_gamepad) then
g.NavActivatePressedId = g.NavId
ImGui.NavHighlightActivated(g.NavId)
end
end
if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) ~= 0 then
g.NavCursorVisible = false
elseif g.IO.ConfigNavCursorVisibleAlways and g.NavCursorHideFrames == 0 then
g.NavCursorVisible = true
end
if g.NavActivateId ~= 0 then
IM_ASSERT(g.NavActivateDownId == g.NavActivateId)
end
if g.NavHighlightActivatedTimer > 0.0 then
g.NavHighlightActivatedTimer = ImMax(0.0, g.NavHighlightActivatedTimer - io.DeltaTime)
end
if g.NavHighlightActivatedTimer == 0.0 then
g.NavHighlightActivatedId = 0
end
if g.NavNextActivateId ~= 0 then
g.NavActivateId = g.NavNextActivateId
g.NavActivateDownId = g.NavNextActivateId
g.NavActivatePressedId = g.NavNextActivateId
g.NavActivateFlags = g.NavNextActivateFlags
end
g.NavNextActivateId = 0
ImGui.NavUpdateCreateMoveRequest()
if g.NavMoveDir == ImGuiDir.None then
ImGui.NavUpdateCreateTabbingRequest()
end
ImGui.NavUpdateAnyRequestFlag()
g.NavIdIsAlive = false
if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 and not g.NavWindowingTarget then
local window = g.NavWindow
local scroll_speed = IM_ROUND(window.FontRefSize * 100 * io.DeltaTime)
local move_dir = g.NavMoveDir
if window.DC.NavLayersActiveMask == 0x00 and window.DC.NavWindowHasScrollY and move_dir ~= ImGuiDir.None then
if move_dir == ImGuiDir.Left or move_dir == ImGuiDir.Right then
local delta = (move_dir == ImGuiDir.Left) and -1.0 or 1.0
ImGui.SetScrollX(window, ImTrunc(window.Scroll.x + delta * scroll_speed))
end
if move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down then
local delta = (move_dir == ImGuiDir.Up) and -1.0 or 1.0
ImGui.SetScrollY(window, ImTrunc(window.Scroll.y + delta * scroll_speed))
end
end
if nav_gamepad_active then
local scroll_dir = ImGui.GetKeyMagnitude2d(ImGuiKey.GamepadLStickLeft, ImGuiKey.GamepadLStickRight, ImGuiKey.GamepadLStickUp, ImGuiKey.GamepadLStickDown)
local tweak_factor = 1.0
if ImGui.IsKeyDown(ImGuiKey.NavGamepadTweakSlow) then
tweak_factor = 1.0 / 10.0
elseif ImGui.IsKeyDown(ImGuiKey.NavGamepadTweakFast) then
tweak_factor = 10.0
end
if scroll_dir.x ~= 0.0 and window.ScrollbarX then
ImGui.SetScrollX(window, ImTrunc(window.Scroll.x + scroll_dir.x * scroll_speed * tweak_factor))
end
if scroll_dir.y ~= 0.0 then
ImGui.SetScrollY(window, ImTrunc(window.Scroll.y + scroll_dir.y * scroll_speed * tweak_factor))
end
end
end
if not nav_keyboard_active and not nav_gamepad_active then
g.NavCursorVisible = false
g.NavHighlightItemUnderNav = false
set_mouse_pos = false
end
if set_mouse_pos and io.ConfigNavMoveSetMousePos and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasSetMousePos) ~= 0 then
ImGui.TeleportMousePos(ImGui.NavCalcPreferredRefPos(ImGuiWindowFlags.Popup))
end
g.NavScoringDebugCount = 0
end
end
function ImGui.NavUpdateCancelRequest()
local g = GImGui
local nav_gamepad_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0
local nav_keyboard_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0
if not (nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.Escape, 0, ImGuiKeyOwner_NoOwner)) and not (nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)) then
return
end
-- IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()")
if g.ActiveId ~= 0 then
ImGui.ClearActiveID()
elseif g.NavLayer ~= ImGuiNavLayer.Main then
ImGui.NavRestoreLayer(ImGuiNavLayer.Main)
ImGui.SetNavCursorVisibleAfterMove()
elseif g.NavWindow and g.NavWindow ~= g.NavWindow.RootWindow and bit32.band(g.NavWindow.RootWindowForNav.Flags, ImGuiWindowFlags.Popup) == 0 and g.NavWindow.RootWindowForNav.ParentWindow then
local child_window = g.NavWindow.RootWindowForNav
local parent_window = child_window.ParentWindow
IM_ASSERT(child_window.ChildId ~= 0)
ImGui.FocusWindow(parent_window)
ImGui.SetNavID(child_window.ChildId, ImGuiNavLayer.Main, 0, ImGui.WindowRectAbsToRel(parent_window, child_window:Rect()))
ImGui.SetNavCursorVisibleAfterMove()
elseif g.OpenPopupStack.Size > 0 and g.OpenPopupStack:back().Window ~= nil and bit32.band(g.OpenPopupStack:back().Window.Flags, ImGuiWindowFlags.Modal) == 0 then
ImGui.ClosePopupToLevel(g.OpenPopupStack.Size - 1, true)
else
if g.IO.ConfigNavEscapeClearFocusItem or g.IO.ConfigNavEscapeClearFocusWindow then
if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.Popup) ~= 0 then
g.NavWindow.NavLastIds[0] = 0
end
end
if g.IO.ConfigNavEscapeClearFocusItem or g.IO.ConfigNavEscapeClearFocusWindow then
g.NavId = 0
end
if g.IO.ConfigNavEscapeClearFocusWindow then
ImGui.FocusWindow(nil)
end
end
end
function ImGui.NavMoveRequestButNoResultYet()
local g = GImGui
return g.NavMoveScoringItems and g.NavMoveResultLocal.ID == 0 and g.NavMoveResultOther.ID == 0
end
local function ImGetDirQuadrantFromDelta(dx, dy)
if ImFabs(dx) > ImFabs(dy) then
return (dx > 0.0) and ImGuiDir.Right or ImGuiDir.Left
end
return (dy > 0.0) and ImGuiDir.Down or ImGuiDir.Up
end
local function NavScoreItemDistInterval(cand_min, cand_max, curr_min, curr_max)
if cand_max < curr_min then
return cand_max - curr_min
end
if curr_max < cand_min then
return cand_min - curr_max
end
return 0.0
end
--- @param result ImGuiNavItemData
--- @param nav_bb ImRect
--- @return bool
function ImGui.NavScoreItem(result, nav_bb)
local g = GImGui
local window = g.CurrentWindow
if g.NavLayer ~= window.DC.NavLayerCurrent then
return false
end
local cand = ImRect()
ImRect_Copy(cand, nav_bb)
local curr = g.NavScoringRect
g.NavScoringDebugCount = g.NavScoringDebugCount + 1
if window.ParentWindow == g.NavWindow then
IM_ASSERT(bit32.band(bit32.bor(window.ChildFlags, g.NavWindow.ChildFlags), ImGuiChildFlags.NavFlattened) ~= 0)
if not window.ClipRect:Overlaps(cand) then
return false
end
cand:ClipWithFull(window.ClipRect)
end
local dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x)
local dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2), ImLerp(cand.Min.y, cand.Max.y, 0.8), ImLerp(curr.Min.y, curr.Max.y, 0.2), ImLerp(curr.Min.y, curr.Max.y, 0.8))
if dby ~= 0.0 and dbx ~= 0.0 then
dbx = (dbx / 1000.0) + ((dbx > 0.0) and 1.0 or -1.0)
end
local dist_box = ImFabs(dbx) + ImFabs(dby)
local dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x)
local dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y)
local dist_center = ImFabs(dcx) + ImFabs(dcy)
local quadrant
local dax = 0.0
local day = 0.0
local dist_axial = 0.0
if dbx ~= 0.0 or dby ~= 0.0 then
dax = dbx
day = dby
dist_axial = dist_box
quadrant = ImGetDirQuadrantFromDelta(dbx, dby)
elseif dcx ~= 0.0 or dcy ~= 0.0 then
dax = dcx
day = dcy
dist_axial = dist_center
quadrant = ImGetDirQuadrantFromDelta(dcx, dcy)
else
quadrant = (g.LastItemData.ID < g.NavId) and ImGuiDir.Left or ImGuiDir.Right
end
local move_dir = g.NavMoveDir
local new_best = false
if quadrant == move_dir then
if dist_box < result.DistBox then
result.DistBox = dist_box
result.DistCenter = dist_center
return true
end
if dist_box == result.DistBox then
if dist_center < result.DistCenter then
result.DistCenter = dist_center
new_best = true
elseif dist_center == result.DistCenter then
if (((move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and dby) or dbx) < 0.0 then
new_best = true
end
end
end
end
if result.DistBox == FLT_MAX and dist_axial < result.DistAxial then
if g.NavLayer == ImGuiNavLayer.Menu and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.ChildMenu) == 0 then
if (move_dir == ImGuiDir.Left and dax < 0.0) or (move_dir == ImGuiDir.Right and dax > 0.0) or (move_dir == ImGuiDir.Up and day < 0.0) or (move_dir == ImGuiDir.Down and day > 0.0) then
result.DistAxial = dist_axial
new_best = true
end
end
end
return new_best
end
--- @param result ImGuiNavItemData
function ImGui.NavApplyItemToResult(result)
local g = GImGui
local window = g.CurrentWindow
result.Window = window
result.ID = g.LastItemData.ID
result.FocusScopeId = g.CurrentFocusScopeId
result.ItemFlags = g.LastItemData.ItemFlags
ImRect_Copy(result.RectRel, ImGui.WindowRectAbsToRel(window, g.LastItemData.NavRect))
if bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 then
IM_ASSERT(g.NextItemData.SelectionUserData ~= ImGuiSelectionUserData_Invalid)
result.SelectionUserData = g.NextItemData.SelectionUserData
end
end
--- @param result ImGuiNavItemData
function ImGui.NavMoveRequestResolveWithLastItem(result)
local g = GImGui
g.NavMoveScoringItems = false
ImGui.NavApplyItemToResult(result)
ImGui.NavUpdateAnyRequestFlag()
end
--- @param id ImGuiID
--- @param item_flags ImGuiItemFlags
--- @param move_flags ImGuiNavMoveFlags
function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags)
local g = GImGui
if bit32.band(move_flags, ImGuiNavMoveFlags.FocusApi) == 0 then
if g.NavLayer ~= g.CurrentWindow.DC.NavLayerCurrent then
return
end
if g.NavFocusScopeId ~= g.CurrentFocusScopeId then
return
end
end
local can_stop
if bit32.band(move_flags, ImGuiNavMoveFlags.FocusApi) ~= 0 then
can_stop = true
else
can_stop = bit32.band(item_flags, ImGuiItemFlags.NoTabStop) == 0 and (bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 or bit32.band(item_flags, ImGuiItemFlags.Inputable) ~= 0)
end
local result = g.NavMoveResultLocal
if g.NavTabbingDir == 1 then
if can_stop and g.NavTabbingResultFirst.ID == 0 then
ImGui.NavApplyItemToResult(g.NavTabbingResultFirst)
end
if can_stop and g.NavTabbingCounter > 0 then
g.NavTabbingCounter = g.NavTabbingCounter - 1
if g.NavTabbingCounter == 0 then
ImGui.NavMoveRequestResolveWithLastItem(result)
end
elseif g.NavId == id then
g.NavTabbingCounter = 1
end
elseif g.NavTabbingDir == -1 then
if g.NavId == id then
if result.ID ~= 0 then
g.NavMoveScoringItems = false
ImGui.NavUpdateAnyRequestFlag()
end
elseif can_stop then
ImGui.NavApplyItemToResult(result)
end
elseif g.NavTabbingDir == 0 then
if can_stop and g.NavId == id then
ImGui.NavMoveRequestResolveWithLastItem(result)
end
if can_stop and g.NavTabbingResultFirst.ID == 0 then
ImGui.NavApplyItemToResult(g.NavTabbingResultFirst)
end
end
end
function ImGui.NavProcessItem()
local g = GImGui
local window = g.CurrentWindow
local id = g.LastItemData.ID
local item_flags = g.LastItemData.ItemFlags
local nav_bb = ImRect()
ImRect_Copy(nav_bb, g.LastItemData.NavRect)
if window.DC.NavIsScrollPushableX == false then
nav_bb.Min.x = ImClamp(nav_bb.Min.x, window.ClipRect.Min.x, window.ClipRect.Max.x)
nav_bb.Max.x = ImClamp(nav_bb.Max.x, window.ClipRect.Min.x, window.ClipRect.Max.x)
end
if g.NavInitRequest and g.NavLayer == window.DC.NavLayerCurrent and bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then
local candidate_for_nav_default_focus = bit32.band(item_flags, ImGuiItemFlags.NoNavDefaultFocus) == 0
if candidate_for_nav_default_focus or g.NavInitResult.ID == 0 then
ImGui.NavApplyItemToResult(g.NavInitResult)
end
if candidate_for_nav_default_focus then
g.NavInitRequest = false
ImGui.NavUpdateAnyRequestFlag()
end
end
if g.NavMoveScoringItems and bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.FocusApi) ~= 0 or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then
local is_tabbing = bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0
if is_tabbing then
ImGui.NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags)
elseif g.NavId ~= id or bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AllowCurrentNavId) ~= 0 then
local result = (window == g.NavWindow) and g.NavMoveResultLocal or g.NavMoveResultOther
if ImGui.NavScoreItem(result, nav_bb) then
ImGui.NavApplyItemToResult(result)
end
local VISIBLE_RATIO = 0.70
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) ~= 0 then
local r = window.InnerRect
if r:Overlaps(nav_bb) then
if ImClamp(nav_bb.Max.y, r.Min.y, r.Max.y) - ImClamp(nav_bb.Min.y, r.Min.y, r.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO then
if ImGui.NavScoreItem(g.NavMoveResultLocalVisible, nav_bb) then
ImGui.NavApplyItemToResult(g.NavMoveResultLocalVisible)
end
end
end
end
end
end
end
if g.NavId == id then
if g.NavWindow ~= window then
ImGui.SetNavWindow(window)
end
g.NavLayer = window.DC.NavLayerCurrent
ImGui.SetNavFocusScope(g.CurrentFocusScopeId)
g.NavFocusScopeId = g.CurrentFocusScopeId
g.NavIdIsAlive = true
g.NavIdItemFlags = item_flags
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 then
IM_ASSERT(g.NextItemData.SelectionUserData ~= ImGuiSelectionUserData_Invalid)
g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData
end
window.NavRectRel[window.DC.NavLayerCurrent] = ImGui.WindowRectAbsToRel(window, nav_bb)
end
end
function ImGui.NavInitRequestApplyResult()
local g = GImGui
if not g.NavWindow then
return
end
local result = g.NavInitResult
if g.NavId ~= result.ID then
g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId
g.NavJustMovedToId = result.ID
g.NavJustMovedToFocusScopeId = result.FocusScopeId
g.NavJustMovedToKeyMods = 0
g.NavJustMovedToIsTabbing = false
g.NavJustMovedToHasSelectionData = bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0
end
ImGui.SetNavID(result.ID, g.NavLayer, result.FocusScopeId, result.RectRel)
g.NavIdIsAlive = true
if result.SelectionUserData ~= ImGuiSelectionUserData_Invalid then
g.NavLastValidSelectionUserData = result.SelectionUserData
end
if g.NavInitRequestFromMove then
ImGui.SetNavCursorVisibleAfterMove()
end
end
function ImGui.NavMoveRequestApplyResult()
local g = GImGui
local result
if g.NavMoveResultLocal.ID ~= 0 then
result = g.NavMoveResultLocal
elseif g.NavMoveResultOther.ID ~= 0 then
result = g.NavMoveResultOther
else
result = nil
end
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 and result == nil then
if (g.NavTabbingCounter == 1 or g.NavTabbingDir == 0) and g.NavTabbingResultFirst.ID ~= 0 then
result = g.NavTabbingResultFirst
end
end
local axis = (g.NavMoveDir == ImGuiDir.Up or g.NavMoveDir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X
if result == nil then
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then
g.NavMoveFlags = bit32.bor(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible)
end
if g.NavId ~= 0 and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible) == 0 then
ImGui.SetNavCursorVisibleAfterMove()
end
ImGui.NavClearPreferredPosForAxis(axis)
return
end
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) ~= 0
and g.NavMoveResultLocalVisible.ID ~= 0 and g.NavMoveResultLocalVisible.ID ~= g.NavId then
result = g.NavMoveResultLocalVisible
end
if result ~= g.NavMoveResultOther and g.NavMoveResultOther.ID ~= 0 and g.NavMoveResultOther.Window.ParentWindow == g.NavWindow then
if g.NavMoveResultOther.DistBox < result.DistBox
or (g.NavMoveResultOther.DistBox == result.DistBox and g.NavMoveResultOther.DistCenter < result.DistCenter) then
result = g.NavMoveResultOther
end
end
IM_ASSERT(g.NavWindow and result.Window)
if g.NavLayer == ImGuiNavLayer.Main then
local rect_abs = ImGui.WindowRectRelToAbs(result.Window, result.RectRel)
ImGui.ScrollToRectEx(result.Window, rect_abs, g.NavMoveScrollFlags)
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.ScrollToEdgeY) ~= 0 then
local scroll_target = (g.NavMoveDir == ImGuiDir.Up) and result.Window.ScrollMax.y or 0.0
ImGui.SetScrollY(result.Window, scroll_target)
end
end
if g.NavWindow ~= result.Window then
g.NavWindow = result.Window
g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid
end
if g.ActiveId ~= result.ID and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoClearActiveId) == 0 then
ImGui.ClearActiveID()
end
if (g.NavId ~= result.ID or bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsPageMove) ~= 0)
and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSelect) == 0 then
g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId
g.NavJustMovedToId = result.ID
g.NavJustMovedToFocusScopeId = result.FocusScopeId
g.NavJustMovedToKeyMods = g.NavMoveKeyMods
g.NavJustMovedToIsTabbing = bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0
g.NavJustMovedToHasSelectionData = bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0
end
local root_for_nav = g.NavWindow.RootWindowForNav
local preferred_scoring_pos_rel = ImVec2()
ImVec2_Copy(preferred_scoring_pos_rel, root_for_nav.NavPreferredScoringPosRel[g.NavLayer])
ImGui.SetNavID(result.ID, g.NavLayer, result.FocusScopeId, result.RectRel)
if result.SelectionUserData ~= ImGuiSelectionUserData_Invalid then
g.NavLastValidSelectionUserData = result.SelectionUserData
end
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) == 0 then
preferred_scoring_pos_rel[axis] = result.RectRel:GetCenter()[axis]
ImVec2_Copy(root_for_nav.NavPreferredScoringPosRel[g.NavLayer], preferred_scoring_pos_rel)
end
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0
and bit32.band(result.ItemFlags, ImGuiItemFlags.Inputable) == 0 then
g.NavMoveFlags = bit32.band(g.NavMoveFlags, bit32.bnot(ImGuiNavMoveFlags.Activate))
end
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Activate) ~= 0 then
g.NavNextActivateId = result.ID
g.NavNextActivateFlags = ImGuiActivateFlags.None
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.FocusApi) ~= 0 then
g.NavNextActivateFlags = bit32.bor(g.NavNextActivateFlags, ImGuiActivateFlags.FromFocusApi)
end
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then
g.NavNextActivateFlags = bit32.bor(g.NavNextActivateFlags, ImGuiActivateFlags.PreferInput, ImGuiActivateFlags.TryToPreserveState, ImGuiActivateFlags.FromTabbing)
end
end
if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible) == 0 then
ImGui.SetNavCursorVisibleAfterMove()
end
end
function ImGui.NavUpdateCurrentWindowIsScrollPushableX()
local g = GImGui
local window = g.CurrentWindow
window.DC.NavIsScrollPushableX = (g.CurrentTable == nil and window.DC.CurrentColumns == nil)
end
--- @param result ImGuiNavItemData
--- @param tree_node_data ImGuiTreeNodeStackData
function ImGui.NavMoveRequestResolveWithPastTreeNode(result, tree_node_data)
local g = GImGui
g.NavMoveScoringItems = false
g.LastItemData.ID = tree_node_data.ID
g.LastItemData.ItemFlags = bit32.band(tree_node_data.ItemFlags, bit32.bnot(ImGuiItemFlags.HasSelectionUserData))
ImRect_Copy(g.LastItemData.NavRect, tree_node_data.NavRect)
ImGui.NavApplyItemToResult(result)
ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y)
ImGui.NavUpdateAnyRequestFlag()
end
function ImGui.NavMoveRequestCancel()
local g = GImGui
g.NavMoveSubmitted = false
g.NavMoveScoringItems = false
ImGui.NavUpdateAnyRequestFlag()
end
--- @param move_dir ImGuiDir
--- @param clip_dir ImGuiDir
--- @param move_flags ImGuiNavMoveFlags
--- @param scroll_flags ImGuiScrollFlags
function ImGui.NavMoveRequestForward(move_dir, clip_dir, move_flags, scroll_flags)
local g = GImGui
IM_ASSERT(g.NavMoveForwardToNextFrame == false)
ImGui.NavMoveRequestCancel()
g.NavMoveForwardToNextFrame = true
g.NavMoveDir = move_dir
g.NavMoveClipDir = clip_dir
g.NavMoveFlags = bit32.bor(move_flags, ImGuiNavMoveFlags.Forwarded)
g.NavMoveScrollFlags = scroll_flags
end
--- @param window ImGuiWindow
--- @param wrap_flags ImGuiNavMoveFlags
function ImGui.NavMoveRequestTryWrapping(window, wrap_flags)
local g = GImGui
IM_ASSERT(bit32.band(wrap_flags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(wrap_flags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)) == 0)
if g.NavWindow == window and g.NavMoveScoringItems and g.NavLayer == window.DC.NavLayerCurrent then
g.NavMoveFlags = bit32.bor(bit32.band(g.NavMoveFlags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)), wrap_flags)
end
end
---------------------------------------------------------------------------------------
-- [SECTION] DRAG AND DROP
---------------------------------------------------------------------------------------
function ImGui.IsDragDropPayloadBeingAccepted()
local g = GImGui
return g.DragDropActive and g.DragDropAcceptIdPrev ~= 0
end
---------------------------------------------------------------------------------------
-- [SECTION] LOCALIZATION
---------------------------------------------------------------------------------------
--- @param entries ImGuiLocEntry[]
--- @param count int
function ImGui.LocalizeRegisterEntries(entries, count)
local g = GImGui
for n = 1, count do
g.LocalizationTable[entries[n].Key] = entries[n].Text
end
end
---------------------------------------------------------------------------------------
-- [SECTION] VIEWPORTS, PLATFORM WINDOWS
---------------------------------------------------------------------------------------
function MT.ImGuiViewport:GetDebugName()
local viewport = self
return viewport.Window and viewport.Window.Name or "n/a"
end
function MT.ImGuiPlatformIO:ClearPlatformHandlers()
self.Platform_GetClipboardTextFn = nil; self.Platform_SetClipboardTextFn = nil
self.Platform_ClipboardUserData = nil
self.Platform_OpenInShellFn = nil; self.Platform_OpenInShellUserData = nil
self.Platform_SetImeDataFn = nil; self.Platform_ImeUserData = nil
self.Platform_CreateWindow = nil; self.Platform_DestroyWindow = nil; self.Platform_ShowWindow = nil
self.Platform_SetWindowPos = nil; self.Platform_SetWindowSize = nil
self.Platform_GetWindowPos = nil; self.Platform_GetWindowSize = nil; self.Platform_GetWindowFramebufferScale = nil
self.Platform_SetWindowFocus = nil; self.Platform_GetWindowFocus = nil; self.Platform_GetWindowMinimized = nil
self.Platform_SetWindowTitle = nil; self.Platform_SetWindowAlpha = nil; self.Platform_UpdateWindow = nil
self.Platform_RenderWindow = nil; self.Platform_SwapBuffers = nil; self.Platform_GetWindowDpiScale = nil
self.Platform_OnChangedViewport = nil; self.Platform_GetWindowWorkAreaInsets = nil; self.Platform_CreateVkSurface = nil
end
function MT.ImGuiPlatformIO:ClearRendererHandlers()
self.Renderer_TextureMaxWidth = 0; self.Renderer_TextureMaxHeight = 0
self.Renderer_RenderState = nil
self.Renderer_CreateWindow = nil; self.Renderer_DestroyWindow = nil
self.Renderer_SetWindowSize = nil
self.Renderer_RenderWindow = nil; self.Renderer_SwapBuffers = nil
end
--- @return ImGuiViewport
function ImGui.GetMainViewport()
local g = GImGui
return g.Viewports[1]
end
--- @param viewport_id ImGuiID
--- @return ImGuiViewport?
function ImGui.FindViewportByID(viewport_id)
local g = GImGui
for _, viewport in g.Viewports:iter() do
if viewport.ID == viewport_id then
return viewport
end
end
return nil
end
--- @param current_window? ImGuiWindow
--- @param viewport? ImGuiViewportP
function ImGui.SetCurrentViewport(current_window, viewport)
local g = GImGui
if viewport then
viewport.LastFrameActive = g.FrameCount
end
if g.CurrentViewport == viewport then
return
end
g.CurrentDpiScale = viewport and viewport.DpiScale or 1.0
g.CurrentViewport = viewport
IM_ASSERT(g.CurrentDpiScale > 0.0 and g.CurrentDpiScale < 99.0) -- Typical correct values would be between 1.0f and 4.0f
-- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X", current_window and current_window.Name or "NULL", viewport and viewport.ID or 0)
if g.IO.ConfigDpiScaleFonts then
g.Style.FontScaleDpi = g.CurrentDpiScale
end
-- Notify platform layer of viewport changes
-- FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
if g.CurrentViewport and g.PlatformIO.Platform_OnChangedViewport then
g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport)
end
end
--- @param window ImGuiWindow
--- @param viewport ImGuiViewportP
function ImGui.SetWindowViewport(window, viewport)
-- Abandon viewport
if window.ViewportOwned and window.Viewport.Window == window then
window.Viewport.Size = ImVec2(0.0, 0.0)
end
window.Viewport = viewport
window.ViewportId = viewport.ID
window.ViewportOwned = (viewport.Window == window)
end
--- @param window ImGuiWindow
--- @return bool
function ImGui.GetWindowAlwaysWantOwnViewport(window)
-- Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
local g = GImGui
if g.IO.ConfigViewportsNoAutoMerge or (bit32.band(window.WindowClass.ViewportFlagsOverrideSet, ImGuiViewportFlags.NoAutoMerge) ~= 0) then
if bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) ~= 0 then
if not window.DockIsActive then
if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.ChildMenu, ImGuiWindowFlags.Tooltip)) == 0 then
if bit32.band(window.Flags, ImGuiWindowFlags.Popup) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.Modal) ~= 0 then
return true
end
end
end
end
end
return false
end
--- Heuristic, see #8948: depends on how backends handle OS-level parenting.
--- Due to how parent viewport stack is layed out, note that IsViewportAbove(a,b) isn't always the same as !IsViewportAbove(b,a).
--- @param potential_above ImGuiViewportP
--- @param potential_below ImGuiViewportP
--- @return bool
function ImGui.IsViewportAbove(potential_above, potential_below)
-- If ImGuiBackendFlags.HasParentViewport if set, ->ParentViewport chain should be accurate.
local g = GImGui
if bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasParentViewport) ~= 0 then
local v = potential_above --[[@as ImGuiViewport]]
while v ~= nil and v.ParentViewport do
if v.ParentViewport == potential_below then
return true
end
v = v.ParentViewport
end
else
if potential_above.ParentViewport == potential_below then
return true
end
end
if potential_above.LastFocusedStampCount > potential_below.LastFocusedStampCount then
return true
end
return false
end
--- @param window ImGuiWindow
--- @param viewport_dst ImGuiViewportP
function ImGui.UpdateTryMergeWindowIntoHostViewport(window, viewport_dst)
local g = GImGui
IM_ASSERT(window == window.RootWindowDockTree)
local viewport_src = window.Viewport -- Current viewport
if viewport_src == viewport_dst then
return false
end
if bit32.band(viewport_dst.Flags, ImGuiViewportFlags.CanHostOtherWindows) == 0 then
return false
end
if bit32.band(viewport_dst.Flags, ImGuiViewportFlags.IsMinimized) ~= 0 then
return false
end
if not viewport_dst:GetMainRect():Contains(window:Rect()) then
return false
end
if ImGui.GetWindowAlwaysWantOwnViewport(window) then
return false
end
for _, viewport_obstructing in g.Viewports:iter() do
repeat
if viewport_obstructing == viewport_src or viewport_obstructing == viewport_dst or not viewport_obstructing.PlatformWindowCreated then
break
end
if viewport_obstructing:GetMainRect():Overlaps(window:Rect()) then
if ImGui.IsViewportAbove(viewport_obstructing, viewport_dst) then
if viewport_src == nil or ImGui.IsViewportAbove(viewport_src, viewport_obstructing) then
return false -- viewport_obstructing is between viewport_src and viewport_dst -> Cannot merge.
end
end
end
until true
end
-- Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' merge into Viewport 0X%08X", window.Name, viewport_dst.ID)
if window.ViewportOwned then
for n = 1, g.Windows.Size do
if g.Windows.Data[n].Viewport == viewport_src then
ImGui.SetWindowViewport(g.Windows.Data[n], viewport_dst)
end
end
end
ImGui.SetWindowViewport(window, viewport_dst)
if bit32.band(window.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then
ImGui.BringWindowToDisplayFront(window)
end
return true
end
-- FIXME: handle 0 to N host viewports
--- @param window ImGuiWindow
--- @return bool
function ImGui.UpdateTryMergeWindowIntoHostViewports(window)
local g = GImGui
return ImGui.UpdateTryMergeWindowIntoHostViewport(window, g.Viewports.Data[1])
end
--- Translate Dear ImGui windows when a Host Viewport has been moved
--- (This additionally keeps windows at the same place when ImGuiConfigFlags.ViewportsEnable is toggled!)
--- @param viewport ImGuiViewportP
--- @param old_pos ImVec2
--- @param new_pos ImVec2
--- @param old_size ImVec2
--- @param new_size ImVec2
function ImGui.TranslateWindowsInViewport(viewport, old_pos, new_pos, old_size, new_size)
local g = GImGui
-- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] TranslateWindowsInViewport 0x%08X", viewport.ID)
IM_ASSERT(viewport.Window == nil and (bit32.band(viewport.Flags, ImGuiViewportFlags.CanHostOtherWindows) ~= 0))
-- 1) We test if ImGuiConfigFlags.ViewportsEnable was just toggled, which allows us to conveniently
-- translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
-- 2) If it's not going to fit into the new size, keep it at same absolute position.
-- One problem with this is that most Win32 applications doesn't update their render while dragging,
-- and so the window will appear to teleport when releasing the mouse.
local translate_all_windows = (bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) ~= bit32.band(g.ConfigFlagsLastFrame, ImGuiConfigFlags.ViewportsEnable))
local test_still_fit_rect = ImRect(old_pos, old_pos + old_size)
local delta_pos = new_pos - old_pos
for _, window in g.Windows:iter() do -- FIXME-OPT
if translate_all_windows or (window.Viewport == viewport and (old_size == new_size or test_still_fit_rect:Contains(window:Rect()))) then
ImGui.TranslateWindow(window, delta_pos)
end
end
end
-- If the backend doesn't support ImGuiBackendFlags_HasMouseHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs for it, we do a search ourselves.
-- A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
-- B) It requires Platform_GetWindowFocus to be implemented by backend.
--- @param mouse_platform_pos ImVec2
--- @return ImGuiViewportP?
function ImGui.FindHoveredViewportFromPlatformWindowStack(mouse_platform_pos)
local g = GImGui
local best_candidate = nil
for _, viewport in g.Viewports:iter() do
if bit32.band(viewport.Flags, bit32.bor(ImGuiViewportFlags.NoInputs, ImGuiViewportFlags.IsMinimized)) == 0 and viewport:GetMainRect():Contains(mouse_platform_pos) then
if best_candidate == nil or best_candidate.LastFocusedStampCount < viewport.LastFocusedStampCount then
if viewport.PlatformWindowCreated then
best_candidate = viewport
end
end
end
end
return best_candidate
end
function ImGui.UpdateViewportsNewFrame()
local g = GImGui
IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size)
-- Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
-- Update Focused status
local viewports_enabled = (bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) ~= 0)
if viewports_enabled then
local focused_viewport = nil
for i = 1, g.Viewports.Size do
local viewport = g.Viewports.Data[i]
local platform_funcs_available = viewport.PlatformWindowCreated
if g.PlatformIO.Platform_GetWindowMinimized and platform_funcs_available then
local is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport)
if is_minimized then
viewport.Flags = bit32.bor(viewport.Flags, ImGuiViewportFlags.IsMinimized)
else
viewport.Flags = bit32.band(viewport.Flags, bit32.bnot(ImGuiViewportFlags.IsMinimized))
end
end
-- Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
-- When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
if g.PlatformIO.Platform_GetWindowFocus and platform_funcs_available then
local is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport)
if is_focused then
viewport.Flags = bit32.bor(viewport.Flags, ImGuiViewportFlags.IsFocused)
else
viewport.Flags = bit32.band(viewport.Flags, bit32.bnot(ImGuiViewportFlags.IsFocused))
end
if is_focused then
focused_viewport = viewport
end
end
end
-- Focused viewport has changed?
if focused_viewport and g.PlatformLastFocusedViewportId ~= focused_viewport.ID then
IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X '%s', attempting to apply our focus.", g.PlatformLastFocusedViewportId, focused_viewport.ID, focused_viewport.Window and focused_viewport.Window.Name or "n/a")
local prev_focused_viewport = ImGui.FindViewportByID(g.PlatformLastFocusedViewportId)
local prev_focused_has_been_destroyed = (prev_focused_viewport == nil) or (not prev_focused_viewport.PlatformWindowCreated)
-- Store a tag so we can infer z-order easily from all our windows
-- We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
-- will keep the front most stamp instead of losing it back to their parent viewport.
if focused_viewport.LastFocusedStampCount ~= g.ViewportFocusedStampCount then
g.ViewportFocusedStampCount = g.ViewportFocusedStampCount + 1
focused_viewport.LastFocusedStampCount = g.ViewportFocusedStampCount
end
g.PlatformLastFocusedViewportId = focused_viewport.ID
-- Focus associated dear imgui window
-- - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
-- - if focus didn't happen because we destroyed another window (#6462)
-- FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window.Window ~= nil' case as well.
local apply_imgui_focus_on_focused_viewport = not ImGui.IsAnyMouseDown() and not prev_focused_has_been_destroyed
if apply_imgui_focus_on_focused_viewport and g.IO.ConfigViewportsPlatformFocusSetsImGuiFocus then
focused_viewport.LastFocusedHadNavWindow = focused_viewport.LastFocusedHadNavWindow or (g.NavWindow ~= nil and g.NavWindow.Viewport == focused_viewport) -- Update so a window changing viewport won't lose focus.
local focus_request_flags = bit32.bor(ImGuiFocusRequestFlags.UnlessBelowModal, ImGuiFocusRequestFlags.RestoreFocusedChild)
if focused_viewport.Window ~= nil then
ImGui.FocusWindow(focused_viewport.Window, focus_request_flags)
elseif focused_viewport.LastFocusedHadNavWindow then
ImGui.FocusTopMostWindowUnderOne(nil, nil, focused_viewport, focus_request_flags) -- Focus top most in viewport
else
ImGui.FocusWindow(nil, focus_request_flags) -- No window had focus last time viewport was focused
end
end
end
if focused_viewport then
focused_viewport.LastFocusedHadNavWindow = (g.NavWindow ~= nil) and (g.NavWindow.Viewport == focused_viewport)
end
end
-- Create/update main viewport with current platform position.
-- FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
local main_viewport = g.Viewports.Data[1]
IM_ASSERT(main_viewport.ID == IMGUI_VIEWPORT_DEFAULT_ID)
IM_ASSERT(main_viewport.Window == nil)
local main_viewport_pos
if viewports_enabled then
main_viewport_pos = g.PlatformIO.Platform_GetWindowPos(main_viewport)
else
main_viewport_pos = ImVec2(0.0, 0.0)
end
local main_viewport_size = g.IO.DisplaySize
local main_viewport_framebuffer_scale = g.IO.DisplayFramebufferScale
if viewports_enabled and (bit32.band(main_viewport.Flags, ImGuiViewportFlags.IsMinimized) ~= 0) then
ImVec2_Copy(main_viewport_pos, main_viewport.Pos) -- Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
ImVec2_Copy(main_viewport_size, main_viewport.Size)
main_viewport_framebuffer_scale = main_viewport.FramebufferScale
end
ImGui.AddUpdateViewport(nil, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, bit32.bor(ImGuiViewportFlags.OwnedByApp, ImGuiViewportFlags.CanHostOtherWindows))
local memory_compact_start_time = (g.GcCompactAll or g.IO.ConfigMemoryCompactTimer < 0.0) and FLT_MAX or (g.Time - g.IO.ConfigMemoryCompactTimer)
g.CurrentDpiScale = 0.0
g.CurrentViewport = nil
g.MouseViewport = nil
local n = 1
while n <= g.Viewports.Size do
local viewport = g.Viewports.Data[n]
viewport.Idx = n
-- Erase unused viewports
if n > 1 and viewport.LastFrameActive < g.FrameCount - 2 then
ImGui.DestroyViewport(viewport)
-- n stays the same because we removed an element
else
local platform_funcs_available = viewport.PlatformWindowCreated
if viewports_enabled then
-- Update Position and Size (from Platform Window to ImGui) if requested.
-- We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
if (bit32.band(viewport.Flags, ImGuiViewportFlags.IsMinimized) == 0) and platform_funcs_available then
-- Viewport->WorkPos and WorkSize will be updated below
if viewport.PlatformRequestMove then
ImVec2_Copy(viewport.Pos, g.PlatformIO.Platform_GetWindowPos(viewport))
ImVec2_Copy(viewport.LastPlatformPos, viewport.Pos)
end
if viewport.PlatformRequestResize then
viewport.Size = g.PlatformIO.Platform_GetWindowSize(viewport)
ImVec2_Copy(viewport.LastPlatformSize, viewport.Size)
end
if g.PlatformIO.Platform_GetWindowFramebufferScale ~= nil then
viewport.FramebufferScale = g.PlatformIO.Platform_GetWindowFramebufferScale(viewport)
end
end
end
-- Update/copy monitor info
ImGui.UpdateViewportPlatformMonitor(viewport)
-- Lock down space taken by menu bars and status bars + query initial insets from backend
-- Setup initial value for functions like BeginMainMenuBar(), DockSpaceOverViewport() etc.
viewport.WorkInsetMin = viewport.BuildWorkInsetMin
viewport.WorkInsetMax = viewport.BuildWorkInsetMax
viewport.BuildWorkInsetMin = ImVec2(0.0, 0.0)
viewport.BuildWorkInsetMax = ImVec2(0.0, 0.0)
if g.PlatformIO.Platform_GetWindowWorkAreaInsets ~= nil and platform_funcs_available then
local insets = g.PlatformIO.Platform_GetWindowWorkAreaInsets(viewport)
IM_ASSERT(insets.x >= 0.0 and insets.y >= 0.0 and insets.z >= 0.0 and insets.w >= 0.0)
viewport.BuildWorkInsetMin = ImVec2(insets.x, insets.y)
viewport.BuildWorkInsetMax = ImVec2(insets.z, insets.w)
end
viewport:UpdateWorkRect()
for dl_n = 1, 2 do -- IM_COUNTOF(viewport->BgFgDrawLists)
if viewport.BgFgDrawListsLastTimeActive[dl_n] < memory_compact_start_time and viewport.BgFgDrawLists[dl_n] ~= nil then
IM_DELETE(viewport.BgFgDrawLists, dl_n)
end
end
-- Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
viewport.Alpha = 1.0
-- Translate Dear ImGui windows when a Host Viewport has been moved
-- (This additionally keeps windows at the same place when ImGuiConfigFlags.ViewportsEnable is toggled!)
local viewport_delta_pos = viewport.Pos - viewport.LastPos
if (bit32.band(viewport.Flags, ImGuiViewportFlags.CanHostOtherWindows) ~= 0) and (viewport_delta_pos.x ~= 0.0 or viewport_delta_pos.y ~= 0.0) then
ImGui.TranslateWindowsInViewport(viewport, viewport.LastPos, viewport.Pos, viewport.LastSize, viewport.Size)
end
-- Update DPI scale
local new_dpi_scale
if g.PlatformIO.Platform_GetWindowDpiScale and platform_funcs_available then
new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport)
elseif viewport.PlatformMonitor ~= -1 then
new_dpi_scale = g.PlatformIO.Monitors.Data[viewport.PlatformMonitor].DpiScale
else
new_dpi_scale = (viewport.DpiScale ~= 0.0) and viewport.DpiScale or 1.0
end
IM_ASSERT(new_dpi_scale > 0.0 and new_dpi_scale < 99.0) -- Typical correct values would be between 1.0f and 4.0f
if viewport.DpiScale ~= 0.0 and new_dpi_scale ~= viewport.DpiScale then
local scale_factor = new_dpi_scale / viewport.DpiScale
if g.IO.ConfigDpiScaleViewports then
ImGui.ScaleWindowsInViewport(viewport, scale_factor)
end
-- if viewport == ImGui.GetMainViewport() then
-- g.PlatformInterface.SetWindowSize(viewport, viewport.Size * scale_factor)
-- end
-- Scale our window moving pivot so that the window will rescale roughly around the mouse position.
-- FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
-- (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
-- if g.MovingWindow ~= nil and g.MovingWindow.Viewport == viewport then
-- g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor)
-- end
end
viewport.DpiScale = new_dpi_scale
n = n + 1
end
end
-- Update fallback monitor
g.PlatformMonitorsFullWorkRect = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX)
if g.PlatformIO.Monitors.Size == 0 then
local monitor = g.FallbackMonitor
ImVec2_Copy(monitor.MainPos, main_viewport.Pos)
ImVec2_Copy(monitor.MainSize, main_viewport.Size)
ImVec2_Copy(monitor.WorkPos, main_viewport.WorkPos)
ImVec2_Copy(monitor.WorkSize, main_viewport.WorkSize)
monitor.DpiScale = main_viewport.DpiScale
g.PlatformMonitorsFullWorkRect:Add(monitor.WorkPos)
g.PlatformMonitorsFullWorkRect:Add(monitor.WorkPos + monitor.WorkSize)
else
g.FallbackMonitor = g.PlatformIO.Monitors.Data[1]
end
for i = 1, g.PlatformIO.Monitors.Size do
local monitor = g.PlatformIO.Monitors.Data[i]
g.PlatformMonitorsFullWorkRect:Add(monitor.WorkPos)
g.PlatformMonitorsFullWorkRect:Add(monitor.WorkPos + monitor.WorkSize)
end
if not viewports_enabled then
g.MouseViewport = main_viewport
return
end
-- Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
-- Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags.NoInputs flags set.
local viewport_hovered = nil
if bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasMouseHoveredViewport) ~= 0 then
viewport_hovered = g.IO.MouseHoveredViewport and ImGui.FindViewportByID(g.IO.MouseHoveredViewport) or nil
if viewport_hovered and (bit32.band(viewport_hovered.Flags, ImGuiViewportFlags.NoInputs) ~= 0) then
viewport_hovered = ImGui.FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos) -- Backend failed to handle _NoInputs viewport: revert to our fallback.
end
else
-- If the backend doesn't know how to honor ImGuiViewportFlags.NoInputs, we do a search ourselves. Note that this search:
-- A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
-- B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
-- C) uses LastFocusedStampCount as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
viewport_hovered = ImGui.FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos)
end
if viewport_hovered ~= nil then
g.MouseLastHoveredViewport = viewport_hovered
elseif g.MouseLastHoveredViewport == nil then
g.MouseLastHoveredViewport = g.Viewports.Data[1]
end
-- Update mouse reference viewport
-- (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
-- (MovingViewport->Viewport will be nil in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
if g.MovingWindow and g.MovingWindow.Viewport then
g.MouseViewport = g.MovingWindow.Viewport
else
g.MouseViewport = g.MouseLastHoveredViewport
end
-- When dragging something, always refer to the last hovered viewport.
-- - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
-- - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
-- - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
-- FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags.HasMouseHoveredViewport is set we want to trust when viewport_hovered==nil and use that.
local is_mouse_dragging_with_an_expected_destination = g.DragDropActive
if is_mouse_dragging_with_an_expected_destination and viewport_hovered == nil then
viewport_hovered = g.MouseLastHoveredViewport
end
if is_mouse_dragging_with_an_expected_destination or g.ActiveId == 0 or not ImGui.IsAnyMouseDown() then
if viewport_hovered ~= nil and viewport_hovered ~= g.MouseViewport and (bit32.band(viewport_hovered.Flags, ImGuiViewportFlags.NoInputs) == 0) then
g.MouseViewport = viewport_hovered
end
end
IM_ASSERT(g.MouseViewport ~= nil)
end
function ImGui.UpdateViewportsEndFrame()
local g = GImGui
g.PlatformIO.Viewports:resize(0)
for i = 1, g.Viewports.Size do
repeat
local viewport = g.Viewports.Data[i]
ImVec2_Copy(viewport.LastPos, ImVec2(viewport.Pos.x, viewport.Pos.y))
ImVec2_Copy(viewport.LastSize, ImVec2(viewport.Size.x, viewport.Size.y))
if (viewport.LastFrameActive < g.FrameCount or viewport.Size.x <= 0.0 or viewport.Size.y <= 0.0) and (i > 1) then
break
end
if viewport.Window and not ImGui.IsWindowActiveAndVisible(viewport.Window) then
break
end
if i > 1 then
IM_ASSERT(viewport.Window ~= nil)
end
g.PlatformIO.Viewports:push_back(viewport)
until true
end
g.Viewports.Data[1]:ClearRequestFlags() -- Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
end
--- @param window? ImGuiWindow
--- @param id ImGuiID
--- @param pos ImVec2
--- @param size ImVec2
--- @param flags ImGuiViewportFlags
--- @return ImGuiViewportP
function ImGui.AddUpdateViewport(window, id, pos, size, flags)
local g = GImGui
IM_ASSERT(id ~= 0)
flags = bit32.bor(flags, ImGuiViewportFlags.IsPlatformWindow)
if window ~= nil then
local window_can_use_inputs = (bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs)) == 0)
if g.MovingWindow and g.MovingWindow.RootWindowDockTree == window then
flags = bit32.bor(flags, ImGuiViewportFlags.NoInputs, ImGuiViewportFlags.NoFocusOnAppearing)
end
if not window_can_use_inputs then
flags = bit32.bor(flags, ImGuiViewportFlags.NoInputs)
end
if bit32.band(window.Flags, ImGuiWindowFlags.NoFocusOnAppearing) ~= 0 then
flags = bit32.bor(flags, ImGuiViewportFlags.NoFocusOnAppearing)
end
end
local viewport = ImGui.FindViewportByID(id)
if viewport then
--- @cast viewport ImGuiViewportP
-- Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
local prev_pos = ImVec2(viewport.Pos.x, viewport.Pos.y)
local prev_size = ImVec2(viewport.Size.x, viewport.Size.y)
if not viewport.PlatformRequestMove or viewport.ID == IMGUI_VIEWPORT_DEFAULT_ID then
ImVec2_Copy(viewport.Pos, pos)
end
if not viewport.PlatformRequestResize or viewport.ID == IMGUI_VIEWPORT_DEFAULT_ID then
ImVec2_Copy(viewport.Size, size)
end
-- Preserve existing flags
viewport.Flags = bit32.bor(flags, bit32.band(viewport.Flags, bit32.bor(ImGuiViewportFlags.IsMinimized, ImGuiViewportFlags.IsFocused)))
if prev_pos.x ~= viewport.Pos.x or prev_pos.y ~= viewport.Pos.y or prev_size.x ~= viewport.Size.x or prev_size.y ~= viewport.Size.y then
ImGui.UpdateViewportPlatformMonitor(viewport)
end
else
-- New viewport
viewport = ImGuiViewportP()
viewport.ID = id
viewport.Idx = g.Viewports.Size
ImVec2_Copy(viewport.Pos, pos)
ImVec2_Copy(viewport.LastPos, pos)
ImVec2_Copy(viewport.Size, size)
ImVec2_Copy(viewport.LastSize, size)
viewport.Flags = flags
ImGui.UpdateViewportPlatformMonitor(viewport)
g.Viewports:push_back(viewport)
g.ViewportCreatedCount = g.ViewportCreatedCount + 1
IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'", id, window and window.Name or "<NULL>")
-- We assume the window becomes front-most (even when ImGuiViewportFlags.NoFocusOnAppearing is used).
-- This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
g.ViewportFocusedStampCount = g.ViewportFocusedStampCount + 1
viewport.LastFocusedStampCount = g.ViewportFocusedStampCount
-- We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
-- We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport.Pos.x)
g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport.Pos.y)
g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport.Pos.x + viewport.Size.x)
g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport.Pos.y + viewport.Size.y)
-- Store initial DpiScale before the OS platform window creation, based on expected monitor data.
-- This is so we can select an appropriate font size on the first frame of our window lifetime
viewport.DpiScale = ImGui.GetViewportPlatformMonitor(viewport).DpiScale
end
viewport.Window = window
viewport.LastFrameActive = g.FrameCount
viewport:UpdateWorkRect()
IM_ASSERT(window == nil or viewport.ID == window.ID)
if window ~= nil then
window.ViewportOwned = true
end
return viewport
end
--- @param viewport ImGuiViewportP
function ImGui.DestroyViewport(viewport)
-- Clear references to this viewport in windows (window->ViewportId becomes the master data)
local g = GImGui
for i = 1, g.Windows.Size do
local window = g.Windows.Data[i]
if window.Viewport == viewport then
window.Viewport = nil
window.ViewportOwned = false
end
end
if viewport == g.MouseLastHoveredViewport then
g.MouseLastHoveredViewport = nil
end
-- Destroy
IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'", viewport.ID, viewport.Window and viewport.Window.Name or "n/a")
ImGui.DestroyPlatformWindow(viewport) -- In most circumstances the platform window will already be destroyed here.
IM_ASSERT(not g.PlatformIO.Viewports:contains(viewport))
IM_ASSERT(g.Viewports.Data[viewport.Idx] == viewport)
g.Viewports:erase(viewport.Idx)
-- IM_DELETE(viewport)
end
--- @param window ImGuiWindow
function ImGui.WindowSelectViewport(window)
local g = GImGui
local flags = window.Flags
window.ViewportAllowPlatformMonitorExtend = -1
-- Restore main viewport if multi-viewport is not supported by the backend
local main_viewport = ImGui.GetMainViewport() --[[@as ImGuiViewportP]]
if bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) == 0 then
ImGui.SetWindowViewport(window, main_viewport)
return
end
window.ViewportOwned = false
-- Appearing popups reset their viewport so they can inherit again
if bit32.band(flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0 and window.Appearing then
window.Viewport = nil
window.ViewportId = 0
end
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasViewport) == 0 then
-- By default inherit from parent window
if window.Viewport == nil and window.ParentWindow and (not window.ParentWindow.IsFallbackWindow or window.ParentWindow.WasActive) then
window.Viewport = window.ParentWindow.Viewport
end
-- Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
if window.Viewport == nil and window.ViewportId ~= 0 then
window.Viewport = ImGui.FindViewportByID(window.ViewportId) --[[@as ImGuiViewportP]]
if window.Viewport == nil and window.ViewportPos.x ~= FLT_MAX and window.ViewportPos.y ~= FLT_MAX then
window.Viewport = ImGui.AddUpdateViewport(window, window.ID, window.ViewportPos, window.Size, ImGuiViewportFlags.None)
end
end
end
local lock_viewport = false
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasViewport) ~= 0 then
-- Code explicitly request a viewport
window.Viewport = ImGui.FindViewportByID(g.NextWindowData.ViewportId) --[[@as ImGuiViewportP]]
window.ViewportId = g.NextWindowData.ViewportId -- Store ID even if Viewport isn't resolved yet.
if window.Viewport and bit32.band(window.Flags, ImGuiWindowFlags.DockNodeHost) ~= 0 and window.Viewport.Window ~= nil then
window.Viewport.Window = window
window.Viewport.ID = window.ID
window.ViewportId = window.ID -- Overwrite ID (always owned by node)
end
lock_viewport = true
elseif bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 or bit32.band(flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
-- Always inherit viewport from parent window
if window.DockNode and window.DockNode.HostWindow then
IM_ASSERT(window.DockNode.HostWindow.Viewport == window.ParentWindow.Viewport)
end
window.Viewport = window.ParentWindow.Viewport
elseif window.DockNode and window.DockNode.HostWindow then
-- This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
window.Viewport = window.DockNode.HostWindow.Viewport
elseif bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0 then
window.Viewport = g.MouseViewport
elseif ImGui.GetWindowAlwaysWantOwnViewport(window) then
window.Viewport = ImGui.AddUpdateViewport(window, window.ID, window.Pos, window.Size, ImGuiViewportFlags.None)
elseif g.MovingWindow and g.MovingWindow.RootWindowDockTree == window and ImGui.IsMousePosValid() then
if window.Viewport ~= nil and window.Viewport.Window == window then
window.Viewport = ImGui.AddUpdateViewport(window, window.ID, window.Pos, window.Size, ImGuiViewportFlags.None)
end
else
-- Merge into host viewport?
-- We cannot test window->ViewportOwned as it set lower in the function.
-- Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
local try_to_merge_into_host_viewport = (window.Viewport and window == window.Viewport.Window and (g.ActiveId == 0 or g.ActiveIdAllowOverlap))
if try_to_merge_into_host_viewport then
ImGui.UpdateTryMergeWindowIntoHostViewports(window)
end
end
-- Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
if window.Viewport == nil then
--- @cast main_viewport ImGuiViewportP
if not ImGui.UpdateTryMergeWindowIntoHostViewport(window, main_viewport) then
window.Viewport = ImGui.AddUpdateViewport(window, window.ID, window.Pos, window.Size, ImGuiViewportFlags.None)
end
end
-- Mark window as allowed to protrude outside of its viewport and into the current monitor
if not lock_viewport then
if bit32.band(flags, bit32.bor(ImGuiWindowFlags.Tooltip, ImGuiWindowFlags.Popup)) ~= 0 then
-- We need to take account of the possibility that mouse may become invalid.
-- Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
local mouse_ref = bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0 and g.IO.MousePos or g.BeginPopupStack.Data[g.BeginPopupStack.Size].OpenMousePos
local use_mouse_ref = not g.NavCursorVisible or not g.NavHighlightItemUnderNav or not g.NavWindow
local mouse_valid = ImGui.IsMousePosValid(mouse_ref)
if (window.Appearing or bit32.band(flags, bit32.bor(ImGuiWindowFlags.Tooltip, ImGuiWindowFlags.ChildMenu)) ~= 0) and (not use_mouse_ref or mouse_valid) then
local pos_to_use = (use_mouse_ref and mouse_valid) and mouse_ref or ImGui.NavCalcPreferredRefPos(window.Flags)
window.ViewportAllowPlatformMonitorExtend = ImGui.FindPlatformMonitorForPos(pos_to_use)
else
window.ViewportAllowPlatformMonitorExtend = window.Viewport.PlatformMonitor
end
elseif window.Viewport and window ~= window.Viewport.Window and window.Viewport.Window and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0 and window.DockNode == nil then
-- When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
local will_be_visible = (window.DockIsActive and not window.DockTabIsVisible) and false or true
if bit32.band(window.Flags, ImGuiWindowFlags.DockNodeHost) ~= 0 and window.Viewport.LastFrameActive < g.FrameCount and will_be_visible then
-- Steal/transfer ownership
IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'", window.Name, window.Viewport.ID, window.Viewport.Window.Name)
window.Viewport.Window = window
window.Viewport.ID = window.ID
window.Viewport.LastNameHash = 0
elseif not ImGui.UpdateTryMergeWindowIntoHostViewports(window) then -- Merge?
-- New viewport
window.Viewport = ImGui.AddUpdateViewport(window, window.ID, window.Pos, window.Size, ImGuiViewportFlags.NoFocusOnAppearing)
end
elseif window.ViewportAllowPlatformMonitorExtend < 0 and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0 then
-- Regular (non-child, non-popup) windows by default are also allowed to protrude
-- Child windows are kept contained within their parent.
window.ViewportAllowPlatformMonitorExtend = window.Viewport.PlatformMonitor
end
end
-- Update flags
window.ViewportOwned = (window == window.Viewport.Window)
window.ViewportId = window.Viewport.ID
-- If the OS window has a title bar, hide our imgui title bar
-- if window.ViewportOwned and bit32.band(window.Viewport.Flags, ImGuiViewportFlags.NoDecoration) == 0 then
-- window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.NoTitleBar)
-- end
end
--- @param window ImGuiWindow
--- @param parent_window_in_stack? ImGuiWindow
function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack)
local g = GImGui
local viewport_rect_changed = false
-- Synchronize window --> viewport in most situations
-- Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
if window.Viewport.PlatformRequestMove then
ImVec2_Copy(window.Pos, window.Viewport.Pos)
-- ImGui.MarkIniSettingsDirty(window)
elseif window.Viewport.Pos.x ~= window.Pos.x or window.Viewport.Pos.y ~= window.Pos.y then
viewport_rect_changed = true
ImVec2_Copy(window.Viewport.Pos, window.Pos)
end
if window.Viewport.PlatformRequestResize then
ImVec2_Copy(window.Size, window.Viewport.Size)
ImVec2_Copy(window.SizeFull, window.Viewport.Size)
-- ImGui.MarkIniSettingsDirty(window)
elseif window.Viewport.Size.x ~= window.Size.x or window.Viewport.Size.y ~= window.Size.y then
viewport_rect_changed = true
ImVec2_Copy(window.Viewport.Size, window.Size)
end
window.Viewport:UpdateWorkRect()
-- The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
-- Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
if viewport_rect_changed then
ImGui.UpdateViewportPlatformMonitor(window.Viewport)
end
-- Update common viewport flags
local viewport_flags_to_clear = bit32.bor(ImGuiViewportFlags.TopMost, ImGuiViewportFlags.NoTaskBarIcon, ImGuiViewportFlags.NoDecoration, ImGuiViewportFlags.NoRendererClear)
local viewport_flags = bit32.band(window.Viewport.Flags, bit32.bnot(viewport_flags_to_clear))
local window_flags = window.Flags
local is_modal = bit32.band(window_flags, ImGuiWindowFlags.Modal) ~= 0
local is_short_lived_floating_window = bit32.band(window_flags, bit32.bor(ImGuiWindowFlags.ChildMenu, ImGuiWindowFlags.Tooltip, ImGuiWindowFlags.Popup)) ~= 0
if bit32.band(window_flags, ImGuiWindowFlags.Tooltip) ~= 0 then
viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.TopMost)
end
if (g.IO.ConfigViewportsNoTaskBarIcon or is_short_lived_floating_window) and not is_modal then
viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.NoTaskBarIcon)
end
if g.IO.ConfigViewportsNoDecoration or is_short_lived_floating_window then
viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.NoDecoration)
end
-- Not correct to set modal as topmost because:
-- - Because other popups can be stacked above a modal (e.g. combo box in a modal)
-- - ImGuiViewportFlags.TopMost is currently handled different in backends
-- if bit32.band(window_flags, ImGuiWindowFlags.Modal) ~= 0 then
-- viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.TopMost)
-- end
-- For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
-- won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
-- Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
-- but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
if is_short_lived_floating_window and not is_modal then
viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.NoFocusOnAppearing, ImGuiViewportFlags.NoFocusOnClick)
end
-- We can overwrite viewport flags using ImGuiWindowClass (advanced users)
if window.WindowClass.ViewportFlagsOverrideSet ~= 0 then
viewport_flags = bit32.bor(viewport_flags, window.WindowClass.ViewportFlagsOverrideSet)
end
if window.WindowClass.ViewportFlagsOverrideClear ~= 0 then
viewport_flags = bit32.band(viewport_flags, bit32.bnot(window.WindowClass.ViewportFlagsOverrideClear))
end
-- We can also tell the backend that clearing the platform window won't be necessary,
-- as our window background is filling the viewport and we have disabled BgAlpha.
-- FIXME: Work on support for per-viewport transparency (#2766)
if bit32.band(window_flags, ImGuiWindowFlags.NoBackground) == 0 then
viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.NoRendererClear)
end
window.Viewport.Flags = viewport_flags
-- Update parent viewport ID
-- (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
if window.WindowClass.ParentViewportId ~= 0xFFFFFFFF then
local old_parent_viewport_id = window.Viewport.ParentViewportId
window.Viewport.ParentViewportId = window.WindowClass.ParentViewportId
if window.Viewport.ParentViewportId ~= old_parent_viewport_id then
window.Viewport.ParentViewport = ImGui.FindViewportByID(window.Viewport.ParentViewportId) --[[@as ImGuiViewport]]
end
elseif bit32.band(window_flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0 and parent_window_in_stack and (not parent_window_in_stack.IsFallbackWindow or parent_window_in_stack.WasActive) then
window.Viewport.ParentViewport = parent_window_in_stack.Viewport
window.Viewport.ParentViewportId = parent_window_in_stack.Viewport.ID
else
if g.IO.ConfigViewportsNoDefaultParent then
window.Viewport.ParentViewport = nil
else
window.Viewport.ParentViewport = ImGui.GetMainViewport()
end
window.Viewport.ParentViewportId = g.IO.ConfigViewportsNoDefaultParent and 0 or IMGUI_VIEWPORT_DEFAULT_ID
end
end
function ImGui.UpdatePlatformWindows()
local g = GImGui
IM_ASSERT(g.FrameCountEnded == g.FrameCount, "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?")
IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount)
g.FrameCountPlatformEnded = g.FrameCount
if bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) == 0 then
return
end
-- Create/resize/destroy platform windows to match each active viewport.
-- Skip the main viewport (index 0), which is always fully handled by the application!
for i = 2, g.Viewports.Size do
repeat
local viewport = g.Viewports.Data[i]
-- Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
-- (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
local destroy_platform_window = false
destroy_platform_window = destroy_platform_window or (viewport.LastFrameActive < g.FrameCount - 1)
destroy_platform_window = destroy_platform_window or (viewport.Window and not ImGui.IsWindowActiveAndVisible(viewport.Window)) --[[@as bool]]
if destroy_platform_window then
ImGui.DestroyPlatformWindow(viewport)
break
end
-- New windows that appears directly in a new viewport won't always have a size on their first frame
if viewport.LastFrameActive < g.FrameCount or viewport.Size.x <= 0 or viewport.Size.y <= 0 then
break
end
-- Create window
local is_new_platform_window = not viewport.PlatformWindowCreated
if is_new_platform_window then
IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'", viewport.ID, viewport.Window and viewport.Window.Name or "n/a")
g.PlatformIO.Platform_CreateWindow(viewport)
if g.PlatformIO.Renderer_CreateWindow ~= nil then
g.PlatformIO.Renderer_CreateWindow(viewport)
end
g.PlatformWindowsCreatedCount = g.PlatformWindowsCreatedCount + 1
viewport.LastNameHash = 0
ImVec2_CopyV(viewport.LastPlatformPos, FLT_MAX, FLT_MAX)
ImVec2_CopyV(viewport.LastPlatformSize, FLT_MAX, FLT_MAX) -- By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
ImVec2_Copy(viewport.LastRendererSize, viewport.Size) -- We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
viewport.PlatformWindowCreated = true
end
-- Apply Position and Size (from ImGui to Platform/Renderer backends)
if (viewport.LastPlatformPos.x ~= viewport.Pos.x or viewport.LastPlatformPos.y ~= viewport.Pos.y) and not viewport.PlatformRequestMove then
g.PlatformIO.Platform_SetWindowPos(viewport, viewport.Pos)
end
if (viewport.LastPlatformSize.x ~= viewport.Size.x or viewport.LastPlatformSize.y ~= viewport.Size.y) and not viewport.PlatformRequestResize then
g.PlatformIO.Platform_SetWindowSize(viewport, viewport.Size)
end
if (viewport.LastRendererSize.x ~= viewport.Size.x or viewport.LastRendererSize.y ~= viewport.Size.y) and g.PlatformIO.Renderer_SetWindowSize ~= nil then
g.PlatformIO.Renderer_SetWindowSize(viewport, viewport.Size)
end
ImVec2_Copy(viewport.LastPlatformPos, viewport.Pos)
ImVec2_Copy(viewport.LastPlatformSize, viewport.Size)
ImVec2_Copy(viewport.LastRendererSize, viewport.Size)
-- Update title bar (if it changed)
local window_for_title = GetWindowForTitleDisplay(viewport.Window)
if window_for_title ~= nil then
local title = window_for_title.Name
local title_begin = 1
local title_end = ImGui.FindRenderedTextEnd(title)
local title_hash = ImHashStr(title, title_end - title_begin)
if viewport.LastNameHash ~= title_hash then
-- This still creates new strings
g.PlatformIO.Platform_SetWindowTitle(viewport, string.sub(title, title_begin, title_end - 1))
viewport.LastNameHash = title_hash
end
end
-- Update alpha (if it changed)
if viewport.LastAlpha ~= viewport.Alpha and g.PlatformIO.Platform_SetWindowAlpha ~= nil then
g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport.Alpha)
end
viewport.LastAlpha = viewport.Alpha
-- Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
if g.PlatformIO.Platform_UpdateWindow ~= nil then
g.PlatformIO.Platform_UpdateWindow(viewport)
end
if is_new_platform_window then
-- On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
if g.FrameCount < 3 then
viewport.Flags = bit32.bor(viewport.Flags, ImGuiViewportFlags.NoFocusOnAppearing)
end
-- Show window
g.PlatformIO.Platform_ShowWindow(viewport)
end
-- Clear request flags
viewport:ClearRequestFlags()
until true
end
end
-- This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
-- Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
-- The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
--
-- local platform_io = ImGui.GetPlatformIO()
-- for i = 2, platform_io.Viewports.Size do
-- if bit32.band(platform_io.Viewports.Data[i].Flags, ImGuiViewportFlags.IsMinimized) == 0 then
-- MyRenderFunction(platform_io.Viewports.Data[i], my_args)
-- end
-- end
-- for i = 2, platform_io.Viewports.Size do
-- if bit32.band(platform_io.Viewports.Data[i].Flags, ImGuiViewportFlags.IsMinimized) == 0 then
-- MySwapBufferFunction(platform_io.Viewports.Data[i], my_args)
-- end
-- end
--
function ImGui.RenderPlatformWindowsDefault(platform_render_arg, renderer_render_arg)
-- Skip the main viewport (index 1 in Lua), which is always fully handled by the application!
local platform_io = ImGui.GetPlatformIO()
-- First pass: render all windows
for i = 2, platform_io.Viewports.Size do
local viewport = platform_io.Viewports.Data[i]
if bit32.band(viewport.Flags, ImGuiViewportFlags.IsMinimized) == 0 then
if platform_io.Platform_RenderWindow then
platform_io.Platform_RenderWindow(viewport, platform_render_arg)
end
if platform_io.Renderer_RenderWindow then
platform_io.Renderer_RenderWindow(viewport, renderer_render_arg)
end
end
end
-- Second pass: swap buffers for all windows
for i = 2, platform_io.Viewports.Size do
local viewport = platform_io.Viewports.Data[i]
if bit32.band(viewport.Flags, ImGuiViewportFlags.IsMinimized) == 0 then
if platform_io.Platform_SwapBuffers then
platform_io.Platform_SwapBuffers(viewport, platform_render_arg)
end
if platform_io.Renderer_SwapBuffers then
platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg)
end
end
end
end
--- @param pos ImVec2
function ImGui.FindPlatformMonitorForPos(pos)
local g = GImGui
for monitor_n = 1, g.PlatformIO.Monitors.Size do
local monitor = g.PlatformIO.Monitors.Data[monitor_n]
if ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize):Contains(pos) then
return monitor_n
end
end
return -1
end
--- @param rect ImRect
--- @return int
function ImGui.FindPlatformMonitorForRect(rect)
local g = GImGui
local monitor_count = g.PlatformIO.Monitors.Size
if monitor_count <= 1 then
return monitor_count
end
-- Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
-- This is necessary for tooltips which always resize down to zero at first.
local surface_threshold = math.max(rect:GetWidth() * rect:GetHeight() * 0.5, 1.0)
local best_monitor_n = 1 -- Default to the first monitor as fallback
local best_monitor_surface = 0.001
for monitor_n = 1, g.PlatformIO.Monitors.Size do
if best_monitor_surface >= surface_threshold then
break
end
local monitor = g.PlatformIO.Monitors.Data[monitor_n]
local monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize)
if monitor_rect:Contains(rect) then
return monitor_n
end
local overlapping_rect = ImRect(rect.Min.x, rect.Min.y, rect.Max.x, rect.Max.y)
overlapping_rect:ClipWithFull(monitor_rect)
local overlapping_surface = overlapping_rect:GetWidth() * overlapping_rect:GetHeight()
if overlapping_surface > best_monitor_surface then
best_monitor_surface = overlapping_surface
best_monitor_n = monitor_n
end
end
return best_monitor_n
end
--- @param viewport ImGuiViewportP
function ImGui.UpdateViewportPlatformMonitor(viewport)
viewport.PlatformMonitor = ImGui.FindPlatformMonitorForRect(viewport:GetMainRect())
end
--- @param viewport_p ImGuiViewport
--- @return ImGuiPlatformMonitor
function ImGui.GetViewportPlatformMonitor(viewport_p)
local g = GImGui
local viewport = viewport_p --- @cast viewport ImGuiViewportP
local monitor_idx = viewport.PlatformMonitor
if monitor_idx >= 1 and monitor_idx <= g.PlatformIO.Monitors.Size then
return g.PlatformIO.Monitors.Data[monitor_idx]
end
return g.FallbackMonitor
end
--- @param viewport ImGuiViewportP
function ImGui.DestroyPlatformWindow(viewport)
local g = GImGui
if viewport.PlatformWindowCreated then
IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'", viewport.ID, viewport.Window and viewport.Window.Name or "n/a")
if g.PlatformIO.Renderer_DestroyWindow then
g.PlatformIO.Renderer_DestroyWindow(viewport)
end
if g.PlatformIO.Platform_DestroyWindow then
g.PlatformIO.Platform_DestroyWindow(viewport)
end
IM_ASSERT(viewport.RendererUserData == nil and viewport.PlatformUserData == nil)
-- Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
-- The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
if viewport.ID ~= IMGUI_VIEWPORT_DEFAULT_ID then
viewport.PlatformWindowCreated = false
end
else
IM_ASSERT(viewport.RendererUserData == nil and viewport.PlatformUserData == nil and viewport.PlatformHandle == nil)
end
viewport.RendererUserData = nil
viewport.PlatformUserData = nil
viewport.PlatformHandle = nil
viewport:ClearRequestFlags()
end
function ImGui.DestroyPlatformWindows()
local g = GImGui
for _, viewport in g.Viewports:iter() do
ImGui.DestroyPlatformWindow(viewport)
end
end
---------------------------------------------------------------------------------------
-- [SECTION] METRICS/DEBUGGER WINDOW
---------------------------------------------------------------------------------------
--- @param draw_list ImDrawList
--- @param viewport ImGuiViewport
--- @param bb ImRect
function ImGui.DebugRenderViewportThumbnail(draw_list, viewport, bb)
local g = GImGui
local window = g.CurrentWindow
local scale = bb:GetSize() / viewport.Size
local off = bb.Min - viewport.Pos * scale
local alpha_mul = (bit32.band(viewport.Flags, ImGuiViewportFlags.IsMinimized) ~= 0) and 0.30 or 1.00
window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.Border, alpha_mul * 0.40))
for _, thumb_window in g.Windows:iter() do
repeat
if not thumb_window.WasActive or bit32.band(thumb_window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then
break
end
if thumb_window.Viewport ~= viewport then
break
end
local thumb_r = thumb_window:Rect()
local title_r = thumb_window:TitleBarRect()
thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale))
title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r:GetHeight() * 3.0) * scale))
thumb_r:ClipWithFull(bb)
title_r:ClipWithFull(bb)
local window_is_focused = g.NavWindow and thumb_window.RootWindowForTitleBarHighlight == g.NavWindow.RootWindowForTitleBarHighlight
window.DrawList:AddRectFilled(thumb_r.Min, thumb_r.Max, ImGui.GetColorU32(ImGuiCol.WindowBg, alpha_mul))
window.DrawList:AddRectFilled(title_r.Min, title_r.Max, ImGui.GetColorU32(window_is_focused and ImGuiCol.TitleBgActive or ImGuiCol.TitleBg, alpha_mul))
window.DrawList:AddRect(thumb_r.Min, thumb_r.Max, ImGui.GetColorU32(ImGuiCol.Border, alpha_mul))
window.DrawList:AddText(g.Font, g.FontSize * 1.0, title_r.Min, ImGui.GetColorU32(ImGuiCol.Text, alpha_mul), thumb_window.Name, 1, ImGui.FindRenderedTextEnd(thumb_window.Name))
until true
end
draw_list:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.Border, alpha_mul))
if viewport.ID == g.DebugMetricsConfig.HighlightViewportID then
window.DrawList:AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255))
end
end
local function RenderViewportsThumbnails()
local g = GImGui
local window = g.CurrentWindow
local SCALE = 1.0 / 8.0
local bb_full = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX)
for _, monitor in g.PlatformIO.Monitors:iter() do
bb_full:Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize))
end
local p = window.DC.CursorPos
local off = p - bb_full.Min * SCALE
for _, monitor in g.PlatformIO.Monitors:iter() do
local monitor_draw_bb = ImRect(off + monitor.MainPos * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE)
window.DrawList:AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors:index_from_ptr(monitor)) and IM_COL32(255, 255, 0, 255) or ImGui.GetColorU32(ImGuiCol.Border), 4.0)
window.DrawList:AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui.GetColorU32(ImGuiCol.Border, 0.10), 4.0)
end
for _, viewport in g.Viewports:iter() do
local viewport_draw_bb = ImRect(off + viewport.Pos * SCALE, off + (viewport.Pos + viewport.Size) * SCALE)
ImGui.DebugRenderViewportThumbnail(window.DrawList, viewport, viewport_draw_bb)
end
ImGui.Dummy(bb_full:GetSize() * SCALE)
end
-- TODO:
--- @param open bool?
function ImGui.ShowMetricsWindow(open)
local g = GImGui
local ret
open, ret = ImGui.Begin("ImGui Sincerely Metrics/Debugger", open)
if not ret or ImGui.GetCurrentWindow().BeginCount > 1 then
ImGui.End()
return open
end
if ImGui.TreeNode(string.format("Viewports (%d)", g.Viewports.Size)) then
-- ImGui.SetNextItemOpen(true, ImGuiCond.Once)
if ImGui.TreeNode("Windows Minimap") then
RenderViewportsThumbnails()
ImGui.TreePop()
end
ImGui.TreePop()
end
if ImGui.TreeNode("Memory allocations") then
local info = g.DebugAllocInfo
ImGui.Text("%d current allocations", info.TotalAllocCount - info.TotalFreeCount)
ImGui.Text("Releasing selected unused buffers after: %.2f secs", g.IO.ConfigMemoryCompactTimer)
if ImGui.SmallButton("GC now") then
g.GcCompactAll = true
end
ImGui.Text("Recent frames with allocations:")
local buf_size = #info.LastEntriesBuf
for n = buf_size, 1, -1 do
local idx = (info.LastEntriesIdx - n + buf_size) % buf_size + 1
local entry = info.LastEntriesBuf[idx]
ImGui.BulletText("Frame %06d: %+3d ( %2d alloc, %2d free )", entry.FrameCount, entry.AllocCount - entry.FreeCount, entry.AllocCount, entry.FreeCount)
if n == 0 then
ImGui.SameLine()
ImGui.Text("<- %d frames ago", g.FrameCount - entry.FrameCount)
end
end
ImGui.TreePop()
end
ImGui.End()
return open
end
return true -- [Roblox] ModuleScripts must return exactly one value
end
__FILES['imgui_demo.lua'] = function()
--- ImGui Sincerely WIP
-- (Demo Code)
-- NOTE: Make sure to use fields with different names inside `static`!
local IM_MIN = math.min
local IM_MAX = math.max
local function IM_CLAMP(V, MN, MX) return (V < MN) and MN or (V > MX) and MX or V end
-- TODO: HelpMarker()
-- TODO: ImColor helpers?
--- @class ImGuiDemoWindowData
--- @return ImGuiDemoWindowData
--- @nodiscard
local function ImGuiDemoWindowData()
return {
ShowAppImageViewer = false,
ShowAppFullscreen = false,
ShowMetrics = false,
ShowStyleEditor = false,
}
end
--- @class ExampleImageViewerData
--- @return ExampleImageViewerData
--- @nodiscard
local function ExampleImageViewerData()
return {
ImageBgColor = IM_COL32(100, 100, 100, 255),
GridColor = IM_COL32(255, 255, 255, 100),
GridEnabled = true,
ViewReset = true,
ViewOffset = ImVec2(0, 0),
Zoom = 10.0,
ZoomMin = 1.0,
ZoomMax = 10000.0
}
end
--- @param data ExampleImageViewerData
local function ExampleImageViewer_DrawOptions(data)
ImGui.SetNextItemShortcut(ImGuiKey.G, ImGuiInputFlags.Tooltip)
_, data.GridEnabled = ImGui.Checkbox("Grid", data.GridEnabled)
ImGui.SameLine()
ImGui.SetNextItemWidth(ImGui.GetFontSize() * 10.0)
local zoom_100 = data.Zoom * 100.0
local changed
zoom_100, changed = ImGui.DragFloat("##Zoom", zoom_100, 5.0, data.ZoomMin * 100.0, data.ZoomMax * 100.0, "%.0f%%", ImGuiSliderFlags.AlwaysClamp)
if changed then
data.Zoom = zoom_100 / 100.0
end
end
--- @param data ExampleImageViewerData
--- @param canvas_size ImVec2
--- @param image_tex_ref ImTextureRef
--- @param image_w int
--- @param image_h int
local function ExampleImageViewer_DrawCanvas(data, canvas_size, image_tex_ref, image_w, image_h)
local io = ImGui.GetIO()
local platform_io = ImGui.GetPlatformIO()
local draw_list = ImGui.GetWindowDrawList()
IM_ASSERT(canvas_size.x >= 0.0 and canvas_size.y >= 0.0)
ImGui.InvisibleButton("##Canvas", canvas_size)
local canvas_min = ImGui.GetItemRectMin()
local canvas_max = ImGui.GetItemRectMax()
if data.ViewReset then
data.ViewOffset = ImVec2((canvas_size.x * 0.5 / data.Zoom) - 0.5, (canvas_size.y * 0.5 / data.Zoom) - 0.5)
end
data.ViewReset = false
if ImGui.SetItemKeyOwner(ImGuiKey.MouseWheelY) then
if io.MouseWheel ~= 0.0 then
data.Zoom = IM_CLAMP(data.Zoom * (1.0 + io.MouseWheel * 0.10), data.ZoomMin, data.ZoomMax)
end
end
local zoom = data.Zoom
if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) then
data.ViewOffset.x = data.ViewOffset.x - io.MouseDelta.x / zoom
data.ViewOffset.y = data.ViewOffset.y - io.MouseDelta.y / zoom
end
local image_min = ImVec2(); local image_max = ImVec2()
image_min.x = math.floor((canvas_min.x - (data.ViewOffset.x * zoom)) + (canvas_size.x * 0.5))
image_min.y = math.floor((canvas_min.y - (data.ViewOffset.y * zoom)) + (canvas_size.y * 0.5))
image_max.x = math.floor(image_min.x + image_w * zoom)
image_max.y = math.floor(image_min.y + image_h * zoom)
draw_list:AddRect(ImVec2(canvas_min.x - 1.0, canvas_min.y - 1.0), ImVec2(canvas_max.x + 1.0, canvas_max.y + 1.0), IM_COL32(255, 255, 255, 255))
draw_list:PushClipRect(canvas_min, canvas_max, true)
draw_list:AddRectFilled(image_min, image_max, data.ImageBgColor)
if platform_io.DrawCallback_SetSamplerNearest ~= nil then
draw_list:AddCallback(platform_io.DrawCallback_SetSamplerNearest)
end
draw_list:AddImage(image_tex_ref, image_min, image_max)
if platform_io.DrawCallback_SetSamplerLinear ~= nil then
draw_list:AddCallback(ImGui.GetPlatformIO().DrawCallback_SetSamplerLinear)
end
if data.GridEnabled and zoom > 6.0 then
local step = zoom
for px = math.floor((canvas_min.x - image_min.x) / step), math.floor((canvas_max.x - image_min.x) / step) do
draw_list:AddLineV(image_min.x + px * step, canvas_min.y, canvas_max.y, data.GridColor, 1.0)
end
for py = math.floor((canvas_min.y - image_min.y) / step), math.floor((canvas_max.y - image_min.y) / step) do
draw_list:AddLineH(canvas_min.x, canvas_max.x, image_min.y + py * step, data.GridColor, 1.0)
end
end
draw_list:PopClipRect()
end
local function ShowExampleMenuFile()
ImGui.MenuItem("(demo menu)", nil, false, false)
if ImGui.MenuItem("New") then end
if ImGui.MenuItem("Open", "Ctrl+O") then end
if ImGui.BeginMenu("Open Recent") then
ImGui.MenuItem("fish_hat.c")
ImGui.MenuItem("fish_hat.inl")
ImGui.MenuItem("fish_hat.h")
if ImGui.BeginMenu("More..") then
ImGui.MenuItem("Hello")
ImGui.MenuItem("Sailor")
if ImGui.BeginMenu("Recurse..") then
ShowExampleMenuFile()
ImGui.EndMenu()
end
ImGui.EndMenu()
end
ImGui.EndMenu()
end
if ImGui.MenuItem("Save", "Ctrl+S") then end
if ImGui.MenuItem("Save As..") then end
end
local function DemoWindowMenuBar(demo_data)
if ImGui.BeginMenuBar() then
if ImGui.BeginMenu("Menu") then
ShowExampleMenuFile()
ImGui.EndMenu()
end
if ImGui.BeginMenu("Examples") then
ImGui.SeparatorText("Concepts")
_, demo_data.ShowAppFullscreen = ImGui.MenuItem("Fullscreen window", nil, demo_data.ShowAppFullscreen)
ImGui.EndMenu()
end
if ImGui.BeginMenu("Tools") then
local has_debug_tools = false
if not IMGUI_DISABLE_DEBUG_TOOLS then
has_debug_tools = true
end
_, demo_data.ShowMetrics = ImGui.MenuItem("Metrics/Debugger", nil, demo_data.ShowMetrics, has_debug_tools)
_, demo_data.ShowStyleEditor = ImGui.MenuItem("Style Editor", nil, demo_data.ShowStyleEditor)
ImGui.EndMenu()
end
ImGui.EndMenuBar()
end
end
local DemoWindowWidgetsBasic
do
local static = {}
local clicked = 0
local checked = true
local radio_v = 0
local col0 = ImVec4(0, 0, 0, 1)
local col1 = ImVec4(0, 0, 0, 1)
local col2 = ImVec4(0, 0, 0, 1)
local counter = 0
local str0 = {string.byte("Hello, World!", 1, 13)}
table.insert(str0, 0)
local str1 = {}
str1[1] = 0
local hint0 = {string.byte("enter text here", 1, 15)}
table.insert(hint0, 0)
local vec4a = { 0.10, 0.20, 0.30, 0.44 }
local Element = { Fire = 1, Earth = 2, Air = 3, Water = 4, COUNT = 5 }
local elems_names = { "Fire", "Earth", "Air", "Water" }
function DemoWindowWidgetsBasic()
if ImGui.TreeNode("Basic") then
ImGui.SeparatorText("General")
if ImGui.Button("Button") then
clicked = clicked + 1
end
if clicked % 2 ~= 0 then
ImGui.SameLine()
ImGui.Text("Thanks for clicking me!")
end
_, check = ImGui.Checkbox("checkbox", check)
_, radio_v = ImGui.RadioButton("radio a", radio_v, 0) ImGui.SameLine()
_, radio_v = ImGui.RadioButton("radio b", radio_v, 1) ImGui.SameLine()
_, radio_v = ImGui.RadioButton("radio c", radio_v, 2)
ImGui.AlignTextToFramePadding()
ImGui.TextLinkOpenURL("Hyperlink", "https://github.com/GrayWolf64/imgui-lua")
for i = 1, 7 do
if i > 1 then
ImGui.SameLine()
end
ImGui.PushID(i)
col0.x, col0.y, col0.z = ImGui.ColorConvertHSVtoRGB(i / 7.0, 0.6, 0.6)
col1.x, col1.y, col1.z = ImGui.ColorConvertHSVtoRGB(i / 7.0, 0.7, 0.7)
col2.x, col2.y, col2.z = ImGui.ColorConvertHSVtoRGB(i / 7.0, 0.8, 0.8)
ImGui.PushStyleColor(ImGuiCol.Button, col0)
ImGui.PushStyleColor(ImGuiCol.ButtonHovered, col1)
ImGui.PushStyleColor(ImGuiCol.ButtonActive, col2)
ImGui.Button("Click")
ImGui.PopStyleColor(3)
ImGui.PopID()
end
-- Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements
-- (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!)
-- See 'Demo->Layout->Text Baseline Alignment' for details.
ImGui.AlignTextToFramePadding()
ImGui.Text("Hold to repeat:")
ImGui.SameLine()
-- Arrow buttons with Repeater
local spacing = ImGui.GetStyle().ItemInnerSpacing.x
ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true)
if ImGui.ArrowButton("##left", ImGuiDir.Left) then counter = counter - 1 end
ImGui.SameLine(0.0, spacing)
if ImGui.ArrowButton("##right", ImGuiDir.Right) then counter = counter + 1 end
ImGui.PopItemFlag()
ImGui.SameLine()
ImGui.Text("%d", counter)
ImGui.Button("Tooltip")
ImGui.SetItemTooltip("I am a tooltip")
ImGui.LabelText("label", "Value")
ImGui.SeparatorText("Inputs")
do
ImGui.InputText("input text", str0, 128)
ImGui.InputTextWithHint("input text (w/ hint)", hint0, str1, 128)
if not static.i0 then static.i0 = 233 end
static.i0 = ImGui.InputInt("input int", static.i0)
if not static.f0 then static.f0 = 0.001 end
static.f0 = ImGui.InputFloat("input float", static.f0, 0.01, 1.0)
if not static.d0 then static.d0 = 999999.00000001 end
static.d0 = ImGui.InputDouble("input double", static.d0, 0.01, 1.0, "%.8f")
-- TODO:
ImGui.InputFloat3("input float3", vec4a)
end
ImGui.SeparatorText("Drags")
do
if not static.i1 then static.i1 = 50 end
if not static.i2 then static.i2 = 42 end
if not static.i3 then static.i3 = 128 end
static.i1 = ImGui.DragInt("drag int", static.i1, 1)
static.i2 = ImGui.DragInt("drag int 0..100", static.i2, 1, 0, 100, "%d%%", ImGuiSliderFlags.AlwaysClamp)
static.i3 = ImGui.DragInt("drag int wrap 100..200", static.i3, 1, 100, 200, "%d", ImGuiSliderFlags.WrapAround)
if not static.f1 then static.f1 = 1.00 end
if not static.f2 then static.f2 = 0.0067 end
static.f1 = ImGui.DragFloat("drag float", static.f1, 0.005)
static.f2 = ImGui.DragFloat("drag small float", static.f2, 0.0001, 0.0, 0.0, "%.06f ns")
end
ImGui.SeparatorText("Sliders")
do
if not static.f01 then static.f01 = 0.123 end
if not static.f02 then static.f02 = 0.0 end
static.f01 = ImGui.SliderFloat("slider float", static.f01, 0.0, 1.0, "ratio = %.3f")
static.f02 = ImGui.SliderFloat("slider float (log)", static.f02, -10.0, 10.0, "%.4f", ImGuiSliderFlags.Logarithmic)
if not static.angle then static.angle = 0.0 end
static.angle = ImGui.SliderAngle("slider angle", static.angle)
if not static.elem then static.elem = Element.Fire end
local elem_name = (static.elem >= 1 and static.elem < Element.COUNT) and elems_names[static.elem] or "Unknown"
static.elem = ImGui.SliderInt("slider enum", static.elem, 1, Element.COUNT - 1, elem_name)
end
ImGui.TreePop()
end
end
end
local function DemoWindowWidgetsBullets()
if ImGui.TreeNode("Bullets") then
ImGui.BulletText("Bullet point 1")
ImGui.BulletText("Bullet point 2\nOn multiple lines")
if ImGui.TreeNode("Tree node") then
ImGui.BulletText("Another bullet point")
ImGui.TreePop()
end
ImGui.Bullet() ImGui.Text("Bullet point 3 (two calls)")
ImGui.Bullet() ImGui.SmallButton("Button")
ImGui.TreePop()
end
end
local DemoWindowWidgetsColorAndPickers
do
local color = {114.0 / 255.0, 144.0 / 255.0, 154.0 / 255.0, 200.0 / 255.0}
local base_flags = ImGuiColorEditFlags.None
local ref_color = false
local ref_color_v = {1.0, 0.0, 1.0, 0.5}
local picker_mode = 0
local display_mode = 0
local color_picker_flags = ImGuiColorEditFlags.AlphaBar
local picker_mode_names = {"Auto/Current", "ImGuiColorEditFlags.PickerHueBar", "ImGuiColorEditFlags.PickerHueWheel"}
local display_mode_names = {"Auto/Current", "ImGuiColorEditFlags.NoInputs", "ImGuiColorEditFlags.DisplayRGB", "ImGuiColorEditFlags.DisplayHSV", "ImGuiColorEditFlags.DisplayHex"}
function DemoWindowWidgetsColorAndPickers()
if ImGui.TreeNode("Color/Picker Widgets") then
ImGui.SeparatorText("Options")
_, base_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.NoAlpha", base_flags, ImGuiColorEditFlags.NoAlpha)
_, base_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.AlphaOpaque", base_flags, ImGuiColorEditFlags.AlphaOpaque)
_, base_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.AlphaNoBg", base_flags, ImGuiColorEditFlags.AlphaNoBg)
_, base_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.AlphaPreviewHalf", base_flags, ImGuiColorEditFlags.AlphaPreviewHalf)
_, base_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.NoOptions", base_flags, ImGuiColorEditFlags.NoOptions)
_, base_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.NoDragDrop", base_flags, ImGuiColorEditFlags.NoDragDrop)
_, base_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.NoColorMarkers", base_flags, ImGuiColorEditFlags.NoColorMarkers)
_, base_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.HDR", base_flags, ImGuiColorEditFlags.HDR)
ImGui.SeparatorText("Inline color editor")
ImGui.Text("Color widget:")
ImGui.ColorEdit3("MyColor##1", color, base_flags)
ImGui.Text("Color widget HSV with Alpha:")
ImGui.ColorEdit4("MyColor##2", color, bit32.bor(ImGuiColorEditFlags.DisplayHSV, base_flags))
ImGui.Text("Color widget with Float Display:")
ImGui.ColorEdit4("MyColor##2f", color, bit32.bor(ImGuiColorEditFlags.Float, base_flags))
ImGui.Text("Color button with Picker:")
ImGui.ColorEdit4("MyColor##3", color, bit32.bor(ImGuiColorEditFlags.NoInputs, ImGuiColorEditFlags.NoLabel, base_flags))
-- TODO:
ImGui.SeparatorText("Color picker")
ImGui.PushID("Color picker")
_, color_picker_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.NoAlpha", color_picker_flags, ImGuiColorEditFlags.NoAlpha)
_, color_picker_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.AlphaBar", color_picker_flags, ImGuiColorEditFlags.AlphaBar)
_, color_picker_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.NoSidePreview", color_picker_flags, ImGuiColorEditFlags.NoSidePreview)
if bit32.band(color_picker_flags, ImGuiColorEditFlags.NoSidePreview) ~= 0 then
ImGui.SameLine()
_, ref_color = ImGui.Checkbox("With Ref Color", ref_color)
if ref_color then
ImGui.SameLine()
ImGui.ColorEdit4("##RefColor", ref_color_v, bit32.bor(ImGuiColorEditFlags.NoInputs, base_flags))
end
end
_, color_picker_flags = ImGui.CheckboxFlags("ImGuiColorEditFlags.PickerNoRotate", color_picker_flags, ImGuiColorEditFlags.PickerNoRotate)
if ImGui.BeginCombo("Picker Mode", picker_mode_names[picker_mode + 1], ImGuiComboFlags.None) then
for mode_idx, mode_name in ipairs(picker_mode_names) do
local pressed = ImGui.Selectable(mode_name, mode_idx == picker_mode + 1)
if pressed then
picker_mode = mode_idx - 1
end
end
ImGui.EndCombo()
end
if ImGui.BeginCombo("Display Mode", display_mode_names[display_mode + 1], ImGuiComboFlags.None) then
for mode_idx, mode_name in ipairs(display_mode_names) do
local pressed = ImGui.Selectable(mode_name, mode_idx == display_mode + 1)
if pressed then
display_mode = mode_idx - 1
end
end
ImGui.EndCombo()
end
local flags = bit32.bor(base_flags, color_picker_flags)
if picker_mode == 1 then flags = bit32.bor(flags, ImGuiColorEditFlags.PickerHueBar) end
if picker_mode == 2 then flags = bit32.bor(flags, ImGuiColorEditFlags.PickerHueWheel) end
if display_mode == 1 then flags = bit32.bor(flags, ImGuiColorEditFlags.NoInputs) end -- Disable all RGB/HSV/Hex displays
if display_mode == 2 then flags = bit32.bor(flags, ImGuiColorEditFlags.DisplayRGB) end -- Override display mode
if display_mode == 3 then flags = bit32.bor(flags, ImGuiColorEditFlags.DisplayHSV) end
if display_mode == 4 then flags = bit32.bor(flags, ImGuiColorEditFlags.DisplayHex) end
ImGui.ColorPicker4("MyColor##4", color, flags, ref_color and ref_color_v or nil)
ImGui.TreePop()
end
end
end
local DemoWindowWidgetsImages do
local pressed_count = 0
local image_viewer = ExampleImageViewerData()
function DemoWindowWidgetsImages()
if ImGui.TreeNode("Images") then
ImGui.TextWrapped(
"Below we are displaying the font texture (which is the only texture we have access to in this demo). " ..
"Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. " ..
"Hover the texture for a zoomed view!"
)
-- Grab the current texture identifier used by the font atlas
local io = ImGui.GetIO()
local atlas = io.Fonts
local my_tex_id = atlas.TexRef
local my_tex_w = atlas.TexData.Width
local my_tex_h = atlas.TexData.Height
ImGui.Text("%.0fx%.0f", my_tex_w, my_tex_h)
ImGui.SeparatorText("Image()/ImageWithBg() function")
local uv_min = ImVec2(0.0, 0.0)
local uv_max = ImVec2(1.0, 1.0)
ImGui.PushStyleVar(ImGuiStyleVar.ImageBorderSize, IM_MAX(1.0, ImGui.GetStyle().ImageBorderSize))
ImGui.ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, ImVec4(0.0, 0.0, 0.0, 1.0))
ImGui.PopStyleVar()
-- Fancy widget
ImGui.SeparatorText("Interactive Image Viewer")
local canvas_size = ImVec2(ImGui.GetContentRegionAvail().x, my_tex_h * 2.0)
ExampleImageViewer_DrawOptions(image_viewer)
ExampleImageViewer_DrawCanvas(image_viewer, canvas_size, my_tex_id, my_tex_w, my_tex_h)
ImGui.SeparatorText("Textured Buttons")
ImGui.TextWrapped("And now some textured buttons..")
for i = 1, 8 do
-- UV coordinates are often (0.0f, 0.0f) and (1.0f, 1.0f) to display an entire textures.
-- Here are trying to display only a 32x32 pixels area of the texture, hence the UV computation.
ImGui.PushID(i)
if i > 1 then
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, ImVec2(i, i))
end
local size = ImVec2(32.0, 32.0) -- Size of the image we want to make visible
local uv0 = ImVec2(0.0, 0.0) -- UV coordinates for lower-left
local uv1 = ImVec2(32.0 / my_tex_w, 32.0 / my_tex_h) -- UV coordinates for (32,32) in our texture
local bg_col = ImVec4(0.0, 0.0, 0.0, 1.0) -- Black background
local tint_col = ImVec4(1.0, 1.0, 1.0, 1.0) -- No tint
if ImGui.ImageButton("", my_tex_id, size, uv0, uv1, bg_col, tint_col) then
pressed_count = pressed_count + 1
end
if i > 1 then
ImGui.PopStyleVar()
end
ImGui.PopID()
ImGui.SameLine()
end
ImGui.NewLine()
ImGui.Text("Pressed %d times.", pressed_count)
ImGui.TreePop()
end
end
end
local function DemoWindowWidgetsLiveEdit()
-- TODO:
end
local DemoWindowWidgetsPlotting
do
local animate = true
local arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }
local values_sz = 90
local values = {} for i = 1, values_sz do values[i] = 0 end
local values_offset = 0
local refresh_time = 0.0
local phase = 0.0
function DemoWindowWidgetsPlotting()
if ImGui.TreeNode("Plotting") then
_, animate = ImGui.Checkbox("Animate", animate)
-- Plot as lines and plot as histogram
ImGui.PlotLines("Frame Times", arr, nil, #arr)
ImGui.PlotHistogram("Histogram", arr, nil, #arr, 0, nil, 0.0, 1.0, ImVec2(0, 80.0))
if not animate or refresh_time == 0.0 then
refresh_time = ImGui.GetTime()
end
while refresh_time < ImGui.GetTime() do -- Create data at fixed 60 Hz rate for the demo
values[values_offset + 1] = math.cos(phase)
values_offset = (values_offset + 1) % values_sz
phase = phase + 0.10 * values_offset
refresh_time = refresh_time + 1.0 / 60.0
end
-- Plots can display overlay texts
-- (in this example, we will display an average value)
do
local average = 0.0
for i = 1, values_sz do
average = average + values[i]
end
average = average / values_sz
local overlay = string.format("avg %f", average)
ImGui.PlotLines("Lines", values, nil, values_sz, values_offset, overlay, -1.0, 1.0, ImVec2(0, 80.0))
end
ImGui.TreePop()
end
end
end
local DemoWindowWidgetsProgressBars do
local progress_accum = 0.0
local progress_dir = 1.0
function DemoWindowWidgetsProgressBars()
if ImGui.TreeNode("Progress Bars") then
-- Animate a simple progress bar
progress_accum = progress_accum + progress_dir * 0.4 * ImGui.GetIO().DeltaTime
if progress_accum >= 1.1 then
progress_accum = 1.1
progress_dir = progress_dir * -1.0
end
if progress_accum <= -0.1 then
progress_accum = -0.1
progress_dir = progress_dir * -1.0
end
local progress = IM_CLAMP(progress_accum, 0.0, 1.0)
-- Typically we would use ImVec2(-1.0,0.0) or ImVec2(-math.huge,0.0) to use all available width,
-- or ImVec2(width,0.0) for a specified width. ImVec2(0.0,0.0) uses ItemWidth
ImGui.ProgressBar(progress, ImVec2(0.0, 0.0))
ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x)
ImGui.Text("Progress Bar")
local buf = string.format("%d/%d", math.floor(progress * 1753), 1753)
ImGui.ProgressBar(progress, ImVec2(0.0, 0.0), buf)
-- Pass an animated negative value, e.g. -1.0 * ImGui.GetTime() is the recommended value
-- Adjust the factor if you want to adjust the animation speed
ImGui.ProgressBar(-1.0 * ImGui.GetTime(), ImVec2(0.0, 0.0), "Searching..")
ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x)
ImGui.Text("Indeterminate")
ImGui.TreePop()
end
end
end
local DemoWindowWidgetsVerticalSliders do
local int_value = 0
local values = { 0.0, 0.60, 0.35, 0.9, 0.70, 0.20, 0.0 }
local values2 = { 0.20, 0.80, 0.40, 0.25 }
local col0 = ImVec4(0, 0, 0, 1)
local col1 = ImVec4(0, 0, 0, 1)
local col2 = ImVec4(0, 0, 0, 1)
local col3 = ImVec4(0, 0, 0, 1)
function DemoWindowWidgetsVerticalSliders()
if ImGui.TreeNode("Vertical Sliders") then
local spacing = 4
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(spacing, spacing))
int_value = ImGui.VSliderInt("##int", ImVec2(18, 160), int_value, 0, 5)
ImGui.SameLine()
ImGui.PushID("set1")
for i = 1, 7 do
if i > 1 then ImGui.SameLine() end
ImGui.PushID(i)
local hue = (i - 1) / 7.0
col0.x, col0.y, col0.z = ImGui.ColorConvertHSVtoRGB(hue, 0.5, 0.5)
col1.x, col1.y, col1.z = ImGui.ColorConvertHSVtoRGB(hue, 0.6, 0.5)
col2.x, col2.y, col2.z = ImGui.ColorConvertHSVtoRGB(hue, 0.7, 0.5)
col3.x, col3.y, col3.z = ImGui.ColorConvertHSVtoRGB(hue, 0.9, 0.9)
ImGui.PushStyleColor(ImGuiCol.FrameBg, col0)
ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, col1)
ImGui.PushStyleColor(ImGuiCol.FrameBgActive, col2)
ImGui.PushStyleColor(ImGuiCol.SliderGrab, col3)
values[i] = ImGui.VSliderFloat("##v", ImVec2(18, 160), values[i], 0.0, 1.0, "")
if ImGui.IsItemActive() or ImGui.IsItemHovered() then
ImGui.SetTooltip("%.3f", values[i])
end
ImGui.PopStyleColor(4)
ImGui.PopID()
end
ImGui.PopID()
ImGui.SameLine()
ImGui.PushID("set2")
local rows = 3
local small_slider_size = ImVec2(18, math.floor((160.0 - (rows - 1) * spacing) / rows))
for nx = 1, 4 do
if nx > 1 then ImGui.SameLine() end
ImGui.BeginGroup()
for ny = 1, rows do
ImGui.PushID((nx - 1) * rows + ny)
values2[nx] = ImGui.VSliderFloat("##v", small_slider_size, values2[nx], 0.0, 1.0, "")
if ImGui.IsItemActive() or ImGui.IsItemHovered() then
ImGui.SetTooltip("%.3f", values2[nx])
end
ImGui.PopID()
end
ImGui.EndGroup()
end
ImGui.PopID()
ImGui.SameLine()
ImGui.PushID("set3")
for i = 1, 4 do
if i > 1 then ImGui.SameLine() end
ImGui.PushID(i)
ImGui.PushStyleVar(ImGuiStyleVar.GrabMinSize, 40)
values[i] = ImGui.VSliderFloat("##v", ImVec2(40, 160), values[i], 0.0, 1.0, "%.2f\nsec")
ImGui.PopStyleVar()
ImGui.PopID()
end
ImGui.PopID()
ImGui.PopStyleVar()
ImGui.TreePop()
end
end
end
local function DemoWindowWidgets()
if not ImGui.CollapsingHeader("Widgets") then
return
end
DemoWindowWidgetsBasic()
DemoWindowWidgetsBullets()
DemoWindowWidgetsColorAndPickers()
DemoWindowWidgetsImages()
DemoWindowWidgetsLiveEdit()
DemoWindowWidgetsPlotting()
DemoWindowWidgetsProgressBars()
DemoWindowWidgetsVerticalSliders()
end
local function DemoWindowLayout()
if not ImGui.CollapsingHeader("Layout & Scrolling") then
return
end
end
local function DemoWindowPopups()
if not ImGui.CollapsingHeader("Popups & Modal windows") then
return
end
end
local function DemoWindowTables()
if not ImGui.CollapsingHeader("Tables & Columns") then
return
end
end
local function DemoWindowInputs()
if not ImGui.CollapsingHeader("Inputs & Focus") then
return
end
end
do
local static = {}
local style_idx = -1
local style_names = { "Dark", "Light", "Classic" }
--- @param label string
function ImGui.ShowStyleSelector(label)
local ret = false
if ImGui.BeginCombo(label, (style_idx >= 1 and style_idx <= #style_names) and style_names[style_idx] or "") then
for n = 1, #style_names do
if ImGui.Selectable(style_names[n], style_idx == n, ImGuiSelectableFlags.SelectOnNav) then
style_idx = n
ret = true
if style_idx == 1 then ImGui.StyleColorsDark() end
if style_idx == 2 then ImGui.StyleColorsLight() end
if style_idx == 3 then ImGui.StyleColorsClassic() end
elseif style_idx == n then
ImGui.SetItemDefaultFocus()
end
end
ImGui.EndCombo()
end
return ret
end
--- @param label string
function ImGui.ShowFontSelector(label)
local io = ImGui.GetIO()
local font_current = ImGui.GetFont()
if ImGui.BeginCombo(label, font_current:GetDebugName()) then
for _, font in io.Fonts.Fonts:iter() do
ImGui.PushID(tostring(font):match("0x%x+")) -- (void*)font
if ImGui.Selectable(font:GetDebugName(), font == font_current, ImGuiSelectableFlags.SelectOnNav) then
io.FontDefault = font
end
if font == font_current then
ImGui.SetItemDefaultFocus()
end
ImGui.PopID()
end
ImGui.EndCombo()
end
end
--- @param ref ImGuiStyle?
function ImGui.ShowStyleEditor(ref)
local style = ImGui.GetStyle()
local default_border_size = ImTrunc(style._MainScale)
local max_border_size = ImMax(default_border_size, 2.0)
ImGui.PushItemWidth(ImGui.GetWindowWidth() * 0.50)
ImGui.SeparatorText("General")
do
if ImGui.ShowStyleSelector("Colors##Selector") then
-- TODO:
end
ImGui.ShowFontSelector("Fonts##Selector")
local ret0
style.FontSizeBase, ret0 = ImGui.DragFloat("FontSizeBase", style.FontSizeBase, 0.20, 5.0, 100.0, "%.0f")
if ret0 then
style._NextFrameFontSizeBase = style.FontSizeBase -- FIXME: Temporary hack until we finish remaining work.
end
ImGui.SameLine(0.0, 0.0); ImGui.Text(" (out %.2f)", ImGui.GetFontSize())
style.FontScaleMain = ImGui.DragFloat("FontScaleMain", style.FontScaleMain, 0.02, 0.5, 4.0)
ImGui.BeginDisabled(ImGui.GetIO().ConfigDpiScaleFonts)
style.FontScaleDpi = ImGui.DragFloat("FontScaleDpi", style.FontScaleDpi, 0.02, 0.5, 4.0)
ImGui.SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.")
ImGui.EndDisabled()
local ret1
style.FrameRounding, ret1 = ImGui.SliderFloat("FrameRounding", style.FrameRounding, 0.0, 12.0, "%.0f")
if ret1 then
style.GrabRounding = style.FrameRounding -- Make GrabRounding always the same value as FrameRounding
end
do
local border = (style.WindowBorderSize > 0.0)
local pressed
pressed, border = ImGui.Checkbox("WindowBorder", border)
if pressed then style.WindowBorderSize = (border and default_border_size or 0.0) end
end
ImGui.SameLine()
do
local border = (style.FrameBorderSize > 0.0)
local pressed
pressed, border = ImGui.Checkbox("FrameBorder", border)
if pressed then style.FrameBorderSize = (border and default_border_size or 0.0) end
end
ImGui.SameLine()
do
local border = (style.PopupBorderSize > 0.0)
local pressed
pressed, border = ImGui.Checkbox("PopupBorder", border)
if pressed then style.PopupBorderSize = (border and default_border_size or 0.0) end
end
end
ImGui.SeparatorText("Details")
-- TODO:
ImGui.PopItemWidth()
end
end
local function ShowExampleAppImageViewer()
-- TODO:
end
local ShowExampleAppFullscreen do
local use_work_area = true
local flags = bit32.bor(ImGuiWindowFlags.NoDecoration, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoSavedSettings)
function ShowExampleAppFullscreen(open)
local viewport = ImGui.GetMainViewport()
ImGui.SetNextWindowPos(use_work_area and viewport.WorkPos or viewport.Pos)
ImGui.SetNextWindowSize(use_work_area and viewport.WorkSize or viewport.Size)
local ret
open, ret = ImGui.Begin("Example: Fullscreen window", open, flags)
if ret then
_, use_work_area = ImGui.Checkbox("Use work area instead of main area", use_work_area)
ImGui.SameLine()
_, flags = ImGui.CheckboxFlags("ImGuiWindowFlags.NoBackground", flags, ImGuiWindowFlags.NoBackground)
_, flags = ImGui.CheckboxFlags("ImGuiWindowFlags.NoDecoration", flags, ImGuiWindowFlags.NoDecoration)
ImGui.Indent()
_, flags = ImGui.CheckboxFlags("ImGuiWindowFlags.NoTitleBar", flags, ImGuiWindowFlags.NoTitleBar)
_, flags = ImGui.CheckboxFlags("ImGuiWindowFlags.NoCollapse", flags, ImGuiWindowFlags.NoCollapse)
_, flags = ImGui.CheckboxFlags("ImGuiWindowFlags.NoScrollbar", flags, ImGuiWindowFlags.NoScrollbar)
ImGui.Unindent()
if open and ImGui.Button("Close this window") then
open = false
end
end
ImGui.End()
return open
end
end
do
local demo_data = ImGuiDemoWindowData()
local no_titlebar = false
local no_scrollbar = false
local no_menu = false
local no_move = false
local no_resize = false
local no_collapse = false
local no_close = false
local no_nav = false
local no_background = false
local no_bring_to_front = false
local no_docking = false
local unsaved_document = false
function ImGui.ShowDemoWindow(open)
if demo_data.ShowAppFullscreen then demo_data.ShowAppFullscreen = ShowExampleAppFullscreen(demo_data.ShowAppFullscreen) end
if demo_data.ShowMetrics then
demo_data.ShowMetrics = ImGui.ShowMetricsWindow(demo_data.ShowMetrics)
end
if demo_data.ShowStyleEditor then
demo_data.ShowStyleEditor = ImGui.Begin("ImGui Sincerely Style Editor", demo_data.ShowStyleEditor)
ImGui.ShowStyleEditor()
ImGui.End()
end
local window_flags = 0
if no_titlebar then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoTitleBar) end
if no_scrollbar then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoScrollbar) end
if not no_menu then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.MenuBar) end
if no_move then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoMove) end
if no_resize then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoResize) end
if no_collapse then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoCollapse) end
if no_nav then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoNav) end
if no_background then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoBackground) end
if no_bring_to_front then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoBringToFrontOnFocus) end
if no_docking then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoDocking) end
if unsaved_document then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.UnsavedDocument) end
if no_close then open = nil end
if not no_menu then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.MenuBar) end
local ret -- is_visible
open, ret = ImGui.Begin("ImGui Sincerely Demo", open, window_flags)
if not ret then
ImGui.End()
return open
end
local label_width_base = ImGui.GetFontSize() * 12
local label_width_max = ImGui.GetContentRegionAvail().x * 0.40
local label_width = IM_MIN(label_width_base, label_width_max)
ImGui.PushItemWidth(-label_width)
DemoWindowMenuBar(demo_data)
if ImGui.CollapsingHeader("Help") then
ImGui.SeparatorText("ABOUT THIS DEMO:")
end
if ImGui.CollapsingHeader("Configuration") then
end
if ImGui.CollapsingHeader("Window Options") then
if ImGui.BeginTable("split", 3) then
ImGui.TableNextColumn() _, no_titlebar = ImGui.Checkbox("No titlebar", no_titlebar)
ImGui.TableNextColumn() _, no_scrollbar = ImGui.Checkbox("No scrollbar", no_scrollbar)
ImGui.TableNextColumn() _, no_menu = ImGui.Checkbox("No menu", no_menu)
ImGui.TableNextColumn() _, no_move = ImGui.Checkbox("No move", no_move)
ImGui.TableNextColumn() _, no_resize = ImGui.Checkbox("No resize", no_resize)
ImGui.TableNextColumn() _, no_collapse = ImGui.Checkbox("No collapse", no_collapse)
ImGui.TableNextColumn() _, no_close = ImGui.Checkbox("No close", no_close)
ImGui.TableNextColumn() _, no_nav = ImGui.Checkbox("No nav", no_nav)
ImGui.TableNextColumn() _, no_background = ImGui.Checkbox("No background", no_background)
ImGui.TableNextColumn() _, no_bring_to_front = ImGui.Checkbox("No bring to front", no_bring_to_front)
ImGui.TableNextColumn() _, no_docking = ImGui.Checkbox("No docking", no_docking)
ImGui.TableNextColumn() _, unsaved_document = ImGui.Checkbox("Unsaved document", unsaved_document)
ImGui.EndTable()
end
end
DemoWindowWidgets()
DemoWindowLayout()
DemoWindowPopups()
DemoWindowTables()
DemoWindowInputs()
ImGui.End()
return open
end
end
return true -- [Roblox] ModuleScripts must return exactly one value
end
__FILES['imgui_draw.lua'] = function()
--- ImGui Sincerely WIP
-- (Draw Code)
FONT_ATLAS_DEFAULT_TEX_DATA_W = 122
FONT_ATLAS_DEFAULT_TEX_DATA_H = 27
local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32
local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF
local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE
--- @param str string
--- @return table
--- @nodiscard
--- @package
local function str_to_table(str)
local t = {} for i = 1, #str do t[i] = string.sub(str, i, i) end return t
end
--- @param buf char[] # 1-based
--- @param base int # 1-based start index
--- @param u32 ImU32
local function write_u32(buf, base, u32)
buf[base + 0] = bit32.band(u32, 0xFF)
buf[base + 1] = bit32.band(bit32.rshift(u32, 8), 0xFF)
buf[base + 2] = bit32.band(bit32.rshift(u32, 16), 0xFF)
buf[base + 3] = bit32.band(bit32.rshift(u32, 24), 0xFF)
end
--- Original ImGui pixel art!
local FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS = str_to_table(
"..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX - XX XX " ..
"..- -X.....X- X.X - X.X -X.....X - X.....X- X..X -X..X X..X" ..
"--- -XXX.XXX- X...X - X...X -X....X - X....X- X..X -X...X X...X" ..
"X - X.X - X.....X - X.....X -X...X - X...X- X..X - X...X X...X " ..
"XX - X.X -X.......X- X.......X -X..X.X - X.X..X- X..X - X...X...X " ..
"X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X- X..XXX - X.....X " ..
"X..X - X.X - X.X - X.X -XX X.X - X.X XX- X..X..XXX - X...X " ..
"X...X - X.X - X.X - XX X.X XX - X.X - X.X - X..X..X..XX - X.X " ..
"X....X - X.X - X.X - X.X X.X X.X - X.X - X.X - X..X..X..X.X - X...X " ..
"X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X -XXX X..X..X..X..X- X.....X " ..
"X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X -X..XX........X..X- X...X...X " ..
"X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X -X...X...........X- X...X X...X " ..
"X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X - X..............X-X...X X...X" ..
"X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X - X.............X-X..X X..X" ..
"X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X - X.............X- XX XX " ..
"X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X - X............X--------------" ..
"X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX - X...........X - " ..
"X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------- X..........X - " ..
"X.X X..X - -X.......X- X.......X - XX XX - - X..........X - " ..
"XX X..X - - X.....X - X.....X - X.X X.X - - X........X - " ..
" X..X - - X...X - X...X - X..X X..X - - X........X - " ..
" XX - - X.X - X.X - X...XXXXXXXXXXXXX...X - - XXXXXXXXXX - " ..
"------------- - X - X -X.....................X- ------------------- " ..
" ----------------------------------- X...XXXXXXXXXXXXX...X - " ..
" - X..X X..X - " ..
" - X.X X.X - " ..
" - XX XX - "
)
local FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA = {
-- Pos .......... Size ......... Offset .......
{ ImVec2( 0, 3), ImVec2(12, 19), ImVec2( 0, 0) }, -- ImGuiMouseCursor.Arrow
{ ImVec2( 13, 0), ImVec2( 7, 16), ImVec2( 1, 8) }, -- ImGuiMouseCursor.TextInput
{ ImVec2( 31, 0), ImVec2(23, 23), ImVec2(11, 11) }, -- ImGuiMouseCursor.ResizeAll
{ ImVec2( 21, 0), ImVec2( 9, 23), ImVec2( 4, 11) }, -- ImGuiMouseCursor.ResizeNS
{ ImVec2( 55, 18), ImVec2(23, 9), ImVec2(11, 4) }, -- ImGuiMouseCursor.ResizeEW
{ ImVec2( 73, 0), ImVec2(17, 17), ImVec2( 8, 8) }, -- ImGuiMouseCursor.ResizeNESW
{ ImVec2( 55, 0), ImVec2(17, 17), ImVec2( 8, 8) }, -- ImGuiMouseCursor.ResizeNWSE
{ ImVec2( 91, 0), ImVec2(17, 22), ImVec2( 5, 0) }, -- ImGuiMouseCursor.Hand
{ ImVec2( 0, 3), ImVec2(12, 19), ImVec2( 0, 0) }, -- ImGuiMouseCursor.Wait -- Arrow + custom code in ImGui.RenderMouseCursor()
{ ImVec2( 0, 3), ImVec2(12, 19), ImVec2( 0, 0) }, -- ImGuiMouseCursor.Progress -- Arrow + custom code in ImGui.RenderMouseCursor()
{ ImVec2(109, 0), ImVec2(13, 15), ImVec2( 6, 7) }, -- ImGuiMouseCursor.NotAllowed
}
local MT = ImGui.GetMetatables()
--- @module "imstb_rectpack"
local stbrp = IM_INCLUDE("imstb_rectpack.lua")
--- @module "imstb_truetype"
local stbtt = IM_INCLUDE("imstb_truetype.lua")
---------------------------------------------------------------------------------------
-- [SECTION] STYLE FUNCTIONS
---------------------------------------------------------------------------------------
--- @param a ImVec4
--- @param b ImVec4
--- @param t float
local function ImLerpV4V4F(a, b, t) return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t) end
--- @param dst? ImGuiStyle
function ImGui.StyleColorsDark(dst)
local style = dst and dst or ImGui.GetStyle()
local colors = style.Colors
colors[ImGuiCol.Text] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[ImGuiCol.TextDisabled] = ImVec4(0.50, 0.50, 0.50, 1.00)
colors[ImGuiCol.WindowBg] = ImVec4(0.06, 0.06, 0.06, 0.94)
colors[ImGuiCol.ChildBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.PopupBg] = ImVec4(0.08, 0.08, 0.08, 0.94)
colors[ImGuiCol.Border] = ImVec4(0.43, 0.43, 0.50, 0.50)
colors[ImGuiCol.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.FrameBg] = ImVec4(0.16, 0.29, 0.48, 0.54)
colors[ImGuiCol.FrameBgHovered] = ImVec4(0.26, 0.59, 0.98, 0.40)
colors[ImGuiCol.FrameBgActive] = ImVec4(0.26, 0.59, 0.98, 0.67)
colors[ImGuiCol.TitleBg] = ImVec4(0.04, 0.04, 0.04, 1.00)
colors[ImGuiCol.TitleBgActive] = ImVec4(0.16, 0.29, 0.48, 1.00)
colors[ImGuiCol.TitleBgCollapsed] = ImVec4(0.00, 0.00, 0.00, 0.51)
colors[ImGuiCol.MenuBarBg] = ImVec4(0.14, 0.14, 0.14, 1.00)
colors[ImGuiCol.ScrollbarBg] = ImVec4(0.02, 0.02, 0.02, 0.53)
colors[ImGuiCol.ScrollbarGrab] = ImVec4(0.31, 0.31, 0.31, 1.00)
colors[ImGuiCol.ScrollbarGrabHovered] = ImVec4(0.41, 0.41, 0.41, 1.00)
colors[ImGuiCol.ScrollbarGrabActive] = ImVec4(0.51, 0.51, 0.51, 1.00)
colors[ImGuiCol.CheckMark] = ImVec4(0.26, 0.59, 0.98, 1.00)
colors[ImGuiCol.CheckboxSelectedBg] = ImLerpV4V4F(colors[ImGuiCol.FrameBg], colors[ImGuiCol.FrameBgHovered], 0.65)
colors[ImGuiCol.SliderGrab] = ImVec4(0.24, 0.52, 0.88, 1.00)
colors[ImGuiCol.SliderGrabActive] = ImVec4(0.26, 0.59, 0.98, 1.00)
colors[ImGuiCol.Button] = ImVec4(0.26, 0.59, 0.98, 0.40)
colors[ImGuiCol.ButtonHovered] = ImVec4(0.26, 0.59, 0.98, 1.00)
colors[ImGuiCol.ButtonActive] = ImVec4(0.06, 0.53, 0.98, 1.00)
colors[ImGuiCol.Header] = ImVec4(0.26, 0.59, 0.98, 0.31)
colors[ImGuiCol.HeaderHovered] = ImVec4(0.26, 0.59, 0.98, 0.80)
colors[ImGuiCol.HeaderActive] = ImVec4(0.26, 0.59, 0.98, 1.00)
colors[ImGuiCol.Separator] = colors[ImGuiCol.Border]
colors[ImGuiCol.SeparatorHovered] = ImVec4(0.10, 0.40, 0.75, 0.78)
colors[ImGuiCol.SeparatorActive] = ImVec4(0.10, 0.40, 0.75, 1.00)
colors[ImGuiCol.ResizeGrip] = ImVec4(0.26, 0.59, 0.98, 0.20)
colors[ImGuiCol.ResizeGripHovered] = ImVec4(0.26, 0.59, 0.98, 0.67)
colors[ImGuiCol.ResizeGripActive] = ImVec4(0.26, 0.59, 0.98, 0.95)
colors[ImGuiCol.InputTextCursor] = colors[ImGuiCol.Text]
colors[ImGuiCol.TabHovered] = colors[ImGuiCol.HeaderHovered]
colors[ImGuiCol.Tab] = ImLerpV4V4F(colors[ImGuiCol.Header], colors[ImGuiCol.TitleBgActive], 0.80)
colors[ImGuiCol.TabSelected] = ImLerpV4V4F(colors[ImGuiCol.HeaderActive], colors[ImGuiCol.TitleBgActive], 0.60)
colors[ImGuiCol.TabSelectedOverline] = colors[ImGuiCol.HeaderActive]
colors[ImGuiCol.TabDimmed] = ImLerpV4V4F(colors[ImGuiCol.Tab], colors[ImGuiCol.TitleBg], 0.80)
colors[ImGuiCol.TabDimmedSelected] = ImLerpV4V4F(colors[ImGuiCol.TabSelected], colors[ImGuiCol.TitleBg], 0.40)
colors[ImGuiCol.TabDimmedSelectedOverline] = ImVec4(0.50, 0.50, 0.50, 0.00)
colors[ImGuiCol.PlotLines] = ImVec4(0.61, 0.61, 0.61, 1.00)
colors[ImGuiCol.PlotLinesHovered] = ImVec4(1.00, 0.43, 0.35, 1.00)
colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00)
colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00)
colors[ImGuiCol.TableHeaderBg] = ImVec4(0.19, 0.19, 0.20, 1.00)
colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.35, 1.00)
colors[ImGuiCol.TableBorderLight] = ImVec4(0.23, 0.23, 0.25, 1.00)
colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.TableRowBgAlt] = ImVec4(1.00, 1.00, 1.00, 0.06)
colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive]
colors[ImGuiCol.TextSelectedBg] = ImVec4(0.26, 0.59, 0.98, 0.35)
colors[ImGuiCol.TreeLines] = colors[ImGuiCol.Border]
colors[ImGuiCol.DragDropTarget] = ImVec4(1.00, 1.00, 0.00, 0.90)
colors[ImGuiCol.DragDropTargetBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.UnsavedMarker] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[ImGuiCol.NavCursor] = ImVec4(0.26, 0.59, 0.98, 1.00)
colors[ImGuiCol.NavWindowingHighlight] = ImVec4(1.00, 1.00, 1.00, 0.70)
colors[ImGuiCol.NavWindowingDimBg] = ImVec4(0.80, 0.80, 0.80, 0.20)
colors[ImGuiCol.ModalWindowDimBg] = ImVec4(0.80, 0.80, 0.80, 0.35)
end
--- @param dst? ImGuiStyle
function ImGui.StyleColorsClassic(dst)
local style = dst and dst or ImGui.GetStyle()
local colors = style.Colors
colors[ImGuiCol.Text] = ImVec4(0.90, 0.90, 0.90, 1.00)
colors[ImGuiCol.TextDisabled] = ImVec4(0.60, 0.60, 0.60, 1.00)
colors[ImGuiCol.WindowBg] = ImVec4(0.00, 0.00, 0.00, 0.85)
colors[ImGuiCol.ChildBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.PopupBg] = ImVec4(0.11, 0.11, 0.14, 0.92)
colors[ImGuiCol.Border] = ImVec4(0.50, 0.50, 0.50, 0.50)
colors[ImGuiCol.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.FrameBg] = ImVec4(0.43, 0.43, 0.43, 0.39)
colors[ImGuiCol.FrameBgHovered] = ImVec4(0.47, 0.47, 0.69, 0.40)
colors[ImGuiCol.FrameBgActive] = ImVec4(0.42, 0.41, 0.64, 0.69)
colors[ImGuiCol.TitleBg] = ImVec4(0.27, 0.27, 0.54, 0.83)
colors[ImGuiCol.TitleBgActive] = ImVec4(0.32, 0.32, 0.63, 0.87)
colors[ImGuiCol.TitleBgCollapsed] = ImVec4(0.40, 0.40, 0.80, 0.20)
colors[ImGuiCol.MenuBarBg] = ImVec4(0.40, 0.40, 0.55, 0.80)
colors[ImGuiCol.ScrollbarBg] = ImVec4(0.20, 0.25, 0.30, 0.60)
colors[ImGuiCol.ScrollbarGrab] = ImVec4(0.40, 0.40, 0.80, 0.30)
colors[ImGuiCol.ScrollbarGrabHovered] = ImVec4(0.40, 0.40, 0.80, 0.40)
colors[ImGuiCol.ScrollbarGrabActive] = ImVec4(0.41, 0.39, 0.80, 0.60)
colors[ImGuiCol.CheckMark] = ImVec4(0.90, 0.90, 0.90, 0.50)
colors[ImGuiCol.CheckboxSelectedBg] = ImLerpV4V4F(colors[ImGuiCol.FrameBg], colors[ImGuiCol.FrameBgActive], 0.65)
colors[ImGuiCol.SliderGrab] = ImVec4(1.00, 1.00, 1.00, 0.30)
colors[ImGuiCol.SliderGrabActive] = ImVec4(0.41, 0.39, 0.80, 0.60)
colors[ImGuiCol.Button] = ImVec4(0.35, 0.40, 0.61, 0.62)
colors[ImGuiCol.ButtonHovered] = ImVec4(0.40, 0.48, 0.71, 0.79)
colors[ImGuiCol.ButtonActive] = ImVec4(0.46, 0.54, 0.80, 1.00)
colors[ImGuiCol.Header] = ImVec4(0.40, 0.40, 0.90, 0.45)
colors[ImGuiCol.HeaderHovered] = ImVec4(0.45, 0.45, 0.90, 0.80)
colors[ImGuiCol.HeaderActive] = ImVec4(0.53, 0.53, 0.87, 0.80)
colors[ImGuiCol.Separator] = ImVec4(0.50, 0.50, 0.50, 0.60)
colors[ImGuiCol.SeparatorHovered] = ImVec4(0.60, 0.60, 0.70, 1.00)
colors[ImGuiCol.SeparatorActive] = ImVec4(0.70, 0.70, 0.90, 1.00)
colors[ImGuiCol.ResizeGrip] = ImVec4(1.00, 1.00, 1.00, 0.10)
colors[ImGuiCol.ResizeGripHovered] = ImVec4(0.78, 0.82, 1.00, 0.60)
colors[ImGuiCol.ResizeGripActive] = ImVec4(0.78, 0.82, 1.00, 0.90)
colors[ImGuiCol.InputTextCursor] = colors[ImGuiCol.Text]
colors[ImGuiCol.TabHovered] = colors[ImGuiCol.HeaderHovered]
colors[ImGuiCol.Tab] = ImLerpV4V4F(colors[ImGuiCol.Header], colors[ImGuiCol.TitleBgActive], 0.80)
colors[ImGuiCol.TabSelected] = ImLerpV4V4F(colors[ImGuiCol.HeaderActive], colors[ImGuiCol.TitleBgActive], 0.60)
colors[ImGuiCol.TabSelectedOverline] = colors[ImGuiCol.HeaderActive]
colors[ImGuiCol.TabDimmed] = ImLerpV4V4F(colors[ImGuiCol.Tab], colors[ImGuiCol.TitleBg], 0.80)
colors[ImGuiCol.TabDimmedSelected] = ImLerpV4V4F(colors[ImGuiCol.TabSelected], colors[ImGuiCol.TitleBg], 0.40)
colors[ImGuiCol.TabDimmedSelectedOverline] = ImVec4(0.53, 0.53, 0.87, 0.00)
colors[ImGuiCol.PlotLines] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[ImGuiCol.PlotLinesHovered] = ImVec4(0.90, 0.70, 0.00, 1.00)
colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00)
colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00)
colors[ImGuiCol.TableHeaderBg] = ImVec4(0.27, 0.27, 0.38, 1.00)
colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.45, 1.00)
colors[ImGuiCol.TableBorderLight] = ImVec4(0.26, 0.26, 0.28, 1.00)
colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.TableRowBgAlt] = ImVec4(1.00, 1.00, 1.00, 0.07)
colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive]
colors[ImGuiCol.TextSelectedBg] = ImVec4(0.00, 0.00, 1.00, 0.35)
colors[ImGuiCol.TreeLines] = colors[ImGuiCol.Border]
colors[ImGuiCol.DragDropTarget] = ImVec4(1.00, 1.00, 0.00, 0.90)
colors[ImGuiCol.DragDropTargetBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.UnsavedMarker] = ImVec4(0.90, 0.90, 0.90, 1.00)
colors[ImGuiCol.NavCursor] = colors[ImGuiCol.HeaderHovered]
colors[ImGuiCol.NavWindowingHighlight] = ImVec4(1.00, 1.00, 1.00, 0.70)
colors[ImGuiCol.NavWindowingDimBg] = ImVec4(0.80, 0.80, 0.80, 0.20)
colors[ImGuiCol.ModalWindowDimBg] = ImVec4(0.20, 0.20, 0.20, 0.35)
end
-- Those light colors are better suited with a thicker font than the default one + FrameBorder
--- @param dst? ImGuiStyle
function ImGui.StyleColorsLight(dst)
local style = dst and dst or ImGui.GetStyle()
local colors = style.Colors
colors[ImGuiCol.Text] = ImVec4(0.00, 0.00, 0.00, 1.00)
colors[ImGuiCol.TextDisabled] = ImVec4(0.60, 0.60, 0.60, 1.00)
colors[ImGuiCol.WindowBg] = ImVec4(0.94, 0.94, 0.94, 1.00)
colors[ImGuiCol.ChildBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.PopupBg] = ImVec4(1.00, 1.00, 1.00, 0.98)
colors[ImGuiCol.Border] = ImVec4(0.00, 0.00, 0.00, 0.30)
colors[ImGuiCol.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.FrameBg] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[ImGuiCol.FrameBgHovered] = ImVec4(0.26, 0.59, 0.98, 0.40)
colors[ImGuiCol.FrameBgActive] = ImVec4(0.26, 0.59, 0.98, 0.67)
colors[ImGuiCol.TitleBg] = ImVec4(0.96, 0.96, 0.96, 1.00)
colors[ImGuiCol.TitleBgActive] = ImVec4(0.82, 0.82, 0.82, 1.00)
colors[ImGuiCol.TitleBgCollapsed] = ImVec4(1.00, 1.00, 1.00, 0.51)
colors[ImGuiCol.MenuBarBg] = ImVec4(0.86, 0.86, 0.86, 1.00)
colors[ImGuiCol.ScrollbarBg] = ImVec4(0.98, 0.98, 0.98, 0.53)
colors[ImGuiCol.ScrollbarGrab] = ImVec4(0.69, 0.69, 0.69, 0.80)
colors[ImGuiCol.ScrollbarGrabHovered] = ImVec4(0.49, 0.49, 0.49, 0.80)
colors[ImGuiCol.ScrollbarGrabActive] = ImVec4(0.49, 0.49, 0.49, 1.00)
colors[ImGuiCol.CheckMark] = ImVec4(0.26, 0.59, 0.98, 1.00)
colors[ImGuiCol.CheckboxSelectedBg] = ImVec4(0.95, 0.97, 1.00, 1.00)
colors[ImGuiCol.SliderGrab] = ImVec4(0.26, 0.59, 0.98, 0.78)
colors[ImGuiCol.SliderGrabActive] = ImVec4(0.46, 0.54, 0.80, 0.60)
colors[ImGuiCol.Button] = ImVec4(0.26, 0.59, 0.98, 0.40)
colors[ImGuiCol.ButtonHovered] = ImVec4(0.26, 0.59, 0.98, 1.00)
colors[ImGuiCol.ButtonActive] = ImVec4(0.06, 0.53, 0.98, 1.00)
colors[ImGuiCol.Header] = ImVec4(0.26, 0.59, 0.98, 0.31)
colors[ImGuiCol.HeaderHovered] = ImVec4(0.26, 0.59, 0.98, 0.80)
colors[ImGuiCol.HeaderActive] = ImVec4(0.26, 0.59, 0.98, 1.00)
colors[ImGuiCol.Separator] = ImVec4(0.39, 0.39, 0.39, 0.62)
colors[ImGuiCol.SeparatorHovered] = ImVec4(0.14, 0.44, 0.80, 0.78)
colors[ImGuiCol.SeparatorActive] = ImVec4(0.14, 0.44, 0.80, 1.00)
colors[ImGuiCol.ResizeGrip] = ImVec4(0.35, 0.35, 0.35, 0.17)
colors[ImGuiCol.ResizeGripHovered] = ImVec4(0.26, 0.59, 0.98, 0.67)
colors[ImGuiCol.ResizeGripActive] = ImVec4(0.26, 0.59, 0.98, 0.95)
colors[ImGuiCol.InputTextCursor] = colors[ImGuiCol.Text]
colors[ImGuiCol.TabHovered] = colors[ImGuiCol.HeaderHovered]
colors[ImGuiCol.Tab] = ImLerpV4V4F(colors[ImGuiCol.Header], colors[ImGuiCol.TitleBgActive], 0.90)
colors[ImGuiCol.TabSelected] = ImLerpV4V4F(colors[ImGuiCol.HeaderActive], colors[ImGuiCol.TitleBgActive], 0.60)
colors[ImGuiCol.TabSelectedOverline] = colors[ImGuiCol.HeaderActive]
colors[ImGuiCol.TabDimmed] = ImLerpV4V4F(colors[ImGuiCol.Tab], colors[ImGuiCol.TitleBg], 0.80)
colors[ImGuiCol.TabDimmedSelected] = ImLerpV4V4F(colors[ImGuiCol.TabSelected], colors[ImGuiCol.TitleBg], 0.40)
colors[ImGuiCol.TabDimmedSelectedOverline] = ImVec4(0.26, 0.59, 1.00, 0.00)
colors[ImGuiCol.PlotLines] = ImVec4(0.39, 0.39, 0.39, 1.00)
colors[ImGuiCol.PlotLinesHovered] = ImVec4(1.00, 0.43, 0.35, 1.00)
colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00)
colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.45, 0.00, 1.00)
colors[ImGuiCol.TableHeaderBg] = ImVec4(0.78, 0.87, 0.98, 1.00)
colors[ImGuiCol.TableBorderStrong] = ImVec4(0.57, 0.57, 0.64, 1.00)
colors[ImGuiCol.TableBorderLight] = ImVec4(0.68, 0.68, 0.74, 1.00)
colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.TableRowBgAlt] = ImVec4(0.30, 0.30, 0.30, 0.09)
colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive]
colors[ImGuiCol.TextSelectedBg] = ImVec4(0.26, 0.59, 0.98, 0.35)
colors[ImGuiCol.TreeLines] = colors[ImGuiCol.Border]
colors[ImGuiCol.DragDropTarget] = ImVec4(0.26, 0.59, 0.98, 0.95)
colors[ImGuiCol.DragDropTargetBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[ImGuiCol.UnsavedMarker] = ImVec4(0.00, 0.00, 0.00, 1.00)
colors[ImGuiCol.NavCursor] = colors[ImGuiCol.HeaderHovered]
colors[ImGuiCol.NavWindowingHighlight] = ImVec4(0.70, 0.70, 0.70, 0.70)
colors[ImGuiCol.NavWindowingDimBg] = ImVec4(0.20, 0.20, 0.20, 0.20)
colors[ImGuiCol.ModalWindowDimBg] = ImVec4(0.20, 0.20, 0.20, 0.35)
end
--- @param draw_list ImDrawList
--- @param vert_start_idx int
--- @param vert_end_idx int
--- @param gradient_p0 ImVec2
--- @param gradient_p1 ImVec2
--- @param col0 ImU32
--- @param col1 ImU32
function ImGui.ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col0, col1)
local gradient_extent = gradient_p1 - gradient_p0
local gradient_inv_length2 = 1.0 / ImLengthSqr(gradient_extent)
local col0_r = bit32.band(bit32.rshift(col0, IM_COL32_R_SHIFT), 0xFF)
local col0_g = bit32.band(bit32.rshift(col0, IM_COL32_G_SHIFT), 0xFF)
local col0_b = bit32.band(bit32.rshift(col0, IM_COL32_B_SHIFT), 0xFF)
local col_delta_r = bit32.band(bit32.rshift(col1, IM_COL32_R_SHIFT), 0xFF) - col0_r
local col_delta_g = bit32.band(bit32.rshift(col1, IM_COL32_G_SHIFT), 0xFF) - col0_g
local col_delta_b = bit32.band(bit32.rshift(col1, IM_COL32_B_SHIFT), 0xFF) - col0_b
for vert_idx = vert_start_idx, vert_end_idx - 1 do
local vert = draw_list.VtxBuffer.Data[vert_idx]
local d = ImDot(vert[1] - gradient_p0, gradient_extent)
local t = ImClamp(d * gradient_inv_length2, 0.0, 1.0)
local r = math.floor(col0_r + col_delta_r * t)
local g = math.floor(col0_g + col_delta_g * t)
local b = math.floor(col0_b + col_delta_b * t)
vert[3] = bit32.bor(bit32.lshift(r, IM_COL32_R_SHIFT), bit32.lshift(g, IM_COL32_G_SHIFT), bit32.lshift(b, IM_COL32_B_SHIFT), bit32.band(vert[3], IM_COL32_A_MASK))
end
end
-- Distribute UV over (a, b) rectangle
--- @param draw_list ImDrawList
--- @param vert_start_idx int
--- @param vert_end_idx int
--- @param a ImVec2
--- @param b ImVec2
--- @param uv_a ImVec2
--- @param uv_b ImVec2
--- @param clamp bool
function ImGui.ShadeVertsLinearUV(draw_list, vert_start_idx, vert_end_idx, a, b, uv_a, uv_b, clamp)
local size = b - a
local uv_size = uv_b - uv_a
local scale = ImVec2(
(size.x ~= 0.0) and (uv_size.x / size.x) or 0.0,
(size.y ~= 0.0) and (uv_size.y / size.y) or 0.0
)
local vertex
local verts = draw_list.VtxBuffer.Data
if clamp then
local min = ImMin(uv_a, uv_b)
local max = ImMax(uv_a, uv_b)
for vert_idx = vert_start_idx, vert_end_idx - 1 do
vertex = verts[vert_idx]
ImVec2_Copy(vertex[2], ImClamp(uv_a + ImMul(vertex[1] - a, scale), min, max))
end
else
for vert_idx = vert_start_idx, vert_end_idx - 1 do
vertex = verts[vert_idx]
ImVec2_Copy(vertex[2], uv_a + ImMul(vertex[1] - a, scale))
end
end
end
--- Forward Declarations
local ImFontAtlasTextureAdd
local ImFontAtlasTextureGrow
local ImFontAtlasTextureGetSizeEstimate
local ImFontAtlasTextureBlockCopy
local ImFontAtlasTextureBlockConvert
local ImFontAtlasTextureBlockPostProcess
local ImFontAtlasTextureBlockPostProcessMultiply
local ImFontAtlasTextureBlockQueueUpload
local ImFontAtlasTextureCompact
local ImFontAtlasPackInit
local ImFontAtlasPackAddRect
local ImFontAtlasPackGetRect
local ImFontAtlasPackGetRectSafe
local ImFontAtlasBakedAdd
local ImFontAtlasBakedAddFontGlyph
local ImFontAtlasBakedAddFontGlyphAdvancedX
local ImFontAtlasBakedDiscard
local ImFontAtlasBakedGetOrAdd
local ImFontAtlasBakedGetId
local ImFontAtlasBakedGetClosestMatch
local ImFontAtlasBuildInit
local ImFontAtlasBuildSetTexture
local ImFontAtlasBuildUpdateTexDataLines
local ImFontAtlasBuildUpdateTexDataBasic
local ImFontAtlasBuildSetupFontLoader
local ImFontAtlasBuildSetupFontSpecialGlyphs
local ImFontAtlasBuildSetupFontBakedBlanks
local ImFontAtlasBuildSetupFontBakedEllipsis
local ImFontAtlasBuildSetupFontBakedFallback
local ImFontAtlasBuildDestroy
local ImFontAtlasBuildAcceptCodepointForSource
local ImFontAtlasBuildNotifySetFont
local ImFontAtlasBuildRenderBitmapFromString
local ImFontAtlasFontSourceInit
local ImFontAtlasFontSourceAddToFont
local ImFontAtlasFontDestroySourceData
local ImFontAtlasFontDestroyOutput
local ImFontBaked_BuildGrowIndex
local ImFontBaked_BuildLoadGlyph
local ImFontBaked_BuildLoadGlyphAdvanceX
local ImTextInitClassifiers
local ImTextClassifierGet
local ImTextClassifierClear
local ImTextClassifierSetCharClass
local ImTextClassifierSetCharClassFromStr
local ImTextureDataGetFormatBytesPerPixel
function MT.ImFontAtlas:Clear()
IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlas:Clear()")
local backup_renderer_has_textures = self.RendererHasTextures
self.RendererHasTextures = false
self:ClearFonts()
self:ClearTexData()
self.RendererHasTextures = backup_renderer_has_textures
end
function MT.ImFontAtlas:SetFontLoader(font_loader)
ImFontAtlasBuildSetupFontLoader(self, font_loader)
end
function MT.ImFontAtlas:ClearInputData()
IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!")
for _, font in self.Fonts:iter() do
ImFontAtlasFontDestroyOutput(self, font)
end
for _, font_cfg in self.Sources:iter() do
ImFontAtlasFontDestroySourceData(self, font_cfg)
end
for _, font in self.Fonts:iter() do
font.Sources:clear()
font.Flags = bit32.bor(font.Flags, ImFontFlags.NoLoadGlyphs)
end
self.Sources:clear()
end
function MT.ImFontAtlas:ClearTexData()
IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!")
IM_ASSERT(self.RendererHasTextures == false, "Not supported for dynamic atlases, but you may call Clear().")
for _, tex in self.TexList:iter() do
tex:DestroyPixels()
end
end
function MT.ImFontAtlas:CompactCache()
ImFontAtlasTextureCompact(self)
end
function MT.ImFontAtlas:ClearFonts()
IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlas:ClearFonts()")
IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!")
for _, font in self.Fonts:iter() do
ImFontAtlasBuildNotifySetFont(self, font, nil)
end
ImFontAtlasBuildDestroy(self)
self:ClearInputData()
self.Fonts:clear_delete()
self.TexIsBuilt = false
for _, shared_data in self.DrawListSharedDatas:iter() do
if shared_data.FontAtlas == self then
shared_data.Font = nil
shared_data.FontSize = 0.0
shared_data.FontScale = 0.0
end
end
end
--- @param tex ImTextureData
function ImTextureDataUpdateNewFrame(tex)
local remove_from_list = false
if tex.Status == ImTextureStatus.OK then
tex.Updates:resize(0)
tex.UpdateRect.x = 65535 tex.UpdateRect.y = 65535
tex.UpdateRect.w = 0 tex.UpdateRect.h = 0
end
if (tex.WantDestroyNextFrame and tex.Status ~= ImTextureStatus.Destroyed and tex.Status ~= ImTextureStatus.WantDestroy) then
IM_ASSERT(tex.Status == ImTextureStatus.OK or tex.Status == ImTextureStatus.WantCreate or tex.Status == ImTextureStatus.WantUpdates)
tex.Status = ImTextureStatus.WantDestroy
end
if (tex.Status == ImTextureStatus.WantDestroy and tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil and tex.QueueUserData == nil) then
tex.Status = ImTextureStatus.Destroyed
end
if (tex.Status == ImTextureStatus.Destroyed) then
IM_ASSERT(tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil, "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!")
IM_ASSERT(tex.QueueUserData == nil, "Texture queue set Status to Destroyed but did not clear QueueUserData!")
if (tex.WantDestroyNextFrame) then
remove_from_list = true
else
tex.Status = ImTextureStatus.WantCreate
end
end
if (tex.Status == ImTextureStatus.WantDestroy) then
tex.UnusedFrames = tex.UnusedFrames + 1
end
return remove_from_list
end
--- @param atlas ImFontAtlas
--- @param frame_count int
--- @param renderer_has_textures any
function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures)
IM_ASSERT(atlas.Builder == nil or atlas.Builder.FrameCount < frame_count)
atlas.RendererHasTextures = renderer_has_textures
local tex_n = 1
while tex_n <= atlas.TexList.Size do
local tex = atlas.TexList.Data[tex_n]
if (tex.Status == ImTextureStatus.WantCreate and atlas.RendererHasTextures) then
IM_ASSERT(tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil, "Backend set texture's TexID/BackendUserData but did not update Status to OK.")
end
local remove_from_list = ImTextureDataUpdateNewFrame(tex)
if remove_from_list then
IM_ASSERT(atlas.TexData ~= tex)
tex:DestroyPixels()
atlas.TexList:erase(tex_n)
tex_n = tex_n - 1
end
tex_n = tex_n + 1
end
if (atlas.RendererHasTextures) then
atlas.TexIsBuilt = true
if (atlas.Builder == nil) then
ImFontAtlasBuildMain(atlas)
end
end
if (not atlas.RendererHasTextures) then
IM_ASSERT_USER_ERROR(atlas.TexIsBuilt, "Backend does not support ImGuiBackendFlags.RendererHasTextures, and font atlas is not built! Update backend OR make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8().")
end
if (atlas.TexIsBuilt and atlas.Builder.PreloadedAllGlyphsRanges) then
IM_ASSERT_USER_ERROR(atlas.RendererHasTextures == false, "Called ImFontAtlas::Build() before ImGuiBackendFlags.RendererHasTextures got set! With new backends: you don't need to call Build().")
end
local builder = atlas.Builder
builder.FrameCount = frame_count
for _, font in atlas.Fonts:iter() do
font.LastBaked = nil
end
if builder.BakedDiscardedCount > 0 then
local dst_n = 1
for src_n = 1, builder.BakedPool.Size do
repeat
local p_src = builder.BakedPool.Data[src_n]
if p_src.WantDestroy then
break
end
local p_dst = builder.BakedPool.Data[dst_n]
dst_n = dst_n + 1
if p_dst == p_src then
break
end
builder.BakedPool.Data[dst_n - 1] = p_src
builder.BakedMap[p_src.BakedId] = p_src
until true
end
IM_ASSERT(dst_n - 1 + builder.BakedDiscardedCount == builder.BakedPool.Size)
builder.BakedPool.Size = builder.BakedPool.Size - builder.BakedDiscardedCount
builder.BakedDiscardedCount = 0
end
end
--- @param src_pixels unsigned_char[]
--- @param src_fmt ImTextureFormat
--- @param src_pitch int
--- @param dst_pixels unsigned_char[]
--- @param dst_pixels_base int
--- @param dst_fmt ImTextureFormat
--- @param dst_pitch int
--- @param w int
--- @param h int
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)
local src_pixels_base = 1
if src_fmt == dst_fmt then
local line_sz = w * ImTextureDataGetFormatBytesPerPixel(src_fmt)
for ny = h, 1, -1 do
ImStd.memmove(dst_pixels, dst_pixels_base, src_pixels, src_pixels_base, line_sz)
src_pixels_base = src_pixels_base + src_pitch
dst_pixels_base = dst_pixels_base + dst_pitch
end
elseif src_fmt == ImTextureFormat.Alpha8 and dst_fmt == ImTextureFormat.RGBA32 then
for ny = h, 1, -1 do
for nx = w, 1, -1 do
local alpha = src_pixels[src_pixels_base + 0]
src_pixels_base = src_pixels_base + 1
write_u32(dst_pixels, dst_pixels_base, IM_COL32(255, 255, 255, alpha))
dst_pixels_base = dst_pixels_base + 4
end
src_pixels_base = src_pixels_base + (src_pitch - w)
dst_pixels_base = dst_pixels_base + (dst_pitch - w * 4)
end
elseif src_fmt == ImTextureFormat.RGBA32 and dst_fmt == ImTextureFormat.Alpha8 then
for ny = h, 1, -1 do
for nx = w, 1, -1 do
local alpha = src_pixels[src_pixels_base + 3]
src_pixels_base = src_pixels_base + 4
dst_pixels[dst_pixels_base + 0] = alpha
dst_pixels_base = dst_pixels_base + 1
end
src_pixels_base = src_pixels_base + (src_pitch - w * 4)
dst_pixels_base = dst_pixels_base + (dst_pitch - w)
end
else
IM_ASSERT(false)
end
end
--- @param data ImFontAtlasPostProcessData
function ImFontAtlasTextureBlockPostProcess(data)
if data.FontSrc.RasterizerMultiply ~= 1.0 then
ImFontAtlasTextureBlockPostProcessMultiply(data, data.FontSrc.RasterizerMultiply)
end
end
--- @param data ImFontAtlasPostProcessData
--- @param multiply_factor float
function ImFontAtlasTextureBlockPostProcessMultiply(data, multiply_factor)
local pixels, pixels_base = data.Pixels, data._PixelsBase
local pitch = data.Pitch
if data.Format == ImTextureFormat.Alpha8 then
for ny = data.Height, 1, -1 do
local p = pixels_base
for nx = data.Width, 1, -1 do
local v = ImMin(ImFloor(pixels[p + 0] * multiply_factor), 255)
pixels[p + 0] = v
p = p + 1
end
pixels_base = pixels_base + pitch
end
elseif data.Format == ImTextureFormat.RGBA32 then
for ny = data.Height, 1, -1 do
local p = pixels_base
for nx = data.Width, 1, -1 do
local a = ImMin(ImFloor(pixels[p + 3] * multiply_factor), 255)
write_u32(pixels, p, IM_COL32(pixels[p + 0], pixels[p + 1], pixels[p + 2], a))
p = p + 4
end
pixels_base = pixels_base + pitch
end
else
IM_ASSERT(false)
end
end
--- @param src_tex ImTextureData
--- @param src_x int
--- @param src_y int
--- @param dst_tex ImTextureData
--- @param dst_x int
--- @param dst_y int
--- @param w int
--- @param h int
function ImFontAtlasTextureBlockCopy(src_tex, src_x, src_y, dst_tex, dst_x, dst_y, w, h)
IM_ASSERT(src_tex.Pixels ~= nil and dst_tex.Pixels ~= nil)
IM_ASSERT(src_tex.Format == dst_tex.Format)
IM_ASSERT(src_x >= 0 and src_x + w <= src_tex.Width)
IM_ASSERT(src_y >= 0 and src_y + h <= src_tex.Height)
IM_ASSERT(dst_x >= 0 and dst_x + w <= dst_tex.Width)
IM_ASSERT(dst_y >= 0 and dst_y + h <= dst_tex.Height)
for y = 0, h - 1 do
local dst, dst_base = dst_tex:GetPixelsAt(dst_x, dst_y + y)
local src, src_base = src_tex:GetPixelsAt(src_x, src_y + y)
ImStd.memmove(dst, dst_base, src, src_base, w * dst_tex.BytesPerPixel)
end
end
--- @param tex ImTextureData
--- @param x int
--- @param y int
--- @param w int
--- @param h int
local function ImTextureDataQueueUpload(tex, x, y, w, h)
IM_ASSERT(tex.Status ~= ImTextureStatus.WantDestroy and tex.Status ~= ImTextureStatus.Destroyed)
IM_ASSERT(x >= 0 and x <= 0xFFFF and y >= 0 and y <= 0xFFFF and w >= 0 and x + w <= 0x10000 and h >= 0 and y + h <= 0x10000)
local req = ImTextureRect(x, y, w, h) -- (unsigned short)
local new_x1 = ImMax(tex.UpdateRect.w == 0 and 0 or tex.UpdateRect.x + tex.UpdateRect.w, req.x + req.w)
local new_y1 = ImMax(tex.UpdateRect.h == 0 and 0 or tex.UpdateRect.y + tex.UpdateRect.h, req.y + req.h)
tex.UpdateRect.x = ImMin(tex.UpdateRect.x, req.x)
tex.UpdateRect.y = ImMin(tex.UpdateRect.y, req.y)
tex.UpdateRect.w = (new_x1 - tex.UpdateRect.x) -- (unsigned short)
tex.UpdateRect.h = (new_y1 - tex.UpdateRect.y) -- (unsigned short)
tex.UsedRect.x = ImMin(tex.UsedRect.x, req.x)
tex.UsedRect.y = ImMin(tex.UsedRect.y, req.y)
tex.UsedRect.w = (ImMax(tex.UsedRect.x + tex.UsedRect.w, req.x + req.w) - tex.UsedRect.x) -- (unsigned short)
tex.UsedRect.h = (ImMax(tex.UsedRect.y + tex.UsedRect.h, req.y + req.h) - tex.UsedRect.y) -- (unsigned short)
if (tex.Status == ImTextureStatus.OK or tex.Status == ImTextureStatus.WantUpdates) then
tex.Status = ImTextureStatus.WantUpdates
tex.Updates:push_back(req)
end
end
--- @param atlas ImFontAtlas
--- @param tex ImTextureData
--- @param x int
--- @param y int
--- @param w int
--- @param h int
function ImFontAtlasTextureBlockQueueUpload(atlas, tex, x, y, w, h)
ImTextureDataQueueUpload(tex, x, y, w, h)
atlas.TexIsBuilt = false
end
--- @param atlas ImFontAtlas
--- @param baked ImFontBaked
--- @param src ImFontConfig
--- @param glyph ImFontGlyph
--- @param r ImTextureRect
--- @param src_pixels unsigned_char[]
--- @param src_fmt ImTextureFormat
--- @param src_pitch int
local function ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, src_pixels, src_fmt, src_pitch)
local tex = atlas.TexData
IM_ASSERT(r.x + r.w <= tex.Width and r.y + r.h <= tex.Height)
local out_p, out_p_base = tex:GetPixelsAt(r.x, r.y)
IM_ASSERT(out_p ~= nil)
ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, out_p, out_p_base, tex.Format, tex:GetPitch(), r.w, r.h)
local pp_data = ImFontAtlasPostProcessData(atlas, baked.OwnerFont, src, baked, glyph, out_p, out_p_base, tex.Format, tex:GetPitch(), r.w, r.h)
ImFontAtlasTextureBlockPostProcess(pp_data)
ImFontAtlasTextureBlockQueueUpload(atlas, tex, r.x, r.y, r.w, r.h)
end
local function ImFontAtlasBuildGetOversampleFactors(src, baked)
local raster_size = baked.Size * baked.RasterizerDensity * src.RasterizerDensity
local out_oversample_h
if src.OversampleH ~= 0 then
out_oversample_h = src.OversampleH
elseif raster_size > 36.0 or src.PixelSnapH then
out_oversample_h = 1
else
out_oversample_h = 2
end
local out_oversample_v = (src.OversampleV ~= 0) and src.OversampleV or 1
return out_oversample_h, out_oversample_v
end
local function ImFontAtlasBuildDiscardBakes(atlas, unused_frames)
local builder = atlas.Builder
for baked_n = 1, builder.BakedPool.Size do
repeat
local baked = builder.BakedPool[baked_n]
if (baked.LastUsedFrame + unused_frames > atlas.Builder.FrameCount) then
break
end
if (baked.WantDestroy or (bit32.band(baked.OwnerFont.Flags, ImFontFlags.LockBakedSizes) ~= 0)) then
break
end
ImFontAtlasBakedDiscard(atlas, baked.OwnerFont, baked)
until true
end
end
--- @param atlas ImFontAtlas
--- @param data ImDrawListSharedData
function ImFontAtlasAddDrawListSharedData(atlas, data)
IM_ASSERT(not atlas.DrawListSharedDatas:contains(data))
atlas.DrawListSharedDatas:push_back(data)
end
--- @param atlas ImFontAtlas
--- @param data ImDrawListSharedData
function ImFontAtlasRemoveDrawListSharedData(atlas, data)
IM_ASSERT(atlas.DrawListSharedDatas:contains(data))
atlas.DrawListSharedDatas:find_erase(data)
end
--- @param atlas ImFontAtlas
--- @param w int
--- @param h int
local function ImFontAtlasTextureRepack(atlas, w, h)
local builder = atlas.Builder
builder.LockDisableResize = true
local old_tex = atlas.TexData
local new_tex = ImFontAtlasTextureAdd(atlas, w, h)
new_tex.UseColors = old_tex.UseColors
IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d", old_tex.UniqueID, old_tex.Width, old_tex.Height, new_tex.UniqueID, new_tex.Width, new_tex.Height)
ImFontAtlasPackInit(atlas)
local old_rects = ImVector()
local old_index = builder.RectsIndex:copy()
old_rects:swap(builder.Rects)
for _, index_entry in builder.RectsIndex:iter() do
repeat
if index_entry.IsUsed == false then
break
end
local old_r = old_rects[index_entry.TargetIndex + 1]
if (old_r.w == 0 and old_r.h == 0) then
break
end
local new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, index_entry)
if new_r_id == ImFontAtlasRectId_Invalid then
IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize failed. Will grow.", new_tex.UniqueID)
new_tex.WantDestroyNextFrame = true
builder.Rects:swap(old_rects)
builder.RectsIndex = old_index
ImFontAtlasBuildSetTexture(atlas, old_tex)
ImFontAtlasTextureGrow(atlas, w, h)
return
end
IM_ASSERT(ImFontAtlasRectId_GetIndex(new_r_id) == builder.RectsIndex:index_from_ptr(index_entry))
local new_r = ImFontAtlasPackGetRect(atlas, new_r_id)
ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r.x, new_r.y, new_r.w, new_r.h)
until true
end
IM_ASSERT(old_rects.Size == builder.Rects.Size + builder.RectsDiscardedCount)
builder.RectsDiscardedCount = 0
builder.RectsDiscardedSurface = 0
for baked_n = 1, builder.BakedPool.Size do
for _, glyph in builder.BakedPool[baked_n].Glyphs:iter() do
if (glyph.PackId ~= ImFontAtlasRectId_Invalid) then
local r = ImFontAtlasPackGetRect(atlas, glyph.PackId)
glyph.U0 = (r.x) * atlas.TexUvScale.x
glyph.V0 = (r.y) * atlas.TexUvScale.y
glyph.U1 = (r.x + r.w) * atlas.TexUvScale.x
glyph.V1 = (r.y + r.h) * atlas.TexUvScale.y
end
end
end
ImFontAtlasBuildUpdateTexData(atlas)
builder.LockDisableResize = false
ImFontAtlasUpdateDrawListsSharedData(atlas)
-- ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack");
end
function ImFontAtlasTextureGrow(atlas, old_tex_w, old_tex_h)
local builder = atlas.Builder
old_tex_w = old_tex_w or -1
old_tex_h = old_tex_h or -1
if (old_tex_w == -1) then
old_tex_w = atlas.TexData.Width
end
if (old_tex_h == -1) then
old_tex_h = atlas.TexData.Height
end
IM_ASSERT(ImIsPowerOfTwo(old_tex_w) and ImIsPowerOfTwo(old_tex_h))
IM_ASSERT(ImIsPowerOfTwo(atlas.TexMinWidth) and ImIsPowerOfTwo(atlas.TexMaxWidth) and ImIsPowerOfTwo(atlas.TexMinHeight) and ImIsPowerOfTwo(atlas.TexMaxHeight))
local new_tex_w = (old_tex_h <= old_tex_w) and old_tex_w or old_tex_w * 2
local new_tex_h = (old_tex_h <= old_tex_w) and old_tex_h * 2 or old_tex_h
local pack_padding = atlas.TexGlyphPadding
new_tex_w = ImMax(new_tex_w, ImUpperPowerOfTwo(builder.MaxRectSize.x + pack_padding))
new_tex_h = ImMax(new_tex_h, ImUpperPowerOfTwo(builder.MaxRectSize.y + pack_padding))
new_tex_w = ImClamp(new_tex_w, atlas.TexMinWidth, atlas.TexMaxWidth)
new_tex_h = ImClamp(new_tex_h, atlas.TexMinHeight, atlas.TexMaxHeight)
if (new_tex_w == old_tex_w and new_tex_h == old_tex_h) then
return
end
ImFontAtlasTextureRepack(atlas, new_tex_w, new_tex_h)
end
--- @param atlas ImFontAtlas
local function ImFontAtlasTextureMakeSpace(atlas)
local builder = atlas.Builder
ImFontAtlasBuildDiscardBakes(atlas, 2)
if (builder.RectsDiscardedSurface < builder.RectsPackedSurface * 0.20) then
ImFontAtlasTextureGrow(atlas)
else
ImFontAtlasTextureRepack(atlas, atlas.TexData.Width, atlas.TexData.Height)
end
end
--- @param atlas ImFontAtlas
--- @param rect_idx ImFontAtlasRectId
local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx)
local builder = atlas.Builder
local index_idx, index_entry
if builder.RectsIndexFreeListStart < 0 then
builder.RectsIndex:resize(builder.RectsIndex.Size + 1)
index_idx = builder.RectsIndex.Size - 1
index_entry = ImFontAtlasRectEntry()
builder.RectsIndex.Data[builder.RectsIndex.Size] = index_entry
else
index_idx = builder.RectsIndexFreeListStart
index_entry = builder.RectsIndex[index_idx + 1]
IM_ASSERT(index_entry.IsUsed == false and index_entry.Generation > 0)
builder.RectsIndexFreeListStart = index_entry.TargetIndex
end
index_entry.TargetIndex = rect_idx
index_entry.IsUsed = true
return ImFontAtlasRectId_Make(index_idx, index_entry.Generation)
end
--- @param atlas ImFontAtlas
--- @param index_entry ImFontAtlasRectEntry
local function ImFontAtlasPackReuseRectEntry(atlas, index_entry)
IM_ASSERT(index_entry.IsUsed)
index_entry.TargetIndex = atlas.Builder.Rects.Size - 1
local index_idx = atlas.Builder.RectsIndex:index_from_ptr(index_entry)
return ImFontAtlasRectId_Make(index_idx, index_entry.Generation)
end
--- @param atlas ImFontAtlas
--- @param id ImFontAtlasRectId
function ImFontAtlasPackDiscardRect(atlas, id)
IM_ASSERT(id ~= ImFontAtlasRectId_Invalid)
local rect = ImFontAtlasPackGetRect(atlas, id)
if (rect == nil) then
return
end
local builder = atlas.Builder
local index_idx = ImFontAtlasRectId_GetIndex(id)
local index_entry = builder.RectsIndex.Data[index_idx + 1]
IM_ASSERT(index_entry.IsUsed and index_entry.TargetIndex >= 0)
index_entry.IsUsed = false
index_entry.TargetIndex = builder.RectsIndexFreeListStart
index_entry.Generation = index_entry.Generation + 1
if (index_entry.Generation == 0) then
index_entry.Generation = index_entry.Generation + 1
end
local pack_padding = atlas.TexGlyphPadding
builder.RectsIndexFreeListStart = index_idx
builder.RectsDiscardedCount = builder.RectsDiscardedCount + 1
builder.RectsDiscardedSurface = builder.RectsDiscardedSurface + ((rect.w + pack_padding) * (rect.h + pack_padding))
rect.w = 0 rect.h = 0
end
function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry)
IM_ASSERT(w > 0 and w <= 0xFFFF)
IM_ASSERT(h > 0 and h <= 0xFFFF)
local builder = atlas.Builder
local pack_padding = atlas.TexGlyphPadding
builder.MaxRectSize.x = ImMax(builder.MaxRectSize.x, w)
builder.MaxRectSize.y = ImMax(builder.MaxRectSize.y, h)
local r = ImTextureRect(0, 0, w, h)
for attempts_remaining = 3, 0, -1 do
local pack_r = stbrp.rect()
pack_r.w = w + pack_padding
pack_r.h = h + pack_padding
stbrp.pack_rects(builder.PackContext, {pack_r}, 1)
r.x = pack_r.x -- (unsigned short)
r.y = pack_r.y -- (unsigned short)
if pack_r.was_packed == 1 then
break
end
if (attempts_remaining == 0 or builder.LockDisableResize) then
IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.", w, h)
return ImFontAtlasRectId_Invalid
end
ImFontAtlasTextureMakeSpace(atlas)
end
builder.MaxRectBounds.x = ImMax(builder.MaxRectBounds.x, r.x + r.w + pack_padding)
builder.MaxRectBounds.y = ImMax(builder.MaxRectBounds.y, r.y + r.h + pack_padding)
builder.RectsPackedCount = builder.RectsPackedCount + 1
builder.RectsPackedSurface = builder.RectsPackedSurface + (w + pack_padding) * (h + pack_padding)
builder.Rects:push_back(r)
if (overwrite_entry ~= nil) then
return ImFontAtlasPackReuseRectEntry(atlas, overwrite_entry)
else
return ImFontAtlasPackAllocRectEntry(atlas, builder.Rects.Size - 1)
end
end
--- @param atlas ImFontAtlas
--- @param id ImFontAtlasRectId
--- @return ImTextureRect
function ImFontAtlasPackGetRect(atlas, id)
IM_ASSERT(id ~= ImFontAtlasRectId_Invalid)
local index_idx = ImFontAtlasRectId_GetIndex(id)
local builder = atlas.Builder
local index_entry = builder.RectsIndex.Data[index_idx + 1]
IM_ASSERT(index_entry.Generation == ImFontAtlasRectId_GetGeneration(id))
IM_ASSERT(index_entry.IsUsed)
--- @type ImTextureRect
return builder.Rects.Data[index_entry.TargetIndex + 1]
end
--- @param atlas ImFontAtlas
--- @param id ImFontAtlasRectId
function ImFontAtlasPackGetRectSafe(atlas, id)
if id == ImFontAtlasRectId_Invalid then
return nil
end
local index_idx = ImFontAtlasRectId_GetIndex(id)
if atlas.Builder == nil then
ImFontAtlasBuildInit(atlas)
end
local builder = atlas.Builder
if index_idx >= builder.RectsIndex.Size then
return nil
end
local index_entry = builder.RectsIndex.Data[index_idx + 1]
if (index_entry.Generation ~= ImFontAtlasRectId_GetGeneration(id) or not index_entry.IsUsed) then
return nil
end
return builder.Rects.Data[index_entry.TargetIndex + 1]
end
--- @param src ImFontConfig
--- @param codepoint ImWchar
--- @return bool
function ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)
local exclude_list = src.GlyphExcludeRanges
if exclude_list then
local i = 1
while exclude_list[i] ~= 0 do
if codepoint >= exclude_list[i] and codepoint <= exclude_list[i + 1] then
return false
end
i = i + 2
end
end
return true
end
--- @param baked ImFontBaked
--- @param new_size int
function ImFontBaked_BuildGrowIndex(baked, new_size)
IM_ASSERT(baked.IndexAdvanceX.Size == baked.IndexLookup.Size)
if (new_size <= baked.IndexLookup.Size) then
return
end
baked.IndexAdvanceX:resize(new_size, -1.0)
baked.IndexLookup:resize(new_size, IM_FONTGLYPH_INDEX_UNUSED)
end
--- @class ImGui_ImplStbTrueType_FontSrcData
--- @field FontInfo stbtt_fontinfo
--- @field ScaleFactor float
--- @return ImGui_ImplStbTrueType_FontSrcData
--- @nodiscard
local function ImGui_ImplStbTrueType_FontSrcData()
return {
FontInfo = stbtt.fontinfo(),
ScaleFactor = nil
}
end
-- Need this in Lua since I don't want to include 'stbrp' just for context constructor
-- in ImFontAtlasBuilder def code. The cpp code has 'stbrp_context_opaque' which I don't/can't have here
--- @param atlas ImFontAtlas
local function ImGui_ImplStbTrueType_LoaderInit(atlas)
atlas.Builder.PackContext = atlas.Builder.PackContext or stbrp.context()
end
local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src)
-- IM_UNUSED(atlas)
--- @type ImGui_ImplStbTrueType_FontSrcData?
local bd_font_data = ImGui_ImplStbTrueType_FontSrcData()
IM_ASSERT(src.FontLoaderData == nil)
local font_offset = stbtt.GetFontOffsetForIndex(src.FontData, src.FontNo)
if font_offset < 0 then
bd_font_data = nil
IM_ASSERT_USER_ERROR(0, "stbtt_GetFontOffsetForIndex(): FontData is incorrect, or FontNo cannot be found.")
return false
end
if (not stbtt.InitFont(bd_font_data.FontInfo, src.FontData, font_offset)) then
bd_font_data = nil
IM_ASSERT_USER_ERROR(0, "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize.")
return false
end
src.FontLoaderData = bd_font_data
local ref_size = src.DstFont.Sources[1].SizePixels
if (src.MergeMode and src.SizePixels == 0.0) then
src.SizePixels = ref_size
end
bd_font_data.ScaleFactor = stbtt.ScaleForPixelHeight(bd_font_data.FontInfo, 1.0)
if (src.MergeMode and src.SizePixels ~= 0.0 and ref_size ~= 0.0) then
bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * (src.SizePixels / ref_size)
end
bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * src.ExtraSizeScale
return true
end
local function ImGui_ImplStbTrueType_FontSrcDestroy(atlas, src)
-- IM_UNUSED(atlas)
src.FontLoaderData = nil
end
local function ImGui_ImplStbTrueType_FontSrcContainsGlyph(atlas, src, codepoint)
-- IM_UNUSED(atlas)
local bd_font_data = src.FontLoaderData
IM_ASSERT(bd_font_data ~= nil)
local glyph_index = stbtt.FindGlyphIndex(bd_font_data.FontInfo, codepoint)
return (glyph_index ~= 0)
end
local function ImGui_ImplStbTrueType_FontBakedInit(atlas, src, baked)
-- IM_UNUSED(atlas)
local bd_font_data = src.FontLoaderData
if (src.MergeMode == false) then
local scale_for_layout = bd_font_data.ScaleFactor * baked.Size / src.ExtraSizeScale
local unscaled_ascent, unscaled_descent, unscaled_line_gap = stbtt.GetFontVMetrics(bd_font_data.FontInfo)
baked.Ascent = ImCeil(unscaled_ascent * scale_for_layout)
baked.Descent = ImFloor(unscaled_descent * scale_for_layout)
end
return true
end
--- @param atlas ImFontAtlas
--- @param src ImFontConfig
--- @param baked ImFontBaked
--- @param _ any
--- @param codepoint ImWchar
--- @param out_glyph ImFontGlyph
--- @param advance_x? float
--- @return bool
--- @return float? out_advance_x # Updated `advance_x`
local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, codepoint, out_glyph, advance_x)
local bd_font_data = src.FontLoaderData
IM_ASSERT(bd_font_data ~= nil)
local glyph_index = stbtt.FindGlyphIndex(bd_font_data.FontInfo, codepoint)
if (glyph_index == 0) then
return false, advance_x
end
local oversample_h, oversample_v = ImFontAtlasBuildGetOversampleFactors(src, baked)
local scale_for_layout = bd_font_data.ScaleFactor * baked.Size
local rasterizer_density = src.RasterizerDensity * baked.RasterizerDensity
local scale_for_raster_x = bd_font_data.ScaleFactor * baked.Size * rasterizer_density * oversample_h
local scale_for_raster_y = bd_font_data.ScaleFactor * baked.Size * rasterizer_density * oversample_v
local x0, y0, x1, y1 = stbtt.GetGlyphBitmapBoxSubpixel(bd_font_data.FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0)
local advance, lsb = stbtt.GetGlyphHMetrics(bd_font_data.FontInfo, glyph_index)
if (advance_x ~= nil) then
IM_ASSERT(out_glyph == nil)
advance_x = advance * scale_for_layout
return true, advance_x
end
out_glyph.Codepoint = codepoint
out_glyph.AdvanceX = advance * scale_for_layout
local is_visible = (x0 ~= x1 and y0 ~= y1)
if is_visible then
local w = (x1 - x0 + oversample_h - 1)
local h = (y1 - y0 + oversample_v - 1)
local pack_id = ImFontAtlasPackAddRect(atlas, w, h)
if (pack_id == ImFontAtlasRectId_Invalid) then
-- Pathological out of memory case (TexMaxWidth/TexMaxHeight set too small?)
IM_ASSERT(pack_id ~= ImFontAtlasRectId_Invalid, "Out of texture memory.")
return false, advance_x
end
local r = ImFontAtlasPackGetRect(atlas, pack_id)
x0, y0, x1, y1 = stbtt.GetGlyphBitmapBox(bd_font_data.FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y)
local builder = atlas.Builder
builder.TempBuffer:resize(w * h * 1)
local bitmap_pixels = builder.TempBuffer.Data
ImStd.memset(bitmap_pixels, 0, w * h * 1)
local sub_x, sub_y = stbtt.MakeGlyphBitmapSubpixelPrefilter(bd_font_data.FontInfo, bitmap_pixels, w, h, w,
scale_for_raster_x, scale_for_raster_y, 0, 0, oversample_h, oversample_v, glyph_index)
local ref_size = baked.OwnerFont.Sources[1].SizePixels
local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0
local font_off_x = ImFloor(src.GlyphOffset.x * offsets_scale + 0.5)
local font_off_y = ImFloor(src.GlyphOffset.y * offsets_scale + 0.5)
font_off_x = font_off_x + sub_x
font_off_y = font_off_y + (sub_y + IM_ROUND(baked.Ascent))
local recip_h = 1.0 / (oversample_h * rasterizer_density)
local recip_v = 1.0 / (oversample_v * rasterizer_density)
out_glyph.X0 = x0 * recip_h + font_off_x
out_glyph.Y0 = y0 * recip_v + font_off_y
out_glyph.X1 = (x0 + r.w) * recip_h + font_off_x
out_glyph.Y1 = (y0 + r.h) * recip_v + font_off_y
out_glyph.Visible = true
out_glyph.PackId = pack_id
ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, out_glyph, r, bitmap_pixels, ImTextureFormat.Alpha8, w)
end
return true, advance_x
end
local function ImFontAtlasGetFontLoaderForStbTruetype()
local loader = ImFontLoader()
loader.Name = "stb_truetype"
loader.LoaderInit = ImGui_ImplStbTrueType_LoaderInit
loader.FontSrcInit = ImGui_ImplStbTrueType_FontSrcInit
loader.FontSrcDestroy = ImGui_ImplStbTrueType_FontSrcDestroy
loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph
loader.FontBakedInit = ImGui_ImplStbTrueType_FontBakedInit
loader.FontBakedDestroy = nil
loader.FontBakedLoadGlyph = ImGui_ImplStbTrueType_FontBakedLoadGlyph
return loader
end
--- @param atlas ImFontAtlas
--- @param baked ImFontBaked
function ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked)
local space_glyph = baked:FindGlyphNoFallback(32)
if space_glyph ~= nil then
space_glyph.Visible = false
end
if baked:FindGlyphNoFallback(9) == nil and space_glyph ~= nil then
local tab_glyph = ImFontGlyph()
tab_glyph.Codepoint = 9
tab_glyph.AdvanceX = space_glyph.AdvanceX * IM_TABSIZE
ImFontAtlasBakedAddFontGlyph(atlas, baked, nil, tab_glyph)
end
end
--- @param atlas ImFontAtlas
--- @param font ImFont
--- @param font_size float
--- @param font_rasterizer_density float
--- @param baked_id ImGuiID
--- @return ImFontBaked?
function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id)
IMGUI_DEBUG_LOG_FONT("[font] Created baked %.2fpx", font_size)
local baked = atlas.Builder.BakedPool:push_back(ImFontBaked())
baked.Size = font_size
baked.RasterizerDensity = font_rasterizer_density
baked.BakedId = baked_id
baked.OwnerFont = font
baked.LastUsedFrame = atlas.Builder.FrameCount
local loader_data_size = 0
for _, src in font.Sources:iter() do
local loader = src.FontLoader and src.FontLoader or atlas.FontLoader
loader_data_size = loader_data_size + loader.FontBakedSrcLoaderDataSize
end
-- baked.FontLoaderDatas = (loader_data_size > 0) and IM_ALLOC(loader_data_size) or nil
-- local loader_data_p = baked->FontLoaderDatas
for _, src in font.Sources:iter() do
local loader = src.FontLoader and src.FontLoader or atlas.FontLoader
if (loader.FontBakedInit) then
loader.FontBakedInit(atlas, src, baked--[[, loader_data_p--]])
end
-- loader_data_p += loader->FontBakedSrcLoaderDataSize
end
ImFontAtlasBuildSetupFontBakedBlanks(atlas, baked)
return baked
end
--- @param atlas ImFontAtlas
--- @param font ImFont
--- @param font_size float
--- @param font_rasterizer_density float
--- @return ImFontBaked?
function ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density)
local builder = atlas.Builder
for step_n = 0, 1 do
local closest_larger_match
local closest_smaller_match
for baked_n = 1, builder.BakedPool.Size do
repeat
local baked = builder.BakedPool[baked_n]
if (baked.OwnerFont ~= font or baked.WantDestroy) then
break
end
if (step_n == 0 and baked.RasterizerDensity ~= font_rasterizer_density) then
break
end
if (baked.Size > font_size and (closest_larger_match == nil or baked.Size < closest_larger_match.Size)) then
closest_larger_match = baked
end
if (baked.Size < font_size and (closest_smaller_match == nil or baked.Size > closest_smaller_match.Size)) then
closest_smaller_match = baked
end
until true
end
if (closest_larger_match) then
if (closest_smaller_match == nil or (closest_larger_match.Size >= font_size * 2.0 and closest_smaller_match.Size > font_size * 0.5)) then
return closest_larger_match
end
end
if (closest_smaller_match) then
return closest_smaller_match
end
end
return nil
end
--- @param atlas ImFontAtlas
--- @param font ImFont
--- @param baked ImFontBaked
function ImFontAtlasBakedDiscard(atlas, font, baked)
local builder = atlas.Builder
for _, glyph in baked.Glyphs:iter() do
if glyph.PackId ~= ImFontAtlasRectId_Invalid then
ImFontAtlasPackDiscardRect(atlas, glyph.PackId)
end
end
-- char* loader_data_p = (char*)baked->FontLoaderDatas
for _, src in font.Sources:iter() do
local loader = src.FontLoader and src.FontLoader or atlas.FontLoader
if loader.FontBakedDestroy then
loader.FontBakedDestroy(atlas, src, baked)
end
end
if baked.FontLoaderDatas then
baked.FontLoaderDatas = nil
end
builder.BakedMap[baked.BakedId] = nil
builder.BakedDiscardedCount = builder.BakedDiscardedCount + 1
baked:ClearOutputData()
baked.WantDestroy = true
font.LastBaked = nil
end
local function ImFontAtlasFontDiscardBakes(atlas, font, unused_frames)
local builder = atlas.Builder
if builder then
for baked_n = 1, builder.BakedPool.Size do
repeat
local baked = builder.BakedPool[baked_n]
if baked.LastUsedFrame + unused_frames > atlas.Builder.FrameCount then
break
end
if (baked.OwnerFont ~= font) or baked.WantDestroy then
break
end
ImFontAtlasBakedDiscard(atlas, font, baked)
until true
end
end
end
function ImFontAtlasFontInitOutput(atlas, font)
local ret = true
for _, src in font.Sources:iter() do
if not ImFontAtlasFontSourceInit(atlas, src) then
ret = false
end
end
IM_ASSERT(ret)
return ret
end
function ImFontAtlasFontDestroyOutput(atlas, font)
font:ClearOutputData()
for _, src in font.Sources:iter() do
local loader = src.FontLoader and src.FontLoader or atlas.FontLoader
if loader and loader.FontSrcDestroy ~= nil then
loader.FontSrcDestroy(atlas, src)
end
end
end
--- @param atlas ImFontAtlas
--- @param src ImFontConfig
--- @return boolean
function ImFontAtlasFontSourceInit(atlas, src)
local loader = (src.FontLoader) and src.FontLoader or atlas.FontLoader
if (loader.FontSrcInit ~= nil and not loader.FontSrcInit(atlas, src)) then
return false
end
return true
end
--- @param atlas ImFontAtlas
--- @param font ImFont
--- @param src ImFontConfig
function ImFontAtlasFontSourceAddToFont(atlas, font, src)
if src.MergeMode == false then
font:ClearOutputData()
font.OwnerAtlas = atlas
IM_ASSERT(font.Sources[1] == src)
end
atlas.TexIsBuilt = false
ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src)
end
--- @param atlas ImFontAtlas
--- @param src ImFontConfig
function ImFontAtlasFontDestroySourceData(atlas, src)
-- IM_UNUSED(atlas)
-- if src.FontDataOwnedByAtlas then
-- IM_FREE(src.FontData)
-- end
src.FontData = nil
-- if src.GlyphExcludeRanges then
-- IM_FREE(src.GlyphExcludeRanges)
-- end
src.GlyphExcludeRanges = nil
end
--- @param atlas ImFontAtlas
--- @param font ImFont
--- @param src ImFontConfig
function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src)
-- IM_UNUSED(atlas)
IM_ASSERT(font.Sources:contains(src))
--- @type ImWchar[]
local fallback_chars = {font.FallbackChar, IM_UNICODE_CODEPOINT_INVALID, 63, 32}
if font.FallbackChar == 0 then
for _, candidate_char in ipairs(fallback_chars) do
if candidate_char ~= 0 and font:IsGlyphInFont(candidate_char) then
font.FallbackChar = candidate_char
break
end
end
end
--- @type ImWchar[]
local ellipsis_chars = {src.EllipsisChar, 0x2026, 0x0085}
if font.EllipsisChar == 0 then
for _, candidate_char in ipairs(ellipsis_chars) do
if candidate_char ~= 0 and font:IsGlyphInFont(candidate_char) then
font.EllipsisChar = candidate_char
break
end
end
end
if font.EllipsisChar == 0 then
font.EllipsisChar = 0x0085
font.EllipsisAutoBake = true
end
end
--- @param atlas ImFontAtlas
--- @param baked ImFontBaked
--- @return ImFontGlyph?
function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked)
local font = baked.OwnerFont
IM_ASSERT(font.EllipsisChar ~= 0)
local dot_glyph = baked:FindGlyphNoFallback(46) -- '.'
if (dot_glyph == nil) then
dot_glyph = baked:FindGlyphNoFallback(0xFF0E)
end
if (dot_glyph == nil) then
return nil
end
local dot_r_id = dot_glyph.PackId
local dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id)
local dot_spacing = 1
local dot_step = (dot_glyph.X1 - dot_glyph.X0) + dot_spacing
local pack_id = ImFontAtlasPackAddRect(atlas, (dot_r.w * 3 + dot_spacing * 2), dot_r.h)
local r = ImFontAtlasPackGetRect(atlas, pack_id)
local glyph = ImFontGlyph()
glyph.Codepoint = font.EllipsisChar
glyph.AdvanceX = ImMax(dot_glyph.AdvanceX, dot_glyph.X0 + dot_step * 3.0 - dot_spacing)
glyph.X0 = dot_glyph.X0
glyph.Y0 = dot_glyph.Y0
glyph.X1 = dot_glyph.X0 + dot_step * 3 - dot_spacing
glyph.Y1 = dot_glyph.Y1
glyph.Visible = true
glyph.PackId = pack_id
glyph = ImFontAtlasBakedAddFontGlyph(atlas, baked, nil, glyph)
dot_glyph = nil
dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id)
local tex = atlas.TexData
for n = 0, 2 do
ImFontAtlasTextureBlockCopy(tex, dot_r.x, dot_r.y, tex, r.x + (dot_r.w + dot_spacing) * n, r.y, dot_r.w, dot_r.h)
end
ImFontAtlasTextureBlockQueueUpload(atlas, tex, r.x, r.y, r.w, r.h)
return glyph
end
--- @param baked ImFontBaked
function ImFontAtlasBuildSetupFontBakedFallback(baked)
IM_ASSERT(baked.FallbackGlyphIndex == -1)
IM_ASSERT(baked.FallbackAdvanceX == 0.0)
local font = baked.OwnerFont
local fallback_glyph
if (font.FallbackChar ~= 0) then
fallback_glyph = baked:FindGlyphNoFallback(font.FallbackChar)
end
if (fallback_glyph == nil) then
local space_glyph = baked:FindGlyphNoFallback(32) -- ' '
local glyph = ImFontGlyph()
glyph.Codepoint = 0
glyph.AdvanceX = space_glyph and space_glyph.AdvanceX or IM_ROUND(baked.Size * 0.40)
fallback_glyph = ImFontAtlasBakedAddFontGlyph(font.OwnerAtlas, baked, nil, glyph)
end
baked.FallbackGlyphIndex = baked.Glyphs:index_from_ptr(fallback_glyph) + 1
baked.FallbackAdvanceX = fallback_glyph.AdvanceX
end
function ImFontAtlasBuildSetupFontLoader(atlas, font_loader)
if atlas.FontLoader == font_loader then
return
end
IM_ASSERT(not atlas.Locked, "Cannot modify a locked ImFontAtlas!")
for _, font in atlas.Fonts:iter() do
ImFontAtlasFontDestroyOutput(atlas, font)
end
if atlas.Builder and atlas.FontLoader and atlas.FontLoader.LoaderShutdown then
atlas.FontLoader.LoaderShutdown(atlas)
end
atlas.FontLoader = font_loader
atlas.FontLoaderName = font_loader and font_loader.Name or "NULL"
IM_ASSERT(atlas.FontLoaderData == nil)
if atlas.Builder and atlas.FontLoader and atlas.FontLoader.LoaderInit then
atlas.FontLoader.LoaderInit(atlas)
end
for _, font in atlas.Fonts:iter() do
ImFontAtlasFontInitOutput(atlas, font)
end
for _, font in atlas.Fonts:iter() do
for _, src in font.Sources:iter() do
ImFontAtlasFontSourceAddToFont(atlas, font, src)
end
end
end
local function ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas)
for _, shared_data in atlas.DrawListSharedDatas:iter() do
local imgui_ctx = shared_data.Context
if (imgui_ctx) then
atlas.RendererHasTextures = bit32.band(imgui_ctx.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0
break
end
end
end
local function ImFontAtlasBuildUpdatePointers(atlas)
-- for _, font in atlas.Fonts:iter() do
-- font.Sources:resize(0)
-- end
-- for _, src in atlas.Sources:iter() do
-- src.DstFont.Sources:push_back(src)
-- end
end
--- @param atlas ImFontAtlas
--- @param old_tex ImTextureRef
--- @param new_tex ImTextureRef
local function ImFontAtlasUpdateDrawListsTextures(atlas, old_tex, new_tex)
for _, shared_data in atlas.DrawListSharedDatas:iter() do
repeat
if (shared_data.Context and not shared_data.Context.WithinFrameScope) then
break
end
for _, draw_list in shared_data.DrawLists:iter() do
if (draw_list.CmdBuffer.Size > 0 and draw_list._CmdHeader.TexRef == old_tex) then
draw_list:_SetTexture(new_tex)
end
for i, stacked_tex in draw_list._TextureStack:iter() do
if (stacked_tex == old_tex) then
draw_list._TextureStack.Data[i] = new_tex
end
end
end
until true
end
end
function ImFontAtlasBuildSetTexture(atlas, tex)
local old_tex_ref = atlas.TexRef
atlas.TexData = tex
atlas.TexUvScale = ImVec2(1.0 / tex.Width, 1.0 / tex.Height)
atlas.TexRef._TexData = tex
-- atlas->TexRef._TexID = tex->TexID; <-- We intentionally don't do that. It would be misleading and betray promise that both fields aren't set.
ImFontAtlasUpdateDrawListsTextures(atlas, old_tex_ref, atlas.TexRef)
end
--- @param atlas ImFontAtlas
function ImFontAtlasBuildUpdateTexData(atlas)
ImFontAtlasBuildUpdateTexDataLines(atlas)
ImFontAtlasBuildUpdateTexDataBasic(atlas)
end
function ImFontAtlasTextureAdd(atlas, w, h)
local old_tex = atlas.TexData
local new_tex
-- FIXME: Cannot reuse texture because old UV may have been used already (unless we remap UV).
new_tex = ImTextureData()
new_tex.UniqueID = atlas.TexNextUniqueID
atlas.TexNextUniqueID = atlas.TexNextUniqueID + 1
atlas.TexList:push_back(new_tex)
if old_tex ~= nil then
old_tex.WantDestroyNextFrame = true
IM_ASSERT(old_tex.Status == ImTextureStatus.OK or old_tex.Status == ImTextureStatus.WantCreate or old_tex.Status == ImTextureStatus.WantUpdates)
end
new_tex:Create(atlas.TexDesiredFormat, w, h)
atlas.TexIsBuilt = false
ImFontAtlasBuildSetTexture(atlas, new_tex)
return new_tex
end
--- @param atlas ImFontAtlas
--- @return ImVec2
function ImFontAtlasTextureGetSizeEstimate(atlas)
local min_w = ImUpperPowerOfTwo(atlas.TexMinWidth)
local min_h = ImUpperPowerOfTwo(atlas.TexMinHeight)
if (atlas.Builder == nil or atlas.TexData == nil or atlas.TexData.Status == ImTextureStatus.WantDestroy) then
return ImVec2(min_w, min_h) -- ImVec2i
end
local builder = atlas.Builder
min_w = ImMax(ImUpperPowerOfTwo(builder.MaxRectSize.x), min_w)
min_h = ImMax(ImUpperPowerOfTwo(builder.MaxRectSize.y), min_h)
local surface_approx = builder.RectsPackedSurface - builder.RectsDiscardedSurface
local surface_sqrt = ImFloor(ImSqrt(surface_approx))
local new_tex_w
local new_tex_h
if (min_w >= min_h) then
new_tex_w = ImMax(min_w, ImUpperPowerOfTwo(surface_sqrt))
new_tex_h = ImMax(min_h, ImFloor((surface_approx + new_tex_w - 1) / new_tex_w))
if (bit32.band(atlas.Flags, ImFontAtlasFlags.NoPowerOfTwoHeight) == 0) then
new_tex_h = ImUpperPowerOfTwo(new_tex_h)
end
else
new_tex_h = ImMax(min_h, ImUpperPowerOfTwo(surface_sqrt))
if (bit32.band(atlas.Flags, ImFontAtlasFlags.NoPowerOfTwoHeight) == 0) then
new_tex_h = ImUpperPowerOfTwo(new_tex_h)
end
new_tex_w = ImMax(min_w, ImFloor((surface_approx + new_tex_h - 1) / new_tex_h))
end
IM_ASSERT(ImIsPowerOfTwo(new_tex_w) and ImIsPowerOfTwo(new_tex_h))
return ImVec2(new_tex_w, new_tex_h) -- ImVec2i
end
--- @param atlas ImFontAtlas
local function ImFontAtlasBuildClear(atlas)
local new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas) -- ImVec2i
ImFontAtlasBuildDestroy(atlas)
ImFontAtlasTextureAdd(atlas, new_tex_size.x, new_tex_size.y)
ImFontAtlasBuildInit(atlas)
for _, src in atlas.Sources:iter() do
ImFontAtlasFontSourceInit(atlas, src)
end
for _, font in atlas.Fonts:iter() do
for _, src in font.Sources:iter() do
ImFontAtlasFontSourceAddToFont(atlas, font, src)
end
end
end
--- @param atlas ImFontAtlas
function ImFontAtlasTextureCompact(atlas)
local builder = atlas.Builder
ImFontAtlasBuildDiscardBakes(atlas, 1)
local old_tex = atlas.TexData
local old_tex_size = ImVec2(old_tex.Width, old_tex.Height)
local new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas)
if (builder.RectsDiscardedCount == 0 and new_tex_size.x == old_tex_size.x and new_tex_size.y == old_tex_size.y) then
return
end
ImFontAtlasTextureRepack(atlas, new_tex_size.x, new_tex_size.y)
end
--- @param atlas ImFontAtlas
function ImFontAtlasPackInit(atlas)
local tex = atlas.TexData
local builder = atlas.Builder
local pack_node_count = ImFloor(tex.Width / 2)
builder.PackNodes:resize(pack_node_count)
for i = 1, builder.PackNodes.Size do builder.PackNodes.Data[i] = stbrp.node() end
stbrp.init_target(builder.PackContext, tex.Width, tex.Height, builder.PackNodes.Data, builder.PackNodes.Size)
builder.RectsPackedCount = 0
builder.RectsPackedSurface = 0
builder.MaxRectSize = ImVec2(0, 0) -- ImVec2i
builder.MaxRectBounds = ImVec2(0, 0) -- ImVec2i
end
--- @param atlas ImFontAtlas
function ImFontAtlasBuildUpdateTexDataLines(atlas)
if bit32.band(atlas.Flags, ImFontAtlasFlags.NoBakedLines) ~= 0 then
return
end
local tex = atlas.TexData
local builder = atlas.Builder
local r = ImFontAtlasRect()
local add_and_draw = (atlas:GetCustomRect(builder.PackIdLinesTexData, r) == false)
if add_and_draw then
local pack_size = ImVec2(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) -- ImVec2i
builder.PackIdLinesTexData = atlas:AddCustomRect(pack_size.x, pack_size.y, r)
IM_ASSERT(builder.PackIdLinesTexData ~= ImFontAtlasRectId_Invalid)
end
for n = 0, IM_DRAWLIST_TEX_LINES_WIDTH_MAX do
local y = n
local line_width = n
--- @type int # If not floored, will cause black and purple horizontal stripes appearing on the right of the arrow(triangle) in the upper-left most area of the atlas
local pad_left = math.floor((r.w - line_width) / 2)
--- @type int
local pad_right = r.w - (pad_left + line_width)
IM_ASSERT(pad_left + line_width + pad_right == r.w and y < r.h)
if (add_and_draw and tex.Format == ImTextureFormat.Alpha8) then
local write_ptr, write_ptr_base = tex:GetPixelsAt(r.x, r.y + y)
for i = 0, pad_left - 1 do
write_ptr[write_ptr_base + i] = 0x00
end
for i = 0, line_width - 1 do
write_ptr[write_ptr_base + pad_left + i] = 0xFF
end
for i = 0, pad_right - 1 do
write_ptr[write_ptr_base + pad_left + line_width + i] = 0x00
end
elseif (add_and_draw and tex.Format == ImTextureFormat.RGBA32) then
local write_ptr, write_ptr_base = tex:GetPixelsAt(r.x, r.y + y)
for i = 0, pad_left - 1 do
write_u32(write_ptr, write_ptr_base + i * 4, IM_COL32(255, 255, 255, 0))
end
for i = 0, line_width - 1 do
write_u32(write_ptr, write_ptr_base + (pad_left + i) * 4, IM_COL32_WHITE)
end
for i = 0, pad_right - 1 do
write_u32(write_ptr, write_ptr_base + (pad_left + line_width + i) * 4, IM_COL32(255, 255, 255, 0))
end
end
local uv0 = ImVec2(r.x + pad_left - 1, r.y + y) * atlas.TexUvScale
local uv1 = ImVec2(r.x + pad_left + line_width + 1, r.y + y + 1) * atlas.TexUvScale
local half_v = (uv0.y + uv1.y) * 0.5
atlas.TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v)
end
end
--- @param atlas ImFontAtlas
--- @param x int
--- @param y int
--- @param w int
--- @param h int
--- @param in_str string[]
--- @param in_marker_char string
function ImFontAtlasBuildRenderBitmapFromString(atlas, x, y, w, h, in_str, in_marker_char)
local tex = atlas.TexData
IM_ASSERT(x >= 0 and x + w <= tex.Width)
IM_ASSERT(y >= 0 and y + h <= tex.Height)
if tex.Format == ImTextureFormat.Alpha8 then
local out_p, out_p_base = tex:GetPixelsAt(x, y)
local str_base = 1
for off_y = 0, h - 1 do
for off_x = 0, w - 1 do
out_p[out_p_base + off_x] = (in_str[str_base + off_x] == in_marker_char) and 0xFF or 0x00
end
out_p_base = out_p_base + tex.Width
str_base = str_base + w
end
elseif tex.Format == ImTextureFormat.RGBA32 then
local out_p, out_p_base = tex:GetPixelsAt(x, y)
local str_base = 1
for off_y = 0, h - 1 do
for off_x = 0, w - 1 do
write_u32(out_p, out_p_base + off_x * 4, (in_str[str_base + off_x] == in_marker_char) and IM_COL32_WHITE or IM_COL32_BLACK_TRANS)
end
out_p_base = out_p_base + tex.Width * 4
str_base = str_base + w
end
end
end
--- @param atlas ImFontAtlas
function ImFontAtlasBuildUpdateTexDataBasic(atlas)
local builder = atlas.Builder
local pack_size = (bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0) and ImVec2(2, 2) or ImVec2(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H)
local r = ImFontAtlasRect()
local add_and_draw = (atlas:GetCustomRect(builder.PackIdMouseCursors, r) == false)
if (add_and_draw) then
builder.PackIdMouseCursors = atlas:AddCustomRect(pack_size.x, pack_size.y, r)
IM_ASSERT(builder.PackIdMouseCursors ~= ImFontAtlasRectId_Invalid)
if bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0 then
ImFontAtlasBuildRenderBitmapFromString(atlas, r.x, r.y, 2, 2, {"X", "X", "X", "X"}, "X")
else
local x_for_white = r.x
local x_for_black = r.x + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1
ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_white, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, ".")
ImFontAtlasBuildRenderBitmapFromString(atlas, x_for_black, r.y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, "X")
end
end
atlas.TexUvWhitePixel = ImVec2((r.x + 0.5) * atlas.TexUvScale.x, (r.y + 0.5) * atlas.TexUvScale.y)
end
function ImFontAtlasUpdateDrawListsSharedData(atlas)
for _, shared_data in atlas.DrawListSharedDatas:iter() do
if (shared_data.FontAtlas == atlas) then
shared_data.TexUvWhitePixel = atlas.TexUvWhitePixel
shared_data.TexUvLines = atlas.TexUvLines
end
end
end
function ImFontAtlasBuildInit(atlas)
if atlas.FontLoader == nil then
-- IMGUI_ENABLE_STB_TRUETYPE
atlas:SetFontLoader(ImFontAtlasGetFontLoaderForStbTruetype())
end
if atlas.TexData == nil or atlas.TexData.Pixels == nil then
ImFontAtlasTextureAdd(atlas, ImUpperPowerOfTwo(atlas.TexMinWidth), ImUpperPowerOfTwo(atlas.TexMinHeight))
end
atlas.Builder = ImFontAtlasBuilder()
if atlas.FontLoader.LoaderInit then
atlas.FontLoader.LoaderInit(atlas)
end
ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas)
ImFontAtlasPackInit(atlas)
ImFontAtlasBuildUpdateTexData(atlas)
ImFontAtlasBuildUpdatePointers(atlas)
ImFontAtlasUpdateDrawListsSharedData(atlas)
ImTextInitClassifiers()
end
--- @param atlas ImFontAtlas
function ImFontAtlasBuildDestroy(atlas)
for _, font in atlas.Fonts:iter() do
ImFontAtlasFontDestroyOutput(atlas, font)
end
if atlas.Builder and atlas.FontLoader and atlas.FontLoader.LoaderShutdown then
atlas.FontLoader.LoaderShutdown(atlas)
IM_ASSERT(atlas.FontLoaderData == nil)
end
atlas.Builder = nil
end
--- @param atlas ImFontAtlas
--- @param old_font ImFont?
--- @param new_font ImFont?
function ImFontAtlasBuildNotifySetFont(atlas, old_font, new_font)
for _, shared_data in atlas.DrawListSharedDatas:iter() do
if shared_data.Font == old_font then
shared_data.Font = new_font
end
local ctx = shared_data.Context
if ctx then
repeat
if old_font == nil and ctx.Font == nil and ctx.FontSizeBase == 0.0 then
-- While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed.
-- Also fixes erroneously rewriting style.FontSizeBase during init if adding default fonts.
break
end
if ctx.IO.FontDefault == old_font then
ctx.IO.FontDefault = new_font
end
if ctx.Font == old_font then
local curr_ctx = ImGui.GetCurrentContext()
local need_bind_ctx = ctx ~= curr_ctx
if need_bind_ctx then
ImGui.SetCurrentContext(ctx)
end
ImGui.SetCurrentFont(new_font, ctx.FontSizeBase, ctx.FontSize)
if need_bind_ctx then
ImGui.SetCurrentContext(curr_ctx)
end
end
for _, font_stack_data in ctx.FontStack:iter() do
if font_stack_data.Font == old_font then
font_stack_data.Font = new_font
end
end
until true
end
end
end
--- @param atlas ImFontAtlas
function ImFontAtlasBuildMain(atlas)
IM_ASSERT(not atlas.Locked, "Cannot modify a locked ImFontAtlas!")
if (atlas.TexData and atlas.TexData.Format ~= atlas.TexDesiredFormat) then
ImFontAtlasBuildClear(atlas)
end
if atlas.Builder == nil then
ImFontAtlasBuildInit(atlas)
end
-- Default font is none are specified
if atlas.Sources.Size == 0 then
atlas:AddFontDefault()
end
-- [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs
-- ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas);
-- if atlas.RendererHasTextures == false then
-- ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas)
-- end
atlas.TexIsBuilt = true
end
function MT.ImTextureData:DestroyPixels()
self.Pixels = nil
self.UseColors = false
end
function ImTextureDataGetFormatBytesPerPixel(format)
if format == ImTextureFormat.Alpha8 then
return 1
elseif format == ImTextureFormat.RGBA32 then
return 4
end
IM_ASSERT(false)
return 0
end
function MT.ImTextureData:Create(format, w, h)
IM_ASSERT(self.Status == ImTextureStatus.Destroyed)
self:DestroyPixels()
self.Format = format
self.Status = ImTextureStatus.WantCreate
self.Width = w
self.Height = h
self.BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format)
self.UseColors = false
self.Pixels = {}
ImStd.memset(self.Pixels, 0, self.Width * self.Height * self.BytesPerPixel)
self.UsedRect.x = 0
self.UsedRect.y = 0
self.UsedRect.w = 0
self.UsedRect.h = 0
self.UpdateRect.x = 65535
self.UpdateRect.y = 65535
self.UpdateRect.w = 0
self.UpdateRect.h = 0
end
function MT.ImFontBaked:ClearOutputData()
self.FallbackAdvanceX = 0.0
self.Glyphs:clear()
self.IndexAdvanceX:clear()
self.IndexLookup:clear()
self.FallbackGlyphIndex = -1
self.Ascent = 0.0
self.Descent = 0.0
self.MetricsTotalSurface = 0
end
--- @param c ImWchar
--- @return ImFontGlyph?
function MT.ImFontBaked:FindGlyph(c)
if c < self.IndexLookup.Size then
local i = self.IndexLookup.Data[c + 1]
if i == IM_FONTGLYPH_INDEX_NOT_FOUND then
return self.Glyphs.Data[self.FallbackGlyphIndex]
end
if i ~= IM_FONTGLYPH_INDEX_UNUSED then
return self.Glyphs.Data[i]
end
end
local glyph = ImFontBaked_BuildLoadGlyph(self, c, nil)
return (glyph) and glyph or self.Glyphs.Data[self.FallbackGlyphIndex]
end
--- @param c ImWchar
--- @return ImFontGlyph?
function MT.ImFontBaked:FindGlyphNoFallback(c)
if c < self.IndexLookup.Size then -- IM_LIKELY
local i = self.IndexLookup.Data[c + 1]
if i == IM_FONTGLYPH_INDEX_NOT_FOUND then
return nil
end
if i ~= IM_FONTGLYPH_INDEX_UNUSED then
return self.Glyphs.Data[i]
end
end
self.LoadNoFallback = true
local glyph = ImFontBaked_BuildLoadGlyph(self, c, nil)
self.LoadNoFallback = false
return glyph
end
function MT.ImFont:ClearOutputData()
local atlas = self.OwnerAtlas
if atlas ~= nil then
ImFontAtlasFontDiscardBakes(atlas, self, 0)
end
for i = 1, (IM_UNICODE_CODEPOINT_MAX + 1) / 8192 / 8 do self.Used8kPagesMap[i] = 0 end
self.LastBaked = nil
end
--- @param font_id ImGuiID
--- @param baked_size float
--- @param rasterizer_density float
--- @return ImGuiID
function ImFontAtlasBakedGetId(font_id, baked_size, rasterizer_density)
local hashed_data = {font_id, baked_size, rasterizer_density}
return ImHashData(hashed_data)
end
--- @param atlas ImFontAtlas
--- @param font ImFont
--- @param font_size float
--- @param font_rasterizer_density float
--- @return ImFontBaked?
function ImFontAtlasBakedGetOrAdd(atlas, font, font_size, font_rasterizer_density)
IM_ASSERT(font_size > 0.0 and font_rasterizer_density > 0.0)
local baked_id = ImFontAtlasBakedGetId(font.FontId, font_size, font_rasterizer_density)
local builder = atlas.Builder
local baked = builder.BakedMap[baked_id]
if baked ~= nil then
IM_ASSERT(baked.Size == font_size and baked.OwnerFont == font and baked.BakedId == baked_id)
return baked
end
if (bit32.band(font.Flags, ImFontFlags.LockBakedSizes) ~= 0 or atlas.Locked) then
baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density)
if baked ~= nil then
return baked
end
if atlas.Locked then
IM_ASSERT(not atlas.Locked, "Cannot use dynamic font size with a locked ImFontAtlas!")
return nil
end
end
baked = ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id)
builder.BakedMap[baked_id] = baked
return baked
end
--- @param atlas ImFontAtlas
--- @param baked ImFontBaked
--- @param src? ImFontConfig
--- @param in_glyph ImFontGlyph
--- @return ImFontGlyph
function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph)
local glyph_idx = baked.Glyphs.Size + 1
baked.Glyphs:push_back(in_glyph)
local glyph = baked.Glyphs.Data[glyph_idx]
IM_ASSERT(baked.Glyphs.Size < 0xFFFE)
if (glyph.PackId ~= ImFontAtlasRectId_Invalid) then
local r = ImFontAtlasPackGetRect(atlas, glyph.PackId)
IM_ASSERT(glyph.U0 == 0.0 and glyph.V0 == 0.0 and glyph.U1 == 0.0 and glyph.V1 == 0.0)
glyph.U0 = (r.x) * atlas.TexUvScale.x
glyph.V0 = (r.y) * atlas.TexUvScale.y
glyph.U1 = (r.x + r.w) * atlas.TexUvScale.x
glyph.V1 = (r.y + r.h) * atlas.TexUvScale.y
baked.MetricsTotalSurface = baked.MetricsTotalSurface + r.w * r.h
end
if (src ~= nil) then
local ref_size = baked.OwnerFont.Sources[1].SizePixels
local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0
local advance_x = ImClamp(glyph.AdvanceX, src.GlyphMinAdvanceX * offsets_scale, src.GlyphMaxAdvanceX * offsets_scale)
if (advance_x ~= glyph.AdvanceX) then
local char_off_x = src.PixelSnapH and ImTrunc((advance_x - glyph.AdvanceX) * 0.5) or (advance_x - glyph.AdvanceX) * 0.5
glyph.X0 = glyph.X0 + char_off_x
glyph.X1 = glyph.X1 + char_off_x
end
if (src.PixelSnapH) then
advance_x = IM_ROUND(advance_x)
end
glyph.AdvanceX = advance_x + src.GlyphExtraAdvanceX
end
if (glyph.Colored) then
atlas.TexData.UseColors = true
atlas.TexPixelsUseColors = true
end
local codepoint = glyph.Codepoint
ImFontBaked_BuildGrowIndex(baked, codepoint + 1)
baked.IndexAdvanceX.Data[codepoint + 1] = glyph.AdvanceX
baked.IndexLookup.Data[codepoint + 1] = glyph_idx -- (ImU16)
local page_n = math.floor(codepoint / 8192)
baked.OwnerFont.Used8kPagesMap[bit32.rshift(page_n, 3) + 1] = bit32.bor(baked.OwnerFont.Used8kPagesMap[bit32.rshift(page_n, 3) + 1], bit32.lshift(1, bit32.band(page_n, 7)))
return glyph
end
--- @param atlas ImFontAtlas
--- @param baked ImFontBaked
--- @param src? ImFontConfig
--- @param codepoint ImWchar
--- @param advance_x float
function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, advance_x)
-- IM_UNUSED(atlas)
if (src ~= nil) then
local ref_size = baked.OwnerFont.Sources[1].SizePixels
local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0
advance_x = ImClamp(advance_x, src.GlyphMinAdvanceX * offsets_scale, src.GlyphMaxAdvanceX * offsets_scale)
if (src.PixelSnapH) then
advance_x = IM_ROUND(advance_x)
end
advance_x = advance_x + src.GlyphExtraAdvanceX
end
ImFontBaked_BuildGrowIndex(baked, codepoint + 1)
baked.IndexAdvanceX.Data[codepoint + 1] = advance_x
end
--- @param size float
--- @param density float?
--- @return ImFontBaked?
function MT.ImFont:GetFontBaked(size, density)
if not density then density = -1.0 end
--- @type ImFontBaked?
local baked = self.LastBaked
size = ImGui.GetRoundedFontSize(size)
if density < 0.0 then
density = self.CurrentRasterizerDensity
end
if baked and baked.Size == size and baked.RasterizerDensity == density then
return baked
end
local atlas = self.OwnerAtlas
local builder = atlas.Builder
baked = ImFontAtlasBakedGetOrAdd(atlas, self, size, density)
if baked == nil then
return nil
end
baked.LastUsedFrame = builder.FrameCount
self.LastBaked = baked
return baked
end
--- @param atlas ImFontAtlas
--- @param font ImFont
--- @param c ImWchar
--- @return ImWchar
--- @nodiscard
local function ImFontAtlas_FontHookRemapCodepoint(atlas, font, c)
-- IM_UNUSED(atlas)
if #font.RemapPairs > 0 then
local ret = font.RemapPairs[c]
return (ret ~= nil) and ret or c
end
return c
end
--- @param baked ImFontBaked
--- @param codepoint ImWchar
--- @param only_load_advance_x? float
--- @return ImFontGlyph?
--- @return float? # Updated `only_load_advance_x`
function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x)
local font = baked.OwnerFont
local atlas = font.OwnerAtlas
if atlas.Locked or bit32.band(font.Flags, ImFontFlags.NoLoadGlyphs) ~= 0 then
if baked.FallbackGlyphIndex == -1 and baked.LoadNoFallback == false then
ImFontAtlasBuildSetupFontBakedFallback(baked)
end
return nil, only_load_advance_x
end
local src_codepoint = codepoint
codepoint = ImFontAtlas_FontHookRemapCodepoint(atlas, font, codepoint)
if (codepoint == font.EllipsisChar and font.EllipsisAutoBake) then
local glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked)
if (glyph) then
return glyph, only_load_advance_x
end
end
local loader_user_data_p = baked.FontLoaderDatas
local src_n = 1
for _, src in font.Sources:iter() do
local loader = src.FontLoader and src.FontLoader or atlas.FontLoader
if (not src.GlyphExcludeRanges or ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) then
if only_load_advance_x == nil then
local glyph_buf = ImFontGlyph()
if loader.FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, glyph_buf, nil) then
glyph_buf.Codepoint = src_codepoint
glyph_buf.SourceIdx = src_n
return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph_buf)
end
else
local ret --[[@as bool]]
ret, only_load_advance_x = loader.FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, nil, only_load_advance_x)
if ret then
--- @cast only_load_advance_x float
ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, only_load_advance_x)
return nil, only_load_advance_x
end
end
end
-- loader_user_data_p = loader_user_data_p + loader.FontBakedSrcLoaderDataSize
src_n = src_n + 1
end
if (baked.LoadNoFallback) then
return nil, only_load_advance_x
end
if (baked.FallbackGlyphIndex == -1) then
ImFontAtlasBuildSetupFontBakedFallback(baked)
end
ImFontBaked_BuildGrowIndex(baked, codepoint + 1);
baked.IndexAdvanceX.Data[codepoint + 1] = baked.FallbackAdvanceX
baked.IndexLookup.Data[codepoint + 1] = IM_FONTGLYPH_INDEX_NOT_FOUND
return nil, only_load_advance_x
end
--- @param baked ImFontBaked
--- @param codepoint ImWchar
--- @return float
function ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint)
if (baked.Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE) or baked.LoadNoRenderOnLayout then
local only_advance_x
local glyph
glyph, only_advance_x = ImFontBaked_BuildLoadGlyph(baked, codepoint, only_advance_x)
--- @cast only_advance_x float
return glyph and glyph.AdvanceX or only_advance_x
else
local glyph = ImFontBaked_BuildLoadGlyph(baked, codepoint, nil)
return glyph and glyph.AdvanceX or baked.FallbackAdvanceX
end
end
--- @param c ImWchar
--- @return bool
function MT.ImFont:IsGlyphInFont(c)
local atlas = self.OwnerAtlas
c = ImFontAtlas_FontHookRemapCodepoint(atlas, self, c)
for _, src in self.Sources:iter() do
local loader = src.FontLoader and src.FontLoader or atlas.FontLoader
if loader.FontSrcContainsGlyph ~= nil and loader.FontSrcContainsGlyph(atlas, src, c) then
return true
end
end
return false
end
--- @param c ImWchar
--- @return float
function MT.ImFontBaked:GetCharAdvance(c)
if c < self.IndexAdvanceX.Size then
local x = self.IndexAdvanceX.Data[c + 1]
if x >= 0.0 then
return x
end
end
return ImFontBaked_BuildLoadGlyphAdvanceX(self, c)
end
function BuildLoadGlyphGetAdvanceOrFallback(baked, codepoint)
return ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint)
end
--- @param text ImString
--- @param text_begin int
--- @param text_end int
--- @param flags ImDrawTextFlags
--- @return int
local function ImTextCalcWordWrapNextLineStart(text, text_begin, text_end, flags)
local pos = text_begin
if bit32.band(flags, ImDrawTextFlags.WrapKeepBlanks) == 0 then
while pos < text_end and ImCharIsBlankA(ImStrByte(text, pos)) do
pos = pos + 1
end
end
if pos < text_end and ImStrByte(text, pos) == 10 then -- '\n'
pos = pos + 1
end
return pos
end
--- @param bits ImU32[]
--- @param codepoint_min unsigned_int
--- @param codepoint_end unsigned_int
--- @param char_class ImWcharClass
function ImTextClassifierClear(bits, codepoint_min, codepoint_end, char_class)
for c = codepoint_min, codepoint_end - 1 do
ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c)
end
end
--- @param bits ImU32[]
--- @param codepoint_min unsigned_int
--- @param codepoint_end unsigned_int
--- @param char_class ImWcharClass
--- @param c unsigned_int
function ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c)
IM_ASSERT(c >= codepoint_min and c < codepoint_end)
-- IM_UNUSED(codepoint_end)
c = c - codepoint_min
local shift = bit32.lshift(bit32.band(c, 15), 1)
bits[bit32.rshift(c, 4) + 1] = bit32.bor(bit32.band(bits[bit32.rshift(c, 4) + 1], bit32.bnot(bit32.lshift(0x03, shift))), bit32.lshift(char_class, shift))
end
function ImTextClassifierSetCharClassFromStr(bits, codepoint_min, codepoint_end, char_class, s)
local s_end = #s + 1
local pos = 1
while (pos < s_end) do
local wanted, c = ImStd.ImTextCharFromUtf8(s, pos, s_end)
pos = pos + wanted
ImTextClassifierSetCharClass(bits, codepoint_min, codepoint_end, char_class, c)
end
end
function ImTextClassifierGet(_BITS, _CHAR_OFFSET)
return bit32.band(bit32.rshift(_BITS[bit32.rshift(_CHAR_OFFSET, 4) + 1], bit32.lshift(bit32.band(_CHAR_OFFSET, 15), 1)), 0x03)
end
local g_CharClassifierIsSeparator_0000_007f = {} for i = 1, 128 / 16 do g_CharClassifierIsSeparator_0000_007f[i] = 0 end
local g_CharClassifierIsSeparator_3000_300f = {} for i = 1, 16 / 16 do g_CharClassifierIsSeparator_3000_300f[i] = 0 end
function ImTextInitClassifiers()
if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, 44) ~= 0) then
return
end
ImTextClassifierClear(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Other)
ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Blank, " \t")
ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Punct, ".,;!?\"")
ImTextClassifierClear(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass.Other)
ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass.Blank, 0x3000)
ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass.Punct, 0x3001)
ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass.Punct, 0x3002)
end
--- @param font ImFont
--- @param size float
--- @param text ImString
--- @param pos int
--- @param text_end int
--- @param wrap_width float
--- @param flags ImDrawTextFlags
--- @return int
function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_width, flags)
local baked = font:GetFontBaked(size)
local scale = size / baked.Size
local line_width = 0.0
local blank_width = 0.0
wrap_width = wrap_width / scale
local s = pos
IM_ASSERT(text_end ~= nil)
local prev_type = ImWcharClass.Other
local keep_blanks = bit32.band(flags, ImDrawTextFlags.WrapKeepBlanks) ~= 0
local span_end = s
local span_width = 0.0
local stop = false
while s < text_end do
repeat
--- @type unsigned_int
local c = ImStrByte(text, s)
local next_s
if c < 0x80 then
next_s = s + 1
else
local wanted, out_char = ImStd.ImTextCharFromUtf8(text, s, text_end)
c = out_char
next_s = s + wanted
end
if c < 32 then
if c == 10 then -- '\n'
return s
end
if c == 13 then -- '\r'
s = next_s
break
end
end
local char_width = (c < baked.IndexAdvanceX.Size) and baked.IndexAdvanceX.Data[c + 1] or -1.0
if char_width < 0.0 then
char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c)
end
local curr_type
if c < 128 then
curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, c)
elseif (c >= 0x3000 and c < 0x3010) then
curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_3000_300f, bit32.band(c, 15))
else
curr_type = ImWcharClass.Other
end
if curr_type == ImWcharClass.Blank then
if (prev_type ~= ImWcharClass.Blank and not keep_blanks) then
span_end = s
line_width = line_width + span_width
span_width = 0.0
end
blank_width = blank_width + char_width
else
if (prev_type == ImWcharClass.Punct and curr_type ~= ImWcharClass.Punct and not (c >= 48 and c <= 57)) then
span_end = s
line_width = line_width + (span_width + blank_width)
blank_width = 0.0
span_width = 0.0
elseif (prev_type == ImWcharClass.Blank and keep_blanks) then
span_end = s
line_width = line_width + (span_width + blank_width)
blank_width = 0.0
span_width = 0.0
end
span_width = span_width + char_width
end
if (span_width + blank_width + line_width > wrap_width) then
if span_width + blank_width > wrap_width then
stop = true; break
end
return span_end
end
prev_type = curr_type
s = next_s
until true
if stop then break end
end
if s == pos and s < text_end then
local bytes = ImStd.ImTextCountUtf8BytesFromChar(text, s, text_end)
return s + bytes
end
return s
end
--- @param font ImFont
--- @param size float
--- @param max_width float
--- @param wrap_width float
--- @param text ImString
--- @param text_begin int
--- @param text_end_display? int
--- @param text_end? int
--- @param out_offset? ImVec2
--- @param flags ImDrawTextFlags
--- @return ImVec2 text_size
--- @return int remaining
function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begin, text_end_display, text_end, out_offset, flags)
if not text_end then
text_end = #text + 1
end
if not text_end_display then
text_end_display = text_end
end
local baked = font:GetFontBaked(size)
local line_height = size
local scale = line_height / baked.Size
local text_size = ImVec2()
local line_width = 0.0
local word_wrap_enabled = (wrap_width > 0.0)
local word_wrap_eol
local s = text_begin
local stop = false
while s < text_end_display do
repeat
if word_wrap_enabled then
if not word_wrap_eol then
word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, text, s, text_end, wrap_width - line_width, flags)
end
if s >= word_wrap_eol then
if text_size.x < line_width then
text_size.x = line_width
end
text_size.y = text_size.y + line_height
line_width = 0.0
s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags)
if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then
stop = true; break
end
word_wrap_eol = nil
break
end
end
local prev_s = s
local c = ImStrByte(text, s)
if c < 0x80 then
s = s + 1
else
local wanted, out_char = ImStd.ImTextCharFromUtf8(text, s, text_end)
c = out_char
s = s + wanted
end
if c == 10 then -- '\n'
text_size.x = ImMax(text_size.x, line_width)
text_size.y = text_size.y + line_height
line_width = 0.0
if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then
stop = true; break
end
break
end
if c == 13 then -- '\r'
break
end
local char_width = (c < baked.IndexAdvanceX.Size) and baked.IndexAdvanceX.Data[c + 1] or -1.0
if (char_width < 0.0) then
char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c)
end
char_width = char_width * scale
if (line_width + char_width >= max_width) then
s = prev_s
stop = true; break
end
line_width = line_width + char_width
until true
if stop then break end
end
if (text_size.x < line_width) then
text_size.x = line_width
end
if out_offset then
out_offset.x = line_width
out_offset.y = text_size.y + line_height
end
if (line_width > 0 or text_size.y == 0.0) then
text_size.y = text_size.y + line_height
end
local out_remaining = s
return text_size, out_remaining
end
--- @param size float
--- @param max_width float
--- @param wrap_width float
--- @param text ImString
--- @param text_begin int
--- @param text_end? int
function MT.ImFont:CalcTextSizeA(size, max_width, wrap_width, text, text_begin, text_end)
return ImFontCalcTextSizeEx(self, size, max_width, wrap_width, text, text_begin, text_end, text_end, nil, ImDrawTextFlags.None)
end
--- Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound.
--- @param draw_list ImDrawList
--- @param size float
--- @param pos ImVec2
--- @param col ImU32
--- @param c ImWchar
--- @param cpu_fine_clip ImVec4
function MT.ImFont:RenderChar(draw_list, size, pos, col, c, cpu_fine_clip)
local baked = self:GetFontBaked(size)
local glyph = baked:FindGlyph(c)
if not glyph or not glyph.Visible then
return
end
if glyph.Colored then
col = bit32.bor(col, bit32.bnot(IM_COL32_A_MASK))
end
local scale
if size >= 0.0 then
scale = size / baked.Size
else
scale = 1.0
end
local x = pos.x
local y = pos.y
if bit32.band(draw_list.Flags, ImDrawListFlags.TextNoPixelSnap) == 0 then
x = IM_TRUNC(x)
y = IM_TRUNC(y)
end
local x1 = x + glyph.X0 * scale
local x2 = x + glyph.X1 * scale
if cpu_fine_clip and (x1 > cpu_fine_clip.z or x2 < cpu_fine_clip.x) then
return
end
local y1 = y + glyph.Y0 * scale
local y2 = y + glyph.Y1 * scale
local u1 = glyph.U0
local v1 = glyph.V0
local u2 = glyph.U1
local v2 = glyph.V1
-- Always CPU fine clip. Code extracted from RenderText().
-- CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads.
if cpu_fine_clip then
if x1 < cpu_fine_clip.x then u1 = u1 + (1.0 - (x2 - cpu_fine_clip.x) / (x2 - x1)) * (u2 - u1); x1 = cpu_fine_clip.x end
if y1 < cpu_fine_clip.y then v1 = v1 + (1.0 - (y2 - cpu_fine_clip.y) / (y2 - y1)) * (v2 - v1); y1 = cpu_fine_clip.y end
if x2 > cpu_fine_clip.z then u2 = u1 + ((cpu_fine_clip.z - x1) / (x2 - x1)) * (u2 - u1); x2 = cpu_fine_clip.z end
if y2 > cpu_fine_clip.w then v2 = v1 + ((cpu_fine_clip.w - y1) / (y2 - y1)) * (v2 - v1); y2 = cpu_fine_clip.w end
if y1 >= y2 then return end
end
draw_list:PrimReserve(6, 4)
draw_list:PrimRectUV(ImVec2(x1, y1), ImVec2(x2, y2), ImVec2(u1, v1), ImVec2(u2, v2), col)
end
function MT.ImFontAtlas:AddFont(font_cfg_in)
IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!")
IM_ASSERT((font_cfg_in.FontData ~= nil and font_cfg_in.FontDataSize > 0) or (font_cfg_in.FontLoader ~= nil))
IM_ASSERT(font_cfg_in.SizePixels > 0.0, "Is ImFontConfig struct correctly initialized?")
IM_ASSERT(font_cfg_in.RasterizerDensity > 0.0, "Is ImFontConfig struct correctly initialized?")
if font_cfg_in.GlyphOffset.x ~= 0.0 or font_cfg_in.GlyphOffset.y ~= 0.0 or
font_cfg_in.GlyphMinAdvanceX ~= 0.0 or font_cfg_in.GlyphMaxAdvanceX ~= FLT_MAX then
IM_ASSERT(font_cfg_in.SizePixels ~= 0.0,
"Specifying glyph offset/advances requires a reference size to base it on.")
end
if self.Builder == nil then
ImFontAtlasBuildInit(self)
end
local is_first_font = (self.Fonts.Size == 0)
local font
if not font_cfg_in.MergeMode then
font = ImFont()
font.FontId = self.FontNextUniqueID
self.FontNextUniqueID = self.FontNextUniqueID + 1
font.Flags = font_cfg_in.Flags
font.LegacySize = font_cfg_in.SizePixels
font.CurrentRasterizerDensity = font_cfg_in.RasterizerDensity
self.Fonts:push_back(font)
else
IM_ASSERT(self.Fonts.Size > 0, "Cannot use MergeMode for the first font!")
font = (font_cfg_in.DstFont ~= nil) and font_cfg_in.DstFont or self.Fonts:back()
ImFontAtlasFontDiscardBakes(self, font, 0)
end
self.Sources:push_back(font_cfg_in)
local font_cfg = self.Sources:back()
if (font_cfg.DstFont == nil) then
font_cfg.DstFont = font
end
font.Sources:push_back(font_cfg)
ImFontAtlasBuildUpdatePointers(self)
if font_cfg.GlyphExcludeRanges ~= nil then
local size = 0
for _, v in ipairs(font_cfg.GlyphExcludeRanges) do if v == 0 then break end size = size + 1 end
IM_ASSERT(bit32.band(size, 1) == 0, "GlyphExcludeRanges[] size must be multiple of two!")
IM_ASSERT(size <= 64, "GlyphExcludeRanges[] size must be small!")
end
if font_cfg.FontLoader ~= nil then
IM_ASSERT(font_cfg.FontLoader.FontBakedLoadGlyph ~= nil)
IM_ASSERT(font_cfg.FontLoader.LoaderInit == nil and font_cfg.FontLoader.LoaderShutdown == nil)
end
if font_cfg_in.MergeMode and font_cfg_in.SizePixels > 0 then
IM_ASSERT(bit32.band(font.Flags, ImFontFlags.ImplicitRefSize) == 0, "Cannot use MergeMode with an explicit reference size when the destination font used an implicit reference size!")
end
IM_ASSERT(font_cfg.FontLoaderData == nil)
if not ImFontAtlasFontSourceInit(self, font_cfg) then
ImFontAtlasFontDestroySourceData(self, font_cfg)
self.Sources:pop_back()
font.Sources:pop_back()
if not font_cfg.MergeMode then
font = nil
self.Fonts:pop_back()
end
return nil
end
ImFontAtlasFontSourceAddToFont(self, font, font_cfg)
if (is_first_font) then
ImFontAtlasBuildNotifySetFont(self, nil, font)
end
return font
end
--- @param ctx ImGuiContext
--- @return float
local function GetExpectedContextFontSize(ctx)
return ((ctx.Style.FontSizeBase > 0.0) and ctx.Style.FontSizeBase or 13.0) * ctx.Style.FontScaleMain * ctx.Style.FontScaleDpi
end
--- @param font_cfg ImFontConfig
function MT.ImFontAtlas:AddFontDefault(font_cfg)
if self.OwnerContext == nil or GetExpectedContextFontSize(self.OwnerContext) >= 15.0 then
return self:AddFontDefaultVector(font_cfg)
else
return self:AddFontDefaultBitmap(font_cfg)
end
end
function MT.ImFontAtlas:AddFontFromMemoryTTF(font_data, font_data_size, size_pixels, font_cfg_template, glyph_ranges)
IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!")
local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig()
IM_ASSERT(font_cfg.FontData == nil)
IM_ASSERT(font_data_size > 100, "Incorrect value for font_data_size!")
font_cfg.FontData = font_data
font_cfg.FontDataSize = font_data_size
font_cfg.SizePixels = (size_pixels > 0.0) and size_pixels or font_cfg.SizePixels
if glyph_ranges then
font_cfg.GlyphRanges = glyph_ranges
end
return self:AddFont(font_cfg)
end
-- TODO: GetDefaultCompressedFontDataProggyClean, GetDefaultCompressedFontDataProggyForever
function MT.ImFontAtlas:AddFontFromMemoryCompressedTTF()
-- TODO:
end
function MT.ImFontAtlas:AddFontFromFileTTF(filename, size_pixels, font_cfg_template, glyph_ranges)
IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!")
local data, data_size = ImStd.ImFileLoadToMemory(filename, "rb")
if not data then
if (font_cfg_template == nil or (bit32.band(font_cfg_template.Flags, ImFontFlags.NoLoadError) == 0)) then
-- IMGUI_DEBUG_LOG("While loading '%s'\n", filename)
IM_ASSERT_USER_ERROR(0, "Could not load font file!")
end
return nil
end
local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig()
if not font_cfg.Name or font_cfg.Name == "" then
for i = #filename, 1, -1 do
local c = string.byte(filename, i, i)
if (c == 47 or c == 92) then -- '/' or '\\'
font_cfg.Name = string.sub(filename, i + 1)
break
end
end
end
return self:AddFontFromMemoryTTF(data, data_size, size_pixels, font_cfg, glyph_ranges)
end
function GetDefaultFontDataProggyClean()
return ImStd.ImFileLoadToMemory("resource/fonts/ProggyClean.ttf", "rb")
end
function GetDefaultFontDataProggyForever()
return ImStd.ImFileLoadToMemory("resource/fonts/ProggyForever.ttf", "rb")
end
-- TODO: IMGUI_DISABLE_DEFAULT_FONT, IMGUI_DISABLE_DEFAULT_FONT_BITMAP
--- @param font_cfg_template ImFontConfig
function MT.ImFontAtlas:AddFontDefaultBitmap(font_cfg_template)
local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig()
if not font_cfg_template then
font_cfg.PixelSnapH = true
end
if font_cfg.SizePixels <= 0.0 then
font_cfg.SizePixels = 13.0
font_cfg.Flags = bit32.bor(font_cfg.Flags, ImFontFlags.ImplicitRefSize)
end
if not font_cfg.Name or font_cfg.Name == "" then
font_cfg.Name = "ProggyClean.ttf"
end
font_cfg.EllipsisChar = 0x0085
font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 1.0 * (font_cfg.SizePixels / 13.0)
local ttf_data, ttf_data_size = GetDefaultFontDataProggyClean()
return self:AddFontFromMemoryTTF(ttf_data, ttf_data_size, font_cfg.SizePixels, font_cfg)
end
--- @param font_cfg_template ImFontConfig
function MT.ImFontAtlas:AddFontDefaultVector(font_cfg_template)
local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig()
if not font_cfg_template then
font_cfg.PixelSnapH = true
end
if font_cfg.SizePixels <= 0.0 then
font_cfg.SizePixels = 13.0
font_cfg.Flags = bit32.bor(font_cfg.Flags, ImFontFlags.ImplicitRefSize)
end
if not font_cfg.Name or font_cfg.Name == "" then
font_cfg.Name = "ProggyForever.ttf"
end
font_cfg.ExtraSizeScale = font_cfg.ExtraSizeScale * 1.015
font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 0.5 * (font_cfg.SizePixels / 16.0)
local ttf_data, ttf_data_size = GetDefaultFontDataProggyForever()
return self:AddFontFromMemoryTTF(ttf_data, ttf_data_size, font_cfg.SizePixels, font_cfg)
end
function MT.ImFontAtlas:GetCustomRect(id, out_r)
local r = ImFontAtlasPackGetRectSafe(self, id)
if r == nil then
return false
end
IM_ASSERT(self.TexData.Width > 0 and self.TexData.Height > 0)
if out_r == nil then
return true
end
out_r.x = r.x
out_r.y = r.y
out_r.w = r.w
out_r.h = r.h
ImVec2_Copy(out_r.uv0, ImVec2((r.x), (r.y)) * self.TexUvScale)
ImVec2_Copy(out_r.uv1, ImVec2((r.x + r.w), (r.y + r.h)) * self.TexUvScale)
return true
end
--- @param atlas ImFontAtlas
--- @param cursor_type ImGuiMouseCursor
--- @param out_offset ImVec2
--- @param out_size ImVec2
--- @param out_uv_border ImVec2[]
--- @param out_uv_fill ImVec2[]
function ImFontAtlasGetMouseCursorTexData(atlas, cursor_type, out_offset, out_size, out_uv_border, out_uv_fill)
if cursor_type <= ImGuiMouseCursor.None or cursor_type >= ImGuiMouseCursor.COUNT then
return false
end
if bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0 then
return false
end
local r = ImFontAtlasPackGetRect(atlas, atlas.Builder.PackIdMouseCursors)
local pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type + 1][1] + ImVec2(r.x, r.y)
local size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type + 1][2]
ImVec2_Copy(out_size, size)
ImVec2_Copy(out_offset, FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type + 1][3])
ImVec2_Copy(out_uv_border[1], (pos) * atlas.TexUvScale)
ImVec2_Copy(out_uv_border[2], (pos + size) * atlas.TexUvScale)
pos.x = pos.x + (FONT_ATLAS_DEFAULT_TEX_DATA_W + 1)
ImVec2_Copy(out_uv_fill[1], (pos) * atlas.TexUvScale)
ImVec2_Copy(out_uv_fill[2], (pos + size) * atlas.TexUvScale)
return true
end
function MT.ImFontAtlas:AddCustomRect(width, height, out_r)
IM_ASSERT(width > 0 and width <= 0xFFFF)
IM_ASSERT(height > 0 and height <= 0xFFFF)
if (self.Builder == nil) then
ImFontAtlasBuildInit(self)
end
local r_id = ImFontAtlasPackAddRect(self, width, height)
if (r_id == ImFontAtlasRectId_Invalid) then
return ImFontAtlasRectId_Invalid
end
if (out_r ~= nil) then
self:GetCustomRect(r_id, out_r)
end
if (self.RendererHasTextures) then
local r = ImFontAtlasPackGetRect(self, r_id)
ImFontAtlasTextureBlockQueueUpload(self, self.TexData, r.x, r.y, r.w, r.h)
end
return r_id
end
local function IM_NORMALIZE2F_OVER_ZERO(VX, VY)
local d2 = VX * VX + VY * VY
if d2 > 0.0 then
local inv_len = ImRsqrt(d2)
VX = VX * inv_len
VY = VY * inv_len
end
return VX, VY
end
local function IM_FIXNORMAL2F(VX, VY)
local IM_FIXNORMAL2F_MAX_INVLEN2 = 100
local d2 = VX * VX + VY * VY
if d2 > 0.000001 then
local inv_len2 = 1.0 / d2
if inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2 then
inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2
end
VX = VX * inv_len2
VY = VY * inv_len2
end
return VX, VY
end
function MT.ImDrawData:Clear()
self.Valid = false
self.FrameCount = 0; self.TotalIdxCount = 0; self.TotalVtxCount = 0
self.CmdLists:resize(0)
self.DisplayPos = ImVec2(0.0, 0.0)
self.DisplaySize = ImVec2(0.0, 0.0)
self.FramebufferScale = ImVec2(0.0, 0.0)
self.OwnerViewport = nil
self.Textures = nil
end
function ImGui.AddDrawListToDrawDataEx(draw_data, out_list, draw_list)
if draw_list.CmdBuffer.Size == 0 then
return
end
if draw_list.CmdBuffer.Size == 1 and draw_list.CmdBuffer.Data[1].ElemCount == 0 and draw_list.CmdBuffer.Data[1].UserCallback == nil then
return
end
IM_ASSERT(draw_list.VtxBuffer.Size == 0 or draw_list._VtxWritePtr == draw_list.VtxBuffer.Size + 1)
IM_ASSERT(draw_list.IdxBuffer.Size == 0 or draw_list._IdxWritePtr == draw_list.IdxBuffer.Size + 1)
if (bit32.band(draw_list.Flags, ImDrawListFlags.AllowVtxOffset) == 0) then
IM_ASSERT(draw_list._VtxCurrentIdx == draw_list.VtxBuffer.Size + 1)
end
out_list:push_back(draw_list)
draw_data.TotalVtxCount = draw_data.TotalVtxCount + draw_list.VtxBuffer.Size
draw_data.TotalIdxCount = draw_data.TotalIdxCount + draw_list.IdxBuffer.Size
end
function MT.ImDrawData:AddDrawList(draw_list)
draw_list:_PopUnusedDrawCmd()
ImGui.AddDrawListToDrawDataEx(self, self.CmdLists, draw_list)
end
local IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN = 4
local IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX = 512
local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD, _MAXERROR) return ImClamp(IM_ROUNDUP_TO_EVEN(ImCeil(IM_PI / ImAcos(1 - ImMin(_MAXERROR, _RAD) / _RAD))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX) end
local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N, _MAXERROR) return (_MAXERROR / (1 - ImCos(IM_PI / ImMax(_N, IM_PI)))) end
local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N, _RAD) return ((1 - ImCos(IM_PI / ImMax(_N, IM_PI))) / _RAD) end
function MT.ImDrawListSharedData:SetCircleTessellationMaxError(max_error)
if self.CircleTessellationMaxError == max_error then
return
end
IM_ASSERT(max_error > 0)
self.CircleTessellationMaxError = max_error
for i = 1, 64 do -- IM_COUNTOF(CircleSegmentCounts)
local radius = (i - 1)
self.CircleSegmentCounts[i] = (i > 1) and IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self.CircleTessellationMaxError) or IM_DRAWLIST_ARCFAST_SAMPLE_MAX
end
self.ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, self.CircleTessellationMaxError)
end
--- @param data ImDrawListSharedData
function MT.ImDrawList:_SetDrawListSharedData(data)
if self._Data ~= nil then
self._Data.DrawLists:find_erase_unsorted(self)
end
self._Data = data
if self._Data ~= nil then
self._Data.DrawLists:push_back(self)
end
end
-- TODO:
function MT.ImDrawList:_ResetForNewFrame()
self.CmdBuffer:resize(0)
self.IdxBuffer:resize(0)
self.VtxBuffer:resize(0)
self.Flags = self._Data.InitialFlags
self._CmdHeader = ImDrawCmdHeader() -- memset(&_CmdHeader, 0, sizeof(_CmdHeader))
self._VtxCurrentIdx = 1
self._VtxWritePtr = 1
self._IdxWritePtr = 1
self._ClipRectStack:resize(0)
self._TextureStack:resize(0)
self._Path:resize(0)
self.CmdBuffer:push_back(ImDrawCmd())
self._FringeScale = self._Data.InitialFringeScale
end
function MT.ImDrawList:_ClearFreeMemory()
self.CmdBuffer:clear()
self.IdxBuffer:clear()
self.VtxBuffer:clear()
self.Flags = ImDrawListFlags.None
self._VtxCurrentIdx = 1
self._VtxWritePtr = 1
self._IdxWritePtr = 1
self._ClipRectStack:clear()
self._TextureStack:clear()
-- self._CallbacksDataBuf:clear()
self._Path:clear()
-- self._Splitter.ClearFreeMemory()
end
function MT.ImDrawList:AddDrawCmd()
local draw_cmd = ImDrawCmd()
ImVec4_Copy(draw_cmd.ClipRect, self._CmdHeader.ClipRect) -- Same as calling ImDrawCmd_HeaderCopy()?
draw_cmd.TexRef = self._CmdHeader.TexRef
draw_cmd.VtxOffset = self._CmdHeader.VtxOffset
draw_cmd.IdxOffset = self.IdxBuffer.Size
IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z and draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w)
self.CmdBuffer:push_back(draw_cmd)
end
function MT.ImDrawList:_PopUnusedDrawCmd()
while self.CmdBuffer.Size > 0 do
local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
if curr_cmd.ElemCount ~= 0 or curr_cmd.UserCallback ~= nil then
break
end
self.CmdBuffer:pop_back()
end
end
--- @param callback ImDrawCallback
--- @param userdata any
--- @param userdata_size? size_t
function MT.ImDrawList:AddCallback(callback, userdata, userdata_size)
if userdata_size == nil then userdata_size = 0 end
IM_ASSERT(callback ~= nil)
IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0)
local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
IM_ASSERT(curr_cmd.UserCallback == nil)
if curr_cmd.ElemCount ~= 0 then
self:AddDrawCmd()
curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
end
curr_cmd.UserCallback = callback
-- TODO: _CallbacksDataBuf?
if userdata_size == 0 then
curr_cmd.UserCallbackData = userdata
else
IM_ASSERT(userdata ~= nil)
IM_ASSERT(userdata_size < bit32.lshift(1, 31))
end
self:AddDrawCmd()
end
--- Compare ClipRect, TexRef, VtxOffset
--- @param CMD_LHS ImDrawCmd|ImDrawCmdHeader
--- @param CMD_RHS ImDrawCmd|ImDrawCmdHeader
--- @return bool
local function ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS)
if CMD_LHS.ClipRect.x ~= CMD_RHS.ClipRect.x or
CMD_LHS.ClipRect.y ~= CMD_RHS.ClipRect.y or
CMD_LHS.ClipRect.z ~= CMD_RHS.ClipRect.z or
CMD_LHS.ClipRect.w ~= CMD_RHS.ClipRect.w then
return false
end
if CMD_LHS.TexRef._TexData ~= CMD_RHS.TexRef._TexData or
CMD_LHS.TexRef._TexID ~= CMD_RHS.TexRef._TexID then
return false
end
if CMD_LHS.VtxOffset ~= CMD_RHS.VtxOffset then
return false
end
return true
end
--- Copy ClipRect, TexRef, VtxOffset
--- @param CMD_DST ImDrawCmd|ImDrawCmdHeader
--- @param CMD_SRC ImDrawCmd|ImDrawCmdHeader
local function ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC)
CMD_DST.ClipRect.x = CMD_SRC.ClipRect.x
CMD_DST.ClipRect.y = CMD_SRC.ClipRect.y
CMD_DST.ClipRect.z = CMD_SRC.ClipRect.z
CMD_DST.ClipRect.w = CMD_SRC.ClipRect.w
CMD_DST.TexRef._TexData = CMD_SRC.TexRef._TexData
CMD_DST.TexRef._TexID = CMD_SRC.TexRef._TexID
CMD_DST.VtxOffset = CMD_SRC.VtxOffset
end
--- @param CMD_0 ImDrawCmd
--- @param CMD_1 ImDrawCmd
local function ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1)
return CMD_0.IdxOffset + CMD_0.ElemCount == CMD_1.IdxOffset
end
function MT.ImDrawList:_TryMergeDrawCmds()
IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0)
local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1]
if ImDrawCmd_HeaderCompare(curr_cmd, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and curr_cmd.UserCallback == nil and prev_cmd.UserCallback == nil then
prev_cmd.ElemCount = prev_cmd.ElemCount + curr_cmd.ElemCount
self.CmdBuffer:pop_back()
end
end
function MT.ImDrawList:_OnChangedClipRect()
IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0)
local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
if (curr_cmd.ElemCount ~= 0 and self._CmdHeader.ClipRect ~= curr_cmd.ClipRect) then
self:AddDrawCmd()
return
end
IM_ASSERT(curr_cmd.UserCallback == nil)
local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1]
if (curr_cmd.ElemCount == 0 and self.CmdBuffer.Size > 1 and ImDrawCmd_HeaderCompare(self._CmdHeader, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and prev_cmd.UserCallback == nil) then
self.CmdBuffer:pop_back()
return
end
ImVec4_Copy(curr_cmd.ClipRect, self._CmdHeader.ClipRect)
end
function MT.ImDrawList:_OnChangedTexture()
IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0)
local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
if curr_cmd.ElemCount ~= 0 and curr_cmd.TexRef ~= self._CmdHeader.TexRef then
self:AddDrawCmd()
return
end
if curr_cmd.UserCallback ~= nil then
return
end
local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1]
if curr_cmd.ElemCount == 0 and self.CmdBuffer.Size > 1 and ImDrawCmd_HeaderCompare(self._CmdHeader, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and prev_cmd.UserCallback == nil then
self.CmdBuffer:pop_back()
return
end
curr_cmd.TexRef = self._CmdHeader.TexRef
end
function MT.ImDrawList:_OnChangedVtxOffset()
self._VtxCurrentIdx = 1
IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0)
local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
if curr_cmd.ElemCount ~= 0 then
self:AddDrawCmd()
return
end
IM_ASSERT(curr_cmd.UserCallback == nil)
curr_cmd.VtxOffset = self._CmdHeader.VtxOffset
end
--- @param points ImVec2[]
--- @param points_count int
--- @param col ImU32
function MT.ImDrawList:AddConvexPolyFilled(points, points_count, col)
if points_count < 3 or bit32.band(col, IM_COL32_A_MASK) == 0 then
return
end
local uv = self._Data.TexUvWhitePixel
if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedFill) ~= 0 then
local AA_SIZE = self._FringeScale
local col_trans = bit32.band(col, bit32.bnot(IM_COL32_A_MASK))
local idx_count = (points_count - 2) * 3 + points_count * 6
local vtx_count = points_count * 2
self:PrimReserve(idx_count, vtx_count)
local vtx_inner_idx = self._VtxCurrentIdx
local vtx_outer_idx = self._VtxCurrentIdx + 1
local idx_data = self.IdxBuffer.Data
for i = 2, points_count - 1 do
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = vtx_inner_idx; idx_data[idx_write_ptr + 1] = vtx_inner_idx + ((i - 1) * 2); idx_data[idx_write_ptr + 2] = vtx_inner_idx + (i * 2)
self._IdxWritePtr = idx_write_ptr + 3
end
self._Data.TempBuffer:reserve_discard(points_count)
local temp_normals = self._Data.TempBuffer.Data
local i0 = points_count
for i1 = 1, points_count do
local p0 = points[i0]
local p1 = points[i1]
local dx = p1.x - p0.x
local dy = p1.y - p0.y
dx, dy = IM_NORMALIZE2F_OVER_ZERO(dx, dy)
temp_normals[i0].x = dy
temp_normals[i0].y = -dx
i0 = i1
end
local vtx_data = self.VtxBuffer.Data
i0 = points_count
for i1 = 1, points_count do
local n0 = temp_normals[i0]
local n1 = temp_normals[i1]
local dm_x = (n0.x + n1.x) * 0.5
local dm_y = (n0.y + n1.y) * 0.5
dm_x, dm_y = IM_FIXNORMAL2F(dm_x, dm_y)
dm_x = dm_x * AA_SIZE * 0.5
dm_y = dm_y * AA_SIZE * 0.5
local vtx_write_ptr = self._VtxWritePtr
vtx_data[vtx_write_ptr + 0][1].x = points[i1].x - dm_x; vtx_data[vtx_write_ptr + 0][1].y = points[i1].y - dm_y; ImVec2_Copy(vtx_data[vtx_write_ptr + 0][2], uv); vtx_data[vtx_write_ptr + 0][3] = col
vtx_data[vtx_write_ptr + 1][1].x = points[i1].x + dm_x; vtx_data[vtx_write_ptr + 1][1].y = points[i1].y + dm_y; ImVec2_Copy(vtx_data[vtx_write_ptr + 1][2], uv); vtx_data[vtx_write_ptr + 1][3] = col_trans
self._VtxWritePtr = vtx_write_ptr + 2
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = vtx_inner_idx + ((i1 - 1) * 2); idx_data[idx_write_ptr + 1] = vtx_inner_idx + ((i0 - 1) * 2); idx_data[idx_write_ptr + 2] = vtx_outer_idx + ((i0 - 1) * 2)
idx_data[idx_write_ptr + 3] = vtx_outer_idx + ((i0 - 1) * 2); idx_data[idx_write_ptr + 4] = vtx_outer_idx + ((i1 - 1) * 2); idx_data[idx_write_ptr + 5] = vtx_inner_idx + ((i1 - 1) * 2)
self._IdxWritePtr = idx_write_ptr + 6
i0 = i1
end
self._VtxCurrentIdx = self._VtxCurrentIdx + vtx_count
else
local idx_count = (points_count - 2) * 3
local vtx_count = points_count
self:PrimReserve(idx_count, vtx_count)
local idx_data = self.IdxBuffer.Data; local vtx_data = self.VtxBuffer.Data
for i = 1, vtx_count do
local vtx_write_ptr = self._VtxWritePtr
ImVec2_Copy(vtx_data[vtx_write_ptr + 0][1], points[i]); ImVec2_Copy(vtx_data[vtx_write_ptr + 0][2], uv); vtx_data[vtx_write_ptr + 0][3] = col
self._VtxWritePtr = vtx_write_ptr + 1
end
for i = 3, points_count do
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = self._VtxCurrentIdx; idx_data[idx_write_ptr + 1] = self._VtxCurrentIdx + i - 2; idx_data[idx_write_ptr + 2] = self._VtxCurrentIdx + i - 1
self._IdxWritePtr = idx_write_ptr + 3
end
self._VtxCurrentIdx = self._VtxCurrentIdx + vtx_count
end
end
function MT.ImDrawList:PushTexture(tex_ref)
self._TextureStack:push_back(tex_ref)
self._CmdHeader.TexRef = tex_ref
if (tex_ref._TexData ~= nil) then
IM_ASSERT(tex_ref._TexData.WantDestroyNextFrame == false)
end
self:_OnChangedTexture()
end
function MT.ImDrawList:PopTexture()
self._TextureStack:pop_back()
self._CmdHeader.TexRef = (self._TextureStack.Size == 0) and ImTextureRef() or self._TextureStack.Data[self._TextureStack.Size]
self:_OnChangedTexture()
end
function MT.ImDrawList:_SetTexture(tex_ref)
if (self._CmdHeader.TexRef == tex_ref) then
return
end
self._CmdHeader.TexRef = tex_ref
self._TextureStack.Data[self._TextureStack.Size] = tex_ref
self:_OnChangedTexture()
end
function MT.ImDrawList:PrimReserve(idx_count, vtx_count)
IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0)
if (self._VtxCurrentIdx + vtx_count >= bit32.lshift(1, 16)) and (bit32.band(self.Flags, ImDrawListFlags.AllowVtxOffset) ~= 0) then
self._CmdHeader.VtxOffset = self.VtxBuffer.Size + 1
self:_OnChangedVtxOffset()
end
local draw_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
draw_cmd.ElemCount = draw_cmd.ElemCount + idx_count
local vtx_buffer_old_size = self.VtxBuffer.Size
self.VtxBuffer:resize(vtx_buffer_old_size + vtx_count)
self._VtxWritePtr = vtx_buffer_old_size + 1
local idx_buffer_old_size = self.IdxBuffer.Size
self.IdxBuffer:resize(idx_buffer_old_size + idx_count)
self._IdxWritePtr = idx_buffer_old_size + 1
end
function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count)
IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0)
local draw_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size]
draw_cmd.ElemCount = draw_cmd.ElemCount - idx_count
self.VtxBuffer:shrink(self.VtxBuffer.Size - vtx_count)
self.IdxBuffer:shrink(self.IdxBuffer.Size - idx_count)
self._VtxWritePtr = self.VtxBuffer.Size + 1
self._IdxWritePtr = self.IdxBuffer.Size + 1
end
--- @param a ImVec2
--- @param c ImVec2
--- @param col ImU32
function MT.ImDrawList:PrimRect(a, c, col)
local uv = self._Data.TexUvWhitePixel
local idx = self._VtxCurrentIdx
local idx_data = self.IdxBuffer.Data; local vtx_data = self.VtxBuffer.Data
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = idx
idx_data[idx_write_ptr + 1] = idx + 1
idx_data[idx_write_ptr + 2] = idx + 2
idx_data[idx_write_ptr + 3] = idx
idx_data[idx_write_ptr + 4] = idx + 2
idx_data[idx_write_ptr + 5] = idx + 3
local vtx_write_ptr = self._VtxWritePtr
ImVec2_Copy(vtx_data[vtx_write_ptr + 0][1], a)
ImVec2_Copy(vtx_data[vtx_write_ptr + 0][2], uv)
vtx_data[vtx_write_ptr + 0][3] = col
ImVec2_CopyV(vtx_data[vtx_write_ptr + 1][1], c[1], a[2])
ImVec2_Copy(vtx_data[vtx_write_ptr + 1][2], uv)
vtx_data[vtx_write_ptr + 1][3] = col
ImVec2_Copy(vtx_data[vtx_write_ptr + 2][1], c)
ImVec2_Copy(vtx_data[vtx_write_ptr + 2][2], uv)
vtx_data[vtx_write_ptr + 2][3] = col
ImVec2_CopyV(vtx_data[vtx_write_ptr + 3][1], a[1], c[2])
ImVec2_Copy(vtx_data[vtx_write_ptr + 3][2], uv)
vtx_data[vtx_write_ptr + 3][3] = col
self._VtxWritePtr = vtx_write_ptr + 4
self._VtxCurrentIdx = idx + 4
self._IdxWritePtr = idx_write_ptr + 6
end
--- @param a ImVec2
--- @param c ImVec2
--- @param uv_a ImVec2
--- @param uv_c ImVec2
--- @param col any
function MT.ImDrawList:PrimRectUV(a, c, uv_a, uv_c, col)
local idx = self._VtxCurrentIdx
local idx_data = self.IdxBuffer.Data; local vtx_data = self.VtxBuffer.Data
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = idx
idx_data[idx_write_ptr + 1] = idx + 1
idx_data[idx_write_ptr + 2] = idx + 2
idx_data[idx_write_ptr + 3] = idx
idx_data[idx_write_ptr + 4] = idx + 2
idx_data[idx_write_ptr + 5] = idx + 3
local vtx_write_ptr = self._VtxWritePtr
ImVec2_Copy(vtx_data[vtx_write_ptr + 0][1], a)
ImVec2_Copy(vtx_data[vtx_write_ptr + 0][2], uv_a)
vtx_data[vtx_write_ptr + 0][3] = col
ImVec2_CopyV(vtx_data[vtx_write_ptr + 1][1], c[1], a[2])
ImVec2_CopyV(vtx_data[vtx_write_ptr + 1][2], uv_c[1], uv_a[2])
vtx_data[vtx_write_ptr + 1][3] = col
ImVec2_Copy(vtx_data[vtx_write_ptr + 2][1], c)
ImVec2_Copy(vtx_data[vtx_write_ptr + 2][2], uv_c)
vtx_data[vtx_write_ptr + 2][3] = col
ImVec2_CopyV(vtx_data[vtx_write_ptr + 3][1], a[1], c[2])
ImVec2_CopyV(vtx_data[vtx_write_ptr + 3][2], uv_a[1], uv_c[2])
vtx_data[vtx_write_ptr + 3][3] = col
self._VtxWritePtr = vtx_write_ptr + 4
self._VtxCurrentIdx = idx + 4
self._IdxWritePtr = idx_write_ptr + 6
end
--- @param points ImVec2[]
--- @param points_count int
--- @param col ImU32
--- @param thickness float
--- @param flags? ImDrawFlags
function MT.ImDrawList:AddPolyline(points, points_count, col, thickness, flags)
if flags == nil then flags = 0 end
if points_count < 2 or bit32.band(col, IM_COL32_A_MASK) == 0 then
return
end
local closed = bit32.band(flags, ImDrawFlags.Closed) ~= 0
local opaque_uv = self._Data.TexUvWhitePixel
local count = closed and points_count or points_count - 1 -- Number of line segments
local thick_line = thickness > self._FringeScale
IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?")
if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLines) ~= 0 then
-- Anti-aliased stroke
local AA_SIZE = self._FringeScale
local col_trans = bit32.band(col, bit32.bnot(IM_COL32_A_MASK))
-- Thicknesses <1.0 should behave like thickness 1.0
thickness = ImMax(thickness, 1.0)
local integer_thickness = ImFloor(thickness)
local fractional_thickness = thickness - integer_thickness
-- Do we want to draw this line using a texture?
local use_texture = bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLinesUseTex) ~= 0 and integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX and fractional_thickness <= 0.00001 and AA_SIZE == 1.0
IM_ASSERT_PARANOID((not use_texture) or bit32.band(self._Data.Font.OwnerAtlas.Flags, ImFontAtlasFlags.NoBakedLines) == 0)
local idx_count = use_texture and (count * 6) or (thick_line and count * 18 or count * 12)
local vtx_count = use_texture and (points_count * 2) or (thick_line and points_count * 4 or points_count * 3)
self:PrimReserve(idx_count, vtx_count)
-- Temporary buffer
local temp_buffer_size = points_count * ((use_texture or not thick_line) and 3 or 5)
self._Data.TempBuffer:reserve_discard(temp_buffer_size)
local temp_normals = self._Data.TempBuffer.Data
local temp_points = self._Data.TempBuffer.Data; local temp_points_start = points_count + 1
-- Calculate normals for each line segment
for i1 = 1, count do
local i2 = (i1 == points_count) and 1 or i1 + 1
local p1 = points[i1]
local p2 = points[i2]
local dx = p2[1] - p1[1]
local dy = p2[2] - p1[2]
dx, dy = IM_NORMALIZE2F_OVER_ZERO(dx, dy)
temp_normals[i1][1] = dy
temp_normals[i1][2] = -dx
end
if not closed then
ImVec2_Copy(temp_normals[points_count], temp_normals[points_count - 1])
end
-- If we are drawing a one-pixel-wide line without a texture, or a textured line of any width
if use_texture or not thick_line then
-- [PATH 1] Texture-based lines (thick or non-thick)
-- [PATH 2] Non texture-based lines (non-thick)
local half_draw_size = use_texture and (thickness * 0.5 + 1) or AA_SIZE
-- If line is not closed, the first and last points need to be generated differently
if not closed then
ImVec2_CopyV(temp_points[temp_points_start + 0], ImVec2_AddVA(points[1], ImVec2_MulVX(temp_normals[1], half_draw_size)))
ImVec2_CopyV(temp_points[temp_points_start + 1], ImVec2_SubVA(points[1], ImVec2_MulVX(temp_normals[1], half_draw_size)))
ImVec2_CopyV(temp_points[temp_points_start + (points_count - 1) * 2 + 0], ImVec2_AddVA(points[points_count], ImVec2_MulVX(temp_normals[points_count], half_draw_size)))
ImVec2_CopyV(temp_points[temp_points_start + (points_count - 1) * 2 + 1], ImVec2_SubVA(points[points_count], ImVec2_MulVX(temp_normals[points_count], half_draw_size)))
end
-- Generate indices and vertices
local idx1 = self._VtxCurrentIdx
local idx_data = self.IdxBuffer.Data; local vtx_data = self.VtxBuffer.Data
for i1 = 1, count do
local i2 = (i1 == points_count) and 1 or i1 + 1
local idx2 = (i1 == points_count) and self._VtxCurrentIdx or (idx1 + (use_texture and 2 or 3))
-- Average normals
local dm_x = (temp_normals[i1][1] + temp_normals[i2][1]) * 0.5
local dm_y = (temp_normals[i1][2] + temp_normals[i2][2]) * 0.5
dm_x, dm_y = IM_FIXNORMAL2F(dm_x, dm_y)
dm_x = dm_x * half_draw_size
dm_y = dm_y * half_draw_size
-- Add temporary vertices for the outer edges
local out_off = (i2 - 1) * 2
temp_points[temp_points_start + out_off + 0][1] = points[i2][1] + dm_x
temp_points[temp_points_start + out_off + 0][2] = points[i2][2] + dm_y
temp_points[temp_points_start + out_off + 1][1] = points[i2][1] - dm_x
temp_points[temp_points_start + out_off + 1][2] = points[i2][2] - dm_y
if use_texture then
-- Add indices for two triangles
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = idx2 + 0; idx_data[idx_write_ptr + 1] = idx1 + 0; idx_data[idx_write_ptr + 2] = idx1 + 1
idx_data[idx_write_ptr + 3] = idx2 + 1; idx_data[idx_write_ptr + 4] = idx1 + 1; idx_data[idx_write_ptr + 5] = idx2 + 0
self._IdxWritePtr = idx_write_ptr + 6
else
-- Add indices for four triangles
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = idx2 + 0; idx_data[idx_write_ptr + 1] = idx1 + 0; idx_data[idx_write_ptr + 2] = idx1 + 2
idx_data[idx_write_ptr + 3] = idx1 + 2; idx_data[idx_write_ptr + 4] = idx2 + 2; idx_data[idx_write_ptr + 5] = idx2 + 0
idx_data[idx_write_ptr + 6] = idx2 + 1; idx_data[idx_write_ptr + 7] = idx1 + 1; idx_data[idx_write_ptr + 8] = idx1 + 0
idx_data[idx_write_ptr + 9] = idx1 + 0; idx_data[idx_write_ptr + 10] = idx2 + 0; idx_data[idx_write_ptr + 11] = idx2 + 1
self._IdxWritePtr = idx_write_ptr + 12
end
idx1 = idx2
end
-- Add vertices
if use_texture then
-- Texture-based: need to implement TexUvLines lookup
local tex_uvs = self._Data.TexUvLines[integer_thickness]
local tex_uv0 = ImVec2(tex_uvs.x, tex_uvs.y)
local tex_uv1 = ImVec2(tex_uvs.z, tex_uvs.w)
for i = 0, points_count - 1 do
local vtx_write_ptr = self._VtxWritePtr
ImVec2_Copy(vtx_data[vtx_write_ptr + 0][1], temp_points[temp_points_start + i * 2 + 0]); ImVec2_Copy(vtx_data[vtx_write_ptr + 0][2], tex_uv0); vtx_data[vtx_write_ptr + 0][3] = col
ImVec2_Copy(vtx_data[vtx_write_ptr + 1][1], temp_points[temp_points_start + i * 2 + 1]); ImVec2_Copy(vtx_data[vtx_write_ptr + 1][2], tex_uv1); vtx_data[vtx_write_ptr + 1][3] = col
self._VtxWritePtr = vtx_write_ptr + 2
end
else
-- If we're not using a texture, we need the center vertex as well
for i = 0, points_count - 1 do
local vtx_write_ptr = self._VtxWritePtr
ImVec2_Copy(vtx_data[vtx_write_ptr + 0][1], points[i + 1]); ImVec2_Copy(vtx_data[vtx_write_ptr + 0][2], opaque_uv); vtx_data[vtx_write_ptr + 0][3] = col
ImVec2_Copy(vtx_data[vtx_write_ptr + 1][1], temp_points[temp_points_start + i * 2 + 0]); ImVec2_Copy(vtx_data[vtx_write_ptr + 1][2], opaque_uv); vtx_data[vtx_write_ptr + 1][3] = col_trans
ImVec2_Copy(vtx_data[vtx_write_ptr + 2][1], temp_points[temp_points_start + i * 2 + 1]); ImVec2_Copy(vtx_data[vtx_write_ptr + 2][2], opaque_uv); vtx_data[vtx_write_ptr + 2][3] = col_trans
self._VtxWritePtr = vtx_write_ptr + 3
end
end
else
-- [PATH 3] Non texture-based lines (thick)
local half_inner_thickness = (thickness - AA_SIZE) * 0.5
-- If line is not closed, handle first and last points
if not closed then
local points_last = points_count - 1
ImVec2_CopyV(temp_points[temp_points_start + 0], ImVec2_AddVA(points[1], ImVec2_MulVX(temp_normals[1], (half_inner_thickness + AA_SIZE))))
ImVec2_CopyV(temp_points[temp_points_start + 1], ImVec2_AddVA(points[1], ImVec2_MulVX(temp_normals[1], half_inner_thickness)))
ImVec2_CopyV(temp_points[temp_points_start + 2], ImVec2_SubVA(points[1], ImVec2_MulVX(temp_normals[1], half_inner_thickness)))
ImVec2_CopyV(temp_points[temp_points_start + 3], ImVec2_SubVA(points[1], ImVec2_MulVX(temp_normals[1], (half_inner_thickness + AA_SIZE))))
ImVec2_CopyV(temp_points[temp_points_start + points_last * 4 + 0], ImVec2_AddVA(points[points_count], ImVec2_MulVX(temp_normals[points_last + 1], (half_inner_thickness + AA_SIZE))))
ImVec2_CopyV(temp_points[temp_points_start + points_last * 4 + 1], ImVec2_AddVA(points[points_count], ImVec2_MulVX(temp_normals[points_last + 1], half_inner_thickness)))
ImVec2_CopyV(temp_points[temp_points_start + points_last * 4 + 2], ImVec2_SubVA(points[points_count], ImVec2_MulVX(temp_normals[points_last + 1], half_inner_thickness)))
ImVec2_CopyV(temp_points[temp_points_start + points_last * 4 + 3], ImVec2_SubVA(points[points_count], ImVec2_MulVX(temp_normals[points_last + 1], (half_inner_thickness + AA_SIZE))))
end
-- Generate indices and vertices
local idx1 = self._VtxCurrentIdx
local idx_data = self.IdxBuffer.Data; local vtx_data = self.VtxBuffer.Data
for i1 = 1, count do
local i2 = (i1 == points_count) and 1 or i1 + 1
local idx2 = (i1 == points_count) and self._VtxCurrentIdx or (idx1 + 4)
-- Average normals
local dm_x = (temp_normals[i1][1] + temp_normals[i2][1]) * 0.5
local dm_y = (temp_normals[i1][2] + temp_normals[i2][2]) * 0.5
dm_x, dm_y = IM_FIXNORMAL2F(dm_x, dm_y)
local dm_out_x = dm_x * (half_inner_thickness + AA_SIZE)
local dm_out_y = dm_y * (half_inner_thickness + AA_SIZE)
local dm_in_x = dm_x * half_inner_thickness
local dm_in_y = dm_y * half_inner_thickness
-- Add temporary vertices
local out_off = (i2 - 1) * 4
temp_points[temp_points_start + out_off + 0][1] = points[i2][1] + dm_out_x
temp_points[temp_points_start + out_off + 0][2] = points[i2][2] + dm_out_y
temp_points[temp_points_start + out_off + 1][1] = points[i2][1] + dm_in_x
temp_points[temp_points_start + out_off + 1][2] = points[i2][2] + dm_in_y
temp_points[temp_points_start + out_off + 2][1] = points[i2][1] - dm_in_x
temp_points[temp_points_start + out_off + 2][2] = points[i2][2] - dm_in_y
temp_points[temp_points_start + out_off + 3][1] = points[i2][1] - dm_out_x
temp_points[temp_points_start + out_off + 3][2] = points[i2][2] - dm_out_y
-- Add indices
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = idx2 + 1; idx_data[idx_write_ptr + 1] = idx1 + 1; idx_data[idx_write_ptr + 2] = idx1 + 2
idx_data[idx_write_ptr + 3] = idx1 + 2; idx_data[idx_write_ptr + 4] = idx2 + 2; idx_data[idx_write_ptr + 5] = idx2 + 1
idx_data[idx_write_ptr + 6] = idx2 + 1; idx_data[idx_write_ptr + 7] = idx1 + 1; idx_data[idx_write_ptr + 8] = idx1 + 0
idx_data[idx_write_ptr + 9] = idx1 + 0; idx_data[idx_write_ptr + 10] = idx2 + 0; idx_data[idx_write_ptr + 11] = idx2 + 1
idx_data[idx_write_ptr + 12] = idx2 + 2; idx_data[idx_write_ptr + 13] = idx1 + 2; idx_data[idx_write_ptr + 14] = idx1 + 3
idx_data[idx_write_ptr + 15] = idx1 + 3; idx_data[idx_write_ptr + 16] = idx2 + 3; idx_data[idx_write_ptr + 17] = idx2 + 2
self._IdxWritePtr = idx_write_ptr + 18
idx1 = idx2
end
-- Add vertices
for i = 0, points_count - 1 do
local vtx_write_ptr = self._VtxWritePtr
ImVec2_Copy(vtx_data[vtx_write_ptr + 0][1], temp_points[temp_points_start + i * 4 + 0]); ImVec2_Copy(vtx_data[vtx_write_ptr + 0][2], opaque_uv); vtx_data[vtx_write_ptr + 0][3] = col_trans
ImVec2_Copy(vtx_data[vtx_write_ptr + 1][1], temp_points[temp_points_start + i * 4 + 1]); ImVec2_Copy(vtx_data[vtx_write_ptr + 1][2], opaque_uv); vtx_data[vtx_write_ptr + 1][3] = col
ImVec2_Copy(vtx_data[vtx_write_ptr + 2][1], temp_points[temp_points_start + i * 4 + 2]); ImVec2_Copy(vtx_data[vtx_write_ptr + 2][2], opaque_uv); vtx_data[vtx_write_ptr + 2][3] = col
ImVec2_Copy(vtx_data[vtx_write_ptr + 3][1], temp_points[temp_points_start + i * 4 + 3]); ImVec2_Copy(vtx_data[vtx_write_ptr + 3][2], opaque_uv); vtx_data[vtx_write_ptr + 3][3] = col_trans
self._VtxWritePtr = vtx_write_ptr + 4
end
end
self._VtxCurrentIdx = self._VtxCurrentIdx + vtx_count
else
-- [PATH 4] Non texture-based, Non anti-aliased lines
local idx_count = count * 6
local vtx_count = count * 4
self:PrimReserve(idx_count, vtx_count)
local idx_data = self.IdxBuffer.Data; local vtx_data = self.VtxBuffer.Data
for i1 = 1, count do
local i2 = (i1 == points_count) and 1 or i1 + 1
local p1 = points[i1]
local p2 = points[i2]
local dx = p2[1] - p1[1]
local dy = p2[2] - p1[2]
dx, dy = IM_NORMALIZE2F_OVER_ZERO(dx, dy)
dx = dx * (thickness * 0.5)
dy = dy * (thickness * 0.5)
local vtx_write_ptr = self._VtxWritePtr
vtx_data[vtx_write_ptr + 0][1][1] = p1[1] + dy; vtx_data[vtx_write_ptr + 0][1][2] = p1[2] - dx; ImVec2_Copy(vtx_data[vtx_write_ptr + 0][2], opaque_uv); vtx_data[vtx_write_ptr + 0][3] = col
vtx_data[vtx_write_ptr + 1][1][1] = p2[1] + dy; vtx_data[vtx_write_ptr + 1][1][2] = p2[2] - dx; ImVec2_Copy(vtx_data[vtx_write_ptr + 1][2], opaque_uv); vtx_data[vtx_write_ptr + 1][3] = col
vtx_data[vtx_write_ptr + 2][1][1] = p2[1] - dy; vtx_data[vtx_write_ptr + 2][1][2] = p2[2] + dx; ImVec2_Copy(vtx_data[vtx_write_ptr + 2][2], opaque_uv); vtx_data[vtx_write_ptr + 2][3] = col
vtx_data[vtx_write_ptr + 3][1][1] = p1[1] - dy; vtx_data[vtx_write_ptr + 3][1][2] = p1[2] + dx; ImVec2_Copy(vtx_data[vtx_write_ptr + 3][2], opaque_uv); vtx_data[vtx_write_ptr + 3][3] = col
self._VtxWritePtr = vtx_write_ptr + 4
local idx_write_ptr = self._IdxWritePtr
idx_data[idx_write_ptr + 0] = self._VtxCurrentIdx + 0; idx_data[idx_write_ptr + 1] = self._VtxCurrentIdx + 1; idx_data[idx_write_ptr + 2] = self._VtxCurrentIdx + 2
idx_data[idx_write_ptr + 3] = self._VtxCurrentIdx + 0; idx_data[idx_write_ptr + 4] = self._VtxCurrentIdx + 2; idx_data[idx_write_ptr + 5] = self._VtxCurrentIdx + 3
self._IdxWritePtr = idx_write_ptr + 6
self._VtxCurrentIdx = self._VtxCurrentIdx + 4
end
end
end
function MT.ImDrawList:PathRect(a, b, rounding, flags)
if not rounding then rounding = 0.0 end
if not flags then flags = 0 end
if rounding >= 0.5 then
IM_ASSERT(bit32.band(flags, 0x0F) == 0, "Misuse of legacy hardcoded ImDrawCornerFlags values!")
if bit32.band(flags, ImDrawFlags.RoundCornersMask_) == 0 then
flags = bit32.bor(flags, ImDrawFlags.RoundCornersAll)
end
rounding = ImMin(rounding, ImAbs(b.x - a.x) * (((bit32.band(flags, ImDrawFlags.RoundCornersTop) == ImDrawFlags.RoundCornersTop) or (bit32.band(flags, ImDrawFlags.RoundCornersBottom) == ImDrawFlags.RoundCornersBottom)) and 0.5 or 1.0) - 1.0)
rounding = ImMin(rounding, ImAbs(b.y - a.y) * (((bit32.band(flags, ImDrawFlags.RoundCornersLeft) == ImDrawFlags.RoundCornersLeft) or (bit32.band(flags, ImDrawFlags.RoundCornersRight) == ImDrawFlags.RoundCornersRight)) and 0.5 or 1.0) - 1.0)
end
if rounding < 0.5 or (bit32.band(flags, ImDrawFlags.RoundCornersMask_) == ImDrawFlags.RoundCornersNone) then
self:PathLineTo(a)
self:PathLineTo(ImVec2(b.x, a.y))
self:PathLineTo(b)
self:PathLineTo(ImVec2(a.x, b.y))
else
local rounding_tl = (bit32.band(flags, ImDrawFlags.RoundCornersTopLeft) ~= 0) and rounding or 0.0
local rounding_tr = (bit32.band(flags, ImDrawFlags.RoundCornersTopRight) ~= 0) and rounding or 0.0
local rounding_br = (bit32.band(flags, ImDrawFlags.RoundCornersBottomRight) ~= 0) and rounding or 0.0
local rounding_bl = (bit32.band(flags, ImDrawFlags.RoundCornersBottomLeft) ~= 0) and rounding or 0.0
self:PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9)
self:PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12)
self:PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3)
self:PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6)
end
end
function MT.ImDrawList:AddRectFilled(p_min, p_max, col, rounding, flags)
if not rounding then rounding = 0.0 end
if not flags then flags = 0 end
if bit32.band(col, IM_COL32_A_MASK) == 0 then return end
if rounding < 0.5 or (bit32.band(flags, ImDrawFlags.RoundCornersMask_) == ImDrawFlags.RoundCornersNone) then
self:PrimReserve(6, 4)
self:PrimRect(p_min, p_max, col)
else
self:PathRect(p_min, p_max, rounding, flags)
self:PathFillConvex(col)
end
end
--- @param p_min ImVec2
--- @param p_max ImVec2
--- @param col_upr_left ImU32
--- @param col_upr_right ImU32
--- @param col_bot_right ImU32
--- @param col_bot_left ImU32
function MT.ImDrawList:AddRectFilledMultiColor(p_min, p_max, col_upr_left, col_upr_right, col_bot_right, col_bot_left)
if bit32.band(bit32.bor(col_upr_left, col_upr_right, col_bot_right, col_bot_left), IM_COL32_A_MASK) == 0 then
return
end
local uv = self._Data.TexUvWhitePixel
self:PrimReserve(6, 4)
self:PrimWriteIdx(self._VtxCurrentIdx); self:PrimWriteIdx(self._VtxCurrentIdx + 1); self:PrimWriteIdx(self._VtxCurrentIdx + 2)
self:PrimWriteIdx(self._VtxCurrentIdx); self:PrimWriteIdx(self._VtxCurrentIdx + 2); self:PrimWriteIdx(self._VtxCurrentIdx + 3)
self:PrimWriteVtx(p_min, uv, col_upr_left)
self:PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv, col_upr_right)
self:PrimWriteVtx(p_max, uv, col_bot_right)
self:PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left)
end
--- @param p_min ImVec2
--- @param p_max ImVec2
--- @param col ImU32
--- @param rounding float
--- @param thickness? float
--- @param flags? ImDrawFlags
function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags)
if thickness == nil then thickness = 1.0 end
if flags == nil then flags = 0 end
IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?")
if bit32.band(col, IM_COL32_A_MASK) == 0 then
return
end
if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLines) ~= 0 then
self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.50, 0.50), rounding, flags)
else
self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.49, 0.49), rounding, flags)
end
self:PathStroke(col, thickness, ImDrawFlags.Closed)
end
function MT.ImDrawList:AddLine(p1, p2, col, thickness)
if bit32.band(col, IM_COL32_A_MASK) == 0 then return end
self:PathLineTo(p1 + ImVec2(0.5, 0.5))
self:PathLineTo(p2 + ImVec2(0.5, 0.5))
self:PathStroke(col, thickness)
end
--- @param min_x float
--- @param max_x float
--- @param y float
--- @param col ImU32
--- @param thickness? float
function MT.ImDrawList:AddLineH(min_x, max_x, y, col, thickness)
if thickness == nil then thickness = 1.0 end
if bit32.band(col, IM_COL32_A_MASK) == 0 then
return
end
self:PathLineTo(ImVec2(min_x + 0.5, y + 0.5))
self:PathLineTo(ImVec2(max_x + 0.5, y + 0.5))
self:PathStroke(col, thickness)
end
--- @param x float
--- @param min_y float
--- @param max_y float
--- @param col ImU32
--- @param thickness? float
function MT.ImDrawList:AddLineV(x, min_y, max_y, col, thickness)
if thickness == nil then thickness = 1.0 end
if bit32.band(col, IM_COL32_A_MASK) == 0 then
return
end
self:PathLineTo(ImVec2(x + 0.5, min_y + 0.5))
self:PathLineTo(ImVec2(x + 0.5, max_y + 0.5))
self:PathStroke(col, thickness)
end
function MT.ImDrawList:AddTriangle(p1, p2, p3, col, thickness)
if bit32.band(col, IM_COL32_A_MASK) == 0 then
return
end
self:PathLineTo(p1)
self:PathLineTo(p2)
self:PathLineTo(p3)
self:PathStroke(col, thickness, ImDrawFlags.Closed)
end
function MT.ImDrawList:AddTriangleFilled(p1, p2, p3, col)
if bit32.band(col, IM_COL32_A_MASK) == 0 then return end
self:PathLineTo(p1)
self:PathLineTo(p2)
self:PathLineTo(p3)
self:PathFillConvex(col)
end
--- @param center ImVec2
--- @param radius float
--- @param col ImU32
--- @param num_segments int
--- @param thickness float
function MT.ImDrawList:AddCircle(center, radius, col, num_segments, thickness)
if num_segments == nil then num_segments = 0 end
if thickness == nil then thickness = 1.0 end
if bit32.band(col, IM_COL32_A_MASK) == 0 or radius < 0.5 then
return
end
if num_segments <= 0 then
-- Use arc with automatic segment count
self:_PathArcToFastEx(center, radius - 0.5, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0)
self._Path.Size = self._Path.Size - 1
else
-- Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)
num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX)
-- Because we are filling a closed shape we remove 1 from the count of segments/points
local a_max = (IM_PI * 2.0) * (num_segments - 1) / num_segments
self:PathArcTo(center, radius - 0.5, 0.0, a_max, num_segments - 1)
end
self:PathStroke(col, thickness, ImDrawFlags.Closed)
end
--- @param center ImVec2
--- @param radius float
--- @param col ImU32
--- @param num_segments int
function MT.ImDrawList:AddCircleFilled(center, radius, col, num_segments)
if num_segments == nil then num_segments = 0 end
if bit32.band(col, IM_COL32_A_MASK) == 0 or radius < 0.5 then
return
end
if num_segments <= 0 then
-- Use arc with automatic segment count
self:_PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0)
self._Path.Size = self._Path.Size - 1
else
-- Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)
num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX)
-- Because we are filling a closed shape we remove 1 from the count of segments/points
local a_max = (IM_PI * 2.0) * (num_segments - 1) / num_segments
self:PathArcTo(center, radius, 0.0, a_max, num_segments - 1)
end
self:PathFillConvex(col)
end
--- @param font ImFont
--- @param font_size float
--- @param pos ImVec2
--- @param col ImU32
--- @param text string
--- @param text_begin? int # Defaults to 1
--- @param text_end int
--- @param wrap_width float
--- @param cpu_fine_clip_rect? ImVec4
function MT.ImDrawList:AddText(font, font_size, pos, col, text, text_begin, text_end, wrap_width, cpu_fine_clip_rect)
if text_begin == nil then text_begin = 1 end
if bit32.band(col, IM_COL32_A_MASK) == 0 then return end
if text_begin == text_end then
return
end
if font == nil then
font = self._Data.Font
end
if font_size == 0.0 then
font_size = self._Data.FontSize
end
local clip_rect = ImVec4() -- Don't modify the clip rect!
ImVec4_Copy(clip_rect, self._CmdHeader.ClipRect)
if (cpu_fine_clip_rect) then
clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect.x)
clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect.y)
clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect.z)
clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect.w)
end
font:RenderText(self, font_size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, (cpu_fine_clip_rect ~= nil) and ImDrawTextFlags.CpuFineClip or ImDrawTextFlags.None)
end
--- @param tex_ref ImTextureRef
--- @param p_min ImVec2
--- @param p_max ImVec2
--- @param uv_min? ImVec2
--- @param uv_max? ImVec2
--- @param col? ImU32
function MT.ImDrawList:AddImage(tex_ref, p_min, p_max, uv_min, uv_max, col)
if uv_min == nil then uv_min = ImVec2(0, 0) end
if uv_max == nil then uv_max = ImVec2(1, 1) end
if col == nil then col = IM_COL32_WHITE end
if bit32.band(col, IM_COL32_A_MASK) == 0 then
return
end
local push_texture_id = tex_ref ~= self._CmdHeader.TexRef
if push_texture_id then
self:PushTexture(tex_ref)
end
self:PrimReserve(6, 4)
self:PrimRectUV(p_min, p_max, uv_min, uv_max, col)
if push_texture_id then
self:PopTexture()
end
end
--- @param tex_ref ImTextureRef
--- @param p_min ImVec2
--- @param p_max ImVec2
--- @param uv_min ImVec2
--- @param uv_max ImVec2
--- @param col ImU32
--- @param rounding float
--- @param flags ImDrawFlags
function MT.ImDrawList:AddImageRounded(tex_ref, p_min, p_max, uv_min, uv_max, col, rounding, flags)
if bit32.band(col, IM_COL32_A_MASK) == 0 then
return
end
IM_ASSERT(bit32.band(flags, 0x0F) == 0, "Misuse of legacy hardcoded ImDrawCornerFlags values!")
if bit32.band(flags, ImDrawFlags.RoundCornersMask_) == 0 then
flags = bit32.bor(flags, ImDrawFlags.RoundCornersAll)
end
if rounding < 0.5 or bit32.band(flags, ImDrawFlags.RoundCornersMask_) == ImDrawFlags.RoundCornersNone then
self:AddImage(tex_ref, p_min, p_max, uv_min, uv_max, col)
return
end
local push_texture_id = (tex_ref ~= self._CmdHeader.TexRef)
if push_texture_id then
self:PushTexture(tex_ref)
end
local vert_start_idx = self.VtxBuffer.Size + 1
self:PathRect(p_min, p_max, rounding, flags)
self:PathFillConvex(col)
local vert_end_idx = self.VtxBuffer.Size + 1
ImGui.ShadeVertsLinearUV(self, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true)
if push_texture_id then
self:PopTexture()
end
end
--- @param radius float
function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius)
local radius_idx = ImFloor(radius + 0.999) + 1
if radius_idx >= 1 and radius_idx <= 64 then -- IM_COUNTOF(_Data->CircleSegmentCounts)
return self._Data.CircleSegmentCounts[radius_idx]
else
return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self._Data.CircleTessellationMaxError)
end
end
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)
if intersect_with_current_clip_rect then
local current = self._CmdHeader.ClipRect
if cr.x < current.x then cr.x = current.x end
if cr.y < current.y then cr.y = current.y end
if cr.z > current.z then cr.z = current.z end
if cr.w > current.w then cr.w = current.w end
end
cr.z = ImMax(cr.x, cr.z)
cr.w = ImMax(cr.y, cr.w)
self._ClipRectStack:push_back(cr)
ImVec4_Copy(self._CmdHeader.ClipRect, cr)
self:_OnChangedClipRect()
end
function MT.ImDrawList:PopClipRect()
self._ClipRectStack:pop_back()
if (self._ClipRectStack.Size == 0) then -- LUA: No "Ternary Operator"
ImVec4_Copy(self._CmdHeader.ClipRect, self._Data.ClipRectFullscreen)
else
ImVec4_Copy(self._CmdHeader.ClipRect, self._ClipRectStack.Data[self._ClipRectStack.Size])
end
self:_OnChangedClipRect()
end
--- @param center ImVec2
--- @param radius float
--- @param a_min_sample int
--- @param a_max_sample int
--- @param a_step int
function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_sample, a_step)
if radius < 0.5 then
self._Path:push_back(center)
return
end
if a_step <= 0 then
a_step = math.floor(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / self:_CalcCircleAutoSegmentCount(radius))
end
a_step = ImClamp(a_step, 1, math.floor(IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4))
local sample_range = ImAbs(a_max_sample - a_min_sample)
local a_next_step = a_step
local samples = sample_range + 1
local extra_max_sample = false
if a_step > 1 then
samples = math.floor(sample_range / a_step) + 1
local overstep = sample_range % a_step
if overstep > 0 then
extra_max_sample = true
samples = samples + 1
if sample_range > 0 then
a_step = a_step - math.floor((a_step - overstep) / 2)
end
end
end
self._Path:resize(self._Path.Size + samples)
local out_ptr = self._Path.Size - samples + 1
local sample_index = a_min_sample
if sample_index < 0 or sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX then
sample_index = sample_index % IM_DRAWLIST_ARCFAST_SAMPLE_MAX
if sample_index < 0 then
sample_index = sample_index + IM_DRAWLIST_ARCFAST_SAMPLE_MAX
end
end
if a_max_sample >= a_min_sample then
local a = a_min_sample
while a <= a_max_sample do
if sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX then
sample_index = sample_index - IM_DRAWLIST_ARCFAST_SAMPLE_MAX
end
local s = self._Data.ArcFastVtx[sample_index + 1]
ImVec2_CopyV(self._Path.Data[out_ptr], center.x + s.x * radius, center.y + s.y * radius)
out_ptr = out_ptr + 1
a = a + a_step
sample_index = sample_index + a_step
a_step = a_next_step
end
else
local a = a_min_sample
while a >= a_max_sample do
if sample_index < 0 then
sample_index = sample_index + IM_DRAWLIST_ARCFAST_SAMPLE_MAX
end
local s = self._Data.ArcFastVtx[sample_index + 1]
ImVec2_CopyV(self._Path.Data[out_ptr], center.x + s.x * radius, center.y + s.y * radius)
out_ptr = out_ptr + 1
a = a - a_step
sample_index = sample_index - a_step
a_step = a_next_step
end
end
if extra_max_sample then
local normalized_max_sample = a_max_sample % IM_DRAWLIST_ARCFAST_SAMPLE_MAX
if normalized_max_sample < 0 then
normalized_max_sample = normalized_max_sample + IM_DRAWLIST_ARCFAST_SAMPLE_MAX
end
local s = self._Data.ArcFastVtx[normalized_max_sample + 1]
ImVec2_CopyV(self._Path.Data[out_ptr], center.x + s.x * radius, center.y + s.y * radius)
out_ptr = out_ptr + 1
end
IM_ASSERT_PARANOID(self._Path.Size == out_ptr - 1)
end
function MT.ImDrawList:PathArcToFast(center, radius, a_min_of_12, a_max_of_12)
if radius < 0.5 then
self._Path:push_back(center)
return
end
self:_PathArcToFastEx(center, radius, a_min_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, a_max_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, 0)
end
--- @param center ImVec2
--- @param radius float
--- @param a_min float
--- @param a_max float
--- @param num_segments int
function MT.ImDrawList:_PathArcToN(center, radius, a_min, a_max, num_segments)
if radius < 0.5 then
self._Path:push_back(center)
return
end
-- Note that we are adding a point at both a_min and a_max.
-- If you are trying to draw a full closed circle you don't want the overlapping points!
self._Path:reserve(self._Path.Size + (num_segments + 1))
for i = 0, num_segments do
local a = a_min + (i / num_segments) * (a_max - a_min)
self._Path:push_back(ImVec2(center.x + ImCos(a) * radius, center.y + ImSin(a) * radius))
end
end
--- @param center ImVec2
--- @param radius float
--- @param a_min float
--- @param a_max float
--- @param num_segments? int
function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments)
if num_segments == nil then num_segments = 0 end
if radius < 0.5 then
self._Path:push_back(center)
return
end
if num_segments > 0 then
self:_PathArcToN(center, radius, a_min, a_max, num_segments)
return
end
if radius <= self._Data.ArcFastRadiusCutoff then
local a_is_reverse = a_max < a_min
local a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0)
local a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0)
local a_min_sample = a_is_reverse and ImFloor(a_min_sample_f) or ImCeil(a_min_sample_f)
local a_max_sample = a_is_reverse and ImCeil(a_max_sample_f) or ImFloor(a_max_sample_f)
local a_mid_samples = a_is_reverse and ImMax(a_min_sample - a_max_sample, 0) or ImMax(a_max_sample - a_min_sample, 0)
local a_min_segment_angle = a_min_sample * IM_PI * 2.0 / IM_DRAWLIST_ARCFAST_SAMPLE_MAX
local a_max_segment_angle = a_max_sample * IM_PI * 2.0 / IM_DRAWLIST_ARCFAST_SAMPLE_MAX
local a_emit_start = ImAbs(a_min_segment_angle - a_min) >= 1e-5
local a_emit_end = ImAbs(a_max - a_max_segment_angle) >= 1e-5
self._Path:reserve(self._Path.Size + (a_mid_samples + 1 + (a_emit_start and 1 or 0) + (a_emit_end and 1 or 0)))
if a_emit_start then self._Path:push_back(ImVec2(center.x + ImCos(a_min) * radius, center.y + ImSin(a_min) * radius)) end
if a_mid_samples > 0 then self:_PathArcToFastEx(center, radius, a_min_sample, a_max_sample, 0) end
if a_emit_end then self._Path:push_back(ImVec2(center.x + ImCos(a_max) * radius, center.y + ImSin(a_max) * radius)) end
else
local arc_length = ImAbs(a_max - a_min)
local circle_segment_count = self:_CalcCircleAutoSegmentCount(radius)
local arc_segment_count = ImMax(ImCeil(circle_segment_count * arc_length / (IM_PI * 2.0)), 1)
self:_PathArcToN(center, radius, a_min, a_max, arc_segment_count)
end
end
-- Not recommended to call this directly!
--- @param draw_list ImDrawList
--- @param size float
--- @param pos ImVec2
--- @param col ImU32
--- @param clip_rect ImVec4
--- @param text ImString
--- @param text_begin int
--- @param text_end int
--- @param wrap_width? float
--- @param flags? ImDrawTextFlags
function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags)
if wrap_width == nil then wrap_width = .0 end
if flags == nil then flags = 0 end
local x = pos.x
local y = pos.y
if y > clip_rect.w then
return
end
if bit32.band(draw_list.Flags, ImDrawListFlags.TextNoPixelSnap) == 0 then
x = IM_TRUNC(x)
y = IM_TRUNC(y)
end
-- if not text_end then
-- end
local line_height = size
local baked = self:GetFontBaked(size)
local scale = size / baked.Size
local origin_x = x
local word_wrap_enabled = (wrap_width > 0.0)
local s = text_begin
if y + line_height < clip_rect.y then
while y + line_height < clip_rect.y and s < text_end do
local line_end = ImMemchr(text, '\n', s)
if word_wrap_enabled then
s = ImFontCalcWordWrapPositionEx(self, size, text, s, (line_end ~= nil) and line_end or text_end, wrap_width, flags)
s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags)
else
s = (line_end ~= nil) and (line_end + 1) or text_end
end
y = y + line_height
end
end
if text_end - s > 1e4 and not word_wrap_enabled then
local s_end = s
local y_end = y
while (y_end < clip_rect.w and s_end < text_end) do
local _end = ImMemchr(text, '\n', s_end)
s_end = (_end ~= nil) and (_end + 1) or text_end
y_end = y_end + line_height
end
text_end = s_end
end
if s == text_end then
return
end
local vtx_count_max = (text_end - s) * 4
local idx_count_max = (text_end - s) * 6
local idx_expected_size = draw_list.IdxBuffer.Size + idx_count_max
draw_list:PrimReserve(idx_count_max, vtx_count_max)
local vtx_write = draw_list._VtxWritePtr
local idx_write = draw_list._IdxWritePtr
local vtx_index = draw_list._VtxCurrentIdx
local cmd_count = draw_list.CmdBuffer.Size
local cpu_fine_clip = bit32.band(flags, ImDrawTextFlags.CpuFineClip) ~= 0
local idx_data = draw_list.IdxBuffer.Data; local vtx_data = draw_list.VtxBuffer.Data
local color_untinted = bit32.bor(col, bit32.bnot(IM_COL32_A_MASK))
local word_wrap_eol
local stop = false
while s < text_end do
repeat
if word_wrap_enabled then
if not word_wrap_eol then
word_wrap_eol = ImFontCalcWordWrapPositionEx(self, size, text, s, text_end, wrap_width - (x - origin_x), flags)
end
if s >= word_wrap_eol then
x = origin_x
y = y + line_height
if y > clip_rect.w then
stop = true; break
end
word_wrap_eol = nil
s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags)
break
end
end
local c = ImStrByte(text, s)
if c < 0x80 then
s = s + 1
else
local wanted, out_char = ImStd.ImTextCharFromUtf8(text, s, text_end)
c = out_char
s = s + wanted
end
if c < 32 then
if c == 10 then -- '\n'
x = origin_x
y = y + line_height
if y > clip_rect.w then
stop = true; break
end
break
end
if c == 13 then -- '\r'
break
end
end
local glyph = baked:FindGlyph(c)
local char_width = glyph.AdvanceX * scale
if glyph.Visible then
local x1 = x + glyph.X0 * scale
local x2 = x + glyph.X1 * scale
local y1 = y + glyph.Y0 * scale
local y2 = y + glyph.Y1 * scale
if x1 <= clip_rect.z and x2 >= clip_rect.x then
local u1 = glyph.U0
local v1 = glyph.V0
local u2 = glyph.U1
local v2 = glyph.V1
if (cpu_fine_clip) then
if (x1 < clip_rect.x) then
u1 = u1 + (1.0 - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1)
x1 = clip_rect.x
end
if (y1 < clip_rect.y) then
v1 = v1 + (1.0 - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1)
y1 = clip_rect.y
end
if (x2 > clip_rect.z) then
u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1)
x2 = clip_rect.z
end
if (y2 > clip_rect.w) then
v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1)
y2 = clip_rect.w
end
if (y1 >= y2) then
x = x + char_width
break
end
end
local glyph_col = glyph.Colored and color_untinted or col
do
local vtx0 = vtx_data[vtx_write + 0]; vtx0[1][1] = x1; vtx0[1][2] = y1; vtx0[3] = glyph_col; vtx0[2][1] = u1; vtx0[2][2] = v1;
local vtx1 = vtx_data[vtx_write + 1]; vtx1[1][1] = x2; vtx1[1][2] = y1; vtx1[3] = glyph_col; vtx1[2][1] = u2; vtx1[2][2] = v1;
local vtx2 = vtx_data[vtx_write + 2]; vtx2[1][1] = x2; vtx2[1][2] = y2; vtx2[3] = glyph_col; vtx2[2][1] = u2; vtx2[2][2] = v2;
local vtx3 = vtx_data[vtx_write + 3]; vtx3[1][1] = x1; vtx3[1][2] = y2; vtx3[3] = glyph_col; vtx3[2][1] = u1; vtx3[2][2] = v2;
idx_data[idx_write + 0] = vtx_index; idx_data[idx_write + 1] = vtx_index + 1; idx_data[idx_write + 2] = vtx_index + 2;
idx_data[idx_write + 3] = vtx_index; idx_data[idx_write + 4] = vtx_index + 2; idx_data[idx_write + 5] = vtx_index + 3;
vtx_write = vtx_write + 4
vtx_index = vtx_index + 4
idx_write = idx_write + 6
end
end
end
x = x + char_width
until true
if stop then break end
end
-- Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui.* calls because CalcTextSize() is always used
if cmd_count ~= draw_list.CmdBuffer.Size then
IM_ASSERT(draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount == 0)
draw_list.CmdBuffer:pop_back()
draw_list:PrimUnreserve(idx_count_max, vtx_count_max)
draw_list:AddDrawCmd()
return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- was `goto begin`
end
draw_list.VtxBuffer.Size = vtx_write - 1
draw_list.IdxBuffer.Size = idx_write - 1
draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount = draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount - (idx_expected_size - draw_list.IdxBuffer.Size)
draw_list._VtxWritePtr = vtx_write
draw_list._IdxWritePtr = idx_write
draw_list._VtxCurrentIdx = vtx_index
end
--- @param draw_list ImDrawList
--- @param pos ImVec2
--- @param color ImU32
--- @param dir ImGuiDir
--- @param scale? float
function ImGui.RenderArrow(draw_list, pos, color, dir, scale)
if scale == nil then scale = 1.0 end
local h = draw_list._Data.FontSize * 1.00
local r = h * 0.40 * scale
local center = pos + ImVec2(h * 0.50, h * 0.50 * scale)
local a, b, c
if dir == ImGuiDir.Up or dir == ImGuiDir.Down then
if dir == ImGuiDir.Up then r = -r end
a = ImVec2( 0.000, 0.750) * r
b = ImVec2(-0.866, -0.750) * r
c = ImVec2( 0.866, -0.750) * r
elseif dir == ImGuiDir.Left or dir == ImGuiDir.Right then
if dir == ImGuiDir.Left then r = -r end
a = ImVec2( 0.750, 0.000) * r
b = ImVec2(-0.750, 0.866) * r
c = ImVec2(-0.750, -0.866) * r
elseif dir == ImGuiDir.None or dir == ImGuiDir.COUNT then
IM_ASSERT(false)
end
draw_list:AddTriangleFilled(center + a, center + b, center + c, color)
end
--- @param draw_list ImDrawList
--- @param pos ImVec2
--- @param col ImU32
function ImGui.RenderBullet(draw_list, pos, col)
-- FIXME-OPT: This should be baked in font now that it's easier
local font_size = draw_list._Data.FontSize
draw_list:AddCircleFilled(pos, font_size * 0.20, col, (font_size < 22) and 8 or ((font_size < 40) and 12 or 0)) -- Hardcode optimal/nice tessellation threshold
end
--- @param draw_list ImDrawList
--- @param pos ImVec2
--- @param col ImU32
--- @param sz float
function ImGui.RenderCheckMark(draw_list, pos, col, sz)
local thickness = ImMax(sz / 5.0, 1.0)
sz = sz - thickness * 0.5
pos = pos + ImVec2(thickness * 0.25, thickness * 0.25)
local third = sz / 3.0
local bx = pos.x + third
local by = pos.y + sz - third * 0.5
draw_list:PathLineTo(ImVec2(bx - third, by - third))
draw_list:PathLineTo(ImVec2(bx, by))
draw_list:PathLineTo(ImVec2(bx + third * 2.0, by - third * 2.0))
draw_list:PathStroke(col, thickness)
end
-- Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side
--- @param draw_list ImDrawList
--- @param pos ImVec2
--- @param half_sz ImVec2
--- @param direction ImGuiDir
--- @param col ImU32
function ImGui.RenderArrowPointingAt(draw_list, pos, half_sz, direction, col)
if direction == ImGuiDir.Left then
draw_list:AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col)
elseif direction == ImGuiDir.Right then
draw_list:AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col)
elseif direction == ImGuiDir.Up then
draw_list:AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col)
elseif direction == ImGuiDir.Down then
draw_list:AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col)
elseif direction == ImGuiDir.None or direction == ImGuiDir.COUNT then
end
end
local function ImAcos01(x)
if x <= 0.0 then return IM_PI * 0.5 end
if x >= 1.0 then return 0.0 end
return ImAcos(x)
end
-- FIXME: Cleanup and move code to ImDrawList
--- @param draw_list ImDrawList
--- @param rect ImRect
--- @param col ImU32
--- @param fill_x0 float
--- @param fill_x1 float
--- @param rounding float
function ImGui.RenderRectFilledInRangeH(draw_list, rect, col, fill_x0, fill_x1, rounding)
if fill_x0 > fill_x1 then
return
end
local p0 = ImVec2(fill_x0, rect.Min.y)
local p1 = ImVec2(fill_x1, rect.Max.y)
if rounding == 0.0 then
draw_list:AddRectFilled(p0, p1, col, 0.0)
return
end
rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5, (rect.Max.y - rect.Min.y) * 0.5) - 1.0, 0.0, rounding)
local inv_rounding = 1.0 / rounding
local arc0_b = ImAcos01(1.0 - (p0.x - rect.Min.x) * inv_rounding)
local arc0_e = ImAcos01(1.0 - (p1.x - rect.Min.x) * inv_rounding)
local half_pi = IM_PI * 0.5 -- We will == compare to this because we know this is the exact value ImAcos01 can return.
local x0 = ImMax(p0.x, rect.Min.x + rounding)
if arc0_b == arc0_e then
draw_list:PathLineTo(ImVec2(x0, p1.y))
draw_list:PathLineTo(ImVec2(x0, p0.y))
elseif arc0_b == 0.0 and arc0_e == half_pi then
draw_list:PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6) -- BL
draw_list:PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9) -- TR
else
draw_list:PathArcTo(ImVec2(x0, p1.y - rounding), rounding, math.pi - arc0_e, math.pi - arc0_b) -- BL
draw_list:PathArcTo(ImVec2(x0, p0.y + rounding), rounding, math.pi + arc0_b, math.pi + arc0_e) -- TR
end
if p1.x > rect.Min.x + rounding then
local arc1_b = ImAcos01(1.0 - (rect.Max.x - p1.x) * inv_rounding)
local arc1_e = ImAcos01(1.0 - (rect.Max.x - p0.x) * inv_rounding)
local x1 = ImMin(p1.x, rect.Max.x - rounding)
if arc1_b == arc1_e then
draw_list:PathLineTo(ImVec2(x1, p0.y))
draw_list:PathLineTo(ImVec2(x1, p1.y))
elseif arc1_b == 0.0 and arc1_e == half_pi then
draw_list:PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12) -- TR
draw_list:PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3) -- BR
else
draw_list:PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b) -- TR
draw_list:PathArcTo(ImVec2(x1, p1.y - rounding), rounding, arc1_b, arc1_e) -- BR
end
end
draw_list:PathFillConvex(col)
end
--- @param r_in ImRect
--- @param r_outer ImRect
--- @param threshold float
--- @return ImDrawFlags
function ImGui.CalcRoundingFlagsForRectInRect(r_in, r_outer, threshold)
local round_l = r_in.Min.x <= r_outer.Min.x + threshold
local round_r = r_in.Max.x >= r_outer.Max.x - threshold
local round_t = r_in.Min.y <= r_outer.Min.y + threshold
local round_b = r_in.Max.y >= r_outer.Max.y - threshold
local flags = ImDrawFlags.RoundCornersNone
if round_t and round_l then
flags = bit32.bor(flags, ImDrawFlags.RoundCornersTopLeft)
end
if round_t and round_r then
flags = bit32.bor(flags, ImDrawFlags.RoundCornersTopRight)
end
if round_b and round_l then
flags = bit32.bor(flags, ImDrawFlags.RoundCornersBottomLeft)
end
if round_b and round_r then
flags = bit32.bor(flags, ImDrawFlags.RoundCornersBottomRight)
end
return flags
end
-- Helper for ColorPicker4()
-- NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
-- Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether.
-- FIXME: uses ImGui.GetColorU32
--- @param draw_list ImDrawList
--- @param p_min ImVec2
--- @param p_max ImVec2
--- @param col ImU32
--- @param grid_step float
--- @param grid_off ImVec2
--- @param rounding? float
--- @param flags? ImDrawFlags
function ImGui.RenderColorRectWithAlphaCheckerboard(draw_list, p_min, p_max, col, grid_step, grid_off, rounding, flags)
if rounding == nil then rounding = 0.0 end
if flags == nil then flags = 0 end
if bit32.band(flags, ImDrawFlags.RoundCornersMask_) == 0 then
flags = ImDrawFlags.RoundCornersDefault_
end
if bit32.rshift(bit32.band(col, IM_COL32_A_MASK), IM_COL32_A_SHIFT) < 0xFF then
local col_bg1 = ImGui.GetColorU32(ImStd.ImAlphaBlendColors(IM_COL32(128, 128, 128, 255), col), nil, true)
local col_bg2 = ImGui.GetColorU32(ImStd.ImAlphaBlendColors(IM_COL32(204, 204, 204, 255), col), nil, true)
draw_list:AddRectFilled(p_min, p_max, col_bg1, rounding, flags)
local yi = 0
local y = p_min.y + grid_off.y
local x_start
local x
local cell_flags
while y < p_max.y do
repeat
local y1 = ImClamp(y, p_min.y, p_max.y)
local y2 = ImMin(y + grid_step, p_max.y)
if y2 <= y1 then
break
end
x_start = p_min.x + grid_off.x + ((yi + 1) % 2) * grid_step
x = x_start
while x < p_max.x do
repeat
local x1 = ImClamp(x, p_min.x, p_max.x)
local x2 = ImMin(x + grid_step, p_max.x)
if x2 <= x1 then
break
end
cell_flags = ImDrawFlags.RoundCornersNone
if y1 <= p_min.y then
if x1 <= p_min.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersTopLeft) end
if x2 >= p_max.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersTopRight) end
end
if y2 >= p_max.y then
if x1 <= p_min.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersBottomLeft) end
if x2 >= p_max.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersBottomRight) end
end
-- Combine flags
if flags == ImDrawFlags.RoundCornersNone or cell_flags == ImDrawFlags.RoundCornersNone then
cell_flags = ImDrawFlags.RoundCornersNone
else
cell_flags = bit32.band(cell_flags, flags)
end
draw_list:AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg2, rounding, cell_flags)
until true
x = x + grid_step * 2.0
end
until true
y = y + grid_step
yi = yi + 1
end
else
draw_list:AddRectFilled(p_min, p_max, col, rounding, flags)
end
end
return true -- [Roblox] ModuleScripts must return exactly one value
end
__FILES['imgui_h.lua'] = function()
--- ImGui Sincerely WIP
-- (Definitions)
--- @meta
local type = ImGui._GetTypeFunc()
local rawget = rawget; local rawset = rawset
-- [LuaBitOp](https://bitop.luajit.org/semantics.html)
local bitAnd = bit32.band; local bitOr = bit32.bor
local bitLShift = bit32.lshift
--- @class char : integer
--- @class unsigned_char : integer
--- @alias ImS8 char
--- @alias ImU8 unsigned_char
--- @class ImU16 : integer
--- @class ImS16 : integer
--- @class ImU32 : integer
--- @class ImS32 : integer
--- @param val number
--- @return ImU8
function ImU8(val) return bitAnd(val, 0xFF) end
--- @param val number
--- @return ImS8
function ImS8(val) return bitAnd(val, 0xFF) - (bitAnd(val, 0x80) ~= 0 and 0x100 or 0) end
--- @param val number
--- @return ImU16
function ImU16(val) return bitAnd(val, 0xFFFF) end
--- @param val number
--- @return ImS16
function ImS16(val) return bitAnd(val, 0xFFFF) - (bitAnd(val, 0x8000) ~= 0 and 0x10000 or 0) end
--- @param val number
--- @return ImU32
function ImU32(val) return bitAnd(val, 0xFFFFFFFF) end
--- @param val number
--- @return ImS32
function ImS32(val) return bitAnd(val, 0xFFFFFFFF) end
--- @alias float number
--- @class double : number
--- @alias int integer
--- @alias unsigned_int integer
--- @alias short integer
--- @alias unsigned_short integer
--- @alias size_t unsigned_int
--- @alias ImWchar16 unsigned_short
--- @alias ImWchar ImWchar16
--- @alias bool boolean
--- @alias ImGuiID unsigned_int
--- @alias ImTextureID integer
--- @alias ImGuiKeyChord int
--- @alias ImDrawIdx unsigned_int
IM_UNICODE_CODEPOINT_INVALID = 0xFFFD
IM_UNICODE_CODEPOINT_MAX = 0xFFFF
IM_ALLOC = ImGui.MemAlloc
IM_FREE = ImGui.MemFree
--- @param owner table
--- @param field string|int
IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end
---------------------------------------------------------------------------------------
-- [SECTION] METATABLE MANAGEMENT
---------------------------------------------------------------------------------------
--- File-scope metatable storage
local MT = {}
function ImGui.GetMetatables() return MT end
--- @param _EXPR any
--- @param _MSG string?
function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end
IM_ASSERT_PARANOID = IM_ASSERT
--- Note that `S64` and `U64` are not supported
--- @enum ImGuiDataType
ImGuiDataType =
{
S8 = 0, -- signed char / char
U8 = 1, -- unsigned char
S16 = 2, -- short
U16 = 3, -- unsigned short
S32 = 4, -- int
U32 = 5, -- unsigned int
Float = 6, -- float
Double = 7, -- double
Bool = 8, -- bool (provided for user convenience, not supported by scalar widgets)
String = 9, -- string (provided for user convenience, not supported by scalar widgets)
COUNT = 10
}
ImTextureID_Invalid = -1
--- @enum ImTextureFormat
ImTextureFormat =
{
RGBA32 = 0,
Alpha8 = 1,
}
--- @enum ImTextureStatus
ImTextureStatus =
{
OK = 0,
Destroyed = 1,
WantCreate = 2,
WantUpdates = 3,
WantDestroy = 4,
}
--- @enum ImFontAtlasFlags
ImFontAtlasFlags =
{
None = 0,
NoPowerOfTwoHeight = bitLShift(1, 0),
NoMouseCursors = bitLShift(1, 1),
NoBakedLines = bitLShift(1, 2)
}
--- @enum ImGuiDir
ImGuiDir =
{
None = -1,
Left = 0,
Right = 1,
Up = 2,
Down = 3,
COUNT = 4
}
--- @enum ImGuiMouseButton
ImGuiMouseButton =
{
Left = 0,
Right = 1,
Middle = 2,
COUNT = 5
}
--- @enum ImGuiMouseCursor
ImGuiMouseCursor =
{
None = -1,
Arrow = 0,
TextInput = 1,
ResizeAll = 2,
ResizeNS = 3,
ResizeEW = 4,
ResizeNESW = 5,
ResizeNWSE = 6,
Hand = 7,
Wait = 8,
Progress = 9,
NotAllowed = 10,
COUNT = 11
}
--- @class ImTextureRect
--- @field x unsigned_short
--- @field y unsigned_short
--- @field w unsigned_short
--- @field h unsigned_short
--- @param x? unsigned_short
--- @param y? unsigned_short
--- @param w? unsigned_short
--- @param h? unsigned_short
--- @return ImTextureRect
function ImTextureRect(x, y, w, h) return { x = x, y = y, w = w, h = h } end
-- This structure supports indexing on string keys `x`, `y` and number keys 1, 2.
-- But note that the former is likely to be more expensive.
--- @class ImVec2
--- @operator add(ImVec2): ImVec2
--- @operator sub(ImVec2): ImVec2
--- @operator mul(number): ImVec2
--- @operator mul(ImVec2): ImVec2
--- @operator div(number): ImVec2
--- @operator div(ImVec2): ImVec2
--- @field [1] number
--- @field [2] number
--- @field x number
--- @field y number
local IM_VEC2 = {}
--- @param t ImVec2
--- @param k string
IM_VEC2.__index = function(t, k)
if k == "x" then return rawget(t, 1)
elseif k == "y" then return rawget(t, 2)
end
end
--- @param t ImVec2
--- @param k string
--- @param v number
IM_VEC2.__newindex = function(t, k, v)
if k == "x" then rawset(t, 1, v)
elseif k == "y" then rawset(t, 2, v)
else IM_ASSERT(false)
end
end
--- @param x? number
--- @param y? number
--- @return ImVec2
--- @nodiscard
function ImVec2(x, y) return setmetatable({x or 0, y or 0}, IM_VEC2) end
function IM_VEC2.__add(lhs, rhs) return ImVec2(lhs[1] + rhs[1], lhs[2] + rhs[2]) end
function IM_VEC2.__sub(lhs, rhs) return ImVec2(lhs[1] - rhs[1], lhs[2] - rhs[2]) end
--- @overload fun(lhs: ImVec2, rhs: number): ImVec2
--- @overload fun(lhs: ImVec2, rhs: ImVec2): ImVec2
function IM_VEC2.__mul(lhs, rhs)
if type(lhs) == "table" and type(rhs) == "number" then return ImVec2(lhs[1] * rhs, lhs[2] * rhs)
elseif type(lhs) == "table" and type(rhs) == "table" then return ImVec2(lhs[1] * rhs[1], lhs[2] * rhs[2])
end
end
--- @overload fun(lhs: ImVec2, rhs: number): ImVec2
--- @overload fun(lhs: ImVec2, rhs: ImVec2): ImVec2
function IM_VEC2.__div(lhs, rhs)
if type(lhs) == "table" and type(rhs) == "number" then return ImVec2(lhs[1] / rhs, lhs[2] / rhs)
elseif type(lhs) == "table" and type(rhs) == "table" then return ImVec2(lhs[1] / rhs[1], lhs[2] / rhs[2])
end
end
function IM_VEC2.__eq(lhs, rhs) return lhs[1] == rhs[1] and lhs[2] == rhs[2] end
function IM_VEC2:__tostring() return string.format("ImVec2(%g, %g)", self.x, self.y) end
--- @param dest ImVec2
--- @param src ImVec2
function ImVec2_Copy(dest, src) dest[1] = src[1]; dest[2] = src[2] end
--- @param dest ImVec2
--- @param src_x number
--- @param src_y number
function ImVec2_CopyV(dest, src_x, src_y) dest[1] = src_x; dest[2] = src_y end
--- @param v ImVec2
--- @param add_x number
--- @param add_y number
function ImVec2_AddVA(v, add_x, add_y) return v[1] + add_x, v[2] + add_y end
--- @param v ImVec2
--- @param sub_x number
--- @param sub_y number
function ImVec2_SubVA(v, sub_x, sub_y) return v[1] - sub_x, v[2] - sub_y end
--- @param a ImVec2
--- @param scalar number
function ImVec2_MulVX(a, scalar)
return a[1] * scalar, a[2] * scalar
end
--- An inlined version of `ImVec2_Copy` currently for use in certain ImVector<ImVec2> `push_back`
--- @param t ImVec2[]
--- @param k int
--- @param v ImVec2
local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest[1] = v[1]; dest[2] = v[2]; end
-- This structure supports indexing on string keys `x`, `y`, `z`, `w` and number keys 1, 2, 3, 4.
-- But note that the former is likely to be more expensive.
--- @class ImVec4
--- @operator add(ImVec4): ImVec4
--- @operator sub(ImVec4): ImVec4
--- @operator mul(number): ImVec4
--- @field [1] number
--- @field [2] number
--- @field [3] number
--- @field [4] number
--- @field x number
--- @field y number
--- @field z number
--- @field w number
local IM_VEC4 = {}
--- @param t ImVec4
--- @param k string
IM_VEC4.__index = function(t, k)
if k == "x" then return rawget(t, 1)
elseif k == "y" then return rawget(t, 2)
elseif k == "z" then return rawget(t, 3)
elseif k == "w" then return rawget(t, 4)
end
end
--- @param t ImVec4
--- @param k string
--- @param v number
IM_VEC4.__newindex = function(t, k, v)
if k == "x" then rawset(t, 1, v)
elseif k == "y" then rawset(t, 2, v)
elseif k == "z" then rawset(t, 3, v)
elseif k == "w" then rawset(t, 4, v)
else IM_ASSERT(false)
end
end
--- @param x? number
--- @param y? number
--- @param z? number
--- @param w? number
--- @return ImVec4
--- @nodiscard
function ImVec4(x, y, z, w) return setmetatable({x or 0, y or 0, z or 0, w or 0}, IM_VEC4) end
function IM_VEC4.__add(lhs, rhs) return ImVec4(lhs[1] + rhs[1], lhs[2] + rhs[2], lhs[3] + rhs[3], lhs[4] + rhs[4]) end
function IM_VEC4.__sub(lhs, rhs) return ImVec4(lhs[1] - rhs[1], lhs[2] - rhs[2], lhs[3] - rhs[3], lhs[4] - rhs[4]) end
function IM_VEC4.__mul(lhs, rhs) return ImVec4(lhs[1] * rhs, lhs[2] * rhs, lhs[3] * rhs, lhs[4] * rhs) end
function IM_VEC4.__eq(lhs, rhs) return lhs[1] == rhs[1] and lhs[2] == rhs[2] and lhs[3] == rhs[3] and lhs[4] == rhs[4] end
function IM_VEC4:__tostring() return string.format("ImVec4(%g, %g, %g, %g)", self.x, self.y, self.z, self.w) end
--- @param dest ImVec4
--- @param src ImVec4
function ImVec4_Copy(dest, src) dest[1] = src[1]; dest[2] = src[2]; dest[3] = src[3]; dest[4] = src[4] end
--- A compact ImVector clone
--- @class ImVector<T>
--- @field Data T[] # 1-based table
--- @field Size int # >= 0
--- @field _Constructor function
--- @field _CopyFunc function
local IM_VECTOR = {}
-- Support 1-based number key indexing while keep method accessing speed
--- @param t ImVector
--- @param k string|int
--- @return any
IM_VECTOR.__index = function(t, k)
if k == "Data" then return nil end -- Data has already been discarded
return IM_VECTOR[k] or t.Data[IM_ASSERT(k >= 1 and k <= t.Size) or k] -- if the mt access turns out nil, the k must be int index into Data
end
--- @param t ImVector
--- @param k int
--- @param v any
IM_VECTOR.__newindex = function(t, k, v)
if k == "Data" then rawset(t, "Data", v); return; end -- set new Data. old Data is already discarded
IM_ASSERT(k >= 1 and k <= t.Size)
t.Data[k] = v
end
local _default_constructor = function() return nil end
local _default_copyfunc = function(t, k, v) t[k] = v end
local function _grow_capacity(v, sz) local new_capacity = (v.Capacity ~= 0) and math.floor(v.Capacity + v.Capacity / 2) or 8; return (new_capacity > sz) and new_capacity or sz; end
--- @param T? function
--- @param COPY_FUNC? function
--- @return ImVector
--- @nodiscard
function ImVector(T, COPY_FUNC) return setmetatable({Data = nil, Size = 0, Capacity = 0, _Constructor = T or _default_constructor, _CopyFunc = COPY_FUNC or _default_copyfunc}, IM_VECTOR) end
function IM_VECTOR:push_back(value) if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; self._CopyFunc(self.Data, self.Size + 1, value); self.Size = self.Size + 1; return value end
function IM_VECTOR:pop_back() IM_ASSERT(self.Size > 0); self.Size = self.Size - 1; end
function IM_VECTOR:push_front(value) if self.Size == 0 then self:push_back(value) else self:insert(1, value) end end
function IM_VECTOR:clear() if self.Data then self.Size = 0; self.Capacity = 0; IM_FREE(self, "Data"); self.Data = nil end end
function IM_VECTOR:clear_delete() for i = 1, self.Size do self.Data[i] = nil end self.Size = 0 end
function IM_VECTOR:empty() return self.Size == 0 end
function IM_VECTOR:back() IM_ASSERT(self.Size > 0) return self.Data[self.Size] end
function IM_VECTOR:erase(i) IM_ASSERT(i >= 1 and i <= self.Size) local removed = (table.remove(self.Data, i)) ~= nil self.Size = self.Size - 1 return removed end
local function _iter(v, i) i = i + 1 if i <= v.Size then return i, v.Data[i] end end
function IM_VECTOR:iter() return _iter, self, 0 end
function IM_VECTOR:find_index(value) for i = 1, self.Size do if self.Data[i] == value then return i end end return nil end
function IM_VECTOR:erase_unsorted(index) IM_ASSERT(index >= 1 and index <= self.Size) local last_idx = self.Size if index ~= last_idx then self.Data[index] = self.Data[last_idx] end self.Data[last_idx] = nil self.Size = self.Size - 1 return true end
function IM_VECTOR:find_erase(value) local idx = self:find_index(value) if idx then return self:erase(idx) end return false end
function IM_VECTOR:find_erase_unsorted(value) local idx = self:find_index(value) if idx then return self:erase_unsorted(idx) end return false end
function IM_VECTOR:reserve(new_capacity)
if new_capacity <= self.Capacity then return end
local new_data = IM_ALLOC(self._Constructor, new_capacity)
if self.Data then
ImStd.memmove(new_data, 1, self.Data, 1, self.Size)
IM_FREE(self, "Data")
end
self.Data = new_data
self.Capacity = new_capacity
end
function IM_VECTOR:reserve_discard(new_capacity)
if new_capacity <= self.Capacity then return end
if self.Data then IM_FREE(self, "Data") end
self.Data = IM_ALLOC(self._Constructor, new_capacity)
self.Capacity = new_capacity
end
function IM_VECTOR:shrink(new_size) IM_ASSERT(new_size <= self.Size) self.Size = new_size end
function IM_VECTOR:resize(new_size, v)
if new_size > self.Capacity then self:reserve(_grow_capacity(self, new_size)) end
if v ~= nil and new_size > self.Size then
local data = self.Data
for n = self.Size + 1, new_size do data[n] = v end
end
self.Size = new_size
end
function IM_VECTOR:swap(other) self.Size, other.Size = other.Size, self.Size; self.Capacity, other.Capacity = other.Capacity, self.Capacity; self.Data, other.Data = other.Data, self.Data end
function IM_VECTOR:contains(v) for i = 1, self.Size do if self.Data[i] == v then return true end end return false end
-- NOTE: This currently does not use type-aware copy!
function IM_VECTOR:insert(pos, value) IM_ASSERT(pos >= 1 and pos <= self.Size + 1); if self.Size == self.Capacity then self:reserve(_grow_capacity(self, self.Size + 1)) end; for i = self.Size, pos, -1 do self.Data[i + 1] = self.Data[i] end self.Data[pos] = value self.Size = self.Size + 1 return value end
-- NOTE: This currently does not copy type related info!
--- @nodiscard
function IM_VECTOR:copy()
local v = ImVector(); v:resize(self.Size)
local dest = v.Data; local src = self.Data
for i = 1, v.Size do dest[i] = src[i] end
return v
end
-- Not keeping value-key records inside `ImVector`, instead just find it
--- @return int # 0-based index
function IM_VECTOR:index_from_ptr(p)
local data = self.Data; for i = 1, self.Size do if p == data[i] then return i - 1 end end
--- @diagnostic disable-next-line
IM_ASSERT(false, "index_from_ptr failed!")
end
--- @class ImDrawCmd
--- @field ClipRect ImVec4
--- @field TexRef ImTextureRef
--- @field VtxOffset unsigned_int
--- @field IdxOffset unsigned_int
--- @field ElemCount unsigned_int
--- @field UserCallback ImDrawCallback
--- @field UserCallbackData any
--- @field UserCallbackDataSize int
--- @field UserCallbackDataOffset int
local IM_DRAWCMD = {}
IM_DRAWCMD.__index = IM_DRAWCMD
--- @return ImDrawCmd
--- @nodiscard
function ImDrawCmd()
return setmetatable({
ClipRect = ImVec4(),
TexRef = nil,
VtxOffset = 0,
IdxOffset = 0,
ElemCount = 0,
UserCallback = nil,
UserCallbackData = nil,
UserCallbackDataSize = 0,
UserCallbackDataOffset = 0
}, IM_DRAWCMD)
end
--- @return ImTextureID
function IM_DRAWCMD:GetTexID()
local tex_id = (self.TexRef._TexData) and self.TexRef._TexData.TexID or self.TexRef._TexID
if self.TexRef._TexData ~= nil then
IM_ASSERT(tex_id ~= ImTextureID_Invalid, "ImDrawCmd is referring to ImTextureData that wasn't uploaded to graphics system. Backend must call ImTextureData::SetTexID() after handling ImTextureStatus_WantCreate request!")
end
return tex_id
end
--- @class ImDrawVert
--- @field [1] ImVec2 # pos
--- @field [2] ImVec2 # uv
--- @field [3] ImU32 # col
--- @return ImDrawVert
--- @nodiscard
function ImDrawVert() return { ImVec2(), ImVec2(), nil } end
--- @class ImDrawCmdHeader
--- @field ClipRect ImVec4
--- @field TexRef ImTextureRef
--- @field VtxOffset unsigned_int
--- @return ImDrawCmdHeader
--- @nodiscard
function ImDrawCmdHeader() return { ClipRect = ImVec4(), TexRef = nil, VtxOffset = 0 } end
--- @class ImDrawChannel
--- @field _CmdBuffer ImVector<ImDrawCmd>
--- @field _IdxBuffer ImVector<ImDrawIdx>
--- @return ImDrawChannel
--- @nodiscard
function ImDrawChannel() return { _CmdBuffer = ImVector(), _IdxBuffer = ImVector() } end
--- @class ImDrawListSplitter
--- @field _Current int
--- @field _Count int
--- @field _Channels ImVector<ImDrawChannel>
--- @return ImDrawListSplitter
--- @nodiscard
function ImDrawListSplitter() return { _Current = 0, _Count = 0, _Channels = ImVector() } end
--- @class ImDrawList
--- @field CmdBuffer ImVector<ImDrawCmd>
--- @field IdxBuffer ImVector<ImDrawIdx>
--- @field VtxBuffer ImVector<ImDrawVert>
--- @field Flags ImDrawListFlags
--- @field _VtxCurrentIdx unsigned_int # 1-based, generally == (VtxBuffer.Size + 1)
--- @field _Data ImDrawListSharedData # Pointes to shared draw data
--- @field _VtxWritePtr unsigned_int # 1-based, points to the current writing index in VtxBuffer.Data
--- @field _IdxWritePtr unsigned_int # 1-based, points to the current writing index in IdxBuffer.Data
--- @field _Path ImVector<ImVec2> # current path building
--- @field _CmdHeader ImDrawCmdHeader # template of active commands. Fields should match those of CmdBuffer:back()
--- @field _Splitter ImDrawListSplitter
--- @field _ClipRectStack ImVector<ImVec4>
--- @field _TextureStack ImVector<ImTextureRef>
--- @field _CallbacksDataBuf any
--- @field _FringeScale float
--- @field _OwnerName string
MT.ImDrawList = {}
MT.ImDrawList.__index = MT.ImDrawList
--- @param pos ImVec2
--- @param uv ImVec2
--- @param col ImU32
function MT.ImDrawList:PrimWriteVtx(pos, uv, col)
local vtx = self.VtxBuffer.Data[self._VtxWritePtr]
ImVec2_Copy(vtx[1], pos)
ImVec2_Copy(vtx[2], uv)
vtx[3] = col
self._VtxWritePtr = self._VtxWritePtr + 1
self._VtxCurrentIdx = self._VtxCurrentIdx + 1
end
--- @param idx ImDrawIdx
function MT.ImDrawList:PrimWriteIdx(idx)
self.IdxBuffer.Data[self._IdxWritePtr] = idx
self._IdxWritePtr = self._IdxWritePtr + 1
end
--- @param pos ImVec2
--- @param uv ImVec2
--- @param col ImU32
function MT.ImDrawList:PrimVtx(pos, uv, col)
self:PrimWriteIdx(self._VtxCurrentIdx)
self:PrimWriteVtx(pos, uv, col)
end
--- @param data? ImDrawListSharedData
--- @return ImDrawList
--- @nodiscard
function ImDrawList(data)
--- @type ImDrawList
local this = setmetatable({
CmdBuffer = ImVector(),
IdxBuffer = ImVector(),
VtxBuffer = ImVector(ImDrawVert),
Flags = 0,
_VtxCurrentIdx = 1,
_Data = nil,
_VtxWritePtr = 1,
_IdxWritePtr = 1,
_Path = ImVector(ImVec2, ImVec2_TCopy),
_CmdHeader = ImDrawCmdHeader(),
_Splitter = ImDrawListSplitter(),
_ClipRectStack = ImVector(),
_TextureStack = ImVector(),
_CallbacksDataBuf = nil,
_FringeScale = 0,
_OwnerName = nil
}, MT.ImDrawList)
this:_SetDrawListSharedData(data)
return this
end
--- @class ImDrawData
--- @field Valid bool
--- @field FrameCount int
--- @field TotalIdxCount int
--- @field TotalVtxCount int
--- @field CmdLists ImVector<ImDrawList>
--- @field DisplayPos ImVec2
--- @field DisplaySize ImVec2
--- @field FramebufferScale ImVec2
--- @field OwnerViewport ImGuiViewport
--- @field Textures ImVector<ImTextureData>
MT.ImDrawData = {}
MT.ImDrawData.__index = MT.ImDrawData
--- @return ImDrawData
function ImDrawData()
--- @type ImDrawData
local this = setmetatable({}, MT.ImDrawData)
this.CmdLists = ImVector()
this:Clear()
return this
end
--- @class ImTextureData
--- @field UniqueID int
--- @field Status ImTextureStatus
--- @field BackendUserData any
--- @field QueueUserData any
--- @field TexID ImTextureID
--- @field Format ImTextureFormat
--- @field Width int
--- @field Height int
--- @field BytesPerPixel int
--- @field Pixels unsigned_char[]
--- @field UsedRect ImTextureRect
--- @field UpdateRect ImTextureRect
--- @field Updates ImVector<ImTextureRect>
--- @field UnusedFrames int
--- @field RefCount unsigned_short
--- @field UseColors bool
--- @field WantDestroyNextFrame bool
MT.ImTextureData = {}
MT.ImTextureData.__index = MT.ImTextureData
--- @return ImTextureData
--- @nodiscard
function ImTextureData()
--- @type ImTextureData
local this = setmetatable({}, MT.ImTextureData)
this.UniqueID = 0
this.Status = ImTextureStatus.Destroyed
this.BackendUserData = nil
this.TexID = ImTextureID_Invalid
this.Format = 0
this.Width = 0
this.Height = 0
this.BytesPerPixel = 0
this.Pixels = nil
this.UsedRect = ImTextureRect()
this.UpdateRect = ImTextureRect()
this.Updates = ImVector()
this.UnusedFrames = 0
this.RefCount = 0
this.UseColors = false
this.WantDestroyNextFrame = false
return this
end
--- @param x int
--- @param y int
function MT.ImTextureData:GetPixelsAt(x, y)
return self.Pixels, (x + y * self.Width) * self.BytesPerPixel + 1
end
function MT.ImTextureData:GetPitch() return self.Width * self.BytesPerPixel end
function MT.ImTextureData:GetTexID() return self.TexID end
--- @param tex_id ImTextureID
function MT.ImTextureData:SetTexID(tex_id) self.TexID = tex_id end
--- @param status ImTextureStatus
function MT.ImTextureData:SetStatus(status) self.Status = status if (status == ImTextureStatus.Destroyed and not self.WantDestroyNextFrame and self.Pixels ~= nil) then self.Status = ImTextureStatus.WantCreate end end
--- @class ImTextureRef
--- @field _TexData? ImTextureData
--- @field _TexID ImTextureID
local IM_TEXTURE_REF = {}
IM_TEXTURE_REF.__index = IM_TEXTURE_REF
--- @return ImTextureRef
--- @nodiscard
function ImTextureRef(tex_id)
return setmetatable({
_TexData = nil,
_TexID = tex_id or ImTextureID_Invalid
}, IM_TEXTURE_REF)
end
--- @class ImFontBaked
--- @field IndexAdvanceX ImVector<float> # Glyphs->AdvanceX in a directly indexable way. Note that codepoint starts from 0, so IndexAdvanceX.Data[0 + 1] holds the advanceX of glyph at codepoint 0
--- @field FallbackAdvanceX float
--- @field Size float
--- @field RasterizerDensity float
--- @field IndexLookup ImVector<ImU16> # Index glyphs by Unicode codepoint. use IndexLookup.Data[codepoint + 1] for codepoint. Stores 1-based index!
--- @field Glyphs ImVector<ImFontGlyph>
--- @field FallbackGlyphIndex int # Initial value = -1, then becomes 1-based index if fallback char is set
--- @field Ascent float
--- @field Descent float
--- @field MetricsTotalSurface unsigned_int
--- @field WantDestroy bool
--- @field LoadNoFallback bool
--- @field LoadNoRenderOnLayout bool
--- @field LastUsedFrame int
--- @field BakedId ImGuiID
--- @field OwnerFont ImFont
--- @field FontLoaderDatas any
MT.ImFontBaked = {}
MT.ImFontBaked.__index = MT.ImFontBaked
--- @return ImFontBaked
--- @nodiscard
function ImFontBaked()
--- @type ImFontBaked
local this = setmetatable({}, MT.ImFontBaked)
this.IndexAdvanceX = ImVector()
this.FallbackAdvanceX = 0
this.Size = 0
this.RasterizerDensity = 0
this.IndexLookup = ImVector()
this.Glyphs = ImVector()
this.FallbackGlyphIndex = -1
this.Ascent = 0
this.Descent = 0
this.MetricsTotalSurface = 0
this.WantDestroy = false
this.LoadNoFallback = false
this.LoadNoRenderOnLayout = false
this.LastUsedFrame = 0
this.BakedId = 0
this.OwnerFont = nil
this.FontLoaderDatas = nil
return this
end
--- @class ImFont
--- @field LastBaked ImFontBaked
--- @field OwnerAtlas ImFontAtlas
--- @field Flags ImFontFlags
--- @field CurrentRasterizerDensity float
--- @field FontId ImGuiID
--- @field LegacySize float
--- @field Sources ImVector<ImFontConfig>
--- @field EllipsisChar ImWchar
--- @field FallbackChar ImWchar
--- @field Used8kPagesMap ImU8[] # 1-based table
--- @field EllipsisAutoBake bool
--- @field RemapPairs table<ImGuiID, any> # LUA: No ImGuiStorage
--- @field Scale float
MT.ImFont = {}
MT.ImFont.__index = MT.ImFont
function MT.ImFont:IsLoaded() return self.OwnerAtlas ~= nil end
function MT.ImFont:GetDebugName() if self.Sources.Size > 0 then return self.Sources[1].Name else return "<unknown>" end end
--- @return ImFont
--- @nodiscard
function ImFont()
--- @type ImFont
local this = setmetatable({}, MT.ImFont)
this.LastBaked = nil
this.OwnerAtlas = nil
this.Flags = 0
this.CurrentRasterizerDensity = 0
this.FontId = 0
this.LegacySize = 0
this.Sources = ImVector()
this.EllipsisChar = 0
this.FallbackChar = 0
this.Used8kPagesMap = {}
this.EllipsisAutoBake = false
this.RemapPairs = {}
this.Scale = 0
return this
end
--- @class ImFontConfig
--- @field Name string
--- @field FontData table
--- @field FontDataSize int
--- @field FontDataOwnedByAtlas bool
--- @field MergeMode bool
--- @field PixelSnapH bool
--- @field OversampleH ImS8
--- @field OversampleV ImS8
--- @field EllipsisChar ImWchar
--- @field SizePixels float
--- @field GlyphRanges ImWchar[]
--- @field GlyphExcludeRanges ImWchar[]
--- @field GlyphOffset ImVec2
--- @field GlyphMinAdvanceX float
--- @field GlyphMaxAdvanceX float
--- @field GlyphExtraAdvanceX float
--- @field FontNo ImU32
--- @field FontLoaderFlags unsigned_int
--- @field RasterizerMultiply float
--- @field RasterizerDensity float
--- @field ExtraSizeScale float
--- @field Flags ImFontFlags
--- @field DstFont ImFont
--- @field FontLoader ImFontLoader
--- @field FontLoaderData any
local IM_FONT_CONFIG = {}
IM_FONT_CONFIG.__index = IM_FONT_CONFIG
--- @return ImFontConfig
--- @nodiscard
function ImFontConfig()
--- @type ImFontConfig
local this = setmetatable({}, IM_FONT_CONFIG)
this.Name = nil
this.FontData = nil
this.FontDataSize = 0
this.FontDataOwnedByAtlas = true
this.MergeMode = false
this.PixelSnapH = false
this.OversampleH = 0
this.OversampleV = 0
this.EllipsisChar = 0
this.SizePixels = 0
this.GlyphRanges = nil
this.GlyphExcludeRanges = nil
this.GlyphOffset = ImVec2()
this.GlyphMinAdvanceX = 0
this.GlyphMaxAdvanceX = FLT_MAX
this.GlyphExtraAdvanceX = 0
this.FontNo = 0
this.FontLoaderFlags = 0
this.RasterizerMultiply = 1.0
this.RasterizerDensity = 1.0
this.ExtraSizeScale = 1.0
this.Flags = 0
this.DstFont = nil
this.FontLoader = nil
this.FontLoaderData = nil
return this
end
--- @class ImFontAtlas
--- @field Flags ImFontAtlasFlags
--- @field TexDesiredFormat ImTextureFormat
--- @field TexGlyphPadding int
--- @field TexMinWidth int
--- @field TexMinHeight int
--- @field TexMaxWidth int
--- @field TexMaxHeight int
--- @field TexRef ImTextureRef
--- @field TexData ImTextureData
--- @field TexList ImVector<ImTextureData>
--- @field Locked bool
--- @field RendererHasTextures bool
--- @field TexPixelsUseColors bool
--- @field TexUvScale ImVec2
--- @field TexUvWhitePixel ImVec2
--- @field Fonts ImVector<ImFont>
--- @field Sources ImVector<ImFontConfig>
--- @field TexUvLines ImVec4[] # 0-based table
--- @field TexNextUniqueID int
--- @field FontNextUniqueID int
--- @field DrawListSharedDatas ImVector<ImDrawListSharedData>
--- @field Builder ImFontAtlasBuilder
--- @field FontLoader ImFontLoader
--- @field FontLoaderName string
--- @field FontLoaderData any
--- @field FontLoaderFlags unsigned_int
--- @field RefCount int
--- @field OwnerContext ImGuiContext
MT.ImFontAtlas = {}
MT.ImFontAtlas.__index = MT.ImFontAtlas
--- @return ImFontAtlas
--- @nodiscard
function ImFontAtlas()
--- @type ImFontAtlas
local this = setmetatable({}, MT.ImFontAtlas)
this.Flags = 0
this.TexDesiredFormat = ImTextureFormat.RGBA32
this.TexGlyphPadding = 1
this.TexMinWidth = 512
this.TexMinHeight = 128
this.TexMaxWidth = 8192
this.TexMaxHeight = 8192
this.TexRef = ImTextureRef()
this.TexData = nil
this.TexList = ImVector()
this.Locked = false
this.RendererHasTextures = false
this.TexPixelsUseColors = nil
this.TexUvScale = nil
this.TexUvWhitePixel = nil
this.Fonts = ImVector()
this.Sources = ImVector()
this.TexUvLines = {}
this.TexNextUniqueID = 1
this.FontNextUniqueID = 1
this.DrawListSharedDatas = ImVector()
this.Builder = nil
this.FontLoader = nil
this.FontLoaderName = nil
this.FontLoaderData = nil
this.FontLoaderFlags = nil
this.RefCount = 0
this.OwnerContext = nil
return this
end
--- @class ImFontAtlasRect
--- @field x unsigned_short
--- @field y unsigned_short
--- @field w unsigned_short
--- @field h unsigned_short
--- @field uv0 ImVec2
--- @field uv1 ImVec2
--- @alias ImFontAtlasRectId int
ImFontAtlasRectId_Invalid = -1
--- @return ImFontAtlasRect
--- @nodiscard
function ImFontAtlasRect()
return {
x = nil, y = nil,
w = nil, h = nil,
uv0 = ImVec2(),
uv1 = ImVec2()
}
end
--- @class ImFontGlyph
--- @field Colored boolean
--- @field Visible boolean
--- @field SourceIdx unsigned_int
--- @field Codepoint unsigned_int
--- @field AdvanceX float
--- @field X0 float
--- @field Y0 float
--- @field X1 float
--- @field Y1 float
--- @field U0 float
--- @field V0 float
--- @field U1 float
--- @field V1 float
--- @field PackId int
--- @return ImFontGlyph
--- @nodiscard
function ImFontGlyph()
return {
Colored = false,
Visible = false,
SourceIdx = 0,
Codepoint = 0,
AdvanceX = 0,
X0 = 0, Y0 = 0, X1 = 0, Y1 = 0,
U0 = 0, V0 = 0, U1 = 0, V1 = 0,
PackId = -1
}
end
--- @class ImGuiKeyData
--- @field Down bool
--- @field DownDuration float
--- @field DownDurationPrev float
--- @field AnalogValue float
--- @return ImGuiKeyData
--- @nodiscard
function ImGuiKeyData() return { Down = false, DownDuration = 0.0, DownDurationPrev = 0.0, AnalogValue = 0.0 } end
--- @enum ImGuiConfigFlags
ImGuiConfigFlags = {
None = 0,
NavEnableKeyboard = bitLShift(1, 0),
NavEnableGamepad = bitLShift(1, 1),
NoMouse = bitLShift(1, 4),
NoMouseCursorChange = bitLShift(1, 5),
NoKeyboard = bitLShift(1, 6),
ViewportsEnable = bitLShift(1, 10),
IsSRGB = bitLShift(1, 20),
IsTouchScreen = bitLShift(1, 21)
}
--- @class ImGuiIO
MT.ImGuiIO = {}
MT.ImGuiIO.__index = MT.ImGuiIO
--- @return ImGuiIO
function ImGuiIO()
local this = {
Ctx = nil,
KeyCtrl = false,
KeyShift = false,
KeyAlt = false,
KeySuper = false,
KeyMods = nil,
BackendFlags = ImGuiBackendFlags.None,
ConfigFlags = ImGuiConfigFlags.None,
DisplaySize = ImVec2(-1.0, -1.0),
DeltaTime = 1.0 / 60.0,
DisplayFramebufferScale = ImVec2(1.0, 1.0),
MousePos = ImVec2(),
MousePosPrev = ImVec2(),
WantSetMousePos = false,
MouseDelta = ImVec2(),
MouseDown = {[0] = false, [1] = false, [2] = false},
MouseWheel = 0,
MouseWheelH = 0,
MouseCtrlLeftAsRightClick = false,
MouseWheelRequestAxisSwap = false,
ConfigColorEditFlags = ImGuiColorEditFlags.DefaultOptions_,
ConfigMacOSXBehaviors = false,
ConfigNavCursorVisibleAuto = true,
ConfigNavCursorVisibleAlways = false,
ConfigInputTrickleEventQueue = true,
ConfigWindowsResizeFromEdges = true,
ConfigDebugIniSettings = false,
ConfigViewportsNoAutoMerge = false,
ConfigViewportsNoTaskBarIcon = false,
ConfigViewportsNoDecoration = true,
ConfigViewportsNoDefaultParent = true,
ConfigViewportsPlatformFocusSetsImGuiFocus = true,
ConfigMemoryCompactTimer = 60.0,
MouseDrawCursor = false,
MouseClicked = {[0] = false, [1] = false, [2] = false},
MouseReleased = {[0] = false, [1] = false, [2] = false},
MouseClickedCount = {[0] = 0, [1] = 0, [2] = 0},
MouseClickedLastCount = {[0] = 0, [1] = 0, [2] = 0},
MouseDownDuration = {[0] = -1, [1] = -1, [2] = -1},
MouseDownDurationPrev = {[0] = -1, [1] = -1, [2] = -1},
MouseDragMaxDistanceAbs = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()},
MouseDragMaxDistanceSqr = {[0] = 0, [1] = 0, [2] = 0},
MouseDownOwned = {[0] = nil, [1] = nil, [2] = nil},
MouseDownOwnedUnlessPopupClose = {[0] = nil, [1] = nil, [2] = nil},
MouseClickedTime = {[0] = 0, [1] = 0, [2] = 0},
MouseReleasedTime = {[0] = 0, [1] = 0, [2] = 0},
MouseClickedPos = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()},
MouseDoubleClicked = {[0] = false, [1] = false, [2] = false},
MouseDoubleClickTime = 0.30,
MouseDoubleClickMaxDist = 6.0,
MouseDragThreshold = 6.0,
KeyRepeatDelay = 0.275,
KeyRepeatRate = 0.050,
KeysData = {}, -- size = ImGuiKey.NamedKey_COUNT
WantCaptureMouse = nil,
WantCaptureKeyboard = nil,
WantTextInput = nil,
Framerate = 0,
NavActive = false,
NavVisible = false,
MetricsRenderWindows = 0,
Fonts = nil,
FontDefault = nil,
BackendPlatformUserData = nil,
BackendRendererUserData = nil,
InputQueueCharacters = ImVector(),
AppAcceptingEvents = true,
InputQueueSurrogate = 0
}
for i = 0, ImGuiKey.NamedKey_COUNT - 1 do
this.KeysData[i] = ImGuiKeyData()
end
return setmetatable(this, MT.ImGuiIO)
end
--- @class ImGuiPlatformImeData
--- @field WantVisible bool
--- @field WantTextInput bool
--- @field InputPos ImVec2
--- @field InputLineHeight float
--- @field ViewportId ImGuiID
--- @return ImGuiPlatformImeData
--- @nodiscard
function ImGuiPlatformImeData()
return {
WantVisible = false,
WantTextInput = false,
InputPos = ImVec2(),
InputLineHeight = 0.0,
ViewportId = 0
}
end
--- @param dest ImGuiPlatformImeData
--- @param src ImGuiPlatformImeData
function ImGuiPlatformImeData_Copy(dest, src)
dest.WantVisible = src.WantVisible
dest.WantTextInput = src.WantTextInput
ImVec2_Copy(dest.InputPos, src.InputPos)
dest.InputLineHeight = src.InputLineHeight
dest.ViewportId = src.ViewportId
end
--- @param data1 ImGuiPlatformImeData
--- @param data2 ImGuiPlatformImeData
function ImGuiPlatformImeData_Compare(data1, data2)
if data1.WantVisible ~= data2.WantVisible or
data1.WantTextInput ~= data2.WantTextInput or
data1.InputPos ~= data2.InputPos or
data1.InputLineHeight ~= data2.InputLineHeight or
data1.ViewportId ~= data2.ViewportId then
return false
end
return true
end
--- @enum ImGuiViewportFlags
ImGuiViewportFlags = {
None = 0,
IsPlatformWindow = bitLShift(1, 0),
IsPlatformMonitor = bitLShift(1, 1),
OwnedByApp = bitLShift(1, 2),
NoDecoration = bitLShift(1, 3),
NoTaskBarIcon = bitLShift(1, 4),
NoFocusOnAppearing = bitLShift(1, 5),
NoFocusOnClick = bitLShift(1, 6),
NoInputs = bitLShift(1, 7),
NoRendererClear = bitLShift(1, 8),
NoAutoMerge = bitLShift(1, 9),
TopMost = bitLShift(1, 10),
CanHostOtherWindows = bitLShift(1, 11),
IsMinimized = bitLShift(1, 12),
IsFocused = bitLShift(1, 13)
}
--- @class ImGuiViewport
--- @field ID ImGuiID
--- @field Flags ImGuiViewportFlags
--- @field Pos ImVec2
--- @field Size ImVec2
--- @field FramebufferScale ImVec2
--- @field WorkPos ImVec2
--- @field WorkSize ImVec2
--- @field DpiScale float
--- @field ParentViewportId ImGuiID
--- @field ParentViewport ImGuiViewport
--- @field DrawData ImDrawData
--- @field RendererUserData any
--- @field PlatformUserData any
--- @field PlatformHandle any
--- @field PlatformHandleRaw any
--- @field PlatformWindowCreated bool
--- @field PlatformRequestMove bool
--- @field PlatformRequestResize bool
--- @field PlatformRequestClose bool
MT.ImGuiViewport = {}
MT.ImGuiViewport.__index = MT.ImGuiViewport
function MT.ImGuiViewport:GetCenter()
return ImVec2(self.Pos.x + self.Size.x * 0.5, self.Pos.y + self.Size.y * 0.5)
end
function MT.ImGuiViewport:GetWorkCenter()
return ImVec2(self.WorkPos.x + self.WorkSize.x * 0.5, self.WorkPos.y + self.WorkSize.y * 0.5)
end
--- @return ImGuiViewport
--- @nodiscard
function ImGuiViewport()
return setmetatable({
ID = 0,
Flags = 0,
Pos = ImVec2(),
Size = ImVec2(),
FramebufferScale = ImVec2(),
WorkPos = ImVec2(),
WorkSize = ImVec2(),
DpiScale = 0,
PlatformHandle = nil,
PlatformHandleRaw = nil,
PlatformWindowCreated = false
}, MT.ImGuiViewport)
end
--- @class ImGuiPlatformIO
--- @field Platform_GetClipboardTextFn fun(ctx?: ImGuiContext): string
--- @field Platform_CreateWindow fun(vp: ImGuiViewport)
--- @field Platform_OnChangedViewport fun(vp: ImGuiViewport)
--- @field Monitors ImVector<ImGuiPlatformMonitor>
--- @field Textures ImVector<ImTextureData>
--- @field Viewports ImVector<ImGuiViewport>
MT.ImGuiPlatformIO = {}
MT.ImGuiPlatformIO.__index = MT.ImGuiPlatformIO
--- @return ImGuiPlatformIO
--- @nodiscard
function ImGuiPlatformIO()
local this = {
Platform_GetClipboardTextFn = nil,
Platform_SetClipboardTextFn = nil,
Platform_OpenInShellFn = nil,
Platform_OpenInShellUserData = nil,
Renderer_TextureMaxWidth = 0,
Renderer_TextureMaxHeight = 0,
Renderer_RenderState = nil,
Monitors = ImVector(),
Textures = ImVector(),
Viewports = ImVector(),
Platform_LocaleDecimalPoint = 46, -- '.'
Platform_OnChangedViewport = nil,
}
return setmetatable(this, MT.ImGuiPlatformIO)
end
--- @class ImGuiPlatformMonitor
--- @field MainPos ImVec2
--- @field MainSize ImVec2
--- @field WorkPos ImVec2
--- @field WorkSize ImVec2
--- @field DpiScale float
--- @field PlatformHandle any
--- @return ImGuiPlatformMonitor
--- @nodiscard
function ImGuiPlatformMonitor()
return {
MainPos = ImVec2(0, 0),
MainSize = ImVec2(0, 0),
WorkPos = ImVec2(0, 0),
WorkSize = ImVec2(0, 0),
DpiScale = 1.0,
PlatformHandle = nil
}
end
--- @enum ImGuiWindowFlags
ImGuiWindowFlags = {
None = 0,
NoTitleBar = bitLShift(1, 0),
NoResize = bitLShift(1, 1),
NoMove = bitLShift(1, 2),
NoScrollbar = bitLShift(1, 3),
NoScrollWithMouse = bitLShift(1, 4),
NoCollapse = bitLShift(1, 5),
AlwaysAutoResize = bitLShift(1, 6),
NoBackground = bitLShift(1, 7),
NoSavedSettings = bitLShift(1, 8),
NoMouseInputs = bitLShift(1, 9),
MenuBar = bitLShift(1, 10),
HorizontalScrollbar = bitLShift(1, 11),
NoFocusOnAppearing = bitLShift(1, 12),
NoBringToFrontOnFocus = bitLShift(1, 13),
AlwaysVerticalScrollbar = bitLShift(1, 14),
AlwaysHorizontalScrollbar = bitLShift(1, 15),
NoNavInputs = bitLShift(1, 16),
NoNavFocus = bitLShift(1, 17),
UnsavedDocument = bitLShift(1, 18),
NoDocking = bitLShift(1, 19),
DockNodeHost = bitLShift(1, 23),
ChildWindow = bitLShift(1, 24),
Tooltip = bitLShift(1, 25),
Popup = bitLShift(1, 26),
Modal = bitLShift(1, 27),
ChildMenu = bitLShift(1, 28)
}
-- [Internal]
ImGuiWindowFlags.NoNav = bitOr(ImGuiWindowFlags.NoNavInputs, ImGuiWindowFlags.NoNavFocus)
ImGuiWindowFlags.NoDecoration = bitOr(ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoCollapse)
ImGuiWindowFlags.NoInputs = bitOr(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs, ImGuiWindowFlags.NoNavFocus)
--- @enum ImGuiItemFlags
ImGuiItemFlags = {
None = 0,
NoTabStop = bitLShift(1, 0),
NoNav = bitLShift(1, 1),
NoNavDefaultFocus = bitLShift(1, 2),
ButtonRepeat = bitLShift(1, 3),
AutoClosePopups = bitLShift(1, 4),
AllowDuplicateId = bitLShift(1, 5),
Disabled = bitLShift(1, 6),
LiveEditOnInputText = bitLShift(1, 7),
LiveEditOnInputScalar = bitLShift(1, 8)
}
ImGuiItemFlags.LiveEditOnInput = bitOr(ImGuiItemFlags.LiveEditOnInputText, ImGuiItemFlags.LiveEditOnInputScalar)
--- @enum ImGuiItemStatusFlags
ImGuiItemStatusFlags = {
None = 0,
HoveredRect = bitLShift(1, 0),
HasDisplayRect = bitLShift(1, 1),
Edited = bitLShift(1, 2),
ToggledSelection = bitLShift(1, 3),
ToggledOpen = bitLShift(1, 4),
HasDeactivated = bitLShift(1, 5),
Deactivated = bitLShift(1, 6),
HoveredWindow = bitLShift(1, 7),
Visible = bitLShift(1, 8),
HasClipRect = bitLShift(1, 9),
HasShortcut = bitLShift(1, 10),
EditedInternal = bitLShift(1, 11)
}
--- @enum ImGuiChildFlags
ImGuiChildFlags = {
None = 0,
Borders = bitLShift(1, 0),
AlwaysUseWindowPadding = bitLShift(1, 1),
ResizeX = bitLShift(1, 2),
ResizeY = bitLShift(1, 3),
AutoResizeX = bitLShift(1, 4),
AutoResizeY = bitLShift(1, 5),
AlwaysAutoResize = bitLShift(1, 6),
FrameStyle = bitLShift(1, 7),
NavFlattened = bitLShift(1, 8)
}
ImGuiChildFlags.ResizeBoth = bitOr(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)
ImGuiChildFlags.ResizeXAndY = ImGuiChildFlags.ResizeBoth
--- @enum ImGuiNextItemDataFlags
ImGuiNextItemDataFlags = {
None = 0,
HasWidth = bitLShift(1, 0),
HasOpen = bitLShift(1, 1),
HasShortcut = bitLShift(1, 2),
HasRefVal = bitLShift(1, 3),
HasStorageID = bitLShift(1, 4),
HasColorMarker = bitLShift(1, 5)
}
--- @enum ImDrawFlags
ImDrawFlags = {
None = 0,
RoundCornersTopLeft = bitLShift(1, 4),
RoundCornersTopRight = bitLShift(1, 5),
RoundCornersBottomLeft = bitLShift(1, 6),
RoundCornersBottomRight = bitLShift(1, 7),
RoundCornersNone = bitLShift(1, 8),
Closed = bitLShift(1, 9)
}
ImDrawFlags.RoundCornersTop = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight)
ImDrawFlags.RoundCornersBottom = bitOr(ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight)
ImDrawFlags.RoundCornersLeft = bitOr(ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersTopLeft)
ImDrawFlags.RoundCornersRight = bitOr(ImDrawFlags.RoundCornersBottomRight, ImDrawFlags.RoundCornersTopRight)
ImDrawFlags.RoundCornersAll = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight, ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight)
ImDrawFlags.RoundCornersDefault_ = ImDrawFlags.RoundCornersAll
ImDrawFlags.RoundCornersMask_ = bitOr(ImDrawFlags.RoundCornersAll, ImDrawFlags.RoundCornersNone)
ImDrawFlags.InvalidMask_ = 0x8000000F
--- @enum ImDrawListFlags
ImDrawListFlags = {
None = 0,
AntiAliasedLines = bitLShift(1, 0),
AntiAliasedLinesUseTex = bitLShift(1, 1),
AntiAliasedFill = bitLShift(1, 2),
AllowVtxOffset = bitLShift(1, 3),
TextNoPixelSnap = bitLShift(1, 4)
}
--- @enum ImFontFlags
ImFontFlags = {
None = 0,
NoLoadError = bitLShift(1, 1),
NoLoadGlyphs = bitLShift(1, 2),
LockBakedSizes = bitLShift(1, 3),
ImplicitRefSize = bitLShift(1, 4)
}
--- @enum ImGuiMouseSource
ImGuiMouseSource = {
Mouse = 0,
TouchScreen = 1,
Pen = 2,
COUNT = 3
}
--- @enum ImGuiCond
ImGuiCond = {
None = 0,
Always = bitLShift(1, 0),
Once = bitLShift(1, 1),
FirstUseEver = bitLShift(1, 2),
Appearing = bitLShift(1, 3)
}
--- @enum ImGuiInputFlags
ImGuiInputFlags = {
None = 0,
Repeat = bitLShift(1, 0),
RouteActive = bitLShift(1, 10),
RouteFocused = bitLShift(1, 11),
RouteGlobal = bitLShift(1, 12),
RouteAlways = bitLShift(1, 13),
RouteOverFocused = bitLShift(1, 14),
RouteOverActive = bitLShift(1, 15),
RouteUnlessBgFocused = bitLShift(1, 16),
RouteFromRootWindow = bitLShift(1, 17),
Tooltip = bitLShift(1, 18)
}
--- @enum ImGuiButtonFlags
ImGuiButtonFlags = {
None = 0,
MouseButtonLeft = bitLShift(1, 0),
MouseButtonRight = bitLShift(1, 1),
MouseButtonMiddle = bitLShift(1, 2),
EnableNav = bitLShift(1, 3),
PressedOnClick = bitLShift(1, 4),
PressedOnClickRelease = bitLShift(1, 5),
PressedOnClickReleaseAnywhere = bitLShift(1, 6),
PressedOnRelease = bitLShift(1, 7),
PressedOnDoubleClick = bitLShift(1, 8),
PressedOnDragDropHold = bitLShift(1, 9),
FlattenChildren = bitLShift(1, 11),
AllowOverlap = bitLShift(1, 12),
AlignTextBaseLine = bitLShift(1, 15),
NoKeyModsAllowed = bitLShift(1, 16),
NoHoldingActiveId = bitLShift(1, 17),
NoNavFocus = bitLShift(1, 18),
NoHoveredOnFocus = bitLShift(1, 19),
NoSetKeyOwner = bitLShift(1, 20),
NoTestKeyOwner = bitLShift(1, 21),
NoFocus = bitLShift(1, 22)
}
ImGuiButtonFlags.MouseButtonMask_ = bitOr(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight, ImGuiButtonFlags.MouseButtonMiddle)
ImGuiButtonFlags.PressedOnMask_ = bitOr(ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.PressedOnClickRelease, ImGuiButtonFlags.PressedOnClickReleaseAnywhere, ImGuiButtonFlags.PressedOnRelease, ImGuiButtonFlags.PressedOnDoubleClick, ImGuiButtonFlags.PressedOnDragDropHold)
ImGuiButtonFlags.PressedOnDefault_ = ImGuiButtonFlags.PressedOnClickRelease
ImGuiButtonFlags.NoKeyModifiers = ImGuiButtonFlags.NoKeyModsAllowed
--- @enum ImGuiStyleVar
ImGuiStyleVar = {
Alpha = 0,
DisabledAlpha = 1,
WindowPadding = 2,
WindowRounding = 3,
WindowBorderSize = 4,
WindowMinSize = 5,
WindowTitleAlign = 6,
ChildRounding = 7,
ChildBorderSize = 8,
PopupRounding = 9,
PopupBorderSize = 10,
FramePadding = 11,
FrameRounding = 12,
FrameBorderSize = 13,
ItemSpacing = 14,
ItemInnerSpacing = 15,
IndentSpacing = 16,
CellPadding = 17,
ScrollbarSize = 18,
ScrollbarRounding = 19,
ScrollbarPadding = 20,
GrabMinSize = 21,
GrabRounding = 22,
ImageRounding = 23,
ImageBorderSize = 24,
TabRounding = 25,
TabBorderSize = 26,
TabMinWidthBase = 27,
TabMinWidthShrink = 28,
TabBarBorderSize = 29,
TabBarOverlineSize = 30,
TableAngledHeadersAngle = 31,
TableAngledHeadersTextAlign = 32,
TreeLinesSize = 33,
TreeLinesRounding = 34,
MenuItemRounding = 35,
SelectableRounding = 36,
DragDropTargetRounding = 37,
ButtonTextAlign = 38,
SelectableTextAlign = 39,
SeparatorTextBorderSize = 40,
SeparatorTextAlign = 41,
SeparatorTextPadding = 42,
COUNT = 43
}
--- @enum ImGuiHoveredFlags
ImGuiHoveredFlags = {
None = 0,
ChildWindows = bitLShift(1, 0),
RootWindow = bitLShift(1, 1),
AnyWindow = bitLShift(1, 2),
NoPopupHierarchy = bitLShift(1, 3),
AllowWhenBlockedByPopup = bitLShift(1, 5),
AllowWhenBlockedByActiveItem = bitLShift(1, 7),
AllowWhenOverlappedByItem = bitLShift(1, 8),
AllowWhenOverlappedByWindow = bitLShift(1, 9),
AllowWhenDisabled = bitLShift(1, 10),
NoNavOverride = bitLShift(1, 11),
ForTooltip = bitLShift(1, 12),
Stationary = bitLShift(1, 13),
DelayNone = bitLShift(1, 14),
DelayShort = bitLShift(1, 15),
DelayNormal = bitLShift(1, 16),
NoSharedDelay = bitLShift(1, 17)
}
ImGuiHoveredFlags.AllowWhenOverlapped = bitOr(ImGuiHoveredFlags.AllowWhenOverlappedByItem, ImGuiHoveredFlags.AllowWhenOverlappedByWindow)
ImGuiHoveredFlags.RectOnly = bitOr(ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.AllowWhenOverlapped)
ImGuiHoveredFlags.RootAndChildWindows = bitOr(ImGuiHoveredFlags.RootWindow, ImGuiHoveredFlags.ChildWindows)
ImGuiHoveredFlags.DelayMask_ = bitOr(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal, ImGuiHoveredFlags.NoSharedDelay)
ImGuiHoveredFlags.AllowedMaskForIsWindowHovered = bitOr(ImGuiHoveredFlags.ChildWindows, ImGuiHoveredFlags.RootWindow, ImGuiHoveredFlags.AnyWindow, ImGuiHoveredFlags.NoPopupHierarchy, ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.Stationary)
ImGuiHoveredFlags.AllowedMaskForIsItemHovered = bitOr(ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.AllowWhenOverlapped, ImGuiHoveredFlags.AllowWhenDisabled, ImGuiHoveredFlags.NoNavOverride, ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayMask_)
--- @enum ImGuiKey
ImGuiKey = {
None = 0,
NamedKey_BEGIN = 512,
Tab = 512,
LeftArrow = 513,
RightArrow = 514,
UpArrow = 515,
DownArrow = 516,
PageUp = 517,
PageDown = 518,
Home = 519,
End = 520,
Insert = 521,
Delete = 522,
Backspace = 523,
Space = 524,
Enter = 525,
Escape = 526,
LeftCtrl = 527, LeftShift = 528, LeftAlt = 529, LeftSuper = 530,
RightCtrl = 531, RightShift = 532, RightAlt = 533, RightSuper = 534,
Menu = 535,
-- 1 ~ 9
K0 = 536, K1 = 537, K2 = 538, K3 = 539, K4 = 540, K5 = 541, K6 = 542, K7 = 543, K8 = 544, K9 = 545,
A = 546, B = 547, C = 548, D = 549, E = 550, F = 551, G = 552, H = 553, I = 554, J = 555,
K = 556, L = 557, M = 558, N = 559, O = 560, P = 561, Q = 562, R = 563, S = 564, T = 565,
U = 566, V = 567, W = 568, X = 569, Y = 570, Z = 571,
F1 = 572, F2 = 573, F3 = 574, F4 = 575, F5 = 576, F6 = 577,
F7 = 578, F8 = 579, F9 = 580, F10 = 581, F11 = 582, F12 = 583,
F13 = 584, F14 = 585, F15 = 586, F16 = 587, F17 = 588, F18 = 589,
F19 = 590, F20 = 591, F21 = 592, F22 = 593, F23 = 594, F24 = 595,
Apostrophe = 596, Comma = 597, Minus = 598, Period = 599, Slash = 600, Semicolon = 601, Equal = 602, LeftBracket = 603, Backslash = 604, RightBracket = 605, GraveAccent = 606,
CapsLock = 607, ScrollLock = 608, NumLock = 609, PrintScreen = 610, Pause = 611,
Keypad0 = 612, Keypad1 = 613, Keypad2 = 614, Keypad3 = 615, Keypad4 = 616, Keypad5 = 617, Keypad6 = 618, Keypad7 = 619, Keypad8 = 620, Keypad9 = 621,
KeypadDecimal = 622, KeypadDivide = 623, KeypadMultiply = 624, KeypadSubtract = 625, KeypadAdd = 626, KeypadEnter = 627, KeypadEqual = 628,
AppBack = 629,
AppForward = 630,
Oem102 = 631,
GamepadStart = 632, GamepadBack = 633,
GamepadFaceLeft = 634, GamepadFaceRight = 635, GamepadFaceUp = 636, GamepadFaceDown = 637,
GamepadDpadLeft = 638, GamepadDpadRight = 639, GamepadDpadUp = 640, GamepadDpadDown = 641,
GamepadL1 = 642, GamepadR1 = 643,
GamepadL2 = 644, GamepadR2 = 645,
GamepadL3 = 646, GamepadR3 = 647,
GamepadLStickLeft = 648, GamepadLStickRight = 649, GamepadLStickUp = 650, GamepadLStickDown = 651,
GamepadRStickLeft = 652, GamepadRStickRight = 653, GamepadRStickUp = 654, GamepadRStickDown = 655,
MouseLeft = 656, MouseRight = 657, MouseMiddle = 658, MouseX1 = 659, MouseX2 = 660, MouseWheelX = 661, MouseWheelY = 662,
ReservedForModCtrl = 663, ReservedForModShift = 664, ReservedForModAlt = 665, ReservedForModSuper = 666,
NamedKey_END = 667
}
ImGuiKey.NamedKey_COUNT = ImGuiKey.NamedKey_END - ImGuiKey.NamedKey_BEGIN
ImGuiMod_None = 0
ImGuiMod_Ctrl = bitLShift(1, 12)
ImGuiMod_Shift = bitLShift(1, 13)
ImGuiMod_Alt = bitLShift(1, 14)
ImGuiMod_Super = bitLShift(1, 15)
ImGuiMod_Mask_ = 0xF000
--- @enum ImGuiCol
ImGuiCol = {
Text = 0,
TextDisabled = 1,
WindowBg = 2,
ChildBg = 3,
PopupBg = 4,
Border = 5,
BorderShadow = 6,
FrameBg = 7,
FrameBgHovered = 8,
FrameBgActive = 9,
TitleBg = 10,
TitleBgActive = 11,
TitleBgCollapsed = 12,
MenuBarBg = 13,
ScrollbarBg = 14,
ScrollbarGrab = 15,
ScrollbarGrabHovered = 16,
ScrollbarGrabActive = 17,
CheckMark = 18,
CheckboxSelectedBg = 19,
SliderGrab = 20,
SliderGrabActive = 21,
Button = 22,
ButtonHovered = 23,
ButtonActive = 24,
Header = 25,
HeaderHovered = 26,
HeaderActive = 27,
Separator = 28,
SeparatorHovered = 29,
SeparatorActive = 30,
ResizeGrip = 31,
ResizeGripHovered = 32,
ResizeGripActive = 33,
InputTextCursor = 34,
TabHovered = 35,
Tab = 36,
TabSelected = 37,
TabSelectedOverline = 38,
TabDimmed = 39,
TabDimmedSelected = 40,
TabDimmedSelectedOverline = 41,
PlotLines = 42,
PlotLinesHovered = 43,
PlotHistogram = 44,
PlotHistogramHovered = 45,
TableHeaderBg = 46,
TableBorderStrong = 47,
TableBorderLight = 48,
TableRowBg = 49,
TableRowBgAlt = 50,
TextLink = 51,
TextSelectedBg = 52,
TreeLines = 53,
DragDropTarget = 54,
DragDropTargetBg = 55,
UnsavedMarker = 56,
NavCursor = 57,
NavWindowingHighlight = 58,
NavWindowingDimBg = 59,
ModalWindowDimBg = 60,
COUNT = 61
}
--- @enum ImGuiBackendFlags
ImGuiBackendFlags = {
None = 0,
HasGamepad = bitLShift(1, 0),
HasMouseCursors = bitLShift(1, 1),
HasSetMousePos = bitLShift(1, 2),
RendererHasVtxOffset = bitLShift(1, 3),
RendererHasTextures = bitLShift(1, 4),
-- [BETA] Multi-Viewports
RendererHasViewports = bitLShift(1, 10),
PlatformHasViewports = bitLShift(1, 11),
HasMouseHoveredViewport = bitLShift(1, 12),
HasParentViewport = bitLShift(1, 13)
}
--- @enum ImGuiDragDropFlags
ImGuiDragDropFlags = {
None = 0,
SourceNoPreviewTooltip = bitLShift(1, 0),
SourceNoDisableHover = bitLShift(1, 1),
SourceNoHoldToOpenOthers = bitLShift(1, 2),
SourceAllowNullID = bitLShift(1, 3),
SourceExtern = bitLShift(1, 4),
PayloadAutoExpire = bitLShift(1, 5),
PayloadNoCrossContext = bitLShift(1, 6),
PayloadNoCrossProcess = bitLShift(1, 7),
AcceptBeforeDelivery = bitLShift(1, 10),
AcceptNoDrawDefaultRect = bitLShift(1, 11),
AcceptNoPreviewTooltip = bitLShift(1, 12),
AcceptDrawAsHovered = bitLShift(1, 13)
}
ImGuiDragDropFlags.AcceptPeekOnly = bitOr(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)
IM_COL32_R_SHIFT = 0
IM_COL32_G_SHIFT = 8
IM_COL32_B_SHIFT = 16
IM_COL32_A_SHIFT = 24
IM_COL32_A_MASK = 0xFF000000
--- @param R ImU32
--- @param G ImU32
--- @param B ImU32
--- @param A ImU32
IM_COL32 = function(R, G, B, A) return (bitOr(bitLShift(A, IM_COL32_A_SHIFT), bitLShift(B, IM_COL32_B_SHIFT), bitLShift(G, IM_COL32_G_SHIFT), bitLShift(R, IM_COL32_R_SHIFT))) end
IM_COL32_WHITE = IM_COL32(255, 255, 255, 255)
IM_COL32_BLACK = IM_COL32(0, 0, 0, 255)
IM_COL32_BLACK_TRANS = IM_COL32(0, 0, 0, 0)
--- @enum ImGuiPopupFlags
ImGuiPopupFlags = {
None = 0,
MouseButtonLeft = bitLShift(1, 2),
MouseButtonRight = bitLShift(2, 2),
MouseButtonMiddle = bitLShift(3, 2),
NoReopen = bitLShift(1, 5),
NoOpenOverExistingPopup = bitLShift(1, 7),
NoOpenOverItems = bitLShift(1, 8),
AnyPopupId = bitLShift(1, 10),
AnyPopupLevel = bitLShift(1, 11)
}
ImGuiPopupFlags.AnyPopup = bitOr(ImGuiPopupFlags.AnyPopupId, ImGuiPopupFlags.AnyPopupLevel)
ImGuiPopupFlags.MouseButtonShift_ = 2
ImGuiPopupFlags.MouseButtonMask_ = 0x0C
ImGuiPopupFlags.InvalidMask_ = 0x03
--- @enum ImGuiComboFlags
ImGuiComboFlags = {
None = 0,
PopupAlignLeft = bitLShift(1, 0),
HeightSmall = bitLShift(1, 1),
HeightRegular = bitLShift(1, 2),
HeightLarge = bitLShift(1, 3),
HeightLargest = bitLShift(1, 4),
NoArrowButton = bitLShift(1, 5),
NoPreview = bitLShift(1, 6),
WidthFitPreview = bitLShift(1, 7)
}
ImGuiComboFlags.HeightMask_ = bitOr(ImGuiComboFlags.HeightSmall, ImGuiComboFlags.HeightRegular, ImGuiComboFlags.HeightLarge, ImGuiComboFlags.HeightLargest)
ImGuiComboFlags.CustomPreview = bitLShift(1, 20)
--- @enum ImGuiSelectableFlags
ImGuiSelectableFlags = {
None = 0,
NoAutoClosePopups = bitLShift(1, 0),
SpanAllColumns = bitLShift(1, 1),
AllowDoubleClick = bitLShift(1, 2),
Disabled = bitLShift(1, 3),
AllowOverlap = bitLShift(1, 4),
Highlight = bitLShift(1, 5),
SelectOnNav = bitLShift(1, 6),
NoHoldingActiveID = bitLShift(1, 20),
SelectOnClick = bitLShift(1, 22),
SelectOnRelease = bitLShift(1, 23),
SpanAvailWidth = bitLShift(1, 24),
SetNavIdOnHover = bitLShift(1, 25),
NoPadWithHalfSpacing = bitLShift(1, 26),
NoSetKeyOwner = bitLShift(1, 27),
}
--- @enum ImGuiColorEditFlags
ImGuiColorEditFlags = {
None = 0,
NoAlpha = bitLShift(1, 1),
NoPicker = bitLShift(1, 2),
NoOptions = bitLShift(1, 3),
NoSmallPreview = bitLShift(1, 4),
NoInputs = bitLShift(1, 5),
NoTooltip = bitLShift(1, 6),
NoLabel = bitLShift(1, 7),
NoSidePreview = bitLShift(1, 8),
NoDragDrop = bitLShift(1, 9),
NoBorder = bitLShift(1, 10),
NoColorMarkers = bitLShift(1, 11),
-- Alpha preview
AlphaOpaque = bitLShift(1, 12),
AlphaNoBg = bitLShift(1, 13),
AlphaPreviewHalf = bitLShift(1, 14),
-- User Options (right-click on widget to change some of them)
AlphaBar = bitLShift(1, 18),
HDR = bitLShift(1, 19),
DisplayRGB = bitLShift(1, 20),
DisplayHSV = bitLShift(1, 21),
DisplayHex = bitLShift(1, 22),
Uint8 = bitLShift(1, 23),
Float = bitLShift(1, 24),
PickerHueBar = bitLShift(1, 25),
PickerHueWheel = bitLShift(1, 26),
PickerNoRotate = bitLShift(1, 27),
InputRGB = bitLShift(1, 28),
InputHSV = bitLShift(1, 29)
}
ImGuiColorEditFlags.DefaultOptions_ = bitOr(ImGuiColorEditFlags.Uint8, ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.InputRGB, ImGuiColorEditFlags.PickerHueBar)
ImGuiColorEditFlags.AlphaMask_ = bitOr( ImGuiColorEditFlags.NoAlpha, ImGuiColorEditFlags.AlphaOpaque, ImGuiColorEditFlags.AlphaNoBg, ImGuiColorEditFlags.AlphaPreviewHalf )
ImGuiColorEditFlags.DisplayMask_ = bitOr( ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.DisplayHSV, ImGuiColorEditFlags.DisplayHex )
ImGuiColorEditFlags.DataTypeMask_ = bitOr( ImGuiColorEditFlags.Uint8, ImGuiColorEditFlags.Float )
ImGuiColorEditFlags.PickerMask_ = bitOr( ImGuiColorEditFlags.PickerHueWheel, ImGuiColorEditFlags.PickerHueBar )
ImGuiColorEditFlags.InputMask_ = bitOr( ImGuiColorEditFlags.InputRGB, ImGuiColorEditFlags.InputHSV )
--- @enum ImGuiSliderFlags
ImGuiSliderFlags = {
None = 0,
Logarithmic = bitLShift(1, 5),
NoRoundToFormat = bitLShift(1, 6),
NoInput = bitLShift(1, 7),
WrapAround = bitLShift(1, 8),
ClampOnInput = bitLShift(1, 9),
ClampZeroRange = bitLShift(1, 10),
NoSpeedTweaks = bitLShift(1, 11),
ColorMarkers = bitLShift(1, 12),
InvalidMask_ = 0x7000000F,
}
ImGuiSliderFlags.AlwaysClamp = bitOr(ImGuiSliderFlags.ClampOnInput, ImGuiSliderFlags.ClampZeroRange)
ImGuiSliderFlags.Vertical = bitLShift(1, 20)
ImGuiSliderFlags.ReadOnly = bitLShift(1, 21)
--- @class ImGuiWindowClass
--- @field ClassId ImGuiID
--- @field ParentViewportId ImGuiID
--- @field FocusRouteParentWindowId ImGuiID
--- @field ViewportFlagsOverrideSet ImGuiViewportFlags
--- @field ViewportFlagsOverrideClear ImGuiViewportFlags
--- @return ImGuiWindowClass
--- @nodiscard
function ImGuiWindowClass()
return {
ClassId = 0,
ParentViewportId = 0xFFFFFFFF,
FocusRouteParentWindowId = 0,
ViewportFlagsOverrideSet = 0,
ViewportFlagsOverrideClear = 0,
TabItemFlagsOverrideSet = 0,
DockNodeFlagsOverrideSet = 0,
DockingAlwaysTabBar = false,
DockingAllowUnclassed = true
}
end
--- @enum ImGuiInputTextFlags
ImGuiInputTextFlags = {
None = 0,
-- Basic filters (also see ImGuiInputTextFlags.CallbackCharFilter)
CharsDecimal = bitLShift(1, 0),
CharsHexadecimal = bitLShift(1, 1),
CharsScientific = bitLShift(1, 2),
CharsUppercase = bitLShift(1, 3),
CharsNoBlank = bitLShift(1, 4),
-- Inputs
AllowTabInput = bitLShift(1, 5),
EnterReturnsTrue = bitLShift(1, 6),
EscapeClearsAll = bitLShift(1, 7),
CtrlEnterForNewLine = bitLShift(1, 8),
-- Other options
ReadOnly = bitLShift(1, 9),
Password = bitLShift(1, 10),
AlwaysOverwrite = bitLShift(1, 11),
AutoSelectAll = bitLShift(1, 12),
ParseEmptyRefVal = bitLShift(1, 13),
DisplayEmptyRefVal = bitLShift(1, 14),
NoHorizontalScroll = bitLShift(1, 15),
NoUndoRedo = bitLShift(1, 16),
-- Elide display / Alignment
ElideLeft = bitLShift(1, 17),
-- Callback features
CallbackCompletion = bitLShift(1, 18),
CallbackHistory = bitLShift(1, 19),
CallbackAlways = bitLShift(1, 20),
CallbackCharFilter = bitLShift(1, 21),
CallbackResize = bitLShift(1, 22),
CallbackEdit = bitLShift(1, 23),
-- Multi-line Word-Wrapping [BETA]
WordWrap = bitLShift(1, 24),
-- [Internal]
Multiline = bitLShift(1, 26),
TempInput = bitLShift(1, 27),
LocalizeDecimalPoint = bitLShift(1, 28),
}
--- @class ImGuiInputTextCallbackData
--- @return ImGuiInputTextCallbackData
function ImGuiInputTextCallbackData()
return {}
end
--- @alias ImGuiInputTextCallback fun(data: ImGuiInputTextCallbackData)
--- @alias ImGuiMemAllocFunc fun(T: function, start_idx: int, end_idx: int, userdata: any): table
--- @alias ImGuiMemFreeFunc fun(owner: table, field: string, userdata: any)
--- @alias ImDrawCallback fun(parent_list: ImDrawList, cmd: ImDrawCmd)
--- @enum ImGuiTreeNodeFlags
ImGuiTreeNodeFlags = {
None = 0,
Selected = bitLShift(1, 0),
Framed = bitLShift(1, 1),
AllowOverlap = bitLShift(1, 2),
NoTreePushOnOpen = bitLShift(1, 3),
NoAutoOpenOnLog = bitLShift(1, 4),
DefaultOpen = bitLShift(1, 5),
OpenOnDoubleClick = bitLShift(1, 6),
OpenOnArrow = bitLShift(1, 7),
Leaf = bitLShift(1, 8),
Bullet = bitLShift(1, 9),
FramePadding = bitLShift(1, 10),
SpanAvailWidth = bitLShift(1, 11),
SpanFullWidth = bitLShift(1, 12),
SpanLabelWidth = bitLShift(1, 13),
SpanAllColumns = bitLShift(1, 14),
LabelSpanAllColumns = bitLShift(1, 15),
NavLeftJumpsToParent = bitLShift(1, 17),
DrawLinesNone = bitLShift(1, 18),
DrawLinesFull = bitLShift(1, 19),
DrawLinesToNodes = bitLShift(1, 20),
NoNavFocus = bitLShift(1, 27),
ClipLabelForTrailingButton = bitLShift(1, 28),
UpsideDownArrow = bitLShift(1, 29),
}
ImGuiTreeNodeFlags.CollapsingHeader = bitOr(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.NoTreePushOnOpen, ImGuiTreeNodeFlags.NoAutoOpenOnLog)
ImGuiTreeNodeFlags.OpenOnMask_ = bitOr(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.OpenOnArrow)
ImGuiTreeNodeFlags.DrawLinesMask_ = bitOr(ImGuiTreeNodeFlags.DrawLinesNone, ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes)
--- @enum ImGuiTableFlags
ImGuiTableFlags =
{
None = 0,
}
return true -- [Roblox] ModuleScripts must return exactly one value
end
__FILES['imgui_impl_roblox.lua'] = function()
--- ImGui Backend for Roblox
--- - Renderer: exact software rasterizer (1:1 with imgui's triangles) into 256x256 EditableImage tiles at native
--- screen resolution; only tiles whose content changed are redrawn/uploaded (see RenderDrawData).
--- - Platform: UserInputService
--- - Files: an in-memory file system (VFS), pre-filled with the fonts from imgui_impl_roblox_fonts.lua
--- Requires "Allow Mesh / Image APIs" (EditableImage) in game settings.
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local AssetService = game:GetService("AssetService")
local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max
local readu8, readu32, writeu32, readstring = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.readstring
local band, rshift = bit32.band, bit32.rshift
local ImGui_ImplRoblox_GetBackendData
local ImGui_ImplRoblox_UpdateTexture
local ImGui_ImplRoblox_RenderDrawData
local ImGui_ImplRoblox_Shutdown
local KEY_MAP = {} -- Enum.KeyCode -> ImGuiKey
do
local names = {
Return = "Enter", Escape = "Escape", Backspace = "Backspace", Tab = "Tab", Space = "Space", KeypadEnter = "KeypadEnter",
Up = "UpArrow", Down = "DownArrow", Left = "LeftArrow", Right = "RightArrow",
Home = "Home", End = "End", PageUp = "PageUp", PageDown = "PageDown", Insert = "Insert", Delete = "Delete",
LeftControl = "LeftCtrl", RightControl = "RightCtrl", LeftShift = "LeftShift", RightShift = "RightShift",
LeftAlt = "LeftAlt", RightAlt = "RightAlt", LeftSuper = "LeftSuper", RightSuper = "RightSuper",
Quote = "Apostrophe", Comma = "Comma", Minus = "Minus", Period = "Period", Slash = "Slash", Semicolon = "Semicolon",
Equals = "Equal", LeftBracket = "LeftBracket", BackSlash = "Backslash", RightBracket = "RightBracket", Backquote = "GraveAccent",
CapsLock = "CapsLock",
KeypadPeriod = "KeypadDecimal", KeypadDivide = "KeypadDivide", KeypadMultiply = "KeypadMultiply",
KeypadMinus = "KeypadSubtract", KeypadPlus = "KeypadAdd", KeypadEquals = "KeypadEqual",
}
local digits = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }
for i = 0, 9 do
names[digits[i + 1]] = "K" .. i
names["Keypad" .. digits[i + 1]] = "Keypad" .. i
end
for i = 1, 12 do names["F" .. i] = "F" .. i end
for c in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):gmatch(".") do names[c] = c end
for rbx_name, imgui_name in pairs(names) do
KEY_MAP[Enum.KeyCode[rbx_name]] = ImGuiKey[imgui_name]
end
end
-- Roblox has no "text input" event, so characters come from KeyCode.Value (ASCII for printable keys) + a US layout shift table.
local SHIFTED = {
["1"] = "!", ["2"] = "@", ["3"] = "#", ["4"] = "$", ["5"] = "%", ["6"] = "^", ["7"] = "&", ["8"] = "*", ["9"] = "(", ["0"] = ")",
["-"] = "_", ["="] = "+", ["["] = "{", ["]"] = "}", ["\\"] = "|", [";"] = ":", ["'"] = "\"", [","] = "<", ["."] = ">", ["/"] = "?", ["`"] = "~",
}
local MOUSE_BUTTONS = {
[Enum.UserInputType.MouseButton1] = 0, -- ImGuiMouseButton.Left
[Enum.UserInputType.MouseButton2] = 1, -- ImGuiMouseButton.Right
[Enum.UserInputType.MouseButton3] = 2, -- ImGuiMouseButton.Middle
}
--- @return boolean ctrl, boolean shift, boolean alt
local function ImGui_ImplRoblox_UpdateKeyModifiers()
local io = ImGui.GetIO()
local K = Enum.KeyCode
local ctrl = UserInputService:IsKeyDown(K.LeftControl) or UserInputService:IsKeyDown(K.RightControl)
local shift = UserInputService:IsKeyDown(K.LeftShift) or UserInputService:IsKeyDown(K.RightShift)
local alt = UserInputService:IsKeyDown(K.LeftAlt) or UserInputService:IsKeyDown(K.RightAlt)
io:AddKeyEvent(ImGuiMod_Ctrl, ctrl)
io:AddKeyEvent(ImGuiMod_Shift, shift)
io:AddKeyEvent(ImGuiMod_Alt, alt)
io:AddKeyEvent(ImGuiMod_Super, UserInputService:IsKeyDown(K.LeftSuper) or UserInputService:IsKeyDown(K.RightSuper))
return ctrl, shift, alt
end
--- @return table?
function ImGui_ImplRoblox_GetBackendData()
return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil
end
local function ImGui_ImplRoblox_UpdateMonitors(w, h)
local platform_io = ImGui.GetPlatformIO()
platform_io.Monitors:resize(0)
local imgui_monitor = ImGuiPlatformMonitor()
ImVec2_Copy(imgui_monitor.MainSize, ImVec2(w, h))
ImVec2_Copy(imgui_monitor.WorkSize, ImVec2(w, h))
platform_io.Monitors:push_back(imgui_monitor)
end
---------------------------------------------------------
-- PLATFORM DATA & CALLBACKS
---------------------------------------------------------
-- Games can't touch the OS clipboard, so copy/paste only works inside ImGui
local clipboard = ""
local function ImGui_ImplRoblox_PlatformSetClipboardText(ctx, text) clipboard = text end
local function ImGui_ImplRoblox_PlatformGetClipboardText(ctx) return clipboard end
---------------------------------------------------------
-- FILE SYSTEM (in-memory, Roblox has no file access)
---------------------------------------------------------
local VFS = {} -- path -> string of raw bytes
--- Registers a file so ImGui can load it, e.g. ImGui_ImplRoblox.AddFile("fonts/MyFont.ttf", bytes)
--- then io.Fonts:AddFontFromFileTTF("fonts/MyFont.ttf", 16)
local function ImGui_ImplRoblox_AddFile(path, bytes) VFS[path] = bytes end
for path, hex in pairs(IM_INCLUDE("imgui_impl_roblox_fonts.lua")) do
VFS[path] = hex:gsub("%s", ""):gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end)
end
function ImStd.ImFileOpen(filename, mode)
local data = VFS[filename]
return data and { Data = data, Pos = 0 } or nil
end
function ImStd.ImFileClose(f) end
function ImStd.ImFileGetSize(f) return #f.Data end
function ImStd.ImFileRead(f, data, count)
local s, pos = f.Data, f.Pos
count = min(count, #s - pos)
for i = 1, count do data[i] = string.byte(s, pos + i) end
f.Pos = pos + count
return count
end
function ImStd.ImFileLoadToMemory(filename, mode)
local f = ImStd.ImFileOpen(filename, mode)
if not f or #f.Data == 0 then return end
local file_data = {}
local size = ImStd.ImFileRead(f, file_data, #f.Data)
return file_data, size
end
---------------------------------------------------------
-- TEXTURE MANAGEMENT
---------------------------------------------------------
-- Copies a region of ImTextureData pixels (1-based byte table) into our RGBA8 buffer
local function CopyTexturePixels(tex, dst, x, y, w, h)
local bpp, tex_w = tex.BytesPerPixel, tex.Width
for row = 0, h - 1 do
local src, src_base = tex:GetPixelsAt(x, y + row)
local dst_off = ((y + row) * tex_w + x) * 4
if bpp == 4 then
for i = 0, w - 1 do
local s = src_base + i * 4
writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216)
end
else -- Alpha8: white with alpha
for i = 0, w - 1 do
writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216)
end
end
end
end
function ImGui_ImplRoblox_UpdateTexture(tex)
local bd = ImGui_ImplRoblox_GetBackendData()
if tex.Status == ImTextureStatus.WantCreate then
local t = { Buffer = buffer.create(tex.Width * tex.Height * 4), Width = tex.Width, Height = tex.Height }
CopyTexturePixels(tex, t.Buffer, 0, 0, tex.Width, tex.Height)
bd.TextureCount = bd.TextureCount + 1
bd.Textures[bd.TextureCount] = t
tex.BackendUserData = bd.TextureCount
tex:SetTexID(bd.TextureCount)
tex:SetStatus(ImTextureStatus.OK)
elseif tex.Status == ImTextureStatus.WantUpdates then
local t = bd.Textures[tex.BackendUserData]
IM_ASSERT(t ~= nil)
for _, r in tex.Updates:iter() do
CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h)
end
tex:SetStatus(ImTextureStatus.OK)
elseif tex.Status == ImTextureStatus.WantDestroy then
if tex.BackendUserData then
bd.Textures[tex.BackendUserData] = nil
tex.BackendUserData = nil
end
tex:SetTexID(ImTextureID_Invalid)
tex:SetStatus(ImTextureStatus.Destroyed)
end
end
---------------------------------------------------------
-- RENDERING (software rasterizer into tile buffers)
---------------------------------------------------------
-- Buffer layout: 4 bytes per pixel, R G B A, row-major, 0-based offsets. ImU32 colours are already R | G<<8 | B<<16 | A<<24.
-- Blending is non-premultiplied "over" with a transparent (alpha 0) background, so the game stays visible behind ImGui.
local buf, buf_w -- buffer/width of the tile being drawn
local TILE_SIZE -- Vector2, set below
-- Blends one pixel (r, g, b, a are 0..255). One u32 read/write, one division in the general case.
-- FillSpan below inlines the same math with per-span constants - keep the two in sync.
local function BlendPixel(o, r, g, b, a)
if a >= 255 then
writeu32(buf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080)
return
end
if a <= 0 then return end
local d = readu32(buf, o)
local da = rshift(d, 24)
if da == 0 then
writeu32(buf, o, floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216)
return
end
local sa = a / 255
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if da == 255 then
local ns = 1 - sa
writeu32(buf, o, floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 + floor(b * sa + db * ns + 0.5) * 65536 + 4278190080)
else
local k = da * ((1 - sa) / 255)
local oa = sa + k
local inv = 1 / oa
writeu32(buf, o, 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
-- Fills pixels [x0, x1) of row y with one colour
local function FillSpan(y, x0, x1, r, g, b, a)
if a <= 0 then return end
local o0 = (y * buf_w + x0) * 4
local o1 = o0 + (x1 - x0 - 1) * 4
if a >= 255 then
local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080
for o = o0, o1, 4 do writeu32(buf, o, packed) end
return
end
local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216
local sa = a / 255
local ns = 1 - sa
local c1 = ns / 255
local rs, gs, bs = r * sa, g * sa, b * sa
local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination
for o = o0, o1, 4 do
local d = readu32(buf, o)
local da = rshift(d, 24)
if d == last_d then
writeu32(buf, o, last_v)
elseif da == 0 then
writeu32(buf, o, packed0)
else
last_d = d
local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255)
if da == 255 then
last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256 + floor(bs + db * ns + 0.5) * 65536 + 4278190080
else
local k = da * c1
local oa = sa + k
local inv = 1 / oa
last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256
+ floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216
end
writeu32(buf, o, last_v)
end
end
end
local function UnpackColor(col)
return col % 256, floor(col / 256) % 256, floor(col / 65536) % 256, floor(col / 16777216) % 256
end
-- Nearest texel at (u, v) as r, g, b, a (0..255)
local function SampleTexture(t, u, v)
local tw, th = t.Width, t.Height
local tx, ty = floor(u * tw), floor(v * 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 o = (ty * tw + tx) * 4
local tb = t.Buffer
return readu8(tb, o), readu8(tb, o + 1), readu8(tb, o + 2), readu8(tb, o + 3)
end
-- Axis aligned, single colour quad (rects, glyphs, images). Pixel centers inside [x0, x1) x [y0, y1) are drawn.
local function DrawRect(x0, y0, x1, y1, u0, v0, u1, v1, col, t, cx0, cy0, cx1, cy1)
local r, g, b, a = UnpackColor(col)
if a == 0 then return end
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)
if px0 >= px1 or py0 >= py1 then return end
if not t or (u0 == u1 and v0 == v1) then
if t then
local tr, tg, tb, ta = SampleTexture(t, u0, v0)
r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
end
if a <= 0 then return end
-- Rows of a flat rect usually blend over identical rows: when this row's destination equals the previous
-- row's (exact string compare), the result is identical too, so memcpy the previous row's result.
local len = (px1 - px0) * 4
local prev_dst, prev_o = nil, 0
for y = py0, py1 - 1 do
local o = (y * buf_w + px0) * 4
if a >= 255 then
if prev_dst then buffer.copy(buf, o, buf, prev_o, len) else FillSpan(y, px0, px1, r, g, b, a); prev_dst = true end
else
local dst = readstring(buf, o, len)
if dst == prev_dst then
buffer.copy(buf, o, buf, prev_o, len)
else
FillSpan(y, px0, px1, r, g, b, a)
prev_dst = dst
end
end
prev_o = o
end
return
end
local du, dv = (u1 - u0) / (x1 - x0), (v1 - v0) / (y1 - y0)
local tw, th, tbuf = t.Width, t.Height, t.Buffer
local r255, g255, b255, a255 = r / 255, g / 255, b / 255, a / 255
for y = py0, py1 - 1 do
local ty = floor((v0 + (y + 0.5 - y0) * dv) * th)
if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end
local trow = ty * tw
local o = (y * buf_w + px0) * 4
for x = px0, px1 - 1 do
local tx = floor((u0 + (x + 0.5 - x0) * du) * tw)
if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end
local to = (trow + tx) * 4
local ta = readu8(tbuf, to + 3)
if ta > 0 then
BlendPixel(o, readu8(tbuf, to) * r255, readu8(tbuf, to + 1) * g255, readu8(tbuf, to + 2) * b255, ta * a255)
end
o = o + 4
end
end
end
-- Generic triangle: per-vertex colour + uv, top-left fill rule, clipped to [cx0, cx1) x [cy0, cy1)
local function DrawTriangle(va, vb, vc, t, cx0, cy0, cx1, cy1, ox, oy)
local x0, y0 = va[1][1] - ox, va[1][2] - oy
local x1, y1 = vb[1][1] - ox, vb[1][2] - oy
local x2, y2 = vc[1][1] - ox, vc[1][2] - oy
local area = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0)
if area == 0 then return end
if area < 0 then -- make the winding consistent so "inside" means all edge functions >= 0
vb, vc = vc, vb
x1, y1, x2, y2 = x2, y2, x1, y1
area = -area
end
local minx, maxx = max(floor(min(x0, x1, x2)), cx0), min(ceil(max(x0, x1, x2)), cx1 - 1)
local miny, maxy = max(floor(min(y0, y1, y2)), cy0), min(ceil(max(y0, y1, y2)), cy1 - 1)
if minx > maxx or miny > maxy then return end
-- Edge functions E(p) = A*px + B*py + C, w0 is opposite va, w1 opposite vb, w2 opposite vc
local A0, B0 = y1 - y2, x2 - x1; local C0 = -(A0 * x1 + B0 * y1)
local A1, B1 = y2 - y0, x0 - x2; local C1 = -(A1 * x2 + B1 * y2)
local A2, B2 = y0 - y1, x1 - x0; local C2 = -(A2 * x0 + B2 * y0)
local 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 inv = 1 / area
local ra, ga, ba, aa = UnpackColor(va[3])
local rb, gb, bb, ab = UnpackColor(vb[3])
local rc, gc, bc, ac = UnpackColor(vc[3])
local ua, vva, ub, vvb, uc, vvc = va[2][1], va[2][2], vb[2][1], vb[2][2], vc[2][1], vc[2][2]
local textured = t and not (ua == ub and ua == uc and vva == vvb and vva == vvc)
if t and not textured then -- constant uv (e.g. the atlas white pixel): fold the texel into the vertex colours
local tr, tg, tb, ta = SampleTexture(t, ua, vva)
ra, ga, ba, aa = ra * tr / 255, ga * tg / 255, ba * tb / 255, aa * ta / 255
rb, gb, bb, ab = rb * tr / 255, gb * tg / 255, bb * tb / 255, ab * ta / 255
rc, gc, bc, ac = rc * tr / 255, gc * tg / 255, bc * tb / 255, ac * ta / 255
end
local flat = not textured and ra == rb and ra == rc and ga == gb and ga == gc and ba == bb and ba == bc and aa == ab and aa == ac
if flat and aa <= 0 then return end
for y = miny, maxy do
local py = y + 0.5
-- Narrow the x range of this row using the edges (expanded by one pixel, exact test below)
local xl, xr = minx, maxx
local e0, e1, e2 = B0 * py + C0, B1 * py + C1, B2 * py + C2
if A0 ~= 0 then local xe = -e0 / A0 - 0.5; if A0 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end
if A1 ~= 0 then local xe = -e1 / A1 - 0.5; if A1 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end
if A2 ~= 0 then local xe = -e2 / A2 - 0.5; if A2 > 0 then xl = max(xl, floor(xe)) else xr = min(xr, ceil(xe)) end end
local row = y * buf_w
for x = xl, xr do
local px = x + 0.5
local w0, w1, w2 = A0 * px + e0, A1 * px + e1, A2 * px + e2
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
local o = (row + x) * 4
if flat then
BlendPixel(o, ra, ga, ba, aa)
else
w0, w1, w2 = w0 * inv, w1 * inv, w2 * inv
local r = w0 * ra + w1 * rb + w2 * rc
local g = w0 * ga + w1 * gb + w2 * gc
local b = w0 * ba + w1 * bb + w2 * bc
local a = w0 * aa + w1 * ab + w2 * ac
if textured then
local tr, tg, tb, ta = SampleTexture(t, w0 * ua + w1 * ub + w2 * uc, w0 * vva + w1 * vvb + w2 * vvc)
r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255
end
BlendPixel(o, r, g, b, a)
end
end
end
end
end
-- Quads emitted by PrimRect/PrimRectUV/RenderText use indices (a, b, c, a, c, d) with a=TL, b=TR, c=BR, d=BL.
-- When such a quad is axis aligned with one colour it is drawn with the much cheaper DrawRect.
local function TryDrawRect(va, vb, vc, vd, t, cx0, cy0, cx1, cy1, ox, oy)
local pa, pb, pc, pd = va[1], vb[1], vc[1], vd[1]
if not (pa[2] == pb[2] and pb[1] == pc[1] and pc[2] == pd[2] and pd[1] == pa[1] and pa[1] < pb[1] and pa[2] < pd[2]) then return false end
local col = va[3]
if vb[3] ~= col or vc[3] ~= col or vd[3] ~= col then return false end
local ta, tb, tc, td = va[2], vb[2], vc[2], vd[2]
if not (tb[1] == tc[1] and tb[2] == ta[2] and td[1] == ta[1] and td[2] == tc[2]) then return false end
DrawRect(pa[1] - ox, pa[2] - oy, pc[1] - ox, pc[2] - oy, ta[1], ta[2], tc[1], tc[2], col, t, cx0, cy0, cx1, cy1)
return true
end
-- Tiles: the screen is covered by TILE x TILE EditableImages (one ImageLabel each). Every frame each primitive
-- (triangle, or axis aligned quad) is hashed into the tiles it touches; only tiles whose hash changed are
-- re-rasterized and uploaded. Static UI therefore costs ~nothing to draw, and the result is pixel-identical to a
-- full redraw (the hash covers everything that affects a tile's pixels: geometry, uv, colour, texture, clip, order).
local TILE = 256
TILE_SIZE = Vector2.new(TILE, TILE)
local P1, P2 = 2147483647, 2147483629 -- two independent 31 bit hashes per tile (collision odds ~2^-62)
-- Primitive arrays (reused between frames, no per-frame allocation)
local pr_a, pr_b, pr_c, pr_d, pr_t = {}, {}, {}, {}, {} -- vertices (pr_d == false -> triangle), texture
local pr_cx0, pr_cy0, pr_cx1, pr_cy1 = {}, {}, {}, {} -- clip (screen pixels)
local function HashVertex(h1, h2, v)
local p, u, c = v[1], v[2], v[3]
local x, y = p[1], p[2]
local uv = u[1] * 8192 + u[2]
h1 = (h1 * 48271 + x * 4096 + y) % P1
h1 = (h1 * 48271 + uv * 4096) % P1
h1 = (h1 * 48271 + c) % P1
h2 = (h2 * 16807 + y * 4093 + x) % P2
h2 = (h2 * 16807 + uv * 65521) % P2
h2 = (h2 * 16807 + c) % P2
return h1, h2
end
local function GetTile(bd, index, tx, ty)
local tile = bd.Tiles[index]
if tile then return tile end
local img = AssetService:CreateEditableImage({ Size = Vector2.new(TILE, TILE) })
assert(img, "imgui_impl_roblox: EditableImage memory budget exceeded")
local label = Instance.new("ImageLabel")
label.Name = "Tile" .. index
label.BackgroundTransparency = 1
label.BorderSizePixel = 0
label.Size = UDim2.fromOffset(TILE, TILE)
label.Position = UDim2.fromOffset(tx * TILE, ty * TILE)
label.ResampleMode = Enum.ResamplerMode.Pixelated
label.ImageContent = Content.fromObject(img)
label.Visible = false
label.Parent = bd.Gui
tile = { Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4), H1 = -1, H2 = -1, Visible = false }
bd.Tiles[index] = tile
return tile
end
local function DestroyTiles(bd)
for _, tile in pairs(bd.Tiles) do tile.Label:Destroy(); tile.Image:Destroy() end
bd.Tiles = {}
end
function ImGui_ImplRoblox_RenderDrawData(draw_data)
local bd = ImGui_ImplRoblox_GetBackendData()
if draw_data.Textures ~= nil then
for _, tex in draw_data.Textures:iter() do
if tex.Status ~= ImTextureStatus.OK then
ImGui_ImplRoblox_UpdateTexture(tex)
bd.ForceRedraw = true -- texture contents changed: tiles sampling it must be redrawn
end
end
end
local sw, sh = floor(draw_data.DisplaySize.x), floor(draw_data.DisplaySize.y)
if sw <= 0 or sh <= 0 then return end
local cols, rows = ceil(sw / TILE), ceil(sh / TILE)
if cols ~= bd.TileCols or rows ~= bd.TileRows then
DestroyTiles(bd)
bd.TileCols, bd.TileRows = cols, rows
end
local ntiles = cols * rows
local ox, oy = draw_data.DisplayPos.x, draw_data.DisplayPos.y
-- Per tile: hashes and the list of primitives touching it
local th1, th2, tn, tl = bd.TH1, bd.TH2, bd.TN, bd.TL
for t = 0, ntiles - 1 do
th1[t], th2[t], tn[t] = 0, 0, 0
if not tl[t] then tl[t] = {} end
end
-- Pass 1: collect primitives, hash them into tiles
local n = 0
for _, draw_list in draw_data.CmdLists:iter() do
local vtx, idx = draw_list.VtxBuffer.Data, draw_list.IdxBuffer.Data
for _, pcmd in draw_list.CmdBuffer:iter() do
if pcmd.UserCallback ~= nil then
pcmd.UserCallback(draw_list, pcmd)
elseif pcmd.ElemCount > 0 then
local clip = pcmd.ClipRect
local cx0, cy0 = max(floor(clip.x - ox), 0), max(floor(clip.y - oy), 0)
local cx1, cy1 = min(floor(clip.z - ox), sw), min(floor(clip.w - oy), sh)
if cx1 > cx0 and cy1 > cy0 then
local tex_id = pcmd:GetTexID()
local t = bd.Textures[tex_id]
local ch1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1
local ch2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2
local vo = pcmd.VtxOffset
local i, last = pcmd.IdxOffset + 1, pcmd.IdxOffset + pcmd.ElemCount
while i <= last do
local ia, ic = idx[i], idx[i + 2]
local va, vb, vc = vtx[vo + ia], vtx[vo + idx[i + 1]], vtx[vo + ic]
local vd = false
local pa, pb, pc = va[1], vb[1], vc[1]
local bx0, by0, bx1, by1
if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then
local d = vtx[vo + idx[i + 5]]
local pd = d[1]
-- axis aligned quad (TL, TR, BR, BL) with one colour and a matching uv rect
if pa[2] == pb[2] and pb[1] == pc[1] and pc[2] == pd[2] and pd[1] == pa[1] and pa[1] < pb[1] and pa[2] < pd[2] then
local col = va[3]
local ta, tb, tc, td = va[2], vb[2], vc[2], d[2]
if vb[3] == col and vc[3] == col and d[3] == col
and tb[1] == tc[1] and tb[2] == ta[2] and td[1] == ta[1] and td[2] == tc[2] then
vd = d
bx0, by0 = ceil(pa[1] - ox - 0.5), ceil(pa[2] - oy - 0.5)
bx1, by1 = ceil(pc[1] - ox - 0.5), ceil(pc[2] - oy - 0.5)
end
end
end
if vd then
i = i + 6
else
bx0, by0 = floor(min(pa[1], pb[1], pc[1]) - ox), floor(min(pa[2], pb[2], pc[2]) - oy)
bx1, by1 = ceil(max(pa[1], pb[1], pc[1]) - ox) + 1, ceil(max(pa[2], pb[2], pc[2]) - oy) + 1
i = i + 3
end
if bx0 < cx0 then bx0 = cx0 end
if by0 < cy0 then by0 = cy0 end
if bx1 > cx1 then bx1 = cx1 end
if by1 > cy1 then by1 = cy1 end
if bx0 < bx1 and by0 < by1 then
n = n + 1
pr_a[n], pr_b[n], pr_c[n], pr_d[n], pr_t[n] = va, vb, vc, vd, t
pr_cx0[n], pr_cy0[n], pr_cx1[n], pr_cy1[n] = cx0, cy0, cx1, cy1
local h1, h2 = HashVertex(ch1, ch2, va)
h1, h2 = HashVertex(h1, h2, vb)
h1, h2 = HashVertex(h1, h2, vc)
if vd then h1, h2 = HashVertex(h1, h2, vd) end
for ty = floor(by0 / TILE), floor((by1 - 1) / TILE) do
for tx = floor(bx0 / TILE), floor((bx1 - 1) / TILE) do
local ti = ty * cols + tx
local k = tn[ti] + 1
tn[ti] = k
tl[ti][k] = n
th1[ti] = (th1[ti] * 48271 + h1) % P1
th2[ti] = (th2[ti] * 16807 + h2 + k) % P2
end
end
end
end
end
end
end
end
-- Pass 2: redraw + upload changed tiles
local force = bd.ForceRedraw
bd.ForceRedraw = false
for ty = 0, rows - 1 do
for tx = 0, cols - 1 do
local ti = ty * cols + tx
local count = tn[ti]
local tile = bd.Tiles[ti]
if count == 0 then
if tile and tile.Visible then
tile.Visible = false
tile.Label.Visible = false
tile.H1 = -1
end
else
tile = tile or GetTile(bd, ti, tx, ty)
if force or tile.H1 ~= th1[ti] or tile.H2 ~= th2[ti] then
tile.H1, tile.H2 = th1[ti], th2[ti]
local x0, y0 = tx * TILE, ty * TILE
local x1, y1 = x0 + TILE, y0 + TILE
buf, buf_w = tile.Buffer, TILE
buffer.fill(buf, 0, 0)
local list = tl[ti]
local tox, toy = ox + x0, oy + y0
for k = 1, count do
local p = list[k]
local cx0, cy0 = max(pr_cx0[p], x0) - x0, max(pr_cy0[p], y0) - y0
local cx1, cy1 = min(pr_cx1[p], x1) - x0, min(pr_cy1[p], y1) - y0
local va, vc, vd = pr_a[p], pr_c[p], pr_d[p]
if vd then
local pa, pc, ta, tc = va[1], vc[1], va[2], vc[2]
DrawRect(pa[1] - tox, pa[2] - toy, pc[1] - tox, pc[2] - toy, ta[1], ta[2], tc[1], tc[2], va[3], pr_t[p], cx0, cy0, cx1, cy1)
else
DrawTriangle(va, pr_b[p], vc, pr_t[p], cx0, cy0, cx1, cy1, tox, toy)
end
end
tile.Image:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf)
end
if not tile.Visible then
tile.Visible = true
tile.Label.Visible = true
end
end
end
end
-- drop references so old vertex tables can be collected
for k = n + 1, bd.LastPrimCount do pr_a[k], pr_b[k], pr_c[k], pr_d[k], pr_t[k] = nil, nil, nil, nil, nil end
bd.LastPrimCount = n
end
---------------------------------------------------------
-- CORE LIFECYCLE
---------------------------------------------------------
--- @param parent Instance? # where the ScreenGui goes, defaults to the local player's PlayerGui
function ImGui_ImplRoblox_Init(parent)
local io = ImGui.GetIO()
local gui = Instance.new("ScreenGui")
gui.Name = "ImGui"
gui.IgnoreGuiInset = true -- so GetMouseLocation() and the tiles share the same origin
gui.ResetOnSpawn = false
gui.DisplayOrder = 1000
gui.Parent = parent or Players.LocalPlayer:WaitForChild("PlayerGui")
local bd = {
Time = os.clock(), Gui = gui, Connections = {},
Textures = {}, TextureCount = 0, MouseX = -1, MouseY = -1,
Tiles = {}, TileCols = 0, TileRows = 0, TH1 = {}, TH2 = {}, TN = {}, TL = {}, LastPrimCount = 0, ForceRedraw = true,
}
io.BackendPlatformUserData = bd
io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.RendererHasTextures, ImGuiBackendFlags.RendererHasVtxOffset)
local platform_io = ImGui.GetPlatformIO()
platform_io.Platform_SetClipboardTextFn = ImGui_ImplRoblox_PlatformSetClipboardText
platform_io.Platform_GetClipboardTextFn = ImGui_ImplRoblox_PlatformGetClipboardText
local screen = gui.AbsoluteSize
ImGui_ImplRoblox_UpdateMonitors(screen.X, screen.Y)
local function connect(signal, fn) table.insert(bd.Connections, signal:Connect(fn)) end
connect(UserInputService.InputBegan, function(input, game_processed)
local io = ImGui.GetIO()
local button = MOUSE_BUTTONS[input.UserInputType]
if button then
io:AddMouseSourceEvent(ImGuiMouseSource.Mouse)
io:AddMouseButtonEvent(button, true)
elseif input.UserInputType == Enum.UserInputType.Keyboard and not game_processed then
local ctrl, shift, alt = ImGui_ImplRoblox_UpdateKeyModifiers()
local key = KEY_MAP[input.KeyCode]
if key then io:AddKeyEvent(key, true) end
-- Text: printable ASCII keys, skipped while Ctrl/Alt are held (shortcuts)
local v = input.KeyCode.Value
if v >= 32 and v < 127 and not (ctrl or alt) then
local c = string.char(v)
if shift then c = SHIFTED[c] or c:upper() end
io:AddInputCharacter(string.byte(c))
end
end
end)
connect(UserInputService.InputEnded, function(input, game_processed)
local io = ImGui.GetIO()
local button = MOUSE_BUTTONS[input.UserInputType]
if button then
io:AddMouseButtonEvent(button, false)
elseif input.UserInputType == Enum.UserInputType.Keyboard then
ImGui_ImplRoblox_UpdateKeyModifiers()
local key = KEY_MAP[input.KeyCode]
if key then io:AddKeyEvent(key, false) end
end
end)
connect(UserInputService.InputChanged, function(input, game_processed)
if input.UserInputType == Enum.UserInputType.MouseWheel then
ImGui.GetIO():AddMouseWheelEvent(0, input.Position.Z)
end
end)
connect(UserInputService.WindowFocused, function() ImGui.GetIO():AddFocusEvent(true) end)
connect(UserInputService.WindowFocusReleased, function() ImGui.GetIO():AddFocusEvent(false) end)
end
function ImGui_ImplRoblox_Shutdown()
local io = ImGui.GetIO()
local bd = ImGui_ImplRoblox_GetBackendData()
for _, c in ipairs(bd.Connections) do c:Disconnect() end
DestroyTiles(bd)
bd.Gui:Destroy()
io.BackendPlatformUserData = nil
io.BackendFlags = bit32.band(io.BackendFlags, bit32.bnot(bit32.bor(
ImGuiBackendFlags.RendererHasTextures,
ImGuiBackendFlags.RendererHasVtxOffset
)))
end
function ImGui_ImplRoblox_NewFrame()
local io = ImGui.GetIO()
local bd = ImGui_ImplRoblox_GetBackendData()
local screen = bd.Gui.AbsoluteSize
local w, h = floor(screen.X), floor(screen.Y)
if w ~= bd.ScreenW or h ~= bd.ScreenH then
bd.ScreenW, bd.ScreenH = w, h
ImGui_ImplRoblox_UpdateMonitors(w, h)
end
ImVec2_CopyV(io.DisplaySize, w, h)
local current_time = os.clock()
io.DeltaTime = (current_time > bd.Time) and (current_time - bd.Time) or (1.0 / 60.0)
bd.Time = current_time
local m = UserInputService:GetMouseLocation()
if m.X ~= bd.MouseX or m.Y ~= bd.MouseY then
bd.MouseX, bd.MouseY = m.X, m.Y
io:AddMouseSourceEvent(ImGuiMouseSource.Mouse)
io:AddMousePosEvent(m.X, m.Y)
end
end
ImGui_ImplRoblox = {
Init = ImGui_ImplRoblox_Init,
Shutdown = ImGui_ImplRoblox_Shutdown,
NewFrame = ImGui_ImplRoblox_NewFrame,
RenderDrawData = ImGui_ImplRoblox_RenderDrawData,
AddFile = ImGui_ImplRoblox_AddFile,
}
return true -- [Roblox] ModuleScripts must return exactly one value
end
__FILES['imgui_impl_roblox_fonts.lua'] = function()
-- [Roblox] Embedded copies of resource/fonts/*.ttf (Roblox can't read files). Generated: hex encoded bytes.
-- Add your own fonts the same way, or at runtime with ImGui_ImplRoblox.AddFile(path, bytes).
return {
["resource/fonts/ProggyClean.ttf"] = [[
00010000000c0080000300404f532f3288eb7490000001480000004e636d617002122375000003a0000001526376742000000000000004fc00000002676c796612af8956000007040000928068656164
d79166d3000000cc0000003668686561084201c30000010400000024686d74788a007e8000000198000002066c6f63618c73b0d800000500000002046d61787001ae00da00000128000000206e616d65
2559bb96000099840000019e706f7374a6ac83ef00009b24000005d27072657069020112000004f40000000800010000000100003c55e9d55f0f3cf50003080000000000b767778400000000bd92a6d7
0000fe80038005000000000300020000000000000001000004c0fe40000003800000000003800001000000000000000000000000000000020001000001010090002400000000000200080040000a0000
00760008000000000000038001900005000002bc028a0000008f02bc028a000001c50032020000000000040900000000000000000000000000000000000000000000416c74730040000020ac08000000
0000050001800000038000000380038003800380038003800380038003800380038003800380038003800380038003800380038003800380038003800380038003800380038003800380038003800380
0180010000000080000000800180010001000080008000800080010000800080008000800080008000800080008000800080018000800000008000800080000000800080008000800080008000800080
0100008000800080000000800080008000800080008000000080000000000080000000800100008001000080000001000080008000800080008000800080008001000080008001000000008000800080
0080008000800100008000800000008000800080008001800080000003800080038001000080010000800080008000800080008000800000038000800380038001800100010000800080008000000080
0000008000800000038000800000038001800080008000000000018000800100000000800080008003800000000000800080008000800180000000800100018000800080008000800080000000800080
0080008000800080008000000080008000800080008001000100010001000000008000800080008000800080008000800080008000800080000000800000008000800080008000800080000000800080
00800080008001000100010001000080008000800080008000800080008000800080008000800080008000800080000000000003000000000000001c000100000000004c000300010000001c00040030
00000008000800020000007f00ff20acffff00000000008120acffff00010001dfd500010000000000000000000001060000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000810000000000000000000000000000000000000000000000000000000000000000000000000000b100018db801ff8500000000
000000c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600c600f4011c019e02140288
02fc03140358039c03de041404320450046204a20516056605bc0612067406d60738077e07ec084e086c089608d00910094a09880a160a800b040b560bc80c2e0c820cea0d5e0da40dea0e500e960f28
0fb01012107410e0115211b61204126e12c4134c13ac13f6145814ae14ea1540158015a615b81612167e16c61734178e17e0185618ba18ee1936199619d41a481a9c1af01b5c1bc81c041c4c1c961cea
1d2a1d921dd21e401e8e1ee01f241f761fa61fa620102010202e208a20b220c821142174219821ee22622286230c230c238023802380239823b023d82400244a2468249024ae25062560258225f825f8
265826aa26aa26d82740279a280a286828a8290e292029b829f82a362a602a602b022b2a2b5e2bac2be62c202c342c9a2d282d5c2d782daa2de82e262ea62f262fb62ff4305e30c8313e31b4321e329e
331e338233ee345c34ce353a358635d43626367236e6377637d8383a38a63912397439ae3a2e3a9a3b063b7c3be83c3a3c963d223d863dec3e563ec63f2a3f9a4012406a40d0413641a242084240427a
42b842f0436243cc442a448a44ee455845b645e2465446b44714477a47da485448c6494000240000fe800380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043
0047004b004f00530057005b005f00630067006b006f00730077007b007f00830087008b008f000011353315313533153135331531353315313533153135331531353315053533152135331505353315
2135331505353315213533150535331521353315053533152135331505353315213533150535331521353315053533152135331505353315213533150535331521353315053533152135331505353315
31353315313533153135331531353315313533153135331580808080808080fc8080028080fc8080028080fc8080028080fc8080028080fc8080028080fc8080028080fc8080028080fc8080028080fc
8080028080fc8080028080fc8080028080fc8080808080808080048080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080
80808080808080808080808080808080808080808080808080808080808080800007018000000200040000030007000b000f00130017001b000001353315073533150735331507353315073533150735
33150335331501808080808080808080808080808003808080808080808080808080808080808080ff0080800006010003000280048000030007000b000f001300170000013533153335331505353315
3335331505353315333533150100808080fe80808080fe8080808004008080808080808080808080808080000018000000000380040000030007000b000f00130017001b001f00230027002b002f0033
0037003b003f00430047004b004f00530057005b005f00000135331533353315053533153335331505353315313533153135331531353315313533153135331505353315333533150535331533353315
053533153135331531353315313533153135331531353315053533153335331505353315333533150180808080fe80808080fd80808080808080fd80808080fe80808080fd80808080808080fd808080
80fe808080800380808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000150080ff800300040000030007000b
000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00530000013533150535331531353315313533153135331505353315333533150535331533353315053533153135
331531353315053533153335331505353315333533150535331531353315313533153135331505353315018080ff0080808080fd80808080fe80808080ff00808080ff00808080fe80808080fd808080
8080ff0080038080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000000014000000000380040000030007000b000f0013
0017001b001f00230027002b002f00330037003b003f00430047004b004f0000133533152135331505353315333533153335331505353315333533153335331505353315333533150735331533353315
05353315333533153335331505353315333533153335331505353315213533158080018080fd008080808080fd808080808080fe0080808080808080fe008080808080fd808080808080fd0080018080
038080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000000014008000000380040000030007000b000f00130017001b001f0023
0027002b002f00330037003b003f00430047004b004f00000135331531353315053533152135331505353315213533150535331531353315213533150535331521353315333533150535331521353315
05353315213533150535331531353315313533153335331501008080fe8080010080fe0080010080fe808080010080fd00800100808080fd0080018080fd8080018080fe008080808080038080808080
80808080808080808080808080808080808080808080808080808080808080808080808080808080808080000003018003000200048000030007000b0000013533150735331507353315018080808080
800400808080808080808000000b0100ff000280048000030007000b000f00130017001b001f00230027002b0000013533150535331507353315053533150735331507353315073533150735331d0135
33150735331d01353315020080ff00808080ff00808080808080808080808080800400808080808080808080808080808080808080808080808080808080808080808000000b0100ff00028004800003
0007000b000f00130017001b001f00230027002b00000135331d013533150735331d01353315073533150735331507353315073533150535331507353315053533150100808080808080808080808080
80ff00808080ff00800400808080808080808080808080808080808080808080808080808080808080808000000b008000800300030000030007000b000f00130017001b001f00230027002b00000135
331505353315333533153335331505353315313533153135331505353315333533153335331505353315018080fe808080808080fe00808080fe008080808080fe808002808080808080808080808080
808080808080808080808080808080000009008000800300030000030007000b000f00130017001b001f0023000001353315073533150535331531353315313533153135331531353315053533150735
33150180808080fe808080808080fe808080800280808080808080808080808080808080808080808080800000040080ff000180010000030007000b000f000025353315073533150735331505353315
01008080808080ff008080808080808080808080808000000005008001800300020000030007000b000f0013000013353315313533153135331531353315313533158080808080800180808080808080
80808080000201000000018001000003000700002535331507353315010080808080808080808000000a0080ff800300048000030007000b000f00130017001b001f0023002700000135331507353315
05353315073533150535331507353315053533150735331505353315073533150280808080ff00808080ff00808080ff00808080ff008080800400808080808080808080808080808080808080808080
80808080808080800014008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00000135331531353315313533150535331521353315
0535331521353315053533153335331533353315053533153335331533353315053533152135331505353315213533150535331531353315313533150100808080fe0080018080fd8080018080fd8080
80808080fd808080808080fd8080018080fd8080018080fe0080808003808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080000000
000e008000000300040000030007000b000f00130017001b001f00230027002b002f00330037000001353315053533153135331505353315333533150735331507353315073533150735331505353315
31353315313533153135331531353315018080ff008080fe808080808080808080808080fe80808080808003808080808080808080808080808080808080808080808080808080808080808080808080
000f008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b00000135331531353315313533150535331521353315073533150535331505353315053533150535
331507353315313533153135331531353315313533150100808080fe00800180808080ff0080ff0080ff0080ff0080808080808080038080808080808080808080808080808080808080808080808080
808080808080808080808080000f008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b00000135331531353315313533150535331521353315073533150535
33153135331d013533150735331505353315213533150535331531353315313533150100808080fe00800180808080fe808080808080fd8080018080fe00808080038080808080808080808080808080
8080808080808080808080808080808080808080808080800011008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043000001353315053533153135
33150535331533353315053533152135331505353315213533150535331531353315313533153135331531353315313533150535331507353315028080ff008080fe80808080fe0080010080fd808001
8080fd80808080808080ff008080800380808080808080808080808080808080808080808080808080808080808080808080808080808080808000000012008000000300040000030007000b000f0013
0017001b001f00230027002b002f00330037003b003f004300470000133533153135331531353315313533153135331505353315073533150735331531353315313533153135331d0135331507353315
0535331521353315053533153135331531353315808080808080fd808080808080808080808080fd8080018080fe00808080038080808080808080808080808080808080808080808080808080808080
808080808080808080808080808080000011008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430000013533153135331505353315053533150735
331531353315313533153135331505353315213533150535331521353315053533152135331505353315313533153135331501808080fe8080ff00808080808080fe0080018080fd8080018080fd8080
018080fe008080800380808080808080808080808080808080808080808080808080808080808080808080808080808080808000000c008000000300040000030007000b000f00130017001b001f0023
0027002b002f00001335331531353315313533153135331531353315073533150535331507353315053533150735331505353315073533158080808080808080ff00808080ff00808080ff0080808003
80808080808080808080808080808080808080808080808080808080808080800013008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b
0000013533153135331531353315053533152135331505353315213533150535331531353315313533150535331521353315053533152135331505353315213533150535331531353315313533150100
808080fe0080018080fd8080018080fe00808080fe0080018080fd8080018080fd8080018080fe0080808003808080808080808080808080808080808080808080808080808080808080808080808080
8080808080808080808000000011008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043000001353315313533153135331505353315213533150535
331521353315053533152135331505353315313533153135331531353315073533150535331505353315313533150100808080fe0080018080fd8080018080fd8080018080fe00808080808080ff0080
fe80808003808080808080808080808080808080808080808080808080808080808080808080808080808080808080000004018000000200030000030007000b000f0000013533150735331503353315
0735331501808080808080808002808080808080fe8080808080800000060080ff000180030000030007000b000f00130017000001353315073533150335331507353315073533150535331501008080
80808080808080ff008002808080808080fe8080808080808080808080800000000a000000800300030000030007000b000f00130017001b001f00230027000001353315313533150535331531353315
053533153135331d013533153135331d013533153135331502008080fe008080fe0080808080808002808080808080808080808080808080808080808080808080800000000c00800100038002800003
0007000b000f00130017001b001f00230027002b002f000013353315313533153135331531353315313533153135331501353315313533153135331531353315313533153135331580808080808080fd
008080808080800200808080808080808080808080ff0080808080808080808080808000000a008000800380030000030007000b000f00130017001b001f002300270000133533153135331d01353315
3135331d01353315313533150535331531353315053533153135331580808080808080fe008080fe0080800280808080808080808080808080808080808080808080808080000000000a008000000300
040000030007000b000f00130017001b001f002300270000013533153135331531353315053533152135331507353315053533150535331507353315033533150100808080fe00800180808080ff0080
ff00808080808003808080808080808080808080808080808080808080808080ff008080001a000000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043
0047004b004f00530057005b005f006300670000013533153135331531353315053533152135331505353315213533153135331533353315053533153335331533353315333533150535331533353315
3335331533353315053533152135331531353315313533150535331d013533153135331531353315313533150100808080fe0080018080fd0080010080808080fc8080808080808080fc808080808080
8080fc80800100808080fd808080808080038080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000
0012008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043004700000135331531353315053533153135331505353315213533150535331521353315
0535331531353315313533153135331505353315213533150535331521353315053533152135331501808080ff008080fe8080010080fe0080010080fe0080808080fd8080020080fd0080020080fd00
800200800380808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000000018008000000380040000030007000b000f00130017001b001f0023
0027002b002f00330037003b003f00430047004b004f00530057005b005f0000133533153135331531353315313533150535331521353315053533152135331505353315313533153135331531353315
3135331505353315213533150535331521353315053533152135331505353315313533153135331531353315313533158080808080fe0080018080fd8080018080fd808080808080fd8080020080fd00
80020080fd0080020080fd0080808080800380808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000000e0080
00000380040000030007000b000f00130017001b001f00230027002b002f00330037000001353315313533153135331505353315213533150535331507353315073533150735331d0135331521353315
0535331531353315313533150180808080fe0080018080fd008080808080808080018080fe00808080038080808080808080808080808080808080808080808080808080808080808080808080800000
0014008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f000013353315313533153135331531353315053533152135331505353315
213533150535331521353315053533152135331505353315213533150535331521353315053533153135331531353315313533158080808080fe0080018080fd8080020080fd0080020080fd00800200
80fd0080020080fd0080018080fd808080808003808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080001300800000030004000003
0007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b0000133533153135331531353315313533153135331505353315073533150735331531353315313533153135
33150535331507353315073533150735331531353315313533153135331531353315808080808080fd808080808080808080fe0080808080808080808080800380808080808080808080808080808080
8080808080808080808080808080808080808080808080808080808080800000000f008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b0000133533153135
331531353315313533153135331505353315073533150735331531353315313533153135331505353315073533150735331507353315808080808080fd808080808080808080fe008080808080808003
808080808080808080808080808080808080808080808080808080808080808080808080808000000012008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b
003f004300470000013533153135331531353315053533152135331505353315073533150735331521353315313533153135331505353315213533150535331521353315053533153135331531353315
0180808080fe0080018080fd0080808080800100808080fd0080020080fd8080018080fe0080808003808080808080808080808080808080808080808080808080808080808080808080808080808080
80808080800000000014008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00001335331521353315053533152135331505353315
2135331505353315313533153135331531353315313533153135331505353315213533150535331521353315053533152135331505353315213533158080020080fd0080020080fd0080020080fd0080
8080808080fd0080020080fd0080020080fd0080020080fd0080020080038080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000
000c010000000280040000030007000b000f00130017001b001f00230027002b002f00000135331531353315313533150535331507353315073533150735331507353315073533150535331531353315
313533150100808080ff008080808080808080808080ff00808080038080808080808080808080808080808080808080808080808080808080808080000c008000000280040000030007000b000f0013
0017001b001f00230027002b002f000001353315313533153135331507353315073533150735331507353315073533150735331505353315313533153135331501008080808080808080808080808080
80fe00808080038080808080808080808080808080808080808080808080808080808080808080000011008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b
003f0043000013353315213533150535331521353315053533152135331505353315333533150535331531353315313533150535331521353315053533152135331505353315213533158080020080fd
0080018080fd8080010080fe00808080fe80808080fe8080010080fe0080018080fd80800200800380808080808080808080808080808080808080808080808080808080808080808080808080808080
80800000000c008000000300040000030007000b000f00130017001b001f00230027002b002f000013353315073533150735331507353315073533150735331507353315073533153135331531353315
31353315313533158080808080808080808080808080808080808080038080808080808080808080808080808080808080808080808080808080808080000000001a000000000380040000030007000b
000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00530057005b005f0063006700001135331531353315213533153135331505353315313533152135331531353315
053533153335331533353315333533150535331533353315333533153335331505353315213533152135331505353315213533152135331505353315213533150535331521353315808001808080fc80
808001808080fc8080808080808080fc8080808080808080fc8080010080010080fc8080010080010080fc8080028080fc80800280800380808080808080808080808080808080808080808080808080
8080808080808080808080808080808080808080808080808080808080808080808080000018008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043
0047004b004f00530057005b005f000013353315313533152135331505353315313533152135331505353315333533152135331505353315333533152135331505353315213533153335331505353315
2135331533353315053533152135331531353315053533152135331531353315808080018080fd008080018080fd00808080010080fd00808080010080fd00800100808080fd00800100808080fd0080
01808080fd008001808080038080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080001000800000038004000003
0007000b000f00130017001b001f00230027002b002f00330037003b003f0000013533153135331505353315213533150535331521353315053533152135331505353315213533150535331521353315
0535331521353315053533153135331501808080fe8080010080fd8080020080fd0080020080fd0080020080fd0080020080fd8080010080fe8080800380808080808080808080808080808080808080
8080808080808080808080808080808080808080800000000011008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043000013353315313533153135
331531353315053533152135331505353315213533150535331521353315053533153135331531353315313533150535331507353315073533158080808080fe0080018080fd8080018080fd80800180
80fd8080808080fe0080808080800380808080808080808080808080808080808080808080808080808080808080808080808080808080808000000000120080ff800380040000030007000b000f0013
0017001b001f00230027002b002f00330037003b003f00430047000001353315313533150535331521353315053533152135331505353315213533150535331521353315053533152135331505353315
213533150535331531353315333533150735331501808080fe8080010080fd8080020080fd0080020080fd0080020080fd0080020080fd8080010080fe80808080808080038080808080808080808080
8080808080808080808080808080808080808080808080808080808080808080808000000014008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043
0047004b004f0000133533153135331531353315313533150535331521353315053533152135331505353315213533150535331531353315313533153135331505353315213533150535331521353315
05353315213533158080808080fe0080018080fd8080018080fd8080018080fd8080808080fe0080010080fe0080018080fd808002008003808080808080808080808080808080808080808080808080
8080808080808080808080808080808080808080808080800012008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043004700000135331531353315
313533153135331505353315213533150535331d013533153135331d013533153135331d01353315053533152135331505353315313533153135331531353315010080808080fd8080020080fd008080
80808080fd0080020080fd8080808080038080808080808080808080808080808080808080808080808080808080808080808080808080808080808080000000000e000000000380040000030007000b
000f00130017001b001f00230027002b002f0033003700001135331531353315313533153135331531353315313533153135331505353315073533150735331507353315073533150735331507353315
80808080808080fe008080808080808080808080808003808080808080808080808080808080808080808080808080808080808080808080808080000012008000000380040000030007000b000f0013
0017001b001f00230027002b002f00330037003b003f00430047000013353315213533150535331521353315053533152135331505353315213533150535331521353315053533152135331505353315
21353315053533153135331531353315313533158080020080fd0080020080fd0080020080fd0080020080fd0080020080fd0080020080fd0080020080fd808080808003808080808080808080808080
8080808080808080808080808080808080808080808080808080808080808080000e000000000380040000030007000b000f00130017001b001f00230027002b002f0033003700001135331521353315
05353315213533150535331521353315053533152135331505353315333533150535331533353315053533150735331580028080fc8080028080fd0080018080fd8080018080fe00808080fe80808080
ff008080800380808080808080808080808080808080808080808080808080808080808080808080808000000018000000000380040000030007000b000f00130017001b001f00230027002b002f0033
0037003b003f00430047004b004f00530057005b005f00001135331521353315053533152135331521353315053533152135331521353315053533153335331533353315333533150535331533353315
3335331533353315053533153135331533353315313533150535331521353315053533152135331580028080fc8080010080010080fc8080010080010080fc8080808080808080fc8080808080808080
fd008080808080fd8080018080fd808001808003808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000100080
00000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f000013353315213533150535331521353315053533152135331505353315313533150535331531353315
0535331521353315053533152135331505353315213533158080020080fd0080020080fd8080010080fe808080ff008080fe8080010080fd8080020080fd008002008003808080808080808080808080
80808080808080808080808080808080808080808080808080808080000c000000000380040000030007000b000f00130017001b001f00230027002b002f000011353315213533150535331521353315
053533152135331505353315333533150535331507353315073533150735331580028080fc8080028080fd0080018080fe00808080ff0080808080808080038080808080808080808080808080808080
808080808080808080808080808080000012008000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047000013353315313533153135331531353315
3135331531353315073533150535331505353315053533150535331505353315073533153135331531353315313533153135331531353315808080808080808080ff0080ff0080ff0080ff0080ff0080
80808080808080038080808080808080808080808080808080808080808080808080808080808080808080808080808080808080000f0100ff000280048000030007000b000f00130017001b001f0023
0027002b002f00330037003b00000135331531353315313533150535331507353315073533150735331507353315073533150735331507353315073533150735331531353315313533150100808080fe
80808080808080808080808080808080808080808080040080808080808080808080808080808080808080808080808080808080808080808080808080808080000a0080ff800300048000030007000b
000f00130017001b001f002300270000133533150735331d013533150735331d013533150735331d013533150735331d0135331507353315808080808080808080808080808080800400808080808080
808080808080808080808080808080808080808080808000000f0100ff000280048000030007000b000f00130017001b001f00230027002b002f00330037003b00000135331531353315313533150735
331507353315073533150735331507353315073533150735331507353315073533150535331531353315313533150100808080808080808080808080808080808080808080fe80808080040080808080
808080808080808080808080808080808080808080808080808080808080808080808080000a008001800300048000030007000b000f00130017001b001f002300270000013533150735331505353315
333533150535331533353315053533152135331505353315213533150180808080ff00808080fe80808080fe0080018080fd808001808004008080808080808080808080808080808080808080808080
8080000000070000ff800380000000030007000b000f00130017001b00001535331531353315313533153135331531353315313533153135331580808080808080808080808080808080808080808080
000201000380020004800003000700000135331d013533150100808004008080808080000010008000000300030000030007000b000f00130017001b001f00230027002b002f00330037003b003f0000
01353315313533153135331d01353315053533153135331531353315313533150535331521353315053533152135331505353315313533153135331531353315010080808080fe0080808080fd808001
8080fd8080018080fe00808080800280808080808080808080808080808080808080808080808080808080808080808080808080800000000013008000000300048000030007000b000f00130017001b
001f00230027002b002f00330037003b003f00430047004b0000133533150735331507353315073533153135331531353315313533150535331521353315053533152135331505353315213533150535
331521353315053533153135331531353315313533158080808080808080808080fe0080018080fd8080018080fd8080018080fd8080018080fd80808080800400808080808080808080808080808080
8080808080808080808080808080808080808080808080808080808080808000000c008000000300030000030007000b000f00130017001b001f00230027002b002f0000013533153135331531353315
0535331521353315053533150735331507353315213533150535331531353315313533150100808080fe0080018080fd808080808080018080fe00808080028080808080808080808080808080808080
808080808080808080808080800000000013008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b00000135331507353315073533150535
331531353315313533153135331505353315213533150535331521353315053533152135331505353315213533150535331531353315313533153135331502808080808080fe0080808080fd80800180
80fd8080018080fd8080018080fd8080018080fe008080808004008080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000000000100080
00000300030000030007000b000f00130017001b001f00230027002b002f00330037003b003f000001353315313533153135331505353315213533150535331531353315313533153135331531353315
0535331507353315213533150535331531353315313533150100808080fe0080018080fd808080808080fd80808080018080fe0080808002808080808080808080808080808080808080808080808080
80808080808080808080808080800000000e008000000300048000030007000b000f00130017001b001f00230027002b002f003300370000013533153135331531353315053533150735331505353315
31353315313533153135331505353315073533150735331507353315073533150180808080fe00808080ff0080808080fe80808080808080808080040080808080808080808080808080808080808080
808080808080808080808080808080808000000000150080fe800300030000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00530000013533153135
3315313533153135331505353315213533150535331521353315053533152135331505353315213533150535331531353315313533153135331507353315073533150535331531353315313533150100
80808080fd8080018080fd8080018080fd8080018080fd8080018080fe008080808080808080fe0080808002808080808080808080808080808080808080808080808080808080808080808080808080
808080808080808080808080808080000011008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430000133533150735331507353315073533153135
33153135331531353315053533152135331505353315213533150535331521353315053533152135331505353315213533158080808080808080808080fe0080018080fd8080018080fd8080018080fd
8080018080fd80800180800400808080808080808080808080808080808080808080808080808080808080808080808080808080808080000008010000000200048000030007000b000f00130017001b
001f00000135331501353315313533150735331507353315073533150735331507353315018080ff0080808080808080808080808004008080fe80808080808080808080808080808080808080800000
000c0080ff000280048000030007000b000f00130017001b001f00230027002b002f00000135331501353315313533150735331507353315073533150735331507353315073533150535331531353315
31353315020080ff008080808080808080808080808080fe0080808004008080fe808080808080808080808080808080808080808080808080808080808080000010008000000300048000030007000b
000f00130017001b001f00230027002b002f00330037003b003f000013353315073533150735331507353315213533150535331521353315053533153335331505353315313533153135331505353315
2135331505353315213533158080808080808080018080fd8080010080fe00808080fe80808080fe8080010080fe00800180800400808080808080808080808080808080808080808080808080808080
80808080808080808080808080000000000a010000000200048000030007000b000f00130017001b001f0023002700000135331531353315073533150735331507353315073533150735331507353315
0735331507353315010080808080808080808080808080808080808004008080808080808080808080808080808080808080808080808080808000000014000000000380030000030007000b000f0013
0017001b001f00230027002b002f00330037003b003f00430047004b004f0000113533153135331531353315333533153135331505353315213533152135331505353315213533152135331505353315
2135331521353315053533152135331521353315053533152135331521353315808080808080fd0080010080010080fc8080010080010080fc8080010080010080fc8080010080010080fc8080010080
01008002808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000000e008000000300030000030007000b000f00130017001b001f0023
0027002b002f00330037000013353315313533153135331531353315053533152135331505353315213533150535331521353315053533152135331505353315213533158080808080fe0080018080fd
8080018080fd8080018080fd8080018080fd808001808002808080808080808080808080808080808080808080808080808080808080808080800000000e008000000300030000030007000b000f0013
0017001b001f00230027002b002f003300370000013533153135331531353315053533152135331505353315213533150535331521353315053533152135331505353315313533153135331501008080
80fe0080018080fd8080018080fd8080018080fd8080018080fe00808080028080808080808080808080808080808080808080808080808080808080808080808000000000130080fe80030003000003
0007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b0000133533153135331531353315313533150535331521353315053533152135331505353315213533150535
331521353315053533153135331531353315313533150535331507353315073533158080808080fe0080018080fd8080018080fd8080018080fd8080018080fd8080808080fe00808080808002808080
808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000130080fe800300030000030007000b000f00130017001b001f00230027002b002f0033
0037003b003f00430047004b0000013533153135331531353315313533150535331521353315053533152135331505353315213533150535331521353315053533153135331531353315313533150735
33150735331507353315010080808080fd8080018080fd8080018080fd8080018080fd8080018080fe008080808080808080808002808080808080808080808080808080808080808080808080808080
8080808080808080808080808080808080808080000a008000000300030000030007000b000f00130017001b001f00230027000013353315333533153135331505353315313533152135331505353315
0735331507353315073533158080808080fe008080010080fd8080808080808080028080808080808080808080808080808080808080808080808080000d008000000300030000030007000b000f0013
0017001b001f00230027002b002f00330000013533153135331531353315313533150535331d013533153135331d0135331d0135331505353315313533153135331531353315010080808080fd808080
808080fd80808080800280808080808080808080808080808080808080808080808080808080808080800000000d010000000300040000030007000b000f00130017001b001f00230027002b002f0033
00000135331507353315073533153135331531353315313533150535331507353315073533150735331d01353315313533153135331501008080808080808080fe008080808080808080808003808080
8080808080808080808080808080808080808080808080808080808080808000000e008000000300030000030007000b000f00130017001b001f00230027002b002f0033003700001335331521353315
0535331521353315053533152135331505353315213533150535331521353315053533153135331531353315313533158080018080fd8080018080fd8080018080fd8080018080fd8080018080fe0080
80808002808080808080808080808080808080808080808080808080808080808080808080800000000a008000000300030000030007000b000f00130017001b001f0023002700001335331521353315
05353315213533150535331533353315053533153335331505353315073533158080018080fd8080018080fe00808080fe80808080ff0080808002808080808080808080808080808080808080808080
80808080800000000012000000000380030000030007000b000f00130017001b001f00230027002b002f00330037003b003f004300470000113533152135331505353315213533152135331505353315
21353315213533150535331533353315333533153335331505353315313533153335331531353315053533152135331580028080fc8080010080010080fc8080010080010080fc8080808080808080fd
008080808080fd80800180800280808080808080808080808080808080808080808080808080808080808080808080808080808080808000000a008000000300030000030007000b000f00130017001b
001f002300270000133533152135331505353315333533150535331507353315053533153335331505353315213533158080018080fe00808080ff00808080ff00808080fe0080018080028080808080
80808080808080808080808080808080808080808000000000130080fe800300030000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b0000133533152135
331505353315213533150535331521353315053533152135331505353315213533150535331531353315313533153135331507353315073533150535331531353315313533158080018080fd80800180
80fd8080018080fd8080018080fd8080018080fe008080808080808080fe0080808002808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080
80800000000e008000000300030000030007000b000f00130017001b001f00230027002b002f003300370000133533153135331531353315313533153135331507353315053533150535331505353315
05353315313533153135331531353315313533158080808080808080ff0080ff0080ff0080ff008080808080028080808080808080808080808080808080808080808080808080808080808080808000
000e0080ff000300048000030007000b000f00130017001b001f00230027002b002f003300370000013533153135331505353315073533150735331507353315053533153135331d0135331507353315
073533150735331d013533153135331502008080fe8080808080808080fe8080808080808080808080800400808080808080808080808080808080808080808080808080808080808080808080808080
80800000000b0180ff000200048000030007000b000f00130017001b001f00230027002b0000013533150735331507353315073533150735331507353315073533150735331507353315073533150735
331501808080808080808080808080808080808080808080800400808080808080808080808080808080808080808080808080808080808080808000000e0080ff000300048000030007000b000f0013
0017001b001f00230027002b002f003300370000133533153135331d0135331507353315073533150735331d013533153135331505353315073533150735331507353315053533153135331580808080
8080808080808080fe8080808080808080fe808080040080808080808080808080808080808080808080808080808080808080808080808080808080800000000008000001800380028000030007000b
000f00130017001b001f0000133533153135331531353315213533150535331521353315313533153135331580808080010080fc80800100808080020080808080808080808080808080808080800000
0013008000000380038000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b0000013533153135331531353315053533152135331505353315313533153135
331531353315053533150535331531353315313533153135331505353315213533150535331531353315313533150180808080fe0080018080fd0080808080fe8080ff0080808080fe8080018080fe00
8080800300808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000000000040100ff000200010000030007000b000f00002535331507353315
073533150535331501808080808080ff0080808080808080808080808080000000100080ff000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f000001353315
31353315053533150735331505353315313533153135331531353315053533150735331507353315073533150735331507353315053533153135331502008080fe80808080ff0080808080fe80808080
8080808080808080fe808080040080808080808080808080808080808080808080808080808080808080808080808080808080808080808000060100ff800280010000030007000b000f001300170000
2535331533353315053533153335331505353315333533150100808080fe80808080fe8080808080808080808080808080808080808000000003008000000300008000030007000b0000333533153335
3315333533158080808080808080808080800000000d008000000300048000030007000b000f00130017001b001f00230027002b002f0033000001353315073533150535331531353315313533153135
3315313533150535331507353315073533150735331507353315073533150180808080fe808080808080fe80808080808080808080808004008080808080808080808080808080808080808080808080
8080808080808080808080000011008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043000001353315073533150535331531353315313533153135
331531353315053533150535331531353315313533153135331531353315053533150735331507353315073533150180808080fe808080808080fe8080fe808080808080fe8080808080808080040080
80808080808080808080808080808080808080808080808080808080808080808080808080808080800000000005008003000300048000030007000b000f001300000135331505353315333533150535
331521353315018080ff00808080fe008001808004008080808080808080808080800000000e008000000380040000030007000b000f00130017001b001f00230027002b002f00330037000001353315
05353315213533150535331533353315073533150535331507353315333533153335331505353315213533153335331505353315020080fe0080010080fe008080808080ff0080808080808080fd0080
0100808080fd0080038080808080808080808080808080808080808080808080808080808080808080808080800000000015008000000380050000030007000b000f00130017001b001f00230027002b
002f00330037003b003f00430047004b004f005300000135331533353315053533150535331531353315313533153135331505353315213533150535331d013533153135331d013533153135331d0135
33150535331521353315053533153135331531353315313533150100808080ff0080ff0080808080fd8080020080fd00808080808080fd0080020080fd80808080800480808080808080808080808080
808080808080808080808080808080808080808080808080808080808080808080808080808080000005008000800200030000030007000b000f0013000001353315053533150535331d0135331d0135
3315018080ff0080ff00808080028080808080808080808080808080800000000018000000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b
004f00530057005b005f00001335331531353315333533153135331531353315053533152135331505353315213533150535331521353315313533153135331505353315213533150535331521353315
0535331521353315053533153135331533353315313533153135331580808080808080fc8080010080fe0080010080fe00800100808080fd0080010080fe0080010080fe0080010080fe808080808080
8003808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000000015008000000380050000030007000b000f0013
0017001b001f00230027002b002f00330037003b003f00430047004b004f0053000001353315333533150535331505353315313533153135331531353315313533153135331507353315053533150535
33150535331505353315053533150735331531353315313533153135331531353315313533150100808080ff0080fe808080808080808080ff0080ff0080ff0080ff0080ff0080808080808080800480
808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080000003018003000280048000030007000b0000013533150735331d0135
33150180808080800400808080808080808000000003010003000200048000030007000b00000135331507353315053533150180808080ff008004008080808080808080000601000300030004800003
0007000b000f0013001700000135331533353315053533153335331505353315333533150100808080fe80808080ff008080800400808080808080808080808080808000000600800300028004800003
0007000b000f0013001700000135331533353315053533153335331505353315333533150100808080fe80808080fe008080800400808080808080808080808080808000000d00800080030003000003
0007000b000f00130017001b001f00230027002b002f00330000013533150535331531353315313533150535331531353315313533153135331531353315053533153135331531353315053533150180
80ff00808080fe008080808080fe00808080ff008002808080808080808080808080808080808080808080808080808080808080800000000005008001800300020000030007000b000f001300001335
3315313533153135331531353315313533158080808080800180808080808080808080800007000001800380020000030007000b000f00130017001b0000113533153135331531353315313533153135
3315313533153135331580808080808080018080808080808080808080808080800000000004008003000280040000030007000b000f0000013533153335331505353315333533150100808080fe0080
808003808080808080808080800000000010000002000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00001135331531353315313533153335331531353315
313533150535331521353315313533153135331505353315213533153335331505353315213533153335331580808080808080fd00800100808080fd00800100808080fd008001008080800380808080
80808080808080808080808080808080808080808080808080808080808080800010008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f000001353315
3335331505353315013533153135331531353315313533150535331d013533153135331d0135331d01353315053533153135331531353315313533150100808080ff0080ff0080808080fd8080808080
80fd8080808080040080808080808080ff00808080808080808080808080808080808080808080808080808080808080800000000005008000800200030000030007000b000f001300001335331d0135
331d01353315053533150535331580808080ff0080ff0080028080808080808080808080808080800015000000000380030000030007000b000f00130017001b001f00230027002b002f00330037003b
003f00430047004b004f00530000133533153135331533353315313533150535331521353315213533150535331521353315313533153135331531353315053533152135331505353315213533152135
331505353315313533153335331531353315808080808080fd0080010080010080fc8080010080808080fc8080010080fe0080010080010080fd00808080808002808080808080808080808080808080
8080808080808080808080808080808080808080808080808080808080808080800000000011008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043
000001353315333533150535331501353315313533153135331531353315313533150735331505353315053533150535331505353315313533153135331531353315313533150100808080ff0080fe80
80808080808080ff0080ff0080ff0080ff008080808080040080808080808080ff0080808080808080808080808080808080808080808080808080808080808080808000000d00000000038004800003
0007000b000f00130017001b001f00230027002b002f00330000013533153335331501353315213533150535331521353315053533152135331505353315333533150535331507353315073533150100
808080fd8080028080fc8080028080fd0080018080fe00808080ff008080808080040080808080ff00808080808080808080808080808080808080808080808080808080800000000007018000000200
040000030007000b000f00130017001b00000135331503353315073533150735331507353315073533150735331501808080808080808080808080808003808080ff0080808080808080808080808080
8080808000120080ff800300038000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047000001353315053533153135331531353315053533153335331533353315
0535331533353315053533153335331505353315333533153335331505353315313533153135331505353315018080ff00808080fe008080808080fd80808080fe80808080fe808080808080fe008080
80ff00800300808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000000010008000000300040000030007000b000f00130017001b001f0023
0027002b002f00330037003b003f000001353315313533150535331507353315053533153135331531353315313533150535331507353315053533150735331531353315313533153135331531353315
01808080fe80808080ff0080808080fe80808080ff0080808080808080038080808080808080808080808080808080808080808080808080808080808080808080808080808000000014000000000380
038000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f0000113533152135331505353315313533153135331531353315313533150535331521353315
053533152135331505353315213533150535331531353315313533153135331531353315053533152135331580028080fd008080808080fd8080018080fd8080018080fd8080018080fd808080808080
fd008002808003008080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000000010000000000380040000030007000b000f00130017001b
001f00230027002b002f00330037003b003f0000113533152135331505353315213533150535331521353315053533153335331505353315053533153135331531353315313533153135331505353315
0735331580028080fc8080028080fd0080018080fe00808080ff0080fe808080808080fe8080808003808080808080808080808080808080808080808080808080808080808080808080808080808080
80000000000a0180ff000200048000030007000b000f00130017001b001f0023002700000135331507353315073533150735331507353315033533150735331507353315073533150735331501808080
808080808080808080808080808080808004008080808080808080808080808080ff0080808080808080808080808080800000000012008000000300048000030007000b000f00130017001b001f0023
0027002b002f00330037003b003f00430047000001353315313533153135331505353315213533150535331d01353315313533150535331533353315053533153135331d013533150535331521353315
0535331531353315313533150100808080fe0080018080fd80808080ff00808080ff00808080fd8080018080fe0080808004008080808080808080808080808080808080808080808080808080808080
80808080808080808080808080808000000201000400028004800003000700000135331533353315010080808004008080808000001c000000000380040000030007000b000f00130017001b001f0023
0027002b002f00330037003b003f00430047004b004f00530057005b005f00630067006b006f000013353315313533153135331531353315313533150535331521353315053533152135331531353315
333533150535331533353315213533150535331533353315213533150535331521353315313533153335331505353315213533150535331531353315313533153135331531353315808080808080fd00
80028080fc8080010080808080fc80808080018080fc80808080018080fc8080010080808080fc8080028080fd0080808080800380808080808080808080808080808080808080808080808080808080
808080808080808080808080808080808080808080808080808080808080808080808080000b008001800280040000030007000b000f00130017001b001f00230027002b0000013533153135331d0135
331505353315313533153135331505353315213533150535331531353315313533150100808080fe80808080fe0080010080fe8080808003808080808080808080808080808080808080808080808080
80808000000a008000800300030000030007000b000f00130017001b001f0023002700000135331533353315053533153335331505353315333533150535331533353315053533153335331501808080
80fe00808080fe00808080ff00808080ff008080800280808080808080808080808080808080808080808080808080000007008000000280020000030007000b000f00130017001b0000133533153135
33153135331531353315073533150735331507353315808080808080808080808001808080808080808080808080808080808080001e000000000380040000030007000b000f00130017001b001f0023
0027002b002f00330037003b003f00430047004b004f00530057005b005f00630067006b006f007300770000133533153135331531353315313533153135331505353315213533150535331533353315
3135331521353315053533153335331533353315333533150535331533353315313533152135331505353315333533153335331533353315053533152135331505353315313533153135331531353315
31353315808080808080fd0080028080fc8080808080010080fc8080808080808080fc8080808080010080fc8080808080808080fc8080028080fd008080808080038080808080808080808080808080
80808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000000007000004800380050000030007000b000f00130017001b
00001135331531353315313533153135331531353315313533153135331580808080808080048080808080808080808080808080800000000008008002800280048000030007000b000f00130017001b
001f0000013533153135331505353315213533150535331521353315053533153135331501008080fe8080010080fe0080010080fe808080040080808080808080808080808080808080808080000000
000e008000000300038000030007000b000f00130017001b001f00230027002b002f00330037000001353315073533150535331531353315313533153135331531353315053533150735331501353315
313533153135331531353315313533150180808080fe808080808080fe80808080fe808080808080030080808080808080808080808080808080808080808080ff0080808080808080808080000a0080
02000280048000030007000b000f00130017001b001f00230027000013353315313533153135331d013533150535331505353315053533153135331531353315313533158080808080ff0080ff0080ff
0080808080040080808080808080808080808080808080808080808080808000000a008002000280048000030007000b000f00130017001b001f00230027000013353315313533153135331d01353315
053533153135331d013533150535331531353315313533158080808080fe80808080fe008080800400808080808080808080808080808080808080808080808080000000000201800380028004800003
000700000135331505353315020080ff00800400808080808000000000110000ff000380030000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430000133533152135
33150535331521353315053533152135331505353315213533150535331531353315213533150535331533353315313533153335331505353315053533158080018080fd8080018080fd8080018080fd
8080018080fd808080010080fd80808080808080fd0080ff008002808080808080808080808080808080808080808080808080808080808080808080808080808080808080000000001a0080ff800380
040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00530057005b005f006300670000013533153135331531353315313533153135331505353315
3135331531353315333533150535331531353315313533153335331505353315313533153335331505353315333533150535331533353315053533153335331505353315333533150535331533353315
01008080808080fd008080808080fd808080808080fe0080808080fe80808080fe80808080fe80808080fe80808080fe8080808003808080808080808080808080808080808080808080808080808080
8080808080808080808080808080808080808080808080808080808080808080808000000009010001000280028000030007000b000f00130017001b001f002300000135331531353315313533150535
331531353315313533150535331531353315313533150100808080fe80808080fe80808080020080808080808080808080808080808080808080800000040180fe800280000000030007000b000f0000
05353315313533150735331505353315018080808080ff008080808080808080808080800008008002000200048000030007000b000f00130017001b001f000001353315053533153135331507353315
07353315053533153135331531353315010080ff00808080808080ff00808080040080808080808080808080808080808080808080800000000a008002000280048000030007000b000f00130017001b
001f0023002700000135331531353315053533152135331505353315213533150535331521353315053533153135331501008080fe8080010080fe0080010080fe0080010080fe808080040080808080
8080808080808080808080808080808080808080000a008000800300030000030007000b000f00130017001b001f00230027000013353315333533150535331533353315053533153335331505353315
33353315053533153335331580808080ff00808080ff00808080fe00808080fe00808080028080808080808080808080808080808080808080808080808000000016008000000380050000030007000b
000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00530057000001353315053533152135331505353315213533150535331521353315053533153335331507353315
053533152135331505353315333533153135331505353315333533153135331531353315313533150535331521353315028080fd8080018080fd8080010080fe0080010080fe008080808080ff008001
0080fe0080808080fd80808080808080fd008001808004808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080000000
0016008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f005300570000013533150535331521353315053533152135331505353315
21353315053533153335331507353315313533153135331505353315213533150535331521353315053533152135331505353315213533153135331531353315028080fd8080018080fd8080010080fe
0080010080fe0080808080808080fe0080018080fd8080010080fd8080010080fe0080010080808004808080808080808080808080808080808080808080808080808080808080808080808080808080
80808080808080808080808080808000001a000000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00530057005b005f006300670000
0135331505353315313533152135331505353315333533150535331531353315333533150535331531353315053533153135331533353315053533152135331505353315333533153135331505353315
333533153135331531353315313533150535331521353315028080fd008080018080fe00808080fe0080808080fe808080fe0080808080ff0080010080fe0080808080fd80808080808080fd00800180
80048080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080000a008000000300040000030007000b
000f00130017001b001f0023002700000135331503353315073533150535331505353315073533152135331505353315313533153135331501808080808080ff0080ff00808080018080fe0080808003
808080ff0080808080808080808080808080808080808080808080800012008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043004700000135331d
013533150135331531353315053533152135331505353315213533150535331531353315313533153135331505353315213533150535331521353315053533152135331501808080ff008080fe808001
0080fe0080010080fe0080808080fd8080020080fd0080020080fd008002008004808080808080ff00808080808080808080808080808080808080808080808080808080808080808080808080808000
0012008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043004700000135331505353315033533153135331505353315213533150535331521353315
05353315313533153135331531353315053533152135331505353315213533150535331521353315020080ff0080808080fe8080010080fe0080010080fe0080808080fd8080020080fd0080020080fd
008002008004808080808080ff0080808080808080808080808080808080808080808080808080808080808080808080808080800014008000000380050000030007000b000f00130017001b001f0023
0027002b002f00330037003b003f00430047004b004f00000135331531353315053533152135331501353315313533150535331521353315053533152135331505353315313533153135331531353315
05353315213533150535331521353315053533152135331501808080fe8080010080fe808080fe8080010080fe0080010080fe0080808080fd8080020080fd0080020080fd0080020080048080808080
8080808080ff0080808080808080808080808080808080808080808080808080808080808080808080808080800000000014008000000380050000030007000b000f00130017001b001f00230027002b
002f00330037003b003f00430047004b004f0000013533153335331505353315333533150135331531353315053533152135331505353315213533150535331531353315313533153135331505353315
21353315053533152135331505353315213533150180808080fe00808080ff008080fe8080010080fe0080010080fe0080808080fd8080020080fd0080020080fd008002008004808080808080808080
80ff0080808080808080808080808080808080808080808080808080808080808080808080808080800000000012008000000380048000030007000b000f00130017001b001f00230027002b002f0033
0037003b003f0043004700000135331521353315013533153135331505353315213533150535331521353315053533153135331531353315313533150535331521353315053533152135331505353315
21353315010080010080fe808080fe8080010080fe0080010080fe0080808080fd8080020080fd0080020080fd0080020080040080808080ff0080808080808080808080808080808080808080808080
808080808080808080808080808080800016008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f0053005700000135331531353315
0535331521353315053533152135331505353315313533150535331521353315053533152135331505353315313533153135331531353315053533152135331505353315213533150535331521353315
01808080fe8080010080fe0080010080fe808080fe8080010080fe0080010080fe0080808080fd8080020080fd0080020080fd0080020080048080808080808080808080808080808080808080808080
80808080808080808080808080808080808080808080808080808080808080000017000000000380040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b
004f00530057005b000001353315313533153135331531353315053533153335331505353315333533150535331521353315313533150535331531353315313533153135331505353315213533150535
33152135331505353315213533153135331531353315018080808080fd80808080fe80808080fe008001008080fd8080808080fd8080018080fd8080018080fd80800180808080038080808080808080
80808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080000000110080fe800380040000030007000b000f00130017001b001f00230027002b
002f00330037003b003f0043000001353315313533153135331505353315213533150535331507353315073533150735331d013533152135331505353315313533153135331505353315073533150535
33150180808080fe0080018080fd008080808080808080018080fe00808080ff00808080ff00800380808080808080808080808080808080808080808080808080808080808080808080808080808080
80808080800000000014008000000300050000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00000135331d01353315013533153135331531353315
31353315313533150535331507353315073533153135331531353315313533150535331507353315073533153135331531353315313533153135331501008080fe808080808080fd8080808080808080
80fe0080808080808080808004808080808080ff00808080808080808080808080808080808080808080808080808080808080808080808080808080808080000014008000000300050000030007000b
000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00000135331505353315013533153135331531353315313533153135331505353315073533150735331531353315
313533153135331505353315073533150735331531353315313533153135331531353315020080ff0080fe808080808080fd808080808080808080fe0080808080808080808004808080808080ff0080
80808080808080808080808080808080808080808080808080808080808080808080808080808080800000000015008000000300050000030007000b000f00130017001b001f00230027002b002f0033
0037003b003f00430047004b004f005300000135331505353315333533150135331531353315313533153135331531353315053533150735331507353315313533153135331531353315053533150735
33150735331531353315313533153135331531353315018080ff00808080fe008080808080fd808080808080808080fe00808080808080808080048080808080808080ff008080808080808080808080
80808080808080808080808080808080808080808080808080808080808080000014008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b
004f000001353315333533150135331531353315313533153135331531353315053533150735331507353315313533153135331531353315053533150735331507353315313533153135331531353315
313533150100808080fe008080808080fd808080808080808080fe00808080808080808080040080808080ff008080808080808080808080808080808080808080808080808080808080808080808080
8080808080808000000d010000000280050000030007000b000f00130017001b001f00230027002b002f003300000135331d013533150135331531353315313533150535331507353315073533150735
33150735331505353315313533153135331501808080fe80808080ff00808080808080808080ff0080808004808080808080ff0080808080808080808080808080808080808080808080808080808080
000d010000000280050000030007000b000f00130017001b001f00230027002b002f00330000013533150535331501353315313533153135331505353315073533150735331507353315073533150535
33153135331531353315020080ff0080ff00808080ff00808080808080808080ff0080808004808080808080ff00808080808080808080808080808080808080808080808080808080800000000e0100
00000280050000030007000b000f00130017001b001f00230027002b002f0033003700000135331505353315333533150135331531353315313533150535331507353315073533150735331507353315
053533153135331531353315018080ff00808080fe80808080ff00808080808080808080ff00808080048080808080808080ff0080808080808080808080808080808080808080808080808080808080
000d010000000280048000030007000b000f00130017001b001f00230027002b002f00330000013533153335331501353315313533153135331505353315073533150735331507353315073533150535
331531353315313533150100808080fe80808080ff00808080808080808080ff00808080040080808080ff00808080808080808080808080808080808080808080808080808080800015000000000380
038000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f0053000013353315313533153135331531353315053533152135331505353315213533150535
33153135331531353315313533152135331505353315213533150535331521353315053533153135331531353315313533158080808080fe0080018080fd8080020080fc8080808080010080fd008002
0080fd0080018080fd808080808003008080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800019008000000380050000030007000b
000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00530057005b005f0063000001353315333533150535331533353315013533153135331521353315053533153335
3315213533150535331533353315213533150535331521353315333533150535331521353315333533150535331521353315313533150535331521353315313533150180808080fe00808080fe008080
018080fd00808080010080fd00808080010080fd00800100808080fd00800100808080fd008001808080fd0080018080800480808080808080808080ff00808080808080808080808080808080808080
80808080808080808080808080808080808080808080808080808080808000000010008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f00000135331d
01353315013533153135331505353315213533150535331521353315053533152135331505353315213533150535331521353315053533153135331501808080ff008080fe8080010080fd8080020080
fd0080020080fd0080020080fd8080010080fe80808004808080808080ff0080808080808080808080808080808080808080808080808080808080808080808080000000001000800000038005000003
0007000b000f00130017001b001f00230027002b002f00330037003b003f0000013533150535331503353315313533150535331521353315053533152135331505353315213533150535331521353315
05353315213533150535331531353315020080ff0080808080fe8080010080fd8080020080fd0080020080fd0080020080fd8080010080fe80808004808080808080ff00808080808080808080808080
8080808080808080808080808080808080808080808000000012008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043004700000135331531353315
0535331521353315013533153135331505353315213533150535331521353315053533152135331505353315213533150535331521353315053533153135331501808080fe8080010080fe808080fe80
80010080fd8080020080fd0080020080fd0080020080fd8080010080fe8080800480808080808080808080ff008080808080808080808080808080808080808080808080808080808080808080808000
0012008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043004700000135331533353315053533153335331501353315313533150535331521353315
053533152135331505353315213533150535331521353315053533152135331505353315313533150180808080fe00808080ff008080fe8080010080fd8080020080fd0080020080fd0080020080fd80
80010080fe8080800480808080808080808080ff0080808080808080808080808080808080808080808080808080808080808080808080000010008000000380048000030007000b000f00130017001b
001f00230027002b002f00330037003b003f0000013533152135331501353315313533150535331521353315053533152135331505353315213533150535331521353315053533152135331505353315
31353315010080010080fe808080fe8080010080fd8080020080fd0080020080fd0080020080fd8080010080fe808080040080808080ff00808080808080808080808080808080808080808080808080
8080808080808080808000000009008000800300030000030007000b000f00130017001b001f002300001335331521353315053533153335331505353315053533153335331505353315213533158080
018080fe00808080ff0080ff00808080fe008001808002808080808080808080808080808080808080808080808000000016008000000380040000030007000b000f00130017001b001f00230027002b
002f00330037003b003f00430047004b004f0053005700000135331531353315333533150535331521353315053533152135331533353315053533152135331533353315053533153335331521353315
0535331533353315213533150535331521353315053533153335331531353315018080808080fd8080010080fd80800100808080fd00800100808080fd00808080010080fd00808080010080fd808001
0080fd808080808003808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800000000012008000000380050000030007000b
000f00130017001b001f00230027002b002f00330037003b003f0043004700000135331d0135331501353315213533150535331521353315053533152135331505353315213533150535331521353315
05353315213533150535331531353315313533153135331501808080fe0080020080fd0080020080fd0080020080fd0080020080fd0080020080fd0080020080fd808080808004808080808080ff0080
808080808080808080808080808080808080808080808080808080808080808080808080800000000012008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b
003f004300470000013533150535331501353315213533150535331521353315053533152135331505353315213533150535331521353315053533152135331505353315313533153135331531353315
020080ff0080fe8080020080fd0080020080fd0080020080fd0080020080fd0080020080fd0080020080fd808080808004808080808080ff008080808080808080808080808080808080808080808080
808080808080808080808080808080000014008000000380050000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f0000013533153135331505353315
213533150135331521353315053533152135331505353315213533150535331521353315053533152135331505353315213533150535331531353315313533153135331501808080fe8080010080fd80
80020080fd0080020080fd0080020080fd0080020080fd0080020080fd0080020080fd80808080800480808080808080808080ff00808080808080808080808080808080808080808080808080808080
8080808080808080808080000012008000000380048000030007000b000f00130017001b001f00230027002b002f00330037003b003f0043004700000135331521353315013533152135331505353315
21353315053533152135331505353315213533150535331521353315053533152135331505353315313533153135331531353315010080010080fd8080020080fd0080020080fd0080020080fd008002
0080fd0080020080fd0080020080fd8080808080040080808080ff0080808080808080808080808080808080808080808080808080808080808080808080808080800000000d00000000038005000003
0007000b000f00130017001b001f00230027002b002f00330000013533150535331501353315213533150535331521353315053533152135331505353315333533150535331507353315073533150200
80ff0080fe0080028080fc8080028080fd0080018080fe00808080ff00808080808004808080808080ff0080808080808080808080808080808080808080808080808080808080000010008000000300
040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00001335331507353315073533153135331531353315313533150535331521353315053533152135331505353315
3135331531353315313533150535331507353315808080808080808080fe0080018080fd8080018080fd8080808080fe0080808003808080808080808080808080808080808080808080808080808080
8080808080808080808080808000000000190000ff800380048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f00530057005b005f006300000135
3315313533153135331505353315213533150535331521353315053533153135331531353315313533150535331521353315053533152135331505353315213533150535331521353315053533153135
3315313533153135331531353315053533150100808080fe0080018080fd8080018080fd8080808080fe0080018080fd8080020080fd0080020080fd0080020080fd008080808080fd00800400808080
80808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080800012008000000300048000030007000b000f00130017001b
001f00230027002b002f00330037003b003f0043004700000135331d0135331501353315313533153135331d013533150535331531353315313533153135331505353315213533150535331521353315
0535331531353315313533153135331501808080fe8080808080fe0080808080fd8080018080fd8080018080fe008080808004008080808080ff00808080808080808080808080808080808080808080
808080808080808080808080808080800012008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047000001353315053533150135331531353315
3135331d01353315053533153135331531353315313533150535331521353315053533152135331505353315313533153135331531353315020080ff0080ff0080808080fe0080808080fd8080018080
fd8080018080fe008080808004008080808080ff008080808080808080808080808080808080808080808080808080808080808080808080808000000013008000000300048000030007000b000f0013
0017001b001f00230027002b002f00330037003b003f00430047004b000001353315053533153335331501353315313533153135331d0135331505353315313533153135331531353315053533152135
3315053533152135331505353315313533153135331531353315018080ff00808080fe8080808080fe0080808080fd8080018080fd8080018080fe0080808080040080808080808080ff008080808080
80808080808080808080808080808080808080808080808080808080808080800014008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b
004f00000135331533353315053533153335331501353315313533153135331d013533150535331531353315313533153135331505353315213533150535331521353315053533153135331531353315
313533150180808080fe00808080fe8080808080fe0080808080fd8080018080fd8080018080fe00808080800400808080808080808080ff008080808080808080808080808080808080808080808080
808080808080808080808080808000000012008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047000001353315333533150135331531353315
3135331d013533150535331531353315313533153135331505353315213533150535331521353315053533153135331531353315313533150100808080fe8080808080fe0080808080fd8080018080fd
8080018080fe0080808080038080808080ff00808080808080808080808080808080808080808080808080808080808080808080808080800014008000000300050000030007000b000f00130017001b
001f00230027002b002f00330037003b003f00430047004b004f00000135331505353315333533150535331501353315313533153135331d013533150535331531353315313533153135331505353315
21353315053533152135331505353315313533153135331531353315018080ff00808080ff0080ff0080808080fe0080808080fd8080018080fd8080018080fe00808080800480808080808080808080
80ff00808080808080808080808080808080808080808080808080808080808080808080808080800016000000000380030000030007000b000f00130017001b001f00230027002b002f00330037003b
003f00430047004b004f00530057000013353315313533153335331531353315053533152135331505353315313533153135331531353315313533153135331505353315213533150535331521353315
213533150535331531353315313533153135331531353315808080808080fe8080010080fd00808080808080fc8080010080fe0080010080010080fd0080808080800280808080808080808080808080
80808080808080808080808080808080808080808080808080808080808080808080808080000000000f0080fe800300030000030007000b000f00130017001b001f00230027002b002f00330037003b
00000135331531353315313533150535331521353315053533150735331507353315213533150535331531353315313533150535331507353315053533150100808080fe0080018080fd808080808080
018080fe00808080ff00808080ff0080028080808080808080808080808080808080808080808080808080808080808080808080808080800012008000000300048000030007000b000f00130017001b
001f00230027002b002f00330037003b003f0043004700000135331d01353315013533153135331531353315053533152135331505353315313533153135331531353315313533150535331507353315
2135331505353315313533153135331501008080ff00808080fe0080018080fd808080808080fd80808080018080fe0080808004008080808080ff008080808080808080808080808080808080808080
80808080808080808080808080808080800000000012008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f004300470000013533150535331503353315
313533153135331505353315213533150535331531353315313533153135331531353315053533150735331521353315053533153135331531353315018080ff008080808080fe0080018080fd808080
808080fd80808080018080fe0080808004008080808080ff008080808080808080808080808080808080808080808080808080808080808080808080808000000013008000000300048000030007000b
000f00130017001b001f00230027002b002f00330037003b003f00430047004b000001353315053533153335331501353315313533153135331505353315213533150535331531353315313533153135
331531353315053533150735331521353315053533153135331531353315018080ff00808080fe80808080fe0080018080fd808080808080fd80808080018080fe00808080040080808080808080ff00
808080808080808080808080808080808080808080808080808080808080808080808080800000000012008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b
003f004300470000013533153335331501353315313533153135331505353315213533150535331531353315313533153135331531353315053533150735331521353315053533153135331531353315
0100808080fe80808080fe0080018080fd808080808080fd80808080018080fe00808080038080808080ff00808080808080808080808080808080808080808080808080808080808080808080808080
800000000009010000000200048000030007000b000f00130017001b001f002300000135331d013533150135331531353315073533150735331507353315073533150735331501008080ff0080808080
808080808080808004008080808080ff00808080808080808080808080808080808080800009010000000200048000030007000b000f00130017001b001f002300000135331505353315033533153135
33150735331507353315073533150735331507353315018080ff00808080808080808080808080808004008080808080ff0080808080808080808080808080808080808080000000000a010000000280
048000030007000b000f00130017001b001f00230027000001353315053533153335331501353315313533150735331507353315073533150735331507353315018080ff00808080fe80808080808080
808080808080040080808080808080ff00808080808080808080808080808080808080800009010000000280048000030007000b000f00130017001b001f002300000135331533353315013533153135
331507353315073533150735331507353315073533150100808080fe80808080808080808080808080040080808080fe8080808080808080808080808080808080808080001400800000030004800003
0007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f000001353315313533153335331505353315053533153335331507353315053533153135331531353315
31353315053533152135331505353315213533150535331521353315053533153135331531353315010080808080ff0080ff008080808080fe0080808080fd8080018080fd8080018080fd8080018080
fe008080800400808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080000012008000000300048000030007000b000f00130017001b
001f00230027002b002f00330037003b003f0043004700000135331533353315053533153335331501353315313533153135331531353315053533152135331505353315213533150535331521353315
053533152135331505353315213533150100808080fe00808080fe8080808080fe0080018080fd8080018080fd8080018080fd8080018080fd80800180800400808080808080808080ff008080808080
808080808080808080808080808080808080808080808080808080800010008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00000135331d01353315
013533153135331531353315053533152135331505353315213533150535331521353315053533152135331505353315313533153135331501008080ff00808080fe0080018080fd8080018080fd8080
018080fd8080018080fe0080808004008080808080ff008080808080808080808080808080808080808080808080808080808080808080800010008000000300048000030007000b000f00130017001b
001f00230027002b002f00330037003b003f0000013533150535331501353315313533153135331505353315213533150535331521353315053533152135331505353315213533150535331531353315
31353315020080ff0080ff00808080fe0080018080fd8080018080fd8080018080fd8080018080fe0080808004008080808080ff00808080808080808080808080808080808080808080808080808080
80808080808000000011008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f004300000135331505353315333533150135331531353315313533150535
331521353315053533152135331505353315213533150535331521353315053533153135331531353315018080ff00808080fe80808080fe0080018080fd8080018080fd8080018080fd8080018080fe
00808080040080808080808080ff008080808080808080808080808080808080808080808080808080808080808080800012008000000300048000030007000b000f00130017001b001f00230027002b
002f00330037003b003f00430047000001353315333533150535331533353315013533153135331531353315053533152135331505353315213533150535331521353315053533152135331505353315
31353315313533150180808080fe00808080fe80808080fe0080018080fd8080018080fd8080018080fd8080018080fe008080800400808080808080808080ff00808080808080808080808080808080
80808080808080808080808080808080808000000010008000000300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f000001353315333533150135331531353315
3135331505353315213533150535331521353315053533152135331505353315213533150535331531353315313533150100808080fe80808080fe0080018080fd8080018080fd8080018080fd808001
8080fe00808080038080808080ff008080808080808080808080808080808080808080808080808080808080808080800007008000800300030000030007000b000f00130017001b0000013533150135
33153135331531353315313533153135331501353315018080fe808080808080fe808002808080ff0080808080808080808080ff0080800000140080ff800300038000030007000b000f00130017001b
001f00230027002b002f00330037003b003f00430047004b004f000001353315053533153135331531353315053533152135331531353315053533153335331533353315053533153335331533353315
05353315313533152135331505353315313533153135331505353315028080fe00808080fe008001008080fd808080808080fd808080808080fd808080010080fe00808080fe00800300808080808080
80808080808080808080808080808080808080808080808080808080808080808080808080808080800000000010008000000300048000030007000b000f00130017001b001f00230027002b002f0033
0037003b003f00000135331d01353315013533152135331505353315213533150535331521353315053533152135331505353315213533150535331531353315313533153135331501008080fe808001
8080fd8080018080fd8080018080fd8080018080fd8080018080fe008080808004008080808080ff00808080808080808080808080808080808080808080808080808080808080808080000000100080
00000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f000001353315053533150135331521353315053533152135331505353315213533150535331521353315
053533152135331505353315313533153135331531353315018080ff0080ff0080018080fd8080018080fd8080018080fd8080018080fd8080018080fe008080808004008080808080ff008080808080
808080808080808080808080808080808080808080808080808080800011008000000300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430000013533150535
3315333533150135331521353315053533152135331505353315213533150535331521353315053533152135331505353315313533153135331531353315018080ff00808080fe0080018080fd808001
8080fd8080018080fd8080018080fd8080018080fe0080808080040080808080808080ff0080808080808080808080808080808080808080808080808080808080808080808000000010008000000300
040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00000135331533353315013533152135331505353315213533150535331521353315053533152135331505353315
21353315053533153135331531353315313533150100808080fe0080018080fd8080018080fd8080018080fd8080018080fd8080018080fe0080808080038080808080ff008080808080808080808080
80808080808080808080808080808080808080808080000000150080fe800300048000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f005300000135
3315053533150135331521353315053533152135331505353315213533150535331521353315053533152135331505353315313533153135331531353315073533150735331505353315313533153135
3315020080ff0080fe8080018080fd8080018080fd8080018080fd8080018080fd8080018080fe008080808080808080fe0080808004008080808080ff00808080808080808080808080808080808080
8080808080808080808080808080808080808080808080808080808000140080ff000300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f0000
1335331507353315073533153135331531353315313533150535331521353315053533152135331505353315213533150535331521353315053533153135331531353315313533150535331507353315
808080808080808080fe0080018080fd8080018080fd8080018080fd8080018080fd8080808080fe00808080038080808080808080808080808080808080808080808080808080808080808080808080
8080808080808080808080808080800000150080fe800300040000030007000b000f00130017001b001f00230027002b002f00330037003b003f00430047004b004f0053000001353315333533150135
33152135331505353315213533150535331521353315053533152135331505353315213533150535331531353315313533153135331507353315073533150535331531353315313533150100808080fe
0080018080fd8080018080fd8080018080fd8080018080fd8080018080fe008080808080808080fe00808080038080808080ff0080808080808080808080808080808080808080808080808080808080
80808080808080808080808080808080808000000000001501020000000000000000002400480000000000000001001a00820000000000000002000e006c0000000000000003001a0082000000000000
0004001a00820000000000000005001400000000000000000006001a00820001000000000000001200140001000000000001000d003100010000000000020007002600010000000000030011002d0001
000000000004000d00310001000000000005000a003e0001000000000006000d00310003000104090000002400480003000104090001001a00820003000104090002000e006c00030001040900030022
007a0003000104090004001a00820003000104090005001400000003000104090006001a00820032003000300034002f00300034002f003100356279205472697374616e204772696d6d657252656775
6c61725454582050726f676779436c65616e5454323030342f30342f3135006200790020005400720069007300740061006e0020004700720069006d006d006500720052006500670075006c00610072
005400540058002000500072006f0067006700790043006c00650061006e0054005400000002000000000000000000140000000100000000000000000000000000000000010100000001010201030104
01050106010701080109010a010b010c010d010e010f0110011101120113011401150116011701180119011a011b011c011d011e011f01200003000400050006000700080009000a000b000c000d000e
000f0010001100120013001400150016001700180019001a001b001c001d001e001f0020002100220023002400250026002700280029002a002b002c002d002e002f0030003100320033003400350036
003700380039003a003b003c003d003e003f0040004100420043004400450046004700480049004a004b004c004d004e004f0050005100520053005400550056005700580059005a005b005c005d005e
005f00600061012101220123012401250126012701280129012a012b012c012d012e012f0130013101320133013401350136013701380139013a013b013c013d013e013f0140014100ac00a300840085
00bd009600e80086008e008b009d00a900a400ef008a00da0083009300f200f3008d0097008800c300de00f1009e00aa00f500f400f600a200ad00c900c700ae006200630090006400cb006500c800ca
00cf00cc00cd00ce00e9006600d300d000d100af006700f0009100d600d400d5006800eb00ed0089006a0069006b006d006c006e00a0006f0071007000720073007500740076007700ea0078007a0079
007b007d007c00b800a1007f007e0080008100ec00ee00ba0e756e69636f6465233078303030310e756e69636f6465233078303030320e756e69636f6465233078303030330e756e69636f6465233078
303030340e756e69636f6465233078303030350e756e69636f6465233078303030360e756e69636f6465233078303030370e756e69636f6465233078303030380e756e69636f6465233078303030390e
756e69636f6465233078303030610e756e69636f6465233078303030620e756e69636f6465233078303030630e756e69636f6465233078303030640e756e69636f6465233078303030650e756e69636f
6465233078303030660e756e69636f6465233078303031300e756e69636f6465233078303031310e756e69636f6465233078303031320e756e69636f6465233078303031330e756e69636f6465233078
303031340e756e69636f6465233078303031350e756e69636f6465233078303031360e756e69636f6465233078303031370e756e69636f6465233078303031380e756e69636f6465233078303031390e
756e69636f6465233078303031610e756e69636f6465233078303031620e756e69636f6465233078303031630e756e69636f6465233078303031640e756e69636f6465233078303031650e756e69636f
6465233078303031660664656c657465044575726f0e756e69636f6465233078303038310e756e69636f6465233078303038320e756e69636f6465233078303038330e756e69636f6465233078303038
340e756e69636f6465233078303038350e756e69636f6465233078303038360e756e69636f6465233078303038370e756e69636f6465233078303038380e756e69636f6465233078303038390e756e69
636f6465233078303038610e756e69636f6465233078303038620e756e69636f6465233078303038630e756e69636f6465233078303038640e756e69636f6465233078303038650e756e69636f646523
3078303038660e756e69636f6465233078303039300e756e69636f6465233078303039310e756e69636f6465233078303039320e756e69636f6465233078303039330e756e69636f6465233078303039
340e756e69636f6465233078303039350e756e69636f6465233078303039360e756e69636f6465233078303039370e756e69636f6465233078303039380e756e69636f6465233078303039390e756e69
636f6465233078303039610e756e69636f6465233078303039620e756e69636f6465233078303039630e756e69636f6465233078303039640e756e69636f6465233078303039650e756e69636f646523
3078303039660000
]],
["resource/fonts/ProggyForever.ttf"] = [[
00010000000d0080000300504646544db071471100004e180000001c474445460027001800004df8000000204f532f326861dc280000015800000060636d61709393e3be000003440000018a67617370
ffff000300004df000000008676c7966789d738700000658000041a8686561642c3ad262000000dc0000003668686561043e00e60000011400000024686d747817821441000001b80000018c6c6f6361
99df8a52000004d0000001866d617870010900e400000138000000206e616d65b5c86e22000048000000041a706f7374a844032500004c1c000001d10001000000010000e47302ad5f0f3cf5000b03e8
00000000e5afbb4200000000e5b3d43bffe1ff4401d702bc000000080002000000000000000100000283ff47000001b8ffe1ffe201d70001000000000000000000000000000000040001000000c200e1
000500000000000200000001000100000040000000000000000401b8019000050000028a02bb0000008c028a02bb000001df003101020000000000000000000000008000000710000002000000000000
00005858585800400020e9120283ff47000002af00bb00000003000000000185020600000020000101b800060000000001b8000001b8000000a60074fff900310005000400b900870087001b0016009a
003500a600270029004f0032002d001600310029002e0027002900a6008f001800180018002fffe100050026002f00270034003a0023002a0042004100130031001300290023002c000d0026002a0009
0025000dfffa0000000500210068002700680025fff2007c00300032003b0032002500280032003e008b0064002900850014003e002a003200320045004500570036001dfff90014002f0040003f00bc
003f0016009f003f00280037000500bc0040006dfff9005c0032fff9006d006500180073006d008300250030009f008f00720053003200130013001200490005000500050005000500050002002f0034
00340034003400420042004200420011002a0023002300230023002e0001002e002e002e002f0005002a002a0026002600260026002600260005003b00250025002500250033004400440044002a003e
002b002b002b002b002b0018000c003d003d003d003d001a0032001a00260015001e001800000003000000030000001c0001000000000084000300010000001c0004006800000016001000030006007e
00ab00d200d300ff01010178202620ace912ffff0000002000a100ae00d300d401010178202620ace912ffffffe3ffc1ffbfff5fffbeffbdfec4e099e01417af00010000000000000000000000000000
00000000000000000000010600000100000000000000010200000002000000000000000000000000000000010000030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2021222324
25262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f6061008384868890949a9f9ea0a2a1a3a5a7a6a8a9
abaaacadafb1b0b2b4b3b8b7b9ba006f63646800759d6d6a00736900859600700000667400000000006b7900a4b67e6200000000006c7abf007f82930000000000000000b500bd3c00c0000000000076
0000008189808a878c8d8e8b329200919899970000006e0000007700000000000000002800280028002800440056008600d4010e016a0176019601b601d601ea02080216022802380266027c02ae02ea
030603400378038a03d80410042c0456046a047e049204d4052e0548058405ac05c805e005f40628063c0654066e0686069606b006c606f00750078207aa07f60808082e0840085c0874088808a008b2
08c208d408e608f409020950098009a209d209fa0a1a0a540a720a900ab60ace0ade0b0e0b2e0b4c0b7c0bac0bce0c0a0c260c480c5c0c780c900d0c0d260d5e0d6a0da20dd60df20e220e4a0e800ea6
0eba0f260f480f800fd20fee10321040105e107a10a210dc10ea1120113e1150116a117e11a411c011ee122c127e12b812d812f8131c1350138413ba13de141814361456147814aa14c814e61508153a
156e15a015d016041648168c16a616e6170a172e1756178e17aa17cc1812186818be1918198819f21a581b161b4e1b7c1bac1bde1c221c401c601c821cb41cfc1d3c1d621d881db21df01e2a1e5e1e96
1ec21eee1f1c1f5c1f881fae1fee2044208420c420d4000000050006000001b202bc000300060009000c000f0000132111211b020b01111303210313110601acfe541cbabac6b4c0b80172aeb602bcfd
4402a8fecb0135feb6012cfda70118fecc0149fed1025d00000200a6fffe011202230005000d00003723033733150232161406222634fb3b0e0153402c20202c20c401045b5bfea11f2c20202c000000
000200740146014402070003000700001323353317233533b541418e40400146c0c0c0000002fff8000301bf0203001b001f000001230733152307233723072337233533372335333733073337330733
0737230701bf681f5c6a263b265c263a26606e1f6270263b265c263a265ac11e5c1e013c73368f8f8f8f36733690909090a9737300030031fff1018702160028002d00340000131e031514071523352e
012f01351e0217352e03353436373533151e011f0115262715322735061514173e0135342627fe16282e1c8d3c24430f0f061545251f2c2b164b413c19370f0f2b43023e4884202924250121040f1c32
21720f2c2b010e06063f040b1603a2060f1a2a1d3543092d2a020b05053e1d04960c870c3d2cee07251f1e200a00000000050005000b01b201fa0007000f0017001f0023000012140622263436320614
1632363426221632161406222634163236342622061413330123d13c543b3b545c1e291d1d29cb543c3c543b51291e1e291d2f47fede4701c14f38384f384c271b1b271bfd384f38384f561b271b1b27
01a1fe1500030004fff601b3021500220035003f000025163123262706232226353436372e0235343633321615140e0207161736353714011c021e05173e013534262322061332372e01270615141601
7043480d153c594868342c16130f3f3c3d330f201918593a243dfec301020306080c0725251f171823603425196e1841504f4f0f18316042324a21191928182945373114242214116b454148016c010d
01070307050a090d1009192818151920fe6c241c831c363b303e0000000100b9014600ff02080003000013233533fe44440147c100010087ffc10131023e00110000010e01141617232e04343e023f01
01312b37372b3c040f261d181720210b0b023d3cb1a1b13c061544466761664b3d10100000010087ffc10131023e00110000131e04140e020f01233e01342627c3040f261d181720210b0b3c2b37372b
023d061644476761654b3c10103cb1a1b13c00000001001b0045019d01c700110000010717072715233507273727371735331537019d83832180408120838320814080014d474732468e8e4632474732
468e8e4600010016004a01a201b9000b0000133315231523352335333533fba6a63ea6a63e011f3b9a9a3b9a0001009aff81011e006b0010000036321615140e020f012736372e013534d12d1f151f1e
0b0b1a370a11196b2016203d28200707253029011f1516000001003500e30183012000030000252135210183feb2014ee43c0000000100a6ffff01120069000700003632161406222634c62c20202c20
691f2c1f1f2c000000010027ffde0190022700030000090123010190fedd4501220227fdb802480000030029fff7018f020e00050010001b000013321023221017220e03151417372603323e03353427
0716dcb2b2b2b2111c1f140e04bd1a39111c1e150e04be1b020efdea02163a081a2c4e352721e534fe5f071a2c4e352822e634000001004f000001680207000a0000132737331133152137331151016a
4469fee901690167514efe373d3d017a000100320000018602110020000013273e0233321e0215140607063121152135343736373e01353426232206073701081d5125304824112c3b930101fead0d01
a525283a2d1a4b18019f4105101b1e302e15284e3a923d2e0e0c01a5265021212f1b0d000001002dfff6018b02100029000001161514062322262f01351e023332363534262b01353332363534262322
060f013536333216151406011a706b55224e1617071950293941413140402e38372d214814144a444e623301161e6d41540d070645040c1333312e343a2d26252b0e070740174a3b3237000000020016
000001a20207000a000d00002533152315233523351333031103014a585843f1d0643ab3b53a7b7b490142feaf0112feee00000000010031fff601870207002800001311211523153633321e0315140e
022322262f01351e0233323e0235342e0223220607480121dd18291930332618233d43262b460e0e07184c261527271717282c191c380e010201043b7f0b0a19263f28314826120b060547040b130b19
30212130190c0d0700020029fff8018f0208001b0025000013321e0215140623222635343e023332161f011526232206153613323534232206151416ea1f38311d5b525762243f4f30182e0b0a1f3b45
59244e6565293b3b01571428442b5a597288496e3f1f08040342195f6248fed9777939403f3800000001002e0000018a020700060000133521150323132e015bc54ebe01cb3b1dfe1701ca0000030027
fff6019102110014002400340000011e0115140623222635343726353436333216151426220e02141e02323e02342e0102323e02342e02220e02141e01012c3034684c4d6863545f47466093251d1d10
111d1c241c1e10101d442a2020121221202820211212200115104834454e4d466b211e5b3e45463d5aa606112535251006061025352511fe5907142a3f2a130707132a3f2a140000000200290000018f
0210001b0025000037222e0235343633321615140e022322262f013516333236350603221514333236353426cd1e39301d5b52566324404f2f182e0b0b203b4459234f64642a3b3cb11427442c595a72
88496e3f1f08030441185f62480127787838404038000000000200a60051011201ab0007000f000036321614062226343622263436321614c62c20202c204c2c20202c20bb1f2c1f1f2ca51f2c1f1f2c
0002008fffd1011201ab00100018000036321615140e020f012736372e0135343622263436321614c62c20161e1f0b0a1b370a11194d2d1f1f2d1fbb2016213c291f0707253029011f1516a61f2c1f1f
2c00000000010018005401a001b0000600001325150d011525180187fec80138fe79011e913e6f703e910000000200180098019f01720003000700000121352115213521019ffe790187fe7901870137
3bd93b0000010018005401a001b00006000013051505352d01180187fe790138fec801b09139913e6f7000000002002f00000187021f0007002e0000363216140622263413321615140e031d01233534
3e0435342623220e020f012e03173e04c22d1f1f2d1f3f53521d2a2a1d461521262116342b192d1d160405030c170f01020a22263d6a1f2c1f1f2c01d444341c2f211e2111292916271c1d171f101e21
10171708080207100a01040e231a16000002ffe1ffe901d702200039004100002535170e0423222e0335343633321615140e02071523350623222634363332161f013235342623220615141e0233323e
0237263236342622061401b026020b262b47253f67432e148d6969800f18150a37242b374f50371c310a0b2d54465176273d4b272340281e07d33c2b2b3c2b67012e040b1b151121374a4f2a78a34e43
1823110701c6131f5d835e1a0d0d1c22397c683557371e0d14140747384f39394f00000000020005000001b202070007000a000001132327230723130333030109a94d29c1284da9229e4f0206fdfa88
880206feba010900000300260000019202070015001e00270000011e0415140e022b011133321e021514062715163736353426231332363534262b011501210c172219121e32391fc2b12b3e200f31d2
472754312a0841343e2d7901160307141b301f2639200e0205192b2e182a37b29c0102044c2a21fe6d2f342f2bbd00000001002ffff801890212001a000025150623222e02353436333217152623220e
0215141e0133320188314f3856321870684d33334d2639200f1a42324d5d491c2a4a5f3a759720472d213b4a2e3e5b3b000200270000019002070007000e00001332111023063111133235342b0111c7
c9c8a09f7d7d540206fefdfefe010206fe34cac9fe6d000000010034000001830207000b000013211521173315231521152135014dfefd01e3e40104feb202063b993bbc3b0000000001003a0000017e
020700090000132115231f01152315233a0143f901b5b64a02063b9e013bf10000010023fff801940212002400002527233533150e0423222e02353436333217152623220e0215141e0133323637014e
0163aa02071b20361e3855331870684e32334d2639200e1942321b2907438d3adf0207120d0b2a4a5f3a759720472d213b4a2e3e5b3b0a050001002a0000018d0207000b000033113315333533112335
23152b4bcc4b4bcc0206d4d4fdfaf7f600010042000001750207000b00001335211523113315053537114301327474fece7301cb3b3bfe703a0139010191000000010041fff901760207000e00001333
111406230631353332363511239ed8424ea49330258c0206fe9e505a0139303a012f000000010013000001a50207000b0000331133153733071323030715134be955d4dd5ab4390206e6e6d4fece0104
39ca00000001003100000187020700050000371133112115314b010a010205fe353a000000010013000001a40207000c0000331133173733110711032303111464636564416b396a0206fefefdfb0101
c5feef0113fe3a00000100290000018e020700090000330333131133112303112d0362ba485fba0206fe5a01a6fdfa01a6fe5a0000020023fffa0195021200050019000013321023221012323e03342e
03220e03141e02dcb8b8b8a7221b1e140d0d141e1b221b1e140e0e141f0211fdea0216fe25081a2b4e6a4e2c1a08081a2c4e6a4e2b1a00000002002cffff018b02070010008100001332161514062b01
1c011e011c0131231117323e0235342e022b0115390a3339023339013331333133313331333133313b02313b41db555b55546c01014ba1202e160a0a152a1e5d01010101010101010101010101010101
0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010102065046475905153730321d0206fc131f1f11
111f1f12c30000000002000dffb801ab020f000c002000001332111407171523270623221012323e03342e03220e03141e02c6b828543052283ab8a7221a1f140d0d141e1b221b1e140e0e141e020efe
f57b43612c5b1b0216fe25081a2b4e6a4e2c1a08081a2c4e6a4e2b1a00020026000001910207000d00170000370723113332161514060717232737231516373e01353426720348b34f53392c7a4f6f02
634427223335dbda020559452d4510e5d9f3b80102022e2d2b2f00000001002afff6018d02110036000001152e0223220615141e07171e031514062322262f01351e02333236353426272e0335343633
321e0217016d061543233e3d060e0b190c1f092101172a301d65592b4e1212071b562d2d423d4522302f1867571228201b0801f547040d1529300b120f0b0a05070305010411213a274e4a1009084905
101b2e2d2e250e06111f3222485205080902000000010009000001af02070007000013352115231107110a01a4ac4b01cb3b3bfe360101cb00010025fff6019302070018000037113311141e02333236
35113311140e03222e03254c06132b2043304b061626445f46261607a60160fe991a2322123643015ffead21303521161520322c0001000d000001ab0207000600003303331b013303aea149868648a1
0206fe3a01c6fdfa0001fff9000001be0207000c00003303331b01331b013303230b014b513f3a3f53403940514948490206fe63019dfe62019efdfa01b8fe480001ffff000001b90207000b00001327
33173733071323270723b8a050797b51a5b1508d8d500113f3c3c3f3feeddada00010005000001b2020700080000370333173733031523b6b04f878650b14bea011ce4e4fee3e9000001002100000197
02070009000013352115012115053501290166fee00128fe8a011801cb3b35fe6a3a01380193000000010068ffbd01500249000700000127113315231133014fa2a2e7e7021201fde238028c00010027
ffde0190022700030000130123016d012346fede0227fdb80248000000010068ffbd0150024900070000133311233533110768e7e7a3a30249fd7438021e010000010025013f01930207000600001317
2327072337fc9652646552960206c68d8dc600000001fff1ffbe01c7fff7000300000521352101c6fe2c01d4423800000001007c01a0013c02390003000013172327cf6c526d02399999000000020030
fff60188018f0026003800001315321e02150631233627062322263534373e011f01303c012e0623063135323613323e03352223260e04151416d6263a341d013d02022663404f6817551e1f02030709
0f121a107a123a182030170d020a15182d2720160d33018f010c21412ff1191b3d3f3e5d1d060501010e07110a100a0c0705023602fe9d1a21311b110102030a121c14252300000000020032fff70186
02310014001e00001332161514062322262f0107231133153e0402323635342622061514e84757583b203e100f073d44010512172b247032336e34018e6665626a1d0f0f31022fdd030814100cfe9f52
44435353434400000001003bfff7017d018f00140000012206151416333237150623222634363332171526010d414848413e312f4e556e6e554e2f3101594a4c4c4a2b41206ac46a20412b0000020032
fff7018602310016001e000001331123270e0423222635343633321e021f0102323534262206150142443e0603081a1b29143b585746192a18110304c8c83068300230fdd1310307150f0d6a6265660c
11110607feda96435353430000020025fff70193018f0014001a00003714163332363715062322263534363332161514312722061533346c3e432a3e2e4652596d694f5b5aaf2f45e0b4384f1215401d
6d5f5d6e614930a54430740000010028000301900224001300000122061d013315231123112335333534363b01150128231f7d7d447a7a41406c01ed19254b39fed9012739344e3e3700000000020032
ff460186018f001d0027000001331114062b013533323e023d010e04232226353436333216170332353423220615141601483d5a5182881c2a170a010512182a19475b5b3c30341c6b63633533330185
fe6e56563a162425123b0206100c0a65646265141dfed78e965244414d0000000001003e0001017a0231001200001332161511233534262322061d012311331536fd35484428252f3844442501924e43
ff00fa2d303d3bdf022fda3c0002008b0001012d021e0005001100001335331123113723223d01343b01321d01148ba1443b380a0a3809014b3bfe7b014a7f0a400909400a00000000020064ff460154
021e000b001800000123223d01343b01321d011407353311142b01353332363511014a380a0a3809aeae7f70691d2501ca0a400909400a7e3afe62a13b34320164000000000100290002018e021e000b
0000371723270715231133113733d2bc519a334646b550f5f3c92d9c021bfec9a1000000000100850001013302080005000013331123112385ad45680207fdfa01ca000000010014fffe01a4018f001e
000001321615112311342322060711231134232206071123113315363332173e0101442b343d341a1a033d341a1a033e3e1f2a341a0d30018f4535feea0105542225feee0105542124feec0185121d31
161b00000001003e0001017a0193001200001332161511233534262322061d012311331736fd35484428252f384440042501924e43ff00fa2d303d3bdf0185303c0000000002002afff7018d01900007
0011000012321615142035341632363534262206151489a65efe9e835c3a3b5a3b01906666cdcd66fe4850504646505000020032ff4e018601880016001e000013321615140623222e022f0115231133
173e040232363534221514eb42595747192918120303443d070106141929236730c70188696365670c12110606dd023031020814100dfe9e524394944300000000020032ff4e018601880016001e0000
01331123350e0423222635343633321e021f01023236353422151401483e44010512182a194657594217291a130404a26830c8017efdd0dd0208150f0d676563690c12110606fed95243949443000000
0001004500000173018e001300000132161f01152e022322061d01231133073e01010c1d340b0b0410381f38474444021145018e0f070841050c143c23f50185351b230000010045fffe017301970029
0000371e011514062322262f01351e02333e013534272e0135343e023332161f01152e022322151416e8464558491f461414081c491d2e315b53390e20412c213e0e0f06133f215a24ea0b2e3739420c
060641040c1501241a310f0f352c162624140b06063e040b1139191d00010057000601610204001200003732311523222e03351133153315231514d8887d192129181044a2a2413a030f1a3222017c76
3acc460000010036fff601820185001600003735331514333236353631331323350e042322263644562c3e03440140010311172d1b4f4991f4f1663527fbfe7c2a0207130d0c4a000001001d0000019b
0185000600000133032303331301544694569347780185fe7b0185feba0000000001fff8ffff01c00185000c000001330323270723033313373317017c43613f444141614444354c3c0185fe7bd7d701
85fed0c0c000000000010014ffff01a30185000b00002517232707233727331737330101a24e7a784ea2954c6e6d4ccbcb9b9bccb98d8d000001002fff440189018600ae0000011215140e022b013533
323e04353435390323390223390123312331233123312331233123312b01312b02312b6d222635123133151416331631030186030c182f20c3b010170d08030101010101010101010101010101010101
0101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101
0101010101010101010101010101010101010101010101010101010a474801441d2989010185fe8730112f34243b0c181622110e04024e310106e5313201014900010040ffff01770186000e00003733
1721353e0327223135211589ed01feca0f32694501e5012d34343b113a7a5201323c00000001003fffb201780254002a000001151407161d0114163b01152223222e033d0134262b01353332363d0134
3e0333323115232206010b4848262a1d1f0d26361b0e03262b33332b26030e1b36262c1d2a2601d7645f11116063221d3e141a2c1e17562b2042202a57171e2c1a133e1d000100bcffc800fc023f0003
000017231133fc40403702750001003fffb201780254002a0000133534262b01353233321e031d0114163b01152322061d01140e03232231353332363d01343726ac252a1d1e0e25361b0f02262c3333
2c26020f1b36252c1d2a254848017364211d3e131a2c1e17572a2042202b56181d2c1a143e1d2164601110000001001600b101a1015d0021000001170e0423222e03070e010f01273e0433321e03373e
013701673a050511152819192b1e1c1f10141903033a050511152819192b1e1c1f1014190301420d15152d18141a23241502032d15150d15162c18151a24231603032d140002009fffeb011902090005
000d00001333170723351222263436321614c42e1d01654c3223233223014bc49b9b010a23312323310000000002003fff93017901f20016001c0000011136371506071523352e013534363735331516
17152603110e011514011939272d33264e666450263d23285e323a0158fed702193b15036465066b5c5f6804616205143c19fede012606494386000000010028ffff01900210001b0000373315213533
352335333534363332161f0115262322061d01331523cac5fe99574949524f2134090a302a323288883b3b3ba1325258580a0505401e353f5832000000020037003f0180017d0017001f000000140717
072706222707273726343727371736321737170706323634262206140159163c223e1f491f3e223c16163c223e1f491f3e223c88412e2e412e0103491e39233c13133c23391e491e39233c13133c2339
8d2c3d2b2b3d000000010005000001b20207001800000107331523071533152315233523353335272335332733173701b2785b732194944b949421735b774f87860206c227350b27b6b6270b3527c2e4
e4000000000200bcffce00fc02390003000700001323113311231133fc4040404001320107fd95010800000000020040ffbc01770210003b004b0000251e011514062322262f01351633323635342627
26272e04353436372e013534363332161f0115262322061514161716171e04151406273e013534262726270e011514161716013019154548193910103a33242a252f08031c1927110e26211915444a18
360e0e33332528242f08031d1827110e2647151c302e1916161b302d19751222172c420a0505391a2019141e1a0402100e1c1722131c32101222182b3b0a0505391b1a19141e1a04020f0f1c1721141c
32090c230f1a2c190e0d0c240f1a2c190e0000000002006d01d4014b021b000b001700001323223d01343b01321d01143323223d01343b01321d0114b03a09093a088a3a09093a0901d5093409093409
09340909340900000003fff8002801c001da0014001c0024000036343633321715262322061514163332371506232202321614062226341232363426220614544e3e391e2b222f34342f2e1f24333d25
bc8585bc86969c6f6f9c6fc37e420f26153031312f122411015b7fb37f7fb3fef4699369699300000003005c00a2015b021200280037003b00003722263534373e011f013c012e022322060f01353e06
333216151431232e031506372223220e0415141633323617233533c72f3b4d113d1615080f20161a320b0c021207110c11120939492d01020302282805081918251314082416312935f7f7f22c2b4314
05030101080a160e0b0b06062c0106020602030139409f0208110c012d8e0103060b120d18183db62b000000000200320031018601700006000d00001307171527353733150717152735df6f6fadada7
7070ae012d5d5d42911c92435d5d42911c0000000004fff8002801c001da0007000f0023002d0000123216140622263412323634262206143716171631232627262322311523353332151406273e0135
34262b0115167ebc8585bc86969c6f6f9c6fe6111a2a341e1115181b2f5c67223d131b1d15311f01da7fb37f7fb3fef469936969933e0726412c1a2167f24a15201201141313144f010000000001006d
01b7014b01eb0003000001233533014adcdc01b733000000000200650132015202100007000f000012321614062226341632363426220614ab6245456245583b2a2a3b29020f415b41415b7027372727
3700000000020018ffff019f01970003000f000005213521273315231523352335333533019ffe790187a4a4a43ea5a53e013bea3b73733b72000000000100730185014502ad00190000133315233536
37363534262322060f0135363332161514060706ad98d24d202a251c112a0c0d2733393a1b245601ac2726481d282412190b06062914331c162d224d0001006d0182014b02b000270000011406232226
2f0135163332363534262b01353332363534262322060f0135363332161514060716014b443715310f0e322a1a302b1f1f1f1d241e1b152c0c0c2f2c313f211e4701d6252f0704042a121a19191b2616
1512160804042a0d2a211c1d070d00000001008301b5013502390003000013330723eb49783802398300000000010025ff6b01920184002500002532363f0115062322262f010e042322262715231133
151416333236353631331015140178070c04031b1d131a0403010410162a1b1a2f0b3c402d252b3b034131040202340f1a0d0d0207120e0b1c1ac00218f130353526fbfee2181d0000010030ffb90188
020700100000133311231123101506222f011122263436d8af3446011a0d0d4563630206fdb60220fde5050201010127557955000001009f00c60119013f000700001232161406222634c33223233223
013f2332232332000001008fff7701290001000e0000211615142322262f013516333227300100285b0e1f0808181b5b4929253b0402022e0b5e0000000100720184014602a7000a0000133315233533
3507353733fa4bcc4c53553301ab2626d40e280d0003005300a2016502100007001100150000242035343632161526220615141632363534132335330164feef497f4966452e2d472d2af9f9f38f4747
4747652f363631313636feeb2b000000000200320031018601700006000d00001317150735372717150735372735d8aeae707007ad6f6f0170921c91425d5d4f1c91425d5d43000000040013ffa201a5
0240000a00150018001c000013073537331533152335331715331523152335233537073335371705277b5257304bcb4bf72b2b3290865d665c09fe7809021a0e270dfc272780bc2541412ab7bb909625
5b25000000030013ffa201a50240000a0024002800001307353733153315233533130631331523353637363534262322060f012736333216151406371705277c5257304bcb4be05698d24d202a251c11
290d0c012733393b1c1b09fe7809021a0e270dfc2727fed24d2727471e272413190c06062a13331b172df7255b25000000040012ffa201a50246002600310034003800000114062322262f0135163332
3634262b01353332363534262322060f0135363332161514060716171533152315233523353707332737170527010c483715300d0d292e242a2622211e1f252119182d0a0a2e2c323e211e48692b2b31
91865c66015909fe7809016c242f07040429121d2f1c25171514140804042a0c29201d1d080ee9bc2541412ab7bb9096255b250000020049fff7016f021b00070026000000222634363216140332363f
01150e0223222635343e043d013315140e0315141601092c20202c203e1d42121307184522524e131d221d13471a25261a2f01b11f2c1f1f2cfe60180b0c41050c154136182b1e1e181f11453d1e3022
1f27151f2400000000030005000001b302830007000a000e00000113232723072313033303372327330109a94d29c1284da9229e4f2d3854440206fdfa87870206feb9010a5d5c0000030005000001b3
02830007000a000e00000113232723072313033303370723370109a94d28c1294da9229e4f5f5438480206fdfa87870206feb9010ab95c5c00030005ffff01b302830007000a00110000011323272307
2313033303350723373317230109a94d28c1294da9229e4f3d334e454e330205fdfa87870206feb9010a9d3e5c5c000000030005fffe01b3027b0007000a001f00000113232723072313033303272206
1523343633321633323635373314062322260109a94d28c1294da9229e4f330c0c2f24221a3e0f0b0d012e22241c3a0205fdfa87870206feb9010a891310212b221109081933230000040005ffff01b3
0283000b0017001f002200001323223d01343b01321d01143323223d01343b01321d01140713232723072313033303b03a09093a09893a09093a0942a94d28c1294da9229e4f023d0934090934090934
0909340938fdfa87870206feb9010a0000030005fffe01b30295000f001c001f0000011323272307231326353436321615142733141617333e01353426220603330301139f4d28c1294d9f2f3c543c9f
0112102c1013212f22169e4f01e6fe19878701e71c33283737283334111a06061a11151f1ffe73010a00000000020002ffff01b60207000f001300002515331523352307231325072317370f01112303
013580ca7f2544960117017a016f01b9254bf6bc3b86850205023d99013c38010dfef4000001002fff77018902100028000001220e0215141e0133323715060716151406232227351633323534272e03
353436333217152601082639200e1942324d332538212d262d19181f2e1a3651301770684d333301d5203c4a2e3e5b3b2e49150524201f1e092d0b1f1620032a4a5d38759720472d0002003400030184
02870003000f00000123273303211521112115231f011523010d395444450104feb20147fd01f1f2022a5dfdb83b02063b99013b000200340004018402870003000f0000010723370321152111211523
1f011523012c543848690104feb20147fd01f1f202875d5dfdb93b02063b99013b000000000200340004018402880006001200001307233733172303211521112115231f011523d53d344e464e349301
04feb20147fd01f1f202693e5d5dfe153b02063b99013b0000030034000001840285000b0017002300003721152111211523173315231323223d01343b01321d01143323223d01343b01321d01147f01
04feb20147fd01f1f2313a09093a09893a09093a093b3b02063b993b0148083409093408083409093408000000020042fffe017602830003000f000001232733172311171521353311233521010b3854
44b27373fece7474013202265cb8fe6f01393b01903b0000000200420003017602870003000f0000010723371723113315213533112735210139543848807474fece7373013202875d5db8fe703b3901
91013b000002004200030176028800060012000013072337331723172311331521353311273521e13d344e464e34577474fece7373013202693e5d5d5cfe703b390191013b00000000030042fffe0176
0283000b0017002300000123113315213537112335212723223d01343b01321d01143323223d01343b01321d011401757474fece73730132c53a09093a09893a09093a0901cafe703b390101913b3809
34090934090934090934090000020011000401a7020b00120024000013321e03140e03232231352335333513323e03342e032b011533152315c91f383d2d1d1d2d3d381e8b2e2e8913242a1e14141e2a
24133e6363020b0c23375f7d6036230bf535dcfe33091b2a4b624b2a1b08a235bc0000000002002a0000018e02820009001e000001331123031123033313032206152334363332163332363537331406
2322260146485fba470462ba9d0c0c2f24221a3e0f0b0d012e22241c3a0206fdfa01a6fe5a0206fe5a01f81310212b22110908193323000000030023fffa0195028700030009001d0000012327331732
1023221012323e03342e03220e03141e02011239544413b8b8b8a8211b1e140d0d141d1c221b1e140d0d141f022a5d76fdea0216fe25081a2b4e6a4e2c1a08081a2c4e6a4e2b1a0000030023fffa0195
02880006000c002000001307233733172307321023221012323e03342e03220e03141e02dc3d344e464e343db8b8b8a8211b1e140d0d141d1c221b1e140d0d141f02693e5d5d1afdea0216fe25081a2b
4e6a4e2c1a08081a2c4e6a4e2b1a000000030023fffb0195028100050019002e000013321023221012323e03342e03220e03141e02032206152334363332163332363735331406232226dcb8b8b8a821
1b1e140d0d141d1c221b1e140d0d141f080b0d2f2423193e0f0b0d012e22231d3a0211fdea0216fe25081a2c4e694e2c1b07071b2c4e694e2c1a02191310212b221109081933230000040023fffa0195
0288000b0017001d003100001323223d01343b01321d01143323223d01343b01321d011407321023221012323e03342e03220e03141e02b03a09093a09893a09093a096fb8b8b8a8211b1e140d0d141d
1c221b1e140d0d141f024209340909340909340909340931fdea0216fe25081a2b4e6a4e2c1a08081a2c4e6a4e2b1a000001002e004101890189000b0000010717072707273727371737018981812d80
812d81812d8180015e79792a79792a79792a797900030001ffea01b702220011001c00270000010716151023222707273726351033321737011417372623220e0313323e03353427071601b7411eb853
2e3624411eb8532e36fede07b91a3b111b1e140d6b111b1e140d07b81a0208584169fef5384819584169010b3848fee5382af93a081a2c4efefb081a2b4e35382af83a000002002efff6018a02830003
001500000123273317331114232235113311141633323e02350113395445734baab04b273d1e28130702265c7cfea0b0bd0153fea0433412212419000002002efff6018a028300030015000001072337
17331114232235113311141633323e02350132543948514baab04b273d1e28130702825c5c7cfea0b0bd0153fea04334122124190002002efff6018a0283000600180000130723373317231733111423
2235113311141633323e0235dc3d344e464e34254baab04b273d1e28130702653e5c5c21fea0b0bd0153fea043341122241900000003002ffff6018a0283000b0017002900001323223d01343b01321d
01143323223d01343b01321d011407331114232235113311141633323e0235b13a09093a09893a09093a090e4cabb04b283d1e271307023d09340909340909340909340937fea0b0bd0153fea0433411
2224190000020005ffff01b302820003000c00000107233717330315233703331701365439497050b14b01b14f8702825c5c7cfee3e9ea011ce500000002002affff018e0206000b0014000013321615
142b0115231133151732363534262b0115dc535fb2674b4b5d313d3f2f5d01aa4b4a967f02065cf02b302f2ab40000000001002afff2018e021c0030000013141e0315140e012627351633323635342e
0335343e023f0126362e022322061511231134363332152206ea22303021334e58263133292d212f2f211823220c0c01030a0e261b2e294449529b2f48013214211b2035232b391405103815241d1825
191b2d1e1c2c180f0202010f1716103032fe7b01854d4a982c00000000030026fff501920245002b003a003e0000251514161f012326270e012322263534363332313c022e052322060f01353e063332
03323e0227302a01230e0115141613232733017e0a0505440907154c2641505b5b5c0206080f141e122647101103190b1811181a0da8c124341a0a01242f0b3c34336f397648e27419370f0f16252025
403c3e46010f09120d100b0a05120a093f01090308030402fe9b1d2f321a02202c2624019783000000030026fff501920245002b003a003e0000251514161f012326270e012322263534363332313c02
2e052322060f01353e06333203323e02272a02230e0115141613072337017e0a0505440907154c2641505b5b5c0206080f141e122647101103190b1811181a0da8c225341a0a0101232f0b3c3433b776
3967e27419370f0f16252025403c3e46010f09120d100b0a05120a093f01090308030402fe9b1d2f321a02202c2624021a83830000030026fff501920245002b003a00410000251514161f012326270e
012322263534363332313c022e052322060f01353e06333203323e0227302a01230e0115141613072337331723017e0a0505440907154c2641505b5b5c0206080f141e122647101103190b1811181a0d
a8c124341a0a01242f0b3c34333f42345a385a34e27419370f0f16252025403c3f45010f09120d100b0a05120a093f01090308030402fe9b1d2f321a02202c262401ef588383000000030026fff50192
0233002b003a00540000251514161f012326270e012322263534363332313c022e052322060f01353e06333203323e0227302a01230e011514161333221523343633321e013332363d0133140e022322
2e02017e0a0505440907154c2641505b5b5c0206080f141e122647101103190b1811181a0da8c124341a0a01242f0b3c343309011a2d242515221e0d0c0d2e050d1e15151f1116e27419370f0f162520
25403c3e46010f09120d100b0a05120a093f01090308030402fe9b1d2f321a02202c262401dc362b371b1a1a0d0e0f1d211511141100000000040026fff50192021d002b003a00460052000025151416
1f012326270e012322263534363332313c022e052322060f01353e06333203323e02272a02230e011514161323223d01343b01321d01143323223d01343b01321d0114017e0a0505440907154c264150
5b5b5c0206080f141e122647101103190b1811181a0da8c225341a0a0101232f0b3c3433103a09093a09893a09093a09e27419370f0f16252025403c3e46010f09120d100b0a05120a093f0109030803
0402fe9b1d2f321a02202c262401ab0934090934090934090934090000040026fff501920272002b003a0042004a0000251514161f012326270e012322263534363332313c022e052322060f01353e06
333203323e02272a02230e0115141612222634363216142622061416323634017e0a0505440907154c2641505b5b5c0206080f141e122647101103190b1811181a0da8c225341a0a0101232f0b3c3433
66543c3c543c4f2e21212e21e27419370f0f16252025403c3e46010f09120d100b0a05120a093f01090308030402fe9b1d2f321a02202c2624018638503838505d1f2c1f1f2c000000030005fff501b3
018f00ca00d600e000002515303901233901233123312b7b1c021e053316363f01150e0223222e022f010e042322263534363b013534262322060f01353633321e021f013e04333216171e0115073631
2322061514163332363714313336272e01232201b20101010101010101010101010101010101010101010101010101010101010102010101010101010101020101010102010101020101010201010201
01020101020102010102010201020102010201020102010201020102010202010201020201020201020201020201020202010202020102020201020202020102020202090204060a0e150c2234090a05
0f3019192a16100203010410152416393c4644322a1e132e0d0e2c41131e120c020201030e1324163a30080201f4011c352c2517231b41790102031b1f39b301011c0a1c0d170b0e060111090a3c030a
100b111006050207130f0c3c3839411c32270e08073a18090d0d040502060f0b0a3b4c122a0c42362026231f24b01b17162326000001003bff77017d018e00250000012206151416333237150e010f01
16151406232227351633323534272e013534363332171526010d414848413e310e2b0f0f212d262d19181f2e1a526a6e554e2f3101584a4c4c4a2b410b0f020224201f1e082e0c20161f036960626a20
412b000000030025fff7019302450014001a001e0000371416333236371506232226353436333216151631272206153334272327336c3e432a3e2e4652596d694f5c5901b02e46e03c397648b4384f12
15401d6d5f5d6e614930a5443074698300030025fff7019302450014001a001e0000371416333236371506232226353436333216151631272206153334370723376c3e432a3e2e4652596d694f5c5901
b02e46e00e773866b4384f1215401d6d5f5d6e614930a5443074ec838300000000030025fff7019302450014001a00210000371416333236371506232226353436333216151631272206153334270723
373317236c3e432a3e2e4652596d694f5c5901b02e46e06e43345a395a34b4384f1215401d6d5f5d6e614930a5443074c158838300040025fff70193021d0014001a0026003200003714163332363715
062322263534363332161516312722061533342723223d01343b01321d01143323223d01343b01321d01146c3e432a3e2e4652596d694f5c5901b02e46e09c3a09093a09893909093909b4384f121540
1d6d5f5d6e614930a54430747d09340909340909340909340900000000020033fffc0175023b0003001200001323273313153315222322263d012335331514e3397749a950184736415a9e01b883fdf9
01364e3fc932fb5600020044fffc0174023b0003001200000107233713153315222322263d012335331514014c773967224f174835425a9e023b8383fdf901364e3fc932fb56000000020044fffc0174
0245000e0015000025153315222322263d0123353315140307233733172301254f174835425a9e2842345a385a333401364e3fc932fb5601e658838300030044fffc0174021a000d0019002500002533
15222322263d0123353315140323223d01343b01321d01143323223d01343b01321d011401254f174835425a9e48390909390989390909390933364e3fc932fb5701a109340909340909340909340900
0002002afff4018e021b0020002f000001141e06151406232226353436172e012f01072737273317371707160332363534262f01262322061514160140140613080d0605595858596b64051b0a0b670c
5843512f6a0d5d24492d3c140a0a12322b3b3c0183011b0a1d13211d2613566b6b5e5d6608081f0c0b1f221b453120221c22fe81464726430f0e0945494945000002003e0000017a02200019002d0000
1333221523343633321e013332363d0133140e0223222e02172332161511233534262322061d012311331736a9011a2d242514231e0d0c0d2e050e1d15151f1116490135484427262f384440042501f4
362c361b1a1a0e0d0f1d2115111411634e43ff00fa2d303d3bdf01842f3c00000003002bfff4018d024500070011001500001232161514203534163236353426220615141323273389a65efe9e835c3a
3b5a3b9b387749018d6666cccc66fd475050464650500151830000000003002bfff4018d024500070011001500001232161514203534163236353426220615141307233789a65efe9e835c3a3b5a3be2
763967018d6666cccc66fd4750504646505001d4838300000003002bfff4018d024500070011001800001232161514203534163236353426220615141307233733172389a65efe9e835c3a3b5a3b6842
345a385a34018d6666cccc66fd4750504646505001a95883830000000003002bfff4018d022000070011002a000012321615142035341632363534262206151413221523343633321e013332363d0133
140e0223222e0289a65efe9e835c3a3b5a3b35192e242614231d0e0c0d2e050e1e1514201016018d6666cccc66fd475050464650500183362c361b1a1a0e0d0f1d211511141100000004002bfff4018d
021a00070011001d002900001232161514203534163236353426220615141323223d01343b01321d01143323223d01343b01321d011489a65efe9e835c3a3b5a3b3c3a09093a09893a09093a09018d66
66cccc66fd4750504646505001630934090934090934090934090000000300180031019f0188000f001f00230000372322263d0134363b0132161d011406032322263d0134363b0132161d0114061721
3521fe460407070446050606054604070704460506069cfe7901873206053f040707043f0506010106053f050606053f0506733b0003000cffde01ac01a60012001a0022000001071615142322270727
3726353436333217370514173726232206173236353427071601ac3d21b24b2c39223e1d5e53472e37feec09a81b2e2d3b682f390aa91b018b443451cc283f1a4632516666273fe32a1fbd2146e74850
2a20bd250002003dfff6017b023b0017001b000001331123270e042322263d01331514163332363536272327330136443f060205141726154d3d43262b2c3503293977490185fe7c39020a17120e4852
f4f034343b32eb33830000000002003dfff6017b023b0017001b000001331123270e042322263d01331514163332363536370723370136443f060205141726154d3d43262b2c35031d7738660185fe7c
39020a17120e4852f4f034343b32ebb6838300000002003dfff6017b02450017001e0000011123270e042322263d013315141633323635363127072337331723017a3f060205141726154d3d43262a2d
35025942345a385a340185fe7c39020a17120e4852f4f034343b32eb955883830003003dfff6017b021b00170023002f000001331123270e042322263d013315141633323635362723223d01343b0132
1d01143323223d01343b01321d01140136443f060205141726154d3d43262a2d3503893a09093a09893a08083a090185fe7c39020a17120e4852f4f034343b32eb500934090934090934090934090000
0002001aff6b019e023b0003001a000001072337173302070e032b01353033323e02373631033313014677386659488c270e20241912362e0f17120a060ca0487b023b8383b6feaf62232c1205360c18
13101d017ffed00000020032ff6b01860220000d00170000133216151423222715231133153612323635342622061514da505bab432044441f185937395638018d6666cc41ca02b4d03dfe9d47505046
465050000003001aff6b019e0211000b0017002e00001323223d01343b01321d01143323223d01343b01321d0114173302070e032b01353033323e02373631033313af3a09093a098939090939090c48
8c270e20241912362e0f17120a060ca0487b01cb09340909340909340909340946feaf62232c1205360c1813101d017ffed0000000030026fff501920208002b003a003e0000251514161f012326270e
012322263534363332313c022e052322060f01353e06333203323e02272a02230e0115141613233533017e0a0505440907154c2641505b5b5c0206080f141e122647101103190b1811181a0da8c22534
1a0a0101232f0b3c3433aadddde27419370f0f16252025403c3e46010f09120d100b0a05120a093f01090308030402fe9b1d2f321a02202c262401a93400000000030015000001a3006a000f001f002f
00002532161d0114062b0122263d013436332332161d0114062b0122263d013436332332161d0114062b0122263d01343633019605070705460507070551050707054605070705510507070547040808
04690705510507070551050707055105070705510507070551050707055105070001001efff901990214002b0000012207330723061514153307231e0333323637150623222627233733263437233733
3e01333217152e01012c6e14b212a30184116f061b262517143d1b2f3d58670e41122c02023e122f0e675341301c3d01dc90241e04110f252c3c1d0a1318471c685f251d091c245f691d481815000000
00010018008101a0012c00050000011523352135019f3efeb7012cab703b000000000016010e0001000000000000004700900001000000000001000d00f4000100000000000200070112000100000000
0003001a01500001000000000004000d01870001000000000005002301dd00010000000000060014022b000100000000000900210284000100000000000d000b02be0001000000000010000d02e60001
000000000011000703040003000104090000008e00000003000104090001001a00d80003000104090002000e010200030001040900030034011a0003000104090004001a016b00030001040900050046
0195000300010409000600280201000300010409000900420240000300010409000d001602a60003000104090010001a02ca0003000104090011000e02f40043006f0070007900720069006700680074
00200028006300290020003200300032003600200044006900730063006f002000480065006c006c006f002c00200043006f007000790072006900670068007400200028006300290020003200300031
0039002c00320030003200330020005400720069007300740061006e0020004700720069006d006d006500720000436f7079726967687420286329203230323620446973636f2048656c6c6f2c20436f
707972696768742028632920323031392c32303233205472697374616e204772696d6d65720000500072006f0067006700790046006f00720065007600650072000050726f676779466f726576657200
0052006500670075006c006100720000526567756c6172000031002e003000310032003b00500072006f0067006700790046006f007200650076006500720052006500670075006c006100720000312e
3031323b50726f676779466f7265766572526567756c61720000500072006f0067006700790046006f00720065007600650072000050726f676779466f72657665720000560065007200730069006f00
6e00200031002e003000310032003b0046006f006e007400730065006c00660020004d0061006b0065007200200033002e0035002e00310037000056657273696f6e20312e3031323b466f6e7473656c
66204d616b657220332e352e31370000500072006f0067006700790046006f007200650076006500720052006500670075006c00610072000050726f676779466f7265766572526567756c6172000054
00720069007300740061006e0020004700720069006d006d00650072002c00200054006800690065006200610075006c007400200043006f00750072006f007400005472697374616e204772696d6d65
722c20546869656261756c7420436f75726f7400004d004900540020004c006900630065006e0073006500004d4954204c6963656e73650000500072006f0067006700790046006f0072006500760065
0072000050726f676779466f7265766572000052006500670075006c006100720000526567756c6172000000000200000000000000000000000000010000000000000000000000000000000000c20000
000100020003000400050006000700080009000a000b000c000d000e000f0010001100120013001400150016001700180019001a001b001c001d001e001f002000210022002300240025002600270028
0029002a002b002c002d002e002f0030003100320033003400350036003700380039003a003b003c003d003e003f0040004100420043004400450046004700480049004a004b004c004d004e004f0050
005100520053005400550056005700580059005a005b005c005d005e01020060006100a30084008500bd009600e80086008e008b009d00a9008a01030083009300f200f3008d0097008800c300de00f1
009e00aa00f500f400f600a200ad00c900c700ae006200630090006400cb006500c800ca00cf00cc00cd00ce00e9006600d300d100af006700f0009100d600d400d5006800eb00ed0089006a0069006b
006d006c006e00a0006f0071007000720073007500740076007700ea0078007a0079007b007d007c00b800a1007f007e0080008100ec00ee00ba010400ab010501060b766572746963616c626172096f
76657273636f726507616d6163726f6e044575726f07756e696539313200000000000001ffff000200010000000c00000010001800020000000400000002000000010000000100000000000100000000
e50db79300000000e5afbb4200000000e5b3d43b
]],
}
end
__FILES['imgui_internal.lua'] = function()
--- ImGui Sincerely WIP
-- (internal structures/api)
--- @meta
local type = ImGui._GetTypeFunc()
local rawget = rawget
local mathMin = math.min; local mathMax = math.max
local mathFloor = math.floor; local mathCeil = math.ceil
local bitNot = bit32.bnot
local bitAnd = bit32.band; local bitOr = bit32.bor
local bitLShift = bit32.lshift; local bitRShift = bit32.rshift
local t_sort = table.sort
--- @alias ImGuiTableColumnIdx ImS16
-- TODO: Implement actual ImString type
--- @alias ImString char[]|string
--- @alias ImStringBuffer char[]
-- NOTE: temporary solution
--- @param buf char[]
--- @param buf_begin int
--- @param buf_end int # exclusive
function ImGui._ByteArrayToString(buf, buf_begin, buf_end)
local str = {}
for i = buf_begin, buf_end - 1 do
table.insert(str, string.char(buf[i]))
end
return table.concat(str)
end
--- @type ImGuiContext?
local GImGui
-- Sets local `GImGui` in this file(imgui_internal.lua).
-- This is currently only used in main code `ImGui.SetCurrentContext()`
--- @param ctx ImGuiContext?
function ImGui._SetCurrentContext_Internal(ctx)
GImGui = ctx
end
local setmetatable = setmetatable
local MT = ImGui.GetMetatables()
IM_TABSIZE = 4
FLT_MIN = 1.1754943508223e-38
FLT_MAX = 3.4028234663853e+38
DBL_MAX = 1.7976931348623e+308
INT_MIN = -0x7fffffff - 1
INT_MAX = 0x7fffffff
UINT_MAX = 0x7fffffff * 2 + 1
NAV_WINDOWING_HIGHLIGHT_DELAY = 0.5
NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10
NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = 0.60
IM_PI = math.pi
ImPow = math.pow
ImLog = math.log
ImAbs = math.abs
ImFabs = math.abs
ImFmod = function(a, b) if b < 0 then b = -b end; if a < 0 then return -(-a % b) else return a % b end; end
ImRound64 = function(val) return math.floor(val + 0.5) end -- FIXME: Positive values only
ImCeil = math.ceil
ImSin = math.sin
ImCos = math.cos
ImAcos = math.acos
ImAtan2 = math.atan2
ImSqrt = math.sqrt
--- @generic T: number
--- @param a T
--- @param b T
--- @param mn T
--- @param mx T
--- @return T
function ImAddClampOverflow(a, b, mn, mx)
if b < 0 and (a < mn - b) then return mn end
if b > 0 and (a > mx - b) then return mx end
return a + b
end
--- @generic T: number
--- @param a T
--- @param b T
--- @param mn T
--- @param mx T
--- @return T
function ImSubClampOverflow(a, b, mn, mx)
if b > 0 and (a < mn + b) then return mn end
if b < 0 and (a > mx + b) then return mx end
return a - b
end
--- @overload fun(lhs: number, rhs: number): number
--- @overload fun(lhs: ImVec2, rhs: ImVec2): ImVec2
function ImMin(lhs, rhs)
if type(lhs) == "number" and type(rhs) == "number" then return mathMin(lhs, rhs)
elseif type(lhs) == "table" and type(rhs) == "table" then return ImVec2(mathMin(lhs[1], rhs[1]), mathMin(lhs[2], rhs[2]))
end
end
--- @overload fun(lhs: number, rhs: number): number
--- @overload fun(lhs: ImVec2, rhs: ImVec2): ImVec2
function ImMax(lhs, rhs)
if type(lhs) == "number" and type(rhs) == "number" then return mathMax(lhs, rhs)
elseif type(lhs) == "table" and type(rhs) == "table" then return ImVec2(mathMax(lhs[1], rhs[1]), mathMax(lhs[2], rhs[2]))
end
end
--- @param base table
--- @param count int
--- @param cmp_func fun(lhs, rhs): bool
ImStd.ImQsort = function(base, count, cmp_func) if count > 0 then t_sort(base, cmp_func) end end
--- @overload fun(v: number, mn: number, mx: number): number
--- @overload fun(v: ImVec2, mn: ImVec2, mx: ImVec2): ImVec2
function ImClamp(v, mn, mx)
if type(v) == "number" and type(mn) == "number" and type(mx) == "number" then return mathMin(mathMax(v, mn), mx)
elseif type(v) == "table" and type(mn) == "table" and type(mx) == "table" then return ImVec2(mathMax(mn[1], mathMin(v[1], mx[1])), mathMax(mn[2], mathMin(v[2], mx[2])))
end
end
--- @overload fun(a: number, b: number, t: number): number
--- @overload fun(a: ImVec2, b: ImVec2, t: number): ImVec2
--- @overload fun(a: ImVec2, b: ImVec2, t: ImVec2): ImVec2
function ImLerp(a, b, t)
if type(a) == "number" and type(b) == "number" and type(t) == "number" then return ((a) + ((b) - (a)) * (t))
elseif type(a) == "table" and type(b) == "table" and type(t) == "number" then return ImVec2(a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t)
elseif type(a) == "table" and type(b) == "table" and type(t) == "table" then return ImVec2(a[1] + (b[1] - a[1]) * t[1], a[2] + (b[2] - a[2]) * t[2])
end
end
local function _Trunc(val) if val >= 0 then return mathFloor(val) else return mathCeil(val) end end
--- @overload fun(v: float): float
--- @overload fun(v: ImVec2): ImVec2
function ImTrunc(v)
if type(v) == "number" then return _Trunc(v)
elseif type(v) == "table" then return ImVec2(_Trunc(v[1]), _Trunc(v[2]))
end
end
ImTrunc64 = _Trunc
--- @param f float
function ImCeilFast(f)
local i
if f >= 0 then i = math.floor(f) else i = math.ceil(f) end -- same as `ImTrunc()`
if f > i then return i + 1 end
return i
end
function IM_ROUNDUP_TO_EVEN(n) return (ImCeil((n) / 2) * 2) end
function ImRsqrt(x) return (1 / ImSqrt(x)) end
function IM_TRUNC(VAL) return math.floor(VAL) end -- Positive values only!
function IM_ROUND(VAL) return math.floor(VAL + 0.5) end
function ImFloor(f) if f >= 0 or math.floor(f) == f then return math.floor(f) else return math.floor(f) - 1 end end
--- @param v int
function ImIsPowerOfTwo(v)
return (v ~= 0) and (bitAnd(v, (v - 1)) == 0)
end
function ImUpperPowerOfTwo(v)
if v <= 0 then return 0 end
if v <= 1 then return 1 end
v = v - 1
v = bitOr(v, bitRShift(v, 1))
v = bitOr(v, bitRShift(v, 2))
v = bitOr(v, bitRShift(v, 4))
v = bitOr(v, bitRShift(v, 8))
v = bitOr(v, bitRShift(v, 16))
return v + 1
end
--- @param v unsigned_int
--- @return unsigned_int
function ImCountSetBits(v)
local count = 0
while v > 0 do
v = bitAnd(v, v - 1)
count = count + 1
end
return count
end
--- @param avg float
--- @param sample float
--- @param n int
--- @return float
function ImStd.ImExponentialMovingAverage(avg, sample, n)
avg = avg - avg / n
avg = avg + sample / n
return avg
end
-- Uses `string.match` internally
--- @param str string
function ImAtof(str)
return tonumber(string.match(str, "[+-]?%d*%.?%d+"))
end
--- @param s table # 1-based
--- @param c any
--- @param n int
function ImStd.memset(s, c, n)
for i = 1, n do s[i] = c end
end
do
local _memmove = function(dest, dest_start, src, src_start, count)
if count <= 0 then return end
-- more compact instead of writing separate if-else and for loops
local c = (dest == src and dest_start >= src_start)
for i = (c and count - 1 or 0), (c and 0 or count - 1), (c and -1 or 1) do
dest[dest_start + i] = src[src_start + i]
end
end
if table.move then
--- [GMod] Platform specific: the `table.move` polyfill in non-x86-64 currently uses `unpack` which will break if too many elements
-- Remove this check when the polyfill is fixed or removed
if not gmod or (gmod and BRANCH == "x86-64") then
_memmove = function(dest, dest_start, src, src_start, count)
table.move(src, src_start, src_start + count - 1, dest_start, dest)
end
end
end
ImStd.memmove = _memmove
end
--- @param str1 ImStringBuffer
--- @param str2 ImStringBuffer
function ImStd.strcmp(str1, str2)
local i = 1
while true do
local c1 = str1[i] or 0
local c2 = str2[i] or 0
if c1 ~= c2 then
return c1 - c2
end
if c1 == 0 then
return 0
end
i = i + 1
end
end
--- @param str1 ImStringBuffer
--- @param str2 ImStringBuffer
--- @param max_count int
function ImStd.strncmp(str1, str2, max_count)
for i = 1, max_count do
local c1 = str1[i] or 0
local c2 = str2[i] or 0
if c1 ~= c2 then
return c1 - c2
end
if c1 == 0 then
return 0
end
end
return 0
end
function ImSaturate(f) return ((f < 0.0 and 0.0) or (f > 1.0 and 1.0) or f) end
IM_F32_TO_INT8_UNBOUND = function(val) return math.floor(val * 255.0 + (val >= 0 and 0.5 or -0.5)) end
IM_F32_TO_INT8_SAT = function(val) return math.floor(ImSaturate(val) * 255.0 + 0.5) end
--- @param s ImString
--- @param i int
--- @return char
function ImStrByte(s, i)
if type(s) == "string" then
return string.byte(s, i, i)
else --- @cast s char[]
return s[i]
end
end
--- @class ImGuiColorMod
--- @field Col ImGuiCol
--- @field BackupValue ImVec4
--- @param col ImGuiCol
--- @param backup_value ImVec4
--- @return ImGuiColorMod
function ImGuiColorMod(col, backup_value)
local this = {
Col = col,
BackupValue = ImVec4()
}
ImVec4_Copy(this.BackupValue, backup_value)
return this
end
--- @param lhs ImVec2
--- @return float
function ImLengthSqr(lhs) return (lhs.x * lhs.x) + (lhs.y * lhs.y) end
--- @param v ImVec2
--- @param cos_a float
--- @param sin_a float
--- @return ImVec2
--- @nodiscard
function ImRotate(v, cos_a, sin_a)
return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a)
end
--- @param a ImVec2
--- @param b ImVec2
function ImDot(a, b)
return a.x * b.x + a.y * b.y
end
--- @param lhs ImVec2
--- @param rhs ImVec2
--- @nodiscard
function ImMul(lhs, rhs)
return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y)
end
--- @param str char[]
--- @param begin? int
function ImStd.ImStrlen(str, begin)
if begin == nil then begin = 1 end
local l = #str
for i = begin, l do
if str[i] == 0 then
return i - begin
end
end
IM_ASSERT(false)
end
-- FIXME: should also accept count?
-- FIXME: avoid dynamic type checking?
-- string.find with patterns disabled
--- @param str string|char[]
--- @param s string|char
--- @param start_pos? int
--- @return int?
function ImMemchr(str, s, start_pos)
local start = start_pos or 1
if start < 1 then start = 1 end
if type(str) == "table" then
for i = start, #str do
if str[i] == 0 then break end
if str[i] == s then
return i
end
end
return nil
end
--- @cast str string
local pos = string.find(str, s, start, true)
return pos
end
IMGUI_FONT_SIZE_MAX = 512.0
IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE = 128.0
IMGUI_WINDOW_HARD_MIN_SIZE = 4.0
IM_DRAWLIST_ARCFAST_TABLE_SIZE = 48
IM_DRAWLIST_ARCFAST_SAMPLE_MAX = IM_DRAWLIST_ARCFAST_TABLE_SIZE
function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end
function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end
function IMGUI_DEBUG_LOG_ACTIVEID(_str, ...) local g = GImGui if bitAnd(g.DebugLogFlags, ImGuiDebugLogFlags.EventActiveId) ~= 0 then print(string.format(_str, ...)) end end
function IMGUI_DEBUG_LOG_POPUP(_str, ...) local g = GImGui if bitAnd(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then print(string.format(_str, ...)) end end
function IMGUI_DEBUG_LOG_FONT(_str, ...) local g2 = GImGui if g2 and bitAnd(g2.DebugLogFlags, ImGuiDebugLogFlags.EventFont) ~= 0 then print(string.format(_str, ...)) end end
function IMGUI_DEBUG_LOG_VIEWPORT(_str, ...) local g = GImGui if bitAnd(g.DebugLogFlags, ImGuiDebugLogFlags.EventViewport) ~= 0 then print(string.format(_str, ...)) end end
--- @alias ImGuiSelectionUserData any
ImGuiSelectionUserData_Invalid = -1
ImGuiKeyOwner_Any = 0
ImGuiKeyOwner_NoOwner = 4294967295
--- @param button ImGuiMouseButton
--- @return ImGuiKey
function ImGui.MouseButtonToKey(button) IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) return ImGuiKey.MouseLeft + button end
--- @param key ImGuiKey
function ImGui.IsNamedKey(key)
return key >= ImGuiKey.NamedKey_BEGIN and key < ImGuiKey.NamedKey_END
end
--- @param key ImGuiKey
function ImGui.IsKeyboardKey(key)
return key >= ImGuiKey_Keyboard_BEGIN and key < ImGuiKey_Keyboard_END
end
--- @param key ImGuiKey
function ImGui.IsGamepadKey(key)
return key >= ImGuiKey_Gamepad_BEGIN and key < ImGuiKey_Gamepad_END
end
--- @param key ImGuiKey
function ImGui.IsMouseKey(key)
return key >= ImGuiKey_Mouse_BEGIN and key < ImGuiKey_Mouse_END
end
--- @param key ImGuiKey
function ImGui.IsAliasKey(key)
return key >= ImGuiKey_Aliases_BEGIN and key < ImGuiKey_Aliases_END
end
--- @param key ImGuiKey
function ImGui.IsLRModKey(key)
return key >= ImGuiKey.LeftCtrl and key <= ImGuiKey.RightSuper
end
--- @param key ImGuiKey
--- @return bool
function ImGui.IsNamedKeyOrMod(key)
return (key >= ImGuiKey.NamedKey_BEGIN and key < ImGuiKey.NamedKey_END) or key == ImGuiMod_Ctrl or key == ImGuiMod_Shift or key == ImGuiMod_Alt or key == ImGuiMod_Super
end
--- @param key ImGuiKey
--- @return ImGuiKey
function ImGui.ConvertSingleModFlagToKey(key)
if key == ImGuiMod_Ctrl then
return ImGuiKey.ReservedForModCtrl
elseif key == ImGuiMod_Shift then
return ImGuiKey.ReservedForModShift
elseif key == ImGuiMod_Alt then
return ImGuiKey.ReservedForModAlt
elseif key == ImGuiMod_Super then
return ImGuiKey.ReservedForModSuper
end
return key
end
--- @param ctx ImGuiContext
--- @param key ImGuiKey
function ImGui.GetKeyOwnerData(ctx, key)
if bitAnd(key, ImGuiMod_Mask_) ~= 0 then key = ImGui.ConvertSingleModFlagToKey(key) end
IM_ASSERT(ImGui.IsNamedKey(key))
return ctx.KeysOwnerData[key - ImGuiKey.NamedKey_BEGIN]
end
--- @class ImGuiKeyOwnerData
--- @return ImGuiKeyOwnerData
--- @nodiscard
function ImGuiKeyOwnerData()
return {
OwnerCurr = ImGuiKeyOwner_NoOwner,
OwnerNext = ImGuiKeyOwner_NoOwner,
LockThisFrame = false,
LockUntilRelease = false
}
end
--- @param size float
--- @return float
function ImGui.GetRoundedFontSize(size) return IM_ROUND(size) end
--- @param window ImGuiWindow
--- @param r ImRect
--- @return ImRect
--- @nodiscard
function ImGui.WindowRectAbsToRel(window, r) local off = window.DC.CursorStartPos return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y) end
--- @param window ImGuiWindow
--- @param r ImRect
--- @nodiscard
function ImGui.WindowRectRelToAbs(window, r) local off = window.DC.CursorStartPos return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y) end
--- @param dir ImGuiDir
--- @return bool
function ImGui.IsActiveIdUsingNavDir(dir)
local g = GImGui
return bit32.band(g.ActiveIdUsingNavDirMask, bit32.lshift(1, dir)) ~= 0
end
--- @param window ImGuiWindow
--- @param p ImVec2
--- @return ImVec2
--- @nodiscard
function ImGui.WindowPosAbsToRel(window, p) local off = window.DC.CursorStartPos return ImVec2(p.x - off.x, p.y - off.y) end
--- @param c char
--- @return bool # True if this character is a ' ' or '\t'
function ImCharIsBlankA(c) return c == 32 or c == 9 end
--- @param c char
function ImCharIsBlankW(c) return c == 32 or c == 9 or c == 0x3000 end
--- @enum ImGuiNavMoveFlags
ImGuiNavMoveFlags =
{
None = 0,
LoopX = bitLShift(1, 0),
LoopY = bitLShift(1, 1),
WrapX = bitLShift(1, 2),
WrapY = bitLShift(1, 3),
AllowCurrentNavId = bitLShift(1, 4),
AlsoScoreVisibleSet = bitLShift(1, 5),
ScrollToEdgeY = bitLShift(1, 6),
Forwarded = bitLShift(1, 7),
DebugNoResult = bitLShift(1, 8),
FocusApi = bitLShift(1, 9),
IsTabbing = bitLShift(1, 10),
IsPageMove = bitLShift(1, 11),
Activate = bitLShift(1, 12),
NoSelect = bitLShift(1, 13),
NoSetNavCursorVisible = bitLShift(1, 14),
NoClearActiveId = bitLShift(1, 15),
}
ImGuiNavMoveFlags.WrapMask_ = bitOr(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.LoopY, ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.WrapY)
--- @enum ImGuiNavLayer
ImGuiNavLayer =
{
Main = 0,
Menu = 1,
COUNT = 2
}
ImGuiItemFlags.ReadOnly = bitLShift(1, 11)
ImGuiItemFlags.MixedValue = bitLShift(1, 12)
ImGuiItemFlags.NoWindowHoverableCheck = bitLShift(1, 13)
ImGuiItemFlags.AllowOverlap = bitLShift(1, 14)
ImGuiItemFlags.NoNavDisableMouseHover = bitLShift(1, 15)
ImGuiItemFlags.NoMarkEdited = bitLShift(1, 16)
ImGuiItemFlags.NoFocus = bitLShift(1, 17)
ImGuiItemFlags.Inputable = bitLShift(1, 20)
ImGuiItemFlags.HasSelectionUserData = bitLShift(1, 21)
ImGuiItemFlags.IsMultiSelect = bitLShift(1, 22)
ImGuiItemFlags.Default_ = bitOr(ImGuiItemFlags.AutoClosePopups, ImGuiItemFlags.LiveEditOnInputText)
--- @enum ImDrawTextFlags
ImDrawTextFlags =
{
None = 0,
CpuFineClip = bitLShift(1, 0),
WrapKeepBlanks = bitLShift(1, 1),
StopOnNewLine = bitLShift(1, 2)
}
--- @enum ImGuiFocusRequestFlags
ImGuiFocusRequestFlags =
{
None = 0,
RestoreFocusedChild = bitLShift(1, 0),
UnlessBelowModal = bitLShift(1, 1)
}
--- @enum ImGuiTextFlags
ImGuiTextFlags =
{
None = 0,
NoWidthForLargeClippedText = bitLShift(1, 0)
}
--- @enum ImWcharClass
ImWcharClass =
{
Blank = 0,
Punct = 1,
Other = 2
}
--- @class ImVec1
--- @field x number
local IM_VEC1 = {}
IM_VEC1.__index = IM_VEC1
local function ImVec1(x) return setmetatable({x = x or 0}, IM_VEC1) end
function IM_VEC1:__tostring() return string.format("ImVec1(%g)", self.x) end
--- @param dest ImVec1
--- @param src ImVec1
function ImVec1_Copy(dest, src)
dest.x = src.x
end
--- @class ImRect
--- @field [1] ImVec2
--- @field [2] ImVec2
--- @field Min ImVec2
--- @field Max ImVec2
local IM_RECT = {}
--- @param t ImRect
--- @param k string
IM_RECT.__index = function(t, k)
local method = IM_RECT[k]
if method ~= nil then return method end
if k == "Min" then return rawget(t, 1)
elseif k == "Max" then return rawget(t, 2)
end
end
--- @param t ImRect
--- @param k string
--- @param v ImVec2
IM_RECT.__newindex = function(t, k, v)
if k == "Min" then ImVec2_Copy(rawget(t, 1), v)
elseif k == "Max" then ImVec2_Copy(rawget(t, 2), v)
else IM_ASSERT(false)
end
end
--- @return ImRect
--- @nodiscard
function ImRect(a, b, c, d) if c and d then return setmetatable({ ImVec2(a, b), ImVec2(c, d) }, IM_RECT) end return setmetatable({ ImVec2(a and a.x or 0, a and a.y or 0), ImVec2(b and b.x or 0, b and b.y or 0) }, IM_RECT) end
function IM_RECT:__eq(other) return self[1] == other[1] and self[2] == other[2] end
function IM_RECT:__tostring() return string.format("ImRect(Min: %g,%g, Max: %g,%g)", self.Min.x, self.Min.y, self.Max.x, self.Max.y) end
--- @param p ImRect|ImVec2
function IM_RECT:Contains(p)
if p.Min then
--- @cast p ImRect
return p[1][1] >= self[1][1] and p[2][1] <= self[2][1] and p[1][2] >= self[1][2] and p[2][2] <= self[2][2]
else
--- @cast p ImVec2
return p[1] >= self[1][1] and p[2] >= self[1][2] and p[1] < self[2][1] and p[2] < self[2][2]
end
end
--- @param p ImVec2
--- @param pad ImVec2
function IM_RECT:ContainsWithPad(p, pad)
return p[1] >= self[1][1] - pad[1] and p[2] >= self[1][2] - pad[2] and p[1] < self[2][1] + pad[1] and p[2] < self[2][2] + pad[2]
end
--- @param r ImRect
function IM_RECT:Overlaps(r)
return self[1][1] <= r[2][1] and self[2][1] >= r[1][1] and self[1][2] <= r[2][2] and self[2][2] >= r[1][2]
end
--- @nodiscard
function IM_RECT:GetCenter() return ImVec2((self[1][1] + self[2][1]) * 0.5, (self[1][2] + self[2][2]) * 0.5) end
function IM_RECT:GetWidth() return self[2][1] - self[1][1] end
function IM_RECT:GetHeight() return self[2][2] - self[1][2] end
--- @nodiscard
function IM_RECT:GetSize() return ImVec2(self[2][1] - self[1][1], self[2][2] - self[1][2]) end
--- @nodiscard
function IM_RECT:GetTL() return ImVec2(self[1][1], self[1][2]) end
--- @nodiscard
function IM_RECT:GetTR() return ImVec2(self[2][1], self[1][2]) end
--- @nodiscard
function IM_RECT:GetBL() return ImVec2(self[1][1], self[2][2]) end
--- @nodiscard
function IM_RECT:GetBR() return ImVec2(self[2][1], self[2][2]) end
--- @param r ImRect
function IM_RECT:ClipWith(r)
ImVec2_Copy(self[1], ImMax(self[1], r[1])); ImVec2_Copy(self[2], ImMin(self[2], r[2]))
end
--- @param r ImRect
function IM_RECT:ClipWithFull(r)
ImVec2_Copy(self[1], ImClamp(self[1], r[1], r[2])); ImVec2_Copy(self[2], ImClamp(self[2], r[1], r[2]))
end
--- @param p ImRect|ImVec2
function IM_RECT:Add(p)
if p.Min then
--- @cast p ImRect
if (self[1][1] > p[1][1]) then self[1][1] = p[1][1] end
if (self[1][2] > p[1][2]) then self[1][2] = p[1][2] end
if (self[2][1] < p[2][1]) then self[2][1] = p[2][1] end
if (self[2][2] < p[2][2]) then self[2][2] = p[2][2] end
else
--- @cast p ImVec2
if p[1] < self[1][1] then self[1][1] = p[1] end
if p[2] < self[1][2] then self[1][2] = p[2] end
if p[1] > self[2][1] then self[2][1] = p[1] end
if p[2] > self[2][2] then self[2][2] = p[2] end
end
end
--- @param amount float|ImVec2
function IM_RECT:Expand(amount)
if type(amount) == "number" then
self[1][1] = self[1][1] - amount; self[1][2] = self[1][2] - amount
self[2][1] = self[2][1] + amount; self[2][2] = self[2][2] + amount
elseif type(amount) == "table" then
self[1][1] = self[1][1] - amount[1]; self[1][2] = self[1][2] - amount[2]
self[2][1] = self[2][1] + amount[1]; self[2][2] = self[2][2] + amount[2]
end
end
--- @nodiscard
function IM_RECT:ToVec4()
return ImVec4(self[1][1], self[1][2], self[2][1], self[2][2])
end
--- @param d ImVec2
function IM_RECT:Translate(d)
self[1][1] = self[1][1] + d[1]; self[1][2] = self[1][2] + d[2]
self[2][1] = self[2][1] + d[1]; self[2][2] = self[2][2] + d[2]
end
--- @param dy float
function IM_RECT:TranslateY(dy)
self[1][2] = self[1][2] + dy; self[2][2] = self[2][2] + dy
end
function IM_RECT:IsInverted() return self[1][1] > self[2][1] or self[1][2] > self[2][2] end
function IM_RECT:GetArea() return (self[2][1] - self[1][1]) * (self[2][2] - self[1][2]) end
--- @nodiscard
function IM_RECT:AsVec4() return ImVec4(self[1][1], self[1][2], self[2][1], self[2][2]) end
--- @param dest ImRect
--- @param src ImRect
function ImRect_Copy(dest, src)
dest[1][1] = src[1][1]; dest[1][2] = src[1][2]
dest[2][1] = src[2][1]; dest[2][2] = src[2][2]
end
--- @param dest ImRect
--- @param src ImVec4
function ImRect_CopyFromV4(dest, src)
dest[1][1] = src[1]; dest[1][2] = src[2]
dest[2][1] = src[3]; dest[2][2] = src[4]
end
--- @param _ARRAY ImU32[]
--- @param _N int
function IM_BITARRAY_TESTBIT(_ARRAY, _N)
return bitAnd(_ARRAY[bitRShift(_N - 1, 5) + 1], bitLShift(1, bitAnd(_N - 1, 31))) ~= 0
end
--- @param _ARRAY ImU32[]
--- @param _N int
function IM_BITARRAY_CLEARBIT(_ARRAY, _N)
local idx = bitRShift(_N - 1, 5) + 1
_ARRAY[idx] = bitAnd(_ARRAY[idx], bitNot(bitLShift(1, bitAnd(_N - 1, 31))))
end
--- @param arr ImU32[]
--- @param n int
function ImBitArraySetBit(arr, n)
local mask = bitLShift(1, bitAnd(n - 1, 31))
local idx = bitRShift(n - 1, 5) + 1
arr[idx] = bitOr(arr[idx], mask)
end
--- @alias ImBitArrayForNamedKeys ImBitArray
--- NOTE: This struct is expensive to create
--- @class ImBitArray<BITCOUNT, OFFSET>
--- @field Data ImU32[]
--- @param BITCOUNT int
--- @param OFFSET? int
--- @return ImBitArray
function ImBitArray(BITCOUNT, OFFSET)
if OFFSET == nil then OFFSET = 0 end
local this = { Data = {} }
local size = bitRShift(BITCOUNT + 31, 5)
this.ClearAllBits = function(self) local data = self.Data; for i = 1, size do data[i] = 0 end end
this.SetAllBits = function(self) local data = self.Data; for i = 1, size do data[i] = 0xFFFFFFFF end end
--- @param n int # 1-based
--- @return boolean
this.TestBit = function(self, n) n = n + OFFSET; IM_ASSERT(n >= 1 and n <= BITCOUNT); return IM_BITARRAY_TESTBIT(self.Data, n); end
--- @param n int # 1-based
this.SetBit = function(self, n) n = n + OFFSET; IM_ASSERT(n >= 1 and n <= BITCOUNT); ImBitArraySetBit(self.Data, n); end
this:ClearAllBits()
return this
end
function MT.ImDrawList:PathClear() self._Path:clear() end
--- @param pos ImVec2
function MT.ImDrawList:PathLineTo(pos) self._Path:push_back(pos) end
function MT.ImDrawList:PathLineToMergeDuplicate(pos)
local path_size = self._Path.Size
if path_size == 0 or self._Path.Data[path_size].x ~= pos.x or self._Path.Data[path_size].y ~= pos.y then
self._Path:push_back(pos)
end
end
function MT.ImDrawList:PathFillConvex(col)
self:AddConvexPolyFilled(self._Path.Data, self._Path.Size, col)
self._Path.Size = 0
end
--- @param col ImU32
--- @param thickness? float
--- @param flags? ImDrawFlags
function MT.ImDrawList:PathStroke(col, thickness, flags)
if not thickness then thickness = 1.0 end
if not flags then flags = 0 end
self:AddPolyline(self._Path.Data, self._Path.Size, col, thickness, flags)
self._Path.Size = 0
end
--- @param col ImU32
function ImGui.SetNextItemColorMarker(col)
local g = GImGui
g.NextItemData.HasFlags = bitOr(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasColorMarker)
g.NextItemData.ColorMarker = col
end
--- @class ImDrawListSharedData
--- @field TexUvWhitePixel ImVec2
--- @field TexUvLines ImVec4[]
--- @field FontAtlas ImFontAtlas
--- @field Font ImFont
--- @field FontSize float
--- @field FontScale float
--- @field CurveTessellationTol float
--- @field CircleTessellationMaxError float
--- @field InitialFringeScale float
--- @field InitialFlags ImDrawListFlags
--- @field ClipRectFullscreen? ImVec4
--- @field TempBuffer ImVector<ImVec2>
--- @field DrawLists ImVector<ImDrawList>
--- @field Context? ImGuiContext
--- @field ArcFastVtx table<ImVec2> # 1-based table
--- @field ArcFastRadiusCutoff float
--- @field CircleSegmentCounts table<int> # 1-based table
MT.ImDrawListSharedData = {}
MT.ImDrawListSharedData.__index = MT.ImDrawListSharedData
--- @return ImDrawListSharedData
--- @nodiscard
function ImDrawListSharedData()
local this = setmetatable({
TexUvWhitePixel = nil,
TexUvLines = nil,
FontAtlas = nil,
Font = nil,
FontSize = 0,
FontScale = 0,
CurveTessellationTol = 0,
CircleTessellationMaxError = 0,
InitialFringeScale = 1,
InitialFlags = 0,
ClipRectFullscreen = nil,
TempBuffer = ImVector(ImVec2),
DrawLists = ImVector(),
ArcFastVtx = {},
ArcFastRadiusCutoff = nil,
CircleSegmentCounts = {},
Context = nil
}, MT.ImDrawListSharedData)
for i = 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE do
local a = ((i - 1) * 2 * IM_PI) / IM_DRAWLIST_ARCFAST_TABLE_SIZE
this.ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a))
end
return this
end
--- @class ImFontAtlasBuilder
--- @field PackContext stbrp_context
--- @field PackNodes ImVector<stbrp_node>
--- @field Rects ImVector<ImTextureRect>
--- @field RectsIndex ImVector<ImFontAtlasRectEntry>
--- @field TempBuffer ImVector<char>
--- @field RectsIndexFreeListStart int
--- @field RectsPackedCount int
--- @field RectsPackedSurface int
--- @field RectsDiscardedCount int
--- @field RectsDiscardedSurface int
--- @field FrameCount int
--- @field MaxRectSize ImVec2
--- @field MaxRectBounds ImVec2
--- @field LockDisableResize bool
--- @field PreloadedAllGlyphsRanges bool
--- @field BakedPool ImVector<ImFontBaked>
--- @field BakedMap table<ImGuiID, any> # LUA: No ImGuiStorage
--- @field BakedDiscardedCount int
--- @field PackIdMouseCursors ImFontAtlasRectId
--- @field PackIdLinesTexData ImFontAtlasRectId
MT.ImFontAtlasBuilder = {}
MT.ImFontAtlasBuilder.__index = MT.ImFontAtlasBuilder
--- @return ImFontAtlasBuilder
function ImFontAtlasBuilder()
--- @type ImFontAtlasBuilder
local this = setmetatable({}, MT.ImFontAtlasBuilder)
this.PackContext = nil -- struct stbrp_context_opaque { char data[80]; };
this.PackNodes = ImVector()
this.Rects = ImVector()
this.RectsIndex = ImVector()
this.TempBuffer = ImVector()
this.RectsIndexFreeListStart = -1
this.RectsPackedCount = 0
this.RectsPackedSurface = 0
this.RectsDiscardedCount = 0
this.RectsDiscardedSurface = 0
this.FrameCount = -1
this.MaxRectSize = ImVec2()
this.MaxRectBounds = ImVec2()
this.LockDisableResize = false
this.PreloadedAllGlyphsRanges = false
this.BakedPool = ImVector() -- ImStableVector<ImFontBaked,32>
this.BakedMap = {}
this.BakedDiscardedCount = 0
this.PackIdMouseCursors = -1
this.PackIdLinesTexData = -1
return this
end
--- @class ImFontStackData
--- @field Font ImFont
--- @field FontSizeBeforeScaling float
--- @field FontSizeAfterScaling float
--- @return ImFontStackData
--- @param font ImFont
--- @param font_size_before_scaling float
--- @param font_size_after_scaling float
--- @nodiscard
function ImFontStackData(font, font_size_before_scaling, font_size_after_scaling)
return {
Font = font,
FontSizeBeforeScaling = font_size_before_scaling,
FontSizeAfterScaling = font_size_after_scaling
}
end
--- `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers!
--- @class ImGuiStyleVarInfo
--- @field Count ImU32
--- @field DataType ImGuiDataType
--- @field Key string # key in parent structure. Note that the cpp Dear ImGui uses `ImU32 Offset`!
--- @param count ImU32
--- @param data_type ImGuiDataType
--- @param key string
--- @return ImGuiStyleVarInfo
--- @nodiscard
function ImGuiStyleVarInfo(count, data_type, key)
return { Count = count, DataType = data_type, Key = key }
end
--- @class ImGuiStyleMod
--- @field VarIdx ImGuiStyleVar
--- @field BackupVal table
--- @param idx ImGuiStyleVar
--- @param v int|float|ImVec2
function ImGuiStyleMod(idx, v)
local this = { VarIdx = idx, BackupVal = {nil, nil} }
--- @cast this ImGuiStyleMod
if type(v) == "number" then
this.BackupVal[1] = v
else -- ImVec2
this.BackupVal[1] = v.x; this.BackupVal[2] = v.y
end
return this
end
--- Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo()
--- @class ImGuiDataTypeInfo
--- @field Size size_t # Size in bytes
--- @field Name string # Short descriptive name for the type, for debugging
--- @field PrintFmt string # Default printf format for the type
--- @field ScanFmt string # Default scanf format for the type
--- @class ImGuiLastItemData
--- @field ID ImGuiID
--- @field ItemFlags ImGuiItemFlags
--- @field StatusFlags ImGuiItemStatusFlags
--- @field Rect ImRect
--- @field NavRect ImRect
--- @field DisplayRect ImRect
--- @field ClipRect ImRect
--- @field Shortcut ImGuiKeyChord
--- @return ImGuiLastItemData
--- @nodiscard
function ImGuiLastItemData()
return {
ID = 0,
ItemFlags = 0,
StatusFlags = 0,
Rect = ImRect(),
NavRect = ImRect(),
DisplayRect = ImRect(),
ClipRect = ImRect(),
Shortcut = 0
}
end
--- @param dest ImGuiLastItemData
--- @param src ImGuiLastItemData
function ImGuiLastItemData_Copy(dest, src)
dest.ID = src.ID
dest.ItemFlags = src.ItemFlags
dest.StatusFlags = src.StatusFlags
ImRect_Copy(dest.Rect, src.Rect)
ImRect_Copy(dest.NavRect, src.NavRect)
ImRect_Copy(dest.DisplayRect, src.DisplayRect)
ImRect_Copy(dest.ClipRect, src.ClipRect)
dest.Shortcut = src.Shortcut
end
--- @class ImGuiTreeNodeStackData
--- @field ID ImGuiID
--- @field TreeFlags ImGuiTreeNodeFlags
--- @field ItemFlags ImGuiItemFlags
--- @field NavRect ImRect
--- @field DrawLinesX1 float
--- @field DrawLinesToNodesY2 float
--- @field DrawLinesTableColumn ImGuiTableColumnIdx
--- @return ImGuiTreeNodeStackData
--- @nodiscard
local function ImGuiTreeNodeStackData()
return {
ID = nil,
TreeFlags = nil,
ItemFlags = nil,
NavRect = ImRect(),
DrawLinesX1 = nil,
DrawLinesToNodesY2 = nil,
DrawLinesTableColumn = nil
}
end
--- @class ImGuiNextItemData
--- @field HasFlags ImGuiNextItemDataFlags
--- @field ItemFlagsSet ImGuiItemFlags
--- @field FocusScopeId ImGuiID
--- @field SelectionUserData any
--- @field Width number
--- @field Shortcut ImGuiKeyChord
--- @field ShortcutFlags ImGuiInputFlags
--- @field OpenVal boolean
--- @field OpenCond ImGuiCond
--- @field RefVal any
--- @field StorageId ImGuiID
--- @field ColorMarker ImU32
local IMGUI_NEXT_ITEM_DATA = {}
IMGUI_NEXT_ITEM_DATA.__index = IMGUI_NEXT_ITEM_DATA
function IMGUI_NEXT_ITEM_DATA:ClearFlags()
self.HasFlags = ImGuiNextItemDataFlags.None
self.ItemFlagsSet = ImGuiItemFlags.None
end
--- @return ImGuiNextItemData
--- @nodiscard
function ImGuiNextItemData()
return setmetatable({
HasFlags = 0,
ItemFlagsSet = 0,
FocusScopeId = 0,
SelectionUserData = -1,
Width = 0.0,
Shortcut = 0,
ShortcutFlags = 0,
OpenVal = false,
OpenCond = 0,
RefVal = 0,
StorageId = 0,
ColorMarker = 0
}, IMGUI_NEXT_ITEM_DATA)
end
--- @class ImGuiNextWindowData
--- @field HasFlags ImGuiNextWindowDataFlags
--- @field PosCond ImGuiCond
--- @field SizeCond ImGuiCond
--- @field CollapsedCond ImGuiCond
--- @field PosVal ImVec2?
--- @field PosPivotVal ImVec2?
--- @field SizeVal ImVec2?
--- @field ContentSizeVal ImVec2?
--- @field ScrollVal ImVec2?
--- @field WindowFlags ImGuiWindowFlags?
--- @field ChildFlags ImGuiChildFlags?
--- @field CollapsedVal boolean?
--- @field SizeConstraintRect ImRect?
--- @field SizeCallback function?
--- @field SizeCallbackUserData any
--- @field BgAlphaVal number?
--- @field MenuBarOffsetMinVal ImVec2?
--- @field RefreshFlagsVal int?
local IMGUI_NEXT_WINDOW_DATA = {}
IMGUI_NEXT_WINDOW_DATA.__index = IMGUI_NEXT_WINDOW_DATA
function IMGUI_NEXT_WINDOW_DATA:ClearFlags()
self.HasFlags = ImGuiNextWindowDataFlags.None
end
--- @return ImGuiNextWindowData
--- @nodiscard
function ImGuiNextWindowData()
return setmetatable({
HasFlags = 0,
PosCond = 0,
SizeCond = 0,
CollapsedCond = 0,
PosVal = ImVec2(),
PosPivotVal = ImVec2(),
SizeVal = ImVec2(),
ContentSizeVal = ImVec2(),
ScrollVal = ImVec2(),
WindowFlags = nil,
ChildFlags = nil,
CollapsedVal = nil,
SizeConstraintRect = nil,
SizeCallback = nil,
SizeCallbackUserData = nil,
BgAlphaVal = nil,
MenuBarOffsetMinVal = ImVec2(),
RefreshFlagsVal = nil
}, IMGUI_NEXT_WINDOW_DATA)
end
--- @enum ImGuiWindowBgClickFlags
ImGuiWindowBgClickFlags = {
None = 0,
Move = bitLShift(1, 0),
}
--- @enum ImGuiNextWindowDataFlags
ImGuiNextWindowDataFlags = {
None = 0,
HasPos = bitLShift(1, 0),
HasSize = bitLShift(1, 1),
HasContentSize = bitLShift(1, 2),
HasCollapsed = bitLShift(1, 3),
HasSizeConstraint = bitLShift(1, 4),
HasFocus = bitLShift(1, 5),
HasBgAlpha = bitLShift(1, 6),
HasScroll = bitLShift(1, 7),
HasWindowFlags = bitLShift(1, 8),
HasChildFlags = bitLShift(1, 9),
HasRefreshPolicy = bitLShift(1, 10),
HasViewport = bitLShift(1, 11),
HasDock = bitLShift(1, 12),
HasWindowClass = bitLShift(1, 13)
}
--- @enum ImGuiLayoutType
ImGuiLayoutType =
{
Horizontal = 0,
Vertical = 1
}
--- @enum ImGuiSeparatorFlags
ImGuiSeparatorFlags =
{
None = 0,
Horizontal = bitLShift(1, 0), -- Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar
Vertical = bitLShift(1, 1),
SpanAllColumns = bitLShift(1, 2) -- Make separator cover all columns of a legacy Columns() set
}
--- @class ImGuiStyle
MT.ImGuiStyle = {}
MT.ImGuiStyle.__index = MT.ImGuiStyle
--- @return ImGuiStyle
--- @nodiscard
function ImGuiStyle()
--- @type ImGuiStyle
local this = {
FontSizeBase = 0.0,
FontScaleMain = 1.0,
FontScaleDpi = 1.0,
Alpha = 1.0,
DisabledAlpha = 0.60,
FramePadding = ImVec2(4, 3),
FrameRounding = 0.0,
FrameBorderSize = 0.0,
WindowPadding = ImVec2(8, 8),
TouchExtraPadding = ImVec2(0, 0),
IndentSpacing = 21.0,
WindowRounding = 0,
WindowBorderSize = 1,
ScrollbarSize = 14.0,
ScrollbarRounding = 9.0,
ScrollbarPadding = 2.0,
GrabMinSize = 12.0,
GrabRounding = 0.0,
ImageRounding = 0.0,
ImageBorderSize = 0.0,
WindowBorderHoverPadding = 4.0,
TreeLinesFlags = ImGuiTreeNodeFlags.DrawLinesNone,
TreeLinesSize = 1.0,
TreeLinesRounding = 0.0,
MenuItemRounding = 0.0,
SelectableRounding = 0.0,
ColorMarkerSize = 3.0,
ColorButtonPosition = ImGuiDir.Right,
InputTextCursorSize = 1.0,
SeparatorSize = 1.0,
SeparatorTextBorderSize = 3.0,
SeparatorTextAlign = ImVec2(0.0, 0.5),
SeparatorTextPadding = ImVec2(20.0, 3.0),
DisplaySafeAreaPadding = ImVec2(3, 3),
DisplayWindowPadding = ImVec2(19, 19),
AntiAliasedLines = true,
AntiAliasedLinesUseTex = true,
AntiAliasedFill = true,
CurveTessellationTol = 1.25,
CircleTessellationMaxError = 0.30,
HoverStationaryDelay = 0.15,
HoverDelayShort = 0.15,
HoverDelayNormal = 0.40,
Colors = {},
ButtonTextAlign = ImVec2(0.5, 0.5),
SelectableTextAlign = ImVec2(0.0, 0.0),
WindowMinSize = ImVec2(32, 32),
WindowTitleAlign = ImVec2(0.0, 0.5),
WindowMenuButtonPosition = ImGuiDir.Left,
ChildRounding = 0.0,
ChildBorderSize = 1.0,
PopupRounding = 0.0,
PopupBorderSize = 1.0,
DockingSeparatorSize = 2.0,
MouseCursorScale = 1.0,
ItemSpacing = ImVec2(8, 4),
ItemInnerSpacing = ImVec2(4, 4),
CellPadding = ImVec2(4, 2),
ColumnsMinSpacing = 6.0,
LogSliderDeadzone = 4.0,
TabRounding = 5.0,
TabBorderSize = 0.0,
TabMinWidthBase = 1.0,
TabMinWidthShrink = 80.0,
TabCloseButtonMinWidthSelected = -1.0,
TabCloseButtonMinWidthUnselected = 0.0,
TabBarBorderSize = 1.0,
TabBarOverlineSize = 1.0,
TableAngledHeadersAngle = 35.0 * (IM_PI / 180.0),
TableAngledHeadersTextAlign = ImVec2(0.5, 0.0),
DragDropTargetRounding = 0.0,
DragDropTargetBorderSize = 2.0,
DragDropTargetPadding = 3.0,
HoverFlagsForTooltipMouse = bitOr(ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.AllowWhenDisabled),
HoverFlagsForTooltipNav = bitOr(ImGuiHoveredFlags.NoSharedDelay, ImGuiHoveredFlags.DelayNormal, ImGuiHoveredFlags.AllowWhenDisabled),
-- [Internal]
_MainScale = 1.0,
_NextFrameFontSizeBase = 0.0
}
ImGui.StyleColorsDark(this)
setmetatable(this, MT.ImGuiStyle)
return this
end
--- @class ImGuiWindowStackData
--- @return ImGuiWindowStackData
--- @nodiscard
function ImGuiWindowStackData()
return {
Window = nil,
ParentLastItemDataBackup = ImGuiLastItemData(),
StackSizesInBegin = nil,
DisabledOverrideReenable = nil,
DisabledOverrideReenableAlphaBackup = nil
}
end
--- @class ImGuiComboPreviewData
--- @field PreviewRect ImRect
--- @field BackupCursorPos ImVec2
--- @field BackupCursorMaxPos ImVec2
--- @field BackupCursorPosPrevLine ImVec2
--- @field BackupPrevLineTextBaseOffset float
--- @field BackupLayout ImGuiLayoutType
--- @return ImGuiComboPreviewData
--- @nodiscard
local function ImGuiComboPreviewData()
return {
PreviewRect = ImRect(),
BackupCursorPos = ImVec2(),
BackupCursorMaxPos = ImVec2(),
BackupCursorPosPrevLine = ImVec2(),
BackupPrevLineTextBaseOffset = 0.0,
BackupLayout = 0
}
end
--- @alias IMSTB_TEXTEDIT_STRING ImGuiInputTextState
--- @alias ImStbTexteditState STB_TexteditState
--- @class ImGuiInputTextState
--- @field Ctx ImGuiContext # parent UI context (needs to be set explicitly by parent)
--- @field Stb ImStbTexteditState # State for stb_textedit.lua
--- @field Flags ImGuiInputTextFlags
--- @field ID ImGuiID # widget id owning the text state
--- @field TextLen int # UTF-8 length of the string in TextA (in bytes)
--- @field TextSrc ImStringBuffer # == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call
--- @field TextA ImVector<char> # main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1)
--- @field TextToRevertTo ImVector<char> # value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered)
--- @field CallbackTextBackup ImVector<char> # temporary storage for callback to support automatic reconcile of undo-stack
--- @field BufCapacity int # end-user buffer capacity (include zero terminator)
--- @field Scroll ImVec2 # horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y)
--- @field LineCount int # last line count (solely for debugging)
--- @field WrapWidth float # word-wrapping width
--- @field CursorAnim float # timer for cursor blink, reset on every user action so the cursor reappears immediately
--- @field CursorFollow bool # set when we want scrolling to follow the current cursor position (not always!)
--- @field CursorCenterY bool # set when we want scrolling to be centered over the cursor position (while resizing a word-wrapping field)
--- @field SelectedAllMouseLock bool # after a double-click to select all, we ignore further mouse drags to update selection
--- @field EditedBefore bool # edited since activated
--- @field EditedThisFrame bool # edited this frame
MT.ImGuiInputTextState = {}
MT.ImGuiInputTextState.__index = MT.ImGuiInputTextState
local function ImGuiInputTextState()
local this = {
Ctx = nil,
Stb = STB_TexteditState(), -- FIXME: no global!
Flags = 0,
ID = 0,
TextLen = 0,
TextSrc = nil,
TextA = ImVector(),
TextToRevertTo = ImVector(),
CallbackTextBackup = ImVector(),
BufCapacity = 0,
Scroll = ImVec2(),
LineCount = 0,
WrapWidth = 0.0,
CursorAnim = 0.0,
CursorFollow = false,
CursorCenterY = false,
SelectedAllMouseLock = false,
EditedBefore = false,
EditedThisFrame = false,
}
return setmetatable(this, MT.ImGuiInputTextState)
end
--- @class ImGuiInputTextDeactivatedState
--- @field ID ImGuiID # widget id owning the text state (which just got deactivated)
--- @field ElapseFrame int
--- @field TextA ImVector<char> # text buffer
local IMGUI_INPUT_TEXT_DEACTIVATED_STATE = {}
IMGUI_INPUT_TEXT_DEACTIVATED_STATE.__index = IMGUI_INPUT_TEXT_DEACTIVATED_STATE
function IMGUI_INPUT_TEXT_DEACTIVATED_STATE:ClearFreeMemory()
self.ID = 0
self.ElapseFrame = 0
self.TextA:clear()
end
--- @return ImGuiInputTextDeactivatedState
--- @nodiscard
local function ImGuiInputTextDeactivatedState()
return setmetatable({
ID = 0,
ElapseFrame = 0,
TextA = ImVector()
}, IMGUI_INPUT_TEXT_DEACTIVATED_STATE)
end
--- @alias ImGuiKeyRoutingIndex ImS16
--- @class ImGuiKeyRoutingData
--- @field NextEntryIndex ImGuiKeyRoutingIndex
--- @field Mods ImU16
--- @field RoutingCurrScore ImU16
--- @field RoutingNextScore ImU16
--- @field RoutingCurr ImGuiID
--- @field RoutingNext ImGuiID
--- @return ImGuiKeyRoutingData
--- @nodiscard
function ImGuiKeyRoutingData()
return {
NextEntryIndex = -1,
Mods = 0,
RoutingCurrScore = 0,
RoutingNextScore = 0,
RoutingCurr = ImGuiKeyOwner_NoOwner,
RoutingNext = ImGuiKeyOwner_NoOwner
}
end
--- @class ImGuiKeyRoutingTable
--- @field Index ImGuiKeyRoutingIndex[]
--- @field Entries ImVector<ImGuiKeyRoutingData>
--- @field EntriesNext ImVector<ImGuiKeyRoutingData>
local _ImGuiKeyRoutingTable = {}
_ImGuiKeyRoutingTable.__index = _ImGuiKeyRoutingTable
function _ImGuiKeyRoutingTable:Clear()
for n = 1, ImGuiKey.NamedKey_COUNT do self.Index[n] = -1 end
self.Entries:clear()
self.EntriesNext:clear()
end
--- @return ImGuiKeyRoutingTable
local function ImGuiKeyRoutingTable()
local this = setmetatable({
Index = {},
Entries = ImVector(),
EntriesNext = ImVector()
}, _ImGuiKeyRoutingTable)
this:Clear()
return this
end
--- @class ImGuiTextIndex
--- @field Offsets ImVector<int>
--- @field EndOffset int
local IMGUI_TEXT_INDEX = {}
IMGUI_TEXT_INDEX.__index = IMGUI_TEXT_INDEX
function IMGUI_TEXT_INDEX:clear() self.Offsets:clear(); self.EndOffset = 0; end
function IMGUI_TEXT_INDEX:get_line_begin(base, n)
return base + (self.Offsets.Size ~= 0 and self.Offsets[n] or 0)
end
function IMGUI_TEXT_INDEX:get_line_end(base, n)
return base + ((n + 1 < self.Offsets.Size) and (self.Offsets[n + 1] - 1) or self.EndOffset)
end
--- @return ImGuiTextIndex
local function ImGuiTextIndex()
return setmetatable({ Offsets = ImVector(), EndOffset = 0 }, IMGUI_TEXT_INDEX)
end
--- @class ImGuiDebugAllocEntry
--- @field FrameCount int
--- @field AllocCount int
--- @field FreeCount int
--- @return ImGuiDebugAllocEntry
local function ImGuiDebugAllocEntry()
return { FrameCount = 0, AllocCount = 0, FreeCount = 0 }
end
--- @class ImGuiDebugAllocInfo
--- @field TotalAllocCount int
--- @field TotalFreeCount int
--- @field LastEntriesIdx ImS16
--- @field LastEntriesBuf ImGuiDebugAllocEntry[]
--- @return ImGuiDebugAllocInfo
local function ImGuiDebugAllocInfo()
local this = {
TotalAllocCount = 0,
TotalFreeCount = 0,
LastEntriesIdx = 1,
LastEntriesBuf = {nil, nil, nil, nil, nil, nil},
}
for i = 1, 6 do
this.LastEntriesBuf[i] = ImGuiDebugAllocEntry()
end
return this
end
--- @class ImGuiMetricsConfig
--- @return ImGuiMetricsConfig
local function ImGuiMetricsConfig()
return
{
HighlightMonitorIdx = -1,
HighlightViewportID = 0,
}
end
--- @class ImGuiNavItemData
--- @field Window ImGuiWindow?
--- @field ID ImGuiID
--- @field FocusScopeId ImGuiID
--- @field RectRel ImRect
--- @field ItemFlags ImGuiItemFlags
--- @field SelectionUserData ImGuiSelectionUserData
--- @field DistBox float
--- @field DistCenter float
--- @field DistAxial float
local IMGUI_NAV_ITEM_DATA = {}
IMGUI_NAV_ITEM_DATA.__index = IMGUI_NAV_ITEM_DATA
function IMGUI_NAV_ITEM_DATA:Clear()
self.Window = nil
self.ID = 0
self.FocusScopeId = 0
self.ItemFlags = 0
self.SelectionUserData = ImGuiSelectionUserData_Invalid
self.DistBox = FLT_MAX
self.DistCenter = FLT_MAX
self.DistAxial = FLT_MAX
end
--- @return ImGuiNavItemData
local function ImGuiNavItemData()
local this = setmetatable({ }, IMGUI_NAV_ITEM_DATA)
this.RectRel = ImRect()
this:Clear()
return this
end
--- @class ImGuiContext
--- @field Initialized bool
--- @field WithinFrameScope bool
--- @field WithinFrameScopeWithImplicitWindow bool
--- @field FrameCount int
--- @field FrameCountEnded int
--- @field CurrentWindow ImGuiWindow
--- @field HoveredWindow ImGuiWindow
--- @field Style ImGuiStyle
--- @field FontAtlases ImVector<ImFontAtlas>
--- @field Font ImFont
--- @field FontBaked ImFontBaked?
--- @field FontSize float
--- @field FontSizeBase float
--- @field FontBakedScale float
--- @field FontRasterizerDensity float
--- @field DrawListSharedData ImDrawListSharedData
--- @field NextItemData ImGuiNextItemData
--- @field LastItemData ImGuiLastItemData
--- @field NextWindowData ImGuiNextWindowData
--- @field WithinEndChildID ImGuiID
--- @field WithinEndPopupID ImGuiID
--- @field StyleVarStack ImVector
--- @field AnyIdHasBeenEditedThisFrame bool
--- @field ActiveId ImGuiID
--- @field ActiveIdMouseButton ImS8
--- @field Windows ImVector<ImGuiWindow>
--- @field WindowsFocusOrder ImVector<ImGuiWindow>
--- @field WindowsTempSortBuffer ImVector<ImGuiWindow>
--- @field CurrentWindowStack ImVector<ImGuiWindowStackData>
--- @field FocusScopeStack ImVector<ImGuiFocusScopeData>
--- @field ItemFlagsStack ImVector<ImGuiItemFlags>
--- @field GroupStack ImVector<ImGuiGroupData>
--- @field OpenPopupStack ImVector<ImGuiPopupData>
--- @field BeginPopupStack ImVector<ImGuiPopupData>
--- @field TreeNodeStack ImVector<ImGuiTreeNodeStackData>
--- @field IO ImGuiIO
--- @field PlatformIO ImGuiPlatformIO
--- @field Viewports ImVector<ImGuiViewportP>
--- @field DebugLogFlags ImGuiDebugLogFlags
--- @field DebugFlashStyleColorIdx ImGuiCol
--- @field ColorEditCurrentID ImGuiID # Set temporarily while inside of the parent-most ColorEdit4/ColorPicker4 (because they call each others)
--- @field ColorEditSavedID ImGuiID # ID we are saving/restoring HS for
--- @field ColorEditSavedHue float # Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips
--- @field ColorEditSavedSat float # Backup of last Saturation associated to LastColor, so we can restore Saturation in lossy RGB<>HSV round trips
--- @field ColorEditSavedColor ImU32 # RGB value with alpha set to 0
--- @field ColorPickerRef ImVec4 # Initial/reference color at the time of opening the color picker
--- @field MenusIdSubmittedThisFrame ImVector<ImGuiID>
--- @field InputTextState ImGuiInputTextState
--- @field InputTextLineIndex ImGuiTextIndex
--- @field InputTextDeactivatedState ImGuiInputTextDeactivatedState
--- @field InputTextPasswordFontBackupBaked ImFontBaked
--- @field KeysMayBeCharInput ImBitArrayForNamedKeys
--- @field KeysOwnerData ImGuiKeyOwnerData[]
--- @field KeysRoutingTable ImGuiKeyRoutingTable
--- @field NavFocusRoute ImVector<ImGuiFocusScopeData>
--- @field PlatformImeData ImGuiPlatformImeData
--- @field PlatformImeDataPrev ImGuiPlatformImeData
--- @field UserTextures ImVector<ImTextureData>
--- @field DebugMetricsConfig ImGuiMetricsConfig
--- @field DebugAllocInfo ImGuiDebugAllocInfo
--- @field TempBuffer ImVector<char>
--- @param shared_font_atlas? ImFontAtlas
--- @return ImGuiContext
--- @nodiscard
function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this structure
local this = {
Style = ImGuiStyle(),
ColorStack = ImVector(),
StyleVarStack = ImVector(),
Config = nil,
Initialized = false,
WithinFrameScope = false,
WithinFrameScopeWithImplicitWindow = false,
Windows = ImVector(), -- Windows sorted in display order, back to front
WindowsById = {}, -- Map window's ID to window ref
WindowsBorderHoverPadding = 0,
WindowsActiveCount = 0,
WindowsTempSortBuffer = ImVector(),
CurrentWindowStack = ImVector(),
CurrentWindow = nil,
WindowsFocusOrder = ImVector(),
IO = ImGuiIO(),
PlatformIO = ImGuiPlatformIO(),
ConfigFlagsCurrFrame = ImGuiConfigFlags.None,
ConfigFlagsLastFrame = ImGuiConfigFlags.None,
MouseLastValidPos = ImVec2(),
KeysMayBeCharInput = ImBitArray(ImGuiKey.NamedKey_COUNT, -ImGuiKey.NamedKey_BEGIN),
KeysOwnerData = {}, -- size = ImGuiKey.NamedKey_COUNT
KeysRoutingTable = ImGuiKeyRoutingTable(),
InputEventsQueue = ImVector(),
InputEventsNextMouseSource = ImGuiMouseSource.Mouse,
InputEventsNextEventId = 1,
MovingWindow = nil,
WheelingWindow = nil,
WheelingWindowStartFrame = -1, WheelingWindowScrolledFrame = -1,
WheelingWindowReleaseTimer = 0.0,
WheelingWindowRefMousePos = ImVec2(),
WheelingWindowWheelRemainder = ImVec2(),
WheelingAxisAvg = ImVec2(),
ActiveIdClickOffset = ImVec2(),
HoveredWindow = nil,
HoveredWindowUnderMovingWindow = nil,
HoveredIdIsDisabled = false,
ActiveIdFromShortcut = false,
AnyIdHasBeenEditedThisFrame = false,
ActiveId = 0,
ActiveIdWindow = nil,
ActiveIdMouseButton = -1,
ActiveIdIsJustActivated = false,
ActiveIdWasSelected = false, ActiveIdWasSoleSelected = false,
LastActiveIdWasSelected = false, LastActiveIdWasSoleSelected = false,
ActiveIdNoClearOnFocusLoss = false,
ActiveIdHasBeenPressedBefore = false,
ActiveIdIsAlive = nil,
ActiveIdPreviousFrame = 0,
ActiveIdTimer = 0.0,
LastActiveId = 0,
LastActiveIdTimer = 0.0,
ActiveIdUsingNavDirMask = 0x00,
ActiveIdUsingAllKeyboardKeys = false,
DeactivatedItemData = {
ID = 0,
ElapseFrame = 0,
HasBeenEditedBefore = false,
IsAlive = false
},
HoveredId = 0,
HoveredIdTimer = 0.0,
HoveredIdNotActiveTimer = 0.0,
HoveredIdAllowOverlap = false,
HoverItemDelayId = 0, HoverItemDelayIdPreviousFrame = 0, HoverItemUnlockedStationaryId = 0, HoverWindowUnlockedStationaryId = 0,
HoverItemDelayTimer = 0.0, HoverItemDelayClearTimer = 0.0,
ActiveIdAllowOverlap = false,
NavLayer = ImGuiNavLayer.Main,
NavId = 0,
NavOpenContextMenuItemId = 0, NavOpenContextMenuWindowId = 0,
NavWindow = nil,
NavHighlightActivatedId = 0,
NavHighlightActivatedTimer = 0.0,
NavCursorVisible = false,
NavCursorHideFrames = 0,
NavHighlightItemUnderNav = false,
NavIdIsAlive = false,
NavInputSource = ImGuiInputSource.Keyboard,
NavWindowingTarget = nil, NavWindowingTargetAnim = nil, NavWindowingListWindow = nil,
NavWindowingTimer = 0.0, NavWindowingHighlightAlpha = 0.0,
NavWindowingToggleLayer = false,
NavWindowingToggleKey = ImGuiKey.None,
NavWindowingInputSource = ImGuiInputSource.None,
NavWindowingAccumDeltaPos = ImVec2(0.0, 0.0), NavWindowingAccumDeltaSize = ImVec2(0.0, 0.0),
DimBgRatio = 0.0,
LastKeyboardKeyPressTime = -1.0, LastKeyModsChangeTime = -1.0, LastKeyModsChangeFromNoneTime = -1.0,
ConfigNavWindowingKeyNext = bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Tab),
ConfigNavWindowingKeyPrev = bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Tab),
ConfigNavWindowingWithGamepad = true,
NavFocusRoute = ImVector(),
NavAnyRequest = false,
NavInitRequest = false,
NavInitRequestFromMove = false,
NavInitResult = ImGuiNavItemData(),
NavMoveSubmitted = false,
NavMoveScoringItems = false,
NavMoveForwardToNextFrame = false,
NavMoveFlags = ImGuiNavMoveFlags.None,
NavMoveScrollFlags = ImGuiScrollFlags.None,
NavMoveKeyMods = ImGuiMod_None,
NavMoveDir = ImGuiDir.None, NavMoveDirForDebug = ImGuiDir.None, NavMoveClipDir = ImGuiDir.None,
NavMoveResultLocal = ImGuiNavItemData(),
NavMoveResultOther = ImGuiNavItemData(),
NavMoveResultLocalVisible = ImGuiNavItemData(),
NavTabbingResultFirst = ImGuiNavItemData(),
NavScoringRect = ImRect(),
NavScoringNoClipRect = ImRect(),
ConfigNavEnableTabbing = true,
NavTabbingCounter = 0,
NavTabbingDir = 0,
NavNextActivateId = 0,
NavNextActivateFlags = ImGuiActivateFlags.None,
NavActivateId = 0, NavActivateDownId = 0, NavActivatePressedId = 0,
NavActivateFlags = ImGuiActivateFlags.None,
FrameCount = -1,
FrameCountEnded = -1,
FrameCountPlatformEnded = -1,
FrameCountRendered = -1,
Time = 0,
NextItemData = ImGuiNextItemData(),
LastItemData = ImGuiLastItemData(),
NextWindowData = ImGuiNextWindowData(),
Viewports = ImVector(),
FallbackMonitor = nil,
GcCompactAll = false,
CurrentViewport = nil,
MouseViewport = nil, MouseLastHoveredViewport = nil,
PlatformLastFocusedViewportId = 1,
ViewportCreatedCount = 0, PlatformWindowsCreatedCount = 0,
ViewportFocusedStampCount = 0,
Font = nil,
FontSize = 0.0,
FontSizeBase = 0.0,
CurrentDpiScale = 0.0,
FontRefSize = 0.0,
FontRasterizerDensity = 1.0,
FontAtlases = ImVector(),
FontStack = ImVector(),
OpenPopupStack = ImVector(),
BeginPopupStack = ImVector(),
TreeNodeStack = ImVector(ImGuiTreeNodeStackData),
WithinEndChildID = 0, WithinEndPopupID = 0,
BeginMenuDepth = 0, BeginComboDepth = 0,
ColorEditCurrentID = 0, ColorEditSavedID = 0,
ColorEditSavedHue = 0.0, ColorEditSavedSat = 0.0,
ColorEditSavedColor = 0,
ColorPickerRef = ImVec4(),
MenusIdSubmittedThisFrame = ImVector(),
DrawListSharedData = ImDrawListSharedData(),
StackSizesInBeginForCurrentWindow = nil,
MouseCursor = ImGuiMouseCursor.Arrow,
MouseStationaryTimer = 0.0,
InputTextState = ImGuiInputTextState(),
InputTextLineIndex = ImGuiTextIndex(),
InputTextDeactivatedState = ImGuiInputTextDeactivatedState(),
InputTextPasswordFontBackupBaked = ImFontBaked(),
InputTextReactivateId = 0,
TempInputId = 0,
ActiveIdValueOnActivation = 0,
DataTypeZeroValue = 0,
ComboPreviewData = ImGuiComboPreviewData(),
WindowResizeBorderExpectedRect = ImRect(),
WindowResizeRelativeMode = false,
ScrollbarSeekMode = 0,
ScrollbarClickDeltaToGrabCenter = 0.0,
SliderGrabClickOffset = 0.0,
SliderCurrentAccum = 0.0,
SliderCurrentAccumDirty = false,
DragCurrentAccumDirty = false,
DragCurrentAccum = 0.0,
DragSpeedDefaultRatio = 1.0 / 100.0,
TooltipOverrideCount = 0,
TooltipPreviousWindow = nil,
FocusScopeStack = ImVector(),
CurrentFocusScopeId = 0,
CurrentItemFlags = ImGuiItemFlags.None,
DisabledAlphaBackup = 0.0,
DisabledStackSize = 0,
ItemFlagsStack = ImVector(),
GroupStack = ImVector(),
PlatformImeData = ImGuiPlatformImeData(),
PlatformImeDataPrev = ImGuiPlatformImeData(),
-- Extensions
UserTextures = ImVector(),
-- Settings
SettingsWindows = ImVector(),
-- Drag and Drop
DragDropActive = false,
DragDropWithinSource = false,
DragDropWithinTarget = false,
DragDropSourceFlags = 0,
DragDropAcceptIdPrev = 0, DragDropAcceptIdCurr = 0,
LocalizationTable = {},
DebugLogFlags = bitOr(ImGuiDebugLogFlags.EventError, ImGuiDebugLogFlags.OutputToTTY),
DebugFlashStyleColorIdx = nil,
DebugMetricsConfig = ImGuiMetricsConfig(),
DebugAllocInfo = ImGuiDebugAllocInfo(),
--- Misc
FramerateSecPerFrame = {}, -- size = 60
FramerateSecPerFrameIdx = 0,
FramerateSecPerFrameCount = 0,
FramerateSecPerFrameAccum = 0,
WantCaptureMouseNextFrame = -1,
WantCaptureKeyboardNextFrame = -1,
WantTextInputNextFrame = -1,
TempBuffer = ImVector(),
}
for i = 0, 59 do this.FramerateSecPerFrame[i] = 0 end
this.IO.Fonts = (shared_font_atlas ~= nil) and shared_font_atlas or ImFontAtlas()
if shared_font_atlas == nil then
this.IO.Fonts.OwnerContext = this
end
for i = 0, ImGuiKey.NamedKey_COUNT - 1 do
this.KeysOwnerData[i] = ImGuiKeyOwnerData()
end
this.IO.Ctx = this
this.InputTextState.Ctx = this
ImVec2_Copy(this.PlatformImeDataPrev.InputPos, ImVec2(-1.0, -1.0))
return this
end
--- @class ImGuiWindowSettings
--- @field ID int # Window ID
--- @field Pos ImVec2 # Window position
--- @field Size ImVec2 # Window size
--- @field Collapsed bool # Whether window is collapsed
--- @field IsChild bool # Whether window is a child window
--- @field WantApply bool # Set when loaded from .ini data
--- @field WantDelete bool # Set to invalidate/delete the settings entry
--- @field Name string # Window name
local IMGUI_WINDOW_SETTINGS = {}
IMGUI_WINDOW_SETTINGS.__index = IMGUI_WINDOW_SETTINGS
function IMGUI_WINDOW_SETTINGS:GetName()
return self.Name
end
function ImGuiWindowSettings()
return setmetatable({
ID = 0,
Pos = ImVec2(0, 0),
Size = ImVec2(0, 0),
Collapsed = false,
IsChild = false,
WantApply = false,
WantDelete = false,
Name = "",
}, IMGUI_WINDOW_SETTINGS)
end
--- @class ImGuiMenuColumns
--- @field TotalWidth ImU32
--- @field NextTotalWidth ImU32
--- @field Spacing ImU16
--- @field OffsetIcon ImU16 # Always zero for now
--- @field OffsetLabel ImU16 # Offsets are locked in Update()
--- @field OffsetShortcut ImU16
--- @field OffsetMark ImU16
--- @field Widths ImU16[] # Width of: Icon, Label, Shortcut, Mark (accumulators for current frame)
MT.ImGuiMenuColumns = {}
MT.ImGuiMenuColumns.__index = MT.ImGuiMenuColumns
--- @return ImGuiMenuColumns
local function ImGuiMenuColumns()
return setmetatable({
TotalWidth = 0,
NextTotalWidth = 0,
Spacing = 0,
OffsetIcon = 0,
OffsetLabel = 0,
OffsetShortcut = 0,
OffsetMark = 0,
Widths = {0, 0, 0, 0}
}, MT.ImGuiMenuColumns)
end
--- @class ImGuiWindowTempData
--- @field CursorPos ImVec2
--- @field CursorPosPrevLine ImVec2
--- @field CursorStartPos ImVec2
--- @field CursorMaxPos ImVec2
--- @field IdealMaxPos ImVec2
--- @field CurrLineSize ImVec2
--- @field PrevLineSize ImVec2
--- @field CurrLineTextBaseOffset float
--- @field PrevLineTextBaseOffset float
--- @field IsSameLine bool
--- @field IsSetPos bool
--- @field Indent ImVec1
--- @field ColumnsOffset ImVec1
--- @field GroupOffset ImVec1
--- @field CursorStartPosLossyness ImVec2
--- @field TextWrapPos float
--- @field TextWrapPosStack ImVector
--- @field MenuBarAppending bool
--- @field MenuBarOffset ImVec2
--- @field MenuColumns ImGuiMenuColumns
--- @field TreeDepth int
--- @field TreeHasStackDataDepthMask ImU32
--- @field TreeRecordsClippedNodesY2Mask ImU32
--- @field ChildWindows ImVector<ImGuiWindow>
--- @field LayoutType ImGuiLayoutType
--- @return ImGuiWindowTempData
--- @nodiscard
local function ImGuiWindowTempData()
return {
CursorPos = ImVec2(),
CursorPosPrevLine = ImVec2(),
CursorStartPos = ImVec2(),
CursorMaxPos = ImVec2(),
IdealMaxPos = ImVec2(),
CurrLineSize = ImVec2(),
PrevLineSize = ImVec2(),
CurrLineTextBaseOffset = 0,
PrevLineTextBaseOffset = 0,
IsSameLine = false,
IsSetPos = false,
Indent = ImVec1(),
ColumnsOffset = ImVec1(),
GroupOffset = ImVec1(),
CursorStartPosLossyness = ImVec2(),
ItemWidth = 0,
ItemWidthDefault = 0,
TextWrapPos = 0,
ItemWidthStack = ImVector(),
TextWrapPosStack = ImVector(),
MenuBarAppending = false, -- FIXME: Remove this
MenuBarOffset = ImVec2(),
MenuColumns = ImGuiMenuColumns(),
TreeDepth = 0,
TreeHasStackDataDepthMask = nil,
TreeRecordsClippedNodesY2Mask = nil,
ChildWindows = ImVector(),
StateStorage = nil,
LayoutType = nil
}
end
--- @class ImGuiWindow
--- @field Ctx ImGuiContext
--- @field Name string
--- @field ID ImGuiID
--- @field Flags ImGuiWindowFlags
--- @field FlagsPreviousFrame ImGuiWindowFlags
--- @field ChildFlags ImGuiChildFlags
--- @field WindowClass ImGuiWindowClass
--- @field Viewport ImGuiViewportP
--- @field ViewportId ImGuiID
--- @field ViewportPos ImVec2
--- @field ViewportAllowPlatformMonitorExtend int
--- @field Pos ImVec2
--- @field Size ImVec2
--- @field SizeFull ImVec2
--- @field ContentSize ImVec2
--- @field ContentSizeIdeal ImVec2
--- @field ContentSizeExplicit ImVec2
--- @field Scroll ImVec2
--- @field IsExplicitChild bool
--- @field FocusOrder short # 1-based, order within WindowsFocusOrder, altered when windows are focused. Can be -1 if invalid
--- @field IDStack ImVector<ImGuiID>
--- @field DC ImGuiWindowTempData
--- @field OuterRectClipped ImRect
--- @field InnerRect ImRect
--- @field InnerClipRect ImRect
--- @field WorkRect ImRect
--- @field ParentWorkRect ImRect
--- @field ClipRect ImRect
--- @field ContentRegionRect ImRect
--- @field DrawList ImDrawList # Points to DrawListInst
--- @field DrawListInst ImDrawList
--- @field ParentWindow? ImGuiWindow
--- @field RootWindow ImGuiWindow
--- @field RootWindowPopupTree ImGuiWindow
--- @field RootWindowDockTree ImGuiWindow
--- @field StateStorage {[ImGuiID]: bool}
--- @field MemoryDrawListIdxCapacity int
--- @field MemoryDrawListVtxCapacity int
--- @field MemoryCompacted bool
MT.ImGuiWindow = {}
MT.ImGuiWindow.__index = MT.ImGuiWindow
--- @return ImRect
--- @nodiscard
function MT.ImGuiWindow:Rect()
return ImRect(self.Pos.x, self.Pos.y, self.Pos.x + self.Size.x, self.Pos.y + self.Size.y)
end
--- @return ImRect
--- @nodiscard
function MT.ImGuiWindow:TitleBarRect()
return ImRect(self.Pos, ImVec2(self.Pos.x + self.SizeFull.x, self.Pos.y + self.TitleBarHeight))
end
--- @return ImRect
--- @nodiscard
function MT.ImGuiWindow:MenuBarRect()
local y1 = self.Pos.y + self.TitleBarHeight
return ImRect(self.Pos.x, y1, self.Pos.x + self.SizeFull.x, y1 + self.MenuBarHeight)
end
--- @return ImGuiWindow
--- @nodiscard
function ImGuiWindow(ctx, name)
local this = {
ID = 0,
MoveId = 0,
Ctx = ctx,
Name = name,
Flags = 0,
ChildFlags = 0,
WindowClass = ImGuiWindowClass(),
Pos = ImVec2(),
Size = ImVec2(), -- Current size (==SizeFull or collapsed title bar size)
SizeFull = ImVec2(),
Active = false,
WasActive = false,
Collapsed = false,
SkipItems = false,
SkipRefresh = false,
Appearing = false,
Hidden = false,
IsFallbackWindow = false,
IsExplicitChild = nil,
ResizeBorderHovered = -1,
ResizeBorderHeld = -1,
BeginCount = 0,
BeginCountPreviousFrame = 0,
BeginOrderWithinParent = 0,
BeginOrderWithinContext = 0,
FocusOrder = nil,
HiddenFramesCanSkipItems = 0,
HiddenFramesCannotSkipItems = 0,
HiddenFramesForRenderOnly = 0,
DisableInputsFrames = 0,
WindowRounding = 0,
WindowBorderSize = 1,
TitleBarHeight = 0, MenuBarHeight = 0,
DecoOuterSizeX1 = 0, DecoOuterSizeY1 = 0,
DecoOuterSizeX2 = 0, DecoOuterSizeY2 = 0,
DecoInnerSizeX1 = 0, DecoInnerSizeY1 = 0,
ContentSize = ImVec2(),
ContentSizeIdeal = ImVec2(),
ContentSizeExplicit = ImVec2(),
AutoFitFramesX = -1, AutoFitFramesY = -1,
AutoFitOnlyGrows = false,
HasCloseButton = true,
BgClickFlags = 0,
SetWindowPosAllowFlags = 0, SetWindowSizeAllowFlags = 0, SetWindowCollapsedAllowFlags = 0,
SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX),
SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX),
SettingsOffset = -1,
ScrollbarSizes = ImVec2(),
Scroll = ImVec2(),
ScrollbarX = false,
ScrollbarY = false,
ScrollMax = ImVec2(),
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX),
ScrollTargetCenterRatio = ImVec2(0.5, 0.5),
ScrollTargetEdgeSnapDist = ImVec2(),
ScrollbarXStabilizeToggledHistory = 0,
DrawList = nil,
DrawListInst = ImDrawList(ctx.DrawListSharedData),
RootWindow = nil,
RootWindowPopupTree = nil,
RootWindowDockTree = nil,
ParentWindow = nil,
ParentWindowInBeginStack = nil,
IDStack = ImVector(),
ViewportAllowPlatformMonitorExtend = -1,
Viewport = nil,
ViewportId = 0,
ViewportPos = ImVec2(FLT_MAX, FLT_MAX),
ViewportOwned = nil,
DC = ImGuiWindowTempData(),
OuterRectClipped = ImRect(),
InnerRect = ImRect(),
InnerClipRect = ImRect(),
WorkRect = ImRect(),
ParentWorkRect = ImRect(),
ContentRegionRect = ImRect(),
ClipRect = ImRect(),
LastFrameActive = -1,
LastFrameJustFocused = -1,
LastTimeActive = -1.0,
StateStorage = {},
WriteAccessed = false,
FontWindowScale = 1.0,
FontWindowScaleParents = 1.0,
HitTestHoleSize = ImVec2(),
NavLastChildNavWindow = nil,
NavLastIds = {[0] = 0, [1] = 0}, -- FIXME: 1-based instead
NavRectRel = {[0] = ImRect(), [1] = ImRect()},
NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()},
NavRootFocusScopeId = 0
}
this.DrawList = this.DrawListInst
this.DrawList._OwnerName = name
setmetatable(this, MT.ImGuiWindow)
this.ID = ImHashStr(name)
this.IDStack:push_back(this.ID)
this.MoveId = this:GetID("#MOVE")
return this
end
--- @class ImDrawDataBuilder
--- @field Layers [ImVector<ImDrawList>?, ImVector<ImDrawList>?]
--- @field LayerData1 ImVector<ImDrawList>
--- @return ImDrawDataBuilder
--- @nodiscard
local function ImDrawDataBuilder()
return
{
Layers = {nil, nil},
LayerData1 = ImVector()
}
end
--- @class ImGuiViewportP : ImGuiViewport
--- @field Window? ImGuiWindow
--- @field Idx int # Initial value = -1, then becomes 1-based index
--- @field LastFrameActive int
--- @field LastFocusedStampCount int
--- @field LastNameHash ImGuiID
--- @field LastPos ImVec2
--- @field LastSize ImVec2
--- @field Alpha float
--- @field LastAlpha float
--- @field LastFocusedHadNavWindow bool
--- @field PlatformMonitor short
--- @field BgFgDrawListsLastTimeActive [int, int] # 1-based
--- @field BgFgDrawLists [ImDrawList, ImDrawList] # 1-based
--- @field DrawDataP ImDrawData
--- @field DrawDataBuilder ImDrawDataBuilder
--- @field LastPlatformPos ImVec2
--- @field LastPlatformSize ImVec2
--- @field LastRendererSize ImVec2
--- @field WorkInsetMin ImVec2
--- @field WorkInsetMax ImVec2
--- @field BuildWorkInsetMin ImVec2
--- @field BuildWorkInsetMax ImVec2
local IMGUI_VIEWPORT_P = {}
IMGUI_VIEWPORT_P.__index = IMGUI_VIEWPORT_P
setmetatable(IMGUI_VIEWPORT_P, {__index = MT.ImGuiViewport})
function IMGUI_VIEWPORT_P:ClearRequestFlags()
self.PlatformRequestClose = false
self.PlatformRequestMove = false
self.PlatformRequestResize = false
end
function IMGUI_VIEWPORT_P:CalcWorkRectPos(inset_min)
return ImVec2(self.Pos.x + inset_min.x, self.Pos.y + inset_min.y)
end
function IMGUI_VIEWPORT_P:CalcWorkRectSize(inset_min, inset_max)
return ImVec2(ImMax(0.0, self.Size.x - inset_min.x - inset_max.x), ImMax(0.0, self.Size.y - inset_min.y - inset_max.y))
end
function IMGUI_VIEWPORT_P:UpdateWorkRect()
self.WorkPos = self:CalcWorkRectPos(self.WorkInsetMin)
self.WorkSize = self:CalcWorkRectSize(self.WorkInsetMin, self.WorkInsetMax)
end
--- @nodiscard
function IMGUI_VIEWPORT_P:GetMainRect()
return ImRect(self.Pos.x, self.Pos.y,
self.Pos.x + self.Size.x,
self.Pos.y + self.Size.y)
end
--- @nodiscard
function IMGUI_VIEWPORT_P:GetWorkRect()
return ImRect(self.WorkPos.x, self.WorkPos.y,
self.WorkPos.x + self.WorkSize.x,
self.WorkPos.y + self.WorkSize.y)
end
--- @nodiscard
function IMGUI_VIEWPORT_P:GetBuildWorkRect()
local pos = self:CalcWorkRectPos(self.BuildWorkInsetMin)
local size = self:CalcWorkRectSize(self.BuildWorkInsetMin, self.BuildWorkInsetMax)
return ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y)
end
--- @return ImGuiViewportP
--- @nodiscard
function ImGuiViewportP()
local this = setmetatable(ImGuiViewport(), IMGUI_VIEWPORT_P) --- @cast this ImGuiViewportP
this.Window = nil
this.Idx = -1
this.LastFrameActive = -1
this.LastFocusedStampCount = -1
this.LastNameHash = 0
this.LastPos = ImVec2() -- ImGuiViewport() { memset(this, 0, sizeof(*this)); }
this.LastSize = ImVec2()
this.Alpha = 1.0
this.LastAlpha = 1.0
this.LastFocusedHadNavWindow = false
this.PlatformMonitor = -1
this.BgFgDrawListsLastTimeActive = {-1, -1}
this.BgFgDrawLists = {nil, nil}
this.DrawDataP = ImDrawData()
this.DrawDataBuilder = ImDrawDataBuilder()
this.LastPlatformPos = ImVec2(FLT_MAX, FLT_MAX)
this.LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX)
this.LastRendererSize = ImVec2(FLT_MAX, FLT_MAX)
this.WorkInsetMin = ImVec2(0, 0)
this.WorkInsetMax = ImVec2(0, 0)
this.BuildWorkInsetMin = ImVec2(0, 0)
this.BuildWorkInsetMax = ImVec2(0, 0)
return this
end
--- @class ImFontLoader
--- @field Name string
--- @field LoaderInit? fun(atlas: ImFontAtlas): bool
--- @field LoaderShutdown? fun(atlas: ImFontAtlas)
--- @field FontSrcInit? fun(atlas: ImFontAtlas, src: ImFontConfig): bool
--- @field FontSrcDestroy? fun(atlas: ImFontAtlas, src: ImFontConfig)
--- @field FontSrcContainsGlyph? fun(atlas: ImFontAtlas, src: ImFontConfig, codepoint: ImWchar): bool
--- @field FontBakedInit? fun(atlas: ImFontAtlas, src: ImFontConfig, baked: ImFontBaked, loader_data_for_baked_src?: any): bool
--- @field FontBakedDestroy? fun(atlas: ImFontAtlas, src: ImFontConfig, baked: ImFontBaked, loader_data_for_baked_src?: any)
--- @field FontBakedLoadGlyph fun(atlas: ImFontAtlas, src: ImFontConfig, baked: ImFontBaked, loader_data_for_baked_src?: any, codepoint: ImWchar, out_glyph?: ImFontGlyph, advance_x?: float): bool, float?
--- @field FontBakedSrcLoaderDataSize unsigned_int
MT.ImFontLoader = {}
MT.ImFontLoader.__index = MT.ImFontLoader
--- @return ImFontLoader
--- @nodiscard
function ImFontLoader()
--- @type ImFontLoader
local this = setmetatable({}, MT.ImFontLoader)
this.Name = nil
this.LoaderInit = nil
this.LoaderShutdown = nil
this.FontSrcInit = nil
this.FontSrcDestroy = nil
this.FontSrcContainsGlyph = nil
this.FontBakedInit = nil
this.FontBakedDestroy = nil
this.FontBakedLoadGlyph = nil
this.FontBakedSrcLoaderDataSize = 0
return this
end
--- @class ImFontAtlasRectEntry
--- @field TargetIndex int # 0-based! When IsUsed = true, TargetIndex = this rect's index in Rects; IsUsed = false, TargetIndex = the next unused RectsIndex entry's index
--- @field Generation unsigned_int # How many times this entry is reused
--- @field IsUsed bool
--- @return ImFontAtlasRectEntry
--- @nodiscard
function ImFontAtlasRectEntry()
return {
TargetIndex = 0,
Generation = 0,
IsUsed = false
}
end
local ImFontAtlasRectId_IndexMask_ = 0x0007FFFF
local ImFontAtlasRectId_GenerationMask_ = 0x3FF00000
local ImFontAtlasRectId_GenerationShift_ = 20
--- @param id ImFontAtlasRectId # Expects 0-based!
--- @return int # 0-based!
function ImFontAtlasRectId_GetIndex(id) return bitAnd(id, ImFontAtlasRectId_IndexMask_) end
--- @param id ImFontAtlasRectId # Expects 0-based!
--- @return unsigned_int
function ImFontAtlasRectId_GetGeneration(id) return bitRShift(bitAnd(id, ImFontAtlasRectId_GenerationMask_), ImFontAtlasRectId_GenerationShift_) end
--- @param index_idx int # Expects 0-based!
--- @param gen_idx int
--- @return ImFontAtlasRectId # 0-based!
function ImFontAtlasRectId_Make(index_idx, gen_idx)
IM_ASSERT(index_idx >= 0 and index_idx <= ImFontAtlasRectId_IndexMask_ and gen_idx <= bitRShift(ImFontAtlasRectId_GenerationMask_, ImFontAtlasRectId_GenerationShift_))
return bitOr(index_idx, bitLShift(gen_idx, ImFontAtlasRectId_GenerationShift_))
end
--- @class ImFontAtlasPostProcessData
--- @field FontAtlas ImFontAtlas
--- @field Font ImFont
--- @field FontSrc ImFontConfig
--- @field FontBaked ImFontBaked
--- @field Glyph ImFontGlyph
--- @field Pixels unsigned_char[]
--- @field _PixelsBase int # LUA: in cpp code the `Pixels` is a pointer. we can do this to avoid creating another custom structure to mimic it
--- @field Format ImTextureFormat
--- @field Pitch int
--- @field Width int
--- @field Height int
--- @param atlas ImFontAtlas
--- @param font ImFont
--- @param font_src ImFontConfig
--- @param font_baked ImFontBaked
--- @param glyph ImFontGlyph
--- @param pixels unsigned_char[]
--- @param pixels_base int
--- @param format ImTextureFormat
--- @param pitch int
--- @param width int
--- @param height int
--- @return ImFontAtlasPostProcessData
--- @nodiscard
function ImFontAtlasPostProcessData(atlas, font, font_src, font_baked, glyph, pixels, pixels_base, format, pitch, width, height)
return {
FontAtlas = atlas,
Font = font,
FontSrc = font_src,
FontBaked = font_baked,
Glyph = glyph,
Pixels = pixels,
_PixelsBase = pixels_base,
Format = format,
Pitch = pitch,
Width = width,
Height = height,
}
end
--- @enum ImGuiInputSource
ImGuiInputSource = {
None = 0,
Mouse = 1,
Keyboard = 2,
Gamepad = 3,
COUNT = 4
}
--- @class ImGuiInputEventMousePos
--- @field PosX float
--- @field PosY float
--- @field MouseSource ImGuiMouseSource
--- @return ImGuiInputEventMousePos
--- @nodiscard
function ImGuiInputEventMousePos()
return { PosX = 0, PosY = 0, MouseSource = ImGuiMouseSource.Mouse }
end
--- @class ImGuiInputEventMouseButton
--- @field Button int
--- @field Down bool
--- @field MouseSource ImGuiMouseSource
--- @return ImGuiInputEventMouseButton
--- @nodiscard
function ImGuiInputEventMouseButton()
return { Button = 0, Down = false, MouseSource = ImGuiMouseSource.Mouse }
end
--- @class ImGuiInputEventMouseWheel
--- @field WheelX float
--- @field WheelY float
--- @field MouseSource ImGuiMouseSource
--- @return ImGuiInputEventMouseWheel
--- @nodiscard
function ImGuiInputEventMouseWheel()
return { WheelX = 0, WheelY = 0, MouseSource = ImGuiMouseSource.Mouse }
end
--- @class ImGuiInputEventKey
--- @field Key ImGuiKey
--- @field Down bool
--- @field AnalogValue float
--- @return ImGuiInputEventKey
--- @nodiscard
function ImGuiInputEventKey()
return { Key = 0, Down = false, AnalogValue = 0 }
end
--- @class ImGuiInputEventText
--- @field Char unsigned_int
--- @return ImGuiInputEventText
--- @nodiscard
function ImGuiInputEventText()
return { Char = nil }
end
--- @class ImGuiInputEventAppFocused
--- @field Focused bool
--- @return ImGuiInputEventAppFocused
--- @nodiscard
function ImGuiInputEventAppFocused()
return { Focused = nil }
end
--- @class ImGuiInputEventMouseViewport
--- @field HoveredViewportID ImGuiID
--- @return ImGuiInputEventMouseViewport
--- @nodiscard
function ImGuiInputEventMouseViewport()
return { HoveredViewportID = 0 }
end
--- @class ImGuiInputEvent
--- @return ImGuiInputEvent
--- @nodiscard
function ImGuiInputEvent()
return {
Type = 0,
Source = 0,
EventId = 0,
-- union
MousePos = nil, -- if Type == ImGuiInputEventType.MousePos
MouseWheel = nil, -- if Type == ImGuiInputEventType.MouseWheel
MouseButton = nil, -- if Type == ImGuiInputEventType.MouseButton
MouseViewport = nil, -- if Type == ImGuiInputEventType.MouseViewport
Key = nil, -- if Type == ImGuiInputEventType.Key
Text = nil, -- if Type == ImGuiInputEventType.Text
AppFocused = nil, -- if Type == ImGuiInputEventType.Focus
}
end
ImGuiKey_Keyboard_BEGIN = ImGuiKey.NamedKey_BEGIN
ImGuiKey_Keyboard_END = ImGuiKey.GamepadStart
ImGuiKey_Gamepad_BEGIN = ImGuiKey.GamepadStart
ImGuiKey_Gamepad_END = ImGuiKey.GamepadRStickDown + 1
ImGuiKey_Mouse_BEGIN = ImGuiKey.MouseLeft
ImGuiKey_Mouse_END = ImGuiKey.MouseWheelY + 1
ImGuiKey_Aliases_BEGIN = ImGuiKey_Mouse_BEGIN
ImGuiKey_Aliases_END = ImGuiKey_Mouse_END
ImGuiKey.NavKeyboardTweakSlow = ImGuiMod_Ctrl
ImGuiKey.NavKeyboardTweakFast = ImGuiMod_Shift
ImGuiKey.NavGamepadTweakSlow = ImGuiKey.GamepadL1
ImGuiKey.NavGamepadTweakFast = ImGuiKey.GamepadR1
ImGuiKey.NavGamepadMenu = ImGuiKey.GamepadFaceLeft
ImGuiKey.NavGamepadContextMenu = ImGuiKey.GamepadFaceUp
--- @enum ImGuiInputEventType
ImGuiInputEventType = {
None = 0,
MousePos = 1,
MouseWheel = 2,
MouseButton = 3,
MouseViewport = 4,
Key = 5,
Text = 6,
Focus = 7,
COUNT = 8
}
ImGuiInputFlags.RepeatRateDefault = bitLShift(1, 1)
ImGuiInputFlags.RepeatRateNavMove = bitLShift(1, 2)
ImGuiInputFlags.RepeatRateNavTweak = bitLShift(1, 3)
ImGuiInputFlags.RepeatUntilRelease = bitLShift(1, 4)
ImGuiInputFlags.RepeatUntilKeyModsChange = bitLShift(1, 5)
ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone = bitLShift(1, 6)
ImGuiInputFlags.RepeatUntilOtherKeyPress = bitLShift(1, 7)
ImGuiInputFlags.LockThisFrame = bitLShift(1, 20)
ImGuiInputFlags.LockUntilRelease = bitLShift(1, 21)
ImGuiInputFlags.CondHovered = bitLShift(1, 22)
ImGuiInputFlags.CondActive = bitLShift(1, 23)
ImGuiInputFlags.CondDefault_ = bitOr(ImGuiInputFlags.CondHovered, ImGuiInputFlags.CondActive)
ImGuiInputFlags.RepeatRateMask_ = bitOr(ImGuiInputFlags.RepeatRateDefault, ImGuiInputFlags.RepeatRateNavMove, ImGuiInputFlags.RepeatRateNavTweak)
ImGuiInputFlags.RepeatUntilMask_ = bitOr(ImGuiInputFlags.RepeatUntilRelease, ImGuiInputFlags.RepeatUntilKeyModsChange, ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone, ImGuiInputFlags.RepeatUntilOtherKeyPress)
ImGuiInputFlags.RepeatMask_ = bitOr(ImGuiInputFlags.Repeat, ImGuiInputFlags.RepeatRateMask_, ImGuiInputFlags.RepeatUntilMask_)
ImGuiInputFlags.CondMask_ = bitOr(ImGuiInputFlags.CondHovered, ImGuiInputFlags.CondActive)
ImGuiInputFlags.RouteTypeMask_ = bitOr(ImGuiInputFlags.RouteActive, ImGuiInputFlags.RouteFocused, ImGuiInputFlags.RouteGlobal, ImGuiInputFlags.RouteAlways)
ImGuiInputFlags.RouteOptionsMask_ = bitOr(ImGuiInputFlags.RouteOverFocused, ImGuiInputFlags.RouteOverActive, ImGuiInputFlags.RouteUnlessBgFocused, ImGuiInputFlags.RouteFromRootWindow)
ImGuiInputFlags.SupportedByIsKeyPressed = ImGuiInputFlags.RepeatMask_
ImGuiInputFlags.SupportedByIsMouseClicked = ImGuiInputFlags.Repeat
ImGuiInputFlags.SupportedByShortcut = bitOr(ImGuiInputFlags.RepeatMask_, ImGuiInputFlags.RouteTypeMask_, ImGuiInputFlags.RouteOptionsMask_)
ImGuiInputFlags.SupportedBySetNextItemShortcut = bitOr(ImGuiInputFlags.RepeatMask_, ImGuiInputFlags.RouteTypeMask_, ImGuiInputFlags.RouteOptionsMask_, ImGuiInputFlags.Tooltip)
ImGuiInputFlags.SupportedBySetKeyOwner = bitOr(ImGuiInputFlags.LockThisFrame, ImGuiInputFlags.LockUntilRelease)
ImGuiInputFlags.SupportedBySetItemKeyOwner = bitOr(ImGuiInputFlags.SupportedBySetKeyOwner, ImGuiInputFlags.CondMask_)
--- @enum ImGuiAxis # can be used to index ImVec2
ImGuiAxis =
{
None = 0,
X = 1,
Y = 2
}
--- @enum ImGuiPlotType
ImGuiPlotType =
{
Lines = 0,
Histogram = 1
}
--- @enum ImGuiActivateFlags
ImGuiActivateFlags = {
None = 0,
PreferInput = bitLShift(1, 0),
PreferTweak = bitLShift(1, 1),
TryToPreserveState = bitLShift(1, 2),
FromTabbing = bitLShift(1, 3),
FromShortcut = bitLShift(1, 4),
FromFocusApi = bitLShift(1, 5)
}
--- @enum ImGuiScrollFlags
ImGuiScrollFlags = {
None = 0,
KeepVisibleEdgeX = bitLShift(1, 0),
KeepVisibleEdgeY = bitLShift(1, 1),
KeepVisibleCenterX = bitLShift(1, 2),
KeepVisibleCenterY = bitLShift(1, 3),
AlwaysCenterX = bitLShift(1, 4),
AlwaysCenterY = bitLShift(1, 5),
NoScrollParent = bitLShift(1, 6),
}
ImGuiScrollFlags.MaskX_ = bitOr(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleCenterX, ImGuiScrollFlags.AlwaysCenterX)
ImGuiScrollFlags.MaskY_ = bitOr(ImGuiScrollFlags.KeepVisibleEdgeY, ImGuiScrollFlags.KeepVisibleCenterY, ImGuiScrollFlags.AlwaysCenterY)
--- @class ImGuiGroupData
--- @field WindowID ImGuiID
--- @field BackupCursorPos ImVec2
--- @field BackupCursorMaxPos ImVec2
--- @field BackupCursorPosPrevLine ImVec2
--- @field BackupIndent ImVec1
--- @field BackupGroupOffset ImVec1
--- @field BackupCurrLineSize ImVec2
--- @field BackupCurrLineTextBaseOffset float
--- @field BackupActiveIdIsAlive ImGuiID
--- @field BackupAnyIdHasBeenEditedThisFrame bool
--- @field BackupDeactivatedIdIsAlive bool
--- @field BackupHoveredIdIsAlive bool
--- @field BackupIsSameLine bool
--- @field EmitItem bool
--- @return ImGuiGroupData
--- @nodiscard
function ImGuiGroupData()
return
{
WindowID = nil,
BackupCursorPos = ImVec2(),
BackupCursorMaxPos = ImVec2(),
BackupCursorPosPrevLine = ImVec2(),
BackupIndent = ImVec1(),
BackupGroupOffset = ImVec1(),
BackupCurrLineSize = ImVec2(),
BackupCurrLineTextBaseOffset = nil,
BackupActiveIdIsAlive = nil,
BackupAnyIdHasBeenEditedThisFrame = nil,
BackupDeactivatedIdIsAlive = nil,
BackupHoveredIdIsAlive = nil,
BackupIsSameLine = nil,
EmitItem = nil
}
end
--- @enum ImGuiTooltipFlags
ImGuiTooltipFlags =
{
None = 0,
OverridePrevious = bitLShift(1, 1)
}
--- @enum ImGuiPopupPositionPolicy
ImGuiPopupPositionPolicy =
{
Default = 0,
ComboBox = 1,
Tooltip = 2
}
--- @class ImGuiPopupData
--- @field PopupId ImGuiID
--- @field Window ImGuiWindow
--- @field RestoreNavWindow ImGuiWindow
--- @field ParentNavLayer int
--- @field OpenFrameCount int
--- @field OpenParentId ImGuiID
--- @field OpenPopupPos ImVec2
--- @field OpenMousePos ImVec2
--- @return ImGuiPopupData
--- @nodiscard
function ImGuiPopupData()
return {
PopupId = 0,
Window = nil,
RestoreNavWindow = nil,
ParentNavLayer = -1,
OpenFrameCount = -1,
OpenParentId = 0,
OpenPopupPos = ImVec2(),
OpenMousePos = ImVec2()
}
end
--- @enum ImGuiWindowRefreshFlags
ImGuiWindowRefreshFlags = {
None = 0,
TryToAvoidRefresh = bitLShift(1, 0),
RefreshOnHover = bitLShift(1, 1),
RefreshOnFocus = bitLShift(1, 2)
}
--- @enum ImGuiNavRenderCursorFlags
ImGuiNavRenderCursorFlags = {
None = 0,
Compact = bitLShift(1, 1), -- Compact highlight, no padding/distance from focused item
AlwaysDraw = bitLShift(1, 2), -- Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse
}
--- @enum ImGuiDebugLogFlags
ImGuiDebugLogFlags = {
-- Event types
None = 0,
EventError = bitLShift(1, 0), -- Error submitted by IM_ASSERT_USER_ERROR()
EventActiveId = bitLShift(1, 1),
EventFocus = bitLShift(1, 2),
EventPopup = bitLShift(1, 3),
EventNav = bitLShift(1, 4),
EventClipper = bitLShift(1, 5),
EventSelection = bitLShift(1, 6),
EventIO = bitLShift(1, 7),
EventFont = bitLShift(1, 8),
EventInputRouting = bitLShift(1, 9),
EventDocking = bitLShift(1, 10),
EventViewport = bitLShift(1, 11),
EventTable = bitLShift(1, 12),
OutputToTTY = bitLShift(1, 20),
OutputToDebugger = bitLShift(1, 21),
OutputToTestEngine = bitLShift(1, 22),
}
ImGuiDebugLogFlags.EventMask_ = bitOr(
ImGuiDebugLogFlags.EventError,
ImGuiDebugLogFlags.EventActiveId,
ImGuiDebugLogFlags.EventFocus,
ImGuiDebugLogFlags.EventPopup,
ImGuiDebugLogFlags.EventNav,
ImGuiDebugLogFlags.EventClipper,
ImGuiDebugLogFlags.EventSelection,
ImGuiDebugLogFlags.EventTable,
ImGuiDebugLogFlags.EventIO,
ImGuiDebugLogFlags.EventFont,
ImGuiDebugLogFlags.EventInputRouting,
ImGuiDebugLogFlags.EventDocking,
ImGuiDebugLogFlags.EventViewport
)
--- @enum ImGuiLocKey
ImGuiLocKey = {
VersionStr = 1,
TableSizeOne = 2,
TableSizeAllFit = 3,
TableSizeAllDefault = 4,
TableReset = 5,
TableResetOrder = 6,
TableResetVisibility = 7,
WindowingMainMenuBar = 8,
WindowingPopup = 9,
WindowingUntitled = 10,
OpenLink_s = 11,
CopyLink = 12,
DockingHideTabBar = 13,
DockingHoldShiftToDock = 14,
DockingDragToUndockOrMoveNode = 15,
COUNT = 15
}
--- @class ImGuiLocEntry
--- @field Key ImGuiLocKey
--- @field Text string
--- @param key ImGuiLocKey
--- @return string
function ImGui.LocalizeGetMsg(key)
local g = GImGui
local msg = g.LocalizationTable[key]
if msg then return msg else return "*Missing Text*" end
end
--- @param id ImGuiID
function ImGui.TempInputIsActive(id)
local g = GImGui
return (g.TempInputId == id and g.ActiveId == id) or (g.InputTextDeactivatedState.ID == id)
end
--- @param id ImGuiID
--- @return ImGuiInputTextState?
function ImGui.GetInputTextState(id)
local g = GImGui
if id ~= 0 and g.InputTextState.ID == id then
return g.InputTextState
end
return nil
end
-- Storage for PushFocusScope(), g.FocusScopeStack[], g.NavFocusRoute[]
--- @class ImGuiFocusScopeData
--- @field ID ImGuiID
--- @field WindowID ImGuiID
--- @return ImGuiFocusScopeData
--- @nodiscard
function ImGuiFocusScopeData() return { ID = nil, WindowID = nil } end
return true -- [Roblox] ModuleScripts must return exactly one value
end
__FILES['imgui_tables.lua'] = function()
--- ImGui Sincerely WIP
-- (Tables and Columns Code)
--- @type ImGuiContext?
local GImGui
-- Sets local `GImGui` in this file(imgui_tables.lua).
-- This is currently only used in main code `ImGui.SetCurrentContext()`
--- @param ctx ImGuiContext?
function ImGui._SetCurrentContext_Tables(ctx)
GImGui = ctx
end
--- @param str_id string
--- @param columns_count int
--- @param flags? ImGuiTableFlags
--- @param outer_size? ImVec2
--- @param inner_width? float
function ImGui.BeginTable(str_id, columns_count, flags, outer_size, inner_width)
if flags == nil then flags = 0 end
if outer_size == nil then outer_size = ImVec2(0.0, 0.0) end
if inner_width == nil then inner_width = 0.0 end
-- TODO:
return true
end
function ImGui.EndTable()
-- TODO:
end
function ImGui.TableNextColumn()
-- TODO:
end
function ImGui.TablePushBackgroundChannel()
-- TODO:
end
function ImGui.TablePopBackgroundChannel()
-- TODO:
end
return true -- [Roblox] ModuleScripts must return exactly one value
end
__FILES['imgui_widgets.lua'] = function()
--- ImGui Sincerely WIP
-- (Widgets Code)
--- @type ImGuiContext?
local GImGui
-- Sets local `GImGui` in this file(imgui_widgets.lua).
-- This is currently only used in main code `ImGui.SetCurrentContext()`
--- @param ctx ImGuiContext?
function ImGui._SetCurrentContext_Widgets(ctx)
GImGui = ctx
end
local DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70 -- Time for drag-hold to activate items accepting the ImGuiButtonFlags.PressedOnDragDropHold button behavior
local DRAG_MOUSE_THRESHOLD_FACTOR = 0.50 -- Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags
local IM_S8_MIN = -128
local IM_S8_MAX = 127
local IM_U8_MIN = 0
local IM_U8_MAX = 0xFF
local IM_S16_MIN = -32768
local IM_S16_MAX = 32767
local IM_U16_MIN = 0
local IM_U16_MAX = 0xFFFF
local IM_S32_MIN = INT_MIN
local IM_S32_MAX = INT_MAX
local IM_U32_MIN = 0
local IM_U32_MAX = UINT_MAX
----------------------------------------------------------------
-- [SECTION] TEXT
----------------------------------------------------------------
--- @param text string
--- @param text_end? int
--- @param flags? ImGuiTextFlags
function ImGui.TextEx(text, text_end, flags)
if not flags then flags = 0 end
local g = GImGui
local window = g.CurrentWindow
if window.SkipItems then
return
end
if not text or text == "" then
text = ""
text_end = 1
end
if text_end == nil then
text_end = #text + 1
end
local text_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset)
local wrap_pos_x = window.DC.TextWrapPos
local wrap_enabled = (wrap_pos_x >= 0.0)
if (text_end - 1 <= 2000) or wrap_enabled then
local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(window.DC.CursorPos, wrap_pos_x) or 0.0
local text_size = ImGui.CalcTextSize(text, text_end, false, wrap_width)
local bb = ImRect(text_pos, text_pos + text_size)
ImGui.ItemSize(text_size, 0.0)
if not ImGui.ItemAdd(bb, 0) then
return
end
ImGui.RenderTextWrapped(bb.Min, text, text_end, wrap_width)
else
local line = 1
local line_height = ImGui.GetTextLineHeight()
local text_size = ImVec2(0, 0)
local pos = ImVec2(text_pos.x, text_pos.y)
if not g.LogEnabled then
local lines_skippable = ImFloor((window.ClipRect.Min.y - text_pos.y) / line_height)
if lines_skippable > 0 then
local lines_skipped = 0
while line < text_end and lines_skipped < lines_skippable do
local line_end = ImMemchr(text, "\n", line)
if not line_end then
line_end = text_end
end
if bit32.band(flags, ImGuiTextFlags.NoWidthForLargeClippedText) == 0 then
local line_size = ImGui.CalcTextSizeEx(text, line, line_end)
text_size.x = ImMax(text_size.x, line_size.x)
end
line = line_end + 1
lines_skipped = lines_skipped + 1
end
pos.y = pos.y + lines_skipped * line_height
end
end
if line < text_end then
local line_rect = ImRect(pos, pos + ImVec2(FLT_MAX, line_height))
while line < text_end do
if ImGui.IsClippedEx(line_rect, 0) then
break
end
local line_end = ImMemchr(text, "\n", line)
if not line_end then
line_end = text_end
end
local line_size = ImGui.CalcTextSizeEx(text, line, line_end)
text_size.x = ImMax(text_size.x, line_size.x)
ImGui.RenderText(pos, text, line, nil, false)
line = line_end + 1
line_rect.Min.y = line_rect.Min.y + line_height
line_rect.Max.y = line_rect.Max.y + line_height
pos.y = pos.y + line_height
end
local lines_skipped = 0
while line < text_end do
local line_end = ImMemchr(text, "\n", line)
if not line_end then
line_end = text_end
end
if bit32.band(flags, ImGuiTextFlags.NoWidthForLargeClippedText) == 0 then
local line_size = ImGui.CalcTextSizeEx(text, line, line_end)
text_size.x = ImMax(text_size.x, line_size.x)
end
line = line_end + 1
lines_skipped = lines_skipped + 1
end
pos.y = pos.y + lines_skipped * line_height
end
text_size.y = pos.y - text_pos.y
local bb = ImRect(text_pos, text_pos + text_size)
ImGui.ItemSize(text_size, 0.0)
ImGui.ItemAdd(bb, 0)
end
end
--- @param text string
--- @param text_end? int
function ImGui.TextUnformatted(text, text_end)
ImGui.TextEx(text, text_end, ImGuiTextFlags.NoWidthForLargeClippedText)
end
--- @param fmt string
--- @param ... any
function ImGui.TextV(fmt, ...)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local text = ImFormatString(fmt, ...)
ImGui.TextEx(text, nil, ImGuiTextFlags.NoWidthForLargeClippedText)
end
--- @param fmt string
--- @param ... any
function ImGui.Text(fmt, ...)
if select('#', ...) > 0 then
ImGui.TextV(fmt, ...)
else
ImGui.TextEx(fmt)
end
end
--- @param col ImVec4
--- @param fmt string
--- @param ... any
function ImGui.TextColored(col, fmt, ...)
ImGui.PushStyleColor(ImGuiCol.Text, col)
ImGui.TextV(fmt, ...)
ImGui.PopStyleColor()
end
--- @param fmt string
--- @param ... any
function ImGui.TextDisabled(fmt, ...)
local g = GImGui
ImGui.PushStyleColor(ImGuiCol.Text, g.Style.Colors[ImGuiCol.TextDisabled])
ImGui.TextV(fmt, ...)
ImGui.PopStyleColor()
end
--- @param fmt string
--- @param ... any
function ImGui.TextWrapped(fmt, ...)
local g = GImGui
local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0)
if need_backup then
ImGui.PushTextWrapPos(0.0)
end
ImGui.TextV(fmt, ...)
if need_backup then
ImGui.PopTextWrapPos()
end
end
-- align_x: 0.0f = left, 0.5f = center, 1.0f = right.
-- size_x : 0.0f = shortcut for GetContentRegionAvail().x
-- FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024)
--- @param align_x float
--- @param size_x float
--- @param fmt string
--- @param ... any
function ImGui.TextAligned(align_x, size_x, fmt, ...)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local text = ImFormatString(fmt, ...)
local text_end = #text + 1
local text_size = ImGui.CalcTextSize(text, text_end)
size_x = ImGui.CalcItemSize(ImVec2(size_x, 0.0), 0.0, text_size.y).x
local pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset)
local pos_max = ImVec2(pos.x + size_x, window.ClipRect.Max.y)
local size = ImVec2(ImMin(size_x, text_size.x), text_size.y)
window.DC.CursorMaxPos.x = ImMax(window.DC.CursorMaxPos.x, pos.x + text_size.x)
window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, pos.x + text_size.x)
if align_x > 0.0 and text_size.x < size_x then
pos.x = pos.x + ImTrunc((size_x - text_size.x) * align_x)
end
ImGui.RenderTextEllipsis(window.DrawList, pos, pos_max, pos_max.x, text, text_end, text_size)
local backup_max_pos = ImVec2()
ImVec2_Copy(backup_max_pos, window.DC.CursorMaxPos)
ImGui.ItemSize(size)
ImGui.ItemAdd(ImRect(pos, pos + size), 0)
window.DC.CursorMaxPos.x = backup_max_pos.x -- Cancel out extending content size because right-aligned text would otherwise mess it up
if size_x < text_size.x and ImGui.IsItemHovered(bit32.bor(ImGuiHoveredFlags.NoNavOverride, ImGuiHoveredFlags.AllowWhenDisabled, ImGuiHoveredFlags.ForTooltip)) then
ImGui.SetTooltip("%.*s", text_end - 1, text)
end
end
-- Add a label+text combo aligned to other label+value widgets
--- @param label string
--- @param fmt string
--- @param ... any
function ImGui.LabelText(label, fmt, ...)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local g = GImGui
local style = g.Style
local w = ImGui.CalcItemWidth()
local value_text = ImFormatString(fmt, ...)
local value_text_end = #value_text + 1
local value_size = ImGui.CalcTextSize(value_text, value_text_end, false)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local value_bb = ImRect(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2))
local total_bb = ImRect(pos, pos + ImVec2(w + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0), ImMax(value_size.y, label_size.y) + style.FramePadding.y * 2))
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, 0) then
return
end
-- Render
ImGui.RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text, value_text_end, value_size, ImVec2(0.0, 0.0))
if label_size.x > 0.0 then
ImGui.RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
end
end
--- @param fmt string
--- @param ... any
function ImGui.BulletText(fmt, ...)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local g = GImGui
local style = g.Style
local text = ImFormatString(fmt, ...)
local text_end = #text + 1
local label_size = ImGui.CalcTextSize(text, text_end, false)
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 pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
pos.y = pos.y + window.DC.CurrLineTextBaseOffset
ImGui.ItemSize(total_size, 0.0)
local bb = ImRect(pos, pos + total_size)
if not ImGui.ItemAdd(bb, 0) then
return
end
-- Render
local text_col = ImGui.GetColorU32(ImGuiCol.Text)
ImGui.RenderBullet(window.DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5, g.FontSize * 0.5), text_col)
ImGui.RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0), text, 1, text_end, false)
end
----------------------------------------------------------------
-- [SECTION] MAIN: BUTTONS, SCROLLBARS, ...
----------------------------------------------------------------
--- @param bb ImRect
--- @param id ImGuiID
--- @param flags? ImGuiButtonFlags
function ImGui.ButtonBehavior(bb, id, flags)
if flags == nil then flags = 0 end
local g = GImGui
local window = g.CurrentWindow
local item_flags = (g.LastItemData.ID == id) and g.LastItemData.ItemFlags or g.CurrentItemFlags
if bit32.band(flags, ImGuiButtonFlags.AllowOverlap) ~= 0 then
item_flags = bit32.bor(item_flags, ImGuiItemFlags.AllowOverlap)
end
if bit32.band(item_flags, ImGuiItemFlags.NoFocus) ~= 0 then
flags = bit32.bor(flags, ImGuiButtonFlags.NoFocus, ImGuiButtonFlags.NoNavFocus)
end
-- Default only reacts to left mouse button
if bit32.band(flags, ImGuiButtonFlags.MouseButtonMask_) == 0 then
flags = bit32.bor(flags, ImGuiButtonFlags.MouseButtonLeft)
end
-- Default behavior requires click + release inside bounding box
if bit32.band(flags, ImGuiButtonFlags.PressedOnMask_) == 0 then
flags = bit32.bor(flags, (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and ImGuiButtonFlags.PressedOnClick or ImGuiButtonFlags.PressedOnDefault_)
end
local backup_hovered_window = g.HoveredWindow
local flatten_hovered_children = (bit32.band(flags, ImGuiButtonFlags.FlattenChildren) ~= 0) and g.HoveredWindow and g.HoveredWindow.RootWindowDockTree == window.RootWindowDockTree
if flatten_hovered_children then
g.HoveredWindow = window
end
local pressed = false
local hovered = ImGui.ItemHoverable(bb, id, item_flags)
if g.DragDropActive then
if (bit32.band(flags, ImGuiButtonFlags.PressedOnDragDropHold) ~= 0) and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoHoldToOpenOthers) == 0) and ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) then
hovered = true
ImGui.SetHoveredID(id)
if (g.HoveredIdTimer - g.IO.DeltaTime <= DRAGDROP_HOLD_TO_OPEN_TIMER) and (g.HoveredIdTimer >= DRAGDROP_HOLD_TO_OPEN_TIMER) then
pressed = true
g.DragDropHoldJustPressedId = id
ImGui.FocusWindow(window)
end
end
if (g.DragDropAcceptIdPrev == id) and (bit32.band(g.DragDropAcceptFlagsPrev, ImGuiDragDropFlags.AcceptDrawAsHovered) ~= 0) then
hovered = true
end
end
if (flatten_hovered_children) then
g.HoveredWindow = backup_hovered_window
end
local test_owner_id = (bit32.band(flags, ImGuiButtonFlags.NoTestKeyOwner) ~= 0) and ImGuiKeyOwner_Any or id
if hovered then
IM_ASSERT(id ~= 0)
local mouse_button_clicked = -1
local mouse_button_released = -1
for button = 0, 2 do
if bit32.band(flags, bit32.lshift(ImGuiButtonFlags.MouseButtonLeft, button)) ~= 0 then -- Handle ImGuiButtonFlags.MouseButtonRight and ImGuiButtonFlags.MouseButtonMiddle here.
if (ImGui.IsMouseClickedEx(button, ImGuiInputFlags.None, test_owner_id) and mouse_button_clicked == -1) then mouse_button_clicked = button end
if (ImGui.IsMouseReleased(button, test_owner_id) and mouse_button_released == -1) then mouse_button_released = button end
end
end
local mods_ok = (bit32.band(flags, ImGuiButtonFlags.NoKeyModsAllowed) == 0) or (not g.IO.KeyCtrl and not g.IO.KeyShift and not g.IO.KeyAlt)
if mods_ok then
if mouse_button_clicked ~= -1 and g.ActiveId ~= id then
--- @cast mouse_button_clicked ImGuiMouseButton
if bit32.band(flags, ImGuiButtonFlags.NoSetKeyOwner) == 0 then
ImGui.SetKeyOwner(ImGui.MouseButtonToKey(mouse_button_clicked), id)
end
if bit32.band(flags, bit32.bor(ImGuiButtonFlags.PressedOnClickRelease, ImGuiButtonFlags.PressedOnClickReleaseAnywhere)) ~= 0 then
ImGui.SetActiveID(id, window)
g.ActiveIdMouseButton = mouse_button_clicked
if bit32.band(flags, ImGuiButtonFlags.NoNavFocus) == 0 then
ImGui.SetFocusID(id, window)
ImGui.FocusWindow(window)
elseif bit32.band(flags, ImGuiButtonFlags.NoFocus) == 0 then
ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild)
end
end
if (bit32.band(flags, ImGuiButtonFlags.PressedOnClick) ~= 0) or ((bit32.band(flags, ImGuiButtonFlags.PressedOnDoubleClick) ~= 0) and g.IO.MouseClickedCount[mouse_button_clicked] == 2) then
pressed = true
if bit32.band(flags, ImGuiButtonFlags.NoHoldingActiveId) ~= 0 then
ImGui.ClearActiveID()
else
ImGui.SetActiveID(id, window)
end
g.ActiveIdMouseButton = mouse_button_clicked
if bit32.band(flags, ImGuiButtonFlags.NoNavFocus) == 0 then
ImGui.SetFocusID(id, window)
ImGui.FocusWindow(window)
elseif bit32.band(flags, ImGuiButtonFlags.NoFocus) == 0 then
ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild)
end
end
if bit32.band(flags, ImGuiButtonFlags.PressedOnRelease) ~= 0 then
-- FIXME: Traditionally ImGuiButtonFlags.PressedOnRelease never took ActiveId. Adding it in 2026-03-20 since ImGuiButtonFlags_NoHoldingActiveId can always be added.
-- We don't yet perform an explicit ClearActiveID() to reduce scope of change, but this possibility could be investigated.
if bit32.band(flags, ImGuiButtonFlags.NoHoldingActiveId) == 0 then
ImGui.SetActiveID(id, window) -- Hold on ID
end
g.ActiveIdMouseButton = mouse_button_clicked
end
end
if bit32.band(flags, ImGuiButtonFlags.PressedOnRelease) ~= 0 then
if mouse_button_released ~= -1 then
local has_repeated_at_least_once = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay
if not has_repeated_at_least_once then
pressed = true
end
if bit32.band(flags, ImGuiButtonFlags.NoNavFocus) == 0 then
ImGui.SetFocusID(id, window) -- FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why.
end
ImGui.ClearActiveID()
end
end
-- 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
-- Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
if g.ActiveId == id and (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) then
if g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0 and ImGui.IsMouseClickedEx(g.ActiveIdMouseButton, ImGuiInputFlags.Repeat, test_owner_id) then
pressed = true
end
end
end
if pressed and g.IO.ConfigNavCursorVisibleAuto then
g.NavCursorVisible = false
end
end
-- Keyboard/Gamepad navigation handling
-- We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse
if bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then
if g.NavId == id and g.NavCursorVisible and g.NavHighlightItemUnderNav then
if bit32.band(flags, ImGuiButtonFlags.NoHoveredOnFocus) == 0 then
hovered = true
end
end
if g.NavActivateDownId == id then
local nav_activated_by_code = (g.NavActivateId == id)
local nav_activated_by_inputs = (g.NavActivatePressedId == id)
if not nav_activated_by_inputs and bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0 then
-- Avoid pressing multiple keys from triggering excessive amount of repeat events
local key1 = ImGui.GetKeyData(g, ImGuiKey.Space)
local key2 = ImGui.GetKeyData(g, ImGuiKey.Enter)
local key3 = ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate)
local t1 = ImMax(ImMax(key1.DownDuration, key2.DownDuration), key3.DownDuration)
nav_activated_by_inputs = ImGui.CalcTypematicRepeatAmount(t1 - g.IO.DeltaTime, t1, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0
end
if nav_activated_by_code or nav_activated_by_inputs then
-- Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
pressed = true
ImGui.SetActiveID(id, window)
g.ActiveIdSource = g.NavInputSource
if bit32.band(flags, ImGuiButtonFlags.NoNavFocus) == 0 and bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromShortcut) == 0 then
ImGui.SetFocusID(id, window)
end
if bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromShortcut) ~= 0 then
g.ActiveIdFromShortcut = true
end
end
end
end
local held = false
if g.ActiveId == id then
if g.ActiveIdSource == ImGuiInputSource.Mouse then
if g.ActiveIdIsJustActivated then
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min
end
local mouse_button = g.ActiveIdMouseButton
if mouse_button == -1 then
-- Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304).
ImGui.ClearActiveID()
elseif ImGui.IsMouseDown(mouse_button, test_owner_id) then
held = true
else
local release_in = hovered and (bit32.band(flags, ImGuiButtonFlags.PressedOnClickRelease) ~= 0)
local release_anywhere = (bit32.band(flags, ImGuiButtonFlags.PressedOnClickReleaseAnywhere) ~= 0)
if (release_in or release_anywhere) and not g.DragDropActive then
-- Report as pressed when releasing the mouse (this is the most common path)
local is_double_click_release = (bit32.band(flags, ImGuiButtonFlags.PressedOnDoubleClick) ~= 0) and g.IO.MouseReleased[mouse_button] and g.IO.MouseClickedLastCount[mouse_button] == 2
local is_repeating_already = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay
local is_button_avail_or_owned = ImGui.TestKeyOwner(ImGui.MouseButtonToKey(mouse_button), test_owner_id)
if not is_double_click_release and not is_repeating_already and is_button_avail_or_owned then
pressed = true
end
end
ImGui.ClearActiveID()
end
if bit32.band(flags, ImGuiButtonFlags.NoNavFocus) == 0 and g.IO.ConfigNavCursorVisibleAuto then
g.NavCursorVisible = false
end
elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then
-- When activated using Nav, we hold on the ActiveID until activation button is released
if g.NavActivateDownId == id then
held = true -- hovered == true not true as we are already likely hovered on direct activation.
else
ImGui.ClearActiveID()
end
end
if pressed then
g.ActiveIdHasBeenPressedBefore = true
end
end
if g.NavHighlightActivatedId == id and (bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0) then
hovered = true
end
return pressed, hovered, held
end
--- @param label string
--- @param size_arg? ImVec2
--- @param flags? ImGuiButtonFlags
--- @return bool
function ImGui.ButtonEx(label, size_arg, flags)
if size_arg == nil then size_arg = ImVec2(0, 0) end
if flags == nil then flags = 0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local style = g.Style
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local pos = ImVec2() -- Don't modify the cursor!
ImVec2_Copy(pos, window.DC.CursorPos)
if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and style.FramePadding.y < window.DC.CurrLineTextBaseOffset then
pos.y = pos.y + window.DC.CurrLineTextBaseOffset - style.FramePadding.y
end
local size = ImGui.CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0, label_size.y + style.FramePadding.y * 2.0)
local bb = ImRect(pos, pos + size)
ImGui.ItemSize(size, style.FramePadding.y)
if not ImGui.ItemAdd(bb, id) then
return false
end
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, flags)
local col
if held and hovered then
col = ImGui.GetColorU32(ImGuiCol.ButtonActive)
elseif hovered then
col = ImGui.GetColorU32(ImGuiCol.ButtonHovered)
else
col = ImGui.GetColorU32(ImGuiCol.Button)
end
ImGui.RenderNavCursor(bb, id)
ImGui.RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding)
-- if (g.LogEnabled)
-- LogSetNextTextDecoration("[", "]");
ImGui.RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, label_end, label_size, style.ButtonTextAlign, bb)
-- Automatically close popups
--if (pressed && !(flags & ImGuiButtonFlags.DontClosePopups) && (window->Flags & ImGuiWindowFlags.Popup))
-- CloseCurrentPopup();
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
return pressed
end
--- @param label string
--- @param size_arg? ImVec2
--- @return bool
function ImGui.Button(label, size_arg)
return ImGui.ButtonEx(label, size_arg, ImGuiButtonFlags.None)
end
--- @param label string
--- @return bool
function ImGui.SmallButton(label)
local g = GImGui
local backup_padding_y = g.Style.FramePadding.y
g.Style.FramePadding.y = 0.0
local pressed = ImGui.ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags.AlignTextBaseLine)
g.Style.FramePadding.y = backup_padding_y
return pressed
end
--- @param str_id string
--- @param size_arg ImVec2
--- @param flags? ImGuiButtonFlags
function ImGui.InvisibleButton(str_id, size_arg, flags)
if flags == nil then flags = 0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
-- Ensure zero-size fits to contents
local size = ImGui.CalcItemSize(ImVec2(size_arg.x ~= 0.0 and size_arg.x or -FLT_MIN, size_arg.y ~= 0.0 and size_arg.y or -FLT_MIN), 0.0, 0.0)
local id = window:GetID(str_id)
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + size)
ImGui.ItemSize(size)
local item_flags = (bit32.band(flags, ImGuiButtonFlags.EnableNav) ~= 0) and ImGuiItemFlags.None or ImGuiItemFlags.NoNav
if not ImGui.ItemAdd(bb, id, nil, item_flags) then
return false
end
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, flags)
ImGui.RenderNavCursor(bb, id)
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags)
return pressed
end
--- @param str_id string
--- @param dir ImGuiDir
--- @param size ImVec2
--- @param flags? ImGuiButtonFlags
function ImGui.ArrowButtonEx(str_id, dir, size, flags)
if flags == nil then flags = 0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local id = window:GetID(str_id)
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + size)
local default_size = ImGui.GetFrameHeight()
ImGui.ItemSize(size, (size.y >= default_size) and g.Style.FramePadding.y or -1.0)
if not ImGui.ItemAdd(bb, id) then
return false
end
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, flags)
-- Render
local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.ButtonActive or hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)
local text_col = ImGui.GetColorU32(ImGuiCol.Text)
ImGui.RenderNavCursor(bb, id)
ImGui.RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding)
ImGui.RenderArrow(window.DrawList, bb.Min + ImVec2(ImMax(0.0, (size.x - g.FontSize) * 0.5), ImMax(0.0, (size.y - g.FontSize) * 0.5)), text_col, dir)
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags)
return pressed
end
--- @param str_id string
--- @param dir ImGuiDir
function ImGui.ArrowButton(str_id, dir)
local sz = ImGui.GetFrameHeight()
return ImGui.ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags.None)
end
--- @param id ImGuiID
--- @param pos ImVec2
--- @return bool
function ImGui.CloseButton(id, pos)
local g = GImGui
local window = g.CurrentWindow
local bb = ImRect(pos, pos + ImVec2(g.FontSize, g.FontSize))
local bb_interact = ImRect()
ImRect_Copy(bb_interact, bb)
local area_to_visible_ratio = window.OuterRectClipped:GetArea() / bb:GetArea()
if area_to_visible_ratio < 1.5 then
bb_interact:Expand(ImTrunc(bb_interact:GetSize() * -0.25))
end
local is_clipped = not ImGui.ItemAdd(bb_interact, id)
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id)
if is_clipped then
return pressed
end
local bg_col
if held then
bg_col = ImGui.GetColorU32(ImGuiCol.ButtonActive)
else
bg_col = ImGui.GetColorU32(ImGuiCol.ButtonHovered)
end
if hovered then
window.DrawList:AddRectFilled(bb.Min, bb.Max, bg_col)
end
local cross_center = bb:GetCenter() - ImVec2(0.5, 0.5)
local cross_extent = g.FontSize * 0.5 * 0.7071 - 1
local cross_col = ImGui.GetColorU32(ImGuiCol.Text)
local cross_thickness = 1.0 -- FIXME-DPI
window.DrawList:AddLine(cross_center + ImVec2(cross_extent, cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness)
window.DrawList:AddLine(cross_center + ImVec2(cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, cross_extent), cross_col, cross_thickness)
return pressed
end
--- @return bool
function ImGui.CollapseButton(id, pos)
local g = GImGui
local window = g.CurrentWindow
local bb = ImRect(pos, pos + ImVec2(g.FontSize, g.FontSize))
local is_clipped = not ImGui.ItemAdd(bb, id)
local pressed, hovered = ImGui.ButtonBehavior(bb, id)
if hovered then
window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.ButtonHovered))
end
if window.Collapsed then
ImGui.RenderArrow(window.DrawList, bb.Min, ImGui.GetColorU32(ImGuiCol.Text), ImGuiDir.Right, 1)
else
ImGui.RenderArrow(window.DrawList, bb.Min, ImGui.GetColorU32(ImGuiCol.Text), ImGuiDir.Down, 1)
end
return pressed
end
--- @param window ImGuiWindow
--- @param axis ImGuiAxis
--- @return ImGuiID
function ImGui.GetWindowScrollbarID(window, axis)
if axis == ImGuiAxis.X then
return window:GetID("#SCROLLX")
else
return window:GetID("#SCROLLY")
end
end
--- @param window ImGuiWindow
--- @param axis ImGuiAxis
--- @return ImRect
--- @nodiscard
function ImGui.GetWindowScrollbarRect(window, axis)
local g = GImGui
local outer_rect = window:Rect()
local inner_rect = window.InnerRect
-- (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar)
local scrollbar_size = window.ScrollbarSizes[axis == ImGuiAxis.X and ImGuiAxis.Y or ImGuiAxis.X]
IM_ASSERT(scrollbar_size >= 0.0)
local border_size = IM_ROUND(window.WindowBorderSize * 0.5)
local border_top = (bit32.band(window.Flags, ImGuiWindowFlags.MenuBar) ~= 0) and IM_ROUND(g.Style.FrameBorderSize * 0.5) or (bit32.band(window.Flags, ImGuiWindowFlags.NoTitleBar) ~= 0 and border_size or 0)
if axis == ImGuiAxis.X then
return ImRect(inner_rect.Min.x + border_size, ImMax(outer_rect.Min.y + border_size, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x - border_size, outer_rect.Max.y - border_size)
else
return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y + border_top, outer_rect.Max.x - border_size, inner_rect.Max.y - border_size)
end
end
--- @param window ImGuiWindow
--- @param bb ImRect
--- @param threshold float
--- @param axis ImGuiAxis
function ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb, threshold, axis)
local window_rect = window.RootWindow:Rect()
local viewport_rect = window.Viewport:GetMainRect()
if window_rect.Min[axis] == viewport_rect.Min[axis] and bb.Min[axis] > window_rect.Min[axis] and bb.Min[axis] - threshold <= window_rect.Min[axis] then
bb.Min[axis] = window_rect.Min[axis]
end
if window_rect.Max[axis] == viewport_rect.Max[axis] and bb.Max[axis] < window_rect.Max[axis] and bb.Max[axis] + threshold >= window_rect.Max[axis] then
bb.Max[axis] = window_rect.Max[axis]
end
end
--- @param bb_frame ImRect
--- @param id ImGuiID
--- @param axis ImGuiAxis
--- @param p_scroll_v number
--- @param size_visible_v number
--- @param size_contents_v number
--- @param draw_rounding_flags ImDrawFlags
--- @return bool is_held
--- @return number scroll_v # Updated p_scroll_v
function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_contents_v, draw_rounding_flags)
local g = GImGui
local window = g.CurrentWindow
if window.SkipItems then
return false, p_scroll_v
end
local bb_frame_width = bb_frame:GetWidth()
local bb_frame_height = bb_frame:GetHeight()
if bb_frame_width <= 0.0 or bb_frame_height <= 0.0 then
return false, p_scroll_v
end
local alpha = 1.0
if axis == ImGuiAxis.Y and bb_frame_height < bb_frame_width then
alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0, 1.0))
end
if alpha <= 0.0 then
return false, p_scroll_v
end
local style = g.Style
local allow_interaction = (alpha >= 1.0)
local bb = ImRect()
ImRect_Copy(bb, bb_frame)
local padding = IM_TRUNC(ImMin(style.ScrollbarPadding, ImMin(bb_frame_width, bb_frame_height) * 0.5))
bb:Expand(-padding)
-- V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
local scrollbar_size_v
if axis == ImGuiAxis.X then
scrollbar_size_v = bb:GetWidth()
else
scrollbar_size_v = bb:GetHeight()
end
if scrollbar_size_v < 1.0 then
return false, p_scroll_v
end
IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0)
local win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), 1)
local grab_h_minsize = ImMin(bb:GetSize()[axis], style.GrabMinSize)
local grab_h_pixels = ImTrunc(ImClamp(scrollbar_size_v * (size_visible_v / win_size_v), grab_h_minsize, scrollbar_size_v))
local grab_h_norm = grab_h_pixels / scrollbar_size_v
-- As a special thing, we allow scrollbar near the edge of a screen/viewport to be reachable with mouse at the extreme edge (#9276)
local bb_hit = ImRect()
ImRect_Copy(bb_hit, bb_frame)
ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, ImGuiAxis.X + ImGuiAxis.Y - axis) -- swap axis here
ImGui.ItemAdd(bb_frame, id, nil, ImGuiItemFlags.NoNav)
local pressed, hovered, held = ImGui.ButtonBehavior(bb_hit, id, ImGuiButtonFlags.NoNavFocus)
local scroll_max = ImMax(1, size_contents_v - size_visible_v)
local scroll_ratio = ImSaturate(p_scroll_v / scroll_max)
local grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v
if held and allow_interaction and grab_h_norm < 1.0 then
local scrollbar_pos_v = bb.Min[axis]
local mouse_pos_v = g.IO.MousePos[axis]
local clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v)
local held_dir
if clicked_v_norm < grab_v_norm then
held_dir = -1
elseif clicked_v_norm > grab_v_norm + grab_h_norm then
held_dir = 1
else
held_dir = 0
end
if g.ActiveIdIsJustActivated then
local scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false) or g.IO.KeyShift or held_dir == 0
if scroll_to_clicked_location then
g.ScrollbarSeekMode = 0
else
g.ScrollbarSeekMode = held_dir
end
if held_dir == 0 and not g.IO.KeyShift then
g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5
else
g.ScrollbarClickDeltaToGrabCenter = 0.0
end
end
if g.ScrollbarSeekMode == 0 then
scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5) / (1.0 - grab_h_norm))
p_scroll_v = scroll_v_norm * scroll_max
else
if ImGui.IsMouseClickedEx(ImGuiMouseButton.Left, ImGuiInputFlags.Repeat) and held_dir == g.ScrollbarSeekMode then
local page_dir
if g.ScrollbarSeekMode > 0.0 then
page_dir = 1.0
else
page_dir = -1.0
end
p_scroll_v = ImClamp(p_scroll_v + page_dir * size_visible_v, 0, scroll_max)
end
end
scroll_ratio = ImSaturate(p_scroll_v / scroll_max)
grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v
end
local bg_col = ImGui.GetColorU32(ImGuiCol.ScrollbarBg)
local grab_col
if held then
grab_col = ImGui.GetColorU32(ImGuiCol.ScrollbarGrabActive, alpha)
elseif hovered then
grab_col = ImGui.GetColorU32(ImGuiCol.ScrollbarGrabHovered, alpha)
else
grab_col = ImGui.GetColorU32(ImGuiCol.ScrollbarGrab, alpha)
end
window.DrawList:AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window.WindowRounding, draw_rounding_flags)
local grab_rect
if axis == ImGuiAxis.X then
local x1 = ImLerp(bb.Min.x, bb.Max.x, grab_v_norm)
grab_rect = ImRect(x1, bb.Min.y, x1 + grab_h_pixels, bb.Max.y)
else
local y1 = ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)
grab_rect = ImRect(bb.Min.x, y1, bb.Max.x, y1 + grab_h_pixels)
end
window.DrawList:AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding)
return held, p_scroll_v
end
--- @param axis ImGuiAxis
function ImGui.Scrollbar(axis)
local g = GImGui
local window = g.CurrentWindow
local id = ImGui.GetWindowScrollbarID(window, axis)
-- Calculate scrollbar bounding box
local bb = ImGui.GetWindowScrollbarRect(window, axis)
local rounding_corners = ImGui.CalcRoundingFlagsForRectInRect(bb, window:Rect(), g.Style.WindowBorderSize)
local size_visible = window.InnerRect.Max[axis] - window.InnerRect.Min[axis]
local size_contents = window.ContentSize[axis] + window.WindowPadding[axis] * 2.0
local scroll = window.Scroll[axis]
local held
held, scroll = ImGui.ScrollbarEx(bb, id, axis, scroll, size_visible, size_contents, rounding_corners)
window.Scroll[axis] = scroll
end
-- - `uv0` and `uv1` are texture coordinates
--- @param tex_ref ImTextureRef
--- @param image_size ImVec2
--- @param uv0? ImVec2
--- @param uv1? ImVec2
--- @param bg_col? ImVec4
--- @param tint_col? ImVec4
function ImGui.ImageWithBg(tex_ref, image_size, uv0, uv1, bg_col, tint_col)
if uv0 == nil then uv0 = ImVec2(0, 0) end
if uv1 == nil then uv1 = ImVec2(1, 1) end
if bg_col == nil then bg_col = ImVec4(0, 0, 0, 0) end
if tint_col == nil then tint_col = ImVec4(1, 1, 1, 1) end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local g = GImGui
local padding = ImVec2(g.Style.ImageBorderSize, g.Style.ImageBorderSize)
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + image_size + padding * 2.0)
ImGui.ItemSize(bb)
if not ImGui.ItemAdd(bb, 0) then
return
end
-- Render
local rounding = g.Style.ImageRounding
if bg_col.w > 0.0 then
window.DrawList:AddRectFilled(bb.Min + padding, bb.Max - padding, ImGui.GetColorU32(bg_col), rounding)
end
if rounding > 0.0 then
window.DrawList:AddImageRounded(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, ImGui.GetColorU32(tint_col), rounding)
else
window.DrawList:AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, ImGui.GetColorU32(tint_col))
end
if g.Style.ImageBorderSize > 0.0 then
window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.Border), rounding, g.Style.ImageBorderSize, ImDrawFlags.None)
end
end
--- @param tex_ref ImTextureRef
--- @param image_size ImVec2
--- @param uv0? ImVec2
--- @param uv1? ImVec2
function ImGui.Image(tex_ref, image_size, uv0, uv1)
ImGui.ImageWithBg(tex_ref, image_size, uv0, uv1)
end
--- @param id ImGuiID
--- @param tex_ref ImTextureRef
--- @param image_size ImVec2
--- @param uv0 ImVec2
--- @param uv1 ImVec2
--- @param bg_col ImVec4
--- @param tint_col ImVec4
--- @param flags? ImGuiButtonFlags
function ImGui.ImageButtonEx(id, tex_ref, image_size, uv0, uv1, bg_col, tint_col, flags)
if flags == nil then flags = 0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local padding = g.Style.FramePadding
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + image_size + padding * 2.0)
ImGui.ItemSize(bb)
if not ImGui.ItemAdd(bb, id) then
return false
end
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, flags)
-- Render
local col = ImGui.GetColorU32((held and hovered) and ImGuiCol.ButtonActive or hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)
ImGui.RenderNavCursor(bb, id)
ImGui.RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding)
if bg_col.w > 0.0 then
window.DrawList:AddRectFilled(bb.Min + padding, bb.Max - padding, ImGui.GetColorU32(bg_col))
end
local image_rounding = ImMax(g.Style.FrameRounding - ImMax(padding.x, padding.y), g.Style.ImageRounding)
if image_rounding > 0.0 then
window.DrawList:AddImageRounded(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, ImGui.GetColorU32(tint_col), image_rounding)
else
window.DrawList:AddImage(tex_ref, bb.Min + padding, bb.Max - padding, uv0, uv1, ImGui.GetColorU32(tint_col))
end
return pressed
end
-- - ImageButton() adds style.FramePadding*2.0 to provided size. This is in order to facilitate fitting an image in a button.
-- - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. (#8165) -- FIXME: Maybe that's not the best design?
--- @param str_id string
--- @param tex_ref ImTextureRef
--- @param image_size ImVec2
--- @param uv0 ImVec2
--- @param uv1 ImVec2
--- @param bg_col ImVec4
--- @param tint_col ImVec4
function ImGui.ImageButton(str_id, tex_ref, image_size, uv0, uv1, bg_col, tint_col)
local g = GImGui
local window = g.CurrentWindow
if window.SkipItems then
return false
end
return ImGui.ImageButtonEx(window:GetID(str_id), tex_ref, image_size, uv0, uv1, bg_col, tint_col)
end
--- @param label string
--- @param v bool
--- @return bool is_pressed
--- @return bool is_checked # The updated `v` passed in
function ImGui.Checkbox(label, v)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false, v
end
local g = GImGui
local style = g.Style
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local square_sz = ImGui.GetFrameHeight()
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local total_width
if label_size.x > 0.0 then
total_width = square_sz + style.ItemInnerSpacing.x + label_size.x
else
total_width = square_sz
end
local total_bb = ImRect(pos, pos + ImVec2(total_width, label_size.y + style.FramePadding.y * 2.0))
ImGui.ItemSize(total_bb, style.FramePadding.y)
local is_visible = ImGui.ItemAdd(total_bb, id)
local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0)
if not is_visible then
if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(total_bb) then -- Extra layer of "no logic clip" for box-select support
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0))
return false, v
end
end
local checked = v
if is_multi_select then
-- TODO: MultiSelectItemHeader()
end
local pressed, hovered, held = ImGui.ButtonBehavior(total_bb, id)
if is_multi_select then
-- TODO: MultiSelectItemFooter()
elseif pressed then
checked = not checked
end
if v ~= checked then
v = checked
pressed = true
ImGui.MarkItemEdited(id)
end
local check_bb = ImRect(pos, pos + ImVec2(square_sz, square_sz))
local mixed_value = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.MixedValue) ~= 0)
if is_visible then
ImGui.RenderNavCursor(total_bb, id)
local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ((mixed_value or checked) and ImGuiCol.CheckboxSelectedBg or ImGuiCol.FrameBg)))
local check_col = ImGui.GetColorU32(ImGuiCol.CheckMark)
ImGui.RenderFrame(check_bb.Min, check_bb.Max, bg_col, true, style.FrameRounding)
if mixed_value then
-- Undocumented tristate/mixed/indeterminate checkbox (#2644)
-- This may seem awkwardly designed because the aim is to make ImGuiItemFlags.MixedValue supported by all widgets (not just checkbox)
local pad_val = ImMax(1.0, IM_TRUNC(square_sz / 3.6))
local pad = ImVec2(pad_val, pad_val)
window.DrawList:AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding)
elseif v then
local pad = ImMax(1.0, IM_TRUNC(square_sz / 6.0))
ImGui.RenderCheckMark(window.DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0)
end
end
local label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y)
if g.LogEnabled then
-- ImGui.LogRenderedText(label_pos, mixed_value and "[~]" or (v and "[x]" or "[ ]"))
end
if is_visible and label_size.x > 0.0 then
ImGui.RenderText(label_pos, label, 1, label_end, false)
end
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0))
return pressed, v
end
--- @param label string
--- @param flags int
--- @param flags_value int
--- @return bool is_pressed
--- @return int flags_new # Updated `flags`
function ImGui.CheckboxFlags(label, flags, flags_value)
local all_on = bit32.band(flags, flags_value) == flags_value
local any_on = bit32.band(flags, flags_value) ~= 0
local pressed
if not all_on and any_on then
local g = GImGui
g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.MixedValue)
pressed, all_on = ImGui.Checkbox(label, all_on)
else
pressed, all_on = ImGui.Checkbox(label, all_on)
end
if pressed then
if all_on then
flags = bit32.bor(flags, flags_value)
else
flags = bit32.band(flags, bit32.bnot(flags_value))
end
end
return pressed, flags
end
--- @param label string
--- @param active bool
--- @return bool is_pressed
function ImGui.RadioButtonEx(label, active)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local style = g.Style
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local square_sz = ImGui.GetFrameHeight()
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local check_bb = ImRect(pos, pos + ImVec2(square_sz, square_sz))
local total_bb = ImRect(pos, pos + ImVec2(square_sz + (label_size.x > 0.0 and style.ItemInnerSpacing.x + label_size.x or 0.0), label_size.y + style.FramePadding.y * 2.0))
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, id) then
return false
end
local center = check_bb:GetCenter()
center.x = IM_ROUND(center.x)
center.y = IM_ROUND(center.y)
local radius = (square_sz - 1.0) * 0.5
local pressed, hovered, held = ImGui.ButtonBehavior(total_bb, id)
if (pressed) then
ImGui.MarkItemEdited(id)
end
ImGui.RenderNavCursor(total_bb, id)
local num_segment = window.DrawList:_CalcCircleAutoSegmentCount(radius)
local col
if held and hovered then
col = ImGui.GetColorU32(ImGuiCol.FrameBgActive)
else
if hovered then
col = ImGui.GetColorU32(ImGuiCol.FrameBgHovered)
else
col = ImGui.GetColorU32(ImGuiCol.FrameBg)
end
end
window.DrawList:AddCircleFilled(center, radius, col, num_segment)
if active then
local pad = ImMax(1.0, IM_TRUNC(square_sz / 6.0))
window.DrawList:AddCircleFilled(center, radius - pad, ImGui.GetColorU32(ImGuiCol.CheckMark))
end
if style.FrameBorderSize > 0.0 then
window.DrawList:AddCircle(center + ImVec2(1, 1), radius, ImGui.GetColorU32(ImGuiCol.BorderShadow), num_segment, style.FrameBorderSize)
window.DrawList:AddCircle(center, radius, ImGui.GetColorU32(ImGuiCol.Border), num_segment, style.FrameBorderSize)
end
local label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y)
if g.LogEnabled then
-- ImGui.LogRenderedText(label_pos, active and "(x)" or "( )")
end
if label_size.x > 0.0 then
ImGui.RenderText(label_pos, label, 1, label_end, false)
end
return pressed
end
-- `rawequal` is used here to check if v == v_button
--- @param label string
--- @param v any
--- @param v_button any
--- @return bool is_pressed
--- @return any v # Updated v
function ImGui.RadioButton(label, v, v_button)
local pressed = ImGui.RadioButtonEx(label, rawequal(v, v_button))
if pressed then
v = v_button
end
return pressed, v
end
-- size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
--- @param fraction float
--- @param size_arg? ImVec2
--- @param overlay? string
function ImGui.ProgressBar(fraction, size_arg, overlay)
if size_arg == nil then size_arg = ImVec2(-FLT_MIN, 0) end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local g = GImGui
local style = g.Style
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local size = ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0)
local bb = ImRect(pos, pos + size)
ImGui.ItemSize(size, style.FramePadding.y)
if not ImGui.ItemAdd(bb, 0) then
return
end
-- Fraction < 0.0 will display an indeterminate progress bar animation
-- The value must be animated along with time, so e.g. passing '-1.0 * ImGui.GetTime()' as fraction works
local is_indeterminate = (fraction < 0.0)
if not is_indeterminate then
fraction = ImSaturate(fraction)
end
-- Out of courtesy we accept a NaN fraction without crashing
local fill_n0 = 0.0
local fill_n1 = (fraction == fraction) and fraction or 0.0
if is_indeterminate then
local fill_width_n = 0.2
fill_n0 = ImFmod(-fraction, 1.0) * (1.0 + fill_width_n) - fill_width_n
fill_n1 = ImSaturate(fill_n0 + fill_width_n)
fill_n0 = ImSaturate(fill_n0)
end
-- Render
ImGui.RenderFrame(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), true, style.FrameRounding)
bb:Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize))
local fill_x0 = ImLerp(bb.Min.x, bb.Max.x, fill_n0)
local fill_x1 = ImLerp(bb.Min.x, bb.Max.x, fill_n1)
if fill_x0 < fill_x1 then
ImGui.RenderRectFilledInRangeH(window.DrawList, bb, ImGui.GetColorU32(ImGuiCol.PlotHistogram), fill_x0, fill_x1, style.FrameRounding)
end
-- Default displaying the fraction as percentage string, but user can override it
-- Don't display text for indeterminate bars by default
if not is_indeterminate or overlay ~= nil then
if overlay == nil then
overlay = ImFormatString("%.0f%%", fraction * 100 + 0.01)
end
local overlay_size = ImGui.CalcTextSize(overlay, nil)
if overlay_size.x > 0.0 then
local text_x = is_indeterminate and ((bb.Min.x + bb.Max.x - overlay_size.x) * 0.5) or (fill_x1 + style.ItemSpacing.x)
ImGui.RenderTextClipped(ImVec2(ImClamp(text_x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, nil, overlay_size, ImVec2(0.0, 0.5), bb)
end
end
end
function ImGui.Bullet()
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local g = GImGui
local style = g.Style
local line_height = ImMax(ImMin(window.DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), g.FontSize)
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(g.FontSize, line_height))
ImGui.ItemSize(bb)
if not ImGui.ItemAdd(bb, 0) then
ImGui.SameLine(0, style.FramePadding.x * 2)
return
end
-- Render and stay on same line
local text_col = ImGui.GetColorU32(ImGuiCol.Text)
ImGui.RenderBullet(window.DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5, line_height * 0.5), text_col)
ImGui.SameLine(0, style.FramePadding.x * 2.0)
end
--- @param label string
function ImGui.TextLink(label)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset)
local size = ImGui.CalcTextSize(label, label_end, false)
local bb = ImRect(pos, pos + size)
ImGui.ItemSize(size, 0.0)
if not ImGui.ItemAdd(bb, id) then
return false
end
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id)
ImGui.RenderNavCursor(bb, id)
if hovered then
ImGui.SetMouseCursor(ImGuiMouseCursor.Hand)
end
local text_colf = ImVec4()
ImVec4_Copy(text_colf, g.Style.Colors[ImGuiCol.TextLink])
local line_colf = ImVec4()
ImVec4_Copy(line_colf, text_colf)
do
-- FIXME-STYLE: Read comments above. This widget is NOT written in the same style as some earlier widgets,
-- as we are currently experimenting/planning a different styling system.
local h, s, v = ImGui.ColorConvertRGBtoHSV(text_colf.x, text_colf.y, text_colf.z)
if held or hovered then
v = ImSaturate(v + (held and 0.4 or 0.3))
h = ImFmod(h + 0.02, 1.0)
end
text_colf.x, text_colf.y, text_colf.z = ImGui.ColorConvertHSVtoRGB(h, s, v)
v = ImSaturate(v - 0.20)
line_colf.x, line_colf.y, line_colf.z = ImGui.ColorConvertHSVtoRGB(h, s, v)
end
local line_y = bb.Max.y + ImFloor(g.FontBaked.Descent * g.FontBakedScale * 0.20)
window.DrawList:AddLineH(bb.Min.x, bb.Max.x, line_y, ImGui.GetColorU32(line_colf), 1.0 * ImTrunc(g.Style._MainScale)) -- FIXME-DPI
ImGui.PushStyleColor(ImGuiCol.Text, ImGui.GetColorU32(text_colf))
ImGui.RenderText(bb.Min, label, 1, label_end, false)
ImGui.PopStyleColor()
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags)
return pressed
end
--- @param label string
--- @param url string
function ImGui.TextLinkOpenURL(label, url)
local g = GImGui
if url == nil then
url = label
end
local pressed = ImGui.TextLink(label)
if pressed and g.PlatformIO.Platform_OpenInShellFn ~= nil then
g.PlatformIO.Platform_OpenInShellFn(g, url)
end
ImGui.SetItemTooltip(ImGui.LocalizeGetMsg(ImGuiLocKey.OpenLink_s), url)
if ImGui.BeginPopupContextItem() then
if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.CopyLink)) then
ImGui.SetClipboardText(url)
end
ImGui.EndPopup()
end
return pressed
end
----------------------------------------------------------------
-- [SECTION] Low-level Layout helpers
----------------------------------------------------------------
function ImGui.Spacing()
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
ImGui.ItemSize(ImVec2(0, 0))
end
--- @param size ImVec2
function ImGui.Dummy(size)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + size)
ImGui.ItemSize(size)
ImGui.ItemAdd(bb, 0)
end
function ImGui.NewLine()
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local g = GImGui
local backup_layout_type = window.DC.LayoutType
window.DC.LayoutType = ImGuiLayoutType.Vertical
window.DC.IsSameLine = false
if window.DC.CurrLineSize.y > 0.0 then
-- In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
ImGui.ItemSize(ImVec2(0, 0))
else
ImGui.ItemSize(ImVec2(0.0, g.FontSize))
end
window.DC.LayoutType = backup_layout_type
end
function ImGui.AlignTextToFramePadding()
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local g = GImGui
window.DC.CurrLineSize.y = ImMax(window.DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2)
window.DC.CurrLineTextBaseOffset = ImMax(window.DC.CurrLineTextBaseOffset, g.Style.FramePadding.y)
end
--- @param flags ImGuiSeparatorFlags
--- @param thickness float
function ImGui.SeparatorEx(flags, thickness)
if thickness == nil then thickness = 1.0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
local g = GImGui
IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, bit32.bor(ImGuiSeparatorFlags.Horizontal, ImGuiSeparatorFlags.Vertical)))) -- Check that only 1 option is selected
IM_ASSERT(thickness > 0.0)
if bit32.band(flags, ImGuiSeparatorFlags.Vertical) ~= 0 then
-- Vertical separator, for menu bars (use current line height).
local y1 = window.DC.CursorPos.y
local y2 = window.DC.CursorPos.y + window.DC.CurrLineSize.y
local bb = ImRect(ImVec2(window.DC.CursorPos.x, y1), ImVec2(window.DC.CursorPos.x + thickness, y2))
ImGui.ItemSize(ImVec2(thickness, 0.0))
if not ImGui.ItemAdd(bb, 0) then
return
end
-- Draw
window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.Separator))
if g.LogEnabled then
ImGui.LogText(" |")
end
elseif bit32.band(flags, ImGuiSeparatorFlags.Horizontal) ~= 0 then
-- Horizontal Separator
local x1 = window.DC.CursorPos.x
local x2 = window.WorkRect.Max.x
-- Preserve legacy behavior inside Columns()
-- Before Tables API happened, we relied on Separator() to span all columns of a Columns() set.
-- We currently don't need to provide the same feature for tables because tables naturally have border features.
local columns = (bit32.band(flags, ImGuiSeparatorFlags.SpanAllColumns) ~= 0) and window.DC.CurrentColumns or nil
if columns then
x1 = window.Pos.x + window.DC.Indent.x -- Used to be Pos.x before 2023/10/03
x2 = window.Pos.x + window.Size.x
ImGui.PushColumnsBackground()
end
-- We don't provide our width to the layout so that it doesn't get feed back into AutoFit
-- FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell)
local bb = ImRect(ImVec2(x1, window.DC.CursorPos.y), ImVec2(x2, window.DC.CursorPos.y + thickness))
ImGui.ItemSize(ImVec2(0.0, thickness))
if ImGui.ItemAdd(bb, 0) then
-- Draw
window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.Separator))
if g.LogEnabled then
ImGui.LogRenderedText(bb.Min, "--------------------------------")
end
end
if columns then
ImGui.PopColumnsBackground()
columns.LineMinY = window.DC.CursorPos.y
end
end
end
function ImGui.Separator()
local g = GImGui
local window = g.CurrentWindow
if window.SkipItems then
return
end
-- Those flags should eventually be configurable by the user
local flags
if window.DC.LayoutType == ImGuiLayoutType.Horizontal then
flags = ImGuiSeparatorFlags.Vertical
else
flags = ImGuiSeparatorFlags.Horizontal
end
-- Only applies to legacy Columns() api as they relied on Separator() a lot.
if window.DC.CurrentColumns then
flags = bit32.bor(flags, ImGuiSeparatorFlags.SpanAllColumns)
end
ImGui.SeparatorEx(flags, ImMax(g.Style.SeparatorSize, 1.0))
end
--- @param id ImGuiID
--- @param label string
--- @param label_end? int
--- @param extra_w float
function ImGui.SeparatorTextEx(id, label, label_end, extra_w)
local g = GImGui
local window = g.CurrentWindow
local style = g.Style
local label_size = ImGui.CalcTextSize(label, label_end, false)
local pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y)
local padding = style.SeparatorTextPadding
local separator_thickness = style.SeparatorTextBorderSize
local min_size = ImVec2(label_size.x + extra_w + padding.x * 2.0, ImMax(label_size.y + padding.y * 2.0, separator_thickness))
local bb = ImRect(pos, ImVec2(window.WorkRect.Max.x, pos.y + min_size.y))
local text_baseline_y = ImTrunc((bb:GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.999) -- ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f))
ImGui.ItemSize(min_size, text_baseline_y)
if not ImGui.ItemAdd(bb, id) then
return
end
local sep1_x1 = pos.x
local sep2_x2 = bb.Max.x
local seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5 + 0.999)
local label_avail_w = ImMax(0.0, sep2_x2 - sep1_x1 - padding.x * 2.0)
local label_pos = ImVec2(pos.x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y) -- FIXME-ALIGN
-- This allows using SameLine() to position something in the 'extra_w'
window.DC.CursorPosPrevLine.x = label_pos.x + label_size.x
local separator_col = ImGui.GetColorU32(ImGuiCol.Separator)
if label_size.x > 0.0 then
local sep1_x2 = label_pos.x - style.ItemSpacing.x
local sep2_x1 = label_pos.x + label_size.x + extra_w + style.ItemSpacing.x
if sep1_x2 > sep1_x1 and separator_thickness > 0.0 then
window.DrawList:AddLineH(sep1_x1, sep1_x2, seps_y, separator_col, separator_thickness)
end
if sep2_x2 > sep2_x1 and separator_thickness > 0.0 then
window.DrawList:AddLineH(sep2_x1, sep2_x2, seps_y, separator_col, separator_thickness)
end
if g.LogEnabled then
ImGui.LogSetNextTextDecoration("---", nil)
end
ImGui.RenderTextEllipsis(window.DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, label_size)
else
if g.LogEnabled then
ImGui.LogText("---")
end
if separator_thickness > 0.0 then
window.DrawList:AddLineH(sep1_x1, sep2_x2, seps_y, separator_col, separator_thickness)
end
end
end
--- @param label string
function ImGui.SeparatorText(label)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return
end
ImGui.SeparatorTextEx(0, label, ImGui.FindRenderedTextEnd(label), 0.0)
end
----------------------------------------------------------------
-- [SECTION] COMBO BOX
----------------------------------------------------------------
--- @param items_count float
--- @return float
local function CalcMaxPopupHeightFromItemCount(items_count)
local g = GImGui
if items_count <= 0 then
return FLT_MAX
end
return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2)
end
--- @param label string
--- @param preview_value? string
--- @param flags? ImGuiComboFlags
function ImGui.BeginCombo(label, preview_value, flags)
if flags == nil then flags = 0 end
local g = GImGui
local window = ImGui.GetCurrentWindow()
local backup_next_window_data_flags = g.NextWindowData.HasFlags
g.NextWindowData:ClearFlags()
if window.SkipItems then
return false
end
local style = g.Style
local id = window:GetID(label)
IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiComboFlags.NoArrowButton, ImGuiComboFlags.NoPreview)) ~= bit32.bor(ImGuiComboFlags.NoArrowButton, ImGuiComboFlags.NoPreview)) -- Can't use both flags together
if bit32.band(flags, ImGuiComboFlags.WidthFitPreview) ~= 0 then
IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiComboFlags.NoPreview, ImGuiComboFlags.CustomPreview)) == 0)
end
local arrow_size
if (bit32.band(flags, ImGuiComboFlags.NoArrowButton) ~= 0) then
arrow_size = 0.0
else
arrow_size = ImGui.GetFrameHeight()
end
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local preview_width
if ((bit32.band(flags, ImGuiComboFlags.WidthFitPreview) ~= 0) and (preview_value ~= nil)) then
preview_width = ImGui.CalcTextSize(preview_value, nil, false).x
else
preview_width = 0.0
end
local w
if bit32.band(flags, ImGuiComboFlags.NoPreview) ~= 0 then
w = arrow_size
elseif bit32.band(flags, ImGuiComboFlags.WidthFitPreview) ~= 0 then
w = arrow_size + preview_width + style.FramePadding.x * 2.0
else
w = ImGui.CalcItemWidth()
end
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0))
local label_offset = (label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0
local total_bb = ImRect(bb.Min, bb.Max + ImVec2(label_offset, 0.0))
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, id, bb) then
return false
end
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id)
local popup_id = ImHashStr("##ComboPopup", nil, id)
local popup_open = ImGui.IsPopupOpen(popup_id, ImGuiPopupFlags.None)
if pressed and not popup_open then
ImGui.OpenPopupEx(popup_id, ImGuiPopupFlags.None)
popup_open = true
end
-- Render shape
local frame_col = ImGui.GetColorU32(hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg)
local value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size)
ImGui.RenderNavCursor(bb, id)
if bit32.band(flags, ImGuiComboFlags.NoPreview) == 0 then
window.DrawList:AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (bit32.band(flags, ImGuiComboFlags.NoArrowButton) ~= 0) and ImDrawFlags.RoundCornersAll or ImDrawFlags.RoundCornersLeft)
end
if bit32.band(flags, ImGuiComboFlags.NoArrowButton) == 0 then
local bg_col = ImGui.GetColorU32((popup_open or hovered) and ImGuiCol.ButtonHovered or ImGuiCol.Button)
local text_col = ImGui.GetColorU32(ImGuiCol.Text)
window.DrawList:AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) and ImDrawFlags.RoundCornersAll or ImDrawFlags.RoundCornersRight)
if value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x then
ImGui.RenderArrow(window.DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir.Down, 1.0)
end
end
ImGui.RenderFrameBorder(bb.Min, bb.Max, style.FrameRounding)
-- Custom preview
if bit32.band(flags, ImGuiComboFlags.CustomPreview) ~= 0 then
g.ComboPreviewData.PreviewRect = ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y)
IM_ASSERT(preview_value == nil or preview_value == "")
preview_value = nil
end
-- Render preview and label
if preview_value ~= nil and bit32.band(flags, ImGuiComboFlags.NoPreview) == 0 then
if g.LogEnabled then
ImGui.LogSetNextTextDecoration("{", "}")
end
ImGui.RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, nil, nil)
end
if label_size.x > 0 then
ImGui.RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
end
if not popup_open then
return false
end
g.NextWindowData.HasFlags = backup_next_window_data_flags
return ImGui.BeginComboPopup(popup_id, bb, flags)
end
--- @param popup_id ImGuiID
--- @param bb ImRect
--- @param flags ImGuiComboFlags
function ImGui.BeginComboPopup(popup_id, bb, flags)
local g = GImGui
if not ImGui.IsPopupOpen(popup_id, ImGuiPopupFlags.None) then
g.NextWindowData:ClearFlags()
return false
end
local w = bb:GetWidth()
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 then
g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w)
else
if bit32.band(flags, ImGuiComboFlags.HeightMask_) == 0 then
flags = bit32.bor(flags, ImGuiComboFlags.HeightRegular)
end
IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiComboFlags.HeightMask_)))
local popup_max_height_in_items = -1
if bit32.band(flags, ImGuiComboFlags.HeightRegular) ~= 0 then
popup_max_height_in_items = 8
elseif bit32.band(flags, ImGuiComboFlags.HeightSmall) ~= 0 then
popup_max_height_in_items = 4
elseif bit32.band(flags, ImGuiComboFlags.HeightLarge) ~= 0 then
popup_max_height_in_items = 20
end
local constraint_min = ImVec2(0.0, 0.0)
local constraint_max = ImVec2(FLT_MAX, FLT_MAX)
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.x <= 0.0 then
constraint_min.x = w
end
if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.y <= 0.0 then
constraint_max.y = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)
end
ImGui.SetNextWindowSizeConstraints(constraint_min, constraint_max)
end
-- This is essentially a specialized version of BeginPopupEx()
local name = ImFormatString("##Combo_%02d", g.BeginComboDepth)
-- Set position given a custom constraint (peak into expected window size so we can position it)
-- FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function?
-- FIXME: This might be moved to Begin() or at least around the same spot where Tooltips and other Popups are calling FindBestWindowPosForPopupEx()?
local popup_window = ImGui.FindWindowByName(name)
if popup_window then
if popup_window.WasActive then
-- Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us.
local size_expected = ImGui.CalcWindowNextAutoFitSize(popup_window)
popup_window.AutoPosLastDirection = (bit32.band(flags, ImGuiComboFlags.PopupAlignLeft) ~= 0) and ImGuiDir.Left or ImGuiDir.Down
local r_outer = ImGui.GetPopupAllowedExtentRect(popup_window)
local pos
pos, popup_window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(bb:GetBL(), size_expected, popup_window.AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy.ComboBox)
ImGui.SetNextWindowPos(pos)
end
end
-- We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx()
local window_flags = bit32.bor(ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.Popup, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoMove)
ImGui.PushStyleVarX(ImGuiStyleVar.WindowPadding, g.Style.FramePadding.x) -- Horizontally align ourselves with the framed text
local _, ret = ImGui.Begin(name, nil, window_flags)
ImGui.PopStyleVar()
if not ret then
ImGui.EndPopup()
if not g.IO.ConfigDebugBeginReturnValueOnce and not g.IO.ConfigDebugBeginReturnValueLoop then
-- Begin may only return false with those debug tools activated.
IM_ASSERT(false) -- This should never happen as we tested for IsPopupOpen() above
end
return false
end
g.BeginComboDepth = g.BeginComboDepth + 1
return true
end
function ImGui.EndCombo()
local g = GImGui
g.BeginComboDepth = g.BeginComboDepth - 1
local name = ImFormatString("##Combo_%02d", g.BeginComboDepth) -- FIXME: Move those to helpers?
if g.CurrentWindow.Name ~= name then
IM_ASSERT_USER_ERROR_RET(false, "Calling EndCombo() in wrong window!")
end
ImGui.EndPopup()
end
-- Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements
-- (Experimental, see GitHub issues: #1658, #4168)
function ImGui.BeginComboPreview()
local g = GImGui
local window = g.CurrentWindow
local preview_data = g.ComboPreviewData
if window.SkipItems or not (bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0) then
return false
end
IM_ASSERT(g.LastItemData.Rect.Min.x == preview_data.PreviewRect.Min.x and g.LastItemData.Rect.Min.y == preview_data.PreviewRect.Min.y) -- Didn't call after BeginCombo/EndCombo block or forgot to pass ImGuiComboFlags.CustomPreview flag?
if not window.ClipRect:Overlaps(preview_data.PreviewRect) then -- Narrower test (optional)
return false
end
-- FIXME: This could be contained in a PushWorkRect() api
ImVec2_Copy(preview_data.BackupCursorPos, window.DC.CursorPos)
ImVec2_Copy(preview_data.BackupCursorMaxPos, window.DC.CursorMaxPos)
ImVec2_Copy(preview_data.BackupCursorPosPrevLine, window.DC.CursorPosPrevLine)
preview_data.BackupPrevLineTextBaseOffset = window.DC.PrevLineTextBaseOffset
preview_data.BackupLayout = window.DC.LayoutType
ImVec2_Copy(window.DC.CursorPos, preview_data.PreviewRect.Min + g.Style.FramePadding)
ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos)
window.DC.LayoutType = ImGuiLayoutType.Horizontal
window.DC.IsSameLine = false
ImGui.PushClipRect(preview_data.PreviewRect.Min, preview_data.PreviewRect.Max, true)
return true
end
function ImGui.EndComboPreview()
local g = GImGui
local window = g.CurrentWindow
local preview_data = g.ComboPreviewData
local draw_list = window.DrawList
if window.DC.CursorMaxPos.x < preview_data.PreviewRect.Max.x and window.DC.CursorMaxPos.y < preview_data.PreviewRect.Max.y then
if draw_list.CmdBuffer.Size > 1 then -- Unlikely case that the PushClipRect() didn't create a command
ImVec4_Copy(draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ClipRect, draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size - 1].ClipRect)
ImVec4_Copy(draw_list._CmdHeader.ClipRect, draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ClipRect)
draw_list:_TryMergeDrawCmds()
end
end
ImGui.PopClipRect()
ImVec2_Copy(window.DC.CursorPos, preview_data.BackupCursorPos)
ImVec2_Copy(window.DC.CursorMaxPos, ImMax(window.DC.CursorMaxPos, preview_data.BackupCursorMaxPos))
ImVec2_Copy(window.DC.CursorPosPrevLine, preview_data.BackupCursorPosPrevLine)
window.DC.PrevLineTextBaseOffset = preview_data.BackupPrevLineTextBaseOffset
window.DC.LayoutType = preview_data.BackupLayout
window.DC.IsSameLine = false
preview_data.PreviewRect = ImRect()
end
----------------------------------------------------------------
-- [SECTION] DATA TYPE & DATA FORMATTING [Internal]
----------------------------------------------------------------
local function float(val) return val end
local function double(val) return val end
local GDefaultRgbaColorMarkers = {
IM_COL32(240, 20, 20, 255), IM_COL32(20, 240, 20, 255), IM_COL32(20, 20, 240, 255), IM_COL32(140, 140, 140, 255)
}
--- @param size size_t
--- @param name string
--- @param print_fmt string
--- @param scan_fmt string
--- @return ImGuiDataTypeInfo
--- @nodiscard
--- @package
local function ImGuiDataTypeInfo(size, name, print_fmt, scan_fmt)
return { Size = size, Name = name, PrintFmt = print_fmt, ScanFmt = scan_fmt }
end
local GDataTypeInfo = {
ImGuiDataTypeInfo(1, "S8", "%d", "%d"),
ImGuiDataTypeInfo(1, "U8", "%u", "%u"),
ImGuiDataTypeInfo(2, "S16", "%d", "%d"),
ImGuiDataTypeInfo(2, "U16", "%u", "%u"),
ImGuiDataTypeInfo(4, "S32", "%d", "%d"),
ImGuiDataTypeInfo(4, "U32", "%u", "%u"),
ImGuiDataTypeInfo(4, "float", "%.3f", "%f"),
ImGuiDataTypeInfo(8, "double", "%f", "%lf"),
ImGuiDataTypeInfo(1, "bool", "%d", "%d"),
ImGuiDataTypeInfo(0, "string", "%s", "%s")
}
--- @param data_type ImGuiDataType
function ImGui.DataTypeGetInfo(data_type)
IM_ASSERT(data_type >= 0 and data_type < ImGuiDataType.COUNT)
return GDataTypeInfo[data_type + 1]
end
--- @param buf char[]
--- @param buf_size int
--- @param data_type ImGuiDataType
--- @param data number
--- @param format string
function ImGui.DataTypeFormatString(buf, buf_size, data_type, data, format)
local str
if data_type == ImGuiDataType.S32 then
str = ImFormatString(format, (ImS32)(data))
elseif data_type == ImGuiDataType.U32 then
str = ImFormatString(format, (ImU32)(data))
elseif data_type == ImGuiDataType.Float then
str = ImFormatString(format, data)
elseif data_type == ImGuiDataType.Double then
str = ImFormatString(format, data)
elseif data_type == ImGuiDataType.S8 then
str = ImFormatString(format, (ImS8)(data))
elseif data_type == ImGuiDataType.U8 then
str = ImFormatString(format, (ImU8)(data))
elseif data_type == ImGuiDataType.S16 then
str = ImFormatString(format, (ImS16)(data))
elseif data_type == ImGuiDataType.U16 then
str = ImFormatString(format, (ImU16)(data))
else
IM_ASSERT(false)
end
ImStd.ImStrncpy(buf, 1, { string.byte(str, 1, #str) }, 1, ImMin(#str + 1, buf_size)) -- TODO: update this when new ImFormatString is implemented
end
--- @param data_type ImGuiDataType
--- @param op int
--- @param arg1 number
--- @param arg2 number
function ImGui.DataTypeApplyOp(data_type, op, arg1, arg2)
IM_ASSERT(op == 43 or op == 45) -- '+' or '-'
if data_type == ImGuiDataType.S8 then
if op == 43 then
return ImAddClampOverflow(arg1, arg2, IM_S8_MIN, IM_S8_MAX)
elseif op == 45 then
return ImSubClampOverflow(arg1, arg2, IM_S8_MIN, IM_S8_MAX)
end
elseif data_type == ImGuiDataType.U8 then
if op == 43 then
return ImAddClampOverflow(arg1, arg2, IM_U8_MIN, IM_U8_MAX)
elseif op == 45 then
return ImSubClampOverflow(arg1, arg2, IM_U8_MIN, IM_U8_MAX)
end
elseif data_type == ImGuiDataType.S16 then
if op == 43 then
return ImAddClampOverflow((ImS16)(arg1), (ImS16)(arg2), IM_S16_MIN, IM_S16_MAX)
elseif op == 45 then
return ImSubClampOverflow((ImS16)(arg1), (ImS16)(arg2), IM_S16_MIN, IM_S16_MAX)
end
elseif data_type == ImGuiDataType.U16 then
if op == 43 then
return ImAddClampOverflow((ImU16)(arg1), (ImU16)(arg2), IM_U16_MIN, IM_U16_MAX)
elseif op == 45 then
return ImSubClampOverflow((ImU16)(arg1), (ImU16)(arg2), IM_U16_MIN, IM_U16_MAX)
end
elseif data_type == ImGuiDataType.S32 then
if op == 43 then
return ImAddClampOverflow(arg1, arg2, IM_S32_MIN, IM_S32_MAX)
elseif op == 45 then
return ImSubClampOverflow(arg1, arg2, IM_S32_MIN, IM_S32_MAX)
end
elseif data_type == ImGuiDataType.U32 then
if op == 43 then
return ImAddClampOverflow(arg1, arg2, IM_U32_MIN, IM_U32_MAX)
elseif op == 45 then
return ImSubClampOverflow(arg1, arg2, IM_U32_MIN, IM_U32_MAX)
end
elseif data_type == ImGuiDataType.Float then
if op == 43 then
return arg1 + arg2
elseif op == 45 then
return arg1 - arg2
end
elseif data_type == ImGuiDataType.Double then
if op == 43 then
return arg1 + arg2
elseif op == 45 then
return arg1 - arg2
end
end
IM_ASSERT(false)
end
local ImParseFormatSanitizeForScanning
--- @param buf char[]
--- @param data_type ImGuiDataType
--- @param data number
--- @param format string
--- @param data_when_empty? number
function ImGui.DataTypeApplyFromText(buf, data_type, data, format, data_when_empty)
local type_info = ImGui.DataTypeGetInfo(data_type)
local data_backup = data
local p = 1
while ImCharIsBlankA(buf[p]) do
p = p + 1
end
if buf[p] == 0 then
if data_when_empty ~= nil then
data = data_when_empty
return data, data_backup ~= data
end
return data, false
end
local format_sanitized, format_sanitized_size = {}, 32
if (data_type == ImGuiDataType.Float or data_type == ImGuiDataType.Double) then
format = type_info.ScanFmt
else
format = ImParseFormatSanitizeForScanning(format, format_sanitized, format_sanitized_size)
if format[1] == 0 then
format = type_info.ScanFmt
end
end
local v32 = 0
local res = {}
if ImStd.sscanf(buf, 1, format, res) < 1 then
return data, false
end
if type_info.Size >= 4 then
data = res[1]
else
v32 = res[1]
end
if type_info.Size < 4 then
if data_type == ImGuiDataType.S8 then
data = (ImS8)(ImClamp(v32, IM_S8_MIN, IM_S8_MAX))
elseif data_type == ImGuiDataType.U8 then
data = (ImU8)(ImClamp(v32, IM_U8_MIN, IM_U8_MAX))
elseif data_type == ImGuiDataType.S16 then
data = (ImS16)(ImClamp(v32, IM_S16_MIN, IM_S16_MAX))
elseif data_type == ImGuiDataType.U16 then
data = (ImU16)(ImClamp(v32, IM_U16_MIN, IM_U16_MAX))
else
IM_ASSERT(false)
end
end
return data, data_backup ~= data
end
--- @generic T : number
--- @param lhs T
--- @param rhs T
local function DataTypeCompareT(lhs, rhs)
if lhs < rhs then return -1 end
if lhs > rhs then return 1 end
return 0
end
--- @param data_type ImGuiDataType
--- @param arg1 number
--- @param arg2 number
function ImGui.DataTypeCompare(data_type, arg1, arg2)
if data_type == ImGuiDataType.S8 then return DataTypeCompareT((ImS8)(arg1), (ImS8)(arg2))
elseif data_type == ImGuiDataType.U8 then return DataTypeCompareT((ImU8)(arg1), (ImU8)(arg2))
elseif data_type == ImGuiDataType.S16 then return DataTypeCompareT((ImS16)(arg1), (ImS16)(arg2))
elseif data_type == ImGuiDataType.U16 then return DataTypeCompareT((ImU16)(arg1), (ImU16)(arg2))
elseif data_type == ImGuiDataType.S32 then return DataTypeCompareT((ImS32)(arg1), (ImS32)(arg2))
elseif data_type == ImGuiDataType.U32 then return DataTypeCompareT((ImU32)(arg1), (ImU32)(arg2))
elseif data_type == ImGuiDataType.Float then return DataTypeCompareT(arg1, arg2)
elseif data_type == ImGuiDataType.Double then return DataTypeCompareT(arg1, arg2)
end
IM_ASSERT(false)
return 0
end
--- @generic T : number
--- @param v T
--- @param v_min? T
--- @param v_max? T
--- @return T, boolean
local function DataTypeClampT(v, v_min, v_max)
if v_min and v < v_min then return v_min, true end
if v_max and v > v_max then return v_max, true end
return v, false
end
--- @param data_type ImGuiDataType
--- @param data number
--- @param min? number
--- @param max? number
function ImGui.DataTypeClamp(data_type, data, min, max)
if data_type == ImGuiDataType.S8 then return DataTypeClampT((ImS8)(data), min and (ImS8)(min), max and (ImS8)(max))
elseif data_type == ImGuiDataType.U8 then return DataTypeClampT((ImU8)(data), min and (ImU8)(min), max and (ImU8)(max))
elseif data_type == ImGuiDataType.S16 then return DataTypeClampT((ImS16)(data), min and (ImS16)(min), max and (ImS16)(max))
elseif data_type == ImGuiDataType.U16 then return DataTypeClampT((ImU16)(data), min and (ImU16)(min), max and (ImU16)(max))
elseif data_type == ImGuiDataType.S32 then return DataTypeClampT((ImS32)(data), min and (ImS32)(min), max and (ImS32)(max))
elseif data_type == ImGuiDataType.U32 then return DataTypeClampT((ImU32)(data), min and (ImU32)(min), max and (ImU32)(max))
elseif data_type == ImGuiDataType.Float then return DataTypeClampT(data, min, max)
elseif data_type == ImGuiDataType.Double then return DataTypeClampT(data, min, max)
end
IM_ASSERT(false)
return data, false
end
--- @param data_type ImGuiDataType
--- @param data number
function ImGui.DataTypeIsZero(data_type, data)
local g = GImGui
return ImGui.DataTypeCompare(data_type, data, g.DataTypeZeroValue) == 0
end
local GetMinimumStepAtDecimalPrecision do
local min_steps = { 1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001, 0.000000001 }
--- @param decimal_precision int
--- @return float
function GetMinimumStepAtDecimalPrecision(decimal_precision)
if decimal_precision < 0 then
return FLT_MIN
end
if decimal_precision < #min_steps then
return min_steps[decimal_precision + 1]
else
return ImPow(10.0, -decimal_precision)
end
end
end
local ImParseFormatFindStart
--- @param format string
--- @param data_type ImGuiDataType
--- @param v number
function ImGui.RoundScalarWithFormatT(format, data_type, v)
-- IM_UNUSED(data_type)
IM_ASSERT(data_type == ImGuiDataType.Float or data_type == ImGuiDataType.Double)
local fmt_start = ImParseFormatFindStart(format)
if string.byte(format, fmt_start) ~= 37 or string.byte(format, fmt_start + 1) == 37 then
return v -- Don't apply if the value is not visible in the format string
end
-- TODO: Sanitize format
local str = ImFormatString(format, v)
v = ImAtof(str) or v
return v
end
----------------------------------------------------------------
-- [SECTION] INPUTXXX
----------------------------------------------------------------
--- @param fmt string
function ImParseFormatFindStart(fmt)
local len = #fmt
local i = 1
local c
while i < len do
c = string.byte(fmt, i)
if c == 37 and string.byte(fmt, i + 1) ~= 37 then -- '%'
return i
elseif c == 37 then
i = i + 1
end
i = i + 1
end
return nil
end
--- @param fmt string
--- @param pos int
local function ImParseFormatFindEnd(fmt, pos)
-- Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format
if string.byte(fmt, pos) ~= 37 then -- '%'
return pos
end
local ignored_uppercase_mask = bit32.bor(bit32.lshift(1, 73 - 65), bit32.lshift(1, 76 - 65))
local ignored_lowercase_mask = bit32.bor(bit32.lshift(1, 104 - 97), bit32.lshift(1, 106 - 97), bit32.lshift(1, 108 - 97), bit32.lshift(1, 116 - 97), bit32.lshift(1, 119 - 97), bit32.lshift(1, 122 - 97))
local len = #fmt
local c
for i = pos, len do
c = string.byte(fmt, i)
if c >= 65 and c <= 90 and (bit32.band(bit32.lshift(1, c - 65), ignored_uppercase_mask) == 0) then
return i + 1
end
if c >= 97 and c <= 122 and (bit32.band(bit32.lshift(1, c - 97), ignored_lowercase_mask) == 0) then
return i + 1
end
end
return len + 1
end
-- TODO: temporary patch. does not look good
--- @param fmt string
local function ImParseFormatTrimDecorations(fmt)
local fmt_start = ImParseFormatFindStart(fmt)
if string.byte(fmt, fmt_start) ~= 37 then -- '%'
return ""
end
--- @cast fmt_start int
local fmt_end = ImParseFormatFindEnd(fmt, fmt_start)
if string.byte(fmt, fmt_end) ~= 37 then
return string.sub(fmt, fmt_start)
end
return string.sub(fmt, fmt_start, fmt_end)
end
--- @param fmt_in string
--- @param fmt_out char[]
--- @param fmt_out_size size_t
function ImParseFormatSanitizeForScanning(fmt_in, fmt_out, fmt_out_size)
local fmt_end = ImParseFormatFindEnd(fmt_in, 1)
-- IM_UNUSED(fmt_out_size)
IM_ASSERT(fmt_end < fmt_out_size)
local has_type = false
local fmt_in_begin = 1
local fmt_out_begin = 1
while fmt_in_begin < fmt_end do
repeat
local c = string.byte(fmt_in, fmt_in_begin, fmt_in_begin)
fmt_in_begin = fmt_in_begin + 1
if (not has_type and ((c >= 48 and c <= 57) or c == 46 or c == 43 or c == 35)) then
break
end
has_type = has_type or ((c >= 97 and c <= 122) or (c >= 65 and c <= 90))
if c ~= 39 and c ~= 36 and c ~= 95 then
fmt_out[fmt_out_begin] = c
fmt_out_begin = fmt_out_begin + 1
end
until true
end
-- fmt_out[fmt_out_begin] = 0
return string.char(unpack(fmt_out)) -- FIXME: not ideal
end
--- @param str string
--- @param pos int
local function ImAtoi(str, pos)
local negative = false
if string.byte(str, pos) == 45 then -- '-'
negative = true
pos = pos + 1
end
if string.byte(str, pos) == 43 then -- '+'
pos = pos + 1
end
local len = #str
local v = 0
local c = string.byte(str, pos)
while c >= 48 and c <= 57 do
v = v * 10 + c - 48
pos = pos + 1
c = string.byte(str, pos)
if pos > len then break end
end
return negative and -v or v, pos
end
--- @param fmt string
--- @param default_precision int
local function ImParseFormatPrecision(fmt, default_precision)
local pos = ImParseFormatFindStart(fmt)
if not pos then
return default_precision
end
pos = pos + 1
local len = #fmt
local c = string.byte(fmt, pos)
while c >= 48 and c <= 57 do
pos = pos + 1
c = string.byte(fmt, pos)
if pos > len then break end
end
local precision = INT_MAX
if c == 46 then -- '.'
precision, pos = ImAtoi(fmt, pos + 1)
if precision < 0 or precision > 99 then
precision = default_precision
end
end
c = string.byte(fmt, pos)
if c == 101 or c == 69 then -- Maximum precision with scientific notation
precision = -1
end
if (c == 103 or c == 71) and precision == INT_MAX then
precision = -1
end
return (precision == INT_MAX) and default_precision or precision
end
--- @param bb ImRect
--- @param id ImGuiID
--- @param label string
--- @param buf char[]
--- @param buf_size int
--- @param flags? ImGuiInputTextFlags
--- @param callback? ImGuiInputTextCallback
--- @param user_data any
function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user_data)
if flags == nil then flags = 0 end
local g = GImGui
local window = g.CurrentWindow
local is_deactivated = (g.InputTextDeactivatedState.ID == id)
local is_active = (g.TempInputId == id)
if (not is_active and not is_deactivated) then
ImGui.ClearActiveID()
end
local backup_pos = ImVec2()
ImVec2_Copy(backup_pos, window.DC.CursorPos)
ImVec2_Copy(window.DC.CursorPos, bb.Min)
g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowDuplicateId)
local value_changed = ImGui.InputTextEx(label, nil, buf, buf_size, bb:GetSize(), bit32.bor(flags, ImGuiInputTextFlags.TempInput, ImGuiInputTextFlags.AutoSelectAll), callback, user_data)
ImGui.KeepAliveID(id)
if (not is_active and not is_deactivated) then
IM_ASSERT(g.ActiveId == id)
g.TempInputId = g.ActiveId
end
if is_active and g.ActiveId ~= id then
g.TempInputId = 0
end
ImVec2_Copy(window.DC.CursorPos, backup_pos)
return value_changed
end
--- @param bb ImRect
--- @param id ImGuiID
--- @param label string
--- @param data_type ImGuiDataType
--- @param data number
--- @param format string
--- @param clamp_min? number
--- @param clamp_max? number
function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min, clamp_max)
local g = GImGui
local type_info = ImGui.DataTypeGetInfo(data_type)
local data_buf, data_buf_size = {}, 32
format = ImParseFormatTrimDecorations(format)
if format == "" then
format = type_info.PrintFmt
end
ImGui.DataTypeFormatString(data_buf, data_buf_size, data_type, data, format)
ImStd.ImStrTrimBlanks(data_buf)
local flags = bit32.bor(ImGuiInputTextFlags.AutoSelectAll, ImGuiInputTextFlags.LocalizeDecimalPoint)
g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited)
g.LastItemData.ItemFlags = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0) and bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputText) or bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.LiveEditOnInputText))
if not ImGui.TempInputText(bb, id, label, data_buf, data_buf_size, flags) then
return data, false
end
local data_backup = data
data = ImGui.DataTypeApplyFromText(data_buf, data_type, data, format, nil)
if clamp_min or clamp_max then
if clamp_min and clamp_max and ImGui.DataTypeCompare(data_type, clamp_min, clamp_max) > 0 then
clamp_min, clamp_max = clamp_max, clamp_min
end
data = ImGui.DataTypeClamp(data_type, data, clamp_min, clamp_max)
end
g.LastItemData.ItemFlags = bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.NoMarkEdited))
local value_changed = data_backup ~= data
if value_changed then
ImGui.MarkItemEdited(id)
end
return data, value_changed
end
--- @param label string
--- @param data_type ImGuiDataType
--- @param data number
--- @param step? number
--- @param step_fast? number
--- @param format? string
--- @param flags? ImGuiInputTextFlags
function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flags)
if flags == nil then flags = 0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return data, false
end
local g = GImGui
local style = g.Style
if format == nil then
format = ImGui.DataTypeGetInfo(data_type).PrintFmt
end
local data_default = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasRefVal) ~= 0) and g.NextItemData.RefVal or g.DataTypeZeroValue
local buf, buf_size = {}, 64 -- TODO: IM_COUNTOF()
if bit32.band(flags, ImGuiInputTextFlags.DisplayEmptyRefVal) ~= 0 and ImGui.DataTypeCompare(data_type, data, data_default) == 0 then
buf[1] = 0
else
ImGui.DataTypeFormatString(buf, buf_size, data_type, data, format)
end
g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoMarkEdited)
flags = bit32.bor(flags, ImGuiInputTextFlags.AutoSelectAll, ImGuiInputTextFlags.LocalizeDecimalPoint)
local has_step_buttons = (step ~= nil)
local button_size = has_step_buttons and ImGui.GetFrameHeight() or 0.0
local ret
if has_step_buttons then
ImGui.BeginGroup()
ImGui.PushID(label)
ImGui.SetNextItemWidth(ImMax(1.0, ImGui.CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2))
ret = ImGui.InputText("", buf, buf_size, flags)
-- IMGUI_TEST_ENGINE_ITEM_INFO()
else
ret = ImGui.InputText(label, buf, buf_size, flags)
end
local value_changed = false
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0 then
local input_edited = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) ~= 0
if input_edited then
data, value_changed = ImGui.DataTypeApplyFromText(buf, data_type, data, format, bit32.band(flags, ImGuiInputTextFlags.ParseEmptyRefVal) ~= 0 and data_default or nil)
end
else
-- g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_Edited
if (g.DeactivatedItemData.ID == g.LastItemData.ID) then
-- g.DeactivatedItemData.HasBeenEditedBefore = false; // Will be set below by MarkItemEdited()
-- if (IsItemDeactivated()) // Should be unnecessary
data, value_changed = ImGui.DataTypeApplyFromText(buf, data_type, data, format, bit32.band(flags, ImGuiInputTextFlags.ParseEmptyRefVal) ~= 0 and data_default or nil)
end
end
if has_step_buttons then
local backup_frame_padding = ImVec2()
ImVec2_Copy(backup_frame_padding, style.FramePadding)
style.FramePadding.x = style.FramePadding.y
if bit32.band(flags, ImGuiInputTextFlags.ReadOnly) ~= 0 then
ImGui.BeginDisabled()
end
ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true)
ImGui.SameLine(0, style.ItemInnerSpacing.x)
--- @cast step number
if ImGui.ButtonEx("-", ImVec2(button_size, button_size)) then
data = ImGui.DataTypeApplyOp(data_type, 45, data, ((g.IO.KeyCtrl and step_fast) and step_fast or step))
value_changed = true
ret = true
end
ImGui.SameLine(0, style.ItemInnerSpacing.x)
if ImGui.ButtonEx("+", ImVec2(button_size, button_size)) then
data = ImGui.DataTypeApplyOp(data_type, 43, data, ((g.IO.KeyCtrl and step_fast) and step_fast or step))
value_changed = true
ret = true
end
ImGui.PopItemFlag()
if bit32.band(flags, ImGuiInputTextFlags.ReadOnly) ~= 0 then
ImGui.EndDisabled()
end
local label_end = ImGui.FindRenderedTextEnd(label)
if label_end ~= 1 then
ImGui.SameLine(0, style.ItemInnerSpacing.x)
ImGui.TextEx(label, label_end)
end
ImVec2_Copy(style.FramePadding, backup_frame_padding)
ImGui.PopID()
ImGui.EndGroup()
end
g.LastItemData.ItemFlags = bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.NoMarkEdited))
if value_changed then
ImGui.MarkItemEdited(g.LastItemData.ID)
end
if bit32.band(flags, ImGuiInputTextFlags.EnterReturnsTrue) ~= 0 then
return data, ret
end
return data, value_changed
end
--- @param label string
--- @param data_type ImGuiDataType
--- @param data number[]
--- @param components int
--- @param step? number
--- @param step_fast? number
--- @param format? string
--- @param flags? ImGuiInputTextFlags
function ImGui.InputScalarN(label, data_type, data, components, step, step_fast, format, flags)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local value_changed = false
ImGui.BeginGroup()
ImGui.PushID(label)
ImGui.PushMultiItemsWidths(components, ImGui.CalcItemWidth())
for i = 1, components do
ImGui.PushID(i - 1)
if i > 1 then
ImGui.SameLine(0, g.Style.ItemInnerSpacing.x)
end
local changed
data[i], changed = ImGui.InputScalar("", data_type, data[i], step, step_fast, format, flags)
if changed then
value_changed = true
end
ImGui.PopID()
ImGui.PopItemWidth()
end
ImGui.PopID()
local label_end = ImGui.FindRenderedTextEnd(label)
if label_end > 1 then
ImGui.SameLine(0.0, g.Style.ItemInnerSpacing.x)
ImGui.TextEx(label, label_end)
end
ImGui.EndGroup()
return value_changed
end
--- @param label string
--- @param v [float, float, float]
--- @param format? string
--- @param flags? ImGuiInputTextFlags
function ImGui.InputFloat3(label, v, format, flags)
if format == nil then format = "%.3f" end
return ImGui.InputScalarN(label, ImGuiDataType.Float, v, 3, nil, nil, format, flags)
end
--- @param label string
--- @param v int
--- @param step? int
--- @param step_fast? int
--- @param flags? ImGuiInputTextFlags
function ImGui.InputInt(label, v, step, step_fast, flags)
if step == nil then step = 1 end
if step_fast == nil then step_fast = 100 end
if flags == nil then flags = 0 end
local format = (bit32.band(flags, ImGuiInputTextFlags.CharsHexadecimal) ~= 0) and "%08X" or "%d"
return ImGui.InputScalar(label, ImGuiDataType.S32, v, (step > 0) and step or nil, (step_fast > 0) and step_fast or nil, format, flags)
end
--- @param label string
--- @param v float
--- @param step? float
--- @param step_fast? float
--- @param format? string
--- @param flags? ImGuiInputTextFlags
function ImGui.InputFloat(label, v, step, step_fast, format, flags)
if step == nil then step = .0 end
if step_fast == nil then step_fast = .0 end
if format == nil then format = "%.3f" end
return ImGui.InputScalar(label, ImGuiDataType.Float, v, (step > 0.0 and step or nil), (step_fast > 0.0 and step_fast or nil), format, flags)
end
--- @param label string
--- @param v double
--- @param step? double
--- @param step_fast? double
--- @param format? string
--- @param flags? ImGuiInputTextFlags
function ImGui.InputDouble(label, v, step, step_fast, format, flags)
if step == nil then step = .0 end
if step_fast == nil then step_fast = .0 end
if format == nil then format = "%.6f" end
return ImGui.InputScalar(label, ImGuiDataType.Double, v, (step > 0.0 and step or nil), (step_fast > 0.0 and step_fast or nil), format, flags)
end
----------------------------------------------------------------
-- [SECTION] DRAGXXX
----------------------------------------------------------------
-- This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)
--- @generic T : number
--- @param TYPE fun(val: number): T
--- @param SIGNEDTYPE fun(val: number): T
--- @param data_type ImGuiDataType
--- @param v T
--- @param v_speed float
--- @param v_min T
--- @param v_max T
--- @param format string
--- @param flags ImGuiSliderFlags
--- @return T new_v # Updated `v`
--- @return bool changed
function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_max, format, flags)
local g = GImGui
local axis = (bit32.band(flags, ImGuiSliderFlags.Vertical) ~= 0) and ImGuiAxis.Y or ImGuiAxis.X
local is_bounded = (v_min < v_max) or ((v_min == v_max) and (v_min ~= 0.0 or (bit32.band(flags, ImGuiSliderFlags.ClampZeroRange) ~= 0)))
local is_wrapped = is_bounded and (bit32.band(flags, ImGuiSliderFlags.WrapAround) ~= 0)
local is_logarithmic = bit32.band(flags, ImGuiSliderFlags.Logarithmic) ~= 0
local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double)
-- Default tweak speed
if v_speed == 0.0 and is_bounded and (v_max - v_min < math.huge) then
v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio
end
-- Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings
local adjust_delta = 0.0
if g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMousePosValid() and ImGui.IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR) then
adjust_delta = g.IO.MouseDelta[axis]
if g.IO.KeyAlt and bit32.band(flags, ImGuiSliderFlags.NoSpeedTweaks) == 0 then
adjust_delta = adjust_delta / 100.0
end
if g.IO.KeyShift and bit32.band(flags, ImGuiSliderFlags.NoSpeedTweaks) == 0 then
adjust_delta = adjust_delta * 10.0
end
elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then
local decimal_precision
if is_floating_point then
decimal_precision = ImParseFormatPrecision(format, 3)
else
decimal_precision = 0
end
local slow_key = (g.NavInputSource == ImGuiInputSource.Gamepad) and ImGuiKey.NavGamepadTweakSlow or ImGuiKey.NavKeyboardTweakSlow
local fast_key = (g.NavInputSource == ImGuiInputSource.Gamepad) and ImGuiKey.NavGamepadTweakFast or ImGuiKey.NavKeyboardTweakFast
local tweak_factor
if bit32.band(flags, ImGuiSliderFlags.NoSpeedTweaks) ~= 0 then
tweak_factor = 1.0
elseif ImGui.IsKeyDown(slow_key) then
tweak_factor = 1.0 / 10.0
elseif ImGui.IsKeyDown(fast_key) then
tweak_factor = 10.0
else
tweak_factor = 1.0
end
adjust_delta = ImGui.GetNavTweakPressedAmount(axis) * tweak_factor
v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision))
end
adjust_delta = adjust_delta * v_speed
-- For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter
if axis == ImGuiAxis.Y then
adjust_delta = -adjust_delta
end
-- For logarithmic use our range is effectively 0..1 so scale the delta into that range
if is_logarithmic and (v_max - v_min < FLT_MAX) and (v_max - v_min > 0.000001) then -- Epsilon to avoid /0
adjust_delta = adjust_delta / (v_max - v_min)
end
-- Clear current value on activation
-- Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300.
local is_just_activated = g.ActiveIdIsJustActivated
local is_already_past_limits_and_pushing_outward = is_bounded and not is_wrapped and ((v >= v_max and adjust_delta > 0.0) or (v <= v_min and adjust_delta < 0.0))
if is_just_activated or is_already_past_limits_and_pushing_outward then
g.DragCurrentAccum = 0.0
g.DragCurrentAccumDirty = false
elseif adjust_delta ~= 0.0 then
g.DragCurrentAccum = g.DragCurrentAccum + adjust_delta
g.DragCurrentAccumDirty = true
end
if not g.DragCurrentAccumDirty then
return v, false
end
local v_cur = (TYPE)(v)
local v_old_ref_for_accum_remainder = 0.0
local logarithmic_zero_epsilon = 0.0 -- Only valid when is_logarithmic is true
local zero_deadzone_halfsize = 0.0 -- Drag widgets have no deadzone (as it doesn't make sense)
if is_logarithmic then
-- When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound.
local decimal_precision
if is_floating_point then
decimal_precision = ImParseFormatPrecision(format, 3)
else
decimal_precision = 1
end
logarithmic_zero_epsilon = ImPow(0.1, decimal_precision)
-- Convert to parametric space, apply delta, convert back
local v_old_parametric = ImGui.ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
local v_new_parametric = v_old_parametric + g.DragCurrentAccum
v_cur = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, v_new_parametric, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
v_old_ref_for_accum_remainder = v_old_parametric
else
v_cur = (TYPE)(v_cur + (SIGNEDTYPE)(g.DragCurrentAccum))
end
-- Round to user desired precision based on format string
if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then
v_cur = ImGui.RoundScalarWithFormatT(format, data_type, v_cur)
end
-- Preserve remainder after rounding has been applied. This also allow slow tweaking of values
g.DragCurrentAccumDirty = false
if is_logarithmic then
-- Convert to parametric space, apply delta, convert back
local v_new_parametric = ImGui.ScaleRatioFromValueT(data_type, v_cur, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
g.DragCurrentAccum = g.DragCurrentAccum - (v_new_parametric - v_old_ref_for_accum_remainder)
else
g.DragCurrentAccum = g.DragCurrentAccum - ((SIGNEDTYPE)(v_cur) - (SIGNEDTYPE)(v))
end
-- This does nothing
if v_cur == (TYPE)(-0) then
v_cur = (TYPE)(0)
end
if v ~= v_cur and is_bounded then
if is_wrapped then
-- Wrap values
if v_cur < v_min then
v_cur = (TYPE)(v_cur + (TYPE)((TYPE)(v_max - v_min) + (is_floating_point and 0 or 1)))
end
if v_cur > v_max then
v_cur = (TYPE)(v_cur - (TYPE)((TYPE)(v_max - v_min) - (is_floating_point and 0 or 1)))
end
else
-- Clamp values + handle overflow/wrap-around for integer types
if v_cur < v_min or (v_cur > v and adjust_delta < 0.0 and not is_floating_point) then
v_cur = (TYPE)(v_min)
end
if v_cur > v_max or (v_cur < v and adjust_delta > 0.0 and not is_floating_point) then
v_cur = (TYPE)(v_max)
end
end
end
-- Apply result
if v == v_cur then
return v, false
end
v = v_cur
return v, true
end
--- @param id ImGuiID
--- @param data_type ImGuiDataType
--- @param v number
--- @param v_speed float
--- @param min number
--- @param max number
--- @param format string
--- @param flags ImGuiSliderFlags
function ImGui.DragBehavior(id, data_type, v, v_speed, min, max, format, flags)
IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.")
local g = GImGui
if g.ActiveId == id then
if g.ActiveIdSource == ImGuiInputSource.Mouse and not g.IO.MouseDown[0] then
ImGui.ClearActiveID()
elseif (g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad) and g.NavActivatePressedId == id and not g.ActiveIdIsJustActivated then
ImGui.ClearActiveID()
end
end
if g.ActiveId ~= id then
return v, false
end
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.ReadOnly) ~= 0 or bit32.band(flags, ImGuiSliderFlags.ReadOnly) ~= 0 then
return v, false
end
if data_type == ImGuiDataType.S8 then
return ImGui.DragBehaviorT(ImS32, ImS32, ImGuiDataType.S32, v, v_speed, min and min or IM_S8_MIN, max and max or IM_S8_MAX, format, flags)
elseif data_type == ImGuiDataType.U8 then
return ImGui.DragBehaviorT(ImU32, ImS32, ImGuiDataType.U32, v, v_speed, min and min or IM_U8_MIN, max and max or IM_U8_MAX, format, flags)
elseif data_type == ImGuiDataType.S16 then
return ImGui.DragBehaviorT(ImS32, ImS32, ImGuiDataType.S32, v, v_speed, min and min or IM_S16_MIN, max and max or IM_S16_MAX, format, flags)
elseif data_type == ImGuiDataType.U16 then
return ImGui.DragBehaviorT(ImU32, ImS32, ImGuiDataType.U32, v, v_speed, min and min or IM_U16_MIN, max and max or IM_U16_MAX, format, flags)
elseif data_type == ImGuiDataType.S32 then
return ImGui.DragBehaviorT(ImS32, ImS32, data_type, v, v_speed, min and min or IM_S32_MIN, max and max or IM_S32_MAX, format, flags)
elseif data_type == ImGuiDataType.U32 then
return ImGui.DragBehaviorT(ImU32, ImS32, data_type, v, v_speed, min and min or IM_U32_MIN, max and max or IM_U32_MAX, format, flags)
elseif data_type == ImGuiDataType.Float then
return ImGui.DragBehaviorT(float, float, data_type, v, v_speed, min and min or -FLT_MAX, max and max or FLT_MAX, format, flags)
elseif data_type == ImGuiDataType.Double then
return ImGui.DragBehaviorT(double, double, data_type, v, v_speed, min and min or -DBL_MAX, max and max or DBL_MAX, format, flags)
end
IM_ASSERT(false)
return v, false
end
--- @param flags ImGuiSliderFlags
--- @param data_type ImGuiDataType
--- @param min number
--- @param max number
local function TempInputIsClampEnabled(flags, data_type, min, max)
if bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 and (min ~= nil or max ~= nil) then
local clamp_range_dir = 0
if min ~= nil and max ~= nil then
clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max)
end
if min == nil or max == nil or clamp_range_dir < 0 then
return true
end
if clamp_range_dir == 0 then
return ImGui.DataTypeIsZero(data_type, min) and (bit32.band(flags, ImGuiSliderFlags.ClampZeroRange) ~= 0) or true
end
end
return false
end
--- @param label string
--- @param data_type ImGuiDataType
--- @param data number
--- @param v_speed float
--- @param min number
--- @param max number
--- @param format string
--- @param flags ImGuiSliderFlags
function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, flags)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return data, false
end
local g = GImGui
local style = g.Style
local id = window:GetID(label)
local w = ImGui.CalcItemWidth()
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_size = ImGui.CalcTextSize(label, label_end, false)
local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0))
local total_bb = ImRect(frame_bb.Min, frame_bb.Max + ImVec2((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0, 0.0))
local temp_input_allowed = (bit32.band(flags, ImGuiSliderFlags.NoInput) == 0)
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, id, frame_bb, temp_input_allowed and ImGuiItemFlags.Inputable or 0) then
return data, false
end
-- Default format string when passing NULL
if format == nil then
format = ImGui.DataTypeGetInfo(data_type).PrintFmt
end
local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags)
local temp_input_is_active = temp_input_allowed and ImGui.TempInputIsActive(id)
if not temp_input_is_active then
local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id)
local double_clicked = (hovered and g.IO.MouseClickedCount[0] == 2 and ImGui.TestKeyOwner(ImGuiKey.MouseLeft, id))
local make_active = (clicked or double_clicked or g.NavActivateId == id)
if make_active and (clicked or double_clicked) then
ImGui.SetKeyOwner(ImGuiKey.MouseLeft, id)
end
if make_active and temp_input_allowed then
if (clicked and g.IO.KeyCtrl) or double_clicked or (g.NavActivateId == id and bit32.band(g.NavActivateFlags, ImGuiActivateFlags.PreferInput) ~= 0) then
temp_input_is_active = true
end
end
-- (Optional) simple click (without moving) turns Drag into an InputText
if g.IO.ConfigDragClickToInputText and temp_input_allowed and not temp_input_is_active then
if g.ActiveId == id and hovered and g.IO.MouseReleased[0] and not ImGui.IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR) then
g.NavActivateId = id
g.NavActivateFlags = ImGuiActivateFlags.PreferInput
temp_input_is_active = true
end
end
-- Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert)
if make_active then
g.ActiveIdValueOnActivation = data
end
if make_active and not temp_input_is_active then
ImGui.SetActiveID(id, window)
ImGui.SetFocusID(id, window)
ImGui.FocusWindow(window)
g.ActiveIdUsingNavDirMask = bit32.bor(bit32.lshift(1, ImGuiDir.Left), bit32.lshift(1, ImGuiDir.Right))
end
end
if temp_input_is_active then
local clamp_enabled = TempInputIsClampEnabled(flags, data_type, min, max)
return ImGui.TempInputScalar(frame_bb, id, label, data_type, data, format, clamp_enabled and min or nil, clamp_enabled and max or nil)
end
-- Draw frame
local frame_col = ImGui.GetColorU32(g.ActiveId == id and ImGuiCol.FrameBgActive or hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg)
ImGui.RenderNavCursor(frame_bb, id)
ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding)
if color_marker ~= 0 and style.ColorMarkerSize > 0.0 then
ImGui.RenderColorComponentMarker(frame_bb, ImGui.GetColorU32(color_marker, nil, true), style.FrameRounding)
end
ImGui.RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding)
-- Drag behavior
local value_changed
data, value_changed = ImGui.DragBehavior(id, data_type, data, v_speed, min, max, format, flags)
if value_changed then
ImGui.MarkItemEdited(id)
end
-- TODO: ImGui.DataTypeFormatString() should be used here instead of ImFormatString()
-- Display value using user-provided display format so user can add prefix/suffix/decorations to the value
ImGui.RenderTextClipped(frame_bb.Min, frame_bb.Max, ImFormatString(format, data), nil, nil, ImVec2(0.5, 0.5))
if label_size.x > 0.0 then
ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
end
return data, value_changed
end
--- @param label string
--- @param v float
--- @param v_speed? float
--- @param v_min? float
--- @param v_max? float
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.DragFloat(label, v, v_speed, v_min, v_max, format, flags)
if v_speed == nil then v_speed = 1.0 end
if v_min == nil then v_min = 0.0 end
if v_max == nil then v_max = 0.0 end
if format == nil then format = "%.3f" end
if flags == nil then flags = 0 end
return ImGui.DragScalar(label, ImGuiDataType.Float, v, v_speed, v_min, v_max, format, flags)
end
--- @param label string
--- @param v int
--- @param v_speed? float
--- @param v_min? int
--- @param v_max? int
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.DragInt(label, v, v_speed, v_min, v_max, format, flags)
if v_speed == nil then v_speed = 1.0 end
if v_min == nil then v_min = 0 end
if v_max == nil then v_max = 0 end
if format == nil then format = "%d" end
if flags == nil then flags = 0 end
return ImGui.DragScalar(label, ImGuiDataType.S32, v, v_speed, v_min, v_max, format, flags)
end
----------------------------------------------------------------
-- [SECTION] SLIDERXXX
----------------------------------------------------------------
-- Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT)
--- @param data_type ImGuiDataType
--- @param v number
--- @param v_min number
--- @param v_max number
--- @param logarithmic_zero_epsilon float
--- @param zero_deadzone_halfsize float
function ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
if v_min == v_max then
return 0.0
end
-- IM_UNUSED(data_type)
local v_clamped
if v_min < v_max then
v_clamped = ImClamp(v, v_min, v_max)
else
v_clamped = ImClamp(v, v_max, v_min)
end
if logarithmic_zero_epsilon > 0.0 then -- == is_logarithmic from caller
local flipped = v_max < v_min
if flipped then -- Handle the case where the range is backwards
v_min, v_max = v_max, v_min
end
-- Fudge min/max to avoid getting close to log(0)
local v_min_fudged
if ImAbs(v_min) < logarithmic_zero_epsilon then
v_min_fudged = (v_min < 0.0) and -logarithmic_zero_epsilon or logarithmic_zero_epsilon
else
v_min_fudged = v_min
end
local v_max_fudged
if ImAbs(v_max) < logarithmic_zero_epsilon then
v_max_fudged = (v_max < 0.0) and -logarithmic_zero_epsilon or logarithmic_zero_epsilon
else
v_max_fudged = v_max
end
-- Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)
if v_min == 0.0 and v_max < 0.0 then
v_min_fudged = -logarithmic_zero_epsilon
elseif v_max == 0.0 and v_min < 0.0 then
v_max_fudged = -logarithmic_zero_epsilon
end
local result
if v_clamped <= v_min_fudged then
result = 0.0 -- Workaround for values that are in-range but below our fudge
elseif v_clamped >= v_max_fudged then
result = 1.0 -- Workaround for values that are in-range but above our fudge
elseif v_min * v_max < 0.0 then -- Range crosses zero, so split into two portions
local zero_point_center = (-v_min) / (v_max - v_min) -- The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine)
local zero_point_snap_L = zero_point_center - zero_deadzone_halfsize
local zero_point_snap_R = zero_point_center + zero_deadzone_halfsize
if v == 0.0 then
result = zero_point_center -- Special case for exactly zero
elseif v < 0.0 then
result = (1.0 - (ImLog(-v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L
else
result = zero_point_snap_R + ((ImLog(v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0 - zero_point_snap_R))
end
elseif v_min < 0.0 or v_max < 0.0 then -- Entirely negative slider
result = 1.0 - (ImLog(-v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged))
else
result = ImLog(v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged)
end
return flipped and (1.0 - result) or result
else
-- Linear slider
return (v_clamped - v_min) / (v_max - v_min)
end
end
-- Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT)
--- @param TYPE fun(val: number): number
--- @param SIGNEDTYPE fun(val: number): number
--- @param data_type ImGuiDataType
--- @param t float
--- @param v_min number
--- @param v_max number
--- @param logarithmic_zero_epsilon float
--- @param zero_deadzone_halfsize float
function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
-- We special-case the extents because otherwise our logarithmic fudging can lead to "mathematically correct"
-- but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value. Also generally simpler.
if t <= 0.0 or v_min == v_max then
return v_min
end
if t >= 1.0 then
return v_max
end
local result = 0
if logarithmic_zero_epsilon > 0.0 then -- == is_logarithmic from caller
-- Fudge min/max to avoid getting silly results close to zero
local v_min_fudged
if ImAbs(v_min) < logarithmic_zero_epsilon then
v_min_fudged = (v_min < 0.0) and -logarithmic_zero_epsilon or logarithmic_zero_epsilon
else
v_min_fudged = v_min
end
local v_max_fudged
if ImAbs(v_max) < logarithmic_zero_epsilon then
v_max_fudged = (v_max < 0.0) and -logarithmic_zero_epsilon or logarithmic_zero_epsilon
else
v_max_fudged = v_max
end
local flipped = v_max < v_min -- Check if range is "backwards"
if flipped then
v_min_fudged, v_max_fudged = v_max_fudged, v_min_fudged
end
-- Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)
if v_max == 0.0 and v_min < 0.0 then
v_max_fudged = -logarithmic_zero_epsilon
end
local t_with_flip = flipped and (1.0 - t) or t -- t, but flipped if necessary to account for us flipping the range
if v_min * v_max < 0.0 then -- Range crosses zero, so we have to do this in two parts
local zero_point_center = (-ImMin(v_min, v_max)) / ImAbs(v_max - v_min) -- The zero point in parametric space
local zero_point_snap_L = zero_point_center - zero_deadzone_halfsize
local zero_point_snap_R = zero_point_center + zero_deadzone_halfsize
if t_with_flip >= zero_point_snap_L and t_with_flip <= zero_point_snap_R then
result = (TYPE)(0.0) -- Special case to make getting exactly zero possible (the epsilon prevents it otherwise)
elseif t_with_flip < zero_point_center then
result = (TYPE)(-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, 1.0 - (t_with_flip / zero_point_snap_L))))
else
result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (t_with_flip - zero_point_snap_R) / (1.0 - zero_point_snap_R)))
end
elseif v_min < 0.0 or v_max < 0.0 then -- Entirely negative slider
result = (TYPE)(-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, 1.0 - t_with_flip)))
else
result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, t_with_flip))
end
else
-- Linear slider
local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double)
if is_floating_point then
result = ImLerp(v_min, v_max, t)
elseif t < 1.0 then
local v_new_off_f = (SIGNEDTYPE)((v_max - v_min)) * t
result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- LUA: + 0 instead of + ((v_min > v_max) and -0.5 or 0.5)
end
end
return result
end
--- @generic T : number
--- @param TYPE fun(val: number): T
--- @param SIGNEDTYPE fun(val: number): T
--- @param bb ImRect
--- @param id ImGuiID
--- @param data_type ImGuiDataType
--- @param v T
--- @param v_min T
--- @param v_max T
--- @param format string
--- @param flags ImGuiSliderFlags
--- @param out_grab_bb ImRect
--- @return T v # updated `v` passed in
--- @return bool value_changed
function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_max, format, flags, out_grab_bb)
local g = GImGui
local style = g.Style
local axis = (bit32.band(flags, ImGuiSliderFlags.Vertical) ~= 0) and ImGuiAxis.Y or ImGuiAxis.X
local is_logarithmic = bit32.band(flags, ImGuiSliderFlags.Logarithmic) ~= 0
local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double)
local v_range_f = (v_min < v_max) and (v_max - v_min) or (v_min - v_max)
local grab_padding = 2.0
local slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0
local grab_sz = style.GrabMinSize
if not is_floating_point and v_range_f >= 0.0 then
grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize)
end
grab_sz = ImMin(grab_sz, slider_sz)
local slider_usable_sz = slider_sz - grab_sz
local slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5
local slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5
local logarithmic_zero_epsilon = 0.0
local zero_deadzone_halfsize = 0.0
if is_logarithmic then
local decimal_precision = is_floating_point and ImParseFormatPrecision(format, 3) or 1
logarithmic_zero_epsilon = ImPow(0.1, decimal_precision)
zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5) / ImMax(slider_usable_sz, 1.0)
end
local value_changed = false
if g.ActiveId == id then
local set_new_value = false
local clicked_t = 0.0
if g.ActiveIdSource == ImGuiInputSource.Mouse then
if not g.IO.MouseDown[0] then
ImGui.ClearActiveID()
else
local mouse_abs_pos = g.IO.MousePos[axis]
if g.ActiveIdIsJustActivated then
local grab_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
if axis == ImGuiAxis.Y then
grab_t = 1.0 - grab_t
end
local grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t)
local clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5 - 1.0) and (mouse_abs_pos <= grab_pos + grab_sz * 0.5 + 1.0)
g.SliderGrabClickOffset = (clicked_around_grab and is_floating_point) and (mouse_abs_pos - grab_pos) or 0.0
end
if slider_usable_sz > 0.0 then
clicked_t = ImSaturate((mouse_abs_pos - g.SliderGrabClickOffset - slider_usable_pos_min) / slider_usable_sz)
end
if axis == ImGuiAxis.Y then
clicked_t = 1.0 - clicked_t
end
set_new_value = true
end
elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then
if g.ActiveIdIsJustActivated then
g.SliderCurrentAccum = 0.0
g.SliderCurrentAccumDirty = false
end
local input_delta = (axis == ImGuiAxis.X) and ImGui.GetNavTweakPressedAmount(axis) or -ImGui.GetNavTweakPressedAmount(axis)
if input_delta ~= 0.0 then
local tweak_slow = ImGui.IsKeyDown((g.NavInputSource == ImGuiInputSource.Gamepad) and ImGuiKey.NavGamepadTweakSlow or ImGuiKey.NavKeyboardTweakSlow)
local tweak_fast = ImGui.IsKeyDown((g.NavInputSource == ImGuiInputSource.Gamepad) and ImGuiKey.NavGamepadTweakFast or ImGuiKey.NavKeyboardTweakFast)
local decimal_precision = is_floating_point and ImParseFormatPrecision(format, 3) or 0
if decimal_precision > 0 then
input_delta = input_delta / 100.0
if tweak_slow then
input_delta = input_delta / 10.0
end
else
if (v_range_f >= -100.0 and v_range_f <= 100.0 and v_range_f ~= 0.0) or tweak_slow then
input_delta = ((input_delta < 0.0) and -1.0 or 1.0) / v_range_f
else
input_delta = input_delta / 100.0
end
end
if tweak_fast then
input_delta = input_delta * 10.0
end
g.SliderCurrentAccum = g.SliderCurrentAccum + input_delta
g.SliderCurrentAccumDirty = true
end
local delta = g.SliderCurrentAccum
if g.NavActivatePressedId == id and not g.ActiveIdIsJustActivated then
ImGui.ClearActiveID()
elseif g.SliderCurrentAccumDirty then
clicked_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
if (clicked_t >= 1.0 and delta > 0.0) or (clicked_t <= 0.0 and delta < 0.0) then
set_new_value = false
g.SliderCurrentAccum = 0.0
else
set_new_value = true
local old_clicked_t = clicked_t
clicked_t = ImSaturate(clicked_t + delta)
local v_new = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then
v_new = ImGui.RoundScalarWithFormatT(format, data_type, v_new)
end
local new_clicked_t = ImGui.ScaleRatioFromValueT(data_type, v_new, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
if delta > 0 then
g.SliderCurrentAccum = g.SliderCurrentAccum - ImMin(new_clicked_t - old_clicked_t, delta)
else
g.SliderCurrentAccum = g.SliderCurrentAccum - ImMax(new_clicked_t - old_clicked_t, delta)
end
end
g.SliderCurrentAccumDirty = false
end
end
if set_new_value then
if (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.ReadOnly) ~= 0) or (bit32.band(flags, ImGuiSliderFlags.ReadOnly) ~= 0) then
set_new_value = false
end
end
if set_new_value then
local v_new = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then
v_new = ImGui.RoundScalarWithFormatT(format, data_type, v_new)
end
if v ~= v_new then
v = v_new
value_changed = true
end
end
end
if slider_sz < 1.0 then
ImRect_Copy(out_grab_bb, ImRect(bb.Min, bb.Min))
else
local grab_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize)
if axis == ImGuiAxis.Y then
grab_t = 1.0 - grab_t
end
local grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t)
if axis == ImGuiAxis.X then
ImRect_Copy(out_grab_bb, ImRect(grab_pos - grab_sz * 0.5, bb.Min.y + grab_padding, grab_pos + grab_sz * 0.5, bb.Max.y - grab_padding))
else
ImRect_Copy(out_grab_bb, ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz * 0.5, bb.Max.x - grab_padding, grab_pos + grab_sz * 0.5))
end
end
return v, value_changed
end
--- @generic T : number
--- @param bb ImRect
--- @param id ImGuiID
--- @param data_type ImGuiDataType
--- @param v T
--- @param min T
--- @param max T
--- @param format string
--- @param flags ImGuiSliderFlags
--- @param out_grab_bb ImRect
--- @return T v
--- @return bool value_changed
function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out_grab_bb)
IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.")
IM_ASSERT(bit32.band(flags, ImGuiSliderFlags.WrapAround) == 0)
if data_type == ImGuiDataType.S8 then
local v32 = (ImS32)((ImS8)(v)); local r
v32, r = ImGui.SliderBehaviorT(ImS32, ImS32, bb, id, ImGuiDataType.S32, v32, min, max, format, flags, out_grab_bb)
if r then v = (ImS8)(v32) end
return v, r
elseif data_type == ImGuiDataType.U8 then
local v32 = (ImU32)((ImU8)(v)); local r
v32, r = ImGui.SliderBehaviorT(ImU32, ImS32, bb, id, ImGuiDataType.U32, v32, min, max, format, flags, out_grab_bb)
if r then v = (ImU8)(v32) end
return v, r
elseif data_type == ImGuiDataType.S16 then
local v32 = (ImS32)((ImS16)(v)); local r
v32, r = ImGui.SliderBehaviorT(ImS32, ImS32, bb, id, ImGuiDataType.S32, v32, min, max, format, flags, out_grab_bb)
if r then v = (ImS16)(v32) end
return v, r
elseif data_type == ImGuiDataType.U16 then
local v32 = (ImU32)((ImU16)(v)); local r
v32, r = ImGui.SliderBehaviorT(ImU32, ImS32, bb, id, ImGuiDataType.U32, v32, min, max, format, flags, out_grab_bb)
if r then v = (ImU16)(v32) end
return v, r
elseif data_type == ImGuiDataType.S32 then
IM_ASSERT(min >= math.floor(IM_S32_MIN / 2) and max <= math.floor(IM_S32_MAX / 2))
return ImGui.SliderBehaviorT(ImS32, ImS32, bb, id, data_type, v, min, max, format, flags, out_grab_bb)
elseif data_type == ImGuiDataType.U32 then
IM_ASSERT(max <= math.floor(IM_U32_MAX / 2))
return ImGui.SliderBehaviorT(ImU32, ImS32, bb, id, data_type, v, min, max, format, flags, out_grab_bb)
elseif data_type == ImGuiDataType.Float then
IM_ASSERT(min >= -FLT_MAX / 2.0 and max <= FLT_MAX / 2.0)
return ImGui.SliderBehaviorT(float, float, bb, id, data_type, v, min, max, format, flags, out_grab_bb)
elseif data_type == ImGuiDataType.Double then
IM_ASSERT(min >= -DBL_MAX / 2.0 and max <= DBL_MAX / 2.0)
return ImGui.SliderBehaviorT(double, double, bb, id, data_type, v, min, max, format, flags, out_grab_bb)
end
IM_ASSERT(false)
return v, false
end
--- @generic T : number
--- @param label string
--- @param data_type ImGuiDataType
--- @param data T
--- @param min T
--- @param max T
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.SliderScalar(label, data_type, data, min, max, format, flags)
if flags == nil then flags = 0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return data, false
end
local g = GImGui
local style = g.Style
local id = window:GetID(label)
local w = ImGui.CalcItemWidth()
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_size = ImGui.CalcTextSize(label, label_end, false)
local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(w, 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 = ImRect(frame_bb.Min, ImVec2(total_bb_x, frame_bb.Max.y))
local temp_input_allowed = bit32.band(flags, ImGuiSliderFlags.NoInput) == 0
ImGui.ItemSize(total_bb, style.FramePadding.y)
local item_flags = temp_input_allowed and ImGuiItemFlags.Inputable or 0
if not ImGui.ItemAdd(total_bb, id, frame_bb, item_flags) then
return data, false
end
if format == nil then
format = ImGui.DataTypeGetInfo(data_type).PrintFmt
end
local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags)
local temp_input_is_active = temp_input_allowed and ImGui.TempInputIsActive(id)
if not temp_input_is_active then
local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id)
local make_active = clicked or g.NavActivateId == id
if make_active and clicked then
ImGui.SetKeyOwner(ImGuiKey.MouseLeft, id)
end
if make_active and temp_input_allowed then
if (clicked and g.IO.KeyCtrl) or (g.NavActivateId == id and bit32.band(g.NavActivateFlags, ImGuiActivateFlags.PreferInput) ~= 0) then
temp_input_is_active = true
end
end
if make_active then
g.ActiveIdValueOnActivation = data
end
if make_active and not temp_input_is_active then
ImGui.SetActiveID(id, window)
ImGui.SetFocusID(id, window)
ImGui.FocusWindow(window)
g.ActiveIdUsingNavDirMask = bit32.bor(g.ActiveIdUsingNavDirMask, bit32.lshift(1, ImGuiDir.Left), bit32.lshift(1, ImGuiDir.Right))
end
end
if temp_input_is_active then
local clamp_enabled = bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0
return ImGui.TempInputScalar(frame_bb, id, label, data_type, data, format, clamp_enabled and min or nil, clamp_enabled and max or nil)
end
local frame_col = ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg))
ImGui.RenderNavCursor(frame_bb, id)
ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding)
if color_marker ~= 0 and style.ColorMarkerSize > 0.0 then
ImGui.RenderColorComponentMarker(frame_bb, ImGui.GetColorU32(color_marker, nil, true), style.FrameRounding)
end
ImGui.RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding)
local grab_bb = ImRect()
local value_changed
data, value_changed = ImGui.SliderBehavior(frame_bb, id, data_type, data, min, max, format, flags, grab_bb)
if value_changed then
ImGui.MarkItemEdited(id)
end
if grab_bb.Max.x > grab_bb.Min.x then
window.DrawList:AddRectFilled(grab_bb.Min, grab_bb.Max, ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.SliderGrabActive or ImGuiCol.SliderGrab), style.GrabRounding)
end
-- TODO: ImGui.DataTypeFormatString() should be used here instead of ImFormatString()
-- if g.LogEnabled then
-- ImGui.LogSetNextTextDecoration("{", "}")
-- end
ImGui.RenderTextClipped(frame_bb.Min, frame_bb.Max, ImFormatString(format, data), nil, nil, ImVec2(0.5, 0.5))
if label_size.x > 0.0 then
ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
end
-- IMGUI_TEST_ENGINE_ITEM_INFO()
return data, value_changed
end
--- @param label string
--- @param data_type ImGuiDataType
--- @param v table
--- @param components int
--- @param v_min number
--- @param v_max number
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.SliderScalarN(label, data_type, v, components, v_min, v_max, format, flags)
if flags == nil then flags = 0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local value_changed = false
ImGui.BeginGroup()
ImGui.PushID(label)
ImGui.PushMultiItemsWidths(components, ImGui.CalcItemWidth())
for i = 1, components do
ImGui.PushID(i - 1)
if i > 1 then
ImGui.SameLine(0, g.Style.ItemInnerSpacing.x)
end
if bit32.band(flags, ImGuiSliderFlags.ColorMarkers) ~= 0 then
ImGui.SetNextItemColorMarker(GDefaultRgbaColorMarkers[i])
end
local changed
v[i], changed = ImGui.SliderScalar("", data_type, v[i], v_min, v_max, format, flags)
value_changed = value_changed or changed
ImGui.PopID()
ImGui.PopItemWidth()
end
ImGui.PopID()
local label_end = ImGui.FindRenderedTextEnd(label)
if label_end > 1 then
ImGui.SameLine(0, g.Style.ItemInnerSpacing.x)
ImGui.TextEx(label, label_end)
end
ImGui.EndGroup()
return value_changed
end
--- @param label string
--- @param v [float, float]
--- @param v_min float
--- @param v_max float
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.SliderFloat2(label, v, v_min, v_max, format, flags)
return ImGui.SliderScalarN(label, ImGuiDataType.Float, v, 2, v_min, v_max, format, flags)
end
--- @param label string
--- @param v [float, float, float]
--- @param v_min float
--- @param v_max float
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.SliderFloat3(label, v, v_min, v_max, format, flags)
return ImGui.SliderScalarN(label, ImGuiDataType.Float, v, 3, v_min, v_max, format, flags)
end
--- @param label string
--- @param v [float, float, float, float]
--- @param v_min float
--- @param v_max float
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.SliderFloat4(label, v, v_min, v_max, format, flags)
return ImGui.SliderScalarN(label, ImGuiDataType.Float, v, 4, v_min, v_max, format, flags)
end
--- @param label string
--- @param v float
--- @param v_min float
--- @param v_max float
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.SliderFloat(label, v, v_min, v_max, format, flags)
if format == nil then format = "%.3f" end
if flags == nil then flags = 0 end
return ImGui.SliderScalar(label, ImGuiDataType.Float, v, v_min, v_max, format, flags)
end
--- @param label string
--- @param v_rad float
--- @param v_degrees_min? float
--- @param v_degrees_max? float
--- @param format? string
--- @param flags? ImGuiSliderFlags
--- @return float v_rad # updated `v_rad`
--- @return bool value_changed
function ImGui.SliderAngle(label, v_rad, v_degrees_min, v_degrees_max, format, flags)
if v_degrees_min == nil then v_degrees_min = -360.0 end
if v_degrees_max == nil then v_degrees_max = 360.0 end
if format == nil then format = "%.0f deg" end
if flags == nil then flags = 0 end
local v_deg = v_rad * 360.0 / (2 * IM_PI)
local value_changed
v_deg, value_changed = ImGui.SliderFloat(label, v_deg, v_degrees_min, v_degrees_max, format, flags)
if value_changed then
v_rad = v_deg * (2 * IM_PI) / 360.0
end
return v_rad, value_changed
end
--- @param label string
--- @param v int
--- @param v_min int
--- @param v_max int
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.SliderInt(label, v, v_min, v_max, format, flags)
if format == nil then format = "%d" end
if flags == nil then flags = 0 end
return ImGui.SliderScalar(label, ImGuiDataType.S32, v, v_min, v_max, format, flags)
end
--- @param label string
--- @param size ImVec2
--- @param data_type ImGuiDataType
--- @param data number
--- @param min number
--- @param max number
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, flags)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return data, false
end
local g = GImGui
local style = g.Style
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + size)
local bb = ImRect(frame_bb.Min, ImVec2(frame_bb.Max.x + (label_size.x > 0.0 and (style.ItemInnerSpacing.x + label_size.x) or 0.0), frame_bb.Max.y))
ImGui.ItemSize(bb, style.FramePadding.y)
if not ImGui.ItemAdd(frame_bb, id) then
return data, false
end
if format == nil then
format = ImGui.DataTypeGetInfo(data_type).PrintFmt
end
local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags)
local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id)
if clicked or g.NavActivateId == id then
if clicked then
ImGui.SetKeyOwner(ImGuiKey.MouseLeft, id)
end
ImGui.SetActiveID(id, window)
ImGui.SetFocusID(id, window)
ImGui.FocusWindow(window)
g.ActiveIdUsingNavDirMask = bit32.bor(g.ActiveIdUsingNavDirMask, bit32.lshift(1, ImGuiDir.Up), bit32.lshift(1, ImGuiDir.Down))
end
local frame_col = ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg))
ImGui.RenderNavCursor(frame_bb, id)
ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding)
local grab_bb = ImRect()
local value_changed
data, value_changed = ImGui.SliderBehavior(frame_bb, id, data_type, data, min, max, format, bit32.bor(flags or 0, ImGuiSliderFlags.Vertical), grab_bb)
if value_changed then
ImGui.MarkItemEdited(id)
end
if grab_bb.Max.y > grab_bb.Min.y then
window.DrawList:AddRectFilled(grab_bb.Min, grab_bb.Max, ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.SliderGrabActive or ImGuiCol.SliderGrab), style.GrabRounding)
end
-- local value_buf, value_buf_size = {}, 64
-- TODO: ImGui.DataTypeFormatString()
ImGui.RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, ImFormatString(format, data), nil, nil, ImVec2(0.5, 0.0))
if label_size.x > 0.0 then
ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
end
-- IMGUI_TEST_ENGINE_ITEM_INFO()
return data, value_changed
end
--- @param label string
--- @param size ImVec2
--- @param v float
--- @param v_min float
--- @param v_max float
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.VSliderFloat(label, size, v, v_min, v_max, format, flags)
if format == nil then format = "%.3f" end
return ImGui.VSliderScalar(label, size, ImGuiDataType.Float, v, v_min, v_max, format, flags)
end
--- @param label string
--- @param size ImVec2
--- @param v int
--- @param v_min int
--- @param v_max int
--- @param format? string
--- @param flags? ImGuiSliderFlags
function ImGui.VSliderInt(label, size, v, v_min, v_max, format, flags)
if format == nil then format = "%d" end
return ImGui.VSliderScalar(label, size, ImGuiDataType.S32, v, v_min, v_max, format, flags)
end
----------------------------------------------------------------
-- [SECTION] INPUT TEXT
----------------------------------------------------------------
--- @param label string
--- @param buf char[]
--- @param buf_size int
--- @param flags? ImGuiInputTextFlags
--- @param callback? ImGuiInputTextCallback
--- @param user_data any
function ImGui.InputText(label, buf, buf_size, flags, callback, user_data)
if flags == nil then flags = 0 end
IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0)
return ImGui.InputTextEx(label, nil, buf, buf_size, ImVec2(0, 0), flags, callback, user_data)
end
ImStb = {}
--- @module "imstb_textedit"
local stbte
local IMSTB_TEXTEDIT_GETWIDTH_NEWLINE = -1.0
ImStb.TEXTEDIT_memmove = ImStd.memmove
--- @param ctx ImGuiContext
--- @param text char[]
--- @param text_begin int
--- @param text_end_display int
--- @param text_end int
--- @param out_offset? ImVec2
--- @param flags? ImDrawTextFlags
local function InputTextCalcTextSize(ctx, text, text_begin, text_end_display, text_end, out_offset, flags)
if flags == nil then flags = 0 end
local g = ctx
local obj = g.InputTextState
IM_ASSERT(text_end_display >= text_begin and text_end_display <= text_end)
return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj.WrapWidth, text, text_begin, text_end_display, text_end, out_offset, flags)
end
--- @param obj ImGuiInputTextState
--- @return int
function ImStb.TEXTEDIT_STRINGLEN(obj) return obj.TextLen end
--- @param obj ImGuiInputTextState
--- @param idx int # 1-based
function ImStb.TEXTEDIT_GETCHAR(obj, idx) IM_ASSERT(idx >= 1 and idx <= obj.TextLen + 1); return obj.TextSrc[idx] end
--- @param obj ImGuiInputTextState
--- @param line_start_idx int # 1-based
--- @param char_idx int # 1-based
--- @return float
function ImStb.TEXTEDIT_GETWIDTH(obj, line_start_idx, char_idx) local _, c = ImStd.ImTextCharFromUtf8(obj.TextSrc, line_start_idx + char_idx - 1, obj.TextLen + 1); if c == 10 then return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE end; local g = obj.Ctx; return g.FontBaked:GetCharAdvance(c) * g.FontBakedScale end
--- @param r StbTexteditRow
--- @param obj ImGuiInputTextState
--- @param line_start_idx int # 1-based
function ImStb.TEXTEDIT_LAYOUTROW(r, obj, line_start_idx)
local text = obj.TextSrc
local size, text_remaining = InputTextCalcTextSize(obj.Ctx, text, line_start_idx, obj.TextLen + 1, obj.TextLen + 1, nil, bit32.bor(ImDrawTextFlags.StopOnNewLine, ImDrawTextFlags.WrapKeepBlanks))
r.x0 = 0.0
r.x1 = size.x
r.baseline_y_delta = size.y
r.ymin = 0.0
r.ymax = size.y
r.num_chars = text_remaining - line_start_idx
end
--- @param obj ImGuiInputTextState
--- @param idx int
function ImStb.TEXTEDIT_GETNEXTCHARINDEX(obj, idx)
if idx >= obj.TextLen then
return obj.TextLen + 1
end
return idx + ImStd.ImTextCharFromUtf8(obj.TextSrc, idx, obj.TextLen + 1)
end
--- @param obj ImGuiInputTextState
--- @param idx int
function ImStb.TEXTEDIT_GETPREVCHARINDEX(obj, idx)
if idx <= 1 then
return -1
end
local p = ImStd.ImTextFindPreviousUtf8Codepoint(obj.TextSrc, 1, idx)
return p
end
local ImCharIsSeparatorW do
local separator_list = {
44, 0x3001, 46, 0x3002, 59, 0xFF1B, 40, 0xFF08, 41, 0xFF09, 123, 0xFF5B, 125, 0xFF5D,
91, 0x300C, 93, 0x300D, 124, 0xFF5C, 33, 0xFF01, 92, 0xFFE5, 47, 0x30FB, 0xFF0F,
10, 13
}
--- @param c unsigned_int
function ImCharIsSeparatorW(c)
for i = 1, #separator_list do
if c == separator_list[i] then
return true
end
end
return false
end
end
--- @param obj ImGuiInputTextState
--- @param idx int
function ImStb.is_word_boundary_from_right(obj, idx)
-- When ImGuiInputTextFlags.Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators
if bit32.band(obj.Flags, ImGuiInputTextFlags.Password) ~= 0 or idx <= 1 then
return false
end
local prev = ImStd.ImTextFindPreviousUtf8Codepoint(obj.TextSrc, 1, idx)
local _, curr_c = ImStd.ImTextCharFromUtf8(obj.TextSrc, idx, obj.TextLen + 1)
local _, prev_c = ImStd.ImTextCharFromUtf8(obj.TextSrc, prev, obj.TextLen + 1)
local prev_white = ImCharIsBlankW(prev_c)
local prev_separ = ImCharIsSeparatorW(prev_c)
local curr_white = ImCharIsBlankW(curr_c)
local curr_separ = ImCharIsSeparatorW(curr_c)
return ((prev_white or prev_separ) and not (curr_separ or curr_white)) or (curr_separ and not prev_separ)
end
--- @param obj ImGuiInputTextState
--- @param idx int
function ImStb.is_word_boundary_from_left(obj, idx)
if bit32.band(obj.Flags, ImGuiInputTextFlags.Password) ~= 0 or idx <= 1 then
return false
end
local prev = ImStd.ImTextFindPreviousUtf8Codepoint(obj.TextSrc, 1, idx)
local _, prev_c = ImStd.ImTextCharFromUtf8(obj.TextSrc, idx, obj.TextLen + 1)
local _, curr_c = ImStd.ImTextCharFromUtf8(obj.TextSrc, prev, obj.TextLen + 1)
local prev_white = ImCharIsBlankW(prev_c)
local prev_separ = ImCharIsSeparatorW(prev_c)
local curr_white = ImCharIsBlankW(curr_c)
local curr_separ = ImCharIsSeparatorW(curr_c)
return (prev_white and not (curr_separ or curr_white)) or (curr_separ and not prev_separ)
end
--- @param obj ImGuiInputTextState
--- @param idx int
function ImStb.TEXTEDIT_MOVEWORDLEFT(obj, idx)
idx = ImStb.TEXTEDIT_GETPREVCHARINDEX(obj, idx)
while idx >= 1 and not ImStb.is_word_boundary_from_right(obj, idx) do
idx = ImStb.TEXTEDIT_GETPREVCHARINDEX(obj, idx)
end
return (idx < 1) and 1 or idx
end
--- @param obj ImGuiInputTextState
--- @param idx int
local function STB_TEXTEDIT_MOVEWORDRIGHT_MAC(obj, idx)
local len = obj.TextLen
idx = ImStb.TEXTEDIT_GETNEXTCHARINDEX(obj, idx)
while idx <= len and not ImStb.is_word_boundary_from_left(obj, idx) do
idx = ImStb.TEXTEDIT_GETNEXTCHARINDEX(obj, idx)
end
return (idx > len + 1) and len + 1 or idx
end
--- @param obj ImGuiInputTextState
--- @param idx int
local function STB_TEXTEDIT_MOVEWORDRIGHT_WIN(obj, idx)
idx = ImStb.TEXTEDIT_GETNEXTCHARINDEX(obj, idx)
local len = obj.TextLen
while idx <= len and not ImStb.is_word_boundary_from_right(obj, idx) do
idx = ImStb.TEXTEDIT_GETNEXTCHARINDEX(obj, idx)
end
return (idx > len + 1) and len + 1 or idx
end
--- @param obj ImGuiInputTextState
--- @param idx int
function ImStb.TEXTEDIT_MOVEWORDRIGHT(obj, idx)
local g = obj.Ctx
if g.IO.ConfigMacOSXBehaviors then
return STB_TEXTEDIT_MOVEWORDRIGHT_MAC(obj, idx)
else
return STB_TEXTEDIT_MOVEWORDRIGHT_WIN(obj, idx)
end
end
-- Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping
--- @param obj ImGuiInputTextState
--- @param state STB_TexteditState
--- @param cursor int
function ImStb.TEXTEDIT_MOVELINESTART(obj, state, cursor)
if state.single_line then
return 1
end
if obj.WrapWidth > 0.0 then
local g = obj.Ctx
local bol = ImStd.ImStrbol(obj.TextSrc, cursor, 1)
local p = bol
local text_end = obj.TextLen + 1 -- End of line would be enough
while p >= bol do
local eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, obj.TextSrc, p, text_end, obj.WrapWidth, ImDrawTextFlags.WrapKeepBlanks)
if p == cursor then -- If we are already on a visible beginning-of-line, return real beginning-of-line (would be same as regular handler below)
return bol
end
if eol == cursor and obj.TextA[cursor] ~= 10 and obj.LastMoveDirectionLR == ImGuiDir.Left then
return bol
end
if eol >= cursor then
return p
end
p = (obj.TextSrc[eol] == 10) and eol + 1 or eol
end
end
-- Regular handler, same as stb_textedit_move_line_start()
while cursor > 1 do
local prev_cursor = ImStb.TEXTEDIT_GETPREVCHARINDEX(obj, cursor)
if (ImStb.TEXTEDIT_GETCHAR(obj, prev_cursor) == STB_TEXTEDIT_NEWLINE) then
break
end
cursor = prev_cursor
end
return cursor
end
--- @param obj ImGuiInputTextState
--- @param state STB_TexteditState
--- @param cursor int
function ImStb.TEXTEDIT_MOVELINEEND(obj, state, cursor)
local n = ImStb.TEXTEDIT_STRINGLEN(obj)
if state.single_line then
return n + 1
end
if obj.WrapWidth > 0.0 then
local g = obj.Ctx
local p = ImStd.ImStrbol(obj.TextSrc, cursor, 1)
local text_end = obj.TextLen + 1 -- End of line would be enough
while p < text_end do
local eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, obj.TextSrc, p, text_end, obj.WrapWidth, ImDrawTextFlags.WrapKeepBlanks)
cursor = eol
if eol == cursor and obj.LastMoveDirectionLR ~= ImGuiDir.Left then -- If we are already on a visible end-of-line, switch to regular handle
break
end
if eol > cursor then
return cursor
end
p = (obj.TextSrc[eol] == 10) and eol + 1 or eol
end
end
-- Regular handler, same as stb_textedit_move_line_end()
while (cursor < n and ImStb.TEXTEDIT_GETCHAR(obj, cursor) ~= STB_TEXTEDIT_NEWLINE) do
cursor = ImStb.TEXTEDIT_GETNEXTCHARINDEX(obj, cursor)
end
return cursor
end
--- @param obj ImGuiInputTextState
--- @param pos int
--- @param n int
function ImStb.TEXTEDIT_DELETECHARS(obj, pos, n)
IM_ASSERT(obj.TextSrc == obj.TextA.Data)
ImStd.memmove(obj.TextA.Data, pos, obj.TextA.Data, pos + n, obj.TextLen - n - pos + 2)
obj.EditedBefore = true
obj.EditedThisFrame = true
obj.TextLen = obj.TextLen - n
end
--- @param obj ImGuiInputTextState
--- @param pos int
--- @param new_text ImStringBuffer
--- @param new_text_pos int
--- @param new_text_len int
function ImStb.TEXTEDIT_INSERTCHARS(obj, pos, new_text, new_text_pos, new_text_len)
local is_resizable = bit32.band(obj.Flags, ImGuiInputTextFlags.CallbackResize) ~= 0
local text_len = obj.TextLen
IM_ASSERT(pos <= text_len + 1)
-- We support partial insertion (with a mod in stb_textedit)
local avail = obj.BufCapacity - 1 - obj.TextLen
if not is_resizable and new_text_len > avail then
new_text_len = math.floor(ImStd.ImTextFindValidUtf8CodepointEnd(new_text, new_text_pos, new_text_len + 1, avail) - new_text_pos) -- Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion
end
if new_text_len == 0 then
return 0
end
-- Grow internal buffer if needed
IM_ASSERT(obj.TextSrc == obj.TextA.Data)
if text_len + new_text_len + 1 > obj.TextA.Size and is_resizable then
obj.TextA:resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1)
obj.TextSrc = obj.TextA.Data
end
local text = obj.TextA.Data
if pos ~= text_len + 1 then
ImStd.memmove(text, pos + new_text_len, text, pos, text_len - pos + 1)
end
ImStd.memmove(text, pos, new_text, new_text_pos, new_text_len)
obj.EditedBefore = true
obj.EditedThisFrame = true
obj.TextLen = obj.TextLen + new_text_len
obj.TextA[obj.TextLen + 1] = 0
return new_text_len
end
stbte = IM_INCLUDE"imstb_textedit.lua"
--- @param str ImGuiInputTextState
--- @param state STB_TexteditState
--- @param text IMSTB_TEXTEDIT_CHARTYPE[]
--- @param text_len int
function ImStb.stb_textedit_replace(str, state, text, text_len)
stbte.makeundo_replace(str, state, 1, str.TextLen, text_len)
ImStb.TEXTEDIT_DELETECHARS(str, 1, str.TextLen)
state.cursor = 1
state.select_start = 1
state.select_end = 1
if text_len <= 0 then
return
end
local text_len_inserted = ImStb.TEXTEDIT_INSERTCHARS(str, 1, text, 1, text_len)
if text_len_inserted > 0 then
state.cursor = text_len + 1
state.select_start = text_len + 1
state.select_end = text_len + 1
state.has_preferred_x = false
return
end
IM_ASSERT(false) -- Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace()
end
local MT = ImGui.GetMetatables()
do
--- @param key int
function MT.ImGuiInputTextState:OnKeyPressed(key)
stbte.key(self, self.Stb, key)
self.CursorFollow = true
self:CursorAnimReset()
local key_u = bit32.band(key, bit32.bnot(STB_TEXTEDIT_K_SHIFT))
if key_u == STB_TEXTEDIT_K_LEFT or key_u == STB_TEXTEDIT_K_LINESTART or key_u == STB_TEXTEDIT_K_TEXTSTART or key_u == STB_TEXTEDIT_K_BACKSPACE or key_u == STB_TEXTEDIT_K_WORDLEFT then
self.LastMoveDirectionLR = ImGuiDir.Left
elseif key_u == STB_TEXTEDIT_K_RIGHT or key_u == STB_TEXTEDIT_K_LINEEND or key_u == STB_TEXTEDIT_K_TEXTEND or key_u == STB_TEXTEDIT_K_DELETE or key_u == STB_TEXTEDIT_K_WORDRIGHT then
self.LastMoveDirectionLR = ImGuiDir.Right
end
end
local utf8 = {0, 0, 0, 0, 0}
--- @param c unsigned_int
function MT.ImGuiInputTextState:OnCharPressed(c)
for i = 1, 5 do utf8[i] = 0 end
-- Convert the key to a UTF8 byte sequence.
-- The changes we had to make to stb_textedit_key made it very much UTF-8 specific which is not too great.
ImStd.ImTextCharToUtf8(utf8, c)
stbte.text(self, self.Stb, utf8, ImStd.ImStrlen(utf8))
self.CursorFollow = true
self:CursorAnimReset()
end
-- After a user-input the cursor stays on for a while without blinking
function MT.ImGuiInputTextState:CursorAnimReset() self.CursorAnim = -0.30 end
function MT.ImGuiInputTextState:CursorClamp()
self.Stb.cursor = ImMin(self.Stb.cursor, self.TextLen + 1)
self.Stb.select_start = ImMin(self.Stb.select_start, self.TextLen + 1)
self.Stb.select_end = ImMin(self.Stb.select_end, self.TextLen + 1)
end
function MT.ImGuiInputTextState:HasSelection() return self.Stb.select_start ~= self.Stb.select_end end
function MT.ImGuiInputTextState:SelectAll()
self.Stb.select_start = 1
self.Stb.cursor = self.TextLen + 1
self.Stb.select_end = self.TextLen + 1
self.Stb.has_preferred_x = false
end
end
function ImGui.PushPasswordFont()
local g = GImGui
local backup = g.InputTextPasswordFontBackupBaked
IM_ASSERT(backup.IndexAdvanceX.Size == 0 and backup.IndexLookup.Size == 0)
local glyph = g.FontBaked:FindGlyph(42) -- '*'
g.InputTextPasswordFontBackupFlags = g.Font.Flags
backup.FallbackGlyphIndex = g.FontBaked.FallbackGlyphIndex
backup.FallbackAdvanceX = g.FontBaked.FallbackAdvanceX
backup.IndexLookup:swap(g.FontBaked.IndexLookup)
backup.IndexAdvanceX:swap(g.FontBaked.IndexAdvanceX)
g.Font.Flags = bit32.bor(g.Font.Flags, ImFontFlags.NoLoadGlyphs)
g.FontBaked.FallbackGlyphIndex = g.FontBaked.Glyphs:index_from_ptr(glyph) + 1
g.FontBaked.FallbackAdvanceX = glyph.AdvanceX
end
function ImGui.PopPasswordFont()
local g = GImGui
local backup = g.InputTextPasswordFontBackupBaked
g.Font.Flags = g.InputTextPasswordFontBackupFlags
g.FontBaked.FallbackGlyphIndex = backup.FallbackGlyphIndex
g.FontBaked.FallbackAdvanceX = backup.FallbackAdvanceX
g.FontBaked.IndexLookup:swap(backup.IndexLookup)
g.FontBaked.IndexAdvanceX:swap(backup.IndexAdvanceX)
IM_ASSERT(backup.IndexAdvanceX.Size == 0 and backup.IndexLookup.Size == 0)
end
--- @param ctx ImGuiContext
--- @param state ImGuiInputTextState
--- @param char unsigned_int
--- @param callback? ImGuiInputTextCallback
--- @param user_data any
--- @param input_source_is_clipboard? bool
--- @return unsigned_int out_char
--- @return bool
local function InputTextFilterCharacter(ctx, state, char, callback, user_data, input_source_is_clipboard)
if input_source_is_clipboard == nil then input_source_is_clipboard = false end
IM_ASSERT(state ~= nil)
local c = char
local flags = state.Flags
-- Filter non-printable (NB: isprint is unreliable! see #2467)
local apply_named_filters = true
if c < 0x20 then
local pass = false
pass = pass or (c == 10) and (bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0) -- Note that an Enter KEY will emit \r and be ignored (we poll for KEY in InputText() code)
if c == 10 and input_source_is_clipboard and (bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) then -- In single line mode, replace \n with a space
char = 32
c = 32
pass = true
end
pass = pass or (c == 10) and (bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)
pass = pass or (c == 9) and (bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0) -- tab
if not pass then
return char, false
end
apply_named_filters = false -- Override named filters below so newline and tabs can still be inserted.
end
if not input_source_is_clipboard then
-- We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817)
if c == 127 then
return char, false
end
-- Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME)
if c >= 0xE000 and c <= 0xF8FF then
return char, false
end
end
-- Filter Unicode ranges we are not handling in this build
if c > IM_UNICODE_CODEPOINT_MAX then
return char, false
end
-- Generic named filters
if apply_named_filters and (bit32.band(flags, bit32.bor(ImGuiInputTextFlags.CharsDecimal, ImGuiInputTextFlags.CharsHexadecimal, ImGuiInputTextFlags.CharsUppercase, ImGuiInputTextFlags.CharsNoBlank, ImGuiInputTextFlags.CharsScientific, ImGuiInputTextFlags.LocalizeDecimalPoint))) ~= 0 then
-- The standard mandate that programs starts in the "C" locale where the decimal point is '.'.
-- We don't really intend to provide widespread support for it, but out of empathy for people stuck with using odd API, we support the bare minimum aka overriding the decimal point.
-- Change the default decimal_point with:
-- ImGui::GetPlatformIO()->Platform_LocaleDecimalPoint = *localeconv()->decimal_point;
-- Users of non-default decimal point (in particular ',') may be affected by word-selection logic (is_word_boundary_from_right/is_word_boundary_from_left) functions.
local g = ctx
local c_decimal_point = g.PlatformIO.Platform_LocaleDecimalPoint
if bit32.band(flags, bit32.bor(ImGuiInputTextFlags.CharsDecimal, ImGuiInputTextFlags.CharsScientific, ImGuiInputTextFlags.LocalizeDecimalPoint)) ~= 0 then
if c == 46 or c == 44 then -- '.' or ','
c = c_decimal_point
end
end
-- Full-width -> half-width conversion for numeric fields: https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block)
-- While this is mostly convenient, this has the side-effect for uninformed users accidentally inputting full-width characters that they may
-- scratch their head as to why it works in numerical fields vs in generic text fields it would require support in the font.
if bit32.band(flags, bit32.bor(ImGuiInputTextFlags.CharsDecimal, ImGuiInputTextFlags.CharsScientific, ImGuiInputTextFlags.CharsHexadecimal)) ~= 0 then
if c >= 0xFF01 and c <= 0xFF5E then
c = c - 0xFF01 + 0x21
end
end
-- Allow 0-9 . - + * /
if bit32.band(flags, ImGuiInputTextFlags.CharsDecimal) ~= 0 then
if not (c >= 48 and c <= 57) and (c ~= c_decimal_point) and (c ~= 45) and (c ~= 43) and (c ~= 42) and (c ~= 47) then -- 0-9 . - + * /
return char, false
end
end
-- Allow 0-9 . - + * / e E
if bit32.band(flags, ImGuiInputTextFlags.CharsScientific) ~= 0 then
if not (c >= 48 and c <= 57) and (c ~= c_decimal_point) and (c ~= 45) and (c ~= 43) and (c ~= 42) and (c ~= 47) and (c ~= 101) and (c ~= 69) then -- 0-9 . - + * / e E
return char, false
end
end
-- Allow 0-9 a-F A-F
if bit32.band(flags, ImGuiInputTextFlags.CharsHexadecimal) ~= 0 then
if not (c >= 48 and c <= 57) and not (c >= 97 and c <= 102) and not (c >= 65 and c <= 70) then -- 0-9 a-f A-F
return char, false
end
end
-- Turn a-z into A-Z
if bit32.band(flags, ImGuiInputTextFlags.CharsUppercase) ~= 0 then
if c >= 97 and c <= 122 then -- a-z
c = c + (65 - 97) -- 'A' - 'a'
end
end
if bit32.band(flags, ImGuiInputTextFlags.CharsNoBlank) ~= 0 then
if ImStd.ImCharIsBlankW(c) then
return char, false
end
end
char = c
end
-- Custom callback filter
if bit32.band(flags, ImGuiInputTextFlags.CallbackCharFilter) ~= 0 then
local g = GImGui
local callback_data = ImGuiInputTextCallbackData()
callback_data.Ctx = g
callback_data.ID = state.ID
callback_data.Flags = flags
callback_data.EventFlag = ImGuiInputTextFlags.CallbackCharFilter
callback_data.EventChar = c
callback_data.EventActivated = (state ~= nil and g.ActiveId == state.ID and g.ActiveIdIsJustActivated)
callback_data.CursorPos = state.Stb.cursor
callback_data.SelectionStart = state.Stb.select_start
callback_data.SelectionEnd = state.Stb.select_end
callback_data.UserData = user_data
if callback(callback_data) ~= 0 then
return char, false
end
char = callback_data.EventChar
if not callback_data.EventChar then
return char, false
end
end
return char, true
end
-- Find the shortest single replacement we can make to get from old_buf to new_buf
-- Note that this doesn't directly alter state->TextA, state->TextLen. They are expected to be made valid separately.
-- FIXME: Ideally we should transition toward (1) making InsertChars()/DeleteChars() update undo-stack (2) discourage (and keep reconcile) or obsolete (and remove reconcile) accessing buffer directly
--- @param state ImGuiInputTextState
--- @param old_buf ImStringBuffer
--- @param old_length int
--- @param new_buf ImStringBuffer
--- @param new_length int
local function InputTextReconcileUndoState(state, old_buf, old_length, new_buf, new_length)
local shorter_length = ImMin(old_length, new_length)
local first_diff
for i = 1, shorter_length do
first_diff = i
if old_buf[first_diff] ~= new_buf[first_diff] then
break
end
end
if first_diff == old_length + 1 and first_diff == new_length + 1 then
return
end
local old_last_diff = old_length
local new_last_diff = new_length
while old_last_diff >= first_diff and new_last_diff >= first_diff do
if old_buf[old_last_diff] ~= new_buf[new_last_diff] then
break
end
old_last_diff = old_last_diff - 1
new_last_diff = new_last_diff - 1
end
local insert_len = new_last_diff - first_diff + 1
local delete_len = old_last_diff - first_diff + 1
if insert_len > 0 or delete_len > 0 then
local undostate = state.Stb.undostate
local p = stbte.createundo(undostate, first_diff, delete_len, insert_len)
if p then
for i = 0, delete_len - 1 do
undostate.undo_char[p + i] = old_buf[first_diff + i]
end
end
end
end
--- @param id ImGuiID
function ImGui.InputTextDeactivateHook(id)
local g = GImGui
local state = g.InputTextState
if id == 0 or state.ID ~= id or g.ActiveId ~= id then
return
end
if not state.EditedBefore then
return
end
-- IMGUI_DEBUG_LOG_ACTIVEID("InputTextDeactivateHook() id = 0x%08X\n", id);
g.InputTextDeactivatedState.ID = state.ID
g.InputTextDeactivatedState.ElapseFrame = g.FrameCount + 1
if bit32.band(state.Flags, ImGuiInputTextFlags.ReadOnly) ~= 0 then
g.InputTextDeactivatedState.TextA:resize(0) -- In theory this data won't be used, but clear to be neat
else
IM_ASSERT(state.TextA.Data ~= nil)
-- IM_ASSERT(state.TextA[state.TextLen + 1] == 0)
g.InputTextDeactivatedState.TextA:resize(state.TextLen + 1)
ImStd.memmove(g.InputTextDeactivatedState.TextA.Data, 1, state.TextA.Data, 1, state.TextLen) -- state.TextLen + 1
end
end
--- @param flags ImGuiInputTextFlags
--- @param line_index ImGuiTextIndex
--- @param buf char[]
--- @param buf_end int
--- @param wrap_width float
--- @param max_output_buffer_size int
--- @return int size
--- @return int? out_buf_end
local function InputTextLineIndexBuild(flags, line_index, buf, buf_end, wrap_width, max_output_buffer_size)
local g = GImGui
local size = 0
local s = 1
local trailing_line_already_counted = false
if bit32.band(flags, ImGuiInputTextFlags.WordWrap) ~= 0 then
while s < buf_end do
if size <= max_output_buffer_size then
line_index.Offsets:push_back(s - 1)
end
size = size + 1
s = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, buf, s, buf_end, wrap_width, ImDrawTextFlags.WrapKeepBlanks)
if buf[s] == 10 then s = s + 1 end
end
elseif buf_end ~= nil then
while s < buf_end do
if size <= max_output_buffer_size then
line_index.Offsets:push_back(s - 1)
end
size = size + 1
s = ImMemchr(buf, 10, s) --[[@as int]] -- FIXME:
if s then s = s + 1 else s = buf_end end
end
else
-- Inactive path: we don't know buf_end ahead of time.
local s_eol
s = 1
while true do
if size <= max_output_buffer_size then
line_index.Offsets:push_back(s - 1)
end
size = size + 1
s_eol = ImMemchr(buf, 10, s)
if s_eol == nil then
s = s + ImStd.ImStrlen(buf) - s -- FIXME:
trailing_line_already_counted = true
break
end
s = s_eol + 1
end
end
local out_buf_end
if out_buf_end ~= nil then
out_buf_end = s
buf_end = s
end
if size == 0 then
line_index.Offsets:push_back(0)
size = size + 1
end
if s > 1 and buf[s - 1] == 10 and not trailing_line_already_counted then
local old_size = size
size = size + 1
if old_size <= max_output_buffer_size then
line_index.Offsets:push_back(s - 1)
end
end
return size, out_buf_end
end
--- @param t table
--- @param in_begin int
--- @param in_end int
--- @param v int
local function ImLowerBound(t, in_begin, in_end, v)
local in_p = in_begin
local count = in_end - in_begin
local floor = math.floor
local rshift = bit32.rshift
while count > 0 do
local count2 = floor(rshift(count, 1))
local mid = in_p + count2
if t[mid] < v then
in_p = mid + 1
count = count - count2 - 1
else
count = count2
end
end
return in_p
end
--- @param g ImGuiContext
--- @param state ImGuiInputTextState
--- @param line_index ImGuiTextIndex
--- @param buf char[]
--- @param buf_end int
--- @param cursor_n int
--- @return ImVec2
local function InputTextLineIndexGetPosOffset(g, state, line_index, buf, buf_end, cursor_n)
local cursor_ptr = cursor_n
local it = ImLowerBound(line_index.Offsets, 1, line_index.Offsets.Size + 1, cursor_ptr)
if it > 1 then
if it > line_index.Offsets.Size or line_index.Offsets[it] ~= cursor_ptr or (state ~= nil and state.WrapWidth > 0.0 and state.LastMoveDirectionLR == ImGuiDir.Right and
buf[cursor_ptr - 1] ~= 10 and buf[cursor_ptr - 1] ~= 0) then
it = it - 1
end
end
local line_no = it
local line_start = (line_no == 1) and 1 or line_index.Offsets[line_no] + 1
local offset = ImVec2()
offset.x = InputTextCalcTextSize(g, buf, line_start, cursor_ptr, buf_end, nil, ImDrawTextFlags.WrapKeepBlanks).x
offset.y = line_no * g.FontSize
return offset
end
-- Edit a string of text
--- @param label string
--- @param hint? char[]
--- @param buf char[]
--- @param buf_size int
--- @param size_arg ImVec2
--- @param flags ImGuiInputTextFlags
--- @param callback? ImGuiInputTextCallback
--- @param callback_user_data any
function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback, callback_user_data)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
IM_ASSERT(buf ~= nil and buf_size >= 0)
IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.CallbackHistory) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Can't use both together (they both use up/down keys)
IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.CallbackCompletion) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0)) -- Can't use both together (they both use tab key)
IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Multiline does not not work with left-trimming
IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Password) == 0) -- WordWrap does not work with Password mode
IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0) -- WordWrap does not work in single-line mode
local g = GImGui --[[@as ImGuiContext]]
local io = g.IO
local style = g.Style
local RENDER_SELECTION_WHEN_INACTIVE = false
local is_multiline = bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0
if is_multiline then -- Open group before calling GetID() because groups tracks id created within their scope (including the scrollbar)
ImGui.BeginGroup()
end
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local frame_size = ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), (is_multiline and g.FontSize * 8.0 or label_size.y) + style.FramePadding.y * 2.0) -- Arbitrary default of 8 lines high for multi-line
local total_size = ImVec2(frame_size.x + ((label_size.x > 0.0) and (style.ItemInnerSpacing.x + label_size.x) or 0.0), frame_size.y)
local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + frame_size)
local total_bb = ImRect(frame_bb.Min, frame_bb.Min + total_size)
local draw_window = window
local inner_size = ImVec2()
ImVec2_Copy(inner_size, frame_size)
local item_data_backup = ImGuiLastItemData()
if is_multiline then
local backup_pos = ImVec2()
ImVec2_Copy(backup_pos, window.DC.CursorPos)
ImGui.ItemSize(total_bb, style.FramePadding.y)
local no_clip = (g.InputTextDeactivatedState.ID == id) or (g.ActiveId == id) or (id == g.NavActivateId) -- Mimic some of ItemAdd() logic + add InputTextDeactivatedState.ID check.
if not ImGui.ItemAdd(total_bb, id, frame_bb, ImGuiItemFlags.Inputable) and not no_clip then
ImGui.EndGroup()
return false
end
ImGuiLastItemData_Copy(item_data_backup, g.LastItemData)
ImVec2_Copy(window.DC.CursorPos, backup_pos)
-- Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping
if g.NavActivateId == id and (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromTabbing) ~= 0) and (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromFocusApi) == 0) and (bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0) then
g.NavActivateId = 0
end
-- Prevent NavActivate reactivating in BeginChild() when we are already active
local backup_activate_id = g.NavActivateId
if g.ActiveId == id then -- Prevent reactivation
g.NavActivateId = 0
end
-- We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug
ImGui.PushStyleColor(ImGuiCol.ChildBg, style.Colors[ImGuiCol.FrameBg])
ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.FrameRounding)
ImGui.PushStyleVar(ImGuiStyleVar.ChildBorderSize, style.FrameBorderSize)
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0, 0)) -- Ensure no clip rect so mouse hover can reach FramePadding edges
local child_visible = ImGui.BeginChildEx(label, id, frame_bb:GetSize(), ImGuiChildFlags.Borders, ImGuiWindowFlags.NoMove)
g.NavActivateId = backup_activate_id
ImGui.PopStyleVar(3)
ImGui.PopStyleColor()
if not child_visible and not no_clip then
ImGui.EndChild()
ImGui.EndGroup()
return false
end
draw_window = g.CurrentWindow -- Child window
draw_window.DC.NavLayersActiveMaskNext = bit32.bor(draw_window.DC.NavLayersActiveMaskNext, bit32.lshift(1, draw_window.DC.NavLayerCurrent)) -- This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it
ImVec2_Copy(draw_window.DC.CursorPos, draw_window.DC.CursorPos + style.FramePadding)
inner_size.x = inner_size.x - draw_window.ScrollbarSizes.x
-- FIXME: Could this be a ImGuiChildFlags to affect the SetLastItemDataForWindow() call?
g.LastItemData.ID = id
g.LastItemData.ItemFlags = item_data_backup.ItemFlags
g.LastItemData.StatusFlags = item_data_backup.StatusFlags
else
ImGui.ItemSize(total_bb, style.FramePadding.y)
if bit32.band(flags, ImGuiInputTextFlags.TempInput) == 0 then
if not ImGui.ItemAdd(total_bb, id, frame_bb, ImGuiItemFlags.Inputable) then
return false
end
end
end
-- Ensure mouse cursor is set even after switching to keyboard/gamepad mode. May generalize further? (#6417)
local hovered = ImGui.ItemHoverable(frame_bb, id, bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.NoNavDisableMouseHover))
if hovered then
ImGui.SetMouseCursor(ImGuiMouseCursor.TextInput)
end
if hovered and g.NavHighlightItemUnderNav then
hovered = false
end
-- We are only allowed to access the state if we are already the active widget
local state = ImGui.GetInputTextState(id)
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.ReadOnly) ~= 0 then
flags = bit32.bor(flags, ImGuiInputTextFlags.ReadOnly)
end
local is_readonly = bit32.band(flags, ImGuiInputTextFlags.ReadOnly) ~= 0
local is_password = bit32.band(flags, ImGuiInputTextFlags.Password) ~= 0
local is_undoable = bit32.band(flags, ImGuiInputTextFlags.NoUndoRedo) == 0
local is_resizable = bit32.band(flags, ImGuiInputTextFlags.CallbackResize) ~= 0
if is_resizable then
IM_ASSERT(callback ~= nil) -- Must provide a callback if you set the ImGuiInputTextFlags.CallbackResize flag!
end
-- Word-wrapping: enforcing a fixed width not altered by vertical scrollbar makes things easier, notably to track cursor reliably and avoid one-frame glitches.
-- Instead of using ImGuiWindowFlags_AlwaysVerticalScrollbar we account for that space if the scrollbar is not visible.
local is_wordwrap = bit32.band(flags, ImGuiInputTextFlags.WordWrap) ~= 0
local wrap_width = 0.0
if is_wordwrap then
wrap_width = ImMax(1.0, ImGui.GetContentRegionAvail().x + (draw_window.ScrollbarY and 0.0 or -g.Style.ScrollbarSize))
end
local user_clicked = hovered and io.MouseClicked[0]
local input_requested_by_nav = (g.ActiveId ~= id) and (g.NavActivateId == id) and ((bit32.band(g.NavActivateFlags, ImGuiActivateFlags.PreferInput) ~= 0) or (g.NavInputSource == ImGuiInputSource.Keyboard))
local input_requested_by_reactivate = (g.InputTextReactivateId == id) -- for io.ConfigInputTextEnterKeepActive
local input_requested_by_user = (user_clicked) or (g.ActiveId == 0 and bit32.band(flags, ImGuiInputTextFlags.TempInput) ~= 0 and g.InputTextDeactivatedState.ID ~= id)
local scrollbar_id = (is_multiline and state ~= nil) and ImGui.GetWindowScrollbarID(draw_window, ImGuiAxis.Y) or 0
local user_scroll_finish = is_multiline and state ~= nil and g.ActiveId == 0 and g.ActiveIdPreviousFrame == scrollbar_id
local user_scroll_active = is_multiline and state ~= nil and g.ActiveId == scrollbar_id
local clear_active_id = false
local select_all = false
local scroll_y = is_multiline and draw_window.Scroll.y or FLT_MAX
local init_reload_from_user_buf = (state ~= nil and state.WantReloadUserBuf)
local init_changed_specs_multiline = (state ~= nil and (state.Stb.single_line ~= (not is_multiline)))
local init_changed_specs_readonly = (state ~= nil and (bit32.band(bit32.bxor(state.Flags, flags), ImGuiInputTextFlags.ReadOnly) ~= 0)) -- state ~= nil means it's our state
local init_make_active = (input_requested_by_user or input_requested_by_nav or input_requested_by_reactivate or user_scroll_finish)
if init_reload_from_user_buf then
local new_len = ImStd.ImStrlen(buf)
IM_ASSERT(new_len + 1 <= buf_size, "Is your input buffer properly zero-terminated?")
state.WantReloadUserBuf = false
--- @cast state ImGuiInputTextState
InputTextReconcileUndoState(state, state.TextA.Data, state.TextLen, buf, new_len)
state.TextA:resize(buf_size + 1)
state.TextLen = new_len
ImStd.memmove(state.TextA.Data, 1, buf, 1, state.TextLen + 1)
state.Stb.select_start = state.ReloadSelectionStart
state.Stb.cursor = state.ReloadSelectionEnd
state.Stb.select_end = state.ReloadSelectionEnd -- will be clamped to bounds below
elseif (init_make_active and g.ActiveId ~= id) or init_changed_specs_multiline or init_changed_specs_readonly then
-- Access state even if we don't own it yet
state = g.InputTextState
state:CursorAnimReset()
-- Backup state of deactivating item so they'll have a chance to do a write to output buffer on the same frame they report IsItemDeactivatedAfterEdit (#4714)
if (state.ID ~= id and state.ID == g.ActiveId and (init_make_active and g.ActiveId ~= id)) then
ImGui.InputTextDeactivateHook(state.ID) -- <-- this is essentially an earlier call to what SetActiveID() would do below.
end
-- Take a copy of the initial buffer value.
-- From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode)
local buf_len = ImStd.ImStrlen(buf)
IM_ASSERT(((buf_len + 1 <= buf_size) or (buf_len == 0 and buf_size == 0)), "Is your input buffer properly zero-terminated?")
if not user_scroll_finish then
state.TextToRevertTo:resize(buf_len + 1)
ImStd.memmove(state.TextToRevertTo.Data, 1, buf, 1, buf_len + 1)
end
-- Preserve cursor position and undo/redo stack if we come back to same widget
-- FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
local recycle_state = (state.ID == id and not init_changed_specs_multiline)
if (recycle_state and not init_changed_specs_readonly and (state.TextLen ~= buf_len or (state.TextA.Data == nil or ImStd.strncmp(state.TextA.Data, buf, buf_len) ~= 0))) then
recycle_state = false
end
-- Start edition
state.ID = id
state.TextLen = buf_len
state.EditedBefore = false
if not is_readonly then
state.TextA:resize(buf_size + 1)
ImStd.memmove(state.TextA.Data, 1, buf, 1, state.TextLen + 1)
end
-- Find initial scroll position for right alignment
ImVec2_Copy(state.Scroll, ImVec2(0.0, 0.0))
if bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 then
state.Scroll.x = state.Scroll.x + ImMax(0.0, ImGui.CalcTextSize(table.concat(buf)).x - frame_size.x + style.FramePadding.x * 2.0) -- FIXME: no table.concat here
end
-- Recycle existing cursor/selection/undo stack but clamp position
-- Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler
if not recycle_state then
stbte.initialize_state(state.Stb, not is_multiline)
end
if not is_multiline then
if bit32.band(flags, ImGuiInputTextFlags.AutoSelectAll) ~= 0 then
select_all = true
end
if input_requested_by_nav and (not recycle_state or (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.TryToPreserveState) == 0)) then
select_all = true
end
if user_clicked and io.KeyCtrl then
select_all = true
end
end
if bit32.band(flags, ImGuiInputTextFlags.AlwaysOverwrite) ~= 0 then
state.Stb.insert_mode = true -- stb field name is indeed incorrect (see #2863)
end
end
local is_osx = io.ConfigMacOSXBehaviors
if init_make_active and g.ActiveId ~= id then
IM_ASSERT(state ~= nil and state.ID == id)
ImGui.SetActiveID(id, window)
ImGui.SetFocusID(id, window)
ImGui.FocusWindow(window)
if input_requested_by_nav then
ImGui.SetNavCursorVisibleAfterMove()
end
end
if g.ActiveId == id then
-- Declare some inputs, the other are registered and polled via Shortcut() routing system
-- FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combination into individual shortcuts
local always_owned_keys = { ImGuiKey.LeftArrow, ImGuiKey.RightArrow, ImGuiKey.Delete, ImGuiKey.Backspace, ImGuiKey.Home, ImGuiKey.End }
for _, key in ipairs(always_owned_keys) do
ImGui.SetKeyOwner(key, id)
end
if user_clicked then
ImGui.SetKeyOwner(ImGuiKey.MouseLeft, id)
end
g.ActiveIdUsingNavDirMask = bit32.bor(g.ActiveIdUsingNavDirMask, bit32.lshift(1, ImGuiDir.Left), bit32.lshift(1, ImGuiDir.Right))
if is_multiline or (bit32.band(flags, ImGuiInputTextFlags.CallbackHistory) ~= 0) then
g.ActiveIdUsingNavDirMask = bit32.bor(g.ActiveIdUsingNavDirMask, bit32.lshift(1, ImGuiDir.Up), bit32.lshift(1, ImGuiDir.Down))
ImGui.SetKeyOwner(ImGuiKey.UpArrow, id)
ImGui.SetKeyOwner(ImGuiKey.DownArrow, id)
end
if is_multiline then
ImGui.SetKeyOwner(ImGuiKey.PageUp, id)
ImGui.SetKeyOwner(ImGuiKey.PageDown, id)
end
-- FIXME: May be a problem to always steal Alt on OSX, would ideally still allow an uninterrupted Alt down-up to toggle menu
if is_osx then
ImGui.SetKeyOwner(ImGuiMod_Alt, id)
end
-- Expose scroll in a manner that is agnostic to us using a child window
if is_multiline and state ~= nil then
state.Scroll.y = draw_window.Scroll.y
end
-- Read-only mode always ever read from source buffer. Refresh TextLen when active.
if is_readonly and state ~= nil then
state.TextLen = ImStd.ImStrlen(buf)
end
if state ~= nil then
state:CursorClamp()
end
-- if is_readonly and state ~= nil then
-- state.TextA:clear() -- Uncomment to facilitate debugging, but we otherwise prefer to keep/amortize th allocation.
-- end
end
if state ~= nil then
state.TextSrc = is_readonly and buf or state.TextA.Data
end
-- We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
if g.ActiveId == id and state == nil then
ImGui.ClearActiveID()
end
-- Release focus when we click outside
if g.ActiveId == id and io.MouseClicked[0] and not init_make_active then
clear_active_id = true
end
-- Lock the decision of whether we are going to take the path displaying the cursor or selection
local render_cursor = (g.ActiveId == id) or (state and user_scroll_active) --[[@as bool]]
local render_selection = state and (state:HasSelection() or select_all) and (RENDER_SELECTION_WHEN_INACTIVE or render_cursor)
local value_changed = false
local validated = false
-- Select the buffer to render
local buf_display_from_state = (render_cursor or render_selection or g.ActiveId == id) and not is_readonly and state ~= nil
local is_displaying_hint = (hint ~= nil and (buf_display_from_state and state.TextA.Data or buf)[1] == 0)
-- Password pushes a temporary font with only a fallback glyph
if is_password and not is_displaying_hint then
ImGui.PushPasswordFont()
end
if state ~= nil and state.ID == id then
state.Flags = flags
-- Word-wrapping: attempt to keep cursor in view while resizing frame/parent (FIXME-WORDWRAP: would be better to preserve same relative offset)
if is_wordwrap and state.WrapWidth ~= wrap_width then
state.CursorCenterY = true
state.WrapWidth = wrap_width
render_cursor = true
end
end
-- Process mouse inputs and character inputs
if g.ActiveId == id then
--- @cast state ImGuiInputTextState
IM_ASSERT(state ~= nil)
state.EditedThisFrame = false
state.BufCapacity = buf_size
state.WrapWidth = wrap_width
-- Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
-- Down the line we should have a cleaner library-wide concept of Selected vs Active
g.ActiveIdAllowOverlap = not io.MouseDown[0]
-- Edit in progress
local mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state.Scroll.x
local mouse_y = (is_multiline and (io.MousePos.y - draw_window.DC.CursorPos.y) or (g.FontSize * 0.5))
if select_all then
state:SelectAll()
state.SelectedAllMouseLock = true
elseif hovered and io.MouseClickedCount[0] >= 2 and not io.KeyShift then
stbte.click(state, state.Stb, mouse_x, mouse_y)
local multiclick_count = (io.MouseClickedCount[0] - 2)
if multiclick_count % 2 == 0 then
-- Double-click: Select word
-- We always use the "Mac" word advance for double-click select vs Ctrl+Right which use the platform dependent variant:
-- FIXME: There are likely many ways to improve this behavior, but there's no "right" behavior (depends on use-case, software, OS)
local is_bol = (state.Stb.cursor == 1) or ImStb.TEXTEDIT_GETCHAR(state, state.Stb.cursor - 1) == 10
if stbte.HAS_SELECTION(state.Stb) or not is_bol then
state:OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT)
end
-- state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_WORDRIGHT, STB_TEXTEDIT_K_SHIFT))
if not stbte.HAS_SELECTION(state.Stb) then
stbte.prep_selection_at_cursor(state.Stb)
end
state.Stb.cursor = STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state.Stb.cursor)
state.Stb.select_end = state.Stb.cursor
stbte.clamp(state, state.Stb)
else
-- Triple-click: Select line
local is_eol = ImStb.TEXTEDIT_GETCHAR(state, state.Stb.cursor) == 10
state.WrapWidth = 0.0 -- Temporarily disable wrapping so we use real line start
state:OnKeyPressed(STB_TEXTEDIT_K_LINESTART)
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_LINEEND, STB_TEXTEDIT_K_SHIFT))
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_RIGHT, STB_TEXTEDIT_K_SHIFT))
state.WrapWidth = wrap_width
if not is_eol and is_multiline then
state.Stb.select_start, state.Stb.select_end = state.Stb.select_end, state.Stb.select_start
state.Stb.cursor = state.Stb.select_end
end
state.CursorFollow = false
end
state:CursorAnimReset()
elseif io.MouseClicked[0] and not state.SelectedAllMouseLock then
if hovered then
if io.KeyShift then
stbte.drag(state, state.Stb, mouse_x, mouse_y)
else
stbte.click(state, state.Stb, mouse_x, mouse_y)
end
state:CursorAnimReset()
end
elseif io.MouseDown[0] and not state.SelectedAllMouseLock and (io.MouseDelta.x ~= 0.0 or io.MouseDelta.y ~= 0.0) then
stbte.drag(state, state.Stb, mouse_x, mouse_y)
state:CursorAnimReset()
state.CursorFollow = true
end
if state.SelectedAllMouseLock and not io.MouseDown[0] then
state.SelectedAllMouseLock = false
end
if bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0 and not is_readonly then
if ImGui.Shortcut(ImGuiKey.Tab, ImGuiInputFlags.Repeat, id) then
local c = 9 -- Insert TAB
local ret2
c, ret2 = InputTextFilterCharacter(g, state, c, callback, callback_user_data)
if ret2 then
state:OnCharPressed(c)
end
end
-- FIXME: Implement Shift+Tab
end
-- Process regular text input
local ignore_char_inputs = io.KeyCtrl and not io.KeyAlt
if io.InputQueueCharacters.Size > 0 then
if not ignore_char_inputs and not is_readonly and not input_requested_by_nav then
for n = 1, io.InputQueueCharacters.Size do
repeat
-- Insert character if they pass filtering
local c = io.InputQueueCharacters[n]
if c == 9 then -- Skip Tab, see above
break
end
local ret2
c, ret2 = InputTextFilterCharacter(g, state, c, callback, callback_user_data)
if ret2 then
state:OnCharPressed(c)
end
until true
end
end
-- Consume characters
io.InputQueueCharacters:resize(0)
end
end
-- Process other shortcuts/key-presses
local revert_edit = false
if g.ActiveId == id and not g.ActiveIdIsJustActivated and not clear_active_id then
IM_ASSERT(state ~= nil)
--- @cast state ImGuiInputTextState
local row_count_per_page = ImMax(ImTrunc((inner_size.y - style.FramePadding.y) / g.FontSize), 1)
state.Stb.row_count_per_page = row_count_per_page
local k_mask = (io.KeyShift and STB_TEXTEDIT_K_SHIFT or 0)
local is_wordmove_key_down = is_osx and io.KeyAlt or io.KeyCtrl
local is_startend_key_down = is_osx and io.KeyCtrl and not io.KeySuper and not io.KeyAlt
local f_repeat = ImGuiInputFlags.Repeat
local is_cut = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.X), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Shift, ImGuiKey.Delete), f_repeat, id)) and not is_readonly and not is_password and (not is_multiline or state:HasSelection())
local is_copy = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.C), 0, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Insert), 0, id)) and not is_password and (not is_multiline or state:HasSelection())
local is_paste = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.V), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Shift, ImGuiKey.Insert), f_repeat, id)) and not is_readonly
local is_undo = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Z), f_repeat, id)) and not is_readonly and is_undoable
local is_redo = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Y), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Z), f_repeat, id)) and not is_readonly and is_undoable
local is_select_all = ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.A), 0, id)
local nav_gamepad_active = (bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0) and (bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0)
local is_enter = ImGui.Shortcut(ImGuiKey.Enter, f_repeat, id) or ImGui.Shortcut(ImGuiKey.KeypadEnter, f_repeat, id)
local is_ctrl_enter = ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Enter), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.KeypadEnter), f_repeat, id)
local is_shift_enter = ImGui.Shortcut(bit32.bor(ImGuiMod_Shift, ImGuiKey.Enter), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Shift, ImGuiKey.KeypadEnter), f_repeat, id)
local is_gamepad_validate = nav_gamepad_active and ImGui.IsKeyPressed(ImGuiKey.NavGamepadActivate, false)
local is_cancel = ImGui.Shortcut(ImGuiKey.Escape, f_repeat, id) or (nav_gamepad_active and ImGui.Shortcut(ImGuiKey.NavGamepadCancel, f_repeat, id))
if ImGui.IsKeyPressed(ImGuiKey.LeftArrow) then
state:OnKeyPressed(bit32.bor(is_startend_key_down and STB_TEXTEDIT_K_LINESTART or (is_wordmove_key_down and STB_TEXTEDIT_K_WORDLEFT or STB_TEXTEDIT_K_LEFT), k_mask))
elseif ImGui.IsKeyPressed(ImGuiKey.RightArrow) then
state:OnKeyPressed(bit32.bor(is_startend_key_down and STB_TEXTEDIT_K_LINEEND or (is_wordmove_key_down and STB_TEXTEDIT_K_WORDRIGHT or STB_TEXTEDIT_K_RIGHT), k_mask))
elseif ImGui.IsKeyPressed(ImGuiKey.UpArrow) and is_multiline then
if io.KeyCtrl then
ImGui.SetScrollY(draw_window, ImMax(draw_window.Scroll.y - g.FontSize, 0.0))
else
state:OnKeyPressed(bit32.bor(is_startend_key_down and STB_TEXTEDIT_K_TEXTSTART or STB_TEXTEDIT_K_UP, k_mask))
end
elseif ImGui.IsKeyPressed(ImGuiKey.DownArrow) and is_multiline then
if io.KeyCtrl then
ImGui.SetScrollY(draw_window, ImMin(draw_window.Scroll.y + g.FontSize, ImGui.GetScrollMaxY()))
else
state:OnKeyPressed(bit32.bor(is_startend_key_down and STB_TEXTEDIT_K_TEXTEND or STB_TEXTEDIT_K_DOWN, k_mask))
end
elseif ImGui.IsKeyPressed(ImGuiKey.PageUp) and is_multiline then
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_PGUP, k_mask))
scroll_y = scroll_y - row_count_per_page * g.FontSize
elseif ImGui.IsKeyPressed(ImGuiKey.PageDown) and is_multiline then
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_PGDOWN, k_mask))
scroll_y = scroll_y + row_count_per_page * g.FontSize
elseif ImGui.IsKeyPressed(ImGuiKey.Home) then
state:OnKeyPressed(io.KeyCtrl and bit32.bor(STB_TEXTEDIT_K_TEXTSTART, k_mask) or bit32.bor(STB_TEXTEDIT_K_LINESTART, k_mask))
elseif ImGui.IsKeyPressed(ImGuiKey.End) then
state:OnKeyPressed(io.KeyCtrl and bit32.bor(STB_TEXTEDIT_K_TEXTEND, k_mask) or bit32.bor(STB_TEXTEDIT_K_LINEEND, k_mask))
elseif ImGui.IsKeyPressed(ImGuiKey.Delete) and not is_readonly and not is_cut then
if not state:HasSelection() then
if is_wordmove_key_down then
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_WORDRIGHT, STB_TEXTEDIT_K_SHIFT))
end
end
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_DELETE, k_mask))
elseif ImGui.IsKeyPressed(ImGuiKey.Backspace) and not is_readonly then
if not state:HasSelection() then
if is_wordmove_key_down then
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_WORDLEFT, STB_TEXTEDIT_K_SHIFT))
elseif is_osx and io.KeyCtrl and not io.KeyAlt and not io.KeySuper then
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_LINESTART, STB_TEXTEDIT_K_SHIFT))
end
end
state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_BACKSPACE, k_mask))
elseif is_enter or is_ctrl_enter or is_shift_enter or is_gamepad_validate then
local ctrl_enter_for_new_line = bit32.band(flags, ImGuiInputTextFlags.CtrlEnterForNewLine) ~= 0
local is_new_line = is_multiline and not is_gamepad_validate and (is_shift_enter or (is_enter and not ctrl_enter_for_new_line) or (is_ctrl_enter and ctrl_enter_for_new_line))
if not is_new_line then
validated = true
clear_active_id = true
if io.ConfigInputTextEnterKeepActive and not is_multiline and not is_ctrl_enter and not is_shift_enter then
state:SelectAll()
g.InputTextReactivateId = id
end
elseif not is_readonly then
local c = 10 -- Insert new line
local ret2
c, ret2 = InputTextFilterCharacter(g, state, c, callback, callback_user_data)
if ret2 then
state:OnCharPressed(c)
end
end
elseif is_cancel then
if bit32.band(flags, ImGuiInputTextFlags.EscapeClearsAll) ~= 0 then
if state.TextA.Data[1] ~= 0 then
revert_edit = true
else
render_cursor = false
render_selection = false
clear_active_id = true
end
else
clear_active_id = true
revert_edit = true
render_cursor = false
render_selection = false
end
elseif is_undo or is_redo then
state:OnKeyPressed(is_undo and STB_TEXTEDIT_K_UNDO or STB_TEXTEDIT_K_REDO)
state:ClearSelection()
elseif is_select_all then
state:SelectAll()
state.CursorFollow = true
elseif is_cut or is_copy then
if g.PlatformIO.Platform_SetClipboardTextFn ~= nil then
local ib = state:HasSelection() and ImMin(state.Stb.select_start, state.Stb.select_end) or 1
local ie = state:HasSelection() and ImMax(state.Stb.select_start, state.Stb.select_end) or state.TextLen + 1
g.TempBuffer:reserve(ie - ib + 1)
ImStd.memmove(g.TempBuffer.Data, 1, state.TextSrc, ib, ie - ib)
g.TempBuffer.Data[ie - ib + 1] = 0
ImGui.SetClipboardText(ImGui._ByteArrayToString(g.TempBuffer.Data, 1, ie - ib + 1))
end
if is_cut then
if not state:HasSelection() then
state:SelectAll()
end
state.CursorFollow = true
stbte.cut(state, state.Stb)
end
elseif is_paste then
local clipboard = ImGui.GetClipboardText()
if clipboard then
local clipboard_len = #clipboard
local clipboard_end = clipboard_len + 1
local clipboard_filtered = ImVector()
clipboard_filtered:reserve(clipboard_len + 1)
local s
local i = 1
while i <= clipboard_len do
repeat
s = string.byte(clipboard, i)
local c, ret2
local in_len
in_len, c = ImStd.ImTextCharFromUtf8(clipboard, i, clipboard_end)
i = i + in_len
c, ret2 = InputTextFilterCharacter(g, state, c, callback, callback_user_data, true)
if ret2 then
break
end
local c_utf8 = {0, 0, 0, 0, 0}
ImStd.ImTextCharToUtf8(c_utf8, c)
local out_len = ImStd.ImStrlen(c_utf8)
clipboard_filtered:resize(clipboard_filtered.Size + out_len)
ImStd.memmove(clipboard_filtered.Data, clipboard_filtered.Size - out_len, c_utf8, 1, out_len)
until true
end
if clipboard_filtered.Size > 0 then
clipboard_filtered:push_back(0)
stbte.paste(state, state.Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1)
state.CursorFollow = true
end
end
end
render_selection = render_selection or (state:HasSelection() and (RENDER_SELECTION_WHEN_INACTIVE or render_cursor))
end
-- Process revert and user callbacks
local apply_new_text = nil
local apply_new_text_length = 0
if g.ActiveId == id then
IM_ASSERT(state ~= nil)
--- @cast state ImGuiInputTextState
if revert_edit and not is_readonly then
if bit32.band(flags, ImGuiInputTextFlags.EscapeClearsAll) ~= 0 then
IM_ASSERT(state.TextA.Data[1] ~= 0)
apply_new_text = {0}
apply_new_text_length = 0
value_changed = true
local empty_string = {0}
ImStb.stb_textedit_replace(state, state.Stb, empty_string, 0)
elseif ImStd.strcmp(state.TextA.Data, state.TextToRevertTo.Data) ~= 0 then
apply_new_text = state.TextToRevertTo.Data
apply_new_text_length = state.TextToRevertTo.Size - 1
value_changed = true
ImStb.stb_textedit_replace(state, state.Stb, state.TextToRevertTo.Data, state.TextToRevertTo.Size - 1)
end
end
if bit32.band(flags, bit32.bor(ImGuiInputTextFlags.CallbackCompletion, ImGuiInputTextFlags.CallbackHistory, ImGuiInputTextFlags.CallbackEdit, ImGuiInputTextFlags.CallbackAlways)) ~= 0 then
IM_ASSERT(callback ~= nil)
local event_flag = 0
local event_key = ImGuiKey.None
if bit32.band(flags, ImGuiInputTextFlags.CallbackCompletion) ~= 0 and ImGui.Shortcut(ImGuiKey.Tab, 0, id) then
event_flag = ImGuiInputTextFlags.CallbackCompletion
event_key = ImGuiKey.Tab
elseif bit32.band(flags, ImGuiInputTextFlags.CallbackHistory) ~= 0 and ImGui.IsKeyPressed(ImGuiKey.UpArrow) then
event_flag = ImGuiInputTextFlags.CallbackHistory
event_key = ImGuiKey.UpArrow
elseif bit32.band(flags, ImGuiInputTextFlags.CallbackHistory) ~= 0 and ImGui.IsKeyPressed(ImGuiKey.DownArrow) then
event_flag = ImGuiInputTextFlags.CallbackHistory
event_key = ImGuiKey.DownArrow
elseif bit32.band(flags, ImGuiInputTextFlags.CallbackEdit) ~= 0 and state.EditedThisFrame then
event_flag = ImGuiInputTextFlags.CallbackEdit
elseif bit32.band(flags, ImGuiInputTextFlags.CallbackAlways) ~= 0 then
event_flag = ImGuiInputTextFlags.CallbackAlways
end
if event_flag ~= 0 then
local callback_data = ImGuiInputTextCallbackData()
callback_data.Ctx = g
callback_data.ID = id
callback_data.Flags = flags
callback_data.EventFlag = event_flag
callback_data.EventActivated = (g.ActiveId == state.ID and g.ActiveIdIsJustActivated)
callback_data.UserData = callback_user_data
local callback_buf = is_readonly and buf or state.TextA.Data
IM_ASSERT(callback_buf == state.TextSrc)
state.CallbackTextBackup:resize(state.TextLen + 1)
ImStd.memmove(state.CallbackTextBackup.Data, 1, callback_buf, 1, state.TextLen + 1)
callback_data.EventKey = event_key
callback_data.Buf = callback_buf
callback_data.BufTextLen = state.TextLen
callback_data.BufSize = state.BufCapacity
callback_data.BufDirty = false
callback_data.CursorPos = state.Stb.cursor
callback_data.SelectionStart = state.Stb.select_start
callback_data.SelectionEnd = state.Stb.select_end
callback(callback_data)
callback_buf = is_readonly and buf or state.TextA.Data
IM_ASSERT(callback_data.Buf == callback_buf)
IM_ASSERT(callback_data.BufSize == state.BufCapacity)
IM_ASSERT(callback_data.Flags == flags)
if callback_data.BufDirty or callback_data.CursorPos ~= state.Stb.cursor then
state.CursorFollow = true
end
state.Stb.cursor = ImClamp(callback_data.CursorPos, 0, callback_data.BufTextLen)
state.Stb.select_start = ImClamp(callback_data.SelectionStart, 0, callback_data.BufTextLen)
state.Stb.select_end = ImClamp(callback_data.SelectionEnd, 0, callback_data.BufTextLen)
if callback_data.BufDirty then
IM_ASSERT(callback_data.BufTextLen == ImStd.ImStrlen(callback_data.Buf))
InputTextReconcileUndoState(state, state.CallbackTextBackup.Data, state.CallbackTextBackup.Size - 1, callback_data.Buf, callback_data.BufTextLen)
state.TextLen = callback_data.BufTextLen
state.EditedBefore = true; state.EditedThisFrame = true
state:CursorAnimReset()
end
end
end
if not is_readonly then
if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0 then
-- Apply when modified
if (ImStd.strcmp(state.TextSrc, buf) ~= 0) then
apply_new_text = state.TextSrc
apply_new_text_length = state.TextLen
value_changed = true
end
else
-- Apply on validation/deactivation, otherwise cancel out previous apply attempts (e.g. revert)
value_changed = ((validated or clear_active_id or revert_edit) and ImStd.strcmp(state.TextSrc, buf) ~= 0)
apply_new_text = value_changed and state.TextSrc or NULL
apply_new_text_length = value_changed and state.TextLen or 0
end
end
end
if g.InputTextDeactivatedState.ID == id then
-- The state only exists after an Edit. IsItemDeactivatedAfterEdit() is not valid in every code path (see "widgets_inputtext_status_noliveedit" test).
if ((g.ActiveId ~= id and ImGui.IsItemDeactivated()) or (g.ActiveId == id and bit32.band(flags, ImGuiInputTextFlags.TempInput) ~= 0)) then
if (not is_readonly and ImStd.strcmp(g.InputTextDeactivatedState.TextA.Data, buf) ~= 0) then
apply_new_text = g.InputTextDeactivatedState.TextA.Data
apply_new_text_length = g.InputTextDeactivatedState.TextA.Size - 1
value_changed = true
-- IMGUI_DEBUG_LOG("InputText(): apply Deactivated data for 0x%08X: \"%.*s\".\n", id, apply_new_text_length, apply_new_text);
end
end
g.InputTextDeactivatedState.ID = 0
end
if apply_new_text ~= nil then
IM_ASSERT(apply_new_text_length >= 0)
if is_resizable then
local callback_data = ImGuiInputTextCallbackData()
callback_data.Ctx = g
callback_data.ID = id
callback_data.Flags = flags
callback_data.EventFlag = ImGuiInputTextFlags.CallbackResize
callback_data.EventActivated = (g.ActiveId == state.ID and g.ActiveIdIsJustActivated)
callback_data.Buf = buf
callback_data.BufTextLen = apply_new_text_length
callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1)
callback_data.UserData = callback_user_data
callback(callback_data)
buf = callback_data.Buf
buf_size = callback_data.BufSize
apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1)
IM_ASSERT(apply_new_text_length <= buf_size)
end
ImStd.ImStrncpy(buf, 1, apply_new_text, 1, ImMin(apply_new_text_length + 1, buf_size))
end
-- Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
-- Otherwise request text input ahead for next frame.
if g.ActiveId == id and clear_active_id then
state.ID = 0
ImGui.ClearActiveID()
state.ID = id
end
-- Render frame
if not is_multiline then
ImGui.RenderNavCursor(frame_bb, id)
ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), true, style.FrameRounding)
end
local draw_pos = ImVec2()
ImVec2_Copy(draw_pos, is_multiline and draw_window.DC.CursorPos or (frame_bb.Min + style.FramePadding))
local clip_rect = ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y) -- Not using frame_bb.Max because we have adjusted size
if is_multiline then
clip_rect:ClipWith(draw_window.ClipRect)
end
-- Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
-- without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
-- Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash.
local buf_display_max_length = 2 * 1024 * 1024
local buf_display = buf_display_from_state and state.TextA.Data or buf
local buf_display_end = nil -- We have specialized paths below for setting the length
-- Display hint when contents is empty
-- At this point we need to handle the possibility that a callback could have modified the underlying buffer (#8368)
local new_is_displaying_hint = (hint ~= nil and (buf_display_from_state and state.TextA.Data or buf)[1] == 0)
if new_is_displaying_hint ~= is_displaying_hint then
if is_password and not is_displaying_hint then
ImGui.PopPasswordFont()
end
is_displaying_hint = new_is_displaying_hint
if is_password and not is_displaying_hint then
ImGui.PushPasswordFont()
end
end
if is_displaying_hint then
--- @cast hint char[]
buf_display = hint
buf_display_end = ImStd.ImStrlen(hint) + 1
else
if render_cursor or render_selection or g.ActiveId == id then
buf_display_end = state.TextLen + 1
elseif is_multiline and not is_wordwrap then
buf_display_end = nil -- Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path
else
buf_display_end = ImStd.ImStrlen(buf_display) + 1
end
end
-- Calculate visibility
local line_visible_n0, line_visible_n1 = 1, 2
if is_multiline then
line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize)
end
local line_index = g.InputTextLineIndex
line_index.Offsets:resize(0)
local line_count = 1
if is_multiline then
local will_scroll_y = state and ((state.CursorFollow and render_cursor) or (state.CursorCenterY and (render_cursor or render_selection)))
--- @cast buf_display_end int
local out_buf_end
line_count, out_buf_end = InputTextLineIndexBuild(flags, line_index, buf_display, buf_display_end, wrap_width, will_scroll_y and INT_MAX or (line_visible_n1 + 1))
if buf_display_end then
buf_display_end = out_buf_end
end
end
line_index.EndOffset = buf_display_end - 1
line_visible_n1 = ImMin(line_visible_n1, line_count + 1)
local text_size_y = line_count * g.FontSize
--- @cast buf_display_end int
local cursor_offset = (render_cursor and state) and InputTextLineIndexGetPosOffset(g, state, line_index, buf_display, buf_display_end, state.Stb.cursor) or ImVec2(0.0, 0.0)
local draw_scroll = ImVec2()
local text_col = ImGui.GetColorU32(is_displaying_hint and ImGuiCol.TextDisabled or ImGuiCol.Text)
if render_cursor or render_selection then
IM_ASSERT(state ~= nil)
state.LineCount = line_count
local new_scroll_y = scroll_y
if render_cursor and state.CursorFollow then
if bit32.band(flags, ImGuiInputTextFlags.NoHorizontalScroll) == 0 then
local scroll_increment_x = inner_size.x * 0.25
local visible_width = inner_size.x - style.FramePadding.x
if cursor_offset.x < state.Scroll.x then
state.Scroll.x = IM_TRUNC(ImMax(0.0, cursor_offset.x - scroll_increment_x))
elseif cursor_offset.x - visible_width >= state.Scroll.x then
state.Scroll.x = IM_TRUNC(cursor_offset.x - visible_width + scroll_increment_x)
end
else
state.Scroll.x = 0.0
end
if is_multiline then
if cursor_offset.y - g.FontSize < scroll_y then
new_scroll_y = ImMax(0.0, cursor_offset.y - g.FontSize)
elseif cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0) >= scroll_y then
new_scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0
end
end
state.CursorFollow = false
end
if state.CursorCenterY then
if is_multiline then
new_scroll_y = cursor_offset.y - g.FontSize - (inner_size.y * 0.5 - style.FramePadding.y)
end
state.CursorCenterY = false
render_cursor = false
end
if new_scroll_y ~= scroll_y then
local scroll_max_y = ImMax((text_size_y + style.FramePadding.y * 2.0) - inner_size.y, 0.0)
scroll_y = ImClamp(new_scroll_y, 0.0, scroll_max_y)
draw_pos.y = draw_pos.y + (draw_window.Scroll.y - scroll_y)
draw_window.Scroll.y = scroll_y
line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize)
line_visible_n1 = ImMin(line_visible_n1, line_count)
end
draw_scroll.x = state.Scroll.x
if render_selection then
local bg_color = ImGui.GetColorU32(ImGuiCol.TextSelectedBg, render_cursor and 1.0 or 0.6)
local bg_offy_up = is_multiline and 0.0 or -1.0
local bg_offy_dn = is_multiline and 0.0 or 2.0
local bg_eol_width = IM_TRUNC(g.FontBaked:GetCharAdvance(32) * 0.50)
local text_selected_begin = ImMin(state.Stb.select_start, state.Stb.select_end)
local text_selected_end = ImMax(state.Stb.select_start, state.Stb.select_end)
for line_n = line_visible_n0, line_visible_n1 - 1 do
repeat
local p = line_index:get_line_begin(1, line_n)
local p_eol = line_index:get_line_end(1, line_n)
local p_eol_is_wrap = (p_eol < buf_display_end and buf_display[p_eol] ~= 10)
if p_eol_is_wrap then
p_eol = p_eol + 1
end
local line_selected_begin = (text_selected_begin > p) and text_selected_begin or p
local line_selected_end = (text_selected_end < p_eol) and text_selected_end or p_eol
local rect_width = 0.0
if line_selected_begin < line_selected_end then
rect_width = rect_width + ImGui.CalcTextSizeEx(buf_display, line_selected_begin, line_selected_end).x
end
if text_selected_begin <= p_eol and text_selected_end > p_eol and not p_eol_is_wrap then
rect_width = rect_width + bg_eol_width
end
if rect_width == 0.0 then
break
end
local rect = ImRect()
rect.Min.x = draw_pos.x - draw_scroll.x + ImGui.CalcTextSizeEx(buf_display, p, line_selected_begin).x
rect.Min.y = draw_pos.y - draw_scroll.y + (line_n - 1) * g.FontSize
rect.Max.x = rect.Min.x + rect_width
rect.Max.y = rect.Min.y + bg_offy_dn + g.FontSize
rect.Min.y = rect.Min.y + bg_offy_up
rect:ClipWith(clip_rect)
draw_window.DrawList:AddRectFilled(rect.Min, rect.Max, bg_color)
until true
end
end
end
if g.ActiveId ~= id and bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and not render_cursor and not render_selection then
draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - ImGui.CalcTextSize(buf_display, nil).x - style.FramePadding.x)
end
if (is_multiline or (buf_display_end - 1) < buf_display_max_length) and bit32.band(text_col, IM_COL32_A_MASK) ~= 0 and line_visible_n0 < line_visible_n1 then
g.Font:RenderText(draw_window.DrawList, g.FontSize,
draw_pos - draw_scroll + ImVec2(0.0, (line_visible_n0 - 1) * g.FontSize),
text_col, clip_rect:AsVec4(),
buf_display,
line_index:get_line_begin(1, line_visible_n0),
line_index:get_line_end(1, line_visible_n1 - 1),
wrap_width, bit32.bor(ImDrawTextFlags.WrapKeepBlanks, ImDrawTextFlags.CpuFineClip))
end
if render_cursor then
state.CursorAnim = state.CursorAnim + io.DeltaTime
local cursor_is_visible = (not g.IO.ConfigInputTextCursorBlink) or (state.CursorAnim <= 0.0) or (ImFmod(state.CursorAnim, 1.20) <= 0.80)
local cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll)
local cursor_screen_rect = ImRect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5, cursor_screen_pos.x + 1.0, cursor_screen_pos.y - 1.5)
if cursor_is_visible and cursor_screen_rect:Overlaps(clip_rect) then
draw_window.DrawList:AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, ImGui.GetColorU32(ImGuiCol.InputTextCursor), style.InputTextCursorSize)
end
if not is_readonly and g.ActiveId == id then
local ime_data = g.PlatformImeData
ime_data.WantVisible = true
ime_data.WantTextInput = true
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.ViewportId = window.Viewport.ID
end
end
if is_password and not is_displaying_hint then
ImGui.PopPasswordFont()
end
if is_multiline then
-- For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags.Inputable (see #4761, #7870)...
ImGui.Dummy(ImVec2(0.0, text_size_y + style.FramePadding.y))
g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.Inputable, ImGuiItemFlags.NoTabStop)
ImGui.EndChild()
item_data_backup.StatusFlags = bit32.bor(item_data_backup.StatusFlags, bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow))
-- ...and then we need to undo the group overriding last item data, which gets a bit messy as EndGroup() tries to forward scrollbar being active...
-- FIXME: This quite messy/tricky, should attempt to get rid of the child window.
ImGui.EndGroup()
if g.LastItemData.ID == 0 or g.LastItemData.ID ~= ImGui.GetWindowScrollbarID(draw_window, ImGuiAxis.Y) then
g.LastItemData.ID = id
g.LastItemData.ItemFlags = item_data_backup.ItemFlags
g.LastItemData.StatusFlags = item_data_backup.StatusFlags
end
end
if state and is_readonly then
state.TextSrc = nil
end
if label_size.x > 0.0 then
ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label, 1, label_end, false)
end
if value_changed then
ImGui.MarkItemEdited(id)
end
if bit32.band(flags, ImGuiInputTextFlags.EnterReturnsTrue) ~= 0 then
return validated
else
return value_changed
end
end
--- @param label string
--- @param hint char[]
--- @param buf char[]
--- @param buf_size size_t
--- @param flags? ImGuiInputTextFlags
--- @param callback? ImGuiInputTextCallback
--- @param user_data? any
function ImGui.InputTextWithHint(label, hint, buf, buf_size, flags, callback, user_data)
if flags == nil then flags = 0 end
IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0)
return ImGui.InputTextEx(label, hint, buf, buf_size, ImVec2(0, 0), flags, callback, user_data)
end
----------------------------------------------------------------
-- [SECTION] COLOR EDIT / PICKER
----------------------------------------------------------------
--- @param col float[]
--- @param H float
--- @return float
local function ColorEditRestoreH(col, H)
local g = GImGui
IM_ASSERT(g.ColorEditCurrentID ~= 0)
if g.ColorEditSavedID ~= g.ColorEditCurrentID or g.ColorEditSavedColor ~= ImGui.ColorConvertFloat4ToU32(ImVec4(col[1], col[2], col[3], 0)) then
return H
end
H = g.ColorEditSavedHue
return H
end
--- @param col float[]
--- @param H float
--- @param S float
--- @param V float
--- @return float, float, float
local function ColorEditRestoreHS(col, H, S, V)
local g = GImGui
IM_ASSERT(g.ColorEditCurrentID ~= 0)
if g.ColorEditSavedID ~= g.ColorEditCurrentID or g.ColorEditSavedColor ~= ImGui.ColorConvertFloat4ToU32(ImVec4(col[1], col[2], col[3], 0)) then
return H, S, V
end
-- When S == 0, H is undefined.
-- When H == 1 it wraps around to 0.
if S == 0.0 or (H == 0.0 and g.ColorEditSavedHue == 1) then
H = g.ColorEditSavedHue
end
-- When V == 0, S is undefined.
if V == 0.0 then
S = g.ColorEditSavedSat
end
return H, S, V
end
do --[[ColorEdit4]]
local ids = { "##X", "##Y", "##Z", "##W" }
local fmt_table_int = {
{ "%3d", "%3d", "%3d", "%3d" }, -- Short display
{ "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, -- Long display for RGBA
{ "H:%3d", "S:%3d", "V:%3d", "A:%3d" } -- Long display for HSVA
}
local fmt_table_float = {
{ "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, -- Short display
{ "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, -- Long display for RGBA
{ "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } -- Long display for HSVA
}
--- @param label string
--- @param col float[]
--- @param flags ImGuiColorEditFlags
function ImGui.ColorEdit4(label, col, flags)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local style = g.Style
local square_sz = ImGui.GetFrameHeight()
local label_display_end = ImGui.FindRenderedTextEnd(label)
local w_full = ImGui.CalcItemWidth()
g.NextItemData:ClearFlags()
ImGui.BeginGroup()
ImGui.PushID(label)
local set_current_color_edit_id = (g.ColorEditCurrentID == 0)
if set_current_color_edit_id then
g.ColorEditCurrentID = window.IDStack:back()
end
-- If we're not showing any slider there's no point in doing any HSV conversions
local flags_untouched = flags
if bit32.band(flags, ImGuiColorEditFlags.NoInputs) ~= 0 then
flags = bit32.bor(bit32.band(flags, bit32.bnot(ImGuiColorEditFlags.DisplayMask_)), ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.NoOptions)
end
-- Context menu: display and modify options (before defaults are applied)
if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then
ImGui.ColorEditOptionsPopup(col, flags)
end
-- Read stored options
if bit32.band(flags, ImGuiColorEditFlags.DisplayMask_) == 0 then
flags = bit32.bor(flags, bit32.band(g.IO.ConfigColorEditFlags, ImGuiColorEditFlags.DisplayMask_))
end
if bit32.band(flags, ImGuiColorEditFlags.DataTypeMask_) == 0 then
flags = bit32.bor(flags, bit32.band(g.IO.ConfigColorEditFlags, ImGuiColorEditFlags.DataTypeMask_))
end
if bit32.band(flags, ImGuiColorEditFlags.PickerMask_) == 0 then
flags = bit32.bor(flags, bit32.band(g.IO.ConfigColorEditFlags, ImGuiColorEditFlags.PickerMask_))
end
if bit32.band(flags, ImGuiColorEditFlags.InputMask_) == 0 then
flags = bit32.bor(flags, bit32.band(g.IO.ConfigColorEditFlags, ImGuiColorEditFlags.InputMask_))
end
flags = bit32.bor(flags, bit32.band(g.IO.ConfigColorEditFlags, bit32.bnot(bit32.bor(ImGuiColorEditFlags.DisplayMask_, ImGuiColorEditFlags.DataTypeMask_, ImGuiColorEditFlags.PickerMask_, ImGuiColorEditFlags.InputMask_))))
IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiColorEditFlags.DisplayMask_))) -- Check that only 1 is selected
IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiColorEditFlags.InputMask_))) -- Check that only 1 is selected
local alpha = bit32.band(flags, ImGuiColorEditFlags.NoAlpha) == 0
local hdr = bit32.band(flags, ImGuiColorEditFlags.HDR) ~= 0
local components = alpha and 4 or 3
local w_button = (bit32.band(flags, ImGuiColorEditFlags.NoSmallPreview) ~= 0) and 0.0 or (square_sz + style.ItemInnerSpacing.x)
local w_inputs = ImMax(w_full - w_button, 1.0)
w_full = w_inputs + w_button
-- Convert to the formats we need
local f = { col[1], col[2], col[3], alpha and col[4] or 1.0 }
if bit32.band(flags, ImGuiColorEditFlags.InputHSV) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.DisplayRGB) ~= 0 then
f[1], f[2], f[3] = ImGui.ColorConvertHSVtoRGB(f[1], f[2], f[3])
elseif bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.DisplayHSV) ~= 0 then
-- Hue is lost when converting from grayscale rgb (saturation=0). Restore it.
f[1], f[2], f[3] = ImGui.ColorConvertRGBtoHSV(f[1], f[2], f[3])
f[1], f[2], f[3] = ColorEditRestoreHS(col, f[1], f[2], f[3])
end
local i = { IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]), IM_F32_TO_INT8_UNBOUND(f[4]) }
local value_changed = false
local value_changed_as_float = false
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local inputs_offset_x = (style.ColorButtonPosition == ImGuiDir.Left) and w_button or 0.0
window.DC.CursorPos.x = pos.x + inputs_offset_x
if bit32.band(flags, bit32.bor(ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.DisplayHSV)) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.NoInputs) == 0 then
local w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1)
local w_per_component = IM_TRUNC(w_items / components)
local draw_color_marker = bit32.band(flags, bit32.bor(ImGuiColorEditFlags.DisplayHSV, ImGuiColorEditFlags.NoColorMarkers)) == 0
local hide_prefix = draw_color_marker or (w_per_component <= ImGui.CalcTextSize((bit32.band(flags, ImGuiColorEditFlags.Float) ~= 0) and "M:0.000" or "M:000").x)
local fmt_idx
if hide_prefix then
fmt_idx = 1
elseif bit32.band(flags, ImGuiColorEditFlags.DisplayHSV) ~= 0 then
fmt_idx = 3
else
fmt_idx = 2
end
local drag_flags = draw_color_marker and ImGuiSliderFlags.ColorMarkers or ImGuiSliderFlags.None
local prev_split = 0.0
for n = 1, components do
if n > 1 then
ImGui.SameLine(0, style.ItemInnerSpacing.x)
end
local next_split = IM_TRUNC(w_items * n / components)
ImGui.SetNextItemWidth(ImMax(next_split - prev_split, 1.0))
prev_split = next_split
if draw_color_marker then
ImGui.SetNextItemColorMarker(GDefaultRgbaColorMarkers[n])
end
-- FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0
if bit32.band(flags, ImGuiColorEditFlags.Float) ~= 0 then
local changed
f[n], changed = ImGui.DragFloat(ids[n], f[n], 1.0 / 255.0, 0.0, hdr and 0.0 or 1.0, fmt_table_float[fmt_idx][n], drag_flags)
value_changed = value_changed or changed
value_changed_as_float = value_changed_as_float or value_changed
else
local changed
i[n], changed = ImGui.DragInt(ids[n], i[n], 1.0, 0, hdr and 0 or 255, fmt_table_int[fmt_idx][n], drag_flags)
value_changed = value_changed or changed
end
if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then
ImGui.OpenPopupOnItemClick("context", ImGuiPopupFlags.MouseButtonRight)
end
end
elseif bit32.band(flags, ImGuiColorEditFlags.DisplayHex) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.NoInputs) == 0 then
-- RGB Hexadecimal Input
-- TODO: resolve sprintf, sscanf requirement. currently this section creates a lot of temp tables and strings...
local buf, buf_size = nil, 64
if alpha then
local str = ImFormatString("#%02X%02X%02X%02X", ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255), ImClamp(i[4], 0, 255))
buf = { string.byte(str, 1, #str) }
buf[#buf + 1] = 0
else
local str = ImFormatString("#%02X%02X%02X", ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255))
buf = { string.byte(str, 1, #str) }
buf[#buf + 1] = 0
end
ImGui.SetNextItemWidth(w_inputs)
if ImGui.InputText("##Text", buf, buf_size, ImGuiInputTextFlags.CharsUppercase) then
value_changed = true
local p = 1
while buf[p] == 35 or ImCharIsBlankA(buf[p]) do
p = p + 1
end
i[1], i[2], i[3] = 0, 0, 0
i[4] = 0xFF
local r
if alpha then
r = ImStd.sscanf(buf, p, "%02X%02X%02X%02X", i)
else
r = ImStd.sscanf(buf, p, "%02X%02X%02X", i)
end
-- IM_UNUSED(r)
end
if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then
ImGui.OpenPopupOnItemClick("context", ImGuiPopupFlags.MouseButtonRight)
end
end
local picker_active_window = nil
if bit32.band(flags, ImGuiColorEditFlags.NoSmallPreview) == 0 then
local button_offset_x = (bit32.band(flags, ImGuiColorEditFlags.NoInputs) ~= 0 or style.ColorButtonPosition == ImGuiDir.Left) and 0.0 or (w_inputs + style.ItemInnerSpacing.x)
ImVec2_Copy(window.DC.CursorPos, ImVec2(pos.x + button_offset_x, pos.y))
local col_v4 = ImVec4(col[1], col[2], col[3], alpha and col[4] or 1.0)
if ImGui.ColorButton("##ColorButton", col_v4, flags) then
if bit32.band(flags, ImGuiColorEditFlags.NoPicker) == 0 then
-- Store current color and open a picker
ImVec4_Copy(g.ColorPickerRef, col_v4)
ImGui.OpenPopup("picker")
ImGui.SetNextWindowPos(g.LastItemData.Rect:GetBL() + ImVec2(0.0, style.ItemSpacing.y))
end
end
if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then
ImGui.OpenPopupOnItemClick("context", ImGuiPopupFlags.MouseButtonRight)
end
if ImGui.BeginPopup("picker") then
if g.CurrentWindow.BeginCount == 1 then
picker_active_window = g.CurrentWindow
if label ~= "" and label_display_end > 1 then
ImGui.TextEx(label, label_display_end)
ImGui.Spacing()
end
local picker_flags_to_forward = bit32.bor(ImGuiColorEditFlags.DataTypeMask_, ImGuiColorEditFlags.PickerMask_, ImGuiColorEditFlags.InputMask_, ImGuiColorEditFlags.HDR, ImGuiColorEditFlags.NoAlpha, ImGuiColorEditFlags.AlphaBar)
local picker_flags = bit32.bor(bit32.band(flags_untouched, picker_flags_to_forward), ImGuiColorEditFlags.DisplayMask_, ImGuiColorEditFlags.NoLabel, ImGuiColorEditFlags.AlphaPreviewHalf)
ImGui.SetNextItemWidth(square_sz * 12.0) -- Use 256 + bar sizes?
value_changed = value_changed or ImGui.ColorPicker4("##picker", col, picker_flags, g.ColorPickerRef)
end
ImGui.EndPopup()
end
end
if label ~= "" and label_display_end > 1 and bit32.band(flags, ImGuiColorEditFlags.NoLabel) == 0 then
-- Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left),
-- but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this
ImGui.SameLine(0.0, style.ItemInnerSpacing.x)
window.DC.CursorPos.x = pos.x + ((bit32.band(flags, ImGuiColorEditFlags.NoInputs) ~= 0) and w_button or (w_full + style.ItemInnerSpacing.x))
ImGui.TextEx(label, label_display_end)
end
-- Convert back
if value_changed and picker_active_window == nil then
if not value_changed_as_float then
for n = 1, 4 do
f[n] = i[n] / 255.0
end
end
if bit32.band(flags, ImGuiColorEditFlags.DisplayHSV) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 then
g.ColorEditSavedHue = f[1]
g.ColorEditSavedSat = f[2]
f[1], f[2], f[3] = ImGui.ColorConvertHSVtoRGB(f[1], f[2], f[3])
g.ColorEditSavedID = g.ColorEditCurrentID
g.ColorEditSavedColor = ImGui.ColorConvertFloat4ToU32(ImVec4(f[1], f[2], f[3], 0))
end
if bit32.band(flags, ImGuiColorEditFlags.DisplayRGB) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.InputHSV) ~= 0 then
f[1], f[2], f[3] = ImGui.ColorConvertRGBtoHSV(f[1], f[2], f[3])
end
col[1] = f[1]
col[2] = f[2]
col[3] = f[3]
if alpha then
col[4] = f[4]
end
end
if set_current_color_edit_id then
g.ColorEditCurrentID = 0
end
ImGui.PopID()
ImGui.EndGroup()
-- Drag and Drop Target
-- TODO:
-- When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4()
if picker_active_window and g.ActiveId ~= 0 and g.ActiveIdWindow == picker_active_window then
g.LastItemData.ID = g.ActiveId
end
if value_changed and g.LastItemData.ID ~= 0 then -- In case of ID collision, the second EndGroup() won't catch g.ActiveId
ImGui.MarkItemEdited(g.LastItemData.ID)
end
return value_changed
end
end
--- @param label string
--- @param col [float, float, float]
--- @param flags? ImGuiColorEditFlags
function ImGui.ColorEdit3(label, col, flags)
if flags == nil then flags = 0 end
return ImGui.ColorEdit4(label, col, bit32.bor(flags, ImGuiColorEditFlags.NoAlpha))
end
-- Helper for ColorPicker4()
--- @param draw_list ImDrawList
--- @param pos ImVec2
--- @param half_sz ImVec2
--- @param bar_w float
--- @param alpha float
local function RenderArrowsForVerticalBar(draw_list, pos, half_sz, bar_w, alpha)
local alpha8 = IM_F32_TO_INT8_SAT(alpha)
ImGui.RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir.Right, IM_COL32(0, 0, 0, alpha8))
ImGui.RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir.Right, IM_COL32(255, 255, 255, alpha8))
ImGui.RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir.Left, IM_COL32(0, 0, 0, alpha8))
ImGui.RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir.Left, IM_COL32(255, 255, 255, alpha8))
end
do --[[ColorPicker4]]
local backup_initial_col = {0, 0, 0, 0}
--- @param label string
--- @param col float[]
--- @param flags ImGuiColorEditFlags
--- @param ref_col? float[]
function ImGui.ColorPicker4(label, col, flags, ref_col)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local draw_list = window.DrawList
local g = GImGui
local style = g.Style
local io = g.IO
local width = ImGui.CalcItemWidth()
local is_readonly = bit32.band(bit32.bor(g.NextItemData.ItemFlagsSet, g.CurrentItemFlags), ImGuiItemFlags.ReadOnly) ~= 0
g.NextItemData:ClearFlags()
ImGui.PushID(label)
local set_current_color_edit_id = (g.ColorEditCurrentID == 0)
if set_current_color_edit_id then
g.ColorEditCurrentID = window.IDStack:back()
end
ImGui.BeginGroup()
if bit32.band(flags, ImGuiColorEditFlags.NoSidePreview) == 0 then
flags = bit32.bor(flags, ImGuiColorEditFlags.NoSmallPreview)
end
-- Context menu: display and store options.
if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then
ImGui.ColorPickerOptionsPopup(col, flags)
end
-- Read stored options
if bit32.band(flags, ImGuiColorEditFlags.PickerMask_) == 0 then
local picker_flags = bit32.band(g.IO.ConfigColorEditFlags, ImGuiColorEditFlags.PickerMask_)
if picker_flags ~= 0 then
flags = bit32.bor(flags, picker_flags)
else
flags = bit32.bor(flags, bit32.band(ImGuiColorEditFlags.DefaultOptions_, ImGuiColorEditFlags.PickerMask_))
end
end
if bit32.band(flags, ImGuiColorEditFlags.InputMask_) == 0 then
local input_flags = bit32.band(g.IO.ConfigColorEditFlags, ImGuiColorEditFlags.InputMask_)
if input_flags ~= 0 then
flags = bit32.bor(flags, input_flags)
else
flags = bit32.bor(flags, bit32.band(ImGuiColorEditFlags.DefaultOptions_, ImGuiColorEditFlags.InputMask_))
end
end
IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiColorEditFlags.PickerMask_))) -- Check that only 1 is selected
IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiColorEditFlags.InputMask_))) -- Check that only 1 is selected
if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then
flags = bit32.bor(flags, bit32.band(g.IO.ConfigColorEditFlags, ImGuiColorEditFlags.AlphaBar))
end
-- Setup
local components = (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0) and 3 or 4
local alpha_bar = (bit32.band(flags, ImGuiColorEditFlags.AlphaBar) ~= 0) and (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) == 0)
local picker_pos = ImVec2()
ImVec2_Copy(picker_pos, window.DC.CursorPos)
local square_sz = ImGui.GetFrameHeight()
local bars_width = square_sz -- Arbitrary smallish width of Hue/Alpha picking bars
local sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar and 2 or 1) * (bars_width + style.ItemInnerSpacing.x)) -- Saturation/Value picking box
local bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x
local bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x
local bars_triangles_half_sz = IM_TRUNC(bars_width * 0.20)
backup_initial_col[1], backup_initial_col[2], backup_initial_col[3], backup_initial_col[4] = col[1], col[2], col[3], col[4]
local wheel_thickness = sv_picker_size * 0.08
local wheel_r_outer = sv_picker_size * 0.50
local wheel_r_inner = wheel_r_outer - wheel_thickness
local wheel_center = ImVec2(picker_pos.x + (sv_picker_size + bars_width) * 0.5, picker_pos.y + sv_picker_size * 0.5)
-- Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
local triangle_rotate = bit32.band(flags, ImGuiColorEditFlags.PickerNoRotate) == 0
local triangle_r = wheel_r_inner - math.floor(sv_picker_size * 0.027)
local triangle_pa, triangle_pb, triangle_pc
if triangle_rotate then triangle_pa = ImVec2( triangle_r, 0.0) else triangle_pa = ImVec2( triangle_r * 0.866, triangle_r * 0.5) end -- Hue point
if triangle_rotate then triangle_pb = ImVec2(triangle_r * -0.5, triangle_r * -0.866) else triangle_pb = ImVec2( 0.0, -triangle_r) end -- Black point
if triangle_rotate then triangle_pc = ImVec2(triangle_r * -0.5, triangle_r * 0.866) else triangle_pc = ImVec2(triangle_r * -0.866, triangle_r * 0.5) end -- White point
local H = col[1]; local S = col[2]; local V = col[3]
local R = col[1]; local G = col[2]; local B = col[3]
if bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 then
-- Hue is lost when converting from grayscale rgb (saturation=0). Restore it.
H, S, V = ImGui.ColorConvertRGBtoHSV(R, G, B)
H, S, V = ColorEditRestoreHS(col, H, S, V)
elseif bit32.band(flags, ImGuiColorEditFlags.InputHSV) ~= 0 then
R, G, B = ImGui.ColorConvertHSVtoRGB(H, S, V)
end
local value_changed = false; local value_changed_h = false; local value_changed_sv = false
ImGui.PushItemFlag(ImGuiItemFlags.NoNav, true)
if bit32.band(flags, ImGuiColorEditFlags.PickerHueWheel) ~= 0 then
-- Hue wheel + SV triangle logic
ImGui.InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size))
if ImGui.IsItemActive() and not is_readonly then
local initial_off = g.IO.MouseClickedPos[0] - wheel_center
local current_off = g.IO.MousePos - wheel_center
local initial_dist2 = ImLengthSqr(initial_off)
if initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) and initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1) then
-- Interactive with Hue wheel
H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5
if H < 0.0 then
H = H + 1.0
end
value_changed = true
value_changed_h = true
end
local cos_hue_angle = triangle_rotate and ImCos(-H * 2.0 * IM_PI) or 1.0
local sin_hue_angle = triangle_rotate and ImSin(-H * 2.0 * IM_PI) or 0.0
if ImStd.ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)) then
-- Interacting with SV triangle
local current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle)
if not ImStd.ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated) then
current_off_unrotated = ImStd.ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated)
end
local uu, vv, ww
uu, vv, ww = ImStd.ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated)
V = ImClamp(1.0 - vv, 0.0001, 1.0)
S = ImClamp(uu / V, 0.0001, 1.0)
value_changed = true
value_changed_sv = true
end
end
if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then
ImGui.OpenPopupOnItemClick("context", ImGuiPopupFlags.MouseButtonRight)
end
elseif bit32.band(flags, ImGuiColorEditFlags.PickerHueBar) ~= 0 then
-- SV rectangle logic
ImGui.InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size))
if ImGui.IsItemActive() and not is_readonly then
S = ImSaturate((io.MousePos.x - picker_pos.x) / ImMax(sv_picker_size - 1, 0.0001))
V = 1.0 - ImSaturate((io.MousePos.y - picker_pos.y) / ImMax(sv_picker_size - 1, 0.0001))
H = ColorEditRestoreH(col, H) -- Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square.
value_changed = true
value_changed_sv = true
end
if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then
ImGui.OpenPopupOnItemClick("context", ImGuiPopupFlags.MouseButtonRight)
end
-- Hue bar logic
ImGui.SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y))
ImGui.InvisibleButton("hue", ImVec2(bars_width, sv_picker_size))
if ImGui.IsItemActive() and not is_readonly then
H = ImSaturate((io.MousePos.y - picker_pos.y) / ImMax(sv_picker_size - 1, 0.0001))
value_changed = true
value_changed_h = true
end
end
-- Alpha bar logic
if alpha_bar then
ImGui.SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y))
ImGui.InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size))
if ImGui.IsItemActive() then
col[4] = 1.0 - ImSaturate((io.MousePos.y - picker_pos.y) / ImMax(sv_picker_size - 1, 0.0001))
value_changed = true
end
end
ImGui.PopItemFlag()
if bit32.band(flags, ImGuiColorEditFlags.NoSidePreview) == 0 then
ImGui.SameLine(0, style.ItemInnerSpacing.x)
ImGui.BeginGroup()
end
if bit32.band(flags, ImGuiColorEditFlags.NoLabel) == 0 then
local label_display_end = ImGui.FindRenderedTextEnd(label)
if label ~= "" and label_display_end > 1 then
if bit32.band(flags, ImGuiColorEditFlags.NoSidePreview) ~= 0 then
ImGui.SameLine(0, style.ItemInnerSpacing.x)
end
ImGui.TextEx(label, label_display_end)
end
end
if bit32.band(flags, ImGuiColorEditFlags.NoSidePreview) == 0 then
ImGui.PushItemFlag(ImGuiItemFlags.NoNavDefaultFocus, true)
local col_v4 = ImVec4(col[1], col[2], col[3], (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0) and 1.0 or col[4])
if bit32.band(flags, ImGuiColorEditFlags.NoLabel) ~= 0 then
ImGui.Text("Current")
end
local sub_flags_to_forward = bit32.bor(ImGuiColorEditFlags.InputMask_, ImGuiColorEditFlags.HDR, ImGuiColorEditFlags.AlphaMask_, ImGuiColorEditFlags.NoTooltip)
ImGui.ColorButton("##current", col_v4, bit32.band(flags, sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2))
if ref_col ~= nil then
ImGui.Text("Original")
local ref_col_v4 = ImVec4(ref_col[1], ref_col[2], ref_col[3], (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0) and 1.0 or ref_col[4])
if ImGui.ColorButton("##original", ref_col_v4, bit32.band(flags, sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)) then
for i = 1, components do
col[i] = ref_col[i]
end
value_changed = true
end
end
ImGui.PopItemFlag()
ImGui.EndGroup()
end
-- Convert back color to RGB
if value_changed_h or value_changed_sv then
if bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 then
col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, S, V) -- Lua 1-based indexing
g.ColorEditSavedHue = H
g.ColorEditSavedSat = S
g.ColorEditSavedID = g.ColorEditCurrentID
g.ColorEditSavedColor = ImGui.ColorConvertFloat4ToU32(ImVec4(col[1], col[2], col[3], 0))
elseif bit32.band(flags, ImGuiColorEditFlags.InputHSV) ~= 0 then
col[1] = H
col[2] = S
col[3] = V
end
end
-- R,G,B and H,S,V slider color editor
local value_changed_fix_hue_wrap = false
if bit32.band(flags, ImGuiColorEditFlags.NoInputs) == 0 then
ImGui.PushItemWidth((alpha_bar and bar1_pos_x or bar0_pos_x) + bars_width - picker_pos.x)
local sub_flags_to_forward = bit32.bor(ImGuiColorEditFlags.DataTypeMask_, ImGuiColorEditFlags.InputMask_, ImGuiColorEditFlags.HDR, ImGuiColorEditFlags.AlphaMask_, ImGuiColorEditFlags.NoOptions, ImGuiColorEditFlags.NoTooltip, ImGuiColorEditFlags.NoSmallPreview)
local sub_flags = bit32.bor(bit32.band(flags, sub_flags_to_forward), ImGuiColorEditFlags.NoPicker)
if bit32.band(flags, ImGuiColorEditFlags.DisplayRGB) ~= 0 or bit32.band(flags, ImGuiColorEditFlags.DisplayMask_) == 0 then
if ImGui.ColorEdit4("##rgb", col, bit32.bor(sub_flags, ImGuiColorEditFlags.DisplayRGB)) then
-- FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget.
-- For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050)
value_changed_fix_hue_wrap = (g.ActiveId ~= 0 and not g.ActiveIdAllowOverlap)
value_changed = true
end
end
if bit32.band(flags, ImGuiColorEditFlags.DisplayHSV) ~= 0 or bit32.band(flags, ImGuiColorEditFlags.DisplayMask_) == 0 then
if ImGui.ColorEdit4("##hsv", col, bit32.bor(sub_flags, ImGuiColorEditFlags.DisplayHSV)) then
value_changed = true
end
end
if bit32.band(flags, ImGuiColorEditFlags.DisplayHex) ~= 0 or bit32.band(flags, ImGuiColorEditFlags.DisplayMask_) == 0 then
if ImGui.ColorEdit4("##hex", col, bit32.bor(sub_flags, ImGuiColorEditFlags.DisplayHex)) then
value_changed = true
end
end
ImGui.PopItemWidth()
end
-- Try to cancel hue wrap (after ColorEdit4 call), if any
if value_changed_fix_hue_wrap and bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 then
local new_H, new_S, new_V = ImGui.ColorConvertRGBtoHSV(col[1], col[2], col[3]) -- Lua 1-based indexing
if new_H <= 0 and H > 0 then
if new_V <= 0 and V ~= new_V then
col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, S, (new_V <= 0) and (V * 0.5) or new_V)
elseif new_S <= 0 then
col[1], col[2], col[3] = ImGui.ColorConvertHSVtoRGB(H, (new_S <= 0) and (S * 0.5) or new_S, new_V)
end
end
end
if value_changed then
if bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 then
R = col[1]
G = col[2]
B = col[3]
H, S, V = ImGui.ColorConvertRGBtoHSV(R, G, B)
H, S, V = ColorEditRestoreHS(col, H, S, V) -- Fix local Hue as display below will use it immediately.
elseif bit32.band(flags, ImGuiColorEditFlags.InputHSV) ~= 0 then
H = col[1]
S = col[2]
V = col[3]
R, G, B = ImGui.ColorConvertHSVtoRGB(H, S, V)
end
end
local style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha)
local col_black = IM_COL32(0, 0, 0, style_alpha8)
local col_white = IM_COL32(255, 255, 255, style_alpha8)
local col_midgrey = IM_COL32(128, 128, 128, style_alpha8)
local col_hues = { IM_COL32(255, 0, 0, style_alpha8), IM_COL32(255, 255, 0, style_alpha8), IM_COL32(0, 255, 0, style_alpha8), IM_COL32(0, 255, 255, style_alpha8), IM_COL32(0, 0, 255, style_alpha8), IM_COL32(255, 0, 255, style_alpha8), IM_COL32(255, 0, 0, style_alpha8) }
local hue_color_f = ImVec4(1, 1, 1, style.Alpha)
hue_color_f.x, hue_color_f.y, hue_color_f.z = ImGui.ColorConvertHSVtoRGB(H, 1, 1)
local hue_color32 = ImGui.ColorConvertFloat4ToU32(hue_color_f)
local user_col32_striped_of_alpha = ImGui.ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)) -- Important: this is still including the main rendering/style alpha!!
local sv_cursor_pos = ImVec2()
if bit32.band(flags, ImGuiColorEditFlags.PickerHueWheel) ~= 0 then
-- Render Hue Wheel
local aeps = 0.5 / wheel_r_outer -- Half a pixel arc length in radians (2pi cancels out).
local segment_per_arc = ImMax(4, math.floor(wheel_r_outer / 12))
for n = 1, 6 do
local a0 = (n - 1) / 6.0 * 2.0 * IM_PI - aeps
local a1 = n / 6.0 * 2.0 * IM_PI + aeps
local vert_start_idx = draw_list.VtxBuffer.Size + 1
draw_list:PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer) * 0.5, a0, a1, segment_per_arc)
draw_list:PathStroke(col_white, wheel_thickness)
local vert_end_idx = draw_list.VtxBuffer.Size + 1
-- Paint colors over existing vertices
local gradient_p0 = ImVec2(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner)
local gradient_p1 = ImVec2(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner)
ImGui.ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n + 1])
end
-- Render Cursor + preview on Hue Wheel
local cos_hue_angle = ImCos(H * 2.0 * IM_PI)
local sin_hue_angle = ImSin(H * 2.0 * IM_PI)
local hue_cursor_pos = ImVec2(wheel_center.x + cos_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5, wheel_center.y + sin_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5)
local hue_cursor_rad = value_changed_h and (wheel_thickness * 0.65) or (wheel_thickness * 0.55)
local hue_cursor_segments = draw_list:_CalcCircleAutoSegmentCount(hue_cursor_rad) -- Lock segment count so the +1 one matches others.
draw_list:AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments)
draw_list:AddCircle(hue_cursor_pos, hue_cursor_rad + 1, col_midgrey, hue_cursor_segments)
draw_list:AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments)
if triangle_rotate == false then
cos_hue_angle = 1.0
sin_hue_angle = 0.0
end
-- Render SV triangle (rotated according to hue)
local tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle)
local trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle)
local trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle)
local uv_white = ImGui.GetFontTexUvWhitePixel()
draw_list:PrimReserve(3, 3)
draw_list:PrimVtx(tra, uv_white, hue_color32)
draw_list:PrimVtx(trb, uv_white, col_black)
draw_list:PrimVtx(trc, uv_white, col_white)
draw_list:AddTriangle(tra, trb, trc, col_midgrey, 1.5)
sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V))
elseif bit32.band(flags, ImGuiColorEditFlags.PickerHueBar) ~= 0 then
-- Render SV Square
draw_list:AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white)
draw_list:AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black)
ImGui.RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0)
-- Sneakily prevent the circle to stick out too much
sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2)
sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2)
-- Render Hue Bar
for i = 1, 6 do
draw_list:AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + (i - 1) * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + i * (sv_picker_size / 6)), col_hues[i], col_hues[i], col_hues[i + 1], col_hues[i + 1])
end
local bar0_line_y = IM_ROUND(picker_pos.y + H * sv_picker_size)
ImGui.RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0)
RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0, style.Alpha)
end
-- Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
local sv_cursor_rad = value_changed_sv and (wheel_thickness * 0.55) or (wheel_thickness * 0.40)
local sv_cursor_segments = draw_list:_CalcCircleAutoSegmentCount(sv_cursor_rad) -- Lock segment count so the +1 one matches others.
draw_list:AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, sv_cursor_segments)
draw_list:AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, sv_cursor_segments)
draw_list:AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, sv_cursor_segments)
-- Render alpha bar
if alpha_bar then
local alpha = ImSaturate(col[4])
local bar1_bb = ImRect(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size)
ImGui.RenderColorRectWithAlphaCheckerboard(draw_list, bar1_bb.Min, bar1_bb.Max, 0, bar1_bb:GetWidth() / 2.0, ImVec2(0.0, 0.0))
draw_list:AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, user_col32_striped_of_alpha, user_col32_striped_of_alpha, bit32.band(user_col32_striped_of_alpha, bit32.bnot(IM_COL32_A_MASK)), bit32.band(user_col32_striped_of_alpha, bit32.bnot(IM_COL32_A_MASK)))
local bar1_line_y = IM_ROUND(picker_pos.y + (1.0 - alpha) * sv_picker_size)
ImGui.RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0)
RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0, style.Alpha)
end
ImGui.EndGroup()
if value_changed then
for i = 1, components do
if backup_initial_col[i] ~= col[i] then
break
end
if i == components then
value_changed = false
end
end
end
if value_changed and g.LastItemData.ID ~= 0 then -- In case of ID collision, the second EndGroup() won't catch g.ActiveId
ImGui.MarkItemEdited(g.LastItemData.ID)
end
if set_current_color_edit_id then
g.ColorEditCurrentID = 0
end
ImGui.PopID()
return value_changed
end
end
--- @param desc_id string
--- @param col ImVec4
--- @param flags? ImGuiColorEditFlags
--- @param size_arg? ImVec2
function ImGui.ColorButton(desc_id, col, flags, size_arg)
if flags == nil then flags = 0 end
if size_arg == nil then size_arg = ImVec2(0, 0) end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local id = window:GetID(desc_id)
local default_size = ImGui.GetFrameHeight()
local size = ImVec2(size_arg.x == 0.0 and default_size or size_arg.x, size_arg.y == 0.0 and default_size or size_arg.y)
local bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + size)
ImGui.ItemSize(bb, (size.y >= default_size) and g.Style.FramePadding.y or 0.0)
if not ImGui.ItemAdd(bb, id) then
return false
end
local pressed, hovered, _ = ImGui.ButtonBehavior(bb, id)
if bit32.band(flags, bit32.bor(ImGuiColorEditFlags.NoAlpha, ImGuiColorEditFlags.AlphaOpaque)) ~= 0 then
flags = bit32.band(flags, bit32.bnot(bit32.bor(ImGuiColorEditFlags.AlphaNoBg, ImGuiColorEditFlags.AlphaPreviewHalf)))
end
local col_rgb = ImVec4(col.x, col.y, col.z, col.w)
if bit32.band(flags, ImGuiColorEditFlags.InputHSV) ~= 0 then
col_rgb.x, col_rgb.y, col_rgb.z = ImGui.ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z)
end
local col_rgb_without_alpha = ImVec4(col_rgb.x, col_rgb.y, col_rgb.z, 1.0)
local grid_step = ImMin(size.x, size.y) / 2.99
local rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5)
local bb_inner = ImRect()
ImRect_Copy(bb_inner, bb)
local off = 0.0
if bit32.band(flags, ImGuiColorEditFlags.NoBorder) == 0 then
off = -0.75
bb_inner:Expand(off)
end
if bit32.band(flags, ImGuiColorEditFlags.AlphaPreviewHalf) ~= 0 and col_rgb.w < 1.0 then
local mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5)
if bit32.band(flags, ImGuiColorEditFlags.AlphaNoBg) == 0 then
ImGui.RenderColorRectWithAlphaCheckerboard(window.DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, ImGui.GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags.RoundCornersRight)
else
window.DrawList:AddRectFilled(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, ImGui.GetColorU32(col_rgb), rounding, ImDrawFlags.RoundCornersRight)
end
window.DrawList:AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), ImGui.GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags.RoundCornersLeft)
else
local col_source = (bit32.band(flags, ImGuiColorEditFlags.AlphaOpaque) ~= 0) and col_rgb_without_alpha or col_rgb
if col_source.w < 1.0 and bit32.band(flags, ImGuiColorEditFlags.AlphaNoBg) == 0 then
ImGui.RenderColorRectWithAlphaCheckerboard(window.DrawList, bb_inner.Min, bb_inner.Max, ImGui.GetColorU32(col_source), grid_step, ImVec2(off, off), rounding)
else
window.DrawList:AddRectFilled(bb_inner.Min, bb_inner.Max, ImGui.GetColorU32(col_source), rounding)
end
end
ImGui.RenderNavCursor(bb, id)
if bit32.band(flags, ImGuiColorEditFlags.NoBorder) == 0 then
if g.Style.FrameBorderSize > 0.0 then
ImGui.RenderFrameBorder(bb.Min, bb.Max, rounding)
else
window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), rounding)
end
end
-- Drag and Drop Source
-- NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test.
-- if g.ActiveId == id and bit32.band(flags, ImGuiColorEditFlags.NoDragDrop) == 0 and ImGui.BeginDragDropSource() then
-- if bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0 then
-- ImGui.SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, col_rgb, ImGuiCond.Once)
-- else
-- ImGui.SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, col_rgb, ImGuiCond.Once)
-- end
-- ImGui.ColorButton(desc_id, col, flags)
-- ImGui.SameLine()
-- ImGui.TextEx("Color")
-- ImGui.EndDragDropSource()
-- end
-- Tooltip
if bit32.band(flags, ImGuiColorEditFlags.NoTooltip) == 0 and hovered and ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip) then
ImGui.ColorTooltip(desc_id, col, bit32.band(flags, bit32.bor(ImGuiColorEditFlags.InputMask_, ImGuiColorEditFlags.AlphaMask_)))
end
return pressed
end
--- @param text? string
--- @param col ImVec4
--- @param flags ImGuiColorEditFlags
function ImGui.ColorTooltip(text, col, flags)
local g = GImGui
if not ImGui.BeginTooltipEx(ImGuiTooltipFlags.OverridePrevious, ImGuiWindowFlags.None) then
return
end
local text_end = text and ImGui.FindRenderedTextEnd(text, nil) or 1
if text_end > 1 then
--- @cast text string
ImGui.TextEx(text, text_end)
ImGui.Separator()
end
local sz = ImVec2(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2)
local cf = ImVec4(col.x, col.y, col.z, (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0) and 1.0 or col.w)
local cr = IM_F32_TO_INT8_SAT(col.x)
local cg = IM_F32_TO_INT8_SAT(col.y)
local cb = IM_F32_TO_INT8_SAT(col.z)
local ca = (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0) and 255 or IM_F32_TO_INT8_SAT(col.w)
local flags_to_forward = bit32.bor(ImGuiColorEditFlags.InputMask_, ImGuiColorEditFlags.AlphaMask_)
ImGui.ColorButton("##preview", cf, bit32.bor(bit32.band(flags, flags_to_forward), ImGuiColorEditFlags.NoTooltip), sz)
ImGui.SameLine()
if bit32.band(flags, ImGuiColorEditFlags.InputRGB) ~= 0 or bit32.band(flags, ImGuiColorEditFlags.InputMask_) == 0 then
if bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0 then
ImGui.Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col.x, col.y, col.z)
else
ImGui.Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col.x, col.y, col.z, col.w)
end
elseif bit32.band(flags, ImGuiColorEditFlags.InputHSV) ~= 0 then
if bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0 then
ImGui.Text("H: %.3f, S: %.3f, V: %.3f", col.x, col.y, col.z)
else
ImGui.Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col.x, col.y, col.z, col.w)
end
end
ImGui.EndTooltip()
end
--- @param col float[]
--- @param flags ImGuiColorEditFlags
function ImGui.ColorEditOptionsPopup(col, flags)
local allow_opt_inputs = bit32.band(flags, ImGuiColorEditFlags.DisplayMask_) == 0
local allow_opt_datatype = bit32.band(flags, ImGuiColorEditFlags.DataTypeMask_) == 0
if (not allow_opt_inputs and not allow_opt_datatype) or not ImGui.BeginPopup("context") then
return
end
local g = GImGui
ImGui.PushItemFlag(ImGuiItemFlags.NoMarkEdited, true)
local opts = g.IO.ConfigColorEditFlags
if allow_opt_inputs then
if ImGui.RadioButtonEx("RGB", bit32.band(opts, ImGuiColorEditFlags.DisplayRGB) ~= 0) then
opts = bit32.bor(bit32.band(opts, bit32.bnot(ImGuiColorEditFlags.DisplayMask_)), ImGuiColorEditFlags.DisplayRGB)
end
if ImGui.RadioButtonEx("HSV", bit32.band(opts, ImGuiColorEditFlags.DisplayHSV) ~= 0) then
opts = bit32.bor(bit32.band(opts, bit32.bnot(ImGuiColorEditFlags.DisplayMask_)), ImGuiColorEditFlags.DisplayHSV)
end
if ImGui.RadioButtonEx("Hex", bit32.band(opts, ImGuiColorEditFlags.DisplayHex) ~= 0) then
opts = bit32.bor(bit32.band(opts, bit32.bnot(ImGuiColorEditFlags.DisplayMask_)), ImGuiColorEditFlags.DisplayHex)
end
end
if allow_opt_datatype then
if allow_opt_inputs then ImGui.Separator() end
if ImGui.RadioButtonEx("0..255", bit32.band(opts, ImGuiColorEditFlags.Uint8) ~= 0) then
opts = bit32.bor(bit32.band(opts, bit32.bnot(ImGuiColorEditFlags.DataTypeMask_)), ImGuiColorEditFlags.Uint8)
end
if ImGui.RadioButtonEx("0.00..1.00", bit32.band(opts, ImGuiColorEditFlags.Float) ~= 0) then
opts = bit32.bor(bit32.band(opts, bit32.bnot(ImGuiColorEditFlags.DataTypeMask_)), ImGuiColorEditFlags.Float)
end
end
if allow_opt_inputs or allow_opt_datatype then
ImGui.Separator()
end
if ImGui.Button("Copy as..", ImVec2(-1, 0)) then
ImGui.OpenPopup("Copy")
end
if ImGui.BeginPopup("Copy") then
local cr = IM_F32_TO_INT8_SAT(col[1])
local cg = IM_F32_TO_INT8_SAT(col[2])
local cb = IM_F32_TO_INT8_SAT(col[3])
local ca = (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0) and 255 or IM_F32_TO_INT8_SAT(col[4])
local buf1 = ImFormatString("(%.3ff, %.3ff, %.3ff, %.3ff)", col[1], col[2], col[3], (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) ~= 0) and 1.0 or col[4])
if ImGui.Selectable(buf1) then
ImGui.SetClipboardText(buf1)
end
local buf2 = ImFormatString("(%d,%d,%d,%d)", cr, cg, cb, ca)
if ImGui.Selectable(buf2) then
ImGui.SetClipboardText(buf2)
end
local buf3 = ImFormatString("#%02X%02X%02X", cr, cg, cb)
if ImGui.Selectable(buf3) then
ImGui.SetClipboardText(buf3)
end
if bit32.band(flags, ImGuiColorEditFlags.NoAlpha) == 0 then
local buf4 = ImFormatString("#%02X%02X%02X%02X", cr, cg, cb, ca)
if ImGui.Selectable(buf4) then
ImGui.SetClipboardText(buf4)
end
end
ImGui.EndPopup()
end
g.IO.ConfigColorEditFlags = opts
ImGui.PopItemFlag()
ImGui.EndPopup()
end
--- @param ref_col float[]
--- @param flags ImGuiColorEditFlags
function ImGui.ColorPickerOptionsPopup(ref_col, flags)
local allow_opt_picker = bit32.band(flags, ImGuiColorEditFlags.PickerMask_) == 0
local allow_opt_alpha_bar = (bit32.band(flags, ImGuiColorEditFlags.NoAlpha) == 0) and (bit32.band(flags, ImGuiColorEditFlags.AlphaBar) == 0)
if (not allow_opt_picker and not allow_opt_alpha_bar) or not ImGui.BeginPopup("context") then
return
end
local g = GImGui
ImGui.PushItemFlag(ImGuiItemFlags.NoMarkEdited, true)
if allow_opt_picker then
local picker_size = ImVec2(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui.GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0)) -- FIXME: Picker size copied from main picker function
ImGui.PushItemWidth(picker_size.x)
for picker_type = 0, 1 do
if picker_type > 0 then
ImGui.Separator()
end
ImGui.PushID(picker_type)
local picker_flags = bit32.bor(ImGuiColorEditFlags.NoInputs, ImGuiColorEditFlags.NoOptions, ImGuiColorEditFlags.NoLabel, ImGuiColorEditFlags.NoSidePreview, bit32.band(flags, ImGuiColorEditFlags.NoAlpha))
if picker_type == 0 then
picker_flags = bit32.bor(picker_flags, ImGuiColorEditFlags.PickerHueBar)
end
if picker_type == 1 then
picker_flags = bit32.bor(picker_flags, ImGuiColorEditFlags.PickerHueWheel)
end
local backup_pos = ImGui.GetCursorScreenPos()
-- By default, Selectable() is closing popup
if ImGui.Selectable("##selectable", false, 0, picker_size) then
g.IO.ConfigColorEditFlags = bit32.bor(bit32.band(g.IO.ConfigColorEditFlags, bit32.bnot(ImGuiColorEditFlags.PickerMask_)), bit32.band(picker_flags, ImGuiColorEditFlags.PickerMask_))
end
ImGui.SetCursorScreenPos(backup_pos)
local previewing_ref_col = ImVec4()
for i = 1, (bit32.band(picker_flags, ImGuiColorEditFlags.NoAlpha) ~= 0 and 3 or 4) do
previewing_ref_col[i] = ref_col[i]
end
ImGui.ColorPicker4("##previewing_picker", previewing_ref_col, picker_flags)
ImGui.PopID()
end
ImGui.PopItemWidth()
end
if allow_opt_alpha_bar then
if allow_opt_picker then
ImGui.Separator()
end
_, g.IO.ConfigColorEditFlags = ImGui.CheckboxFlags("Alpha Bar", g.IO.ConfigColorEditFlags, ImGuiColorEditFlags.AlphaBar)
end
ImGui.PopItemFlag()
ImGui.EndPopup()
end
----------------------------------------------------------------
-- [SECTION] TREES
----------------------------------------------------------------
--- @param label string
function ImGui.TreeNode(label)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local id = window:GetID(label)
return ImGui.TreeNodeBehavior(id, ImGuiTreeNodeFlags.None, label, nil)
end
--- @param storage_id ImGuiID
function ImGui.TreeNodeGetOpen(storage_id)
local g = GImGui
local storage = g.CurrentWindow.DC.StateStorage
return (storage[storage_id]) and true or false
end
--- @param storage_id ImGuiID
--- @param is_open bool
function ImGui.TreeNodeSetOpen(storage_id, is_open)
local g = GImGui
local storage = g.CurrentWindow.DC.StateStorage
storage[storage_id] = is_open
end
--- @param storage_id ImGuiID
--- @param flags ImGuiTreeNodeFlags
function ImGui.TreeNodeUpdateNextOpen(storage_id, flags)
if bit32.band(flags, ImGuiTreeNodeFlags.Leaf) ~= 0 then
return true
end
local g = GImGui
local window = g.CurrentWindow
local storage = window.DC.StateStorage
local is_open
if bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasOpen) ~= 0 then
if bit32.band(g.NextItemData.OpenCond, ImGuiCond.Always) ~= 0 then
is_open = g.NextItemData.OpenVal
ImGui.TreeNodeSetOpen(storage_id, is_open)
else
local stored_value = storage[storage_id]
if stored_value == nil then
is_open = g.NextItemData.OpenVal
ImGui.TreeNodeSetOpen(storage_id, is_open)
else
is_open = stored_value ~= 0
end
end
else
is_open = (storage[storage_id] == nil) and (bit32.band(flags, ImGuiTreeNodeFlags.DefaultOpen) ~= 0) or storage[storage_id]
end
if g.LogEnabled and bit32.band(flags, ImGuiTreeNodeFlags.NoAutoOpenOnLog) == 0 and (window.DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand then
is_open = true
end
return is_open
end
--- @param flags ImGuiTreeNodeFlags
--- @param x1 float
local function TreeNodeStoreStackData(flags, x1)
local g = GImGui
local window = g.CurrentWindow
g.TreeNodeStack:resize(g.TreeNodeStack.Size + 1)
local tree_node_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size]
tree_node_data.ID = g.LastItemData.ID
tree_node_data.TreeFlags = flags
tree_node_data.ItemFlags = g.LastItemData.ItemFlags
ImRect_Copy(tree_node_data.NavRect, g.LastItemData.NavRect)
local draw_lines = bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes)) ~= 0
tree_node_data.DrawLinesX1 = draw_lines and (x1 + g.FontSize * 0.5 + g.Style.FramePadding.x) or FLT_MAX
tree_node_data.DrawLinesTableColumn = (draw_lines and g.CurrentTable) and g.CurrentTable.CurrentColumn or -1
tree_node_data.DrawLinesToNodesY2 = -FLT_MAX
window.DC.TreeHasStackDataDepthMask = window.DC.TreeHasStackDataDepthMask or bit32.lshift(1, window.DC.TreeDepth)
if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesToNodes) ~= 0 then
window.DC.TreeRecordsClippedNodesY2Mask = window.DC.TreeRecordsClippedNodesY2Mask or bit32.lshift(1, window.DC.TreeDepth)
end
end
--- @param id ImGuiID
--- @param flags ImGuiTreeNodeFlags
--- @param label string
--- @param label_end? int
function ImGui.TreeNodeBehavior(id, flags, label, label_end)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local style = g.Style
local display_frame = bit32.band(flags, ImGuiTreeNodeFlags.Framed) ~= 0
local use_frame_padding = display_frame or (bit32.band(flags, ImGuiTreeNodeFlags.FramePadding) ~= 0)
local padding
if use_frame_padding then
padding = style.FramePadding
else
padding = ImVec2(style.FramePadding.x, ImMin(window.DC.CurrLineTextBaseOffset, style.FramePadding.y))
end
if label_end == nil then
label_end = ImGui.FindRenderedTextEnd(label)
end
local label_size = ImGui.CalcTextSize(label, label_end, false)
local text_offset_x = g.FontSize + (display_frame and (padding.x * 3) or (padding.x * 2))
local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset
local text_width = g.FontSize + label_size.x + padding.x * 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_label = bit32.band(flags, ImGuiTreeNodeFlags.LabelSpanAllColumns) ~= 0 and (g.CurrentTable ~= nil)
local frame_bb = ImRect()
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.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.y = window.DC.CursorPos.y + (text_offset_y - padding.y) + frame_height
if display_frame then
local outer_extend = IM_TRUNC(window.WindowPadding.x * 0.5)
frame_bb.Min.x = frame_bb.Min.x - outer_extend
frame_bb.Max.x = frame_bb.Max.x + outer_extend
end
local text_pos = ImVec2(window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y)
ImGui.ItemSize(ImVec2(text_width, frame_height), padding.y)
local interact_bb = ImRect()
ImRect_Copy(interact_bb, frame_bb)
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)
end
local storage_id = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasStorageID) ~= 0) and g.NextItemData.StorageId or id
local is_open = ImGui.TreeNodeUpdateNextOpen(storage_id, flags)
local is_visible
if span_all_columns or span_all_columns_label then
local backup_clip_rect_min_x = window.ClipRect.Min.x
local backup_clip_rect_max_x = window.ClipRect.Max.x
window.ClipRect.Min.x = window.ParentWorkRect.Min.x
window.ClipRect.Max.x = window.ParentWorkRect.Max.x
is_visible = ImGui.ItemAdd(interact_bb, id)
window.ClipRect.Min.x = backup_clip_rect_min_x
window.ClipRect.Max.x = backup_clip_rect_max_x
else
is_visible = ImGui.ItemAdd(interact_bb, id)
end
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasDisplayRect)
ImRect_Copy(g.LastItemData.DisplayRect, frame_bb)
local store_tree_node_stack_data = false
if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesMask_) == 0 then
flags = bit32.bor(flags, g.Style.TreeLinesFlags)
end
local draw_tree_lines = (bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes)) ~= 0) and (frame_bb.Min.y < window.ClipRect.Max.y) and (g.Style.TreeLinesSize > 0.0)
if bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then
store_tree_node_stack_data = draw_tree_lines
if bit32.band(flags, ImGuiTreeNodeFlags.NavLeftJumpsToParent) ~= 0 and not g.NavIdIsAlive then
if g.NavMoveDir == ImGuiDir.Left and g.NavWindow == window and ImGui.NavMoveRequestButNoResultYet() then
store_tree_node_stack_data = true
end
end
end
local is_leaf = bit32.band(flags, ImGuiTreeNodeFlags.Leaf) ~= 0
if not is_visible then
if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesToNodes) ~= 0 and bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.lshift(1, (window.DC.TreeDepth - 1))) ~= 0 then
local parent_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size]
parent_data.DrawLinesToNodesY2 = ImMax(parent_data.DrawLinesToNodesY2, window.DC.CursorPos.y)
if frame_bb.Min.y >= window.ClipRect.Max.y then
window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(bit32.lshift(1, (window.DC.TreeDepth - 1))))
end
end
if is_open and store_tree_node_stack_data then
ImGui.TreeNodeStoreStackData(flags, text_pos.x - text_offset_x)
end
if is_open and bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then
ImGui.TreePushOverrideID(id)
end
-- IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0))
return is_open
end
if span_all_columns or span_all_columns_label then
ImGui.TablePushBackgroundChannel()
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasClipRect)
ImRect_Copy(g.LastItemData.ClipRect, window.ClipRect)
end
local button_flags = ImGuiTreeNodeFlags.None
if bit32.band(flags, ImGuiTreeNodeFlags.AllowOverlap) ~= 0 or bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowOverlap) ~= 0 then
button_flags = bit32.bor(button_flags, ImGuiButtonFlags.AllowOverlap)
end
if not is_leaf then
button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnDragDropHold)
end
local arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x
local arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0) + style.TouchExtraPadding.x
local is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 and g.IO.MousePos.x < arrow_hit_x2)
local is_multi_select = bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0
if is_multi_select then
flags = bit32.bor(flags, (bit32.band(flags, ImGuiTreeNodeFlags.OpenOnMask_) == 0) and bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick) or ImGuiTreeNodeFlags.OpenOnArrow)
end
if is_mouse_x_over_arrow then
button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick)
elseif bit32.band(flags, ImGuiTreeNodeFlags.OpenOnDoubleClick) ~= 0 then
button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClickRelease, ImGuiButtonFlags.PressedOnDoubleClick)
else
button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClickRelease)
end
if bit32.band(flags, ImGuiTreeNodeFlags.NoNavFocus) ~= 0 then
button_flags = bit32.bor(button_flags, ImGuiButtonFlags.NoNavFocus)
end
local selected = bit32.band(flags, ImGuiTreeNodeFlags.Selected) ~= 0
local was_selected = selected
if is_multi_select then
selected, button_flags = ImGui.MultiSelectItemHeader(id, selected, button_flags)
if is_mouse_x_over_arrow then
button_flags = bit32.band(bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick), bit32.bnot(ImGuiButtonFlags.PressedOnClickRelease))
end
else
if window ~= g.HoveredWindow or not is_mouse_x_over_arrow then
button_flags = bit32.bor(button_flags, ImGuiButtonFlags.NoKeyModsAllowed)
end
end
local pressed, hovered, held = ImGui.ButtonBehavior(interact_bb, id, button_flags)
local toggled = false
if not is_leaf then
if pressed and g.DragDropHoldJustPressedId ~= id then
if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnMask_) == 0 or (g.NavActivateId == id and not is_multi_select) then
toggled = true
end
if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnArrow) ~= 0 then
toggled = toggled or (is_mouse_x_over_arrow and not g.NavHighlightItemUnderNav)
end
if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnDoubleClick) ~= 0 and g.IO.MouseClickedCount[0] == 2 then
toggled = true
end
elseif pressed and g.DragDropHoldJustPressedId == id then
IM_ASSERT(bit32.band(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) ~= 0)
if not is_open then
toggled = true
else
pressed = false
end
end
if g.NavId == id and g.NavMoveDir == ImGuiDir.Left and is_open then
toggled = true
ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X)
ImGui.NavMoveRequestCancel()
end
if g.NavId == id and g.NavMoveDir == ImGuiDir.Right and not is_open then
toggled = true
ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X)
ImGui.NavMoveRequestCancel()
end
if toggled then
is_open = not is_open
window.DC.StateStorage[storage_id] = is_open
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledOpen)
end
end
if is_multi_select then
local pressed_copy = pressed and not toggled
selected, pressed_copy = ImGui.MultiSelectItemFooter(id, selected, pressed_copy)
if pressed then
ImGui.SetNavID(id, window.DC.NavLayerCurrent, g.CurrentFocusScopeId, interact_bb)
end
end
if selected ~= was_selected then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledSelection)
end
-- Render
do
local text_col = ImGui.GetColorU32(ImGuiCol.Text)
local nav_render_cursor_flags = ImGuiNavRenderCursorFlags.Compact
if is_multi_select then
nav_render_cursor_flags = bit32.bor(nav_render_cursor_flags, ImGuiNavRenderCursorFlags.AlwaysDraw)
end
if display_frame then
local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header))
ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding)
ImGui.RenderNavCursor(frame_bb, id, nav_render_cursor_flags)
if span_all_columns and not span_all_columns_label then
ImGui.TablePopBackgroundChannel()
end
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)
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)
else
text_pos.x = text_pos.x - (text_offset_x - padding.x)
end
if bit32.band(flags, ImGuiTreeNodeFlags.ClipLabelForTrailingButton) ~= 0 then
frame_bb.Max.x = frame_bb.Max.x - (g.FontSize + style.FramePadding.x)
end
-- if g.LogEnabled then
-- ImGui.LogSetNextTextDecoration("###", "###")
-- end
else
if hovered or selected then
local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header))
ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false, 0.0)
end
ImGui.RenderNavCursor(frame_bb, id, nav_render_cursor_flags, 0.0)
if span_all_columns and not span_all_columns_label then
ImGui.TablePopBackgroundChannel()
end
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)
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)
end
-- if g.LogEnabled then
-- ImGui.LogSetNextTextDecoration(">", nil)
-- end
end
if draw_tree_lines then
ImGui.TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5))
end
if display_frame then
ImGui.RenderTextClipped(text_pos, frame_bb.Max, label, label_end, label_size)
else
ImGui.RenderText(text_pos, label, 1, label_end, false)
end
if span_all_columns_label then
ImGui.TablePopBackgroundChannel()
end
end
if is_open and store_tree_node_stack_data then
TreeNodeStoreStackData(flags, text_pos.x - text_offset_x)
end
if is_open and bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then
ImGui.TreePushOverrideID(id)
end
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
return is_open
end
--- @param target_pos ImVec2
function ImGui.TreeNodeDrawLineToChildNode(target_pos)
local g = GImGui
local window = g.CurrentWindow
if window.DC.TreeDepth == 0 or bit32.band(window.DC.TreeHasStackDataDepthMask, bit32.lshift(1, window.DC.TreeDepth - 1)) == 0 then
return
end
local parent_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size]
local x1 = ImTrunc(parent_data.DrawLinesX1)
local x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x)
local y = ImTrunc(target_pos.y)
local rounding = (g.Style.TreeLinesRounding > 0.0) and ImMin(x2 - x1, g.Style.TreeLinesRounding) or 0.0
parent_data.DrawLinesToNodesY2 = ImMax(parent_data.DrawLinesToNodesY2, y - rounding)
if x1 >= x2 then
return
end
if rounding > 0.0 then
x1 = x1 + 0.5 + rounding
window.DrawList:PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3)
if x1 < x2 then
window.DrawList:PathLineTo(ImVec2(x2, y))
end
window.DrawList:PathStroke(ImGui.GetColorU32(ImGuiCol.TreeLines), g.Style.TreeLinesSize)
else
window.DrawList:AddLineH(x1, x2, y, ImGui.GetColorU32(ImGuiCol.TreeLines), g.Style.TreeLinesSize)
end
end
--- @param id ImGuiID
function ImGui.TreePushOverrideID(id)
local g = GImGui
local window = g.CurrentWindow
ImGui.Indent()
window.DC.TreeDepth = window.DC.TreeDepth + 1
ImGui.PushOverrideID(id)
end
function ImGui.TreePop()
local g = GImGui
local window = g.CurrentWindow
ImGui.Unindent()
window.DC.TreeDepth = window.DC.TreeDepth - 1
local tree_depth_mask = bit32.lshift(1, window.DC.TreeDepth)
if bit32.band(window.DC.TreeHasStackDataDepthMask, tree_depth_mask) ~= 0 then
local data = g.TreeNodeStack.Data[g.TreeNodeStack.Size]
IM_ASSERT(data.ID == window.IDStack:back())
if bit32.band(data.TreeFlags, ImGuiTreeNodeFlags.NavLeftJumpsToParent) ~= 0 then
if g.NavIdIsAlive and g.NavMoveDir == ImGuiDir.Left and g.NavWindow == window and ImGui.NavMoveRequestButNoResultYet() then
ImGui.NavMoveRequestResolveWithPastTreeNode(g.NavMoveResultLocal, data)
end
end
if data.DrawLinesX1 ~= FLT_MAX and window.DC.CursorPos.y >= window.ClipRect.Min.y then
ImGui.TreeNodeDrawLineToTreePop(data)
end
g.TreeNodeStack:pop_back()
window.DC.TreeHasStackDataDepthMask = bit32.band(window.DC.TreeHasStackDataDepthMask, bit32.bnot(tree_depth_mask))
window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(tree_depth_mask))
end
IM_ASSERT(window.IDStack.Size > 1)
ImGui.PopID()
end
--- @param is_open bool
--- @param cond? ImGuiCond
function ImGui.SetNextItemOpen(is_open, cond)
if cond == nil then cond = 0 end
local g = GImGui
if g.CurrentWindow.SkipItems then
return
end
g.NextItemData.HasFlags = bit32.bor(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasOpen)
g.NextItemData.OpenVal = is_open
g.NextItemData.OpenCond = (ImU8)((cond ~= 0) and cond or ImGuiCond.Always)
end
--- @param label string
--- @param flags? ImGuiTreeNodeFlags
function ImGui.CollapsingHeader(label, flags)
if flags == nil then flags = 0 end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local id = window:GetID(label)
return ImGui.TreeNodeBehavior(id, bit32.bor(flags, ImGuiTreeNodeFlags.CollapsingHeader), label)
end
----------------------------------------------------------------
-- [SECTION] SELECTABLE
----------------------------------------------------------------
-- - Selectable()
----------------------------------------------------------------
-- Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image.
-- But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id.
-- With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags.
-- FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported.
--- @param label string
--- @param selected? bool
--- @param flags? ImGuiSelectableFlags
--- @param size_arg? any
--- @return bool is_pressed
--- @return bool is_selected # Updated `selected`
function ImGui.Selectable(label, selected, flags, size_arg)
if selected == nil then selected = false end
if flags == nil then flags = 0 end
if size_arg == nil then size_arg = ImVec2(0, 0) end
local window = ImGui.GetCurrentWindow()
if (window.SkipItems) then
return false, selected
end
local g = GImGui
local style = g.Style
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local size = ImVec2((size_arg.x ~= 0.0) and size_arg.x or label_size.x, (size_arg.y ~= 0.0) and size_arg.y or label_size.y)
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
pos.y = pos.y + window.DC.CurrLineTextBaseOffset
ImGui.ItemSize(size, 0.0)
-- Fill horizontal space
-- We don't support (size < 0.0) in Selectable() because the ItemSpacing extension would make explicitly right-aligned sizes not visibly match other widgets.
local span_all_columns = bit32.band(flags, ImGuiSelectableFlags.SpanAllColumns) ~= 0
local min_x = span_all_columns and window.ParentWorkRect.Min.x or pos.x
local max_x = span_all_columns and window.ParentWorkRect.Max.x or window.WorkRect.Max.x
if size_arg.x == 0.0 or bit32.band(flags, ImGuiSelectableFlags.SpanAvailWidth) ~= 0 then
size.x = ImMax(label_size.x, max_x - min_x)
end
-- Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
-- FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos.
local bb = ImRect(min_x, pos.y, min_x + size.x, pos.y + size.y)
if bit32.band(flags, ImGuiSelectableFlags.NoPadWithHalfSpacing) == 0 then
local spacing_x = span_all_columns and 0.0 or style.ItemSpacing.x
local spacing_y = style.ItemSpacing.y
local spacing_L = IM_TRUNC(spacing_x * 0.50)
local spacing_U = IM_TRUNC(spacing_y * 0.50)
bb.Min.x = bb.Min.x - spacing_L
bb.Min.y = bb.Min.y - spacing_U
bb.Max.x = bb.Max.x + (spacing_x - spacing_L)
bb.Max.y = bb.Max.y + (spacing_y - spacing_U)
end
local disabled_item = bit32.band(flags, ImGuiSelectableFlags.Disabled) ~= 0
local extra_item_flags = disabled_item and ImGuiItemFlags.Disabled or ImGuiItemFlags.None
local is_visible
if span_all_columns then
-- Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable..
local backup_clip_rect_min_x = window.ClipRect.Min.x
local backup_clip_rect_max_x = window.ClipRect.Max.x
window.ClipRect.Min.x = window.ParentWorkRect.Min.x
window.ClipRect.Max.x = window.ParentWorkRect.Max.x
is_visible = ImGui.ItemAdd(bb, id, nil, extra_item_flags)
window.ClipRect.Min.x = backup_clip_rect_min_x
window.ClipRect.Max.x = backup_clip_rect_max_x
else
is_visible = ImGui.ItemAdd(bb, id, nil, extra_item_flags)
end
local is_multi_select = bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0
if not is_visible then
if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(bb) then
-- Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd)
return false, selected
end
end
local disabled_global = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0
if disabled_item and not disabled_global then
-- Only testing this as an optimization
ImGui.BeginDisabled()
end
-- FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,
-- which would be advantageous since most selectable are not selected.
if span_all_columns then
if g.CurrentTable then
ImGui.TablePushBackgroundChannel()
elseif window.DC.CurrentColumns then
ImGui.PushColumnsBackground()
end
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasClipRect)
ImRect_Copy(g.LastItemData.ClipRect, window.ClipRect)
end
-- We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries
local button_flags = 0
if bit32.band(flags, ImGuiSelectableFlags.NoHoldingActiveID) ~= 0 then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.NoHoldingActiveId) end
if bit32.band(flags, ImGuiSelectableFlags.NoSetKeyOwner) ~= 0 then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.NoSetKeyOwner) end
if bit32.band(flags, ImGuiSelectableFlags.SelectOnClick) ~= 0 then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick) end
if bit32.band(flags, ImGuiSelectableFlags.SelectOnRelease) ~= 0 then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnRelease) end
if bit32.band(flags, ImGuiSelectableFlags.AllowDoubleClick) ~= 0 then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClickRelease, ImGuiButtonFlags.PressedOnDoubleClick) end
if bit32.band(flags, ImGuiSelectableFlags.AllowOverlap) ~= 0 or bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowOverlap) ~= 0 then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.AllowOverlap) end
-- Multi-selection support (header)
local was_selected = selected
if is_multi_select then
-- Handle multi-select + alter button flags for it
-- TODO: selected, button_flags = ImGui.MultiSelectItemHeader(id, selected, button_flags)
end
local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, button_flags)
local auto_selected = false
-- Multi-selection support (footer)
if is_multi_select then
-- TODO: selected, pressed = ImGui.MultiSelectItemFooter(id, selected, pressed)
else
-- Auto-select when moved into
-- - This will be more fully fleshed in the range-select branch
-- - This is not exposed as it won't nicely work with some user side handling of shift/control
-- - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons
-- - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope())
-- - (2) usage will fail with clipped items
-- The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API.
if bit32.band(flags, ImGuiSelectableFlags.SelectOnNav) ~= 0 and g.NavJustMovedToId ~= 0 and g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId then
if g.NavJustMovedToId == id and bit32.band(g.NavJustMovedToKeyMods, ImGuiMod_Ctrl) == 0 then
selected = true
pressed = true
auto_selected = true
end
end
end
-- Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad
if pressed or (hovered and bit32.band(flags, ImGuiSelectableFlags.SetNavIdOnHover) ~= 0) then
if not g.NavHighlightItemUnderNav and g.NavWindow == window and g.NavLayer == window.DC.NavLayerCurrent then
ImGui.SetNavID(id, window.DC.NavLayerCurrent, g.CurrentFocusScopeId, ImGui.WindowRectAbsToRel(window, bb)) -- (bb == NavRect)
if g.IO.ConfigNavCursorVisibleAuto then
g.NavCursorVisible = false
end
end
end
if pressed then
ImGui.MarkItemEdited(id)
end
if selected ~= was_selected then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledSelection)
end
if g.ActiveId == id and g.ActiveIdIsJustActivated then
g.ActiveIdWasSelected = was_selected
g.ActiveIdWasSoleSelected = was_selected and (not is_multi_select or g.CurrentMultiSelect.IsSoleOrUnknownSelectionSize)
end
-- Render
if is_visible then
local highlighted = hovered or (bit32.band(flags, ImGuiSelectableFlags.Highlight) ~= 0)
if highlighted or selected then
-- Between 1.91.0 and 1.91.4 we made selected Selectable use an arbitrary lerp between _Header and _HeaderHovered. Removed that now. (#8106)
local col
if held and highlighted then
col = ImGui.GetColorU32(ImGuiCol.HeaderActive)
elseif highlighted then
col = ImGui.GetColorU32(ImGuiCol.HeaderHovered)
else
col = ImGui.GetColorU32(ImGuiCol.Header)
end
ImGui.RenderFrame(bb.Min, bb.Max, col, false, style.SelectableRounding)
end
if g.NavId == id then
local nav_render_cursor_flags = ImGuiNavRenderCursorFlags.Compact
if is_multi_select then
nav_render_cursor_flags = bit32.bor(nav_render_cursor_flags, ImGuiNavRenderCursorFlags.AlwaysDraw) -- Always show the nav rectangle
end
ImGui.RenderNavCursor(bb, id, nav_render_cursor_flags, style.SelectableRounding)
end
end
if span_all_columns then
if g.CurrentTable then
ImGui.TablePopBackgroundChannel()
elseif window.DC.CurrentColumns then
ImGui.PopColumnsBackground()
end
end
-- Text stays at the submission position. Alignment/clipping extents ignore SpanAllColumns.
if is_visible then
ImGui.RenderTextClipped(pos, ImVec2(ImMin(pos.x + size.x, window.WorkRect.Max.x), pos.y + size.y), label, label_end, label_size, style.SelectableTextAlign, bb)
end
-- Automatically close popups
if pressed and not auto_selected and bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 and bit32.band(flags, ImGuiSelectableFlags.NoAutoClosePopups) == 0 and bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.AutoClosePopups) ~= 0 then
ImGui.CloseCurrentPopup()
end
if disabled_item and not disabled_global then
ImGui.EndDisabled()
end
-- Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve
-- selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect().
return pressed, selected
end
----------------------------------------------------------------
-- [SECTION] BASIC PLOTTING
----------------------------------------------------------------
--- @param plot_type ImGuiPlotType
--- @param label string
--- @param values_getter fun(data?: table, idx: int): float
--- @param data? table # 1-based table
--- @param values_count int
--- @param values_offset int
--- @param overlay_text? string
--- @param scale_min float
--- @param scale_max float
--- @param size_arg ImVec2
--- @return int
function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, size_arg)
local g = GImGui
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return -1
end
local style = g.Style
local id = window:GetID(label)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local frame_size = ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0)
local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + frame_size)
local inner_bb = ImRect(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding)
local total_bb = ImRect(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0 and style.ItemInnerSpacing.x + label_size.x or 0.0, 0))
ImGui.ItemSize(total_bb, style.FramePadding.y)
if not ImGui.ItemAdd(total_bb, id, frame_bb, ImGuiItemFlags.NoNav) then
return -1
end
local _, hovered, _ = ImGui.ButtonBehavior(frame_bb, id)
if scale_min == FLT_MAX or scale_max == FLT_MAX then
local v_min = FLT_MAX
local v_max = -FLT_MAX
for i = 1, values_count do
local v = values_getter(data, i) -- NaN isn't checked here
v_min = ImMin(v_min, v)
v_max = ImMax(v_max, v)
end
if scale_min == FLT_MAX then
scale_min = v_min
end
if scale_max == FLT_MAX then
scale_max = v_max
end
end
ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), true, style.FrameRounding)
local values_count_min = (plot_type == ImGuiPlotType.Lines) and 2 or 1
local idx_hovered = -1
if values_count >= values_count_min then
local res_w = ImMin(math.floor(frame_size.x), values_count) + ((plot_type == ImGuiPlotType.Lines) and -1 or 0)
local item_count = values_count + ((plot_type == ImGuiPlotType.Lines) and -1 or 0)
if hovered and inner_bb:Contains(g.IO.MousePos) then
local t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0, 0.999)
local v_idx = math.floor(t * item_count) + 1
IM_ASSERT(v_idx >= 1 and v_idx <= values_count)
local v0 = values_getter(data, (v_idx - 1 + values_offset) % values_count + 1)
local v1 = values_getter(data, (v_idx - 1 + 1 + values_offset) % values_count + 1)
if plot_type == ImGuiPlotType.Lines then
ImGui.SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1)
elseif plot_type == ImGuiPlotType.Histogram then
ImGui.SetTooltip("%d: %8.4g", v_idx, v0)
end
idx_hovered = v_idx
end
local t_step = 1.0 / res_w
local inv_scale = (scale_min == scale_max) and 0.0 or (1.0 / (scale_max - scale_min))
local v0 = values_getter(data, (0 + values_offset) % values_count + 1)
local t0 = 0.0
local tp0 = ImVec2(t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale))
local histogram_zero_line_t = (scale_min * scale_max < 0.0) and (1 + scale_min * inv_scale) or (scale_min < 0.0 and 0.0 or 1.0)
local col_base = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLines or ImGuiCol.PlotHistogram)
local col_hovered = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLinesHovered or ImGuiCol.PlotHistogramHovered)
for _ = 0, res_w - 1 do
local t1 = t0 + t_step
local v1_idx = math.floor(t0 * item_count + 0.5) + 1
IM_ASSERT(v1_idx >= 1 and v1_idx <= values_count)
local v1 = values_getter(data, (v1_idx - 1 + values_offset + 1) % values_count + 1)
local tp1 = ImVec2(t1, 1.0 - ImSaturate((v1 - scale_min) * inv_scale))
local pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0)
local pos1
if plot_type == ImGuiPlotType.Lines then
pos1 = ImLerp(inner_bb.Min, inner_bb.Max, tp1)
else
pos1 = ImLerp(inner_bb.Min, inner_bb.Max, ImVec2(tp1.x, histogram_zero_line_t))
end
if plot_type == ImGuiPlotType.Lines then
window.DrawList:AddLine(pos0, pos1, idx_hovered == v1_idx and col_hovered or col_base)
elseif plot_type == ImGuiPlotType.Histogram then
if pos1.x >= pos0.x + 2.0 then
pos1.x = pos1.x - 1.0
end
window.DrawList:AddRectFilled(pos0, pos1, idx_hovered == v1_idx and col_hovered or col_base)
end
t0 = t1
tp0 = tp1
end
end
if overlay_text then
ImGui.RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, nil, nil, ImVec2(0.5, 0.0))
end
if label_size.x > 0.0 then
ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label, 1, label_end, false)
end
return idx_hovered
end
--- @class ImGuiPlotArrayGetterData
--- @field Values float[]
--- @field Stride int
--- @param values float[]
--- @param stride int
--- @return ImGuiPlotArrayGetterData
--- @nodiscard
function ImGuiPlotArrayGetterData(values, stride)
return {
Values = values,
Stride = stride
}
end
--- @param data ImGuiPlotArrayGetterData
--- @param idx int
--- @return float
--- @package
local function Plot_ArrayGetter(data, idx)
return data.Values[idx * data.Stride]
end
--- @param label string
--- @param values_or_getter table|fun(data:table, i:int) # 1-based table or a function
--- @param data? table # 1-based table
--- @param values_count int
--- @param values_offset? int # Defaults to 0
--- @param overlay_text? string
--- @param scale_min? float # Defaults to FLT_MAX
--- @param scale_max? float # Defaults to FLT_MAX
--- @param graph_size? ImVec2 # Defaults to ImVec2(0, 0)
--- @param stride? int # Defaults to 1
function ImGui.PlotLines(label, values_or_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size, stride)
if values_offset == nil then values_offset = 0 end
if scale_min == nil then scale_min = FLT_MAX end
if scale_max == nil then scale_max = FLT_MAX end
if graph_size == nil then graph_size = ImVec2(0, 0) end
if stride == nil then stride = 1 end
if type(values_or_getter) == "function" then
ImGui.PlotEx(ImGuiPlotType.Lines, label, values_or_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size)
else
data = ImGuiPlotArrayGetterData(values_or_getter, stride)
ImGui.PlotEx(ImGuiPlotType.Lines, label, Plot_ArrayGetter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size)
end
end
--- @param label string
--- @param values_or_getter table|fun(data:table, i:int) # 1-based table or a function
--- @param data? table # 1-based table
--- @param values_count int
--- @param values_offset? int # Defaults to 0
--- @param overlay_text? string
--- @param scale_min? float # Defaults to FLT_MAX
--- @param scale_max? float # Defaults to FLT_MAX
--- @param graph_size? ImVec2 # Defaults to ImVec2(0, 0)
--- @param stride? int # Defaults to 1
function ImGui.PlotHistogram(label, values_or_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size, stride)
if values_offset == nil then values_offset = 0 end
if scale_min == nil then scale_min = FLT_MAX end
if scale_max == nil then scale_max = FLT_MAX end
if graph_size == nil then graph_size = ImVec2(0, 0) end
if stride == nil then stride = 1 end
if type(values_or_getter) == "function" then
ImGui.PlotEx(ImGuiPlotType.Histogram, label, values_or_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size)
else
data = ImGuiPlotArrayGetterData(values_or_getter, stride)
ImGui.PlotEx(ImGuiPlotType.Histogram, label, Plot_ArrayGetter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size)
end
end
----------------------------------------------------------------
-- [SECTION] MENU RELATED
----------------------------------------------------------------
--- @param spacing float
--- @param window_reappearing bool
function MT.ImGuiMenuColumns:Update(spacing, window_reappearing)
if window_reappearing then
for i = 1, #self.Widths do self.Widths[i] = 0 end
end
self.Spacing = spacing
self:CalcNextTotalWidth(true)
for i = 1, #self.Widths do self.Widths[i] = 0 end
self.TotalWidth = self.NextTotalWidth
self.NextTotalWidth = 0
end
--- @param update_offsets bool
function MT.ImGuiMenuColumns:CalcNextTotalWidth(update_offsets)
local offset = 0
local want_spacing = false
for i = 1, #self.Widths do
local width = self.Widths[i]
if want_spacing and width > 0 then
offset = offset + self.Spacing
end
want_spacing = want_spacing or (width > 0)
if update_offsets then
if i == 2 then self.OffsetLabel = offset end
if i == 3 then self.OffsetShortcut = offset end
if i == 4 then self.OffsetMark = offset end
end
offset = offset + width
end
self.NextTotalWidth = offset
end
--- @param w_icon float
--- @param w_label float
--- @param w_shortcut float
--- @param w_mark float
function MT.ImGuiMenuColumns:DeclColumns(w_icon, w_label, w_shortcut, w_mark)
self.Widths[1] = ImMax(self.Widths[1], (ImU16)(w_icon))
self.Widths[2] = ImMax(self.Widths[2], (ImU16)(w_label))
self.Widths[3] = ImMax(self.Widths[3], (ImU16)(w_shortcut))
self.Widths[4] = ImMax(self.Widths[4], (ImU16)(w_mark))
self:CalcNextTotalWidth(false)
return ImMax(self.TotalWidth, self.NextTotalWidth)
end
-- FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere..
-- Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer.
-- Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags.MenuBar will become unnecessary.
-- Then later the same system could be used for multiple menu-bars, scrollbars, side-bars.
function ImGui.BeginMenuBar()
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
if bit32.band(window.Flags, ImGuiWindowFlags.MenuBar) == 0 then
return false
end
IM_ASSERT(not window.DC.MenuBarAppending)
ImGui.BeginGroup() -- FIXME: Misleading to use a group for that backup/restore
ImGui.PushID("##MenuBar")
-- We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect.
-- We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy.
local border_top = ImMax(IM_ROUND(window.WindowBorderSize * 0.5 - window.TitleBarHeight), 0.0)
local border_half = IM_ROUND(window.WindowBorderSize * 0.5)
local bar_rect = window:MenuBarRect()
local clip_rect = ImRect(ImFloor(bar_rect.Min.x + border_half), ImFloor(bar_rect.Min.y + border_top), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window.WindowRounding, border_half))), ImFloor(bar_rect.Max.y))
clip_rect:ClipWith(window.OuterRectClipped)
ImGui.PushClipRect(clip_rect.Min, clip_rect.Max, false)
-- We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags)
ImVec2_Copy(window.DC.CursorPos, ImVec2(bar_rect.Min.x + window.DC.MenuBarOffset.x, bar_rect.Min.y + window.DC.MenuBarOffset.y))
ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos)
window.DC.LayoutType = ImGuiLayoutType.Horizontal
window.DC.IsSameLine = false
window.DC.NavLayerCurrent = ImGuiNavLayer.Menu
window.DC.MenuBarAppending = true
ImGui.AlignTextToFramePadding()
return true
end
function ImGui.EndMenuBar()
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.MenuBar) ~= 0)
IM_ASSERT(window.DC.MenuBarAppending)
-- Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings
if ImGui.NavMoveRequestButNoResultYet() and (g.NavMoveDir == ImGuiDir.Left or g.NavMoveDir == ImGuiDir.Right) and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
local nav_earliest_child = g.NavWindow
while nav_earliest_child.ParentWindow and bit32.band(nav_earliest_child.ParentWindow.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 do
nav_earliest_child = nav_earliest_child.ParentWindow
end
if nav_earliest_child.ParentWindow == window and nav_earliest_child.DC.ParentLayoutType == ImGuiLayoutType.Horizontal and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) == 0 then
local layer = ImGuiNavLayer.Menu
IM_ASSERT(bit32.band(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, layer)) ~= 0)
ImGui.FocusWindow(window)
ImGui.SetNavID(window.NavLastIds[layer], layer, 0, window.NavRectRel[layer])
if g.NavCursorVisible then
g.NavCursorVisible = false
g.NavCursorHideFrames = 2
end
g.NavHighlightItemUnderNav = true
g.NavMousePosDirty = true
ImGui.NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags)
end
else
ImGui.NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags.WrapX)
end
ImGui.PopClipRect()
ImGui.PopID()
window.DC.MenuBarOffset.x = window.DC.CursorPos.x - window.Pos.x -- Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos
-- FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here
local group_data = g.GroupStack:back()
group_data.EmitItem = false
local restore_cursor_max_pos = ImVec2()
ImVec2_Copy(restore_cursor_max_pos, group_data.BackupCursorMaxPos)
window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, window.DC.CursorMaxPos.x - window.Scroll.x) -- Convert ideal extents for scrolling layer equivalent
ImGui.EndGroup() -- Restore position on layer 0 // FIXME: Misleading to use a group for that backup/restore
window.DC.LayoutType = ImGuiLayoutType.Vertical
window.DC.IsSameLine = false
window.DC.NavLayerCurrent = ImGuiNavLayer.Main
window.DC.MenuBarAppending = false
ImVec2_Copy(window.DC.CursorMaxPos, restore_cursor_max_pos)
end
local function IsRootOfOpenMenuSet()
local g = GImGui
local window = g.CurrentWindow
if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) or (bit32.band(window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0) then
return false
end
local upper_popup = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1]
if window.DC.NavLayerCurrent ~= upper_popup.ParentNavLayer then
return false
end
return upper_popup.Window and (bit32.band(upper_popup.Window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0) and ImGui.IsWindowChildOf(upper_popup.Window, window, true, false)
end
--- @param label string
--- @param icon? string
--- @param enabled bool
function ImGui.BeginMenuEx(label, icon, enabled)
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local style = g.Style
local id = window:GetID(label)
local menu_is_open = ImGui.IsPopupOpen(id, ImGuiPopupFlags.None)
local window_flags = bit32.bor(ImGuiWindowFlags.ChildMenu, ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoNavFocus)
if bit32.band(window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then
window_flags = bit32.bor(window_flags, ImGuiWindowFlags.ChildWindow)
end
if g.MenusIdSubmittedThisFrame:contains(id) then
if menu_is_open then
menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags)
else
g.NextWindowData:ClearFlags()
end
return menu_is_open
end
g.MenusIdSubmittedThisFrame:push_back(id)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local menuset_is_open = IsRootOfOpenMenuSet()
if menuset_is_open then
g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoWindowHoverableCheck)
end
local popup_pos
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
ImGui.PushID(label)
if not enabled then
ImGui.BeginDisabled()
end
local pressed
local backup_rounding = style.SelectableRounding
style.SelectableRounding = style.MenuItemRounding
local selectable_flags = bit32.bor(ImGuiSelectableFlags.SelectOnClick, ImGuiSelectableFlags.NoAutoClosePopups)
local offsets = window.DC.MenuColumns
if window.DC.LayoutType == ImGuiLayoutType.Horizontal then
window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5)
ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0)
local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, pos.y + window.DC.CurrLineTextBaseOffset)
pressed = ImGui.Selectable("", menu_is_open, selectable_flags, label_size)
-- TODO: ImGui.LogSetNextTextDecoration("[", "]")
ImGui.RenderText(text_pos, label, 1, label_end, false)
ImGui.PopStyleVar()
window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5))
popup_pos = ImVec2(pos.x - 1.0 - IM_TRUNC(style.ItemSpacing.x * 0.5), text_pos.y - style.FramePadding.y + window.MenuBarHeight)
else
local icon_w
if (icon and icon ~= "") then icon_w = ImGui.CalcTextSize(icon, nil).x else icon_w = 0.0 end
local checkmark_w = IM_TRUNC(g.FontSize * 1.20)
local min_w = offsets:DeclColumns(icon_w, label_size.x, 0.0, checkmark_w)
local extra_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w)
local text_pos = ImVec2(window.DC.CursorPos.x, pos.y + window.DC.CurrLineTextBaseOffset)
pressed = ImGui.Selectable("", menu_is_open, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y))
-- ImGui.LogSetNextTextDecoration("", ">")
ImGui.RenderText(ImVec2(text_pos.x + offsets.OffsetLabel, text_pos.y), label, 1, label_end, false)
if icon_w > 0.0 then
--- @cast icon string
ImGui.RenderText(ImVec2(text_pos.x + offsets.OffsetIcon, text_pos.y), icon)
end
ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x + offsets.OffsetMark + extra_w + g.FontSize * 0.30, text_pos.y), ImGui.GetColorU32(ImGuiCol.Text), ImGuiDir.Right)
popup_pos = ImVec2(pos.x, text_pos.y - style.WindowPadding.y)
end
style.SelectableRounding = backup_rounding
if not enabled then
ImGui.EndDisabled()
end
if g.ActiveId == id and g.HoveredId ~= id and g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMouseDragging(0) then
ImGui.ClearActiveID()
ImGui.SetKeyOwner(ImGuiKey.MouseLeft, ImGuiKeyOwner_NoOwner)
end
local hovered = g.HoveredId == id and enabled and not g.NavHighlightItemUnderNav
local want_open = false
local want_open_nav_init = false
local want_close = false
if window.DC.LayoutType == ImGuiLayoutType.Vertical then
local moving_toward_child_menu = false
local child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) and g.OpenPopupStack[g.BeginPopupStack.Size + 1] or nil
local child_menu_window = (child_popup and child_popup.Window and child_popup.Window.ParentWindow == window) and child_popup.Window or nil
if g.HoveredWindow == window and child_menu_window ~= nil then
local ref_unit = g.FontSize
local child_dir = (window.Pos.x < child_menu_window.Pos.x) and 1.0 or -1.0
local next_window_rect = child_menu_window:Rect()
local ta = (g.IO.MousePos - g.IO.MouseDelta)
local tb
local tc
if child_dir > 0.0 then
tb = next_window_rect:GetTL()
tc = next_window_rect:GetBL()
else
tb = next_window_rect:GetTR()
tc = next_window_rect:GetBR()
end
local pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30, ref_unit * 0.5, ref_unit * 2.5)
ta.x = ta.x + child_dir * -0.5
tb.x = tb.x + child_dir * ref_unit
tc.x = tc.x + child_dir * ref_unit
tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0)
tc.y = ta.y + ImMin((tc.y + pad_farmost_h) - ta.y, ref_unit * 8.0)
moving_toward_child_menu = ImStd.ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos)
end
if menu_is_open and not hovered and g.HoveredWindow == window and not moving_toward_child_menu and not g.NavHighlightItemUnderNav and g.ActiveId == 0 then
want_close = true
end
if not menu_is_open and pressed then
want_open = true
elseif not menu_is_open and hovered and not moving_toward_child_menu then
want_open = true
elseif not menu_is_open and hovered and g.HoveredIdTimer >= 0.30 and g.MouseStationaryTimer >= 0.30 then
want_open = true
end
if g.NavId == id and g.NavMoveDir == ImGuiDir.Right then
want_open = true
want_open_nav_init = true
ImGui.NavMoveRequestCancel()
ImGui.SetNavCursorVisibleAfterMove()
end
else
if menu_is_open and pressed and menuset_is_open then
want_close = true
want_open = false
menu_is_open = false
elseif pressed or (hovered and menuset_is_open and not menu_is_open) then
want_open = true
elseif g.NavId == id and g.NavMoveDir == ImGuiDir.Down then
want_open = true
ImGui.NavMoveRequestCancel()
end
end
if not enabled then
want_close = true
end
if want_close and ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then
ImGui.ClosePopupToLevel(g.BeginPopupStack.Size, true)
end
-- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0))
ImGui.PopID()
if g.ActiveId == id and want_open then
g.ActiveIdNoClearOnFocusLoss = true
end
if want_open and not menu_is_open and g.OpenPopupStack.Size > g.BeginPopupStack.Size then
ImGui.OpenPopup(label)
elseif want_open then
menu_is_open = true
ImGui.OpenPopup(label, ImGuiPopupFlags.NoReopen)
end
if menu_is_open then
local last_item_in_parent = ImGuiLastItemData()
ImGuiLastItemData_Copy(last_item_in_parent, g.LastItemData)
ImGui.SetNextWindowPos(popup_pos, ImGuiCond.Always)
ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.PopupRounding)
menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags)
ImGui.PopStyleVar()
if menu_is_open then
if want_open and want_open_nav_init and not g.NavInitRequest then
ImGui.FocusWindow(g.CurrentWindow, ImGuiFocusRequestFlags.UnlessBelowModal)
ImGui.NavInitWindow(g.CurrentWindow, false)
end
ImGuiLastItemData_Copy(g.LastItemData, last_item_in_parent)
if g.HoveredWindow == window then
g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow)
end
end
else
g.NextWindowData:ClearFlags()
end
return menu_is_open
end
--- @param label string
--- @param enabled? bool
function ImGui.BeginMenu(label, enabled)
if enabled == nil then enabled = true end
return ImGui.BeginMenuEx(label, nil, enabled)
end
function ImGui.EndMenu()
local g = GImGui
local window = g.CurrentWindow
IM_ASSERT_USER_ERROR_RET(bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu)) == bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu), "Calling EndMenu() in wrong window!")
local parent_window = window.ParentWindow
if window.BeginCount == window.BeginCountPreviousFrame then
if g.NavMoveDir == ImGuiDir.Left and ImGui.NavMoveRequestButNoResultYet() then
if g.NavWindow and g.NavWindow.RootWindowForNav == window and parent_window.DC.LayoutType == ImGuiLayoutType.Vertical then
ImGui.ClosePopupToLevel(g.BeginPopupStack.Size - 1, true)
ImGui.NavMoveRequestCancel()
end
end
end
ImGui.EndPopup()
end
--- @param label string
--- @param icon? string
--- @param shortcut? string
--- @param selected? bool
--- @param enabled? bool
function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled)
if selected == nil then selected = false end
if enabled == nil then enabled = true end
local window = ImGui.GetCurrentWindow()
if window.SkipItems then
return false
end
local g = GImGui
local style = g.Style
local pos = ImVec2()
ImVec2_Copy(pos, window.DC.CursorPos)
local label_end = ImGui.FindRenderedTextEnd(label)
local label_size = ImGui.CalcTextSize(label, label_end, false)
local menuset_is_open = IsRootOfOpenMenuSet()
if menuset_is_open then
g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoWindowHoverableCheck)
end
ImGui.PushID(label)
if not enabled then
ImGui.BeginDisabled()
end
local pressed
local backup_rounding = style.SelectableRounding
style.SelectableRounding = style.MenuItemRounding
local selectable_flags = bit32.bor(ImGuiSelectableFlags.SelectOnRelease, ImGuiSelectableFlags.SetNavIdOnHover)
local offsets = window.DC.MenuColumns
if window.DC.LayoutType == ImGuiLayoutType.Horizontal then
window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5)
local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset)
ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0)
pressed = ImGui.Selectable("", selected, selectable_flags, ImVec2(label_size.x, 0.0))
ImGui.PopStyleVar()
if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 then
ImGui.RenderText(text_pos, label, 1, label_end, false)
end
window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5))
else
local icon_w = 0.0
if icon and icon ~= "" then
icon_w = ImGui.CalcTextSize(icon, nil).x
end
local shortcut_w = 0.0
if shortcut and shortcut ~= "" then
shortcut_w = ImGui.CalcTextSize(shortcut, nil).x
end
local checkmark_w = IM_TRUNC(g.FontSize * 1.20)
local min_w = offsets:DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w)
local stretch_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w)
local text_pos = ImVec2(pos.x, pos.y + window.DC.CurrLineTextBaseOffset)
pressed = ImGui.Selectable("", false, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y))
if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 then
ImGui.RenderText(text_pos + ImVec2(offsets.OffsetLabel, 0.0), label, 1, label_end, false)
if icon_w > 0.0 then
--- @cast icon string
ImGui.RenderText(text_pos + ImVec2(offsets.OffsetIcon, 0.0), icon)
end
if shortcut_w > 0.0 then
ImGui.PushStyleColor(ImGuiCol.Text, style.Colors[ImGuiCol.TextDisabled])
-- ImGui.LogSetNextTextDecoration("(", ")")
--- @cast shortcut string
ImGui.RenderText(text_pos + ImVec2(offsets.OffsetShortcut + stretch_w, 0.0), shortcut, nil, nil, false)
ImGui.PopStyleColor()
end
if selected then
ImGui.RenderCheckMark(window.DrawList, text_pos + ImVec2(offsets.OffsetMark + stretch_w + g.FontSize * 0.40, g.FontSize * 0.134 * 0.5), ImGui.GetColorU32(ImGuiCol.Text), g.FontSize * 0.866)
end
end
end
style.SelectableRounding = backup_rounding
local id = g.LastItemData.ID
if g.ActiveId == id and g.HoveredId ~= id and g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMouseDragging(0) then
ImGui.ClearActiveID()
ImGui.SetKeyOwner(ImGuiKey.MouseLeft, ImGuiKeyOwner_NoOwner)
end
-- IMGUI_TEST_ENGINE_ITEM_INFO()
if not enabled then
ImGui.EndDisabled()
end
ImGui.PopID()
return pressed
end
--- @param label string
--- @param shortcut? string
--- @param selected? bool
--- @param enabled? bool
function ImGui.MenuItem(label, shortcut, selected, enabled)
if ImGui.MenuItemEx(label, nil, shortcut, selected, enabled) then
if selected ~= nil then
selected = not selected
end
return true, selected
end
return false, selected
end
return true -- [Roblox] ModuleScripts must return exactly one value
end
__FILES['imstb_rectpack.lua'] = function()
--- ImGui Sincerely
-- This is a Lua port of original `imstb_rectpack.h`
-- ALL TABLES IN THIS FILE ARE 1-BASED!
-- Avoids table creation when possible
--- The `prev_link` can be stbrp_context or stbrp_node
--- @diagnostic disable
local bit32 = bit32
local STBRP_SORT = table.sort
local STBRP_ASSERT = assert
local STBRP__NOTUSED = function(_) end
local STBRP__MAXVAL = 0x7fffffff
--- @enum STBRP_HEURISTIC_Skyline
local STBRP_HEURISTIC_Skyline = {
default = 0,
BL_sortHeight = 0,
BF_sortHeight = 1
}
local STBRP__INIT_skyline = 1
--- @enum STBRP__PREV_LINK_TYPE
local STBRP__PREV_LINK_TYPE = {
ACTIVE_HEAD = 0,
NEXT = 1
}
--- @alias stbrp_coord int
--- @class stbrp_rect
--- @field id int
--- @field w stbrp_coord
--- @field h stbrp_coord
--- @field x stbrp_coord
--- @field y stbrp_coord
--- @field was_packed int
--- @return stbrp_rect
--- @nodiscard
local function stbrp_rect()
return {
id = 0,
w = 0,
h = 0,
x = 0,
y = 0,
was_packed = 0
}
end
--- @class stbrp_node
--- @field x stbrp_coord
--- @field y stbrp_coord
--- @field next stbrp_node
--- @return stbrp_node
--- @nodiscard
local function stbrp_node()
return {
x = 0,
y = 0,
next = nil
}
end
--- @class stbrp_context
--- @field width int
--- @field height int
--- @field align int
--- @field init_mode int
--- @field heuristic int
--- @field num_nodes int
--- @field active_head stbrp_node
--- @field free_head stbrp_node
--- @field extra stbrp_node[]
--- @return stbrp_context
--- @nodiscard
local function stbrp_context()
return {
width = 0,
height = 0,
align = 0,
init_mode = 0,
heuristic = 0,
num_nodes = 0,
active_head = nil,
free_head = nil,
extra = {stbrp_node(), stbrp_node()}
}
end
--- @class stbrp__findresult
--- @field x int
--- @field y int
--- @field prev_link? table
--- @field prev_link_type? int
--- @return stbrp__findresult
local function stbrp__findresult()
return {
x = 0,
y = 0,
prev_link = nil,
prev_link_type = nil
}
end
--------------------------
--------------------------
---
--- IMPLEMENTATION SECTION
---
---
--- @param context stbrp_context
--- @param heuristic int
local function stbrp_setup_heuristic(context, heuristic)
if context.init_mode == STBRP__INIT_skyline then
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight or heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight)
context.heuristic = heuristic
else
STBRP_ASSERT(false)
end
end
--- @param context stbrp_context
--- @param allow_out_of_mem boolean
local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem)
if allow_out_of_mem then
context.align = 1
else
context.align = (context.width + context.num_nodes - 1) / context.num_nodes
end
end
--- @param context stbrp_context
--- @param width int
--- @param height int
--- @param nodes stbrp_node[]
--- @param num_nodes int
function stbrp_init_target(context, width, height, nodes, num_nodes)
for i = 1, num_nodes - 1 do
nodes[i].next = nodes[i + 1]
end
nodes[num_nodes].next = nil
context.init_mode = STBRP__INIT_skyline
context.heuristic = STBRP_HEURISTIC_Skyline.default
context.free_head = nodes[1]
context.active_head = context.extra[1]
context.width = width
context.height = height
context.num_nodes = num_nodes
stbrp_setup_allow_out_of_mem(context, false)
context.extra[1].x = 0
context.extra[1].y = 0
context.extra[1].next = context.extra[2]
context.extra[2].x = width
context.extra[2].y = bit32.lshift(1, 30)
context.extra[2].next = nil
end
--- @param c stbrp_context
--- @param first stbrp_node
--- @param x0 int
--- @param width int
--- @return int, int
local function stbrp__skyline_find_min_y(c, first, x0, width)
local node = first
local x1 = x0 + width
STBRP__NOTUSED(c)
STBRP_ASSERT(first.x <= x0)
STBRP_ASSERT(node.next.x > x0)
STBRP_ASSERT(node.x <= x0)
local min_y = 0
local waste_area = 0
local visited_width = 0
while node.x < x1 do
if node.y > min_y then
waste_area = waste_area + visited_width * (node.y - min_y)
min_y = node.y
if node.x < x0 then
visited_width = visited_width + node.next.x - x0
else
visited_width = visited_width + node.next.x - node.x
end
else
local under_width = node.next.x - node.x
if under_width + visited_width > width then
under_width = width - visited_width
end
waste_area = waste_area + under_width * (min_y - node.y)
visited_width = visited_width + under_width
end
node = node.next
end
return min_y, waste_area
end
--- @param c stbrp_context
--- @param width int
--- @param height int
--- @return stbrp__findresult
local function stbrp__skyline_find_best_pos(c, width, height)
local best_waste = bit32.lshift(1, 30)
local best_x = 0
local best_y = bit32.lshift(1, 30)
local fr = stbrp__findresult()
local best_prev_link = nil
local best_prev_link_type = nil
width = width + c.align - 1
width = width - width % c.align
STBRP_ASSERT(width % c.align == 0)
if width > c.width or height > c.height then
fr.prev_link = nil
fr.prev_link_type = nil
fr.x = 0
fr.y = 0
return fr
end
local prev_link = c
local prev_link_type = STBRP__PREV_LINK_TYPE.ACTIVE_HEAD
local node = c.active_head
while (node.x + width <= c.width) do
local y, waste = stbrp__skyline_find_min_y(c, node, node.x, width)
if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then
if y < best_y then
best_y = y
best_prev_link = prev_link
best_prev_link_type = prev_link_type
best_x = node.x
end
else
if y + height <= c.height then
if y < best_y or (y == best_y and waste < best_waste) then
best_y = y
best_waste = waste
best_prev_link = prev_link
best_prev_link_type = prev_link_type
best_x = node.x
end
end
end
prev_link = node
prev_link_type = STBRP__PREV_LINK_TYPE.NEXT
node = node.next
end
if c.heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight then
local tail = c.active_head
local node_scan = c.active_head
local prev_link_scan = c
local prev_link_scan_type = STBRP__PREV_LINK_TYPE.ACTIVE_HEAD
while tail and tail.x < width do
tail = tail.next
end
while tail do
local xpos = tail.x - width
STBRP_ASSERT(xpos >= 0)
while node_scan.next and node_scan.next.x <= xpos do
prev_link_scan = node_scan
prev_link_scan_type = STBRP__PREV_LINK_TYPE.NEXT
node_scan = node_scan.next
end
if node_scan then
STBRP_ASSERT(node_scan.next.x > xpos and node_scan.x <= xpos)
local y, waste = stbrp__skyline_find_min_y(c, node_scan, xpos, width)
if y + height <= c.height then
if y <= best_y then
if y < best_y or waste < best_waste or (waste == best_waste and xpos < best_x) then
best_x = xpos
best_y = y
best_waste = waste
best_prev_link = prev_link_scan
best_prev_link_type = prev_link_scan_type
end
end
end
end
tail = tail.next
end
end
fr.prev_link = best_prev_link
fr.prev_link_type = best_prev_link_type
fr.x = best_x
fr.y = best_y
return fr
end
--- @param context stbrp_context
--- @param width int
--- @param height int
--- @return stbrp__findresult
local function stbrp__skyline_pack_rectangle(context, width, height)
local res = stbrp__skyline_find_best_pos(context, width, height)
if res.prev_link == nil or res.y + height > context.height or context.free_head == nil then
res.prev_link = nil
res.prev_link_type = nil
return res
end
local node = context.free_head
node.x = res.x
node.y = res.y + height
context.free_head = node.next
local cur
if res.prev_link_type == STBRP__PREV_LINK_TYPE.ACTIVE_HEAD then
cur = res.prev_link.active_head
else
cur = res.prev_link.next
end
if cur.x < res.x then
local next = cur.next
cur.next = node
cur = next
else
if res.prev_link_type == STBRP__PREV_LINK_TYPE.ACTIVE_HEAD then
res.prev_link.active_head = node
else
res.prev_link.next = node
end
end
while cur.next and cur.next.x <= res.x + width do
local next = cur.next
cur.next = context.free_head
context.free_head = cur
cur = next
end
node.next = cur
if cur.x < res.x + width then
cur.x = res.x + width
end
return res
end
--- @param a stbrp_rect
--- @param b stbrp_rect
--- @return bool
--- @package
local function rect_height_compare(a, b)
if a.h > b.h then
return true
elseif a.h < b.h then
return false
else
return a.w > b.w
end
end
--- @param a stbrp_rect
--- @param b stbrp_rect
--- @return bool
--- @package
local function rect_original_order(a, b)
return a.was_packed < b.was_packed
end
--- @param context stbrp_context
--- @param rects stbrp_rect[]
--- @param num_rects int
--- @return int
local function stbrp_pack_rects(context, rects, num_rects)
local all_rects_packed = 1
for i = 1, num_rects do
rects[i].was_packed = (i - 1)
end
STBRP_SORT(rects, rect_height_compare)
for i = 1, num_rects do
if rects[i].w == 0 or rects[i].h == 0 then
rects[i].x = 0
rects[i].y = 0
else
local fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h)
if fr.prev_link then
rects[i].x = fr.x
rects[i].y = fr.y
else
rects[i].x = STBRP__MAXVAL
rects[i].y = STBRP__MAXVAL
end
end
end
STBRP_SORT(rects, rect_original_order)
for i = 1, num_rects do
rects[i].was_packed = (rects[i].x == STBRP__MAXVAL and rects[i].y == STBRP__MAXVAL) and 0 or 1
if rects[i].was_packed == 0 then
all_rects_packed = 0
end
end
return all_rects_packed
end
return {
context = stbrp_context,
rect = stbrp_rect,
node = stbrp_node,
pack_rects = stbrp_pack_rects,
init_target = stbrp_init_target,
setup_allow_out_of_mem = stbrp_setup_allow_out_of_mem,
setup_heuristic = stbrp_setup_heuristic
}
end
__FILES['imstb_textedit.lua'] = function()
--- ImGui Sincerely
-- This is a Lua port of original `imstb_textedit.h`
-- ALL TABLES IN THIS FILE ARE 1-BASED!
-- Character Indexing:
-- idx=n, the n'th char (1-based)
-- Cursor Indexing:
-- idx=n, the position before the n'th char
-- idx=n+1, the position after the n'th char
-- Symbols that must be defined before using this:
local STB_TEXTEDIT_STRINGLEN = ImStb.TEXTEDIT_STRINGLEN
local STB_TEXTEDIT_GETCHAR = ImStb.TEXTEDIT_GETCHAR
local STB_TEXTEDIT_GETWIDTH = ImStb.TEXTEDIT_GETWIDTH
local STB_TEXTEDIT_LAYOUTROW = ImStb.TEXTEDIT_LAYOUTROW
local IMSTB_TEXTEDIT_GETNEXTCHARINDEX = ImStb.TEXTEDIT_GETNEXTCHARINDEX
local IMSTB_TEXTEDIT_GETPREVCHARINDEX = ImStb.TEXTEDIT_GETPREVCHARINDEX
local STB_TEXTEDIT_MOVEWORDLEFT = ImStb.TEXTEDIT_MOVEWORDLEFT
local STB_TEXTEDIT_MOVEWORDRIGHT = ImStb.TEXTEDIT_MOVEWORDRIGHT
local STB_TEXTEDIT_MOVELINESTART = ImStb.TEXTEDIT_MOVELINESTART
local STB_TEXTEDIT_MOVELINEEND = ImStb.TEXTEDIT_MOVELINEEND
local STB_TEXTEDIT_DELETECHARS = ImStb.TEXTEDIT_DELETECHARS
local STB_TEXTEDIT_INSERTCHARS = ImStb.TEXTEDIT_INSERTCHARS
STB_TEXTEDIT_NEWLINE = 10
STB_TEXTEDIT_K_LEFT = 0x200000 -- keyboard input to move cursor left
STB_TEXTEDIT_K_RIGHT = 0x200001 -- keyboard input to move cursor right
STB_TEXTEDIT_K_UP = 0x200002 -- keyboard input to move cursor up
STB_TEXTEDIT_K_DOWN = 0x200003 -- keyboard input to move cursor down
STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line
STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line
STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text
STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text
STB_TEXTEDIT_K_DELETE = 0x200008 -- keyboard input to delete selection or character under cursor
STB_TEXTEDIT_K_BACKSPACE = 0x200009 -- keyboard input to delete selection or character left of cursor
STB_TEXTEDIT_K_UNDO = 0x20000A -- keyboard input to perform undo
STB_TEXTEDIT_K_REDO = 0x20000B -- keyboard input to perform redo
STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word
STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word
STB_TEXTEDIT_K_PGUP = 0x20000E -- keyboard input to move cursor up a page
STB_TEXTEDIT_K_PGDOWN = 0x20000F -- keyboard input to move cursor down a page
STB_TEXTEDIT_K_SHIFT = 0x400000
IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99
local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999
local IMSTB_TEXTEDIT_memmove = ImStb.TEXTEDIT_memmove
local stb_text_undo
local stb_text_redo
----------------------------------------------------------------
----------------------------------------------------------------
---
--- STB_TexteditState
---
--- Definition of STB_TexteditState which you should store
--- per-textfield; it includes cursor position, selection state,
--- and undo state.
---
--- @alias IMSTB_TEXTEDIT_POSITIONTYPE int
--- @alias IMSTB_TEXTEDIT_CHARTYPE char
--- @alias STB_TEXTEDIT_KEYTYPE int
--- @class StbUndoRecord
--- @field where IMSTB_TEXTEDIT_POSITIONTYPE
--- @field insert_length IMSTB_TEXTEDIT_POSITIONTYPE
--- @field delete_length IMSTB_TEXTEDIT_POSITIONTYPE
--- @field char_storage int
--- @return StbUndoRecord
--- @nodiscard
local function StbUndoRecord()
return {
where = 1,
insert_length = 0,
delete_length = 0,
char_storage = 1
}
end
--- @class StbUndoState
--- @field undo_rec StbUndoRecord[] # size = IMSTB_TEXTEDIT_UNDOSTATECOUNT
--- @field undo_char IMSTB_TEXTEDIT_CHARTYPE[] # size = IMSTB_TEXTEDIT_UNDOCHARCOUNT
--- @field undo_point short # next available slot
--- @field redo_point short # next available slot
--- @field undo_char_point int # next available slot
--- @field redo_char_point int # next available slot
--- @return StbUndoState
--- @nodiscard
local function StbUndoState()
local undo_rec = {}
for i = 1, IMSTB_TEXTEDIT_UNDOSTATECOUNT do
undo_rec[i] = StbUndoRecord()
end
local undo_char = {}
for i = 1, IMSTB_TEXTEDIT_UNDOCHARCOUNT do
undo_char[i] = 0
end
return {
undo_rec = undo_rec,
undo_char = undo_char,
undo_point = 1,
redo_point = 1,
undo_char_point = 1,
redo_char_point = 1
}
end
--- @class STB_TexteditState
--- @field cursor int # position of the text cursor within the string
--- @field select_start int # selection start point
--- @field select_end int
--- @field insert_mode bool
--- @field row_count_per_page int
--- @field cursor_at_end_of_line bool # not implemented yet
--- @field initialized bool
--- @field has_preferred_x bool
--- @field single_line bool
--- @field padding1 unsigned_char
--- @field padding2 unsigned_char
--- @field padding3 unsigned_char
--- @field preferred_x float
--- @field undostate StbUndoState
--- @return STB_TexteditState
--- @nodiscard
function STB_TexteditState()
return {
cursor = 0,
select_start = 0,
select_end = 0,
insert_mode = false,
row_count_per_page = 0,
cursor_at_end_of_line = false,
initialized = false,
has_preferred_x = false,
single_line = false,
padding1 = 0,
padding2 = 0,
padding3 = 0,
preferred_x = 0.0,
undostate = StbUndoState()
}
end
--- @param s STB_TexteditState
local function STB_TEXT_HAS_SELECTION(s)
return s.select_start ~= s.select_end
end
--- @class StbTexteditRow
--- @field x0 float # starting x location
--- @field x1 float # end x location
--- @field baseline_y_delta float # position of baseline relative to previous row's baseline
--- @field ymin float # height of row above baseline
--- @field ymax float # height of row below baseline
--- @field num_chars int
--- @return StbTexteditRow
--- @nodiscard
local function StbTexteditRow()
return {
x0 = 0.0,
x1 = 0.0,
baseline_y_delta = 0.0,
ymin = 0.0,
ymax = 0.0,
num_chars = 0
}
end
--- @param r StbTexteditRow
local function StbTexteditRow_Reset(r)
r.x0 = 0.0
r.x1 = 0.0
r.baseline_y_delta = 0.0
r.ymin = 0.0
r.ymax = 0.0
r.num_chars = 0
end
----------------------------------------
----------------------------------------
---
--- Implementation
---
---
local stb_text_locate_coord do
-- only create once, reuse later
local r = StbTexteditRow()
--- traverse the layout to locate the nearest character to a display position
--- @param str IMSTB_TEXTEDIT_STRING
--- @param x float
--- @param y float
--- @return int idx
--- @return bool side_on_line
function stb_text_locate_coord(str, x, y)
local n = STB_TEXTEDIT_STRINGLEN(str)
local base_y = 0
local prev_x
StbTexteditRow_Reset(r)
local out_side_on_line = false
-- search rows to find one that straddles 'y'
local i = 1
while i <= n do
STB_TEXTEDIT_LAYOUTROW(r, str, i)
if r.num_chars <= 0 then
return n + 1, out_side_on_line
end
if i == 1 and y < base_y + r.ymin then
return 1, out_side_on_line
end
if y < base_y + r.ymax then
break
end
i = i + r.num_chars
base_y = base_y + r.baseline_y_delta
end
-- below all text, return 'after' last character
if i > n then
out_side_on_line = true
return n + 1, out_side_on_line
end
-- check if it's before the beginning of the line
if x < r.x0 then
return i, out_side_on_line
end
-- check if it's before the end of the line
if x < r.x1 then
-- search characters in row for one that straddles 'x'
prev_x = r.x0
local k = 1
while k <= r.num_chars do
local w = STB_TEXTEDIT_GETWIDTH(str, i, k)
if x < prev_x + w then
out_side_on_line = (k == 1) and false or true
if x < prev_x + w / 2 then
return k + i - 1, out_side_on_line
else
return IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k - 1), out_side_on_line
end
end
prev_x = prev_x + w
k = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, i + k - 1) - i + 1
end
-- shouldn't happen, but if it does, fall through to end-of-line case
end
-- if the last character is a newline, return that. otherwise return 'after' the last character
out_side_on_line = true
if STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) == STB_TEXTEDIT_NEWLINE then
return i + r.num_chars - 1, out_side_on_line
else
return i + r.num_chars, out_side_on_line
end
end
end
local stb_textedit_click do
local r = StbTexteditRow()
-- API click: on mouse down, move the cursor to the clicked location, and reset the selection
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @param x float
--- @param y float
function stb_textedit_click(str, state, x, y)
-- In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
-- goes off the top or bottom of the text
local side_on_line
if state.single_line then
StbTexteditRow_Reset(r)
STB_TEXTEDIT_LAYOUTROW(r, str, 1)
y = r.ymin
end
state.cursor, side_on_line = stb_text_locate_coord(str, x, y)
state.select_start = state.cursor
state.select_end = state.cursor
state.has_preferred_x = false
str.LastMoveDirectionLR = side_on_line and ImGuiDir.Right or ImGuiDir.Left
end
end
local stb_textedit_drag do
local r = StbTexteditRow()
-- API drag: on mouse drag, move the cursor and selection endpoint to the clicked location
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @param x float
--- @param y float
function stb_textedit_drag(str, state, x, y)
local p = 1
local side_on_line
-- In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
-- goes off the top or bottom of the text
if state.single_line then
StbTexteditRow_Reset(r)
STB_TEXTEDIT_LAYOUTROW(r, str, 1)
y = r.ymin
end
if state.select_start == state.select_end then
state.select_start = state.cursor
end
p, side_on_line = stb_text_locate_coord(str, x, y)
state.cursor = p
state.select_end = p
str.LastMoveDirectionLR = (side_on_line ~= false) and ImGuiDir.Right or ImGuiDir.Left
end
end
---------------------------
---------------------------
---
--- Keyboard input handling
---
---
local stb_text_makeundo_insert
local stb_text_makeundo_delete
local stb_text_makeundo_replace
--- @class StbFindState
--- @field x float # position of n'th character
--- @field y float
--- @field height float # height of line
--- @field first_char int # first char of row, and length
--- @field length int
--- @field prev_first int # first char of previous row
--- @return StbFindState
local function StbFindState()
return {
x = 0.0, y = 0.0,
height = 0.0,
first_char = 0, length = 0,
prev_first = 0
}
end
--- @param f StbFindState
local function StbFindState_Reset(f)
f.x = 0.0
f.y = 0.0
f.height = 0.0
f.first_char = 0
f.length = 0
f.prev_first = 0
end
local stb_textedit_find_charpos do
local r = StbTexteditRow()
-- find the x/y location of a character, and remember info about the previous row in
-- case we get a move-up event (for page up, we'll have to rescan)
--- @param find StbFindState
--- @param str IMSTB_TEXTEDIT_STRING
--- @param n int
--- @param single_line bool
function stb_textedit_find_charpos(find, str, n, single_line)
StbTexteditRow_Reset(r)
local prev_start = 1
local z = STB_TEXTEDIT_STRINGLEN(str)
local first
-- special case if it's at the end (may not be needed?)
if n == z + 1 and single_line then
STB_TEXTEDIT_LAYOUTROW(r, str, 1)
find.y = 0
find.first_char = 1
find.length = z
find.height = r.ymax - r.ymin
find.x = r.x1
return
end
-- search rows to find the one that straddles character n
find.y = 0
local i = 1
while true do
STB_TEXTEDIT_LAYOUTROW(r, str, i)
if n < i + r.num_chars - 1 then
break
end
if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] Wrapping point handling
break
end
if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] special handling for last line
break
end
prev_start = i
i = i + r.num_chars
find.y = find.y + r.baseline_y_delta
if i == z + 1 then -- [IMGUI]
r.num_chars = 0
break
end
end
find.first_char = i
first = i
find.length = r.num_chars
find.height = r.ymax - r.ymin
find.prev_first = prev_start
-- now scan to find xpos
find.x = r.x0
i = 1
while first + i <= n + 1 do
find.x = find.x + STB_TEXTEDIT_GETWIDTH(str, first, i)
i = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, first + i - 1) - first + 1
end
end
end
-- make the selection/cursor state valid if client altered the string
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
local function stb_textedit_clamp(str, state)
local n = STB_TEXTEDIT_STRINGLEN(str)
if STB_TEXT_HAS_SELECTION(state) then
if state.select_start > n + 1 then state.select_start = n + 1 end
if state.select_end > n + 1 then state.select_end = n + 1 end
-- if clamping forced them to be equal, move the cursor to match
if state.select_start == state.select_end then
state.cursor = state.select_start
end
end
if state.cursor > n + 1 then state.cursor = n + 1 end
end
-- delete characters while updating undo
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @param where int
--- @param len int
local function stb_textedit_delete(str, state, where, len)
stb_text_makeundo_delete(str, state, where, len)
STB_TEXTEDIT_DELETECHARS(str, where, len)
state.has_preferred_x = false
end
-- delete the selection
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
local function stb_textedit_delete_selection(str, state)
stb_textedit_clamp(str, state)
if STB_TEXT_HAS_SELECTION(state) then
if state.select_start < state.select_end then
stb_textedit_delete(str, state, state.select_start, state.select_end - state.select_start)
state.cursor = state.select_start
state.select_end = state.cursor
else
stb_textedit_delete(str, state, state.select_end, state.select_start - state.select_end)
state.cursor = state.select_end
state.select_start = state.cursor
end
state.has_preferred_x = false
end
end
-- canonicalize the selection so start <= end
--- @param state STB_TexteditState
local function stb_textedit_sortselection(state)
if state.select_end < state.select_start then
local temp = state.select_end
state.select_end = state.select_start
state.select_start = temp
end
end
-- move cursor to first character of selection
--- @param state STB_TexteditState
local function stb_textedit_move_to_first(state)
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_sortselection(state)
state.cursor = state.select_start
state.select_end = state.select_start
state.has_preferred_x = false
end
end
-- move cursor to last character of selection
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
local function stb_textedit_move_to_last(str, state)
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_sortselection(state)
stb_textedit_clamp(str, state)
state.cursor = state.select_end
state.select_start = state.select_end
state.has_preferred_x = false
end
end
-- update selection and cursor to match each other
--- @param state STB_TexteditState
local function stb_textedit_prep_selection_at_cursor(state)
if not STB_TEXT_HAS_SELECTION(state) then
state.select_start = state.cursor
state.select_end = state.cursor
else
state.cursor = state.select_end
end
end
-- API cut: delete selection
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @return bool
local function stb_textedit_cut(str, state)
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_delete_selection(str, state) -- implicitly clamps
state.has_preferred_x = false
return true
end
return false
end
-- API paste: replace existing selection with passed-in text
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @param text IMSTB_TEXTEDIT_CHARTYPE[]
--- @param len int
--- @return bool
local function stb_textedit_paste_internal(str, state, text, len)
-- if there's a selection, the paste should delete it
stb_textedit_clamp(str, state)
stb_textedit_delete_selection(str, state)
-- try to insert the characters
len = STB_TEXTEDIT_INSERTCHARS(str, state.cursor, text, 1, len)
if len then
stb_text_makeundo_insert(state, state.cursor, len)
state.cursor = state.cursor + len
state.has_preferred_x = false
return true
end
-- note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details)
return false
end
-- API key: process text input
-- [IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility.
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @param text IMSTB_TEXTEDIT_CHARTYPE[]
--- @param text_len int
local function stb_textedit_text(str, state, text, text_len)
-- can't add newline in single-line mode
if text[1] == STB_TEXTEDIT_NEWLINE and state.single_line then
return
end
if state.insert_mode and not STB_TEXT_HAS_SELECTION(state) and state.cursor < STB_TEXTEDIT_STRINGLEN(str) then
stb_text_makeundo_replace(str, state, state.cursor, 1, 1)
STB_TEXTEDIT_DELETECHARS(str, state.cursor, 1)
text_len = STB_TEXTEDIT_INSERTCHARS(str, state.cursor, text, 1, text_len)
if text_len then
state.cursor = state.cursor + text_len
state.has_preferred_x = false
end
else
stb_textedit_delete_selection(str, state) -- implicitly clamps
text_len = STB_TEXTEDIT_INSERTCHARS(str, state.cursor, text, 1, text_len)
if text_len then
stb_text_makeundo_insert(state, state.cursor, text_len)
state.cursor = state.cursor + text_len
state.has_preferred_x = false
end
end
end
local stb_textedit_key do
local find = StbFindState()
local row = StbTexteditRow()
-- API key: process a keyboard input
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @param key STB_TEXTEDIT_KEYTYPE
function stb_textedit_key(str, state, key)
if key == STB_TEXTEDIT_K_UNDO then
stb_text_undo(str, state)
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_REDO then
stb_text_redo(str, state)
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_LEFT then
-- if currently there's a selection, move cursor to start of selection
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_move_to_first(state)
else
if state.cursor > 1 then
state.cursor = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state.cursor)
end
end
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_RIGHT then
-- if currently there's a selection, move cursor to end of selection
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_move_to_last(str, state)
else
state.cursor = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state.cursor)
end
stb_textedit_clamp(str, state)
state.has_preferred_x = false
elseif key == bit32.bor(STB_TEXTEDIT_K_LEFT, STB_TEXTEDIT_K_SHIFT) then
stb_textedit_clamp(str, state)
stb_textedit_prep_selection_at_cursor(state)
-- move selection left
if state.select_end > 1 then
state.select_end = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state.select_end)
end
state.cursor = state.select_end
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_WORDLEFT then
-- if currently there's a selection, move cursor to start of selection
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_move_to_first(state)
else
state.cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state.cursor)
stb_textedit_clamp(str, state)
end
elseif key == bit32.bor(STB_TEXTEDIT_K_WORDLEFT, STB_TEXTEDIT_K_SHIFT) then
if not STB_TEXT_HAS_SELECTION(state) then
stb_textedit_prep_selection_at_cursor(state)
end
state.cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state.cursor)
state.select_end = state.cursor
stb_textedit_clamp(str, state)
elseif key == STB_TEXTEDIT_K_WORDRIGHT then
-- if currently there's a selection, move cursor to end of selection
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_move_to_last(str, state)
else
state.cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state.cursor)
stb_textedit_clamp(str, state)
end
elseif key == bit32.bor(STB_TEXTEDIT_K_WORDRIGHT, STB_TEXTEDIT_K_SHIFT) then
if not STB_TEXT_HAS_SELECTION(state) then
stb_textedit_prep_selection_at_cursor(state)
end
state.cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state.cursor)
state.select_end = state.cursor
stb_textedit_clamp(str, state)
elseif key == bit32.bor(STB_TEXTEDIT_K_RIGHT, STB_TEXTEDIT_K_SHIFT) then
stb_textedit_prep_selection_at_cursor(state)
-- move selection right
state.select_end = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state.select_end)
stb_textedit_clamp(str, state)
state.cursor = state.select_end
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_DOWN
or key == bit32.bor(STB_TEXTEDIT_K_DOWN, STB_TEXTEDIT_K_SHIFT)
or key == STB_TEXTEDIT_K_PGDOWN
or key == bit32.bor(STB_TEXTEDIT_K_PGDOWN, STB_TEXTEDIT_K_SHIFT) then
StbFindState_Reset(find)
StbTexteditRow_Reset(row)
local sel = (bit32.band(key, STB_TEXTEDIT_K_SHIFT) ~= 0)
local is_page = (bit32.band(key, bit32.bnot(STB_TEXTEDIT_K_SHIFT)) == STB_TEXTEDIT_K_PGDOWN)
local row_count = is_page and state.row_count_per_page or 1
if not is_page and state.single_line then
-- on windows, up&down in single-line behave like left&right
key = bit32.bor(STB_TEXTEDIT_K_RIGHT, bit32.band(key, STB_TEXTEDIT_K_SHIFT))
return stb_textedit_key(str, state, key) -- was `goto retry`
end
if sel then
stb_textedit_prep_selection_at_cursor(state)
elseif STB_TEXT_HAS_SELECTION(state) then
stb_textedit_move_to_last(str, state)
end
-- compute current position of cursor point
stb_textedit_clamp(str, state)
stb_textedit_find_charpos(find, str, state.cursor, state.single_line)
for j = 1, row_count do
local goal_x = state.has_preferred_x and state.preferred_x or find.x
local x
local start = find.first_char + find.length
if find.length == 0 then
break
end
-- [IMGUI]
-- going down while being on the last line shouldn't bring us to that line end
--if STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) ~= STB_TEXTEDIT_NEWLINE then
-- break
--end
-- now find character position down a row
state.cursor = start
STB_TEXTEDIT_LAYOUTROW(row, str, state.cursor)
x = row.x0
local i = 1
while i <= row.num_chars do
local dx = STB_TEXTEDIT_GETWIDTH(str, start, i)
local next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state.cursor)
x = x + dx
if x > goal_x then
break
end
i = i + (next - state.cursor)
state.cursor = next
end
stb_textedit_clamp(str, state)
if state.cursor == find.first_char + find.length then
str.LastMoveDirectionLR = ImGuiDir.Left
end
state.has_preferred_x = true
state.preferred_x = goal_x
if sel then
state.select_end = state.cursor
end
-- go to next line
find.first_char = find.first_char + find.length
find.length = row.num_chars
end
elseif key == STB_TEXTEDIT_K_UP
or key == bit32.bor(STB_TEXTEDIT_K_UP, STB_TEXTEDIT_K_SHIFT)
or key == STB_TEXTEDIT_K_PGUP
or key == bit32.bor(STB_TEXTEDIT_K_PGUP, STB_TEXTEDIT_K_SHIFT) then
StbFindState_Reset(find)
StbTexteditRow_Reset(row)
local sel = (bit32.band(key, STB_TEXTEDIT_K_SHIFT) ~= 0)
local is_page = (bit32.band(key, bit32.bnot(STB_TEXTEDIT_K_SHIFT)) == STB_TEXTEDIT_K_PGUP)
local row_count = is_page and state.row_count_per_page or 1
if not is_page and state.single_line then
-- on windows, up&down become left&right
key = bit32.bor(STB_TEXTEDIT_K_LEFT, bit32.band(key, STB_TEXTEDIT_K_SHIFT))
return stb_textedit_key(str, state, key) -- was `goto retry`
end
if sel then
stb_textedit_prep_selection_at_cursor(state)
elseif STB_TEXT_HAS_SELECTION(state) then
stb_textedit_move_to_first(state)
end
-- compute current position of cursor point
stb_textedit_clamp(str, state)
stb_textedit_find_charpos(find, str, state.cursor, state.single_line)
for j = 1, row_count do
local goal_x
if state.has_preferred_x then
goal_x = state.preferred_x
else
goal_x = find.x
end
local x
-- can only go up if there's a previous row
if find.prev_first == find.first_char then
break
end
-- now find character position up a row
state.cursor = find.prev_first
STB_TEXTEDIT_LAYOUTROW(row, str, state.cursor)
x = row.x0
local i = 1
while i <= row.num_chars do
local dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i)
local next = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state.cursor)
x = x + dx
if x > goal_x then
break
end
i = i + (next - state.cursor)
state.cursor = next
end
stb_textedit_clamp(str, state)
if state.cursor == find.first_char then
str.LastMoveDirectionLR = ImGuiDir.Right
elseif state.cursor == find.prev_first then
str.LastMoveDirectionLR = ImGuiDir.Left
end
state.has_preferred_x = true
state.preferred_x = goal_x
if sel then
state.select_end = state.cursor
end
-- go to previous line
-- (we need to scan previous line the hard way. maybe we could expose this as a new API function?)
local prev_scan = find.prev_first > 1 and find.prev_first - 1 or 1
while prev_scan > 1 do
local prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, prev_scan)
if STB_TEXTEDIT_GETCHAR(str, prev) == STB_TEXTEDIT_NEWLINE then
break
end
prev_scan = prev
end
find.first_char = find.prev_first
find.prev_first = STB_TEXTEDIT_MOVELINESTART(str, state, prev_scan)
end
elseif key == STB_TEXTEDIT_K_DELETE
or key == bit32.bor(STB_TEXTEDIT_K_DELETE, STB_TEXTEDIT_K_SHIFT) then
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_delete_selection(str, state)
else
local n = STB_TEXTEDIT_STRINGLEN(str)
if state.cursor <= n then
stb_textedit_delete(str, state, state.cursor, IMSTB_TEXTEDIT_GETNEXTCHARINDEX(str, state.cursor) - state.cursor)
end
end
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_BACKSPACE
or key == bit32.bor(STB_TEXTEDIT_K_BACKSPACE, STB_TEXTEDIT_K_SHIFT) then
if STB_TEXT_HAS_SELECTION(state) then
stb_textedit_delete_selection(str, state)
else
stb_textedit_clamp(str, state)
if state.cursor > 1 then
local prev = IMSTB_TEXTEDIT_GETPREVCHARINDEX(str, state.cursor)
stb_textedit_delete(str, state, prev, state.cursor - prev)
state.cursor = prev
end
end
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_TEXTSTART then
state.cursor = 1
state.select_start = 1
state.select_end = 1
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_TEXTEND then
state.cursor = STB_TEXTEDIT_STRINGLEN(str) + 1
state.select_start = 1
state.select_end = 1
state.has_preferred_x = false
elseif key == bit32.bor(STB_TEXTEDIT_K_TEXTSTART, STB_TEXTEDIT_K_SHIFT) then
stb_textedit_prep_selection_at_cursor(state)
state.cursor = 1
state.select_end = 1
state.has_preferred_x = false
elseif key == bit32.bor(STB_TEXTEDIT_K_TEXTEND, STB_TEXTEDIT_K_SHIFT) then
stb_textedit_prep_selection_at_cursor(state)
state.cursor = STB_TEXTEDIT_STRINGLEN(str) + 1
state.select_end = state.cursor
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_LINESTART then
stb_textedit_clamp(str, state)
stb_textedit_move_to_first(state)
state.cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state.cursor)
state.has_preferred_x = false
elseif key == STB_TEXTEDIT_K_LINEEND then
stb_textedit_clamp(str, state)
stb_textedit_move_to_last(str, state)
state.cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state.cursor)
state.has_preferred_x = false
elseif key == bit32.bor(STB_TEXTEDIT_K_LINESTART, STB_TEXTEDIT_K_SHIFT) then
stb_textedit_clamp(str, state)
stb_textedit_prep_selection_at_cursor(state)
state.cursor = STB_TEXTEDIT_MOVELINESTART(str, state, state.cursor)
state.select_end = state.cursor
state.has_preferred_x = false
elseif key == bit32.bor(STB_TEXTEDIT_K_LINEEND, STB_TEXTEDIT_K_SHIFT) then
stb_textedit_clamp(str, state)
stb_textedit_prep_selection_at_cursor(state)
state.cursor = STB_TEXTEDIT_MOVELINEEND(str, state, state.cursor)
state.select_end = state.cursor
state.has_preferred_x = false
end
end
end
-----------------------------------------------------
-----------------------------------------------------
---
--- Undo processing
--- OPTIMIZE: the undo/redo buffer should be circular
---
--- @param state StbUndoState
local function stb_textedit_flush_redo(state)
state.redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT + 1
state.redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT + 1
end
-- discard the oldest entry in the undo list
--- @param state StbUndoState
local function stb_textedit_discard_undo(state)
if state.undo_point > 0 then
-- if the 1th undo state has characters, clean those up
if state.undo_rec[1].char_storage >= 0 then
local n = state.undo_rec[1].insert_length
-- delete n characters from all other records
state.undo_char_point = state.undo_char_point - n
IMSTB_TEXTEDIT_memmove(state.undo_char, 1, state.undo_char, n + 1, state.undo_char_point - 1)
for i = 1, state.undo_point do
if state.undo_rec[i].char_storage >= 0 then
state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- OPTIMIZE: get rid of char_storage and infer it
end
end
end
state.undo_point = state.undo_point - 1
IMSTB_TEXTEDIT_memmove(state.undo_rec, 1, state.undo_rec, 2, state.undo_point - 1)
end
end
-- discard the oldest entry in the redo list--it's bad if this
-- ever happens, but because undo & redo have to store the actual
-- characters in different cases, the redo character buffer can
-- fill up even though the undo buffer didn't
--- @param state StbUndoState
local function stb_textedit_discard_redo(state)
local k = IMSTB_TEXTEDIT_UNDOSTATECOUNT
if state.redo_point <= k then
-- if the k'th undo state has characters, clean those up
if state.undo_rec[k].char_storage >= 1 then
local n = state.undo_rec[k].insert_length
-- move the remaining redo character data to the end of the buffer
state.redo_char_point = state.redo_char_point + n
IMSTB_TEXTEDIT_memmove(state.undo_char, state.redo_char_point, state.undo_char, state.redo_char_point - n, IMSTB_TEXTEDIT_UNDOCHARCOUNT - state.redo_char_point + 1)
-- adjust the position of all the other records to account for above memmove
for i = state.redo_point, k - 1 do
if state.undo_rec[i].char_storage >= 1 then
state.undo_rec[i].char_storage = state.undo_rec[i].char_storage + n
end
end
end
-- now move all the redo records towards the end of the buffer; the first one is at 'redo_point'
-- [IMGUI]
local move_size = IMSTB_TEXTEDIT_UNDOSTATECOUNT - state.redo_point - 1
IMSTB_TEXTEDIT_memmove(state.undo_rec, state.redo_point + 1, state.undo_rec, state.redo_point, move_size)
-- now move redo_point to point to the new one
state.redo_point = state.redo_point + 1
end
end
--- @param state StbUndoState
--- @param numchars int
local function stb_text_create_undo_record(state, numchars)
-- any time we create a new undo record, we discard redo
stb_textedit_flush_redo(state)
-- if we have no free records, we have to make room, by sliding the
-- existing records down
if state.undo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT then
stb_textedit_discard_undo(state)
end
-- if the characters to store won't possibly fit in the buffer, we can't undo
if numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT then
state.undo_point = 1
state.undo_char_point = 1
return nil
end
-- if we don't have enough free characters in the buffer, we have to make room
while state.undo_char_point + numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT do
stb_textedit_discard_undo(state)
end
local ret = state.undo_rec[state.undo_point]
state.undo_point = state.undo_point + 1
return ret
end
--- @param state StbUndoState
--- @param pos int
--- @param insert_len int
--- @param delete_len int
--- @return int? # index into undostate.undo_char[]
local function stb_text_createundo(state, pos, insert_len, delete_len)
local r = stb_text_create_undo_record(state, insert_len)
if r == nil then
return nil
end
r.where = pos
r.insert_length = insert_len
r.delete_length = delete_len
if insert_len == 0 then
r.char_storage = -1
return nil
else
r.char_storage = state.undo_char_point
state.undo_char_point = state.undo_char_point + insert_len
return r.char_storage
end
end
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
function stb_text_undo(str, state)
local s = state.undostate
if s.undo_point == 1 then
return
end
-- we need to do two things: apply the undo record, and create a redo record
local u = s.undo_rec[s.undo_point - 1]
local r = s.undo_rec[s.redo_point - 1]
r.char_storage = -1
r.insert_length = u.delete_length
r.delete_length = u.insert_length
r.where = u.where
if u.delete_length > 0 then
-- if the undo record says to delete characters, then the redo record will
-- need to re-insert the characters that get deleted, so we need to store
-- them.
-- there are three cases:
-- there's enough room to store the characters
-- characters stored for *redoing* don't leave room for redo
-- characters stored for *undoing* don't leave room for redo
-- if the last is true, we have to bail
if s.undo_char_point + u.delete_length > IMSTB_TEXTEDIT_UNDOCHARCOUNT then
-- the undo records take up too much character space; there's no space to store the redo characters
r.insert_length = 0
else
-- there's definitely room to store the characters eventually
while s.undo_char_point + u.delete_length > s.redo_char_point do
-- should never happen:
if s.redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT + 1 then
return
end
-- there's currently not enough room, so discard a redo record
stb_textedit_discard_redo(s)
end
r = s.undo_rec[s.redo_point - 1]
r.char_storage = s.redo_char_point - u.delete_length
s.redo_char_point = s.redo_char_point - u.delete_length
-- now save the characters
for i = 0, u.delete_length - 1 do
s.undo_char[r.char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i)
end
end
-- now we can carry out the deletion
STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length)
end
-- check type of recorded action:
if u.insert_length > 0 then
-- easy case: was a deletion, so we need to insert n characters
u.insert_length = STB_TEXTEDIT_INSERTCHARS(str, u.where, s.undo_char, u.char_storage, u.insert_length)
s.undo_char_point = s.undo_char_point - u.insert_length
end
state.cursor = u.where + u.insert_length
s.undo_point = s.undo_point - 1
s.redo_point = s.redo_point - 1
end
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
function stb_text_redo(str, state)
local s = state.undostate
if s.undo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT + 1 then
return
end
-- we need to do two things: apply the redo record, and create an undo record
local u = s.undo_rec[s.undo_point]
local r = s.undo_rec[s.redo_point]
u.delete_length = r.insert_length
u.insert_length = r.delete_length
u.where = r.where
u.char_storage = -1
if r.delete_length > 0 then
-- the redo record requires us to delete characters, so the undo record
-- needs to store the characters
if s.undo_char_point + u.insert_length > s.redo_char_point then
u.insert_length = 0
u.delete_length = 0
else
u.char_storage = s.undo_char_point
s.undo_char_point = s.undo_char_point + u.insert_length
for i = 0, u.insert_length - 1 do
s.undo_char[u.char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i)
end
end
STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length)
end
if r.insert_length ~= 0 then
r.insert_length = STB_TEXTEDIT_INSERTCHARS(str, r.where, s.undo_char, r.char_storage, r.insert_length)
s.redo_char_point = s.redo_char_point + r.insert_length
end
state.cursor = r.where + r.insert_length
s.undo_point = s.undo_point + 1
s.redo_point = s.redo_point + 1
end
--- @param state STB_TexteditState
--- @param where int
--- @param length int
function stb_text_makeundo_insert(state, where, length)
stb_text_createundo(state.undostate, where, 0, length)
end
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @param where int
--- @param length int
function stb_text_makeundo_delete(str, state, where, length)
local s = state.undostate
local p = stb_text_createundo(s, where, length, 0)
if p then
for i = 0, length - 1 do
s.undo_char[p + i] = STB_TEXTEDIT_GETCHAR(str, where + i)
end
end
end
--- @param str IMSTB_TEXTEDIT_STRING
--- @param state STB_TexteditState
--- @param where int
--- @param old_length int
--- @param new_length int
function stb_text_makeundo_replace(str, state, where, old_length, new_length)
local s = state.undostate
local p = stb_text_createundo(s, where, old_length, new_length)
if p then
for i = 0, old_length - 1 do
s.undo_char[p + i] = STB_TEXTEDIT_GETCHAR(str, where + i)
end
end
end
--- @param state STB_TexteditState
--- @param is_single_line bool
local function stb_textedit_clear_state(state, is_single_line)
state.undostate.undo_point = 1
state.undostate.undo_char_point = 1
state.undostate.redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT + 1
state.undostate.redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT + 1
state.select_end = 1
state.select_start = 1
state.cursor = 1
state.has_preferred_x = false
state.preferred_x = 0
state.cursor_at_end_of_line = false
state.initialized = true
state.single_line = is_single_line
state.insert_mode = false
state.row_count_per_page = 0
end
return {
click = stb_textedit_click,
drag = stb_textedit_drag,
createundo = stb_text_createundo,
initialize_state = stb_textedit_clear_state,
text = stb_textedit_text,
key = stb_textedit_key,
makeundo_replace = stb_text_makeundo_replace,
clamp = stb_textedit_clamp,
prep_selection_at_cursor = stb_textedit_prep_selection_at_cursor,
cut = stb_textedit_cut,
paste = stb_textedit_paste_internal,
HAS_SELECTION = STB_TEXT_HAS_SELECTION
}
end
__FILES['imstb_truetype.lua'] = function()
--- ImGui Sincerely
-- This is a Lua port of original `imstb_truetype.h`
--- STBTT_RASTERIZER_VERSION == 2
local stbtt_fontinfo
local stbtt_InitFont
local stbtt_MakeGlyphBitmapSubpixelPrefilter
local stbtt_GetFontVMetrics
local stbtt__GetGlyphInfoT2
local stbtt__GetGlyphShapeT2
local stbtt_GetGlyphShape
local stbtt_GetGlyphBitmapBox
local stbtt_GetGlyphBitmapBoxSubpixel
local stbtt_GetGlyphHMetrics
local stbtt_GetFontOffsetForIndex
local stbtt_ScaleForPixelHeight
local stbtt_FindGlyphIndex
local STBTT_MAX_OVERSAMPLE = 8
--- @enum STBTT_PLATFORM_ID
local STBTT_PLATFORM_ID = {
UNICODE = 0,
MAC = 1,
ISO = 2,
MICROSOFT = 3,
}
--- @enum STBTT_MS_EID
local STBTT_MS_EID = {
SYMBOL = 0,
UNICODE_BMP = 1,
SHIFTJIS = 2,
UNICODE_FULL = 10
}
-- original enum doesn't have a name, so we name it
--- @enum STBTT_VTX
local STBTT_VTX = {
MOVE = 1,
LINE = 2,
CURVE = 3,
CUBIC = 4
}
local bit32 = bit32
local math = math
local STBTT_assert = assert
local STBTT_sort = table.sort
local STBTT_sqrt = math.sqrt
local STBTT_fabs = math.abs
local STBTT_ifloor = math.floor
local STBTT_iceil = math.ceil
local trunc = function(x)
if x >= 0 then
return math.floor(x)
else
return math.ceil(x)
end
end
local function STBTT__NOTUSED(_) return end
--- @alias stbtt_int32 int
local stbtt_int32 = ImS32
local stbtt_uint32 = ImU32
local stbtt_int16 = ImS16
local stbtt_uint16 = ImU16
local stbtt_int8 = ImS8
local stbtt_uint8 = ImU8
local unsigned_char = stbtt_uint8
--- @class stbtt__buf
--- @field data? table # 1-based byte table
--- @field offset int # Every access to `data` will be offset by this
--- @field cursor int # >= 0
--- @field size int
--- @param initial_offset? int
--- @return stbtt__buf
--- @nodiscard
local function stbtt__buf(initial_offset)
return {
data = nil,
offset = initial_offset or 0,
cursor = 0,
size = nil
}
end
--- @class stbtt_fontinfo
--- @field userdata any
--- @field data table # pointer to .ttf file
--- @field fontstart int # offset of start of font
--- @field numGlyphs int # number of glyphs, needed for range checking
--- @field loca int # table location as offset from start of .ttf
--- @field head int # table location as offset from start of .ttf
--- @field glyf int # table location as offset from start of .ttf
--- @field hhea int # table location as offset from start of .ttf
--- @field hmtx int # table location as offset from start of .ttf
--- @field kern int # table location as offset from start of .ttf
--- @field gpos int # table location as offset from start of .ttf
--- @field svg int # table location as offset from start of .ttf
--- @field index_map int # a cmap mapping for our chosen character encoding
--- @field indexToLocFormat int # format needed to map from glyph index to glyph
--- @field cff stbtt__buf # cff font data
--- @field charstrings stbtt__buf # the charstring index
--- @field gsubrs stbtt__buf # global charstring subroutines index
--- @field subrs stbtt__buf # private charstring subroutines index
--- @field fontdicts stbtt__buf # array of font dicts
--- @field fdselect stbtt__buf # map from glyph to fontdict
--- @return stbtt_fontinfo
function stbtt_fontinfo()
return {
data = nil,
fontstart = nil,
numGlyphs = nil,
loca = nil,
head = nil,
glyf = nil,
hhea = nil,
hmtx = nil,
kern = nil,
gpos = nil,
svg = nil,
index_map = nil,
indexToLocFormat = nil,
cff = nil,
charstrings = nil,
gsubrs = nil,
subrs = nil,
fontdicts = nil,
fdselect = nil
}
end
--- @class stbtt_vertex
--- @field x int
--- @field y int
--- @field cx int
--- @field cy int
--- @field cx1 int
--- @field cy1 int
--- @field type int
--- @field padding int
--- @return stbtt_vertex
--- @nodiscard
local function stbtt_vertex()
return {
x = nil,
y = nil,
cx = nil,
cy = nil,
cx1 = nil,
cy1 = nil,
type = nil,
padding = nil
}
end
--- @class stbtt__csctx
--- @field bounds bool
--- @field started bool
--- @field first_x float
--- @field first_y float
--- @field x float
--- @field y float
--- @field min_x int
--- @field max_x int
--- @field min_y int
--- @field max_y int
--- @field pvertices stbtt_vertex[]
--- @field num_vertices int
--- @return stbtt__csctx
--- @nodiscard
local function stbtt__csctx()
return {
bounds = false,
started = false,
first_x = nil,
first_y = nil,
x = nil,
y = nil,
min_x = nil,
max_x = nil,
min_y = nil,
max_y = nil,
pvertices = nil,
num_vertices = nil
}
end
--- @param bounds bool
--- @return stbtt__csctx
--- @nodiscard
local function STBTT__CSCTX_INIT(bounds)
local this = stbtt__csctx()
this.bounds = bounds
this.started = false
this.first_x = 0
this.first_y = 0
this.x = 0
this.y = 0
this.min_x = 0
this.max_x = 0
this.min_y = 0
this.max_y = 0
this.pvertices = nil
this.num_vertices = 0
return this
end
--- stbtt_kerningentry
--- stbtt_pack_range
--- stbtt_packedchar
--- @class stbtt__edge
--- @field x0 float
--- @field y0 float
--- @field x1 float
--- @field y1 float
--- @field invert bool
--- @return stbtt__edge
--- @nodiscard
local function stbtt__edge()
return {
x0 = nil,
y0 = nil,
x1 = nil,
y1 = nil,
invert = false
}
end
--- @class stbtt__active_edge
--- @return stbtt__active_edge
--- @nodiscard
local function stbtt__active_edge()
return {
next = nil,
fx = nil,
fdx = nil,
fdy = nil,
direction = nil,
sy = nil,
ey = nil
}
end
--- @return stbtt__active_edge
--- @nodiscard
local function stbtt__new_active(e, off_x, start_point)
local z = stbtt__active_edge()
local dxdy = (e.x1 - e.x0) / (e.y1 - e.y0)
z.fdx = dxdy
z.fdy = (dxdy ~= 0.0) and (1.0 / dxdy) or 0.0
z.fx = e.x0 + dxdy * (start_point - e.y0)
z.fx = z.fx - off_x
z.direction = (e.invert) and 1.0 or -1.0
z.sy = e.y0
z.ey = e.y1
z.next = nil
return z
end
--- @class stbtt__bitmap
--- @field w int
--- @field h int
--- @field stride int
--- @field pixels unsigned_char[]
--- @return stbtt__bitmap
--- @nodiscard
local function stbtt__bitmap()
return {
w = nil,
h = nil,
stride = nil,
pixels = nil
}
end
--- @class stbtt__point
--- @field x number
--- @field y number
--- @return stbtt__point
--- @nodiscard
local function stbtt__point() return { x = nil, y = nil } end
----------------------------------------------
----------------------------------------------
---
--- stbtt__buf helpers to parse data from file
---
---
--- @param b stbtt__buf
local function stbtt__buf_get8(b)
if b.cursor >= b.size then return 0 end
local result = b.data[b.offset + b.cursor + 1]
b.cursor = b.cursor + 1
return result
end
--- @param b stbtt__buf
local function stbtt__buf_peek8(b)
if b.cursor >= b.size then return 0 end
return b.data[b.offset + b.cursor + 1]
end
--- @param b stbtt__buf
--- @param o int
local function stbtt__buf_seek(b, o)
STBTT_assert(not (o > b.size or o < 0))
if o > b.size or o < 0 then
b.cursor = b.size
else
b.cursor = o
end
end
--- @param b stbtt__buf
--- @param o int
local function stbtt__buf_skip(b, o)
stbtt__buf_seek(b, b.cursor + o)
end
local function stbtt__buf_get(b, n)
local v = 0
STBTT_assert(n >= 1 and n <= 4)
for _ = 1, n do
v = bit32.bor(bit32.lshift(v, 8), stbtt__buf_get8(b))
end
return v
end
--- @param p? table
--- @param size int
--- @param offset? int
--- @return stbtt__buf
--- @nodiscard
local function stbtt__new_buf(p, size, offset)
local r = stbtt__buf(offset)
STBTT_assert(size < 0x40000000)
r.data = p
r.size = trunc(size)
r.cursor = 0
return r
end
--- @param b stbtt__buf
local function stbtt__buf_get16(b) return stbtt__buf_get(b, 2) end
--- @param b stbtt__buf
local function stbtt__buf_get32(b) return stbtt__buf_get(b, 4) end
--- @param b stbtt__buf
--- @param o int
--- @param s int
--- @return stbtt__buf
--- @nodiscard
local function stbtt__buf_range(b, o, s)
local r = stbtt__new_buf(nil, 0)
if (o < 0 or s < 0 or o > b.size or s > (b.size - o)) then
return r
end
r.data = b.data
r.offset = b.offset + o
r.size = s
return r
end
--- @param b stbtt__buf
local function stbtt__cff_get_index(b)
local count, start, offsize
start = b.cursor
count = stbtt__buf_get16(b)
if count > 0 then
offsize = stbtt__buf_get8(b)
STBTT_assert(offsize >= 1 and offsize <= 4)
stbtt__buf_skip(b, count * offsize)
stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1)
end
return stbtt__buf_range(b, start, b.cursor - start)
end
--- @param b stbtt__buf
local function stbtt__cff_int(b)
local b0 = stbtt__buf_get8(b)
if b0 >= 32 and b0 <= 246 then return b0 - 139
elseif b0 >= 247 and b0 <= 250 then return (b0 - 247) * 256 + stbtt__buf_get8(b) + 108
elseif b0 >= 251 and b0 <= 254 then return -(b0 - 251) * 256 - stbtt__buf_get8(b) - 108
elseif b0 == 28 then return stbtt__buf_get16(b)
elseif b0 == 29 then return stbtt__buf_get32(b)
end
STBTT_assert(false)
return 0
end
--- @param b stbtt__buf
local function stbtt__cff_skip_operand(b)
local v
local b0 = stbtt__buf_peek8(b)
STBTT_assert(b0 >= 28)
if b0 == 30 then
stbtt__buf_skip(b, 1)
while b.cursor < b.size do
v = stbtt__buf_get8(b)
if (bit32.band(v, 0xF) == 0xF or bit32.rshift(v, 4) == 0xF) then
break
end
end
else
stbtt__cff_int(b)
end
end
--- @param b stbtt__buf
--- @param key int
--- @return stbtt__buf
--- @nodiscard
local function stbtt__dict_get(b, key)
stbtt__buf_seek(b, 0)
while b.cursor < b.size do
local start = b.cursor
local _end, op
while stbtt__buf_peek8(b) >= 28 do
stbtt__cff_skip_operand(b)
end
_end = b.cursor
op = stbtt__buf_get8(b)
if op == 12 then op = bit32.bor(stbtt__buf_get8(b), 0x100) end
if op == key then return stbtt__buf_range(b, start, _end - start) end
end
return stbtt__buf_range(b, 0, 0)
end
--- @param b stbtt__buf
--- @param key int
--- @param outcount int
--- @return int[]
--- @nodiscard
local function stbtt__dict_get_ints(b, key, outcount)
local operands = stbtt__dict_get(b, key)
local out = {}
for i = 1, outcount do
if operands.cursor >= operands.size then break end
out[i] = stbtt__cff_int(operands)
end
return out
end
--- @param b stbtt__buf
local function stbtt__cff_index_count(b)
stbtt__buf_seek(b, 0)
return stbtt__buf_get16(b)
end
--- @param b stbtt__buf
--- @param i int
--- @return stbtt__buf
--- @nodiscard
local function stbtt__cff_index_get(b, i)
local count, offsize, start, _end
stbtt__buf_seek(b, 0)
count = stbtt__buf_get16(b)
offsize = stbtt__buf_get8(b)
STBTT_assert(i >= 0 and i < count)
STBTT_assert(offsize >= 1 and offsize <= 4)
stbtt__buf_skip(b, i * offsize)
start = stbtt__buf_get(b, offsize)
_end = stbtt__buf_get(b, offsize)
return stbtt__buf_range(b, 2 + (count + 1) * offsize + start, _end - start)
end
-------------------------------------
-------------------------------------
---
--- Accessors to parse data from file
---
---
--- UNIMPLEMENTED / UNUSED:
--- stbtt_IsGlyphEmpty
--- stbtt_GetKerningTableLength
--- stbtt_GetKerningTable
--- stbtt__GetGlyphKernInfoAdvance
--- stbtt__GetCoverageIndex
--- stbtt__GetGlyphClass
--- stbtt__GetGlyphGPOSInfoAdvance
--- stbtt_GetGlyphKernAdvance
--- stbtt_FindSVGDoc
--- stbtt_GetGlyphSVG
--- stbtt_GetCodepointSVG
--- stbtt_GetCodepointKernAdvance
--- stbtt_GetFontVMetricsOS2
--- stbtt_GetCodepointHMetrics
--- stbtt_ScaleForMappingEmToPixels
--- stbtt_GetFontBoundingBox
--- stbtt_GetCodepointBitmapBox
--- stbtt_GetCodepointBitmapBoxSubpixel
--- stbtt_GetCodepointBox
--- stbtt_GetNumberOfFonts_internal
--- stbtt__get_svg
local function ttUSHORT(p, offset) return stbtt_uint16(p[offset + 1] * 256 + p[offset + 2]) end
local function ttSHORT(p, offset) return stbtt_int16(p[offset + 1] * 256 + p[offset + 2]) 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
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 ttBYTE(p, offset) return stbtt_uint8(p[offset + 1]) end
local function ttCHAR(p, offset) return stbtt_int8(p[offset + 1]) 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
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__isfont(font)
if stbtt_tag4(font, 49, 0, 0, 0) then return true end
if stbtt_tag(font, "typ1") then return true end
if stbtt_tag(font, "OTTO") then return true end
if stbtt_tag4(font, 0, 1, 0, 0) then return true end
if stbtt_tag(font, "true") then return true end
return false
end
local function stbtt__find_table(data, font_start, tag)
local num_tables = ttUSHORT(data, font_start + 4)
local tabledir = font_start + 12
for i = 0, num_tables - 1 do
local loc = tabledir + i * 16
if stbtt_tag(data, tag, loc + 0) then
return ttULONG(data, loc + 8)
end
end
return 0
end
local function stbtt_GetFontOffsetForIndex_internal(font_collection, index)
if stbtt__isfont(font_collection) then
if index == 0 then return 0 else return -1 end
end
if stbtt_tag(font_collection, "ttcf") then
if ttULONG(font_collection, 4) == 0x00010000 or ttULONG(font_collection, 4) == 0x00020000 then
local n = ttLONG(font_collection, 8)
if index >= n then
return -1
end
return ttULONG(font_collection, 12 + index * 4)
end
end
return -1
end
--- @param cff stbtt__buf
--- @param fontdict stbtt__buf
local function stbtt__get_subrs(cff, fontdict)
local private_loc = stbtt__dict_get_ints(fontdict, 18, 2)
if (private_loc[2] == 0 or private_loc[1] == 0) then
return stbtt__new_buf(nil, 0)
end
local pdict = stbtt__buf_range(cff, private_loc[2], private_loc[1])
local subrsoff = stbtt__dict_get_ints(pdict, 19, 1)
if subrsoff[1] == 0 then
return stbtt__new_buf(nil, 0)
end
stbtt__buf_seek(cff, private_loc[2] + subrsoff[1])
return stbtt__cff_get_index(cff)
end
--- @return bool
local function stbtt_InitFont_internal(info, data, fontstart)
local cmap
local numTables
info.data = data
info.fontstart = fontstart
info.cff = stbtt__new_buf(nil, 0)
cmap = stbtt__find_table(data, fontstart, "cmap")
info.loca = stbtt__find_table(data, fontstart, "loca")
info.head = stbtt__find_table(data, fontstart, "head")
info.glyf = stbtt__find_table(data, fontstart, "glyf")
info.hhea = stbtt__find_table(data, fontstart, "hhea")
info.hmtx = stbtt__find_table(data, fontstart, "hmtx")
info.kern = stbtt__find_table(data, fontstart, "kern")
info.gpos = stbtt__find_table(data, fontstart, "GPOS")
if (cmap == 0 or info.head == 0 or info.hhea == 0 or info.hmtx == 0) then
return false
end
if info.glyf ~= 0 then
if info.loca == 0 then
return false
end
else
local cff = stbtt__find_table(data, fontstart, "CFF ")
if cff == 0 then
return false
end
info.fontdicts = stbtt__new_buf(nil, 0)
info.fdselect = stbtt__new_buf(nil, 0)
info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- TODO: this should use size from table
local b = info.cff
-- read the header
stbtt__buf_skip(b, 2)
stbtt__buf_seek(b, stbtt__buf_get8(b))
-- TODO: the name INDEX could list multiple fonts, but we just use the first one.
stbtt__cff_get_index(b) -- name INDEX
local topdictidx = stbtt__cff_get_index(b)
local topdict = stbtt__cff_index_get(topdictidx, 0)
stbtt__cff_get_index(b) -- string INDEX
info.gsubrs = stbtt__cff_get_index(b)
local charstrings = stbtt__dict_get_ints(topdict, 17, 1)
local cstype = stbtt__dict_get_ints(topdict, bit32.bor(0x100, 6), 1)
local fdarrayoff = stbtt__dict_get_ints(topdict, bit32.bor(0x100, 36), 1)
local fdselectoff = stbtt__dict_get_ints(topdict, bit32.bor(0x100, 37), 1)
info.subrs = stbtt__get_subrs(b, topdict)
if cstype[1] ~= 2 then
return false
end
if charstrings[1] == 0 then
return false
end
if fdarrayoff[1] ~= 0 then
if fdselectoff[1] == 0 then
return false
end
stbtt__buf_seek(b, fdarrayoff[1])
info.fontdicts = stbtt__cff_get_index(b)
info.fdselect = stbtt__buf_range(b, fdselectoff[1], b.size - fdselectoff[1])
end
stbtt__buf_seek(b, charstrings[1])
info.charstrings = stbtt__cff_get_index(b)
end
local t = stbtt__find_table(data, fontstart, "maxp")
if t ~= 0 then
info.numGlyphs = ttUSHORT(data, t + 4)
else
info.numGlyphs = 0xffff
end
info.svg = -1
numTables = ttUSHORT(data, cmap + 2)
info.index_map = 0
for i = 0, numTables - 1 do
local encoding_record = cmap + 4 + 8 * i
local platform_id = ttUSHORT(data, encoding_record)
if platform_id == STBTT_PLATFORM_ID.MICROSOFT then
local ms_eid = ttUSHORT(data, encoding_record + 2)
if ms_eid == STBTT_MS_EID.UNICODE_BMP or ms_eid == STBTT_MS_EID.UNICODE_FULL then
info.index_map = cmap + ttULONG(data, encoding_record + 4)
end
elseif platform_id == STBTT_PLATFORM_ID.UNICODE then
info.index_map = cmap + ttULONG(data, encoding_record + 4)
end
end
if info.index_map == 0 then
return false
end
info.indexToLocFormat = ttUSHORT(data, info.head + 50)
return true
end
--- @param info stbtt_fontinfo
--- @param unicode_codepoint int
function stbtt_FindGlyphIndex(info, unicode_codepoint)
local data = info.data
local index_map = info.index_map
local format = ttUSHORT(data, index_map + 0)
if format == 0 then
local bytes = ttUSHORT(data, index_map + 2)
if unicode_codepoint < bytes - 6 then
return ttBYTE(data, index_map + 6 + unicode_codepoint)
end
return 0
elseif format == 6 then
local first = ttUSHORT(data, index_map + 6)
local count = ttUSHORT(data, index_map + 8)
if unicode_codepoint >= first and unicode_codepoint < first + count then
return ttUSHORT(data, index_map + 10 + (unicode_codepoint - first) * 2)
end
return 0
elseif format == 2 then
STBTT_assert(false) -- TODO: high-byte mapping for japanese/chinese/korean
return 0
elseif format == 4 then
local segcount = bit32.rshift(ttUSHORT(data, index_map + 6), 1)
local searchRange = bit32.rshift(ttUSHORT(data, index_map + 8), 1)
local entrySelector = ttUSHORT(data, index_map + 10)
local rangeShift = bit32.rshift(ttUSHORT(data, index_map + 12), 1)
local endCount = index_map + 14
local search = endCount
if unicode_codepoint > 0xffff then
return 0
end
if unicode_codepoint >= ttUSHORT(data, search + rangeShift * 2) then
search = search + rangeShift * 2
end
search = search - 2
while entrySelector ~= 0 do
searchRange = bit32.rshift(searchRange, 1)
local _end = ttUSHORT(data, search + searchRange * 2)
if unicode_codepoint > _end then
search = search + searchRange * 2
end
entrySelector = entrySelector - 1
end
search = search + 2
do
local item = stbtt_uint16(bit32.rshift(search - endCount, 1))
local start = ttUSHORT(data, index_map + 14 + segcount * 2 + 2 + 2 * item)
local last = ttUSHORT(data, endCount + 2 * item)
if unicode_codepoint < start or unicode_codepoint > last then
return 0
end
local offset = ttUSHORT(data, index_map + 14 + segcount * 6 + 2 + 2 * item)
if offset == 0 then
return stbtt_uint16(unicode_codepoint + ttSHORT(data, index_map + 14 + segcount * 4 + 2 + 2 * item))
end
return ttUSHORT(data, offset + (unicode_codepoint - start) * 2 + index_map + 14 + segcount * 6 + 2 + 2 * item)
end
elseif format == 12 or format == 13 then
local ngroups = ttULONG(data, index_map + 12)
local low = 0
local high = ngroups
while low < high do
local mid = low + bit32.rshift(high - low, 1)
local start_char = ttULONG(data, index_map + 16 + mid * 12)
local end_char = ttULONG(data, index_map + 16 + mid * 12 + 4)
if unicode_codepoint < start_char then
high = mid
elseif unicode_codepoint > end_char then
low = mid + 1
else
local start_glyph = ttULONG(data, index_map + 16 + mid * 12 + 8)
if format == 12 then
return start_glyph + unicode_codepoint - start_char
else -- format == 13
return start_glyph
end
end
end
return 0
end
-- TODO:
STBTT_assert(false)
return 0
end
--- @param v stbtt_vertex
--- @param vtx_type STBTT_VTX
--- @param x stbtt_int32
--- @param y stbtt_int32
--- @param cx stbtt_int32
--- @param cy stbtt_int32
local function stbtt_setvertex(v, vtx_type, x, y, cx, cy)
v.type = vtx_type
v.x = (stbtt_int16)(x)
v.y = (stbtt_int16)(y)
v.cx = (stbtt_int16)(cx)
v.cy = (stbtt_int16)(cy)
end
local function stbtt__GetGlyfOffset(info, glyph_index)
STBTT_assert(info.cff.size == 0)
if glyph_index >= info.numGlyphs then return -1 end
if info.indexToLocFormat >= 2 then return -1 end
local g1, g2
if info.indexToLocFormat == 0 then
g1 = info.glyf + ttUSHORT(info.data, info.loca + glyph_index * 2) * 2
g2 = info.glyf + ttUSHORT(info.data, info.loca + glyph_index * 2 + 2) * 2
else
g1 = info.glyf + ttULONG(info.data, info.loca + glyph_index * 4)
g2 = info.glyf + ttULONG(info.data, info.loca + glyph_index * 4 + 4)
end
if g1 == g2 then return -1 else return g1 end
end
--- @return integer, integer?, integer?, integer?, integer?
local function stbtt_GetGlyphBox(info, glyph_index)
local n, x0, y0, x1, y1
if info.cff.size ~= 0 then
n, x0, y0, x1, y1 = stbtt__GetGlyphInfoT2(info, glyph_index)
else
local g = stbtt__GetGlyfOffset(info, glyph_index)
if g < 0 then return 0 end
x0 = ttSHORT(info.data, g + 2)
y0 = ttSHORT(info.data, g + 4)
x1 = ttSHORT(info.data, g + 6)
y1 = ttSHORT(info.data, g + 8)
end
return 1, x0, y0, x1, y1
end
--- @param vertices stbtt_vertex[]
--- @param num_vertices int
--- @param was_off bool
--- @param start_off bool
--- @param sx stbtt_int32
--- @param sy stbtt_int32
--- @param scx stbtt_int32
--- @param scy stbtt_int32
--- @param cx stbtt_int32
--- @param cy stbtt_int32
local function stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy)
if start_off then
if was_off then
stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.CURVE, bit32.rshift(cx + scx, 1), bit32.rshift(cy + scy, 1), cx, cy)
num_vertices = num_vertices + 1
end
stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.CURVE, sx, sy, scx, scy)
num_vertices = num_vertices + 1
else
if was_off then
stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.CURVE, sx, sy, cx, cy)
num_vertices = num_vertices + 1
else
stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.LINE, sx, sy, 0, 0)
num_vertices = num_vertices + 1
end
end
return num_vertices
end
--- @param info stbtt_fontinfo
--- @param glyph_index int
--- @return int num_vertices
--- @return stbtt_vertex[]? vertices
local function stbtt__GetGlyphShapeTT(info, glyph_index)
local data = info.data
local num_vertices
local vertices = nil
local g = stbtt__GetGlyfOffset(info, glyph_index)
if g < 0 then return 0 end
local numberOfContours = ttSHORT(data, g)
if numberOfContours > 0 then
local endPtsOfContours = g + 10
local ins = ttUSHORT(data, endPtsOfContours + numberOfContours * 2)
local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- 1-based idx
local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2)
local m = n + 2 * numberOfContours
vertices = {}
for i = 1, m do vertices[i] = stbtt_vertex() end
local j = 0
local was_off = false
local start_off = false
local next_move = 0
local flagcount = 0
local off = m - n
-- first load flags
local flags = 0
for i = 1, n do
if flagcount == 0 then
flags = data[points]
points = points + 1
if bit32.band(flags, 8) ~= 0 then
flagcount = data[points]
points = points + 1
end
else
flagcount = flagcount - 1
end
vertices[off + i].type = flags
end
-- now load x coordinates
local x = 0
for i = 1, n do
flags = vertices[off + i].type
if bit32.band(flags, 2) ~= 0 then
local dx = data[points]
points = points + 1
if bit32.band(flags, 16) ~= 0 then
x = x + dx
else
x = x - dx
end
else
if bit32.band(flags, 16) == 0 then
x = x + stbtt_int16(data[points] * 256 + data[points + 1])
points = points + 2
end
end
vertices[off + i].x = stbtt_int16(x)
end
-- now load y coordinates
local y = 0
for i = 1, n do
flags = vertices[off + i].type
if bit32.band(flags, 4) ~= 0 then
local dy = data[points]
points = points + 1
if bit32.band(flags, 32) ~= 0 then
y = y + dy
else
y = y - dy
end
else
if bit32.band(flags, 32) == 0 then
y = y + stbtt_int16(data[points] * 256 + data[points + 1])
points = points + 2
end
end
vertices[off + i].y = stbtt_int16(y)
end
-- now convert them to our format
num_vertices = 0
local sx, sy, cx, cy, scx, scy = 0, 0, 0, 0, 0, 0
for i = 1, n do
flags = vertices[off + i].type
x = stbtt_int16(vertices[off + i].x)
y = stbtt_int16(vertices[off + i].y)
if next_move == i - 1 then
if i ~= 1 then
num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy)
end
-- now start the new one
start_off = (bit32.band(flags, 1) == 0)
if start_off then
scx = x
scy = y
if bit32.band(vertices[off + i + 1].type, 1) == 0 then
sx = bit32.rshift(x + stbtt_int32(vertices[off + i + 1].x), 1)
sy = bit32.rshift(y + stbtt_int32(vertices[off + i + 1].y), 1)
else
sx = stbtt_int32(vertices[off + i + 1].x)
sy = stbtt_int32(vertices[off + i + 1].y)
i = i + 1
end
else
sx = x
sy = y
end
stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.MOVE, sx, sy, 0, 0)
num_vertices = num_vertices + 1
was_off = false
next_move = 1 + ttUSHORT(data, endPtsOfContours + j * 2)
j = j + 1
else
if bit32.band(flags, 1) == 0 then
if was_off then
stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.CURVE, bit32.rshift(cx + x, 1), bit32.rshift(cy + y, 1), cx, cy)
num_vertices = num_vertices + 1
end
cx = x
cy = y
was_off = true
else
if was_off then
stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.CURVE, x, y, cx, cy)
num_vertices = num_vertices + 1
else
stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.LINE, x, y, 0, 0)
num_vertices = num_vertices + 1
end
was_off = false
end
end
end
num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy)
elseif numberOfContours < 0 then
local more = 1
local comp = g + 10
num_vertices = 0
while more ~= 0 do
local flags, gidx
local comp_num_vertices = 0
local comp_verts
local mtx = {1, 0, 0, 1, 0, 0}
local m, n
flags = ttSHORT(data, comp) comp = comp + 2
gidx = ttSHORT(data, comp) comp = comp + 2
if bit32.band(flags, 2) ~= 0 then
if bit32.band(flags, 1) ~= 0 then
mtx[5] = ttSHORT(data, comp) comp = comp + 2
mtx[6] = ttSHORT(data, comp) comp = comp + 2
else
mtx[5] = ttCHAR(data, comp) comp = comp + 1
mtx[6] = ttCHAR(data, comp) comp = comp + 1
end
else
-- TODO: handle matching point
STBTT_assert(false)
end
if bit32.band(flags, bit32.lshift(1, 3)) ~= 0 then -- WE_HAVE_A_SCALE
mtx[4] = ttSHORT(data, comp) / 16384.0
mtx[1] = mtx[4]
comp = comp + 2
mtx[3] = 0
mtx[2] = mtx[3]
elseif bit32.band(flags, bit32.lshift(1, 6)) ~= 0 then -- WE_HAVE_AN_X_AND_YSCALE
mtx[1] = ttSHORT(data, comp) / 16384.0
comp = comp + 2
mtx[3] = 0
mtx[2] = mtx[3]
mtx[4] = ttSHORT(data, comp) / 16384.0
comp = comp + 2
elseif bit32.band(flags, bit32.lshift(1, 7)) ~= 0 then -- WE_HAVE_A_TWO_BY_TWO
mtx[1] = ttSHORT(data, comp) / 16384.0 comp = comp + 2
mtx[2] = ttSHORT(data, comp) / 16384.0 comp = comp + 2
mtx[3] = ttSHORT(data, comp) / 16384.0 comp = comp + 2
mtx[4] = ttSHORT(data, comp) / 16384.0 comp = comp + 2
end
m = STBTT_sqrt(mtx[1] * mtx[1] + mtx[2] * mtx[2])
n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4])
comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx)
if comp_num_vertices > 0 then
for i = 1, comp_num_vertices do
local v = comp_verts[i]
local x = v.x
local y = v.y
v.x = stbtt_int16(m * (mtx[1] * x + mtx[3] * y + mtx[5]))
v.y = stbtt_int16(n * (mtx[2] * x + mtx[4] * y + mtx[6]))
x = v.cx
y = v.cy
v.cx = stbtt_int16(m * (mtx[1] * x + mtx[3] * y + mtx[5]))
v.cy = stbtt_int16(n * (mtx[2] * x + mtx[4] * y + mtx[6]))
end
if num_vertices == 0 then -- LUA: No malloc
vertices = comp_verts
else
for i = 1, comp_num_vertices do
vertices[num_vertices + i] = comp_verts[i]
end
end
num_vertices = num_vertices + comp_num_vertices
end
more = bit32.band(flags, bit32.lshift(1, 5))
end
end
return num_vertices, vertices
end
--- @param c stbtt__csctx
--- @param x stbtt_int32
--- @param y stbtt_int32
local function stbtt__track_vertex(c, x, y)
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 x < c.min_x or not c.started then c.min_x = x end
if y < c.min_y or not c.started then c.min_y = y end
c.started = true
end
--- @param c stbtt__csctx
--- @param vtx_type STBTT_VTX
--- @param x stbtt_int32
--- @param y stbtt_int32
--- @param cx stbtt_int32
--- @param cy stbtt_int32
--- @param cx1 stbtt_int32
--- @param cy1 stbtt_int32
local function stbtt__csctx_v(c, vtx_type, x, y, cx, cy, cx1, cy1)
if c.bounds then
stbtt__track_vertex(c, x, y)
if vtx_type == STBTT_VTX.CUBIC then
stbtt__track_vertex(c, cx, cy)
stbtt__track_vertex(c, cx1, cy1)
end
else
stbtt_setvertex(c.pvertices[c.num_vertices + 1], vtx_type, x, y, cx, cy)
c.pvertices[c.num_vertices + 1].cx1 = stbtt_int16(cx1)
c.pvertices[c.num_vertices + 1].cy1 = stbtt_int16(cy1)
end
end
--- @param ctx stbtt__csctx
local function stbtt__csctx_close_shape(ctx)
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)
end
end
--- @param ctx stbtt__csctx
--- @param dx float
--- @param dy float
local function stbtt__csctx_rmove_to(ctx, dx, dy)
stbtt__csctx_close_shape(ctx)
ctx.x = ctx.x + dx
ctx.first_x = ctx.x
ctx.y = ctx.y + dy
ctx.first_y = ctx.y
stbtt__csctx_v(ctx, STBTT_VTX.MOVE, trunc(ctx.x), trunc(ctx.y), 0, 0, 0, 0)
end
--- @param ctx stbtt__csctx
--- @param dx float
--- @param dy float
local function stbtt__csctx_rline_to(ctx, dx, dy)
ctx.x = ctx.x + dx
ctx.y = ctx.y + dy
stbtt__csctx_v(ctx, STBTT_VTX.LINE, trunc(ctx.x), trunc(ctx.y), 0, 0, 0, 0)
end
--- @param ctx stbtt__csctx
--- @param dx1 float
--- @param dy1 float
--- @param dx2 float
--- @param dy2 float
--- @param dx3 float
--- @param dy3 float
local function stbtt__csctx_rccurve_to(ctx, dx1, dy1, dx2, dy2, dx3, dy3)
local cx1 = ctx.x + dx1
local cy1 = ctx.y + dy1
local cx2 = cx1 + dx2
local cy2 = cy1 + dy2
ctx.x = cx2 + dx3
ctx.y = cy2 + dy3
stbtt__csctx_v(ctx, STBTT_VTX.CUBIC, trunc(ctx.x), trunc(ctx.y), trunc(cx1), trunc(cy1), trunc(cx2), trunc(cy2))
end
local function stbtt__get_subr(idx, n)
local count = stbtt__cff_index_count(idx)
local bias = 107
if count >= 33900 then
bias = 32768
elseif count >= 1240 then
bias = 1131
end
n = n + bias
if n < 0 or n >= count then
return stbtt__new_buf(nil, 0)
end
return stbtt__cff_index_get(idx, n)
end
local function stbtt__cid_get_glyph_subrs(info, glyph_index)
local fdselect = info.fdselect
local fdselector = -1
stbtt__buf_seek(fdselect, 0)
local fmt = stbtt__buf_get8(fdselect)
if fmt == 0 then
-- untested
stbtt__buf_skip(fdselect, glyph_index)
fdselector = stbtt__buf_get8(fdselect)
elseif fmt == 3 then
local nranges = stbtt__buf_get16(fdselect)
local start = stbtt__buf_get16(fdselect)
for i = 0, nranges - 1 do
local v = stbtt__buf_get8(fdselect)
local _end = stbtt__buf_get16(fdselect)
if glyph_index >= start and glyph_index < _end then
fdselector = v
break
end
start = _end
end
end
if fdselector == -1 then return stbtt__new_buf(nil, 0) end -- [DEAR IMGUI] fixed, see #6007 and nothings/stb#1422
return stbtt__get_subrs(info.cff, stbtt__cff_index_get(info.fontdicts, fdselector))
end
--- @param info stbtt_fontinfo
--- @param glyph_index int
--- @param c stbtt__csctx
local function stbtt__run_charstring(info, glyph_index, c)
local in_header = true
local maskbits = 0
local subr_stack_height = 0
local sp = 0
local has_subrs = 0
local clear_stack
local s = {} -- size = 48, 0-based
local subr_stack = {} for i = 1, 10 do subr_stack[i] = stbtt__buf() end
local subrs = info.subrs
local b, f
local function STBTT__CSERR(_s) return 0 end
-- this currently ignores the initial width value, which isn't needed if we have hmtx
b = stbtt__cff_index_get(info.charstrings, glyph_index)
local i, v, b0
while b.cursor < b.size do
i = 0
clear_stack = 1
b0 = stbtt__buf_get8(b)
-- TODO: implement hinting
if b0 == 0x13 or b0 == 0x14 then -- hintmask or cntrmask
if in_header then
maskbits = maskbits + trunc(sp / 2) -- implicit "vstem"
end
in_header = false
stbtt__buf_skip(b, trunc((maskbits + 7) / 8))
elseif b0 == 0x01 or b0 == 0x03 or b0 == 0x12 or b0 == 0x17 then -- hstem, vstem, hstemhm, vstemhm
maskbits = maskbits + trunc(sp / 2)
elseif b0 == 0x15 then -- rmoveto
in_header = false
if sp < 2 then return STBTT__CSERR("rmoveto stack") end
stbtt__csctx_rmove_to(c, s[sp - 2], s[sp - 1])
elseif b0 == 0x04 then -- vmoveto
in_header = false
if sp < 1 then return STBTT__CSERR("vmoveto stack") end
stbtt__csctx_rmove_to(c, 0, s[sp - 1])
elseif b0 == 0x16 then -- hmoveto
in_header = false
if sp < 1 then return STBTT__CSERR("hmoveto stack") end
stbtt__csctx_rmove_to(c, s[sp - 1], 0)
elseif b0 == 0x05 then -- rlineto
if sp < 2 then return STBTT__CSERR("rlineto stack") end
while i + 1 < sp do
stbtt__csctx_rline_to(c, s[i], s[i + 1])
i = i + 2
end
-- hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical
-- starting from a different place.
elseif b0 == 0x07 then -- vlineto
if sp < 1 then return STBTT__CSERR("vlineto stack") end
while true do
if i >= sp then break end
stbtt__csctx_rline_to(c, 0, s[i])
i = i + 1
if i >= sp then break end
stbtt__csctx_rline_to(c, s[i], 0)
i = i + 1
end
elseif b0 == 0x06 then -- hlineto
if sp < 1 then return STBTT__CSERR("hlineto stack") end
while true do
if i >= sp then break end
stbtt__csctx_rline_to(c, s[i], 0)
i = i + 1
-- vlineto
if i >= sp then break end
stbtt__csctx_rline_to(c, 0, s[i])
i = i + 1
end
elseif b0 == 0x1F then -- hvcurveto
if sp < 4 then return STBTT__CSERR("hvcurveto stack") end
while true do
if i + 3 >= sp then break end
stbtt__csctx_rccurve_to(c, s[i], 0, s[i + 1], s[i + 2], ((sp - i) == 5) and s[i + 4] or 0.0, s[i + 3])
i = i + 4
if i + 3 >= sp then break end
stbtt__csctx_rccurve_to(c, 0, s[i], s[i + 1], s[i + 2], s[i + 3], ((sp - i) == 5) and s[i + 4] or 0.0)
i = i + 4
end
elseif b0 == 0x1E then -- vhcurveto
if sp < 4 then return STBTT__CSERR("vhcurveto stack") end
while true do
if i + 3 >= sp then break end
stbtt__csctx_rccurve_to(c, 0, s[i], s[i + 1], s[i + 2], s[i + 3], ((sp - i) == 5) and s[i + 4] or 0.0)
i = i + 4
-- hvcurveto
if i + 3 >= sp then break end
stbtt__csctx_rccurve_to(c, s[i], 0, s[i + 1], s[i + 2], ((sp - i) == 5) and s[i + 4] or 0.0, s[i + 3])
i = i + 4
end
elseif b0 == 0x08 then -- rrcurveto
if sp < 6 then return STBTT__CSERR("rcurveline stack") end
while i + 5 < sp do
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5])
i = i + 6
end
elseif b0 == 0x18 then -- rcurveline
if sp < 8 then return STBTT__CSERR("rcurveline stack") end
while i + 5 < sp - 2 do
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5])
i = i + 6
end
if i + 1 >= sp then return STBTT__CSERR("rcurveline stack") end
stbtt__csctx_rline_to(c, s[i], s[i + 1])
elseif b0 == 0x19 then -- rlinecurve
if sp < 8 then return STBTT__CSERR("rlinecurve stack") end
while i + 1 < sp - 6 do
stbtt__csctx_rline_to(c, s[i], s[i + 1])
i = i + 2
end
if i + 5 >= sp then return STBTT__CSERR("rlinecurve stack") end
stbtt__csctx_rccurve_to(c, s[i], s[i + 1], s[i + 2], s[i + 3], s[i + 4], s[i + 5])
elseif b0 == 0x1A or b0 == 0x1B then -- vvcurveto or hhcurveto
if sp < 4 then return STBTT__CSERR("(vv|hh)curveto stack") end
f = 0.0
if bit32.band(sp, 1) ~= 0 then
f = s[i]
i = i + 1
end
while i + 3 < sp do
if b0 == 0x1B then
stbtt__csctx_rccurve_to(c, s[i], f, s[i + 1], s[i + 2], s[i + 3], 0.0)
else
stbtt__csctx_rccurve_to(c, f, s[i], s[i + 1], s[i + 2], 0.0, s[i + 3])
end
f = 0.0
i = i + 4
end
elseif b0 == 0x0A -- callsubr
or b0 == 0x1D then
if b0 == 0x0A and has_subrs == 0 then
if info.fdselect.size ~= 0 then
subrs = stbtt__cid_get_glyph_subrs(info, glyph_index)
end
has_subrs = 1
end
-- callgsubr
if sp < 1 then return STBTT__CSERR("call(g|)subr stack") end
sp = sp - 1
v = trunc(s[sp])
if subr_stack_height >= 10 then return STBTT__CSERR("recursion limit") end
subr_stack[subr_stack_height + 1] = b
subr_stack_height = subr_stack_height + 1
b = stbtt__get_subr((b0 == 0x0A) and subrs or info.gsubrs, v)
if b.size == 0 then return STBTT__CSERR("subr not found") end
b.cursor = 0
clear_stack = 0
elseif b0 == 0x0B then -- return
if subr_stack_height <= 0 then return STBTT__CSERR("return outside subr") end
subr_stack_height = subr_stack_height - 1
b = subr_stack[subr_stack_height + 1]
clear_stack = 0
elseif b0 == 0x0E then -- endchar
stbtt__csctx_close_shape(c)
return 1
elseif b0 == 0x0C then -- two-byte escape
local b1 = stbtt__buf_get8(b)
if b1 == 0x22 then -- hflex
if sp < 7 then return STBTT__CSERR("hflex stack") end
local dx1 = s[0]
local dx2 = s[1]
local dy2 = s[2]
local dx3 = s[3]
local dx4 = s[4]
local dx5 = s[5]
local dx6 = s[6]
stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0)
stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0)
elseif b1 == 0x23 then -- flex
if sp < 13 then return STBTT__CSERR("flex stack") end
local dx1 = s[0]
local dy1 = s[1]
local dx2 = s[2]
local dy2 = s[3]
local dx3 = s[4]
local dy3 = s[5]
local dx4 = s[6]
local dy4 = s[7]
local dx5 = s[8]
local dy5 = s[9]
local dx6 = s[10]
local dy6 = s[11]
-- fd is s[12]
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3)
stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6)
elseif b1 == 0x24 then -- hflex1
if sp < 9 then return STBTT__CSERR("hflex1 stack") end
local dx1 = s[0]
local dy1 = s[1]
local dx2 = s[2]
local dy2 = s[3]
local dx3 = s[4]
local dx4 = s[5]
local dx5 = s[6]
local dy5 = s[7]
local dx6 = s[8]
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0)
stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1 + dy2 + dy5))
elseif b1 == 0x25 then -- flex1
if sp < 11 then return STBTT__CSERR("flex1 stack") end
local dx1 = s[0]
local dy1 = s[1]
local dx2 = s[2]
local dy2 = s[3]
local dx3 = s[4]
local dy3 = s[5]
local dx4 = s[6]
local dy4 = s[7]
local dx5 = s[8]
local dy5 = s[9]
local dx6 = s[10]
local dy6 = s[10]
local dx = dx1 + dx2 + dx3 + dx4 + dx5
local dy = dy1 + dy2 + dy3 + dy4 + dy5
if STBTT_fabs(dx) > STBTT_fabs(dy) then
dy6 = -dy
else
dx6 = -dx
end
stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3)
stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6)
else
return STBTT__CSERR("unimplemented")
end
else
if b0 ~= 255 and b0 ~= 28 and b0 < 32 then
return STBTT__CSERR("reserved operator")
end
-- push immediate
if b0 == 255 then
f = stbtt__buf_get32(b) / 0x10000
else
stbtt__buf_skip(b, -1)
f = stbtt_int16(stbtt__cff_int(b))
end
if sp >= 48 then return STBTT__CSERR("push stack overflow") end
s[sp] = f
sp = sp + 1
clear_stack = 0
end
if clear_stack ~= 0 then
sp = 0
end
end
return STBTT__CSERR("no endchar")
end
--- @param info stbtt_fontinfo
--- @param glyph_index int
--- @return int num_vertices
--- @return stbtt_vertex[]? vertices
function stbtt__GetGlyphShapeT2(info, glyph_index)
-- runs the charstring twice, once to count and once to output (to avoid realloc)
local vertices = nil
local count_ctx = STBTT__CSCTX_INIT(true)
local output_ctx = STBTT__CSCTX_INIT(false)
if stbtt__run_charstring(info, glyph_index, count_ctx) ~= 0 then
vertices = {} for i = 1, count_ctx.num_vertices do vertices[i] = stbtt_vertex() end
output_ctx.pvertices = vertices
if stbtt__run_charstring(info, glyph_index, output_ctx) ~= 0 then
STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices)
return output_ctx.num_vertices, vertices
end
end
return 0, vertices
end
--- @param info stbtt_fontinfo
--- @param glyph_index int
--- @return int
--- @return int x0
--- @return int y0
--- @return int x1
--- @return int y1
function stbtt__GetGlyphInfoT2(info, glyph_index)
local c = STBTT__CSCTX_INIT(true)
local r = stbtt__run_charstring(info, glyph_index, c)
local x0 = (r ~= 0) and c.min_x or 0
local y0 = (r ~= 0) and c.min_y or 0
local x1 = (r ~= 0) and c.max_x or 0
local y1 = (r ~= 0) and c.max_y or 0
return ((r ~= 0) and c.num_vertices or 0), x0, y0, x1, y1
end
--- @param info stbtt_fontinfo
--- @param glyph_index int
function stbtt_GetGlyphShape(info, glyph_index)
if info.cff.size == 0 then
return stbtt__GetGlyphShapeTT(info, glyph_index)
else
return stbtt__GetGlyphShapeT2(info, glyph_index)
end
end
--- @param info stbtt_fontinfo
--- @param glyph_index int
function stbtt_GetGlyphHMetrics(info, glyph_index)
local numOfLongHorMetrics = ttUSHORT(info.data, info.hhea + 34)
local advanceWidth, leftSideBearing
if glyph_index < numOfLongHorMetrics then
advanceWidth = ttSHORT(info.data, info.hmtx + 4 * glyph_index)
leftSideBearing = ttSHORT(info.data, info.hmtx + 4 * glyph_index + 2)
else
advanceWidth = ttSHORT(info.data, info.hmtx + 4 * (numOfLongHorMetrics - 1))
leftSideBearing = ttSHORT(info.data, info.hmtx + 4 * numOfLongHorMetrics + 2 * (glyph_index - numOfLongHorMetrics))
end
return advanceWidth, leftSideBearing
end
--- @param info stbtt_fontinfo
function stbtt_GetFontVMetrics(info)
local ascent = ttSHORT(info.data, info.hhea + 4)
local descent = ttSHORT(info.data, info.hhea + 6)
local lineGap = ttSHORT(info.data, info.hhea + 8)
return ascent, descent, lineGap
end
--- @param info stbtt_fontinfo
--- @param height float
function stbtt_ScaleForPixelHeight(info, height)
local fheight = ttSHORT(info.data, info.hhea + 4) - ttSHORT(info.data, info.hhea + 6)
return height / fheight
end
------------------------------------
------------------------------------
---
--- Antialiasing software rasterizer
---
---
--- @param font stbtt_fontinfo
--- @param glyph int
--- @param scale_x float
--- @param scale_y float
--- @param shift_x float
--- @param shift_y float
function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, shift_y)
local n, x0, y0, x1, y1 = stbtt_GetGlyphBox(font, glyph)
local ix0, iy0, ix1, iy1
if n == 0 then
-- e.g. space character
ix0 = 0
iy0 = 0
ix1 = 0
iy1 = 0
else
-- move to integral bboxes (treating pixels as little squares, what pixels get touched)?
ix0 = STBTT_ifloor( x0 * scale_x + shift_x)
iy0 = STBTT_ifloor(-y1 * scale_y + shift_y)
ix1 = STBTT_iceil( x1 * scale_x + shift_x)
iy1 = STBTT_iceil(-y0 * scale_y + shift_y)
end
return ix0, iy0, ix1, iy1
end
--- @param font stbtt_fontinfo
--- @param glyph int
--- @param scale_x float
--- @param scale_y float
function stbtt_GetGlyphBitmapBox(font, glyph, scale_x, scale_y)
return stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, 0.0, 0.0)
end
--------------
--------------
---
--- Rasterizer
---
---
--- UNIMPLEMENTED / UNUSED:
--- stbtt_MakeCodepointBitmap
--- stbtt_MakeCodepointBitmapSubpixelPrefilter
--- stbtt_GetGlyphBitmap
--- stbtt_MakeGlyphBitmap
--- stbtt_GetGlyphBitmapSubpixel
--- @param scanline float[]
--- @param x int
--- @param e stbtt__active_edge
--- @param x0 float
--- @param y0 float
--- @param x1 float
--- @param y1 float
local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1)
if y0 == y1 then return end
STBTT_assert(y0 < y1)
STBTT_assert(e.sy <= e.ey)
if y0 > e.ey then return end
if y1 < e.sy then return end
if y0 < e.sy then
x0 = x0 + (x1 - x0) * (e.sy - y0) / (y1 - y0)
y0 = e.sy
end
if y1 > e.ey then
x1 = x1 + (x1 - x0) * (e.ey - y1) / (y1 - y0)
y1 = e.ey
end
if x0 == x then
STBTT_assert(x1 <= x + 1)
elseif x0 == x + 1 then
STBTT_assert(x1 >= x)
elseif x0 <= x then
STBTT_assert(x1 <= x)
elseif x0 >= x + 1 then
STBTT_assert(x1 >= x + 1)
else
STBTT_assert(x1 >= x and x1 <= x + 1)
end
if x0 <= x and x1 <= x then
scanline[x] = scanline[x] + e.direction * (y1 - y0)
elseif x0 >= x + 1 and x1 >= x + 1 then
-- do nothing
else
STBTT_assert(x0 >= x and x0 <= x + 1 and x1 >= x and x1 <= x + 1)
scanline[x] = scanline[x] + e.direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2)
end
end
--- @param height float
--- @param top_width float
--- @param bottom_width float
local function stbtt__sized_trapezoid_area(height, top_width, bottom_width)
STBTT_assert(top_width >= 0)
STBTT_assert(bottom_width >= 0)
return (top_width + bottom_width) / 2.0 * height
end
--- @param height float
--- @param tx0 float
--- @param tx1 float
--- @param bx0 float
--- @param bx1 float
local function stbtt__position_trapezoid_area(height, tx0, tx1, bx0, bx1)
return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0)
end
--- @param height float
--- @param width float
local function stbtt__sized_triangle_area(height, width)
return height * width / 2
end
--- @param scanline float[]
--- @param scanline_fill float[]
--- @param len int
--- @param e stbtt__active_edge
--- @param y_top float
local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_top)
local y_bottom = y_top + 1
while e do
-- brute force every pixel
-- compute intersection points with top & bottom
STBTT_assert(e.ey >= y_top)
if e.fdx == 0 then
local x0 = e.fx
if x0 < len then
if x0 >= 0 then
stbtt__handle_clipped_edge(scanline, trunc(x0), e, x0, y_top, x0, y_bottom)
stbtt__handle_clipped_edge(scanline_fill, trunc(x0) + 1, e, x0, y_top, x0, y_bottom)
else
stbtt__handle_clipped_edge(scanline_fill, 0, e, x0, y_top, x0, y_bottom)
end
end
else
local x0 = e.fx
local dx = e.fdx
local xb = x0 + dx
local x_top, x_bottom
local sy0, sy1
local dy = e.fdy
STBTT_assert(e.sy <= y_bottom and e.ey >= y_top)
-- compute endpoints of line segment clipped to this scanline (if the
-- line segment starts on this scanline. x0 is the intersection of the
-- line with y_top, but that may be off the line segment.
if e.sy > y_top then
x_top = x0 + dx * (e.sy - y_top)
sy0 = e.sy
else
x_top = x0
sy0 = y_top
end
if e.ey < y_bottom then
x_bottom = x0 + dx * (e.ey - y_top)
sy1 = e.ey
else
x_bottom = xb
sy1 = y_bottom
end
if x_top >= 0 and x_bottom >= 0 and x_top < len and x_bottom < len then
-- from here on, we don't have to range check x values
if trunc(x_top) == trunc(x_bottom) then
-- simple case, only spans one pixel
local height
local x = trunc(x_top)
height = (sy1 - sy0) * e.direction
STBTT_assert(x >= 0 and x < len)
scanline[x] = scanline[x] + stbtt__position_trapezoid_area(height, x_top, x + 1.0, x_bottom, x + 1.0)
scanline_fill[x + 1] = scanline_fill[x + 1] + height -- everything right of this pixel is filled
else
local x1, x2
local y_crossing, y_final, step, sign, area
-- covers 2+ pixels
if x_top > x_bottom then
-- flip scanline vertically; signed area is the same
sy0 = y_bottom - (sy0 - y_top)
sy1 = y_bottom - (sy1 - y_top)
local t
t = sy0; sy0 = sy1; sy1 = t
t = x_bottom; x_bottom = x_top; x_top = t
dx = -dx
dy = -dy
t = x0; x0 = xb; xb = t
end
STBTT_assert(dy >= 0)
STBTT_assert(dx >= 0)
x1 = trunc(x_top)
x2 = trunc(x_bottom)
-- compute intersection with y axis at x1+1
y_crossing = y_top + dy * (x1 + 1 - x0)
-- compute intersection with y axis at x2
y_final = y_top + dy * (x2 - x0)
-- if x2 is right at the right edge of x1, y_crossing can blow up, github #1057
-- TODO: maybe test against sy1 rather than y_bottom?
if y_crossing > y_bottom then
y_crossing = y_bottom
end
sign = e.direction
-- area of the rectangle covered from sy0..y_crossing
area = sign * (y_crossing - sy0)
-- area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing)
scanline[x1] = scanline[x1] + stbtt__sized_triangle_area(area, x1 + 1 - x_top)
-- check if final y_crossing is blown up; no test case for this
if y_final > y_bottom then
local denom = (x2 - (x1 + 1))
y_final = y_bottom
if denom ~= 0 then -- [DEAR IMGUI] Avoid div by zero (https://github.com/nothings/stb/issues/1316)
dy = (y_final - y_crossing) / denom -- if denom=0, y_final = y_crossing, so y_final <= y_bottom
end
end
step = sign * dy * 1 -- dy is dy/dx, change in y for every 1 change in x,
-- which multiplied by 1-pixel-width is how much pixel area changes for each step in x
-- so the area advances by 'step' every time
for x = x1 + 1, x2 - 1 do
scanline[x] = scanline[x] + area + step / 2 -- area of trapezoid is 1*step/2
area = area + step
end
STBTT_assert(STBTT_fabs(area) <= 1.01) -- accumulated error from area += step unless we round step down
STBTT_assert(sy1 > y_final - 0.01)
-- area covered in the last pixel is the rectangle from all the pixels to the left,
-- plus the trapezoid filled by the line segment in this pixel all the way to the right edge
scanline[x2] = scanline[x2] + area + sign * stbtt__position_trapezoid_area(sy1 - y_final, x2, x2 + 1.0, x_bottom, x2 + 1.0)
-- the rest of the line is filled based on the total height of the line segment in this pixel
scanline_fill[x2 + 1] = scanline_fill[x2 + 1] + sign * (sy1 - sy0)
end
else
for x = 0, len - 1 do
-- rename variables to clearly-defined pairs
local y0 = y_top
local x1 = x
local x2 = x + 1
local x3 = xb
local y3 = y_bottom
-- x = e->x + e->dx * (y-y_top)
-- (y-y_top) = (x - e->x) / e->dx
-- y = (x - e->x) / e->dx + y_top
local y1 = (x - x0) / dx + y_top
local y2 = (x + 1 - x0) / dx + y_top
if x0 < x1 and x3 > x2 then -- three segments descending down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1)
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x2, y2)
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3)
elseif x3 < x1 and x0 > x2 then -- three segments descending down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2)
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x1, y1)
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3)
elseif x0 < x1 and x3 > x1 then -- two segments across x, down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1)
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3)
elseif x3 < x1 and x0 > x1 then -- two segments across x, down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1)
stbtt__handle_clipped_edge(scanline, x, e, x1, y1, x3, y3)
elseif x0 < x2 and x3 > x2 then -- two segments across x+1, down-right
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2)
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3)
elseif x3 < x2 and x0 > x2 then -- two segments across x+1, down-left
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x2, y2)
stbtt__handle_clipped_edge(scanline, x, e, x2, y2, x3, y3)
else -- one segment
stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x3, y3)
end
end
end
end
e = e.next
end
end
--- @param result stbtt__bitmap
--- @param e stbtt__edge
--- @param n int
--- @param vsubsample int
--- @param off_x int
--- @param off_y int
local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y)
local active = nil
local scanline = {} -- size = result.w, 0-based
local scanline2 = {} -- size = result.w + 1, 0-based
STBTT__NOTUSED(vsubsample)
local y = off_y
e[n + 1].y0 = off_y + result.h + 1
local j = 0
local p = 1
while j < result.h do
-- find center of pixel for this scanline
local scan_y_top = y + 0.0
local scan_y_bottom = y + 1.0
for i = 0, result.w - 1 do scanline[i] = 0 end
for i = 0, result.w do scanline2[i] = 0 end
local prev = nil
local curr = active
while curr do
local next = curr.next
if curr.ey <= scan_y_top then
if prev then prev.next = next
else active = next end
curr.direction = 0
else
prev = curr
end
curr = next
end
local edge = e[p]
while edge.y0 <= scan_y_bottom do
if edge.y0 ~= edge.y1 then
local z = stbtt__new_active(edge, off_x, scan_y_top)
if j == 0 and off_y ~= 0 and z.ey < scan_y_top then
z.ey = scan_y_top
end
STBTT_assert(z.ey >= scan_y_top)
z.next = active
active = z
end
p = p + 1
edge = e[p]
end
if active then
stbtt__fill_active_edges_new(scanline, scanline2, result.w, active, scan_y_top)
end
do
local sum = 0
for i = 0, result.w - 1 do
local k
local m
sum = sum + scanline2[i]
k = scanline[i] + sum
k = STBTT_fabs(k) * 255 + 0.5
m = trunc(k)
if m > 255 then m = 255 end
result.pixels[j * result.stride + i + 1] = unsigned_char(m)
end
end
step = active
while step do
step.fx = step.fx + step.fdx
step = step.next
end
y = y + 1
j = j + 1
end
end
--- @param a stbtt__edge
--- @param b stbtt__edge
local STBTT__COMPARE = function(a, b)
if a.y0 == nil then return false end -- sentinels on the back
if b.y0 == nil then return true end
return a.y0 < b.y0
end
--- @param p stbtt__edge[]
local function stbtt__sort_edges(p)
STBTT_sort(p, STBTT__COMPARE)
end
--- @param result stbtt__bitmap
--- @param pts stbtt__point[]
--- @param wcount int[]
--- @param windings int
--- @param scale_x float
--- @param scale_y float
--- @param shift_x float
--- @param shift_y float
--- @param off_x int
--- @param off_y int
--- @param invert bool
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 vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2
-- now we have to blow out the windings into explicit edge lists
local n = 0
for i = 1, windings do
n = n + wcount[i]
end
local e = {} for i = 1, n + 1 do e[i] = stbtt__edge() end -- add an extra one as a sentinel
n = 0
local m = 0
local j
for i = 1, windings do
local p = m
m = m + wcount[i]
j = wcount[i]
for k = 1, wcount[i] do
repeat
local a = k
local b = j
-- skip the edge if horizontal
if pts[p + j].y == pts[p + k].y then
break
end
-- add edge from j to k to the list
n = n + 1
e[n].invert = false
if invert then
if pts[p + j].y > pts[p + k].y then
e[n].invert = true
a = j
b = k
end
else
if pts[p + j].y < pts[p + k].y then
e[n].invert = true
a = j
b = k
end
end
e[n].x0 = pts[p + a].x * scale_x + shift_x
e[n].y0 = (pts[p + a].y * y_scale_inv + shift_y) * vsubsample
e[n].x1 = pts[p + b].x * scale_x + shift_x
e[n].y1 = (pts[p + b].y * y_scale_inv + shift_y) * vsubsample
until true
j = k
end
end
-- now sort the edges by their highest point (should snap to integer, and then by x)
stbtt__sort_edges(e)
-- 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)
end
--- @param points? stbtt__point[]
--- @param n int
--- @param x float
--- @param y float
local function stbtt__add_point(points, n, x, y)
if points == nil then return end -- during first pass, it's unallocated
points[n + 1].x = x
points[n + 1].y = y
end
-- tessellate until threshold p is happy...
-- TODO: warped to compensate for non-linear stretching
--- @param points? stbtt__point[]
--- @param num_points int
--- @param x0 float
--- @param y0 float
--- @param x1 float
--- @param y1 float
--- @param x2 float
--- @param y2 float
--- @param objspace_flatness_squared float
--- @param n int
--- @return int num_points # updated num_points passed in
local function stbtt__tesselate_curve(points, num_points, x0, y0, x1, y1, x2, y2, objspace_flatness_squared, n)
-- midpoint
local mx = (x0 + 2 * x1 + x2) / 4
local my = (y0 + 2 * y1 + y2) / 4
-- versus directly drawn line
local dx = (x0 + x2) / 2 - mx
local dy = (y0 + y2) / 2 - my
if n > 16 then -- 65536 segments on one curve better be enough!
return num_points
end
if dx * dx + dy * dy > objspace_flatness_squared then -- half-pixel error allowed... need to be smaller if AA
num_points = stbtt__tesselate_curve(points, num_points, x0, y0, (x0 + x1) / 2.0, (y0 + y1) / 2.0, mx, my, objspace_flatness_squared, n + 1)
num_points = stbtt__tesselate_curve(points, num_points, mx, my, (x1 + x2) / 2.0, (y1 + y2) / 2.0, x2, y2, objspace_flatness_squared, n + 1)
else
stbtt__add_point(points, num_points, x2, y2)
num_points = num_points + 1
end
return num_points
end
--- @param points? stbtt__point[]
--- @param num_points int
--- @param x0 float
--- @param y0 float
--- @param x1 float
--- @param y1 float
--- @param x2 float
--- @param y2 float
--- @param x3 float
--- @param y3 float
--- @param objspace_flatness_squared float
--- @param n int
--- @return int num_points # updated num_points passed in
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
local dx0 = x1 - x0
local dy0 = y1 - y0
local dx1 = x2 - x1
local dy1 = y2 - y1
local dx2 = x3 - x2
local dy2 = y3 - y2
local dx = x3 - x0
local dy = y3 - y0
local longlen = STBTT_sqrt(dx0 * dx0 + dy0 * dy0) + STBTT_sqrt(dx1 * dx1 + dy1 * dy1) + STBTT_sqrt(dx2 * dx2 + dy2 * dy2)
local shortlen = STBTT_sqrt(dx * dx + dy * dy)
local flatness_squared = longlen * longlen - shortlen * shortlen
if n > 16 then -- 65536 segments on one curve better be enough!
return num_points
end
if flatness_squared > objspace_flatness_squared then
local x01 = (x0 + x1) / 2
local y01 = (y0 + y1) / 2
local x12 = (x1 + x2) / 2
local y12 = (y1 + y2) / 2
local x23 = (x2 + x3) / 2
local y23 = (y2 + y3) / 2
local xa = (x01 + x12) / 2
local ya = (y01 + y12) / 2
local xb = (x12 + x23) / 2
local yb = (y12 + y23) / 2
local mx = (xa + xb) / 2
local my = (ya + yb) / 2
num_points = stbtt__tesselate_cubic(points, num_points, x0, y0, x01, y01, xa, ya, mx, my, objspace_flatness_squared, n + 1)
num_points = stbtt__tesselate_cubic(points, num_points, mx, my, xb, yb, x23, y23, x3, y3, objspace_flatness_squared, n + 1)
else
stbtt__add_point(points, num_points, x3, y3)
num_points = num_points + 1
end
return num_points
end
--- @param vertices stbtt_vertex[]
--- @param num_verts int
--- @param objspace_flatness float
--- @return stbtt__point[]? points
--- @return int? num_contours
--- @return int[]? contour_lengths
local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness)
local points = nil
local num_points = 0
local objspace_flatness_squared = objspace_flatness * objspace_flatness
local n = 0
local start = 0
-- count how many "moves" there are to get the contour count
for i = 1, num_verts do
if vertices[i].type == STBTT_VTX.MOVE then
n = n + 1
end
end
local num_contours = n
if n == 0 then return nil end
local contour_lengths = {} -- size = n
-- make two passes through the points so we don't need to realloc
for pass = 0, 1 do
local x, y = 0, 0
if pass == 1 then
points = {}
for i = 1, num_points do points[i] = stbtt__point() end
end
num_points = 0
n = -1
for i = 1, num_verts do
if vertices[i].type == STBTT_VTX.MOVE then
-- start the next contour
if n >= 0 then
contour_lengths[n + 1] = num_points - start
end
n = n + 1
start = num_points
x = vertices[i].x
y = vertices[i].y
stbtt__add_point(points, num_points, x, y)
num_points = num_points + 1
elseif vertices[i].type == STBTT_VTX.LINE then
x = vertices[i].x
y = vertices[i].y
stbtt__add_point(points, num_points, x, y)
num_points = num_points + 1
elseif vertices[i].type == STBTT_VTX.CURVE then
num_points = stbtt__tesselate_curve(points, num_points, x, y,
vertices[i].cx, vertices[i].cy,
vertices[i].x, vertices[i].y,
objspace_flatness_squared, 0)
x = vertices[i].x
y = vertices[i].y
elseif vertices[i].type == STBTT_VTX.CUBIC then
num_points = stbtt__tesselate_cubic(points, num_points, x, y,
vertices[i].cx, vertices[i].cy,
vertices[i].cx1, vertices[i].cy1,
vertices[i].x, vertices[i].y,
objspace_flatness_squared, 0)
x = vertices[i].x
y = vertices[i].y
end
end
contour_lengths[n + 1] = num_points - start
end
return points, num_contours, contour_lengths
end
--- @param result stbtt__bitmap
--- @param flatness_in_pixels float
--- @param vertices stbtt_vertex[]
--- @param num_verts int
--- @param scale_x float
--- @param scale_y float
--- @param shift_x float
--- @param shift_y float
--- @param x_off int
--- @param y_off int
--- @param invert bool
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 windings, winding_count, winding_lengths = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale)
if windings then
--- @cast winding_lengths int[]
--- @cast winding_count int
stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert)
end
end
--- @param info stbtt_fontinfo
--- @param output unsigned_char[]
--- @param out_w int
--- @param out_h int
--- @param out_stride int
--- @param scale_x float
--- @param scale_y float
--- @param shift_x float
--- @param shift_y float
--- @param glyph int
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 gbm = stbtt__bitmap()
local ix0, iy0 = stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y)
gbm.pixels = output
gbm.w = out_w
gbm.h = out_h
gbm.stride = out_stride
if gbm.w ~= 0 and gbm.h ~= 0 then
stbtt_Rasterize(gbm, 0.35, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, true)
end
end
-----------------
-----------------
---
--- Bitmap baking
---
---
--- UNIMPLEMENTED / UNUSED:
--- stbtt_BakeFontBitmap_internal
--- stbtt_BakeFontBitmap
--- stbtt_GetBakedQuad
---------------------------
---------------------------
---
--- Bitmap baking / packing
---
---
--- UNIMPLEMENTED / UNUSED:
--- stbtt_PackBegin
--- stbtt_PackSetOversampling
--- stbtt_PackSetSkipMissingCodepoints
--- stbtt_PackFontRangesGatherRects
--- stbtt_PackFontRangesRenderIntoRects
--- stbtt_PackFontRangesPackRects
--- stbtt_PackFontRanges
--- stbtt_PackFontRange
--- stbtt_GetPackedQuad
--- stbtt_GetScaledFontVMetrics
local STBTT__OVER_MASK = STBTT_MAX_OVERSAMPLE - 1
--- @param pixels table
--- @param w int
--- @param h int
--- @param stride_in_bytes int
--- @param kernel_width unsigned_int
local function stbtt__h_prefilter(pixels, w, h, stride_in_bytes, kernel_width)
local buffer = {}
local safe_w = w - kernel_width
for j = 0, h - 1 do
local total = 0
local row_offset = j * stride_in_bytes
for i = 1, kernel_width do buffer[i] = 0 end
for i = 0, safe_w do
total = total + pixels[row_offset + i + 1] - buffer[bit32.band(i, STBTT__OVER_MASK) + 1]
buffer[bit32.band(i + kernel_width, STBTT__OVER_MASK) + 1] = pixels[row_offset + i + 1]
pixels[row_offset + i + 1] = unsigned_char(total / kernel_width)
end
for i = safe_w + 1, w - 1 do
STBTT_assert(pixels[row_offset + i + 1] == 0)
total = total - buffer[bit32.band(i, STBTT__OVER_MASK) + 1]
pixels[row_offset + i + 1] = unsigned_char(total / kernel_width)
end
end
end
--- @param pixels table
--- @param w int
--- @param h int
--- @param stride_in_bytes int
--- @param kernel_width unsigned_int
local function stbtt__v_prefilter(pixels, w, h, stride_in_bytes, kernel_width)
local buffer = {}
local safe_h = h - kernel_width
for j = 0, w - 1 do
local total = 0
local col_offset = j
for i = 1, kernel_width do buffer[i] = 0 end
for i = 0, safe_h do
total = total + pixels[col_offset + i * stride_in_bytes + 1] - buffer[bit32.band(i, STBTT__OVER_MASK) + 1]
buffer[bit32.band(i + kernel_width, STBTT__OVER_MASK) + 1] = pixels[col_offset + i * stride_in_bytes + 1]
pixels[col_offset + i * stride_in_bytes + 1] = unsigned_char(total / kernel_width)
end
for i = safe_h + 1, h - 1 do
STBTT_assert(pixels[col_offset + i * stride_in_bytes + 1] == 0)
total = total - buffer[bit32.band(i, STBTT__OVER_MASK) + 1]
pixels[col_offset + i * stride_in_bytes + 1] = unsigned_char(total / kernel_width)
end
end
end
--- @param oversample int
--- @return float
local function stbtt__oversample_shift(oversample)
if oversample == 0 then
return 0.0
end
return -(oversample - 1) / (2.0 * oversample)
end
--- @param info stbtt_fontinfo
--- @param output unsigned_char[]
--- @param out_w int
--- @param out_h int
--- @param out_stride int
--- @param scale_x float
--- @param scale_y float
--- @param shift_x float
--- @param shift_y float
--- @param prefilter_x int
--- @param prefilter_y int
--- @param glyph int
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)
if prefilter_x > 1 then
stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x)
end
if prefilter_y > 1 then
stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y)
end
local sub_x, sub_y
sub_x = stbtt__oversample_shift(prefilter_x)
sub_y = stbtt__oversample_shift(prefilter_y)
return sub_x, sub_y
end
-------------------
-------------------
---
--- SDF computation
---
---
--- UNIMPLEMENTED / UNUSED:
--- stbtt__ray_intersect_bezier
--- stbtt__compute_crossings_x
--- stbtt__cuberoot
--- stbtt__solve_cubic
--- stbtt_GetGlyphSDF
--- stbtt_GetCodepointSDF
-----------------------------------------------------
-----------------------------------------------------
---
--- Font name matching -- recommended not to use this
---
---
--- UNIMPLEMENTED / UNUSED:
--- stbtt__CompareUTF8toUTF16_bigendian_prefix
--- stbtt_CompareUTF8toUTF16_bigendian_internal
--- stbtt_GetFontNameString
--- stbtt__matchpair
--- stbtt__matches
--- @param data table
--- @param index int
function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end
--- @param info stbtt_fontinfo
--- @param data table
--- @param offset int
function stbtt_InitFont(info, data, offset) return stbtt_InitFont_internal(info, data, offset) end
return {
fontinfo = stbtt_fontinfo,
InitFont = stbtt_InitFont,
FindGlyphIndex = stbtt_FindGlyphIndex,
MakeGlyphBitmapSubpixelPrefilter = stbtt_MakeGlyphBitmapSubpixelPrefilter,
GetFontVMetrics = stbtt_GetFontVMetrics,
GetGlyphBitmapBox = stbtt_GetGlyphBitmapBox,
GetGlyphBitmapBoxSubpixel = stbtt_GetGlyphBitmapBoxSubpixel,
GetGlyphHMetrics = stbtt_GetGlyphHMetrics,
GetFontOffsetForIndex = stbtt_GetFontOffsetForIndex,
ScaleForPixelHeight = stbtt_ScaleForPixelHeight
}
end
__FILES['imstd_minstdio.lua'] = function()
--- ImGui Sincerely
-- This is a minimal Lua impl of C-like sscanf, sprintf sub-set
-- Supports:
-- - %x, %X, %nx, %nX (where n is a number)
-- - %d, %nd (where n is a number)
-- - %f, %lf (very limited)
--
-- Returns items_matched instead of EOF on error
local _byte = string.byte
local CHAR_PERCENT = _byte'%'
local CHAR_DOT = _byte'.'
local CHAR_PLUS, CHAR_MINUS = _byte'+', _byte'-'
local CHAR_0, CHAR_9 = _byte'0', _byte'9'
local CHAR_a, CHAR_A = _byte'a', _byte'A'
local CHAR_d = _byte'd'
local CHAR_l = _byte'l'
local CHAR_f, CHAR_F = _byte'f', _byte'F'
local CHAR_x, CHAR_X = _byte'x', _byte'X'
local function isspace(c) return c == 32 or c == 9 end
local function isdigit(c) return c >= CHAR_0 and c <= CHAR_9 end
local function isxdigit(c) return isdigit(c) or (c >= CHAR_a and c <= CHAR_f) or (c >= CHAR_A and c <= CHAR_F) end
local function isdigit_under_base(c, base)
if base == 10 then return isdigit(c)
elseif base == 16 then return isxdigit(c)
end
end
local function hex_digit_to_int(c)
if c >= CHAR_0 and c <= CHAR_9 then return c - CHAR_0 end
if c >= CHAR_a and c <= CHAR_f then return c - CHAR_a + 10 end
if c >= CHAR_A and c <= CHAR_F then return c - CHAR_A + 10 end
end
-- we force this behavior by default
local function clamp_if_overflow(spec, val)
if spec == CHAR_d or spec == CHAR_x or spec == CHAR_X then
if val > INT_MAX then return INT_MAX end
if val < INT_MIN then return INT_MIN end
end
return val
end
--- @param buffer char[]
--- @param buffer_begin int
--- @param format string
--- @param result table # table to store parsed values
local function sscanf(buffer, buffer_begin, format, result)
local p = buffer_begin
local f = 1 -- format_begin
local format_len = #format
local assigned = 0
local items_matched = 0
while f <= format_len do
repeat
if isspace(_byte(format, f, f)) then
while isspace(buffer[p]) do
p = p + 1
end
f = f + 1
break
end
if _byte(format, f, f) ~= CHAR_PERCENT then
if buffer[p] == _byte(format, f, f) then
p = p + 1
f = f + 1
else
return items_matched
end
break
end
-- encountered % in fmt
f = f + 1
-- %%
if _byte(format, f, f) == CHAR_PERCENT then
if buffer[p] == CHAR_PERCENT then
p = p + 1
f = f + 1
else
return items_matched
end
break
end
-- handle optional width
local width = 0
while isdigit(_byte(format, f, f)) do
width = width * 10 + _byte(format, f, f) - CHAR_0
f = f + 1
end
if width == 0 then
width = math.huge
end
local spec = _byte(format, f, f)
local base
local is_float = false
if spec == CHAR_x or spec == CHAR_X then
base = 16
elseif spec == CHAR_d then
base = 10
elseif spec == CHAR_f or spec == CHAR_F then
is_float = true
elseif spec == CHAR_l then
f = f + 1
if _byte(format, f, f) == CHAR_f then
is_float = true -- TODO: distinguish from float?
else
return items_matched
end
else
return items_matched
end
f = f + 1
while isspace(buffer[p]) do
p = p + 1
end
local val
if is_float then
local sign = 1
if buffer[p] == CHAR_PLUS then
p = p + 1
elseif buffer[p] == CHAR_MINUS then
sign = -1
p = p + 1
end
-- inf, nan are not handled
local p_start = p
local int_part = 0
while isdigit(buffer[p]) do
int_part = int_part * 10 + (buffer[p] - CHAR_0)
p = p + 1
end
local frac_part = 0
local frac_div = 1
if buffer[p] == CHAR_DOT then
p = p + 1
while isdigit(buffer[p]) do
frac_part = frac_part * 10 + (buffer[p] - CHAR_0)
frac_div = frac_div * 10
p = p + 1
end
end
if p == p_start then
return items_matched
end
val = sign * (int_part + frac_part / frac_div)
else
local sign = 1
-- optional sign
if base == 10 then
if buffer[p] == CHAR_PLUS then
p = p + 1
width = width - 1
elseif buffer[p] == CHAR_MINUS then
sign = -1
p = p + 1
width = width - 1
end
end
local p_start = p
while width > 0 and buffer[p] and isdigit_under_base(buffer[p], base) do
p = p + 1
width = width - 1
end
if p == p_start then
-- failed to match
return items_matched
end
val = 0
while p_start < p do
local c = buffer[p_start]
p_start = p_start + 1
val = val * base + sign * hex_digit_to_int(c)
local old_val = val
val = clamp_if_overflow(spec, val)
if old_val ~= val then
break
end
end
end
result[assigned + 1] = val
assigned = assigned + 1
items_matched = items_matched + 1
until true
end
return items_matched
end
local function sprintf()
end
return sscanf
end
IM_INCLUDE('imgui.lua')
IM_INCLUDE('imgui_impl_roblox.lua')
IM_INCLUDE('imgui_demo.lua')
return {
BuildLoadGlyphGetAdvanceOrFallback = BuildLoadGlyphGetAdvanceOrFallback,
CalcNextScrollFromScrollTargetAndClamp = CalcNextScrollFromScrollTargetAndClamp,
DBL_MAX = DBL_MAX,
DemoWindowWidgetsBasic = DemoWindowWidgetsBasic,
DemoWindowWidgetsColorAndPickers = DemoWindowWidgetsColorAndPickers,
DemoWindowWidgetsImages = DemoWindowWidgetsImages,
DemoWindowWidgetsPlotting = DemoWindowWidgetsPlotting,
DemoWindowWidgetsProgressBars = DemoWindowWidgetsProgressBars,
DemoWindowWidgetsVerticalSliders = DemoWindowWidgetsVerticalSliders,
FLT_MAX = FLT_MAX,
FLT_MIN = FLT_MIN,
FONT_ATLAS_DEFAULT_TEX_DATA_H = FONT_ATLAS_DEFAULT_TEX_DATA_H,
FONT_ATLAS_DEFAULT_TEX_DATA_W = FONT_ATLAS_DEFAULT_TEX_DATA_W,
GetDefaultFontDataProggyClean = GetDefaultFontDataProggyClean,
GetDefaultFontDataProggyForever = GetDefaultFontDataProggyForever,
GetMinimumStepAtDecimalPrecision = GetMinimumStepAtDecimalPrecision,
IMGUI_DEBUG_LOG_ACTIVEID = IMGUI_DEBUG_LOG_ACTIVEID,
IMGUI_DEBUG_LOG_FONT = IMGUI_DEBUG_LOG_FONT,
IMGUI_DEBUG_LOG_POPUP = IMGUI_DEBUG_LOG_POPUP,
IMGUI_DEBUG_LOG_VIEWPORT = IMGUI_DEBUG_LOG_VIEWPORT,
IMGUI_DISABLE_DEBUG_TOOLS = IMGUI_DISABLE_DEBUG_TOOLS,
IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS = IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS,
IMGUI_FONT_SIZE_MAX = IMGUI_FONT_SIZE_MAX,
IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE = IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE,
IMGUI_WINDOW_HARD_MIN_SIZE = IMGUI_WINDOW_HARD_MIN_SIZE,
IMSTB_TEXTEDIT_UNDOSTATECOUNT = IMSTB_TEXTEDIT_UNDOSTATECOUNT,
IM_ALLOC = IM_ALLOC,
IM_ASSERT = IM_ASSERT,
IM_ASSERT_PARANOID = IM_ASSERT_PARANOID,
IM_ASSERT_USER_ERROR = IM_ASSERT_USER_ERROR,
IM_ASSERT_USER_ERROR_RET = IM_ASSERT_USER_ERROR_RET,
IM_BITARRAY_CLEARBIT = IM_BITARRAY_CLEARBIT,
IM_BITARRAY_TESTBIT = IM_BITARRAY_TESTBIT,
IM_COL32 = IM_COL32,
IM_COL32_A_MASK = IM_COL32_A_MASK,
IM_COL32_A_SHIFT = IM_COL32_A_SHIFT,
IM_COL32_BLACK = IM_COL32_BLACK,
IM_COL32_BLACK_TRANS = IM_COL32_BLACK_TRANS,
IM_COL32_B_SHIFT = IM_COL32_B_SHIFT,
IM_COL32_G_SHIFT = IM_COL32_G_SHIFT,
IM_COL32_R_SHIFT = IM_COL32_R_SHIFT,
IM_COL32_WHITE = IM_COL32_WHITE,
IM_DELETE = IM_DELETE,
IM_DRAWLIST_ARCFAST_SAMPLE_MAX = IM_DRAWLIST_ARCFAST_SAMPLE_MAX,
IM_DRAWLIST_ARCFAST_TABLE_SIZE = IM_DRAWLIST_ARCFAST_TABLE_SIZE,
IM_F32_TO_INT8_SAT = IM_F32_TO_INT8_SAT,
IM_F32_TO_INT8_UNBOUND = IM_F32_TO_INT8_UNBOUND,
IM_FILE_CLOSE = IM_FILE_CLOSE,
IM_FILE_READ = IM_FILE_READ,
IM_FILE_SIZE = IM_FILE_SIZE,
IM_FILE_WRITE = IM_FILE_WRITE,
IM_FREE = IM_FREE,
IM_PI = IM_PI,
IM_ROUND = IM_ROUND,
IM_ROUNDUP_TO_EVEN = IM_ROUNDUP_TO_EVEN,
IM_TABSIZE = IM_TABSIZE,
IM_TRUNC = IM_TRUNC,
IM_UNICODE_CODEPOINT_INVALID = IM_UNICODE_CODEPOINT_INVALID,
IM_UNICODE_CODEPOINT_MAX = IM_UNICODE_CODEPOINT_MAX,
INT_MAX = INT_MAX,
INT_MIN = INT_MIN,
ImAbs = ImAbs,
ImAcos = ImAcos,
ImAddClampOverflow = ImAddClampOverflow,
ImAtan2 = ImAtan2,
ImAtof = ImAtof,
ImBitArray = ImBitArray,
ImBitArraySetBit = ImBitArraySetBit,
ImCeil = ImCeil,
ImCeilFast = ImCeilFast,
ImCharIsBlankA = ImCharIsBlankA,
ImCharIsBlankW = ImCharIsBlankW,
ImCharIsSeparatorW = ImCharIsSeparatorW,
ImClamp = ImClamp,
ImCos = ImCos,
ImCountSetBits = ImCountSetBits,
ImDot = ImDot,
ImDrawChannel = ImDrawChannel,
ImDrawCmd = ImDrawCmd,
ImDrawCmdHeader = ImDrawCmdHeader,
ImDrawData = ImDrawData,
ImDrawFlags = ImDrawFlags,
ImDrawList = ImDrawList,
ImDrawListFlags = ImDrawListFlags,
ImDrawListSharedData = ImDrawListSharedData,
ImDrawListSplitter = ImDrawListSplitter,
ImDrawTextFlags = ImDrawTextFlags,
ImDrawVert = ImDrawVert,
ImFabs = ImFabs,
ImFloor = ImFloor,
ImFmod = ImFmod,
ImFont = ImFont,
ImFontAtlas = ImFontAtlas,
ImFontAtlasAddDrawListSharedData = ImFontAtlasAddDrawListSharedData,
ImFontAtlasBakedAdd = ImFontAtlasBakedAdd,
ImFontAtlasBakedAddFontGlyph = ImFontAtlasBakedAddFontGlyph,
ImFontAtlasBakedAddFontGlyphAdvancedX = ImFontAtlasBakedAddFontGlyphAdvancedX,
ImFontAtlasBakedDiscard = ImFontAtlasBakedDiscard,
ImFontAtlasBakedGetClosestMatch = ImFontAtlasBakedGetClosestMatch,
ImFontAtlasBakedGetId = ImFontAtlasBakedGetId,
ImFontAtlasBakedGetOrAdd = ImFontAtlasBakedGetOrAdd,
ImFontAtlasBuildAcceptCodepointForSource = ImFontAtlasBuildAcceptCodepointForSource,
ImFontAtlasBuildDestroy = ImFontAtlasBuildDestroy,
ImFontAtlasBuildInit = ImFontAtlasBuildInit,
ImFontAtlasBuildMain = ImFontAtlasBuildMain,
ImFontAtlasBuildNotifySetFont = ImFontAtlasBuildNotifySetFont,
ImFontAtlasBuildRenderBitmapFromString = ImFontAtlasBuildRenderBitmapFromString,
ImFontAtlasBuildSetTexture = ImFontAtlasBuildSetTexture,
ImFontAtlasBuildSetupFontBakedBlanks = ImFontAtlasBuildSetupFontBakedBlanks,
ImFontAtlasBuildSetupFontBakedEllipsis = ImFontAtlasBuildSetupFontBakedEllipsis,
ImFontAtlasBuildSetupFontBakedFallback = ImFontAtlasBuildSetupFontBakedFallback,
ImFontAtlasBuildSetupFontLoader = ImFontAtlasBuildSetupFontLoader,
ImFontAtlasBuildSetupFontSpecialGlyphs = ImFontAtlasBuildSetupFontSpecialGlyphs,
ImFontAtlasBuildUpdateTexData = ImFontAtlasBuildUpdateTexData,
ImFontAtlasBuildUpdateTexDataBasic = ImFontAtlasBuildUpdateTexDataBasic,
ImFontAtlasBuildUpdateTexDataLines = ImFontAtlasBuildUpdateTexDataLines,
ImFontAtlasBuilder = ImFontAtlasBuilder,
ImFontAtlasFlags = ImFontAtlasFlags,
ImFontAtlasFontDestroyOutput = ImFontAtlasFontDestroyOutput,
ImFontAtlasFontDestroySourceData = ImFontAtlasFontDestroySourceData,
ImFontAtlasFontInitOutput = ImFontAtlasFontInitOutput,
ImFontAtlasFontSourceAddToFont = ImFontAtlasFontSourceAddToFont,
ImFontAtlasFontSourceInit = ImFontAtlasFontSourceInit,
ImFontAtlasGetMouseCursorTexData = ImFontAtlasGetMouseCursorTexData,
ImFontAtlasPackAddRect = ImFontAtlasPackAddRect,
ImFontAtlasPackDiscardRect = ImFontAtlasPackDiscardRect,
ImFontAtlasPackGetRect = ImFontAtlasPackGetRect,
ImFontAtlasPackGetRectSafe = ImFontAtlasPackGetRectSafe,
ImFontAtlasPackInit = ImFontAtlasPackInit,
ImFontAtlasPostProcessData = ImFontAtlasPostProcessData,
ImFontAtlasRect = ImFontAtlasRect,
ImFontAtlasRectEntry = ImFontAtlasRectEntry,
ImFontAtlasRectId_GetGeneration = ImFontAtlasRectId_GetGeneration,
ImFontAtlasRectId_GetIndex = ImFontAtlasRectId_GetIndex,
ImFontAtlasRectId_Invalid = ImFontAtlasRectId_Invalid,
ImFontAtlasRectId_Make = ImFontAtlasRectId_Make,
ImFontAtlasRemoveDrawListSharedData = ImFontAtlasRemoveDrawListSharedData,
ImFontAtlasTextureAdd = ImFontAtlasTextureAdd,
ImFontAtlasTextureBlockConvert = ImFontAtlasTextureBlockConvert,
ImFontAtlasTextureBlockCopy = ImFontAtlasTextureBlockCopy,
ImFontAtlasTextureBlockPostProcess = ImFontAtlasTextureBlockPostProcess,
ImFontAtlasTextureBlockPostProcessMultiply = ImFontAtlasTextureBlockPostProcessMultiply,
ImFontAtlasTextureBlockQueueUpload = ImFontAtlasTextureBlockQueueUpload,
ImFontAtlasTextureCompact = ImFontAtlasTextureCompact,
ImFontAtlasTextureGetSizeEstimate = ImFontAtlasTextureGetSizeEstimate,
ImFontAtlasTextureGrow = ImFontAtlasTextureGrow,
ImFontAtlasUpdateDrawListsSharedData = ImFontAtlasUpdateDrawListsSharedData,
ImFontAtlasUpdateNewFrame = ImFontAtlasUpdateNewFrame,
ImFontBaked = ImFontBaked,
ImFontBaked_BuildGrowIndex = ImFontBaked_BuildGrowIndex,
ImFontBaked_BuildLoadGlyph = ImFontBaked_BuildLoadGlyph,
ImFontBaked_BuildLoadGlyphAdvanceX = ImFontBaked_BuildLoadGlyphAdvanceX,
ImFontCalcTextSizeEx = ImFontCalcTextSizeEx,
ImFontCalcWordWrapPositionEx = ImFontCalcWordWrapPositionEx,
ImFontConfig = ImFontConfig,
ImFontFlags = ImFontFlags,
ImFontGlyph = ImFontGlyph,
ImFontLoader = ImFontLoader,
ImFontStackData = ImFontStackData,
ImFormatString = ImFormatString,
ImGui = ImGui,
ImGuiActivateFlags = ImGuiActivateFlags,
ImGuiAxis = ImGuiAxis,
ImGuiBackendFlags = ImGuiBackendFlags,
ImGuiButtonFlags = ImGuiButtonFlags,
ImGuiChildFlags = ImGuiChildFlags,
ImGuiCol = ImGuiCol,
ImGuiColorEditFlags = ImGuiColorEditFlags,
ImGuiColorMod = ImGuiColorMod,
ImGuiComboFlags = ImGuiComboFlags,
ImGuiCond = ImGuiCond,
ImGuiConfigFlags = ImGuiConfigFlags,
ImGuiContext = ImGuiContext,
ImGuiDataType = ImGuiDataType,
ImGuiDebugLogFlags = ImGuiDebugLogFlags,
ImGuiDir = ImGuiDir,
ImGuiDragDropFlags = ImGuiDragDropFlags,
ImGuiFocusRequestFlags = ImGuiFocusRequestFlags,
ImGuiFocusScopeData = ImGuiFocusScopeData,
ImGuiGroupData = ImGuiGroupData,
ImGuiHoveredFlags = ImGuiHoveredFlags,
ImGuiIO = ImGuiIO,
ImGuiInputEvent = ImGuiInputEvent,
ImGuiInputEventAppFocused = ImGuiInputEventAppFocused,
ImGuiInputEventKey = ImGuiInputEventKey,
ImGuiInputEventMouseButton = ImGuiInputEventMouseButton,
ImGuiInputEventMousePos = ImGuiInputEventMousePos,
ImGuiInputEventMouseViewport = ImGuiInputEventMouseViewport,
ImGuiInputEventMouseWheel = ImGuiInputEventMouseWheel,
ImGuiInputEventText = ImGuiInputEventText,
ImGuiInputEventType = ImGuiInputEventType,
ImGuiInputFlags = ImGuiInputFlags,
ImGuiInputSource = ImGuiInputSource,
ImGuiInputTextCallbackData = ImGuiInputTextCallbackData,
ImGuiInputTextFlags = ImGuiInputTextFlags,
ImGuiItemFlags = ImGuiItemFlags,
ImGuiItemStatusFlags = ImGuiItemStatusFlags,
ImGuiKey = ImGuiKey,
ImGuiKeyData = ImGuiKeyData,
ImGuiKeyOwnerData = ImGuiKeyOwnerData,
ImGuiKeyOwner_Any = ImGuiKeyOwner_Any,
ImGuiKeyOwner_NoOwner = ImGuiKeyOwner_NoOwner,
ImGuiKeyRoutingData = ImGuiKeyRoutingData,
ImGuiKey_Aliases_BEGIN = ImGuiKey_Aliases_BEGIN,
ImGuiKey_Aliases_END = ImGuiKey_Aliases_END,
ImGuiKey_Gamepad_BEGIN = ImGuiKey_Gamepad_BEGIN,
ImGuiKey_Gamepad_END = ImGuiKey_Gamepad_END,
ImGuiKey_Keyboard_BEGIN = ImGuiKey_Keyboard_BEGIN,
ImGuiKey_Keyboard_END = ImGuiKey_Keyboard_END,
ImGuiKey_Mouse_BEGIN = ImGuiKey_Mouse_BEGIN,
ImGuiKey_Mouse_END = ImGuiKey_Mouse_END,
ImGuiLastItemData = ImGuiLastItemData,
ImGuiLastItemData_Copy = ImGuiLastItemData_Copy,
ImGuiLayoutType = ImGuiLayoutType,
ImGuiLocKey = ImGuiLocKey,
ImGuiMod_Alt = ImGuiMod_Alt,
ImGuiMod_Ctrl = ImGuiMod_Ctrl,
ImGuiMod_Mask_ = ImGuiMod_Mask_,
ImGuiMod_None = ImGuiMod_None,
ImGuiMod_Shift = ImGuiMod_Shift,
ImGuiMod_Super = ImGuiMod_Super,
ImGuiMouseButton = ImGuiMouseButton,
ImGuiMouseCursor = ImGuiMouseCursor,
ImGuiMouseSource = ImGuiMouseSource,
ImGuiNavLayer = ImGuiNavLayer,
ImGuiNavMoveFlags = ImGuiNavMoveFlags,
ImGuiNavRenderCursorFlags = ImGuiNavRenderCursorFlags,
ImGuiNextItemData = ImGuiNextItemData,
ImGuiNextItemDataFlags = ImGuiNextItemDataFlags,
ImGuiNextWindowData = ImGuiNextWindowData,
ImGuiNextWindowDataFlags = ImGuiNextWindowDataFlags,
ImGuiPlatformIO = ImGuiPlatformIO,
ImGuiPlatformImeData = ImGuiPlatformImeData,
ImGuiPlatformImeData_Compare = ImGuiPlatformImeData_Compare,
ImGuiPlatformImeData_Copy = ImGuiPlatformImeData_Copy,
ImGuiPlatformMonitor = ImGuiPlatformMonitor,
ImGuiPlotArrayGetterData = ImGuiPlotArrayGetterData,
ImGuiPlotType = ImGuiPlotType,
ImGuiPopupData = ImGuiPopupData,
ImGuiPopupFlags = ImGuiPopupFlags,
ImGuiPopupPositionPolicy = ImGuiPopupPositionPolicy,
ImGuiScrollFlags = ImGuiScrollFlags,
ImGuiSelectableFlags = ImGuiSelectableFlags,
ImGuiSelectionUserData_Invalid = ImGuiSelectionUserData_Invalid,
ImGuiSeparatorFlags = ImGuiSeparatorFlags,
ImGuiSliderFlags = ImGuiSliderFlags,
ImGuiStyle = ImGuiStyle,
ImGuiStyleMod = ImGuiStyleMod,
ImGuiStyleVar = ImGuiStyleVar,
ImGuiStyleVarInfo = ImGuiStyleVarInfo,
ImGuiTableFlags = ImGuiTableFlags,
ImGuiTextFlags = ImGuiTextFlags,
ImGuiTooltipFlags = ImGuiTooltipFlags,
ImGuiTreeNodeFlags = ImGuiTreeNodeFlags,
ImGuiViewport = ImGuiViewport,
ImGuiViewportFlags = ImGuiViewportFlags,
ImGuiViewportP = ImGuiViewportP,
ImGuiWindow = ImGuiWindow,
ImGuiWindowBgClickFlags = ImGuiWindowBgClickFlags,
ImGuiWindowClass = ImGuiWindowClass,
ImGuiWindowFlags = ImGuiWindowFlags,
ImGuiWindowRefreshFlags = ImGuiWindowRefreshFlags,
ImGuiWindowSettings = ImGuiWindowSettings,
ImGuiWindowStackData = ImGuiWindowStackData,
ImGui_ImplRoblox = ImGui_ImplRoblox,
ImGui_ImplRoblox_GetBackendData = ImGui_ImplRoblox_GetBackendData,
ImGui_ImplRoblox_Init = ImGui_ImplRoblox_Init,
ImGui_ImplRoblox_NewFrame = ImGui_ImplRoblox_NewFrame,
ImGui_ImplRoblox_RenderDrawData = ImGui_ImplRoblox_RenderDrawData,
ImGui_ImplRoblox_Shutdown = ImGui_ImplRoblox_Shutdown,
ImGui_ImplRoblox_UpdateTexture = ImGui_ImplRoblox_UpdateTexture,
ImHashData = ImHashData,
ImHashStr = ImHashStr,
ImIsPowerOfTwo = ImIsPowerOfTwo,
ImLengthSqr = ImLengthSqr,
ImLerp = ImLerp,
ImLog = ImLog,
ImMax = ImMax,
ImMemchr = ImMemchr,
ImMin = ImMin,
ImMul = ImMul,
ImParseFormatFindStart = ImParseFormatFindStart,
ImParseFormatSanitizeForScanning = ImParseFormatSanitizeForScanning,
ImPow = ImPow,
ImRect = ImRect,
ImRect_Copy = ImRect_Copy,
ImRect_CopyFromV4 = ImRect_CopyFromV4,
ImRotate = ImRotate,
ImRound64 = ImRound64,
ImRsqrt = ImRsqrt,
ImS16 = ImS16,
ImS32 = ImS32,
ImS8 = ImS8,
ImSaturate = ImSaturate,
ImSin = ImSin,
ImSqrt = ImSqrt,
ImStb = ImStb,
ImStd = ImStd,
ImStrByte = ImStrByte,
ImSubClampOverflow = ImSubClampOverflow,
ImTextClassifierClear = ImTextClassifierClear,
ImTextClassifierGet = ImTextClassifierGet,
ImTextClassifierSetCharClass = ImTextClassifierSetCharClass,
ImTextClassifierSetCharClassFromStr = ImTextClassifierSetCharClassFromStr,
ImTextInitClassifiers = ImTextInitClassifiers,
ImTextureData = ImTextureData,
ImTextureDataGetFormatBytesPerPixel = ImTextureDataGetFormatBytesPerPixel,
ImTextureDataUpdateNewFrame = ImTextureDataUpdateNewFrame,
ImTextureFormat = ImTextureFormat,
ImTextureID_Invalid = ImTextureID_Invalid,
ImTextureRect = ImTextureRect,
ImTextureRef = ImTextureRef,
ImTextureStatus = ImTextureStatus,
ImTrunc = ImTrunc,
ImTrunc64 = ImTrunc64,
ImU16 = ImU16,
ImU32 = ImU32,
ImU8 = ImU8,
ImUpperPowerOfTwo = ImUpperPowerOfTwo,
ImVec1_Copy = ImVec1_Copy,
ImVec2 = ImVec2,
ImVec2_AddVA = ImVec2_AddVA,
ImVec2_Copy = ImVec2_Copy,
ImVec2_CopyV = ImVec2_CopyV,
ImVec2_MulVX = ImVec2_MulVX,
ImVec2_SubVA = ImVec2_SubVA,
ImVec4 = ImVec4,
ImVec4_Copy = ImVec4_Copy,
ImVector = ImVector,
ImWcharClass = ImWcharClass,
NAV_ACTIVATE_HIGHLIGHT_TIMER = NAV_ACTIVATE_HIGHLIGHT_TIMER,
NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY,
NAV_WINDOWING_HIGHLIGHT_DELAY = NAV_WINDOWING_HIGHLIGHT_DELAY,
STB_TEXTEDIT_K_BACKSPACE = STB_TEXTEDIT_K_BACKSPACE,
STB_TEXTEDIT_K_DELETE = STB_TEXTEDIT_K_DELETE,
STB_TEXTEDIT_K_DOWN = STB_TEXTEDIT_K_DOWN,
STB_TEXTEDIT_K_LEFT = STB_TEXTEDIT_K_LEFT,
STB_TEXTEDIT_K_LINEEND = STB_TEXTEDIT_K_LINEEND,
STB_TEXTEDIT_K_LINESTART = STB_TEXTEDIT_K_LINESTART,
STB_TEXTEDIT_K_PGDOWN = STB_TEXTEDIT_K_PGDOWN,
STB_TEXTEDIT_K_PGUP = STB_TEXTEDIT_K_PGUP,
STB_TEXTEDIT_K_REDO = STB_TEXTEDIT_K_REDO,
STB_TEXTEDIT_K_RIGHT = STB_TEXTEDIT_K_RIGHT,
STB_TEXTEDIT_K_SHIFT = STB_TEXTEDIT_K_SHIFT,
STB_TEXTEDIT_K_TEXTEND = STB_TEXTEDIT_K_TEXTEND,
STB_TEXTEDIT_K_TEXTSTART = STB_TEXTEDIT_K_TEXTSTART,
STB_TEXTEDIT_K_UNDO = STB_TEXTEDIT_K_UNDO,
STB_TEXTEDIT_K_UP = STB_TEXTEDIT_K_UP,
STB_TEXTEDIT_K_WORDLEFT = STB_TEXTEDIT_K_WORDLEFT,
STB_TEXTEDIT_K_WORDRIGHT = STB_TEXTEDIT_K_WORDRIGHT,
STB_TEXTEDIT_NEWLINE = STB_TEXTEDIT_NEWLINE,
STB_TexteditState = STB_TexteditState,
ShowExampleAppFullscreen = ShowExampleAppFullscreen,
TILE_SIZE = TILE_SIZE,
UINT_MAX = UINT_MAX,
stb_text_locate_coord = stb_text_locate_coord,
stb_text_makeundo_delete = stb_text_makeundo_delete,
stb_text_makeundo_insert = stb_text_makeundo_insert,
stb_text_makeundo_replace = stb_text_makeundo_replace,
stb_text_redo = stb_text_redo,
stb_text_undo = stb_text_undo,
stb_textedit_click = stb_textedit_click,
stb_textedit_drag = stb_textedit_drag,
stb_textedit_find_charpos = stb_textedit_find_charpos,
stb_textedit_key = stb_textedit_key,
stbrp_init_target = stbrp_init_target,
stbte = stbte,
stbtt_FindGlyphIndex = stbtt_FindGlyphIndex,
stbtt_GetFontOffsetForIndex = stbtt_GetFontOffsetForIndex,
stbtt_GetFontVMetrics = stbtt_GetFontVMetrics,
stbtt_GetGlyphBitmapBox = stbtt_GetGlyphBitmapBox,
stbtt_GetGlyphBitmapBoxSubpixel = stbtt_GetGlyphBitmapBoxSubpixel,
stbtt_GetGlyphHMetrics = stbtt_GetGlyphHMetrics,
stbtt_GetGlyphShape = stbtt_GetGlyphShape,
stbtt_InitFont = stbtt_InitFont,
stbtt_MakeGlyphBitmapSubpixelPrefilter = stbtt_MakeGlyphBitmapSubpixelPrefilter,
stbtt_ScaleForPixelHeight = stbtt_ScaleForPixelHeight,
stbtt__GetGlyphInfoT2 = stbtt__GetGlyphInfoT2,
stbtt__GetGlyphShapeT2 = stbtt__GetGlyphShapeT2,
stbtt_fontinfo = stbtt_fontinfo,
}
end
SOURCE_FNS['main.client.luau'] = function(game, workspace, Instance, Enum, Vector2, Vector3, UDim2, Color3, Content, warn, require, script, os)
-- LocalScript. Build the library first: `python3 tools/bundle.py` -> build/ImGui.luau (see default.project.json)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local G = require(ReplicatedStorage:WaitForChild("ImGui"))
local ImGui, ImVec4, ImGuiConfigFlags, ImGui_ImplRoblox = G.ImGui, G.ImVec4, G.ImGuiConfigFlags, G.ImGui_ImplRoblox
local main_scale = 1.0
local clear_color = ImVec4(0.45, 0.55, 0.60, 1.00)
local show_demo_window = true
local show_another_window = false
local f = 0.0
local counter = 0
ImGui.CreateContext()
local io = ImGui.GetIO()
io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard)
local style = ImGui.GetStyle()
style:ScaleAllSizes(main_scale)
style.FontScaleDpi = main_scale
ImGui_ImplRoblox.Init()
RunService.Stepped:Connect(function()
ImGui_ImplRoblox.NewFrame()
ImGui.NewFrame()
if show_demo_window then
ImGui.ShowDemoWindow()
end
do
ImGui.Begin("Hello, world!")
ImGui.Text("This is some useful text.")
local _
_, show_demo_window = ImGui.Checkbox("Demo Window", show_demo_window)
_, show_another_window = ImGui.Checkbox("Another Window", show_another_window)
f = ImGui.SliderFloat("float", f, 0.0, 1.0)
ImGui.ColorEdit3("clear color", clear_color)
if ImGui.Button("Button") then
counter = counter + 1
end
ImGui.SameLine()
ImGui.Text("counter = %d", counter)
ImGui.Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / io.Framerate, io.Framerate)
ImGui.End()
end
if show_another_window then
show_another_window = ImGui.Begin("Another Window", show_another_window)
ImGui.Text("Hello from another window!")
if ImGui.Button("Close Me") then
show_another_window = false
end
ImGui.End()
end
ImGui.EndFrame()
ImGui.Render()
ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
end)
end
-- Minimal Roblox mock for running the imgui Roblox backend + the real CanvasDraw module in the Luau CLI.
local realG = {} -- (no getfenv: it would mark the global env unsafe and deoptimize everything)
FAKE_TIME = 0
local SCREEN_W, SCREEN_H = 1920, 1080
local NFRAMES = tonumber(ARG_FRAMES) or 400
local FORCE = ARG_FORCE == true
local DUMP_FRAMES = { [60] = true, [200] = true, [NFRAMES] = true }
local function Signal()
local s = { conns = {} }
function s:Connect(fn)
local c = { fn = fn, Connected = true }
function c:Disconnect() c.Connected = false end
table.insert(s.conns, c)
return c
end
function s:Fire(...) for _, c in ipairs(s.conns) do if c.Connected then c.fn(...) end end end
return s
end
local V2 = {}
V2.__index = V2
local function v2(x, y) return setmetatable({ X = x or 0, Y = y or 0 }, V2) end
V2.__add = function(a, b) return v2(a.X + b.X, a.Y + b.Y) end
V2.__sub = function(a, b) return v2(a.X - b.X, a.Y - b.Y) end
V2.__mul = function(a, b) if type(b) == "number" then return v2(a.X * b, a.Y * b) end return v2(a.X * b.X, a.Y * b.Y) end
V2.__div = function(a, b) if type(b) == "number" then return v2(a.X / b, a.Y / b) end return v2(a.X / b.X, a.Y / b.Y) end
V2.__eq = function(a, b) return a.X == b.X and a.Y == b.Y end
local Vector2 = { new = v2, zero = v2(0, 0), one = v2(1, 1) }
-- Enums: KeyCode values as in Roblox; unknown KeyCode names error (catches typos in the backend)
local KEYCODES = {
Unknown = 0, Backspace = 8, Tab = 9, Return = 13, Escape = 27, Space = 32, Quote = 39, Comma = 44, Minus = 45, Period = 46, Slash = 47,
Semicolon = 59, Equals = 61, LeftBracket = 91, BackSlash = 92, RightBracket = 93, Backquote = 96, Delete = 127,
KeypadPeriod = 266, KeypadDivide = 267, KeypadMultiply = 268, KeypadMinus = 269, KeypadPlus = 270, KeypadEnter = 271, KeypadEquals = 272,
Up = 273, Down = 274, Right = 275, Left = 276, Insert = 277, Home = 278, End = 279, PageUp = 280, PageDown = 281,
CapsLock = 301, RightShift = 303, LeftShift = 304, RightControl = 305, LeftControl = 306, RightAlt = 307, LeftAlt = 308,
LeftSuper = 311, RightSuper = 312,
}
local digits = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }
for i = 0, 9 do KEYCODES[digits[i + 1]] = 48 + i; KEYCODES["Keypad" .. digits[i + 1]] = 256 + i end
for i = 0, 25 do KEYCODES[string.char(65 + i)] = 97 + i end
for i = 1, 15 do KEYCODES["F" .. i] = 281 + i end
local Enum = setmetatable({}, { __index = function(t, enum_name)
local e = setmetatable({}, { __index = function(e, item)
local value = 0
if enum_name == "KeyCode" then value = KEYCODES[item]; assert(value, "invalid KeyCode " .. item) end
local it = { Name = item, Value = value, EnumType = enum_name }
rawset(e, item, it)
return it
end })
rawset(t, enum_name, e)
return e
end })
-- Instances
local InstMethods = {}
local InstMT = {}
InstMT.__index = function(t, k)
if k == "Parent" then return rawget(t, "_parent") end
local m = InstMethods[k]; if m then return m end
for _, c in ipairs(rawget(t, "_children")) do if c.Name == k then return c end end
return nil
end
InstMT.__newindex = function(t, k, v)
if k == "Parent" then
local old = rawget(t, "_parent")
if old then local ch = rawget(old, "_children"); for i, c in ipairs(ch) do if c == t then table.remove(ch, i) break end end end
rawset(t, "_parent", v)
if v then table.insert(rawget(v, "_children"), t) end
else
rawset(t, k, v)
end
end
local function newInst(class, name, parent)
local o = setmetatable({ ClassName = class, Name = name or class, _children = {} }, InstMT)
if class == "ScreenGui" or class == "Frame" or class == "ImageLabel" then o.AbsoluteSize = v2(SCREEN_W, SCREEN_H) end
o.Visible = true
if class == "BindableEvent" then local sig = Signal(); rawset(o, "Event", sig); rawset(o, "Fire", function(_, ...) sig:Fire(...) end) end
if parent then o.Parent = parent end
return o
end
function InstMethods:FindFirstChild(name, recursive)
for _, c in ipairs(rawget(self, "_children")) do if c.Name == name then return c end end
if recursive then for _, c in ipairs(rawget(self, "_children")) do local r = c:FindFirstChild(name, true); if r then return r end end end
return nil
end
function InstMethods:WaitForChild(name) return assert(self:FindFirstChild(name), "WaitForChild would hang: " .. name) end
function InstMethods:FindFirstChildOfClass(class) for _, c in ipairs(rawget(self, "_children")) do if c.ClassName == class then return c end end end
function InstMethods:GetChildren() return table.clone(rawget(self, "_children")) end
function InstMethods:IsA(class)
if class == "GuiObject" then return self.ClassName == "Frame" or self.ClassName == "ImageLabel" end
return self.ClassName == class
end
function InstMethods:Destroy() self.Parent = nil end
-- Services
local mouse = v2(0, 0)
local keys_down = {}
local UIS = {
InputBegan = Signal(), InputEnded = Signal(), InputChanged = Signal(), WindowFocused = Signal(), WindowFocusReleased = Signal(),
}
function UIS:GetMouseLocation() return mouse end
function UIS:IsKeyDown(kc) return keys_down[kc] == true end
local RunService = { Heartbeat = Signal(), Stepped = Signal(), PreAnimation = Signal(), RenderStepped = Signal() }
local last_pixels -- last buffer written to an EditableImage
local AssetService = {}
function AssetService:CreateEditableImage(opts)
local img = { Size = opts.Size, Pixels = buffer.create(opts.Size.X * opts.Size.Y * 4) }
UPLOADS = 0
function img:WritePixelsBuffer(origin, size, buf) buffer.copy(img.Pixels, 0, buf); _G_UPLOADS = (_G_UPLOADS or 0) + 1 end
function img:Destroy() end
return img
end
local ReplicatedStorage = newInst("ReplicatedStorage")
local PlayerGui = newInst("PlayerGui")
local LocalPlayer = newInst("Player"); PlayerGui.Parent = LocalPlayer
local services = {
UserInputService = UIS, RunService = RunService, AssetService = AssetService, ReplicatedStorage = ReplicatedStorage,
Players = { LocalPlayer = LocalPlayer }, HttpService = {}, GuiService = { GetGuiInset = function() return v2(0, 0), v2(0, 0) end },
}
local game = {}
function game:GetService(name) services[name] = services[name] or {}; return services[name] end
local fakeG = {} -- Roblox's shared _G
local cache = {}
local ROBLOX
local function makeEnv(inst) return setmetatable({ script = inst }, { __index = ROBLOX }) end
local GLOBAL_NAMES = { "game", "workspace", "Instance", "Enum", "Vector2", "Vector3", "UDim2", "Color3", "Content", "warn", "require", "script", "os" }
-- Load like Roblox does but WITHOUT setfenv (which would disable Luau optimizations): Roblox globals become chunk locals.
local function loadAsScript(src_name, inst)
local fn = SOURCE_FNS[src_name]
local vals = {}
for i, n in ipairs(GLOBAL_NAMES) do vals[i] = (n == "script") and inst or ROBLOX[n] end
return function() return fn(table.unpack(vals, 1, #GLOBAL_NAMES)) end
end
local function rbxrequire(inst)
assert(type(inst) == "table" and inst.ClassName == "ModuleScript", "require() expects a ModuleScript")
if cache[inst] then return cache[inst].v end
local r = table.pack(loadAsScript(rawget(inst, "_src"), inst)())
assert(r.n == 1, "Module code did not return exactly one value")
cache[inst] = { v = r[1] }
return r[1]
end
ROBLOX = setmetatable({
game = game, workspace = { CurrentCamera = { ViewportSize = v2(SCREEN_W, SCREEN_H) } }, require = rbxrequire, _G = fakeG,
Instance = { new = function(class) return newInst(class) end },
Enum = Enum, Vector2 = Vector2,
Vector3 = { new = function(x, y, z) return { X = x, Y = y, Z = z } end },
UDim2 = { new = function(...) return { ... } end, fromScale = function(...) return { ... } end, fromOffset = function(x, y) return { X = x, Y = y } end },
Color3 = { new = function(r, g, b) return { R = r or 0, G = g or 0, B = b or 0 } end },
Content = { fromObject = function(o) return { Object = o } end },
warn = function(...) print("WARN", ...) end,
os = { clock = function() return FAKE_TIME end, time = os.time },
}, { __index = realG })
local mod = newInst("ModuleScript", "ImGui", ReplicatedStorage); rawset(mod, "_src", "ImGui.luau")
-- Run main.lua as a LocalScript
local main = loadAsScript("main.client.luau", newInst("LocalScript", "main"))
main()
local G = cache[mod].v
local render_time = 0
local realDemo = G.ImGui.ShowDemoWindow
local realCH = G.ImGui.CollapsingHeader
G.ImGui.CollapsingHeader = function(...)
if ARG_OPEN then G.ImGui.SetNextItemOpen(true, G.ImGuiCond.Always) end
return realCH(...)
end
local realTN = G.ImGui.TreeNode
G.ImGui.TreeNode = function(...)
if ARG_OPEN then G.ImGui.SetNextItemOpen(true, G.ImGuiCond.Always) end
return realTN(...)
end
G.ImGui.ShowDemoWindow = function(...)
if ARG_BIG then G.ImGui.SetNextWindowSize(G.ImVec2(900, 1000), G.ImGuiCond.Always) end
return realDemo(...)
end
local realRender = G.ImGui_ImplRoblox.RenderDrawData
G.ImGui_ImplRoblox.RenderDrawData = function(dd)
if FORCE then G.ImGui.GetIO().BackendPlatformUserData.ForceRedraw = true end
local t0 = os.clock(); realRender(dd); render_time = render_time + os.clock() - t0
end
-- Drive frames with scripted (deterministic) input
local seed = 12345
local function rnd(n) seed = (seed * 1103515245 + 12345) % 2147483648; return seed % n end
local function input(t, kc, pos) return { UserInputType = Enum.UserInputType[t], KeyCode = Enum.KeyCode[kc or "Unknown"], Position = pos or { X = 0, Y = 0, Z = 0 } } end
local held = false
local typing = { "H", "E", "L", "L", "O", "Space", "One", "Two", "Minus", "Backspace", "Left", "Return" }
local hex = {}
for i = 0, 255 do hex[i] = string.format("%02x", i) end
local total = 0
for frame = 1, NFRAMES do
local r = rnd(100)
if r < 40 then
mouse = v2(math.clamp(mouse.X + rnd(81) - 40, 0, SCREEN_W - 1), math.clamp(mouse.Y + rnd(81) - 40, 0, SCREEN_H - 1))
elseif r < 55 then
held = not held
if held then UIS.InputBegan:Fire(input("MouseButton1"), false) else UIS.InputEnded:Fire(input("MouseButton1"), false) end
elseif r < 60 then
UIS.InputChanged:Fire(input("MouseWheel", nil, { X = 0, Y = 0, Z = rnd(3) - 1 }), false)
elseif r < 75 then
local k = typing[rnd(#typing) + 1]
local shift = rnd(4) == 0
if shift then keys_down[Enum.KeyCode.LeftShift] = true; UIS.InputBegan:Fire(input("Keyboard", "LeftShift"), false) end
UIS.InputBegan:Fire(input("Keyboard", k), false)
UIS.InputEnded:Fire(input("Keyboard", k), false)
if shift then keys_down[Enum.KeyCode.LeftShift] = nil; UIS.InputEnded:Fire(input("Keyboard", "LeftShift"), false) end
elseif r < 90 then
mouse = v2(rnd(700), rnd(500))
end
FAKE_TIME = frame / 60
local t0 = os.clock()
RunService.Stepped:Fire(frame / 60, 1 / 60)
local dt = os.clock() - t0
if frame > 10 then total = total + dt end
if frame == 10 then render_time = 0; _G_UPLOADS = 0 end
if DUMP_FRAMES[frame] and ARG_DUMP then
local W, H = SCREEN_W, SCREEN_H
local screen = buffer.create(W * H * 4)
local gui = PlayerGui:FindFirstChild("ImGui")
for _, label in ipairs(gui:GetChildren()) do
if label.Visible then
local img, px, py = label.ImageContent.Object, label.Position.X, label.Position.Y
local tw, th = img.Size.X, img.Size.Y
for y = 0, th - 1 do
if py + y < H then
local n = math.min(tw, W - px)
buffer.copy(screen, ((py + y) * W + px) * 4, img.Pixels, y * tw * 4, n * 4)
end
end
end
end
local parts = {}
for i = 0, W * H * 4 - 1 do parts[#parts + 1] = hex[buffer.readu8(screen, i)] end
print(string.format("IMG %d %d %d %s", frame, W, H, table.concat(parts)))
end
end
print(string.format("avg frame total %.2f ms, of which render %.2f ms, uploads/frame %.2f", total / (NFRAMES - 10) * 1000, render_time / (NFRAMES - 10) * 1000, _G_UPLOADS / (NFRAMES - 10)))