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

UBP

Известный
329
168
1710358780869.png


Lua:
local slider_value = 0.5
slider_value = customSliderFloat("My Slider", slider_value, 0.0, 1.0, "%.3f")
Lua:
function customSliderFloat(label, value, min, max, format)
    local style = imgui.GetStyle()
    local draw_list = imgui.GetWindowDrawList()
    local cursor_pos = imgui.GetCursorScreenPos()
    local text_size = imgui.CalcTextSize(label)
    local value_text = string.format(format, value)
    local value_text_size = imgui.CalcTextSize(value_text)
    local slider_size = imgui.ImVec2(200, 8) -- размер слайдера
    local total_width = text_size.x + style.ItemInnerSpacing.x + slider_size.x + style.ItemInnerSpacing.x + value_text_size.x
    local padding = 10 -- Увеличиваемое расстояние от текста до слайдера
    local slider_pos = imgui.ImVec2(cursor_pos.x + text_size.x + style.ItemInnerSpacing.x + padding, cursor_pos.y)
    local slider_end_pos = imgui.ImVec2(slider_pos.x + slider_size.x, slider_pos.y + slider_size.y)

    -- Рассчитываем положение ползунка на основе текущего значения
    local fraction = (value - min) / (max - min)
    local handle_pos = slider_pos.x + fraction * slider_size.x

    -- Цвета
    local color_background = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.2, 0.2, 0.2, 1.0)) -- фон слайдера
    local color_filled = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.2, 0.4, 0.8, 1.0)) -- заполненная часть слайдера
    local color_slider = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.4, 0.4, 0.4, 1.0)) -- ползунок слайдера

    -- Рисуем фон слайдера
    draw_list:AddRectFilled(slider_pos, slider_end_pos, color_background, style.FrameRounding)

    -- Рисуем заполненную часть слайдера
    local filled_rect_end_pos = imgui.ImVec2(handle_pos, slider_end_pos.y)
    draw_list:AddRectFilled(slider_pos, filled_rect_end_pos, color_filled, style.FrameRounding)

    -- Рисуем ползунок
    local handle_size = imgui.ImVec2(10, slider_size.y)
    local handle_rect_min = imgui.ImVec2(handle_pos - handle_size.x * 0.5, slider_pos.y)
    local handle_rect_max = imgui.ImVec2(handle_pos + handle_size.x * 0.5, slider_end_pos.y)
    draw_list:AddRectFilled(handle_rect_min, handle_rect_max, color_slider, style.FrameRounding)

    -- Обработка ввода
    local is_active = false
    local is_hovered = imgui.IsMouseHoveringRect(handle_rect_min, handle_rect_max)
    if is_hovered and imgui.IsMouseDown(0) then
        local mouse_x = imgui.GetIO().MousePos.x
        local new_fraction = (mouse_x - slider_pos.x) / slider_size.x
        value = min + new_fraction * (max - min)
        value = math.max(min, math.min(max, value)) -- ограничиваем значение
        is_active = true
    end

    -- Отображаем метку слайдера
    imgui.PushFont(Font[15]) -- Предполагается, что Font[18] - это ваш крупный шрифт
    imgui.SetCursorScreenPos(imgui.ImVec2(cursor_pos.x, cursor_pos.y + (slider_size.y - text_size.y) * 0.7))
    imgui.Text(label)
    imgui.PopFont()

    -- Отображаем значение слайдера справа от слайдера
    imgui.PushStyleColor(imgui.Col.Text, style.Colors[imgui.Col.TextDisabled])
    imgui.SetCursorScreenPos(imgui.ImVec2(slider_end_pos.x + style.ItemInnerSpacing.x, cursor_pos.y + (slider_size.y - value_text_size.y) * 0.5))
    imgui.Text(value_text)
    imgui.PopStyleColor()

    -- Возвращаем измененное значение
    return value
end
 
Последнее редактирование:

ARMOR

kjor32 is legend
Модератор
4,851
6,080
Описание: Возвращает PaketLoss

Lua:
local memory = require("memory")

function getPacketLoss()
    local pRakClient = sampGetRakclientInterface()
    local pRakClientStatistic = callMethod(sampGetRakclientFuncAddressByIndex(51), sampGetRakclientInterface(), 1, 0, pRakClient)
    local nStatValue1 = memory.getuint32(pRakClientStatistic + 0x94, true)
    local nStatValue2 = memory.getuint32(pRakClientStatistic + 0xB8, true)
    return nStatValue1 * 100.0 / nStatValue2
end
 

UBP

Известный
329
168
Grand Theft Auto  San Andreas 2024.03.14 - 08.43.14.01.gif

Рисует вертикальное меню


Lua:
local Tab = 1
local menu_items = {u8'Главная', u8'Дрифт', u8'Настройки'}
Tab = customVerticalMenu(menu_items, Tab)


Lua:
function customVerticalMenu(items, current)
    imgui.PushFont(Font[20]) -- Установка шрифта для пунктов меню

    local button_padding = 8 -- Отступ между кнопками
    local button_height = 35 -- Высота кнопки
    local button_width = 250 -- Ширина кнопки
    local corner_radius = 5 -- Радиус закругления углов

    for i, item in ipairs(items) do
        local is_selected = (current == i)
       
        -- Определение цветов для различных состояний пункта меню
        local color_normal = imgui.ImVec4(0.15, 0.15, 0.15, 0.0) -- Прозрачный фон
        local color_hovered = imgui.ImVec4(0.25, 0.25, 0.25, 0.5) -- Полупрозрачный фон при наведении
        local color_active = imgui.ImVec4(0.35, 0.35, 0.35, 0.5) -- Полупрозрачный фон при активации
        local color_text = imgui.ImVec4(0.75, 0.75, 0.75, 0.7)
        local color_text_selected = imgui.ImVec4(1.00, 1.00, 1.00, 1.0)

        -- Установка стилей для пункта меню
        imgui.PushStyleColor(imgui.Col.Text, is_selected and color_text_selected or color_text)
        imgui.PushStyleColor(imgui.Col.Button, color_normal)
        imgui.PushStyleColor(imgui.Col.ButtonHovered, color_hovered)
        imgui.PushStyleColor(imgui.Col.ButtonActive, color_active)
        imgui.PushStyleVarFloat(imgui.StyleVar.FrameRounding, corner_radius)
        imgui.PushStyleVarVec2(imgui.StyleVar.ItemSpacing, imgui.ImVec2(0, button_padding))

        -- Отрисовка пункта меню
        if imgui.Button(item, imgui.ImVec2(button_width, button_height)) then
            current = i
            setAudioStreamVolume(space, 1)
            setAudioStreamState(space, as_action.PLAY)
        end

        -- Анимация подсветки при наведении
        if imgui.IsItemHovered() then
            local draw_list = imgui.GetWindowDrawList()
            local min = imgui.GetItemRectMin()
            local max = imgui.GetItemRectMax()
            draw_list:AddRectFilled(min, max, imgui.ColorConvertFloat4ToU32(is_selected and color_active or color_hovered), corner_radius)
        end

        imgui.PopStyleColor(4) -- Возврат стилей к исходным значениям
        imgui.PopStyleVar(2) -- Возврат переменных стиля к исходным значениям
    end

    imgui.PopFont() -- Возврат шрифта к исходному
    return current
end
 
Последнее редактирование:

Use[R]

Известный
1,267
396
Посмотреть вложение 234460

Lua:
local slider_value = 0.5
slider_value = customSliderFloat("My Slider", slider_value, 0.0, 1.0, "%.3f")
Lua:
function customSliderFloat(label, value, min, max, format)
    local style = imgui.GetStyle()
    local draw_list = imgui.GetWindowDrawList()
    local cursor_pos = imgui.GetCursorScreenPos()
    local text_size = imgui.CalcTextSize(label)
    local value_text = string.format(format, value)
    local value_text_size = imgui.CalcTextSize(value_text)
    local slider_size = imgui.ImVec2(200, 8) -- размер слайдера
    local total_width = text_size.x + style.ItemInnerSpacing.x + slider_size.x + style.ItemInnerSpacing.x + value_text_size.x
    local padding = 10 -- Увеличиваемое расстояние от текста до слайдера
    local slider_pos = imgui.ImVec2(cursor_pos.x + text_size.x + style.ItemInnerSpacing.x + padding, cursor_pos.y)
    local slider_end_pos = imgui.ImVec2(slider_pos.x + slider_size.x, slider_pos.y + slider_size.y)

    -- Рассчитываем положение ползунка на основе текущего значения
    local fraction = (value - min) / (max - min)
    local handle_pos = slider_pos.x + fraction * slider_size.x

    -- Цвета
    local color_background = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.2, 0.2, 0.2, 1.0)) -- фон слайдера
    local color_filled = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.2, 0.4, 0.8, 1.0)) -- заполненная часть слайдера
    local color_slider = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.4, 0.4, 0.4, 1.0)) -- ползунок слайдера

    -- Рисуем фон слайдера
    draw_list:AddRectFilled(slider_pos, slider_end_pos, color_background, style.FrameRounding)

    -- Рисуем заполненную часть слайдера
    local filled_rect_end_pos = imgui.ImVec2(handle_pos, slider_end_pos.y)
    draw_list:AddRectFilled(slider_pos, filled_rect_end_pos, color_filled, style.FrameRounding)

    -- Рисуем ползунок
    local handle_size = imgui.ImVec2(10, slider_size.y)
    local handle_rect_min = imgui.ImVec2(handle_pos - handle_size.x * 0.5, slider_pos.y)
    local handle_rect_max = imgui.ImVec2(handle_pos + handle_size.x * 0.5, slider_end_pos.y)
    draw_list:AddRectFilled(handle_rect_min, handle_rect_max, color_slider, style.FrameRounding)

    -- Обработка ввода
    local is_active = false
    local is_hovered = imgui.IsMouseHoveringRect(handle_rect_min, handle_rect_max)
    if is_hovered and imgui.IsMouseDown(0) then
        local mouse_x = imgui.GetIO().MousePos.x
        local new_fraction = (mouse_x - slider_pos.x) / slider_size.x
        value = min + new_fraction * (max - min)
        value = math.max(min, math.min(max, value)) -- ограничиваем значение
        is_active = true
    end

    -- Отображаем метку слайдера
    imgui.PushFont(Font[15]) -- Предполагается, что Font[18] - это ваш крупный шрифт
    imgui.SetCursorScreenPos(imgui.ImVec2(cursor_pos.x, cursor_pos.y + (slider_size.y - text_size.y) * 0.7))
    imgui.Text(label)
    imgui.PopFont()

    -- Отображаем значение слайдера справа от слайдера
    imgui.PushStyleColor(imgui.Col.Text, style.Colors[imgui.Col.TextDisabled])
    imgui.SetCursorScreenPos(imgui.ImVec2(slider_end_pos.x + style.ItemInnerSpacing.x, cursor_pos.y + (slider_size.y - value_text_size.y) * 0.5))
    imgui.Text(value_text)
    imgui.PopStyleColor()

    -- Возвращаем измененное значение
    return value
end
Если курсор убрать с ползунка, то значение не меняется
 

UBP

Известный
329
168
1710447049017.png

CustomArrowCombo
Lua:
local selectedIndices = {
    MaxAngleSteering = 1,
}
-- Списки опций для каждой настройки
local options = {
    MaxAngleSteering = {'Off', '35', '45', '50', '60', '70', '90'},
}
--v imgui
local optionsWidth = 100
customArrowCombo(u8'Максимальный выворот колёс', 'MaxAngleSteering', optionsWidth)
Lua:
function applySetting(key)
    local value = options[key][selectedIndices[key]]
    if key == 'MaxAngleSteering' then
        if value == 'Off' then
        elseif value == '35' then
        --code
        elseif value == '45' then
        --code
        end
    end
end


Lua:
-- Функция для отображения кнопок влево и вправо для выбора опций
function customArrowCombo(label, key, optionsWidth)
    imgui.AlignTextToFramePadding()
    imgui.PushFont(Font[16]) imgui.Text(label) imgui.PopFont()
    imgui.SameLine()

    -- Устанавливаем курсор дальше от текста
    local windowWidth = imgui.GetWindowWidth()
    imgui.SetCursorPosX(windowWidth - optionsWidth)

    -- Кнопка влево
    imgui.PushFont(Font[16])
    imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(0.06, 0.07, 0.08, 0))
    imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(0.38, 0.54, 0.86, 1.00))
    imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(0.26, 0.27, 0.28,1))
    if imgui.ArrowButton("##left_" .. key, imgui.Dir.Left) then
        selectedIndices[key] = math.max(1, selectedIndices[key] - 1)
        applySetting(key) -- Применяем настройку после изменения
    end
    imgui.SameLine()
    -- Если выбрана опция 'Off', делаем текст серым
    if options[key][selectedIndices[key]] == 'Off' then
        imgui.PushStyleColor(imgui.Col.Text, imgui.GetStyle().Colors[imgui.Col.TextDisabled])
    end
    -- Текущее выбранное значение
    imgui.AlignTextToFramePadding()
    imgui.Text(options[key][selectedIndices[key]])
    -- Возвращаем цвет текста обратно, если он был изменен
    if options[key][selectedIndices[key]] == 'Off' then
        imgui.PopStyleColor()
    end

    imgui.SameLine()

    -- Кнопка вправо
    if imgui.ArrowButton("##right_" .. key, imgui.Dir.Right) then
        selectedIndices[key] = math.min(#options[key], selectedIndices[key] + 1)
        applySetting(key) -- Применяем настройку после изменения
    end
    imgui.PopStyleColor(0)
    imgui.PopFont()
end
 

Use[R]

Известный
1,267
396
Посмотреть вложение 234533
CustomArrowCombo
Lua:
local selectedIndices = {
    MaxAngleSteering = 1,
}
-- Списки опций для каждой настройки
local options = {
    MaxAngleSteering = {'Off', '35', '45', '50', '60', '70', '90'},
}
--v imgui
local optionsWidth = 100
customArrowCombo(u8'Максимальный выворот колёс', 'MaxAngleSteering', optionsWidth)
Lua:
function applySetting(key)
    local value = options[key][selectedIndices[key]]
    if key == 'MaxAngleSteering' then
        if value == 'Off' then
        elseif value == '35' then
        --code
        elseif value == '45' then
        --code
        end
    end
end


Lua:
-- Функция для отображения кнопок влево и вправо для выбора опций
function customArrowCombo(label, key, optionsWidth)
    imgui.AlignTextToFramePadding()
    imgui.PushFont(Font[16]) imgui.Text(label) imgui.PopFont()
    imgui.SameLine()

    -- Устанавливаем курсор дальше от текста
    local windowWidth = imgui.GetWindowWidth()
    imgui.SetCursorPosX(windowWidth - optionsWidth)

    -- Кнопка влево
    imgui.PushFont(Font[16])
    imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(0.06, 0.07, 0.08, 0))
    imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(0.38, 0.54, 0.86, 1.00))
    imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(0.26, 0.27, 0.28,1))
    if imgui.ArrowButton("##left_" .. key, imgui.Dir.Left) then
        selectedIndices[key] = math.max(1, selectedIndices[key] - 1)
        applySetting(key) -- Применяем настройку после изменения
    end
    imgui.SameLine()
    -- Если выбрана опция 'Off', делаем текст серым
    if options[key][selectedIndices[key]] == 'Off' then
        imgui.PushStyleColor(imgui.Col.Text, imgui.GetStyle().Colors[imgui.Col.TextDisabled])
    end
    -- Текущее выбранное значение
    imgui.AlignTextToFramePadding()
    imgui.Text(options[key][selectedIndices[key]])
    -- Возвращаем цвет текста обратно, если он был изменен
    if options[key][selectedIndices[key]] == 'Off' then
        imgui.PopStyleColor()
    end

    imgui.SameLine()

    -- Кнопка вправо
    if imgui.ArrowButton("##right_" .. key, imgui.Dir.Right) then
        selectedIndices[key] = math.min(#options[key], selectedIndices[key] + 1)
        applySetting(key) -- Применяем настройку после изменения
    end
    imgui.PopStyleColor(0)
    imgui.PopFont()
end
Это mimgui?
 
  • Злость
Реакции: qdIbp

UBP

Известный
329
168
0315(1).gif


Lua:
local show_loading = false
local loading_animation_angle = 0
--v imgui
renderButtonWithLoadingAnimation(u8"Активировать", 50, 50, 10, 25)


Lua:
function renderButtonWithLoadingAnimation(button_label, button_width, button_height, animation_radius, segments)
    local button_size = imgui.ImVec2(button_width+(animation_radius*5), button_height)

    if not show_loading then
        -- Стилизация кнопки
        imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(0.10, 0.10, 0.10, 1)) -- Цвет кнопки
        imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(0.1, 0.1, 1, 1)) -- pri navedenie
        imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(0.2, 0.2, 1, 1)) -- pri нажатии

        -- Создание кнопки с настраиваемым размером
        if imgui.Button(button_label, button_size) then
            show_loading = true
        end

        -- Восстановление стандартных цветов
        imgui.PopStyleColor(3)
    end


    -- Если кнопка нажата, показываем анимацию загрузки
    if show_loading then
        local cursor_pos = imgui.GetCursorScreenPos()
        local draw_list = imgui.GetWindowDrawList()
        local num_segments = segments
        local start_angle = math.fmod(loading_animation_angle, 2 * math.pi)
        -- Рассчитываем центр анимации внутри кнопки справа
        local center = imgui.ImVec2(cursor_pos.x + button_size.x / 2, cursor_pos.y + button_height / 2)

        -- Рисуем анимацию загрузки внутри кнопки справа
        for i = 0, num_segments - 1 do
            local angle = start_angle + ((2 * math.pi) / num_segments) * i
            local x = center.x + math.cos(angle) * animation_radius
            local y = center.y + math.sin(angle) * animation_radius
            local alpha = (i / num_segments) * 255
            local color = imgui.ImVec4(1, 1, 1, alpha / 255) -- Используем белый цвет для анимации
            draw_list:AddCircleFilled(imgui.ImVec2(x, y), animation_radius * 0.3, imgui.ColorConvertFloat4ToU32(color))
        end

        -- Обновляем угол для анимации
        loading_animation_angle = loading_animation_angle + 0.05
        if loading_animation_angle > (2 * math.pi) then
            loading_animation_angle = loading_animation_angle - (2 * math.pi)
        end
    end
end



Lua:
local loading_animation_angle = 0
local center = imgui.ImVec2(x, y) -- координаты центра, где должна отображаться анимация
renderLoadingAnimation(center, radius, segments)


Lua:
function renderLoadingAnimation(center, radius, segments)
    local draw_list = imgui.GetWindowDrawList()
    local start_angle = math.fmod(loading_animation_angle, 2 * math.pi)

    -- Рисуем анимацию загрузки
    for i = 0, segments - 1 do
        local angle = start_angle + ((2 * math.pi) / segments) * i
        local x = center.x + math.cos(angle) * radius
        local y = center.y + math.sin(angle) * radius
        local alpha = (i / segments) * 255
        local color = imgui.ImVec4(1, 1, 1, alpha / 255) -- Используем белый цвет для анимации
        draw_list:AddCircleFilled(imgui.ImVec2(x, y), radius * 0.3, imgui.GetColorU32(color))
    end

    -- Обновляем угол для анимации
    loading_animation_angle = loading_animation_angle + 0.05
    if loading_animation_angle > (2 * math.pi) then
        loading_animation_angle = loading_animation_angle - (2 * math.pi)
    end
end

0315(2).gif

Lua:
-- Переменные для анимации
local loading_percentage = 0 -- Начальный процент загрузки
local loading_speed = 5 -- Скорость загрузки (проценты в секунду)

-- В рендер имгуи
local delta_time = 1 / 60 -- Вместо 60 - частота обновления экрана
updateLoadingAnimation(delta_time)
imgui.SetCursorPosX(80) -- Смещение вправо для читабельности текста(da da)
renderLoadingAnimation(10)
--


Lua:
function updateLoadingAnimation(delta_time)
    -- Обновляем процент загрузки
    loading_percentage = loading_percentage + loading_speed * delta_time
    if loading_percentage > 100 then
        loading_percentage = 100 -- Ограничиваем максимальное значение 100%
    end
end

function renderLoadingAnimation(line_thickness, cursor_pos)
    cursor_pos = cursor_pos or imgui.GetCursorScreenPos()
    local draw_list = imgui.GetWindowDrawList()
    imgui.PushFont(Font[25]) -- Используйте шрифт соответствующего размера
    local text = string.format("Loading   %d%%", math.floor(loading_percentage))

    -- Расчет позиции текста
    local text_size = imgui.CalcTextSize(text)
    local text_pos = imgui.ImVec2(
        cursor_pos.x - text_size.x / 2,
        cursor_pos.y - text_size.y / 2 - line_thickness - 6 -- Смещаем текст вверх от линии
    )

    -- Цвета
    local text_color = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.9, 0.9, 0.9, 1)) -- Светло-серый цвет текста
    local line_color_background = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.2, 0.2, 0.2, 1)) -- Темно-серый цвет фона линии
    local line_color_active = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(0.26, 0.59, 0.98, 1)) -- Синий цвет активной части линии

    -- Отрисовка текста "Loading"
    draw_list:AddText(text_pos, text_color, text)

    -- Отрисовка фона линии
    local line_start = imgui.ImVec2(cursor_pos.x - text_size.x / 2, cursor_pos.y + 4)
    local line_end = imgui.ImVec2(cursor_pos.x + text_size.x / 2, cursor_pos.y + 4 + line_thickness)
    draw_list:AddRectFilled(line_start, line_end, line_color_background, 4.0) -- Закругление углов

    -- Отрисовка активной части линии (от 0% до loading_percentage)
    local line_end_active = imgui.ImVec2(line_start.x + text_size.x * (loading_percentage / 100), cursor_pos.y + 4 + line_thickness)
    draw_list:AddRectFilled(line_start, line_end_active, line_color_active, 4.0) -- Закругление углов

    imgui.PopFont()
end

- Максимально простая реализация(уебанская)


0315(3).gif


Lua:
-- Таблица для хранения состояния перемещения для каждого элемента
local draggableStates = {}


local key = "unique_element_key" - уникальный ид элемента
--В рендере имгуи
if draggableStates[key] then imgui.SetCursorPos(draggableStates[key].position) end - перед рендером обьекта, который хотим передвигать
if imgui.Button("Draggable Button inside") then
-- Обработка нажатия кнопки
end
MakeElementDraggable(key) - вызов функции сразу после элемента
Lua:
function MakeElementDraggable(key)
    local ImGui = imgui
    local io = ImGui.GetIO()
    local mousePos = ImGui.GetMousePos()

    -- Если состояние для элемента ещё не создано, инициализируем его
    if not draggableStates[key] then
        draggableStates[key] = {
            isDragging = false,
            dragStartX = 0,
            dragStartY = 0,
            dragOffsetX = 0,
            dragOffsetY = 0,
            position = ImGui.GetCursorScreenPos() -- Используем начальную позицию курсора
        }
    end

    local state = draggableStates[key]
    local position = state.position

    -- Получаем текущие координаты элемента
    local itemMin = ImGui.GetItemRectMin()
    local itemMax = ImGui.GetItemRectMax()
    local size = { x = itemMax.x - itemMin.x, y = itemMax.y - itemMin.y }

    -- Проверяем, находится ли курсор мыши в пределах элемента
    if mousePos.x >= itemMin.x and mousePos.x <= itemMax.x and
       mousePos.y >= itemMin.y and mousePos.y <= itemMax.y then
        -- Проверяем, нажата ли левая кнопка мыши
        if ImGui.IsMouseDown(0) then
            if not state.isDragging then
                -- Начинаем перемещение
                state.isDragging = true
                state.dragStartX = mousePos.x
                state.dragStartY = mousePos.y
                state.dragOffsetX = mousePos.x - position.x
                state.dragOffsetY = mousePos.y - position.y
            end
        end
    end

    if state.isDragging then
        -- Обновляем позицию элемента
        position.x = mousePos.x - state.dragOffsetX
        position.y = mousePos.y - state.dragOffsetY
        state.position = position -- Сохраняем новую позицию
    end

    -- Если кнопка мыши отпущена, останавливаем перемещение
    if state.isDragging and not ImGui.IsMouseDown(0) then
        state.isDragging = false
    end

    -- Возвращаем новую позицию элемента
    return position
end


0315(3).gif



Lua:
customBeginChild("##dynamicOutlineChild", imgui.ImVec2(300, 300), 2, 20, 10)
imgui.EndChild()
Lua:
function customBeginChild(id, size, border, padding, rounding)
    local ImGui = imgui
    local ImVec4 = imgui.ImVec4

    -- Получаем текущее время для анимации
    local time = os.clock()

    -- Вычисляем цвета для эффекта радуги
    local r, g, b, a = rainbow(0.5, 1, time)
    local borderColor = ImVec4(r / 255, g / 255, b / 255, a)

    -- Устанавливаем стиль границы и отступы
    ImGui.PushStyleVarVec2(ImGui.StyleVar.WindowPadding, imgui.ImVec2(padding, padding))
    ImGui.PushStyleVarFloat(ImGui.StyleVar.ChildBorderSize, border)
    ImGui.PushStyleColor(ImGui.Col.Border, borderColor)
    ImGui.PushStyleVarFloat(ImGui.StyleVar.ChildRounding, rounding)

    -- Создаем Child Window
    local result = ImGui.BeginChild(id, size, true)

    -- Возвращаем стили к исходным значениям после создания Child Window
    ImGui.PopStyleVar(2)
    ImGui.PopStyleColor(1)
    
    return result
end
function join_argb(a, r, g, b)
    local argb = b
    argb = bit.bor(argb, bit.lshift(g, 8))
    argb = bit.bor(argb, bit.lshift(r, 16))
    argb = bit.bor(argb, bit.lshift(a, 24))
    return argb
end

function rainbow(speed, alpha, offset) -- by rraggerr
    local clock = os.clock() + offset
    local r = math.floor(math.sin(clock * speed) * 127 + 128)
    local g = math.floor(math.sin(clock * speed + 2) * 127 + 128)
    local b = math.floor(math.sin(clock * speed + 4) * 127 + 128)
    return r,g,b,alpha
end
--очень простой пример
1710531688915.png




Lua:
local notifications = {} -- вне imgui.begin

addNotification("Уведомление справа с радужной рамкой", 300, "right", true) -- добавить уведомление
addNotification("Уведомление слева без радужной рамки", 300, "left", false)

drawNotifications() -- перед imgui.End() или в любое другое место кроме функций


Lua:
function addNotification(text, duration, position, hasRainbowBorder)
    table.insert(notifications, {
        text = text,
        duration = duration,
        alpha = 0,
        state = "appearing",
        position = position or "right", -- "right" или "left"
        hasRainbowBorder = hasRainbowBorder or false
    })
end -- функция добавления уведомления

function drawNotifications()
    local ImGui = imgui
    local ImVec2 = imgui.ImVec2
    local ImVec4 = imgui.ImVec4
    local screenW, screenH = getScreenResolution()
    local startY = screenH * 0.3 -- Начальная позиция уведомлений на экране
    local spacing = 15 -- Расстояние между уведомлениями

    for i, notification in ipairs(notifications) do
        if notification.state == "appearing" then
            notification.alpha = notification.alpha + 0.02 -- Плавное увеличение альфа
            if notification.alpha >= 1 then
                notification.alpha = 1
                notification.state = "displaying"
            end
        elseif notification.state == "displaying" then
            notification.duration = notification.duration - 1
            if notification.duration <= 0 then
                notification.state = "disappearing"
            end
        elseif notification.state == "disappearing" then
            notification.alpha = notification.alpha - 0.02 -- Плавное уменьшение альфа
            if notification.alpha <= 0 then
                table.remove(notifications, i)
            end
        end

        local windowPosX = notification.position == "right" and (screenW - 300) or 0
        ImGui.SetNextWindowPos(ImVec2(windowPosX, startY + (i-1) * (50 + spacing)), ImGui.Cond.Always)
        ImGui.SetNextWindowSize(ImVec2(280, 50), ImGui.Cond.Always)
        ImGui.PushStyleVarFloat(ImGui.StyleVar.Alpha, notification.alpha)

        if ImGui.Begin("Notification" .. i, _, ImGui.WindowFlags.NoTitleBar + ImGui.WindowFlags.NoResize + ImGui.WindowFlags.NoMove + ImGui.WindowFlags.NoScrollbar) then
            ImGui.Text(notification.text)
            local drawList = ImGui.GetWindowDrawList()
            local windowPos = ImGui.GetWindowPos()
            local windowSize = ImGui.GetWindowSize()
            if notification.hasRainbowBorder then
                local time = os.clock()
                local r, g, b, a = rainbow(0.5, 1, time)
                drawList:AddRect(windowPos, ImVec2(windowPos.x + windowSize.x, windowPos.y + windowSize.y), ImGui.ColorConvertFloat4ToU32(ImVec4(r / 255, g / 255, b / 255, notification.alpha)), 0.0, 0, 1.5)
            else
                drawList:AddRect(windowPos, ImVec2(windowPos.x + windowSize.x, windowPos.y + windowSize.y), ImGui.ColorConvertFloat4ToU32(ImVec4(1, 1, 1, notification.alpha)), 0.0, 0, 1.5)
            end
        end
        ImGui.End()
        ImGui.PopStyleVar()
    end
end

function rainbow(speed, alpha, offset) -- by rraggerr
    local clock = os.clock() + offset
    local r = math.floor(math.sin(clock * speed) * 127 + 128)
    local g = math.floor(math.sin(clock * speed + 2) * 127 + 128)
    local b = math.floor(math.sin(clock * speed + 4) * 127 + 128)
    return r,g,b,alpha
end
 
Последнее редактирование:

UBP

Известный
329
168
1710704074140.png


Lua:
drawModernSlider("Прозрачность", sliderValue, 0.0, 1.0, 0.01, 200, 8, window_center)

Lua:
function drawModernSlider(label, value, min, max, step, slider_length, slider_height, slider_pos)
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()
    local cursor_pos = ImGui.GetCursorScreenPos()
    local slider_length = slider_length or 200 -- длина слайдера
    local slider_height = slider_height or 8 -- высота слайдера
    local knob_radius = 10 -- радиус ручки слайдера
    local value_normalized = (value[0] - min) / (max - min) -- нормализованное значение для расчета позиции ручки

    -- Рассчитываем позицию текста
    local text_pos = ImGui.ImVec2(slider_pos.x, slider_pos.y - 20) -- Позиция текста над слайдером

    -- Рисуем текст слайдера
    ImGui.SetCursorScreenPos(text_pos)
    ImGui.Text(label .. ": " .. string.format("%.2f", value[0]))

    -- Рисуем фон слайдера
    draw_list:AddRectFilled(ImGui.ImVec2(slider_pos.x, slider_pos.y), ImGui.ImVec2(slider_pos.x + slider_length, slider_pos.y + slider_height), ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.5, 0.5, 0.5, 0.5)), slider_height / 2)

    -- Рисуем заполненную часть слайдера
    draw_list:AddRectFilled(ImGui.ImVec2(slider_pos.x, slider_pos.y), ImGui.ImVec2(slider_pos.x + slider_length * value_normalized, slider_pos.y + slider_height), ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.26, 0.59, 0.98, 0.8)), slider_height / 2)

    -- Рисуем ручку слайдера
    local knob_pos = ImGui.ImVec2(slider_pos.x + slider_length * value_normalized, slider_pos.y + slider_height / 2)
    draw_list:AddCircleFilled(knob_pos, knob_radius, ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(1, 1, 1, 1)), 16)

    -- Реализация взаимодействия с ручкой слайдера
    local is_hovered = ImGui.IsMouseHoveringRect(ImGui.ImVec2(knob_pos.x - knob_radius, knob_pos.y - knob_radius), ImGui.ImVec2(knob_pos.x + knob_radius, knob_pos.y + knob_radius))
    local mouse_delta = ImGui.GetIO().MouseDelta
    if is_hovered and ImGui.IsMouseDown(0) then
        value[0] = value[0] + mouse_delta.x * (max - min) / slider_length
        if value[0] < min then value[0] = min end
        if value[0] > max then value[0] = max end
    end

    -- Сдвигаем курсор после рисования слайдера
    ImGui.SetCursorScreenPos(ImGui.ImVec2(cursor_pos.x, slider_pos.y + slider_height + 20))
end
1710704406737.png


Lua:
drawLoadingIndicator(window_center.x, window_center.y, 40, 8, {0.4, 0.6, 0.9, 1})
Lua:
function drawLoadingIndicator(x, y, radius, dotsCount, color)
    local draw_list = imgui.GetWindowDrawList()
    local centre = imgui.ImVec2(x, y)
    local time = os.clock()

    for i = 1, dotsCount do
        local angle = (time * 2 + i / dotsCount * 2 * math.pi) % (2 * math.pi)
        local dotRadius = radius * 0.1
        local dotX = centre.x + radius * math.cos(angle)
        local dotY = centre.y + radius * math.sin(angle)
        local alpha = (math.sin(time * 10 + i) + 1) / 2 -- Анимация прозрачности
        local dotColor = imgui.ColorConvertFloat4ToU32(imgui.ImVec4(color[1], color[2], color[3], alpha))

        draw_list:AddCircleFilled(imgui.ImVec2(dotX, dotY), dotRadius, dotColor)
    end
end



1710704774479.png


Lua:
drawRotatingGradientCircle(window_center.x, window_center.y, 50, 6)

Lua:
function drawRotatingGradientCircle(x, y, radius, segments)
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()
    local time = os.clock() * 0.5 -- Уменьшаем скорость вращения
    local full_circle = math.pi * 2
    local segment_angle = full_circle / segments

    for i = 0, segments - 1 do
        local start_angle = (i * segment_angle) + time
        local end_angle = start_angle + segment_angle
        -- Генерируем цвет на основе угла
        local r = math.abs(math.sin(start_angle)) -- Красный канал изменяется по синусу
        local g = math.abs(math.sin(start_angle + full_circle / 3)) -- Зеленый сдвигается на треть круга
        local b = math.abs(math.sin(start_angle + full_circle * 2 / 3)) -- Синий сдвигается на две трети
        local color = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(r, g, b, 1))

        draw_list:PathArcTo(ImGui.ImVec2(x, y), radius, start_angle, end_angle, 10)
        draw_list:PathStroke(color, false, 2.0)
    end
end


1710704973883.png



Lua:
 -- в рендер в начало или перед imgui.End()
drawNotifications()
-- Другой код интерфейса

-- вызываем после нажатия кнопки например
addNotification("Привет, это тестовое уведомление!", 5) -- текст и продолжительность в секундах
Lua:
local notifications = {}

function addNotification(text, duration)
    table.insert(notifications, {
        text = text,
        duration = duration,
        alpha = 0, -- начальная прозрачность
        state = "appearing" -- начальное состояние
    })
end

function drawNotifications()
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()
    local screen_width, screen_height = getScreenResolution()
    local notification_height = 30
    local notification_margin = 10
    local animation_speed = 0.02

    for i, notification in ipairs(notifications) do
        if notification.state == "appearing" then
            notification.alpha = notification.alpha + animation_speed
            if notification.alpha >= 1 then
                notification.alpha = 1
                notification.state = "displaying"
                notification.display_start = os.clock()
            end
        elseif notification.state == "displaying" then
            if os.clock() - notification.display_start >= notification.duration then
                notification.state = "disappearing"
            end
        elseif notification.state == "disappearing" then
            notification.alpha = notification.alpha - animation_speed
            if notification.alpha <= 0 then
                table.remove(notifications, i)
            end
        end

        local text_size = ImGui.CalcTextSize(notification.text)
        local notification_width = text_size.x + 20
        local x = (screen_width - notification_width) / 2
        local y = screen_height - (notification_height + notification_margin) * i

        draw_list:AddRectFilled(ImGui.ImVec2(x, y), ImGui.ImVec2(x + notification_width, y + notification_height), ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.1, 0.1, 0.1, notification.alpha)), 5)
        draw_list:AddText(ImGui.ImVec2(x + 10, y + (notification_height - text_size.y) / 2), ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(1, 1, 1, notification.alpha)), notification.text)
    end
end

1710705675048.png



Lua:
local value1 = imgui.new.float(20)
local value2 = imgui.new.float(80)
drawDoubleValueSlider(window_center.x, window_center.y, 300, 0, 100, value1, value2, "Выберите диапазон")
Lua:
function drawDoubleValueSlider(x, y, width, min, max, value1, value2, label)
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()
    local sliderHeight = 20
    local knobRadius = 12
    local lineY = y + sliderHeight / 2
    local value1Pos = (value1[0] - min) / (max - min) * width
    local value2Pos = (value2[0] - min) / (max - min) * width
    local gradientStartColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.6, 0.6, 0.9, 1))
    local gradientEndColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.3, 0.3, 0.8, 1))
    local knobColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(1, 1, 1, 1))
    local textColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(1, 1, 1, 1))
    local shadowColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0, 0, 0, 0.5))

    -- Рисуем градиентную линию слайдера
    draw_list:AddRectFilledMultiColor(ImGui.ImVec2(x, lineY - sliderHeight / 2), ImGui.ImVec2(x + width, lineY + sliderHeight / 2), gradientStartColor, gradientEndColor, gradientEndColor, gradientStartColor)

    -- Рисуем активную область слайдера
    draw_list:AddRectFilled(ImGui.ImVec2(x + value1Pos, lineY - sliderHeight / 2), ImGui.ImVec2(x + value2Pos, lineY + sliderHeight / 2), ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.26, 0.59, 0.98, 0.8)), knobRadius / 2)

    -- Рисуем ручки слайдера с тенью
    draw_list:AddCircleFilled(ImGui.ImVec2(x + value1Pos + 2, lineY + 2), knobRadius, shadowColor, 16)
    draw_list:AddCircleFilled(ImGui.ImVec2(x + value1Pos, lineY), knobRadius, knobColor, 16)
    draw_list:AddCircleFilled(ImGui.ImVec2(x + value2Pos + 2, lineY + 2), knobRadius, shadowColor, 16)
    draw_list:AddCircleFilled(ImGui.ImVec2(x + value2Pos, lineY), knobRadius, knobColor, 16)

    -- Рисуем текст слайдера
    if label then
        draw_list:AddText(ImGui.ImVec2(x + (width / 2) - ImGui.CalcTextSize(label).x / 2, y - 30), textColor, label)
    end

    -- Отображение текущих значений
    local valueText1 = string.format("%.2f", value1[0])
    local valueText2 = string.format("%.2f", value2[0])
    draw_list:AddText(ImGui.ImVec2(x + value1Pos - ImGui.CalcTextSize(valueText1).x / 2, lineY + knobRadius + 5), textColor, valueText1)
    draw_list:AddText(ImGui.ImVec2(x + value2Pos - ImGui.CalcTextSize(valueText2).x / 2, lineY + knobRadius + 5), textColor, valueText2)

    -- Взаимодействие с ручками слайдера
    local isHovered1 = ImGui.IsMouseHoveringRect(ImGui.ImVec2(x + value1Pos - knobRadius, lineY - knobRadius), ImGui.ImVec2(x + value1Pos + knobRadius, lineY + knobRadius))
    local isHovered2 = ImGui.IsMouseHoveringRect(ImGui.ImVec2(x + value2Pos - knobRadius, lineY - knobRadius), ImGui.ImVec2(x + value2Pos + knobRadius, lineY + knobRadius))
    local mouseDelta = ImGui.GetIO().MouseDelta.x
    if isHovered1 and ImGui.IsMouseDown(0) then
        value1[0] = math.min(math.max(value1[0] + mouseDelta * (max - min) / width, min), value2[0])
    elseif isHovered2 and ImGui.IsMouseDown(0) then
        value2[0] = math.max(math.min(value2[0] + mouseDelta * (max - min) / width, max), value1[0])
    end
end
1710706175723.png

Lua:
drawLoadingIndicator(window_center.x, window_center.y, 50, 8, 0.1)

-- последнее значчение от 0 до 1


Lua:
function drawLoadingIndicator(x, y, radius, thickness, progress)
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()
    local start_angle = -math.pi / 2
    local max_angle = 2 * math.pi
    local progress_angle = start_angle + max_angle * progress
    local bg_color = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.2, 0.2, 0.2, 1))
    local fg_color = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.4, 0.7, 0.2, 1))

    -- Рисуем фон индикатора
    draw_list:PathArcTo(ImGui.ImVec2(x, y), radius, start_angle, start_angle + max_angle, 64)
    draw_list:PathStroke(bg_color, false, thickness)

    -- Рисуем прогресс индикатора
    draw_list:PathArcTo(ImGui.ImVec2(x, y), radius, start_angle, progress_angle, 64)
    draw_list:PathStroke(fg_color, false, thickness)
end



1710706835063.png


Lua:
local tasks = {
    {name = "Задача 1", completed = false},
    {name = "Задача 2", completed = true},
    {name = "Задача 3", completed = false},
}

imgui.SetCursorPos(window_center)
drawTaskList(tasks)

Lua:
function drawTaskList(tasks)
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()

    for i, task in ipairs(tasks) do
        local checkboxID = "##taskCheckbox" .. tostring(i)
        local checkboxSize = 20
        local cursorPos = ImGui.GetCursorScreenPos()
        local checkboxPos = {x = cursorPos.x + 5, y = cursorPos.y + 5}
        local textSize = ImGui.CalcTextSize(task.name)
        local rowHeight = math.max(checkboxSize, textSize.y) + 10
        local isChecked = ImGui.new.bool(task.completed)

        -- Рисуем кастомный чекбокс
        if ImGui.InvisibleButton(checkboxID, ImGui.ImVec2(checkboxSize, checkboxSize)) then
            task.completed = not task.completed
        end
        local col = task.completed and ImGui.GetColorU32(ImGui.Col.FrameBgActive) or ImGui.GetColorU32(ImGui.Col.FrameBg)
        draw_list:AddRectFilled(ImGui.ImVec2(checkboxPos.x, checkboxPos.y), ImGui.ImVec2(checkboxPos.x + checkboxSize, checkboxPos.y + checkboxSize), col, 4)
        if task.completed then
            draw_list:AddLine(ImGui.ImVec2(checkboxPos.x + 4, checkboxPos.y + checkboxSize / 2), ImGui.ImVec2(checkboxPos.x + checkboxSize - 4, checkboxPos.y + checkboxSize / 2), ImGui.GetColorU32(ImGui.Col.Text))
        end

        -- Рисуем текст задачи
        ImGui.SetCursorScreenPos(ImGui.ImVec2(cursorPos.x + checkboxSize + 10, cursorPos.y + (rowHeight - textSize.y) / 2))
        if task.completed then
            ImGui.PushStyleColor(ImGui.Col.Text, ImGui.ImVec4(0.5, 0.5, 0.5, 1)) -- Используем ImVec4 для цвета
        else
            ImGui.PushStyleColor(ImGui.Col.Text, ImGui.ImVec4(1, 1, 1, 1)) -- Белый цвет для невыполненных задач
        end
        ImGui.Text(task.name)
        ImGui.PopStyleColor()

        -- Сдвигаем курсор вниз для следующей задачи
        ImGui.SetCursorScreenPos(ImGui.ImVec2(cursorPos.x, cursorPos.y + rowHeight))
    end
end



1710707821040.png



Lua:
updateAndDrawFloatingTexts() -- где то в рендере имгуи

addFloatingText("Привет, мир!", 5, 1, 1, imgui.ImVec2(100, 100)) -- например по нажатию кнопки


Lua:
local floatingTexts = {}
function addFloatingText(text, duration, fadeInTime, fadeOutTime, position)
    table.insert(floatingTexts, {
        text = text,
        totalDuration = duration,
        fadeInTime = fadeInTime,
        fadeOutTime = fadeOutTime,
        position = position,
        alpha = 0,
        timer = 0
    })
end

function updateAndDrawFloatingTexts()
    local ImGui = imgui
    for i = #floatingTexts, 1, -1 do
        local ft = floatingTexts[i]
        ft.timer = ft.timer + ImGui.GetIO().DeltaTime

        -- Рассчитываем альфа-канал для эффекта появления и исчезновения
        if ft.timer < ft.fadeInTime then
            ft.alpha = ft.timer / ft.fadeInTime
        elseif ft.timer > (ft.totalDuration - ft.fadeOutTime) then
            ft.alpha = 1 - (ft.timer - (ft.totalDuration - ft.fadeOutTime)) / ft.fadeOutTime
        else
            ft.alpha = 1
        end

        -- Отрисовка текста с учетом альфа-канала
        ImGui.PushStyleColor(ImGui.Col.Text, ImGui.ImVec4(1, 1, 1, ft.alpha))
        ImGui.SetCursorPos(ft.position)
        ImGui.Text(ft.text)
        ImGui.PopStyleColor()

        -- Удаление текста, если его время отображения истекло
        if ft.timer >= ft.totalDuration then
            table.remove(floatingTexts, i)
        end
    end
end


1710708267567.png

Lua:
drawLoadingIndicator2(window_center.x, window_center.y, 50, 12, 2)


Lua:
function drawLoadingIndicator2(centerX, centerY, radius, segments, speed)
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()
    local time = ImGui.GetTime()

    -- Определяем цвета для градиента
    local colors = {
        ImGui.ImVec4(0.4, 0.8, 1.0, 1), -- Светло-голубой
        ImGui.ImVec4(0.2, 0.4, 0.8, 1)  -- Темно-синий
    }

    for i = 1, segments do
        local angle = (2 * math.pi / segments) * (i - 1) + (time * speed)
        local segmentRadius = radius * (0.8 + 0.2 * math.sin(time * speed + i)) -- Радиус сегмента с анимацией

        -- Создаем градиент для сегмента
        local color = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(
            colors[1].x * (1 - i / segments) + colors[2].x * (i / segments),
            colors[1].y * (1 - i / segments) + colors[2].y * (i / segments),
            colors[1].z * (1 - i / segments) + colors[2].z * (i / segments),
            0.5 + 0.5 * math.sin(time * speed + i) -- Изменение прозрачности для создания эффекта глубины
        ))

        -- Рисуем сегменты с градиентом и эффектом глубины
        for layer = 1, 3 do
            local layerRadius = segmentRadius - (layer - 1) * 5 -- Уменьшаем радиус для создания слоев
            local center = ImGui.ImVec2(
                centerX + layerRadius * math.cos(angle),
                centerY + layerRadius * math.sin(angle)
            )
            draw_list:AddCircleFilled(center, radius * 0.1, color, 12)
        end
    end
end

1710745030044.png



Lua:
drawMagicCircle(window_center.x, window_center.y, 111)

Lua:
function drawMagicCircle(centerX, centerY, radius)
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()
    local mousePos = ImGui.GetMousePos()
    local distance = math.sqrt((mousePos.x - centerX)^2 + (mousePos.y - centerY)^2)
    local maxDistance = radius
    local distanceRatio = math.min(distance / maxDistance, 1)
    local color = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(1 - distanceRatio, distanceRatio, 0, 1))

    -- Рисуем волшебный круг
    draw_list:AddCircleFilled(ImGui.ImVec2(centerX, centerY), radius, color, 24)

    -- Опционально: рисуем рамку вокруг круга
    draw_list:AddCircle(ImGui.ImVec2(centerX, centerY), radius, ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(1, 1, 1, 0.5)), 24)
end


1710746362376.png


Lua:
drawRotatingCompass(window_center.x, window_center.y, 99)


Lua:
function drawRotatingCompass(centerX, centerY, radius)
    local ImGui = imgui
    local draw_list = ImGui.GetWindowDrawList()
    local mousePos = ImGui.GetMousePos()
    local angleToMouse = math.atan2(mousePos.y - centerY, mousePos.x - centerX)
    local time = ImGui.GetTime()
    local pulsate = math.sin(time * 5) * 0.5 + 0.5

    -- Цвета
    local baseColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.1, 0.1, 0.1, 0.9)) -- Темный с полупрозрачностью
    local arrowColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.9, 0.3, 0.3, 1)) -- Ярко-красный
    local textColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(1, 1, 1, 1)) -- Белый
    local outlineColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0.7, 0.7, 0.7, 0.5)) -- Серый с полупрозрачностью

    -- Тень для текста
    local textShadowColor = ImGui.ColorConvertFloat4ToU32(ImGui.ImVec4(0, 0, 0, 0.5))

    -- Основа компаса
    draw_list:AddCircleFilled(ImGui.ImVec2(centerX, centerY), radius, baseColor, 24)
    draw_list:AddCircle(ImGui.ImVec2(centerX, centerY), radius, outlineColor, 24, 1.0) -- Обводка

    -- Стрелка компаса с пульсацией
    local arrowLength = radius * 0.8 * pulsate
    local arrowX = centerX + arrowLength * math.cos(angleToMouse)
    local arrowY = centerY + arrowLength * math.sin(angleToMouse)
    draw_list:AddLine(ImGui.ImVec2(centerX, centerY), ImGui.ImVec2(arrowX, arrowY), arrowColor, 2 + pulsate)
    draw_list:AddCircleFilled(ImGui.ImVec2(arrowX, arrowY), 5 + pulsate, arrowColor)

    -- Метки направлений
    local directions = {"N", "E", "S", "W"}
    for i, dir in ipairs(directions) do
        local angle = math.pi / 2 * (i - 1)
        local dirX = centerX + (radius + 15) * math.cos(angle)
        local dirY = centerY + (radius + 15) * math.sin(angle)
        -- Тень для текста
        draw_list:AddText(ImGui.ImVec2(dirX - ImGui.CalcTextSize(dir).x / 2 + 1, dirY - ImGui.CalcTextSize(dir).y / 2 + 1), textShadowColor, dir)
        draw_list:AddText(ImGui.ImVec2(dirX - ImGui.CalcTextSize(dir).x / 2, dirY - ImGui.CalcTextSize(dir).y / 2), textColor, dir)
    end

    -- Текстовое направление
    local directionText = string.format("Угол: %.2f°", math.deg(angleToMouse))
    -- Тень для текста
    draw_list:AddText(ImGui.ImVec2(centerX - ImGui.CalcTextSize(directionText).x / 2 + 1, centerY + radius + 30 + 1), textShadowColor, directionText)
    draw_list:AddText(ImGui.ImVec2(centerX - ImGui.CalcTextSize(directionText).x / 2, centerY + radius + 30), textColor, directionText)
end
 

Вложения

  • 1710708263045.png
    1710708263045.png
    22.2 KB · Просмотры: 18
Последнее редактирование:

VanoKLR

Известный
641
372
Описание: Рисует таргет бох без мега растягивания на большой дистанции
AxxWuoQjIMk.jpg

Код:
function renderTargetBox(x, y, z, coefZUP, coefZDOWN,color)
    if color == nil then color = 0xAA00CC00 end
    if isPointOnScreen(x,y,z,0) then
        local mx, my, mz = getCharCoordinates(1)
        local radius = 150
        local coef = getDistanceBetweenCoords3d(mx,my,mz,x,y,z)
        local coef2 = getDistanceBetweenCoords3d(mx,my,mz,x,y,z)
        local coef = coef-(coef*2)
        local coef2 = coef2-(coef2*2)
        if coef > -25 then
            coef = -25
            coef2 = -12
            z = z + coefZUP
            local cx, cy = convert3DCoordsToScreen(x,y,z)
            renderDrawLine(cx+coef+60,cy,cx-coef-10,cy,3,color)
            renderDrawLine(cx-coef-60,cy-3,cx+coef+10,cy-3,3,color)
            renderDrawLine(cx+coef+60,cy,cx+coef+60,cy-coef,3,color)
            renderDrawLine(cx-coef-60,cy,cx-coef-60,cy-coef,3,color)
            z = z - coefZDOWN
            local cx, cy = convert3DCoordsToScreen(x,y,z)
            renderDrawLine(cx+coef+60,cy,cx-coef-10,cy,3,color)
            renderDrawLine(cx-coef-60,cy-3,cx+coef+10,cy-3,3,color)
            renderDrawLine(cx+coef+60,cy,cx+coef+60,cy+coef,3,color)
            renderDrawLine(cx-coef-60,cy,cx-coef-60,cy+coef,3,color)
        elseif coef < -25 then
            coef = -1
            coef2 = -55
            z = z + coefZUP
            local cx, cy = convert3DCoordsToScreen(x,y,z) -- верх
            renderDrawLine(cx+coef+coef*5,  cy,   cx-coef+coef2/2.3,  cy,         3,color)
            renderDrawLine(cx-coef-coef*2,  cy-3, cx+2+coef-coef2/3,  cy-3,       3,color)
            renderDrawLine(cx+coef+coef2/3,  cy,   cx+coef+coef2/3,   cy-coef+20, 3,color)
            renderDrawLine(cx-coef-coef2/3,  cy,   cx-coef-coef2/3,   cy-coef+20, 3,color)
            z = z - coefZDOWN
            local cx, cy = convert3DCoordsToScreen(x,y,z) -- низ
            renderDrawLine(cx+coef+coef2/2.5,  cy,   cx+coef+coef2/2.5,   cy-coef-20, 3,color)
            renderDrawLine(cx-coef-coef2/3,  cy,   cx-coef-coef2/3,   cy-coef-20, 3,color)
            renderDrawLine(cx+coef+coef*5,  cy,   cx-coef+coef2/2.3,  cy,         3,color)
            renderDrawLine(cx-coef-coef*2,  cy-3, cx+2+coef-coef2/3,  cy-3,       3,color)
        end
    end
end

Lua:
local target = false

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand("target", function()
            target = not target
        end)
    while true do
        wait(0)
        if target then
            for i, v in ipairs(getAllChars()) do
                if v ~= PLAYER_PED then
                    local x,y,z = getCharCoordinates(v)
                    renderTargetBox(x,y,z, 1,2)
                end
            end
        end
    end
end

function renderTargetBox(x, y, z, coefZUP, coefZDOWN,color) -- x,y,z - центр отрисовки coefUP and coefZDOWN - коэффициент поднятия верхнего уровня и опускания нижнего color - цвет в формате ARGB, если оставить его пустым будет просто зеленый цвет
    if color == nil then color = 0xAA00CC00 end
    if isPointOnScreen(x,y,z,0) then
        local mx, my, mz = getCharCoordinates(1)
        local radius = 150
        local coef = getDistanceBetweenCoords3d(mx,my,mz,x,y,z)
        local coef2 = getDistanceBetweenCoords3d(mx,my,mz,x,y,z)
        local coef = coef-(coef*2)
        local coef2 = coef2-(coef2*2)
        if coef > -25 then
            coef = -25
            coef2 = -12
            z = z + coefZUP
            local cx, cy = convert3DCoordsToScreen(x,y,z)
            renderDrawLine(cx+coef+60,cy,cx-coef-10,cy,3,color)
            renderDrawLine(cx-coef-60,cy-3,cx+coef+10,cy-3,3,color)
            renderDrawLine(cx+coef+60,cy,cx+coef+60,cy-coef,3,color)
            renderDrawLine(cx-coef-60,cy,cx-coef-60,cy-coef,3,color)
            z = z - coefZDOWN
            local cx, cy = convert3DCoordsToScreen(x,y,z)
            renderDrawLine(cx+coef+60,cy,cx-coef-10,cy,3,color)
            renderDrawLine(cx-coef-60,cy-3,cx+coef+10,cy-3,3,color)
            renderDrawLine(cx+coef+60,cy,cx+coef+60,cy+coef,3,color)
            renderDrawLine(cx-coef-60,cy,cx-coef-60,cy+coef,3,color)
        elseif coef < -25 then
            coef = -1
            coef2 = -55
            z = z + coefZUP
            local cx, cy = convert3DCoordsToScreen(x,y,z) -- верх
            renderDrawLine(cx+coef+coef*5,  cy,   cx-coef+coef2/2.3,  cy,         3,color)
            renderDrawLine(cx-coef-coef*2,  cy-3, cx+2+coef-coef2/3,  cy-3,       3,color)
            renderDrawLine(cx+coef+coef2/3,  cy,   cx+coef+coef2/3,   cy-coef+20, 3,color)
            renderDrawLine(cx-coef-coef2/3,  cy,   cx-coef-coef2/3,   cy-coef+20, 3,color)
            z = z - coefZDOWN
            local cx, cy = convert3DCoordsToScreen(x,y,z) -- низ
            renderDrawLine(cx+coef+coef2/2.5,  cy,   cx+coef+coef2/2.5,   cy-coef-20, 3,color)
            renderDrawLine(cx-coef-coef2/3,  cy,   cx-coef-coef2/3,   cy-coef-20, 3,color)
            renderDrawLine(cx+coef+coef*5,  cy,   cx-coef+coef2/2.3,  cy,         3,color)
            renderDrawLine(cx-coef-coef*2,  cy-3, cx+2+coef-coef2/3,  cy-3,       3,color)
        end
    end
end
UPD: Заметил что-то подобное в EbloFun Hack но там отрисовка была в виде текстуры, тут на линиях
 

why ega

РП игрок
Модератор
2,539
2,233
Описание: Скорее всего баян, но дело было вечером, писал заказ и стало необходимо переписать макросы GET_X_LPARAM и GET_Y_LPARAM из WinAPI
Пример использования:
Lua:
addEventHandler("onWindowMessage", function(message, wparam, lparam)
    if message == windows.msg.WM_LBUTTONUP then      
        print("Click on: ", getPositionFromLParam(lparam))
    end
end)



function getPositionFromLParam(lparam)
    local x = bit.band(lparam, 0xFFFF)
    local y = bit.band(bit.rshift(lparam, 16), 0xFFFF)
    return x, y
end
Код:
Lua:
function getPositionFromLParam(lparam)
    -- Подробнее: https://youtu.be/qewavPO6jcA?t=139&si=wACES-he7EWqQO9A
    -- Устанавливаем все 16 бит в единицу (маской называется)
    local x = bit.band(lparam, 0xFFFF)
    -- Смещаемся на 2 байта вправо и повторяем операцию
    local y = bit.band(bit.rshift(lparam, 16), 0xFFFF)
    return x, y
end
 

XRLM

Известный
2,539
854
Описание: Рисует таргет бох без мега растягивания на большой дистанции
AxxWuoQjIMk.jpg

Код:
function renderTargetBox(x, y, z, coefZUP, coefZDOWN,color)
    if color == nil then color = 0xAA00CC00 end
    if isPointOnScreen(x,y,z,0) then
        local mx, my, mz = getCharCoordinates(1)
        local radius = 150
        local coef = getDistanceBetweenCoords3d(mx,my,mz,x,y,z)
        local coef2 = getDistanceBetweenCoords3d(mx,my,mz,x,y,z)
        local coef = coef-(coef*2)
        local coef2 = coef2-(coef2*2)
        if coef > -25 then
            coef = -25
            coef2 = -12
            z = z + coefZUP
            local cx, cy = convert3DCoordsToScreen(x,y,z)
            renderDrawLine(cx+coef+60,cy,cx-coef-10,cy,3,color)
            renderDrawLine(cx-coef-60,cy-3,cx+coef+10,cy-3,3,color)
            renderDrawLine(cx+coef+60,cy,cx+coef+60,cy-coef,3,color)
            renderDrawLine(cx-coef-60,cy,cx-coef-60,cy-coef,3,color)
            z = z - coefZDOWN
            local cx, cy = convert3DCoordsToScreen(x,y,z)
            renderDrawLine(cx+coef+60,cy,cx-coef-10,cy,3,color)
            renderDrawLine(cx-coef-60,cy-3,cx+coef+10,cy-3,3,color)
            renderDrawLine(cx+coef+60,cy,cx+coef+60,cy+coef,3,color)
            renderDrawLine(cx-coef-60,cy,cx-coef-60,cy+coef,3,color)
        elseif coef < -25 then
            coef = -1
            coef2 = -55
            z = z + coefZUP
            local cx, cy = convert3DCoordsToScreen(x,y,z) -- верх
            renderDrawLine(cx+coef+coef*5,  cy,   cx-coef+coef2/2.3,  cy,         3,color)
            renderDrawLine(cx-coef-coef*2,  cy-3, cx+2+coef-coef2/3,  cy-3,       3,color)
            renderDrawLine(cx+coef+coef2/3,  cy,   cx+coef+coef2/3,   cy-coef+20, 3,color)
            renderDrawLine(cx-coef-coef2/3,  cy,   cx-coef-coef2/3,   cy-coef+20, 3,color)
            z = z - coefZDOWN
            local cx, cy = convert3DCoordsToScreen(x,y,z) -- низ
            renderDrawLine(cx+coef+coef2/2.5,  cy,   cx+coef+coef2/2.5,   cy-coef-20, 3,color)
            renderDrawLine(cx-coef-coef2/3,  cy,   cx-coef-coef2/3,   cy-coef-20, 3,color)
            renderDrawLine(cx+coef+coef*5,  cy,   cx-coef+coef2/2.3,  cy,         3,color)
            renderDrawLine(cx-coef-coef*2,  cy-3, cx+2+coef-coef2/3,  cy-3,       3,color)
        end
    end
end

Lua:
local target = false

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand("target", function()
            target = not target
        end)
    while true do
        wait(0)
        if target then
            for i, v in ipairs(getAllChars()) do
                if v ~= PLAYER_PED then
                    local x,y,z = getCharCoordinates(v)
                    renderTargetBox(x,y,z, 1,2)
                end
            end
        end
    end
end

function renderTargetBox(x, y, z, coefZUP, coefZDOWN,color) -- x,y,z - центр отрисовки coefUP and coefZDOWN - коэффициент поднятия верхнего уровня и опускания нижнего color - цвет в формате ARGB, если оставить его пустым будет просто зеленый цвет
    if color == nil then color = 0xAA00CC00 end
    if isPointOnScreen(x,y,z,0) then
        local mx, my, mz = getCharCoordinates(1)
        local radius = 150
        local coef = getDistanceBetweenCoords3d(mx,my,mz,x,y,z)
        local coef2 = getDistanceBetweenCoords3d(mx,my,mz,x,y,z)
        local coef = coef-(coef*2)
        local coef2 = coef2-(coef2*2)
        if coef > -25 then
            coef = -25
            coef2 = -12
            z = z + coefZUP
            local cx, cy = convert3DCoordsToScreen(x,y,z)
            renderDrawLine(cx+coef+60,cy,cx-coef-10,cy,3,color)
            renderDrawLine(cx-coef-60,cy-3,cx+coef+10,cy-3,3,color)
            renderDrawLine(cx+coef+60,cy,cx+coef+60,cy-coef,3,color)
            renderDrawLine(cx-coef-60,cy,cx-coef-60,cy-coef,3,color)
            z = z - coefZDOWN
            local cx, cy = convert3DCoordsToScreen(x,y,z)
            renderDrawLine(cx+coef+60,cy,cx-coef-10,cy,3,color)
            renderDrawLine(cx-coef-60,cy-3,cx+coef+10,cy-3,3,color)
            renderDrawLine(cx+coef+60,cy,cx+coef+60,cy+coef,3,color)
            renderDrawLine(cx-coef-60,cy,cx-coef-60,cy+coef,3,color)
        elseif coef < -25 then
            coef = -1
            coef2 = -55
            z = z + coefZUP
            local cx, cy = convert3DCoordsToScreen(x,y,z) -- верх
            renderDrawLine(cx+coef+coef*5,  cy,   cx-coef+coef2/2.3,  cy,         3,color)
            renderDrawLine(cx-coef-coef*2,  cy-3, cx+2+coef-coef2/3,  cy-3,       3,color)
            renderDrawLine(cx+coef+coef2/3,  cy,   cx+coef+coef2/3,   cy-coef+20, 3,color)
            renderDrawLine(cx-coef-coef2/3,  cy,   cx-coef-coef2/3,   cy-coef+20, 3,color)
            z = z - coefZDOWN
            local cx, cy = convert3DCoordsToScreen(x,y,z) -- низ
            renderDrawLine(cx+coef+coef2/2.5,  cy,   cx+coef+coef2/2.5,   cy-coef-20, 3,color)
            renderDrawLine(cx-coef-coef2/3,  cy,   cx-coef-coef2/3,   cy-coef-20, 3,color)
            renderDrawLine(cx+coef+coef*5,  cy,   cx-coef+coef2/2.3,  cy,         3,color)
            renderDrawLine(cx-coef-coef*2,  cy-3, cx+2+coef-coef2/3,  cy-3,       3,color)
        end
    end
end
UPD: Заметил что-то подобное в EbloFun Hack но там отрисовка была в виде текстуры, тут на линиях
 

VanoKLR

Известный
641
372

Описание: простая функция позволяющая сделать зачёркнутый текст​

На БХ такую не видел
Lua:
imgui.crossetText("test text",0xFFFFFFFF)

Lua:
function imgui.crossetText(text,color)
    imgui.Text(text)
    color = color or 0xFFFFFFFF
    local s = imgui.CalcTextSize(text)
    local p = imgui.GetCursorScreenPos()
    local DL = imgui.GetWindowDrawList()
    DL:AddLine(imgui.ImVec2(p.x, p.y - 10), imgui.ImVec2(p.x + s.x, p.y - 10), color)
end
 

ARMOR

kjor32 is legend
Модератор
4,851
6,080
Открывает/Закрывает консоль sampfuncs

Lua:
local ffi = require("ffi")
local sampfuncs = getModuleHandle("SampFuncs.asi")
-- R1
function setSFConsoleState(bValue)
    local pSfConsole = ffi.cast("void**", sampfuncs + 0x11572C)[0]
    ffi.cast("void(__thiscall*)(void*, bool)", sampfuncs + 0x12EBB)(pSfConsole, bValue)
end
-- R3
function setSFConsoleState(bValue)
    local pSfConsole = ffi.cast("void**", sampfuncs + 0x1136C0)[0]
    ffi.cast("void(__thiscall*)(void*, bool)", sampfuncs + 0x131E7)(pSfConsole, bValue)
end

Пример использования:
Lua:
setSFConsoleState(true)
 

atomlin

Известный
579
380
Описание: чинит отображение анимации курения у игроков с SPECIAL_ACTION_SMOKE_CIGGY (R1 и R3)

Lua:
local OFFSETS = { [0x35E5B1EC] = { 0xA85E2, 0xA85D5 }, [0x583D6F47] = { 0xAD4B2, 0xAD4A5 } }

function main()
    while not isSampAvailable() do wait(100) end

    local function OFFSET(POS)
        return getModuleHandle("samp.dll") + OFFSETS[readMemory(getModuleHandle("samp.dll") + 0x90, 4, true)][POS]
    end
    
    writeMemory(OFFSET(1), 4, representFloatAsInt(4.0), true)
    writeMemory(OFFSET(2), 4, 0xFFFFFFFF, true)
end


До и после:
without.gif
with (1) (1).gif