Как установить dear imgui
(This library is available under a free and permissive license, but needs financial support to sustain its continued improvements. In addition to maintenance and stability there are many desirable features yet to be added. If your company is using Dear ImGui, please consider reaching out.)
Businesses: support continued development and maintenance via invoiced technical support, maintenance, sponsoring contracts:
E-mail: contact @ dearimgui dot com
Individuals: support continued development and maintenance here.
Dear ImGui is a bloat-free graphical user interface library for C++. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies).
Dear ImGui is designed to enable fast iterations and to empower programmers to create content creation tools and visualization / debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and lacks certain features normally found in more high-level libraries.
Dear ImGui is particularly suited to integration in games engine (for tooling), real-time 3D applications, fullscreen applications, embedded applications, or any applications on consoles platforms where operating system features are non-standard.
The core of Dear ImGui is self-contained within a few platform-agnostic files which you can easily compile in your application/engine. They are all the files in the root folder of the repository (imgui*.cpp, imgui*.h).
You will need a backend to integrate Dear ImGui in your app. The backend passes mouse/keyboard/gamepad inputs and variety of settings to Dear ImGui, and is in charge of rendering the resulting vertices.
Backends for a variety of graphics api and rendering platforms are provided in the backends/ folder, along with example applications in the examples/ folder. See the Integration section of this document for details. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui.
After Dear ImGui is setup in your application, you can use it from _anywhere_ in your program loop:
Result: 

(settings: Dark style (left), Light style (right) / Font: Roboto-Medium, 16px)
Dear ImGui allows you to create elaborate tools as well as very short-lived ones. On the extreme side of short-livedness: using the Edit&Continue (hot code reload) feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! Dear ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, an entire game making editor/framework, etc.
Check out the Wiki’s About the IMGUI paradigm section if you want to understand the core principles behind the IMGUI paradigm. An IMGUI tries to minimize superfluous state duplication, state synchronization and state retention from the user’s point of view. It is less error prone (less code and less bugs) than traditional retained-mode interfaces, and lends itself to create dynamic user interfaces.
Dear ImGui outputs vertex buffers and command lists that you can easily render in your application. The number of draw calls and state changes required to render them is fairly small. Because Dear ImGui doesn’t know or touch graphics state directly, you can call its functions anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate Dear ImGui with your existing codebase.
A common misunderstanding is to mistake immediate mode gui for immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes as the gui functions are called. This is NOT what Dear ImGui does. Dear ImGui outputs vertex buffers and a small list of draw calls batches. It never touches your GPU directly. The draw call batches are decently optimal and you can render them later, in your app or even remotely.
See Releases page. Reading the changelogs is a good way to keep up to date with the things Dear ImGui has to offer, and maybe will give you ideas of some features that you’ve been ignoring until now!
You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don’t, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here:
The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at different scale, and scale your style with style.ScaleAllSizes() (see FAQ).
On most platforms and when using C++, you should be able to use a combination of the imgui_impl_xxxx backends without modification (e.g. imgui_impl_win32.cpp + imgui_impl_dx11.cpp ). If your engine supports multiple platforms, consider using more of the imgui_impl_xxxx files instead of rewriting them: this will be less work for you and you can get Dear ImGui running immediately. You can later decide to rewrite a custom backend using your custom engine functions if you wish so.
Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading one texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles. The examples/ folder is populated with applications doing just that. If you are an experienced programmer at ease with those concepts, it should take you less than two hours to integrate Dear ImGui in your custom engine. Make sure to spend time reading the FAQ, comments, and some of the examples/ application!
Officially maintained backends/bindings (in repository):
Also see Wiki for more links and ideas.
Some of the goals for 2021 are:
For more user-submitted screenshots of projects using Dear ImGui, check out the Gallery Threads!
For a list of third-party widgets and extensions, check out the Useful Extensions/Widgets wiki page.
Support, Frequently Asked Questions (FAQ)
See: Frequently Asked Questions (FAQ) where common questions are answered.
See: Wiki for many links, references, articles.
See: Articles about the IMGUI paradigm to read/learn about the Immediate Mode GUI paradigm.
Getting started? For first-time users having issues compiling/linking/running or issues loading fonts, please use GitHub Discussions.
For other questions, bug reports, requests, feedback, you may post on GitHub Issues. Please read and fill the New Issue template carefully.
Private support is available for paying business customers (E-mail: contact @ dearimgui dot com).
Which version should I get?
We occasionally tag Releases but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported.
Advanced users may want to use the docking branch with Multi-Viewport and Docking features. This branch is kept in sync with master regularly.
Who uses Dear ImGui?
See the Quotes, Sponsors, Software using dear imgui Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also see the Gallery Threads!
How can I help?
How can I help financing further development of Dear ImGui?
Ongoing Dear ImGui development is currently financially supported by users and private sponsors:
Please see detailed list of Dear ImGui supporters for past sponsors. From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations.
THANK YOU to all past and present supporters for helping to keep this project alive and thriving!
Dear ImGui is using software and services provided free of charge for open source projects:
Developed by Omar Cornut and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of Media Molecule and first used internally on the game Tearaway (PS Vita).
Recurring contributors (2020): Omar Cornut @ocornut, Rokas Kupstys @rokups, Ben Carter @ShironekoBen. A large portion of work on automation systems, regression tests and other features are currently unpublished.
Sponsoring, support contracts and other B2B transactions are hosted and handled by Lizardcube.
Omar: «I first discovered the IMGUI paradigm at Q-Games where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I’ve worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it.»
Embeds ProggyClean.ttf font by Tristan Grimmer (MIT license).
Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Also thank you to everyone posting feedback, questions and patches on GitHub.
Moon ImGui — Dear ImGui for MoonLoader
Это работает, но что-то не впечатляет, согласитесь. Окно изначально маленькое, показывается сразу при старте и его нельзя закрыть.
Сделаем его побольше, добавим активацию и какое-нибудь действие:
Разница между C++ API и Lua API
| Описание | В C++ | В Lua |
|---|---|---|
| Все функции из пространства имён ImGui, как и все типы, и все перечисления находятся в таблице, возвращаемой модулем | ImGui::Text(«text»); ImVec2(0.1f, 2.3f); | imgui.Text(«text»); imgui.ImVec2(0.1, 2.3); |
| Названия перечислений (enum) и их значений лишились префиксов и символа «_» в конце | ImGuiWindowFlags_NoTitleBar | imgui.WindowFlags.NoTitleBar |
| Значения базовых типов, которые в ImGui записываются по указателю, должны быть использованы через специальные типы: ImBool для bool, ImFloat для float, ImInt для int и unsigned int, ImFloat2-4 для float3, ImInt2-4 для int2 | static bool win = false; ImGui::Begin(«window», &win); win = false; | local win = imgui.ImBool(false) imgui.Begin(«window», win) win.v = false |
| Функции с переменным количеством аргументов для форматирования текста не поддерживают форматирование, используйте string.format | ImGui::Text(«hey, %s», name) | imgui.Text(string.format(‘hey, %s’, name)) |
| Функции InputText и InputTextMultiline принимают ImBuffer вместо char* buf + size_t buf_size | char buf[256]<>; ImGui::InputText(‘input’, buf, sizeof(buf)) | local buf = imgui.ImBuffer(256); imgui.InputText(‘input’, buf) |
| Динамические массивы в виде массива указателей + количество элементов заменены таблицами | const char* items[] = <"1", "2", "3">; ImGui::ListBox(«list», &lb_cur, items, 3) | imgui.ListBox(‘list’, lb_cur, <'1', '2', '3'>) |
| Функции с аргументами const char* str_start, const char* str_end, идущими подряд, принимают обычную строку | ImGui::TextUnformatted(some_str, some_str + 24) | imgui.TextUnformatted(some_str) |
| Все функции, принимающие калбэк + user_data, принимают ImCallback | void swszCb(ImGuiSizeConstraintCallbackData*) <>; ImGui::SetNextWindowSizeConstraints(size_min, size_max, &swszCb, (void*)&my_data) | local swszCb = imgui.ImCallback(function(data) end) imgui.SetNextWindowSizeConstraints(size_min, size_max, swszCb) |
| ImFont::CalcTextSizeA, ImFontAtlas::CustomRect::CalcCustomRectUV, ImFontAtlas::GetTexDataAsRGBA32, ImFontAtlas::GetTexDataAsAlpha8, ImFontAtlas::GlyphRangesBuilder::BuildRanges, ImGui::ColorConvertRGBtoHSV и ImGui::ColorConvertHSVtoRGB возвращают значения вместо изменения по ссылке | float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); | local r, g, b = imgui.ColorConvertHSVtoRGB(h, s, v) |
| ImGuiIO::IniFilename и ImGuiIO::LogFilename принимают ImBuffer вместо указателя на строку | const char ini_path[] = «my/path.ini»; ImGui::GetIO().IniFilename = ini_path; | local ini_path = imgui.ImBuffer(‘my/path.ini’) imgui.GetIO().IniFilename = ini_path |
| Изменение ImGuiTextEditCallbackData::Buf автоматически обновляет длину и задаёт значение BufDirty | s.copy(data.Buf, data.BufSize); data.BufTextLen = s.length(); data.BufDirty = true; | data.Buf = ‘text’ |
Но это ещё не всё. Вся работа с текстом в ImGui основана на UTF-8, т.е. текст не ограничен лишь стандартным набором символов. Но т.к. GTA, SAMP и MoonLoader не поддерживают юникод, кодировки необходимо конвертировать.
Работа с другими языками на примере русского
В MoonLoader v.025 были добавлены библиотеки lua-iconv и encoding, они призваны помочь в работе с разными кодировками текста.
Следующий пример показывает как использовать текст на русском в ImGui:
Скрипт должен быть сохранён в кодировке Windows-1251
Остальные особенности
В Moon ImGui есть несколько дополнительных возможностей. В частности, они реализуют взаимодействие с игрой и управление интерфейсом.
На этом всё. Во вложениях есть пример с демонстрацией использования всех этих фич, рекомендую посмотреть код и пощупать его в игре. Вот скриншот:
Гайд mimgui — Dear ImGui for MoonLoader
mimgui — это новая графическая библиотека, написанная в результате устаревания предыдущей графической библиотеки Moon ImGui, использующей Dear ImGui v.1.52; использующая в своей основе свежий релиз Dear ImGui v.1.72. Новая библиотека включает в себя все основные возможности фреймворка, а API максимально приближен к оригинальному.
Скачать mimgui
Установка: переместить папку mimgui из архива в папку «*Корневая папка с игрой*/moonloader/lib»
mimgui разрабатывался с декабря 2018 года, однако, широкую популярность он получил только в июле-августе 2019 года, как раз в период выхода первой beta-версии MoonLoader 027.
Примеры использования mimgui можно увидеть в самом репозитории, но несмотря на это, в этой теме также отдельно будут добавлены примеры использования.
Примеры использования
Давайте напишем примитивный скрипт с использованием mimgui.
Само собой, это не все возможности ImGui, поэтому немного преобразим наш скрипт: добавим размер, позицию по умолчанию и клавишу активации для показа окна.
Хорошо, с индексом разобрались, возможно, вам понадобится убрать автоматическое запоминание, давайте выключим:
Давайте теперь напишем что-то на русском языке:
Мы видим здесь каракули и вопросительные знаки, почему это происходит?
Работа с другими языками на примере русского
В MoonLoader 025 были добавлены библиотеки lua-iconv и encoding, они призваны помочь в работе с разными кодировками текста.
Следующий пример показывает, как использовать текст на русском в ImGui:
Скрипт должен быть сохранён в кодировке Windows-1251 (конкретно для данного примера)
Если в вашем скрипте имеется огромный код с использованием ImGui и мало взаимодействия с функциями MoonLoader’a либо SAMPFUNCS’a, то вы при желании можете сохранить ваш скрипт в UTF-8 и вам не придётся проделывать все эти операции.
В примерах не было затронуто наличие «префрейма» (BeforeFrame), применение его и остальных возможностей вы можете увидеть в репозитории по ссылке:
mimgui/mimgui-extra-features.lua at v1.7.0 · THE-FYP/mimgui
ImVec2(0.1f, 2.3f);
imgui.ImVec2(0.1, 2.3)
ImGui::Begin(«window», &win);
win = false;
imgui.Begin(«window», win)
win[0] = false
ImGui::InputText(‘input’, buf, IM_ARRAYSIZE(buf))
imgui.InputText(‘input’, buf, ffi.sizeof(buf))
ImGui::ListBox(«list», &lb_cur, items, 3)
local current = imgui.new.int(0)
local items = imgui.new[‘const char*’][#itemsList](itemsList)
imgui.ListBoxStr_arr(«list», current, items, #itemsList)
Главные различия между MoonImGui и mimgui
Для взаимодействия с ImGui теперь используется встроенная в LuaJIT библиотека ffi, а не самописные функции. Поэтому, получается так, что когда мы пишем код, мы «пишем код» на С++. Поэтому, добавленные в MoonImGui типы: ImBool, ImBuffer, ImInt, ImFloat, ImCallback не требуются, и им на замену пришли встроенные и не встроенные в Си типы:
Следует отметить, что получение исходных значений так же подверглось изменению. Если раньше исходное значение можно было получить через ключ v ( buffer.v; int.v ), то в mimgui они получаются с помощью нулевого индекса ( int[0]; float[0]; bool[0] ), а для типа Char значение необходимо получать через ffi.string ( ffi.string(buffer) ). Не нужно бояться внесёнными в API изменениям, они очень легко осваиваются и для ежедневного кодинга не нужно вникать в их работу.
#Northn
VolodyaHoi
Участник
Известный
VolodyaHoi
Участник
ArzAh
Потрачен
Скажите пожалуйста, эта версия сейчас стабильная?
Стоит переходить с moonimgui и переписывать проект пока что только с 1-й тысячей строк.
Сейчас обратил внимание что старая тема imgui «Не актуальна», начал читать что пишут, вот задаюсь вопросом. На первый взгляд Mimgui удобнее, но на сколько версия здесь и сейчас стабильна по отношению со старым moonimgui?
Так скажем и «полезных снипетов и функций» на mimgui я не наблюдал.
Tema05
Известный
Скажите пожалуйста, эта версия сейчас стабильная?
Стоит переходить с moonimgui и переписывать проект пока что только с 1-й тысячей строк.
Сейчас обратил внимание что старая тема imgui «Не актуальна», начал читать что пишут, вот задаюсь вопросом. На первый взгляд Mimgui удобнее, но на сколько версия здесь и сейчас стабильна по отношению со старым moonimgui?
Так скажем и «полезных снипетов и функций» на mimgui я не наблюдал.
ArzAh
Потрачен
Что она лучше, я это прочитал уже десятки раз, вопрос мой совсем о другом.
Какой шанс что через месяц не выйдет какой нибудь gimgui и будет лучше mimgui как это стало с moonimgui?
Tema05
Известный
Что она лучше, я это прочитал уже десятки раз, вопрос мой совсем о другом.
Какой шанс что через месяц не выйдет какой нибудь gimgui и будет лучше mimgui как это стало с moonimgui?
ArzAh
Потрачен
#Northn
Police Helper «Reborn» — уже с «Monet»!
ArzAh
Потрачен
Главные различия между MoonImGui и mimgui
Для взаимодействия с ImGui теперь используется встроенная в LuaJIT библиотека ffi, а не самописные функции. Поэтому, получается так, что когда мы пишем код, мы «пишем код» на С++. Поэтому, добавленные в MoonImGui типы: ImBool, ImBuffer, ImInt, ImFloat, ImCallback не требуются, и им на замену пришли встроенные и не встроенные в Си типы:
| Тип | Использование в MoonImGui | Использование в mimgui |
|---|---|---|
| Bool | local bool = imgui.ImBool(true/false) | local bool = imgui.new.bool(true/false) |
| Int | local int = imgui.ImInt(5) | local int = imgui.new.int(5) |
| Char | local buffer = imgui.ImBuffer(128, «hello») | local buffer = imgui.new.char[128](«hello») |
| Float | local float = imgui.ImFloat(5.12) | local float = imgui.new.float(5.12) |
| Callback | local test = function(data) print(«hey») return 0 end local callback = imgui.ImCallback(test) | local test = function(data) print(«hey») return 0 end local callback = ffi.cast(‘int (*)(ImGuiInputTextCallbackData* data)’, test) |
Но переходить все же на данный момент не стоит, потому что большенство функций так скажем «плюшек» от сторонних разработчиков не подходят, на подобии imgui pie, fAwesome и прочее прочее.
Стоит переходить только если использовать чистый imgui. Либо еще и переписывать другие «дополнения».
Сейчас даже кастомный стиль imgui не поставить не переписав готовые что выкладывали для moonimgui
Лично я не хочу тратить дополнительное время, на разработку еще и этих плюшек для Mimgui, которые уже давно есть на moonimgui.
Вывод: Чтобы полноценно перейти на mimgui нужно либо использовать чистый imgui без дополнительных библиотек, либо ждать еще пару лет пока их перенесут на mimgui, либо самому писать эти библиотеки/дополнения/плюшки.
Moon ImGui — Dear ImGui for MoonLoader
Это работает, но что-то не впечатляет, согласитесь. Окно изначально маленькое, показывается сразу при старте и его нельзя закрыть.
Сделаем его побольше, добавим активацию и какое-нибудь действие:
Разница между C++ API и Lua API
| Описание | В C++ | В Lua |
|---|---|---|
| Все функции из пространства имён ImGui, как и все типы, и все перечисления находятся в таблице, возвращаемой модулем | ImGui::Text(«text»); ImVec2(0.1f, 2.3f); | imgui.Text(«text»); imgui.ImVec2(0.1, 2.3); |
| Названия перечислений (enum) и их значений лишились префиксов и символа «_» в конце | ImGuiWindowFlags_NoTitleBar | imgui.WindowFlags.NoTitleBar |
| Значения базовых типов, которые в ImGui записываются по указателю, должны быть использованы через специальные типы: ImBool для bool, ImFloat для float, ImInt для int и unsigned int, ImFloat2-4 для float4, ImInt2-4 для int4 | static bool win = false; ImGui::Begin(«window», &win); win = false; | local win = imgui.ImBool(false) imgui.Begin(«window», win) win.v = false |
| Функции с переменным количеством аргументов для форматирования текста не поддерживают форматирование, используйте string.format | ImGui::Text(«hey, %s», name) | imgui.Text(string.format(‘hey, %s’, name)) |
| Функции InputText и InputTextMultiline принимают ImBuffer вместо char* buf + size_t buf_size | char buf[256]<>; ImGui::InputText(‘input’, buf, sizeof(buf)) | local buf = imgui.ImBuffer(256); imgui.InputText(‘input’, buf) |
| Динамические массивы в виде массива указателей + количество элементов заменены таблицами | const char* items[] = <"1", "2", "3">; ImGui::ListBox(«list», &lb_cur, items, 3) | imgui.ListBox(‘list’, lb_cur, <'1', '2', '3'>) |
| Функции с аргументами const char* str_start, const char* str_end, идущими подряд, принимают обычную строку | ImGui::TextUnformatted(some_str, some_str + 24) | imgui.TextUnformatted(some_str) |
| Все функции, принимающие калбэк + user_data, принимают ImCallback | void swszCb(ImGuiSizeConstraintCallbackData*) <>; ImGui::SetNextWindowSizeConstraints(size_min, size_max, &swszCb, (void*)&my_data) | local swszCb = imgui.ImCallback(function(data) end) imgui.SetNextWindowSizeConstraints(size_min, size_max, swszCb) |
| ImFont::CalcTextSizeA, ImFontAtlas::CustomRect::CalcCustomRectUV, ImFontAtlas::GetTexDataAsRGBA32, ImFontAtlas::GetTexDataAsAlpha8, ImFontAtlas::GlyphRangesBuilder::BuildRanges, ImGui::ColorConvertRGBtoHSV и ImGui::ColorConvertHSVtoRGB возвращают значения вместо изменения по ссылке | float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); | local r, g, b = imgui.ColorConvertHSVtoRGB(h, s, v) |
| ImGuiIO::IniFilename и ImGuiIO::LogFilename принимают ImBuffer вместо указателя на строку | const char ini_path[] = «my/path.ini»; ImGui::GetIO().IniFilename = ini_path; | local ini_path = imgui.ImBuffer(‘my/path.ini’) imgui.GetIO().IniFilename = ini_path |
| Изменение ImGuiTextEditCallbackData::Buf автоматически обновляет длину и задаёт значение BufDirty | s.copy(data.Buf, data.BufSize); data.BufTextLen = s.length(); data.BufDirty = true; | data.Buf = ‘text’ |
Но это ещё не всё. Вся работа с текстом в ImGui основана на UTF-8, т.е. текст не ограничен лишь стандартным набором символов. Но т.к. GTA, SAMP и MoonLoader не поддерживают юникод, кодировки необходимо конвертировать.
Работа с другими языками на примере русского
В MoonLoader v.025 были добавлены библиотеки lua-iconv и encoding, они призваны помочь в работе с разными кодировками текста.
Следующий пример показывает как использовать текст на русском в ImGui:
Скрипт должен быть сохранён в кодировке Windows-1251
Остальные особенности
В Moon ImGui есть несколько дополнительных возможностей. В частности, они реализуют взаимодействие с игрой и управление интерфейсом.
На этом всё. Во вложениях есть пример с демонстрацией использования всех этих фич, рекомендую посмотреть код и пощупать его в игре. Вот скриншот:





