Zaml Kontra Deobfuscated

objOct 17th, 2026Never expires Public12 views
Scripts
Luau267.52 KB | 7221 lines
-- pastewiki was here LOOLOLO


local PAYLOAD -- assigned at the bottom of this file

local function main()

    local Players = game:GetService("Players")

    -- application_1/1: cache the UI library and logo in the executor workspace
    pcall(function()
        if not isfolder("zaml") then
            makefolder("zaml")
        end

        local ok, windui = pcall(game.HttpGet, game, "https://raw.githubusercontent.com/amazson/zaml/main/windui.lua")
        if ok and type(windui) == "string" and #windui > 10000 then
            writefile("zaml/windui.lua", windui)
        end

        if not isfile("zaml/zaml.png") then
            local ok2, png = pcall(game.HttpGet, game, "https://raw.githubusercontent.com/amazson/zaml/main/zaml.png")
            if ok2 and type(png) == "string" and png:sub(2, 4) == "PNG" then
                writefile("zaml/zaml.png", png)
            end
        end
    end)

    if type(run_on_actor) == "function" then
        -- Preferred path: run the script inside one of the game's Actors (parallel Luau).
        local ReplicatedStorage = game:GetService("ReplicatedStorage")
        local target = nil

        -- application_1/2: return getactors()
        local ok, actors = pcall(function() return getactors() end)
        if not (ok and type(actors) == "table") then
            actors = {}
        end

        -- Take any actor that contains a script; once one is chosen, only replace it
        -- with an actor that lives under ReplicatedStorage.
        for _, actor in ipairs(actors) do
            local usable = typeof(actor) == "Instance"
                and actor:FindFirstChildWhichIsA("BaseScript")
                and (not target or actor:IsDescendantOf(game:GetService("ReplicatedStorage")))
            if usable then
                target = actor
            end
        end

        if not target then
            local handler = ReplicatedStorage:FindFirstChild("Handler")
            if handler and handler:IsA("Actor") then
                target = handler
            else
                for _, descendant in ipairs(ReplicatedStorage:GetDescendants()) do
                    if descendant:IsA("Actor") and descendant:FindFirstChildWhichIsA("BaseScript") then
                        target = descendant
                        break
                    end
                end
            end
        end

        if target then
            run_on_actor(target, PAYLOAD)
            return
        end
        Players.LocalPlayer:Kick("run script after Kontra has finished loading")
        return
    end

    -- Fallback path: no run_on_actor. Run on the main thread if the game's weapon
    -- module (a table with GetCurrentWeapon / GetWeaponInventory / GetModule) is in memory.
    if type(filtergc) == "function" then
        local ok, found = pcall(filtergc, "table", {
            Keys = { "GetCurrentWeapon", "GetWeaponInventory", "GetModule" },
        }, false)
        if ok and type(found) == "table" and found[1] ~= nil then
            local chunk = loadstring(PAYLOAD)
            if chunk then
                task.spawn(chunk)
                return
            end
        end
    end

    -- Last resort: enable parallel Luau on the main thread for the next join.
    local flagSet = false
    if type(setfflag) == "function" then
        flagSet = pcall(setfflag, "DebugRunParallelLuaOnMainThread", "True")
    end
    if flagSet then
        Players.LocalPlayer:Kick("rejoin the game and run zaml again")
    else
        Players.LocalPlayer:Kick("Your executor is not supported")
    end
end

PAYLOAD = [==[
if not LUAQ_OBFUSCATED then
    LUAQ_NO_VIRTUALIZE = function(f) return f end
end
pcall(function() local Players           = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService        = game:GetService("RunService")

local LocalPlayer = Players.LocalPlayer

do
    --!luaq:no_virtualize
    local function fix(env)
        local orig = type(env) == "table" and rawget(env, "gethui")
        if type(orig) ~= "function" or rawget(env, "__zamlHuiFixed") then return end
        local ok, h = pcall(orig)
        if not (ok and typeof(h) == "Instance" and h:IsA("LayerCollector")) then return end
        rawset(env, "__zamlHuiFixed", true)
        rawset(env, "gethui", function()
            local g = orig()
            if typeof(g) == "Instance" and g:IsA("LayerCollector") then
                return g.Parent or game:GetService("CoreGui")
            end
            return g
        end)
    end
    pcall(fix, getfenv and getfenv(1))
    pcall(fix, getgenv and getgenv())
end

local hub = { unloaded = false, conns = {}, cleanups = {} }
do
    local env = (getgenv and getgenv()) or _G
    if type(env.__zamltraUnload) == "function" then pcall(env.__zamltraUnload) end

    hub.connect = LUAQ_NO_VIRTUALIZE(function(signal, fn)
        local c = signal:Connect(fn)
        local conns = hub.conns
        conns[#conns + 1] = c
        if #conns % 200 == 0 then
            local live = {}
            for _, x in ipairs(conns) do if x.Connected then live[#live + 1] = x end end
            hub.conns = live
        end
        if hub.unloaded then c:Disconnect() end
        return c
    end)

    hub.onUnload = LUAQ_NO_VIRTUALIZE(function(fn)
        hub.cleanups[#hub.cleanups + 1] = fn
    end)

    hub.unload = LUAQ_NO_VIRTUALIZE(function()
        if hub.unloaded then return end
        hub.unloaded = true
        for _, c in ipairs(hub.conns) do pcall(function() c:Disconnect() end) end
        hub.conns = {}
        for i = #hub.cleanups, 1, -1 do pcall(hub.cleanups[i]) end
        hub.cleanups = {}
        if env.__zamltraUnload == hub.unload then env.__zamltraUnload = nil end
    end)
    env.__zamltraUnload = hub.unload
end

local showKeybindList = true

do
    local HANDLE = "ZamltraHubHandle"
    local roots = {}
    pcall(function() roots[#roots + 1] = game:GetService("CoreGui") end)
    pcall(function() if gethui then roots[#roots + 1] = gethui() end end)
    for _, root in ipairs(roots) do
        local old = root:FindFirstChild(HANDLE)
        if old and old:IsA("BindableFunction") then
            pcall(function() old:Invoke() end)
            pcall(function() old:Destroy() end)
        end
    end

    if setthreadidentity then pcall(setthreadidentity, 8) end
    local handle = Instance.new("BindableFunction")
    handle.Name = HANDLE
    handle.OnInvoke = function() hub.unload() end
    handle.Parent = roots[1]
    hub.onUnload(function() pcall(function() handle:Destroy() end) end)
end

do
    local GUI_NAMES = {
        ["WindUI"]               = true,
        ["WindUI/Notifications"] = true,
        ["WindUI/Dropdowns"]     = true,
        ["WindUI/Tooltips"]      = true,
        ["ZamlNametags"]         = true,
        ["ZamltraOverlay"]      = true,
        ["ZamltraKeybinds"]     = true,
        ["ZamltraSpectators"]   = true,
        ["ZamltraBindPopup"]    = true,
        ["ZamltraInvite"]       = true,
        ["ZamltraNametags"]     = true,
    }
    --!luaq:no_virtualize
    local function purge(parent)
        if not parent then return end
        for _, c in ipairs(parent:GetChildren()) do
            if GUI_NAMES[c.Name] then pcall(function() c:Destroy() end) end
        end
    end
    pcall(function() purge(gethui and gethui()) end)
    pcall(function() purge(game:GetService("CoreGui")) end)
    pcall(function() purge(LocalPlayer:FindFirstChildOfClass("PlayerGui")) end)
end

pcall(function()
    if setthreadidentity then pcall(setthreadidentity, 8) end
    if not (isfolder and listfiles and makefolder and isfile) then return end
    local OLD = "Zaml" .. "tra"
    if isfile("zaml/.migrated") then return end
    --!luaq:no_virtualize
    local function copyTree(from, to)
        if not isfolder(from) then return end
        if not isfolder(to) then makefolder(to) end
        for _, p in ipairs(listfiles(from)) do
            local name = p:gsub("\\", "/"):match("[^/]+$")
            if isfolder(p) then
                copyTree(from .. "/" .. name, to .. "/" .. name)
            elseif not isfile(to .. "/" .. name) then
                pcall(function() writefile(to .. "/" .. name, readfile(p)) end)
            end
        end
    end
    copyTree(OLD, "zaml")
    if isfolder("WindUI") then copyTree("WindUI/" .. OLD, "WindUI/zaml") end
    if not isfolder("zaml") then makefolder("zaml") end
    writefile("zaml/.migrated", "1")
end)

local WindUI
do
    if setthreadidentity then pcall(setthreadidentity, 8) end
    local source

    for _, path in ipairs({ "zaml/windui.lua", "windui.lua" }) do
        if not source and isfile and isfile(path) then
            local okR, s = pcall(readfile, path)
            if okR and type(s) == "string" and #s > 10000 then source = s end
        end
    end
    if not source then
        return
    end
    local fn, err = loadstring(source, "=windui")
    if not fn then return end
    local ok, mod = pcall(fn)
    if not ok then return end
    WindUI = mod
end

;(function()
    --!luaq:no_virtualize
    local function hex(h) return Color3.fromHex(h) end
    --!luaq:no_virtualize
    local function grad(a, b, rot)
        return WindUI:Gradient({
            ["0"]   = { Color = hex(a), Transparency = 0 },
            ["100"] = { Color = hex(b), Transparency = 0 },
        }, { Rotation = rot })
    end

    local palettes = {
        { name = "Pink",      bg = { "#1A0A14", "#2B0D22" }, panel = { "#1F0C19", "#2A1024" }, accent = { "#F472B6", "#DB2777" }, text = "#FFEAF5", muted = "#C98BAE", icon = "#F9A8D4", element = "#2A1222", hover = "#3A1830" },
        { name = "Yellow",    bg = { "#15120A", "#221A06" }, panel = { "#1A160B", "#241D0A" }, accent = { "#FACC15", "#CA8A04" }, text = "#FFF9E0", muted = "#C9B77A", icon = "#FDE68A", element = "#262011", hover = "#332B16" },
        { name = "White",     bg = { "#FAFAFA", "#E9E9EE" }, panel = { "#FFFFFF", "#F4F4F5" }, accent = { "#27272A", "#71717A" }, text = "#09090B", muted = "#71717A", icon = "#3F3F46", element = "#FFFFFF", hover = "#F1F1F3", light = true },
        { name = "Black",     bg = { "#000000", "#0A0A0A" }, panel = { "#050505", "#0D0D0D" }, accent = { "#FFFFFF", "#71717A" }, text = "#FFFFFF", muted = "#8A8A8A", icon = "#D4D4D8", element = "#111111", hover = "#1C1C1C" },
        { name = "Orange",    bg = { "#170C05", "#261206" }, panel = { "#1C0F07", "#26150A" }, accent = { "#FB923C", "#EA580C" }, text = "#FFF1E6", muted = "#C9977A", icon = "#FDBA74", element = "#28170C", hover = "#361F11" },
        { name = "Lime",      bg = { "#0A1306", "#122008" }, panel = { "#0D1709", "#13210B" }, accent = { "#A3E635", "#16A34A" }, text = "#F1FFE6", muted = "#9DBB82", icon = "#BEF264", element = "#16220F", hover = "#1F2E15" },
        { name = "Cyan",      bg = { "#051317", "#072029" }, panel = { "#07171C", "#0A2029" }, accent = { "#22D3EE", "#0891B2" }, text = "#E6FCFF", muted = "#7FB3BF", icon = "#67E8F9", element = "#0E222A", hover = "#142E38" },
        { name = "Ocean",     bg = { "#050B1A", "#0A1733" }, panel = { "#08101F", "#0C1730" }, accent = { "#60A5FA", "#2563EB" }, text = "#E8F0FF", muted = "#8497C9", icon = "#93C5FD", element = "#101B33", hover = "#172545" },
        { name = "Grape",     bg = { "#0F0719", "#1C0D33" }, panel = { "#130A1F", "#1B0F2E" }, accent = { "#C084FC", "#7C3AED" }, text = "#F5EDFF", muted = "#A68CC9", icon = "#D8B4FE", element = "#1D1230", hover = "#281A42" },
        { name = "Mint",      bg = { "#06130E", "#0A2019" }, panel = { "#081711", "#0B2018" }, accent = { "#6EE7B7", "#10B981" }, text = "#E9FFF6", muted = "#86BFA8", icon = "#A7F3D0", element = "#0F2219", hover = "#152E23" },
        { name = "Lavender",  bg = { "#0F0C1A", "#1A1530" }, panel = { "#131020", "#1A162D" }, accent = { "#DDD6FE", "#A78BFA" }, text = "#F4F1FF", muted = "#A59CC9", icon = "#C4B5FD", element = "#1C1830", hover = "#262040" },
        { name = "Sunset",    bg = { "#170812", "#260A14" }, panel = { "#1B0B14", "#240D18" }, accent = { "#FB923C", "#EC4899" }, text = "#FFEFEA", muted = "#C98E9A", icon = "#FDA4AF", element = "#2A1220", hover = "#38182A" },
        { name = "Synthwave", bg = { "#12061F", "#07142A" }, panel = { "#150A24", "#0B1530" }, accent = { "#FF2BD6", "#22D3EE" }, text = "#F9EDFF", muted = "#A38CC9", icon = "#F0ABFC", element = "#1E1233", hover = "#2A1A45" },
        { name = "Ice",       bg = { "#08111A", "#0E1B29" }, panel = { "#0B141F", "#101C2A" }, accent = { "#E0F2FE", "#38BDF8" }, text = "#F0F9FF", muted = "#8FB0C9", icon = "#BAE6FD", element = "#13202E", hover = "#1B2C3D" },
    }

    for _, p in ipairs(palettes) do
        local a1, a2 = p.accent[1], p.accent[2]
        local theme = {
            Name = p.name,
            Accent = grad(p.panel[1], p.panel[2], 90),
            Dialog = grad(p.panel[1], p.panel[2], 90),
            Background = grad(p.bg[1], p.bg[2], 135),
            Text = hex(p.text),
            Placeholder = hex(p.muted),
            Icon = hex(p.icon),
            Button = grad(a1, a2, 45),
            Toggle = grad(a1, a2, 45),
            Checkbox = grad(a1, a2, 45),
            Slider = hex(a1),
            Primary = hex(a1),
            WindowOutline = WindUI:Gradient({
                ["0"]   = { Color = hex(a1), Transparency = 0 },
                ["50"]  = { Color = hex(a2), Transparency = 0 },
                ["100"] = { Color = hex(a1), Transparency = 0 },
            }, { Rotation = 45 }),
            SliderIcon = hex(p.muted),
            TabBackgroundActive = hex(a1),
            TabBackgroundActiveTransparency = p.light and 0.75 or 0.82,
            TabBackgroundHover = hex(a1),
            TabBackgroundHoverTransparency = p.light and 0.88 or 0.92,
            PanelBackground = hex(p.light and "#000000" or "#FFFFFF"),
            PanelBackgroundTransparency = 0.95,
            ElementBackground = hex(p.element),
            ElementBackgroundTransparency = 0,
            ElementBackgroundHover = hex(p.hover),
            NotificationBorder = hex(a1),
            NotificationBorderTransparency = 0.7,
        }
        if p.light then
            theme.TabBackground = hex("#FFFFFF")
            theme.LabelBackground = hex("#FFFFFF")
            theme.LabelBackgroundTransparency = 0
        end
        pcall(function() WindUI:AddTheme(theme) end)
    end
end)()

task.wait()
if setthreadidentity then pcall(setthreadidentity, 8) end

local Window = WindUI:CreateWindow({
    Title = "zaml",

    Icon = (function()
        for _, path in ipairs({ "zaml/zaml.png", "zaml.png" }) do
            if isfile and isfile(path) then
                local ok, a = pcall(getcustomasset, path)
                if ok and a then return a end
            end
        end
        return "crosshair"
    end)(),
    IconSize = 38,
    Author = "by amaz",
    Folder = "zaml",
    Size = (function()
        local w, h = 900, 560
        pcall(function()
            if isfile and isfile("zaml/window.json") then
                local d = game:GetService("HttpService"):JSONDecode(readfile("zaml/window.json"))
                if tonumber(d.w) and tonumber(d.h) then w, h = math.max(d.w, 420), math.max(d.h, 260) end
            end
        end)
        return UDim2.fromOffset(w, h)
    end)(),
    MinSize = Vector2.new(420, 260),
    MaxSize = Vector2.new(8192, 8192),
    Theme = "Aurora",
    Transparent = true,
    Acrylic = false,

    OutlineTransparency = 0,
    OutlineThickness = 5,
    OutlineAnimated = true,
    OutlineSpeed = 90,
    SideBarWidth = 200,
    HideSearchBar = false,
    ScrollBarEnabled = true,
    ToggleKey = Enum.KeyCode.K,
    NewElements = false,
    OpenButton = {
        Title = "zaml",
        Enabled = true,
        OnlyMobile = true,
        DragHandle = false,
        IconSize = 30,
        StrokeThickness = 5,
        OutlineAnimated = true,
        OutlineSpeed = 90,
    },
})
Window:SetPanelBackground(false)
Window:OnDestroy(function() hub.unload() end)
task.wait()
if setthreadidentity then pcall(setthreadidentity, 8) end

pcall(function()
    local old, new = "WindUI/zaml/config/Zamltra.json", "WindUI/zaml/config/default.json"
    if isfile and isfile(old) and not isfile(new) then writefile(new, readfile(old)) end
end)

pcall(function()
    local path = "WindUI/zaml/config/default.json"
    if not (isfile and isfile(path)) then return end
    local data = game:GetService("HttpService"):JSONDecode(readfile(path))
    local saved = (data.__elements or data).theme
    local name = type(saved) == "table" and saved.value
    if type(name) == "table" then name = name[1] end
    if type(name) == "string" and name ~= WindUI:GetCurrentTheme() then WindUI:SetTheme(name) end
end)

local Config
pcall(function()
    Config = Window.ConfigManager:CreateConfig("default")
    if Config then Config:SetAsCurrent() end
end)

local currentConfig     = Config
local currentConfigName = "default"
local doLoadConfig, doSaveConfig, doDeleteConfig

--!luaq:no_virtualize
local function listConfigNames()
    local ok, list = pcall(function() return Window.ConfigManager:AllConfigs() end)
    list = (ok and type(list) == "table") and list or {}
    local has = false
    for _, n in ipairs(list) do if n == currentConfigName then has = true break end end
    if not has then table.insert(list, currentConfigName) end
    table.sort(list)
    return list
end
local bindManager
;(function()
    local UIS = game:GetService("UserInputService")
    local TweenService = game:GetService("TweenService")
    local TextService = game:GetService("TextService")
    local HttpService = game:GetService("HttpService")
    local WHITE = Color3.fromRGB(255, 255, 255)

    local binds = {}
    local registry = {}
    local order = {}
    local heldKeys = {}
    local activePopup
    local hoveredName
    local alias = {}

    --!luaq:no_virtualize
    local function keyName(input)
        if input.UserInputType == Enum.UserInputType.Keyboard then
            if input.KeyCode == Enum.KeyCode.Unknown then return nil end
            return input.KeyCode.Name
        elseif input.UserInputType == Enum.UserInputType.MouseButton1 then return "MouseLeft"
        elseif input.UserInputType == Enum.UserInputType.MouseButton2 then return "MouseRight"
        elseif input.UserInputType == Enum.UserInputType.MouseButton3 then return "MouseMiddle"
        end
        return nil
    end

    local list = WindUI:Panel({
        Name = "ZamltraKeybinds", Title = "keybinds", TitleColor = WHITE,
        OutlineThickness = 5,
        Size = UDim2.fromOffset(160, 80),
        Position = UDim2.new(0, 16, 0.5, -80), AnchorPoint = Vector2.new(0, 0),
        Visible = false,
    })

    do
        local POS_FILE = "zaml/keybinds_position.json"
        pcall(function()
            if not (isfile and isfile(POS_FILE)) then return end
            local p = HttpService:JSONDecode(readfile(POS_FILE))
            if type(p) ~= "table" or not (tonumber(p.xs) and tonumber(p.xo) and tonumber(p.ys) and tonumber(p.yo)) then return end
            local vp = workspace.CurrentCamera.ViewportSize
            local x = math.clamp(p.xs * vp.X + p.xo, 0, math.max(0, vp.X - 60))
            local y = math.clamp(p.ys * vp.Y + p.yo, 0, math.max(0, vp.Y - 40))
            list.Frame.Position = UDim2.fromOffset(x, y)
        end)
        local saveGen = 0
        hub.connect(list.Frame:GetPropertyChangedSignal("Position"), function()
            saveGen = saveGen + 1
            local mine = saveGen
            task.delay(0.4, function()
                if mine ~= saveGen or not writefile then return end
                local pos = list.Frame.Position
                pcall(function()
                    if isfolder and makefolder and not isfolder("zaml") then makefolder("zaml") end
                    writefile(POS_FILE, HttpService:JSONEncode({
                        xs = pos.X.Scale, xo = pos.X.Offset, ys = pos.Y.Scale, yo = pos.Y.Offset,
                    }))
                end)
            end)
        end)
    end

    hub.onUnload(function()
        if activePopup then pcall(function() activePopup:Destroy() end) end
        pcall(function() list:Destroy() end)
    end)
    local layout = Instance.new("UIListLayout")
    layout.Padding = UDim.new(0, 4); layout.SortOrder = Enum.SortOrder.LayoutOrder
    layout.Parent = list.Content
    local tpad = Instance.new("UIPadding"); tpad.PaddingTop = UDim.new(0, 6); tpad.Parent = list.Content
    --!luaq:no_virtualize
    local function textW(t, s, f) return TextService:GetTextSize(t, s, f, Vector2.new(1000, 100)).X end

    local rows = {}
    --!luaq:no_virtualize
    local function getRow(i)
        if rows[i] then return rows[i] end
        local row = Instance.new("Frame")
        row.Size = UDim2.new(1, 0, 0, 18); row.BackgroundTransparency = 1
        row.LayoutOrder = i; row.Parent = list.Content
        local label = Instance.new("TextLabel")
        label.Size = UDim2.new(1, -56, 1, 0); label.BackgroundTransparency = 1
        label.Font = Enum.Font.GothamBold; label.TextSize = 14; label.TextColor3 = WHITE
        label.TextXAlignment = Enum.TextXAlignment.Left; label.Parent = row
        local key = Instance.new("TextLabel")
        key.Size = UDim2.new(0, 56, 1, 0); key.Position = UDim2.new(1, -56, 0, 0)
        key.BackgroundTransparency = 1; key.Font = Enum.Font.GothamBold; key.TextSize = 14; key.TextColor3 = WHITE
        key.TextXAlignment = Enum.TextXAlignment.Right; key.Parent = row
        rows[i] = { row = row, label = label, key = key }
        return rows[i]
    end

    --!luaq:no_virtualize
    local function activeBinds()
        local res = {}
        for _, name in ipairs(order) do
            local b, reg = binds[name], registry[name]
            if b and reg then
                local on
                if b.mode == "Always" then on = true
                elseif b.mode == "Hold" then on = heldKeys[name] == true
                else on = reg.isActive and reg.isActive() or false end
                if on then
                    res[#res + 1] = { name = reg.title or name, key = (b.mode == "Always") and "ON" or b.key }
                end
            end
        end
        return res
    end

    --!luaq:no_virtualize
    local function listStroke() return list.Frame:FindFirstChildOfClass("UIStroke") end

    local listShown = false
    local animGen = 0
    local activeTweens = {}
    --!luaq:no_virtualize
    local function cancelTweens()
        for _, tw in ipairs(activeTweens) do pcall(function() tw:Cancel() end) end
        activeTweens = {}
    end
    --!luaq:no_virtualize
    local function play(obj, dur, props, style, dir)
        if not obj then return nil end
        local tw = TweenService:Create(obj,
            TweenInfo.new(dur, style or Enum.EasingStyle.Quint, dir or Enum.EasingDirection.Out), props)
        activeTweens[#activeTweens + 1] = tw
        tw:Play()
        return tw
    end
    --!luaq:no_virtualize
    local function resetVisuals()
        list.Frame.BackgroundTransparency = 0.1
        local st = listStroke(); if st then st.Transparency = 0 end
        if list.Title then list.Title.TextTransparency = 0 end
    end

    --!luaq:no_virtualize
    local function refresh()
        local entries = (showKeybindList ~= false) and activeBinds() or {}

        if #entries == 0 then
            if listShown then
                listShown = false
                animGen = animGen + 1
                local myGen = animGen
                cancelTweens()
                for i = 1, #rows do rows[i].row.Visible = false end
                if list.Title then play(list.Title, 0.12, { TextTransparency = 1 }) end
                play(list.Frame, 0.22, { BackgroundTransparency = 1 })
                local st = listStroke(); if st then play(st, 0.22, { Transparency = 1 }) end
                local t = play(list.Frame, 0.28, { Size = UDim2.fromOffset(0, 0) },
                    Enum.EasingStyle.Exponential, Enum.EasingDirection.InOut)
                if t then
                    t.Completed:Once(function() if myGen == animGen then list:SetVisible(false) end end)
                else
                    list:SetVisible(false)
                end
            end
            return
        end

        for i = 1, #rows do rows[i].row.Visible = false end
        local maxW = textW("Keybinds", 16, Enum.Font.GothamBold)
        for i, e in ipairs(entries) do
            local r = getRow(i); r.row.Visible = true
            r.label.Text = e.name; r.label.TextColor3 = WHITE
            r.key.Text = "[" .. e.key .. "]"; r.key.TextColor3 = WHITE
            maxW = math.max(maxW, textW(e.name, 14, Enum.Font.GothamBold) + 20 + textW("[" .. e.key .. "]", 14, Enum.Font.GothamBold))
        end
        local w = math.clamp(maxW + 28, 130, 340)
        local h = 28 + 6 + #entries * 22 + 8

        animGen = animGen + 1
        cancelTweens()
        if not listShown then
            listShown = true
            list:SetVisible(true)
            resetVisuals()
            list.Frame.Size = UDim2.fromOffset(w, 0)
        else
            resetVisuals()
        end
        play(list.Frame, 0.2, { Size = UDim2.fromOffset(w, h) })
    end

    --!luaq:no_virtualize
    local function saveBinds(persist)
        pcall(function()
            local c = currentConfig or Config
            if not c then return end
            c:Set("zamlBinds", HttpService:JSONEncode(binds))
            if persist ~= false then c:Save() end
        end)
    end

    --!luaq:no_virtualize
    local function setBind(name, key, mode)
        binds[name] = { key = key, mode = mode }
        local reg = registry[name]
        if reg and mode == "Always" and reg.kind == "toggle" then reg.setState(true) end
        saveBinds(); refresh()
    end
    --!luaq:no_virtualize
    local function clearBind(name)
        binds[name] = nil; heldKeys[name] = nil
        saveBinds(); refresh()
    end

    local captureConn
    local capturing = false
    local popGui
    --!luaq:no_virtualize
    local function popupGui()
        if popGui and popGui.Parent then return popGui end
        if setthreadidentity then pcall(setthreadidentity, 8) end
        popGui = Instance.new("ScreenGui")
        popGui.Name = "ZamltraBindPopup"
        popGui.IgnoreGuiInset = true
        popGui.ResetOnSpawn = false
        popGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling
        popGui.DisplayOrder = 2147483025
        popGui.Parent = (gethui and gethui()) or game:GetService("CoreGui")
        return popGui
    end
    hub.onUnload(function() if popGui then pcall(function() popGui:Destroy() end) end end)

    local GuiService = game:GetService("GuiService")
    --!luaq:no_virtualize
    local function mouseInGui()
        return UIS:GetMouseLocation() - GuiService:GetGuiInset()
    end
    --!luaq:no_virtualize
    local function inside(obj, p)
        if not (obj and obj.Parent and obj.Visible) then return false end
        local a, sz = obj.AbsolutePosition, obj.AbsoluteSize
        return p.X >= a.X and p.X <= a.X + sz.X and p.Y >= a.Y and p.Y <= a.Y + sz.Y
    end

    local Creator = WindUI.Creator
    local FONT = (Creator and Creator.Font) or "rbxassetid://12187365364"
    --!luaq:no_virtualize
    local function themed(key, fallback)
        local ok, v = pcall(function() return Creator.GetThemeProperty(key, WindUI.Theme) end)
        if ok then
            if typeof(v) == "Color3" then return v end
            if type(v) == "table" and typeof(v.Color) == "ColorSequence" then return v.Color.Keypoints[1].Value, v end
        end
        return fallback
    end
    --!luaq:no_virtualize
    local function chevron(parent)
        local ok, ic = pcall(function() return Creator.Icon("chevron-down") end)
        if not (ok and type(ic) == "table" and ic[1]) then return nil end
        local img = Instance.new("ImageLabel")
        img.BackgroundTransparency = 1
        img.Image = ic[1]
        img.ImageRectSize = ic[2].ImageRectSize
        img.ImageRectOffset = ic[2].ImageRectPosition
        img.Size = UDim2.fromOffset(14, 14)
        img.AnchorPoint = Vector2.new(1, 0.5)
        img.Position = UDim2.new(1, -7, 0.5, 0)
        img.Parent = parent
        return img
    end

    local POP_W, POP_H, PAD, BOX_H = 158, 36, 5, 26
    local KEY_W = 64
    local MODE_W = POP_W - KEY_W - PAD * 3
    local MODES = { "Hold", "Toggle" }

    --!luaq:no_virtualize
    local function showPopup(name)
        if activePopup then pcall(function() activePopup:Destroy() end); activePopup = nil end
        if captureConn then captureConn:Disconnect(); captureConn = nil end
        capturing = false
        local reg = registry[name]
        local target = reg and reg.frame
        if typeof(target) ~= "Instance" then return end

        local text = themed("Text", WHITE)
        local muted = themed("Placeholder", Color3.fromRGB(160, 160, 170))
        local accent = themed("Primary", Color3.fromRGB(129, 140, 248))
        local element = themed("ElementBackground", Color3.fromRGB(30, 30, 38))
        local hover = themed("ElementBackgroundHover", element:Lerp(WHITE, 0.06))
        local bg, bgGrad = themed("Background", Color3.fromRGB(16, 16, 20))

        --!luaq:no_virtualize
        local function corner(obj, r) local c = Instance.new("UICorner"); c.CornerRadius = UDim.new(0, r); c.Parent = obj end
        --!luaq:no_virtualize
        local function stroke(obj, color, t, thick)
            local st = Instance.new("UIStroke")
            st.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
            st.Color, st.Transparency, st.Thickness = color, t, thick or 1
            st.Parent = obj
            return st
        end
        --!luaq:no_virtualize
        local function backdrop(obj)
            obj.BackgroundColor3 = bg
            obj.BackgroundTransparency = 0.02
            if bgGrad then
                local g = Instance.new("UIGradient")
                g.Color = bgGrad.Color
                g.Rotation = tonumber(bgGrad.Rotation) or 90
                g.Parent = obj
            end
        end
        --!luaq:no_virtualize
        local function label(parent, str, weight)
            local l = Instance.new("TextLabel")
            l.BackgroundTransparency = 1
            l.FontFace = Font.new(FONT, weight or Enum.FontWeight.SemiBold)
            l.TextSize = 14
            l.TextColor3 = text
            l.Text = str
            l.TextTruncate = Enum.TextTruncate.AtEnd
            l.Parent = parent
            return l
        end
        --!luaq:no_virtualize
        local function box(parent, x, w)
            local b = Instance.new("TextButton")
            b.AutoButtonColor = false
            b.Text = ""
            b.BorderSizePixel = 0
            b.BackgroundColor3 = element
            b.Position = UDim2.fromOffset(x, PAD)
            b.Size = UDim2.fromOffset(w, BOX_H)
            b.Parent = parent
            corner(b, 8)
            hub.connect(b.MouseEnter, function() b.BackgroundColor3 = hover end)
            hub.connect(b.MouseLeave, function() b.BackgroundColor3 = element end)
            return b
        end

        local pop = Instance.new("Frame")
        pop.Name = "Popup"
        pop.Size = UDim2.fromOffset(POP_W, POP_H)
        pop.BorderSizePixel = 0
        pop.Active = true
        backdrop(pop)
        corner(pop, 11)
        stroke(pop, accent, 0.55, 1.2)

        local mode = (binds[name] and binds[name].mode == "Hold") and "Hold" or "Toggle"
        --!luaq:no_virtualize
        local function keyText()
            local cur = binds[name]
            if not cur then return "none" end
            if cur.mode == "Always" then return "always" end
            return tostring(cur.key):lower()
        end

        local keyBox = box(pop, PAD, KEY_W)
        local keyStroke = stroke(keyBox, accent, 1, 1.4)
        local keyLabel = label(keyBox, keyText())
        keyLabel.Size = UDim2.fromScale(1, 1)
        --!luaq:no_virtualize
        local function showKey()
            keyLabel.Text = keyText()
            keyLabel.TextColor3 = binds[name] and text or muted
        end
        showKey()

        local modeBox = box(pop, PAD * 2 + KEY_W, MODE_W)
        local modeLabel = label(modeBox, mode:lower())
        modeLabel.TextXAlignment = Enum.TextXAlignment.Left
        modeLabel.Position = UDim2.fromOffset(9, 0)
        modeLabel.Size = UDim2.new(1, -30, 1, 0)
        local chev = chevron(modeBox)
        if chev then chev.ImageColor3 = text end

        local ITEM_H = 24
        local menu = Instance.new("Frame")
        menu.Position = UDim2.fromOffset(PAD * 2 + KEY_W, POP_H + 4)
        menu.Size = UDim2.fromOffset(MODE_W, #MODES * ITEM_H + (#MODES - 1) * 2 + 8)
        menu.BorderSizePixel = 0
        menu.Visible = false
        menu.Active = true
        menu.Parent = pop
        backdrop(menu)
        corner(menu, 10)
        stroke(menu, accent, 0.55, 1.2)

        local items = {}
        --!luaq:no_virtualize
        local function paintItems()
            for m, it in pairs(items) do
                local on = (m == mode)
                it.btn.BackgroundColor3 = on and accent or hover
                it.btn.BackgroundTransparency = on and 0.8 or (it.hot and 0.4 or 1)
                it.lbl.TextTransparency = on and 0 or 0.4
            end
        end
        for k, m in ipairs(MODES) do
            local b = Instance.new("TextButton")
            b.AutoButtonColor = false
            b.Text = ""
            b.BorderSizePixel = 0
            b.Position = UDim2.fromOffset(4, 4 + (k - 1) * (ITEM_H + 2))
            b.Size = UDim2.new(1, -8, 0, ITEM_H)
            b.Parent = menu
            corner(b, 7)
            local l = label(b, m:lower(), Enum.FontWeight.Medium)
            l.TextXAlignment = Enum.TextXAlignment.Left
            l.Position = UDim2.fromOffset(8, 0)
            l.Size = UDim2.new(1, -8, 1, 0)
            local it = { btn = b, lbl = l, hot = false }
            items[m] = it
            hub.connect(b.MouseEnter, function() it.hot = true; paintItems() end)
            hub.connect(b.MouseLeave, function() it.hot = false; paintItems() end)
            hub.connect(b.MouseButton1Click, function()
                mode = m
                modeLabel.Text = m:lower()
                menu.Visible = false
                if chev then chev.Rotation = 0 end
                paintItems()
                local cur = binds[name]
                if cur and cur.mode ~= m and cur.key ~= "ON" then setBind(name, cur.key, m) end
            end)
        end
        paintItems()
        hub.connect(modeBox.MouseButton1Click, function()
            menu.Visible = not menu.Visible
            if chev then chev.Rotation = menu.Visible and 180 or 0 end
        end)

        local followConn, outside
        --!luaq:no_virtualize
        local function stopCapture()
            capturing = false
            if captureConn then captureConn:Disconnect(); captureConn = nil end
            keyStroke.Transparency = 1
        end
        --!luaq:no_virtualize
        local function closePopup()
            stopCapture()
            if followConn then followConn:Disconnect(); followConn = nil end
            if outside then outside:Disconnect(); outside = nil end
            if activePopup == pop then activePopup = nil end
            pcall(function() pop:Destroy() end)
        end

        hub.connect(keyBox.MouseButton1Click, function()
            if capturing then stopCapture(); showKey(); return end
            menu.Visible = false
            if chev then chev.Rotation = 0 end
            capturing = true
            keyLabel.Text = "..."
            keyLabel.TextColor3 = text
            keyStroke.Transparency = 0.1
            if captureConn then captureConn:Disconnect() end

            captureConn = hub.connect(UIS.InputBegan, function(input)
                local t = input.UserInputType
                if t == Enum.UserInputType.Keyboard then
                    if input.KeyCode == Enum.KeyCode.Escape or input.KeyCode == Enum.KeyCode.Backspace then
                        clearBind(name)
                    else
                        local kn = keyName(input)
                        if not kn then return end
                        setBind(name, kn, mode)
                    end
                elseif t == Enum.UserInputType.MouseButton2 or t == Enum.UserInputType.MouseButton3 then
                    setBind(name, keyName(input), mode)
                else
                    return
                end
                stopCapture()
                showKey()
            end)
        end)

        local gui = popupGui()
        pop.Parent = gui
        activePopup = pop

        --!luaq:no_virtualize
        local function place()
            if not (target.Parent and pop.Parent) then closePopup(); return end
            local origin = gui.AbsolutePosition
            local view = gui.AbsoluteSize
            local a, sz = target.AbsolutePosition, target.AbsoluteSize
            local x = a.X + sz.X + 8
            if x + POP_W > origin.X + view.X - 4 then x = a.X - POP_W - 8 end
            local y = a.Y + (sz.Y - POP_H) / 2
            pop.Position = UDim2.fromOffset(x - origin.X, y - origin.Y)
        end
        place()
        followConn = hub.connect(RunService.RenderStepped, place)

        outside = hub.connect(UIS.InputBegan, function(input)
            if activePopup ~= pop then closePopup(); return end
            local t = input.UserInputType
            if t ~= Enum.UserInputType.MouseButton1 and t ~= Enum.UserInputType.MouseButton2 then return end
            if capturing and t == Enum.UserInputType.MouseButton2 then return end
            local p = mouseInGui()
            if not inside(pop, p) and not inside(menu, p) then closePopup() end
        end)
    end

    hub.connect(UIS.InputBegan, function(input)
        if input.UserInputType == Enum.UserInputType.MouseButton3 and hoveredName and not capturing then
            showPopup(hoveredName)
        end
    end)

    hub.connect(UIS.InputBegan, function(input, gp)
        if capturing or UIS:GetFocusedTextBox() then return end
        if gp and input.UserInputType ~= Enum.UserInputType.Keyboard then return end
        local kn = keyName(input)
        if not kn then return end
        for name, b in pairs(binds) do
            if b.key == kn and b.mode ~= "Always" then
                local reg = registry[name]
                if reg then
                    if b.mode == "Toggle" then
                        if reg.kind == "toggle" then reg.setState(not reg.isActive()) else reg.fire() end
                        refresh()
                    elseif b.mode == "Hold" then
                        heldKeys[name] = true
                        if reg.kind == "toggle" then reg.setState(true) else reg.fire() end
                        refresh()
                    end
                end
            end
        end
    end)
    hub.connect(UIS.InputEnded, function(input)
        local kn = keyName(input)
        if not kn then return end
        for name, b in pairs(binds) do
            if b.key == kn and b.mode == "Hold" and heldKeys[name] then
                heldKeys[name] = false
                local reg = registry[name]
                if reg and reg.kind == "toggle" then reg.setState(false) end
                refresh()
            end
        end
    end)

    local lastPoll = 0
    hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function()
        if activePopup and (Window.Closed or Window.Destroyed) then
            if captureConn then captureConn:Disconnect(); captureConn = nil end
            pcall(function() activePopup:Destroy() end)
            activePopup = nil
        end
        for name, b in pairs(binds) do
            local reg = registry[name]
            if reg then
                if b.mode == "Always" then
                    if reg.kind == "toggle" then if reg.isActive and not reg.isActive() then reg.setState(true) end
                    elseif reg.fire then reg.fire() end
                elseif b.mode == "Hold" and heldKeys[name] and reg.kind == "button" and reg.fire then
                    reg.fire()
                end
            end
        end
        if os.clock() - lastPoll >= 0.3 then lastPoll = os.clock(); refresh() end
    end))

    bindManager = {}
    bindManager.register = LUAQ_NO_VIRTUALIZE(function(name, handle, opts)
        if type(handle) == "table" then
            if opts.auto then
                handle.__zbAuto = name
            elseif handle.__zbAuto and handle.__zbAuto ~= name then

                local old = handle.__zbAuto
                alias[old] = name
                registry[old] = nil
                for i = #order, 1, -1 do
                    if order[i] == old then table.remove(order, i) end
                end
            end
        end
        registry[name] = {
            frame = handle and handle.ElementFrame,
            kind = opts.kind, setState = opts.setState, isActive = opts.isActive,
            fire = opts.fire, title = opts.title or name,
        }
        order[#order + 1] = name
        if handle and handle.ElementFrame then
            local f = handle.ElementFrame
            hub.connect(f.MouseEnter, function() hoveredName = alias[name] or name end)
            hub.connect(f.MouseLeave, function()
                if hoveredName == name or hoveredName == alias[name] then hoveredName = nil end
            end)
        end
    end)
    bindManager.loadBinds = LUAQ_NO_VIRTUALIZE(function()
        local loaded = {}
        pcall(function()
            local c = currentConfig or Config
            if c then
                local s = c:Get("zamlBinds")
                if s and s ~= "" then
                    local decoded = HttpService:JSONDecode(s)
                    if type(decoded) == "table" then loaded = decoded end
                end
            end
        end)
        binds = loaded
        table.clear(heldKeys)
        for name, b in pairs(binds) do
            if b.mode == "Always" then
                local reg = registry[name]
                if reg and reg.kind == "toggle" and reg.setState then reg.setState(true) end
            end
        end
        refresh()
    end)
    bindManager.refresh = LUAQ_NO_VIRTUALIZE(function() refresh() end)
    bindManager.saveBinds = LUAQ_NO_VIRTUALIZE(function(persist) saveBinds(persist) end)
end)()

do
    local UIS = game:GetService("UserInputService")
    local TextService = game:GetService("TextService")
    local HttpService = game:GetService("HttpService")

    local METHODS = { "Toggle", "Slider", "Dropdown", "Colorpicker", "Input", "Button", "Keybind",
        "Section", "Paragraph", "Divider", "Space", "Code", "Image" }
    local INFO = { Toggle = true, Slider = true, Dropdown = true, Colorpicker = true, Input = true,
        Button = true, Keybind = true }
    local WEIGHT = { Toggle = 1, Button = 1, Slider = 1.5, Dropdown = 1.2, Colorpicker = 1, Input = 1.2,
        Keybind = 1, Section = 1, Paragraph = 2 }
    local NARROW = 440

    local mainFrame = Window.UIElements and Window.UIElements.Main
    local gui = mainFrame and mainFrame:FindFirstAncestorOfClass("ScreenGui")

    local tip = Instance.new("Frame")
    tip.Name = "ZamltraTip"
    tip.BackgroundColor3 = Color3.fromRGB(13, 13, 17)
    tip.BackgroundTransparency = 0.04
    tip.BorderSizePixel = 0
    tip.Visible = false
    tip.ZIndex = 100000
    tip.Parent = gui
    Instance.new("UICorner", tip).CornerRadius = UDim.new(0, 6)
    local tipStroke = Instance.new("UIStroke", tip)
    tipStroke.Color = Color3.new(1, 1, 1)
    tipStroke.Transparency = 0.8
    local tipLabel = Instance.new("TextLabel")
    tipLabel.BackgroundTransparency = 1
    tipLabel.Position = UDim2.fromOffset(8, 6)
    tipLabel.Font = Enum.Font.GothamMedium
    tipLabel.TextSize = 13
    tipLabel.TextColor3 = Color3.fromRGB(230, 230, 235)
    tipLabel.TextWrapped = true
    tipLabel.TextXAlignment = Enum.TextXAlignment.Left
    tipLabel.TextYAlignment = Enum.TextYAlignment.Top
    tipLabel.ZIndex = 100001
    tipLabel.Parent = tip
    hub.onUnload(function() tip:Destroy() end)

    local tipOwner
    --!luaq:no_virtualize
    local function showTip(owner, text)
        tipOwner = owner
        local size = TextService:GetTextSize(text, 13, Enum.Font.GothamMedium, Vector2.new(260, 1000))
        tipLabel.Text = text
        tipLabel.Size = UDim2.fromOffset(size.X + 2, size.Y + 2)
        tip.Size = UDim2.fromOffset(size.X + 18, size.Y + 14)
        tip.Visible = true
    end
    --!luaq:no_virtualize
    local function hideTip(owner)
        if tipOwner == owner then
            tipOwner = nil
            tip.Visible = false
        end
    end
    hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function()
        if not tip.Visible then return end
        if not (tipOwner and tipOwner:IsDescendantOf(game)) or Window.Closed then
            tipOwner, tip.Visible = nil, false
            return
        end
        local m = UIS:GetMouseLocation()
        local origin = gui and gui.AbsolutePosition or Vector2.new(0, 0)
        local inset = (gui and gui.IgnoreGuiInset) and Vector2.new(0, 0) or game:GetService("GuiService"):GetGuiInset()
        local vp = workspace.CurrentCamera.ViewportSize
        local x = math.min(m.X + 14, vp.X - tip.AbsoluteSize.X - 4)
        local y = math.min(m.Y + 16, vp.Y - tip.AbsoluteSize.Y - 4)
        tip.Position = UDim2.fromOffset(x - origin.X - inset.X, y - origin.Y - inset.Y)
    end))

    --!luaq:no_virtualize
    local function addInfo(frame, desc)
        local outer = frame:FindFirstChild("TitleFrame", true)
        local inner = outer and outer:FindFirstChild("TitleFrame")
        local title = inner and inner:FindFirstChildOfClass("TextLabel")
        if not title then return false end

        local pad = Instance.new("UIPadding")
        pad.PaddingLeft = UDim.new(0, 22)
        pad.Parent = title

        local icon = Instance.new("TextLabel")
        icon.Name = "Info"
        icon.Size = UDim2.fromOffset(15, 15)
        icon.Position = UDim2.fromOffset(-22, 1)
        icon.BackgroundTransparency = 1
        icon.Font = Enum.Font.GothamBold
        icon.TextSize = 11
        icon.Text = "i"
        icon.TextColor3 = title.TextColor3
        icon.TextTransparency = 0.25
        icon.Active = true
        icon.ZIndex = title.ZIndex + 1
        icon.Parent = title
        Instance.new("UICorner", icon).CornerRadius = UDim.new(1, 0)
        local ring = Instance.new("UIStroke", icon)
        ring.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
        ring.Thickness = 1.2
        ring.Color = title.TextColor3
        ring.Transparency = 0.45

        hub.connect(title:GetPropertyChangedSignal("TextColor3"), function()
            icon.TextColor3, ring.Color = title.TextColor3, title.TextColor3
        end)
        hub.connect(icon.MouseEnter, function()
            icon.TextTransparency, ring.Transparency = 0, 0.1
            showTip(icon, desc)
        end)
        hub.connect(icon.MouseLeave, function()
            icon.TextTransparency, ring.Transparency = 0.25, 0.45
            hideTip(icon)
        end)
        return true
    end

    local shaped = {}
    bindManager.shapeTab = LUAQ_NO_VIRTUALIZE(function(tab, tabTitle)
        if type(tab) ~= "table" or shaped[tab] then return tab end
        local st = { col = 1, weight = { 0, 0 } }
        shaped[tab] = st

        --!luaq:no_virtualize
        local function columns()
            if st.cols then return st.cols end
            local container = tab.UIElements and tab.UIElements.ContainerFrame
            if not container then return nil end
            local list = container:FindFirstChildOfClass("UIListLayout")
            if not list then return nil end
            local gap = list.Padding

            local holder = Instance.new("Frame")
            holder.Name = "ZbColumns"
            holder.BackgroundTransparency = 1
            holder.Size = UDim2.new(1, 0, 0, 0)
            holder.AutomaticSize = Enum.AutomaticSize.Y
            holder.LayoutOrder = -1
            holder.Parent = container
            local row = Instance.new("UIListLayout")
            row.FillDirection = Enum.FillDirection.Horizontal
            row.SortOrder = Enum.SortOrder.LayoutOrder
            row.Padding = UDim.new(0, 10)
            row.Parent = holder

            local cols = {}
            for i = 1, 2 do
                local c = Instance.new("Frame")
                c.Name = "Column" .. i
                c.BackgroundTransparency = 1
                c.AutomaticSize = Enum.AutomaticSize.Y
                c.LayoutOrder = i
                c.Parent = holder
                local l = Instance.new("UIListLayout")
                l.SortOrder = Enum.SortOrder.LayoutOrder
                l.Padding = gap
                l.Parent = c
                cols[i] = c
            end

            local narrow
            --!luaq:no_virtualize
            local function fit()
                local now = container.AbsoluteSize.X < NARROW
                if now == narrow then return end
                narrow = now
                row.FillDirection = now and Enum.FillDirection.Vertical or Enum.FillDirection.Horizontal
                for i = 1, 2 do
                    cols[i].Size = now and UDim2.new(1, 0, 0, 0) or UDim2.new(0.5, -5, 0, 0)
                end
            end
            fit()
            hub.connect(container:GetPropertyChangedSignal("AbsoluteSize"), fit)

            st.cols = cols
            return cols
        end

        for _, m in ipairs(METHODS) do
            local orig = tab[m]
            if type(orig) == "function" then
                tab[m] = function(self, cfg, ...)
                    local isCfg = type(cfg) == "table"
                    local desc
                    if isCfg and INFO[m] and type(cfg.Desc) == "string" and cfg.Desc ~= "" then
                        desc = cfg.Desc
                        cfg.Desc = nil
                    end

                    local state, userCb = false, isCfg and cfg.Callback or nil
                    if isCfg and m == "Toggle" then
                        state = cfg.Value == true
                        cfg.Callback = function(v, ...)
                            state = v == true
                            if userCb then return userCb(v, ...) end
                        end
                    end

                    local handle = orig(self, cfg, ...)
                    local frame = type(handle) == "table" and handle.ElementFrame

                    hub.breathe()
                    if typeof(frame) ~= "Instance" then return handle end

                    local cols = columns()
                    if cols then
                        if m == "Section" then
                            st.col = (st.weight[2] < st.weight[1]) and 2 or 1
                        end
                        st.weight[st.col] = st.weight[st.col] + (WEIGHT[m] or 1)
                        frame.Parent = cols[st.col]
                    end

                    if desc and not addInfo(frame, desc) then
                        pcall(function() handle:SetDesc(desc) end)
                    end

                    if m == "Colorpicker" and isCfg and type(userCb) == "function" and type(handle.Update) == "function" then
                        local origUpdate = handle.Update
                        handle.Update = function(self, color, transparency, ...)
                            local r = origUpdate(self, color, transparency, ...)
                            if typeof(color) == "Color3" then pcall(userCb, color, transparency) end
                            return r
                        end
                    end

                    if isCfg and type(cfg.Title) == "string" and (m == "Toggle" or m == "Button") then
                        local key = "auto:" .. (type(cfg.Flag) == "string" and cfg.Flag
                            or (tostring(tabTitle) .. "/" .. cfg.Title))
                        if m == "Toggle" then
                            bindManager.register(key, handle, {
                                auto = true, kind = "toggle", title = cfg.Title,
                                isActive = function() return state end,
                                setState = function(on)
                                    pcall(function() handle:Set(on) end)
                                    if state ~= on then cfg.Callback(on) end
                                end,
                            })
                        elseif type(userCb) == "function" then
                            bindManager.register(key, handle, {
                                auto = true, kind = "button", title = cfg.Title,
                                fire = function() userCb() end,
                            })
                        end
                    end
                    return handle
                end
            end
        end
        return tab
    end)

    hub.building = true
    hub.lastBreath = os.clock()
    hub.breathe = LUAQ_NO_VIRTUALIZE(function()
        if not hub.building or os.clock() - hub.lastBreath < 0.005 or not coroutine.isyieldable() then return end
        task.wait()
        if setthreadidentity then pcall(setthreadidentity, 8) end
        hub.lastBreath = os.clock()
    end)

    do
        local held
        --!luaq:no_virtualize
        local function cursorStep()
            local open = not hub.unloaded and not Window.Closed and not Window.Destroyed
                and mainFrame and mainFrame.Visible
            if open then
                if not held then held = { behavior = UIS.MouseBehavior, icon = UIS.MouseIconEnabled } end
                if UIS.MouseBehavior ~= Enum.MouseBehavior.Default then
                    held.behavior = UIS.MouseBehavior
                    UIS.MouseBehavior = Enum.MouseBehavior.Default
                end
                if not UIS.MouseIconEnabled then
                    held.icon = false
                    UIS.MouseIconEnabled = true
                end
            elseif held then
                UIS.MouseBehavior = held.behavior
                UIS.MouseIconEnabled = held.icon
                held = nil
            end
        end
        local bound = pcall(function()
            RunService:BindToRenderStep("ZamltraCursor", Enum.RenderPriority.Last.Value + 10, cursorStep)
        end)
        if not bound then hub.connect(RunService.RenderStepped, cursorStep) end
        hub.onUnload(function()
            pcall(function() RunService:UnbindFromRenderStep("ZamltraCursor") end)
            if held then
                pcall(function()
                    UIS.MouseBehavior = held.behavior
                    UIS.MouseIconEnabled = held.icon
                end)
                held = nil
            end
        end)

        if mainFrame then
            local modal = Instance.new("TextButton")
            modal.Name = "ZamltraModal"
            modal.Size = UDim2.fromOffset(0, 0)
            modal.BackgroundTransparency = 1
            modal.Text = ""
            modal.Modal = true
            modal.Parent = mainFrame
        end
    end

    local origTab = Window.Tab
    Window.Tab = function(self, cfg, ...)
        local tab = origTab(self, cfg, ...)
        return bindManager.shapeTab(tab, type(cfg) == "table" and cfg.Title or "?")
    end

    local grip
    if mainFrame then
        for _, d in ipairs(mainFrame:GetDescendants()) do
            if d:IsA("ImageLabel") and d.Image == "rbxassetid://120997033468887" then grip = d.Parent break end
        end
    end
    if grip then
        pcall(function() Window:IsResizable(false) end)
        local MIN_W, MIN_H = 420, 260
        local drag

        hub.connect(grip.InputBegan, function(input)
            if input.UserInputType ~= Enum.UserInputType.MouseButton1 or drag then return end
            drag = {
                mouse = UIS:GetMouseLocation(),
                w = mainFrame.Size.X.Offset, h = mainFrame.Size.Y.Offset,
                pos = mainFrame.Position, frozen = {},
            }
            local bar = Window.UIElements.MainBar
            if bar then
                for _, c in ipairs(bar:GetChildren()) do
                    if c:IsA("Frame") and not c.Visible then
                        drag.frozen[c] = c.Size
                        c.Size = UDim2.fromOffset(c.AbsoluteSize.X, c.AbsoluteSize.Y)
                    end
                end
            end
        end)

        hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function()
            if not drag then return end
            local m = UIS:GetMouseLocation()
            if m == drag.last then return end
            drag.last = m
            local vp = workspace.CurrentCamera.ViewportSize
            local w = math.clamp(drag.w + (m.X - drag.mouse.X), MIN_W, math.max(MIN_W, vp.X))
            local h = math.clamp(drag.h + (m.Y - drag.mouse.Y), MIN_H, math.max(MIN_H, vp.Y))
            mainFrame.Size = UDim2.fromOffset(w, h)

            mainFrame.Position = drag.pos + UDim2.fromOffset((w - drag.w) / 2, (h - drag.h) / 2)
            Window.Size = mainFrame.Size
        end))

        hub.connect(UIS.InputEnded, function(input)
            if input.UserInputType ~= Enum.UserInputType.MouseButton1 or not drag then return end
            for c, size in pairs(drag.frozen) do pcall(function() c.Size = size end) end
            drag = nil
            pcall(function()
                if isfolder and makefolder and not isfolder("zaml") then makefolder("zaml") end
                writefile("zaml/window.json", HttpService:JSONEncode({
                    w = mainFrame.Size.X.Offset, h = mainFrame.Size.Y.Offset,
                }))
            end)
        end)
    end
end

local UserInputService = game:GetService("UserInputService")
local TweenService     = game:GetService("TweenService")
local SoundService     = game:GetService("SoundService")
local HttpService      = game:GetService("HttpService")
local Debris           = game:GetService("Debris")

local Camera = workspace.CurrentCamera

local M
do
    local found = filtergc("table", { Keys = { "GetCurrentWeapon", "GetWeaponInventory", "GetModule" } }, false)
    local wc = found and found[1]
    M = wc and debug.getupvalue(wc.GetModule, 1)
    if type(M) ~= "table" or not M.Entities then
        return
    end
end

local WC         = M.WeaponController
local CC         = M.CharacterController
local CamCtl     = M.CameraController
local Entities   = M.Entities
local GameCfg    = M.GameConfiguration
local Bullet     = M.Bullet
local Enums      = M.Enums
local SimCamera  = M.Camera
local f32        = M.Math.f32
local GameStats  = ReplicatedStorage:WaitForChild("GameStats")

local lazySwaps = {}
--!luaq:no_virtualize
local function swapWhen(when, tbl, key, make)
    if type(tbl) ~= "table" or type(tbl[key]) ~= "function" then return end
    lazySwaps[#lazySwaps + 1] = { when = when, tbl = tbl, key = key, make = make }
end
--!luaq:no_virtualize
local function syncSwaps()
    for _, e in ipairs(lazySwaps) do
        local want = (not hub.unloaded) and e.when() and true or false
        if want and not e.mine then
            local orig = e.tbl[e.key]
            if type(orig) == "function" then
                e.orig, e.mine = orig, e.make(orig)
                e.tbl[e.key] = e.mine
            end
        elseif not want and e.mine then
            if e.tbl[e.key] == e.mine then e.tbl[e.key] = e.orig end
            e.orig, e.mine = nil, nil
        end
    end
end
hub.connect(RunService.Heartbeat, syncSwaps)
hub.onUnload(syncSwaps)

local S = {
    silentAim = false, fov = 120, showFov = true, fovColor = Color3.fromRGB(255, 255, 255),
    aimPart = "Head", wallCheck = true, teamCheck = true,
    trigger = false, triggerDelay = 0,
    assist = false, assistMode = "While Firing", assistFov = 80, assistStrength = 35, assistMouse = false,
    assistPart = "Head", assistWall = true, assistCircle = true, assistColor = Color3.fromRGB(120, 200, 255),
    noRecoil = false, noSpread = false,

    rage = false, autoFire = true, autowall = false, rageHitbox = "Head + Body", rageSelect = "Crosshair",
    preferBody = true, minDamage = 1, dmgOverride = false, minDamageOverride = 100, maxDist = 500, autoStop = true, hitChance = 35, autoScope = true, rageNoSpread = false,
    spreadGuard = true,
    aimSpeed = 14, aimSmooth = 50, turnCamera = false, rageRecoil = false, rageReaction = 120, rageShotDelay = 220,
    targetIndicator = true, ignoreFriends = false, rageFov = 180,
    autoReload = false, reloadAt = 0,

    aa = false, aaLeft = false, aaRight = false, aaBase = "Camera", aaYaw = "Backward", aaSpin = 20, aaJitter = 60, aaPitch = "Down",

    esp = false, espColor = Color3.fromRGB(255, 70, 70), espColorMode = "Enemy / Teammate", radarEsp = true,
    tColor = Color3.fromRGB(240, 190, 80), ctColor = Color3.fromRGB(90, 160, 255), espFade = 0.35,
    visCheck = false, visColor = Color3.fromRGB(120, 255, 120),
    showTeam = false, teamColor = Color3.fromRGB(90, 200, 255),
    dormant = false, dormantTime = 4, espDist = 3000,
    chams = true, chamsMode = "Glow", chamsOccluded = false, chamsFill = 0.6,
    box = false, boxStyle = "Corner", boxFill = false, hpBar = false, hpNum = true, armorBar = false,
    names = true, weaponText = false, flags = false, distText = true, textSize = 12,
    skeleton = false, headDot = false, snaplines = false, snapOrigin = "Bottom",
    arrows = false, arrowRadius = 220, arrowSize = 14,
    soundEsp = false, soundColor = Color3.fromRGB(255, 200, 90), soundBox = true, soundLife = 3,
    nametags = false,

    fovChanger = false, fovValue = 90, noZoom = false, noShake = false,
    noBorders = false, scopeStyle = "Line", scopeColor = Color3.fromRGB(170, 140, 255), scopeLen = 60, scopeGap = 12, scopeThick = 1,
    tp = false, tpDist = 8, tpHeight = 0.5, tpShoulder = 0, tpCollide = true, tpBody = "Camera", tpBodyRot = false,
    vmOn = false, vmX = 0, vmY = 0, vmZ = 0,
    vmChams = false, vmMaterial = "ForceField", vmColor = Color3.fromRGB(140, 110, 255), vmTransparency = 0,

    watermark = false, indicators = false, hudArrows = false, speedHud = false, hudColor = Color3.fromRGB(170, 140, 255),
    xhair = false, xhairColor = Color3.fromRGB(0, 255, 120), xhairLen = 6, xhairGap = 4, xhairThick = 2,
    xhairOutline = true, xhairT = false, dot = false, dotColor = Color3.fromRGB(255, 255, 255), dotSize = 4,

    hitMarker = false, hitColor = Color3.fromRGB(255, 255, 255), killColor = Color3.fromRGB(255, 60, 60),
    hitWhere = "Crosshair", hitAnim = "Fade", hitShape = "X", hitOutline = true, killScale = 1.4,
    hitDamage = false, hitRise = 0,
    hitTime = 0.45, hitSize = 10, hitGap = 4, hitThick = 2, dmgNumbers = false, dmgColor = Color3.fromRGB(255, 220, 90),
    killFx = false, killFxColor = Color3.fromRGB(255, 80, 120),
    tracer = false, tracerWidth = 0.08, tracerLife = 1, impact = false,
    tracerStyle = "Line", tracerFrom = "Gun", tracerRainbow = false, tracerOnlyHits = false,
    impactSize = 0.35, impactGlow = false,
    hitSound = false, hitSoundId = "rbxassetid://6607142036", hitVolume = 0.6,
    killSound = false, killSoundId = "rbxassetid://5043539486", killVolume = 1,

    bhop = false, strafe = false, strafeMode = "Rage", fastTurn = true, alignThreshold = 8,
    longJump = false, duckJump = false, airDuckTicks = 16,

    drops = false, dropColor = Color3.fromRGB(235, 235, 240), dropDist = 150, bomb = true,
    hitLogs = true,
}

local tracerColor = Color3.fromRGB(140, 110, 255)
local impactColor = Color3.fromRGB(255, 90, 160)
local tracerColorPicker, impactColorPicker
--!luaq:no_virtualize
local function syncGunFX() end

local rageWhitelist = {}

--!luaq:no_virtualize
local function normalizeId(id)
    id = tostring(id or "")
    if id:find("^rbxassetid://") then return id end
    local digits = id:match("%d+")
    return digits and ("rbxassetid://" .. digits) or nil
end

--!luaq:no_virtualize
local function playSound(id, volume)
    local sid = normalizeId(id)
    if not sid then return end
    local s = Instance.new("Sound")
    s.SoundId = sid
    s.Volume = volume or 1
    s.Parent = SoundService
    s:Play()
    Debris:AddItem(s, 6)
end

--!luaq:no_virtualize
local function wrap(a)
    return (a + math.pi) % (2 * math.pi) - math.pi
end

local overlay = Instance.new("ScreenGui")
overlay.Name = "ZamltraOverlay"
overlay.IgnoreGuiInset = true
overlay.ResetOnSpawn = false
overlay.DisplayOrder = 999
overlay.Parent = (gethui and gethui()) or game:GetService("CoreGui")
hub.onUnload(function() overlay:Destroy() end)

do
    local BASE = 2147483000
    local ORDER = {
        ["WindUI"] = BASE, ["WindUI/Dropdowns"] = BASE + 10,
        ["WindUI/Tooltips"] = BASE + 20, ["WindUI/Notifications"] = BASE + 30,
    }
    local saved = {}
    --!luaq:no_virtualize
    local function raise()
        local roots = { game:GetService("CoreGui") }
        if gethui then roots[2] = gethui() end
        for _, root in ipairs(roots) do
            for _, c in ipairs(root:GetChildren()) do
                local order = ORDER[c.Name]
                if order and c:IsA("ScreenGui") and c.DisplayOrder ~= order then
                    if saved[c] == nil then saved[c] = c.DisplayOrder end
                    c.DisplayOrder = order
                end
            end
        end
    end
    task.spawn(function()
        while not hub.unloaded do
            if setthreadidentity then pcall(setthreadidentity, 8) end
            pcall(raise)
            task.wait(1)
        end
    end)
    hub.onUnload(function()
        for gui, order in pairs(saved) do pcall(function() gui.DisplayOrder = order end) end
    end)
end

local fxFolder = Instance.new("Folder")
fxFolder.Name = "ZamltraFX"
fxFolder.Parent = Camera
hub.onUnload(function() fxFolder:Destroy() end)

--!luaq:no_virtualize
local function elevate()
    if setthreadidentity then pcall(setthreadidentity, 8) end
end

local draw = {}
do
    local BLACK = Color3.new(0, 0, 0)
    local pools = { line = {}, rect = {}, text = {} }
    local used  = { line = 0, rect = 0, text = 0 }

    local makers = {
        line = function()
            local f = Instance.new("Frame")
            f.BorderSizePixel = 0
            f.AnchorPoint = Vector2.new(0.5, 0.5)
            return f
        end,
        rect = function()
            local f = Instance.new("Frame")
            f.BorderSizePixel = 0
            local st = Instance.new("UIStroke")
            st.LineJoinMode = Enum.LineJoinMode.Miter
            st.Parent = f
            return f
        end,
        text = function()
            local t = Instance.new("TextLabel")
            t.BackgroundTransparency = 1
            t.Font = Enum.Font.GothamBold
            t.TextStrokeTransparency = 0.4
            t.TextStrokeColor3 = BLACK
            t.Size = UDim2.fromOffset(0, 0)
            t.AutomaticSize = Enum.AutomaticSize.XY
            return t
        end,
    }

    --!luaq:no_virtualize
    local function get(kind)
        local n = used[kind] + 1
        used[kind] = n
        local o = pools[kind][n]
        if not o then
            elevate()
            o = makers[kind]()
            o.Parent = overlay
            pools[kind][n] = o
        end
        o.Visible = true
        return o
    end

    draw.begin = LUAQ_NO_VIRTUALIZE(function()
        used.line, used.rect, used.text = 0, 0, 0
    end)

    draw.finish = LUAQ_NO_VIRTUALIZE(function()
        for kind, pool in pairs(pools) do
            for i = used[kind] + 1, #pool do
                if not pool[i].Visible then break end
                pool[i].Visible = false
            end
        end
    end)

    draw.line = LUAQ_NO_VIRTUALIZE(function(a, b, color, thick, alpha)
        local d = b - a
        local f = get("line")
        f.Size = UDim2.fromOffset(d.Magnitude, thick or 1)
        f.Position = UDim2.fromOffset((a.X + b.X) / 2, (a.Y + b.Y) / 2)
        f.Rotation = math.deg(math.atan2(d.Y, d.X))
        f.BackgroundColor3 = color
        f.BackgroundTransparency = alpha or 0
    end)

    draw.rect = LUAQ_NO_VIRTUALIZE(function(x, y, w, h, color, thick, fill, alpha)
        local f = get("rect")
        f.Position = UDim2.fromOffset(x, y)
        f.Size = UDim2.fromOffset(w, h)
        f.BackgroundColor3 = color
        f.BackgroundTransparency = fill or 1
        local st = f:FindFirstChildOfClass("UIStroke")
        st.Color = color
        st.Thickness = thick or 1
        st.Transparency = (thick == 0) and 1 or (alpha or 0)
    end)

    draw.text = LUAQ_NO_VIRTUALIZE(function(str, x, y, color, size, align, alpha)
        local t = get("text")
        t.Text = str
        t.TextSize = size or 13
        t.TextColor3 = color
        t.TextTransparency = alpha or 0
        t.TextStrokeTransparency = 0.4 + (alpha or 0) * 0.6
        t.AnchorPoint = Vector2.new(align or 0.5, 0)
        t.Position = UDim2.fromOffset(x, y)
    end)
end

--!luaq:no_virtualize
local function localChar()
    local c = CC.GetCharacter()
    return (c and next(c) and c.Simulation) and c or nil
end

--!luaq:no_virtualize
local function myTeam()
    return LocalPlayer:GetAttribute("Team")
end

--!luaq:no_virtualize
local function tickDt()
    return 1 / (GameCfg.Get("Game", "TickRate") or 64)
end

--!luaq:no_virtualize
local function entPlayer(e)
    local uid = e.UserId
    return (uid and uid ~= 0) and Players:GetPlayerByUserId(uid) or nil
end

--!luaq:no_virtualize
local function entName(e)
    local p = entPlayer(e)
    return p and p.DisplayName or ("Bot " .. tostring(e.Identifier))
end

--!luaq:no_virtualize
local function isEnemy(e)
    if GameCfg.Get("Damage", "Teammate") then return true end
    return not (e.Data and e.Data.Team == myTeam())
end

local friendCache = {}
--!luaq:no_virtualize
local function isFriend(p)
    if not p then return false end
    local v = friendCache[p.UserId]
    if v == nil then
        friendCache[p.UserId] = false
        task.spawn(function()
            local ok, r = pcall(function() return LocalPlayer:IsFriendsWith(p.UserId) end)
            friendCache[p.UserId] = ok and r or false
        end)
        return false
    end
    return v
end

--!luaq:no_virtualize
local function alive(e)
    if not e or (e.Health or 0) <= 0 or not e.Model or not e.PrimaryPart then return false end
    if e.UserId == LocalPlayer.UserId then return false end
    return true
end

--!luaq:no_virtualize
local function targetable(e)
    if not alive(e) or e.FogCulled then return false end
    local p = entPlayer(e)
    if p and p:GetAttribute("SpawnProtected") then return false end
    if S.ignoreFriends and isFriend(p) then return false end
    if p and rageWhitelist[p.Name] then return false end
    return true
end

--!luaq:no_virtualize
local function partPos(e, name)
    local part = e.Model:FindFirstChild(name)
    if not part then return nil end
    if e.Culled then
        return (e.CFrame * e.PrimaryPart.CFrame:ToObjectSpace(part.CFrame)).Position
    end
    return part.Position
end

local mapParams = RaycastParams.new()
mapParams.FilterType = Enum.RaycastFilterType.Include
mapParams.IgnoreWater = true
local mapGeometry
--!luaq:no_virtualize
local function refreshMap()
    local map = workspace:FindFirstChild("Map")
    local geo = map and map:FindFirstChild("Geometry")
    if geo ~= mapGeometry then
        mapGeometry = geo
        mapParams.FilterDescendantsInstances = geo and { geo } or {}
    end
    return geo
end

--!luaq:no_virtualize
local function visible(from, to)
    if not refreshMap() then return true end
    return workspace:Raycast(from, to - from, mapParams) == nil
end

--!luaq:no_virtualize
local function eyePos(sim)
    return sim.Position + Vector3.new(0, sim.CameraOffset + sim.Height, 0)
end

--!luaq:no_virtualize
local function surfaceMod(inst, material)
    local variant = Enums.MaterialVariantPenetrationData[inst.MaterialVariant]
    local data = Enums.MaterialPenetrationData
    if variant then
        return variant.Material, variant.PenetrationModifier or data[variant.Material].PenetrationModifier
    end
    return material or "Default", ((material and data[material]) or data.Default).PenetrationModifier
end

local SAME_MATERIAL = {
    [Enum.Material.Wood] = 3, [Enum.Material.WoodPlanks] = 3, [Enum.Material.Cardboard] = 3,
    [Enum.Material.Plastic] = 2, [Enum.Material.SmoothPlastic] = 2,
}

local exitParams = RaycastParams.new()
exitParams.FilterType = Enum.RaycastFilterType.Include
exitParams.IgnoreWater = true
--!luaq:no_virtualize
local function traceToExit(pos, dir, maxDist)
    exitParams.FilterDescendantsInstances = { mapGeometry }
    local steps = math.floor(maxDist / 0.2776) + 1
    local far = steps * 0.2776
    local enters, exits, exitHits = {}, {}, {}
    local at, n = 0.001, 0
    for _ = 1, 16 do
        local r = workspace:Raycast(pos + dir * at, dir * (far - at), exitParams)
        if not r then break end
        n = n + 1
        enters[n] = at + r.Distance
        at = enters[n] + 0.001
        if at >= far then break end
    end
    local back, m = far, 0
    for _ = 1, 16 do
        local r = back > 0.001 and workspace:Raycast(pos + dir * back, dir * -(back - 0.001), exitParams)
        if not r then break end
        m = m + 1
        exits[m] = back - r.Distance
        exitHits[m] = r
        back = exits[m] - 0.001
    end
    local ei, depth, hit = 1, 1, nil
    for i = 1, steps do
        local d = i * 0.2776
        while ei <= n and enters[ei] <= d do depth = depth + 1; ei = ei + 1 end
        while m >= 1 and exits[m] <= d do depth = depth - 1; hit = exitHits[m]; m = m - 1 end
        if depth <= 0 then break end
    end
    return (depth <= 0) and hit or nil
end

--!luaq:no_virtualize
local function bulletDamage(weapon, origin, point, partName, allowWalls)
    local data = weapon.Data
    if not refreshMap() then return 0, 0 end
    local dir = point - origin
    local total = dir.Magnitude
    if total < 1e-3 then return 0, 0 end
    dir = dir / total
    if total > (data.Range or 0) then return 0, 0 end

    local falloff = GameCfg.Get("Weapon", "DistanceFallOff")
    local minStart = GameCfg.Get("Weapon", "MinimumPenetrationStartDistance")
    local maxPen = GameCfg.Get("Weapon", "MaxPenetrationDistance")
    local lossDiv = GameCfg.Get("Weapon", "PenetrationLossDivisor")
    local mults = data.HitboxMultipliers or GameCfg.Get("Damage", "HitboxMultipliers")

    local damage, pen = data.Damage, data.Penetration
    local pos, travelled, walls, left = origin, 0, 0, 4
    while damage > 0 do
        local rest = point - pos
        local r = workspace:Raycast(pos, rest, mapParams)
        if not r then
            travelled = travelled + rest.Magnitude
            return damage * data.RangeModifier ^ (travelled / falloff) * (mults[partName] or 1), walls
        end
        if not allowWalls or r.Instance.Name == "nowallbang" then return 0, walls end
        travelled = travelled + r.Distance
        local here = damage * data.RangeModifier ^ (travelled / falloff)
        local matIn, modIn = surfaceMod(r.Instance, r.Material)
        if left <= 0 or travelled > minStart or modIn < 0.1 or pen <= 0 then return 0, walls end
        local exit = traceToExit(r.Position, dir, maxPen)
        if not exit then return 0, walls end
        local matOut, modOut = surfaceMod(exit.Instance, exit.Material)
        local combined = (matIn == Enum.Material.Glass) and 3 or (modIn + modOut) / 2
        if matIn == matOut then combined = SAME_MATERIAL[matOut] or combined end
        local thick = (exit.Position - r.Position).Magnitude
        if (exit.Position - origin).Magnitude >= total then

            return 0, walls
        end
        local inv = 1 / combined
        local loss = here * ((matIn == Enum.Material.Glass) and 0.05 or 0.16)
            + math.max(0, 3 / pen * 1.25) * (inv * 3) + inv * thick * thick / lossDiv
        damage = here - math.max(0, loss)
        if damage < 1 then return 0, walls end
        pos = exit.Position
        walls, left = walls + 1, left - 1
    end
    return 0, walls
end

--!luaq:no_virtualize
local function afterArmor(e, weapon, damage, partName)
    local p = entPlayer(e)
    local ok, final = pcall(M.DamageCalculation.ApplyArmor, damage, partName,
        p and p:GetAttribute("ArmorValue") or 0, p and p:GetAttribute("HasHelmet") or false, weapon.Data.ArmorRatio)
    return ok and final or math.floor(damage)
end

local PITCH_MAX = 1.55334

--!luaq:no_virtualize
local function dirToAngles(d)
    return math.asin(math.clamp(d.Y, -1, 1)), math.atan2(-d.X, -d.Z)
end

--!luaq:no_virtualize
local function anglesCF(rx, ry)
    return CFrame.fromEulerAnglesYXZ(rx, ry, 0)
end

--!luaq:no_virtualize
local function quantize(yaw, pitch)
    local qy = math.clamp(math.round((wrap(yaw) + math.pi) / (2 * math.pi) * 65535), 0, 65535)
    local qp = math.clamp(math.round((math.clamp(pitch, -PITCH_MAX, PITCH_MAX) + PITCH_MAX) / (2 * PITCH_MAX) * 65535), 0, 65535)
    return qy, qp
end

--!luaq:no_virtualize
local function dequantize(qy, qp)
    return -math.pi + qy * 2 * math.pi / 65535, -PITCH_MAX + qp * (2 * PITCH_MAX) / 65535
end

--!luaq:no_virtualize
local function spreadSeed(tick)
    local x = bit32.bxor(tick, bit32.rshift(tick, 16))
    x = (x * 34283 % 65536 * 65536 + x * 51819) % 4294967296
    x = bit32.bxor(x, bit32.rshift(x, 13))
    x = (x * 49842 % 65536 * 65536 + x * 44597) % 4294967296
    x = bit32.bxor(x, bit32.rshift(x, 16))
    return bit32.band(x, 255) + 1
end

--!luaq:no_virtualize
local function punchOf(sim)
    return sim.SeenAimPunch or sim.AimPunchAngle
end
--!luaq:no_virtualize
local function recoilScale()
    local cfg = M.Config and M.Config.CFG
    return (cfg and cfg.RecoilScale) or GameCfg.Get("Weapon", "RecoilScale") or 1
end
--!luaq:no_virtualize
local function weaponClock(char, weapon)
    return char.WeaponTimer or weapon.Timer or 0
end

--!luaq:no_virtualize
local function nextSpread(char, weapon, dt)
    local sim = char.Simulation
    local ap, ri, timer = weapon.AccuracyPenalty, weapon.RecoilIndex, weapon.Timer
    local ok, x, y = pcall(function()
        weapon.Timer = f32(weaponClock(char, weapon) + dt)
        weapon:UpdateAccuracyPenalty(char, dt)
        local rng = M.Math.UniformRandomStream(spreadSeed(((sim.CommandCount or 0) + 1) % 65536))
        return Bullet.SpreadOffset(weapon, rng, weapon:GetInaccuracy(sim), weapon:GetSpread(), 1)
    end)
    weapon.AccuracyPenalty, weapon.RecoilIndex, weapon.Timer = ap, ri, timer
    if ok then return x, y end
    return 0, 0
end

--!luaq:no_virtualize
local function solveAngles(dir, punch, sx, sy)
    local rx, ry = dirToAngles(dir)
    if sx and (sx ~= 0 or sy ~= 0) then
        local k = math.sqrt(1 + sx * sx + sy * sy)
        for _ = 1, 3 do
            local cf = anglesCF(rx, ry)
            rx, ry = dirToAngles((dir * k - cf.RightVector * sx - cf.UpVector * sy).Unit)
        end
    end
    local scale = recoilScale()
    local px, py = math.rad(punch.X * scale), math.rad(punch.Y * scale)
    return ry - py, px - rx
end

--!luaq:no_virtualize
local function fixMovement(cmd, oldYaw, newYaw)
    local inp = cmd.Inputs
    local mx = (inp.Right and 1 or 0) - (inp.Left and 1 or 0)
    local mz = (inp.Backward and 1 or 0) - (inp.Forward and 1 or 0)
    if mx == 0 and mz == 0 then return end
    local c, s = math.cos(oldYaw), math.sin(oldYaw)
    local wx, wz = mx * c + mz * s, -mx * s + mz * c
    local c2, s2 = math.cos(newYaw), math.sin(newYaw)
    local nx, nz = c2 * wx - s2 * wz, s2 * wx + c2 * wz
    local t = math.sqrt(nx * nx + nz * nz) * 0.3826834
    inp.Right, inp.Left = nx > t, nx < -t
    inp.Backward, inp.Forward = nz > t, nz < -t
end

--!luaq:no_virtualize
local function isGun(weapon)
    local d = weapon and next(weapon) and weapon.Data
    return d and d.Type ~= "Melee" and d.Type ~= "Bomb" and d.ClipSize ~= nil
end

--!luaq:no_virtualize
local function canFire(weapon, sim, dt, char)
    if not isGun(weapon) or sim.Preparation or sim.Defusing or sim.Planting then return false end
    local d = weapon.Data
    if weapon.Equipping or weapon.Reloading then return false end
    if (d.Ammo or 0) <= 0 then return false end

    if (weapon.BurstFireRemaining or 0) > 0 then return true end
    if weapon.WaitForNoAttack then return false end
    if d.Automatic == false and weapon.WannaShoot then return false end
    return ((char and char.WeaponTimer) or weapon.Timer or 0) + dt >= weapon.FireDelay - 1e-5
end

local BODY = { "UpperTorso", "LowerTorso" }
local HITBOX_SETS = {
    ["Head"] = { "Head" },
    ["Body"] = BODY,
    ["Head + Body"] = { "Head", "UpperTorso", "LowerTorso" },
    ["All"] = { "Head", "UpperTorso", "LowerTorso", "LeftUpperArm", "RightUpperArm", "LeftUpperLeg", "RightUpperLeg" },
}

--!luaq:no_virtualize
local function screenDist(pos)
    local eye = CamCtl.GetAppliedCFrame()
    local lp = eye:PointToObjectSpace(pos)
    if lp.Z >= -0.05 then return math.huge end
    local half = Camera.ViewportSize.Y / 2
    local scale = half / math.tan(math.rad(Camera.FieldOfView) / 2)
    return math.sqrt(lp.X * lp.X + lp.Y * lp.Y) / -lp.Z * scale
end

local ALL_PARTS = {
    "Head", "UpperTorso", "LowerTorso", "LeftUpperArm", "LeftLowerArm", "LeftHand", "RightUpperArm", "RightLowerArm",
    "RightHand", "LeftUpperLeg", "LeftLowerLeg", "LeftFoot", "RightUpperLeg", "RightLowerLeg", "RightFoot",
}
local HEAD_ONLY, BODY_ONLY = { "Head" }, { "UpperTorso" }
local legitLast = { at = 0 }

--!luaq:no_virtualize
local function legitTarget(origin)
    local names = (S.aimPart == "Head") and HEAD_ONLY or (S.aimPart == "Body") and BODY_ONLY or ALL_PARTS
    local now = os.clock()
    local last = (now - legitLast.at < 0.5) and legitLast or nil
    local best, held
    for _, e in pairs(Entities.GetAllCategoryEntities("Character")) do
        if targetable(e) and (not S.teamCheck or isEnemy(e)) then
            for _, name in ipairs(names) do
                local pos = partPos(e, name)
                if pos then
                    local d = screenDist(pos)
                    if d <= S.fov then
                        local isHeld = last ~= nil and last.entity == e and last.part == name
                        if (isHeld or not best or d < best.d) and (not S.wallCheck or visible(origin, pos)) then
                            local cand = { entity = e, pos = pos, part = name, d = d }
                            if isHeld then held = cand end
                            if not best or d < best.d then best = cand end
                        end
                    end
                end
            end
        end
    end

    local pick = best
    if held and best and best ~= held and not (best.d < held.d * 0.6 or held.d - best.d > 25) then
        pick = held
    end
    if not pick then return nil end
    legitLast = { entity = pick.entity, part = pick.part, at = now }
    return pick.entity, pick.pos, pick.part
end

local rageTarget = { entity = nil, pos = nil, part = nil, damage = 0, renderTime = nil }

local aimJitter
--!luaq:no_virtualize
local function rageScan(origin, weapon, camLook)
    local best, bestScore
    local maxCos = math.cos(math.rad(math.min(S.rageFov, 180)))

    local cone = 0
    pcall(function()
        local char = localChar()
        cone = weapon:GetInaccuracy(char.Simulation) + weapon:GetSpread()
    end)

    for _, e in pairs(Entities.GetAllCategoryEntities("Character")) do
        if targetable(e) and isEnemy(e) then
            local root = e.Position
            local dist = (root - origin).Magnitude
            local inFov = S.rageFov >= 180 or camLook:Dot((root - origin).Unit) >= maxCos
            if dist <= S.maxDist and inFov then
                local hp = e.Health
                local names = HITBOX_SETS[S.rageHitbox] or HITBOX_SETS.Head
                local pick

                --!luaq:no_virtualize
                local function try(offset)
                    local bodyLethal
                    for _, name in ipairs(names) do
                        local pos = partPos(e, name)
                        if pos then

                            local jit = aimJitter
                            if not jit or os.clock() - jit.at > 0.5 then
                                local r = Random.new()
                                jit = { at = os.clock(), v = Vector3.new(r:NextNumber(-1, 1), r:NextNumber(-1, 1), r:NextNumber(-1, 1)) }
                                aimJitter = jit
                            end
                            pos = pos + offset + jit.v * ((name == "Head") and 0.16 or 0.3)
                            local raw = bulletDamage(weapon, origin, pos, name, S.autowall)
                            if raw > 0 then
                                local dmg = afterArmor(e, weapon, raw, name)
                                local need = S.dmgOverride and S.minDamageOverride or S.minDamage
                                if dmg >= math.min(need, hp) then

                                    local reach = (S.rageNoSpread and 0 or cone) * (pos - origin).Magnitude
                                    local size = (name == "Head") and 0.55 or 0.9
                                    local chance = (reach <= size) and 1 or size / reach
                                    local cand = { entity = e, pos = pos, part = name, damage = dmg,
                                        chance = chance, ready = chance * 100 >= S.hitChance }

                                    if not pick or (cand.ready and not pick.ready)
                                        or (cand.ready == pick.ready and dmg > pick.damage) then
                                        pick = cand
                                    end
                                    if name ~= "Head" and dmg >= hp and (cand.ready or not (bodyLethal and bodyLethal.ready)) then
                                        bodyLethal = cand
                                    end
                                end
                            end
                        end
                    end
                    if S.preferBody and bodyLethal and (bodyLethal.ready or not pick.ready) then pick = bodyLethal end
                end

                try(Vector3.zero, nil)

                if pick then
                    local score
                    if S.rageSelect == "Distance" then score = dist
                    elseif S.rageSelect == "Lowest HP" then score = hp
                    elseif S.rageSelect == "Highest Damage" then score = -pick.damage
                    else score = -camLook:Dot((pick.pos - origin).Unit) end
                    if not bestScore or score < bestScore then best, bestScore = pick, score end
                end
            end
        end
    end
    return best
end

local trigParams = RaycastParams.new()
trigParams.FilterType = Enum.RaycastFilterType.Include
local trigSince
--!luaq:no_virtualize
local function triggerHit(origin, dir, range)
    local chars = workspace:FindFirstChild("Characters")
    if not chars or not refreshMap() then return false end
    trigParams.FilterDescendantsInstances = { mapGeometry, chars }
    local r = workspace:Raycast(origin, dir * range, trigParams)
    if not r or not r.Instance:IsDescendantOf(chars) then return false end
    local model = r.Instance
    while model and model.Parent ~= chars do model = model.Parent end
    local e = model and Entities.GetEntity("Character", tonumber(model.Name))
    return e ~= nil and targetable(e) and (not S.teamCheck or isEnemy(e))
end

local tickState = {
    camYaw = 0, camPitch = 0,
    aim = nil,
    forcedFire = false,
    lastShot = 0,
    aaYaw = nil,
    strafeSide = 1,
    lastCamYaw = nil,
}

--!luaq:no_virtualize
local function menuBlocked()
    local ok, r = pcall(function() return M.BindsController.HasFramePriority() end)
    return ok and r
end

--!luaq:no_virtualize
local function userFiring()
    if tickState.forcedFire then
        return UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) and not menuBlocked()
            and UserInputService:GetFocusedTextBox() == nil
    end
    return WC.GetKeyState("WishFire") == true
end

do
    hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function(dt)
        if not S.assist or S.rage or hub.unloaded then return end
        if not Window.Closed or menuBlocked() or UserInputService:GetFocusedTextBox() then return end
        local char = localChar()
        if not char then return end
        local weapon = WC.GetCurrentWeapon()
        if not (weapon and next(weapon) and isGun(weapon)) then return end
        local mode = S.assistMode
        if mode == "While Firing" and not userFiring() then return end
        if mode == "While Aiming" and not (UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton2)
            or (weapon.ZoomLevel or 0) > 0) then return end
        if S.assistMouse and UserInputService:GetMouseDelta().Magnitude < 0.5 then return end

        local origin = CamCtl.GetAppliedCFrame().Position
        local names = (S.assistPart == "Head") and HEAD_ONLY or (S.assistPart == "Body") and BODY_ONLY or ALL_PARTS
        local bestD, bestPos
        for _, e in pairs(Entities.GetAllCategoryEntities("Character")) do
            if targetable(e) and (not S.teamCheck or isEnemy(e)) then
                for _, name in ipairs(names) do
                    local pos = partPos(e, name)
                    if pos then
                        local d = screenDist(pos)
                        if d <= S.assistFov and (not bestD or d < bestD) and (not S.assistWall or visible(origin, pos)) then
                            bestD, bestPos = d, pos
                        end
                    end
                end
            end
        end
        if not bestPos then return end

        local rx, ry = dirToAngles((bestPos - origin).Unit)
        local ok, yaw, pitch = pcall(CamCtl.GetAngles)
        if not ok or type(yaw) ~= "number" then return end
        local k = 1 - math.exp(-(S.assistStrength / 100) * 15 * math.min(dt, 0.1))
        local dy, dp = wrap(ry - yaw), (-rx) - pitch
        pcall(CamCtl.SetAngles, wrap(yaw + dy * k), math.clamp(pitch + dp * k, -PITCH_MAX, PITCH_MAX))
    end))
end

--!luaq:no_virtualize
local function chooseAim(char, sim, weapon, dt, camLook)
    if not isGun(weapon) then return nil, false end
    local origin = eyePos(sim)

    if S.rage then
        tickState.scans = (tickState.scans or 0) + 1
        local t = rageScan(origin, weapon, camLook)
        if t then
            tickState.scanHits = (tickState.scanHits or 0) + 1
            t.at = os.clock()

            local id = t.entity.Identifier
            if tickState.seenId ~= id or t.at - (tickState.seenLast or 0) > 0.4 then
                tickState.seenId, tickState.seenSince = id, t.at
            end
            tickState.seenLast = t.at
            if t.ready then
                if (t.at - tickState.seenSince) * 1000 < S.rageReaction
                    or (t.at - (tickState.lastRageShot or 0)) * 1000 < S.rageShotDelay then
                    t.ready = false
                end
            end
            rageTarget = t

            return t, S.autoFire or userFiring()
        end
        return nil, false
    end

    if S.silentAim and (userFiring() or tickState.forcedFire) then
        local e, pos, part = legitTarget(origin)
        if e then return { entity = e, pos = pos, part = part }, false end
    end
    return nil, false
end

--!luaq:no_virtualize
local function antiAimAngles(sim, cmd, camYaw)
    local base = camYaw
    if S.aaBase == "At Target" then
        local origin, bestD = sim.Position, nil
        for _, e in pairs(Entities.GetAllCategoryEntities("Character")) do
            if targetable(e) and isEnemy(e) then
                local d = (e.Position - origin).Magnitude
                if not bestD or d < bestD then
                    bestD = d
                    local _, ry = dirToAngles((e.Position - origin).Unit)
                    base = ry
                end
            end
        end
    end
    local yaw = base
    local mode = S.aaYaw
    if mode == "Backward" then yaw = base + math.pi
    elseif mode == "Left" then yaw = base + math.pi / 2
    elseif mode == "Right" then yaw = base - math.pi / 2
    elseif mode == "Spin" then
        tickState.aaYaw = (tickState.aaYaw or base) + math.rad(S.aaSpin)
        yaw = tickState.aaYaw
    elseif mode == "Jitter" then
        local side = (cmd.ClientTick % 2 == 0) and 1 or -1
        yaw = base + math.pi + math.rad(S.aaJitter / 2) * side
    end
    if S.aaLeft then
        yaw = base + math.pi / 2
    elseif S.aaRight then
        yaw = base - math.pi / 2
    end
    local pitch
    if S.aaPitch == "Down" then pitch = PITCH_MAX
    elseif S.aaPitch == "Up" then pitch = -PITCH_MAX
    elseif S.aaPitch == "Zero" then pitch = 0 end
    return yaw, pitch
end

--!luaq:no_virtualize
local function createMove(char, cmd)
    local sim = char.Simulation
    local weapon = WC.GetCurrentWeapon()
    local dt = tickDt()
    local camYaw, camPitch = dequantize(cmd.Yaw, cmd.Pitch)
    tickState.camYaw, tickState.camPitch = camYaw, camPitch
    tickState.aim = nil

    local add, inp = cmd.AdditionalInputs, cmd.Inputs
    local yaw, pitch = camYaw, camPitch

    local spaceHeld = add.Jump == true
        or (UserInputService:IsKeyDown(Enum.KeyCode.Space) and UserInputService:GetFocusedTextBox() == nil)
    local busy = sim.Planting or sim.Defusing or sim.Climbing or add.PressE or sim.Preparation

    local vel = sim.Velocity
    local speed = math.sqrt(vel.X * vel.X + vel.Z * vel.Z)
    local moveYaw = camYaw
    local grounded = sim.OnGround == true or sim.Climbing == true

    if S.longJump and grounded and speed > 6 and not busy and refreshMap() then

        local down = Vector3.new(0, -5, 0)
        local ahead = sim.Position + Vector3.new(vel.X, 0, vel.Z) * dt * 2
        if workspace:Raycast(sim.Position, down, mapParams) and not workspace:Raycast(ahead, down, mapParams) then
            add.Jump = true
            tickState.jumpTick = cmd.ClientTick
            tickState.longJumping = true
        end
    end
    if S.bhop and spaceHeld and not menuBlocked() then
        add.Jump = grounded
    end
    if add.Jump and grounded then tickState.jumpTick = cmd.ClientTick end
    if grounded and not add.Jump then tickState.longJumping = false end
    if (S.duckJump or tickState.longJumping) and not grounded
        and cmd.ClientTick - (tickState.jumpTick or -1000) <= S.airDuckTicks then
        add.Duck = true
    end

    local strafeWish
    if S.strafe and spaceHeld and not grounded and not busy then
        local mx = (inp.Right and 1 or 0) - (inp.Left and 1 or 0)
        local mz = (inp.Backward and 1 or 0) - (inp.Forward and 1 or 0)
        if S.strafeMode == "Legit" then
            local d = wrap(camYaw - (tickState.lastCamYaw or camYaw))
            if math.abs(d) > 1e-4 then
                inp.Forward, inp.Backward = false, false
                inp.Left, inp.Right = d > 0, d < 0
            end
        else

            local heading = camYaw + ((mx ~= 0 or mz ~= 0) and math.atan2(-mx, -mz) or 0)
            strafeWish = heading
            if speed > 2 then
                local velYaw = math.atan2(-vel.X, -vel.Z)
                local delta = wrap(heading - velYaw)
                local angle = math.pi / 2
                local side
                if math.abs(delta) > math.rad(S.alignThreshold) then
                    side = delta > 0 and 1 or -1
                    if S.fastTurn then

                        local c = sim.Constants
                        local wishSpeed = math.max(sim.CroppedMaxSpeed or c.Speed or 16, 1)
                        local budget = c.AirAcceleration * wishSpeed * dt
                        angle = math.acos(math.clamp((math.min(c.MaxAirStrafeSpeed, wishSpeed) - budget) / speed, -1, 1))
                    end
                else

                    tickState.strafeSide = -tickState.strafeSide
                    side = tickState.strafeSide
                end
                strafeWish = velYaw + side * angle
            end
        end
    end
    tickState.lastCamYaw = camYaw

    if S.aa and not busy and not (weapon and weapon.Data and weapon.Data.Type == "Bomb") then
        local aaYaw, aaPitch = antiAimAngles(sim, cmd, camYaw)
        yaw, pitch = aaYaw, aaPitch or pitch
    else
        tickState.aaYaw = nil
    end

    local camLook = anglesCF(-camPitch, camYaw).LookVector
    local aimNow, aimHoldNow
    if weapon and canFire(weapon, sim, dt, char) then
        local aim, hold = chooseAim(char, sim, weapon, dt, camLook)
        if aim then
            tickState.rageSeen = S.rage
            if S.autoStop and S.rage then

                strafeWish = nil
                add.Jump = false
                local wx, wz = 0, 0
                if grounded and speed > 2 then wx, wz = -vel.X / speed, -vel.Z / speed end
                local c2, s2 = math.cos(camYaw), math.sin(camYaw)
                local nx, nz = c2 * wx - s2 * wz, s2 * wx + c2 * wz
                inp.Right, inp.Left = nx > 0.3827, nx < -0.3827
                inp.Backward, inp.Forward = nz > 0.3827, nz < -0.3827
                moveYaw = camYaw
            end
            if aim.ready ~= false then
                aimNow, aimHoldNow = aim, hold
                tickState.lastAim = { pos = aim.pos, tick = cmd.ClientTick }
            end
        elseif S.noRecoil and (userFiring() or tickState.forcedFire) then
            local punch = SimCamera.DecayAimPunchAngle(punchOf(sim), sim.AimPunchAngleVel, dt)
            yaw, pitch = solveAngles(camLook, punch, 0, 0)
        end
    end

    local trackPos = aimNow and aimNow.pos
    local last = tickState.lastAim
    if not trackPos and last and (S.rage or S.silentAim) and cmd.ClientTick - last.tick <= 14 then
        trackPos = last.pos
    end
    if trackPos then
        local comp = S.noRecoil or (S.rage and S.rageRecoil) or (S.silentAim and not S.rage)
        local punch = comp and SimCamera.DecayAimPunchAngle(punchOf(sim), sim.AimPunchAngleVel, dt) or Vector3.zero
        yaw, pitch = solveAngles((trackPos - eyePos(sim)).Unit, punch, 0, 0)
    end

    do
        local prevYaw, prevPitch = tickState.sentYaw, tickState.sentPitch
        local steering = yaw ~= camYaw or pitch ~= camPitch
        local reached = true

        local limited = (S.rage and not S.rageInstant) or S.turnCamera
        if limited and prevYaw and (steering or tickState.sentOff) then
            local limit = math.rad(S.aimSpeed)
            local dy, dp = wrap(yaw - prevYaw), pitch - prevPitch
            local d = math.sqrt(dy * dy + dp * dp)

            local step = limit
            if S.aimSmooth > 0 then
                step = math.min(limit, math.max(d * (1 - S.aimSmooth / 100), math.rad(1.2)))
            end
            if d > step and S.aimSpeed < 180 then
                yaw, pitch = prevYaw + dy * step / d, prevPitch + dp * step / d
                reached = false
            end
        end
        tickState.sentYaw, tickState.sentPitch = yaw, pitch

        tickState.camWrite = (trackPos and S.turnCamera) and { yaw, pitch } or nil
        tickState.sentOff = math.abs(wrap(yaw - camYaw)) > 1e-4 or math.abs(pitch - camPitch) > 1e-4
        if aimNow and reached then
            tickState.aim = aimNow
            tickState.aimHold = aimHoldNow
        end
    end

    if strafeWish and not tickState.aim then

        local k = math.floor(wrap(strafeWish - yaw) / (math.pi / 4) + 0.5)
        local off = k * math.pi / 4
        yaw = strafeWish - off
        local bx, bz = -math.sin(off), -math.cos(off)
        inp.Right, inp.Left = bx > 0.38, bx < -0.38
        inp.Backward, inp.Forward = bz > 0.38, bz < -0.38
    elseif yaw ~= moveYaw then
        fixMovement(cmd, moveYaw, yaw)
    end
    if yaw ~= camYaw or pitch ~= camPitch then
        cmd.Yaw, cmd.Pitch = quantize(yaw, pitch)
    end
end

local GUARD_PARTS = {
    "Head", "LowerTorso", "UpperTorso", "LeftUpperArm", "RightUpperArm", "LeftLowerArm", "RightLowerArm",
    "LeftUpperLeg", "RightUpperLeg", "LeftLowerLeg", "RightLowerLeg", "LeftFoot", "RightFoot",
}

local GUARD_SPOTS = {
    Vector3.new(0, 0, 0), Vector3.new(0, 0.55, 0), Vector3.new(0, -0.55, 0),
    Vector3.new(0.55, 0, 0), Vector3.new(-0.55, 0, 0),
}
--!luaq:no_virtualize
local function guardedPoint(e, origin, dir, sx, sy)
    if not (e and e.Model and e.PrimaryPart) then return nil end

    local boxes = {}
    local fix = e.Culled and (e.CFrame * e.PrimaryPart.CFrame:Inverse()) or nil
    for _, name in ipairs(GUARD_PARTS) do
        local part = e.Model:FindFirstChild(name)
        if part and part:IsA("BasePart") then
            boxes[#boxes + 1] = { cf = fix and (fix * part.CFrame) or part.CFrame, half = part.Size / 2, name = name }
        end
    end
    if #boxes == 0 then return nil end
    local rx, ry = dirToAngles(dir)
    local view = anglesCF(rx, ry)
    local offset = view.RightVector * sx + view.UpVector * sy
    --!luaq:no_virtualize
    local function onBody(point)
        for _, b in ipairs(boxes) do
            local lp = b.cf:PointToObjectSpace(point)
            if math.abs(lp.X) <= b.half.X * 0.9 and math.abs(lp.Y) <= b.half.Y * 0.9 and math.abs(lp.Z) <= b.half.Z + 0.6 then
                return true
            end
        end
        return false
    end
    for _, b in ipairs(boxes) do
        for _, spot in ipairs(GUARD_SPOTS) do
            local hit = b.cf:PointToWorldSpace(spot * b.half)
            local centre = hit - offset * (hit - origin).Magnitude
            if onBody(centre) then return hit, b.name end
        end
    end
    return nil
end

local restoreInputs
--!luaq:no_virtualize
local function preWeapon(dt)
    local char = localChar()

    restoreInputs(char)
    if not char then return end
    local cmd, sim = char.CurrentCommand, char.Simulation
    if not cmd then return end
    local weapon = WC.GetCurrentWeapon()
    if not weapon or not next(weapon) then return end

    local fireNow = canFire(weapon, sim, dt, char)
    tickState.postRuns = (tickState.postRuns or 0) + 1
    if tickState.aim then tickState.aimTicks = (tickState.aimTicks or 0) + 1 end
    local held = userFiring()
    local want = false

    if isGun(weapon) and fireNow then
        local aim = tickState.aim
        local camLook = anglesCF(-tickState.camPitch, tickState.camYaw).LookVector
        local dir

        if aim then
            dir = (aim.pos - eyePos(sim)).Unit
            want = tickState.aimHold or held
        elseif S.noRecoil or S.noSpread or S.trigger then
            dir = camLook
        end

        if S.trigger and not aim and not S.rage then
            local scale = recoilScale()
            local kick = punchOf(sim)
            local shotCF = S.noRecoil and anglesCF(-tickState.camPitch, tickState.camYaw)
                or anglesCF(-tickState.camPitch + math.rad(kick.X * scale), tickState.camYaw + math.rad(kick.Y * scale))
            local shot = shotCF.LookVector
            if triggerHit(eyePos(sim), shot, weapon.Data.Range or 300) then
                trigSince = trigSince or os.clock()
                if os.clock() - trigSince >= S.triggerDelay / 1000 then want = true end
            else
                trigSince = nil
            end
        end

        local firing = want or held or WC.GetKeyState("WishFire") == true or (tickState.fireHold or 0) > 0
            or (weapon.BurstFireRemaining or 0) > 0
        if dir and firing and (aim or S.noRecoil or S.noSpread) then
            local comp = S.noRecoil or (aim and S.rage and S.rageRecoil) or (aim and not S.rage)
            local punch = comp and punchOf(sim) or nil
            local sx, sy = 0, 0
            tickState.shotGuard = nil
            if S.noSpread or (aim and S.rage and S.rageNoSpread) then
                sx, sy = nextSpread(char, weapon, dt)
                tickState.pred = { sx, sy }
                if aim and aim.entity and S.spreadGuard then
                    local origin = eyePos(sim)
                    local point = guardedPoint(aim.entity, origin, dir, sx, sy)
                    if point then
                        dir = (point - origin).Unit
                        tickState.shotGuard = true
                    else
                        tickState.shotGuard = false
                    end
                end
            else
                tickState.pred = nil
            end
            local yaw, pitch
            if punch then
                yaw, pitch = solveAngles(dir, punch, sx, sy)
            else

                yaw, pitch = solveAngles(dir, Vector3.zero, sx, sy)
            end
            local qy, qp = quantize(yaw, pitch)
            cmd.Yaw, cmd.Pitch = qy, qp
            sim.Yaw, sim.Pitch = dequantize(qy, qp)
        end
    end

    if S.rage and S.autoScope and tickState.rageSeen and weapon.IsSniper and (weapon.ZoomLevel or 0) == 0
        and not weapon.Reloading and not weapon.Equipping then
        tickState.scopePulse = not tickState.scopePulse
        WC.UpdateKeyState("WishFire2", tickState.scopePulse)
        tickState.scoping = true
    elseif tickState.scoping then
        tickState.scoping, tickState.scopePulse = false, false
        WC.UpdateKeyState("WishFire2", UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton2) and not menuBlocked())
    end

    if S.autoReload and isGun(weapon) and not weapon.Reloading and not tickState.aim then
        local d = weapon.Data
        if d.Ammo <= S.reloadAt and d.Ammo < d.ClipSize and (d.ReserveAmmo or 0) > 0 and not held then
            WC.UpdateKeyState("WishReload", true)
            tickState.forcedReload = true
        end
    elseif tickState.forcedReload then
        tickState.forcedReload = false
        WC.UpdateKeyState("WishReload", false)
    end

    if want and not held and (tickState.fireHold or 0) <= 0 and (tickState.fireRelease or 0) <= 0 then
        tickState.forcedShots = (tickState.forcedShots or 0) + 1
        tickState.lastRageShot = os.clock()
        tickState.fireHold = S.fireTap and 1 or math.random(4, 7)
    end
    if (tickState.fireHold or 0) > 0 then
        tickState.fireHold = tickState.fireHold - 1
        WC.UpdateKeyState("WishFire", true)
        tickState.forcedFire = true
        if tickState.fireHold == 0 then tickState.fireRelease = S.fireTap and 1 or math.random(2, 4) end
    else
        if tickState.forcedFire then
            tickState.forcedFire = false
            WC.UpdateKeyState("WishFire", held)
        end
        if (tickState.fireRelease or 0) > 0 then tickState.fireRelease = tickState.fireRelease - 1 end
    end
end

local saved = {}
restoreInputs = LUAQ_NO_VIRTUALIZE(function(char)
    if saved.angles then
        pcall(CamCtl.SetAngles, saved.angles[1], saved.angles[2])
        saved.angles = nil
    end
    if saved.move then
        if char then char.Left, char.Right, char.Forward, char.Backward = saved.move[1], saved.move[2], saved.move[3], saved.move[4] end
        saved.move = nil
    end
    if saved.jump ~= nil then
        if char then char.Jump = saved.jump end
        saved.jump = nil
    end
    if saved.duck ~= nil then
        if char then char.Duck = saved.duck end
        saved.duck = nil
    end
end)

--!luaq:no_virtualize
local function preTick(dt)
    local char = localChar()
    restoreInputs(char)
    tickState.aim = nil
    tickState.pred = nil
    tickState.rageSeen = false
    tickState.preRuns = (tickState.preRuns or 0) + 1
    if not char or menuBlocked() then return end

    local qy, qp = CamCtl.GetMapAngles()
    local mx = (char.Left or 0) + (char.Right or 0)
    local mz = (char.Forward or 0) + (char.Backward or 0)
    local t = math.sqrt(mx * mx + mz * mz) * 0.3826834
    local f0, b0, l0, r0 = mz < -t, mz > t, mx < -t, mx > t
    local j0, d0 = char.Jump == true, char.Duck == true
    local cmd = {
        Yaw = qy, Pitch = qp, ClientTick = M.Tick.GetTick(),
        Inputs = { Forward = f0, Backward = b0, Left = l0, Right = r0 },
        AdditionalInputs = { Jump = j0, Duck = d0, Walk = char.Walk == true, PressE = char.PressE == true },
    }
    createMove(char, cmd)

    if cmd.Yaw ~= qy or cmd.Pitch ~= qp then
        local y0, p0 = CamCtl.GetAngles()
        saved.angles = { y0, p0 }
        local cw = tickState.camWrite
        if cw then

            saved.angles = { wrap(cw[1]), math.clamp(cw[2], -PITCH_MAX, PITCH_MAX) }
        end

        local y, pch = dequantize(cmd.Yaw, cmd.Pitch)
        CamCtl.SetAngles(wrap(y + math.pi / 65535), math.min(pch + PITCH_MAX / 65535, PITCH_MAX))
    end
    local inp, add = cmd.Inputs, cmd.AdditionalInputs
    if inp.Forward ~= f0 or inp.Backward ~= b0 or inp.Left ~= l0 or inp.Right ~= r0 then
        saved.move = { char.Left, char.Right, char.Forward, char.Backward }
        char.Left, char.Right = inp.Left and -1 or 0, inp.Right and 1 or 0
        char.Forward, char.Backward = inp.Forward and -1 or 0, inp.Backward and 1 or 0
    end
    if (add.Jump == true) ~= j0 then
        saved.jump = char.Jump
        char.Jump = add.Jump == true
    end
    if (add.Duck == true) ~= d0 then
        saved.duck = char.Duck
        char.Duck = add.Duck == true
    end
end

do
    local pre = M.Tick.OnTick.Connect({
        Priority = 1,
        SubPriority = 0.5,
        Function = LUAQ_NO_VIRTUALIZE(function(dt)
            if hub.unloaded then return end
            local ok, err = pcall(preTick, dt)
            if not ok then
                pcall(restoreInputs, localChar())
                if not tickState.warned then
                    tickState.warned = true
                end
            end
        end),
    })
    hub.onUnload(function()
        pcall(pre.Disconnect)
        pcall(restoreInputs, localChar())
    end)
end

do
    local slot = M.Tick.OnTick.Connect({
        Priority = 1,
        SubPriority = 1.5,
        Function = LUAQ_NO_VIRTUALIZE(function(dt)
            if hub.unloaded then return end
            local ok, err = pcall(preWeapon, dt)
            if not ok and not tickState.warned2 then
                tickState.warned2 = true
            end
        end),
    })
    hub.onUnload(function()
        pcall(slot.Disconnect)
        if tickState.forcedFire then pcall(WC.UpdateKeyState, "WishFire", false) end
        if tickState.forcedReload then pcall(WC.UpdateKeyState, "WishReload", false) end
    end)
end

swapWhen(function() return S.noRecoil or S.noShake end, M.PlayerCamera, "Update", function(orig)
    return function(self, cf, char, ...)

        local zeroAim = S.noRecoil or S.noShake
        local zeroView = S.noRecoil or S.noShake
        local sim = ((zeroAim or zeroView) and not hub.unloaded and type(char) == "table") and char.Simulation or nil
        if not sim then return orig(self, cf, char, ...) end
        local prev = char.PreviousSimulation
        local a, av, v = sim.AimPunchAngle, sim.AimPunchAngleVel, sim.ViewPunchAngle
        local pg = prev and prev.OnGround
        if zeroAim then
            sim.AimPunchAngle, sim.AimPunchAngleVel = Vector3.zero, Vector3.zero
        end
        sim.ViewPunchAngle = Vector3.zero

        if prev and S.noShake then prev.OnGround = sim.OnGround end
        local res = table.pack(pcall(orig, self, cf, char, ...))
        sim.AimPunchAngle, sim.AimPunchAngleVel, sim.ViewPunchAngle = a, av, v
        if prev then prev.OnGround = pg end
        if not res[1] then return end
        return table.unpack(res, 2, res.n)
    end
end)

swapWhen(function() return S.noShake end, CamCtl, "StartShake", function(orig)
    return function(...)
        if S.noShake and not hub.unloaded then return end
        return orig(...)
    end
end)

local hitLog = { entries = {}, onConfirm = nil }
local markers = {}
local hud = { hits = 0, shots = 0 }
local pend

do

--!luaq:no_virtualize
local function logLine(text, color)
    local list = hitLog.entries
    table.insert(list, 1, { text = text, color = color or Color3.new(1, 1, 1), at = os.clock() })
    while #list > 8 do list[#list] = nil end
end

pend = { list = {}, missColor = Color3.fromRGB(255, 95, 95) }

pend.window = LUAQ_NO_VIRTUALIZE(function()
    local ok, ping = pcall(function() return LocalPlayer:GetNetworkPing() end)
    ping = (ok and tonumber(ping)) or 0.1
    return math.clamp(0.35 + ping * 2.5, 0.45, 1.5)
end)

pend.part = LUAQ_NO_VIRTUALIZE(function(part)
    if type(part) ~= "string" then return nil end
    local p = part:lower()
    if p:find("head") then return "head" end
    if p:find("leg") or p:find("foot") then return "leg" end
    if p:find("arm") or p:find("hand") then return "arm" end
    return "body"
end)

pend.name = LUAQ_NO_VIRTUALIZE(function(userId, e)
    if e then return entName(e) end
    local p = Players:GetPlayerByUserId(userId)
    return p and p.DisplayName or "enemy"
end)

pend.expire = LUAQ_NO_VIRTUALIZE(function(now)
    for i = #pend.list, 1, -1 do
        local h = pend.list[i]
        if now > h.deadline then
            table.remove(pend.list, i)
            if S.hitLogs then
                logLine(string.format("missed %s in the %s due to server", h.name, h.part or "body"), pend.missColor)
            end
        end
    end
end)

--!luaq:no_virtualize
local function fxPart(size, cf, color, life)
    local p = Instance.new("Part")
    p.Anchored, p.CanCollide, p.CanQuery, p.CanTouch, p.CastShadow = true, false, false, false, false
    p.Material = Enum.Material.Neon
    p.Color = color
    p.Size = size
    p.CFrame = cf
    p.Parent = fxFolder
    TweenService:Create(p, TweenInfo.new(life, Enum.EasingStyle.Quad), { Transparency = 1 }):Play()
    Debris:AddItem(p, life + 0.1)
    return p
end

local lastShot = { at = 0 }
local hpSeen = {}
for _, e in pairs(Entities.GetAllCategoryEntities("Character")) do
    if e.UserId then hpSeen[e.UserId] = e.Health end
end

local tracerHue = 0
--!luaq:no_virtualize
local function drawTracer(weapon, origin, finish, hitSomething)
    local start = origin
    if S.tracerFrom == "Gun" then
        local muzzle = weapon.Viewmodel and weapon.Viewmodel:FindFirstChild("Muzzle", true)
        start = (muzzle and muzzle:IsA("BasePart")) and muzzle.Position
            or (CamCtl.GetAppliedCFrame() * Vector3.new(0.35, -0.35, -1.5))
    end
    local color = tracerColor
    if S.tracerRainbow then
        tracerHue = (tracerHue + 0.07) % 1
        color = Color3.fromHSV(tracerHue, 0.85, 1)
    end
    local life, width = S.tracerLife, S.tracerWidth
    local len = (finish - start).Magnitude

    if S.tracer and len > 0.5 then
        if S.tracerStyle == "Beam" then

            local holder = Instance.new("Part")
            holder.Anchored, holder.CanCollide, holder.CanQuery, holder.CanTouch = true, false, false, false
            holder.Transparency, holder.Size, holder.CFrame = 1, Vector3.new(0.1, 0.1, 0.1), CFrame.new(start)
            holder.Parent = fxFolder
            local a0 = Instance.new("Attachment", holder)
            local a1 = Instance.new("Attachment", holder)
            a1.WorldPosition = finish
            local beam = Instance.new("Beam")
            beam.Attachment0, beam.Attachment1 = a0, a1
            beam.Width0, beam.Width1 = width * 2.5, width * 0.6
            beam.FaceCamera = true
            beam.LightEmission, beam.LightInfluence = 1, 0
            beam.Color = ColorSequence.new(color)
            beam.Parent = holder
            task.spawn(function()
                local t0 = os.clock()
                while holder.Parent and os.clock() - t0 < life do
                    local k = (os.clock() - t0) / life
                    beam.Transparency = NumberSequence.new(k * 0.9, math.min(1, 0.3 + k))
                    task.wait(0.03)
                end
                holder:Destroy()
            end)
        elseif S.tracerStyle == "Lightning" then

            local steps = math.clamp(math.floor(len / 4), 4, 14)
            local dir = (finish - start).Unit
            local side = dir:Cross(Vector3.new(0, 1, 0))
            if side.Magnitude < 1e-3 then side = Vector3.new(1, 0, 0) end
            side = side.Unit
            local up = side:Cross(dir).Unit
            local prev = start
            for i = 1, steps do
                local p = start + (finish - start) * (i / steps)
                if i < steps then
                    p = p + side * (math.random() - 0.5) * 0.9 + up * (math.random() - 0.5) * 0.9
                end
                local seg = (p - prev).Magnitude
                if seg > 0.05 then
                    fxPart(Vector3.new(width, width, seg), CFrame.lookAt((prev + p) / 2, p), color, life)
                end
                prev = p
            end
        else
            fxPart(Vector3.new(width, width, len), CFrame.lookAt((start + finish) / 2, finish), color, life)
        end
    end

    if S.impact and hitSomething then
        local size = S.impactSize
        local dotPart = fxPart(Vector3.new(size, size, size), CFrame.new(finish), impactColor, life)
        if S.impactGlow then
            local light = Instance.new("PointLight")
            light.Color, light.Range, light.Brightness = impactColor, 6, 2
            light.Parent = dotPart
        end
    end
end

--!luaq:no_virtualize
local function onFired(weapon)
    hud.shots = hud.shots + 1
    local char = localChar()
    if not char or type(weapon) ~= "table" or not weapon.Data then return end
    local sim = char.Simulation

    local pred = tickState.pred
    tickState.pred = nil
    local sx, sy = 0, 0
    if weapon.Data.Type ~= "Melee" then
        pcall(function()
            local rng = M.Math.UniformRandomStream(spreadSeed(weapon.RandomSeed or 0))
            sx, sy = Bullet.SpreadOffset(weapon, rng, weapon:GetInaccuracy(sim), weapon:GetSpread(), 1)
            if pred then
                local err = math.sqrt((sx - pred[1]) ^ 2 + (sy - pred[2]) ^ 2)
                tickState.spreadChecks = (tickState.spreadChecks or 0) + 1
                tickState.spreadErrMax = math.max(tickState.spreadErrMax or 0, err)
                tickState.spreadSize = math.sqrt(sx * sx + sy * sy)
                if err < 1e-4 then tickState.spreadExact = (tickState.spreadExact or 0) + 1 end
            end
        end)
    end

    local cf = sim:BuildShotCFrame(true)
    local origin = cf.Position
    local dir = (cf.LookVector + cf.RightVector * sx + cf.UpVector * sy).Unit
    local aimed = tickState.aim
    if aimed and aimed.pos then

        local want = aimed.pos - origin
        if want.Magnitude > 0.1 then
            local err = math.deg(math.acos(math.clamp(want.Unit:Dot(dir), -1, 1)))
            tickState.aimShots = (tickState.aimShots or 0) + 1
            tickState.aimErrSum = (tickState.aimErrSum or 0) + err
            tickState.aimErrMax = math.max(tickState.aimErrMax or 0, err)
            tickState.aimErrLast = err
        end
    end
    local range = math.min(weapon.Data.Range or 300, 1200)
    local chars = workspace:FindFirstChild("Characters")
    local filter = {}
    if refreshMap() then filter[#filter + 1] = mapGeometry end
    if chars then filter[#filter + 1] = chars end
    trigParams.FilterDescendantsInstances = filter
    local r = workspace:Raycast(origin, dir * range, trigParams)
    local finish = r and r.Position or (origin + dir * range)
    local shot = { at = os.clock(), origin = origin, dir = dir, weapon = weapon, pos = finish, guard = tickState.shotGuard,
        air = sim.OnGround ~= true, comp = pred ~= nil }
    if shot.comp then
        if shot.air then tickState.airShots = (tickState.airShots or 0) + 1
        else tickState.groundShots = (tickState.groundShots or 0) + 1 end
    end
    tickState.shotGuard = nil
    if r and chars and r.Instance:IsDescendantOf(chars) then
        local model = r.Instance
        while model and model.Parent ~= chars do model = model.Parent end
        shot.entity = model and Entities.GetEntity("Character", tonumber(model.Name))
        shot.part = r.Instance.Name

        if shot.entity and isEnemy(shot.entity) then
            tickState.clientHits = (tickState.clientHits or 0) + 1
            if shot.comp then
                if shot.air then tickState.airClient = (tickState.airClient or 0) + 1
                else tickState.groundClient = (tickState.groundClient or 0) + 1 end
            end
            if shot.guard == true then tickState.cHitG = (tickState.cHitG or 0) + 1
            elseif shot.guard == false then tickState.cHitU = (tickState.cHitU or 0) + 1 end
            if aimed then tickState.clientAimHits = (tickState.clientAimHits or 0) + 1 end
            local uid = shot.entity.UserId
            if uid and (shot.entity.Health or 0) > 0 then
                pend.list[#pend.list + 1] = {
                    userId = uid, name = entName(shot.entity), part = pend.part(shot.part),
                    deadline = shot.at + pend.window(),
                }
            end
        end
    end
    lastShot = shot

    local onTarget = shot.entity ~= nil and isEnemy(shot.entity)
    if weapon.Data.Type ~= "Melee" and (S.tracer or S.impact) and (onTarget or not S.tracerOnlyHits) then
        pcall(drawTracer, weapon, origin, finish, r ~= nil)
    end
end

--!luaq:no_virtualize
local function onHealth(userId, health)
    local before = hpSeen[userId]
    hpSeen[userId] = health
    if not before or not health or health >= before or userId == LocalPlayer.UserId then return end
    local shot = lastShot

    local pending
    for i, h in ipairs(pend.list) do
        if h.userId == userId then
            pending = table.remove(pend.list, i)
            break
        end
    end
    if not pending and os.clock() - shot.at > pend.window() then return end

    local e = Entities.GetCharacterByUserId(userId)
    local mine = pending ~= nil or (shot.entity ~= nil and shot.entity.UserId == userId)
    if not mine and e and e.Position and shot.dir then
        local to = (e.Position + Vector3.new(0, 2.5, 0)) - shot.origin
        mine = to.Magnitude > 0.1 and to.Unit:Dot(shot.dir) > 0.985
    end
    if not mine or (e and not isEnemy(e)) then return end

    local damage = before - math.max(health, 0)
    local lethal = health <= 0
    local base = (shot.weapon and shot.weapon.Data and shot.weapon.Data.Damage) or 30
    local head = (shot.entity and shot.part == "Head") or damage >= base * 2.2
    local name = (pending and pending.name) or pend.name(userId, e)
    local where = (pending and pending.part) or (head and "head" or "body")
    local pos = (shot.entity and shot.entity.UserId == userId) and shot.pos or (e and e.CFrame.Position + Vector3.new(0, 2.5, 0))
    hud.hits = hud.hits + 1
    if shot.comp and not shot.counted then
        if shot.air then tickState.airServer = (tickState.airServer or 0) + 1
        else tickState.groundServer = (tickState.groundServer or 0) + 1 end
    end
    if shot.guard == true and not shot.counted then tickState.sHitG = (tickState.sHitG or 0) + 1
    elseif shot.guard == false and not shot.counted then tickState.sHitU = (tickState.sHitU or 0) + 1 end
    shot.counted = true
    markers[#markers + 1] = { at = os.clock(), kill = lethal, damage = damage, pos = pos }
    if S.hitSound then playSound(S.hitSoundId, S.hitVolume) end
    if S.hitLogs then
        if lethal then
            logLine(string.format("killed %s - %s, %d dmg", name, where, damage), S.killColor)
        else
            logLine(string.format("hit %s in the %s for %d (%d left)", name, where,
                damage, math.max(0, health)), where == "head" and S.killColor or nil)
        end
    end
    if hitLog.onConfirm and e then pcall(hitLog.onConfirm, e, damage, lethal) end

    if lethal then
        if S.killSound then playSound(S.killSoundId, S.killVolume) end
        if S.killFx and pos then
            local ring = fxPart(Vector3.new(1, 1, 1), CFrame.new(pos), S.killFxColor, 0.7)
            ring.Shape = Enum.PartType.Ball
            ring.Transparency = 0.25
            TweenService:Create(ring, TweenInfo.new(0.7, Enum.EasingStyle.Quint, Enum.EasingDirection.Out),
                { Size = Vector3.new(11, 11, 11) }):Play()
        end
    end
end

do
    local conns = {}
    conns[1] = WC.OnWeaponShoot:Connect(function(weapon)
        if not hub.unloaded then pcall(onFired, weapon) end
    end)
    conns[2] = Entities.OnHealthUpdate:Connect(function(userId, health)
        if not hub.unloaded then pcall(onHealth, userId, health) end
    end)
    hub.onUnload(function()
        for _, c in ipairs(conns) do
            pcall(function() if c and c.Disconnect then c:Disconnect() end end)
        end
    end)
end

end

swapWhen(function() return S.fovChanger or S.noZoom end, CamCtl, "SetFOVAmount", function(orig)
    return function(fov, ...)
        if hub.unloaded or type(fov) ~= "number" or not (S.fovChanger or S.noZoom) then
            return orig(fov, ...)
        end
        local base = CamCtl.GetSettingsFieldOfView()
        local zooming = fov < base - 0.01
        local shown, sens = fov, fov / base
        if zooming then
            if S.noZoom then
                shown, sens = S.fovChanger and S.fovValue or base, 1
            elseif S.fovChanger then

                shown = S.fovValue * fov / base
            end
        elseif S.fovChanger then
            shown = S.fovValue
        end
        local r = orig(shown, ...)
        pcall(M.CameraInput.SetSensitivityFieldOfViewMultiplier, sens)
        return r
    end
end)
--!luaq:no_virtualize
local function reapplyFov()
    syncSwaps()
    pcall(function()
        if CamCtl.InFirstPersonView() then CamCtl.SetFOVAmount(CamCtl.GetSettingsFieldOfView()) end
    end)
end
hub.onUnload(function()
    S.fovChanger, S.noZoom = false, false
    reapplyFov()
end)

local tp = { active = false, ent = nil, entId = nil, weaponKey = nil, failed = false }

local layoutScopeLines
do
    local scopeFrame
    --!luaq:no_virtualize
    local function getScope()
        if scopeFrame and scopeFrame.Parent then return scopeFrame end
        local pg = LocalPlayer:FindFirstChildOfClass("PlayerGui")
        local gui = pg and pg:FindFirstChild("GUI")
        local hudFrame = gui and gui:FindFirstChild("HUD")
        scopeFrame = hudFrame and hudFrame:FindFirstChild("Scope")
        return scopeFrame
    end

    local scopeLines = {}
    for i = 1, 4 do
        local line = Instance.new("Frame")
        line.BorderSizePixel = 0
        line.Visible = false
        line.Parent = overlay
        local grad = Instance.new("UIGradient")
        grad.Rotation = i <= 2 and 0 or 90
        grad.Parent = line
        scopeLines[i] = line
    end
    local SOLID = NumberSequence.new(0)
    local FADE_IN, FADE_OUT = NumberSequence.new(1, 0), NumberSequence.new(0, 1)
    layoutScopeLines = LUAQ_NO_VIRTUALIZE(function()
        local gradient = S.scopeStyle == "Gradient"
        local gap = gradient and S.scopeGap or 0
        local len = gradient and (S.scopeLen / 100) or 1
        local thick = gradient and S.scopeThick or 1
        local color = gradient and S.scopeColor or Color3.new(0, 0, 0)
        for i, line in ipairs(scopeLines) do
            local grad = line:FindFirstChildOfClass("UIGradient")
            line.BackgroundColor3 = color
            if i == 1 then
                line.AnchorPoint = Vector2.new(1, 0.5)
                line.Position = UDim2.new(0.5, -gap, 0.5, 0)
                line.Size = UDim2.new(0.5 * len, 0, 0, thick)
                grad.Transparency = gradient and FADE_IN or SOLID
            elseif i == 2 then
                line.AnchorPoint = Vector2.new(0, 0.5)
                line.Position = UDim2.new(0.5, gap, 0.5, 0)
                line.Size = UDim2.new(0.5 * len, 0, 0, thick)
                grad.Transparency = gradient and FADE_OUT or SOLID
            elseif i == 3 then
                line.AnchorPoint = Vector2.new(0.5, 1)
                line.Position = UDim2.new(0.5, 0, 0.5, -gap)
                line.Size = UDim2.new(0, thick, 0.5 * len, 0)
                grad.Transparency = gradient and FADE_IN or SOLID
            else
                line.AnchorPoint = Vector2.new(0.5, 0)
                line.Position = UDim2.new(0.5, 0, 0.5, gap)
                line.Size = UDim2.new(0, thick, 0.5 * len, 0)
                grad.Transparency = gradient and FADE_OUT or SOLID
            end
        end
    end)
    layoutScopeLines()

    local hidden = {}
    --!luaq:no_virtualize
    local function restoreScope()
        for inst in pairs(hidden) do
            if inst.Parent then pcall(function() inst.Visible = true end) end
        end
        table.clear(hidden)
    end

    --!luaq:no_virtualize
    local function rifleScoped(w)
        local alt = w and next(w) and w.Data and w.Data.AltFunction
        return alt ~= nil and alt.Name == "ScopeRifle" and w.Mode == 2
    end
    local vmHiddenFor
    --!luaq:no_virtualize
    local function showViewmodel()
        local w = vmHiddenFor
        vmHiddenFor = nil
        if w then pcall(M.Viewmodel.SetVisible, w, not tp.active and (w.ZoomLevel or 0) == 0) end
    end
    hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function()
        local sf = getScope()
        local weapon = WC.GetCurrentWeapon()
        local rifle = rifleScoped(weapon)
        local art = sf ~= nil and sf.Visible

        if (S.noBorders or tp.active) and art then
            for _, c in ipairs(sf:GetChildren()) do
                if c:IsA("GuiObject") and c.Visible then
                    hidden[c] = true
                    c.Visible = false
                end
            end
        elseif next(hidden) then
            restoreScope()
        end
        local hideVm = S.noBorders and rifle and not tp.active
        if hideVm and vmHiddenFor ~= weapon then
            showViewmodel()
            vmHiddenFor = weapon
            pcall(M.Viewmodel.SetVisible, weapon, false)
        elseif not hideVm and vmHiddenFor then
            showViewmodel()
        end
        local show = S.noBorders and (art or rifle)
        for _, line in ipairs(scopeLines) do line.Visible = show end
    end))
    hub.onUnload(restoreScope)
    hub.onUnload(showViewmodel)
end

do
    local STEP = "ZamltraThirdPerson"

    --!luaq:no_virtualize
    local function destroyBody()
        local ent = tp.ent
        tp.ent, tp.entId, tp.weaponKey = nil, nil, nil
        if ent then
            if tp.onRemove then pcall(tp.onRemove, ent) end
            pcall(function() ent:Destroy() end)
        end
    end

    --!luaq:no_virtualize
    local function buildBody(sim)
        local team = myTeam()
        local agent
        pcall(function()
            local loadout = HttpService:JSONDecode(LocalPlayer:GetAttribute("WeaponLoadout"))[team]
            agent = table.find(Enums.Items.Agents, loadout["15"].SkinName)
        end)
        local ok, ent = pcall(M.Character.new, sim.Identifier, {
            UserId = LocalPlayer.UserId, Team = table.find(Enums.Teams, team), Agent = agent,
        })
        if not ok or type(ent) ~= "table" or not ent.Model then
            tp.failed = true
            return
        end
        ent.Model.Parent = fxFolder
        tp.ent, tp.entId = ent, sim.Identifier

        if tp.onBody then pcall(tp.onBody, ent) end
    end

    --!luaq:no_virtualize
    local function updateBody(char, dt)
        local sim = char.Simulation
        if tp.ent and tp.entId ~= sim.Identifier then destroyBody() end
        if not tp.ent and not tp.failed then buildBody(sim) end
        local ent = tp.ent
        if not ent then return end

        local pos, prev = sim.Position, char.PreviousSimulation
        if prev and prev.Position and (prev.Position - pos).Magnitude < 5 then
            pos = prev.Position:Lerp(pos, math.clamp(M.Tick.GetAccumulatedTime() / tickDt(), 0, 1))
        end
        local yaw, pitch

        local sent = S.tpBody == "Sent Angles" or S.aa
        if sent then
            yaw, pitch = sim.Yaw, sim.Pitch
        else
            yaw, pitch = CamCtl.GetAngles()
        end
        if not (S.tpBodyRot or S.aa) then pitch = 0 end
        local snap = {
            Position = pos, Yaw = yaw, Pitch = pitch, AimPunchAngle = Vector3.zero,
            Ducked = sim.Ducked, Ducking = sim.Ducking, OnGround = sim.OnGround,
            Climbing = sim.Climbing, LadderNormal = sim.LadderNormal,
        }
        ent.Velocity = sim.Velocity
        ent:Interpolate(snap, snap, 1, 0, dt)

        ent.PrimaryPart:PivotTo(ent.CFrame)
        if ent.NameTag then ent.NameTag.Enabled = false end
        if ent.Model.Parent ~= fxFolder then ent.Model.Parent = fxFolder end

        local w = WC.GetCurrentWeapon()
        local key = (w and next(w)) and (w.Name .. "|" .. tostring(w.Skin)) or nil
        if key ~= tp.weaponKey then
            tp.weaponKey = key
            if key then
                local data = {
                    Name = w.Name, Skin = w.Skin, Slot = w.Slot, Mode = w.Mode or 1,
                    Ammo = w.Data.Ammo or 0, ReserveAmmo = w.Data.ReserveAmmo or 0,
                    Reloading = false, Firing = false, ZoomLevel = 0, Variant = 0,
                }
                ent.CharacterCurrentWeapon = data
                pcall(function() ent.CurrentWeaponChanged:Fire(data) end)
            end
        end
    end

    swapWhen(function() return S.tp end, M.Viewmodel, "SetVisible", function(orig)
        return function(weapon, vis, ...)
            if tp.active and not hub.unloaded then vis = false end
            return orig(weapon, vis, ...)
        end
    end)

    --!luaq:no_virtualize
    local function setActive(on, weapon)
        if on == tp.active then return end
        tp.active = on
        if weapon and next(weapon) then
            pcall(M.Viewmodel.SetVisible, weapon, (not on) and (weapon.ZoomLevel or 0) == 0)
        end
        if not on then

            local ent = tp.ent
            if ent then
                pcall(function() ent.PrimaryPart:PivotTo(ent.CFrame + Vector3.new(0, -1000000, 0)) end)
            end
            pcall(function() Camera.CFrame = CamCtl.GetAppliedCFrame() end)
        end
    end

    RunService:BindToRenderStep(STEP, Enum.RenderPriority.Camera.Value + 10, LUAQ_NO_VIRTUALIZE(function(dt)

        if setthreadidentity then pcall(setthreadidentity, 2) end
        local char = localChar()
        local weapon = WC.GetCurrentWeapon()
        local scoped = weapon and next(weapon) and (weapon.ZoomLevel or 0) > 0
        local want = S.tp and char ~= nil and CamCtl.GetTarget() == 1
        if not S.tp then tp.failed = false end
        if not char and tp.ent then destroyBody() end
        setActive(want and true or false, weapon)

        local vm = want and weapon and next(weapon) and weapon.Viewmodel or nil
        if vm ~= tp.vmModel or os.clock() - (tp.vmScan or 0) > 0.25 then
            tp.vmScan = os.clock()
            for part in pairs(tp.vmParts or {}) do
                if not (vm and part:IsDescendantOf(vm)) then pcall(function() part.LocalTransparencyModifier = 0 end) end
            end
            tp.vmModel, tp.vmParts = vm, {}
            if vm then
                for _, d in ipairs(vm:GetDescendants()) do
                    if d:IsA("BasePart") then tp.vmParts[d] = true end
                end
            end
        end
        for part in pairs(tp.vmParts) do part.LocalTransparencyModifier = 1 end
        if not want then return end

        local eye = CamCtl.GetAppliedCFrame()
        local goal = eye * CFrame.new(S.tpShoulder, S.tpHeight, S.tpDist)
        if S.tpCollide and refreshMap() then
            local from = eye.Position
            local d = goal.Position - from
            if d.Magnitude > 0.05 then
                local r = workspace:Spherecast(from, 0.4, d, mapParams)
                if r then goal = goal.Rotation + (from + d.Unit * math.max(r.Distance - 0.1, 0)) end
            end
        end
        Camera.CFrame = goal

        local ok, err = pcall(updateBody, char, dt)
        if not ok and not tp.warned then
            tp.warned = true
        end
    end))
    hub.onUnload(function()
        pcall(function() RunService:UnbindFromRenderStep(STEP) end)
        if setthreadidentity then pcall(setthreadidentity, 2) end
        setActive(false, WC.GetCurrentWeapon())
        for part in pairs(tp.vmParts or {}) do pcall(function() part.LocalTransparencyModifier = 0 end) end
        tp.vmParts = {}
        destroyBody()
        elevate()
    end)
end

swapWhen(function() return S.vmOn end, M.Viewmodel, "Render", function(orig)
    return function(cf, ...)
        if S.vmOn and not hub.unloaded and typeof(cf) == "CFrame" then
            cf = cf * CFrame.new(S.vmX, S.vmY, S.vmZ)
        end
        return orig(cf, ...)
    end
end)

do
    local saved = {}
    --!luaq:no_virtualize
    local function restore()
        for part, o in pairs(saved) do
            pcall(function()
                part.Material, part.Color = o.mat, o.color
                if part.Transparency < 1 then part.Transparency = o.transp end
                if o.tex then part.TextureID = o.tex end
                if o.sa then o.sa.Parent = part end
            end)
        end
        table.clear(saved)
    end
    local last = 0
    hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function()
        if not S.vmChams then
            if next(saved) then restore() end
            return
        end
        if os.clock() - last < 0.2 then return end
        last = os.clock()
        local weapon = WC.GetCurrentWeapon()
        local vm = (weapon and next(weapon) and weapon.Viewmodel) or Camera:FindFirstChild("Viewmodel")
        if not (vm and vm.Parent) then return end
        local material = Enum.Material[S.vmMaterial] or Enum.Material.ForceField
        for _, d in ipairs(vm:GetDescendants()) do
            if d:IsA("BasePart") then
                local o = saved[d]
                if not o and d.Transparency < 1 then
                    o = { mat = d.Material, color = d.Color, transp = d.Transparency }
                    if d:IsA("MeshPart") then o.tex = d.TextureID end
                    saved[d] = o
                end
                if o then
                    pcall(function()

                        local sa = d:FindFirstChildOfClass("SurfaceAppearance")
                        if sa then
                            o.sa = sa
                            sa.Parent = nil
                        end
                        if d:IsA("MeshPart") and d.TextureID ~= "" then
                            o.tex = d.TextureID
                            d.TextureID = ""
                        end
                        d.Material, d.Color = material, S.vmColor
                        if d.Transparency < 1 then d.Transparency = math.max(o.transp, S.vmTransparency) end
                    end)
                end
            end
        end
        for part in pairs(saved) do
            if not part.Parent then saved[part] = nil end
        end
    end))
    hub.onUnload(restore)
end

local soundMarks = {}
do
    --!luaq:no_virtualize
    local function note(pos, kind)
        if not S.soundEsp or hub.unloaded or typeof(pos) ~= "Vector3" then return end
        local char = localChar()
        if char and (char.Simulation.Position - pos).Magnitude < 7 then return end
        for _, e in pairs(Entities.GetAllCategoryEntities("Character")) do

            if (e.Health or 0) > 0 and not e.FogCulled and e.Position and (e.Position - pos).Magnitude < 7 then return end
        end
        local now = os.clock()
        local velocity = Vector3.zero
        for i = #soundMarks, 1, -1 do
            local m = soundMarks[i]
            local gap = now - m.at
            if gap < 1.2 and gap > 0.02 and (m.pos - pos).Magnitude < 14 then
                velocity = (pos - m.pos) / gap
                table.remove(soundMarks, i)
                break
            end
        end
        soundMarks[#soundMarks + 1] = { pos = pos, at = now, kind = kind, vel = velocity }
        while #soundMarks > 24 do table.remove(soundMarks, 1) end
    end

    local SM = M.SoundManager
    if type(SM) == "table" then

        swapWhen(function() return S.soundEsp end, SM, "PlayAudio", function(orig)
            return function(name, opts, ...)
                if type(opts) == "table" and opts.Position and type(name) == "string" and name:sub(1, 8) == "Weapons." then
                    pcall(note, opts.Position, "shot")
                end
                return orig(name, opts, ...)
            end
        end)
        for _, fn in ipairs({ "PlayFootstep", "PlayLanding" }) do
            swapWhen(function() return S.soundEsp end, SM, fn, function(orig)
                return function(a, b, opts, ...)
                    local o = (type(opts) == "table" and opts) or (type(b) == "table" and b) or nil
                    if o and (o.FootstepPosition or o.Position) then pcall(note, o.FootstepPosition or o.Position, "step") end
                    return orig(a, b, opts, ...)
                end
            end)
        end
    end
end

local BONES = {
    { "Head", "UpperTorso" }, { "UpperTorso", "LowerTorso" },
    { "UpperTorso", "LeftUpperArm" }, { "LeftUpperArm", "LeftLowerArm" }, { "LeftLowerArm", "LeftHand" },
    { "UpperTorso", "RightUpperArm" }, { "RightUpperArm", "RightLowerArm" }, { "RightLowerArm", "RightHand" },
    { "LowerTorso", "LeftUpperLeg" }, { "LeftUpperLeg", "LeftLowerLeg" }, { "LeftLowerLeg", "LeftFoot" },
    { "LowerTorso", "RightUpperLeg" }, { "RightUpperLeg", "RightLowerLeg" }, { "RightLowerLeg", "RightFoot" },
}
local GREY = Color3.fromRGB(170, 170, 175)
local WHITE = Color3.new(1, 1, 1)
local BLACK = Color3.new(0, 0, 0)

local chamsFolder = Instance.new("Folder")
chamsFolder.Name = "ZamltraChams"
chamsFolder.Parent = (gethui and gethui()) or game:GetService("CoreGui")
hub.onUnload(function() chamsFolder:Destroy() end)
local chamsOf = {}
local track = {}

--!luaq:no_virtualize
local function w2s(pos)
    local sp, on = Camera:WorldToViewportPoint(pos)
    return Vector2.new(sp.X, sp.Y), on, sp.Z
end

--!luaq:no_virtualize
local function espColorFor(e, enemy, seen)
    if S.espColorMode == "Team Side" then
        return (e.Data and e.Data.Team == "CT") and S.ctColor or S.tColor
    elseif S.espColorMode == "Player Color" then
        local p = entPlayer(e)
        local c = p and p:GetAttribute("Color")
        if typeof(c) == "Color3" then return c end
    end
    if not enemy then return S.teamColor end
    if S.visCheck and seen then return S.visColor end
    return S.espColor
end

--!luaq:no_virtualize
local function drawEntity(top, bottom, color, alpha, info)
    local a, onA, depth = w2s(top)
    local b, onB = w2s(bottom)
    local vp = Camera.ViewportSize
    if depth <= 0 or not (onA or onB) then
        if S.arrows and info.enemy then
            local rel = Camera.CFrame:PointToObjectSpace((top + bottom) / 2)
            local dir = Vector2.new(rel.X, -rel.Y)
            dir = (dir.Magnitude > 1e-3) and dir.Unit or Vector2.new(0, 1)
            local c = vp / 2 + dir * S.arrowRadius
            local side = Vector2.new(-dir.Y, dir.X)
            local tip = c + dir * S.arrowSize
            local l, r = c + side * S.arrowSize * 0.6, c - side * S.arrowSize * 0.6
            draw.line(tip, l, color, 2, alpha); draw.line(tip, r, color, 2, alpha); draw.line(l, r, color, 2, alpha)
        end
        return
    end

    local h = math.abs(b.Y - a.Y)
    if h < 2 then return end
    local w = h * 0.5
    local x, y = (a.X + b.X) / 2 - w / 2, math.min(a.Y, b.Y)
    local soft = 0.35 + alpha * 0.65

    if S.box then
        if S.boxStyle == "Corner" then
            local cw, ch = w * 0.28, h * 0.22
            for _, c in ipairs({ { x, y, 1, 1 }, { x + w, y, -1, 1 }, { x, y + h, 1, -1 }, { x + w, y + h, -1, -1 } }) do
                local pt = Vector2.new(c[1], c[2])
                draw.line(pt, pt + Vector2.new(cw * c[3], 0), color, 1, alpha)
                draw.line(pt, pt + Vector2.new(0, ch * c[4]), color, 1, alpha)
            end
            if S.boxFill then draw.rect(x, y, w, h, color, 0, 0.82 + alpha * 0.18) end
        else
            draw.rect(x - 1, y - 1, w + 2, h + 2, BLACK, 1, 1, soft)
            draw.rect(x, y, w, h, color, 1, S.boxFill and (0.82 + alpha * 0.18) or 1, alpha)
        end
    end

    if info.hp then
        local frac = math.clamp(info.hp / 100, 0, 1)
        if S.hpBar then
            draw.rect(x - 6, y - 1, 3, h + 2, BLACK, 0, soft)
            draw.rect(x - 5, y + h * (1 - frac), 1, h * frac, Color3.fromHSV(frac * 0.33, 0.9, 1), 0, alpha)
        end
        if S.hpNum then
            draw.text(tostring(math.floor(info.hp)), x - (S.hpBar and 9 or 4), y + h * (1 - frac) - 2,
                Color3.fromHSV(frac * 0.33, 0.6, 1), S.textSize - 2, 1, alpha)
        end
    end
    local armorShown = S.armorBar and info.armor and info.armor > 0
    if armorShown then
        local frac = math.clamp(info.armor / 100, 0, 1)
        draw.rect(x - 1, y + h + 2, w + 2, 3, BLACK, 0, soft)
        draw.rect(x, y + h + 3, w * frac, 1, Color3.fromRGB(90, 160, 255), 0, alpha)
    end

    local cx = x + w / 2
    if (S.names or info.forceName) and info.name then
        draw.text(info.name, cx, y - S.textSize - 3, WHITE, S.textSize, 0.5, alpha)
    end
    local below = y + h + (armorShown and 6 or 2)
    if S.weaponText and info.weapon then
        draw.text(info.weapon, cx, below, Color3.fromRGB(220, 220, 225), S.textSize - 1, 0.5, alpha)
        below = below + S.textSize
    end
    if S.distText and info.dist then
        draw.text(string.format("%dm", info.dist), cx, below, Color3.fromRGB(200, 200, 205), S.textSize - 1, 0.5, alpha)
        below = below + S.textSize
    end
    if info.note then
        draw.text(info.note, cx, below, GREY, S.textSize - 1, 0.5, alpha)
    end
    if S.flags and info.flags then
        for i, f in ipairs(info.flags) do
            draw.text(f[1], x + w + 4, y + (i - 1) * (S.textSize - 1), f[2], S.textSize - 2, 0, alpha)
        end
    end
    if S.snaplines and info.enemy then
        local from = (S.snapOrigin == "Top") and Vector2.new(vp.X / 2, 0)
            or (S.snapOrigin == "Center") and vp / 2 or Vector2.new(vp.X / 2, vp.Y)
        draw.line(from, Vector2.new(cx, y + h), color, 1, alpha)
    end
end

--!luaq:no_virtualize
local function setChams(e, color, on, hp)
    local id = e.Identifier
    local h = chamsOf[id]
    if not on then
        if h then h.Enabled = false end
        return
    end
    if not h or h.Parent == nil then
        elevate()
        h = Instance.new("Highlight")
        h.Parent = chamsFolder
        chamsOf[id] = h
    end
    local mode = S.chamsMode
    local fill, outline = S.chamsFill, 0.1
    if mode == "Outline" then fill = 1
    elseif mode == "Solid" then fill, outline = 0, 1
    elseif mode == "Pulse" then fill = S.chamsFill + (1 - S.chamsFill) * (0.5 + 0.5 * math.sin(os.clock() * 4))
    elseif mode == "Rainbow" then color = Color3.fromHSV((os.clock() * 0.25) % 1, 0.85, 1)
    elseif mode == "Health" then color = Color3.fromHSV(math.clamp((hp or 100) / 100, 0, 1) * 0.33, 0.9, 1) end
    h.Adornee = e.Model
    h.Enabled = true
    h.DepthMode = S.chamsOccluded and Enum.HighlightDepthMode.Occluded or Enum.HighlightDepthMode.AlwaysOnTop
    h.FillColor, h.OutlineColor = color, color
    h.FillTransparency, h.OutlineTransparency = fill, outline
end

local leakFn, leakLookedAt = nil, 0
--!luaq:no_virtualize
local function radarLeaks()
    if not leakFn and os.clock() - leakLookedAt > 5 then
        leakLookedAt = os.clock()
        local ok, found = pcall(filtergc, "function", { Name = "ApplyLeak" }, false)
        leakFn = ok and type(found) == "table" and found[1] or nil
    end
    if not leakFn then return nil end
    local ok, blips = pcall(debug.getupvalue, leakFn, 1)
    if not ok or type(blips) ~= "table" then return nil end
    local out = {}
    for id, blip in pairs(blips) do
        if type(blip) == "table" and typeof(blip.position) == "Vector3" then out[id] = blip.position end
    end
    return out
end

--!luaq:no_virtualize
local function renderEsp(dt)
    local ents = Entities.GetAllCategoryEntities("Character")
    local leaks = (S.esp and S.radarEsp) and radarLeaks() or nil
    local camPos = Camera.CFrame.Position
    local now = os.clock()
    local present = {}
    local fadeStep = (S.espFade > 0) and dt / S.espFade or 1

    for id, e in pairs(ents) do
        if alive(e) then
            present[id] = true
            local enemy = isEnemy(e)
            local wanted = enemy or S.showTeam
            local show = (S.esp or S.nametags) and wanted
            local head = show and not e.FogCulled and partPos(e, "Head")
            local dist = head and (head - camPos).Magnitude
            local t = track[id]
            if head and dist <= S.espDist then
                if not t then t = { vis = 0 }; track[id] = t end
                local lf, rf = partPos(e, "LeftFoot"), partPos(e, "RightFoot")
                local footY = math.min(lf and lf.Y or head.Y - 4.6, rf and rf.Y or head.Y - 4.6) - 0.35
                local root = e.CFrame.Position
                local seen = S.visCheck and visible(camPos, head)
                local p = entPlayer(e)
                local flags
                if S.flags then
                    flags = {}
                    local armor = p and p:GetAttribute("ArmorValue") or 0
                    if armor > 0 then flags[#flags + 1] = { (p:GetAttribute("HasHelmet") and "HK" or "K"), Color3.fromRGB(150, 200, 255) } end
                    if p and p:GetAttribute("Cash") then flags[#flags + 1] = { "$" .. tostring(p:GetAttribute("Cash")), Color3.fromRGB(150, 230, 120) } end
                    if e.AnimationScoped then flags[#flags + 1] = { "ZOOM", Color3.fromRGB(255, 220, 110) } end
                    if p and p:GetAttribute("DefuseKit") then flags[#flags + 1] = { "KIT", Color3.fromRGB(120, 230, 160) } end
                    if e.Ducked then flags[#flags + 1] = { "DUCK", Color3.fromRGB(210, 210, 215) } end
                    if p and p:GetAttribute("SpawnProtected") then flags[#flags + 1] = { "IMMUNE", Color3.fromRGB(255, 240, 150) } end
                    if not p then flags[#flags + 1] = { "BOT", Color3.fromRGB(190, 190, 195) } end
                end
                local wpn = e.CharacterCurrentWeapon
                t.top = Vector3.new(root.X, head.Y + 0.75, root.Z)
                t.bottom = Vector3.new(root.X, footY, root.Z)
                t.color = espColorFor(e, enemy, seen)
                t.info = {
                    enemy = enemy, hp = e.Health, armor = p and p:GetAttribute("ArmorValue") or 0,
                    name = entName(e), weapon = wpn and wpn.Name, dist = math.floor(dist * 0.28), flags = flags,
                }
                t.live, t.fog, t.seenAt = true, false, now
                t.vis = math.min(1, t.vis + fadeStep)
                local alpha = 1 - t.vis

                if S.esp then
                    drawEntity(t.top, t.bottom, t.color, alpha, t.info)
                    if S.skeleton then
                        for _, bone in ipairs(BONES) do
                            local p1, p2 = partPos(e, bone[1]), partPos(e, bone[2])
                            if p1 and p2 then
                                local s1, on1 = w2s(p1)
                                local s2, on2 = w2s(p2)
                                if on1 and on2 then draw.line(s1, s2, t.color, 1, alpha) end
                            end
                        end
                    end
                    if S.headDot then
                        local sp, on = w2s(head)
                        if on then draw.rect(sp.X - 2, sp.Y - 2, 4, 4, t.color, 0, alpha) end
                    end
                elseif S.nametags then
                    local sp, on = w2s(t.top + Vector3.new(0, 0.4, 0))
                    if on then
                        draw.text(string.format("%s  %d", t.info.name, e.Health), sp.X, sp.Y - 14, enemy and S.espColor or S.teamColor, 14, 0.5, alpha)
                    end
                end
                setChams(e, t.color, S.esp and S.chams and not e.Culled, e.Health)
            else
                setChams(e, S.espColor, false)
                if t then t.fog = e.FogCulled == true and wanted end

                local leak = S.esp and wanted and enemy and leaks and leaks[id]
                if leak and (leak - camPos).Magnitude <= S.espDist then
                    t = t or { vis = 1 }
                    track[id] = t
                    t.top = leak + Vector3.new(0, 2.75, 0)
                    t.bottom = leak - Vector3.new(0, 2.6, 0)
                    t.color = espColorFor(e, true, false)
                    t.info = {
                        enemy = true, hp = e.Health, name = entName(e), forceName = true,
                        dist = math.floor((leak - camPos).Magnitude * 0.28), note = "radar",
                        weapon = e.CharacterCurrentWeapon and e.CharacterCurrentWeapon.Name,
                    }
                    t.live, t.fog, t.seenAt = true, true, now
                    drawEntity(t.top, t.bottom, t.color, 0.2, t.info)
                end
            end
        end
    end

    for id, t in pairs(track) do
        if t.live then
            t.live = false
        else
            local age = now - (t.seenAt or 0)
            if S.esp and S.dormant and present[id] and t.fog and age < S.dormantTime and t.top then
                local info = { enemy = t.info and t.info.enemy, name = t.info and t.info.name, forceName = true,
                    note = string.format("%.1fs ago", age) }
                drawEntity(t.top, t.bottom, GREY, 0.3 + 0.6 * age / S.dormantTime, info)
            else
                t.vis = t.vis - fadeStep
                if t.vis <= 0 or not t.top then
                    track[id] = nil
                elseif S.esp then
                    drawEntity(t.top, t.bottom, t.color, 1 - t.vis, t.info)
                end
            end
        end
    end

    for id, h in pairs(chamsOf) do
        if not present[id] then h:Destroy(); chamsOf[id] = nil end
    end

    if S.soundEsp then
        for i = #soundMarks, 1, -1 do
            local m = soundMarks[i]
            local age = now - m.at
            if age > S.soundLife then
                table.remove(soundMarks, i)
            else
                local alpha = age / S.soundLife
                local pos = m.pos + m.vel * math.min(age, 1)
                if S.soundBox then
                    drawEntity(pos + Vector3.new(0, 5.2, 0), pos - Vector3.new(0, 0.3, 0), S.soundColor, alpha,
                        { enemy = true, name = (m.kind == "shot") and "shot" or "step", forceName = true })
                else
                    local sp, on = w2s(pos)
                    if on then
                        local r = 6 + 10 * alpha
                        local prev
                        for k = 0, 16 do
                            local a = k / 16 * math.pi * 2
                            local pt = sp + Vector2.new(math.cos(a), math.sin(a)) * r
                            if prev then draw.line(prev, pt, S.soundColor, 1, alpha) end
                            prev = pt
                        end
                    end
                end
            end
        end
    end
end

local fpsSmooth = 60

local fovCircle = Instance.new("Frame")
fovCircle.Name = "FovCircle"
fovCircle.AnchorPoint = Vector2.new(0.5, 0.5)
fovCircle.Position = UDim2.fromScale(0.5, 0.5)
fovCircle.BackgroundTransparency = 1
fovCircle.BorderSizePixel = 0
fovCircle.Visible = false
fovCircle.Parent = overlay
Instance.new("UICorner", fovCircle).CornerRadius = UDim.new(1, 0)
local fovRing = Instance.new("UIStroke", fovCircle)
fovRing.Thickness = 1
fovRing.Transparency = 0.35
do
    local circle = Instance.new("Frame")
    circle.Name = "AssistCircle"
    circle.AnchorPoint = Vector2.new(0.5, 0.5)
    circle.Position = UDim2.fromScale(0.5, 0.5)
    circle.BackgroundTransparency = 1
    circle.BorderSizePixel = 0
    circle.Visible = false
    circle.Parent = overlay
    Instance.new("UICorner", circle).CornerRadius = UDim.new(1, 0)
    local ring = Instance.new("UIStroke", circle)
    ring.Thickness = 1
    ring.Transparency = 0.35
    hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function()
        local show = S.assist and S.assistCircle and not S.rage
        if circle.Visible ~= show then circle.Visible = show end
        if show then
            circle.Size = UDim2.fromOffset(S.assistFov * 2, S.assistFov * 2)
            ring.Color = S.assistColor
        end
    end))
end

--!luaq:no_virtualize
local function drawMarker(centre, mk, age)
    local t = math.clamp(age / S.hitTime, 0, 1)
    local alpha = t
    local color = mk.kill and S.killColor or S.hitColor
    local size = S.hitSize * (mk.kill and S.killScale or 1)
    local gap, rot = S.hitGap, 0
    if S.hitAnim == "Expand" then
        gap = gap + size * t
    elseif S.hitAnim == "Shrink" then
        size = size * (1 + (1 - math.min(t * 4, 1)) * 1.2)
    elseif S.hitAnim == "Spin" then
        rot = t * math.pi / 2
    end
    local thick = S.hitThick
    --!luaq:no_virtualize
    local function seg(a, b)
        if S.hitOutline then
            local d = (b - a)
            d = (d.Magnitude > 0) and d.Unit or Vector2.new(1, 0)
            draw.line(a - d, b + d, BLACK, thick + 2, alpha)
        end
        draw.line(a, b, color, thick, alpha)
    end
    local shape = S.hitShape
    if shape == "X" or shape == "Plus" then
        local base = (shape == "X") and math.pi / 4 or 0
        for k = 0, 3 do
            local a = base + rot + k * math.pi / 2
            local dir = Vector2.new(math.cos(a), math.sin(a))
            seg(centre + dir * gap, centre + dir * (gap + size))
        end
    else
        local n = (shape == "Square") and 4 or 24
        local r = size + gap
        local base = (shape == "Square") and math.pi / 4 or 0
        local prev
        for k = 0, n do
            local a = base + rot + k / n * math.pi * 2
            local pt = centre + Vector2.new(math.cos(a), math.sin(a)) * r
            if prev then seg(prev, pt) end
            prev = pt
        end
    end
    if S.hitDamage and mk.damage then
        draw.text(tostring(math.floor(mk.damage)), centre.X, centre.Y + gap + size + 4, color, 13, 0.5, alpha)
    end
end

--!luaq:no_virtualize
local function renderHud(dt)
    local vp = Camera.ViewportSize
    local centre = vp / 2
    fpsSmooth = fpsSmooth + (1 / math.max(dt, 1e-4) - fpsSmooth) * 0.05

    local showCircle = S.silentAim and S.showFov and not S.rage
    if fovCircle.Visible ~= showCircle then fovCircle.Visible = showCircle end
    if showCircle then
        fovCircle.Size = UDim2.fromOffset(S.fov * 2, S.fov * 2)
        fovRing.Color = S.fovColor
    end

    if S.xhair then
        local g, l, t = S.xhairGap, S.xhairLen, S.xhairThick
        local arms = { { 1, 0 }, { -1, 0 }, { 0, 1 } }
        if not S.xhairT then arms[#arms + 1] = { 0, -1 } end
        for _, d in ipairs(arms) do
            local dir = Vector2.new(d[1], d[2])
            local a, b = centre + dir * g, centre + dir * (g + l)
            if S.xhairOutline then draw.line(a - dir, b + dir, BLACK, t + 2, 0) end
            draw.line(a, b, S.xhairColor, t, 0)
        end
    end
    if S.dot then
        local sz = S.dotSize
        draw.rect(centre.X - sz / 2 - 1, centre.Y - sz / 2 - 1, sz + 2, sz + 2, BLACK, 0, 0)
        draw.rect(centre.X - sz / 2, centre.Y - sz / 2, sz, sz, S.dotColor, 0, 0)
    end

    local now = os.clock()
    for i = #markers, 1, -1 do
        local mk = markers[i]
        local age = now - mk.at
        if age > math.max(S.hitTime, 1) then
            table.remove(markers, i)
        else
            if S.hitMarker and age < S.hitTime then
                if S.hitWhere ~= "Where It Landed" or not mk.pos then drawMarker(centre, mk, age) end
                if S.hitWhere ~= "Crosshair" and mk.pos then
                    local sp, on = w2s(mk.pos + Vector3.new(0, S.hitRise * age / S.hitTime, 0))
                    if on then drawMarker(sp, mk, age) end
                end
            end
            if S.dmgNumbers and mk.pos then
                local sp, on = w2s(mk.pos + Vector3.new(0, 1 + age * 2, 0))
                if on then draw.text("-" .. tostring(math.floor(mk.damage)), sp.X, sp.Y, mk.kill and S.killColor or S.dmgColor, 15, 0.5, math.clamp(age, 0, 1)) end
            end
        end
    end

    local rageLive = S.rage and rageTarget.entity ~= nil and os.clock() - (rageTarget.at or 0) < 0.35
    if rageLive and S.targetIndicator and rageTarget.pos then
        local sp, on = w2s(rageTarget.pos)
        if on then
            draw.rect(sp.X - 4, sp.Y - 4, 8, 8, S.hudColor, 1, 1, 0)
            draw.text(string.format("%s  %d  %d%%", rageTarget.part or "", rageTarget.damage or 0, (rageTarget.chance or 1) * 100),
                sp.X, sp.Y + 8, S.hudColor, 12, 0.5, 0)
        end
    end

    if S.watermark then
        local ping = 0
        pcall(function() ping = math.floor(LocalPlayer:GetNetworkPing() * 1000) end)
        local text = string.format("zamltra  |  %s  |  %d fps  |  %d ms  |  %s", LocalPlayer.Name, fpsSmooth, ping, os.date("%H:%M:%S"))
        local w = #text * 7.2 + 20
        draw.rect(vp.X - w - 12, 8, w, 24, Color3.fromRGB(14, 14, 18), 0, 0.25)
        draw.rect(vp.X - w - 12, 8, w, 2, S.hudColor, 0, 0)
        draw.text(text, vp.X - 22, 13, WHITE, 13, 1, 0)
    end

    local char = localChar()
    local under = centre.Y + 34
    if S.speedHud and char then
        local v = char.Simulation.Velocity
        draw.text(string.format("%.1f", math.sqrt(v.X * v.X + v.Z * v.Z)), centre.X, under, S.hudColor, 15, 0.5, 0)
        under = under + 18
    end
    if S.indicators then
        --!luaq:no_virtualize
        local function line(text, on)
            draw.text(text, centre.X, under, on and S.hudColor or Color3.fromRGB(150, 150, 155), 13, 0.5, on and 0 or 0.4)
            under = under + 15
        end
        if S.rage then line("RAGE", rageLive) end
        if S.silentAim and not S.rage then line("SILENT", tickState.aim ~= nil) end
        if S.trigger then line("TRIGGER", char ~= nil) end
        if S.aa then line("AA", char ~= nil) end
        if S.noRecoil then line("NO RECOIL", true) end
        if S.noSpread then line("NO SPREAD", true) end
        if S.bhop then line("BHOP", char ~= nil) end
        if S.tp then line("3RD", tp.active) end
    end
    if S.hudArrows and S.aa then
        local dim = Color3.fromRGB(120, 120, 125)
        --!luaq:no_virtualize
        local function arrow(dir, lit)
            local c = centre + dir * 46
            local side = Vector2.new(-dir.Y, dir.X)
            local tip, l, r = c + dir * 10, c + side * 7, c - side * 7
            local col = lit and S.hudColor or dim
            local alpha = lit and 0 or 0.45
            draw.line(tip, l, col, 2, alpha); draw.line(tip, r, col, 2, alpha); draw.line(l, r, col, 2, alpha)
        end
        arrow(Vector2.new(-1, 0), S.aaLeft or (not S.aaRight and S.aaYaw == "Left"))
        arrow(Vector2.new(1, 0), S.aaRight or (not S.aaLeft and S.aaYaw == "Right"))
        arrow(Vector2.new(0, 1), S.aaYaw == "Backward" or S.aaYaw == "Jitter" or S.aaYaw == "Spin")
    end

    pend.expire(now)
    if S.hitLogs then
        local y = centre.Y + 70
        for _, entry in ipairs(hitLog.entries) do
            local age = now - entry.at
            if age < 5 then
                draw.text(entry.text, centre.X, y, entry.color, 13, 0.5, math.clamp(age - 4, 0, 1))
                y = y + 16
            end
        end
    end

end

--!luaq:no_virtualize
local function renderItems()
    local camPos = Camera.CFrame.Position
    if S.drops then
        for _, d in pairs(Entities.GetAllCategoryEntities("DroppedWeapon")) do
            local pos = d.Position
            if pos and not d.FogCulled then
                local dist = (pos - camPos).Magnitude
                if dist <= S.dropDist then
                    local sp, on = w2s(pos + Vector3.new(0, 0.6, 0))
                    if on then
                        local c4 = d.Name == "C4"
                        draw.text(string.format("%s  %dm", tostring(d.Name), dist * 0.28), sp.X, sp.Y,
                            c4 and Color3.fromRGB(255, 80, 80) or S.dropColor, 12, 0.5, 0)
                    end
                end
            end
        end
    end
    if S.bomb then
        for _, b in pairs(Entities.GetAllCategoryEntities("Bomb")) do
            local timer = b.BlowTimer
            if timer and timer > 0 and not b.Exploded and not b.Defused then
                local vp = Camera.ViewportSize
                local total = GameCfg.Get("Bomb", "BlowTimer") or 40
                local frac = math.clamp(timer / total, 0, 1)
                local color = timer < 10 and Color3.fromRGB(255, 70, 70) or Color3.fromRGB(255, 200, 90)
                local w = 260
                draw.rect(vp.X / 2 - w / 2 - 1, 43, w + 2, 6, Color3.new(0, 0, 0), 0, 0.4)
                draw.rect(vp.X / 2 - w / 2, 44, w * frac, 4, color, 0, 0)
                draw.text(string.format("C4  %.1fs%s", timer, b.Defusing and "  (defusing)" or ""), vp.X / 2, 52, color, 14, 0.5, 0)
                local pos = b.Position or (b.Model and b.Model:GetPivot().Position)
                if pos then
                    local sp, on = w2s(pos + Vector3.new(0, 1, 0))
                    if on then draw.text(string.format("C4 %.1f", timer), sp.X, sp.Y, color, 13, 0.5, 0) end
                end
            end
        end
    end
end

hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function(dt)
    elevate()
    draw.begin()
    pcall(renderEsp, dt)
    pcall(renderItems)
    pcall(renderHud, dt)
    draw.finish()
end))

pcall(function()
    local env = getgenv and getgenv()
    if not env then return end
    local dbg = { S = S, tick = tickState, rage = function() return rageTarget end }

    task.spawn(function()
        local maskFn
        pcall(function() maskFn = filtergc("function", { Name = "CheckHooks" }, false)[1] end)
        local seen, bits, t0, lastLine, lastWrite = 0, {}, os.clock(), "", 0
        pcall(function() if not isfolder("zaml") then makefolder("zaml") end end)
        while not hub.unloaded do
            local okM, m = pcall(function() return maskFn and debug.getupvalue(maskFn, 4) end)
            if okM and type(m) == "number" and m ~= 0 and bit32.bor(seen, m) ~= seen then
                seen = bit32.bor(seen, m)
                bits[#bits + 1] = string.format("%.0fs:%d", os.clock() - t0, m)
            end
            if os.clock() - lastWrite > 1 then
                lastWrite = os.clock()
                local T = tickState
                local on = {}
                for _, k in ipairs({ "rage", "silentAim", "trigger", "aa", "noRecoil", "noSpread", "rageNoSpread", "rageRecoil",
                    "autowall", "autoFire", "bhop", "strafe", "duckJump", "longJump", "tp", "fovChanger", "noZoom", "esp", "chams",
                    "soundEsp", "vmOn", "vmChams", "noShake", "autoStop", "autoScope", "autoReload" }) do
                    if S[k] then on[#on + 1] = k end
                end
                local line = string.format("t=%.0fs mask=%d [%s] on={%s} aimSpeed=%s hc=%s react=%s delay=%s | scans=%s targets=%s aimTicks=%s presses=%s shots=%s hits=%s | spreadChk=%s exact=%s errMax=%s | aimShots=%s clientHits=%s clientAimHits=%s aimErrAvg=%s aimErrMax=%s | guard: crosshairOnBody client=%s server=%s, offBody client=%s server=%s | nospread ground shots=%s client=%s server=%s, air shots=%s client=%s server=%s | K=%s D=%s",
                    os.clock() - t0, seen, table.concat(bits, ","), table.concat(on, ","), tostring(S.aimSpeed), tostring(S.hitChance),
                    tostring(S.rageReaction), tostring(S.rageShotDelay), tostring(T.scans), tostring(T.scanHits), tostring(T.aimTicks),
                    tostring(T.forcedShots), tostring(hud.shots), tostring(hud.hits), tostring(T.spreadChecks), tostring(T.spreadExact),
                    tostring(T.spreadErrMax), tostring(T.aimShots), tostring(T.clientHits), tostring(T.clientAimHits),
                    tostring(T.aimShots and string.format("%.2f", (T.aimErrSum or 0) / T.aimShots)), tostring(T.aimErrMax and string.format("%.2f", T.aimErrMax)),
                    tostring(T.cHitG), tostring(T.sHitG), tostring(T.cHitU), tostring(T.sHitU),
                    tostring(T.groundShots), tostring(T.groundClient), tostring(T.groundServer),
                    tostring(T.airShots), tostring(T.airClient), tostring(T.airServer),
                    tostring(LocalPlayer:GetAttribute("Kills")), tostring(LocalPlayer:GetAttribute("Deaths")))
                if line ~= lastLine then
                    lastLine = line
                    pcall(writefile, "zaml/debug_log.txt", line)
                end
            end
            task.wait(0.1)
        end
    end)

    dbg.diag = LUAQ_NO_VIRTUALIZE(function()
        local lines = {}
        local char = localChar()
        local weapon = WC.GetCurrentWeapon()
        if not (char and weapon and next(weapon)) then return { "no character / weapon" } end
        local sim = char.Simulation
        local origin = eyePos(sim)
        lines[1] = string.format("weapon=%s gun=%s canFire=%s origin=%s map=%s", tostring(weapon.Name), tostring(isGun(weapon) and true),
            tostring(canFire(weapon, sim, tickDt(), char)), tostring(origin), tostring(refreshMap() ~= nil))
        for id, e in pairs(Entities.GetAllCategoryEntities("Character")) do
            local head = alive(e) and partPos(e, "Head")
            local raw, walls = 0, 0
            if head and isGun(weapon) then raw, walls = bulletDamage(weapon, origin, head, "Head", true) end
            lines[#lines + 1] = string.format("%s alive=%s enemy=%s targetable=%s fog=%s culled=%s dist=%.0f vis=%s rawHead=%.1f walls=%d headY=%.1f posY=%.1f",
                tostring(id), tostring(alive(e)), tostring(isEnemy(e)), tostring(targetable(e)), tostring(e.FogCulled), tostring(e.Culled),
                e.Position and (e.Position - origin).Magnitude or -1, tostring(head and visible(origin, head)), raw, walls,
                head and head.Y or 0, e.Position and e.Position.Y or 0)
        end
        return lines
    end)
    env.__zamltra = dbg
    hub.onUnload(function() if env.__zamltra == dbg then env.__zamltra = nil end end)
end)

--!luaq:no_virtualize
local function pick(v) return (type(v) == "table") and v[1] or v end

local CombatTab = Window:Tab({ Title = "legit", Icon = "target" })

CombatTab:Section({ Title = "silent aim" })

CombatTab:Toggle({
    Title = "silent aim",
    Value = false,
    Flag  = "silentAim",
    Callback = function(state) S.silentAim = state end,
})

CombatTab:Slider({
    Title = "fov radius",
    Value = { Min = 10, Max = 600, Default = 120 },
    Flag  = "fovRadius",
    Callback = function(v) S.fov = v end,
})

CombatTab:Toggle({
    Title = "show fov circle",
    Value = true,
    Flag  = "showFov",
    Callback = function(state) S.showFov = state end,
})

CombatTab:Colorpicker({
    Title = "fov color",
    Default = S.fovColor,
    Flag  = "fovColor",
    Callback = function(c) S.fovColor = c end,
})

CombatTab:Dropdown({
    Title = "aim part",
    Values = { "Head", "Body", "Closest to Crosshair" },
    Value = "Head",
    Flag  = "aimPart",
    Callback = function(v) S.aimPart = pick(v) end,
})

CombatTab:Toggle({
    Title = "wall check",
    Value = true,
    Flag  = "wallCheck",
    Callback = function(state) S.wallCheck = state end,
})

CombatTab:Toggle({
    Title = "team check",
    Value = true,
    Flag  = "teamCheck",
    Callback = function(state) S.teamCheck = state end,
})

CombatTab:Toggle({
    Title = "keep crosshair on target",
    Value = true,
    Flag  = "spreadGuard",
    Callback = function(state) S.spreadGuard = state end,
})

CombatTab:Section({ Title = "aim assist" })

CombatTab:Toggle({
    Title = "aim assist",
    Value = false,
    Flag  = "aimAssist",
    Callback = function(state) S.assist = state end,
})

CombatTab:Dropdown({
    Title = "assist part",
    Values = { "Head", "Body", "Closest to Crosshair" },
    Value = "Head",
    Flag  = "assistPart",
    Callback = function(v) S.assistPart = pick(v) end,
})

CombatTab:Toggle({
    Title = "assist wall check",
    Value = true,
    Flag  = "assistWall",
    Callback = function(state) S.assistWall = state end,
})

CombatTab:Toggle({
    Title = "show assist fov",
    Value = true,
    Flag  = "assistCircle",
    Callback = function(state) S.assistCircle = state end,
})

CombatTab:Colorpicker({
    Title = "assist fov color",
    Default = S.assistColor,
    Flag  = "assistColor",
    Callback = function(c) S.assistColor = c end,
})

CombatTab:Dropdown({
    Title = "assist when",
    Values = { "Always", "While Firing", "While Aiming" },
    Value = "While Firing",
    Flag  = "assistMode",
    Callback = function(v) S.assistMode = pick(v) end,
})

CombatTab:Slider({
    Title = "assist fov",
    Value = { Min = 10, Max = 400, Default = 80 },
    Flag  = "assistFov",
    Callback = function(v) S.assistFov = v end,
})

CombatTab:Slider({
    Title = "assist strength",
    Value = { Min = 1, Max = 100, Default = 35 },
    Flag  = "assistStrength",
    Callback = function(v) S.assistStrength = v end,
})

CombatTab:Toggle({
    Title = "only while moving mouse",
    Value = false,
    Flag  = "assistMouse",
    Callback = function(state) S.assistMouse = state end,
})

CombatTab:Toggle({
    Title = "turn camera",
    Value = false,
    Flag  = "turnCamera",
    Callback = function(state) S.turnCamera = state end,
})

CombatTab:Slider({
    Title = "aim speed",
    Value = { Min = 2, Max = 180, Default = 14 },
    Flag  = "aimSpeed",
    Callback = function(v) S.aimSpeed = v end,
})

CombatTab:Slider({
    Title = "aim smoothing",
    Value = { Min = 0, Max = 90, Default = 50 },
    Step  = 5,
    Flag  = "aimSmooth",
    Callback = function(v) S.aimSmooth = v end,
})

CombatTab:Section({ Title = "triggerbot" })

CombatTab:Toggle({
    Title = "triggerbot",
    Value = false,
    Flag  = "trigger",
    Callback = function(state) S.trigger = state end,
})

CombatTab:Slider({
    Title = "trigger delay (ms)",
    Value = { Min = 0, Max = 300, Default = 0 },
    Step  = 5,
    Flag  = "triggerDelay",
    Callback = function(v) S.triggerDelay = v end,
})

CombatTab:Section({ Title = "gun mods" })

CombatTab:Toggle({
    Title = "no recoil",
    Value = false,
    Flag  = "noRecoil",
    Callback = function(state) S.noRecoil = state end,
})

CombatTab:Toggle({
    Title = "no spread",
    Value = false,
    Flag  = "noSpread",
    Callback = function(state) S.noSpread = state end,
})

--!luaq:no_virtualize
local function isPrivateServer()
    if game.PrivateServerId ~= "" and game.PrivateServerOwnerId ~= 0 then return true end
    local ok, kind = pcall(function()
        local remote = game:GetService("RobloxReplicatedStorage"):WaitForChild("GetServerType", 5)
        return remote and remote:InvokeServer()
    end)
    if setthreadidentity then pcall(setthreadidentity, 8) end
    return ok and kind == "VIPServer"
end

if isPrivateServer() then

S.rageInstant, S.fireTap = true, true
S.rageReaction, S.rageShotDelay, S.hitChance = 0, 0, 0
S.rageNoSpread, S.rageRecoil, S.autowall = true, true, true

local RageTab = Window:Tab({ Title = "rage", Icon = "flame" })

RageTab:Section({ Title = "ragebot" })

RageTab:Toggle({
    Title = "ragebot",
    Value = false,
    Flag  = "rage",
    Callback = function(state)
        S.rage = state
        if not state then rageTarget = { } end
    end,
})

RageTab:Toggle({
    Title = "auto fire",
    Value = true,
    Flag  = "autoFire",
    Callback = function(state) S.autoFire = state end,
})

RageTab:Toggle({
    Title = "wall penetration check",
    Value = true,
    Flag  = "rageAutowall",
    Callback = function(state) S.autowall = state end,
})

RageTab:Dropdown({
    Title = "hitbox",
    Values = { "Head", "Body", "Head + Body", "All" },
    Value = "Head + Body",
    Flag  = "rageHitbox2",
    Callback = function(v) S.rageHitbox = pick(v) end,
})

RageTab:Dropdown({
    Title = "target selection",
    Values = { "Crosshair", "Distance", "Lowest HP", "Highest Damage" },
    Value = "Crosshair",
    Flag  = "rageSelect",
    Callback = function(v) S.rageSelect = pick(v) end,
})

RageTab:Toggle({
    Title = "prefer body when lethal",
    Value = true,
    Flag  = "preferBody",
    Callback = function(state) S.preferBody = state end,
})

RageTab:Toggle({
    Title = "auto stop",
    Value = true,
    Flag  = "rageAutoStop",
    Callback = function(state) S.autoStop = state end,
})

RageTab:Toggle({
    Title = "auto scope",
    Value = true,
    Flag  = "rageAutoScope",
    Callback = function(state) S.autoScope = state end,
})

RageTab:Toggle({
    Title = "target indicator",
    Value = true,
    Flag  = "targetIndicator",
    Callback = function(state) S.targetIndicator = state end,
})

RageTab:Toggle({
    Title = "ignore friends",
    Value = false,
    Flag  = "ignoreFriends",
    Callback = function(state) S.ignoreFriends = state end,
})

RageTab:Slider({
    Title = "max fov",
    Value = { Min = 5, Max = 180, Default = 180 },
    Flag  = "rageFov",
    Callback = function(v) S.rageFov = v end,
})

RageTab:Slider({
    Title = "max distance",
    Value = { Min = 20, Max = 1000, Default = 500 },
    Step  = 10,
    Flag  = "rageMaxDist",
    Callback = function(v) S.maxDist = v end,
})

RageTab:Slider({
    Title = "min damage",
    Value = { Min = 1, Max = 100, Default = 1 },
    Flag  = "rageMinDamage",
    Callback = function(v) S.minDamage = v end,
})

RageTab:Toggle({
    Title = "min damage override",
    Value = false,
    Flag  = "rageDmgOverride",
    Callback = function(state) S.dmgOverride = state end,
})

RageTab:Slider({
    Title = "override damage",
    Value = { Min = 1, Max = 100, Default = 100 },
    Flag  = "rageMinDamageOverride",
    Callback = function(v) S.minDamageOverride = v end,
})

RageTab:Section({ Title = "anti-aim" })

RageTab:Toggle({
    Title = "anti-aim",
    Value = false,
    Flag  = "aa",
    Callback = function(state) S.aa = state end,
})

RageTab:Dropdown({
    Title = "yaw base",
    Values = { "Camera", "At Target" },
    Value = "Camera",
    Flag  = "aaBase",
    Callback = function(v) S.aaBase = pick(v) end,
})

RageTab:Dropdown({
    Title = "yaw",
    Values = { "Off", "Backward", "Left", "Right", "Spin", "Jitter" },
    Value = "Backward",
    Flag  = "aaYaw",
    Callback = function(v) S.aaYaw = pick(v) end,
})

do
    local leftToggle, rightToggle
    leftToggle = RageTab:Toggle({
        Title = "aa left",
        Value = false,
        Callback = function(state)
            S.aaLeft = state
            if state and S.aaRight then
                S.aaRight = false
                pcall(function() rightToggle:Set(false) end)
            end
        end,
    })
    rightToggle = RageTab:Toggle({
        Title = "aa right",
        Value = false,
        Callback = function(state)
            S.aaRight = state
            if state and S.aaLeft then
                S.aaLeft = false
                pcall(function() leftToggle:Set(false) end)
            end
        end,
    })
end

RageTab:Slider({
    Title = "spin speed",
    Value = { Min = 1, Max = 90, Default = 20 },
    Flag  = "aaSpin",
    Callback = function(v) S.aaSpin = v end,
})

RageTab:Slider({
    Title = "jitter range",
    Value = { Min = 0, Max = 180, Default = 60 },
    Flag  = "aaJitter",
    Callback = function(v) S.aaJitter = v end,
})

RageTab:Dropdown({
    Title = "pitch",
    Values = { "Off", "Down", "Up", "Zero" },
    Value = "Down",
    Flag  = "aaPitch",
    Callback = function(v) S.aaPitch = pick(v) end,
})

RageTab:Section({ Title = "weapon" })

RageTab:Toggle({
    Title = "auto reload",
    Value = false,
    Flag  = "autoReload",
    Callback = function(state) S.autoReload = state end,
})

RageTab:Slider({
    Title = "reload at",
    Value = { Min = 0, Max = 30, Default = 0 },
    Flag  = "reloadAt",
    Callback = function(v) S.reloadAt = v end,
})

end

local VisualTab = Window:Tab({ Title = "visual", Icon = "sparkles" })

VisualTab:Section({ Title = "esp" })

VisualTab:Toggle({ Title = "esp", Value = false, Flag = "esp", Callback = function(state) S.esp = state end })

VisualTab:Colorpicker({ Title = "enemy color", Default = S.espColor, Flag = "espEnemyColor", Callback = function(c) S.espColor = c end })

VisualTab:Dropdown({
    Title = "color mode",
    Values = { "Enemy / Teammate", "Team Side", "Player Color" },
    Value = "Enemy / Teammate",
    Flag  = "espColorMode",
    Callback = function(v) S.espColorMode = pick(v) end,
})

VisualTab:Colorpicker({ Title = "terrorist color", Default = S.tColor, Flag = "espTColor", Callback = function(c) S.tColor = c end })
VisualTab:Colorpicker({ Title = "counter-terrorist color", Default = S.ctColor, Flag = "espCTColor", Callback = function(c) S.ctColor = c end })

VisualTab:Slider({
    Title = "fade time (s)",
    Value = { Min = 0, Max = 1.5, Default = 0.35 },
    Step  = 0.05,
    Flag  = "espFade",
    Callback = function(v) S.espFade = v end,
})

VisualTab:Toggle({
    Title = "visible check color",
    Value = false,
    Flag  = "espVisCheck",
    Callback = function(state) S.visCheck = state end,
})

VisualTab:Colorpicker({ Title = "visible color", Default = S.visColor, Flag = "espVisColor", Callback = function(c) S.visColor = c end })
VisualTab:Toggle({ Title = "show teammates", Value = false, Flag = "espTeam", Callback = function(state) S.showTeam = state end })
VisualTab:Colorpicker({ Title = "teammate color", Default = S.teamColor, Flag = "espTeamColor", Callback = function(c) S.teamColor = c end })

VisualTab:Toggle({
    Title = "radar esp",
    Value = true,
    Flag  = "radarEsp",
    Callback = function(state) S.radarEsp = state end,
})

VisualTab:Toggle({
    Title = "dormant esp",
    Value = false,
    Flag  = "espDormant",
    Callback = function(state) S.dormant = state end,
})

VisualTab:Slider({ Title = "dormant time (s)", Value = { Min = 1, Max = 15, Default = 4 }, Flag = "espDormantTime", Callback = function(v) S.dormantTime = v end })

VisualTab:Slider({
    Title = "max distance",
    Value = { Min = 100, Max = 3000, Default = 3000 },
    Step  = 50,
    Flag  = "espMaxDist",
    Callback = function(v) S.espDist = v end,
})

VisualTab:Section({ Title = "esp - chams" })

VisualTab:Toggle({ Title = "chams", Value = true, Flag = "espChams", Callback = function(state) S.chams = state end })

VisualTab:Dropdown({
    Title = "chams mode",
    Values = { "Glow", "Outline", "Solid", "Pulse", "Rainbow", "Health" },
    Value = "Glow",
    Flag  = "espChamsMode",
    Callback = function(v) S.chamsMode = pick(v) end,
})

VisualTab:Toggle({ Title = "visible only", Value = false, Flag = "espChamsOccluded", Callback = function(state) S.chamsOccluded = state end })

VisualTab:Slider({
    Title = "fill transparency",
    Value = { Min = 0, Max = 100, Default = 60 },
    Flag  = "espFill",
    Callback = function(v) S.chamsFill = v / 100 end,
})

VisualTab:Section({ Title = "esp - box" })

VisualTab:Toggle({ Title = "box", Value = false, Flag = "espBox", Callback = function(state) S.box = state end })

VisualTab:Dropdown({
    Title = "box style",
    Values = { "Corner", "Full" },
    Value = "Corner",
    Flag  = "espBoxStyle",
    Callback = function(v) S.boxStyle = pick(v) end,
})

VisualTab:Toggle({ Title = "box fill", Value = false, Flag = "espBoxFill", Callback = function(state) S.boxFill = state end })
VisualTab:Toggle({ Title = "health bar", Value = false, Flag = "espHealth", Callback = function(state) S.hpBar = state end })
VisualTab:Toggle({ Title = "health number", Value = true, Flag = "espHealthText", Callback = function(state) S.hpNum = state end })
VisualTab:Toggle({ Title = "armor bar", Value = false, Flag = "espArmor", Callback = function(state) S.armorBar = state end })

VisualTab:Section({ Title = "esp - info" })

VisualTab:Toggle({ Title = "names", Value = true, Flag = "espNames", Callback = function(state) S.names = state end })
VisualTab:Toggle({ Title = "weapon", Value = false, Flag = "espWeapon", Callback = function(state) S.weaponText = state end })

VisualTab:Toggle({
    Title = "flags",
    Value = false,
    Flag  = "espFlags",
    Callback = function(state) S.flags = state end,
})

VisualTab:Toggle({ Title = "distance", Value = true, Flag = "espDistance", Callback = function(state) S.distText = state end })
VisualTab:Slider({ Title = "text size", Value = { Min = 9, Max = 18, Default = 12 }, Flag = "espTextSize", Callback = function(v) S.textSize = v end })

VisualTab:Section({ Title = "esp - lines" })

VisualTab:Toggle({ Title = "skeleton", Value = false, Flag = "espSkeleton", Callback = function(state) S.skeleton = state end })
VisualTab:Toggle({ Title = "head dot", Value = false, Flag = "espHeadDot", Callback = function(state) S.headDot = state end })
VisualTab:Toggle({ Title = "snaplines", Value = false, Flag = "espSnap", Callback = function(state) S.snaplines = state end })

VisualTab:Dropdown({
    Title = "snapline origin",
    Values = { "Bottom", "Center", "Top" },
    Value = "Bottom",
    Flag  = "espSnapFrom",
    Callback = function(v) S.snapOrigin = pick(v) end,
})

VisualTab:Toggle({ Title = "off-screen arrows", Value = false, Flag = "espArrows", Callback = function(state) S.arrows = state end })

VisualTab:Slider({
    Title = "arrow radius",
    Value = { Min = 60, Max = 500, Default = 220 },
    Step  = 10,
    Flag  = "espArrowRadius",
    Callback = function(v) S.arrowRadius = v end,
})

VisualTab:Slider({ Title = "arrow size", Value = { Min = 8, Max = 30, Default = 14 }, Flag = "espArrowSize", Callback = function(v) S.arrowSize = v end })

VisualTab:Section({ Title = "third person" })

VisualTab:Toggle({ Title = "third person", Value = false, Flag = "thirdPerson", Callback = function(state) S.tp = state end })

VisualTab:Slider({ Title = "distance", Value = { Min = 2, Max = 25, Default = 8 }, Step = 0.5, Flag = "tpDistance", Callback = function(v) S.tpDist = v end })
VisualTab:Slider({ Title = "height", Value = { Min = -2, Max = 5, Default = 0.5 }, Step = 0.25, Flag = "tpHeight", Callback = function(v) S.tpHeight = v end })

VisualTab:Slider({
    Title = "shoulder offset",
    Value = { Min = -4, Max = 4, Default = 0 },
    Step  = 0.25,
    Flag  = "tpShoulder",
    Callback = function(v) S.tpShoulder = v end,
})

VisualTab:Toggle({
    Title = "camera collision",
    Value = true,
    Flag  = "tpCollide",
    Callback = function(state) S.tpCollide = state end,
})

VisualTab:Toggle({
    Title = "body rotation",
    Value = false,
    Flag  = "tpHeadRot",
    Callback = function(state) S.tpBodyRot = state end,
})

VisualTab:Dropdown({
    Title = "body follows",
    Values = { "Camera", "Sent Angles" },
    Value = "Camera",
    Flag  = "tpHeadFollow",
    Callback = function(v) S.tpBody = pick(v) end,
})

VisualTab:Section({ Title = "camera" })

VisualTab:Toggle({ Title = "fov changer", Value = false, Flag = "fovChanger", Callback = function(state) S.fovChanger = state; reapplyFov() end })

VisualTab:Slider({
    Title = "fov",
    Value = { Min = 50, Max = 120, Default = 90 },
    Flag  = "fovSlider",
    Callback = function(v)
        S.fovValue = v
        if S.fovChanger then reapplyFov() end
    end,
})

VisualTab:Toggle({
    Title = "no scope zoom",
    Value = false,
    Flag  = "noScopeZoom",
    Callback = function(state) S.noZoom = state end,
})

VisualTab:Toggle({
    Title = "no scope borders",
    Value = false,
    Flag  = "noScopeBorders",
    Callback = function(state) S.noBorders = state end,
})

VisualTab:Dropdown({
    Title = "scope lines",
    Values = { "Line", "Gradient" },
    Value = "Line",
    Flag  = "scopeStyle",
    Callback = function(v) S.scopeStyle = pick(v); layoutScopeLines() end,
})

VisualTab:Colorpicker({ Title = "scope line color", Default = S.scopeColor, Flag = "scopeColor", Callback = function(c) S.scopeColor = c; layoutScopeLines() end })

VisualTab:Slider({
    Title = "scope line length",
    Value = { Min = 10, Max = 100, Default = 60 },
    Step  = 5,
    Flag  = "scopeLen",
    Callback = function(v) S.scopeLen = v; layoutScopeLines() end,
})

VisualTab:Slider({ Title = "scope line gap", Value = { Min = 0, Max = 80, Default = 12 }, Flag = "scopeGap", Callback = function(v) S.scopeGap = v; layoutScopeLines() end })
VisualTab:Slider({ Title = "scope line thickness", Value = { Min = 1, Max = 5, Default = 1 }, Flag = "scopeThick", Callback = function(v) S.scopeThick = v; layoutScopeLines() end })

VisualTab:Toggle({
    Title = "remove screen shake",
    Value = false,
    Flag  = "noShake",
    Callback = function(state) S.noShake = state end,
})

VisualTab:Toggle({ Title = "viewmodel changer", Value = false, Flag = "vmChanger", Callback = function(state) S.vmOn = state end })

for _, axis in ipairs({ { "X", "vmX", "right" }, { "Y", "vmY", "up" }, { "Z", "vmZ", "back" } }) do
    VisualTab:Slider({
        Title = "viewmodel " .. axis[1],
        Value = { Min = -3, Max = 3, Default = 0 },
        Step  = 0.05,
        Flag  = axis[2] .. "Slider",
        Callback = function(v) S[axis[2]] = v end,
    })
end

VisualTab:Section({ Title = "viewmodel chams" })

VisualTab:Toggle({ Title = "viewmodel chams", Value = false, Flag = "vmChams", Callback = function(state) S.vmChams = state end })

VisualTab:Dropdown({
    Title = "chams material",
    Values = { "ForceField", "Neon", "Glass", "Flat" },
    Value = "ForceField",
    Flag  = "vmChamsMaterial",
    Callback = function(v)
        v = pick(v)
        S.vmMaterial = (v == "Flat") and "SmoothPlastic" or v
    end,
})

VisualTab:Colorpicker({ Title = "chams color", Default = S.vmColor, Flag = "vmChamsColor", Callback = function(c) S.vmColor = c end })

VisualTab:Slider({
    Title = "chams transparency",
    Value = { Min = 0, Max = 95, Default = 0 },
    Step  = 5,
    Flag  = "vmChamsTransp",
    Callback = function(v) S.vmTransparency = v / 100 end,
})

VisualTab:Section({ Title = "character changer" })

do
    local CC = { on = false, target = "Self", source = nil, user = "", avatar = nil, avatarFor = nil, gen = 0,
        file = nil, custom = nil, customFor = nil }
    local CUSTOM_DIRS = { "zaml/characters", "Zamlblox/characters" }

    local R6 = {
        Torso = { "UpperTorso", CFrame.new(0, -0.2, 0) },
        ["Left Arm"] = { "LeftUpperArm", CFrame.new(0, -0.45, 0) },
        ["Right Arm"] = { "RightUpperArm", CFrame.new(0, -0.45, 0) },
        ["Left Leg"] = { "LeftUpperLeg", CFrame.new(0, -0.6, 0) },
        ["Right Leg"] = { "RightUpperLeg", CFrame.new(0, -0.6, 0) },
    }
    local dressed = {}
    local BODY = { Head = true, UpperTorso = true, LowerTorso = true, LeftUpperArm = true, LeftLowerArm = true,
        LeftHand = true, RightUpperArm = true, RightLowerArm = true, RightHand = true, LeftUpperLeg = true,
        LeftLowerLeg = true, LeftFoot = true, RightUpperLeg = true, RightLowerLeg = true, RightFoot = true }

    local agentNames = {}
    pcall(function()
        for _, name in pairs(Enums.Items.Agents) do
            if type(name) == "string" then agentNames[#agentNames + 1] = name end
        end
    end)
    table.sort(agentNames)
    local isAgent = {}
    for _, n in ipairs(agentNames) do isAgent[n] = true end
    CC.source = agentNames[1] or "Roblox Avatar"

    local agentTemplates, agentPending = {}, {}
    --!luaq:no_virtualize
    local function agentTemplate(name)
        if agentTemplates[name] or agentPending[name] then return agentTemplates[name] end
        agentPending[name] = true
        task.spawn(function()

            if setthreadidentity then pcall(setthreadidentity, 2) end
            local ok, model = pcall(M.CharacterModel.new, { Name = "ZtAgentTemplate", Agent = name, Parent = fxFolder })
            if ok and typeof(model) == "Instance" then
                model.Parent = nil
                agentTemplates[name] = model
            else
            end
        end)
        return nil
    end

    --!luaq:no_virtualize
    local function gameModel()
        return isAgent[CC.source] == true
    end

    --!luaq:no_virtualize
    local function template()
        if CC.source == "Roblox Avatar" then return CC.avatar end
        if CC.source == "Custom Model" then return CC.custom end
        return agentTemplate(CC.source)
    end

    --!luaq:no_virtualize
    local function sourceKey()
        if CC.source == "Roblox Avatar" then return "avatar:" .. tostring(CC.avatarFor) end
        if CC.source == "Custom Model" then return "custom:" .. tostring(CC.customFor) end
        return CC.source
    end

    --!luaq:no_virtualize
    local function undress(model)
        local d = dressed[model]
        if not d then return end
        dressed[model] = nil
        pcall(function() d.overlay:Destroy() end)
        for inst, t in pairs(d.hidden) do
            pcall(function() inst.Transparency = t end)
        end
    end

    --!luaq:no_virtualize
    local function undressAll()
        for model in pairs(dressed) do undress(model) end
    end

    --!luaq:no_virtualize
    local function hideRig(model, d)
        local keep = d.keep
        for _, inst in ipairs(model:GetDescendants()) do
            if (inst:IsA("BasePart") or inst:IsA("Decal") or inst:IsA("Texture")) and inst.Transparency < 1
                and not (keep and keep.Parent and inst:IsDescendantOf(keep)) then
                if d.hidden[inst] == nil then d.hidden[inst] = inst.Transparency end
                inst.Transparency = 1
            end
        end
    end

    --!luaq:no_virtualize
    local function dress(model, keep)
        local src = template()
        if not src then return end
        local overlay = src:Clone()
        overlay.Name = "ZtCharacterOverlay"

        for _, d in ipairs(overlay:GetDescendants()) do
            if d:IsA("Humanoid") and not gameModel() then

                pcall(function()
                    d.EvaluateStateMachine = false
                    d.RequiresNeck = false
                    d.BreakJointsOnDeath = false
                    d.PlatformStand = true
                    d.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None
                    d.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff
                end)
            elseif d:IsA("Humanoid") or d:IsA("LuaSourceContainer") or d:IsA("AnimationController") or d:IsA("Animator")
                or d:IsA("BillboardGui") or d:IsA("Highlight") then
                d:Destroy()
            elseif d:IsA("Motor6D") then

                if d.Part1 == nil or BODY[d.Part1.Name] or d.Part1.Name == "HumanoidRootPart" then d:Destroy() end
            elseif d:IsA("BasePart") then
                d.Anchored, d.CanCollide, d.CanQuery, d.CanTouch = false, false, false, false
                d.Massless, d.CastShadow = true, false
            end
        end
        local ridesOn = {}
        for _, part in ipairs(overlay:GetChildren()) do
            if part:IsA("BasePart") then
                local r6 = R6[part.Name]
                local target = model:FindFirstChild((BODY[part.Name] and part.Name) or (r6 and r6[1]) or "")
                if target and target:IsA("BasePart") then
                    local offset = r6 and r6[2] or CFrame.new()
                    part.CFrame = target.CFrame * offset
                    local w = Instance.new("Weld")
                    w.Part0, w.Part1, w.C0 = target, part, offset
                    w.Parent = part
                    ridesOn[part] = { target, offset }
                else
                    part:Destroy()
                end
            end
        end

        for _, acc in ipairs(overlay:GetChildren()) do
            if acc:IsA("Accessory") then
                local handle = acc:FindFirstChild("Handle")
                local att = handle and handle:FindFirstChildOfClass("Attachment")
                local placed = false
                if att then
                    for body, ride in pairs(ridesOn) do
                        local mate = body:FindFirstChild(att.Name)
                        local target = mate and mate:IsA("Attachment") and ride[1]
                        if target then
                            for _, old in ipairs(handle:GetChildren()) do
                                if old:IsA("JointInstance") then old:Destroy() end
                            end
                            local offset = ride[2] * mate.CFrame * att.CFrame:Inverse()
                            handle.CFrame = target.CFrame * offset
                            local w = Instance.new("Weld")
                            w.Part0, w.Part1, w.C0 = target, handle, offset
                            w.Parent = handle
                            placed = true
                            break
                        end
                    end
                end
                if not placed then acc:Destroy() end
            end
        end

        local d = { key = sourceKey(), overlay = overlay, hidden = {}, keep = keep }
        hideRig(model, d)
        overlay.Parent = fxFolder
        dressed[model] = d
    end

    --!luaq:no_virtualize
    local function loadAvatar()
        CC.gen = CC.gen + 1
        local mine = CC.gen
        local who = (CC.user:gsub("^%s+", "")):gsub("%s+$", "")
        if CC.source ~= "Roblox Avatar" or who == "" then return end
        if CC.avatar and CC.avatarFor == who then return end
        CC.avatar, CC.avatarFor = nil, nil
        task.spawn(function()
            local ok, model = pcall(function()
                local id = tonumber(who) or Players:GetUserIdFromNameAsync(who)
                local desc = Players:GetHumanoidDescriptionFromUserId(id)
                desc.Head, desc.Torso, desc.LeftArm, desc.RightArm, desc.LeftLeg, desc.RightLeg = 0, 0, 0, 0, 0, 0
                desc.BodyTypeScale, desc.ProportionScale = 0, 0
                desc.HeightScale, desc.WidthScale, desc.DepthScale, desc.HeadScale = 1, 1, 1, 1
                return Players:CreateHumanoidModelFromDescription(desc, Enum.HumanoidRigType.R15)
            end)
            if mine ~= CC.gen or hub.unloaded then return end
            if ok and model then
                CC.avatar, CC.avatarFor = model, who
            else
                elevate()
                pcall(function()
                    WindUI:Notify({ Title = "character changer", Content = "couldn't load an avatar for '" .. who .. "'", Duration = 4 })
                end)
            end
        end)
    end

    local filePaths = {}
    --!luaq:no_virtualize
    local function customFiles()
        local names = {}
        table.clear(filePaths)
        pcall(function()
            if isfolder and not isfolder(CUSTOM_DIRS[1]) then
                if not isfolder("zaml") then makefolder("zaml") end
                makefolder(CUSTOM_DIRS[1])
            end
        end)
        for _, dir in ipairs(CUSTOM_DIRS) do
            pcall(function()
                if not isfolder(dir) then return end
                for _, path in ipairs(listfiles(dir)) do
                    local name = path:match("([^/\\]+)$")
                    if name and name:lower():match("%.rbxmx?$") then
                        local label = (dir == CUSTOM_DIRS[1]) and name or ("zamlblox/" .. name)
                        filePaths[label] = dir .. "/" .. name
                        names[#names + 1] = label
                    end
                end
            end)
        end
        table.sort(names)
        if #names == 0 then names[1] = "(no files)" end
        return names
    end

    --!luaq:no_virtualize
    local function loadCustom()
        local file = CC.file
        if CC.source ~= "Custom Model" or not file or not filePaths[file] then return end
        if CC.custom and CC.customFor == file then return end
        CC.custom, CC.customFor = nil, nil
        local ok, objs = pcall(function()
            return game:GetObjects(getcustomasset(filePaths[file]))
        end)
        elevate()
        local model = ok and type(objs) == "table" and objs[1]

        if model and not model:IsA("Model") then model = model:FindFirstChildWhichIsA("Model", true) end
        if model then
            CC.custom, CC.customFor = model, file
        else
            pcall(function()
                WindUI:Notify({ Title = "character changer", Content = "couldn't load " .. file, Duration = 4 })
            end)
        end
    end

    --!luaq:no_virtualize
    local function modelOf(who)
        if not who or who == "" then
            return tp.ent and tp.ent.Model, LocalPlayer.Name
        end
        local lower = who:lower()
        for _, e in pairs(Entities.GetAllCategoryEntities("Character")) do
            local pl = entPlayer(e)
            if pl and (pl.Name:lower() == lower or pl.DisplayName:lower() == lower) and e.Model then
                return e.Model, pl.Name
            end
        end
        return nil
    end

    --!luaq:no_virtualize
    local function saveCharacter(who)
        local char, owner = modelOf(who)
        if not char then
            return false, (who == "" or not who) and "turn Third Person on first (your body only exists then)" or "player not found"
        end
        if type(saveinstance) ~= "function" then return false, "no saveinstance" end

        undressAll()
        for _, d in ipairs(char:GetDescendants()) do pcall(function() d.Archivable = true end) end
        char.Archivable = true
        local copy = char:Clone()
        if not copy then return false, "could not clone" end
        for _, d in ipairs(copy:GetDescendants()) do
            if d:IsA("LuaSourceContainer") or d:IsA("Sound") or d:IsA("BillboardGui") or d:IsA("Highlight") then
                d:Destroy()
            elseif d:IsA("BasePart") then
                d.Anchored = true
            end
        end
        local dir = CUSTOM_DIRS[1]
        local highest = 0
        pcall(function()
            if not isfolder("zaml") then makefolder("zaml") end
            if not isfolder(dir) then makefolder(dir) end
            for _, path in ipairs(listfiles(dir)) do
                local n = tonumber((path:match("([^/\\]+)$") or ""):match("^(%d+)%.rbxmx?$"))
                if n and n > highest then highest = n end
            end
        end)
        local name = tostring(highest + 1)
        copy.Name = name
        local temp = "zt_charsave_" .. tostring(math.random(100000, 999999))
        task.spawn(function()
            local ok = pcall(saveinstance, copy, { FileName = temp, mode = "model" })
            local written
            local deadline = os.clock() + 30
            while ok and os.clock() < deadline and not written do
                for _, ext in ipairs({ ".rbxmx", ".rbxm" }) do
                    if isfile(temp .. ext) then written = temp .. ext end
                end
                if not written then task.wait(0.25) end
            end
            local msg = "Saving failed"
            if written then

                local last, stable = -1, 0
                while stable < 3 do
                    local okR, data = pcall(readfile, written)
                    local size = okR and #data or -1
                    if size == last and size > 0 then stable = stable + 1 else stable = 0 end
                    last = size
                    task.wait(0.2)
                end
                pcall(function()
                    writefile(dir .. "/" .. name .. written:match("%.%w+$"), readfile(written))
                    delfile(written)
                end)
                msg = "Saved " .. tostring(owner) .. " as " .. name .. written:match("%.%w+$") .. " in " .. dir
            end
            pcall(function() copy:Destroy() end)
            elevate()
            pcall(function() WindUI:Notify({ Title = "character changer", Content = msg, Duration = 5 }) end)
            if CC.refreshFiles then pcall(CC.refreshFiles) end
        end)
        return true
    end

    --!luaq:no_virtualize
    local function wantsSelf()
        return CC.target == "Self" or CC.target == "Everyone"
    end
    --!luaq:no_virtualize
    local function wantsOther(enemy)
        if CC.target == "Everyone" then return true end
        return (CC.target == "Enemies" and enemy) or (CC.target == "Teammates" and not enemy)
    end

    hub.onUnload(undressAll)

    local remembered = {}
    local lastPass = 0
    --!luaq:no_virtualize
    local function passNow() lastPass = 0 end

    tp.onBody = LUAQ_NO_VIRTUALIZE(function(ent)
        if CC.on and wantsSelf() and ent.Model and template() then
            pcall(dress, ent.Model, ent.CurrentWeaponModel)
        end
    end)
    tp.onRemove = LUAQ_NO_VIRTUALIZE(function(ent)
        if ent.Model then undress(ent.Model) end
    end)
    do
        local conn = Entities.OnEntityCreated:Connect(function(kind, id, ent)
            if hub.unloaded or kind ~= "Character" or type(ent) ~= "table" or not ent.Model then return end
            if CC.on and template() and wantsOther(isEnemy(ent)) and not dressed[ent.Model] then
                remembered[id] = true
                pcall(dress, ent.Model, ent.CurrentWeaponModel)
            end
        end)
        hub.onUnload(function()
            tp.onBody, tp.onRemove = nil, nil
            pcall(function() if conn and conn.Disconnect then conn:Disconnect() end end)
        end)
    end

    for _, name in ipairs(agentNames) do agentTemplate(name) end
    hub.connect(RunService.Heartbeat, LUAQ_NO_VIRTUALIZE(function()
        local now = os.clock()
        if now - lastPass < 0.3 then return end
        lastPass = now
        if not (CC.on and template()) then
            if next(dressed) then undressAll() end
            return
        end

        local live = {}
        --!luaq:no_virtualize
        local function consider(model, keep)
            if not (model and model:IsDescendantOf(workspace) and model:FindFirstChild("UpperTorso")) then return end
            live[model] = true
            local d = dressed[model]
            if d and (d.key ~= sourceKey() or not d.overlay.Parent) then
                undress(model)
                d = nil
            end
            if not d then
                pcall(dress, model, keep)
            else

                d.keep = keep
                hideRig(model, d)
            end
        end

        for id, e in pairs(Entities.GetAllCategoryEntities("Character")) do
            if alive(e) then
                local want = wantsOther(isEnemy(e))
                remembered[id] = want
                if want then consider(e.Model, e.CurrentWeaponModel) end
            end
        end
        local char = localChar()
        if char then remembered[char.Simulation.Identifier] = wantsSelf() end
        if tp.ent and tp.ent.Model and wantsSelf() then
            consider(tp.ent.Model, tp.ent.CurrentWeaponModel)
        end
        local ragdolls = workspace:FindFirstChild("Ragdolls")
        if ragdolls then
            for _, m in ipairs(ragdolls:GetChildren()) do
                if m:IsA("Model") and remembered[tonumber(m.Name)] then consider(m, nil) end
            end
        end
        for model in pairs(dressed) do
            if not live[model] then undress(model) end
        end
    end))

    VisualTab:Toggle({
        Title = "character changer",
        Value = false,
        Flag  = "charChanger",
        Callback = function(state) CC.on = state; undressAll(); passNow() end,
    })

    VisualTab:Dropdown({
        Title = "change who",
        Values = { "Self", "Enemies", "Teammates", "Everyone" },
        Value = "Self",
        Flag  = "charChangerTarget",
        Callback = function(v) CC.target = pick(v); undressAll(); passNow() end,
    })

    local modelValues = table.clone(agentNames)
    modelValues[#modelValues + 1] = "Roblox Avatar"
    modelValues[#modelValues + 1] = "Custom Model"
    VisualTab:Dropdown({
        Title = "character model",
        Values = modelValues,
        Value = CC.source,
        SearchBarEnabled = true,
        Flag  = "charChangerModel",
        Callback = function(v)
            CC.source = pick(v)
            undressAll()
            loadAvatar()
            loadCustom()
            passNow()
        end,
    })

    local fileDropdown = VisualTab:Dropdown({
        Title = "custom model file",
        Values = customFiles(),
        Value = customFiles()[1],
        Flag  = "charChangerFile",
        Callback = function(v)
            CC.file = pick(v)
            undressAll()
            loadCustom()
            passNow()
        end,
    })
    CC.file = customFiles()[1]
    CC.refreshFiles = LUAQ_NO_VIRTUALIZE(function()
        local list = customFiles()
        pcall(function() fileDropdown:Refresh(list) end)
        if not table.find(list, CC.file) then CC.file = list[1] end
    end)

    VisualTab:Button({
        Title = "refresh model files",
        Callback = function() CC.refreshFiles() end,
    })

    local saveWho = ""
    VisualTab:Input({
        Title = "save who",
        Value = "",
        Placeholder = "player name (empty = you)",
        Callback = function(txt) saveWho = tostring(txt or "") end,
    })

    VisualTab:Button({
        Title = "save character",
        Callback = function()
            local ok, why = saveCharacter(saveWho)
            if not ok then
                pcall(function() WindUI:Notify({ Title = "character changer", Content = "can't save: " .. tostring(why), Duration = 4 }) end)
            end
        end,
    })

    VisualTab:Input({
        Title = "avatar account",
        Value = "",
        Placeholder = "username or user id",
        Flag  = "charChangerUser",
        Callback = function(txt)
            txt = tostring(txt or "")
            if txt == CC.user then return end
            CC.user = txt
            undressAll()
            loadAvatar()
        end,
    })
end

VisualTab:Section({ Title = "hit effects" })

VisualTab:Toggle({ Title = "hit marker", Value = false, Flag = "hitMarker", Callback = function(state) S.hitMarker = state end })
VisualTab:Colorpicker({ Title = "hit marker color", Default = S.hitColor, Flag = "hitMarkerColor", Callback = function(c) S.hitColor = c end })
VisualTab:Colorpicker({ Title = "kill marker color", Default = S.killColor, Flag = "hitMarkerKill", Callback = function(c) S.killColor = c end })

VisualTab:Dropdown({
    Title = "hit marker position",
    Values = { "Crosshair", "Where It Landed", "Both" },
    Value = "Crosshair",
    Flag  = "hitMarkerWhere",
    Callback = function(v) S.hitWhere = pick(v) end,
})

VisualTab:Dropdown({
    Title = "hit marker animation",
    Values = { "Fade", "Expand", "Shrink", "Spin" },
    Value = "Fade",
    Flag  = "hitMarkerAnim",
    Callback = function(v) S.hitAnim = pick(v) end,
})

VisualTab:Slider({
    Title = "hit marker time (s)",
    Value = { Min = 0.1, Max = 3, Default = 0.45 },
    Step  = 0.05,
    Flag  = "hitMarkerTime",
    Callback = function(v) S.hitTime = v end,
})

VisualTab:Dropdown({
    Title = "hit marker shape",
    Values = { "X", "Plus", "Square", "Circle" },
    Value = "X",
    Flag  = "hitMarkerShape",
    Callback = function(v) S.hitShape = pick(v) end,
})

VisualTab:Slider({
    Title = "hit marker size",
    Value = { Min = 2, Max = 40, Default = 10 },
    Flag  = "hitMarkerSize",
    Callback = function(v) S.hitSize = v end,
})

VisualTab:Slider({ Title = "hit marker thickness", Value = { Min = 1, Max = 8, Default = 2 }, Flag = "hitMarkerThick", Callback = function(v) S.hitThick = v end })

VisualTab:Slider({
    Title = "hit marker gap",
    Value = { Min = 0, Max = 40, Default = 4 },
    Flag  = "hitMarkerGap",
    Callback = function(v) S.hitGap = v end,
})

VisualTab:Toggle({ Title = "hit marker outline", Value = true, Flag = "hitMarkerOutline", Callback = function(state) S.hitOutline = state end })

VisualTab:Slider({
    Title = "kill marker scale",
    Value = { Min = 1, Max = 3, Default = 1.4 },
    Step  = 0.1,
    Flag  = "hitMarkerKillScale",
    Callback = function(v) S.killScale = v end,
})

VisualTab:Toggle({
    Title = "hit marker damage",
    Value = false,
    Flag  = "hitMarkerDamage",
    Callback = function(state) S.hitDamage = state end,
})

VisualTab:Slider({
    Title = "world marker rise",
    Value = { Min = 0, Max = 6, Default = 0 },
    Step  = 0.5,
    Flag  = "hitMarkerRise",
    Callback = function(v) S.hitRise = v end,
})

VisualTab:Button({
    Title = "test hit marker",
    Callback = function()
        local char = localChar()
        local pos = Camera.CFrame.Position + Camera.CFrame.LookVector * 20
        markers[#markers + 1] = { at = os.clock(), kill = false, damage = 27, pos = pos }
    end,
})

VisualTab:Section({ Title = "bullet tracer" })

VisualTab:Toggle({ Title = "bullet tracer", Value = false, Flag = "tracerEnabled", Callback = function(state) S.tracer = state end })

tracerColorPicker = VisualTab:Colorpicker({
    Title = "tracer color",
    Default = tracerColor,
    Flag  = "tracerColor",
    Callback = function(c) tracerColor = c end,
})

VisualTab:Slider({ Title = "tracer width", Value = { Min = 1, Max = 30, Default = 6 }, Flag = "tracerWidth", Callback = function(v) S.tracerWidth = v / 75 end })

VisualTab:Slider({
    Title = "tracer lifetime (s)",
    Value = { Min = 0.1, Max = 10, Default = 1 },
    Step  = 0.1,
    Flag  = "tracerLife",
    Callback = function(v) S.tracerLife = v end,
})

VisualTab:Dropdown({
    Title = "tracer style",
    Values = { "Line", "Beam", "Lightning" },
    Value = "Line",
    Flag  = "tracerStyle",
    Callback = function(v) S.tracerStyle = pick(v) end,
})

VisualTab:Dropdown({
    Title = "tracer start",
    Values = { "Gun", "Eye" },
    Value = "Gun",
    Flag  = "tracerFrom",
    Callback = function(v) S.tracerFrom = pick(v) end,
})

VisualTab:Toggle({ Title = "rainbow tracers", Value = false, Flag = "tracerRainbow", Callback = function(state) S.tracerRainbow = state end })

VisualTab:Toggle({
    Title = "only on hits",
    Value = false,
    Flag  = "tracerOnlyHits",
    Callback = function(state) S.tracerOnlyHits = state end,
})

VisualTab:Toggle({ Title = "impact marker", Value = false, Flag = "impactEnabled", Callback = function(state) S.impact = state end })

VisualTab:Slider({
    Title = "impact size",
    Value = { Min = 0.1, Max = 1.5, Default = 0.35 },
    Step  = 0.05,
    Flag  = "impactSize",
    Callback = function(v) S.impactSize = v end,
})

VisualTab:Toggle({ Title = "impact glow", Value = false, Flag = "impactGlow", Callback = function(state) S.impactGlow = state end })

impactColorPicker = VisualTab:Colorpicker({
    Title = "impact color",
    Default = impactColor,
    Flag  = "impactColor",
    Callback = function(c) impactColor = c end,
})

VisualTab:Section({ Title = "hit sound" })

VisualTab:Toggle({ Title = "hit sound", Value = false, Flag = "hitSound", Callback = function(state) S.hitSound = state end })

VisualTab:Input({
    Title = "hit sound id",
    Value = S.hitSoundId,
    Placeholder = "asset id",
    Flag  = "hitSoundId",
    Callback = function(txt) S.hitSoundId = txt end,
})

VisualTab:Slider({ Title = "hit volume", Value = { Min = 0, Max = 100, Default = 60 }, Flag = "hitVol", Callback = function(v) S.hitVolume = v / 100 end })
VisualTab:Button({ Title = "test hit sound", Callback = function() playSound(S.hitSoundId, S.hitVolume) end })

VisualTab:Section({ Title = "kill sound" })

VisualTab:Toggle({ Title = "kill sound", Value = false, Flag = "killSound", Callback = function(state) S.killSound = state end })

VisualTab:Input({
    Title = "kill sound id",
    Value = S.killSoundId,
    Placeholder = "asset id",
    Flag  = "killSoundId",
    Callback = function(txt) S.killSoundId = txt end,
})

VisualTab:Slider({ Title = "kill volume", Value = { Min = 0, Max = 100, Default = 100 }, Flag = "killVol", Callback = function(v) S.killVolume = v / 100 end })
VisualTab:Button({ Title = "test kill sound", Callback = function() playSound(S.killSoundId, S.killVolume) end })

local MoveTab = Window:Tab({ Title = "movement", Icon = "move" })

MoveTab:Section({ Title = "bunny hop" })

MoveTab:Toggle({
    Title = "auto bhop",
    Value = false,
    Flag  = "bhop",
    Callback = function(state) S.bhop = state end,
})

MoveTab:Section({ Title = "auto strafe" })

MoveTab:Toggle({
    Title = "silent auto strafe",
    Value = false,
    Flag  = "strafe",
    Callback = function(state) S.strafe = state end,
})

MoveTab:Dropdown({
    Title = "strafe mode",
    Values = { "Rage", "Legit" },
    Value = "Rage",
    Flag  = "strafeMode",
    Callback = function(v) S.strafeMode = pick(v) end,
})

MoveTab:Toggle({
    Title = "fast turn",
    Value = true,
    Flag  = "strafeFastTurn",
    Callback = function(state) S.fastTurn = state end,
})

MoveTab:Slider({
    Title = "align threshold",
    Value = { Min = 2, Max = 60, Default = 8 },
    Flag  = "strafeAlign",
    Callback = function(v) S.alignThreshold = v end,
})

local Lighting = game:GetService("Lighting")

local SKYBOXES = {
    ["Galaxy"]   = { Bk="rbxassetid://159454299", Dn="rbxassetid://159454296", Ft="rbxassetid://159454293", Lf="rbxassetid://159454286", Rt="rbxassetid://159454300", Up="rbxassetid://159454288" },
    ["Pink Sky"] = { Lf="rbxassetid://271042310", Bk="rbxassetid://271042516", Dn="rbxassetid://271077243", Ft="rbxassetid://271042556", Rt="rbxassetid://271042467", Up="rbxassetid://271077958" },
    ["Sunset"]   = { Bk="rbxassetid://458016711", Dn="rbxassetid://458016826", Ft="rbxassetid://458016532", Lf="rbxassetid://458016655", Rt="rbxassetid://458016782", Up="rbxassetid://458016792" },
    ["Night"]    = { Bk="rbxassetid://48020371",  Dn="rbxassetid://48020144",  Ft="rbxassetid://48020234",  Lf="rbxassetid://48020211",  Rt="rbxassetid://48020254",  Up="rbxassetid://48020383" },
    ["Custom"]   = {},
    ["Evening"]  = { Lf="rbxassetid://7950573918", Bk="rbxassetid://7950569153", Dn="rbxassetid://7950570785", Ft="rbxassetid://7950572449", Rt="rbxassetid://7950575055", Up="rbxassetid://7950627627" },
}

local wrlAmbient      = false
local wrlAmbientColor = Color3.fromRGB(75, 58, 222)
local wrlOutdoorColor = Color3.fromRGB(109, 58, 206)
local wrlForceTime    = false
local wrlTimeValue    = 12
local wrlSatValue     = 0
local wrlSkybox       = false
local wrlSkyboxType   = "Galaxy"

local wrlOrigAmbient = Lighting.Ambient
local wrlOrigOutdoor = Lighting.OutdoorAmbient
local wrlOrigClock   = Lighting.ClockTime

local wrlCC = Instance.new("ColorCorrectionEffect")
wrlCC.Name = "ZamltraSaturation"; wrlCC.Enabled = false; wrlCC.Parent = workspace.CurrentCamera
hub.onUnload((function(origShadows)
    return function()
        if wrlAmbient then
            Lighting.Ambient = wrlOrigAmbient
            Lighting.OutdoorAmbient = wrlOrigOutdoor
        end
        if wrlForceTime then pcall(function() Lighting.ClockTime = wrlOrigClock end) end
        pcall(function() Lighting.GlobalShadows = origShadows end)
        pcall(function() wrlCC:Destroy() end)
        local sky = Lighting:FindFirstChild("ZamltraSky")
        if sky then sky:Destroy() end
    end
end)(Lighting.GlobalShadows))

--!luaq:no_virtualize
local function applySkybox()
    local existing = Lighting:FindFirstChild("ZamltraSky")
    if wrlSkybox then
        local s = SKYBOXES[wrlSkyboxType]
        if not (s and s.Bk) then return end
        local sky = existing or Instance.new("Sky")
        sky.Name = "ZamltraSky"
        sky.SkyboxBk, sky.SkyboxDn, sky.SkyboxFt = s.Bk, s.Dn, s.Ft
        sky.SkyboxLf, sky.SkyboxRt, sky.SkyboxUp = s.Lf, s.Rt, s.Up
        sky.Parent = Lighting
    elseif existing then
        existing:Destroy()
    end
end

hub.connect(RunService.Heartbeat, LUAQ_NO_VIRTUALIZE(function()
    local cam = workspace.CurrentCamera
    if cam and wrlCC.Parent ~= cam then
        if not pcall(function() wrlCC.Parent = cam end) then
            local enabled, sat = wrlCC.Enabled, wrlCC.Saturation
            wrlCC = Instance.new("ColorCorrectionEffect")
            wrlCC.Name, wrlCC.Enabled, wrlCC.Saturation = "ZamltraSaturation", enabled, sat
            wrlCC.Parent = cam
        end
    end
    if wrlSkybox and not Lighting:FindFirstChild("ZamltraSky") then applySkybox() end
    if wrlAmbient then
        Lighting.Ambient = wrlAmbientColor
        Lighting.OutdoorAmbient = wrlOutdoorColor
    end
    if wrlForceTime then
        Lighting.ClockTime = wrlTimeValue
    end
end))

local WorldTab = Window:Tab({ Title = "world", Icon = "globe" })

WorldTab:Section({ Title = "lighting" })

WorldTab:Toggle({
    Title = "ambience",
    Value = false,
    Flag  = "wrl_ambient",
    Callback = function(state)
        wrlAmbient = state
        if not state then
            Lighting.Ambient = wrlOrigAmbient
            Lighting.OutdoorAmbient = wrlOrigOutdoor
        end
    end,
})

local wrlAmbientPicker = WorldTab:Colorpicker({
    Title = "ambient color",
    Default = wrlAmbientColor,
    Flag = "wrl_ambientColor",
    Callback = function(c) wrlAmbientColor = c end,
})

local wrlOutdoorPicker = WorldTab:Colorpicker({
    Title = "outdoor color",
    Default = wrlOutdoorColor,
    Flag = "wrl_outdoorColor",
    Callback = function(c) wrlOutdoorColor = c end,
})

WorldTab:Toggle({
    Title = "shadow map",
    Value = Lighting.GlobalShadows,
    Flag  = "wrl_shadows",
    Callback = function(state) pcall(function() Lighting.GlobalShadows = state end) end,
})

WorldTab:Toggle({
    Title = "force time",
    Value = false,
    Flag  = "wrl_forcetime",
    Callback = function(state)
        wrlForceTime = state
        if not state then pcall(function() Lighting.ClockTime = wrlOrigClock end) end
    end,
})

WorldTab:Slider({
    Title = "time",
    Value = { Min = 0, Max = 24, Default = 12 },
    Step  = 1,
    Flag  = "wrl_time",
    Callback = function(v) wrlTimeValue = v end,
})

WorldTab:Section({ Title = "effects" })

WorldTab:Toggle({
    Title = "saturation",
    Value = false,
    Flag  = "wrl_saturation",
    Callback = function(state) wrlCC.Enabled = state; wrlCC.Saturation = wrlSatValue end,
})

WorldTab:Slider({
    Title = "saturation value",
    Value = { Min = -1, Max = 5, Default = 0 },
    Step  = 0.05,
    Flag  = "wrl_satvalue",
    Callback = function(v) wrlSatValue = v; wrlCC.Saturation = v end,
})

WorldTab:Section({ Title = "skybox" })

WorldTab:Toggle({
    Title = "skybox",
    Value = false,
    Flag  = "wrl_skybox",
    Callback = function(state) wrlSkybox = state; applySkybox() end,
})

WorldTab:Dropdown({
    Title = "skybox type",
    Values = { "Galaxy", "Pink Sky", "Sunset", "Night", "Evening", "Custom" },
    Value = "Galaxy",
    Flag  = "wrl_skyboxtype",
    Callback = function(v)
        wrlSkyboxType = (type(v) == "table") and v[1] or v
        applySkybox()
    end,
})

WorldTab:Input({
    Title = "custom skybox id",
    Value = "",
    Placeholder = "asset id",
    Flag  = "wrl_skyboxid",
    Callback = function(txt)
        local id = normalizeId(txt)
        local t = SKYBOXES["Custom"]
        t.Bk, t.Dn, t.Ft, t.Lf, t.Rt, t.Up = id, id, id, id, id, id
        applySkybox()
    end,
})

do
    local W = {
        fullbright = false,
        bright = false, brightness = 2, exposure = 0,
        fog = "Default", fogColor = Color3.fromRGB(190, 200, 220), fogStart = 0, fogEnd = 400,
        noPost = false,
        night = false, nightStrength = 0.6,
        asus = false, asusValue = 0.5, tint = false, tintColor = Color3.fromRGB(110, 90, 255), tintStrength = 0.5,
        weather = "Off", weatherAmount = 1,
    }
    local orig = {
        Brightness = Lighting.Brightness, Exposure = Lighting.ExposureCompensation,
        FogColor = Lighting.FogColor, FogStart = Lighting.FogStart, FogEnd = Lighting.FogEnd,
    }
    local WHITE = Color3.new(1, 1, 1)

    local grade = Instance.new("ColorCorrectionEffect")
    grade.Name = "ZamltraGrade"; grade.Enabled = false; grade.Parent = Camera
    local night = Instance.new("ColorCorrectionEffect")
    night.Name = "ZamltraNight"; night.Enabled = false; night.Parent = Camera
    local bloom = Instance.new("BloomEffect")
    bloom.Name = "ZamltraBloom"; bloom.Enabled = false; bloom.Parent = Camera

    local parkedAtmos = {}
    --!luaq:no_virtualize
    local function setFog(mode)
        W.fog = mode
        if mode == "Default" then
            for _, a in ipairs(parkedAtmos) do pcall(function() a.Parent = Lighting end) end
            parkedAtmos = {}
            Lighting.FogColor, Lighting.FogStart, Lighting.FogEnd = orig.FogColor, orig.FogStart, orig.FogEnd
        else
            for _, a in ipairs(Lighting:GetChildren()) do
                if a:IsA("Atmosphere") then
                    parkedAtmos[#parkedAtmos + 1] = a
                    a.Parent = nil
                end
            end
        end
    end

    local postSaved = {}
    --!luaq:no_virtualize
    local function sweepPost()
        for _, holder in ipairs({ Lighting, Camera }) do
            for _, fx in ipairs(holder:GetChildren()) do
                if fx:IsA("PostEffect") and fx.Name:sub(1, 8) ~= "Zamltra" then
                    if postSaved[fx] == nil then postSaved[fx] = fx.Enabled end
                    if fx.Enabled then fx.Enabled = false end
                end
            end
        end
    end
    --!luaq:no_virtualize
    local function restorePost()
        for fx, was in pairs(postSaved) do pcall(function() fx.Enabled = was end) end
        postSaved = {}
    end

    local mapSaved, mapGen, mapQueued = {}, 0, false
    --!luaq:no_virtualize
    local function mapActive() return W.asus or W.tint end
    --!luaq:no_virtualize
    local function applyMap()
        mapGen = mapGen + 1
        local gen = mapGen
        task.spawn(function()
            local skip = { [Camera] = true }
            for _, n in ipairs({ "Characters", "Debris" }) do
                local f = workspace:FindFirstChild(n)
                if f then skip[f] = true end
            end
            local count = 0
            --!luaq:no_virtualize
            local function visit(d)
                if not d:IsA("BasePart") or d:IsA("Terrain") then return end
                local o = mapSaved[d]
                if not o then
                    if not mapActive() then return end
                    o = { d.Transparency, d.Color }
                    mapSaved[d] = o
                end
                d.Transparency = (W.asus and o[1] < 1) and math.max(o[1], W.asusValue) or o[1]
                d.Color = W.tint and o[2]:Lerp(W.tintColor, W.tintStrength) or o[2]
            end
            for _, top in ipairs(workspace:GetChildren()) do
                if not skip[top] and not Players:GetPlayerFromCharacter(top) then
                    pcall(visit, top)
                    for _, d in ipairs(top:GetDescendants()) do
                        if gen ~= mapGen then return end
                        pcall(visit, d)
                        count = count + 1
                        if count % 2500 == 0 then task.wait() end
                    end
                end
            end
            if not mapActive() then mapSaved = {} end
        end)
    end

    --!luaq:no_virtualize
    local function queueMap()
        if mapQueued then return end
        mapQueued = true
        task.delay(0.3, function()
            mapQueued = false
            if not hub.unloaded then applyMap() end
        end)
    end

    local plate = Instance.new("Part")
    plate.Name = "ZamltraWeather"
    plate.Anchored, plate.CanCollide, plate.CanQuery, plate.CanTouch, plate.CastShadow = true, false, false, false, false
    plate.Transparency = 1
    plate.Size = Vector3.new(140, 1, 140)
    plate.Parent = fxFolder
    local emitter = Instance.new("ParticleEmitter")
    emitter.EmissionDirection = Enum.NormalId.Bottom
    emitter.Enabled = false
    emitter.Parent = plate

    --!luaq:no_virtualize
    local function setWeather()
        local mode, amount = W.weather, W.weatherAmount
        emitter.Enabled = mode ~= "Off"
        if mode == "Snow" then
            emitter.Rate = 350 * amount
            emitter.Lifetime = NumberRange.new(7, 9)
            emitter.Speed = NumberRange.new(8, 12)
            emitter.SpreadAngle = Vector2.new(12, 12)
            emitter.Acceleration = Vector3.new(1.5, 0, 0.5)
            emitter.Size = NumberSequence.new(0.22)
            emitter.Transparency = NumberSequence.new(0.15)
            emitter.Color = ColorSequence.new(WHITE)
            emitter.LightEmission = 0.6
            emitter.RotSpeed = NumberRange.new(-60, 60)
            pcall(function() emitter.Orientation = Enum.ParticleOrientation.FacingCamera end)
            pcall(function() emitter.Squash = NumberSequence.new(0) end)
        elseif mode == "Rain" then
            emitter.Rate = 1400 * amount
            emitter.Lifetime = NumberRange.new(0.8, 1)
            emitter.Speed = NumberRange.new(85, 95)
            emitter.SpreadAngle = Vector2.new(2, 2)
            emitter.Acceleration = Vector3.new(0, 0, 0)
            emitter.Size = NumberSequence.new(0.14)
            emitter.Transparency = NumberSequence.new(0.45)
            emitter.Color = ColorSequence.new(Color3.fromRGB(170, 195, 255))
            emitter.LightEmission = 0.3
            emitter.RotSpeed = NumberRange.new(0)
            pcall(function() emitter.Orientation = Enum.ParticleOrientation.VelocityParallel end)
            pcall(function() emitter.Squash = NumberSequence.new(6) end)
        end
    end

    local lastSweep, lastMap = 0, workspace:GetAttribute("Map")
    hub.connect(RunService.RenderStepped, LUAQ_NO_VIRTUALIZE(function()
        if W.fullbright then
            Lighting.Ambient, Lighting.OutdoorAmbient = WHITE, WHITE
            Lighting.Brightness = 2
        elseif W.bright then
            Lighting.Brightness = W.brightness
        end
        if W.bright then Lighting.ExposureCompensation = W.exposure end
        if W.fog == "None" then
            Lighting.FogStart, Lighting.FogEnd = 1e6, 1e6
        elseif W.fog == "Custom" then
            Lighting.FogColor, Lighting.FogStart, Lighting.FogEnd = W.fogColor, W.fogStart, math.max(W.fogEnd, W.fogStart + 1)
        end
        if W.weather ~= "Off" then
            plate.CFrame = CFrame.new(Camera.CFrame.Position + Vector3.new(0, W.weather == "Rain" and 45 or 35, 0))
        end

        local now = os.clock()
        if now - lastSweep > 0.5 then
            lastSweep = now
            if W.noPost then sweepPost() end
            if W.fog ~= "Default" and Lighting:FindFirstChildOfClass("Atmosphere") then setFog(W.fog) end

            local map = workspace:GetAttribute("Map")
            if map ~= lastMap then
                lastMap = map
                mapSaved = {}
                if mapActive() then task.delay(3, function() if not hub.unloaded then applyMap() end end) end
            end
        end
    end))

    --!luaq:no_virtualize
    local function restoreLight()
        if not W.fullbright and not W.bright then Lighting.Brightness = orig.Brightness end
        if not W.fullbright and not wrlAmbient then
            Lighting.Ambient, Lighting.OutdoorAmbient = wrlOrigAmbient, wrlOrigOutdoor
        end
        if not W.bright then Lighting.ExposureCompensation = orig.Exposure end
    end

    hub.onUnload(function()
        W.fullbright, W.bright, W.noPost, W.asus, W.tint = false, false, false, false, false
        pcall(restoreLight)
        pcall(setFog, "Default")
        pcall(restorePost)
        mapGen = mapGen + 1
        for part, o in pairs(mapSaved) do
            pcall(function() part.Transparency, part.Color = o[1], o[2] end)
        end
        grade:Destroy(); night:Destroy(); bloom:Destroy()
    end)

    --!luaq:no_virtualize
    local function applyNight()
        local s = W.nightStrength
        night.Enabled = W.night
        night.Brightness = -0.28 * s
        night.Contrast = 0.2 * s
        night.Saturation = -0.15 * s
        night.TintColor = WHITE:Lerp(Color3.fromRGB(140, 155, 255), s)
    end

    WorldTab:Section({ Title = "brightness" })

    WorldTab:Toggle({
        Title = "fullbright",
        Value = false,
        Flag  = "wrl_fullbright",
        Callback = function(state) W.fullbright = state; if not state then restoreLight() end end,
    })

    WorldTab:Toggle({
        Title = "custom brightness",
        Value = false,
        Flag  = "wrl_bright",
        Callback = function(state) W.bright = state; if not state then restoreLight() end end,
    })

    WorldTab:Slider({
        Title = "sun brightness",
        Value = { Min = 0, Max = 10, Default = 2 },
        Step  = 0.1,
        Flag  = "wrl_brightness",
        Callback = function(v) W.brightness = v end,
    })

    WorldTab:Slider({
        Title = "exposure",
        Value = { Min = -3, Max = 3, Default = 0 },
        Step  = 0.05,
        Flag  = "wrl_exposure",
        Callback = function(v) W.exposure = v end,
    })

    WorldTab:Toggle({
        Title = "night mode",
        Value = false,
        Flag  = "wrl_night",
        Callback = function(state) W.night = state; applyNight() end,
    })

    WorldTab:Slider({
        Title = "night strength",
        Value = { Min = 0.1, Max = 1, Default = 0.6 },
        Step  = 0.05,
        Flag  = "wrl_nightStrength",
        Callback = function(v) W.nightStrength = v; applyNight() end,
    })

    WorldTab:Section({ Title = "fog" })

    WorldTab:Dropdown({
        Title = "fog",
        Values = { "Default", "None", "Custom" },
        Value = "Default",
        Flag  = "wrl_fog",
        Callback = function(v) setFog((type(v) == "table") and v[1] or v) end,
    })

    WorldTab:Colorpicker({
        Title = "fog color",
        Default = W.fogColor,
        Flag  = "wrl_fogColor",
        Callback = function(c) W.fogColor = c end,
    })

    WorldTab:Slider({
        Title = "fog start",
        Value = { Min = 0, Max = 1000, Default = 0 },
        Step  = 10,
        Flag  = "wrl_fogStart",
        Callback = function(v) W.fogStart = v end,
    })

    WorldTab:Slider({
        Title = "fog end",
        Value = { Min = 20, Max = 3000, Default = 400 },
        Step  = 10,
        Flag  = "wrl_fogEnd",
        Callback = function(v) W.fogEnd = v end,
    })

    WorldTab:Section({ Title = "post processing" })

    WorldTab:Toggle({
        Title = "remove game effects",
        Value = false,
        Flag  = "wrl_noPost",
        Callback = function(state)
            W.noPost = state
            if state then sweepPost() else restorePost() end
        end,
    })

    WorldTab:Toggle({
        Title = "color grading",
        Value = false,
        Flag  = "wrl_grade",
        Callback = function(state) grade.Enabled = state end,
    })

    WorldTab:Slider({
        Title = "contrast",
        Value = { Min = -1, Max = 2, Default = 0 },
        Step  = 0.05,
        Flag  = "wrl_contrast",
        Callback = function(v) grade.Contrast = v end,
    })

    WorldTab:Slider({
        Title = "grade brightness",
        Value = { Min = -1, Max = 1, Default = 0 },
        Step  = 0.05,
        Flag  = "wrl_gradeBright",
        Callback = function(v) grade.Brightness = v end,
    })

    WorldTab:Colorpicker({
        Title = "screen tint",
        Default = WHITE,
        Flag  = "wrl_gradeTint",
        Callback = function(c) grade.TintColor = c end,
    })

    WorldTab:Toggle({
        Title = "bloom",
        Value = false,
        Flag  = "wrl_bloom",
        Callback = function(state) bloom.Enabled = state end,
    })

    WorldTab:Slider({
        Title = "bloom intensity",
        Value = { Min = 0, Max = 5, Default = 1 },
        Step  = 0.05,
        Flag  = "wrl_bloomIntensity",
        Callback = function(v) bloom.Intensity = v end,
    })

    WorldTab:Slider({
        Title = "bloom size",
        Value = { Min = 0, Max = 56, Default = 24 },
        Flag  = "wrl_bloomSize",
        Callback = function(v) bloom.Size = v end,
    })

    WorldTab:Slider({
        Title = "bloom threshold",
        Value = { Min = 0, Max = 4, Default = 2 },
        Step  = 0.05,
        Flag  = "wrl_bloomThreshold",
        Callback = function(v) bloom.Threshold = v end,
    })

    WorldTab:Section({ Title = "map" })

    WorldTab:Toggle({
        Title = "see-through walls",
        Value = false,
        Flag  = "wrl_asus",
        Callback = function(state) W.asus = state; applyMap() end,
    })

    WorldTab:Slider({
        Title = "wall transparency",
        Value = { Min = 10, Max = 95, Default = 50 },
        Step  = 5,
        Flag  = "wrl_asusValue",
        Callback = function(v) W.asusValue = v / 100; if W.asus then queueMap() end end,
    })

    WorldTab:Toggle({
        Title = "map tint",
        Value = false,
        Flag  = "wrl_tint",
        Callback = function(state) W.tint = state; applyMap() end,
    })

    WorldTab:Colorpicker({
        Title = "tint color",
        Default = W.tintColor,
        Flag  = "wrl_tintColor",
        Callback = function(c) W.tintColor = c; if W.tint then queueMap() end end,
    })

    WorldTab:Slider({
        Title = "tint strength",
        Value = { Min = 5, Max = 100, Default = 50 },
        Step  = 5,
        Flag  = "wrl_tintStrength",
        Callback = function(v) W.tintStrength = v / 100; if W.tint then queueMap() end end,
    })

    WorldTab:Section({ Title = "weather" })

    WorldTab:Dropdown({
        Title = "weather",
        Values = { "Off", "Snow", "Rain" },
        Value = "Off",
        Flag  = "wrl_weather",
        Callback = function(v) W.weather = (type(v) == "table") and v[1] or v; setWeather() end,
    })

    WorldTab:Slider({
        Title = "weather amount",
        Value = { Min = 0.2, Max = 3, Default = 1 },
        Step  = 0.1,
        Flag  = "wrl_weatherAmount",
        Callback = function(v) W.weatherAmount = v; setWeather() end,
    })
end

WorldTab:Section({ Title = "items" })

WorldTab:Toggle({
    Title = "dropped weapons",
    Value = false,
    Flag  = "wrl_drops",
    Callback = function(state) S.drops = state end,
})

WorldTab:Colorpicker({
    Title = "dropped weapon color",
    Default = S.dropColor,
    Flag  = "wrl_dropColor",
    Callback = function(c) S.dropColor = c end,
})

WorldTab:Slider({
    Title = "dropped weapon distance",
    Value = { Min = 20, Max = 600, Default = 150 },
    Step  = 10,
    Flag  = "wrl_dropDist",
    Callback = function(v) S.dropDist = v end,
})

WorldTab:Toggle({
    Title = "bomb timer",
    Value = true,
    Flag  = "wrl_bomb",
    Callback = function(state) S.bomb = state end,
})

;(function()
    local SKIN_FILE = "zaml/skins.json"
    local SKINS = {}
    local enabled = false
    local realSkin = setmetatable({}, { __mode = "k" })
    local look = setmetatable({}, { __mode = "k" })

    pcall(function()
        if isfile and isfile(SKIN_FILE) then
            local d = HttpService:JSONDecode(readfile(SKIN_FILE))
            if type(d) == "table" then SKINS = d end
        end
    end)
    --!luaq:no_virtualize
    local function saveSkins()
        pcall(function()
            if isfolder and makefolder and not isfolder("zaml") then makefolder("zaml") end
            writefile(SKIN_FILE, HttpService:JSONEncode(SKINS))
        end)
    end

    local allSkins, allWeapons = {}, {}
    pcall(function() allSkins = M.SkinManager.GetAllSkins() or {} end)
    pcall(function() allWeapons = M.WeaponManager.GetAllWeapons() or {} end)

    --!luaq:no_virtualize
    local function chosen(name)
        local want = enabled and SKINS[name]
        return (want and allSkins[name] and allSkins[name][want]) and want or nil
    end

    local knifeNames, isMelee = {}, {}
    for name, def in pairs(allWeapons) do
        if type(def) == "table" and def.Data and def.Data.Type == "Melee" then
            isMelee[name] = true
            if name ~= "CT Knife" and name ~= "T Knife" then knifeNames[#knifeNames + 1] = name end
        end
    end
    table.sort(knifeNames)
    --!luaq:no_virtualize
    local function knifeModel()
        local k = SKINS.__knife
        return (k and isMelee[k] and k ~= "CT Knife" and k ~= "T Knife") and k or "Default"
    end

    --!luaq:no_virtualize
    local function knifeSkin(name)
        local set = allSkins[name]
        if type(set) ~= "table" then return nil end
        local want = SKINS[name]
        if want and set[want] then return want end
        if set.Vanilla then return "Vanilla" end
        if set.Stock then return "Stock" end
        return (next(set))
    end

    --!luaq:no_virtualize
    local function lookSig()
        if not enabled then return "" end
        local s = (SKINS.__glove and SKINS.__gloveSkin) and (SKINS.__glove .. "/" .. SKINS.__gloveSkin) or ""
        if SKINS.__agent then s = s .. "|" .. SKINS.__agent end
        return s
    end
    --!luaq:no_virtualize
    local function dress(opts)
        if not enabled or type(opts) ~= "table" then return end
        if SKINS.__glove and SKINS.__gloveSkin then
            opts.Gloves = { WeaponName = SKINS.__glove, SkinName = SKINS.__gloveSkin }
        end
        if SKINS.__agent then opts.Agent = SKINS.__agent end
    end

    local visualName = setmetatable({}, { __mode = "k" })
    swapWhen(function() return enabled and (knifeModel() ~= "Default" or lookSig() ~= "") end, M.Viewmodel, "new", function(orig)
        return function(weapon, opts, ...)
            if hub.unloaded or type(weapon) ~= "table" or weapon.Owner ~= LocalPlayer.Name then
                return orig(weapon, opts, ...)
            end
            dress(opts)
            look[weapon] = lookSig()
            local km = knifeModel()
            if enabled and km ~= "Default" and weapon.Data and weapon.Data.Type == "Melee" and weapon.Name ~= km then
                local skin = knifeSkin(km)
                local okDef, def = pcall(M.WeaponManager.Get, km)
                if skin and okDef and def then
                    local name0, skin0 = weapon.Name, weapon.Skin

                    local AM = M.AnimationManager
                    local getRig = AM and AM.GetRig
                    local borrowed = false
                    if type(getRig) == "function" then
                        local okR, rig = pcall(getRig, "Weapon", km)
                        if okR and rig == nil then
                            AM.GetRig = function(cat, n, ...)
                                if cat == "Weapon" and n == km then return getRig(cat, name0, ...) end
                                return getRig(cat, n, ...)
                            end
                            borrowed = true
                        end
                    end
                    weapon.Name, weapon.Skin = km, skin
                    local res = table.pack(pcall(orig, weapon, opts, ...))
                    if borrowed then AM.GetRig = getRig end
                    weapon.Name = name0
                    if res[1] then
                        visualName[weapon] = km
                        return table.unpack(res, 2, res.n)
                    end
                    weapon.Skin = skin0
                end
            end
            return orig(weapon, opts, ...)
        end
    end)

    --!luaq:no_virtualize
    local function rebuild(w)
        local old = w.Viewmodel
        if not old then return false end
        local team = LocalPlayer:GetAttribute("Team")
        local opts = { Scale = 0.15, Team = team, Parent = old.Parent }
        pcall(function()
            local loadout = HttpService:JSONDecode(LocalPlayer:GetAttribute("WeaponLoadout"))[team]
            if loadout then
                local g = loadout["16"]
                if g then opts.Gloves = { WeaponName = g.WeaponName, SkinName = g.SkinName, SkinId = g.SkinId } end
                if loadout["15"] then opts.Agent = loadout["15"].SkinName end
            end
        end)
        local current = WC.GetCurrentWeapon() == w
        if not pcall(M.Viewmodel.Destroy, w) then return false end
        visualName[w] = nil
        local ok = pcall(M.Viewmodel.new, w, opts)
        if not ok or not w.Viewmodel then return false end
        look[w] = lookSig()
        pcall(M.Viewmodel.RestoreScale, w)
        w.ViewmodelIsVisible = true
        if current then

            pcall(function() WC.OnWeaponChanged:Fire(w) end)
            pcall(M.Viewmodel.SetVisible, w, (w.ZoomLevel or 0) == 0)
        else
            pcall(M.Viewmodel.SetVisible, w, false)
        end
        return true
    end

    --!luaq:no_virtualize
    local function applyLive()
        if setthreadidentity then pcall(setthreadidentity, 2) end
        local changed = 0
        local sig = lookSig()
        local km = knifeModel()
        for _, w in pairs(WC.GetWeaponInventory()) do
            if type(w) == "table" and next(w) and w.Name and w.Viewmodel then
                if realSkin[w] == nil then realSkin[w] = visualName[w] and "Stock" or w.Skin end
                local melee = w.Data and w.Data.Type == "Melee"
                local wantKnife = (enabled and melee and km ~= "Default" and w.Name ~= km) and km or nil
                local redo = (look[w] or "") ~= sig
                if wantKnife then
                    redo = redo or visualName[w] ~= wantKnife or w.Skin ~= knifeSkin(wantKnife)
                else
                    local target = chosen(w.Name) or realSkin[w]
                    if visualName[w] then
                        redo = true
                        w.Skin = target or w.Skin
                    elseif target and w.Skin ~= target then
                        redo = true
                        w.Skin = target
                    end
                end
                if redo and rebuild(w) then changed = changed + 1 end
            end
        end
        elevate()
        return changed
    end

    swapWhen(function() return enabled end, WC, "new", function(orig)
        return function(name, slot, owner, skin, ...)
            local real = skin
            if not hub.unloaded and owner == LocalPlayer.Name then
                skin = chosen(name) or skin
            end
            local weapon = orig(name, slot, owner, skin, ...)
            if type(weapon) == "table" then realSkin[weapon] = real or "Stock" end
            return weapon
        end
    end)
    hub.onUnload(function()
        enabled = false
        pcall(applyLive)
    end)

    --!luaq:no_virtualize
    local function changed()
        saveSkins()
        if enabled then
            syncSwaps()
            task.spawn(applyLive)
        end
    end

    local CATS = { "Rifle", "Pistol", "SMG", "Heavy", "Knife" }
    local CAT_OF = { Rifle = "Rifle", SniperRifle = "Rifle", Pistol = "Pistol", SMG = "SMG",
        Shotgun = "Heavy", MachineGun = "Heavy", LMG = "Heavy", Melee = "Knife" }
    local CATALOG = {}
    for _, c in ipairs(CATS) do CATALOG[c] = {} end
    for name, def in pairs(allWeapons) do
        local t = type(def) == "table" and def.Data and def.Data.Type
        local cat = t and (CAT_OF[t] or (t ~= "Bomb" and t ~= "Equipment" and t ~= "Grenade" and "Heavy" or nil))
        local set = allSkins[name]
        if cat and type(set) == "table" then
            for skin, sd in pairs(set) do

                if type(sd) == "table" and (skin ~= "Stock" or cat == "Knife") then
                    local thumb = tonumber(sd.Thumbnail)
                    table.insert(CATALOG[cat], {
                        weapon = name, skin = tostring(skin), rarity = sd.Rarity,
                        image = (thumb and thumb > 0) and ("rbxassetid://" .. thumb) or "",
                    })
                end
            end
        end
    end
    for _, c in ipairs(CATS) do
        table.sort(CATALOG[c], function(a, b)
            if a.weapon ~= b.weapon then return a.weapon < b.weapon end
            return a.skin < b.skin
        end)
    end

    local RARITY = {
        ["Stock"] = Color3.fromRGB(150, 150, 150), ["Consumer"] = Color3.fromRGB(176, 195, 217),
        ["Industrial"] = Color3.fromRGB(94, 152, 217), ["Mil-Spec"] = Color3.fromRGB(75, 105, 255),
        ["Restricted"] = Color3.fromRGB(136, 71, 255), ["Classified"] = Color3.fromRGB(211, 44, 230),
        ["Covert"] = Color3.fromRGB(235, 75, 75), ["Exceeding Rare"] = Color3.fromRGB(255, 215, 0),
        ["Contraband"] = Color3.fromRGB(228, 174, 57),
    }

    local gloveSkins, gloveNames = {}, {}
    pcall(function()
        for k, v in pairs(M.ItemManager.GetGloveCategories()) do
            local name = type(v) == "string" and v or k
            local list = {}
            for sk in pairs(M.ItemManager.GetItems(name) or {}) do list[#list + 1] = tostring(sk) end
            table.sort(list)
            if #list > 0 then
                gloveSkins[name] = list
                gloveNames[#gloveNames + 1] = name
            end
        end
    end)
    table.sort(gloveNames)
    local agentNames = {}
    for name in pairs(allSkins.Arms or {}) do agentNames[#agentNames + 1] = tostring(name) end
    table.sort(agentNames)

    local SkinSection = Window:Section({ Title = "skins", Icon = "palette", Opened = false })
    local SkinTab = SkinSection:Tab({ Title = "settings", Icon = "settings" })
    bindManager.shapeTab(SkinTab, "Skins")

    local refreshCells

    SkinTab:Section({ Title = "skin changer" })

    SkinTab:Toggle({
        Title = "skin changer",
        Value = false,
        Flag  = "skinChanger",
        Callback = function(state)
            enabled = state
            syncSwaps()
            task.spawn(applyLive)
        end,
    })

    SkinTab:Section({ Title = "gloves" })
    do
        local skinDropdown
        local gloveValues = { "Default" }
        for _, n in ipairs(gloveNames) do gloveValues[#gloveValues + 1] = n end
        SkinTab:Dropdown({
            Title = "gloves",
            Values = gloveValues,
            Value = SKINS.__glove or "Default",
            Callback = function(v)
                v = pick(v)
                if v == "Default" or not gloveSkins[v] then
                    SKINS.__glove, SKINS.__gloveSkin = nil, nil
                else
                    SKINS.__glove = v
                    if not table.find(gloveSkins[v], SKINS.__gloveSkin) then SKINS.__gloveSkin = gloveSkins[v][1] end
                end
                if skinDropdown then
                    pcall(function()
                        skinDropdown.Value = SKINS.__gloveSkin
                        skinDropdown:Refresh(gloveSkins[SKINS.__glove] or {})
                    end)
                end
                changed()
            end,
        })
        skinDropdown = SkinTab:Dropdown({
            Title = "glove skin",
            Values = gloveSkins[SKINS.__glove] or {},
            Value = SKINS.__gloveSkin,
            Callback = function(v)
                v = pick(v)
                if SKINS.__glove and gloveSkins[SKINS.__glove] and table.find(gloveSkins[SKINS.__glove], v)
                    and v ~= SKINS.__gloveSkin then
                    SKINS.__gloveSkin = v
                    changed()
                end
            end,
        })
    end

    SkinTab:Section({ Title = "agent" })
    do
        local values = { "Default" }
        for _, n in ipairs(agentNames) do values[#values + 1] = n end
        SkinTab:Dropdown({
            Title = "agent arms",
            Values = values,
            Value = SKINS.__agent or "Default",
            Callback = function(v)
                v = pick(v)
                local new = (v ~= "Default") and v or nil
                if new ~= SKINS.__agent then
                    SKINS.__agent = new
                    changed()
                end
            end,
        })
    end

    SkinTab:Section({ Title = "manage" })
    SkinTab:Button({
        Title = "clear all skins",
        Callback = function()
            table.clear(SKINS)
            changed()
            if refreshCells then refreshCells() end
            WindUI:Notify({ Title = "skins", Content = "cleared.", Duration = 2 })
        end,
    })

    local CELL_SIZE, CELL_PADDING = 84, 6
    local cells = {}

    --!luaq:no_virtualize
    local function isSelected(e)
        if isMelee[e.weapon] then
            if e.weapon == "CT Knife" or e.weapon == "T Knife" then
                return knifeModel() == "Default" and SKINS[e.weapon] == e.skin
            end
            return knifeModel() == e.weapon and SKINS[e.weapon] == e.skin
        end
        return SKINS[e.weapon] == e.skin
    end

    refreshCells = function()
        for _, c in ipairs(cells) do c.stroke.Enabled = isSelected(c.entry) end
    end

    --!luaq:no_virtualize
    local function setupGrid(tab)
        local container = tab.UIElements and tab.UIElements.ContainerFrame
        if not container then return nil end
        local list = container:FindFirstChildOfClass("UIListLayout")
        if list then list:Destroy() end
        if not container:FindFirstChildOfClass("UIGridLayout") then
            local grid = Instance.new("UIGridLayout")
            grid.CellSize = UDim2.fromOffset(CELL_SIZE, CELL_SIZE)
            grid.CellPadding = UDim2.fromOffset(CELL_PADDING, CELL_PADDING)
            grid.SortOrder = Enum.SortOrder.LayoutOrder
            grid.HorizontalAlignment = Enum.HorizontalAlignment.Left
            grid.Parent = container
        end
        return container
    end

    --!luaq:no_virtualize
    local function makeCell(parent, e, order)
        local btn = Instance.new("ImageButton")
        btn.Name = e.weapon .. " | " .. e.skin
        btn.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
        btn.BackgroundTransparency = 0.6
        btn.BorderSizePixel = 0
        btn.Image = e.image
        btn.ScaleType = Enum.ScaleType.Fit
        btn.AutoButtonColor = false
        btn.LayoutOrder = order
        Instance.new("UICorner", btn).CornerRadius = UDim.new(0, 6)

        local stroke = Instance.new("UIStroke")
        stroke.Color = Color3.fromRGB(255, 255, 255)
        stroke.Thickness = 2
        stroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border
        stroke.Enabled = false
        stroke.Parent = btn

        local weaponLabel = Instance.new("TextLabel")
        weaponLabel.Position = UDim2.fromOffset(4, 2)
        weaponLabel.Size = UDim2.new(1, -8, 0, 12)
        weaponLabel.BackgroundTransparency = 1
        weaponLabel.Font = Enum.Font.GothamBold
        weaponLabel.TextSize = 9
        weaponLabel.TextColor3 = Color3.fromRGB(200, 200, 200)
        weaponLabel.TextXAlignment = Enum.TextXAlignment.Left
        weaponLabel.TextTruncate = Enum.TextTruncate.AtEnd
        weaponLabel.Text = e.weapon
        weaponLabel.Parent = btn

        local label = Instance.new("TextLabel")
        label.AnchorPoint = Vector2.new(0.5, 1)
        label.Position = UDim2.new(0.5, 0, 1, -2)
        label.Size = UDim2.new(1, -4, 0, 14)
        label.BackgroundColor3 = Color3.fromRGB(0, 0, 0)
        label.BackgroundTransparency = 0.35
        label.BorderSizePixel = 0
        label.Font = Enum.Font.GothamMedium
        label.TextSize = 10
        label.TextColor3 = Color3.fromRGB(240, 240, 240)
        label.TextTruncate = Enum.TextTruncate.AtEnd
        label.Text = e.skin
        label.Parent = btn
        Instance.new("UICorner", label).CornerRadius = UDim.new(0, 4)

        local bar = Instance.new("Frame")
        bar.AnchorPoint = Vector2.new(0.5, 1)
        bar.Position = UDim2.new(0.5, 0, 1, 0)
        bar.Size = UDim2.new(1, -12, 0, 2)
        bar.BorderSizePixel = 0
        bar.BackgroundColor3 = RARITY[e.rarity] or RARITY.Stock
        bar.Parent = btn

        hub.connect(btn.MouseButton1Click, function()
            if isMelee[e.weapon] then
                if isSelected(e) then
                    SKINS[e.weapon] = nil
                    if SKINS.__knife == e.weapon then SKINS.__knife = nil end
                else
                    SKINS[e.weapon] = e.skin
                    SKINS.__knife = (e.weapon ~= "CT Knife" and e.weapon ~= "T Knife") and e.weapon or nil
                end
            else
                SKINS[e.weapon] = (SKINS[e.weapon] ~= e.skin) and e.skin or nil
            end
            refreshCells()
            changed()
            if not enabled then
                WindUI:Notify({ Title = "skins", Content = "turn skin changer on to see it", Duration = 2 })
            end
        end)

        btn.Parent = parent
        cells[#cells + 1] = { entry = e, stroke = stroke }
    end

    local CAT_TITLES = { Rifle = "rifles", Pistol = "pistols", SMG = "smgs", Heavy = "heavy", Knife = "knives" }
    local CAT_ICONS  = { Rifle = "crosshair", Pistol = "target", SMG = "zap", Heavy = "bomb", Knife = "sword" }

    for _, cat in ipairs(CATS) do
        if #CATALOG[cat] > 0 then
            local tab = SkinSection:Tab({ Title = CAT_TITLES[cat], Icon = CAT_ICONS[cat] })
            local grid = setupGrid(tab)
            if grid then
                for i, e in ipairs(CATALOG[cat]) do
                    makeCell(grid, e, i)
                    hub.breathe()
                end
            end
        end
    end

    refreshCells()
end)()
local MiscTab = Window:Tab({ Title = "misc", Icon = "settings" })

MiscTab:Section({ Title = "name spoofer" })

do
    local on, fake = false, ""
    local touched = setmetatable({}, { __mode = "k" })
    local reals = {}
    for _, n in ipairs({ LocalPlayer.Name, LocalPlayer.DisplayName }) do
        if type(n) == "string" and #n > 0 and not table.find(reals, n) then reals[#reals + 1] = n end
    end
    table.sort(reals, function(x, y) return #x > #y end)

    --!luaq:no_virtualize
    local function replaceAll(text, find, with)
        local out, i = {}, 1
        while true do
            local j, k = text:find(find, i, true)
            if not j then break end
            out[#out + 1] = text:sub(i, j - 1)
            out[#out + 1] = with
            i = k + 1
        end
        out[#out + 1] = text:sub(i)
        return table.concat(out)
    end

    --!luaq:no_virtualize
    local function apply(label)
        local text = label.Text
        if text == "" then return end
        local t = touched[label]
        if t and t.out == text then return end
        local new = text
        for _, real in ipairs(reals) do
            if new:find(real, 1, true) then new = replaceAll(new, real, fake) end
        end
        if new ~= text then
            touched[label] = { orig = text, out = new }
            label.Text = new
        end
    end

    --!luaq:no_virtualize
    local function restore()
        for label, t in pairs(touched) do
            pcall(function()
                if label.Text == t.out then label.Text = t.orig end
            end)
        end
        table.clear(touched)
    end
    hub.onUnload(restore)

    --!luaq:no_virtualize
    local function isText(d)
        return d:IsA("TextLabel") or d:IsA("TextButton") or d:IsA("TextBox")
    end

    --!luaq:no_virtualize
    local function active()
        return on and fake ~= "" and not hub.unloaded
    end

    local armed = false
    local watched = setmetatable({}, { __mode = "k" })
    local queue, cursor = {}, 1

    --!luaq:no_virtualize
    local function watch(d)
        if watched[d] then return end
        watched[d] = true
        hub.connect(d:GetPropertyChangedSignal("Text"), function()
            if active() then pcall(apply, d) end
        end)
    end

    --!luaq:no_virtualize
    local function onAdded(d)
        if not armed or not isText(d) then return end
        watch(d)
        if active() then pcall(apply, d) end
    end

    local playerGui = LocalPlayer:FindFirstChildOfClass("PlayerGui")
    if playerGui then hub.connect(playerGui.DescendantAdded, onAdded) end
    pcall(function() hub.connect(game:GetService("CoreGui").DescendantAdded, onAdded) end)

    --!luaq:no_virtualize
    local function rescan()
        armed = true
        queue, cursor = {}, 1
        --!luaq:no_virtualize
        local function add(root)
            if not root then return end
            for _, d in ipairs(root:GetDescendants()) do
                if isText(d) then queue[#queue + 1] = d end
            end
        end
        add(playerGui)
        if setthreadidentity then pcall(setthreadidentity, 8) end
        pcall(function() add(game:GetService("CoreGui")) end)
    end

    hub.connect(RunService.Heartbeat, LUAQ_NO_VIRTUALIZE(function()
        if cursor > #queue then return end
        if setthreadidentity then pcall(setthreadidentity, 8) end
        local stop = math.min(cursor + 199, #queue)
        for k = cursor, stop do
            local d = queue[k]
            if d.Parent then
                pcall(watch, d)
                if active() then pcall(apply, d) end
            end
        end
        cursor = stop + 1
        if cursor > #queue then queue, cursor = {}, 1 end
    end))

    MiscTab:Toggle({
        Title = "name spoofer",
        Value = false,
        Flag  = "nameSpoof",
        Callback = function(state)
            on = state
            if state then rescan() else restore() end
        end,
    })

    MiscTab:Input({
        Title = "fake name",
        Value = "",
        Placeholder = "any text",
        Flag  = "nameSpoofText",
        Callback = function(txt)
            txt = tostring(txt or "")
            if txt == fake then return end
            restore()
            fake = txt
            if on and fake ~= "" then rescan() end
        end,
    })
end

MiscTab:Section({ Title = "appearance" })

local themeNames = {}
for name in pairs(WindUI:GetThemes()) do
    table.insert(themeNames, name)
end
table.sort(themeNames)

do
    local themeDropdown = MiscTab:Dropdown({
        Title = "theme",
        Values = { WindUI:GetCurrentTheme() },
        Value = WindUI:GetCurrentTheme(),
        SearchBarEnabled = true,
        Flag = "theme",
        Callback = function(theme)
            if type(theme) == "table" then theme = theme[1] end

            if theme == WindUI:GetCurrentTheme() then return end
            pcall(function() WindUI:SetTheme(theme) end)
        end,
    })
    local filled = false
    local frame = themeDropdown and themeDropdown.ElementFrame
    if frame then
        hub.connect(frame.MouseEnter, function()
            if filled then return end
            filled = true
            if setthreadidentity then pcall(setthreadidentity, 8) end
            local current = WindUI:GetCurrentTheme()
            pcall(function() themeDropdown:Refresh(themeNames) end)
            pcall(function() themeDropdown:Select(current) end)
        end)
    end
end

MiscTab:Section({ Title = "config" })

local configNameInput = currentConfigName
MiscTab:Input({
    Title = "config name",
    Value = currentConfigName,
    Placeholder = "MyConfig",
    Callback = function(txt) configNameInput = txt end,
})

local configDropdown
MiscTab:Button({
    Title = "save config",
    Callback = function()
        local ok = doSaveConfig and doSaveConfig(configNameInput)
        if configDropdown then pcall(function() configDropdown:Refresh(listConfigNames()) end) end
        WindUI:Notify({
            Title = ok and "Config Saved" or "Save Failed",
            Content = ok and ("Saved '" .. tostring(configNameInput) .. "'") or "Could not save.",
            Duration = 3,
        })
    end,
})

local selectedConfig = currentConfigName

local AUTOLOAD_FILE = "zaml/autoload.txt"
--!luaq:no_virtualize
local function readAutoload()
    local ok, name = pcall(function() return isfile(AUTOLOAD_FILE) and readfile(AUTOLOAD_FILE) or nil end)
    return (ok and type(name) == "string" and name ~= "") and name or nil
end
--!luaq:no_virtualize
local function writeAutoload(name)
    pcall(function()
        if not isfolder("zaml") then makefolder("zaml") end
        if name then writefile(AUTOLOAD_FILE, name) elseif isfile(AUTOLOAD_FILE) then delfile(AUTOLOAD_FILE) end
    end)
end

configDropdown = MiscTab:Dropdown({
    Title = "configs",
    Values = listConfigNames(),
    Value = readAutoload() or currentConfigName,
    Callback = function(v)
        selectedConfig = (type(v) == "table") and v[1] or v
        if readAutoload() then writeAutoload(selectedConfig) end
    end,
})
selectedConfig = readAutoload() or selectedConfig

MiscTab:Toggle({
    Title = "auto load config",
    Value = readAutoload() ~= nil,
    Callback = function(state)
        writeAutoload(state and tostring(selectedConfig) or nil)
    end,
})

MiscTab:Button({
    Title = "load config",
    Callback = function()
        local ok = doLoadConfig and doLoadConfig(selectedConfig)
        WindUI:Notify({
            Title = ok and "Config Loaded" or "Load Failed",
            Content = ok and ("Loaded '" .. tostring(selectedConfig) .. "'") or "Could not load.",
            Duration = 3,
        })
    end,
})

MiscTab:Button({
    Title = "refresh list",
    Callback = function()
        if configDropdown then pcall(function() configDropdown:Refresh(listConfigNames()) end) end
    end,
})

MiscTab:Button({
    Title = "delete selected",
    Callback = function()
        local ok = doDeleteConfig and doDeleteConfig(selectedConfig)
        if configDropdown then pcall(function() configDropdown:Refresh(listConfigNames()) end) end
        WindUI:Notify({
            Title = ok and "Config Deleted" or "Delete Failed",
            Content = tostring(selectedConfig),
            Duration = 3,
        })
    end,
})

MiscTab:Section({ Title = "window" })

MiscTab:Keybind({
    Title = "show / hide ui",
    Value = "K",
    Flag = "toggleKey",
    Callback = function(key)
        pcall(function() Window:SetToggleKey(Enum.KeyCode[key]) end)
    end,
})

MiscTab:Section({ Title = "hud" })

MiscTab:Toggle({
    Title = "keybind list",
    Value = true,
    Flag = "showKeybindList",
    Callback = function(state) showKeybindList = state end,
})

MiscTab:Toggle({
    Title = "hit logs",
    Value = true,
    Flag = "hitLogs",
    Callback = function(state) S.hitLogs = state end,
})

if Config then
    local ConfigMgr = Window.ConfigManager

    --!luaq:no_virtualize
    local function afterConfigLoad()
        pcall(function()
            if tracerColorPicker and tracerColorPicker.Default then tracerColor = tracerColorPicker.Default end
            if impactColorPicker and impactColorPicker.Default then impactColor = impactColorPicker.Default end
            if wrlAmbientPicker and wrlAmbientPicker.Default then wrlAmbientColor = wrlAmbientPicker.Default end
            if wrlOutdoorPicker and wrlOutdoorPicker.Default then wrlOutdoorColor = wrlOutdoorPicker.Default end
        end)
        pcall(syncGunFX)
    end

    --!luaq:no_virtualize
    local function elemSig(el)
        local v = el.Value
        if type(v) == "table" then
            return tostring(v.Default)
        elseif v ~= nil then
            return tostring(v)
        else
            return tostring(el.Default)
        end
    end
    --!luaq:no_virtualize
    local function configSignature()
        local els = currentConfig and currentConfig.Elements
        if type(els) ~= "table" then return nil end
        local parts = {}
        for flag, el in next, els do
            parts[#parts + 1] = tostring(flag) .. "=" .. elemSig(el)
        end
        table.sort(parts)
        return table.concat(parts, ";")
    end

    local configLastSig

    --!luaq:no_virtualize
    local function sameValue(el, saved)
        local kind = saved.__type
        if kind == "Toggle" or kind == "Input" or kind == "Keybind" then
            return el.Value == saved.value
        elseif kind == "Slider" then
            return type(el.Value) == "table" and el.Value.Default == tonumber(saved.value)
        elseif kind == "Colorpicker" then
            return typeof(el.Default) == "Color3" and el.Default:ToHex():lower() == tostring(saved.value):lower()
                and (el.Transparency or 0) == (saved.transparency or 0)
        elseif kind == "Dropdown" then
            local a, b = el.Value, saved.value
            if type(a) == "table" or type(b) == "table" then
                return HttpService:JSONEncode(a) == HttpService:JSONEncode(b)
            end
            return a == b
        end
        return false
    end

    --!luaq:no_virtualize
    local function stagedLoad(cfg)
        local path = cfg and cfg.Path
        if not (path and isfile and isfile(path)) then return false end
        local okJ, data = pcall(function() return HttpService:JSONDecode(readfile(path)) end)
        if not okJ or type(data) ~= "table" then return false end
        if not data.__version then data = { __elements = data, __custom = {} } end

        pcall(function()
            if Window.PendingFlags then
                for flag, el in next, Window.PendingFlags do cfg:Register(flag, el) end
            end
        end)
        cfg.CustomData = data.__custom or {}

        local parser = ConfigMgr.Parser
        local todo = {}
        for flag, saved in next, (data.__elements or {}) do
            local el = cfg.Elements[flag]
            if el and type(saved) == "table" and parser[saved.__type] then
                local okS, same = pcall(sameValue, el, saved)
                if not (okS and same) then todo[#todo + 1] = { el, saved } end
            end
        end

        local i = 1
        while i <= #todo do
            local started, n = os.clock(), 0
            while i <= #todo and n < 8 and os.clock() - started < 0.004 do
                local item = todo[i]

                task.spawn(function() pcall(parser[item[2].__type].Load, item[1], item[2]) end)
                i, n = i + 1, n + 1
            end
            if i <= #todo and coroutine.isyieldable() then
                task.wait()
                if setthreadidentity then pcall(setthreadidentity, 8) end
            end
        end
        return true
    end

    --!luaq:no_virtualize
    local function bindElements(cfg)
        if cfg and Config.Elements then cfg.Elements = Config.Elements end
    end

    doSaveConfig = function(name)
        name = tostring(name or ""):gsub("^%s+", ""):gsub("%s+$", "")
        if name == "" then return false end
        local cfg = ConfigMgr:GetConfig(name) or ConfigMgr:CreateConfig(name)
        if not cfg then return false end
        bindElements(cfg)
        pcall(function() cfg:SetAsCurrent() end)
        currentConfig, currentConfigName = cfg, name
        if bindManager and bindManager.saveBinds then bindManager.saveBinds(false) end
        local ok = pcall(function() cfg:Save() end)
        configLastSig = configSignature()
        return ok
    end

    doLoadConfig = function(name)
        if not name or name == "" then return false end
        local cfg = ConfigMgr:GetConfig(name) or ConfigMgr:CreateConfig(name)
        if not cfg then return false end
        bindElements(cfg)
        pcall(function() cfg:SetAsCurrent() end)
        currentConfig, currentConfigName = cfg, name
        local ok = stagedLoad(cfg)
        afterConfigLoad()
        pcall(function() if bindManager and bindManager.loadBinds then bindManager.loadBinds() end end)
        configLastSig = configSignature()
        return ok
    end

    doDeleteConfig = function(name)
        if not name or name == "" then return false end
        local cfg = ConfigMgr:GetConfig(name) or ConfigMgr:CreateConfig(name)
        if not cfg or not cfg.Delete then return false end
        local ok = pcall(function() cfg:Delete() end)
        if name == currentConfigName then
            currentConfig, currentConfigName = Config, "default"
        end
        return ok
    end

    hub.building = false
    stagedLoad(Config)
    afterConfigLoad()
    pcall(function() if bindManager and bindManager.loadBinds then bindManager.loadBinds() end end)

    local auto = readAutoload()
    if auto and auto ~= currentConfigName then pcall(doLoadConfig, auto) end
end

task.spawn(function()
    task.wait(1)
    if hub.unloaded then return end
    if setthreadidentity then pcall(setthreadidentity, 8) end
    local INVITE = "https://discord.gg/ppVQvHHWtg"
    pcall(function()
        Window:Dialog({
            Title = "join our discord",
            Content = "discord.gg/ppvqvhhwtg - updates, configs and support",
            Buttons = {
                {
                    Title = "copy link",
                    Variant = "Primary",
                    Callback = function()
                        pcall(function() (setclipboard or toclipboard)(INVITE) end)
                        pcall(function() WindUI:Notify({ Title = "discord", Content = "invite link copied", Duration = 3 }) end)
                    end,
                },
                { Title = "close", Variant = "Secondary", Callback = function() end },
            },
        })
    end)
end)

end)
]==]

main()

Comments 0

Log in or sign up to comment.