Полезные сниппеты и функции

leekyrave

Известный
419
223
Описание: Сравнивает таблицу(tablek) с шаблоном(def). В случае если какого-то индекса не хватает - добавляет значение для этого индекса из шаблона(def).
Lua:
function saveJsonWdefine(tablek, def)
    for k,v in pairs(def) do
        if tablek[k] == nil then
            tablek[k] = v
        elseif type(v) == 'table' then
            tablek[k] = saveJsonWdefine(tablek[k], v)
        end
    end
    return tablek
end


Lua:
local defs = {
    index1 = 'afgagf',
    index2 = 'adsadsdasdasadads',
    ogo = {
        omluvim = 'adsdasadsdasdadas',
        mluvim = 'lolkek'
    },
    
    kek = {
        memokek = {},
    }
}

local tablemain = {
    index1 = 'afgagf',
    index2 = 'aaaaaaaaa',
    ogo = {
        omluvim = 'adsdasadsdasdadas',
    },
    
    kek = {},
}

function saveJsonWdefine(tablek, def)
    for k,v in pairs(def) do
        if tablek[k] == nil then
            tablek[k] = v
        elseif type(v) == 'table' then
            tablek[k] = saveJsonWdefine(tablek[k], v)
        end
    end
    return tablek
end

print(saveJsonWdefine(tablemain, defs))

Результат:
Форматирование (BB-код):
{index2="aaaaaaaaa",kek={memokek={}},index1="afgagf",ogo={omluvim="adsdasadsdasdadas",mluvim="lolkek"}}
 

ARMOR

kjor32 is legend
Модератор
4,843
6,061
Описание: Меняет цвет фона TAB
1660650832874.png

Примечание: Цвет можно менять сколько угодно, только после смены нужно повторно открыть ТАБ

Код:
Lua:
local memory = require("memory")

function setTabColor(lt, rt, lb, rb)
    local samp_module_base = sampGetBase()
    local tab_ptr = memory.getuint32(samp_module_base + 0x21A188, true)
 
    memory.setuint32(tab_ptr + 0x12A, rb, true)
    memory.setuint32(tab_ptr + 0x12E, lb, true)
    memory.setuint32(tab_ptr + 0x132, rt, true)
    memory.setuint32(tab_ptr + 0x136, lt, true)
end

Lua:
local memory = require("memory")

function setTabColor(lt, rt, lb, rb)
    local samp_module_base = sampGetBase()
    local tab_ptr = memory.getuint32(samp_module_base + 0x21A190, true)
 
    memory.setuint32(tab_ptr + 0x12A, rb, true)
    memory.setuint32(tab_ptr + 0x12E, lb, true)
    memory.setuint32(tab_ptr + 0x132, rt, true)
    memory.setuint32(tab_ptr + 0x136, lt, true)
end

Lua:
local memory = require("memory")

function setTabColor(lt, rt, lb, rb)
    local samp_module_base = sampGetBase()
    local tab_ptr = memory.getuint32(samp_module_base + 0x26E970, true)
 
    memory.setuint32(tab_ptr + 0x12A, rb, true)
    memory.setuint32(tab_ptr + 0x12E, lb, true)
    memory.setuint32(tab_ptr + 0x132, rt, true)
    memory.setuint32(tab_ptr + 0x136, lt, true)
end

Lua:
local memory = require("memory")

function setTabColor(lt, rt, lb, rb)
    local samp_module_base = sampGetBase()
    local tab_ptr = memory.getuint32(samp_module_base + 0x26EAA0, true)
 
    memory.setuint32(tab_ptr + 0x12A, rb, true)
    memory.setuint32(tab_ptr + 0x12E, lb, true)
    memory.setuint32(tab_ptr + 0x132, rt, true)
    memory.setuint32(tab_ptr + 0x136, lt, true)
end

Lua:
local memory = require("memory")

function setTabColor(lt, rt, lb, rb)
    local samp_module_base = sampGetBase()
    local tab_ptr = memory.getuint32(samp_module_base + 0x2ACAB8, true)
 
    memory.setuint32(tab_ptr + 0x12A, rb, true)
    memory.setuint32(tab_ptr + 0x12E, lb, true)
    memory.setuint32(tab_ptr + 0x132, rt, true)
    memory.setuint32(tab_ptr + 0x136, lt, true)
end

Пример использования:
Lua:
local memory = require 'memory'

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampRegisterChatCommand("color", function()
        setTabColor(0xFFFFFFFF, 0xFFFFFFFF, 0xFF000000, 0xFF000000)
    end)
    
    wait(-1)
end

function setTabColor(lt, rt, lb, rb)
    local samp_module_base = sampGetBase()
    local tab_ptr = memory.getuint32(samp_module_base + 0x21A188, true)
  
    memory.setuint32(tab_ptr + 0x12A, rb, true)
    memory.setuint32(tab_ptr + 0x12E, lb, true)
    memory.setuint32(tab_ptr + 0x132, rt, true)
    memory.setuint32(tab_ptr + 0x136, lt, true)
end

-- Пример хуйня, но кого это ебет?
 

ewin

Известный
675
369
Описание: генератор никнеймов с БД (5к имен, 70к фамилий)
Код:
Lua:
require 'lib.sampfuncs'
require 'lib.moonloader'

arr_nick = {}

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(1000) end
    local dlstatus = require('moonloader').download_status
    local json = getWorkingDirectory() .. '\\database.json'
    if doesFileExist(json) then os.remove(json) end
    downloadUrlToFile("https://raw.githubusercontent.com/AlannButler/database_names_surnames/main/n_s", json,
      function(id, status, p1, p2)
        if status == dlstatus.STATUSEX_ENDDOWNLOAD then
          if doesFileExist(json) then
            local f = io.open(json, 'r')
            if f then
              arr_nick = decodeJson(f:read('*a'))
              f:close()
            end
          end
        end
      end
    )
    sampRegisterChatCommand("rand_nick", rand_nick)

    while true do
        wait(0)

    end
end

function random(min, max)
    kf = math.random(min, max)
    math.randomseed(os.time() * kf)
    rand = math.random(min, max)
    return tonumber(rand)
end

function rand_nick()
    name = arr_nick[random(1, 5162)]
    surname = arr_nick[random(5163, 81533)]
    sampAddChatMessage(string.format("Ник: %s_%s", name, surname), -1)
end
 

sizeoftrickster

…And Megadeth For All?
Проверенный
120
428
Описание: Один из кусков хука d3d9, который когда-то применял в других играх
Выложу тут потому что могу и потому что у муна пресент вызывается самым последних, в итоге все рисуется даже поверх консоли сампфункса, снипет меняет это поведение
Либу hooks брать тут https://www.blast.hk/threads/55743/
Можете использовать вместе с https://www.blast.hk/threads/13380/post-650507
Lua:
local ffi = require("ffi")
local hook = require("hooks")
do
    local org_addEventHandler = addEventHandler
    local hkPresentQueueu = {}
    function hkPresent(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion)
        for i, f in ipairs(hkPresentQueueu) do
            f()
        end
        return hkPresent(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion)
    end
    local D3D9Device = hook.vmt.new(ffi.cast('intptr_t*', 0xC97C28)[0]) --эти строчки вынести в main или куда там хотите чтобы хукалось самым последним
    hkPresent = D3D9Device.hookMethod('long(__stdcall*)(void*, void*, void*, void*, void*)', hkPresent, 17) --эти строчки вынести чтобы хукалось самым последним
    function addEventHandler(event, func)
        if event == "onD3DPresent" then
            table.insert(hkPresentQueueu, func)
        else
            return org_addEventHandler(event, func)
        end
    end
end
Пример использования:
Это не готовый код, если просто Ctrl+C Ctrl+V, то вас крашнет либо не будет работать потому что sf, moon и другие перезаписывают хук, по этому сделайте так чтобы хукалось после всего
Lua:
local ffi = require("ffi")
local hook = require("hooks")
do
    local org_addEventHandler = addEventHandler
    local hkPresentQueueu = {}
    function hkPresent(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion)
        for i, f in ipairs(hkPresentQueueu) do
            f()
        end
        return hkPresent(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion)
    end
    local D3D9Device = hook.vmt.new(ffi.cast('intptr_t*', 0xC97C28)[0]) --эти строчки вынести в main или куда там хотите чтобы хукалось самым последним
    hkPresent = D3D9Device.hookMethod('long(__stdcall*)(void*, void*, void*, void*, void*)', hkPresent, 17) --эти строчки вынести чтобы хукалось самым последним
    function addEventHandler(event, func)
        if event == "onD3DPresent" then
            table.insert(hkPresentQueueu, func)
        else
            return org_addEventHandler(event, func)
        end
    end
end
local imgui = require("mimgui")
imgui.OnFrame(function() return true end, function()
    imgui.Text("1") 
end)
Предлагаю продолжить насиловать directx.
Описание: аналог трёх функций moonloader'a: onD3DPresent(OnPresent), onD3DDeviceLost(OnReset), onD3DDeviceReset(OnLost), они хукаются раньше, соответстенно таким образом можно обойти какой-нибудь фрапс или бандикам
Код:
Lua:
local xuyna = require( "Direct3D9HookDll" )

-- function onD3DPresent()
function OnPresent() end
-- function onD3DDeviceLost()
function OnReset() end
-- function onD3DDeviceReset()
function OnLost() end
-- Выгрузка(в onScriptTerminate)
xuyna.Uninitialize()
Пример:
Lua:
--[[
В mimgui/init.lua есть:
addEventHandler('onD3DPresent', function() end) -> function OnPresent() end
addEventHandler('onD3DDeviceLost', function() end) -> function OnReset() end
addEventHandler('onD3DDeviceReset', function() end) -> function OnLost() end
Их надо заменить, что-бы не изменять это в самом файле, можно скопировать содержимое файла
и вставить в свой скрипт. Еще в onScriptTerminate нужно добавить Uninitialize()
]]--

-- Вставленный init.lua в свой скрипт ищем и заменяем
--Должно получиться:
function OnPresent() -- вместо addEventHandler('onD3DPresent', function(), и так со всеми остальными
    if active then
        if not renderer then
            InitializeRenderer()
        end
        if renderer and not renderer.lost then
            renderer:SwitchContext()
            for _, sub in ipairs(subscriptionsNewFrame) do
                if sub._render and sub._before then
                    sub:_before()
                end
            end
            renderer:NewFrame()
            local hideCursor = true
            for _, sub in ipairs(subscriptionsNewFrame) do
                if sub._render then
                    sub:_draw()
                    hideCursor = hideCursor and sub.HideCursor
                 end
            end
            if hideCursor and not isCursorActive() then
                imgui.SetMouseCursor(imgui.lib.ImGuiMouseCursor_None)
            end
            renderer:EndFrame()
        end
    end
end
Скриншот игры(F8)

Скриншот записи bandicam

Lua:
local xuyna = require('Direct3D9HookDll')

--[[ MIMGUI -> init.lua ]]--
local imgui = require 'mimgui.imgui'
local DX9 = require 'mimgui.dx9'
local ffi = require 'ffi'
local winmsg = require 'windows.message'
local memory = require 'memory'
local mimgui = {}

local renderer = nil
local subscriptionsInitialize = {}
local subscriptionsNewFrame = {}
local eventsRegistered = false
local active = false
local cursorActive = false
local playerLocked = false
local iniFilePath = nil
local defaultGlyphRanges = nil

setmetatable(mimgui, {__index = imgui, __newindex = function(t, k, v)
    if imgui[k] then
        print('[mimgui] Warning! Overwriting existing key "'..k..'"!')
    end
    rawset(t, k, v)
end})

-- background "Shift" triggering fix
memory.fill(0x00531155, 0x90, 5, true)

local function ShowCursor(show)
    if show then
        showCursor(true)
    elseif cursorActive then
        showCursor(false)
    end
    cursorActive = show
end

local function LockPlayer(lock)
    if lock then
        lockPlayerControl(true)
    elseif playerLocked then
        lockPlayerControl(false)
    end
    playerLocked = lock
end

-- MoonLoader v.027
if not isCursorActive then
    isCursorActive = function() return cursorActive end
end

local function InitializeRenderer()
    -- init renderer
    local hwnd = ffi.cast('HWND', readMemory(0x00C8CF88, 4, false))
    local d3ddevice = ffi.cast('LPDIRECT3DDEVICE9', getD3DDevicePtr())
    renderer = assert(DX9.new(d3ddevice, hwnd))
    renderer:SwitchContext()
   
    -- configure imgui
    imgui.GetIO().ImeWindowHandle = nil -- default causes crash. TODO: why?
    imgui.GetIO().LogFilename = nil
    local confdir = getWorkingDirectory() .. [[\config\mimgui\]]
    if not doesDirectoryExist(confdir) then
        createDirectory(confdir)
    end
    iniFilePath = ffi.new('char[260]', confdir .. script.this.filename .. '.ini')
    imgui.GetIO().IniFilename = iniFilePath
   
    -- change font
    local fontFile = getFolderPath(0x14) .. '\\trebucbd.ttf'
    assert(doesFileExist(fontFile), '[mimgui] Font "' .. fontFile .. '" doesn\'t exist!')
    local builder = imgui.ImFontGlyphRangesBuilder()
    builder:AddRanges(imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
    builder:AddText([[‚„…†‡€‰‹‘’“”•–—™›№]])
    defaultGlyphRanges = imgui.ImVector_ImWchar()
    builder:BuildRanges(defaultGlyphRanges)
    imgui.GetIO().Fonts:AddFontFromFileTTF(fontFile, 14, nil, defaultGlyphRanges[0].Data)

    -- invoke initializers
    for _, cb in ipairs(subscriptionsInitialize) do
        cb()
    end
end

local function RegisterEvents()
function OnPresent()
    if active then
        if not renderer then
            InitializeRenderer()
        end
        if renderer and not renderer.lost then
            renderer:SwitchContext()
            for _, sub in ipairs(subscriptionsNewFrame) do
                if sub._render and sub._before then
                    sub:_before()
                end
            end
            renderer:NewFrame()
            local hideCursor = true
            for _, sub in ipairs(subscriptionsNewFrame) do
                if sub._render then
                    sub:_draw()
                    hideCursor = hideCursor and sub.HideCursor
                 end
            end
            if hideCursor and not isCursorActive() then
                imgui.SetMouseCursor(imgui.lib.ImGuiMouseCursor_None)
            end
            renderer:EndFrame()
        end
    end
end
   
    local keyState = {}
    local WM_MOUSEHWHEEL = 0x020E
    local mouseMsgs = {
        [WM_MOUSEHWHEEL]=true,
        [winmsg.WM_LBUTTONDOWN]=true,
        [winmsg.WM_LBUTTONDBLCLK]=true,
        [winmsg.WM_RBUTTONDOWN]=true,
        [winmsg.WM_RBUTTONDBLCLK]=true,
        [winmsg.WM_MBUTTONDOWN]=true,
        [winmsg.WM_MBUTTONDBLCLK]=true,
        [winmsg.WM_LBUTTONUP]=true,
        [winmsg.WM_RBUTTONUP]=true,
        [winmsg.WM_MBUTTONUP]=true,
        [winmsg.WM_MOUSEWHEEL]=true,
        [winmsg.WM_SETCURSOR]=true
    }
    local keyboardMsgs = {
        [winmsg.WM_KEYDOWN]=true,
        [winmsg.WM_SYSKEYDOWN]=true,
        [winmsg.WM_KEYUP]=true,
        [winmsg.WM_SYSKEYUP]=true,
        [winmsg.WM_CHAR]=true
    }
    addEventHandler('onWindowMessage', function(msg, wparam, lparam)
        if not renderer then
            return
        end
       
        if not mimgui.DisableInput then
            local keyboard = keyboardMsgs[msg]
            local mouse = mouseMsgs[msg]
            if active and (keyboard or mouse) then
                renderer:SwitchContext()
                local io = imgui.GetIO()
                renderer:WindowMessage(msg, wparam, lparam)
                if (keyboard and io.WantCaptureKeyboard) or (mouse and io.WantCaptureMouse) then
                    if msg == winmsg.WM_KEYDOWN or msg == winmsg.WM_SYSKEYDOWN then
                        keyState[wparam] = false
                        consumeWindowMessage(true, true, true)
                    elseif msg == winmsg.WM_KEYUP or msg == winmsg.WM_SYSKEYUP then
                        if not keyState[wparam] then
                            consumeWindowMessage(true, true, true)
                        end
                    else
                        consumeWindowMessage(true, true, true)
                    end
                end
            end
        end

        -- save key states to prevent key sticking
        if msg == winmsg.WM_KILLFOCUS then
            keyState = {}
        elseif wparam < 256 then
            if msg == winmsg.WM_KEYDOWN or msg == winmsg.WM_SYSKEYDOWN then
                keyState[wparam] = true
            elseif msg == winmsg.WM_KEYUP or msg == winmsg.WM_SYSKEYUP then
                keyState[wparam] = false
            end
        end
    end)
   
    function OnReset()
        if renderer and not renderer.lost then
            renderer:InvalidateDeviceObjects()
            renderer.lost = true
        end
    end
   
    function OnLost()
        if renderer then
            renderer.lost = false
        end
    end

    addEventHandler('onScriptTerminate', function(scr)
        if scr == script.this then
            xuyna.Uninitialize()
            ShowCursor(false)
            LockPlayer(false)
        end
    end)
   
    local updaterThread = lua_thread.create(function()
        while true do
            wait(0)
            local activate, hideCursor, lockPlayer = false, true, false
            if #subscriptionsNewFrame > 0 then
                for i, sub in ipairs(subscriptionsNewFrame) do
                    if type(sub.Condition) == 'function' then
                        sub._render = sub.Condition()
                    else
                        sub._render = sub.Condition and true
                    end
                    if sub._render then
                        hideCursor = hideCursor and sub.HideCursor
                        lockPlayer = lockPlayer or sub.LockPlayer
                    end
                    activate = activate or sub._render
                end
            end
            active = activate
            ShowCursor(active and not hideCursor)
            LockPlayer(active and lockPlayer)
        end
    end)
    updaterThread.work_in_pause = true
end

local function Unsubscribe(t, sub)
    for i, v in ipairs(t) do
        if v == sub then
            table.remove(t, i)
            return
        end
    end
end

local function ImGuiEnum(name)
    return setmetatable({__name = name}, {__index = function(t, k)
        return imgui.lib[t.__name .. k]
    end})
end

--- API ---
mimgui._VERSION = '1.7.0'
mimgui.DisableInput = false

mimgui.ComboFlags = ImGuiEnum('ImGuiComboFlags_')
mimgui.Dir = ImGuiEnum('ImGuiDir_')
mimgui.ColorEditFlags = ImGuiEnum('ImGuiColorEditFlags_')
mimgui.Col = ImGuiEnum('ImGuiCol_')
mimgui.WindowFlags = ImGuiEnum('ImGuiWindowFlags_')
mimgui.NavInput = ImGuiEnum('ImGuiNavInput_')
mimgui.FocusedFlags = ImGuiEnum('ImGuiFocusedFlags_')
mimgui.Cond = ImGuiEnum('ImGuiCond_')
mimgui.BackendFlags = ImGuiEnum('ImGuiBackendFlags_')
mimgui.TreeNodeFlags = ImGuiEnum('ImGuiTreeNodeFlags_')
mimgui.StyleVar = ImGuiEnum('ImGuiStyleVar_')
mimgui.DrawCornerFlags = ImGuiEnum('ImDrawCornerFlags_')
mimgui.DragDropFlags = ImGuiEnum('ImGuiDragDropFlags_')
mimgui.SelectableFlags = ImGuiEnum('ImGuiSelectableFlags_')
mimgui.InputTextFlags = ImGuiEnum('ImGuiInputTextFlags_')
mimgui.MouseCursor = ImGuiEnum('ImGuiMouseCursor_')
mimgui.FontAtlasFlags = ImGuiEnum('ImFontAtlasFlags_')
mimgui.HoveredFlags = ImGuiEnum('ImGuiHoveredFlags_')
mimgui.ConfigFlags = ImGuiEnum('ImGuiConfigFlags_')
mimgui.DrawListFlags = ImGuiEnum('ImDrawListFlags_')
mimgui.DataType = ImGuiEnum('ImGuiDataType_')
mimgui.Key = ImGuiEnum('ImGuiKey_')

function mimgui.OnInitialize(cb)
    assert(type(cb) == 'function')
    table.insert(subscriptionsInitialize, cb)
    return {Unsubscribe = function() Unsubscribe(subscriptionsInitialize, cb) end}
end

function mimgui.OnFrame(cond, cbBeforeFrame, cbDraw)
    assert(type(cond) == 'function')
    assert(type(cbBeforeFrame) == 'function')
    if cbDraw then assert(type(cbDraw) == 'function') end
    if not eventsRegistered then
        RegisterEvents()
        eventsRegistered = true
    end
    local sub = {
        Condition = cond,
        LockPlayer = false,
        HideCursor = false,
        _before = cbDraw and cbBeforeFrame or nil,
        _draw = cbDraw or cbBeforeFrame,
        _render = false,
    }
    function sub:Unsubscribe()
        Unsubscribe(subscriptionsNewFrame, self)
    end
    function sub:IsActive()
        return self._render
    end
    table.insert(subscriptionsNewFrame, sub)
    return sub
end

function mimgui.SwitchContext()
    return renderer:SwitchContext()
end

function mimgui.CreateTextureFromFile(path)
    return renderer:CreateTextureFromFile(path)
end

function mimgui.CreateTextureFromFileInMemory(src, size)
    return renderer:CreateTextureFromFileInMemory(src, size)
end

function mimgui.ReleaseTexture(tex)
    return renderer:ReleaseTexture(tex)
end

function mimgui.CreateFontsTexture()
    return renderer:CreateFontsTexture()
end

function mimgui.InvalidateFontsTexture()
    return renderer:InvalidateFontsTexture()
end

function mimgui.GetRenderer()
    return renderer
end

function mimgui.IsInitialized()
    return renderer ~= nil
end

function mimgui.StrCopy(dst, src, len)
    if len or tostring(ffi.typeof(dst)):find('*', 1, true) then
        ffi.copy(dst, src, len)
    else
        len = math.min(ffi.sizeof(dst) - 1, #src)
        ffi.copy(dst, src, len)
        dst[len] = 0
    end
end

local new = {}
setmetatable(new, {
    __index = function(self, key)
        local basetype = ffi.typeof(key)
        local mt = {
            __index = function(self, sz)
                return setmetatable({type = ffi.typeof('$[$]', self.type, sz)}, getmetatable(self))
            end,
            __call = function(self, ...)
                return self.type(...)
            end
        }
        return setmetatable({type = ffi.typeof('$[1]', basetype), basetype = basetype}, {
            __index = function(self, sz)
                return setmetatable({type = ffi.typeof('$[$]', self.basetype, sz)}, mt)
            end,
            __call = mt.__call
        })
    end,
    __call = function(self, t, ...)
        return ffi.new(t, ...)
    end
})
mimgui.new = new
--[[ MIMGUI -> init.lua ]]--

local newFrame = mimgui.OnFrame( --[[Сама функция создания фрейма, их может быть сколько вашей душе угодно.
                                    Обратите внимание, что в mimgui рекомендуется создавать отдельный
                                    фрейм для каждого окна, однако это не является обязательным.]]
    function() return true end, -- Определяет, выполняется/отображается ли текущий фрейм.
    function(player)            --[[Сама область, в которой уже будем рисовать элементы.
                                    В функцию в качестве первой переменной передаются список функций
                                    для взаимодействия с локальным игроком и рядом нескольких возможностей.]]
        imgui.Begin("Main Window")  -- Создаём новое окно с заголовком 'Main Window'
        imgui.Text("Hello")         -- Добавляем туда текст 'Hello'
        imgui.End()                 -- Объявляем конец данного окна
    end
)

function main()
    wait(-1)
end

Lua:
--hueta должна начинаться перед require("mimgui")
do -- begin hueta
require("Direct3D9HookDll")
local origAddEventHandler = addEventHandler
local presentQueue = {}
local lostQueue = {}
local resetQueue = {}
function addEventHandler(name, callback)
    if name == "onD3DPresent" then
        table.insert(presentQueue, callback)
    elseif name == "onD3DDeviceLost" then
        table.insert(lostQueue, callback)
    elseif name == "onD3DDeviceReset" then
        table.insert(resetQueue, callback)
    else
        origAddEventHandler(name, callback)
    end
end
function OnPresent()
    for i, callback in ipairs(presentQueue) do
        callback()
    end
end
function OnLost()
    for i, callback in ipairs(lostQueue) do
        callback()
    end
end
function OnReset()
    for i, callback in ipairs(resetQueue) do
        callback()
    end
end
origAddEventHandler("onScriptTerminate", function(scr)
    if scr == script.this then
        require("Direct3D9HookDll").Uninitialize()
    end   
end)
end -- end hueta

local imgui, ffi = require("mimgui"), require("ffi")

local newFrame = imgui.OnFrame( --[[Сама функция создания фрейма, их может быть сколько вашей душе угодно.
                                    Обратите внимание, что в mimgui рекомендуется создавать отдельный
                                    фрейм для каждого окна, однако это не является обязательным.]]
    function() return true end, -- Определяет, выполняется/отображается ли текущий фрейм.
    function(player)            --[[Сама область, в которой уже будем рисовать элементы.
                                    В функцию в качестве первой переменной передаются список функций
                                    для взаимодействия с локальным игроком и рядом нескольких возможностей.]]
        imgui.Begin("Main Window")  -- Создаём новое окно с заголовком 'Main Window'
        imgui.Text("Hello")         -- Добавляем туда текст 'Hello'
        imgui.End()                 -- Объявляем конец данного окна
    end
)

function main()
    wait(-1)
end

UPD: уменьшил размер Dll(Отключив vcpkg), добавил пример от @RTD
 

Вложения

  • Direct3D9HookDll.dll
    123 KB · Просмотры: 326
Последнее редактирование:

RTD

Нестандартное звание
Модератор
391
413
Предлагаю продолжить насиловать directx.
Описание: аналог трёх функций moonloader'a: onD3DPresent(OnPresent), onD3DDeviceLost(OnReset), onD3DDeviceReset(OnLost), они хукаются раньше, соответстенно таким образом можно обойти какой-нибудь фрапс или бандикам
Код:
Lua:
local xuyna = require( "Direct3D9HookDll" )

-- function onD3DPresent()
function OnPresent() end
-- function onD3DDeviceLost()
function OnReset() end
-- function onD3DDeviceReset()
function OnLost() end
-- Выгрузка(в onScriptTerminate)
xuyna.Uninitialize()
Пример:
Lua:
--[[
В mimgui/init.lua есть:
addEventHandler('onD3DPresent', function() end) -> function OnPresent() end
addEventHandler('onD3DDeviceLost', function() end) -> function OnReset() end
addEventHandler('onD3DDeviceReset', function() end) -> function OnLost() end
Их надо заменить, что-бы не изменять это в самом файле, можно скопировать содержимое файла
и вставить в свой скрипт. Еще в onScriptTerminate нужно добавить Uninitialize()
]]--

-- Вставленный init.lua в свой скрипт ищем и заменяем
--Должно получиться:
function OnPresent() -- вместо addEventHandler('onD3DPresent', function(), и так со всеми остальными
    if active then
        if not renderer then
            InitializeRenderer()
        end
        if renderer and not renderer.lost then
            renderer:SwitchContext()
            for _, sub in ipairs(subscriptionsNewFrame) do
                if sub._render and sub._before then
                    sub:_before()
                end
            end
            renderer:NewFrame()
            local hideCursor = true
            for _, sub in ipairs(subscriptionsNewFrame) do
                if sub._render then
                    sub:_draw()
                    hideCursor = hideCursor and sub.HideCursor
                 end
            end
            if hideCursor and not isCursorActive() then
                imgui.SetMouseCursor(imgui.lib.ImGuiMouseCursor_None)
            end
            renderer:EndFrame()
        end
    end
end
Скриншот игры(F8)

Скриншот записи bandicam

Lua:
local xuyna = require('Direct3D9HookDll')

--[[ MIMGUI -> init.lua ]]--
local imgui = require 'mimgui.imgui'
local DX9 = require 'mimgui.dx9'
local ffi = require 'ffi'
local winmsg = require 'windows.message'
local memory = require 'memory'
local mimgui = {}

local renderer = nil
local subscriptionsInitialize = {}
local subscriptionsNewFrame = {}
local eventsRegistered = false
local active = false
local cursorActive = false
local playerLocked = false
local iniFilePath = nil
local defaultGlyphRanges = nil

setmetatable(mimgui, {__index = imgui, __newindex = function(t, k, v)
    if imgui[k] then
        print('[mimgui] Warning! Overwriting existing key "'..k..'"!')
    end
    rawset(t, k, v)
end})

-- background "Shift" triggering fix
memory.fill(0x00531155, 0x90, 5, true)

local function ShowCursor(show)
    if show then
        showCursor(true)
    elseif cursorActive then
        showCursor(false)
    end
    cursorActive = show
end

local function LockPlayer(lock)
    if lock then
        lockPlayerControl(true)
    elseif playerLocked then
        lockPlayerControl(false)
    end
    playerLocked = lock
end

-- MoonLoader v.027
if not isCursorActive then
    isCursorActive = function() return cursorActive end
end

local function InitializeRenderer()
    -- init renderer
    local hwnd = ffi.cast('HWND', readMemory(0x00C8CF88, 4, false))
    local d3ddevice = ffi.cast('LPDIRECT3DDEVICE9', getD3DDevicePtr())
    renderer = assert(DX9.new(d3ddevice, hwnd))
    renderer:SwitchContext()
   
    -- configure imgui
    imgui.GetIO().ImeWindowHandle = nil -- default causes crash. TODO: why?
    imgui.GetIO().LogFilename = nil
    local confdir = getWorkingDirectory() .. [[\config\mimgui\]]
    if not doesDirectoryExist(confdir) then
        createDirectory(confdir)
    end
    iniFilePath = ffi.new('char[260]', confdir .. script.this.filename .. '.ini')
    imgui.GetIO().IniFilename = iniFilePath
   
    -- change font
    local fontFile = getFolderPath(0x14) .. '\\trebucbd.ttf'
    assert(doesFileExist(fontFile), '[mimgui] Font "' .. fontFile .. '" doesn\'t exist!')
    local builder = imgui.ImFontGlyphRangesBuilder()
    builder:AddRanges(imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
    builder:AddText([[‚„…†‡€‰‹‘’“”•–—™›№]])
    defaultGlyphRanges = imgui.ImVector_ImWchar()
    builder:BuildRanges(defaultGlyphRanges)
    imgui.GetIO().Fonts:AddFontFromFileTTF(fontFile, 14, nil, defaultGlyphRanges[0].Data)

    -- invoke initializers
    for _, cb in ipairs(subscriptionsInitialize) do
        cb()
    end
end

local function RegisterEvents()
function OnPresent()
    if active then
        if not renderer then
            InitializeRenderer()
        end
        if renderer and not renderer.lost then
            renderer:SwitchContext()
            for _, sub in ipairs(subscriptionsNewFrame) do
                if sub._render and sub._before then
                    sub:_before()
                end
            end
            renderer:NewFrame()
            local hideCursor = true
            for _, sub in ipairs(subscriptionsNewFrame) do
                if sub._render then
                    sub:_draw()
                    hideCursor = hideCursor and sub.HideCursor
                 end
            end
            if hideCursor and not isCursorActive() then
                imgui.SetMouseCursor(imgui.lib.ImGuiMouseCursor_None)
            end
            renderer:EndFrame()
        end
    end
end
   
    local keyState = {}
    local WM_MOUSEHWHEEL = 0x020E
    local mouseMsgs = {
        [WM_MOUSEHWHEEL]=true,
        [winmsg.WM_LBUTTONDOWN]=true,
        [winmsg.WM_LBUTTONDBLCLK]=true,
        [winmsg.WM_RBUTTONDOWN]=true,
        [winmsg.WM_RBUTTONDBLCLK]=true,
        [winmsg.WM_MBUTTONDOWN]=true,
        [winmsg.WM_MBUTTONDBLCLK]=true,
        [winmsg.WM_LBUTTONUP]=true,
        [winmsg.WM_RBUTTONUP]=true,
        [winmsg.WM_MBUTTONUP]=true,
        [winmsg.WM_MOUSEWHEEL]=true,
        [winmsg.WM_SETCURSOR]=true
    }
    local keyboardMsgs = {
        [winmsg.WM_KEYDOWN]=true,
        [winmsg.WM_SYSKEYDOWN]=true,
        [winmsg.WM_KEYUP]=true,
        [winmsg.WM_SYSKEYUP]=true,
        [winmsg.WM_CHAR]=true
    }
    addEventHandler('onWindowMessage', function(msg, wparam, lparam)
        if not renderer then
            return
        end
       
        if not mimgui.DisableInput then
            local keyboard = keyboardMsgs[msg]
            local mouse = mouseMsgs[msg]
            if active and (keyboard or mouse) then
                renderer:SwitchContext()
                local io = imgui.GetIO()
                renderer:WindowMessage(msg, wparam, lparam)
                if (keyboard and io.WantCaptureKeyboard) or (mouse and io.WantCaptureMouse) then
                    if msg == winmsg.WM_KEYDOWN or msg == winmsg.WM_SYSKEYDOWN then
                        keyState[wparam] = false
                        consumeWindowMessage(true, true, true)
                    elseif msg == winmsg.WM_KEYUP or msg == winmsg.WM_SYSKEYUP then
                        if not keyState[wparam] then
                            consumeWindowMessage(true, true, true)
                        end
                    else
                        consumeWindowMessage(true, true, true)
                    end
                end
            end
        end

        -- save key states to prevent key sticking
        if msg == winmsg.WM_KILLFOCUS then
            keyState = {}
        elseif wparam < 256 then
            if msg == winmsg.WM_KEYDOWN or msg == winmsg.WM_SYSKEYDOWN then
                keyState[wparam] = true
            elseif msg == winmsg.WM_KEYUP or msg == winmsg.WM_SYSKEYUP then
                keyState[wparam] = false
            end
        end
    end)
   
    function OnReset()
        if renderer and not renderer.lost then
            renderer:InvalidateDeviceObjects()
            renderer.lost = true
        end
    end
   
    function OnLost()
        if renderer then
            renderer.lost = false
        end
    end

    addEventHandler('onScriptTerminate', function(scr)
        if scr == script.this then
            xuyna.Uninitialize()
            ShowCursor(false)
            LockPlayer(false)
        end
    end)
   
    local updaterThread = lua_thread.create(function()
        while true do
            wait(0)
            local activate, hideCursor, lockPlayer = false, true, false
            if #subscriptionsNewFrame > 0 then
                for i, sub in ipairs(subscriptionsNewFrame) do
                    if type(sub.Condition) == 'function' then
                        sub._render = sub.Condition()
                    else
                        sub._render = sub.Condition and true
                    end
                    if sub._render then
                        hideCursor = hideCursor and sub.HideCursor
                        lockPlayer = lockPlayer or sub.LockPlayer
                    end
                    activate = activate or sub._render
                end
            end
            active = activate
            ShowCursor(active and not hideCursor)
            LockPlayer(active and lockPlayer)
        end
    end)
    updaterThread.work_in_pause = true
end

local function Unsubscribe(t, sub)
    for i, v in ipairs(t) do
        if v == sub then
            table.remove(t, i)
            return
        end
    end
end

local function ImGuiEnum(name)
    return setmetatable({__name = name}, {__index = function(t, k)
        return imgui.lib[t.__name .. k]
    end})
end

--- API ---
mimgui._VERSION = '1.7.0'
mimgui.DisableInput = false

mimgui.ComboFlags = ImGuiEnum('ImGuiComboFlags_')
mimgui.Dir = ImGuiEnum('ImGuiDir_')
mimgui.ColorEditFlags = ImGuiEnum('ImGuiColorEditFlags_')
mimgui.Col = ImGuiEnum('ImGuiCol_')
mimgui.WindowFlags = ImGuiEnum('ImGuiWindowFlags_')
mimgui.NavInput = ImGuiEnum('ImGuiNavInput_')
mimgui.FocusedFlags = ImGuiEnum('ImGuiFocusedFlags_')
mimgui.Cond = ImGuiEnum('ImGuiCond_')
mimgui.BackendFlags = ImGuiEnum('ImGuiBackendFlags_')
mimgui.TreeNodeFlags = ImGuiEnum('ImGuiTreeNodeFlags_')
mimgui.StyleVar = ImGuiEnum('ImGuiStyleVar_')
mimgui.DrawCornerFlags = ImGuiEnum('ImDrawCornerFlags_')
mimgui.DragDropFlags = ImGuiEnum('ImGuiDragDropFlags_')
mimgui.SelectableFlags = ImGuiEnum('ImGuiSelectableFlags_')
mimgui.InputTextFlags = ImGuiEnum('ImGuiInputTextFlags_')
mimgui.MouseCursor = ImGuiEnum('ImGuiMouseCursor_')
mimgui.FontAtlasFlags = ImGuiEnum('ImFontAtlasFlags_')
mimgui.HoveredFlags = ImGuiEnum('ImGuiHoveredFlags_')
mimgui.ConfigFlags = ImGuiEnum('ImGuiConfigFlags_')
mimgui.DrawListFlags = ImGuiEnum('ImDrawListFlags_')
mimgui.DataType = ImGuiEnum('ImGuiDataType_')
mimgui.Key = ImGuiEnum('ImGuiKey_')

function mimgui.OnInitialize(cb)
    assert(type(cb) == 'function')
    table.insert(subscriptionsInitialize, cb)
    return {Unsubscribe = function() Unsubscribe(subscriptionsInitialize, cb) end}
end

function mimgui.OnFrame(cond, cbBeforeFrame, cbDraw)
    assert(type(cond) == 'function')
    assert(type(cbBeforeFrame) == 'function')
    if cbDraw then assert(type(cbDraw) == 'function') end
    if not eventsRegistered then
        RegisterEvents()
        eventsRegistered = true
    end
    local sub = {
        Condition = cond,
        LockPlayer = false,
        HideCursor = false,
        _before = cbDraw and cbBeforeFrame or nil,
        _draw = cbDraw or cbBeforeFrame,
        _render = false,
    }
    function sub:Unsubscribe()
        Unsubscribe(subscriptionsNewFrame, self)
    end
    function sub:IsActive()
        return self._render
    end
    table.insert(subscriptionsNewFrame, sub)
    return sub
end

function mimgui.SwitchContext()
    return renderer:SwitchContext()
end

function mimgui.CreateTextureFromFile(path)
    return renderer:CreateTextureFromFile(path)
end

function mimgui.CreateTextureFromFileInMemory(src, size)
    return renderer:CreateTextureFromFileInMemory(src, size)
end

function mimgui.ReleaseTexture(tex)
    return renderer:ReleaseTexture(tex)
end

function mimgui.CreateFontsTexture()
    return renderer:CreateFontsTexture()
end

function mimgui.InvalidateFontsTexture()
    return renderer:InvalidateFontsTexture()
end

function mimgui.GetRenderer()
    return renderer
end

function mimgui.IsInitialized()
    return renderer ~= nil
end

function mimgui.StrCopy(dst, src, len)
    if len or tostring(ffi.typeof(dst)):find('*', 1, true) then
        ffi.copy(dst, src, len)
    else
        len = math.min(ffi.sizeof(dst) - 1, #src)
        ffi.copy(dst, src, len)
        dst[len] = 0
    end
end

local new = {}
setmetatable(new, {
    __index = function(self, key)
        local basetype = ffi.typeof(key)
        local mt = {
            __index = function(self, sz)
                return setmetatable({type = ffi.typeof('$[$]', self.type, sz)}, getmetatable(self))
            end,
            __call = function(self, ...)
                return self.type(...)
            end
        }
        return setmetatable({type = ffi.typeof('$[1]', basetype), basetype = basetype}, {
            __index = function(self, sz)
                return setmetatable({type = ffi.typeof('$[$]', self.basetype, sz)}, mt)
            end,
            __call = mt.__call
        })
    end,
    __call = function(self, t, ...)
        return ffi.new(t, ...)
    end
})
mimgui.new = new
--[[ MIMGUI -> init.lua ]]--

local newFrame = mimgui.OnFrame( --[[Сама функция создания фрейма, их может быть сколько вашей душе угодно.
                                    Обратите внимание, что в mimgui рекомендуется создавать отдельный
                                    фрейм для каждого окна, однако это не является обязательным.]]
    function() return true end, -- Определяет, выполняется/отображается ли текущий фрейм.
    function(player)            --[[Сама область, в которой уже будем рисовать элементы.
                                    В функцию в качестве первой переменной передаются список функций
                                    для взаимодействия с локальным игроком и рядом нескольких возможностей.]]
        imgui.Begin("Main Window")  -- Создаём новое окно с заголовком 'Main Window'
        imgui.Text("Hello")         -- Добавляем туда текст 'Hello'
        imgui.End()                 -- Объявляем конец данного окна
    end
)

function main()
    wait(-1)
end
obs bypass кста
Так проще
Lua:
--hueta должна начинаться перед require("mimgui")
do -- begin hueta
require("Direct3D9HookDll")
local origAddEventHandler = addEventHandler
local presentQueue = {}
local lostQueue = {}
local resetQueue = {}
function addEventHandler(name, callback)
    if name == "onD3DPresent" then
        table.insert(presentQueue, callback)
    elseif name == "onD3DDeviceLost" then
        table.insert(lostQueue, callback)
    elseif name == "onD3DDeviceReset" then
        table.insert(resetQueue, callback)
    else
        origAddEventHandler(name, callback)
    end
end
function OnPresent()
    for i, callback in ipairs(presentQueue) do
        callback()
    end
end
function OnLost()
    for i, callback in ipairs(lostQueue) do
        callback()
    end
end
function OnReset()
    for i, callback in ipairs(resetQueue) do
        callback()
    end
end
origAddEventHandler("onScriptTerminate", function(scr)
    if scr == script.this then
        require("Direct3D9HookDll").Uninitialize()
    end   
end)
end -- end hueta

local imgui, ffi = require("mimgui"), require("ffi")
p.s. че длл так раздута по размеру?
 

ARMOR

kjor32 is legend
Модератор
4,843
6,061
Описание: Меняет стиль шрифта денег.

Скриншот:
1661103852872.png


Код:
Lua:
local memory = require 'memory'

memory.setint8(0x58F57F, 0-3, true)

Описание: Меняет формат денег.

Скриншот:
1661108788975.png

1661109007462.png


Код:
Lua:
local memory = require 'memory'

memory.setint32(0x866C94, 0x6438302524, true) -- Позитивные деньги стандартное значение
memory.setint32(0x866C94, 0x6430302524, true) -- Позитивные деньги с удалением нулей

memory.setint64(0x866C8C, 0x64373025242D, true) -- Негативные деньги стандартное значение
memory.setint64(0x866C8C, 0x64303025242D, true) -- Негативные деньги с удалением нулей

Описание: Меняет символ разделения патронов.

Скриншот:
1661118490793.png


Код:
Lua:
local memory = require 'memory'
memory.setint8(0x866BBE, 0x26, true) -- Вместо 0x26 ставите HEX значение символа. Получить символ можете на этом сайте https://hackware.ru/?p=8604

Описание: Меняет размер обводки displayGameText

Скриншот:
52.png



Код:
Lua:
local memory = require 'memory'
memory.setint8(0x58D3DA, 1, true)
 
Последнее редактирование:

imring

Ride the Lightning
Всефорумный модератор
2,355
2,516
Меняет стиль шрифта денег
хотя бы написал на какой
C++:
enum eFontStyle
{
  FONT_GOTHIC = 0x0,
  FONT_SUBTITLES = 0x1,
  FONT_MENU = 0x2,
  FONT_PRICEDOWN = 0x3,
};

memory.setint32(0x866C94, 0x6437302524, true) -- Позитивные деньги стандартное значение
стандартное $%08d, а не $%07d. да и кто строку записывает как число?
Lua:
-- 1 вариант
local prot = memory.unprotect(0x866C94, 6)
-- ffi.copy(ffi.cast('char*', 0x866C94), '$%08d') -- default
ffi.copy(ffi.cast('char*', 0x866C94), '$%d') -- w/o zeroes
memory.protect(0x866C94, 6, prot)

-- 2 вариант
memory.copy(0x866C94, memory.strptr('$%d'), 6, true)
либо подменить адрес в CHud::DrawPlayerInfo

Меняет символ разделения патронов
почему бы не сразу поменять формат, как для денег?
Lua:
memory.copy(0x866BBC, memory.strptr('%d&%d'), 6, true)

Вместо 0x26 ставите HEX значение символа. Получить символ можете на этом сайте https://hackware.ru/?p=8604
...
Lua:
('&'):byte() -- или string.byte('&')
 

ARMOR

kjor32 is legend
Модератор
4,843
6,061
хотя бы написал на какой
C++:
enum eFontStyle
{
  FONT_GOTHIC = 0x0,
  FONT_SUBTITLES = 0x1,
  FONT_MENU = 0x2,
  FONT_PRICEDOWN = 0x3,
};
Специально указал 0-3 чтобы понимали что нужно вводить от 0 до 3
почему бы не сразу поменять формат, как для денег?
Lua:
memory.copy(0x866BBC, memory.strptr('%d&%d'), 6, true)
Не видел смысла кидать вариант смены полностью формата, ибо думаю никому не нужно будет менять сам формат.

К остальному не прикопаться, проебался)
 
  • Нравится
Реакции: leekyrave

why ega

РП игрок
Модератор
2,540
2,223
Описание: Хз, может уже есть такая функция, но сам искал что-то подобное. Функция кликает левой кнопкой мыши (ЛКМ) на указанных координатах.
Lua:
function ClickPos(x,y,delay)
    lua_thread.create(function()
        local ffi = require("ffi")
        ffi.cdef[[
        bool SetCursorPos(int X, int Y);
        ]]
        local ox, oy = getCursorPos()
        ffi.C.SetCursorPos(x, y)
        setVirtualKeyDown(0x01, true)
        wait(delay)
        setVirtualKeyDown(0x01, false)
        ffi.C.SetCursorPos(ox, oy)
    end)
end
Пример использования:
Lua:
local sizeX, sizeY = getScreenResolution()
ClickPos(sizeX - 100, sizeY - 400, 50) -- кликнет на координатах X: разрешение экрана - 100, Y: разрешение экрана - 400, с задержкой 50 миллисекунд.
 

MrBidloKoder

Известный
425
248
Описание: Визуально убирает/возвращает трейсера от пуль.

Lua:
function RemoveTracers(bool)
    if bool then
        memory.hex2bin("B800000000909090909090", 0x723DB8, 11)
    else
        memory.hex2bin("DB44241CD8C9E87DDD0F00", 0x723DB8, 11)
    end
end

Пример:

Lua:
function main()
    RemoveTracers(true) -- выключит трейсер при заходе в игру
end

спасибо Кустову как всегда
 
Последнее редактирование:
  • Нравится
Реакции: Savchik Blazer и leekyrave

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,763
11,198
Описание: TextColored по середине с двумя разными текстами
Lua:
function imgui.CenterColored(noncolored_text, colored_text, colored, noncolored)
    local colored = colored or imgui.ImVec4(1.00, 0.45, 0.72, 1.00) -- or your color
    local noncolored = noncolored or imgui.ImVec4(1.00, 1.00, 1.00, 1.00) -- or your color
    local width = imgui.GetWindowWidth()
    local noncolored_size = imgui.CalcTextSize(noncolored_text)
    local colored_size = imgui.CalcTextSize(colored_text)
  
    imgui.SetCursorPosX(width / 2 - noncolored_size.x / 2 - colored_size.x / 2)
    imgui.BeginGroup()
        imgui.TextColored(noncolored, noncolored_text)
        imgui.SameLine()
        imgui.TextColored(colored, colored_text)
    imgui.EndGroup()
end
Пример использования:
Lua:
imgui.CenterColored("NICK: ", "default.zone")
Посмотреть вложение 165455
это конечно тоже хуйня, но моя хуйня лучше чем твоя хуйня
1661679955455.png

Lua:
local listToDraw = {
    {'Hello'},
    {'World,', imgui.ImVec4(1, 0, 0.3, 1)},
    {'Ya -', imgui.ImVec4(0, 1, 0, 1)},
    {'dolbaeb', imgui.ImVec4(0, 0, 1, 1)},
}

function imgui.MultiText(list)
    for index, data in ipairs(list) do
        imgui.TextColored(data[2] or imgui.GetStyle().Colors[imgui.Col.Text], data[1])
        if index < #list then imgui.SameLine(0) end
    end
end
 
Последнее редактирование модератором:

ARMOR

kjor32 is legend
Модератор
4,843
6,061
Описание: Изменяет цвет radar_centre

Код:
Lua:
local memory = require 'memory'

memory.setuint8(0x588654, A, true)
memory.setuint8(0x588691, R, true)
memory.setuint8(0x58868C, G, true)
memory.setuint8(0x588687, B, true)

Скрин:
1661729511897.png
 

ARMOR

kjor32 is legend
Модератор
4,843
6,061
Описание: Меняет цвет фиста( Устанавливает цвет поверх фиста. Кароче, хуй знает как это назвать )

Код:
Lua:
memory.setint8(0x58D974, r, true)
memory.setint8(0x58D96F, g, true)
memory.setint8(0x58D96A, b, true)

--Для смены прозрачности меняйте через ffi
local fistAlpha = ffi.new('float[1]')

fistAlpha[0] = 100

ffi.cast('float**', 0x58F620)[0] = fistAlpha

Пример:
Lua:
memory.setint8(0x58D974, 0xFF, true)
memory.setint8(0x58D96F, 0, true)
memory.setint8(0x58D96A, 0, true)

Скриншот:
1661951113390.png


Описание: Меняет цвет иконок оружия( Устанавливает цвет поверх оружия.)

Код:
Lua:
memory.setint8(0x58D88B, A, true)
memory.setint8(0x58D8B0, R, true)
memory.setint8(0x58D8AB, G, true)
memory.setint8(0x58D8A0, B, true)

Пример:
Lua:
memory.setint8(0x58D88B, 0xE0, true)
memory.setint8(0x58D8B0, 0xFF, true)
memory.setint8(0x58D8AB, 0x80, true)
memory.setint8(0x58D8A0, 0x00, true)

Скриншот:
1661951894397.png
 
Последнее редактирование:

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,763
11,198
Описание: по очереди рисует .png картинки из определенной папки в imgui.Image (время каждого кадра указывается в функции UpdateFrame())
Результат:
Код:
Lua:
function imgui.LoadFrames(path) -- вызывать в imgui.OnInitialize
    local function getFilesInPath(path, ftype)
        local Files, SearchHandle, File = {}, findFirstFile(path.."\\"..ftype)
        table.insert(Files, File)
        while File do File = findNextFile(SearchHandle) table.insert(Files, File) end
        return Files
    end
    local Files = getFilesInPath(path, '*.png')
    local t = { Current = 1, Max = #Files, LastFrameTime = os.clock() }
    table.sort(Files, function(a, b)
        local aNum, bNum = tonumber(a:match('(%d+)%.png')), tonumber(b:match('(%d+)%.png'))
        return aNum < bNum
    end)
    for index, File in ipairs(Files) do
        t[index] = imgui.CreateTextureFromFile(path..'\\'..File)
    end
    return t
end

function imgui.DrawFrames(ImagesTable, size, FrameTime) -- вызывать в imgui.OnFrame
    if ImagesTable then
        imgui.Image(ImagesTable[ImagesTable.Current], size)
        if ImagesTable.LastFrameTime + ((FrameTime or 50)/1000) - os.clock() <= 0 then
            ImagesTable.LastFrameTime = os.clock()
            if ImagesTable.Current ~= nil then
                ImagesTable.Current = ImagesTable[ImagesTable.Current + 1] == nil and 1 or ImagesTable.Current + 1 -- тут хотел сделать через os.clock, но забил хуй
            else
                ImagesTable.Current = 1
            end
        end
    end
end
Пример использования:
Lua:
local imgui = require 'mimgui'
local Window = imgui.new.bool(true)
local FrameTime = imgui.new.int(50)
local FramesPath = getWorkingDirectory()..'\\resource\\AnimatedBober'
local MyGif = nil
imgui.OnInitialize(function()
    MyGif = imgui.LoadFrames(FramesPath)
end)

local Draw = imgui.OnFrame(
    function() return Window[0] end,
    function(self)
        local resX, resY = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(300, 330), imgui.Cond.FirstUseEver)
        if imgui.Begin('GifPlayer', Window) then
            imgui.SliderInt('Frame Time', FrameTime, 1, 200)
            local Size = imgui.GetWindowSize()
            imgui.DrawFrames(MyGif, imgui.ImVec2(Size.x - 10, Size.y - 60), FrameTime[0])
            imgui.End()
        end
    end
)

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('gifexample', function()
        Window[0] = not Window[0]
    end)
    wait(-1)
end

function imgui.LoadFrames(path)
    local function getFilesInPath(path, ftype)
        local Files, SearchHandle, File = {}, findFirstFile(path.."\\"..ftype)
        table.insert(Files, File)
        while File do File = findNextFile(SearchHandle) table.insert(Files, File) end
        return Files
    end
    local Files = getFilesInPath(path, '*.png')
    local t = { Current = 1, Max = #Files, LastFrameTime = os.clock() }
    table.sort(Files, function(a, b)
        local aNum, bNum = tonumber(a:match('(%d+)%.png')), tonumber(b:match('(%d+)%.png'))
        return aNum < bNum
    end)
    for index, File in ipairs(Files) do
        t[index] = imgui.CreateTextureFromFile(path..'\\'..File)
    end
    return t
end

function imgui.DrawFrames(ImagesTable, size, FrameTime)
    if ImagesTable then
        imgui.Image(ImagesTable[ImagesTable.Current], size)
        if ImagesTable.LastFrameTime + ((FrameTime or 50)/1000) - os.clock() <= 0 then
            ImagesTable.LastFrameTime = os.clock()
            if ImagesTable.Current ~= nil then
                ImagesTable.Current = ImagesTable[ImagesTable.Current + 1] == nil and 1 or ImagesTable.Current + 1 -- тут хотел сделать через os.clock, но забил хуй
            else
                ImagesTable.Current = 1
            end
        end
    end
end
Файлы должны называться 1.png, 2.png, 3.png и тд
для конвертации гифки в кадры можете юзать этот сайт: https://www.cleverpdf.com/ru/gif-to-png
 
Последнее редактирование: