From 9fae61208b43a321059b80bd35afc980d2bb7fee Mon Sep 17 00:00:00 2001 From: 4DBug <4DBug@github.com> Date: Tue, 20 Oct 2026 20:52:38 -0500 Subject: [PATCH] build: rebuild Roblox bundle + worker (backend and library performance work since 0.4.2) --- build/ImGui.linemap.json | 2 +- build/ImGui.luau | 1193 ++++++++++++++++++++++----------- build/ImGuiWorker.client.luau | 373 +++++++---- 3 files changed, 1063 insertions(+), 505 deletions(-) diff --git a/build/ImGui.linemap.json b/build/ImGui.linemap.json index 7510496..2e07f7f 100644 --- a/build/ImGui.linemap.json +++ b/build/ImGui.linemap.json @@ -1 +1 @@ -[[46, "imgui.lua"], [22688, "imgui_demo.lua"], [34545, "imgui_draw.lua"], [42896, "imgui_h.lua"], [45899, "roblox/raster.lua"], [46699, "roblox/textures.lua"], [46916, "roblox/layers.lua"], [47253, "roblox/overlays.lua"], [47334, "roblox/render.lua"], [48201, "roblox/parallel.lua"], [48648, "imgui_impl_roblox.lua"], [49149, "imgui_impl_roblox_fonts.lua"], [55552, "imgui_internal.lua"], [59520, "imgui_tables.lua"], [64612, "imgui_widgets.lua"], [76880, "imstb_rectpack.lua"], [77557, "imstb_textedit.lua"], [79099, "imstb_truetype.lua"], [82040, "imstd_minstdio.lua"]] \ No newline at end of file +[[46, "imgui.lua"], [22716, "imgui_demo.lua"], [34573, "imgui_draw.lua"], [42966, "imgui_h.lua"], [45969, "roblox/raster.lua"], [46902, "roblox/textures.lua"], [47140, "roblox/layers.lua"], [47524, "roblox/overlays.lua"], [47605, "roblox/render.lua"], [48499, "roblox/parallel.lua"], [49028, "imgui_impl_roblox.lua"], [49529, "imgui_impl_roblox_fonts.lua"], [55932, "imgui_internal.lua"], [59903, "imgui_tables.lua"], [65016, "imgui_widgets.lua"], [77307, "imstb_rectpack.lua"], [77984, "imstb_textedit.lua"], [79526, "imstb_truetype.lua"], [82487, "imstd_minstdio.lua"]] \ No newline at end of file diff --git a/build/ImGui.luau b/build/ImGui.luau index 9984345..e40eae2 100644 --- a/build/ImGui.luau +++ b/build/ImGui.luau @@ -1,7 +1,7 @@ --!optimize 2 -- GENERATED by tools/bundle.py from *.lua, backends/, fonts/ - do not edit -local ImGui, ImVec2, ImVec4, ImRect, ImVec2_Copy, HelpMarker, IMGUI_DEMO_MARKER, ImGuiTableFlags, ImStd, ImVector, ImDrawFlags, ImGuiInputFlags, ImRect_Copy, ImStb, ImGuiDataType, IM_TRUNC, ImGuiKey, ImGuiStyleVarInfo, ImVec2_CopyV, IM_ASSERT_USER_ERROR, ImGuiHoveredFlags, ImHashStr, IM_ASSERT_USER_ERROR_RET, ImIsPowerOfTwo, ImS32, ImGuiColorEditFlags, ImVec4_Copy, ImAbs, ExampleAppConsoleMT, IM_ROUND, ImFormatString, ImGuiTableColumnFlags, ImGuiTreeNodeFlags, PopStyleCompact, PushStyleCompact, IM_ASSERT_PARANOID, ImU16, ExampleNames, ImGuiWindowFlags, ImGuiItemFlags, stbte, ImColor, ImCos, ImGuiButtonFlags, ImGuiDebugLogFlags, ImGuiListClipper, ImGuiLocKey, ImU32, ExampleTreeFuncs, ImS16, _PathArcToFastExXY, ImGuiMultiSelectFlags, ImSin, ImGuiTabBarFlags, ImLengthSqr, ImUpperPowerOfTwo, IM_F32_TO_INT8_SAT, ImFontAtlasPackGetRect, ImS64, DockSettingsRenameNodeReferences, ExampleDualListBoxMT, IM_DRAWLIST_TEX_LINES_WIDTH_MAX, ImCeil, ImFabs, ImGuiCol, ImGuiSelectionBasicStorage, ImS8, ImU8, ExampleAppPropertyEditorMT, ImGuiChildFlags, ImGuiDockNodeFlags, ImGuiLastItemData_Copy, IMGUI_DEBUG_LOG_IO, ImAddClampOverflow, ImGuiScrollFlags, ImLog, ImMemchr, ImStrByte, ImSubClampOverflow, ExampleSelectionWithDeletionMT, IMGUI_DEBUG_LOG_VIEWPORT, ImFontCalcWordWrapPositionEx, ImGuiInputEvent, ImGuiPackedDate, ImGuiTextBuffer, ImHashData, ImPow, ImTrunc64, ImU64, CustomConstraints, ExampleAppLogMT, IMGUI_DEBUG_LOG_FONT, IMGUI_DEBUG_LOG_SELECTION, IMGUI_DISABLE_DEBUG_TOOLS, ImFontAtlasBuildInit, ImFontAtlasFontDestroyOutput, ImGuiComboFlags, ImGuiLastItemData, ImGuiPayload_IsDataType, ImGuiPopupFlags, ImGuiSliderFlags, ImGuiTextFilter, ImRotate, ImSqrt, ImTextClassifierSetCharClass, ImTextureRef, MyDocument, ShowExampleMenuFile, CalcCornerArcStepAndCount, CalcNextScrollFromScrollTargetAndClamp, DataTypeFormatStringCached, IMGUI_PAYLOAD_TYPE_WINDOW, IMGUI_VERSION, ImCharIsBlankW, ImCharIsSeparatorW, ImFmod, ImFontAtlasBakedAddFontGlyph, ImFontAtlasPackAddRect, ImFontBaked_BuildLoadGlyph, ImFontConfig, ImGuiInputTextFlags, ImGuiLogFlags, ImGuiNavMoveFlags, ImGuiStyle_Copy, ImVec1_Copy, ExampleAsset_s_current_sort_specs, ExampleMemberInfo, ExampleTree_CreateNode, IMGUI_PAYLOAD_TYPE_COLOR_4F, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC, IM_F32_TO_INT8_UNBOUND, IM_PI, ImCharIsBlankA, ImFontAtlasBuildNotifySetFont, ImFontAtlasBuildRenderBitmapFromString, ImFontAtlasFontDestroySourceData, ImFontAtlasFontDiscardBakes, ImFontAtlasFontSourceAddToFont, ImFontAtlasFontSourceInit, ImFontAtlasRectId_GetIndex, ImFontAtlasTextureAdd, ImFontAtlasTextureBlockQueueUpload, ImFontAtlasTextureGrow, ImFontBaked_BuildGrowIndex, ImFontGlyph, ImGuiTableColumn, ImGuiWindowClass, ImParseFormatFindStart, ImRect_CopyFromV4, ImTextureRect, MyItem_s_current_sort_specs, stb_textedit_key, stbtt_GetGlyphBitmapBoxSubpixel, DockSettingsHandler_ClearAll, EditTableSizingFlags, ExampleSelectionWithDeletion, FormatCached, IMGUI_DEBUG_LOG_TABLE, IMGUI_PAYLOAD_TYPE_COLOR_3F, IM_FREE +local ImGui, ImVec2, ImVec4, ImRect, ImVec2_Copy, HelpMarker, IMGUI_DEMO_MARKER, ImGuiTableFlags, ImStd, ImVector, ImDrawFlags, ImGuiInputFlags, ImRect_Copy, ImStb, ImGuiDataType, IM_TRUNC, ImGuiKey, ImGuiStyleVarInfo, ImVec2_CopyV, IM_ASSERT_USER_ERROR, ImGuiHoveredFlags, ImHashStr, IM_ASSERT_USER_ERROR_RET, ImIsPowerOfTwo, ImS32, ImGuiColorEditFlags, ImVec4_Copy, ImAbs, ExampleAppConsoleMT, ImFormatString, IM_ROUND, ImGuiTableColumnFlags, ImGuiTreeNodeFlags, PopStyleCompact, PushStyleCompact, IM_ASSERT_PARANOID, ImU16, ExampleNames, ImGuiWindowFlags, ImGuiItemFlags, stbte, ImColor, ImCos, ImGuiButtonFlags, ImGuiDebugLogFlags, ImGuiListClipper, ImGuiLocKey, ImU32, ExampleTreeFuncs, ImS16, _PathArcToFastExXY, ImGuiMultiSelectFlags, ImSin, ImGuiTabBarFlags, ImLengthSqr, ImUpperPowerOfTwo, IM_F32_TO_INT8_SAT, ImFontAtlasPackGetRect, ImS64, DockSettingsRenameNodeReferences, ExampleDualListBoxMT, IM_DRAWLIST_TEX_LINES_WIDTH_MAX, ImCeil, ImFabs, ImGuiCol, ImGuiSelectionBasicStorage, ImS8, ImU8, ExampleAppPropertyEditorMT, ImGuiChildFlags, ImGuiDockNodeFlags, ImGuiLastItemData_Copy, IMGUI_DEBUG_LOG_IO, ImAddClampOverflow, ImGuiScrollFlags, ImLog, ImMemchr, ImStrByte, ImSubClampOverflow, ExampleSelectionWithDeletionMT, IMGUI_DEBUG_LOG_VIEWPORT, ImFontCalcWordWrapPositionEx, ImGuiInputEvent, ImGuiPackedDate, ImGuiTextBuffer, ImHashData, ImPow, ImTrunc64, ImU64, CustomConstraints, ExampleAppLogMT, IMGUI_DEBUG_LOG_FONT, IMGUI_DEBUG_LOG_SELECTION, IMGUI_DISABLE_DEBUG_TOOLS, ImFontAtlasBuildInit, ImFontAtlasFontDestroyOutput, ImGuiComboFlags, ImGuiLastItemData, ImGuiPayload_IsDataType, ImGuiPopupFlags, ImGuiSliderFlags, ImGuiTextFilter, ImRotate, ImSqrt, ImTextClassifierSetCharClass, ImTextureRef, MyDocument, ShowExampleMenuFile, CalcCornerArcStepAndCount, CalcNextScrollFromScrollTargetAndClamp, DataTypeFormatStringCached, IMGUI_PAYLOAD_TYPE_WINDOW, IMGUI_VERSION, ImCharIsBlankW, ImCharIsSeparatorW, ImFmod, ImFontAtlasBakedAddFontGlyph, ImFontAtlasPackAddRect, ImFontBaked_BuildLoadGlyph, ImFontConfig, ImGuiInputTextFlags, ImGuiLogFlags, ImGuiNavMoveFlags, ImGuiStyle_Copy, ImVec1_Copy, ExampleAsset_s_current_sort_specs, ExampleMemberInfo, ExampleTree_CreateNode, IMGUI_PAYLOAD_TYPE_COLOR_4F, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC, IM_F32_TO_INT8_UNBOUND, IM_PI, ImCharIsBlankA, ImFontAtlasBuildNotifySetFont, ImFontAtlasBuildRenderBitmapFromString, ImFontAtlasFontDestroySourceData, ImFontAtlasFontDiscardBakes, ImFontAtlasFontSourceAddToFont, ImFontAtlasFontSourceInit, ImFontAtlasRectId_GetIndex, ImFontAtlasTextureAdd, ImFontAtlasTextureBlockQueueUpload, ImFontAtlasTextureGrow, ImFontBaked_BuildGrowIndex, ImFontGlyph, ImGuiTableColumn, ImGuiWindowClass, ImParseFormatFindStart, ImRect_CopyFromV4, ImTextureRect, MyItem_s_current_sort_specs, stb_textedit_key, stbtt_GetGlyphBitmapBoxSubpixel, DockSettingsHandler_ClearAll, EditTableSizingFlags, ExampleSelectionWithDeletion, FormatCached, IMGUI_DEBUG_LOG_TABLE, IMGUI_PAYLOAD_TYPE_COLOR_3F, IM_FREE local type, mathMin, mathMax, mathFloor, mathCeil, bitOr, bitLShift = type, math.min, math.max, math.floor, math.ceil, bit32.bor, bit32.lshift local function IM_COL32(R, G, B, A) return (bitOr(bitLShift(A, 24 --[[IM_COL32_A_SHIFT]]), bitLShift(B, 16 --[[IM_COL32_B_SHIFT]]), bitLShift(G, 8 --[[IM_COL32_G_SHIFT]]), bitLShift(R, 0 --[[IM_COL32_R_SHIFT]]))) end @native @@ -6828,6 +6828,7 @@ function ImGui.SameLine(offset_from_start_x, spacing_w) end --- @param indent_w? float +@native function ImGui.Indent(indent_w) if indent_w == nil then indent_w = 0.0 end @@ -6844,6 +6845,7 @@ function ImGui.Indent(indent_w) end --- @param indent_w? float +@native function ImGui.Unindent(indent_w) if indent_w == nil then indent_w = 0.0 end @@ -6880,6 +6882,7 @@ function ImGui.PushItemWidth(item_width) g.NextItemData.HasFlags = bit32.band(g.NextItemData.HasFlags, bit32.bnot(1 --[[ImGuiNextItemDataFlags.HasWidth]])) end +@native function ImGui.PopItemWidth() local g = GImGui local window = g.CurrentWindow @@ -7178,12 +7181,14 @@ end --- @param default_w float --- @param default_h float --- @return ImVec2 +@native function ImGui.CalcItemSize(size, default_w, default_h) return ImVec2(ImGui._CalcItemSizeXY(size.x, size.y, default_w, default_h)) -- [Luau] 'size' is by value upstream: never written to end -- [Luau] scalar CalcItemSize(): callers that build 'size' themselves skip both ImVec2 allocations --- @return float, float +@native function ImGui._CalcItemSizeXY(size_x, size_y, default_w, default_h) local avail_x, avail_y if size_x < 0.0 or size_y < 0.0 then @@ -7761,6 +7766,7 @@ end -- Push a given id value ignoring the ID stack as a seed. --- @param id ImGuiID +@native function ImGui.PushOverrideID(id) local g = GImGui local window = g.CurrentWindow @@ -8729,6 +8735,7 @@ end --- @param ctx? ImGuiContext --- @param key ImGuiKey --- @return ImGuiKeyData, int +@native function ImGui.GetKeyData(ctx, key) if ctx == nil then ctx = GImGui end @@ -8796,6 +8803,7 @@ end -- Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey.A) (>= 1.87) --- @param key ImGuiKey --- @param owner_id? ImGuiID +@native function ImGui.IsKeyDown(key, owner_id) if owner_id == nil then owner_id = 0 --[[ImGuiKeyOwner_Any]] end @@ -9030,13 +9038,15 @@ end -- Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6 -- See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation. --- @param rt ImGuiKeyRoutingTable +@native function ImGui.UpdateKeyRoutingTable(rt) local g = GImGui --[[@as ImGuiContext]] rt.EntriesNext:resize(0) + local index, entries_next = rt.Index, rt.EntriesNext -- [Luau] cached field reads (same tables until the swap below) for key = 512 --[[ImGuiKey.NamedKey_BEGIN]], 667 --[[ImGuiKey.NamedKey_END]] - 1 do - local new_routing_start_idx = rt.EntriesNext.Size + 1 + local new_routing_start_idx = entries_next.Size + 1 local routing_entry - local old_routing_idx = rt.Index[key - 512 --[[ImGuiKey.NamedKey_BEGIN]] + 1] + local old_routing_idx = index[key - 512 --[[ImGuiKey.NamedKey_BEGIN]] + 1] while old_routing_idx ~= -1 do repeat routing_entry = rt.Entries[old_routing_idx] @@ -9048,7 +9058,7 @@ function ImGui.UpdateKeyRoutingTable(rt) break end - rt.EntriesNext:push_back(routing_entry) -- Write alive ones into new buffer + entries_next:push_back(routing_entry) -- Write alive ones into new buffer -- Apply routing to owner if there's no owner already (RoutingCurr == None at this point) -- This is the result of previous frame's SetShortcutRouting() call. @@ -9066,9 +9076,9 @@ function ImGui.UpdateKeyRoutingTable(rt) end -- Rewrite linked-list - rt.Index[key - 512 --[[ImGuiKey.NamedKey_BEGIN]] + 1] = (new_routing_start_idx <= rt.EntriesNext.Size and new_routing_start_idx or -1) - for n = new_routing_start_idx, rt.EntriesNext.Size do - rt.EntriesNext[n].NextEntryIndex = (n + 1 <= rt.EntriesNext.Size) and (n + 1) or -1 + index[key - 512 --[[ImGuiKey.NamedKey_BEGIN]] + 1] = (new_routing_start_idx <= entries_next.Size and new_routing_start_idx or -1) + for n = new_routing_start_idx, entries_next.Size do + entries_next[n].NextEntryIndex = (n + 1 <= entries_next.Size) and (n + 1) or -1 end end rt.Entries:swap(rt.EntriesNext) -- Swap new and old indexes @@ -10414,6 +10424,7 @@ end --- @param pos ImVec2 --- @param wrap_pos_x float --- @return float +@native function ImGui.CalcWrapWidthForPos(pos, wrap_pos_x) if wrap_pos_x < 0.0 then return 0.0 @@ -10448,12 +10459,18 @@ end @native function ImGui.FindRenderedTextEnd(text, text_end) local text_display_end = 1 - local text_len = #text - if not text_end then - text_end = text_len + 1 + if type(text) == "string" then + -- [Luau] inline ImMemchr() for strings; string.len(): `#` on a string isn't a native fast path + if not text_end then + text_end = string.len(text) + 1 + end + text_display_end = string.find(text, "##", 1, true) or text_end + else + if not text_end then + text_end = #text + 1 + end + text_display_end = ImMemchr(text, "##", 1) or text_end end - - text_display_end = ImMemchr(text, "##", 1) or text_end text_display_end = math.min(text_display_end, text_end) -- [Luau] scalar ImMin() return text_display_end @@ -10497,6 +10514,7 @@ end --- @param text string --- @param text_end int? --- @param wrap_width float +@native function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width) local g = GImGui local window = g.CurrentWindow @@ -10575,6 +10593,7 @@ end --- @param text_size_if_known? ImVec2 --- @param align? ImVec2 --- @param clip_rect? ImRect +@native function ImGui.RenderTextClipped(pos_min, pos_max, text, text_end, text_size_if_known, align, clip_rect) if not align then align = RenderTextClipped_align0 end @@ -13585,6 +13604,7 @@ function ImGui.GetMergedModsFromKeys() return mods end +@native function ImGui.UpdateKeyboardInputs() local g = GImGui local io = g.IO @@ -13626,14 +13646,15 @@ function ImGui.UpdateKeyboardInputs() end -- Update keys + local keys_data, delta_time = io.KeysData, io.DeltaTime -- [Luau] cached field reads for key = 512 --[[ImGuiKey.NamedKey_BEGIN]], 667 --[[ImGuiKey.NamedKey_END]] - 1 do - local key_data = io.KeysData[key - 512 --[[ImGuiKey.NamedKey_BEGIN]]] + local key_data = keys_data[key - 512 --[[ImGuiKey.NamedKey_BEGIN]]] key_data.DownDurationPrev = key_data.DownDuration if key_data.Down then if key_data.DownDuration < 0.0 then key_data.DownDuration = 0.0 else - key_data.DownDuration = key_data.DownDuration + io.DeltaTime + key_data.DownDuration = key_data.DownDuration + delta_time end else key_data.DownDuration = -1.0 @@ -13648,9 +13669,10 @@ function ImGui.UpdateKeyboardInputs() end -- Update keys/input owner (named keys only): one entry per key + local keys_owner_data = g.KeysOwnerData -- [Luau] cached field read for key = 512 --[[ImGuiKey.NamedKey_BEGIN]], 667 --[[ImGuiKey.NamedKey_END]] - 1 do - local key_data = io.KeysData[key - 512 --[[ImGuiKey.NamedKey_BEGIN]]] - local owner_data = g.KeysOwnerData[key - 512 --[[ImGuiKey.NamedKey_BEGIN]]] + local key_data = keys_data[key - 512 --[[ImGuiKey.NamedKey_BEGIN]]] + local owner_data = keys_owner_data[key - 512 --[[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 = 4294967295 --[[ImGuiKeyOwner_NoOwner]] @@ -14024,6 +14046,7 @@ function ImGui.GetScale() end --- @return ImGuiWindow +@native function ImGui.GetCurrentWindowRead() local g = GImGui return g.CurrentWindow @@ -14032,9 +14055,9 @@ end --- @return ImGuiWindow @native function ImGui.GetCurrentWindow() - local g = GImGui - g.CurrentWindow.WriteAccessed = true - return g.CurrentWindow + local window = GImGui.CurrentWindow -- [Luau] one read: CurrentWindow sits in a hash slot the inline cache can't predict + window.WriteAccessed = true + return window end -- Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. @@ -14733,7 +14756,8 @@ end --- @return ImVec2 @native function ImGui.CalcTextSize(text, text_end, hide_text_after_double_hash, wrap_width) - return ImGui.CalcTextSizeEx(text, 1, text_end, hide_text_after_double_hash, wrap_width) + local x, y = ImGui.CalcTextSizeXY(text, 1, text_end, hide_text_after_double_hash, wrap_width) -- [Luau] inline CalcTextSizeEx() + return ImVec2(x, y) end --- @param text ImString @@ -15135,6 +15159,7 @@ end -- FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 --- @param idx ImGuiCol --- @param col ImU32|ImVec4 +@native function ImGui.PushStyleColor(idx, col) local g = GImGui local backup = ImGuiColorMod(idx, g.Style.Colors[idx]) @@ -15152,6 +15177,7 @@ function ImGui.PushStyleColor(idx, col) end --- @param count? int +@native function ImGui.PopStyleColor(count) if count == nil then count = 1 end @@ -15293,6 +15319,7 @@ end -- ATTENTION THIS IS IN LEGACY LOCAL SPACE. --- @param wrap_local_pos_x float +@native function ImGui.PushTextWrapPos(wrap_local_pos_x) local g = GImGui local window = g.CurrentWindow @@ -15304,6 +15331,7 @@ function ImGui.PushTextWrapPos(wrap_local_pos_x) dc.TextWrapPos = wrap_local_pos_x end +@native function ImGui.PopTextWrapPos() local g = GImGui local window = g.CurrentWindow @@ -35181,6 +35209,10 @@ function MT.ImFontAtlas:ClearFonts() end end +-- [Luau] Pixels of the last atlas texture removed after the backend destroyed it: the next ImTextureData:Create() of +-- the same byte size (atlas repack: same size every time) zero-fills and reuses it instead of allocating a new table +local RecycledTexPixels, RecycledTexPixelsSize = nil, 0 + --- @param tex ImTextureData function ImTextureDataUpdateNewFrame(tex) local remove_from_list = false @@ -35253,6 +35285,9 @@ function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) if remove_from_list then assert(atlas.TexData ~= tex) + if tex.Pixels ~= nil then + RecycledTexPixels, RecycledTexPixelsSize = tex.Pixels, tex.Width * tex.Height * tex.BytesPerPixel + end tex:DestroyPixels() atlas.TexList:erase(tex_n) tex_n = tex_n - 1 @@ -35569,6 +35604,10 @@ function ImFontAtlasRemoveDrawListSharedData(atlas, data) atlas.DrawListSharedDatas:find_erase(data) end +-- [Luau] RectsIndex index of the entry the repack loop is re-adding: ImFontAtlasPackReuseRectEntry() checks it before +-- searching RectsIndex (index_from_ptr is a linear search: O(n^2) per repack otherwise) +local ImFontAtlasPackReuseIndexHint = nil + --- @param atlas ImFontAtlas --- @param w int --- @param h int @@ -35596,7 +35635,7 @@ local function ImFontAtlasTextureRepack(atlas, w, h) local old_index = builder.RectsIndex:copy() old_rects:swap(builder.Rects) - for _, index_entry in builder.RectsIndex:iter() do + for index_n, index_entry in builder.RectsIndex:iter() do repeat if index_entry.IsUsed == false then break @@ -35607,7 +35646,9 @@ local function ImFontAtlasTextureRepack(atlas, w, h) break end + ImFontAtlasPackReuseIndexHint = index_n - 1 local new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, index_entry) + ImFontAtlasPackReuseIndexHint = nil if new_r_id == (-1) --[[ImFontAtlasRectId_Invalid]] then -- Undo, grow texture and try repacking again. -- FIXME-NEWATLAS-TESTS: This is a very rarely exercised path! It needs to be automatically tested properly. @@ -35622,7 +35663,7 @@ local function ImFontAtlasTextureRepack(atlas, w, h) return end - assert(ImFontAtlasRectId_GetIndex(new_r_id) == builder.RectsIndex:index_from_ptr(index_entry)) + assert(ImFontAtlasRectId_GetIndex(new_r_id) == index_n - 1) -- [Luau] == RectsIndex:index_from_ptr(index_entry) local new_r = ImFontAtlasPackGetRect(atlas, new_r_id) ImFontAtlasTextureBlockCopy(old_tex, old_r.x, old_r.y, new_tex, new_r.x, new_r.y, new_r.w, new_r.h) @@ -35737,7 +35778,10 @@ end local function ImFontAtlasPackReuseRectEntry(atlas, index_entry) assert(index_entry.IsUsed) index_entry.TargetIndex = atlas.Builder.Rects.Size - 1 - local index_idx = atlas.Builder.RectsIndex:index_from_ptr(index_entry) + local index_idx = ImFontAtlasPackReuseIndexHint + if index_idx == nil or atlas.Builder.RectsIndex.Data[index_idx + 1] ~= index_entry then + index_idx = atlas.Builder.RectsIndex:index_from_ptr(index_entry) + end return ImFontAtlasRectId_Make(index_idx, index_entry.Generation) end @@ -37249,7 +37293,18 @@ function MT.ImTextureData:Create(format, w, h) self.BytesPerPixel = ImTextureDataGetFormatBytesPerPixel(format) self.UseColors = false local n = self.Width * self.Height * self.BytesPerPixel - if table.create then + if RecycledTexPixels ~= nil and RecycledTexPixelsSize == n then + -- [Luau] same contents as memset: zero the first block, then double it with table.move (native copies) + local p, k = RecycledTexPixels, math.min(n, 4096) + RecycledTexPixels, RecycledTexPixelsSize = nil, 0 + for i = 1, k do p[i] = 0 end + while k < n do + local c = math.min(k, n - k) + table.move(p, 1, c, k + 1) + k = k + c + end + self.Pixels = p + elseif table.create then self.Pixels = table.create(n, 0) -- [Luau] native zero fill, same contents as memset else self.Pixels = {} @@ -37351,6 +37406,7 @@ end -- Find glyph, load if necessary, return fallback if missing --- @param c ImWchar --- @return ImFontGlyph? +@native function MT.ImFontBaked:FindGlyph(c) if c < self.IndexLookup.Size then local i = self.IndexLookup.Data[c + 1] @@ -37555,6 +37611,7 @@ end --- @param size float --- @param density float? --- @return ImFontBaked? +@native function MT.ImFont:GetFontBaked(size, density) if not density then density = -1.0 end @@ -37836,7 +37893,10 @@ local ImFontCalcWordWrapPositionEx_Uncached local WRAP_MEMO_MAX = 4096 function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_width, flags) - local baked = font:GetFontBaked(size) + local baked = font.LastBaked -- [Luau] inline font:GetFontBaked(size) fast path + if not (baked and baked.Size == math.floor(size + 0.5) and baked.RasterizerDensity == font.CurrentRasterizerDensity) then + baked = font:GetFontBaked(size) + end if type(text) ~= "string" then return ImFontCalcWordWrapPositionEx_Uncached(baked, size, text, pos, text_end, wrap_width, flags) end @@ -38025,11 +38085,14 @@ function ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begi -- Advances of a baked font never change once loaded, so entries stay valid. local cache_key = nil local wrap_cache = nil - local text_len1 = text_is_str and #text + 1 or -1 + local text_len1 = text_is_str and string.len(text) + 1 or -1 -- [Luau] string.len(): `#` on a string isn't a native fast path + local baked = font.LastBaked -- [Luau] inline font:GetFontBaked(size) fast path (same baked as the calls below in upstream) + if not (baked and baked.Size == math.floor(size + 0.5) and baked.RasterizerDensity == font.CurrentRasterizerDensity) then + baked = font:GetFontBaked(size) + end local cacheable = text_is_str and text_begin == 1 and out_offset == nil and max_width >= 3.4028234663853e+38 --[[FLT_MAX]] and (text_end == nil or text_end == text_len1) and (text_end_display == nil or text_end_display == text_len1) and (flags == nil or bit32.band(flags, 4 --[[ImDrawTextFlags.StopOnNewLine]]) == 0) if cacheable and wrap_width <= 0.0 then - local baked = font:GetFontBaked(size) local cache = baked._TextSizeCache if cache == nil or baked._TextSizeCacheN >= TEXT_SIZE_CACHE_MAX then cache = {}; baked._TextSizeCache = cache; baked._TextSizeCacheN = 0 @@ -38041,7 +38104,6 @@ function ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begi cache_key = text elseif cacheable and wrap_width > 0.0 then -- [Luau] same for wrapped text (TextWrapped() measures every line every frame): exact results per (size, wrap width, text) - local baked = font:GetFontBaked(size) local cache = baked._TextSizeCache if cache == nil or baked._TextSizeCacheN >= TEXT_SIZE_CACHE_MAX then cache = {}; baked._TextSizeCache = cache; baked._TextSizeCacheN = 0 @@ -38063,7 +38125,6 @@ function ImFontCalcTextSizeXY(font, size, max_width, wrap_width, text, text_begi text_end_display = text_end end - local baked = font:GetFontBaked(size) local line_height = size local scale = line_height / baked.Size @@ -38889,6 +38950,7 @@ function MT.ImDrawList:CloneOutput() return dst end +@native function MT.ImDrawList:AddDrawCmd() local draw_cmd = ImDrawCmd() @@ -39019,6 +39081,7 @@ end -- Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. -- The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. +@native function MT.ImDrawList:_OnChangedClipRect() -- If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) @@ -39276,7 +39339,7 @@ function MT.ImDrawListSplitter:SetCurrentChannel(draw_list, idx) curr_cmd.TexRef = header.TexRef curr_cmd.VtxOffset = header.VtxOffset elseif ccr.x ~= hcr.x or ccr.y ~= hcr.y or ccr.z ~= hcr.z or ccr.w ~= hcr.w - or curr_cmd.TexRef._TexData ~= header.TexRef._TexData or curr_cmd.TexRef._TexID ~= header.TexRef._TexID + or (curr_cmd.TexRef ~= header.TexRef and (curr_cmd.TexRef._TexData ~= header.TexRef._TexData or curr_cmd.TexRef._TexID ~= header.TexRef._TexID)) or curr_cmd.VtxOffset ~= header.VtxOffset then draw_list:AddDrawCmd() end @@ -39378,6 +39441,7 @@ end MT.ImDrawList.PrimReserve = PrimReserve -- Release the number of reserved vertices/indices from the end of the last reservation made with PrimReserve(). +@native function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count) IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0) @@ -39434,6 +39498,7 @@ end --- @param uv_a ImVec2 --- @param uv_c ImVec2 --- @param col any +@native function MT.ImDrawList:PrimRectUV(a, c, uv_a, uv_c, col) local idx = self._VtxCurrentIdx local idx_data = self.IdxBuffer.Data; local vtx_data = self.VtxBuffer.Buf @@ -41546,6 +41611,7 @@ function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius) end -- Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui.PushClipRect() to affect logic (hit-testing and widget culling) +@native function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect) -- [Luau] reuse the stack slot's ImVec4 left from earlier frames (each slot stays uniquely owned by the stack) local stack = self._ClipRectStack @@ -41580,6 +41646,7 @@ function MT.ImDrawList:PushClipRectFullScreen() self:PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.z, cr.w)) end +@native function MT.ImDrawList:PopClipRect() local stack = self._ClipRectStack assert(stack.Size > 0) @@ -41832,7 +41899,10 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b local line_height = size - local baked = self:GetFontBaked(size) + local baked = self.LastBaked -- [Luau] inline self:GetFontBaked(size) fast path + if not (baked and baked.Size == math.floor(size + 0.5) and baked.RasterizerDensity == self.CurrentRasterizerDensity) then + baked = self:GetFontBaked(size) + end local scale = size / baked.Size local origin_x = x @@ -45915,7 +45985,9 @@ local M = { } local TILE = M.TILE -local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0 +-- Pixel (x, y) of the target is at byte (y * TargetWidth + x) * 4 + TargetBase: a target can be a sub-rectangle of the +-- tile (raster straight into the upload buffer) +local TargetBuffer: buffer, TargetWidth, TargetBase = buffer.create(0), 0, 0 local PrevRow = buffer.create(1024) -- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else @@ -45937,30 +46009,46 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean return false end local RectColumns = table.create(256, 0) +-- DrawRect's per-alpha blend cache: GlyphKey[alpha] = GlyphGen + destination value -> GlyphValue[alpha]. GlyphGen +-- (a multiple of 2^32) changes with the vertex colour. +local GlyphKey, GlyphValue = table.create(256, -1), table.create(256, 0) +GlyphKey[0], GlyphValue[0] = -1, 0 +local GlyphCol, GlyphGen = -1, 0 --- Uniform region: [UX0, UX1) x [UY0, UY1) of the target holds only the pixel value UV (empty when UX0 >= UX1). --- Set by ClearRect and by solid rects; shrunk by everything drawn over it. A solid rect inside it blends one pixel and --- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. -local UX0, UY0, UX1, UY1, UV = 0, 0, 0, 0, 0 +-- Uniform rows: [RowX0[y], RowX1[y]) of target row y holds only the pixel value RowV[y] (empty when RowX0 >= RowX1). +-- Set by ClearRect and by solid spans; shrunk by everything drawn over it. A solid span inside it blends one pixel and +-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. Only the rows of the last +-- ClearRect are valid: drawing must stay inside it (callers clip every primitive to the cleared rect). +local RowX0, RowX1, RowV = table.create(TILE, 0), table.create(TILE, 0), table.create(TILE, 0) +RowX0[0], RowX1[0], RowV[0] = 0, 0, 0 --- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece outside it +-- Drawing changed [x0, x1) x [y0, y1): keep the larger uniform piece of each row outside it +@native +local function ApplyDamage(x0: number, y0: number, x1: number, y1: number) + for y = y0, y1 - 1 do + local a, b = RowX0[y], RowX1[y] + if x0 < b and x1 > a then + if x0 - a >= b - x1 then RowX1[y] = x0 else RowX0[y] = x1 end + end + end +end + +-- Only FillSpan reads the uniform rows: damage is collected into one pending rect (nearby rects merged: a text line's +-- glyphs, a shape's triangles) and applied when FillSpan runs. Over-shrinking only loses uniform pixels. +local PX0, PY0, PX1, PY1 = 0, 0, 0, 0 -- pending damage (none when PX0 >= PX1) @native local function Shrink(x0: number, y0: number, x1: number, y1: number) - if x0 >= UX1 or x1 <= UX0 or y0 >= UY1 or y1 <= UY0 or UX0 >= UX1 then return end - local h, w = UY1 - UY0, UX1 - UX0 - local left, right, top, bottom = (x0 - UX0) * h, (UX1 - x1) * h, (y0 - UY0) * w, (UY1 - y1) * w - local best = max(left, right, top, bottom) - if best <= 0 then - UX1 = UX0 - elseif best == left then - UX1 = x0 - elseif best == right then - UX0 = x1 - elseif best == top then - UY1 = y0 - else - UY0 = y1 + if PX0 >= PX1 then + PX0, PY0, PX1, PY1 = x0, y0, x1, y1 + return end + local ux0, uy0, ux1, uy1 = min(x0, PX0), min(y0, PY0), max(x1, PX1), max(y1, PY1) + if (ux1 - ux0) * (uy1 - uy0) <= ((x1 - x0) * (y1 - y0) + (PX1 - PX0) * (PY1 - PY0)) * 1.25 + 256 then + PX0, PY0, PX1, PY1 = ux0, uy0, ux1, uy1 + return + end + ApplyDamage(PX0, PY0, PX1, PY1) + PX0, PY0, PX1, PY1 = x0, y0, x1, y1 end -- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync. @@ -45993,57 +46081,120 @@ local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, end end +-- Wide spans (>= 32 px) over non-uniform rows: rows usually blend over identical rows, so a row whose destination +-- repeats the previous one's copies its result @native local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number, b: number, a: number) if a <= 0 then return end - local w4 = (x1 - x0 - 1) * 4 - if x0 >= UX0 and y0 >= UY0 and x1 <= UX1 and y1 <= UY1 and a < 255 then - -- over one value: FillSpan's per-pixel result for d = UV, then fill - local d, v = UV, 0 - if d < 16777216 then - v = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 - else - local sa = a / 255 - local ns = 1 - sa - local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) - if d >= 4278190080 then - v = floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 - + floor(b * sa + db * ns + 0.5) * 65536 + 4278190080 - else - local k = rshift(d, 24) * (ns / 255) - local oa = sa + k - local inv = 1 / oa - v = floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256 - + floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 - end - end - local first = (y0 * TargetWidth + x0) * 4 - for o = first, first + w4, 4 do writeu32(TargetBuffer, o, v) end - for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end - UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, v - return + if PX0 < PX1 then + ApplyDamage(PX0, PY0, PX1, PY1) + PX1 = PX0 end + local w4 = (x1 - x0 - 1) * 4 + local span = x1 - x0 if a >= 255 then local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 - local first = (y0 * TargetWidth + x0) * 4 + local first = (y0 * TargetWidth + x0) * 4 + TargetBase for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end - for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end - -- now uniform: keep whichever region is larger - local area = (x1 - x0) * (y1 - y0) - Shrink(x0, y0, x1, y1) - if area > (UX1 - UX0) * (UY1 - UY0) or UX0 >= UX1 then UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, packed end + for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4 + TargetBase, TargetBuffer, first, w4 + 4) end + -- now uniform: per row keep whichever piece is larger (the same for following rows with the same piece) + local y = y0 + while y < y1 do + local ra, rb = RowX0[y], RowX1[y] + local na, nb = ra, rb + if x0 < rb and x1 > ra then + if x0 - ra >= rb - x1 then nb = x0 else na = x1 end + end + if span > nb - na then + repeat + RowX0[y], RowX1[y], RowV[y] = x0, x1, packed + y += 1 + until y >= y1 or RowX0[y] ~= ra or RowX1[y] ~= rb + else + repeat + RowX0[y], RowX1[y] = na, nb + y += 1 + until y >= y1 or RowX0[y] ~= ra or RowX1[y] ~= rb + end + end return end - Shrink(x0, y0, x1, y1) local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 local sa = a / 255 local ns = 1 - sa local c1 = ns / 255 local rs, gs, bs = r * sa, g * sa, b * sa local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination - for y = y0, y1 - 1 do - local o0 = (y * TargetWidth + x0) * 4 + local prev_o, prev_v = 0, -1 -- previous row: filled with prev_v (-1: blended) + local wide, has_prev = span >= 32 and y1 - y0 > 1, false + local y = y0 + while y < y1 do + local o0 = (y * TargetWidth + x0) * 4 + TargetBase + local ra, rb = RowX0[y], RowX1[y] + if x0 >= ra and x1 <= rb then + -- over one value: the per-pixel result for d = RowV[y], then fill; following rows with the same uniform + -- piece get the same result + local d = RowV[y] + if d ~= last_d then + last_d = d + if d < 16777216 then + last_v = packed0 + else + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256 + + floor(bs + db * ns + 0.5) * 65536 + 4278190080 + else + local k = rshift(d, 24) * c1 + local oa = sa + k + local inv = 1 / oa + last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256 + + floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 + end + end + end + local v = last_v + if v == prev_v and span > 8 then -- (a call: slower than a few writes) + buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4) + else + for o = o0, o0 + w4, 4 do writeu32(TargetBuffer, o, v) end + end + local na, nb, nv = ra, rb, d + if span >= x0 - ra and span >= rb - x1 then + na, nb, nv = x0, x1, v + elseif x0 - ra >= rb - x1 then + nb = x0 + else + na = x1 + end + RowX0[y], RowX1[y], RowV[y] = na, nb, nv + y += 1 + local stride = TargetWidth * 4 + local o = o0 + while y < y1 and RowX0[y] == ra and RowX1[y] == rb and RowV[y] == d do + o += stride + buffer.copy(TargetBuffer, o, TargetBuffer, o0, w4 + 4) + RowX0[y], RowX1[y], RowV[y] = na, nb, nv + y += 1 + end + prev_o, prev_v, has_prev = o, v, false + continue + end + if x0 < rb and x1 > ra then + if x0 - ra >= rb - x1 then RowX1[y] = x0 else RowX0[y] = x1 end + end + if wide then + local repeats = RowRepeats(o0, w4 + 4, has_prev) + has_prev = true + if repeats then + buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4) + prev_o, prev_v = o0, -1 + y += 1 + continue + end + end + prev_o, prev_v = o0, -1 for o = o0, o0 + w4, 4 do local d = readu32(TargetBuffer, o) if d == last_d then @@ -46066,6 +46217,7 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number writeu32(TargetBuffer, o, last_v) end end + y += 1 end end @@ -46100,23 +46252,7 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 end if a <= 0 then return end - if a >= 255 or px1 - px0 < 32 or (px0 >= UX0 and py0 >= UY0 and px1 <= UX1 and py1 <= UY1) then - FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a) - return - end - -- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result - Shrink(px0, py0, px1, py1) - local len = (px1 - px0) * 4 - local prev_o = 0 - for y = py0, py1 - 1 do - local o = (y * TargetWidth + px0) * 4 - if RowRepeats(o, len, y > py0) then - buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) - else - FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a) - end - prev_o = o - end + FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a) return end @@ -46128,18 +46264,31 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number local cols = RectColumns local ident = col == 4294967295 local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 + local step = true for c = 1, ncol do local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end cols[c] = tx * 4 + if c > 1 and tx * 4 ~= cols[c - 1] + 4 then step = false end end + -- white translucent texels (font atlas): blend result cached per alpha for one destination value and colour + if col ~= GlyphCol then + GlyphCol = col + GlyphGen += 4294967296 + if GlyphGen >= 4503599627370496 then -- 2^52: keys must stay exact + GlyphGen = 4294967296 + for k = 0, 255 do GlyphKey[k] = -1 end + end + end + local gen = GlyphGen for y = py0, py1 - 1 do local ty = floor((v0 + (y + 0.5 - y0) * dv) * th) if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end local trow4 = ty * tw * 4 - local o = (y * TargetWidth + px0) * 4 + local o = (y * TargetWidth + px0) * 4 + TargetBase + local tb0 = trow4 + cols[1] - 4 for c = 1, ncol do - local tv = readu32(tbuf, trow4 + cols[c]) + local tv = readu32(tbuf, step and tb0 + c * 4 or trow4 + cols[c]) if tv < 16777216 then o += 4 continue @@ -46149,6 +46298,17 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number o += 4 continue end + local d, key, al = 0, -1, 0 + if tv % 16777216 == 16777215 then + al = rshift(tv, 24) + d = readu32(dbuf, o) + key = gen + d + if GlyphKey[al] == key then + writeu32(dbuf, o, GlyphValue[al]) + o += 4 + continue + end + end -- BlendPixel inlined (same math) if tv ~= last_tv then last_tv = tv @@ -46159,27 +46319,35 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number fn = 1 - fa fk = (1 - fa) / 255 end + local v = -1 if sa >= 255 then - writeu32(dbuf, o, s_opaque + 4278190080) + v = s_opaque + 4278190080 elseif sa > 0 then - local d = readu32(dbuf, o) + if key < 0 then d = readu32(dbuf, o) end if d < 16777216 then - writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) + v = s_opaque + floor(sa + 0.5) * 16777216 else local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) if d >= 4278190080 then - writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 - + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + v = floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080 else local k = rshift(d, 24) * fk local oa = fa + k local inv = 1 / oa - writeu32(dbuf, o, floor((sr * fa + dr * k) * inv + 0.5) - + floor((sg * fa + dg * k) * inv + 0.5) * 256 - + floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + v = floor((sr * fa + dr * k) * inv + 0.5) + floor((sg * fa + dg * k) * inv + 0.5) * 256 + + floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 end end end + if v >= 0 then + writeu32(dbuf, o, v) + elseif key >= 0 then + v = d -- unchanged + end + if key >= 0 then + GlyphKey[al], GlyphValue[al] = key, v + end o += 4 end end @@ -46279,7 +46447,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, yb -= 1 end if yt > yb then continue end - local o = (yt * TargetWidth + x) * 4 + local o = (yt * TargetWidth + x) * 4 + TargetBase if flat then for _ = yt, yb do BlendPixel(dbuf, o, ra, ga, ba, aa) @@ -46339,7 +46507,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, xr -= 1 end if xl > xr then continue end - local o = (y * TargetWidth + xl) * 4 + local o = (y * TargetWidth + xl) * 4 + TargetBase if flat then local o1 = o + (xr - xl) * 4 if f_opaque then @@ -46515,7 +46683,7 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number, xr -= 1 end if xl > xr then continue end - local o = (y * TargetWidth + xl) * 4 + local o = (y * TargetWidth + xl) * 4 + TargetBase local wrow = WB * py + WC for x = xl, xr do local w = WA * (x + 0.5) + wrow @@ -46588,7 +46756,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1 local opaque = aa >= 255 and ab >= 255 local prev_o = 0 for y = py0, py1 - 1 do - local o = (y * TargetWidth + px0) * 4 + local o = (y * TargetWidth + px0) * 4 + TargetBase if y > py0 and (opaque or RowRepeats(o, len, true)) or (y == py0 and not opaque and RowRepeats(o, len, false)) then buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) @@ -46606,26 +46774,20 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1 end end -function M.SetTarget(buf: buffer, width: number) - TargetBuffer, TargetWidth = buf, width - UX1 = UX0 +-- x0 y0: target pixel stored at buf's byte 0 (a sub-rectangle target: width = its width) +function M.SetTarget(buf: buffer, width: number, x0: number?, y0: number?) + TargetBuffer, TargetWidth, TargetBase = buf, width, -((y0 or 0) * width + (x0 or 0)) * 4 end @native function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) local rw = rx1 - rx0 - UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0 + for y = ry0, ry1 - 1 do RowX0[y], RowX1[y], RowV[y] = rx0, rx1, 0 end + PX1 = PX0 if rw == TargetWidth then - buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) + buffer.fill(TargetBuffer, (ry0 * TargetWidth + rx0) * 4 + TargetBase, 0, (ry1 - ry0) * TargetWidth * 4) else - for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end - end -end - -@native -function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number) - for y = 0, rh - 1 do - buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4) + for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4 + TargetBase, 0, rw * 4) end end end @@ -46652,13 +46814,12 @@ local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, v end M.DrawPrim = DrawPrim --- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback) -local Scratch = buffer.create(TILE * TILE * 4) +-- Packed tile jobs -> one exact-size buffer per rect (rasterized straight into it), in job order (worker + main-thread +-- fallback) @native function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } - local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect + local ClearRect, SetTarget = M.ClearRect, M.SetTarget local REC_A, REC_B, REC_C, REC_D = M.REC_A, M.REC_B, M.REC_C, M.REC_D - M.SetTarget(Scratch, TILE) local out, no = {}, 0 local o = 0 while o < tlen do @@ -46670,6 +46831,9 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } for r = 0, nr - 1 do local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4), readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12) + local rw, rh = rx1 - rx0, ry1 - ry0 + local sub = buffer.create(rw * rh * 4) + SetTarget(sub, rw, rx0, ry0) ClearRect(rx0, ry0, rx1, ry1) for k = 0, count - 1 do local q = readi32(T, po + k * 4) @@ -46683,9 +46847,6 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } if tid >= 0 then t = textures[tid] end DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1) end - local rw, rh = rx1 - rx0, ry1 - ry0 - local sub = buffer.create(rw * rh * 4) - CopySubRect(sub, rx0, ry0, rw, rh) no += 1 out[no] = sub end @@ -46693,6 +46854,48 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } return out end +-- An Actor's texture copies (worker.luau; parallel.lua's Sync mode emulates it): drop the destroyed ids, apply the +-- updates parallel.lua's Flush sent. { id, buf, w, h, fill }: whole texture, rows past buf are all fill; +-- { id, false, w, h, offset, patch }: rows; { id, false, w, h, rects, patch }: x, y, w, h quadruples, rows packed. +function M.ApplyTextures(textures, updates, dropped) + for _, id in dropped or {} do + textures[id] = nil + end + for _, u in updates do + if u[2] then + local b, w, h, fill = u[2], u[3], u[4], u[5] + local n, total = buffer.len(b), w * h * 4 + if n < total then + local full = buffer.create(total) + buffer.copy(full, 0, b) + if fill ~= 0 then + buffer.writeu32(full, n, fill) + local k = 4 + while k < total - n do + local c = math.min(k, total - n - k) + buffer.copy(full, n + k, full, n, c) + k += c + end + end + b = full + end + textures[u[1]] = { Buffer = b, Width = w, Height = h } + elseif type(u[5]) == "table" then + local t, rects, patch = textures[u[1]], u[5], u[6] + local dst, w, o = t.Buffer, t.Width, 0 + for i = 1, #rects, 4 do + local x, y, rw, rh = rects[i], rects[i + 1], rects[i + 2], rects[i + 3] + for yy = y, y + rh - 1 do + buffer.copy(dst, (yy * w + x) * 4, patch, o, rw * 4) + o += rw * 4 + end + end + else + buffer.copy(textures[u[1]].Buffer, u[5], u[6]) + end + end +end + Raster = M end do @@ -46705,7 +46908,8 @@ local TILE = Raster.TILE local M = {} --- One table, not locals: shared by every context and module. FreeTile is set by layers.lua (Evict needs it). +-- One table, not locals: shared by every context and module. FreeTile is set by layers.lua (Evict needs it), +-- TextureDropped(id, record) by parallel.lua (Actors free their copies). local EditableImages = { Cap = 64 * 1024 * 1024, Bytes = 0, Count = 0, ImageBytes = setmetatable({}, { __mode = "k" }), Pool = {}, PoolMax = 16, @@ -46737,33 +46941,45 @@ function M.GetBackendData() return ImGui.GetCurrentContext() and ImGui.GetIO().BackendPlatformUserData or nil end +-- n pixels from the byte table src (1-based index s) to dst (byte offset d). Typed + unrolled by 4: the native code +-- skips the generic table/buffer checks (~40% faster than the plain loop). @native -local function CopyTexturePixels(tex, dst, x, y, w, h, dst_zero) - local bpp, tex_w = tex.BytesPerPixel, tex.Width - if x == 0 and w == tex_w and bpp == 4 then -- whole rows: one flat loop; dst_zero: skip writing zero pixels +local function CopyRGBA(src: { number }, s: number, dst: buffer, d: number, n: number) + for _ = 1, n // 4 do + writeu32(dst, d, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216) + writeu32(dst, d + 4, src[s + 4] + src[s + 5] * 256 + src[s + 6] * 65536 + src[s + 7] * 16777216) + writeu32(dst, d + 8, src[s + 8] + src[s + 9] * 256 + src[s + 10] * 65536 + src[s + 11] * 16777216) + writeu32(dst, d + 12, src[s + 12] + src[s + 13] * 256 + src[s + 14] * 65536 + src[s + 15] * 16777216) + s += 16 + d += 16 + end + for _ = 1, n % 4 do + writeu32(dst, d, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216) + s += 4 + d += 4 + end +end + +@native +local function CopyAlpha8(src: { number }, s: number, dst: buffer, d: number, n: number) -- white with alpha + for _ = 1, n do + writeu32(dst, d, 16777215 + src[s] * 16777216) + s += 1 + d += 4 + end +end + +local function CopyTexturePixels(tex, dst, x, y, w, h) + local tex_w = tex.Width + local copy = tex.BytesPerPixel == 4 and CopyRGBA or CopyAlpha8 + if x == 0 and w == tex_w then -- whole rows: one flat run local src, s = tex:GetPixelsAt(0, y) - local d = y * tex_w * 4 - for _ = 1, w * h do - local v = src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216 - if v ~= 0 or not dst_zero then writeu32(dst, d, v) end - s += 4 - d += 4 - end + copy(src, s, dst, y * tex_w * 4, w * h) return end for row = 0, h - 1 do - local src, src_base = tex:GetPixelsAt(x, y + row) - local dst_off = ((y + row) * tex_w + x) * 4 - if bpp == 4 then - for i = 0, w - 1 do - local s = src_base + i * 4 - writeu32(dst, dst_off + i * 4, src[s] + src[s + 1] * 256 + src[s + 2] * 65536 + src[s + 3] * 16777216) - end - else -- Alpha8: white with alpha - for i = 0, w - 1 do - writeu32(dst, dst_off + i * 4, 16777215 + src[src_base + i] * 16777216) - end - end + local src, s = tex:GetPixelsAt(x, y + row) + copy(src, s, dst, ((y + row) * tex_w + x) * 4, w) end end @@ -46794,9 +47010,9 @@ local function CreateTextureRecord(tex) n += c end end - CopyTexturePixels(tex, b, 0, 0, cw, ch, tex.BytesPerPixel == 4) + CopyTexturePixels(tex, b, 0, 0, cw, ch) else - CopyTexturePixels(tex, b, 0, 0, w, h, true) + CopyTexturePixels(tex, b, 0, 0, w, h) end -- rows FillRow.. hold only Fill (what zero converts to): parallel.lua sends Actors the rows above it local t = { Buffer = b, Width = w, Height = h, FillRow = ch, Fill = tex.BytesPerPixel ~= 4 and 16777215 or 0 } @@ -46817,22 +47033,28 @@ function M.UpdateTexture(tex) return end local y0, y1 = math.huge, -1 + local rects, n = {}, 0 for _, r in tex.Updates:iter() do CopyTexturePixels(tex, t.Buffer, r.x, r.y, r.w, r.h) if r.y < y0 then y0 = r.y end if r.y + r.h > y1 then y1 = r.y + r.h end + rects[n + 1], rects[n + 2], rects[n + 3], rects[n + 4] = r.x, r.y, r.w, r.h + n += 4 end - -- parallel workers hold copies, patched when this changes: Log[V] = changed rows (only the last 16 kept) + -- parallel workers hold copies, patched when this changes: Log[V] = changed rows + the rects (x, y, w, h + -- quadruples) (only the last 16 kept) if t.FillRow and y1 > t.FillRow then t.FillRow = y1 end local v = (t.V or 0) + 1 t.V = v t.Log = t.Log or {} - t.Log[v] = y1 > y0 and { y0, y1 } or { 0, 0 } + t.Log[v] = y1 > y0 and { y0, y1, rects } or { 0, 0 } t.Log[v - 16] = nil tex:SetStatus(0 --[[ImTextureStatus.OK]]) elseif tex.Status == 4 --[[ImTextureStatus.WantDestroy]] then if tex.BackendUserData then - Records[tex.BackendUserData] = nil + local id = tex.BackendUserData + if EditableImages.TextureDropped then EditableImages.TextureDropped(id, Records[id]) end + Records[id] = nil tex.BackendUserData = nil end tex:SetTexID((-1) --[[ImTextureID_Invalid]]) @@ -46848,7 +47070,9 @@ function ImGui_ImplRoblox_CreateTexture(pixels, w, h) end function ImGui_ImplRoblox_DestroyTexture(tex_ref) - Records[tex_ref._TexID] = nil + local id = tex_ref._TexID + if EditableImages.TextureDropped then EditableImages.TextureDropped(id, Records[id]) end + Records[id] = nil end -- Every EditableImage goes through Create/Destroy, counted against Cap. Over the cap (or CreateEditableImage failing): @@ -47032,7 +47256,7 @@ function M.GetTile(BackendData, layer, key, tx, ty) label.Position = UDim2.fromOffset(tx * TILE / scale, ty * TILE / scale) if not old or old.Active ~= BackendData.TilesActive then label.Active = BackendData.TilesActive end if not old or old.Parent ~= layer.Frame then label.Parent = layer.Frame end - -- Content*: content bounds; Valid*: where Buffer == image pixels. A recycled tile keeps both (they still describe + -- Content*: content bounds; Valid*: where the image pixels are current. A recycled tile keeps both (they still describe -- its image): its first draw is a full one (DrawnCount -1) that only clears old + new content bounds. if old then tile = old @@ -47041,7 +47265,7 @@ function M.GetTile(BackendData, layer, key, tx, ty) tile.Scale, tile.Active, tile.Parent = scale, BackendData.TilesActive, layer.Frame else tile = { - Image = img, Label = label, Buffer = buffer.create(TILE * TILE * 4), + Image = img, Label = label, Hash1 = -1, Hash2 = -1, Visible = false, Used = BackendData.FrameNo, ContentX0 = TILE, ContentY0 = TILE, ContentX1 = 0, ContentY1 = 0, ValidX0 = 0, ValidY0 = 0, ValidX1 = TILE, ValidY1 = TILE, @@ -47137,6 +47361,37 @@ function M.Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) set.SnapOK = true end +-- The snapshot of a list CompareDrawList found moved by (dx, dy): only its vertices, clip rects, content clip, +-- scroll origin, primitive bounds and extents move (counts, indices, kinds are equal; Cmd* describe another list now) +@native +function M.ShiftSnapshot(set, draw_list, dx, dy) + buffer.copy(set.SnapVtx, 0, draw_list.VtxBuffer.Buf, 0, set.SnapVtxBytes) + local sc, o = set.SnapCmds, 0 + for _, pcmd in draw_list.CmdBuffer:iter() do + local c = pcmd.ClipRect + writef64(sc, o, c.x) + writef64(sc, o + 8, c.y) + writef64(sc, o + 16, c.z) + writef64(sc, o + 24, c.w) + if buffer.readu8(sc, o + 53) ~= 0 then + buffer.writei32(sc, o + 54, buffer.readi32(sc, o + 54) + dx) + buffer.writei32(sc, o + 58, buffer.readi32(sc, o + 58) + dy) + buffer.writei32(sc, o + 62, buffer.readi32(sc, o + 62) + dx) + buffer.writei32(sc, o + 66, buffer.readi32(sc, o + 66) + dy) + end + o += CMD_STRIDE + end + if set.SnapHasContent then + set.SnapContentX0, set.SnapContentY0, set.SnapContentX1, set.SnapContentY1 = draw_list._ContentClipX0, + draw_list._ContentClipY0, draw_list._ContentClipX1, draw_list._ContentClipY1 + set.SnapScrollX, set.SnapScrollY = draw_list._ScrollOriginX, draw_list._ScrollOriginY + end + set.SnapExtentX0 += dx + set.SnapExtentY0 += dy + set.SnapExtentX1 += dx + set.SnapExtentY1 += dy +end + -- a + d == b exactly, with no rounding in a + d (so every later "x - origin" gives the same result as before the move) @native local function ShiftedExact(a, d, b) @@ -47162,8 +47417,18 @@ function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) local dx, dy = readf64(vb, 0) - readf64(sv, 0), readf64(vb, 8) - readf64(sv, 8) if dx ~= dx or dy ~= dy then return 0 end if dx == 0 and dy == 0 then - -- u32 loop, not readstring ==: that allocated 2 vertex-buffer strings per list per frame (GC spikes) - for o = 0, nv - 4, 4 do if readu32(vb, o) ~= readu32(sv, o) then return 0 end end + -- per vertex: x y u v as f64s + col, not readstring == (that allocated 2 vertex-buffer strings per list per + -- frame: GC spikes) or 9 u32s (3x slower). Equal f64s have equal bits except +-0: their sign words decide. + for v = 0, nv - 36 --[[VTX_STRIDE]], 36 --[[VTX_STRIDE]] do + local x, y, u, w = readf64(vb, v), readf64(vb, v + 8), readf64(vb, v + 16), readf64(vb, v + 24) + if x ~= readf64(sv, v) or y ~= readf64(sv, v + 8) or u ~= readf64(sv, v + 16) + or w ~= readf64(sv, v + 24) or readu32(vb, v + 32) ~= readu32(sv, v + 32) then + return 0 + end + if x == 0 or y == 0 or u == 0 or w == 0 then + for p = v + 4, v + 28, 8 do if readu32(vb, p) ~= readu32(sv, p) then return 0 end end + end + end else if dx ~= floor(dx) or dy ~= floor(dy) or ox ~= 0 or oy ~= 0 or not set.SnapLimitFree then return 0 end -- everything must stay as far from the clip limits as before (nothing newly clamped) @@ -47173,7 +47438,13 @@ function M.CompareDrawList(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) end end local idx, si = draw_list.IdxBuffer.Data, set.SnapIdx - for i = 1, ni do if idx[i] ~= si[i] then return 0 end end + local n4 = ni - ni % 4 + for i = 1, n4, 4 do + if idx[i] ~= si[i] or idx[i + 1] ~= si[i + 1] or idx[i + 2] ~= si[i + 2] or idx[i + 3] ~= si[i + 3] then + return 0 + end + end + for i = n4 + 1, ni do if idx[i] ~= si[i] then return 0 end end local sc, o = set.SnapCmds, 0 local ccx0, ccy0, ccx1, ccy1 = draw_list._ContentClipX0, draw_list._ContentClipY0, draw_list._ContentClipX1, draw_list._ContentClipY1 @@ -47339,14 +47610,14 @@ do local floor, ceil, min, max = math.floor, math.ceil, math.min, math.max local readu32, readf64 = buffer.readu32, buffer.readf64 -local SetTarget, ClearRect, DrawPrim, CopySubRect = Raster.SetTarget, Raster.ClearRect, Raster.DrawPrim, - Raster.CopySubRect +local SetTarget, ClearRect, DrawPrim = Raster.SetTarget, Raster.ClearRect, Raster.DrawPrim local TILE = Raster.TILE local TILE_SIZE = Vector2.new(TILE, TILE) local EditableImages, PB, PE, GetBackendData, UpdateTexture = Textures.EditableImages, Textures.PB, Textures.PE, Textures.GetBackendData, Textures.UpdateTexture local GetLayer, HideLayer, GetTile, DestroyLayerSet, Snapshot, CompareDrawList, ShiftLayer = Layers.GetLayer, Layers.HideLayer, Layers.GetTile, Layers.DestroyLayerSet, Layers.Snapshot, Layers.CompareDrawList, Layers.ShiftLayer +local ShiftSnapshot = Layers.ShiftSnapshot local CmdUnclipped, CmdKind, CmdBoundsX0, CmdBoundsY0, CmdBoundsX1, CmdBoundsY1 = Layers.CmdUnclipped, Layers.CmdKind, Layers.CmdBoundsX0, Layers.CmdBoundsY0, Layers.CmdBoundsX1, Layers.CmdBoundsY1 local CLIP_PAD = Layers.CLIP_PAD @@ -47364,8 +47635,12 @@ local MAX_DEFER_FRAMES = 8 -- a changed tile is redrawn at the latest this many local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient = {}, {}, {}, {}, {}, {} local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = {}, {}, {}, {} local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = {}, {}, {}, {} -local PrimTexId, PrimVtxBuffer, PrimKind = {}, {}, {} +local PrimTexId, PrimVtxBuffer = {}, {} +-- flat rect (one colour, one uv or untextured): HashTiles hashes its clipped rect per tile +local PrimFlat = {} +-- the current draw list's primitives per layer kind (filled by CollectPrims): count, and min bounds for kinds 1 and 3 local LayerPrims1, LayerPrims2, LayerPrims3 = {}, {}, {} +local Kind1Count, Kind2Count, Kind3Count, Kind1X, Kind1Y, Kind3X, Kind3Y = 0, 0, 0, 0, 0, 0, 0 M.PrimA, M.PrimB, M.PrimC, M.PrimD = PrimA, PrimB, PrimC, PrimD M.PrimTexture, M.PrimGradient = PrimTexture, PrimGradient M.PrimClipX0, M.PrimClipY0, M.PrimClipX1, M.PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 @@ -47400,16 +47675,9 @@ function EditableImages.AddRect(n: number, a: number, b: number, c: number, d: n return n end -@native -local function HashVertex(h1: number, h2: number, vbuf: buffer, v: number, ox: number, oy: number) - local x, y = readf64(vbuf, v) - ox, readf64(vbuf, v + 8) - oy - local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24) - local c = readu32(vbuf, v + 32) - -- one % per hash: h < 2^31, so h * 48271 + the terms (|x|, |y| < 2^15, uv < 2^14, c < 2^32) stays below 2^53 - h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1 - h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2 - return h1, h2 -end +-- HashTiles scratch, per touched tile (slot = its index in layer.Touched): tile key -> slot, its list, count, hashes +local KeySlot, SlotCount, SlotHash1, SlotHash2 = {}, {}, {}, {} +local SlotList, SlotListHash1, SlotListHash2, SlotListFlat = {}, {}, {}, {} @native local function HashTiles(layer, plist, np, lx0, ly0, ox, oy) @@ -47418,9 +47686,16 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy) local TileListHash1, TileListHash2, TileListFlat = layer.TileListHash1, layer.TileListHash2, layer.TileListFlat for k = 1, layer.TouchedCount do TileCounts[Touched[k]] = 0 end local TouchedCount = 0 - local CurKey, CurCount, CurHash1, CurHash2, CurList, CurListHash1, CurListHash2, CurListFlat = - nil, 0, 0, 0, nil, nil, nil, nil + local CurKey, CurSlot, CurCount, CurHash1, CurHash2, CurList, CurListHash1, CurListHash2, CurListFlat = + -1, 0, 0, 0, 0, nil, nil, nil, nil local TileXs, TileYs = layer.TileX, layer.TileY + -- upvalues as locals: cheaper in the hot loop + local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 + local PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat = + PrimA, PrimB, PrimC, PrimD, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat + local KeySlot, SlotCount, SlotHash1, SlotHash2 = KeySlot, SlotCount, SlotHash1, SlotHash2 + local SlotList, SlotListHash1, SlotListHash2, SlotListFlat = SlotList, SlotListHash1, SlotListHash2, SlotListFlat + local TILE = TILE for pi = 1, np do local p = plist[pi] local tex_id = PrimTexId[p] @@ -47430,92 +47705,113 @@ local function HashTiles(layer, plist, np, lx0, ly0, ox, oy) local vbuf = PrimVtxBuffer[p] local va, vd = PrimA[p], PrimD[p] -- flat rect: hash its clipped rect per tile, so resizing only changes the tiles its edges cross - local FlatRect, RectColor, RectUV = false, 0, 0 - if vd and not PrimGradient[p] then - local u0, v0 = readf64(vbuf, va + 16), readf64(vbuf, va + 24) - local vc = PrimC[p] - if not PrimTexture[p] or (u0 == readf64(vbuf, vc + 16) and v0 == readf64(vbuf, vc + 24)) then - FlatRect, RectColor, RectUV = true, readu32(vbuf, va + 32), u0 * 8192 + v0 - end + local FlatRect, RectColor, RectUV = PrimFlat[p], 0, 0 + if FlatRect then + RectColor, RectUV = readu32(vbuf, va + 32), readf64(vbuf, va + 16) * 8192 + readf64(vbuf, va + 24) end local h1, h2 = 0, 0 local FlatSig = -1 - if FlatRect then FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1 end - if not FlatRect then + if FlatRect then + FlatSig = ((RectColor * 8191 + RectUV * 4096) % P1 * 64 + tex_id) % P1 + else h1 = ((cx0 * 8191 + cy0) * 8191 + cx1) % P1 h2 = ((cy1 * 8191 + cx1) * 8191 + cy0 + tex_id) % P2 local vax, vay = lx0 + ox, ly0 + oy + -- vertices: triangle a, b, c; axis aligned quad a, c (CollectPrims checked that b, d follow from them + kind); + -- line quad (any shape) a, c, b, d. The kind is mixed in after the second vertex. + local gk, v2, v3, nv = PrimGradient[p], PrimC[p], PrimB[p], 3 if vd then - -- axis aligned quad: CollectPrims checked that TR/BL follow from TL/BR (+ kind) - h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay) - local gk = PrimGradient[p] - if gk then + nv = gk == 3 and 4 or 2 + else + v2, v3 = v3, v2 + end + local v = va + for k = 1, nv do + if k == 2 then v = v2 elseif k == 3 then v = v3 elseif k == 4 then v = vd end + -- inlined (a call per vertex costs more than the hash): one % per hash, h < 2^31, so h * 48271 + the + -- terms (|x|, |y| < 2^15, uv < 2^14, c < 2^32) stays below 2^53 + local x, y = readf64(vbuf, v) - vax, readf64(vbuf, v + 8) - vay + local uv = readf64(vbuf, v + 16) * 8192 + readf64(vbuf, v + 24) + local c = readu32(vbuf, v + 32) + h1 = (h1 * 48271 + (x * 4096 + y) * 31 + uv * 4096 + c) % P1 + h2 = (h2 * 16807 + (y * 4093 + x) * 17 + uv * 65521 + c * 3) % P2 + if k == 2 and gk then h1 = (h1 * 48271 + gk) % P1 h2 = (h2 * 16807 + gk * 3) % P2 end - if gk == 3 then -- line quad: any shape - h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, vd, vax, vay) - end - else - h1, h2 = HashVertex(h1, h2, vbuf, va, vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, PrimB[p], vax, vay) - h1, h2 = HashVertex(h1, h2, vbuf, PrimC[p], vax, vay) end end - for ty = floor((PrimBoundsY0[p] - ly0) / TILE), floor((PrimBoundsY1[p] - 1 - ly0) / TILE) do - for tx = floor((PrimBoundsX0[p] - lx0) / TILE), floor((PrimBoundsX1[p] - 1 - lx0) / TILE) do - if FlatRect then - local tx0, ty0 = tx * TILE, ty * TILE - local ix0, iy0 = max(cx0 - tx0, 0), max(cy0 - ty0, 0) - local ix1, iy1 = min(cx1 - tx0, TILE), min(cy1 - ty0, TILE) - local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1 - h1 = ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1 - h2 = ((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2 + -- the tiles it touches, row by row (one loop, no nested for: most primitives touch one tile; never empty) + local tx0, tx1, ty1 = cx0 // TILE, (cx1 - 1) // TILE, (cy1 - 1) // TILE + local tx, ty = tx0, cy0 // TILE + while true do + if FlatRect then + local px0, py0 = tx * TILE, ty * TILE + local ix0, iy0 = max(cx0 - px0, 0), max(cy0 - py0, 0) + local ix1, iy1 = min(cx1 - px0, TILE), min(cy1 - py0, TILE) + local r = ((ix0 * 131 + iy0) * 131 + ix1) * 131 + iy1 + h1 = ((r * 48271 + RectColor) % P1 * 48271 + RectUV * 4096 + 7) % P1 + h2 = ((r * 16807 + RectColor + tex_id) % P2 * 16807 + RectUV * 65521 + 11) % P2 + end + -- unique for |tx|, |ty| < 32768 (content tiles go negative) + local key = (ty + 32768) * 65536 + tx + 32768 + if key ~= CurKey then + -- consecutive primitives often alternate between tiles: the tile's state is in slot arrays + if CurSlot > 0 then + SlotCount[CurSlot], SlotHash1[CurSlot], SlotHash2[CurSlot] = CurCount, CurHash1, CurHash2 end - -- unique for |tx|, |ty| < 32768 (content tiles go negative) - local key = (ty + 32768) * 65536 + tx + 32768 - if key ~= CurKey then - if CurKey then - TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 - end - CurKey = key - CurCount = TileCounts[key] - if not CurCount or CurCount == 0 then - CurCount, CurHash1, CurHash2 = 0, 0, 0 - if not TileLists[key] then - local ListPool = EditableImages.ListPool - local m = #ListPool - if m >= 4 then - TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] = - ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] - ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] = nil, nil, nil, nil - else - TileLists[key] = {} - TileListHash1[key] = {} - TileListHash2[key] = {} - TileListFlat[key] = {} - end + CurKey = key + local slot = KeySlot[key] + if slot then + CurCount, CurHash1, CurHash2 = SlotCount[slot], SlotHash1[slot], SlotHash2[slot] + else + if not TileLists[key] then + local ListPool = EditableImages.ListPool + local m = #ListPool + if m >= 4 then + TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] = + ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] + ListPool[m - 3], ListPool[m - 2], ListPool[m - 1], ListPool[m] = nil, nil, nil, nil + else + TileLists[key] = {} + TileListHash1[key] = {} + TileListHash2[key] = {} + TileListFlat[key] = {} end - TouchedCount = TouchedCount + 1 - Touched[TouchedCount] = key - TileXs[key], TileYs[key] = tx, ty - else - CurHash1, CurHash2 = TileHash1[key], TileHash2[key] end - CurList, CurListHash1, CurListHash2, CurListFlat = + TouchedCount = TouchedCount + 1 + slot = TouchedCount + KeySlot[key] = slot + Touched[slot] = key + TileXs[key], TileYs[key] = tx, ty + SlotList[slot], SlotListHash1[slot], SlotListHash2[slot], SlotListFlat[slot] = TileLists[key], TileListHash1[key], TileListHash2[key], TileListFlat[key] + CurCount, CurHash1, CurHash2 = 0, 0, 0 end - CurCount += 1 - CurList[CurCount], CurListHash1[CurCount], CurListHash2[CurCount], CurListFlat[CurCount] = - p, h1, h2, FlatSig - CurHash1 = (CurHash1 * 48271 + h1) % P1 - CurHash2 = (CurHash2 * 16807 + h2 + CurCount) % P2 + CurSlot = slot + CurList, CurListHash1, CurListHash2, CurListFlat = + SlotList[slot], SlotListHash1[slot], SlotListHash2[slot], SlotListFlat[slot] + end + CurCount += 1 + CurList[CurCount], CurListHash1[CurCount], CurListHash2[CurCount], CurListFlat[CurCount] = + p, h1, h2, FlatSig + CurHash1 = (CurHash1 * 48271 + h1) % P1 + CurHash2 = (CurHash2 * 16807 + h2 + CurCount) % P2 + if tx < tx1 then + tx += 1 + elseif ty < ty1 then + tx, ty = tx0, ty + 1 + else + break end end end - if CurKey then TileCounts[CurKey], TileHash1[CurKey], TileHash2[CurKey] = CurCount, CurHash1, CurHash2 end + if CurSlot > 0 then SlotCount[CurSlot], SlotHash1[CurSlot], SlotHash2[CurSlot] = CurCount, CurHash1, CurHash2 end + for slot = 1, TouchedCount do + local key = Touched[slot] + TileCounts[key], TileHash1[key], TileHash2[key] = SlotCount[slot], SlotHash1[slot], SlotHash2[slot] + KeySlot[key] = nil + end layer.TouchedCount = TouchedCount return TouchedCount end @@ -47547,6 +47843,7 @@ local function PlaceLayer(layer, scale, lx0, ly0, z, clip_x0, clip_y0, clip_x1, end end +@native local function SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, clip_y0, clip_x1, clip_y1) local TileCounts, Touched = layer.TileCounts, layer.Touched -- content layer: only tiles inside its clip frame are kept, so scrolling holds the visible tiles + a few spares @@ -47580,6 +47877,9 @@ local function SweepTiles(BackendData, layer, TouchedCount, lx0, ly0, clip_x0, c end end +-- the new primitive bounds in the tile (clipped to it); swapped with the tile's Drawn* after a redraw +local NewX0, NewY0, NewX1, NewY1 = {}, {}, {}, {} + @native local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, vy0, vx1, vy1) local qx0, qy0, qx1, qy1 = tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 @@ -47587,17 +47887,20 @@ local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, local DrawnHash1, DrawnHash2, DrawnX0, DrawnY0, DrawnX1, DrawnY1, DrawnCount = tile.DrawnHash1, tile.DrawnHash2, tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1, tile.DrawnCount + local NX0, NY0, NX1, NY1 = NewX0, NewY0, NewX1, NewY1 + local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 + -- content bounds = the union of the clipped primitive bounds (clipping to the tile commutes with min / max) local nx0, ny0, nx1, ny1 = TILE, TILE, 0, 0 for k = 1, count do local p = list[k] - local a, b = PrimBoundsX0[p] - x0, PrimBoundsY0[p] - y0 - local c, d = PrimBoundsX1[p] - x0, PrimBoundsY1[p] - y0 + local a, b = max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0) + local c, d = min(PrimBoundsX1[p] - x0, TILE), min(PrimBoundsY1[p] - y0, TILE) + NX0[k], NY0[k], NX1[k], NY1[k] = a, b, c, d if a < nx0 then nx0 = a end if b < ny0 then ny0 = b end if c > nx1 then nx1 = c end if d > ny1 then ny1 = d end end - nx0, ny0, nx1, ny1 = max(nx0, 0), max(ny0, 0), min(nx1, TILE), min(ny1, TILE) local DX0, DY0, DX1, DY1, AddRect = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1, EditableImages.AddRect local DirtyCount = 0 @@ -47618,9 +47921,7 @@ local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, local of, lf = tile.DrawnFlat, layer.TileListFlat[key] local paired = DrawnCount - j - i == count - j - i for k = i, count - j do - local p = list[k] - local a, b, c, d = max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), - min(PrimBoundsX1[p] - x0, TILE), min(PrimBoundsY1[p] - y0, TILE) + local a, b, c, d = NX0[k], NY0[k], NX1[k], NY1[k] local oa, ob, oc, od = DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] if paired and lf[k] >= 0 and lf[k] == of[k] then -- same flat rect, new bounds: only the strips between the old and new edges can differ @@ -47673,14 +47974,12 @@ local function DirtyRects(tile, layer, key, count, x0, y0, force, exposed, vx0, end tile.ValidX0, tile.ValidY0, tile.ValidX1, tile.ValidY1 = qx0, qy0, qx1, qy1 tile.ContentX0, tile.ContentY0, tile.ContentX1, tile.ContentY1 = nx0, ny0, nx1, ny1 - local DrawnFlat, ListFlat = tile.DrawnFlat, layer.TileListFlat[key] - for k = 1, count do - local p = list[k] - DrawnHash1[k], DrawnHash2[k], DrawnFlat[k] = ListHash1[k], ListHash2[k], ListFlat[k] - DrawnX0[k], DrawnY0[k], DrawnX1[k], DrawnY1[k] = - max(PrimBoundsX0[p] - x0, 0), max(PrimBoundsY0[p] - y0, 0), min(PrimBoundsX1[p] - x0, TILE), - min(PrimBoundsY1[p] - y0, TILE) - end + -- the drawn state is now the tile's list: swap tables instead of copying (HashTiles rewrites the layer's lists) + tile.DrawnHash1, layer.TileListHash1[key] = ListHash1, DrawnHash1 + tile.DrawnHash2, layer.TileListHash2[key] = ListHash2, DrawnHash2 + tile.DrawnFlat, layer.TileListFlat[key] = layer.TileListFlat[key], tile.DrawnFlat + tile.DrawnX0, tile.DrawnY0, tile.DrawnX1, tile.DrawnY1 = NX0, NY0, NX1, NY1 + NewX0, NewY0, NewX1, NewY1 = DrawnX0, DrawnY0, DrawnX1, DrawnY1 tile.DrawnCount = count return RectCount end @@ -47702,14 +48001,12 @@ local function RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1) end end --- WritePixelsBuffer needs the exact size: partial upload buffers are reused by size +-- WritePixelsBuffer needs the exact size: a rect is rasterized straight into an upload buffer of its size (reused by +-- size; the whole tile: TileBuffer). One small buffer stays in cache, unlike a 64 KB buffer per tile. +local TileBuffer = buffer.create(TILE * TILE * 4) local SubBuffers, SubBufferCount = {}, 0 -local function UploadRect(img, buf, rx0, ry0, rx1, ry1) - local rw, rh = rx1 - rx0, ry1 - ry0 - if rw == TILE and rh == TILE then - img:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf) - return - end +local function RectBuffer(rw, rh) + if rw == TILE and rh == TILE then return TileBuffer end local sk = rw * 1024 + rh local sub = SubBuffers[sk] if not sub then @@ -47721,8 +48018,7 @@ local function UploadRect(img, buf, rx0, ry0, rx1, ry1) SubBuffers[sk] = sub SubBufferCount += 1 end - CopySubRect(sub, rx0, ry0, rw, rh) - img:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), sub) + return sub end local function RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, force, exposed, vx0, vy0, vx1, vy1) @@ -47740,23 +48036,30 @@ local function RedrawTile(BackendData, layer, key, tile, count, x0, y0, ox, oy, Parallel.Tile(tile.Image, list, count, x0, y0, tox, toy, RectCount) return end - SetTarget(tile.Buffer, TILE) local DX0, DY0, DX1, DY1 = EditableImages.DX0, EditableImages.DY0, EditableImages.DX1, EditableImages.DY1 for r = 1, RectCount do local rx0, ry0, rx1, ry1 = DX0[r], DY0[r], DX1[r], DY1[r] + local rw, rh = rx1 - rx0, ry1 - ry0 + local buf = RectBuffer(rw, rh) + SetTarget(buf, rw, rx0, ry0) RasterRect(list, count, x0, y0, tox, toy, rx0, ry0, rx1, ry1) PB("ImGui upload") local t_up = Timing and os.clock() if Timing then - Timing.PixelsRasterized += (rx1 - rx0) * (ry1 - ry0) + Timing.PixelsRasterized += rw * rh Timing.Uploads += 1 end - UploadRect(tile.Image, tile.Buffer, rx0, ry0, rx1, ry1) + if buf == TileBuffer then + tile.Image:WritePixelsBuffer(Vector2.zero, TILE_SIZE, buf) + else + tile.Image:WritePixelsBuffer(Vector2.new(rx0, ry0), Vector2.new(rw, rh), buf) + end if Timing then Timing.Upload += os.clock() - t_up end PE() end end +@native local function DrawLayer(BackendData, layer, plist, np, lx0, ly0, ox, oy, force, z, clip_x0, clip_y0, clip_x1, clip_y1) PB("ImGui tile hash") if EditableImages.StageTiming then EditableImages.BeginStage() end @@ -47866,18 +48169,12 @@ local function ReuseDrawList(BackendData, set, draw_list, same, sdx, sdy, z, ox, end end end - if same == 2 then - Snapshot(set, draw_list, ox, oy, ScreenWidth, ScreenHeight) - set.SnapExtentX0 += sdx - set.SnapExtentY0 += sdy - set.SnapExtentX1 += sdx - set.SnapExtentY1 += sdy - end + if same == 2 then ShiftSnapshot(set, draw_list, sdx, sdy) end set.LastUsed = BackendData.FrameNo return PlaceOverlays(BackendData, draw_list, z, ox, oy) end --- Collects primitives into Prim* (from n + 1) and commands into Cmd*; returns n, LimitFree and the extents +-- Collects primitives into Prim* (from n + 1), LayerPrims* and commands into Cmd*; returns n, LimitFree and the extents @native local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1) local vbuf, idx = draw_list.VtxBuffer.Buf, draw_list.IdxBuffer.Data @@ -47891,7 +48188,15 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, if a < LimitX0 or b < LimitY0 or c > LimitX1 or d > LimitY1 then LimitFree = false end ex0, ey0, ex1, ey1 = min(ex0, a), min(ey0, b), max(ex1, c), max(ey1, d) end + -- upvalues as locals: cheaper in the hot loop + local PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat = + PrimA, PrimB, PrimC, PrimD, PrimTexture, PrimGradient, PrimTexId, PrimVtxBuffer, PrimFlat + local PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 = PrimClipX0, PrimClipY0, PrimClipX1, PrimClipY1 + local PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 = PrimBoundsX0, PrimBoundsY0, PrimBoundsX1, PrimBoundsY1 + local LayerPrims1, LayerPrims2, LayerPrims3 = LayerPrims1, LayerPrims2, LayerPrims3 local ci = 0 + local c1, c2, c3 = 0, 0, 0 + local k1x, k1y, k3x, k3y = math.huge, math.huge, math.huge, math.huge for _, pcmd in draw_list.CmdBuffer:iter() do ci += 1 CmdUnclipped[ci], CmdKind[ci] = false, 0 @@ -47937,33 +48242,23 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, local pbx, pby = readf64(vbuf, vb), readf64(vbuf, vb + 8) local pcx, pcy = readf64(vbuf, vc), readf64(vbuf, vc + 8) local bx0, by0, bx1, by1 + local flat = false if i + 5 <= last and idx[i + 3] == ia and idx[i + 4] == ic then local d = (vo + idx[i + 5] - 1) * 36 --[[VTX_STRIDE]] local pdx, pdy = readf64(vbuf, d), readf64(vbuf, d + 8) local col = readu32(vbuf, va + 32) - if t and readu32(vbuf, vb + 32) == col and readu32(vbuf, vc + 32) == col - and readu32(vbuf, d + 32) == col then - -- textured line quad (ImPlot PrimLine): uv a = b, c = d, u a ~= u c (else a textured rect may match) - local tax, tay, tcx, tcy = readf64(vbuf, va + 16), readf64(vbuf, va + 24), - readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) - if tax ~= tcx and readf64(vbuf, vb + 16) == tax - and readf64(vbuf, vb + 24) == tay and readf64(vbuf, d + 16) == tcx - and readf64(vbuf, d + 24) == tcy then - vd, gk = d, 3 - bx0, by0 = floor(min(pax, pbx, pcx, pdx) - ox), floor(min(pay, pby, pcy, pdy) - oy) - bx1 = ceil(max(pax, pbx, pcx, pdx) - ox) + 1 - by1 = ceil(max(pay, pby, pcy, pdy) - oy) + 1 - end - end - if not vd and pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then - local col, colb, colc, cold = readu32(vbuf, va + 32), readu32(vbuf, vb + 32), - readu32(vbuf, vc + 32), readu32(vbuf, d + 32) - local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24) + local colb, colc, cold = readu32(vbuf, vb + 32), readu32(vbuf, vc + 32), readu32(vbuf, d + 32) + local tax, tay = readf64(vbuf, va + 16), readf64(vbuf, va + 24) + local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) + -- axis aligned rect, then textured line quad: never both (a rect with one colour has u b = u c, + -- a line quad u a = u b ~= u c), so the order doesn't change the result + if pay == pby and pbx == pcx and pcy == pdy and pdx == pax and pax < pbx and pay < pdy then local tbx, tby = readf64(vbuf, vb + 16), readf64(vbuf, vb + 24) - local tcx, tcy = readf64(vbuf, vc + 16), readf64(vbuf, vc + 24) local tdx, tdy = readf64(vbuf, d + 16), readf64(vbuf, d + 24) if colb == col and colc == col and cold == col then - if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then vd = d end + if tbx == tcx and tby == tay and tdx == tax and tdy == tcy then + vd, flat = d, not t or (tax == tcx and tay == tcy) + end elseif tax == tbx and tax == tcx and tax == tdx and tay == tby and tay == tcy and tay == tdy then if colb == col and cold == colc then @@ -47979,6 +48274,15 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, bx1, by1 = ceil(pcx - ox - 0.5), ceil(pcy - oy - 0.5) end end + -- textured line quad (ImPlot PrimLine): uv a = b, c = d, u a ~= u c + if not vd and t and colb == col and colc == col and cold == col and tax ~= tcx + and readf64(vbuf, vb + 16) == tax and readf64(vbuf, vb + 24) == tay + and readf64(vbuf, d + 16) == tcx and readf64(vbuf, d + 24) == tcy then + vd, gk = d, 3 + bx0, by0 = floor(min(pax, pbx, pcx, pdx) - ox), floor(min(pay, pby, pcy, pdy) - oy) + bx1 = ceil(max(pax, pbx, pcx, pdx) - ox) + 1 + by1 = ceil(max(pay, pby, pcy, pdy) - oy) + 1 + end end if vd then i = i + 6 @@ -47987,16 +48291,10 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, bx1, by1 = ceil(max(pax, pbx, pcx) - ox) + 1, ceil(max(pay, pby, pcy) - oy) + 1 i = i + 3 end - if bx0 < cx0 or by0 < cy0 or bx1 > cx1 or by1 > cy1 then CmdFree = false end if bx0 < cex0 then cex0 = bx0 end if by0 < cey0 then cey0 = by0 end if bx1 > cex1 then cex1 = bx1 end if by1 > cey1 then cey1 = by1 end - if bx0 < ex0 then ex0 = bx0 end - if by0 < ey0 then ey0 = by0 end - if bx1 > ex1 then ex1 = bx1 end - if by1 > ey1 then ey1 = by1 end - if bx0 < LimitX0 or by0 < LimitY0 or bx1 > LimitX1 or by1 > LimitY1 then LimitFree = false end if bx0 < cx0 then bx0 = cx0 end if by0 < cy0 then by0 = cy0 end if bx1 > cx1 then bx1 = cx1 end @@ -48007,41 +48305,43 @@ local function CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, PrimVtxBuffer[n] = va, vb, vc, vd, t, gk, tex_id, vbuf PrimClipX0[n], PrimClipY0[n], PrimClipX1[n], PrimClipY1[n] = cx0, cy0, cx1, cy1 PrimBoundsX0[n], PrimBoundsY0[n], PrimBoundsX1[n], PrimBoundsY1[n] = bx0, by0, bx1, by1 - PrimKind[n] = kind + PrimFlat[n] = flat + if kind == 2 then + c2 += 1 + LayerPrims2[c2] = n + elseif kind == 1 then + c1 += 1 + LayerPrims1[c1] = n + if bx0 < k1x then k1x = bx0 end + if by0 < k1y then k1y = by0 end + else + c3 += 1 + LayerPrims3[c3] = n + if bx0 < k3x then k3x = bx0 end + if by0 < k3y then k3y = by0 end + end end end + -- per command, from the bounds of all its primitives: one clipped, one past the limits, the extents + if cex0 < cx0 or cey0 < cy0 or cex1 > cx1 or cey1 > cy1 then CmdFree = false end + if cex0 < LimitX0 or cey0 < LimitY0 or cex1 > LimitX1 or cey1 > LimitY1 then LimitFree = false end + if cex0 < ex0 then ex0 = cex0 end + if cey0 < ey0 then ey0 = cey0 end + if cex1 > ex1 then ex1 = cex1 end + if cey1 > ey1 then ey1 = cey1 end end if cex0 > cex1 then cex0, cey0, cex1, cey1 = 0, 0, 0, 0 end CmdUnclipped[ci] = CmdFree CmdBoundsX0[ci], CmdBoundsY0[ci], CmdBoundsX1[ci], CmdBoundsY1[ci] = cex0, cey0, cex1, cey1 end end + Kind1Count, Kind2Count, Kind3Count, Kind1X, Kind1Y, Kind3X, Kind3Y = c1, c2, c3, k1x, k1y, k3x, k3y return n, LimitFree, ex0, ey0, ex1, ey1 end -@native -local function DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1) +local function DrawLists(BackendData, draw_list, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1) local set = BackendData.Layers[draw_list] local ListDeferred = false - local Kind1Count, Kind2Count, Kind3Count = 0, 0, 0 - local Kind1X, Kind1Y, Kind3X, Kind3Y = math.huge, math.huge, math.huge, math.huge - for p = first, n do - local k = PrimKind[p] - if k == 1 then - Kind1Count += 1 - LayerPrims1[Kind1Count] = p - if PrimBoundsX0[p] < Kind1X then Kind1X = PrimBoundsX0[p] end - if PrimBoundsY0[p] < Kind1Y then Kind1Y = PrimBoundsY0[p] end - elseif k == 2 then - Kind2Count += 1 - LayerPrims2[Kind2Count] = p - else - Kind3Count += 1 - LayerPrims3[Kind3Count] = p - if PrimBoundsX0[p] < Kind3X then Kind3X = PrimBoundsX0[p] end - if PrimBoundsY0[p] < Kind3Y then Kind3Y = PrimBoundsY0[p] end - end - end if Kind1Count > 0 then z += 1 if DrawLayer(BackendData, GetLayer(BackendData, draw_list, 1), LayerPrims1, Kind1Count, Kind1X, Kind1Y, ox, @@ -48147,7 +48447,6 @@ function M.RenderDrawData(draw_data) PB("ImGui collect") if EditableImages.StageTiming then EditableImages.BeginStage() end - local first = n + 1 local LimitFree, ex0, ey0, ex1, ey1 n, LimitFree, ex0, ey0, ex1, ey1 = CollectPrims(BackendData, draw_list, n, ox, oy, LimitX0, LimitY0, LimitX1, LimitY1) @@ -48155,8 +48454,7 @@ function M.RenderDrawData(draw_data) PE() local ListDeferred - z, ListDeferred = DrawLists(BackendData, draw_list, first, n, z, ox, oy, force, LimitX0, LimitY0, LimitX1, - LimitY1) + z, ListDeferred = DrawLists(BackendData, draw_list, z, ox, oy, force, LimitX0, LimitY0, LimitX1, LimitY1) set = BackendData.Layers[draw_list] -- deferred tiles: not "unchanged" next frame, so they get redrawn if set then @@ -48268,6 +48566,23 @@ local pending, by_id, batch_no = {}, {}, 0 local open = false local actors, ready, conns, folder = {}, false, {}, nil local sent = {} +-- ids of destroyed textures each Actor holds a copy of, sent with its next job (the Actor drops them) +local drops = {} +local NO_DROPS = {} +local sync_tex = {} -- Sync mode: the "Actors'" texture copies +EditableImages.TextureDropped = function(id, rec) + if not rec then + return + end + for a = 1, NA do + local s = sent[a] + if s and s[rec] ~= nil then + s[rec] = nil + local d = drops[a] + d[#d + 1] = id + end + end +end local function grow(b: buffer, need: number): buffer local n = buffer.len(b) @@ -48451,6 +48766,46 @@ local function fullCopy(rec, v: number): buffer return rec.Head end +-- The pixels changed between versions had and v (rows y0..y1 of rec): the updated rects (rect list -> worker copies +-- each rect's rows), or the whole rows when they are smaller. Built once per (had, v), shared by every Actor. +local function patchCopy(rec, had: number, v: number, y0: number, y1: number): (buffer, any) + if rec.PatchHad == had and rec.PatchV == v then + return rec.Patch, rec.PatchAt + end + local row, src = rec.Width * 4, rec.Buffer + local log, area = rec.Log, 0 + for k = had + 1, v do + local r = log[k][3] + if r then + for i = 1, #r, 4 do area += r[i + 2] * r[i + 3] end + end + end + local patch, at + if area * 4 < (y1 - y0) * row then + patch, at = buffer.create(area * 4), {} + local o, n = 0, 0 + for k = had + 1, v do + local r = log[k][3] + if r then + for i = 1, #r, 4 do + local x, y, w, h = r[i], r[i + 1], r[i + 2], r[i + 3] + at[n + 1], at[n + 2], at[n + 3], at[n + 4] = x, y, w, h + n += 4 + for yy = y, y + h - 1 do + copy(patch, o, src, (yy * rec.Width + x) * 4, w * 4) + o += w * 4 + end + end + end + end + else + patch, at = buffer.create((y1 - y0) * row), y0 * row + copy(patch, 0, src, y0 * row, (y1 - y0) * row) + end + rec.PatchHad, rec.PatchV, rec.Patch, rec.PatchAt = had, v, patch, at + return patch, at +end + function M.Flush() local n = jobs.N if n == 0 then @@ -48521,22 +48876,45 @@ function M.Flush() tex[#tex + 1] = { id, buf, rec.Width, rec.Height, rec.Fill or 0 } Stats.TexBytes += buffer.len(buf) elseif y1 > y0 then - local row = rec.Width * 4 - local patch = buffer.create((y1 - y0) * row) - copy(patch, 0, rec.Buffer, y0 * row, (y1 - y0) * row) - tex[#tex + 1] = { id, false, rec.Width, rec.Height, y0 * row, patch } + local patch, at = patchCopy(rec, had, v, y0, y1) + tex[#tex + 1] = { id, false, rec.Width, rec.Height, at, patch } Stats.TexBytes += buffer.len(patch) end Stats.TexSends += 1 end end Stats.SendBytes += Pn[a] + tl + local d = drops[a] + if #d > 0 then + drops[a] = {} + else + d = NO_DROPS + end if cfg.Sync then + -- like an Actor: own texture copies, kept by the same messages (SendMessage copies: clone the buffers) + local st = sync_tex[a] + if not st then + st = {} + sync_tex[a] = st + end + local msg = table.create(#tex) + for i, u in tex do + local c = table.clone(u) + for k, x in c do + if type(x) == "buffer" then + local nb = buffer.create(buffer.len(x)) + copy(nb, 0, x) + c[k] = nb + end + end + msg[i] = c + end + Raster.ApplyTextures(st, msg, d) if not (cfg.SyncDrop and a % 2 == 0) then - b.Res[a] = RasterJobs(P, T, tl, Records) + b.Res[a] = RasterJobs(P, T, tl, st) end else - actors[a]:SendMessage("job", batch_no, P, T, tex, tl) + actors[a]:SendMessage("job", batch_no, P, T, tex, tl, d) end end if par then @@ -48565,6 +48943,8 @@ local function setActors(n) Tb[a] = Tb[a] or buffer.create(1024) used[a] = used[a] or {} sent[a] = setmetatable({}, { __mode = "k" }) + drops[a] = {} + sync_tex[a] = nil end reset() end @@ -56128,6 +56508,7 @@ ImGuiKeyOwner_NoOwner = 4294967295 -- Require key to have no owner. function ImGui.MouseButtonToKey(button) assert(button >= 0 and button < 5 --[[ImGuiMouseButton.COUNT]]) return 656 --[[ImGuiKey.MouseLeft]] + button end --- @param key ImGuiKey +@native function ImGui.IsNamedKey(key) return key >= 512 --[[ImGuiKey.NamedKey_BEGIN]] and key < 667 --[[ImGuiKey.NamedKey_END]] end @@ -57000,6 +57381,7 @@ MT.ImGuiNextItemData = {} MT.ImGuiNextItemData.__index = MT.ImGuiNextItemData -- Also cleared manually by ItemAdd()! +@native function MT.ImGuiNextItemData:ClearFlags() self.HasFlags = 0 --[[ImGuiNextItemDataFlags.None]] self.ItemFlagsSet = 0 --[[ImGuiItemFlags.None]] @@ -57049,6 +57431,7 @@ end MT.ImGuiNextWindowData = {} MT.ImGuiNextWindowData.__index = MT.ImGuiNextWindowData +@native function MT.ImGuiNextWindowData:ClearFlags() self.HasFlags = 0 --[[ImGuiNextWindowDataFlags.None]] end @@ -59948,6 +60331,7 @@ end --- @param table_ ImGuiTable --- @param instance_no int +@native function ImGui.TableGetInstanceData(table_, instance_no) if instance_no == 0 then return table_.InstanceDataFirst @@ -61778,6 +62162,7 @@ end -- [Public] Starts into the first cell of a new row --- @param row_flags? ImGuiTableRowFlags --- @param row_min_height? float +@native function ImGui.TableNextRow(row_flags, row_min_height) if row_flags == nil then row_flags = 0 end if row_min_height == nil then row_min_height = 0.0 end @@ -61807,6 +62192,7 @@ function ImGui.TableNextRow(row_flags, row_min_height) end -- [Internal] Only called by TableNextRow() +@native function ImGui.TableBeginRow(table_) local window = table_.InnerWindow assert(not table_.IsInsideRow) @@ -61851,6 +62237,7 @@ end local TableEndRow_RowMin, TableEndRow_RowMax = ImVec2(), ImVec2() -- [Internal] Called by TableNextRow() +@native function ImGui.TableEndRow(table_) local g = GImGui local window = g.CurrentWindow @@ -62028,6 +62415,7 @@ function ImGui.TableGetColumnIndex() end -- [Public] Append into a specific column +@native function ImGui.TableSetColumnIndex(column_n) local g = GImGui local table_ = g.CurrentTable @@ -62129,7 +62517,21 @@ function ImGui.TableBeginCell(table_, column_n) --IM_ASSERT(table.DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP) else -- FIXME-TABLE: Could avoid this if draw channel is dummy channel? - ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) + -- [Luau] inline ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) + local cr = column.ClipRect + local x1, y1, x2, y2 = cr.Min.x, cr.Min.y, cr.Max.x, cr.Max.y + local wcr = window.ClipRect + wcr.Min.x = x1; wcr.Min.y = y1; wcr.Max.x = x2; wcr.Max.y = y2 + local draw_list = window.DrawList + local hcr = draw_list._CmdHeader.ClipRect + hcr.x = x1; hcr.y = y1; hcr.z = x2; hcr.w = y2 + local stack = draw_list._ClipRectStack + local top = stack.Data[stack.Size] + if top ~= nil then + top.x = x1; top.y = y1; top.z = x2; top.w = y2 + else + stack.Data[stack.Size] = ImVec4(x1, y1, x2, y2) + end local channel = column.DrawChannelCurrent if splitter._Current ~= channel then splitter:SetCurrentChannel(window.DrawList, channel) @@ -62188,6 +62590,7 @@ end ------------------------------------------------------------------------------- -- Maximum column content width given current layout. Use column.MinX so this value differs on a per-column basis. +@native function ImGui.TableCalcMaxColumnWidth(table_, column_n) local column = table_.Columns[column_n] local max_width = 3.4028234663853e+38 --[[FLT_MAX]] @@ -62215,6 +62618,7 @@ function ImGui.TableCalcMaxColumnWidth(table_, column_n) end -- Note this is meant to be stored in column.WidthAuto, please generally use the WidthAuto field +@native function ImGui.TableGetColumnWidthAuto(table_, column) local content_width_body = mathMax(column.ContentMaxXFrozen, column.ContentMaxXUnfrozen) - column.WorkMinX local content_width_headers = column.ContentMaxXHeadersIdeal - column.WorkMinX @@ -64710,7 +65114,7 @@ function ImGui.TextEx(text, text_end, flags) -- Calculate length if text_end == nil then - text_end = #text + 1 + text_end = (type(text) == "string" and string.len(text) or #text) + 1 -- [Luau] `#` on a string isn't a native fast path end local dc = window.DC @@ -64721,7 +65125,12 @@ function ImGui.TextEx(text, text_end, flags) -- [Luau] scalar text_pos, scratch bb (ItemAdd() copies it, RenderTextWrapped() only reads it) local text_pos_x, text_pos_y = dc.CursorPos.x, dc.CursorPos.y + dc.CurrLineTextBaseOffset local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(dc.CursorPos, wrap_pos_x) or 0.0 - local text_size_x, text_size_y = ImGui.CalcTextSizeXY(text, 1, text_end, false, wrap_width) + -- [Luau] inline ImGui.CalcTextSizeXY(text, 1, text_end, false, wrap_width) + local text_size_x, text_size_y = 0.0, g.FontSize + if text ~= "" and text_end > 1 then + text_size_x, text_size_y = ImFontCalcTextSizeXY(g.Font, text_size_y, 3.4028234663853e+38 --[[FLT_MAX]], wrap_width, text, 1, text_end, text_end, nil, 0 --[[ImDrawTextFlags.None]]) + text_size_x = math.ceil(text_size_x) -- Round (see CalcTextSize()) + end local bb = TextEx_bb local bb_min, bb_max = bb.Min, bb.Max @@ -64837,7 +65246,13 @@ end @native function ImGui.Text(fmt, ...) if select('#', ...) > 0 then - ImGui.TextV(fmt, ...) + -- [Luau] inline ImGui.TextV(fmt, ...) (saves a vararg call per Text()) + local window = GImGui.CurrentWindow -- [Luau] inline GetCurrentWindow() + window.WriteAccessed = true + if window.SkipItems then + return + end + ImGui.TextEx(ImFormatString(fmt, ...), nil, 1 --[[ImGuiTextFlags.NoWidthForLargeClippedText]]) else ImGui.TextEx(fmt) end @@ -64854,6 +65269,7 @@ end --- @param fmt string --- @param ... any +@native function ImGui.TextDisabled(fmt, ...) local g = GImGui ImGui.PushStyleColor(0 --[[ImGuiCol.Text]], g.Style.Colors[1 --[[ImGuiCol.TextDisabled]]]) @@ -64863,6 +65279,7 @@ end --- @param fmt string --- @param ... any +@native function ImGui.TextWrapped(fmt, ...) local g = GImGui local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0) -- Keep existing wrap position if one is already set @@ -65433,6 +65850,7 @@ end --- @param label string --- @param size_arg? ImVec2 --- @return bool +@native function ImGui.Button(label, size_arg) return ImGui.ButtonEx(label, size_arg, 0 --[[ImGuiButtonFlags.None]]) end @@ -68602,6 +69020,7 @@ end --- @param out_grab_bb ImRect --- @return T v # updated `v` passed in --- @return bool value_changed +@native function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_max, format, flags, out_grab_bb) local g = GImGui local style = g.Style @@ -68772,6 +69191,7 @@ end --- @param out_grab_bb ImRect --- @return T v --- @return bool value_changed +@native function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out_grab_bb) -- Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. assert((flags == 1 or bit32.band(flags, 1879048207 --[[ImGuiSliderFlags.InvalidMask_]]) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.") @@ -68855,6 +69275,7 @@ end --- @param max T --- @param format? string --- @param flags? ImGuiSliderFlags +@native function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) if flags == nil then flags = 0 end @@ -69055,6 +69476,7 @@ end --- @param v_max float --- @param format? string --- @param flags? ImGuiSliderFlags +@native function ImGui.SliderFloat(label, v, v_min, v_max, format, flags) if format == nil then format = "%.3f" end if flags == nil then flags = 0 end @@ -72370,6 +72792,7 @@ end --- @param storage_id ImGuiID --- @param is_open bool +@native function ImGui.TreeNodeSetOpen(storage_id, is_open) local g = GImGui local storage = g.CurrentWindow.DC.StateStorage @@ -72378,6 +72801,7 @@ end --- @param storage_id ImGuiID --- @param flags ImGuiTreeNodeFlags +@native function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) -- Leaf node always open a new tree/id scope. If you never use it, add ImGuiTreeNodeFlags.NoTreePushOnOpen. if bit32.band(flags, 256 --[[ImGuiTreeNodeFlags.Leaf]]) ~= 0 then @@ -72833,6 +73257,7 @@ function ImGui.TreePush(str_id) end --- @param id ImGuiID +@native function ImGui.TreePushOverrideID(id) local g = GImGui local window = g.CurrentWindow @@ -72841,6 +73266,7 @@ function ImGui.TreePushOverrideID(id) ImGui.PushOverrideID(id) end +@native function ImGui.TreePop() local g = GImGui local window = g.CurrentWindow @@ -72877,6 +73303,7 @@ end -- Set next TreeNode/CollapsingHeader open state. --- @param is_open bool --- @param cond? ImGuiCond +@native function ImGui.SetNextItemOpen(is_open, cond) if cond == nil then cond = 0 end @@ -79311,7 +79738,8 @@ local STBTT_fabs = math.abs local STBTT_ifloor = math.floor local STBTT_iceil = math.ceil -local trunc = function(x) +@native +local function trunc(x) if x >= 0 then return math.floor(x) else @@ -81164,11 +81592,25 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t if e.fdx == 0 then local x0 = e.fx if x0 < len then - if x0 >= 0 then - stbtt__handle_clipped_edge(scanline, trunc(x0), e, x0, y_top, x0, y_bottom) - stbtt__handle_clipped_edge(scanline_fill, trunc(x0) + 1, e, x0, y_top, x0, y_bottom) - else - stbtt__handle_clipped_edge(scanline_fill, 0, e, x0, y_top, x0, y_bottom) + -- [Luau] the stbtt__handle_clipped_edge() calls, inlined (every edge of pixel fonts like ProggyClean is + -- vertical): x0 == x1, so clipping to sy/ey keeps x, and the same arithmetic gives the same results + local y0, y1 = y_top, y_bottom + local sy, ey = e.sy, e.ey + if y0 <= ey and y1 >= sy then + if y0 < sy then y0 = sy end + if y1 > ey then y1 = ey end + local height = e.direction * (y1 - y0) + if x0 >= 0 then + local x = math.floor(x0) -- trunc(x0) + if x0 <= x then + scanline[x] = scanline[x] + height + else + scanline[x] = scanline[x] + height * (1 - ((x0 - x) + (x0 - x)) / 2) + end + scanline_fill[x + 1] = scanline_fill[x + 1] + height + else + scanline_fill[0] = scanline_fill[0] + height + end end end else @@ -81713,9 +82155,12 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) local n = 0 local start = 0 + -- [Luau] vertex types and the current vertex in locals, stbtt__add_point() inlined (same values) + local VTX_MOVE, VTX_LINE, VTX_CURVE, VTX_CUBIC = STBTT_VTX.MOVE, STBTT_VTX.LINE, STBTT_VTX.CURVE, STBTT_VTX.CUBIC + -- count how many "moves" there are to get the contour count for i = 1, num_verts do - if vertices[i].type == STBTT_VTX.MOVE then + if vertices[i].type == VTX_MOVE then n = n + 1 end end @@ -81735,7 +82180,9 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) num_points = 0 n = -1 for i = 1, num_verts do - if vertices[i].type == STBTT_VTX.MOVE then + local v = vertices[i] + local vtype = v.type + if vtype == VTX_MOVE then -- start the next contour if n >= 0 then contour_lengths[n + 1] = num_points - start @@ -81743,30 +82190,30 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) n = n + 1 start = num_points - x = vertices[i].x - y = vertices[i].y - stbtt__add_point(points, num_points, x, y) + x = v.x + y = v.y num_points = num_points + 1 - elseif vertices[i].type == STBTT_VTX.LINE then - x = vertices[i].x - y = vertices[i].y - stbtt__add_point(points, num_points, x, y) + if points then local pt = points[num_points]; pt.x = x; pt.y = y end -- stbtt__add_point() + elseif vtype == VTX_LINE then + x = v.x + y = v.y num_points = num_points + 1 - elseif vertices[i].type == STBTT_VTX.CURVE then + if points then local pt = points[num_points]; pt.x = x; pt.y = y end -- stbtt__add_point() + elseif vtype == VTX_CURVE then num_points = stbtt__tesselate_curve(points, num_points, x, y, - vertices[i].cx, vertices[i].cy, - vertices[i].x, vertices[i].y, + v.cx, v.cy, + v.x, v.y, objspace_flatness_squared, 0) - x = vertices[i].x - y = vertices[i].y - elseif vertices[i].type == STBTT_VTX.CUBIC then + x = v.x + y = v.y + elseif vtype == VTX_CUBIC then num_points = stbtt__tesselate_cubic(points, num_points, x, y, - vertices[i].cx, vertices[i].cy, - vertices[i].cx1, vertices[i].cy1, - vertices[i].x, vertices[i].y, + v.cx, v.cy, + v.cx1, v.cy1, + v.x, v.y, objspace_flatness_squared, 0) - x = vertices[i].x - y = vertices[i].y + x = v.x + y = v.y end end contour_lengths[n + 1] = num_points - start diff --git a/build/ImGuiWorker.client.luau b/build/ImGuiWorker.client.luau index e88cc52..55b3c40 100644 --- a/build/ImGuiWorker.client.luau +++ b/build/ImGuiWorker.client.luau @@ -26,7 +26,9 @@ local M = { } local TILE = M.TILE -local TargetBuffer: buffer, TargetWidth = buffer.create(0), 0 +-- Pixel (x, y) of the target is at byte (y * TargetWidth + x) * 4 + TargetBase: a target can be a sub-rectangle of the +-- tile (raster straight into the upload buffer) +local TargetBuffer: buffer, TargetWidth, TargetBase = buffer.create(0), 0, 0 local PrevRow = buffer.create(1024) -- True when TargetBuffer[o, o + len) equals the previous row's destination (so its result can be copied); else @@ -48,30 +50,46 @@ local function RowRepeats(o: number, len: number, has_prev: boolean): boolean return false end local RectColumns = table.create(256, 0) +-- DrawRect's per-alpha blend cache: GlyphKey[alpha] = GlyphGen + destination value -> GlyphValue[alpha]. GlyphGen +-- (a multiple of 2^32) changes with the vertex colour. +local GlyphKey, GlyphValue = table.create(256, -1), table.create(256, 0) +GlyphKey[0], GlyphValue[0] = -1, 0 +local GlyphCol, GlyphGen = -1, 0 --- Uniform region: [UX0, UX1) x [UY0, UY1) of the target holds only the pixel value UV (empty when UX0 >= UX1). --- Set by ClearRect and by solid rects; shrunk by everything drawn over it. A solid rect inside it blends one pixel and --- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. -local UX0, UY0, UX1, UY1, UV = 0, 0, 0, 0, 0 +-- Uniform rows: [RowX0[y], RowX1[y]) of target row y holds only the pixel value RowV[y] (empty when RowX0 >= RowX1). +-- Set by ClearRect and by solid spans; shrunk by everything drawn over it. A solid span inside it blends one pixel and +-- fills (window/frame backgrounds over backgrounds), instead of blending every pixel. Only the rows of the last +-- ClearRect are valid: drawing must stay inside it (callers clip every primitive to the cleared rect). +local RowX0, RowX1, RowV = table.create(TILE, 0), table.create(TILE, 0), table.create(TILE, 0) +RowX0[0], RowX1[0], RowV[0] = 0, 0, 0 --- Drawing may change [x0, x1) x [y0, y1): keep the largest uniform piece outside it +-- Drawing changed [x0, x1) x [y0, y1): keep the larger uniform piece of each row outside it +@native +local function ApplyDamage(x0: number, y0: number, x1: number, y1: number) + for y = y0, y1 - 1 do + local a, b = RowX0[y], RowX1[y] + if x0 < b and x1 > a then + if x0 - a >= b - x1 then RowX1[y] = x0 else RowX0[y] = x1 end + end + end +end + +-- Only FillSpan reads the uniform rows: damage is collected into one pending rect (nearby rects merged: a text line's +-- glyphs, a shape's triangles) and applied when FillSpan runs. Over-shrinking only loses uniform pixels. +local PX0, PY0, PX1, PY1 = 0, 0, 0, 0 -- pending damage (none when PX0 >= PX1) @native local function Shrink(x0: number, y0: number, x1: number, y1: number) - if x0 >= UX1 or x1 <= UX0 or y0 >= UY1 or y1 <= UY0 or UX0 >= UX1 then return end - local h, w = UY1 - UY0, UX1 - UX0 - local left, right, top, bottom = (x0 - UX0) * h, (UX1 - x1) * h, (y0 - UY0) * w, (UY1 - y1) * w - local best = max(left, right, top, bottom) - if best <= 0 then - UX1 = UX0 - elseif best == left then - UX1 = x0 - elseif best == right then - UX0 = x1 - elseif best == top then - UY1 = y0 - else - UY0 = y1 + if PX0 >= PX1 then + PX0, PY0, PX1, PY1 = x0, y0, x1, y1 + return end + local ux0, uy0, ux1, uy1 = min(x0, PX0), min(y0, PY0), max(x1, PX1), max(y1, PY1) + if (ux1 - ux0) * (uy1 - uy0) <= ((x1 - x0) * (y1 - y0) + (PX1 - PX0) * (PY1 - PY0)) * 1.25 + 256 then + PX0, PY0, PX1, PY1 = ux0, uy0, ux1, uy1 + return + end + ApplyDamage(PX0, PY0, PX1, PY1) + PX0, PY0, PX1, PY1 = x0, y0, x1, y1 end -- FillSpan and DrawTriangle's flat path inline this math with per-span constants: keep them in sync. @@ -104,57 +122,120 @@ local function BlendPixel(TargetBuffer: buffer, o: number, r: number, g: number, end end +-- Wide spans (>= 32 px) over non-uniform rows: rows usually blend over identical rows, so a row whose destination +-- repeats the previous one's copies its result @native local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number, x1: number, r: number, g: number, b: number, a: number) if a <= 0 then return end - local w4 = (x1 - x0 - 1) * 4 - if x0 >= UX0 and y0 >= UY0 and x1 <= UX1 and y1 <= UY1 and a < 255 then - -- over one value: FillSpan's per-pixel result for d = UV, then fill - local d, v = UV, 0 - if d < 16777216 then - v = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 - else - local sa = a / 255 - local ns = 1 - sa - local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) - if d >= 4278190080 then - v = floor(r * sa + dr * ns + 0.5) + floor(g * sa + dg * ns + 0.5) * 256 - + floor(b * sa + db * ns + 0.5) * 65536 + 4278190080 - else - local k = rshift(d, 24) * (ns / 255) - local oa = sa + k - local inv = 1 / oa - v = floor((r * sa + dr * k) * inv + 0.5) + floor((g * sa + dg * k) * inv + 0.5) * 256 - + floor((b * sa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 - end - end - local first = (y0 * TargetWidth + x0) * 4 - for o = first, first + w4, 4 do writeu32(TargetBuffer, o, v) end - for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end - UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, v - return + if PX0 < PX1 then + ApplyDamage(PX0, PY0, PX1, PY1) + PX1 = PX0 end + local w4 = (x1 - x0 - 1) * 4 + local span = x1 - x0 if a >= 255 then local packed = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + 4278190080 - local first = (y0 * TargetWidth + x0) * 4 + local first = (y0 * TargetWidth + x0) * 4 + TargetBase for o = first, first + w4, 4 do writeu32(TargetBuffer, o, packed) end - for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4, TargetBuffer, first, w4 + 4) end - -- now uniform: keep whichever region is larger - local area = (x1 - x0) * (y1 - y0) - Shrink(x0, y0, x1, y1) - if area > (UX1 - UX0) * (UY1 - UY0) or UX0 >= UX1 then UX0, UY0, UX1, UY1, UV = x0, y0, x1, y1, packed end + for y = y0 + 1, y1 - 1 do buffer.copy(TargetBuffer, (y * TargetWidth + x0) * 4 + TargetBase, TargetBuffer, first, w4 + 4) end + -- now uniform: per row keep whichever piece is larger (the same for following rows with the same piece) + local y = y0 + while y < y1 do + local ra, rb = RowX0[y], RowX1[y] + local na, nb = ra, rb + if x0 < rb and x1 > ra then + if x0 - ra >= rb - x1 then nb = x0 else na = x1 end + end + if span > nb - na then + repeat + RowX0[y], RowX1[y], RowV[y] = x0, x1, packed + y += 1 + until y >= y1 or RowX0[y] ~= ra or RowX1[y] ~= rb + else + repeat + RowX0[y], RowX1[y] = na, nb + y += 1 + until y >= y1 or RowX0[y] ~= ra or RowX1[y] ~= rb + end + end return end - Shrink(x0, y0, x1, y1) local packed0 = floor(r + 0.5) + floor(g + 0.5) * 256 + floor(b + 0.5) * 65536 + floor(a + 0.5) * 16777216 local sa = a / 255 local ns = 1 - sa local c1 = ns / 255 local rs, gs, bs = r * sa, g * sa, b * sa local last_d, last_v = -1, 0 -- UI backgrounds are mostly flat: reuse the previous result for the same destination - for y = y0, y1 - 1 do - local o0 = (y * TargetWidth + x0) * 4 + local prev_o, prev_v = 0, -1 -- previous row: filled with prev_v (-1: blended) + local wide, has_prev = span >= 32 and y1 - y0 > 1, false + local y = y0 + while y < y1 do + local o0 = (y * TargetWidth + x0) * 4 + TargetBase + local ra, rb = RowX0[y], RowX1[y] + if x0 >= ra and x1 <= rb then + -- over one value: the per-pixel result for d = RowV[y], then fill; following rows with the same uniform + -- piece get the same result + local d = RowV[y] + if d ~= last_d then + last_d = d + if d < 16777216 then + last_v = packed0 + else + local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) + if d >= 4278190080 then + last_v = floor(rs + dr * ns + 0.5) + floor(gs + dg * ns + 0.5) * 256 + + floor(bs + db * ns + 0.5) * 65536 + 4278190080 + else + local k = rshift(d, 24) * c1 + local oa = sa + k + local inv = 1 / oa + last_v = floor((rs + dr * k) * inv + 0.5) + floor((gs + dg * k) * inv + 0.5) * 256 + + floor((bs + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 + end + end + end + local v = last_v + if v == prev_v and span > 8 then -- (a call: slower than a few writes) + buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4) + else + for o = o0, o0 + w4, 4 do writeu32(TargetBuffer, o, v) end + end + local na, nb, nv = ra, rb, d + if span >= x0 - ra and span >= rb - x1 then + na, nb, nv = x0, x1, v + elseif x0 - ra >= rb - x1 then + nb = x0 + else + na = x1 + end + RowX0[y], RowX1[y], RowV[y] = na, nb, nv + y += 1 + local stride = TargetWidth * 4 + local o = o0 + while y < y1 and RowX0[y] == ra and RowX1[y] == rb and RowV[y] == d do + o += stride + buffer.copy(TargetBuffer, o, TargetBuffer, o0, w4 + 4) + RowX0[y], RowX1[y], RowV[y] = na, nb, nv + y += 1 + end + prev_o, prev_v, has_prev = o, v, false + continue + end + if x0 < rb and x1 > ra then + if x0 - ra >= rb - x1 then RowX1[y] = x0 else RowX0[y] = x1 end + end + if wide then + local repeats = RowRepeats(o0, w4 + 4, has_prev) + has_prev = true + if repeats then + buffer.copy(TargetBuffer, o0, TargetBuffer, prev_o, w4 + 4) + prev_o, prev_v = o0, -1 + y += 1 + continue + end + end + prev_o, prev_v = o0, -1 for o = o0, o0 + w4, 4 do local d = readu32(TargetBuffer, o) if d == last_d then @@ -177,6 +258,7 @@ local function FillSpan(TargetBuffer: buffer, y0: number, y1: number, x0: number writeu32(TargetBuffer, o, last_v) end end + y += 1 end end @@ -211,23 +293,7 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number r, g, b, a = r * tr / 255, g * tg / 255, b * tb / 255, a * ta / 255 end if a <= 0 then return end - if a >= 255 or px1 - px0 < 32 or (px0 >= UX0 and py0 >= UY0 and px1 <= UX1 and py1 <= UY1) then - FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a) - return - end - -- Wide translucent rect: rows usually blend over identical rows, so copy the previous row's result - Shrink(px0, py0, px1, py1) - local len = (px1 - px0) * 4 - local prev_o = 0 - for y = py0, py1 - 1 do - local o = (y * TargetWidth + px0) * 4 - if RowRepeats(o, len, y > py0) then - buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) - else - FillSpan(TargetBuffer, y, y + 1, px0, px1, r, g, b, a) - end - prev_o = o - end + FillSpan(TargetBuffer, py0, py1, px0, px1, r, g, b, a) return end @@ -239,18 +305,31 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number local cols = RectColumns local ident = col == 4294967295 local last_tv, sa, sr, sg, sb, s_opaque, fa, fn, fk = -1, 0, 0, 0, 0, 0, 0, 0, 0 + local step = true for c = 1, ncol do local tx = floor((u0 + (px0 + c - 1 + 0.5 - x0) * du) * tw) if tx < 0 then tx = 0 elseif tx >= tw then tx = tw - 1 end cols[c] = tx * 4 + if c > 1 and tx * 4 ~= cols[c - 1] + 4 then step = false end end + -- white translucent texels (font atlas): blend result cached per alpha for one destination value and colour + if col ~= GlyphCol then + GlyphCol = col + GlyphGen += 4294967296 + if GlyphGen >= 4503599627370496 then -- 2^52: keys must stay exact + GlyphGen = 4294967296 + for k = 0, 255 do GlyphKey[k] = -1 end + end + end + local gen = GlyphGen for y = py0, py1 - 1 do local ty = floor((v0 + (y + 0.5 - y0) * dv) * th) if ty < 0 then ty = 0 elseif ty >= th then ty = th - 1 end local trow4 = ty * tw * 4 - local o = (y * TargetWidth + px0) * 4 + local o = (y * TargetWidth + px0) * 4 + TargetBase + local tb0 = trow4 + cols[1] - 4 for c = 1, ncol do - local tv = readu32(tbuf, trow4 + cols[c]) + local tv = readu32(tbuf, step and tb0 + c * 4 or trow4 + cols[c]) if tv < 16777216 then o += 4 continue @@ -260,6 +339,17 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number o += 4 continue end + local d, key, al = 0, -1, 0 + if tv % 16777216 == 16777215 then + al = rshift(tv, 24) + d = readu32(dbuf, o) + key = gen + d + if GlyphKey[al] == key then + writeu32(dbuf, o, GlyphValue[al]) + o += 4 + continue + end + end -- BlendPixel inlined (same math) if tv ~= last_tv then last_tv = tv @@ -270,27 +360,35 @@ local function DrawRect(TargetBuffer: buffer, x0: number, y0: number, x1: number fn = 1 - fa fk = (1 - fa) / 255 end + local v = -1 if sa >= 255 then - writeu32(dbuf, o, s_opaque + 4278190080) + v = s_opaque + 4278190080 elseif sa > 0 then - local d = readu32(dbuf, o) + if key < 0 then d = readu32(dbuf, o) end if d < 16777216 then - writeu32(dbuf, o, s_opaque + floor(sa + 0.5) * 16777216) + v = s_opaque + floor(sa + 0.5) * 16777216 else local dr, dg, db = band(d, 255), band(rshift(d, 8), 255), band(rshift(d, 16), 255) if d >= 4278190080 then - writeu32(dbuf, o, floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 - + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080) + v = floor(sr * fa + dr * fn + 0.5) + floor(sg * fa + dg * fn + 0.5) * 256 + + floor(sb * fa + db * fn + 0.5) * 65536 + 4278190080 else local k = rshift(d, 24) * fk local oa = fa + k local inv = 1 / oa - writeu32(dbuf, o, floor((sr * fa + dr * k) * inv + 0.5) - + floor((sg * fa + dg * k) * inv + 0.5) * 256 - + floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216) + v = floor((sr * fa + dr * k) * inv + 0.5) + floor((sg * fa + dg * k) * inv + 0.5) * 256 + + floor((sb * fa + db * k) * inv + 0.5) * 65536 + floor(oa * 255 + 0.5) * 16777216 end end end + if v >= 0 then + writeu32(dbuf, o, v) + elseif key >= 0 then + v = d -- unchanged + end + if key >= 0 then + GlyphKey[al], GlyphValue[al] = key, v + end o += 4 end end @@ -390,7 +488,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, yb -= 1 end if yt > yb then continue end - local o = (yt * TargetWidth + x) * 4 + local o = (yt * TargetWidth + x) * 4 + TargetBase if flat then for _ = yt, yb do BlendPixel(dbuf, o, ra, ga, ba, aa) @@ -450,7 +548,7 @@ local function DrawTriangle(dbuf: buffer, vbuf: buffer, va: number, vb: number, xr -= 1 end if xl > xr then continue end - local o = (y * TargetWidth + xl) * 4 + local o = (y * TargetWidth + xl) * 4 + TargetBase if flat then local o1 = o + (xr - xl) * 4 if f_opaque then @@ -626,7 +724,7 @@ local function DrawLineQuad(dbuf: buffer, vbuf: buffer, va: number, vb: number, xr -= 1 end if xl > xr then continue end - local o = (y * TargetWidth + xl) * 4 + local o = (y * TargetWidth + xl) * 4 + TargetBase local wrow = WB * py + WC for x = xl, xr do local w = WA * (x + 0.5) + wrow @@ -699,7 +797,7 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1 local opaque = aa >= 255 and ab >= 255 local prev_o = 0 for y = py0, py1 - 1 do - local o = (y * TargetWidth + px0) * 4 + local o = (y * TargetWidth + px0) * 4 + TargetBase if y > py0 and (opaque or RowRepeats(o, len, true)) or (y == py0 and not opaque and RowRepeats(o, len, false)) then buffer.copy(TargetBuffer, o, TargetBuffer, prev_o, len) @@ -717,26 +815,20 @@ local function DrawRectGradient(TargetBuffer: buffer, x0: number, y0: number, x1 end end -function M.SetTarget(buf: buffer, width: number) - TargetBuffer, TargetWidth = buf, width - UX1 = UX0 +-- x0 y0: target pixel stored at buf's byte 0 (a sub-rectangle target: width = its width) +function M.SetTarget(buf: buffer, width: number, x0: number?, y0: number?) + TargetBuffer, TargetWidth, TargetBase = buf, width, -((y0 or 0) * width + (x0 or 0)) * 4 end @native function M.ClearRect(rx0: number, ry0: number, rx1: number, ry1: number) local rw = rx1 - rx0 - UX0, UY0, UX1, UY1, UV = rx0, ry0, rx1, ry1, 0 + for y = ry0, ry1 - 1 do RowX0[y], RowX1[y], RowV[y] = rx0, rx1, 0 end + PX1 = PX0 if rw == TargetWidth then - buffer.fill(TargetBuffer, ry0 * TargetWidth * 4, 0, (ry1 - ry0) * TargetWidth * 4) + buffer.fill(TargetBuffer, (ry0 * TargetWidth + rx0) * 4 + TargetBase, 0, (ry1 - ry0) * TargetWidth * 4) else - for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4, 0, rw * 4) end - end -end - -@native -function M.CopySubRect(dst: buffer, rx0: number, ry0: number, rw: number, rh: number) - for y = 0, rh - 1 do - buffer.copy(dst, y * rw * 4, TargetBuffer, ((ry0 + y) * TargetWidth + rx0) * 4, rw * 4) + for y = ry0, ry1 - 1 do buffer.fill(TargetBuffer, (y * TargetWidth + rx0) * 4 + TargetBase, 0, rw * 4) end end end @@ -763,13 +855,12 @@ local function DrawPrim(kind: number, t, vbuf: buffer, va: number, vb: number, v end M.DrawPrim = DrawPrim --- Packed tile jobs -> one exact-size buffer per rect, in job order (worker + main-thread fallback) -local Scratch = buffer.create(TILE * TILE * 4) +-- Packed tile jobs -> one exact-size buffer per rect (rasterized straight into it), in job order (worker + main-thread +-- fallback) @native function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } - local ClearRect, CopySubRect = M.ClearRect, M.CopySubRect + local ClearRect, SetTarget = M.ClearRect, M.SetTarget local REC_A, REC_B, REC_C, REC_D = M.REC_A, M.REC_B, M.REC_C, M.REC_D - M.SetTarget(Scratch, TILE) local out, no = {}, 0 local o = 0 while o < tlen do @@ -781,6 +872,9 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } for r = 0, nr - 1 do local rx0, ry0, rx1, ry1 = readi32(T, ro + r * 16), readi32(T, ro + r * 16 + 4), readi32(T, ro + r * 16 + 8), readi32(T, ro + r * 16 + 12) + local rw, rh = rx1 - rx0, ry1 - ry0 + local sub = buffer.create(rw * rh * 4) + SetTarget(sub, rw, rx0, ry0) ClearRect(rx0, ry0, rx1, ry1) for k = 0, count - 1 do local q = readi32(T, po + k * 4) @@ -794,9 +888,6 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } if tid >= 0 then t = textures[tid] end DrawPrim(readi32(P, q), t, P, q + REC_A, q + REC_B, q + REC_C, q + REC_D, tox, toy, cx0, cy0, cx1, cy1) end - local rw, rh = rx1 - rx0, ry1 - ry0 - local sub = buffer.create(rw * rh * 4) - CopySubRect(sub, rx0, ry0, rw, rh) no += 1 out[no] = sub end @@ -804,36 +895,56 @@ function M.RasterJobs(P: buffer, T: buffer, tlen: number, textures): { buffer } return out end +-- An Actor's texture copies (worker.luau; parallel.lua's Sync mode emulates it): drop the destroyed ids, apply the +-- updates parallel.lua's Flush sent. { id, buf, w, h, fill }: whole texture, rows past buf are all fill; +-- { id, false, w, h, offset, patch }: rows; { id, false, w, h, rects, patch }: x, y, w, h quadruples, rows packed. +function M.ApplyTextures(textures, updates, dropped) + for _, id in dropped or {} do + textures[id] = nil + end + for _, u in updates do + if u[2] then + local b, w, h, fill = u[2], u[3], u[4], u[5] + local n, total = buffer.len(b), w * h * 4 + if n < total then + local full = buffer.create(total) + buffer.copy(full, 0, b) + if fill ~= 0 then + buffer.writeu32(full, n, fill) + local k = 4 + while k < total - n do + local c = math.min(k, total - n - k) + buffer.copy(full, n + k, full, n, c) + k += c + end + end + b = full + end + textures[u[1]] = { Buffer = b, Width = w, Height = h } + elseif type(u[5]) == "table" then + local t, rects, patch = textures[u[1]], u[5], u[6] + local dst, w, o = t.Buffer, t.Width, 0 + for i = 1, #rects, 4 do + local x, y, rw, rh = rects[i], rects[i + 1], rects[i + 2], rects[i + 3] + for yy = y, y + rh - 1 do + buffer.copy(dst, (yy * w + x) * 4, patch, o, rw * 4) + o += rw * 4 + end + end + else + buffer.copy(textures[u[1]].Buffer, u[5], u[6]) + end + end +end + return M end)() local Done = Actor:WaitForChild("Done") local Textures = {} -Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength) - for _, Texture in TexUpdates do - if Texture[2] then - local B, W, H, Fill = Texture[2], Texture[3], Texture[4], Texture[5] - local n, total = buffer.len(B), W * H * 4 - if n < total then -- the rows below were left out: all Fill (parallel.lua fullCopy) - local Full = buffer.create(total) - buffer.copy(Full, 0, B) - if Fill ~= 0 then - buffer.writeu32(Full, n, Fill) - local k = 4 - while k < total - n do - local c = math.min(k, total - n - k) - buffer.copy(Full, n + k, Full, n, c) - k += c - end - end - B = Full - end - Textures[Texture[1]] = { Buffer = B, Width = W, Height = H } - else -- rows changed since the copy this Actor has - local T = Textures[Texture[1]] - buffer.copy(T.Buffer, Texture[5], Texture[6]) - end - end +Actor:BindToMessageParallel("job", function(Id, Prims, Tiles, TexUpdates, TileLength, Dropped) + -- this Actor's texture copies: destroyed ids dropped, changed rows/rects patched (parallel.lua Flush) + Raster.ApplyTextures(Textures, TexUpdates, Dropped) local Results = Raster.RasterJobs(Prims, Tiles, TileLength, Textures) task.synchronize() Done:Fire(Id, Results)