Гайд ImGui часть 1

  • 140
  • 70
Контакты для связи отсутствуют.
Часть 1 :
Заранее скажу, что гайд не полный даже близко, и я много чего не сказал.
Привет. Всех рад видеть в треде о базовых пониманиях при работе в ImGui.
Сначала я бы хотел уяснить, что я буду рассматривать последнюю версию фреймворка. Имгуи используется для создания интерфейса программ, меню или другие визуальные функции. Думаю не стоит тут зацикливаться. Приступим к практике....
Сначала разберём классы в имгуи для работы :
C++:
ImVec2(x, y)
ImVec4(x, y, w, h)
ImColor(r, g, b, a)

>ImVec2 - Используется для задачи позиции, размера объекта или чего либо. Конструкция - ImVec2(float x, float y);
>ImVec4 - используется для установки цвета обьекта (редко), и для установки чего либо с 4 аргументами.
Конструктор - ImVec4(float x, float y, float w, float h); PS: для установки цвета имеет максимальное значение 1.f. Пример:
ImVec4(1.f, 0.2f, 0.1f)
>ImColor - используется для установки только цвета для объектов и тд. Конструктор - ImColor(float red, float green, float blue, float alpha);
Пример : ImColor(37, 73, 243)
>Это близко не все, я разобрал самые основные.
Хотел бы сразу предупредить, что создавать элементы с одинаковыми именами не стоит, тк это сломает имгуи.
Первое что мы должны сделать, это создать окно. Процесс создания контекста и др рассматривать не буду.
C++:
ImGui::Begin("Название окна", nullptr, (int) flags)

C++:
ImGui::Begin("p2chack", nullptr, 0)
//элементы и тд.
ImGui::End();
Стоит сказать, что обязательно вконце окна, после всего прописать End, что бы фреймворк понял, что мы закончили отрсовку элементов на этом окне
1. Первый аргумент в функции как не странно отвечат за название окна.
2.Второй аргумент это переменная bool, которая будет влиять на открытие или закрытие окна. Оно так же может меняться через само окно,если неправильно настроить флаги. Можем ставить nullptr если нас этот вопрос не ебет.
3. Третий аргумент как раз таки меняет внешний вид окна и придаёт ему какие либо изменения. Рассмотрим по подробнее. флаги здесь реализованы через енум, который содержит название флагов.
C++:
enum ImGuiWindowFlags_
{
    ImGuiWindowFlags_None                   = 0,
    ImGuiWindowFlags_NoTitleBar             = 1 << 0,   // Disable title-bar
    ImGuiWindowFlags_NoResize               = 1 << 1,   // Disable user resizing with the lower-right grip
    ImGuiWindowFlags_NoMove                 = 1 << 2,   // Disable user moving the window
    ImGuiWindowFlags_NoScrollbar            = 1 << 3,   // Disable scrollbars (window can still scroll with mouse or programmatically)
    ImGuiWindowFlags_NoScrollWithMouse      = 1 << 4,   // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.
    ImGuiWindowFlags_NoCollapse             = 1 << 5,   // Disable user collapsing window by double-clicking on it
    ImGuiWindowFlags_AlwaysAutoResize       = 1 << 6,   // Resize every window to its content every frame
    ImGuiWindowFlags_NoBackground           = 1 << 7,   // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f).
    ImGuiWindowFlags_NoSavedSettings        = 1 << 8,   // Never load/save settings in .ini file
    ImGuiWindowFlags_NoMouseInputs          = 1 << 9,   // Disable catching mouse, hovering test with pass through.
    ImGuiWindowFlags_MenuBar                = 1 << 10,  // Has a menu-bar
    ImGuiWindowFlags_HorizontalScrollbar    = 1 << 11,  // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section.
    ImGuiWindowFlags_NoFocusOnAppearing     = 1 << 12,  // Disable taking focus when transitioning from hidden to visible state
    ImGuiWindowFlags_NoBringToFrontOnFocus  = 1 << 13,  // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)
    ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14,  // Always show vertical scrollbar (even if ContentSize.y < Size.y)
    ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15,  // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
    ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16,  // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)
    ImGuiWindowFlags_NoNavInputs            = 1 << 18,  // No gamepad/keyboard navigation within the window
    ImGuiWindowFlags_NoNavFocus             = 1 << 19,  // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
    ImGuiWindowFlags_UnsavedDocument        = 1 << 20,  // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. When used in a tab/docking context, tab is selected on closure and closure is deferred by one frame to allow code to cancel the closure (with a confirmation popup, etc.) without flicker.
    ImGuiWindowFlags_NoNav                  = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
    ImGuiWindowFlags_NoDecoration           = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse,
    ImGuiWindowFlags_NoInputs               = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,

    // [Internal]
    ImGuiWindowFlags_NavFlattened           = 1 << 23,  // [BETA] Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!)
    ImGuiWindowFlags_ChildWindow            = 1 << 24,  // Don't use! For internal use by BeginChild()
    ImGuiWindowFlags_Tooltip                = 1 << 25,  // Don't use! For internal use by BeginTooltip()
    ImGuiWindowFlags_Popup                  = 1 << 26,  // Don't use! For internal use by BeginPopup()
    ImGuiWindowFlags_Modal                  = 1 << 27,  // Don't use! For internal use by BeginPopupModal()
    ImGuiWindowFlags_ChildMenu              = 1 << 28   // Don't use! For internal use by BeginMenu()

    // [Obsolete]
    //ImGuiWindowFlags_ResizeFromAnySide    = 1 << 17,  // --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by backend (io.BackendFlags & I mGuiBackendFlags_HasMouseCursors)
};
Абсолютно все флаги рассматривать долго и неудобно, поэтому рассмотрим мы щас самые важные и удобные.

C++:
ImGuiWindowFlags_None
-Без флагов

C++:
ImGuiWindowFlags_NoTitleBar
-Убирает в окне (вверху) прямоугольник, где написано название окна.

C++:
ImGuiWindowFlags_NoResize
Не дает пользователю изменить размер окна, потянув за нижний правый край или зажав сторону окна.

C++:
ImGuiWindowFlags_NoMove
Позиция окна тепепь не меняется, если потянуть окно мышкой.

C++:
ImGuiWindowFlags_NoScrollbar
При переполнении элементов в окне, будет появлятся скролбар для прокрутки, флаг это отключает .

C++:
ImGuiWindowFlags_NoScrollWithMouse
Тоже самое что сверху, но вплане прокрутки колёсиком мыши.

C++:
ImGuiWindowFlags_NoCollapse
Один из самых главных флагов для меню, который не дает свернуть (Минимизировать) окно.

Больше об этом можете почитать -
https://www.blast.hk/threads/3021 (noad)

Следущие флаги разбирать не буду, но если у вас есть хоть чуток мозга, то вы поймете как все работает...
×Забыл упомянуть, что перед созданием окна, вы должны указать его размер и позицию.
Перед Begin :
C++:
ImGui::SetNextWindowPos( ImVec2 pos );
ImGui::SetNextWindowSize( ImVec2 size );
Думаю понятно, что каждая из функций делает.
Сейчас расскажу, как работает расположение объектов в окне.
Для этого используется функция
C++:
ImGui::SetCursorPos(ImVec2 pos);
Не стоить путать курсор в имгуи, с курсорсом мыши.
В имгуи существует так сказать некая кисточка, с позиции которой рисуются элементы окна. Например при позиции курсора - 0, 0. Отрсовка будет начинаться в самом вверху слева.
C++:
ImGui::GetCursorPos()
Возращает позицию курсора.
Курсор очень полезная вещь, ведь можно распологать что либо из элементов без установки точной позиции в окне.
Забыл сказать, минимальная позиция курсора окна начинается с его позиции. А максимальная - конец окна.

Перейдем к элементам..
Рассмотрим эти элементы -
C++:
ImGui::Button("Title", ImVec2 size );
ImGui::Checkbox("Title", &bool_var);
ImGui::SliderInt("Title", &int_var, val, max);
ImGui::Combo("Title", &int_var, text[], size);
ImGui::BeginChild("Title", ImVec2 size, bool outline) ;
Абсолютно все элементы без исключения рисуются на текущем месте курсора (Кисти). При их создании, он смещается ровно на размер прошлого объекта по Y. То есть сделав 2 кнопки. Вторая кнопка будет под первой.
Что бы сделать 2 элемента на 1 линии, вы можете использовать SameLine() который сдвигает курсор на X размера вбок. Это будет понятнее на практике.

> Button
C++:
ImGui::Button("Title", ImVec2 size);
Создает кнопку а текущем окне, как не странно. Текст кнопки расположен роано по середине кнопки. А размер кнопки можно указать в пикселях с помощью ImVec2. В первом аргументе название кнопки. При нажатии кнопка возвращает
C++:
true
, иначе
C++:
false
.
Пример:
C++:
if (ImGui::Button("Load", ImVec2(130, 30))
  // do smth
C++:
if (ImGui::Button("Some Button")) {
    ... // код, вызываемый при нажатии кнопки
}

> Checkbox
C++:
ImGui::Checkbox("Title", &bool_);
Создает чекбокс-переключатель, который при активации будет менять второй аргумент (bool, используя оператор указания "&" ) на
C++:
true
, иначе
C++:
false
.
Первый аргумент - название.
Пример:
C++:
ImGui::Checkbox("Enable", &cfg.aimbot))

> Slider
C++:
ImGui::SliderInt("Title", &int_, 0, 100);
ImGui::SliderFloat("Title", &float_, 0, 100);
Создает слайдер а текущем окне. Все что вам нужно пока знать, что есть 2 типа ( на самом деле больше ) слайдеров :
C++:
int
,
C++:
float
.
Первый тип меняет интеджер значение второго аргумента, второй флот значение. (используя оператор указания "&" )
Первый аргумент - название.
Третий - минимальное значение. Откуда будет начинаться слайдер, и четвёртый - до куда.
Пример:
C++:
static int i;
ImGui::SliderInt("Hitchance", &i, 0, 100))
Вообще у слайдера есть еще аргументы, но пока их разбирать не буду.
Подобнее о элементах сверху :

> Combo
C++:
ImGui::Combo("Title", &int_var, text[], size);
Первый аргумент - название.
Второй, значение которое будет меняться при выборе. Как в примерах выше. Третее это содержание комбо. Какие элементы будут в комбо :
Используйте массив из const char*
C++:
const char* out[] {"Python", "Java", "C++" }
Следущий аргумент просто вписываем ARRAYSIZE( наш массив )
Пример:
C++:
const char* w[] {"Ak-47", "Awp", "Scout"};
ImGui::Combo("Weapon", &cfg.weapon, w, ARRAYSIZE(w) );

>BeginChild и EndChild
Создаёт окно внутри другого, грубо говоря. Чайлд, доп место для элементов. Дает возможность разделить все в нужные подгруппы.
C++:
ImGui::BeginChild("General", ImVec2(130, 500), true );
//какие нить элементы
ImGui::EndChild();
Первый аргумент - название чайлда.
Второй аргумент - его размер.
Как и во всех случаях, рисуется на позиции курсора.
Третий аргумент отвечает за оутлайн чалда, он смещает все элементы в зависимости от вашего по нужному паддингу. Лучше всегда ставить true.
После растановки элементов в чайлде, закройте его.

Так же у нас имеется >Text
C++:
ImGui::Text("Im so good");
Я думаю тут пояснений не надо.

Подробнее о комбо и элементах, о которых я не рассказал :

Полезные источники если че то не понятно :
Использование ImGui с SFML для создания инструментов для разработки игр (noad)
ocornut/imgui (noad)

Следущее что хотел бы задеть, это стили.
В имгуи каждый элемент имеет цвет, который не надо вручную менять в функции. Это реализовано просто.
Вы просто меняется из списка нужный вам цвет или параметр.
Сначала получим текущий стиль.
C++:
auto& style = ImGui::GetStyle();
Затем получаем цвет и меняем его. Например:
C++:
style.Colors[ImGuiCol_Text] = ImColor(255, 0, 0);
Цветов довольно много. Вот весь список для понимания :
C++:
enum ImGuiCol_
{
    ImGuiCol_Text,
    ImGuiCol_TextDisabled,
    ImGuiCol_WindowBg, // Background of normal windows
    ImGuiCol_ChildBg, // Background of child windows
    ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows
    ImGuiCol_Border,
    ImGuiCol_BorderShadow,
    ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input
    ImGuiCol_FrameBgHovered,
    ImGuiCol_FrameBgActive,
    ImGuiCol_TitleBg,
    ImGuiCol_TitleBgActive,
    ImGuiCol_TitleBgCollapsed,
    ImGuiCol_MenuBarBg,
    ImGuiCol_ScrollbarBg,
    ImGuiCol_ScrollbarGrab,
    ImGuiCol_ScrollbarGrabHovered,
    ImGuiCol_ScrollbarGrabActive,
    ImGuiCol_CheckMark,
    ImGuiCol_SliderGrab,
    ImGuiCol_SliderGrabActive,
    ImGuiCol_Button,
    ImGuiCol_ButtonHovered,
    ImGuiCol_ButtonActive,
    ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem
    ImGuiCol_HeaderHovered,
    ImGuiCol_HeaderActive,
    ImGuiCol_Separator,
    ImGuiCol_SeparatorHovered,
    ImGuiCol_SeparatorActive,
    ImGuiCol_ResizeGrip,
    ImGuiCol_ResizeGripHovered,
    ImGuiCol_ResizeGripActive,
    ImGuiCol_Tab,
    ImGuiCol_TabHovered,
    ImGuiCol_TabActive,
    ImGuiCol_TabUnfocused,
    ImGuiCol_TabUnfocusedActive,
    ImGuiCol_PlotLines,
    ImGuiCol_PlotLinesHovered,
    ImGuiCol_PlotHistogram,
    ImGuiCol_PlotHistogramHovered,
    ImGuiCol_TableHeaderBg, // Table header background
    ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here)
    ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here)
    ImGuiCol_TableRowBg, // Table row background (even rows)
    ImGuiCol_TableRowBgAlt, // Table row background (odd rows)
    ImGuiCol_TextSelectedBg,
    ImGuiCol_DragDropTarget,
    ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item
    ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
    ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active
    ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active
    ImGuiCol_COUNT
};
Как видим, цвета стиля понятные и удобные. Обращаемся к массиву из цветов к одному из элементов енума и меняем нужный цвет.
Для полного понимания работы стилей в имгуи, вы можете скачать программу ImGui Example.
more : An introduction to the Dear ImGui library (noad)
Кроме цветов у нас есть и параметры размещения и тд. Вот они:
C++:
struct ImGuiStyle
{
    float Alpha; // Global alpha applies to everything in Dear ImGui.
    ImVec2 WindowPadding; // Padding within a window.
    float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
    float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints().
    ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
    ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left.
    float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
    float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)
    float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets).
    float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).
    float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines.
    ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label).
    ImVec2 CellPadding; // Padding within a table cell
    ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
    float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
    float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
    float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar.
    float ScrollbarRounding; // Radius of grab corners for scrollbar.
    float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar.
    float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
    float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
    float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
    float TabBorderSize; // Thickness of border around tabs.
    float TabMinWidthForCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
    ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
    ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered).
    ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
    ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
    ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly!
    float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
    bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).
    bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList).
    bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).
    float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
    float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
    ImVec4 Colors[ImGuiCol_COUNT];

    IMGUI_API ImGuiStyle();
    IMGUI_API void ScaleAllSizes(float scale_factor);
};

Это все познается на практике, но пару моментов хотел бы уяснить :
C++:
Alpha
- Прозрачность окна.
float. Максимальное значение = 1.f

C++:
ItemSpacing
- Как далеко будут находится объекты друг от друга. ImVec2(x, y)

C++:
WindowPadding
- Грубо говоря, как далеко элементы внутри окна будут находится. ImVec2
Эти настройки находятся внутри самого стайла. GetStyle();
 
Последнее редактирование:
  • colby57
  • UNEXPECTED_KERNEL_MODE_TRAP_M (1000007f)
  • 155
  • 2
  • 238
Часть 1 :
Заранее скажу, что гайд не полный даже близко, и я много чего не сказал.
Привет. Всех рад видеть в треде о базовых пониманиях при работе в ImGui.
Сначала я бы хотел уяснить, что я буду рассматривать последнюю версию фреймворка. Имгуи используется для создания интерфейса программ, меню или другие визуальные функции. Думаю не стоит тут зацикливаться. Приступим к практике....
Сначала разберём классы в имгуи для работы :
C++:
ImVec2(x, y)
ImVec4(x, y, w, h)
ImColor(r, g, b, a)

>ImVec2 - Используется для задачи позиции, размера объекта или чего либо. Деструктор - ImVec2(float x, float y);
>ImVec4 - используется для установки цвета обьекта (редко), и для установки чего либо с 4 аргументами.
Деструктор - ImVec4(float x, float y, float w, float h); PS: для установки цвета имеет максимальное значение 1.f. Пример:
ImVec4(1.f, 0.2f, 0.1f)
>ImColor - используется для установки только цвета для объектов и тд. Деструктор - ImColor(float red, float green, float blue, float alpha);
Пример : ImColor(37, 73, 243)
>Это близко не все, я разобрал самые основные.
Хотел бы сразу предупредить, что создавать элементы с одинаковыми именами не стоит, тк это сломает имгуи.
Первое что мы должны сделать, это создать окно. Процесс создания контекста и др рассматривать не буду.
C++:
ImGui::Begin("Название окна", nullptr, (int) flags)

C++:
ImGui::Begin("p2chack", nullptr, 0)
//элементы и тд.
ImGui::End();
Стоит сказать, что обязательно вконце окна, после всего прописать End, что бы фреймворк понял, что мы закончили отрсовку элементов на этом окне
1. Первый аргумент в функции как не странно отвечат за название окна.
2.Второй аргумент это переменная bool, которая будет влиять на открытие или закрытие окна. Оно так же может меняться через само окно,если неправильно настроить флаги. Можем ставить nullptr если нас этот вопрос не ебет.
3. Третий аргумент как раз таки меняет внешний вид окна и придаёт ему какие либо изменения. Рассмотрим по подробнее. флаги здесь реализованы через енум, который содержит название флагов.
C++:
enum ImGuiWindowFlags_
{
    ImGuiWindowFlags_None                   = 0,
    ImGuiWindowFlags_NoTitleBar             = 1 << 0,   // Disable title-bar
    ImGuiWindowFlags_NoResize               = 1 << 1,   // Disable user resizing with the lower-right grip
    ImGuiWindowFlags_NoMove                 = 1 << 2,   // Disable user moving the window
    ImGuiWindowFlags_NoScrollbar            = 1 << 3,   // Disable scrollbars (window can still scroll with mouse or programmatically)
    ImGuiWindowFlags_NoScrollWithMouse      = 1 << 4,   // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.
    ImGuiWindowFlags_NoCollapse             = 1 << 5,   // Disable user collapsing window by double-clicking on it
    ImGuiWindowFlags_AlwaysAutoResize       = 1 << 6,   // Resize every window to its content every frame
    ImGuiWindowFlags_NoBackground           = 1 << 7,   // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f).
    ImGuiWindowFlags_NoSavedSettings        = 1 << 8,   // Never load/save settings in .ini file
    ImGuiWindowFlags_NoMouseInputs          = 1 << 9,   // Disable catching mouse, hovering test with pass through.
    ImGuiWindowFlags_MenuBar                = 1 << 10,  // Has a menu-bar
    ImGuiWindowFlags_HorizontalScrollbar    = 1 << 11,  // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section.
    ImGuiWindowFlags_NoFocusOnAppearing     = 1 << 12,  // Disable taking focus when transitioning from hidden to visible state
    ImGuiWindowFlags_NoBringToFrontOnFocus  = 1 << 13,  // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)
    ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14,  // Always show vertical scrollbar (even if ContentSize.y < Size.y)
    ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15,  // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
    ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16,  // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)
    ImGuiWindowFlags_NoNavInputs            = 1 << 18,  // No gamepad/keyboard navigation within the window
    ImGuiWindowFlags_NoNavFocus             = 1 << 19,  // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
    ImGuiWindowFlags_UnsavedDocument        = 1 << 20,  // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. When used in a tab/docking context, tab is selected on closure and closure is deferred by one frame to allow code to cancel the closure (with a confirmation popup, etc.) without flicker.
    ImGuiWindowFlags_NoNav                  = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,
    ImGuiWindowFlags_NoDecoration           = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse,
    ImGuiWindowFlags_NoInputs               = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,

    // [Internal]
    ImGuiWindowFlags_NavFlattened           = 1 << 23,  // [BETA] Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!)
    ImGuiWindowFlags_ChildWindow            = 1 << 24,  // Don't use! For internal use by BeginChild()
    ImGuiWindowFlags_Tooltip                = 1 << 25,  // Don't use! For internal use by BeginTooltip()
    ImGuiWindowFlags_Popup                  = 1 << 26,  // Don't use! For internal use by BeginPopup()
    ImGuiWindowFlags_Modal                  = 1 << 27,  // Don't use! For internal use by BeginPopupModal()
    ImGuiWindowFlags_ChildMenu              = 1 << 28   // Don't use! For internal use by BeginMenu()

    // [Obsolete]
    //ImGuiWindowFlags_ResizeFromAnySide    = 1 << 17,  // --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by backend (io.BackendFlags & I mGuiBackendFlags_HasMouseCursors)
};
Абсолютно все флаги рассматривать долго и неудобно, поэтому рассмотрим мы щас самые важные и удобные.

C++:
ImGuiWindowFlags_None
-Без флагов

C++:
ImGuiWindowFlags_NoTitleBar
-Убирает в окне (вверху) прямоугольник, где написано название окна.

C++:
ImGuiWindowFlags_NoResize
Не дает пользователю изменить размер окна, потянув за нижний правый край или зажав сторону окна.

C++:
ImGuiWindowFlags_NoMove
Позиция окна тепепь не меняется, если потянуть окно мышкой.

C++:
ImGuiWindowFlags_NoScrollbar
При переполнении элементов в окне, будет появлятся скролбар для прокрутки, флаг это отключает .

C++:
ImGuiWindowFlags_NoScrollWithMouse
Тоже самое что сверху, но вплане прокрутки колёсиком мыши.

C++:
ImGuiWindowFlags_NoCollapse
Один из самых главных флагов для меню, который не дает свернуть (Минимизировать) окно.

Больше об этом можете почитать -
https://www.blast.hk/threads/3021 (noad)

Следущие флаги разбирать не буду, но если у вас есть хоть чуток мозга, то вы поймете как все работает...
×Забыл упомянуть, что перед созданием окна, вы должны указать его размер и позицию.
Перед Begin :
C++:
ImGui::SetNextWindowPos( ImVec2 pos );
ImGui::SetNextWindowSize( ImVec2 size );
Думаю понятно, что каждая из функций делает.
Сейчас расскажу, как работает расположение объектов в окне.
Для этого используется функция
C++:
ImGui::SetCursorPos(ImVec2 pos);
Не стоить путать курсор в имгуи, с курсорсом мыши.
В имгуи существует так сказать некая кисточка, с позиции которой рисуются элементы окна. Например при позиции курсора - 0, 0. Отрсовка будет начинаться в самом вверху слева.
C++:
ImGui::GetCursorPos()
Возращает позицию курсора.
Курсор очень полезная вещь, ведь можно распологать что либо из элементов без установки точной позиции в окне.
Забыл сказать, минимальная позиция курсора окна начинается с его позиции. А максимальная - конец окна.

Перейдем к элементам..
Рассмотрим эти элементы -
C++:
ImGui::Button("Title", ImVec2 size );
ImGui::Checkbox("Title", &bool_var);
ImGui::SliderInt("Title", &int_var, val, max);
ImGui::Combo("Title", &int_var, text[], size);
ImGui::BeginChild("Title", ImVec2 size, bool outline) ;
Абсолютно все элементы без исключения рисуются на текущем месте курсора (Кисти). При их создании, он смещается ровно на размер прошлого объекта по Y. То есть сделав 2 кнопки. Вторая кнопка будет под первой.
Что бы сделать 2 элемента на 1 линии, вы можете использовать SameLine() который сдвигает курсор на X размера вбок. Это будет понятнее на практике.

> Button
C++:
ImGui::Button("Title", ImVec2 size);
Создает кнопку а текущем окне, как не странно. Текст кнопки расположен роано по середине кнопки. А размер кнопки можно указать в пикселях с помощью ImVec2. В первом аргументе название кнопки. При нажатии кнопка возвращает
C++:
true
, иначе
C++:
false
.
Пример:
C++:
if (ImGui::Button("Load", ImVec2(130, 30))
  // do smth
C++:
if (ImGui::Button("Some Button")) {
    ... // код, вызываемый при нажатии кнопки
}

> Checkbox
C++:
ImGui::Checkbox("Title", &bool_);
Создает чекбокс-переключатель, который при активации будет менять второй аргумент (bool, используя оператор указания "&" ) на
C++:
true
, иначе
C++:
false
.
Первый аргумент - название.
Пример:
C++:
ImGui::Checkbox("Enable", &cfg.aimbot))

> Slider
C++:
ImGui::SliderInt("Title", &int_, 0, 100);
ImGui::SliderFloat("Title", &float_, 0, 100);
Создает слайдер а текущем окне. Все что вам нужно пока знать, что есть 2 типа ( на самом деле больше ) слайдеров :
C++:
int
,
C++:
float
.
Первый тип меняет интеджер значение второго аргумента, второй флот значение. (используя оператор указания "&" )
Первый аргумент - название.
Третий - минимальное значение. Откуда будет начинаться слайдер, и четвёртый - до куда.
Пример:
C++:
static int i;
ImGui::SliderInt("Hitchance", &i, 0, 100))
Вообще у слайдера есть еще аргументы, но пока их разбирать не буду.
Подобнее о элементах сверху :

> Combo
C++:
ImGui::Combo("Title", &int_var, text[], size);
Первый аргумент - название.
Второй, значение которое будет меняться при выборе. Как в примерах выше. Третее это содержание комбо. Какие элементы будут в комбо :
Используйте массив из const char*
C++:
const char* out[] {"Python", "Java", "C++" }
Следущий аргумент просто вписываем ARRAYSIZE( наш массив )
Пример:
C++:
const char* w[] {"Ak-47", "Awp", "Scout"};
ImGui::Combo("Weapon", &cfg.weapon, w, ARRAYSIZE(w) );

>BeginChild и EndChild
Создаёт окно внутри другого, грубо говоря. Чайлд, доп место для элементов. Дает возможность разделить все в нужные подгруппы.
C++:
ImGui::BeginChild("General", ImVec2(130, 500), true );
//какие нить элементы
ImGui::EndChild();
Первый аргумент - название чайлда.
Второй аргумент - его размер.
Как и во всех случаях, рисуется на позиции курсора.
Третий аргумент отвечает за оутлайн чалда, он смещает все элементы в зависимости от вашего по нужному паддингу. Лучше всегда ставить true.
После растановки элементов в чайлде, закройте его.

Так же у нас имеется >Text
C++:
ImGui::Text("Im so good");
Я думаю тут пояснений не надо.

Подробнее о комбо и элементах, о которых я не рассказал :

Полезные источники если че то не понятно :
Использование ImGui с SFML для создания инструментов для разработки игр (noad)
ocornut/imgui (noad)

Следущее что хотел бы задеть, это стили.
В имгуи каждый элемент имеет цвет, который не надо вручную менять в функции. Это реализовано просто.
Вы просто меняется из списка нужный вам цвет или параметр.
Сначала получим текущий стиль.
C++:
auto& style = ImGui::GetStyle();
Затем получаем цвет и меняем его. Например:
C++:
style.Colors[ImGuiCol_Text] = ImColor(255, 0, 0);
Цветов довольно много. Вот весь список для понимания :
C++:
enum ImGuiCol_
{
    ImGuiCol_Text,
    ImGuiCol_TextDisabled,
    ImGuiCol_WindowBg, // Background of normal windows
    ImGuiCol_ChildBg, // Background of child windows
    ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows
    ImGuiCol_Border,
    ImGuiCol_BorderShadow,
    ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input
    ImGuiCol_FrameBgHovered,
    ImGuiCol_FrameBgActive,
    ImGuiCol_TitleBg,
    ImGuiCol_TitleBgActive,
    ImGuiCol_TitleBgCollapsed,
    ImGuiCol_MenuBarBg,
    ImGuiCol_ScrollbarBg,
    ImGuiCol_ScrollbarGrab,
    ImGuiCol_ScrollbarGrabHovered,
    ImGuiCol_ScrollbarGrabActive,
    ImGuiCol_CheckMark,
    ImGuiCol_SliderGrab,
    ImGuiCol_SliderGrabActive,
    ImGuiCol_Button,
    ImGuiCol_ButtonHovered,
    ImGuiCol_ButtonActive,
    ImGuiCol_Header, // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem
    ImGuiCol_HeaderHovered,
    ImGuiCol_HeaderActive,
    ImGuiCol_Separator,
    ImGuiCol_SeparatorHovered,
    ImGuiCol_SeparatorActive,
    ImGuiCol_ResizeGrip,
    ImGuiCol_ResizeGripHovered,
    ImGuiCol_ResizeGripActive,
    ImGuiCol_Tab,
    ImGuiCol_TabHovered,
    ImGuiCol_TabActive,
    ImGuiCol_TabUnfocused,
    ImGuiCol_TabUnfocusedActive,
    ImGuiCol_PlotLines,
    ImGuiCol_PlotLinesHovered,
    ImGuiCol_PlotHistogram,
    ImGuiCol_PlotHistogramHovered,
    ImGuiCol_TableHeaderBg, // Table header background
    ImGuiCol_TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here)
    ImGuiCol_TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here)
    ImGuiCol_TableRowBg, // Table row background (even rows)
    ImGuiCol_TableRowBgAlt, // Table row background (odd rows)
    ImGuiCol_TextSelectedBg,
    ImGuiCol_DragDropTarget,
    ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item
    ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB
    ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active
    ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active
    ImGuiCol_COUNT
};
Как видим, цвета стиля понятные и удобные. Обращаемся к массиву из цветов к одному из элементов енума и меняем нужный цвет.
Для полного понимания работы стилей в имгуи, вы можете скачать программу ImGui Example.
more : An introduction to the Dear ImGui library (noad)
Кроме цветов у нас есть и параметры размещения и тд. Вот они:
C++:
struct ImGuiStyle
{
    float Alpha; // Global alpha applies to everything in Dear ImGui.
    ImVec2 WindowPadding; // Padding within a window.
    float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
    float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints().
    ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
    ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left.
    float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
    float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)
    float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets).
    float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).
    float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
    ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines.
    ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label).
    ImVec2 CellPadding; // Padding within a table cell
    ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
    float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
    float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
    float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar.
    float ScrollbarRounding; // Radius of grab corners for scrollbar.
    float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar.
    float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
    float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
    float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
    float TabBorderSize; // Thickness of border around tabs.
    float TabMinWidthForCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
    ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
    ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered).
    ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
    ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
    ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly!
    float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
    bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).
    bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList).
    bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).
    float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
    float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
    ImVec4 Colors[ImGuiCol_COUNT];

    IMGUI_API ImGuiStyle();
    IMGUI_API void ScaleAllSizes(float scale_factor);
};

Это все познается на практике, но пару моментов хотел бы уяснить :
C++:
Alpha
- Прозрачность окна.
float. Максимальное значение = 1.f

C++:
ItemSpacing
- Как далеко будут находится объекты друг от друга. ImVec2(x, y)

C++:
WindowPadding
- Грубо говоря, как далеко элементы внутри окна будут находится. ImVec2
Эти настройки находятся внутри самого стайла. GetStyle();

Автору печеньку за гайд, но у тебя почему-то деструктор имеет вид конструктора с параметрами
 
Активность
Пока что здесь никого нет
Сверху Снизу