├── misc ├── fonts │ ├── DroidSans.ttf │ ├── ProggyTiny.ttf │ ├── Karla-Regular.ttf │ ├── ProggyClean.ttf │ ├── Roboto-Medium.ttf │ ├── Cousine-Regular.ttf │ └── binary_to_compressed_c.cpp ├── debuggers │ ├── README.txt │ ├── imgui.gdb │ ├── imgui.natstepfilter │ └── imgui.natvis ├── cpp │ ├── README.txt │ ├── imgui_stdlib.h │ └── imgui_stdlib.cpp ├── README.txt ├── single_file │ └── imgui_single_file.h └── freetype │ ├── README.md │ └── imgui_freetype.h ├── docs ├── README.md ├── BACKENDS.md ├── CONTRIBUTING.md ├── EXAMPLES.md └── FONTS.md ├── backends ├── vulkan │ ├── generate_spv.sh │ ├── glsl_shader.frag │ └── glsl_shader.vert ├── imgui_impl_dx9.h ├── imgui_impl_dx10.h ├── imgui_impl_dx11.h ├── imgui_impl_sdlrenderer.h ├── imgui_impl_wgpu.h ├── imgui_impl_android.h ├── imgui_impl_opengl2.h ├── imgui_impl_allegro5.h ├── imgui_impl_osx.h ├── imgui_impl_sdl3.h ├── imgui_impl_sdl2.h ├── imgui_impl_dx12.h ├── imgui_impl_glut.h ├── imgui_impl_opengl3.h ├── imgui_impl_win32.h ├── imgui_impl_metal.h ├── imgui_impl_glfw.h ├── imgui_impl_vulkan.h ├── imgui_impl_sdlrenderer.cpp ├── imgui_impl_glut.cpp ├── imgui_impl_android.cpp ├── imgui_impl_opengl2.cpp └── imgui_impl_dx9.cpp └── imconfig.h /misc/fonts/DroidSans.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/current/deadcell-menu/HEAD/misc/fonts/DroidSans.ttf -------------------------------------------------------------------------------- /misc/fonts/ProggyTiny.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/current/deadcell-menu/HEAD/misc/fonts/ProggyTiny.ttf -------------------------------------------------------------------------------- /misc/fonts/Karla-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/current/deadcell-menu/HEAD/misc/fonts/Karla-Regular.ttf -------------------------------------------------------------------------------- /misc/fonts/ProggyClean.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/current/deadcell-menu/HEAD/misc/fonts/ProggyClean.ttf -------------------------------------------------------------------------------- /misc/fonts/Roboto-Medium.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/current/deadcell-menu/HEAD/misc/fonts/Roboto-Medium.ttf -------------------------------------------------------------------------------- /misc/fonts/Cousine-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/current/deadcell-menu/HEAD/misc/fonts/Cousine-Regular.ttf -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Deadcell's concept brought to life 2 | Design credits go to https://github.com/EternityX/DEADCELL-GUI 3 | 4 | Preview - 5 | 6 | 7 | ![image](https://user-images.githubusercontent.com/4403000/230327126-c4c0a408-07c5-4616-9100-14e13b10fc75.png) 8 | -------------------------------------------------------------------------------- /backends/vulkan/generate_spv.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ## -V: create SPIR-V binary 3 | ## -x: save binary output as text-based 32-bit hexadecimal numbers 4 | ## -o: output file 5 | glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag 6 | glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert 7 | -------------------------------------------------------------------------------- /backends/vulkan/glsl_shader.frag: -------------------------------------------------------------------------------- 1 | #version 450 core 2 | layout(location = 0) out vec4 fColor; 3 | 4 | layout(set=0, binding=0) uniform sampler2D sTexture; 5 | 6 | layout(location = 0) in struct { 7 | vec4 Color; 8 | vec2 UV; 9 | } In; 10 | 11 | void main() 12 | { 13 | fColor = In.Color * texture(sTexture, In.UV.st); 14 | } 15 | -------------------------------------------------------------------------------- /misc/debuggers/README.txt: -------------------------------------------------------------------------------- 1 | 2 | HELPER FILES FOR POPULAR DEBUGGERS 3 | 4 | imgui.gdb 5 | GDB: disable stepping into trivial functions. 6 | (read comments inside file for details) 7 | 8 | imgui.natstepfilter 9 | Visual Studio Debugger: disable stepping into trivial functions. 10 | (read comments inside file for details) 11 | 12 | imgui.natvis 13 | Visual Studio Debugger: describe Dear ImGui types for better display. 14 | With this, types like ImVector<> will be displayed nicely in the debugger. 15 | (read comments inside file for details) 16 | 17 | -------------------------------------------------------------------------------- /backends/vulkan/glsl_shader.vert: -------------------------------------------------------------------------------- 1 | #version 450 core 2 | layout(location = 0) in vec2 aPos; 3 | layout(location = 1) in vec2 aUV; 4 | layout(location = 2) in vec4 aColor; 5 | 6 | layout(push_constant) uniform uPushConstant { 7 | vec2 uScale; 8 | vec2 uTranslate; 9 | } pc; 10 | 11 | out gl_PerVertex { 12 | vec4 gl_Position; 13 | }; 14 | 15 | layout(location = 0) out struct { 16 | vec4 Color; 17 | vec2 UV; 18 | } Out; 19 | 20 | void main() 21 | { 22 | Out.Color = aColor; 23 | Out.UV = aUV; 24 | gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1); 25 | } 26 | -------------------------------------------------------------------------------- /misc/debuggers/imgui.gdb: -------------------------------------------------------------------------------- 1 | # GDB configuration to aid debugging experience 2 | 3 | # To enable these customizations edit $HOME/.gdbinit (or ./.gdbinit if local gdbinit is enabled) and add: 4 | # add-auto-load-safe-path /path/to/imgui.gdb 5 | # source /path/to/imgui.gdb 6 | # 7 | # More Information at: 8 | # * https://sourceware.org/gdb/current/onlinedocs/gdb/gdbinit-man.html 9 | # * https://sourceware.org/gdb/current/onlinedocs/gdb/Init-File-in-the-Current-Directory.html#Init-File-in-the-Current-Directory 10 | 11 | # Disable stepping into trivial functions 12 | skip -rfunction Im(Vec2|Vec4|Strv|Vector|Span)::.+ 13 | -------------------------------------------------------------------------------- /misc/cpp/README.txt: -------------------------------------------------------------------------------- 1 | 2 | imgui_stdlib.h + imgui_stdlib.cpp 3 | InputText() wrappers for C++ standard library (STL) type: std::string. 4 | This is also an example of how you may wrap your own similar types. 5 | 6 | imgui_scoped.h 7 | [Experimental, not currently in main repository] 8 | Additional header file with some RAII-style wrappers for common Dear ImGui functions. 9 | Try by merging: https://github.com/ocornut/imgui/pull/2197 10 | Discuss at: https://github.com/ocornut/imgui/issues/2096 11 | 12 | See more C++ related extension (fmt, RAII, syntaxis sugar) on Wiki: 13 | https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness 14 | -------------------------------------------------------------------------------- /misc/README.txt: -------------------------------------------------------------------------------- 1 | 2 | misc/cpp/ 3 | InputText() wrappers for C++ standard library (STL) type: std::string. 4 | This is also an example of how you may wrap your own similar types. 5 | 6 | misc/debuggers/ 7 | Helper files for popular debuggers. 8 | With the .natvis file, types like ImVector<> will be displayed nicely in Visual Studio debugger. 9 | 10 | misc/fonts/ 11 | Fonts loading/merging instructions (e.g. How to handle glyph ranges, how to merge icons fonts). 12 | Command line tool "binary_to_compressed_c" to create compressed arrays to embed data in source code. 13 | Suggested fonts and links. 14 | 15 | misc/freetype/ 16 | Font atlas builder/rasterizer using FreeType instead of stb_truetype. 17 | Benefit from better FreeType rasterization, in particular for small fonts. 18 | 19 | misc/single_file/ 20 | Single-file header stub. 21 | We use this to validate compiling all *.cpp files in a same compilation unit. 22 | Users of that technique (also called "Unity builds") can generally provide this themselves, 23 | so we don't really recommend you use this in your projects. 24 | -------------------------------------------------------------------------------- /misc/single_file/imgui_single_file.h: -------------------------------------------------------------------------------- 1 | // dear imgui: single-file wrapper include 2 | // We use this to validate compiling all *.cpp files in a same compilation unit. 3 | // Users of that technique (also called "Unity builds") can generally provide this themselves, 4 | // so we don't really recommend you use this in your projects. 5 | 6 | // Do this: 7 | // #define IMGUI_IMPLEMENTATION 8 | // Before you include this file in *one* C++ file to create the implementation. 9 | // Using this in your project will leak the contents of imgui_internal.h and ImVec2 operators in this compilation unit. 10 | 11 | #ifdef IMGUI_IMPLEMENTATION 12 | #define IMGUI_DEFINE_MATH_OPERATORS 13 | #endif 14 | 15 | #include "../../imgui.h" 16 | #ifdef IMGUI_ENABLE_FREETYPE 17 | #include "../../misc/freetype/imgui_freetype.h" 18 | #endif 19 | 20 | #ifdef IMGUI_IMPLEMENTATION 21 | #include "../../imgui.cpp" 22 | #include "../../imgui_demo.cpp" 23 | #include "../../imgui_draw.cpp" 24 | #include "../../imgui_tables.cpp" 25 | #include "../../imgui_widgets.cpp" 26 | #ifdef IMGUI_ENABLE_FREETYPE 27 | #include "../../misc/freetype/imgui_freetype.cpp" 28 | #endif 29 | #endif 30 | -------------------------------------------------------------------------------- /misc/cpp/imgui_stdlib.h: -------------------------------------------------------------------------------- 1 | // dear imgui: wrappers for C++ standard library (STL) types (std::string, etc.) 2 | // This is also an example of how you may wrap your own similar types. 3 | 4 | // Changelog: 5 | // - v0.10: Initial version. Added InputText() / InputTextMultiline() calls with std::string 6 | 7 | // See more C++ related extension (fmt, RAII, syntaxis sugar) on Wiki: 8 | // https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness 9 | 10 | #pragma once 11 | 12 | #include 13 | 14 | namespace ImGui 15 | { 16 | // ImGui::InputText() with std::string 17 | // Because text input needs dynamic resizing, we need to setup a callback to grow the capacity 18 | IMGUI_API bool InputText(const char* label, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); 19 | IMGUI_API bool InputTextMultiline(const char* label, std::string* str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); 20 | IMGUI_API bool InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); 21 | } 22 | -------------------------------------------------------------------------------- /backends/imgui_impl_dx9.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for DirectX9 2 | // This needs to be used along with a Platform Backend (e.g. Win32) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 9 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 10 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 11 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 12 | 13 | #pragma once 14 | #include "imgui.h" // IMGUI_IMPL_API 15 | 16 | struct IDirect3DDevice9; 17 | 18 | IMGUI_IMPL_API bool ImGui_ImplDX9_Init(IDirect3DDevice9* device); 19 | IMGUI_IMPL_API void ImGui_ImplDX9_Shutdown(); 20 | IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame(); 21 | IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data); 22 | 23 | // Use if you want to reset your rendering device without losing Dear ImGui state. 24 | IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); 25 | IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); 26 | -------------------------------------------------------------------------------- /backends/imgui_impl_dx10.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for DirectX10 2 | // This needs to be used along with a Platform Backend (e.g. Win32) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 9 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 10 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 11 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 12 | 13 | #pragma once 14 | #include "imgui.h" // IMGUI_IMPL_API 15 | 16 | struct ID3D10Device; 17 | 18 | IMGUI_IMPL_API bool ImGui_ImplDX10_Init(ID3D10Device* device); 19 | IMGUI_IMPL_API void ImGui_ImplDX10_Shutdown(); 20 | IMGUI_IMPL_API void ImGui_ImplDX10_NewFrame(); 21 | IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data); 22 | 23 | // Use if you want to reset your rendering device without losing Dear ImGui state. 24 | IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects(); 25 | IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects(); 26 | -------------------------------------------------------------------------------- /backends/imgui_impl_dx11.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for DirectX11 2 | // This needs to be used along with a Platform Backend (e.g. Win32) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 9 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 10 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 11 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 12 | 13 | #pragma once 14 | #include "imgui.h" // IMGUI_IMPL_API 15 | 16 | struct ID3D11Device; 17 | struct ID3D11DeviceContext; 18 | 19 | IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context); 20 | IMGUI_IMPL_API void ImGui_ImplDX11_Shutdown(); 21 | IMGUI_IMPL_API void ImGui_ImplDX11_NewFrame(); 22 | IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data); 23 | 24 | // Use if you want to reset your rendering device without losing Dear ImGui state. 25 | IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects(); 26 | IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects(); 27 | -------------------------------------------------------------------------------- /misc/debuggers/imgui.natstepfilter: -------------------------------------------------------------------------------- 1 | 2 | 18 | 19 | 20 | 21 | 22 | 23 | (ImVec2|ImVec4|ImStrv)::.+ 24 | NoStepInto 25 | 26 | 27 | (ImVector|ImSpan).*::operator.+ 28 | NoStepInto 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /backends/imgui_impl_sdlrenderer.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for SDL_Renderer 2 | // (Requires: SDL 2.0.17+) 3 | 4 | // Important to understand: SDL_Renderer is an _optional_ component of SDL. 5 | // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. 6 | // If your application will want to render any non trivial amount of graphics other than UI, 7 | // please be aware that SDL_Renderer offers a limited graphic API to the end-user and it might 8 | // be difficult to step out of those boundaries. 9 | // However, we understand it is a convenient choice to get an app started easily. 10 | 11 | // Implemented features: 12 | // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! 13 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 14 | 15 | #pragma once 16 | #include "imgui.h" // IMGUI_IMPL_API 17 | 18 | struct SDL_Renderer; 19 | 20 | IMGUI_IMPL_API bool ImGui_ImplSDLRenderer_Init(SDL_Renderer* renderer); 21 | IMGUI_IMPL_API void ImGui_ImplSDLRenderer_Shutdown(); 22 | IMGUI_IMPL_API void ImGui_ImplSDLRenderer_NewFrame(); 23 | IMGUI_IMPL_API void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data); 24 | 25 | // Called by Init/NewFrame/Shutdown 26 | IMGUI_IMPL_API bool ImGui_ImplSDLRenderer_CreateFontsTexture(); 27 | IMGUI_IMPL_API void ImGui_ImplSDLRenderer_DestroyFontsTexture(); 28 | IMGUI_IMPL_API bool ImGui_ImplSDLRenderer_CreateDeviceObjects(); 29 | IMGUI_IMPL_API void ImGui_ImplSDLRenderer_DestroyDeviceObjects(); 30 | -------------------------------------------------------------------------------- /backends/imgui_impl_wgpu.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer for WebGPU 2 | // This needs to be used along with a Platform Binding (e.g. GLFW) 3 | // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.) 4 | 5 | // Implemented features: 6 | // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID! 7 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 8 | 9 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 10 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 11 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 12 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 13 | 14 | #pragma once 15 | #include "imgui.h" // IMGUI_IMPL_API 16 | #include 17 | 18 | IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format, WGPUTextureFormat depth_format = WGPUTextureFormat_Undefined); 19 | IMGUI_IMPL_API void ImGui_ImplWGPU_Shutdown(); 20 | IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame(); 21 | IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder); 22 | 23 | // Use if you want to reset your rendering device without losing Dear ImGui state. 24 | IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects(); 25 | IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects(); 26 | -------------------------------------------------------------------------------- /misc/freetype/README.md: -------------------------------------------------------------------------------- 1 | # imgui_freetype 2 | 3 | Build font atlases using FreeType instead of stb_truetype (which is the default font rasterizer). 4 |
by @vuhdo, @mikesart, @ocornut. 5 | 6 | ### Usage 7 | 8 | 1. Get latest FreeType binaries or build yourself (under Windows you may use vcpkg with `vcpkg install freetype --triplet=x64-windows`, `vcpkg integrate install`). 9 | 2. Add imgui_freetype.h/cpp alongside your project files. 10 | 3. Add `#define IMGUI_ENABLE_FREETYPE` in your [imconfig.h](https://github.com/ocornut/imgui/blob/master/imconfig.h) file 11 | 12 | ### About Gamma Correct Blending 13 | 14 | FreeType assumes blending in linear space rather than gamma space. 15 | See FreeType note for [FT_Render_Glyph](https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph). 16 | For correct results you need to be using sRGB and convert to linear space in the pixel shader output. 17 | The default Dear ImGui styles will be impacted by this change (alpha values will need tweaking). 18 | 19 | ### Testbed for toying with settings (for developers) 20 | 21 | See https://gist.github.com/ocornut/b3a9ecf13502fd818799a452969649ad 22 | 23 | ### Known issues 24 | 25 | - Oversampling settins are ignored but also not so much necessary with the higher quality rendering. 26 | 27 | ### Comparison 28 | 29 | Small, thin anti-aliased fonts typically benefit a lot from FreeType's hinting: 30 | ![comparing_font_rasterizers](https://user-images.githubusercontent.com/8225057/107550178-fef87f00-6bd0-11eb-8d09-e2edb2f0ccfc.gif) 31 | 32 | ### Colorful glyphs/emojis 33 | 34 | You can use the `ImGuiFreeTypeBuilderFlags_LoadColor` flag to load certain colorful glyphs. See the 35 | ["Using Colorful Glyphs/Emojis"](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md#using-colorful-glyphsemojis) section of FONTS.md. 36 | 37 | ![colored glyphs](https://user-images.githubusercontent.com/8225057/106171241-9dc4ba80-6191-11eb-8a69-ca1467b206d1.png) 38 | -------------------------------------------------------------------------------- /backends/imgui_impl_android.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Binding for Android native app 2 | // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3) 3 | 4 | // Implemented features: 5 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 6 | // Missing features: 7 | // [ ] Platform: Clipboard support. 8 | // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 9 | // [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. 10 | // Important: 11 | // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. 12 | // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446) 13 | // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446) 14 | 15 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 16 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 17 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 18 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 19 | 20 | #pragma once 21 | 22 | struct ANativeWindow; 23 | struct AInputEvent; 24 | 25 | IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window); 26 | IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event); 27 | IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown(); 28 | IMGUI_IMPL_API void ImGui_ImplAndroid_NewFrame(); 29 | -------------------------------------------------------------------------------- /backends/imgui_impl_opengl2.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline) 2 | // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! 6 | 7 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 8 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 9 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 10 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 11 | 12 | // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** 13 | // **Prefer using the code in imgui_impl_opengl3.cpp** 14 | // This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read. 15 | // If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more 16 | // complicated, will require your code to reset every single OpenGL attributes to their initial state, and might 17 | // confuse your GPU driver. 18 | // The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API. 19 | 20 | #pragma once 21 | #include "imgui.h" // IMGUI_IMPL_API 22 | 23 | IMGUI_IMPL_API bool ImGui_ImplOpenGL2_Init(); 24 | IMGUI_IMPL_API void ImGui_ImplOpenGL2_Shutdown(); 25 | IMGUI_IMPL_API void ImGui_ImplOpenGL2_NewFrame(); 26 | IMGUI_IMPL_API void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data); 27 | 28 | // Called by Init/NewFrame/Shutdown 29 | IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateFontsTexture(); 30 | IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyFontsTexture(); 31 | IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects(); 32 | IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects(); 33 | -------------------------------------------------------------------------------- /backends/imgui_impl_allegro5.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer + Platform Backend for Allegro 5 2 | // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 7 | // [X] Platform: Clipboard support (from Allegro 5.1.12) 8 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. 9 | // Issues: 10 | // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually. 11 | // [ ] Platform: Missing gamepad support. 12 | 13 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 14 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 15 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 16 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 17 | 18 | #pragma once 19 | #include "imgui.h" // IMGUI_IMPL_API 20 | 21 | struct ALLEGRO_DISPLAY; 22 | union ALLEGRO_EVENT; 23 | 24 | IMGUI_IMPL_API bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display); 25 | IMGUI_IMPL_API void ImGui_ImplAllegro5_Shutdown(); 26 | IMGUI_IMPL_API void ImGui_ImplAllegro5_NewFrame(); 27 | IMGUI_IMPL_API void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data); 28 | IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event); 29 | 30 | // Use if you want to reset your rendering device without losing Dear ImGui state. 31 | IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects(); 32 | IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects(); 33 | -------------------------------------------------------------------------------- /misc/debuggers/imgui.natvis: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 15 | 16 | 17 | {{Size={Size} Capacity={Capacity}}} 18 | 19 | 20 | Size 21 | Data 22 | 23 | 24 | 25 | 26 | 27 | {{Size={DataEnd-Data} }} 28 | 29 | 30 | DataEnd-Data 31 | Data 32 | 33 | 34 | 35 | 36 | 37 | {{x={x,g} y={y,g}}} 38 | 39 | 40 | 41 | {{x={x,g} y={y,g} z={z,g} w={w,g}}} 42 | 43 | 44 | 45 | {{Min=({Min.x,g} {Min.y,g}) Max=({Max.x,g} {Max.y,g}) Size=({Max.x-Min.x,g} {Max.y-Min.y,g})}} 46 | 47 | Min 48 | Max 49 | Max.x - Min.x 50 | Max.y - Min.y 51 | 52 | 53 | 54 | 55 | {{Name {Name,s} Active {(Active||WasActive)?1:0,d} Child {(Flags & 0x01000000)?1:0,d} Popup {(Flags & 0x04000000)?1:0,d} Hidden {(Hidden)?1:0,d}} 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /backends/imgui_impl_osx.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for OSX / Cocoa 2 | // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..) 3 | // - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac. 4 | // - Requires linking with the GameController framework ("-framework GameController"). 5 | 6 | // Implemented features: 7 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. 8 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 9 | // [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend). 10 | // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 11 | // [X] Platform: IME support. 12 | 13 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 14 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 15 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 16 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 17 | 18 | #include "imgui.h" // IMGUI_IMPL_API 19 | 20 | #ifdef __OBJC__ 21 | 22 | @class NSEvent; 23 | @class NSView; 24 | 25 | IMGUI_IMPL_API bool ImGui_ImplOSX_Init(NSView* _Nonnull view); 26 | IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); 27 | IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view); 28 | 29 | #endif 30 | 31 | //----------------------------------------------------------------------------- 32 | // C++ API 33 | //----------------------------------------------------------------------------- 34 | 35 | #ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS 36 | // #include 37 | #ifndef __OBJC__ 38 | 39 | IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view); 40 | IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown(); 41 | IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view); 42 | 43 | #endif 44 | #endif 45 | -------------------------------------------------------------------------------- /backends/imgui_impl_sdl3.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*) 2 | // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) 3 | // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) 4 | // (IMPORTANT: SDL 3.0.0 is NOT YET RELEASED. IT IS POSSIBLE THAT ITS SPECS/API WILL CHANGE BEFORE RELEASE) 5 | 6 | // Implemented features: 7 | // [X] Platform: Clipboard support. 8 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 9 | // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 10 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. 11 | // Missing features: 12 | // [x] Platform: Basic IME support. Position somehow broken in SDL3 + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. 13 | 14 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 15 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 16 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 17 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 18 | 19 | #pragma once 20 | #include "imgui.h" // IMGUI_IMPL_API 21 | 22 | struct SDL_Window; 23 | struct SDL_Renderer; 24 | typedef union SDL_Event SDL_Event; 25 | 26 | IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); 27 | IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window); 28 | IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window); 29 | IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window); 30 | IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); 31 | IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown(); 32 | IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame(); 33 | IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); 34 | -------------------------------------------------------------------------------- /backends/imgui_impl_sdl2.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for SDL2 2 | // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) 3 | // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.) 4 | 5 | // Implemented features: 6 | // [X] Platform: Clipboard support. 7 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 8 | // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 9 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. 10 | // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!. 11 | 12 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 13 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 14 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 15 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 16 | 17 | #pragma once 18 | #include "imgui.h" // IMGUI_IMPL_API 19 | 20 | struct SDL_Window; 21 | struct SDL_Renderer; 22 | typedef union SDL_Event SDL_Event; 23 | 24 | IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); 25 | IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window); 26 | IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window); 27 | IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window); 28 | IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); 29 | IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); 30 | IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(); 31 | IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); 32 | 33 | #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS 34 | static inline void ImGui_ImplSDL2_NewFrame(SDL_Window*) { ImGui_ImplSDL2_NewFrame(); } // 1.84: removed unnecessary parameter 35 | #endif 36 | -------------------------------------------------------------------------------- /backends/imgui_impl_dx12.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for DirectX12 2 | // This needs to be used along with a Platform Backend (e.g. Win32) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // Important: to compile on 32-bit systems, this backend requires code to be compiled with '#define ImTextureID ImU64'. 9 | // See imgui_impl_dx12.cpp file for details. 10 | 11 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 12 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 13 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 14 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 15 | 16 | #pragma once 17 | #include "imgui.h" // IMGUI_IMPL_API 18 | #include // DXGI_FORMAT 19 | 20 | struct ID3D12Device; 21 | struct ID3D12DescriptorHeap; 22 | struct ID3D12GraphicsCommandList; 23 | struct D3D12_CPU_DESCRIPTOR_HANDLE; 24 | struct D3D12_GPU_DESCRIPTOR_HANDLE; 25 | 26 | // cmd_list is the command list that the implementation will use to render imgui draw lists. 27 | // Before calling the render function, caller must prepare cmd_list by resetting it and setting the appropriate 28 | // render target and descriptor heap that contains font_srv_cpu_desc_handle/font_srv_gpu_desc_handle. 29 | // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture. 30 | IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* cbv_srv_heap, 31 | D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle); 32 | IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown(); 33 | IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame(); 34 | IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list); 35 | 36 | // Use if you want to reset your rendering device without losing Dear ImGui state. 37 | IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); 38 | IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); 39 | -------------------------------------------------------------------------------- /backends/imgui_impl_glut.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for GLUT/FreeGLUT 2 | // This needs to be used along with a Renderer (e.g. OpenGL2) 3 | 4 | // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! 5 | // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! 6 | // !!! Nowadays, prefer using GLFW or SDL instead! 7 | 8 | // Implemented features: 9 | // [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 10 | // Issues: 11 | // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I 12 | // [ ] Platform: Missing horizontal mouse wheel support. 13 | // [ ] Platform: Missing mouse cursor shape/visibility support. 14 | // [ ] Platform: Missing clipboard support (not supported by Glut). 15 | // [ ] Platform: Missing gamepad support. 16 | 17 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 18 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 19 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 20 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 21 | 22 | #pragma once 23 | #include "imgui.h" // IMGUI_IMPL_API 24 | 25 | IMGUI_IMPL_API bool ImGui_ImplGLUT_Init(); 26 | IMGUI_IMPL_API void ImGui_ImplGLUT_InstallFuncs(); 27 | IMGUI_IMPL_API void ImGui_ImplGLUT_Shutdown(); 28 | IMGUI_IMPL_API void ImGui_ImplGLUT_NewFrame(); 29 | 30 | // You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically, 31 | // or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency.. 32 | //---------------------------------------- GLUT name --------------------------------------------- Decent Name --------- 33 | IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc 34 | IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc 35 | IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc 36 | IMGUI_IMPL_API void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y); // ~ MouseWheelFunc 37 | IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y); // ~ CharPressedFunc 38 | IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc 39 | IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc 40 | IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc 41 | -------------------------------------------------------------------------------- /backends/imgui_impl_opengl3.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline 2 | // - Desktop GL: 2.x 3.x 4.x 3 | // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0) 4 | // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) 5 | 6 | // Implemented features: 7 | // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! 8 | // [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only). 9 | 10 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 11 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 12 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 13 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 14 | 15 | // About GLSL version: 16 | // The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string. 17 | // On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es" 18 | // Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp. 19 | 20 | #pragma once 21 | #include "imgui.h" // IMGUI_IMPL_API 22 | 23 | // Backend API 24 | IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr); 25 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown(); 26 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame(); 27 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data); 28 | 29 | // (Optional) Called by Init/NewFrame/Shutdown 30 | IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture(); 31 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture(); 32 | IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); 33 | IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); 34 | 35 | // Specific OpenGL ES versions 36 | //#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten 37 | //#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android 38 | 39 | // You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line. 40 | #if !defined(IMGUI_IMPL_OPENGL_ES2) \ 41 | && !defined(IMGUI_IMPL_OPENGL_ES3) 42 | 43 | // Try to detect GLES on matching platforms 44 | #if defined(__APPLE__) 45 | #include 46 | #endif 47 | #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__)) 48 | #define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es" 49 | #elif defined(__EMSCRIPTEN__) || defined(__amigaos4__) 50 | #define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100" 51 | #else 52 | // Otherwise imgui_impl_opengl3_loader.h will be used. 53 | #endif 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /backends/imgui_impl_win32.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) 2 | // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) 3 | 4 | // Implemented features: 5 | // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) 6 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 7 | // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 8 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. 9 | 10 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 11 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 12 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 13 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 14 | 15 | #pragma once 16 | #include "imgui.h" // IMGUI_IMPL_API 17 | 18 | IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); 19 | IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); 20 | IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(); 21 | 22 | // Win32 message handler your application need to call. 23 | // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on from this helper. 24 | // - You should COPY the line below into your .cpp code to forward declare the function and then you can call it. 25 | // - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. 26 | 27 | #if 0 28 | extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); 29 | #endif 30 | 31 | // DPI-related helpers (optional) 32 | // - Use to enable DPI awareness without having to create an application manifest. 33 | // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. 34 | // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. 35 | // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, 36 | // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. 37 | IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); 38 | IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd 39 | IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor 40 | 41 | // Transparency related helpers (optional) [experimental] 42 | // - Use to enable alpha compositing transparency with the desktop. 43 | // - Use together with e.g. clearing your framebuffer with zero-alpha. 44 | IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd 45 | -------------------------------------------------------------------------------- /backends/imgui_impl_metal.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for Metal 2 | // This needs to be used along with a Platform Backend (e.g. OSX) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 9 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 10 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 11 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 12 | 13 | #include "imgui.h" // IMGUI_IMPL_API 14 | 15 | //----------------------------------------------------------------------------- 16 | // ObjC API 17 | //----------------------------------------------------------------------------- 18 | 19 | #ifdef __OBJC__ 20 | 21 | @class MTLRenderPassDescriptor; 22 | @protocol MTLDevice, MTLCommandBuffer, MTLRenderCommandEncoder; 23 | 24 | IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id device); 25 | IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); 26 | IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor); 27 | IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, 28 | id commandBuffer, 29 | id commandEncoder); 30 | 31 | // Called by Init/NewFrame/Shutdown 32 | IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(id device); 33 | IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture(); 34 | IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(id device); 35 | IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); 36 | 37 | #endif 38 | 39 | //----------------------------------------------------------------------------- 40 | // C++ API 41 | //----------------------------------------------------------------------------- 42 | 43 | // Enable Metal C++ binding support with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file 44 | // More info about using Metal from C++: https://developer.apple.com/metal/cpp/ 45 | 46 | #ifdef IMGUI_IMPL_METAL_CPP 47 | #include 48 | #ifndef __OBJC__ 49 | 50 | IMGUI_IMPL_API bool ImGui_ImplMetal_Init(MTL::Device* device); 51 | IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); 52 | IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor); 53 | IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, 54 | MTL::CommandBuffer* commandBuffer, 55 | MTL::RenderCommandEncoder* commandEncoder); 56 | 57 | // Called by Init/NewFrame/Shutdown 58 | IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device); 59 | IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture(); 60 | IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device); 61 | IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); 62 | 63 | #endif 64 | #endif 65 | -------------------------------------------------------------------------------- /misc/cpp/imgui_stdlib.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: wrappers for C++ standard library (STL) types (std::string, etc.) 2 | // This is also an example of how you may wrap your own similar types. 3 | 4 | // Changelog: 5 | // - v0.10: Initial version. Added InputText() / InputTextMultiline() calls with std::string 6 | 7 | // See more C++ related extension (fmt, RAII, syntaxis sugar) on Wiki: 8 | // https://github.com/ocornut/imgui/wiki/Useful-Extensions#cness 9 | 10 | #include "imgui.h" 11 | #include "imgui_stdlib.h" 12 | 13 | struct InputTextCallback_UserData 14 | { 15 | std::string* Str; 16 | ImGuiInputTextCallback ChainCallback; 17 | void* ChainCallbackUserData; 18 | }; 19 | 20 | static int InputTextCallback(ImGuiInputTextCallbackData* data) 21 | { 22 | InputTextCallback_UserData* user_data = (InputTextCallback_UserData*)data->UserData; 23 | if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) 24 | { 25 | // Resize string callback 26 | // If for some reason we refuse the new length (BufTextLen) and/or capacity (BufSize) we need to set them back to what we want. 27 | std::string* str = user_data->Str; 28 | IM_ASSERT(data->Buf == str->c_str()); 29 | str->resize(data->BufTextLen); 30 | data->Buf = (char*)str->c_str(); 31 | } 32 | else if (user_data->ChainCallback) 33 | { 34 | // Forward to user callback, if any 35 | data->UserData = user_data->ChainCallbackUserData; 36 | return user_data->ChainCallback(data); 37 | } 38 | return 0; 39 | } 40 | 41 | bool ImGui::InputText(const char* label, std::string* str, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) 42 | { 43 | IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); 44 | flags |= ImGuiInputTextFlags_CallbackResize; 45 | 46 | InputTextCallback_UserData cb_user_data; 47 | cb_user_data.Str = str; 48 | cb_user_data.ChainCallback = callback; 49 | cb_user_data.ChainCallbackUserData = user_data; 50 | return InputText(label, (char*)str->c_str(), str->capacity() + 1, flags, InputTextCallback, &cb_user_data); 51 | } 52 | 53 | bool ImGui::InputTextMultiline(const char* label, std::string* str, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) 54 | { 55 | IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); 56 | flags |= ImGuiInputTextFlags_CallbackResize; 57 | 58 | InputTextCallback_UserData cb_user_data; 59 | cb_user_data.Str = str; 60 | cb_user_data.ChainCallback = callback; 61 | cb_user_data.ChainCallbackUserData = user_data; 62 | return InputTextMultiline(label, (char*)str->c_str(), str->capacity() + 1, size, flags, InputTextCallback, &cb_user_data); 63 | } 64 | 65 | bool ImGui::InputTextWithHint(const char* label, const char* hint, std::string* str, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) 66 | { 67 | IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); 68 | flags |= ImGuiInputTextFlags_CallbackResize; 69 | 70 | InputTextCallback_UserData cb_user_data; 71 | cb_user_data.Str = str; 72 | cb_user_data.ChainCallback = callback; 73 | cb_user_data.ChainCallbackUserData = user_data; 74 | return InputTextWithHint(label, hint, (char*)str->c_str(), str->capacity() + 1, flags, InputTextCallback, &cb_user_data); 75 | } 76 | -------------------------------------------------------------------------------- /backends/imgui_impl_glfw.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for GLFW 2 | // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..) 3 | // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.) 4 | 5 | // Implemented features: 6 | // [X] Platform: Clipboard support. 7 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 8 | // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 9 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange' (note: the resizing cursors requires GLFW 3.4+). 10 | 11 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 12 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 13 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 14 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 15 | 16 | #pragma once 17 | #include "imgui.h" // IMGUI_IMPL_API 18 | 19 | struct GLFWwindow; 20 | struct GLFWmonitor; 21 | 22 | IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks); 23 | IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks); 24 | IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks); 25 | IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown(); 26 | IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame(); 27 | 28 | // GLFW callbacks install 29 | // - When calling Init with 'install_callbacks=true': ImGui_ImplGlfw_InstallCallbacks() is called. GLFW callbacks will be installed for you. They will chain-call user's previously installed callbacks, if any. 30 | // - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call individual function yourself from your own GLFW callbacks. 31 | IMGUI_IMPL_API void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window); 32 | IMGUI_IMPL_API void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window); 33 | 34 | // GFLW callbacks options: 35 | // - Set 'chain_for_all_windows=true' to enable chaining callbacks for all windows (including secondary viewports created by backends or by user) 36 | IMGUI_IMPL_API void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows); 37 | 38 | // GLFW callbacks (individual callbacks to call yourself if you didn't install callbacks) 39 | IMGUI_IMPL_API void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); // Since 1.84 40 | IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); // Since 1.84 41 | IMGUI_IMPL_API void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y); // Since 1.87 42 | IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); 43 | IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); 44 | IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); 45 | IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); 46 | IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event); 47 | -------------------------------------------------------------------------------- /misc/freetype/imgui_freetype.h: -------------------------------------------------------------------------------- 1 | // dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder) 2 | // (headers) 3 | 4 | #pragma once 5 | 6 | #include "imgui.h" // IMGUI_API 7 | 8 | // Forward declarations 9 | struct ImFontAtlas; 10 | struct ImFontBuilderIO; 11 | 12 | // Hinting greatly impacts visuals (and glyph sizes). 13 | // - By default, hinting is enabled and the font's native hinter is preferred over the auto-hinter. 14 | // - When disabled, FreeType generates blurrier glyphs, more or less matches the stb_truetype.h 15 | // - The Default hinting mode usually looks good, but may distort glyphs in an unusual way. 16 | // - The Light hinting mode generates fuzzier glyphs but better matches Microsoft's rasterizer. 17 | // You can set those flags globaly in ImFontAtlas::FontBuilderFlags 18 | // You can set those flags on a per font basis in ImFontConfig::FontBuilderFlags 19 | enum ImGuiFreeTypeBuilderFlags 20 | { 21 | ImGuiFreeTypeBuilderFlags_NoHinting = 1 << 0, // Disable hinting. This generally generates 'blurrier' bitmap glyphs when the glyph are rendered in any of the anti-aliased modes. 22 | ImGuiFreeTypeBuilderFlags_NoAutoHint = 1 << 1, // Disable auto-hinter. 23 | ImGuiFreeTypeBuilderFlags_ForceAutoHint = 1 << 2, // Indicates that the auto-hinter is preferred over the font's native hinter. 24 | ImGuiFreeTypeBuilderFlags_LightHinting = 1 << 3, // A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by Microsoft's ClearType and Adobe's proprietary font renderer. This preserves inter-glyph spacing in horizontal text. 25 | ImGuiFreeTypeBuilderFlags_MonoHinting = 1 << 4, // Strong hinting algorithm that should only be used for monochrome output. 26 | ImGuiFreeTypeBuilderFlags_Bold = 1 << 5, // Styling: Should we artificially embolden the font? 27 | ImGuiFreeTypeBuilderFlags_Oblique = 1 << 6, // Styling: Should we slant the font, emulating italic style? 28 | ImGuiFreeTypeBuilderFlags_Monochrome = 1 << 7, // Disable anti-aliasing. Combine this with MonoHinting for best results! 29 | ImGuiFreeTypeBuilderFlags_LoadColor = 1 << 8, // Enable FreeType color-layered glyphs 30 | ImGuiFreeTypeBuilderFlags_Bitmap = 1 << 9 // Enable FreeType bitmap glyphs 31 | }; 32 | 33 | namespace ImGuiFreeType 34 | { 35 | // This is automatically assigned when using '#define IMGUI_ENABLE_FREETYPE'. 36 | // If you need to dynamically select between multiple builders: 37 | // - you can manually assign this builder with 'atlas->FontBuilderIO = ImGuiFreeType::GetBuilderForFreeType()' 38 | // - prefer deep-copying this into your own ImFontBuilderIO instance if you use hot-reloading that messes up static data. 39 | IMGUI_API const ImFontBuilderIO* GetBuilderForFreeType(); 40 | 41 | // Override allocators. By default ImGuiFreeType will use IM_ALLOC()/IM_FREE() 42 | // However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired. 43 | IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL); 44 | 45 | // Obsolete names (will be removed soon) 46 | // Prefer using '#define IMGUI_ENABLE_FREETYPE' 47 | #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS 48 | static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontBuilderFlags = flags; return atlas->Build(); } 49 | #endif 50 | } 51 | -------------------------------------------------------------------------------- /docs/BACKENDS.md: -------------------------------------------------------------------------------- 1 | _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md or view this file with any Markdown viewer)_ 2 | 3 | ## Dear ImGui: Backends 4 | 5 | **The backends/ folder contains backends for popular platforms/graphics API, which you can use in 6 | your application or engine to easily integrate Dear ImGui.** Each backend is typically self-contained in a pair of files: imgui_impl_XXXX.cpp + imgui_impl_XXXX.h. 7 | 8 | - The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, and windowing.
9 | e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), SDL2 ([imgui_impl_sdl2.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl2.cpp)), etc. 10 | 11 | - The 'Renderer' backends are in charge of: creating atlas texture, and rendering imgui draw data.
12 | e.g. DirectX11 ([imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)), OpenGL/WebGL ([imgui_impl_opengl3.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_opengl3.cpp)), Vulkan ([imgui_impl_vulkan.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_vulkan.cpp)), etc. 13 | 14 | - For some high-level frameworks, a single backend usually handles both 'Platform' and 'Renderer' parts.
15 | e.g. Allegro 5 ([imgui_impl_allegro5.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_allegro5.cpp)). If you end up creating a custom backend for your engine, you may want to do the same. 16 | 17 | An application usually combines one Platform backend + one Renderer backend + main Dear ImGui sources. 18 | For example, the [example_win32_directx11](https://github.com/ocornut/imgui/tree/master/examples/example_win32_directx11) application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. There are 20+ examples in the [examples/](https://github.com/ocornut/imgui/blob/master/examples/) folder. See [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for details. 19 | 20 | **Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** 21 | 22 | 23 | ### What are backends? 24 | 25 | Dear ImGui is highly portable and only requires a few things to run and render, typically: 26 | 27 | - Required: providing mouse/keyboard inputs (fed into the `ImGuiIO` structure). 28 | - Required: uploading the font atlas texture into graphics memory. 29 | - Required: rendering indexed textured triangles with a clipping rectangle. 30 | 31 | Extra features are opt-in, our backends try to support as many as possible: 32 | 33 | - Optional: custom texture binding support. 34 | - Optional: clipboard support. 35 | - Optional: gamepad support. 36 | - Optional: mouse cursor shape support. 37 | - Optional: IME support. 38 | - Optional: multi-viewports support. 39 | etc. 40 | 41 | This is essentially what each backend is doing + obligatory portability cruft. Using default backends ensure you can get all those features including the ones that would be harder to implement on your side (e.g. multi-viewports support). 42 | 43 | It is important to understand the difference between the core Dear ImGui library (files in the root folder) 44 | and the backends which we are describing here (backends/ folder). 45 | 46 | - Some issues may only be backend or platform specific. 47 | - You should be able to write backends for pretty much any platform and any 3D graphics API. 48 | e.g. you can get creative and use software rendering or render remotely on a different machine. 49 | 50 | 51 | ### Integrating a backend 52 | 53 | See "Getting Started" section of [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for more details. 54 | 55 | 56 | ### List of backends 57 | 58 | In the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder: 59 | 60 | List of Platforms Backends: 61 | 62 | imgui_impl_android.cpp ; Android native app API 63 | imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ 64 | imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) 65 | imgui_impl_sdl2.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org 66 | imgui_impl_sdl3.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org (*EXPERIMENTAL*) 67 | imgui_impl_win32.cpp ; Win32 native API (Windows) 68 | imgui_impl_glut.cpp ; GLUT/FreeGLUT (this is prehistoric software and absolutely not recommended today!) 69 | 70 | List of Renderer Backends: 71 | 72 | imgui_impl_dx9.cpp ; DirectX9 73 | imgui_impl_dx10.cpp ; DirectX10 74 | imgui_impl_dx11.cpp ; DirectX11 75 | imgui_impl_dx12.cpp ; DirectX12 76 | imgui_impl_metal.mm ; Metal (with ObjC) 77 | imgui_impl_opengl2.cpp ; OpenGL 2 (legacy, fixed pipeline <- don't use with modern OpenGL context) 78 | imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline) 79 | imgui_impl_sdlrenderer.cpp; SDL_Renderer (optional component of SDL2 available from SDL 2.0.18+) 80 | imgui_impl_vulkan.cpp ; Vulkan 81 | imgui_impl_wgpu.cpp ; WebGPU 82 | 83 | List of high-level Frameworks Backends (combining Platform + Renderer): 84 | 85 | imgui_impl_allegro5.cpp 86 | 87 | Emscripten is also supported! 88 | The SDL+GL, GLFW+GL and SDL+WebGPU examples are all ready to build and run with Emscripten. 89 | 90 | ### Backends for third-party frameworks, graphics API or other languages 91 | 92 | See https://github.com/ocornut/imgui/wiki/Bindings for the full list (e.g. Adventure Game Studio, Cinder, Cocos2d-x, Game Maker Studio2, Godot, LÖVE+LUA, Magnum, Monogame, Ogre, openFrameworks, OpenSceneGraph, SFML, Sokol, Unity, Unreal Engine and many others). 93 | 94 | ### Recommended Backends 95 | 96 | If you are not sure which backend to use, the recommended platform/frameworks for portable applications: 97 | 98 | |Library |Website |Backend |Note | 99 | |--------|--------|--------|-----| 100 | | GLFW | https://github.com/glfw/glfw | imgui_impl_glfw.cpp | | 101 | | SDL2 | https://www.libsdl.org | imgui_impl_sdl2.cpp | | 102 | | Sokol | https://github.com/floooh/sokol | [util/sokol_imgui.h](https://github.com/floooh/sokol/blob/master/util/sokol_imgui.h) | Lower-level than GLFW/SDL | 103 | 104 | 105 | ### Using a custom engine? 106 | 107 | You will likely be tempted to start by rewrite your own backend using your own custom/high-level facilities...
108 | Think twice! 109 | 110 | If you are new to Dear ImGui, first try using the existing backends as-is. 111 | You will save lots of time integrating the library. 112 | You can LATER decide to rewrite yourself a custom backend if you really need to. 113 | In most situations, custom backends have fewer features and more bugs than the standard backends we provide. 114 | If you want portability, you can use multiple backends and choose between them either at compile time 115 | or at runtime. 116 | 117 | **Example A**: your engine is built over Windows + DirectX11 but you have your own high-level rendering 118 | system layered over DirectX11.
119 | Suggestion: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first. 120 | Once it works, if you really need it, you can replace the imgui_impl_dx11.cpp code with a 121 | custom renderer using your own rendering functions, and keep using the standard Win32 code etc. 122 | 123 | **Example B**: your engine runs on Windows, Mac, Linux and uses DirectX11, Metal, and Vulkan respectively.
124 | Suggestion: use multiple generic backends! 125 | Once it works, if you really need it, you can replace parts of backends with your own abstractions. 126 | 127 | **Example C**: your engine runs on platforms we can't provide public backends for (e.g. PS4/PS5, Switch), 128 | and you have high-level systems everywhere.
129 | Suggestion: try using a non-portable backend first (e.g. win32 + underlying graphics API) to get 130 | your desktop builds working first. This will get you running faster and get your acquainted with 131 | how Dear ImGui works and is setup. You can then rewrite a custom backend using your own engine API... 132 | 133 | Generally: 134 | It is unlikely you will add value to your project by creating your own backend. 135 | 136 | Also: 137 | The [multi-viewports feature](https://github.com/ocornut/imgui/issues/1542) of the 'docking' branch allows 138 | Dear ImGui windows to be seamlessly detached from the main application window. This is achieved using an 139 | extra layer to the Platform and Renderer backends, which allows Dear ImGui to communicate platform-specific 140 | requests such as: "create an additional OS window", "create a render context", "get the OS position of this 141 | window" etc. See 'ImGuiPlatformIO' for details. 142 | Supporting the multi-viewports feature correctly using 100% of your own abstractions is more difficult 143 | than supporting single-viewport. 144 | If you decide to use unmodified imgui_impl_XXXX.cpp files, you can automatically benefit from 145 | improvements and fixes related to viewports and platform windows without extra work on your side. 146 | -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | ## Index 4 | 5 | - [Getting Started & General Advice](#getting-started--general-advice) 6 | - [Issues vs Discussions](#issues-vs-discussions) 7 | - [How to open an Issue](#how-to-open-an-issue) 8 | - [How to open a Pull Request](#how-to-open-a-pull-request) 9 | - [Copyright / Contributor License Agreement](#copyright--contributor-license-agreement) 10 | 11 | ## Getting Started & General Advice 12 | 13 | - Article: [How To Ask Good Questions](https://bit.ly/3nwRnx1). 14 | - Please browse the [Wiki](https://github.com/ocornut/imgui/wiki) to find code snippets, links and other resources (e.g. [Useful extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions)). 15 | - Please read [docs/FAQ.md](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md). 16 | - Please read [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) if your question relates to fonts or text. 17 | - Please read one of the [examples/](https://github.com/ocornut/imgui/tree/master/examples) application if your question relates to setting up Dear ImGui. 18 | - Please run `ImGui::ShowDemoWindow()` to explore the demo and its sources. 19 | - Please use the search function of your IDE to search in for comments related to your situation. 20 | - Please use the search function of GitHub to look for similar issues. You may [browse issues by Labels](https://github.com/ocornut/imgui/labels). 21 | - Please use a web search engine to look for similar issues. 22 | - If you get a crash or assert, use a debugger to locate the line triggering it and read the comments around. 23 | - Please don't be a [Help Vampire](https://slash7.com/2006/12/22/vampires/). 24 | 25 | ## Issues vs Discussions 26 | 27 | If you: 28 | - Cannot BUILD or LINK examples. 29 | - Cannot BUILD, or LINK, or RUN Dear ImGui in your application or custom engine. 30 | - Cannot LOAD a font. 31 | 32 | Then please [use the Discussions forums](https://github.com/ocornut/imgui/discussions) instead of opening an issue. 33 | 34 | If Dear ImGui is successfully showing in your app and you have used Dear ImGui before, you can open an issue. Any form of discussions is welcome as a new issue. 35 | 36 | ## How to open an issue 37 | 38 | You may use the Issue Tracker to submit bug reports, feature requests or suggestions. You may ask for help or advice as well. But **PLEASE CAREFULLY READ THIS WALL OF TEXT. ISSUES IGNORING THOSE GUIDELINES MAY BE CLOSED. USERS IGNORING THOSE GUIDELINES MIGHT BE BLOCKED.** 39 | 40 | Please do your best to clarify your request. The amount of incomplete or ambiguous requests due to people not following those guidelines is often overwhelming. Issues created without the requested information may be closed prematurely. Exceptionally entitled, impolite, or lazy requests may lead to bans. 41 | 42 | **PLEASE UNDERSTAND THAT OPEN-SOURCE SOFTWARE LIVES OR DIES BY THE AMOUNT OF ENERGY MAINTAINERS CAN SPARE. WE HAVE LOTS OF STUFF TO DO. THIS IS AN ATTENTION ECONOMY AND MANY LAZY OR MINOR ISSUES ARE HOGGING OUR ATTENTION AND DRAINING ENERGY, TAKING US AWAY FROM MORE IMPORTANT WORK.** 43 | 44 | Steps: 45 | 46 | - Article: [How To Ask Good Questions](https://bit.ly/3nwRnx1). 47 | - **PLEASE DO FILL THE REQUESTED NEW ISSUE TEMPLATE.** Including Dear ImGui version number, branch name, platform/renderer back-ends (imgui_impl_XXX files), operating system. 48 | - **Try to be explicit with your GOALS, your EXPECTATIONS and what you have tried**. Be mindful of [The XY Problem](http://xyproblem.info/). What you have in mind or in your code is not obvious to other people. People frequently discuss problems and suggest incorrect solutions without first clarifying their goals. When requesting a new feature, please describe the usage context (how you intend to use it, why you need it, etc.). If you tried something and it failed, show us what you tried. 49 | - **Attach screenshots (or GIF/video) to clarify the context**. They often convey useful information that is omitted by the description. You can drag pictures/files in the message edit box. Avoid using 3rd party image hosting services, prefer the long-term longevity of GitHub attachments (you can drag pictures into your post). On Windows, you can use [ScreenToGif](https://www.screentogif.com/) to easily capture .gif files. 50 | - **If you are discussing an assert or a crash, please provide a debugger callstack**. Never state "it crashes" without additional information. If you don't know how to use a debugger and retrieve a callstack, learning about it will be useful. 51 | - **Please make sure that your project has asserts enabled.** Calls to IM_ASSERT() are scattered in the code to help catch common issues. When an assert is triggered read the comments around it. By default IM_ASSERT() calls the standard assert() function. To verify that your asserts are enabled, add the line `IM_ASSERT(false);` in your main() function. Your application should display an error message and abort. If your application doesn't report an error, your asserts are disabled. 52 | - **Please provide a Minimal, Complete, and Verifiable Example ([MCVE](https://stackoverflow.com/help/mcve)) to demonstrate your problem**. An ideal submission includes a small piece of code that anyone can paste into one of the examples applications (examples/../main.cpp) or demo (imgui_demo.cpp) to understand and reproduce it. Narrowing your problem to its shortest and purest form is the easiest way to understand it. Please test your shortened code to ensure it exhibits the problem. **Often while creating the MCVE you will end up solving the problem!** Many questions that are missing a standalone verifiable example are missing the actual cause of their issue in the description, which ends up wasting everyone's time. 53 | - Please state if you have made substantial modifications to your copy of Dear ImGui or the back-end. 54 | - If you are not calling Dear ImGui directly from C++, please provide information about your Language and the wrapper/binding you are using. 55 | - Be mindful that messages are being sent to the mailbox of "Watching" users. Try to proofread your messages before sending them. Edits are not seen by those users unless they browse the site. 56 | 57 | **Some unfortunate words of warning** 58 | - If you are involved in cheating schemes (e.g. DLL injection) for competitive online multiplayer games, please don't try posting here. We won't answer and you will be blocked. It doesn't matter if your question relates to said project. We've had too many of you and need to project our time and sanity. 59 | - Due to frequent abuse of this service from the aforementioned users, if your GitHub account is anonymous and was created five minutes ago please understand that your post will receive more scrutiny and incomplete questions will be harshly dismissed. 60 | 61 | If you have been using Dear ImGui for a while or have been using C/C++ for several years or have demonstrated good behavior here, it is ok to not fulfill every item to the letter. Those are guidelines and experienced users or members of the community will know which information is useful in a given context. 62 | 63 | ## How to open a Pull Request 64 | 65 | - **Please understand that by submitting a PR you are also submitting a request for the maintainer to review your code and then take over its maintenance.** PR should be crafted both in the interest of the end-users and also to ease the maintainer into understanding and accepting it. 66 | - Many PRs are useful to demonstrate a need and a possible solution but aren't adequate for merging (causing other issues, not seeing other aspects of the big picture, etc.). In doubt, don't hesitate to push a PR because that is always the first step toward finding the mergeable solution! Even if a PR stays unmerged for a long time, its presence can be useful for other users and helps toward finding a general solution. 67 | - **When adding a feature,** please describe the usage context (how you intend to use it, why you need it, etc.). Be mindful of [The XY Problem](http://xyproblem.info/). 68 | - **When fixing a warning or compilation problem,** please post the compiler log and specify the compiler version and platform you are using. 69 | - **Attach screenshots (or GIF/video) to clarify the context and demonstrate the feature at a glance.** You can drag pictures/files in the message edit box. Prefer the long-term longevity of GitHub attachments over 3rd party hosting (you can drag pictures into your post). 70 | - **Make sure your code follows the coding style already used in the codebase:** 4 spaces indentations (no tabs), `local_variable`, `FunctionName()`, `MemberName`, `// Text Comment`, `//CodeComment();`, C-style casts, etc.. We don't use modern C++ idioms and tend to use only a minimum of C++11 features. The applications under examples/ are generally less consistent because they sometimes try to mimic the coding style often adopted by a certain ecosystem (e.g. DirectX-related code tend to use the style of their sample). 71 | - **Make sure you create a branch dedicated to the pull request**. In Git, 1 PR is associated to 1 branch. If you keep pushing to the same branch after you submitted the PR, your new commits will appear in the PR (we can still cherry-pick individual commits). 72 | 73 | Thank you for reading! 74 | 75 | ## Copyright / Contributor License Agreement 76 | 77 | Any code you submit will become part of the repository and be distributed under the [Dear ImGui license](https://github.com/ocornut/imgui/blob/master/LICENSE.txt). By submitting code to the project you agree that the code is your work and that you can give it to the project. 78 | 79 | You also agree by submitting your code that you grant all transferrable rights to the code to the project maintainer, including for example re-licensing the code, modifying the code, and distributing it in source or binary forms. Specifically, this includes a requirement that you assign copyright to the project maintainer. For this reason, do not modify any copyright statements in files in any PRs. 80 | 81 | -------------------------------------------------------------------------------- /imconfig.h: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------------- 2 | // COMPILE-TIME OPTIONS FOR DEAR IMGUI 3 | // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. 4 | // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. 5 | //----------------------------------------------------------------------------- 6 | // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) 7 | // B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. 8 | //----------------------------------------------------------------------------- 9 | // You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp 10 | // files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. 11 | // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. 12 | // Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. 13 | //----------------------------------------------------------------------------- 14 | 15 | #pragma once 16 | 17 | //---- Define assertion handler. Defaults to calling assert(). 18 | // If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. 19 | //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) 20 | //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts 21 | 22 | //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows 23 | // Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. 24 | // DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() 25 | // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. 26 | //#define IMGUI_API __declspec( dllexport ) 27 | //#define IMGUI_API __declspec( dllimport ) 28 | 29 | //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names. 30 | //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS 31 | //#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87: disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This will be folded into IMGUI_DISABLE_OBSOLETE_FUNCTIONS in a few versions. 32 | 33 | //---- Disable all of Dear ImGui or don't implement standard windows/tools. 34 | // It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp. 35 | //#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. 36 | //#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. 37 | //#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowStackToolWindow() will be empty (this was called IMGUI_DISABLE_METRICS_WINDOW before 1.88). 38 | 39 | //---- Don't implement some functions to reduce linkage requirements. 40 | //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) 41 | //#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) 42 | //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) 43 | //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). 44 | //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). 45 | //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) 46 | //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. 47 | //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) 48 | //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. 49 | //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). 50 | //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available 51 | 52 | //---- Include imgui_user.h at the end of imgui.h as a convenience 53 | //#define IMGUI_INCLUDE_IMGUI_USER_H 54 | 55 | //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) 56 | //#define IMGUI_USE_BGRA_PACKED_COLOR 57 | 58 | //---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) 59 | //#define IMGUI_USE_WCHAR32 60 | 61 | //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version 62 | // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. 63 | //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" 64 | //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" 65 | //#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if enabled 66 | //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION 67 | //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION 68 | 69 | //---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) 70 | // Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h. 71 | //#define IMGUI_USE_STB_SPRINTF 72 | 73 | //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) 74 | // Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). 75 | // On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. 76 | //#define IMGUI_ENABLE_FREETYPE 77 | 78 | //---- Use stb_truetype to build and rasterize the font atlas (default) 79 | // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. 80 | //#define IMGUI_ENABLE_STB_TRUETYPE 81 | 82 | //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. 83 | // This will be inlined as part of ImVec2 and ImVec4 class declarations. 84 | /* 85 | #define IM_VEC2_CLASS_EXTRA \ 86 | constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \ 87 | operator MyVec2() const { return MyVec2(x,y); } 88 | 89 | #define IM_VEC4_CLASS_EXTRA \ 90 | constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \ 91 | operator MyVec4() const { return MyVec4(x,y,z,w); } 92 | */ 93 | //---- ...Or use Dear ImGui's own very basic math operators. 94 | //#define IMGUI_DEFINE_MATH_OPERATORS 95 | 96 | //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. 97 | // Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). 98 | // Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. 99 | // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. 100 | //#define ImDrawIdx unsigned int 101 | 102 | //---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) 103 | //struct ImDrawList; 104 | //struct ImDrawCmd; 105 | //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); 106 | //#define ImDrawCallback MyImDrawCallback 107 | 108 | //---- Debug Tools: Macro to break in Debugger 109 | // (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) 110 | //#define IM_DEBUG_BREAK IM_ASSERT(0) 111 | //#define IM_DEBUG_BREAK __debugbreak() 112 | 113 | //---- Debug Tools: Enable slower asserts 114 | //#define IMGUI_DEBUG_PARANOID 115 | 116 | //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. 117 | /* 118 | namespace ImGui 119 | { 120 | void MyFunction(const char* name, const MyMatrix44& v); 121 | } 122 | */ 123 | -------------------------------------------------------------------------------- /backends/imgui_impl_vulkan.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for Vulkan 2 | // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) 3 | 4 | // Implemented features: 5 | // [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions. 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. 9 | // See imgui_impl_vulkan.cpp file for details. 10 | 11 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 12 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 13 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 14 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 15 | 16 | // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. 17 | // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ 18 | 19 | // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. 20 | // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. 21 | // You will use those if you want to use this rendering backend in your engine/app. 22 | // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by 23 | // the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code. 24 | // Read comments in imgui_impl_vulkan.h. 25 | 26 | #pragma once 27 | #include "imgui.h" // IMGUI_IMPL_API 28 | 29 | // [Configuration] in order to use a custom Vulkan function loader: 30 | // (1) You'll need to disable default Vulkan function prototypes. 31 | // We provide a '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' convenience configuration flag. 32 | // In order to make sure this is visible from the imgui_impl_vulkan.cpp compilation unit: 33 | // - Add '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' in your imconfig.h file 34 | // - Or as a compilation flag in your build system 35 | // - Or uncomment here (not recommended because you'd be modifying imgui sources!) 36 | // - Do not simply add it in a .cpp file! 37 | // (2) Call ImGui_ImplVulkan_LoadFunctions() before ImGui_ImplVulkan_Init() with your custom function. 38 | // If you have no idea what this is, leave it alone! 39 | //#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES 40 | 41 | // Vulkan includes 42 | #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES) 43 | #define VK_NO_PROTOTYPES 44 | #endif 45 | #include 46 | 47 | // Initialization data, for ImGui_ImplVulkan_Init() 48 | // [Please zero-clear before use!] 49 | struct ImGui_ImplVulkan_InitInfo 50 | { 51 | VkInstance Instance; 52 | VkPhysicalDevice PhysicalDevice; 53 | VkDevice Device; 54 | uint32_t QueueFamily; 55 | VkQueue Queue; 56 | VkPipelineCache PipelineCache; 57 | VkDescriptorPool DescriptorPool; 58 | uint32_t Subpass; 59 | uint32_t MinImageCount; // >= 2 60 | uint32_t ImageCount; // >= MinImageCount 61 | VkSampleCountFlagBits MSAASamples; // >= VK_SAMPLE_COUNT_1_BIT (0 -> default to VK_SAMPLE_COUNT_1_BIT) 62 | const VkAllocationCallbacks* Allocator; 63 | void (*CheckVkResultFn)(VkResult err); 64 | }; 65 | 66 | // Called by user code 67 | IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); 68 | IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); 69 | IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); 70 | IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); 71 | IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); 72 | IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); 73 | IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) 74 | 75 | // Register a texture (VkDescriptorSet == ImTextureID) 76 | // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem 77 | // Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions. 78 | IMGUI_IMPL_API VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout); 79 | IMGUI_IMPL_API void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set); 80 | 81 | // Optional: load Vulkan functions with a custom function loader 82 | // This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES 83 | IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr); 84 | 85 | //------------------------------------------------------------------------- 86 | // Internal / Miscellaneous Vulkan Helpers 87 | // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.) 88 | //------------------------------------------------------------------------- 89 | // You probably do NOT need to use or care about those functions. 90 | // Those functions only exist because: 91 | // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files. 92 | // 2) the multi-viewport / platform window implementation needs them internally. 93 | // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings, 94 | // but it is too much code to duplicate everywhere so we exceptionally expose them. 95 | // 96 | // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.). 97 | // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work. 98 | // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions) 99 | //------------------------------------------------------------------------- 100 | 101 | struct ImGui_ImplVulkanH_Frame; 102 | struct ImGui_ImplVulkanH_Window; 103 | 104 | // Helpers 105 | IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wnd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); 106 | IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wnd, const VkAllocationCallbacks* allocator); 107 | IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space); 108 | IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count); 109 | IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode); 110 | 111 | // Helper structure to hold the data needed by one rendering frame 112 | // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) 113 | // [Please zero-clear before use!] 114 | struct ImGui_ImplVulkanH_Frame 115 | { 116 | VkCommandPool CommandPool; 117 | VkCommandBuffer CommandBuffer; 118 | VkFence Fence; 119 | VkImage Backbuffer; 120 | VkImageView BackbufferView; 121 | VkFramebuffer Framebuffer; 122 | }; 123 | 124 | struct ImGui_ImplVulkanH_FrameSemaphores 125 | { 126 | VkSemaphore ImageAcquiredSemaphore; 127 | VkSemaphore RenderCompleteSemaphore; 128 | }; 129 | 130 | // Helper structure to hold the data needed by one rendering context into one OS window 131 | // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.) 132 | struct ImGui_ImplVulkanH_Window 133 | { 134 | int Width; 135 | int Height; 136 | VkSwapchainKHR Swapchain; 137 | VkSurfaceKHR Surface; 138 | VkSurfaceFormatKHR SurfaceFormat; 139 | VkPresentModeKHR PresentMode; 140 | VkRenderPass RenderPass; 141 | VkPipeline Pipeline; // The window pipeline may uses a different VkRenderPass than the one passed in ImGui_ImplVulkan_InitInfo 142 | bool ClearEnable; 143 | VkClearValue ClearValue; 144 | uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) 145 | uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) 146 | uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) 147 | ImGui_ImplVulkanH_Frame* Frames; 148 | ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; 149 | 150 | ImGui_ImplVulkanH_Window() 151 | { 152 | memset((void*)this, 0, sizeof(*this)); 153 | PresentMode = (VkPresentModeKHR)~0; // Ensure we get an error if user doesn't set this. 154 | ClearEnable = true; 155 | } 156 | }; 157 | 158 | -------------------------------------------------------------------------------- /backends/imgui_impl_sdlrenderer.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for SDL_Renderer 2 | // (Requires: SDL 2.0.17+) 3 | 4 | // Important to understand: SDL_Renderer is an _optional_ component of SDL. 5 | // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. 6 | // If your application will want to render any non trivial amount of graphics other than UI, 7 | // please be aware that SDL_Renderer offers a limited graphic API to the end-user and it might 8 | // be difficult to step out of those boundaries. 9 | // However, we understand it is a convenient choice to get an app started easily. 10 | 11 | // Implemented features: 12 | // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! 13 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 14 | 15 | // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 16 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 17 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 18 | 19 | // CHANGELOG 20 | // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. 21 | // 2021-12-21: Update SDL_RenderGeometryRaw() format to work with SDL 2.0.19. 22 | // 2021-12-03: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. 23 | // 2021-10-06: Backup and restore modified ClipRect/Viewport. 24 | // 2021-09-21: Initial version. 25 | 26 | #include "imgui.h" 27 | #include "imgui_impl_sdlrenderer.h" 28 | #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier 29 | #include // intptr_t 30 | #else 31 | #include // intptr_t 32 | #endif 33 | 34 | // Clang warnings with -Weverything 35 | #if defined(__clang__) 36 | #pragma clang diagnostic push 37 | #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness 38 | #endif 39 | 40 | // SDL 41 | #include 42 | #if !SDL_VERSION_ATLEAST(2,0,17) 43 | #error This backend requires SDL 2.0.17+ because of SDL_RenderGeometry() function 44 | #endif 45 | 46 | // SDL_Renderer data 47 | struct ImGui_ImplSDLRenderer_Data 48 | { 49 | SDL_Renderer* SDLRenderer; 50 | SDL_Texture* FontTexture; 51 | ImGui_ImplSDLRenderer_Data() { memset((void*)this, 0, sizeof(*this)); } 52 | }; 53 | 54 | // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts 55 | // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. 56 | static ImGui_ImplSDLRenderer_Data* ImGui_ImplSDLRenderer_GetBackendData() 57 | { 58 | return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; 59 | } 60 | 61 | // Functions 62 | bool ImGui_ImplSDLRenderer_Init(SDL_Renderer* renderer) 63 | { 64 | ImGuiIO& io = ImGui::GetIO(); 65 | IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); 66 | IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!"); 67 | 68 | // Setup backend capabilities flags 69 | ImGui_ImplSDLRenderer_Data* bd = IM_NEW(ImGui_ImplSDLRenderer_Data)(); 70 | io.BackendRendererUserData = (void*)bd; 71 | io.BackendRendererName = "imgui_impl_sdlrenderer"; 72 | io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. 73 | 74 | bd->SDLRenderer = renderer; 75 | 76 | return true; 77 | } 78 | 79 | void ImGui_ImplSDLRenderer_Shutdown() 80 | { 81 | ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); 82 | IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); 83 | ImGuiIO& io = ImGui::GetIO(); 84 | 85 | ImGui_ImplSDLRenderer_DestroyDeviceObjects(); 86 | 87 | io.BackendRendererName = nullptr; 88 | io.BackendRendererUserData = nullptr; 89 | IM_DELETE(bd); 90 | } 91 | 92 | static void ImGui_ImplSDLRenderer_SetupRenderState() 93 | { 94 | ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); 95 | 96 | // Clear out any viewports and cliprect set by the user 97 | // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. 98 | SDL_RenderSetViewport(bd->SDLRenderer, nullptr); 99 | SDL_RenderSetClipRect(bd->SDLRenderer, nullptr); 100 | } 101 | 102 | void ImGui_ImplSDLRenderer_NewFrame() 103 | { 104 | ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); 105 | IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDLRenderer_Init()?"); 106 | 107 | if (!bd->FontTexture) 108 | ImGui_ImplSDLRenderer_CreateDeviceObjects(); 109 | } 110 | 111 | void ImGui_ImplSDLRenderer_RenderDrawData(ImDrawData* draw_data) 112 | { 113 | ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); 114 | 115 | // If there's a scale factor set by the user, use that instead 116 | // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass 117 | // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. 118 | float rsx = 1.0f; 119 | float rsy = 1.0f; 120 | SDL_RenderGetScale(bd->SDLRenderer, &rsx, &rsy); 121 | ImVec2 render_scale; 122 | render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; 123 | render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; 124 | 125 | // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) 126 | int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x); 127 | int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y); 128 | if (fb_width == 0 || fb_height == 0) 129 | return; 130 | 131 | // Backup SDL_Renderer state that will be modified to restore it afterwards 132 | struct BackupSDLRendererState 133 | { 134 | SDL_Rect Viewport; 135 | bool ClipEnabled; 136 | SDL_Rect ClipRect; 137 | }; 138 | BackupSDLRendererState old = {}; 139 | old.ClipEnabled = SDL_RenderIsClipEnabled(bd->SDLRenderer) == SDL_TRUE; 140 | SDL_RenderGetViewport(bd->SDLRenderer, &old.Viewport); 141 | SDL_RenderGetClipRect(bd->SDLRenderer, &old.ClipRect); 142 | 143 | // Will project scissor/clipping rectangles into framebuffer space 144 | ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports 145 | ImVec2 clip_scale = render_scale; 146 | 147 | // Render command lists 148 | ImGui_ImplSDLRenderer_SetupRenderState(); 149 | for (int n = 0; n < draw_data->CmdListsCount; n++) 150 | { 151 | const ImDrawList* cmd_list = draw_data->CmdLists[n]; 152 | const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; 153 | const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; 154 | 155 | for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) 156 | { 157 | const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; 158 | if (pcmd->UserCallback) 159 | { 160 | // User callback, registered via ImDrawList::AddCallback() 161 | // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) 162 | if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) 163 | ImGui_ImplSDLRenderer_SetupRenderState(); 164 | else 165 | pcmd->UserCallback(cmd_list, pcmd); 166 | } 167 | else 168 | { 169 | // Project scissor/clipping rectangles into framebuffer space 170 | ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); 171 | ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); 172 | if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } 173 | if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } 174 | if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; } 175 | if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; } 176 | if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) 177 | continue; 178 | 179 | SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) }; 180 | SDL_RenderSetClipRect(bd->SDLRenderer, &r); 181 | 182 | const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, pos)); 183 | const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, uv)); 184 | #if SDL_VERSION_ATLEAST(2,0,19) 185 | const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, col)); // SDL 2.0.19+ 186 | #else 187 | const int* color = (const int*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, col)); // SDL 2.0.17 and 2.0.18 188 | #endif 189 | 190 | // Bind texture, Draw 191 | SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); 192 | SDL_RenderGeometryRaw(bd->SDLRenderer, tex, 193 | xy, (int)sizeof(ImDrawVert), 194 | color, (int)sizeof(ImDrawVert), 195 | uv, (int)sizeof(ImDrawVert), 196 | cmd_list->VtxBuffer.Size - pcmd->VtxOffset, 197 | idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx)); 198 | } 199 | } 200 | } 201 | 202 | // Restore modified SDL_Renderer state 203 | SDL_RenderSetViewport(bd->SDLRenderer, &old.Viewport); 204 | SDL_RenderSetClipRect(bd->SDLRenderer, old.ClipEnabled ? &old.ClipRect : nullptr); 205 | } 206 | 207 | // Called by Init/NewFrame/Shutdown 208 | bool ImGui_ImplSDLRenderer_CreateFontsTexture() 209 | { 210 | ImGuiIO& io = ImGui::GetIO(); 211 | ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); 212 | 213 | // Build texture atlas 214 | unsigned char* pixels; 215 | int width, height; 216 | io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. 217 | 218 | // Upload texture to graphics system 219 | // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) 220 | bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); 221 | if (bd->FontTexture == nullptr) 222 | { 223 | SDL_Log("error creating texture"); 224 | return false; 225 | } 226 | SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width); 227 | SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND); 228 | SDL_SetTextureScaleMode(bd->FontTexture, SDL_ScaleModeLinear); 229 | 230 | // Store our identifier 231 | io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); 232 | 233 | return true; 234 | } 235 | 236 | void ImGui_ImplSDLRenderer_DestroyFontsTexture() 237 | { 238 | ImGuiIO& io = ImGui::GetIO(); 239 | ImGui_ImplSDLRenderer_Data* bd = ImGui_ImplSDLRenderer_GetBackendData(); 240 | if (bd->FontTexture) 241 | { 242 | io.Fonts->SetTexID(0); 243 | SDL_DestroyTexture(bd->FontTexture); 244 | bd->FontTexture = nullptr; 245 | } 246 | } 247 | 248 | bool ImGui_ImplSDLRenderer_CreateDeviceObjects() 249 | { 250 | return ImGui_ImplSDLRenderer_CreateFontsTexture(); 251 | } 252 | 253 | void ImGui_ImplSDLRenderer_DestroyDeviceObjects() 254 | { 255 | ImGui_ImplSDLRenderer_DestroyFontsTexture(); 256 | } 257 | 258 | #if defined(__clang__) 259 | #pragma clang diagnostic pop 260 | #endif 261 | -------------------------------------------------------------------------------- /docs/EXAMPLES.md: -------------------------------------------------------------------------------- 1 | _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md or view this file with any Markdown viewer)_ 2 | 3 | ## Dear ImGui: Examples 4 | 5 | **The [examples/](https://github.com/ocornut/imgui/blob/master/examples) folder example applications (standalone, ready-to-build) for variety of 6 | platforms and graphics APIs.** They all use standard backends from the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder (see [BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md)). 7 | 8 | The purpose of Examples is to showcase integration with backends, let you try Dear ImGui, and guide you toward 9 | integrating Dear ImGui in your own application/game/engine. 10 | **Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** 11 | 12 | You can find Windows binaries for some of those example applications at: 13 | http://www.dearimgui.org/binaries 14 | 15 | 16 | ### Getting Started 17 | 18 | Integration in a typical existing application, should take <20 lines when using standard backends. 19 | 20 | ```cpp 21 | At initialization: 22 | call ImGui::CreateContext() 23 | call ImGui_ImplXXXX_Init() for each backend. 24 | 25 | At the beginning of your frame: 26 | call ImGui_ImplXXXX_NewFrame() for each backend. 27 | call ImGui::NewFrame() 28 | 29 | At the end of your frame: 30 | call ImGui::Render() 31 | call ImGui_ImplXXXX_RenderDrawData() for your Renderer backend. 32 | 33 | At shutdown: 34 | call ImGui_ImplXXXX_Shutdown() for each backend. 35 | call ImGui::DestroyContext() 36 | ``` 37 | 38 | Example (using [backends/imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp) + [backends/imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)): 39 | 40 | ```cpp 41 | // Create a Dear ImGui context, setup some options 42 | ImGui::CreateContext(); 43 | ImGuiIO& io = ImGui::GetIO(); 44 | io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable some options 45 | 46 | // Initialize Platform + Renderer backends (here: using imgui_impl_win32.cpp + imgui_impl_dx11.cpp) 47 | ImGui_ImplWin32_Init(my_hwnd); 48 | ImGui_ImplDX11_Init(my_d3d_device, my_d3d_device_context); 49 | 50 | // Application main loop 51 | while (true) 52 | { 53 | // Beginning of frame: update Renderer + Platform backend, start Dear ImGui frame 54 | ImGui_ImplDX11_NewFrame(); 55 | ImGui_ImplWin32_NewFrame(); 56 | ImGui::NewFrame(); 57 | 58 | // Any application code here 59 | ImGui::Text("Hello, world!"); 60 | 61 | // End of frame: render Dear ImGui 62 | ImGui::Render(); 63 | ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); 64 | 65 | // Swap 66 | g_pSwapChain->Present(1, 0); 67 | } 68 | 69 | // Shutdown 70 | ImGui_ImplDX11_Shutdown(); 71 | ImGui_ImplWin32_Shutdown(); 72 | ImGui::DestroyContext(); 73 | ``` 74 | 75 | Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. 76 | Please read the comments and instruction at the top of each file. 77 | Please read FAQ at http://www.dearimgui.org/faq 78 | 79 | If you are using any of the backends provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h) 80 | files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with its own individual 81 | Changelog, so if you want to update them later it will be easier to catch up with what changed. 82 | 83 | 84 | ### Examples Applications 85 | 86 | [example_allegro5/](https://github.com/ocornut/imgui/blob/master/examples/example_allegro5/)
87 | Allegro 5 example.
88 | = main.cpp + imgui_impl_allegro5.cpp 89 | 90 | [example_android_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_android_opengl3/)
91 | Android + OpenGL3 (ES) example.
92 | = main.cpp + imgui_impl_android.cpp + imgui_impl_opengl3.cpp 93 | 94 | [example_apple_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_metal/)
95 | OSX & iOS + Metal example.
96 | = main.m + imgui_impl_osx.mm + imgui_impl_metal.mm
97 | It is based on the "cross-platform" game template provided with Xcode as of Xcode 9. 98 | (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. 99 | You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) 100 | 101 | [example_apple_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_apple_opengl2/)
102 | OSX + OpenGL2 example.
103 | = main.mm + imgui_impl_osx.mm + imgui_impl_opengl2.cpp
104 | (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. 105 | You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) 106 | 107 | [example_emscripten_wgpu/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten_wgpu/)
108 | Emcripten + GLFW + WebGPU example.
109 | = main.cpp + imgui_impl_glfw.cpp + imgui_impl_wgpu.cpp 110 | Note that the 'example_glfw_opengl3' and 'example_sdl2_opengl3' examples also supports Emscripten! 111 | 112 | [example_glfw_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_metal/)
113 | GLFW (Mac) + Metal example.
114 | = main.mm + imgui_impl_glfw.cpp + imgui_impl_metal.mm 115 | 116 | [example_glfw_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl2/)
117 | GLFW + OpenGL2 example (legacy, fixed pipeline).
118 | = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp
119 | **DO NOT USE THIS IF YOUR CODE/ENGINE IS USING MODERN GL or WEBGL (SHADERS, VBO, VAO, etc.)**
120 | This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. 121 | If your code is using GL3+ context or any semi modern GL calls, using this renderer is likely to 122 | make things more complicated, will require your code to reset many GL attributes to their initial 123 | state, and might confuse your GPU driver. One star, not recommended. 124 | 125 | [example_glfw_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl3/)
126 | GLFW (Win32, Mac, Linux) + OpenGL3+/ES2/ES3 example (modern, programmable pipeline).
127 | = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp
128 | This uses more modern GL calls and custom shaders.
129 | This support building with Emscripten and targetting WebGL.
130 | Prefer using that if you are using modern GL or WebGL in your application. 131 | 132 | [example_glfw_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/)
133 | GLFW (Win32, Mac, Linux) + Vulkan example.
134 | = main.cpp + imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp
135 | This is quite long and tedious, because: Vulkan. 136 | For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. 137 | 138 | [example_glut_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_glut_opengl2/)
139 | GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2 example.
140 | = main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp
141 | Note that GLUT/FreeGLUT is largely obsolete software, prefer using GLFW or SDL. 142 | 143 | [example_null/](https://github.com/ocornut/imgui/blob/master/examples/example_null/)
144 | Null example, compile and link imgui, create context, run headless with no inputs and no graphics output.
145 | = main.cpp
146 | This is used to quickly test compilation of core imgui files in as many setups as possible. 147 | Because this application doesn't create a window nor a graphic context, there's no graphics output. 148 | 149 | [example_sdl2_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_directx11/)
150 | SDL2 + DirectX11 example, Windows only.
151 | = main.cpp + imgui_impl_sdl2.cpp + imgui_impl_dx11.cpp
152 | This to demonstrate usage of DirectX with SDL2. 153 | 154 | [example_sdl2_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_metal/)
155 | SDL2 + Metal example, Mac only.
156 | = main.mm + imgui_impl_sdl2.cpp + imgui_impl_metal.mm 157 | 158 | [example_sdl2_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_opengl2/)
159 | SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline).
160 | = main.cpp + imgui_impl_sdl2.cpp + imgui_impl_opengl2.cpp
161 | **DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING GL OR WEBGL (SHADERS, VBO, VAO, etc.)**
162 | This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter. 163 | If your code is using GL3+ context or any semi modern GL calls, using this renderer is likely to 164 | make things more complicated, will require your code to reset many GL attributes to their initial 165 | state, and might confuse your GPU driver. One star, not recommended. 166 | 167 | [example_sdl2_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_opengl3/)
168 | SDL2 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example.
169 | = main.cpp + imgui_impl_sdl2.cpp + imgui_impl_opengl3.cpp
170 | This uses more modern GL calls and custom shaders.
171 | This support building with Emscripten and targetting WebGL.
172 | Prefer using that if you are using modern GL or WebGL in your application. 173 | 174 | [example_sdl2_sdlrenderer/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_sdlrenderer/)
175 | SDL2 (Win32, Mac, Linux, etc.) + SDL_Renderer (most graphics backends are supported underneath)
176 | = main.cpp + imgui_impl_sdl2.cpp + imgui_impl_sdlrenderer.cpp
177 | This requires SDL 2.0.18+ (released November 2021)
178 | We do not really recommend using SDL_Renderer as it is a rather primitive API. 179 | 180 | [example_sdl2_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_vulkan/)
181 | SDL2 (Win32, Mac, Linux, etc.) + Vulkan example.
182 | = main.cpp + imgui_impl_sdl2.cpp + imgui_impl_vulkan.cpp
183 | This is quite long and tedious, because: Vulkan.
184 | For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp. 185 | 186 | [example_win32_directx9/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx9/)
187 | DirectX9 example, Windows only.
188 | = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp 189 | 190 | [example_win32_directx10/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx10/)
191 | DirectX10 example, Windows only.
192 | = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx10.cpp 193 | 194 | [example_win32_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx11/)
195 | DirectX11 example, Windows only.
196 | = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx11.cpp 197 | 198 | [example_win32_directx12/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx12/)
199 | DirectX12 example, Windows only.
200 | = main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp
201 | This is quite long and tedious, because: DirectX12. 202 | 203 | 204 | ### Miscellaneous 205 | 206 | **Building** 207 | 208 | Unfortunately nowadays it is still tedious to create and maintain portable build files using external 209 | libraries (the kind we're using here to create a window and render 3D triangles) without relying on 210 | third party software and build systems. For most examples here we choose to provide: 211 | - Makefiles for Linux/OSX 212 | - Batch files for Visual Studio 2008+ 213 | - A .sln project file for Visual Studio 2012+ 214 | - Xcode project files for the Apple examples 215 | Please let us know if they don't work with your setup! 216 | You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those 217 | directly with a command-line compiler. 218 | 219 | If you are interested in using Cmake to build and links examples, see: 220 | https://github.com/ocornut/imgui/pull/1713 and https://github.com/ocornut/imgui/pull/3027 221 | 222 | **About mouse cursor latency** 223 | 224 | Dear ImGui has no particular extra lag for most behaviors, 225 | e.g. the last value passed to 'io.AddMousePosEvent()' before NewFrame() will result in windows being moved 226 | to the right spot at the time of EndFrame()/Render(). At 60 FPS your experience should be pleasant. 227 | 228 | However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated 229 | path and will feel smoother than the majority of contents rendered via regular graphics API (including, 230 | but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane 231 | as the mouse, that disconnect may be jarring to particularly sensitive users. 232 | You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor 233 | using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a 234 | regularly rendered software cursor. 235 | However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at 236 | all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_ 237 | when an interactive drag is in progress. 238 | 239 | Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings. 240 | If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple 241 | drawing a flat 2D shape directly under the mouse cursor! 242 | 243 | -------------------------------------------------------------------------------- /backends/imgui_impl_glut.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for GLUT/FreeGLUT 2 | // This needs to be used along with a Renderer (e.g. OpenGL2) 3 | 4 | // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! 5 | // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! 6 | // !!! Nowadays, prefer using GLFW or SDL instead! 7 | 8 | // Implemented features: 9 | // [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 10 | // Issues: 11 | // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I 12 | // [ ] Platform: Missing horizontal mouse wheel support. 13 | // [ ] Platform: Missing mouse cursor shape/visibility support. 14 | // [ ] Platform: Missing clipboard support (not supported by Glut). 15 | // [ ] Platform: Missing gamepad support. 16 | 17 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 18 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 19 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 20 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 21 | 22 | // CHANGELOG 23 | // (minor and older changes stripped away, please see git history for details) 24 | // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). 25 | // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. 26 | // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). 27 | // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. 28 | // 2019-04-03: Misc: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h. 29 | // 2019-03-25: Misc: Made io.DeltaTime always above zero. 30 | // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. 31 | // 2018-03-22: Added GLUT Platform binding. 32 | 33 | #include "imgui.h" 34 | #include "imgui_impl_glut.h" 35 | #define GL_SILENCE_DEPRECATION 36 | #ifdef __APPLE__ 37 | #include 38 | #else 39 | #include 40 | #endif 41 | 42 | #ifdef _MSC_VER 43 | #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) 44 | #endif 45 | 46 | static int g_Time = 0; // Current time, in milliseconds 47 | 48 | // Glut has 1 function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above. 49 | static ImGuiKey ImGui_ImplGLUT_KeyToImGuiKey(int key) 50 | { 51 | switch (key) 52 | { 53 | case '\t': return ImGuiKey_Tab; 54 | case 256 + GLUT_KEY_LEFT: return ImGuiKey_LeftArrow; 55 | case 256 + GLUT_KEY_RIGHT: return ImGuiKey_RightArrow; 56 | case 256 + GLUT_KEY_UP: return ImGuiKey_UpArrow; 57 | case 256 + GLUT_KEY_DOWN: return ImGuiKey_DownArrow; 58 | case 256 + GLUT_KEY_PAGE_UP: return ImGuiKey_PageUp; 59 | case 256 + GLUT_KEY_PAGE_DOWN: return ImGuiKey_PageDown; 60 | case 256 + GLUT_KEY_HOME: return ImGuiKey_Home; 61 | case 256 + GLUT_KEY_END: return ImGuiKey_End; 62 | case 256 + GLUT_KEY_INSERT: return ImGuiKey_Insert; 63 | case 127: return ImGuiKey_Delete; 64 | case 8: return ImGuiKey_Backspace; 65 | case ' ': return ImGuiKey_Space; 66 | case 13: return ImGuiKey_Enter; 67 | case 27: return ImGuiKey_Escape; 68 | case 39: return ImGuiKey_Apostrophe; 69 | case 44: return ImGuiKey_Comma; 70 | case 45: return ImGuiKey_Minus; 71 | case 46: return ImGuiKey_Period; 72 | case 47: return ImGuiKey_Slash; 73 | case 59: return ImGuiKey_Semicolon; 74 | case 61: return ImGuiKey_Equal; 75 | case 91: return ImGuiKey_LeftBracket; 76 | case 92: return ImGuiKey_Backslash; 77 | case 93: return ImGuiKey_RightBracket; 78 | case 96: return ImGuiKey_GraveAccent; 79 | //case 0: return ImGuiKey_CapsLock; 80 | //case 0: return ImGuiKey_ScrollLock; 81 | case 256 + 0x006D: return ImGuiKey_NumLock; 82 | //case 0: return ImGuiKey_PrintScreen; 83 | //case 0: return ImGuiKey_Pause; 84 | //case '0': return ImGuiKey_Keypad0; 85 | //case '1': return ImGuiKey_Keypad1; 86 | //case '2': return ImGuiKey_Keypad2; 87 | //case '3': return ImGuiKey_Keypad3; 88 | //case '4': return ImGuiKey_Keypad4; 89 | //case '5': return ImGuiKey_Keypad5; 90 | //case '6': return ImGuiKey_Keypad6; 91 | //case '7': return ImGuiKey_Keypad7; 92 | //case '8': return ImGuiKey_Keypad8; 93 | //case '9': return ImGuiKey_Keypad9; 94 | //case 46: return ImGuiKey_KeypadDecimal; 95 | //case 47: return ImGuiKey_KeypadDivide; 96 | case 42: return ImGuiKey_KeypadMultiply; 97 | //case 45: return ImGuiKey_KeypadSubtract; 98 | case 43: return ImGuiKey_KeypadAdd; 99 | //case 13: return ImGuiKey_KeypadEnter; 100 | //case 0: return ImGuiKey_KeypadEqual; 101 | case 256 + 0x0072: return ImGuiKey_LeftCtrl; 102 | case 256 + 0x0070: return ImGuiKey_LeftShift; 103 | case 256 + 0x0074: return ImGuiKey_LeftAlt; 104 | //case 0: return ImGuiKey_LeftSuper; 105 | case 256 + 0x0073: return ImGuiKey_RightCtrl; 106 | case 256 + 0x0071: return ImGuiKey_RightShift; 107 | case 256 + 0x0075: return ImGuiKey_RightAlt; 108 | //case 0: return ImGuiKey_RightSuper; 109 | //case 0: return ImGuiKey_Menu; 110 | case '0': return ImGuiKey_0; 111 | case '1': return ImGuiKey_1; 112 | case '2': return ImGuiKey_2; 113 | case '3': return ImGuiKey_3; 114 | case '4': return ImGuiKey_4; 115 | case '5': return ImGuiKey_5; 116 | case '6': return ImGuiKey_6; 117 | case '7': return ImGuiKey_7; 118 | case '8': return ImGuiKey_8; 119 | case '9': return ImGuiKey_9; 120 | case 'A': case 'a': return ImGuiKey_A; 121 | case 'B': case 'b': return ImGuiKey_B; 122 | case 'C': case 'c': return ImGuiKey_C; 123 | case 'D': case 'd': return ImGuiKey_D; 124 | case 'E': case 'e': return ImGuiKey_E; 125 | case 'F': case 'f': return ImGuiKey_F; 126 | case 'G': case 'g': return ImGuiKey_G; 127 | case 'H': case 'h': return ImGuiKey_H; 128 | case 'I': case 'i': return ImGuiKey_I; 129 | case 'J': case 'j': return ImGuiKey_J; 130 | case 'K': case 'k': return ImGuiKey_K; 131 | case 'L': case 'l': return ImGuiKey_L; 132 | case 'M': case 'm': return ImGuiKey_M; 133 | case 'N': case 'n': return ImGuiKey_N; 134 | case 'O': case 'o': return ImGuiKey_O; 135 | case 'P': case 'p': return ImGuiKey_P; 136 | case 'Q': case 'q': return ImGuiKey_Q; 137 | case 'R': case 'r': return ImGuiKey_R; 138 | case 'S': case 's': return ImGuiKey_S; 139 | case 'T': case 't': return ImGuiKey_T; 140 | case 'U': case 'u': return ImGuiKey_U; 141 | case 'V': case 'v': return ImGuiKey_V; 142 | case 'W': case 'w': return ImGuiKey_W; 143 | case 'X': case 'x': return ImGuiKey_X; 144 | case 'Y': case 'y': return ImGuiKey_Y; 145 | case 'Z': case 'z': return ImGuiKey_Z; 146 | case 256 + GLUT_KEY_F1: return ImGuiKey_F1; 147 | case 256 + GLUT_KEY_F2: return ImGuiKey_F2; 148 | case 256 + GLUT_KEY_F3: return ImGuiKey_F3; 149 | case 256 + GLUT_KEY_F4: return ImGuiKey_F4; 150 | case 256 + GLUT_KEY_F5: return ImGuiKey_F5; 151 | case 256 + GLUT_KEY_F6: return ImGuiKey_F6; 152 | case 256 + GLUT_KEY_F7: return ImGuiKey_F7; 153 | case 256 + GLUT_KEY_F8: return ImGuiKey_F8; 154 | case 256 + GLUT_KEY_F9: return ImGuiKey_F9; 155 | case 256 + GLUT_KEY_F10: return ImGuiKey_F10; 156 | case 256 + GLUT_KEY_F11: return ImGuiKey_F11; 157 | case 256 + GLUT_KEY_F12: return ImGuiKey_F12; 158 | default: return ImGuiKey_None; 159 | } 160 | } 161 | 162 | bool ImGui_ImplGLUT_Init() 163 | { 164 | ImGuiIO& io = ImGui::GetIO(); 165 | 166 | #ifdef FREEGLUT 167 | io.BackendPlatformName = "imgui_impl_glut (freeglut)"; 168 | #else 169 | io.BackendPlatformName = "imgui_impl_glut"; 170 | #endif 171 | g_Time = 0; 172 | 173 | return true; 174 | } 175 | 176 | void ImGui_ImplGLUT_InstallFuncs() 177 | { 178 | glutReshapeFunc(ImGui_ImplGLUT_ReshapeFunc); 179 | glutMotionFunc(ImGui_ImplGLUT_MotionFunc); 180 | glutPassiveMotionFunc(ImGui_ImplGLUT_MotionFunc); 181 | glutMouseFunc(ImGui_ImplGLUT_MouseFunc); 182 | #ifdef __FREEGLUT_EXT_H__ 183 | glutMouseWheelFunc(ImGui_ImplGLUT_MouseWheelFunc); 184 | #endif 185 | glutKeyboardFunc(ImGui_ImplGLUT_KeyboardFunc); 186 | glutKeyboardUpFunc(ImGui_ImplGLUT_KeyboardUpFunc); 187 | glutSpecialFunc(ImGui_ImplGLUT_SpecialFunc); 188 | glutSpecialUpFunc(ImGui_ImplGLUT_SpecialUpFunc); 189 | } 190 | 191 | void ImGui_ImplGLUT_Shutdown() 192 | { 193 | } 194 | 195 | void ImGui_ImplGLUT_NewFrame() 196 | { 197 | // Setup time step 198 | ImGuiIO& io = ImGui::GetIO(); 199 | int current_time = glutGet(GLUT_ELAPSED_TIME); 200 | int delta_time_ms = (current_time - g_Time); 201 | if (delta_time_ms <= 0) 202 | delta_time_ms = 1; 203 | io.DeltaTime = delta_time_ms / 1000.0f; 204 | g_Time = current_time; 205 | 206 | // Start the frame 207 | ImGui::NewFrame(); 208 | } 209 | 210 | static void ImGui_ImplGLUT_UpdateKeyModifiers() 211 | { 212 | ImGuiIO& io = ImGui::GetIO(); 213 | int glut_key_mods = glutGetModifiers(); 214 | io.AddKeyEvent(ImGuiMod_Ctrl, (glut_key_mods & GLUT_ACTIVE_CTRL) != 0); 215 | io.AddKeyEvent(ImGuiMod_Shift, (glut_key_mods & GLUT_ACTIVE_SHIFT) != 0); 216 | io.AddKeyEvent(ImGuiMod_Alt, (glut_key_mods & GLUT_ACTIVE_ALT) != 0); 217 | } 218 | 219 | static void ImGui_ImplGLUT_AddKeyEvent(ImGuiKey key, bool down, int native_keycode) 220 | { 221 | ImGuiIO& io = ImGui::GetIO(); 222 | io.AddKeyEvent(key, down); 223 | io.SetKeyEventNativeData(key, native_keycode, -1); // To support legacy indexing (<1.87 user code) 224 | } 225 | 226 | void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y) 227 | { 228 | // Send character to imgui 229 | //printf("char_down_func %d '%c'\n", c, c); 230 | ImGuiIO& io = ImGui::GetIO(); 231 | if (c >= 32) 232 | io.AddInputCharacter((unsigned int)c); 233 | 234 | ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c); 235 | ImGui_ImplGLUT_AddKeyEvent(key, true, c); 236 | ImGui_ImplGLUT_UpdateKeyModifiers(); 237 | (void)x; (void)y; // Unused 238 | } 239 | 240 | void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y) 241 | { 242 | //printf("char_up_func %d '%c'\n", c, c); 243 | ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c); 244 | ImGui_ImplGLUT_AddKeyEvent(key, false, c); 245 | ImGui_ImplGLUT_UpdateKeyModifiers(); 246 | (void)x; (void)y; // Unused 247 | } 248 | 249 | void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y) 250 | { 251 | //printf("key_down_func %d\n", key); 252 | ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256); 253 | ImGui_ImplGLUT_AddKeyEvent(imgui_key, true, key + 256); 254 | ImGui_ImplGLUT_UpdateKeyModifiers(); 255 | (void)x; (void)y; // Unused 256 | } 257 | 258 | void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y) 259 | { 260 | //printf("key_up_func %d\n", key); 261 | ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256); 262 | ImGui_ImplGLUT_AddKeyEvent(imgui_key, false, key + 256); 263 | ImGui_ImplGLUT_UpdateKeyModifiers(); 264 | (void)x; (void)y; // Unused 265 | } 266 | 267 | void ImGui_ImplGLUT_MouseFunc(int glut_button, int state, int x, int y) 268 | { 269 | ImGuiIO& io = ImGui::GetIO(); 270 | io.AddMousePosEvent((float)x, (float)y); 271 | int button = -1; 272 | if (glut_button == GLUT_LEFT_BUTTON) button = 0; 273 | if (glut_button == GLUT_RIGHT_BUTTON) button = 1; 274 | if (glut_button == GLUT_MIDDLE_BUTTON) button = 2; 275 | if (button != -1 && (state == GLUT_DOWN || state == GLUT_UP)) 276 | io.AddMouseButtonEvent(button, state == GLUT_DOWN); 277 | } 278 | 279 | #ifdef __FREEGLUT_EXT_H__ 280 | void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y) 281 | { 282 | ImGuiIO& io = ImGui::GetIO(); 283 | io.AddMousePosEvent((float)x, (float)y); 284 | if (dir != 0) 285 | io.AddMouseWheelEvent(0.0f, dir > 0 ? 1.0f : -1.0f); 286 | (void)button; // Unused 287 | } 288 | #endif 289 | 290 | void ImGui_ImplGLUT_ReshapeFunc(int w, int h) 291 | { 292 | ImGuiIO& io = ImGui::GetIO(); 293 | io.DisplaySize = ImVec2((float)w, (float)h); 294 | } 295 | 296 | void ImGui_ImplGLUT_MotionFunc(int x, int y) 297 | { 298 | ImGuiIO& io = ImGui::GetIO(); 299 | io.AddMousePosEvent((float)x, (float)y); 300 | } 301 | -------------------------------------------------------------------------------- /misc/fonts/binary_to_compressed_c.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui 2 | // (binary_to_compressed_c.cpp) 3 | // Helper tool to turn a file into a C array, if you want to embed font data in your source code. 4 | 5 | // The data is first compressed with stb_compress() to reduce source code size, 6 | // then encoded in Base85 to fit in a string so we can fit roughly 4 bytes of compressed data into 5 bytes of source code (suggested by @mmalex) 7 | // (If we used 32-bit constants it would require take 11 bytes of source code to encode 4 bytes, and be endianness dependent) 8 | // Note that even with compression, the output array is likely to be bigger than the binary file.. 9 | // Load compressed TTF fonts with ImGui::GetIO().Fonts->AddFontFromMemoryCompressedTTF() 10 | 11 | // Build with, e.g: 12 | // # cl.exe binary_to_compressed_c.cpp 13 | // # g++ binary_to_compressed_c.cpp 14 | // # clang++ binary_to_compressed_c.cpp 15 | // You can also find a precompiled Windows binary in the binary/demo package available from https://github.com/ocornut/imgui 16 | 17 | // Usage: 18 | // binary_to_compressed_c.exe [-base85] [-nocompress] [-nostatic] 19 | // Usage example: 20 | // # binary_to_compressed_c.exe myfont.ttf MyFont > myfont.cpp 21 | // # binary_to_compressed_c.exe -base85 myfont.ttf MyFont > myfont.cpp 22 | 23 | #define _CRT_SECURE_NO_WARNINGS 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | // stb_compress* from stb.h - declaration 30 | typedef unsigned int stb_uint; 31 | typedef unsigned char stb_uchar; 32 | stb_uint stb_compress(stb_uchar* out, stb_uchar* in, stb_uint len); 33 | 34 | static bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression, bool use_static); 35 | 36 | int main(int argc, char** argv) 37 | { 38 | if (argc < 3) 39 | { 40 | printf("Syntax: %s [-base85] [-nocompress] [-nostatic] \n", argv[0]); 41 | return 0; 42 | } 43 | 44 | int argn = 1; 45 | bool use_base85_encoding = false; 46 | bool use_compression = true; 47 | bool use_static = true; 48 | while (argn < (argc - 2) && argv[argn][0] == '-') 49 | { 50 | if (strcmp(argv[argn], "-base85") == 0) { use_base85_encoding = true; argn++; } 51 | else if (strcmp(argv[argn], "-nocompress") == 0) { use_compression = false; argn++; } 52 | else if (strcmp(argv[argn], "-nostatic") == 0) { use_static = false; argn++; } 53 | else 54 | { 55 | fprintf(stderr, "Unknown argument: '%s'\n", argv[argn]); 56 | return 1; 57 | } 58 | } 59 | 60 | bool ret = binary_to_compressed_c(argv[argn], argv[argn + 1], use_base85_encoding, use_compression, use_static); 61 | if (!ret) 62 | fprintf(stderr, "Error opening or reading file: '%s'\n", argv[argn]); 63 | return ret ? 0 : 1; 64 | } 65 | 66 | char Encode85Byte(unsigned int x) 67 | { 68 | x = (x % 85) + 35; 69 | return (char)((x >= '\\') ? x + 1 : x); 70 | } 71 | 72 | bool binary_to_compressed_c(const char* filename, const char* symbol, bool use_base85_encoding, bool use_compression, bool use_static) 73 | { 74 | // Read file 75 | FILE* f = fopen(filename, "rb"); 76 | if (!f) return false; 77 | int data_sz; 78 | if (fseek(f, 0, SEEK_END) || (data_sz = (int)ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return false; } 79 | char* data = new char[data_sz + 4]; 80 | if (fread(data, 1, data_sz, f) != (size_t)data_sz) { fclose(f); delete[] data; return false; } 81 | memset((void*)(((char*)data) + data_sz), 0, 4); 82 | fclose(f); 83 | 84 | // Compress 85 | int maxlen = data_sz + 512 + (data_sz >> 2) + sizeof(int); // total guess 86 | char* compressed = use_compression ? new char[maxlen] : data; 87 | int compressed_sz = use_compression ? stb_compress((stb_uchar*)compressed, (stb_uchar*)data, data_sz) : data_sz; 88 | if (use_compression) 89 | memset(compressed + compressed_sz, 0, maxlen - compressed_sz); 90 | 91 | // Output as Base85 encoded 92 | FILE* out = stdout; 93 | fprintf(out, "// File: '%s' (%d bytes)\n", filename, (int)data_sz); 94 | fprintf(out, "// Exported using binary_to_compressed_c.cpp\n"); 95 | const char* static_str = use_static ? "static " : ""; 96 | const char* compressed_str = use_compression ? "compressed_" : ""; 97 | if (use_base85_encoding) 98 | { 99 | fprintf(out, "%sconst char %s_%sdata_base85[%d+1] =\n \"", static_str, symbol, compressed_str, (int)((compressed_sz + 3) / 4)*5); 100 | char prev_c = 0; 101 | for (int src_i = 0; src_i < compressed_sz; src_i += 4) 102 | { 103 | // This is made a little more complicated by the fact that ??X sequences are interpreted as trigraphs by old C/C++ compilers. So we need to escape pairs of ??. 104 | unsigned int d = *(unsigned int*)(compressed + src_i); 105 | for (unsigned int n5 = 0; n5 < 5; n5++, d /= 85) 106 | { 107 | char c = Encode85Byte(d); 108 | fprintf(out, (c == '?' && prev_c == '?') ? "\\%c" : "%c", c); 109 | prev_c = c; 110 | } 111 | if ((src_i % 112) == 112 - 4) 112 | fprintf(out, "\"\n \""); 113 | } 114 | fprintf(out, "\";\n\n"); 115 | } 116 | else 117 | { 118 | fprintf(out, "%sconst unsigned int %s_%ssize = %d;\n", static_str, symbol, compressed_str, (int)compressed_sz); 119 | fprintf(out, "%sconst unsigned int %s_%sdata[%d/4] =\n{", static_str, symbol, compressed_str, (int)((compressed_sz + 3) / 4)*4); 120 | int column = 0; 121 | for (int i = 0; i < compressed_sz; i += 4) 122 | { 123 | unsigned int d = *(unsigned int*)(compressed + i); 124 | if ((column++ % 12) == 0) 125 | fprintf(out, "\n 0x%08x, ", d); 126 | else 127 | fprintf(out, "0x%08x, ", d); 128 | } 129 | fprintf(out, "\n};\n\n"); 130 | } 131 | 132 | // Cleanup 133 | delete[] data; 134 | if (use_compression) 135 | delete[] compressed; 136 | return true; 137 | } 138 | 139 | // stb_compress* from stb.h - definition 140 | 141 | //////////////////// compressor /////////////////////// 142 | 143 | static stb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen) 144 | { 145 | const unsigned long ADLER_MOD = 65521; 146 | unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; 147 | unsigned long blocklen, i; 148 | 149 | blocklen = buflen % 5552; 150 | while (buflen) { 151 | for (i=0; i + 7 < blocklen; i += 8) { 152 | s1 += buffer[0], s2 += s1; 153 | s1 += buffer[1], s2 += s1; 154 | s1 += buffer[2], s2 += s1; 155 | s1 += buffer[3], s2 += s1; 156 | s1 += buffer[4], s2 += s1; 157 | s1 += buffer[5], s2 += s1; 158 | s1 += buffer[6], s2 += s1; 159 | s1 += buffer[7], s2 += s1; 160 | 161 | buffer += 8; 162 | } 163 | 164 | for (; i < blocklen; ++i) 165 | s1 += *buffer++, s2 += s1; 166 | 167 | s1 %= ADLER_MOD, s2 %= ADLER_MOD; 168 | buflen -= blocklen; 169 | blocklen = 5552; 170 | } 171 | return (s2 << 16) + s1; 172 | } 173 | 174 | static unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen) 175 | { 176 | stb_uint i; 177 | for (i=0; i < maxlen; ++i) 178 | if (m1[i] != m2[i]) return i; 179 | return i; 180 | } 181 | 182 | // simple implementation that just takes the source data in a big block 183 | 184 | static stb_uchar *stb__out; 185 | static FILE *stb__outfile; 186 | static stb_uint stb__outbytes; 187 | 188 | static void stb__write(unsigned char v) 189 | { 190 | fputc(v, stb__outfile); 191 | ++stb__outbytes; 192 | } 193 | 194 | //#define stb_out(v) (stb__out ? *stb__out++ = (stb_uchar) (v) : stb__write((stb_uchar) (v))) 195 | #define stb_out(v) do { if (stb__out) *stb__out++ = (stb_uchar) (v); else stb__write((stb_uchar) (v)); } while (0) 196 | 197 | static void stb_out2(stb_uint v) { stb_out(v >> 8); stb_out(v); } 198 | static void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); } 199 | static void stb_out4(stb_uint v) { stb_out(v >> 24); stb_out(v >> 16); stb_out(v >> 8 ); stb_out(v); } 200 | 201 | static void outliterals(stb_uchar *in, int numlit) 202 | { 203 | while (numlit > 65536) { 204 | outliterals(in,65536); 205 | in += 65536; 206 | numlit -= 65536; 207 | } 208 | 209 | if (numlit == 0) ; 210 | else if (numlit <= 32) stb_out (0x000020 + numlit-1); 211 | else if (numlit <= 2048) stb_out2(0x000800 + numlit-1); 212 | else /* numlit <= 65536) */ stb_out3(0x070000 + numlit-1); 213 | 214 | if (stb__out) { 215 | memcpy(stb__out,in,numlit); 216 | stb__out += numlit; 217 | } else 218 | fwrite(in, 1, numlit, stb__outfile); 219 | } 220 | 221 | static int stb__window = 0x40000; // 256K 222 | 223 | static int stb_not_crap(int best, int dist) 224 | { 225 | return ((best > 2 && dist <= 0x00100) 226 | || (best > 5 && dist <= 0x04000) 227 | || (best > 7 && dist <= 0x80000)); 228 | } 229 | 230 | static stb_uint stb__hashsize = 32768; 231 | 232 | // note that you can play with the hashing functions all you 233 | // want without needing to change the decompressor 234 | #define stb__hc(q,h,c) (((h) << 7) + ((h) >> 25) + q[c]) 235 | #define stb__hc2(q,h,c,d) (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d]) 236 | #define stb__hc3(q,c,d,e) ((q[c] << 14) + (q[d] << 7) + q[e]) 237 | 238 | static unsigned int stb__running_adler; 239 | 240 | static int stb_compress_chunk(stb_uchar *history, 241 | stb_uchar *start, 242 | stb_uchar *end, 243 | int length, 244 | int *pending_literals, 245 | stb_uchar **chash, 246 | stb_uint mask) 247 | { 248 | (void)history; 249 | int window = stb__window; 250 | stb_uint match_max; 251 | stb_uchar *lit_start = start - *pending_literals; 252 | stb_uchar *q = start; 253 | 254 | #define STB__SCRAMBLE(h) (((h) + ((h) >> 16)) & mask) 255 | 256 | // stop short of the end so we don't scan off the end doing 257 | // the hashing; this means we won't compress the last few bytes 258 | // unless they were part of something longer 259 | while (q < start+length && q+12 < end) { 260 | int m; 261 | stb_uint h1,h2,h3,h4, h; 262 | stb_uchar *t; 263 | int best = 2, dist=0; 264 | 265 | if (q+65536 > end) 266 | match_max = (stb_uint)(end-q); 267 | else 268 | match_max = 65536; 269 | 270 | #define stb__nc(b,d) ((d) <= window && ((b) > 9 || stb_not_crap((int)(b),(int)(d)))) 271 | 272 | #define STB__TRY(t,p) /* avoid retrying a match we already tried */ \ 273 | if (p ? dist != (int)(q-t) : 1) \ 274 | if ((m = stb_matchlen(t, q, match_max)) > best) \ 275 | if (stb__nc(m,q-(t))) \ 276 | best = m, dist = (int)(q - (t)) 277 | 278 | // rather than search for all matches, only try 4 candidate locations, 279 | // chosen based on 4 different hash functions of different lengths. 280 | // this strategy is inspired by LZO; hashing is unrolled here using the 281 | // 'hc' macro 282 | h = stb__hc3(q,0, 1, 2); h1 = STB__SCRAMBLE(h); 283 | t = chash[h1]; if (t) STB__TRY(t,0); 284 | h = stb__hc2(q,h, 3, 4); h2 = STB__SCRAMBLE(h); 285 | h = stb__hc2(q,h, 5, 6); t = chash[h2]; if (t) STB__TRY(t,1); 286 | h = stb__hc2(q,h, 7, 8); h3 = STB__SCRAMBLE(h); 287 | h = stb__hc2(q,h, 9,10); t = chash[h3]; if (t) STB__TRY(t,1); 288 | h = stb__hc2(q,h,11,12); h4 = STB__SCRAMBLE(h); 289 | t = chash[h4]; if (t) STB__TRY(t,1); 290 | 291 | // because we use a shared hash table, can only update it 292 | // _after_ we've probed all of them 293 | chash[h1] = chash[h2] = chash[h3] = chash[h4] = q; 294 | 295 | if (best > 2) 296 | assert(dist > 0); 297 | 298 | // see if our best match qualifies 299 | if (best < 3) { // fast path literals 300 | ++q; 301 | } else if (best > 2 && best <= 0x80 && dist <= 0x100) { 302 | outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best); 303 | stb_out(0x80 + best-1); 304 | stb_out(dist-1); 305 | } else if (best > 5 && best <= 0x100 && dist <= 0x4000) { 306 | outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best); 307 | stb_out2(0x4000 + dist-1); 308 | stb_out(best-1); 309 | } else if (best > 7 && best <= 0x100 && dist <= 0x80000) { 310 | outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best); 311 | stb_out3(0x180000 + dist-1); 312 | stb_out(best-1); 313 | } else if (best > 8 && best <= 0x10000 && dist <= 0x80000) { 314 | outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best); 315 | stb_out3(0x100000 + dist-1); 316 | stb_out2(best-1); 317 | } else if (best > 9 && dist <= 0x1000000) { 318 | if (best > 65536) best = 65536; 319 | outliterals(lit_start, (int)(q-lit_start)); lit_start = (q += best); 320 | if (best <= 0x100) { 321 | stb_out(0x06); 322 | stb_out3(dist-1); 323 | stb_out(best-1); 324 | } else { 325 | stb_out(0x04); 326 | stb_out3(dist-1); 327 | stb_out2(best-1); 328 | } 329 | } else { // fallback literals if no match was a balanced tradeoff 330 | ++q; 331 | } 332 | } 333 | 334 | // if we didn't get all the way, add the rest to literals 335 | if (q-start < length) 336 | q = start+length; 337 | 338 | // the literals are everything from lit_start to q 339 | *pending_literals = (int)(q - lit_start); 340 | 341 | stb__running_adler = stb_adler32(stb__running_adler, start, (stb_uint)(q - start)); 342 | return (int)(q - start); 343 | } 344 | 345 | static int stb_compress_inner(stb_uchar *input, stb_uint length) 346 | { 347 | int literals = 0; 348 | stb_uint len,i; 349 | 350 | stb_uchar **chash; 351 | chash = (stb_uchar**) malloc(stb__hashsize * sizeof(stb_uchar*)); 352 | if (chash == NULL) return 0; // failure 353 | for (i=0; i < stb__hashsize; ++i) 354 | chash[i] = NULL; 355 | 356 | // stream signature 357 | stb_out(0x57); stb_out(0xbc); 358 | stb_out2(0); 359 | 360 | stb_out4(0); // 64-bit length requires 32-bit leading 0 361 | stb_out4(length); 362 | stb_out4(stb__window); 363 | 364 | stb__running_adler = 1; 365 | 366 | len = stb_compress_chunk(input, input, input+length, length, &literals, chash, stb__hashsize-1); 367 | assert(len == length); 368 | 369 | outliterals(input+length - literals, literals); 370 | 371 | free(chash); 372 | 373 | stb_out2(0x05fa); // end opcode 374 | 375 | stb_out4(stb__running_adler); 376 | 377 | return 1; // success 378 | } 379 | 380 | stb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length) 381 | { 382 | stb__out = out; 383 | stb__outfile = NULL; 384 | 385 | stb_compress_inner(input, length); 386 | 387 | return (stb_uint)(stb__out - out); 388 | } 389 | -------------------------------------------------------------------------------- /backends/imgui_impl_android.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Binding for Android native app 2 | // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3) 3 | 4 | // Implemented features: 5 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 6 | // Missing features: 7 | // [ ] Platform: Clipboard support. 8 | // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 9 | // [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android. 10 | // Important: 11 | // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this. 12 | // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446) 13 | // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446) 14 | 15 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 16 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 17 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 18 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 19 | 20 | // CHANGELOG 21 | // (minor and older changes stripped away, please see git history for details) 22 | // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). 23 | // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. 24 | // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). 25 | // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. 26 | // 2021-03-04: Initial version. 27 | 28 | #include "imgui.h" 29 | #include "imgui_impl_android.h" 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | 36 | // Android data 37 | static double g_Time = 0.0; 38 | static ANativeWindow* g_Window; 39 | static char g_LogTag[] = "ImGuiExample"; 40 | 41 | static ImGuiKey ImGui_ImplAndroid_KeyCodeToImGuiKey(int32_t key_code) 42 | { 43 | switch (key_code) 44 | { 45 | case AKEYCODE_TAB: return ImGuiKey_Tab; 46 | case AKEYCODE_DPAD_LEFT: return ImGuiKey_LeftArrow; 47 | case AKEYCODE_DPAD_RIGHT: return ImGuiKey_RightArrow; 48 | case AKEYCODE_DPAD_UP: return ImGuiKey_UpArrow; 49 | case AKEYCODE_DPAD_DOWN: return ImGuiKey_DownArrow; 50 | case AKEYCODE_PAGE_UP: return ImGuiKey_PageUp; 51 | case AKEYCODE_PAGE_DOWN: return ImGuiKey_PageDown; 52 | case AKEYCODE_MOVE_HOME: return ImGuiKey_Home; 53 | case AKEYCODE_MOVE_END: return ImGuiKey_End; 54 | case AKEYCODE_INSERT: return ImGuiKey_Insert; 55 | case AKEYCODE_FORWARD_DEL: return ImGuiKey_Delete; 56 | case AKEYCODE_DEL: return ImGuiKey_Backspace; 57 | case AKEYCODE_SPACE: return ImGuiKey_Space; 58 | case AKEYCODE_ENTER: return ImGuiKey_Enter; 59 | case AKEYCODE_ESCAPE: return ImGuiKey_Escape; 60 | case AKEYCODE_APOSTROPHE: return ImGuiKey_Apostrophe; 61 | case AKEYCODE_COMMA: return ImGuiKey_Comma; 62 | case AKEYCODE_MINUS: return ImGuiKey_Minus; 63 | case AKEYCODE_PERIOD: return ImGuiKey_Period; 64 | case AKEYCODE_SLASH: return ImGuiKey_Slash; 65 | case AKEYCODE_SEMICOLON: return ImGuiKey_Semicolon; 66 | case AKEYCODE_EQUALS: return ImGuiKey_Equal; 67 | case AKEYCODE_LEFT_BRACKET: return ImGuiKey_LeftBracket; 68 | case AKEYCODE_BACKSLASH: return ImGuiKey_Backslash; 69 | case AKEYCODE_RIGHT_BRACKET: return ImGuiKey_RightBracket; 70 | case AKEYCODE_GRAVE: return ImGuiKey_GraveAccent; 71 | case AKEYCODE_CAPS_LOCK: return ImGuiKey_CapsLock; 72 | case AKEYCODE_SCROLL_LOCK: return ImGuiKey_ScrollLock; 73 | case AKEYCODE_NUM_LOCK: return ImGuiKey_NumLock; 74 | case AKEYCODE_SYSRQ: return ImGuiKey_PrintScreen; 75 | case AKEYCODE_BREAK: return ImGuiKey_Pause; 76 | case AKEYCODE_NUMPAD_0: return ImGuiKey_Keypad0; 77 | case AKEYCODE_NUMPAD_1: return ImGuiKey_Keypad1; 78 | case AKEYCODE_NUMPAD_2: return ImGuiKey_Keypad2; 79 | case AKEYCODE_NUMPAD_3: return ImGuiKey_Keypad3; 80 | case AKEYCODE_NUMPAD_4: return ImGuiKey_Keypad4; 81 | case AKEYCODE_NUMPAD_5: return ImGuiKey_Keypad5; 82 | case AKEYCODE_NUMPAD_6: return ImGuiKey_Keypad6; 83 | case AKEYCODE_NUMPAD_7: return ImGuiKey_Keypad7; 84 | case AKEYCODE_NUMPAD_8: return ImGuiKey_Keypad8; 85 | case AKEYCODE_NUMPAD_9: return ImGuiKey_Keypad9; 86 | case AKEYCODE_NUMPAD_DOT: return ImGuiKey_KeypadDecimal; 87 | case AKEYCODE_NUMPAD_DIVIDE: return ImGuiKey_KeypadDivide; 88 | case AKEYCODE_NUMPAD_MULTIPLY: return ImGuiKey_KeypadMultiply; 89 | case AKEYCODE_NUMPAD_SUBTRACT: return ImGuiKey_KeypadSubtract; 90 | case AKEYCODE_NUMPAD_ADD: return ImGuiKey_KeypadAdd; 91 | case AKEYCODE_NUMPAD_ENTER: return ImGuiKey_KeypadEnter; 92 | case AKEYCODE_NUMPAD_EQUALS: return ImGuiKey_KeypadEqual; 93 | case AKEYCODE_CTRL_LEFT: return ImGuiKey_LeftCtrl; 94 | case AKEYCODE_SHIFT_LEFT: return ImGuiKey_LeftShift; 95 | case AKEYCODE_ALT_LEFT: return ImGuiKey_LeftAlt; 96 | case AKEYCODE_META_LEFT: return ImGuiKey_LeftSuper; 97 | case AKEYCODE_CTRL_RIGHT: return ImGuiKey_RightCtrl; 98 | case AKEYCODE_SHIFT_RIGHT: return ImGuiKey_RightShift; 99 | case AKEYCODE_ALT_RIGHT: return ImGuiKey_RightAlt; 100 | case AKEYCODE_META_RIGHT: return ImGuiKey_RightSuper; 101 | case AKEYCODE_MENU: return ImGuiKey_Menu; 102 | case AKEYCODE_0: return ImGuiKey_0; 103 | case AKEYCODE_1: return ImGuiKey_1; 104 | case AKEYCODE_2: return ImGuiKey_2; 105 | case AKEYCODE_3: return ImGuiKey_3; 106 | case AKEYCODE_4: return ImGuiKey_4; 107 | case AKEYCODE_5: return ImGuiKey_5; 108 | case AKEYCODE_6: return ImGuiKey_6; 109 | case AKEYCODE_7: return ImGuiKey_7; 110 | case AKEYCODE_8: return ImGuiKey_8; 111 | case AKEYCODE_9: return ImGuiKey_9; 112 | case AKEYCODE_A: return ImGuiKey_A; 113 | case AKEYCODE_B: return ImGuiKey_B; 114 | case AKEYCODE_C: return ImGuiKey_C; 115 | case AKEYCODE_D: return ImGuiKey_D; 116 | case AKEYCODE_E: return ImGuiKey_E; 117 | case AKEYCODE_F: return ImGuiKey_F; 118 | case AKEYCODE_G: return ImGuiKey_G; 119 | case AKEYCODE_H: return ImGuiKey_H; 120 | case AKEYCODE_I: return ImGuiKey_I; 121 | case AKEYCODE_J: return ImGuiKey_J; 122 | case AKEYCODE_K: return ImGuiKey_K; 123 | case AKEYCODE_L: return ImGuiKey_L; 124 | case AKEYCODE_M: return ImGuiKey_M; 125 | case AKEYCODE_N: return ImGuiKey_N; 126 | case AKEYCODE_O: return ImGuiKey_O; 127 | case AKEYCODE_P: return ImGuiKey_P; 128 | case AKEYCODE_Q: return ImGuiKey_Q; 129 | case AKEYCODE_R: return ImGuiKey_R; 130 | case AKEYCODE_S: return ImGuiKey_S; 131 | case AKEYCODE_T: return ImGuiKey_T; 132 | case AKEYCODE_U: return ImGuiKey_U; 133 | case AKEYCODE_V: return ImGuiKey_V; 134 | case AKEYCODE_W: return ImGuiKey_W; 135 | case AKEYCODE_X: return ImGuiKey_X; 136 | case AKEYCODE_Y: return ImGuiKey_Y; 137 | case AKEYCODE_Z: return ImGuiKey_Z; 138 | case AKEYCODE_F1: return ImGuiKey_F1; 139 | case AKEYCODE_F2: return ImGuiKey_F2; 140 | case AKEYCODE_F3: return ImGuiKey_F3; 141 | case AKEYCODE_F4: return ImGuiKey_F4; 142 | case AKEYCODE_F5: return ImGuiKey_F5; 143 | case AKEYCODE_F6: return ImGuiKey_F6; 144 | case AKEYCODE_F7: return ImGuiKey_F7; 145 | case AKEYCODE_F8: return ImGuiKey_F8; 146 | case AKEYCODE_F9: return ImGuiKey_F9; 147 | case AKEYCODE_F10: return ImGuiKey_F10; 148 | case AKEYCODE_F11: return ImGuiKey_F11; 149 | case AKEYCODE_F12: return ImGuiKey_F12; 150 | default: return ImGuiKey_None; 151 | } 152 | } 153 | 154 | int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event) 155 | { 156 | ImGuiIO& io = ImGui::GetIO(); 157 | int32_t event_type = AInputEvent_getType(input_event); 158 | switch (event_type) 159 | { 160 | case AINPUT_EVENT_TYPE_KEY: 161 | { 162 | int32_t event_key_code = AKeyEvent_getKeyCode(input_event); 163 | int32_t event_scan_code = AKeyEvent_getScanCode(input_event); 164 | int32_t event_action = AKeyEvent_getAction(input_event); 165 | int32_t event_meta_state = AKeyEvent_getMetaState(input_event); 166 | 167 | io.AddKeyEvent(ImGuiMod_Ctrl, (event_meta_state & AMETA_CTRL_ON) != 0); 168 | io.AddKeyEvent(ImGuiMod_Shift, (event_meta_state & AMETA_SHIFT_ON) != 0); 169 | io.AddKeyEvent(ImGuiMod_Alt, (event_meta_state & AMETA_ALT_ON) != 0); 170 | io.AddKeyEvent(ImGuiMod_Super, (event_meta_state & AMETA_META_ON) != 0); 171 | 172 | switch (event_action) 173 | { 174 | // FIXME: AKEY_EVENT_ACTION_DOWN and AKEY_EVENT_ACTION_UP occur at once as soon as a touch pointer 175 | // goes up from a key. We use a simple key event queue/ and process one event per key per frame in 176 | // ImGui_ImplAndroid_NewFrame()...or consider using IO queue, if suitable: https://github.com/ocornut/imgui/issues/2787 177 | case AKEY_EVENT_ACTION_DOWN: 178 | case AKEY_EVENT_ACTION_UP: 179 | { 180 | ImGuiKey key = ImGui_ImplAndroid_KeyCodeToImGuiKey(event_key_code); 181 | if (key != ImGuiKey_None && (event_action == AKEY_EVENT_ACTION_DOWN || event_action == AKEY_EVENT_ACTION_UP)) 182 | { 183 | io.AddKeyEvent(key, event_action == AKEY_EVENT_ACTION_DOWN); 184 | io.SetKeyEventNativeData(key, event_key_code, event_scan_code); 185 | } 186 | 187 | break; 188 | } 189 | default: 190 | break; 191 | } 192 | break; 193 | } 194 | case AINPUT_EVENT_TYPE_MOTION: 195 | { 196 | int32_t event_action = AMotionEvent_getAction(input_event); 197 | int32_t event_pointer_index = (event_action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; 198 | event_action &= AMOTION_EVENT_ACTION_MASK; 199 | switch (event_action) 200 | { 201 | case AMOTION_EVENT_ACTION_DOWN: 202 | case AMOTION_EVENT_ACTION_UP: 203 | // Physical mouse buttons (and probably other physical devices) also invoke the actions AMOTION_EVENT_ACTION_DOWN/_UP, 204 | // but we have to process them separately to identify the actual button pressed. This is done below via 205 | // AMOTION_EVENT_ACTION_BUTTON_PRESS/_RELEASE. Here, we only process "FINGER" input (and "UNKNOWN", as a fallback). 206 | if((AMotionEvent_getToolType(input_event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_FINGER) 207 | || (AMotionEvent_getToolType(input_event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_UNKNOWN)) 208 | { 209 | io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); 210 | io.AddMouseButtonEvent(0, event_action == AMOTION_EVENT_ACTION_DOWN); 211 | } 212 | break; 213 | case AMOTION_EVENT_ACTION_BUTTON_PRESS: 214 | case AMOTION_EVENT_ACTION_BUTTON_RELEASE: 215 | { 216 | int32_t button_state = AMotionEvent_getButtonState(input_event); 217 | io.AddMouseButtonEvent(0, (button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0); 218 | io.AddMouseButtonEvent(1, (button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0); 219 | io.AddMouseButtonEvent(2, (button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0); 220 | } 221 | break; 222 | case AMOTION_EVENT_ACTION_HOVER_MOVE: // Hovering: Tool moves while NOT pressed (such as a physical mouse) 223 | case AMOTION_EVENT_ACTION_MOVE: // Touch pointer moves while DOWN 224 | io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); 225 | break; 226 | case AMOTION_EVENT_ACTION_SCROLL: 227 | io.AddMouseWheelEvent(AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_HSCROLL, event_pointer_index), AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_VSCROLL, event_pointer_index)); 228 | break; 229 | default: 230 | break; 231 | } 232 | } 233 | return 1; 234 | default: 235 | break; 236 | } 237 | 238 | return 0; 239 | } 240 | 241 | bool ImGui_ImplAndroid_Init(ANativeWindow* window) 242 | { 243 | g_Window = window; 244 | g_Time = 0.0; 245 | 246 | // Setup backend capabilities flags 247 | ImGuiIO& io = ImGui::GetIO(); 248 | io.BackendPlatformName = "imgui_impl_android"; 249 | 250 | return true; 251 | } 252 | 253 | void ImGui_ImplAndroid_Shutdown() 254 | { 255 | } 256 | 257 | void ImGui_ImplAndroid_NewFrame() 258 | { 259 | ImGuiIO& io = ImGui::GetIO(); 260 | 261 | // Setup display size (every frame to accommodate for window resizing) 262 | int32_t window_width = ANativeWindow_getWidth(g_Window); 263 | int32_t window_height = ANativeWindow_getHeight(g_Window); 264 | int display_width = window_width; 265 | int display_height = window_height; 266 | 267 | io.DisplaySize = ImVec2((float)window_width, (float)window_height); 268 | if (window_width > 0 && window_height > 0) 269 | io.DisplayFramebufferScale = ImVec2((float)display_width / window_width, (float)display_height / window_height); 270 | 271 | // Setup time step 272 | struct timespec current_timespec; 273 | clock_gettime(CLOCK_MONOTONIC, ¤t_timespec); 274 | double current_time = (double)(current_timespec.tv_sec) + (current_timespec.tv_nsec / 1000000000.0); 275 | io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); 276 | g_Time = current_time; 277 | } 278 | -------------------------------------------------------------------------------- /backends/imgui_impl_opengl2.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline) 2 | // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID! 6 | 7 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 8 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 9 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 10 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 11 | 12 | // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** 13 | // **Prefer using the code in imgui_impl_opengl3.cpp** 14 | // This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read. 15 | // If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more 16 | // complicated, will require your code to reset every single OpenGL attributes to their initial state, and might 17 | // confuse your GPU driver. 18 | // The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API. 19 | 20 | // CHANGELOG 21 | // (minor and older changes stripped away, please see git history for details) 22 | // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. 23 | // 2021-12-08: OpenGL: Fixed mishandling of the the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86. 24 | // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). 25 | // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) 26 | // 2021-01-03: OpenGL: Backup, setup and restore GL_SHADE_MODEL state, disable GL_STENCIL_TEST and disable GL_NORMAL_ARRAY client state to increase compatibility with legacy OpenGL applications. 27 | // 2020-01-23: OpenGL: Backup, setup and restore GL_TEXTURE_ENV to increase compatibility with legacy OpenGL applications. 28 | // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. 29 | // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. 30 | // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. 31 | // 2018-08-03: OpenGL: Disabling/restoring GL_LIGHTING and GL_COLOR_MATERIAL to increase compatibility with legacy OpenGL applications. 32 | // 2018-06-08: Misc: Extracted imgui_impl_opengl2.cpp/.h away from the old combined GLFW/SDL+OpenGL2 examples. 33 | // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. 34 | // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplOpenGL2_RenderDrawData() in the .h file so you can call it yourself. 35 | // 2017-09-01: OpenGL: Save and restore current polygon mode. 36 | // 2016-09-10: OpenGL: Uploading font texture as RGBA32 to increase compatibility with users shaders (not ideal). 37 | // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. 38 | 39 | #include "imgui.h" 40 | #include "imgui_impl_opengl2.h" 41 | #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier 42 | #include // intptr_t 43 | #else 44 | #include // intptr_t 45 | #endif 46 | 47 | // Clang/GCC warnings with -Weverything 48 | #if defined(__clang__) 49 | #pragma clang diagnostic push 50 | #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used 51 | #pragma clang diagnostic ignored "-Wnonportable-system-include-path" 52 | #endif 53 | 54 | // Include OpenGL header (without an OpenGL loader) requires a bit of fiddling 55 | #if defined(_WIN32) && !defined(APIENTRY) 56 | #define APIENTRY __stdcall // It is customary to use APIENTRY for OpenGL function pointer declarations on all platforms. Additionally, the Windows OpenGL header needs APIENTRY. 57 | #endif 58 | #if defined(_WIN32) && !defined(WINGDIAPI) 59 | #define WINGDIAPI __declspec(dllimport) // Some Windows OpenGL headers need this 60 | #endif 61 | #if defined(__APPLE__) 62 | #define GL_SILENCE_DEPRECATION 63 | #include 64 | #else 65 | #include 66 | #endif 67 | 68 | struct ImGui_ImplOpenGL2_Data 69 | { 70 | GLuint FontTexture; 71 | 72 | ImGui_ImplOpenGL2_Data() { memset((void*)this, 0, sizeof(*this)); } 73 | }; 74 | 75 | // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts 76 | // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. 77 | static ImGui_ImplOpenGL2_Data* ImGui_ImplOpenGL2_GetBackendData() 78 | { 79 | return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; 80 | } 81 | 82 | // Functions 83 | bool ImGui_ImplOpenGL2_Init() 84 | { 85 | ImGuiIO& io = ImGui::GetIO(); 86 | IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); 87 | 88 | // Setup backend capabilities flags 89 | ImGui_ImplOpenGL2_Data* bd = IM_NEW(ImGui_ImplOpenGL2_Data)(); 90 | io.BackendRendererUserData = (void*)bd; 91 | io.BackendRendererName = "imgui_impl_opengl2"; 92 | 93 | return true; 94 | } 95 | 96 | void ImGui_ImplOpenGL2_Shutdown() 97 | { 98 | ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); 99 | IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); 100 | ImGuiIO& io = ImGui::GetIO(); 101 | 102 | ImGui_ImplOpenGL2_DestroyDeviceObjects(); 103 | io.BackendRendererName = nullptr; 104 | io.BackendRendererUserData = nullptr; 105 | IM_DELETE(bd); 106 | } 107 | 108 | void ImGui_ImplOpenGL2_NewFrame() 109 | { 110 | ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); 111 | IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplOpenGL2_Init()?"); 112 | 113 | if (!bd->FontTexture) 114 | ImGui_ImplOpenGL2_CreateDeviceObjects(); 115 | } 116 | 117 | static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height) 118 | { 119 | // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill. 120 | glEnable(GL_BLEND); 121 | glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 122 | //glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // In order to composite our output buffer we need to preserve alpha 123 | glDisable(GL_CULL_FACE); 124 | glDisable(GL_DEPTH_TEST); 125 | glDisable(GL_STENCIL_TEST); 126 | glDisable(GL_LIGHTING); 127 | glDisable(GL_COLOR_MATERIAL); 128 | glEnable(GL_SCISSOR_TEST); 129 | glEnableClientState(GL_VERTEX_ARRAY); 130 | glEnableClientState(GL_TEXTURE_COORD_ARRAY); 131 | glEnableClientState(GL_COLOR_ARRAY); 132 | glDisableClientState(GL_NORMAL_ARRAY); 133 | glEnable(GL_TEXTURE_2D); 134 | glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); 135 | glShadeModel(GL_SMOOTH); 136 | glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); 137 | 138 | // If you are using this code with non-legacy OpenGL header/contexts (which you should not, prefer using imgui_impl_opengl3.cpp!!), 139 | // you may need to backup/reset/restore other state, e.g. for current shader using the commented lines below. 140 | // (DO NOT MODIFY THIS FILE! Add the code in your calling function) 141 | // GLint last_program; 142 | // glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); 143 | // glUseProgram(0); 144 | // ImGui_ImplOpenGL2_RenderDrawData(...); 145 | // glUseProgram(last_program) 146 | // There are potentially many more states you could need to clear/setup that we can't access from default headers. 147 | // e.g. glBindBuffer(GL_ARRAY_BUFFER, 0), glDisable(GL_TEXTURE_CUBE_MAP). 148 | 149 | // Setup viewport, orthographic projection matrix 150 | // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. 151 | glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); 152 | glMatrixMode(GL_PROJECTION); 153 | glPushMatrix(); 154 | glLoadIdentity(); 155 | glOrtho(draw_data->DisplayPos.x, draw_data->DisplayPos.x + draw_data->DisplaySize.x, draw_data->DisplayPos.y + draw_data->DisplaySize.y, draw_data->DisplayPos.y, -1.0f, +1.0f); 156 | glMatrixMode(GL_MODELVIEW); 157 | glPushMatrix(); 158 | glLoadIdentity(); 159 | } 160 | 161 | // OpenGL2 Render function. 162 | // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. 163 | // This is in order to be able to run within an OpenGL engine that doesn't do so. 164 | void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) 165 | { 166 | // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) 167 | int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); 168 | int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); 169 | if (fb_width == 0 || fb_height == 0) 170 | return; 171 | 172 | // Backup GL state 173 | GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 174 | GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); 175 | GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); 176 | GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); 177 | GLint last_shade_model; glGetIntegerv(GL_SHADE_MODEL, &last_shade_model); 178 | GLint last_tex_env_mode; glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &last_tex_env_mode); 179 | glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT); 180 | 181 | // Setup desired GL state 182 | ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height); 183 | 184 | // Will project scissor/clipping rectangles into framebuffer space 185 | ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports 186 | ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) 187 | 188 | // Render command lists 189 | for (int n = 0; n < draw_data->CmdListsCount; n++) 190 | { 191 | const ImDrawList* cmd_list = draw_data->CmdLists[n]; 192 | const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; 193 | const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; 194 | glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos))); 195 | glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv))); 196 | glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col))); 197 | 198 | for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) 199 | { 200 | const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; 201 | if (pcmd->UserCallback) 202 | { 203 | // User callback, registered via ImDrawList::AddCallback() 204 | // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) 205 | if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) 206 | ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height); 207 | else 208 | pcmd->UserCallback(cmd_list, pcmd); 209 | } 210 | else 211 | { 212 | // Project scissor/clipping rectangles into framebuffer space 213 | ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); 214 | ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); 215 | if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) 216 | continue; 217 | 218 | // Apply scissor/clipping rectangle (Y is inverted in OpenGL) 219 | glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)); 220 | 221 | // Bind texture, Draw 222 | glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()); 223 | glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset); 224 | } 225 | } 226 | } 227 | 228 | // Restore modified GL state 229 | glDisableClientState(GL_COLOR_ARRAY); 230 | glDisableClientState(GL_TEXTURE_COORD_ARRAY); 231 | glDisableClientState(GL_VERTEX_ARRAY); 232 | glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture); 233 | glMatrixMode(GL_MODELVIEW); 234 | glPopMatrix(); 235 | glMatrixMode(GL_PROJECTION); 236 | glPopMatrix(); 237 | glPopAttrib(); 238 | glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]); 239 | glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); 240 | glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); 241 | glShadeModel(last_shade_model); 242 | glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, last_tex_env_mode); 243 | } 244 | 245 | bool ImGui_ImplOpenGL2_CreateFontsTexture() 246 | { 247 | // Build texture atlas 248 | ImGuiIO& io = ImGui::GetIO(); 249 | ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); 250 | unsigned char* pixels; 251 | int width, height; 252 | io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. 253 | 254 | // Upload texture to graphics system 255 | // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) 256 | GLint last_texture; 257 | glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); 258 | glGenTextures(1, &bd->FontTexture); 259 | glBindTexture(GL_TEXTURE_2D, bd->FontTexture); 260 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 261 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 262 | glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); 263 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); 264 | 265 | // Store our identifier 266 | io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture); 267 | 268 | // Restore state 269 | glBindTexture(GL_TEXTURE_2D, last_texture); 270 | 271 | return true; 272 | } 273 | 274 | void ImGui_ImplOpenGL2_DestroyFontsTexture() 275 | { 276 | ImGuiIO& io = ImGui::GetIO(); 277 | ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); 278 | if (bd->FontTexture) 279 | { 280 | glDeleteTextures(1, &bd->FontTexture); 281 | io.Fonts->SetTexID(0); 282 | bd->FontTexture = 0; 283 | } 284 | } 285 | 286 | bool ImGui_ImplOpenGL2_CreateDeviceObjects() 287 | { 288 | return ImGui_ImplOpenGL2_CreateFontsTexture(); 289 | } 290 | 291 | void ImGui_ImplOpenGL2_DestroyDeviceObjects() 292 | { 293 | ImGui_ImplOpenGL2_DestroyFontsTexture(); 294 | } 295 | 296 | #if defined(__clang__) 297 | #pragma clang diagnostic pop 298 | #endif 299 | -------------------------------------------------------------------------------- /backends/imgui_impl_dx9.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for DirectX9 2 | // This needs to be used along with a Platform Backend (e.g. Win32) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 9 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 10 | // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 11 | // Read online: https://github.com/ocornut/imgui/tree/master/docs 12 | 13 | // CHANGELOG 14 | // (minor and older changes stripped away, please see git history for details) 15 | // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. 16 | // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). 17 | // 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1. 18 | // 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) 19 | // 2021-04-23: DirectX9: Explicitly setting up more graphics states to increase compatibility with unusual non-default states. 20 | // 2021-03-18: DirectX9: Calling IDirect3DStateBlock9::Capture() after CreateStateBlock() as a workaround for state restoring issues (see #3857). 21 | // 2021-03-03: DirectX9: Added support for IMGUI_USE_BGRA_PACKED_COLOR in user's imconfig file. 22 | // 2021-02-18: DirectX9: Change blending equation to preserve alpha in output buffer. 23 | // 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. 24 | // 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. 25 | // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects(). 26 | // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288. 27 | // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. 28 | // 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example. 29 | // 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. 30 | // 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud. 31 | // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself. 32 | // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. 33 | 34 | #include "imgui.h" 35 | #include "imgui_impl_dx9.h" 36 | 37 | // DirectX 38 | #include 39 | 40 | // DirectX data 41 | struct ImGui_ImplDX9_Data 42 | { 43 | LPDIRECT3DDEVICE9 pd3dDevice; 44 | LPDIRECT3DVERTEXBUFFER9 pVB; 45 | LPDIRECT3DINDEXBUFFER9 pIB; 46 | LPDIRECT3DTEXTURE9 FontTexture; 47 | int VertexBufferSize; 48 | int IndexBufferSize; 49 | 50 | ImGui_ImplDX9_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } 51 | }; 52 | 53 | struct CUSTOMVERTEX 54 | { 55 | float pos[3]; 56 | D3DCOLOR col; 57 | float uv[2]; 58 | }; 59 | #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) 60 | 61 | #ifdef IMGUI_USE_BGRA_PACKED_COLOR 62 | #define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL) 63 | #else 64 | #define IMGUI_COL_TO_DX9_ARGB(_COL) (((_COL) & 0xFF00FF00) | (((_COL) & 0xFF0000) >> 16) | (((_COL) & 0xFF) << 16)) 65 | #endif 66 | 67 | // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts 68 | // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. 69 | static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData() 70 | { 71 | return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; 72 | } 73 | 74 | // Functions 75 | static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) 76 | { 77 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); 78 | 79 | // Setup viewport 80 | D3DVIEWPORT9 vp; 81 | vp.X = vp.Y = 0; 82 | vp.Width = (DWORD)draw_data->DisplaySize.x; 83 | vp.Height = (DWORD)draw_data->DisplaySize.y; 84 | vp.MinZ = 0.0f; 85 | vp.MaxZ = 1.0f; 86 | bd->pd3dDevice->SetViewport(&vp); 87 | 88 | // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling. 89 | bd->pd3dDevice->SetPixelShader(nullptr); 90 | bd->pd3dDevice->SetVertexShader(nullptr); 91 | bd->pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); 92 | bd->pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); 93 | bd->pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); 94 | bd->pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); 95 | bd->pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); 96 | bd->pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE); 97 | bd->pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); 98 | bd->pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); 99 | bd->pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); 100 | bd->pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); 101 | bd->pd3dDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE); 102 | bd->pd3dDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE); 103 | bd->pd3dDevice->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA); 104 | bd->pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE); 105 | bd->pd3dDevice->SetRenderState(D3DRS_FOGENABLE, FALSE); 106 | bd->pd3dDevice->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE); 107 | bd->pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE, FALSE); 108 | bd->pd3dDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE); 109 | bd->pd3dDevice->SetRenderState(D3DRS_CLIPPING, TRUE); 110 | bd->pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE); 111 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); 112 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); 113 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); 114 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); 115 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); 116 | bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); 117 | bd->pd3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); 118 | bd->pd3dDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); 119 | bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); 120 | bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); 121 | 122 | // Setup orthographic projection matrix 123 | // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. 124 | // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() 125 | { 126 | float L = draw_data->DisplayPos.x + 0.5f; 127 | float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f; 128 | float T = draw_data->DisplayPos.y + 0.5f; 129 | float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f; 130 | D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } }; 131 | D3DMATRIX mat_projection = 132 | { { { 133 | 2.0f/(R-L), 0.0f, 0.0f, 0.0f, 134 | 0.0f, 2.0f/(T-B), 0.0f, 0.0f, 135 | 0.0f, 0.0f, 0.5f, 0.0f, 136 | (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f 137 | } } }; 138 | bd->pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity); 139 | bd->pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity); 140 | bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection); 141 | } 142 | } 143 | 144 | // Render function. 145 | void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) 146 | { 147 | // Avoid rendering when minimized 148 | if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) 149 | return; 150 | 151 | // Create and grow buffers if needed 152 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); 153 | if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) 154 | { 155 | if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } 156 | bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; 157 | if (bd->pd3dDevice->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0) 158 | return; 159 | } 160 | if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) 161 | { 162 | if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } 163 | bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; 164 | if (bd->pd3dDevice->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0) 165 | return; 166 | } 167 | 168 | // Backup the DX9 state 169 | IDirect3DStateBlock9* d3d9_state_block = nullptr; 170 | if (bd->pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0) 171 | return; 172 | if (d3d9_state_block->Capture() < 0) 173 | { 174 | d3d9_state_block->Release(); 175 | return; 176 | } 177 | 178 | // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to) 179 | D3DMATRIX last_world, last_view, last_projection; 180 | bd->pd3dDevice->GetTransform(D3DTS_WORLD, &last_world); 181 | bd->pd3dDevice->GetTransform(D3DTS_VIEW, &last_view); 182 | bd->pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection); 183 | 184 | // Allocate buffers 185 | CUSTOMVERTEX* vtx_dst; 186 | ImDrawIdx* idx_dst; 187 | if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0) 188 | { 189 | d3d9_state_block->Release(); 190 | return; 191 | } 192 | if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0) 193 | { 194 | bd->pVB->Unlock(); 195 | d3d9_state_block->Release(); 196 | return; 197 | } 198 | 199 | // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. 200 | // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and 201 | // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR 202 | // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; } 203 | for (int n = 0; n < draw_data->CmdListsCount; n++) 204 | { 205 | const ImDrawList* cmd_list = draw_data->CmdLists[n]; 206 | const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data; 207 | for (int i = 0; i < cmd_list->VtxBuffer.Size; i++) 208 | { 209 | vtx_dst->pos[0] = vtx_src->pos.x; 210 | vtx_dst->pos[1] = vtx_src->pos.y; 211 | vtx_dst->pos[2] = 0.0f; 212 | vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col); 213 | vtx_dst->uv[0] = vtx_src->uv.x; 214 | vtx_dst->uv[1] = vtx_src->uv.y; 215 | vtx_dst++; 216 | vtx_src++; 217 | } 218 | memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); 219 | idx_dst += cmd_list->IdxBuffer.Size; 220 | } 221 | bd->pVB->Unlock(); 222 | bd->pIB->Unlock(); 223 | bd->pd3dDevice->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX)); 224 | bd->pd3dDevice->SetIndices(bd->pIB); 225 | bd->pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); 226 | 227 | // Setup desired DX state 228 | ImGui_ImplDX9_SetupRenderState(draw_data); 229 | 230 | // Render command lists 231 | // (Because we merged all buffers into a single one, we maintain our own offset into them) 232 | int global_vtx_offset = 0; 233 | int global_idx_offset = 0; 234 | ImVec2 clip_off = draw_data->DisplayPos; 235 | for (int n = 0; n < draw_data->CmdListsCount; n++) 236 | { 237 | const ImDrawList* cmd_list = draw_data->CmdLists[n]; 238 | for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) 239 | { 240 | const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; 241 | if (pcmd->UserCallback != nullptr) 242 | { 243 | // User callback, registered via ImDrawList::AddCallback() 244 | // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) 245 | if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) 246 | ImGui_ImplDX9_SetupRenderState(draw_data); 247 | else 248 | pcmd->UserCallback(cmd_list, pcmd); 249 | } 250 | else 251 | { 252 | // Project scissor/clipping rectangles into framebuffer space 253 | ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); 254 | ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); 255 | if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) 256 | continue; 257 | 258 | // Apply Scissor/clipping rectangle, Bind texture, Draw 259 | const RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; 260 | const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID(); 261 | bd->pd3dDevice->SetTexture(0, texture); 262 | bd->pd3dDevice->SetScissorRect(&r); 263 | bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3); 264 | } 265 | } 266 | global_idx_offset += cmd_list->IdxBuffer.Size; 267 | global_vtx_offset += cmd_list->VtxBuffer.Size; 268 | } 269 | 270 | // Restore the DX9 transform 271 | bd->pd3dDevice->SetTransform(D3DTS_WORLD, &last_world); 272 | bd->pd3dDevice->SetTransform(D3DTS_VIEW, &last_view); 273 | bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection); 274 | 275 | // Restore the DX9 state 276 | d3d9_state_block->Apply(); 277 | d3d9_state_block->Release(); 278 | } 279 | 280 | bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) 281 | { 282 | ImGuiIO& io = ImGui::GetIO(); 283 | IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); 284 | 285 | // Setup backend capabilities flags 286 | ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)(); 287 | io.BackendRendererUserData = (void*)bd; 288 | io.BackendRendererName = "imgui_impl_dx9"; 289 | io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. 290 | 291 | bd->pd3dDevice = device; 292 | bd->pd3dDevice->AddRef(); 293 | 294 | return true; 295 | } 296 | 297 | void ImGui_ImplDX9_Shutdown() 298 | { 299 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); 300 | IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); 301 | ImGuiIO& io = ImGui::GetIO(); 302 | 303 | ImGui_ImplDX9_InvalidateDeviceObjects(); 304 | if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } 305 | io.BackendRendererName = nullptr; 306 | io.BackendRendererUserData = nullptr; 307 | IM_DELETE(bd); 308 | } 309 | 310 | static bool ImGui_ImplDX9_CreateFontsTexture() 311 | { 312 | // Build texture atlas 313 | ImGuiIO& io = ImGui::GetIO(); 314 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); 315 | unsigned char* pixels; 316 | int width, height, bytes_per_pixel; 317 | io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel); 318 | 319 | // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices) 320 | #ifndef IMGUI_USE_BGRA_PACKED_COLOR 321 | if (io.Fonts->TexPixelsUseColors) 322 | { 323 | ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel); 324 | for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++) 325 | *dst = IMGUI_COL_TO_DX9_ARGB(*src); 326 | pixels = (unsigned char*)dst_start; 327 | } 328 | #endif 329 | 330 | // Upload texture to graphics system 331 | bd->FontTexture = nullptr; 332 | if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0) 333 | return false; 334 | D3DLOCKED_RECT tex_locked_rect; 335 | if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK) 336 | return false; 337 | for (int y = 0; y < height; y++) 338 | memcpy((unsigned char*)tex_locked_rect.pBits + (size_t)tex_locked_rect.Pitch * y, pixels + (size_t)width * bytes_per_pixel * y, (size_t)width * bytes_per_pixel); 339 | bd->FontTexture->UnlockRect(0); 340 | 341 | // Store our identifier 342 | io.Fonts->SetTexID((ImTextureID)bd->FontTexture); 343 | 344 | #ifndef IMGUI_USE_BGRA_PACKED_COLOR 345 | if (io.Fonts->TexPixelsUseColors) 346 | ImGui::MemFree(pixels); 347 | #endif 348 | 349 | return true; 350 | } 351 | 352 | bool ImGui_ImplDX9_CreateDeviceObjects() 353 | { 354 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); 355 | if (!bd || !bd->pd3dDevice) 356 | return false; 357 | if (!ImGui_ImplDX9_CreateFontsTexture()) 358 | return false; 359 | return true; 360 | } 361 | 362 | void ImGui_ImplDX9_InvalidateDeviceObjects() 363 | { 364 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); 365 | if (!bd || !bd->pd3dDevice) 366 | return; 367 | if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } 368 | if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } 369 | if (bd->FontTexture) { bd->FontTexture->Release(); bd->FontTexture = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well. 370 | } 371 | 372 | void ImGui_ImplDX9_NewFrame() 373 | { 374 | ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); 375 | IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX9_Init()?"); 376 | 377 | if (!bd->FontTexture) 378 | ImGui_ImplDX9_CreateDeviceObjects(); 379 | } 380 | -------------------------------------------------------------------------------- /docs/FONTS.md: -------------------------------------------------------------------------------- 1 | _(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer)_ 2 | 3 | ## Dear ImGui: Using Fonts 4 | 5 | The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), 6 | a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions. 7 | 8 | You may also load external .TTF/.OTF files. 9 | In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience. 10 | 11 | **Also read the FAQ:** https://www.dearimgui.org/faq (there is a Fonts section!) 12 | 13 | ## Index 14 | - [Readme First](#readme-first) 15 | - [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application) 16 | - [Fonts Loading Instructions](#font-loading-instructions) 17 | - [Using Icon Fonts](#using-icon-fonts) 18 | - [Using FreeType Rasterizer (imgui_freetype)](#using-freetype-rasterizer-imgui_freetype) 19 | - [Using Colorful Glyphs/Emojis](#using-colorful-glyphsemojis) 20 | - [Using Custom Glyph Ranges](#using-custom-glyph-ranges) 21 | - [Using Custom Colorful Icons](#using-custom-colorful-icons) 22 | - [Using Font Data Embedded In Source Code](#using-font-data-embedded-in-source-code) 23 | - [About filenames](#about-filenames) 24 | - [Credits/Licenses For Fonts Included In Repository](#creditslicenses-for-fonts-included-in-repository) 25 | - [Font Links](#font-links) 26 | 27 | --------------------------------------- 28 | ## Readme First 29 | 30 | - You can use the `Metrics/Debugger` window (available in `Demo>Tools`) to browse your fonts and understand what's going on if you have an issue. You can also reach it in `Demo->Tools->Style Editor->Fonts`. The same information are also available in the Style Editor under Fonts. 31 | 32 | ![Fonts debugging](https://user-images.githubusercontent.com/8225057/135429892-0e41ef8d-33c5-4991-bcf6-f997a0bcfd6b.png) 33 | 34 | - You can use the `UTF-8 Encoding viewer` in `Metrics/Debugger` to verify the content of your UTF-8 strings. From C/C++ code, you can call `ImGui::DebugTextEncoding("my string");` function to verify that your UTF-8 encoding is correct. 35 | 36 | ![UTF-8 Encoding viewer](https://user-images.githubusercontent.com/8225057/166505963-8a0d7899-8ee8-4558-abb2-1ae523dc02f9.png) 37 | 38 | - All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of `io.Fonts->GetTexDataAsAlpha8()`, `io.Fonts->GetTexDataAsRGBA32()` or `io.Fonts->Build()` will build the atlas. 39 | 40 | - Make sure your font ranges data are persistent (available during the calls to `GetTexDataAsAlpha8()`/`GetTexDataAsRGBA32()/`Build()`. 41 | 42 | - Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.: 43 | ```cpp 44 | u8"hello" 45 | u8"こんにちは" // this will be encoded as UTF-8 46 | ``` 47 | 48 | ##### [Return to Index](#index) 49 | 50 | ## How should I handle DPI in my application? 51 | 52 | See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-should-i-handle-dpi-in-my-application). 53 | 54 | ##### [Return to Index](#index) 55 | 56 | 57 | ## Font Loading Instructions 58 | 59 | **Load default font:** 60 | ```cpp 61 | ImGuiIO& io = ImGui::GetIO(); 62 | io.Fonts->AddFontDefault(); 63 | ``` 64 | 65 | 66 | **Load .TTF/.OTF file with:** 67 | ```cpp 68 | ImGuiIO& io = ImGui::GetIO(); 69 | io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); 70 | ``` 71 | If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read "[About filenames](#about-filenames)" carefully. 72 | 73 | 74 | **Load multiple fonts:** 75 | ```cpp 76 | // Init 77 | ImGuiIO& io = ImGui::GetIO(); 78 | ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); 79 | ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); 80 | ``` 81 | ```cpp 82 | // In application loop: select font at runtime 83 | ImGui::Text("Hello"); // use the default font (which is the first loaded font) 84 | ImGui::PushFont(font2); 85 | ImGui::Text("Hello with another font"); 86 | ImGui::PopFont(); 87 | ``` 88 | 89 | 90 | **For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):** 91 | ```cpp 92 | ImFontConfig config; 93 | config.OversampleH = 2; 94 | config.OversampleV = 1; 95 | config.GlyphExtraSpacing.x = 1.0f; 96 | ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config); 97 | ``` 98 | 99 | 100 | **Combine multiple fonts into one:** 101 | ```cpp 102 | // Load a first font 103 | ImFont* font = io.Fonts->AddFontDefault(); 104 | 105 | // Add character ranges and merge into the previous font 106 | // The ranges array is not copied by the AddFont* functions and is used lazily 107 | // so ensure it is available at the time of building or calling GetTexDataAsRGBA32(). 108 | static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope. 109 | ImFontConfig config; 110 | config.MergeMode = true; 111 | io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge into first font 112 | io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); // Merge into first font 113 | io.Fonts->Build(); 114 | ``` 115 | 116 | **Add a fourth parameter to bake specific font ranges only:** 117 | 118 | ```cpp 119 | // Basic Latin, Extended Latin 120 | io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault()); 121 | 122 | // Default + Selection of 2500 Ideographs used by Simplified Chinese 123 | io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChineseSimplifiedCommon()); 124 | 125 | // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs 126 | io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); 127 | ``` 128 | See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges. 129 | 130 | 131 | **Example loading and using a Japanese font:** 132 | 133 | ```cpp 134 | ImGuiIO& io = ImGui::GetIO(); 135 | io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); 136 | ``` 137 | ```cpp 138 | ImGui::Text(u8"こんにちは!テスト %d", 123); 139 | if (ImGui::Button(u8"ロード")) 140 | { 141 | // do stuff 142 | } 143 | ImGui::InputText("string", buf, IM_ARRAYSIZE(buf)); 144 | ImGui::SliderFloat("float", &f, 0.0f, 1.0f); 145 | ``` 146 | 147 | ![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png) 148 |
_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_ 149 | 150 | **Font Atlas too large?** 151 | 152 | - If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. The typical result of failing to upload a texture is if every glyph appears as a white rectangle. 153 | - Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours. 154 | 155 | Some solutions: 156 | 157 | 1. Reduce glyphs ranges by calculating them from source localization data. 158 | You can use the `ImFontGlyphRangesBuilder` for this purpose and rebuilding your atlas between frames when new characters are needed. This will be the biggest win! 159 | 2. You may reduce oversampling, e.g. `font_config.OversampleH = 2`, this will largely reduce your texture size. 160 | Note that while OversampleH = 2 looks visibly very close to 3 in most situations, with OversampleH = 1 the quality drop will be noticeable. 161 | 3. Set `io.Fonts.TexDesiredWidth` to specify a texture width to minimize texture height (see comment in `ImFontAtlas::Build()` function). 162 | 4. Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. 163 | 5. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample). 164 | 6. To support the extended range of unicode beyond 0xFFFF (e.g. emoticons, dingbats, symbols, shapes, ancient languages, etc...) add `#define IMGUI_USE_WCHAR32`in your `imconfig.h`. 165 | 166 | ##### [Return to Index](#index) 167 | 168 | ## Using Icon Fonts 169 | 170 | Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application. 171 | A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth. 172 | 173 | To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: https://github.com/juliettef/IconFontCppHeaders. 174 | 175 | So you can use `ICON_FA_SEARCH` as a string that will render as a "Search" icon. 176 | 177 | Example Setup: 178 | ```cpp 179 | // Merge icons into default tool font 180 | #include "IconsFontAwesome.h" 181 | ImGuiIO& io = ImGui::GetIO(); 182 | io.Fonts->AddFontDefault(); 183 | 184 | ImFontConfig config; 185 | config.MergeMode = true; 186 | config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced 187 | static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; 188 | io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges); 189 | ``` 190 | Example Usage: 191 | ```cpp 192 | // Usage, e.g. 193 | ImGui::Text("%s among %d items", ICON_FA_SEARCH, count); 194 | ImGui::Button(ICON_FA_SEARCH " Search"); 195 | // C string _literals_ can be concatenated at compilation time, e.g. "hello" " world" 196 | // ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB" 197 | ``` 198 | See Links below for other icons fonts and related tools. 199 | 200 | Here's an application using icons ("Avoyd", https://www.avoyd.com): 201 | ![avoyd](https://user-images.githubusercontent.com/8225057/81696852-c15d9e80-9464-11ea-9cab-2a4d4fc84396.jpg) 202 | 203 | ##### [Return to Index](#index) 204 | 205 | ## Using FreeType Rasterizer (imgui_freetype) 206 | 207 | - Dear ImGui uses imstb\_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read. 208 | - There is an implementation of the ImFontAtlas builder using FreeType that you can use in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. 209 | - FreeType supports auto-hinting which tends to improve the readability of small fonts. 210 | - Read documentation in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder. 211 | - Correct sRGB space blending will have an important effect on your font rendering quality. 212 | 213 | ##### [Return to Index](#index) 214 | 215 | ## Using Colorful Glyphs/Emojis 216 | 217 | - Rendering of colored emojis is only supported by imgui_freetype with FreeType 2.10+. 218 | - You will need to load fonts with the `ImGuiFreeTypeBuilderFlags_LoadColor` flag. 219 | - Emojis are frequently encoded in upper Unicode layers (character codes >0x10000) and will need dear imgui compiled with `IMGUI_USE_WCHAR32`. 220 | - Not all types of color fonts are supported by FreeType at the moment. 221 | - Stateful Unicode features such as skin tone modifiers are not supported by the text renderer. 222 | 223 | ![colored glyphs](https://user-images.githubusercontent.com/8225057/106171241-9dc4ba80-6191-11eb-8a69-ca1467b206d1.png) 224 | 225 | ```cpp 226 | io.Fonts->AddFontFromFileTTF("../../../imgui_dev/data/fonts/NotoSans-Regular.ttf", 16.0f); 227 | static ImWchar ranges[] = { 0x1, 0x1FFFF, 0 }; 228 | static ImFontConfig cfg; 229 | cfg.OversampleH = cfg.OversampleV = 1; 230 | cfg.MergeMode = true; 231 | cfg.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_LoadColor; 232 | io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg, ranges); 233 | ``` 234 | 235 | ##### [Return to Index](#index) 236 | 237 | ## Using Custom Glyph Ranges 238 | 239 | You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs. 240 | ```cpp 241 | ImVector ranges; 242 | ImFontGlyphRangesBuilder builder; 243 | builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) 244 | builder.AddChar(0x7262); // Add a specific character 245 | builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges 246 | builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) 247 | 248 | io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); 249 | io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted. 250 | ``` 251 | 252 | ##### [Return to Index](#index) 253 | 254 | ## Using Custom Colorful Icons 255 | 256 | As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiFreeTypeBuilderFlags_LoadColor`, you may allocate your own space in the texture atlas and write yourself into it. **(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)** 257 | 258 | - You can use the `ImFontAtlas::AddCustomRect()` and `ImFontAtlas::AddCustomRectFontGlyph()` api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build()`. 259 | - You can then use `ImFontAtlas::GetCustomRectByIndex(int)` to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles. 260 | - This API is beta because it is likely to change in order to support multi-dpi (multiple viewports on multiple monitors with varying DPI scale). 261 | 262 | #### Pseudo-code: 263 | ```cpp 264 | // Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font 265 | ImFont* font = io.Fonts->AddFontDefault(); 266 | int rect_ids[2]; 267 | rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1); 268 | rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1); 269 | 270 | // Build atlas 271 | io.Fonts->Build(); 272 | 273 | // Retrieve texture in RGBA format 274 | unsigned char* tex_pixels = NULL; 275 | int tex_width, tex_height; 276 | io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height); 277 | 278 | for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++) 279 | { 280 | int rect_id = rect_ids[rect_n]; 281 | if (const ImFontAtlasCustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id)) 282 | { 283 | // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!) 284 | for (int y = 0; y < rect->Height; y++) 285 | { 286 | ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X); 287 | for (int x = rect->Width; x > 0; x--) 288 | *p++ = IM_COL32(255, 0, 0, 255); 289 | } 290 | } 291 | } 292 | ``` 293 | 294 | ##### [Return to Index](#index) 295 | 296 | ## Using Font Data Embedded In Source Code 297 | 298 | - Compile and use [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) to create a compressed C style array that you can embed in source code. 299 | - See the documentation in [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) for instructions on how to use the tool. 300 | - You may find a precompiled version binary_to_compressed_c.exe for Windows inside the demo binaries package (see [README](https://github.com/ocornut/imgui/blob/master/docs/README.md)). 301 | - The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the actual binary will be about 20% bigger. 302 | 303 | Then load the font with: 304 | ```cpp 305 | ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); 306 | ``` 307 | or 308 | ```cpp 309 | ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); 310 | ``` 311 | 312 | ##### [Return to Index](#index) 313 | 314 | ## About filenames 315 | 316 | **Please note that many new C/C++ users have issues loading their files _because the filename they provide is wrong_.** 317 | 318 | Two things to watch for: 319 | - Make sure your IDE/debugger settings starts your executable from the right working directory. In Visual Studio you can change your working directory in project `Properties > General > Debugging > Working Directory`. People assume that their execution will start from the root folder of the project, where by default it often starts from the folder where object or executable files are stored. 320 | ```cpp 321 | // Relative filename depends on your Working Directory when running your program! 322 | io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...); 323 | 324 | // Load from the parent folder of your Working Directory 325 | io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...); 326 | ``` 327 | - In C/C++ and most programming languages if you want to use a backslash `\` within a string literal, you need to write it double backslash `\\`. At it happens, Windows uses backslashes as a path separator, so be mindful. 328 | ```cpp 329 | io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!! 330 | io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT 331 | ``` 332 | In some situations, you may also use `/` path separator under Windows. 333 | 334 | ##### [Return to Index](#index) 335 | 336 | ## Credits/Licenses For Fonts Included In Repository 337 | 338 | Some fonts files are available in the `misc/fonts/` folder: 339 | 340 | **Roboto-Medium.ttf**, by Christian Robetson 341 |
Apache License 2.0 342 |
https://fonts.google.com/specimen/Roboto 343 | 344 | **Cousine-Regular.ttf**, by Steve Matteson 345 |
Digitized data copyright (c) 2010 Google Corporation. 346 |
Licensed under the SIL Open Font License, Version 1.1 347 |
https://fonts.google.com/specimen/Cousine 348 | 349 | **DroidSans.ttf**, by Steve Matteson 350 |
Apache License 2.0 351 |
https://www.fontsquirrel.com/fonts/droid-sans 352 | 353 | **ProggyClean.ttf**, by Tristan Grimmer 354 |
MIT License 355 |
(recommended loading setting: Size = 13.0, GlyphOffset.y = +1) 356 |
http://www.proggyfonts.net/ 357 | 358 | **ProggyTiny.ttf**, by Tristan Grimmer 359 |
MIT License 360 |
(recommended loading setting: Size = 10.0, GlyphOffset.y = +1) 361 |
http://www.proggyfonts.net/ 362 | 363 | **Karla-Regular.ttf**, by Jonathan Pinhorn 364 |
SIL OPEN FONT LICENSE Version 1.1 365 | 366 | ##### [Return to Index](#index) 367 | 368 | ## Font Links 369 | 370 | #### ICON FONTS 371 | 372 | - C/C++ header for icon fonts (#define with code points to use in source code string literals) https://github.com/juliettef/IconFontCppHeaders 373 | - FontAwesome https://fortawesome.github.io/Font-Awesome 374 | - OpenFontIcons https://github.com/traverseda/OpenFontIcons 375 | - Google Icon Fonts https://design.google.com/icons/ 376 | - Kenney Icon Font (Game Controller Icons) https://github.com/nicodinh/kenney-icon-font 377 | - IcoMoon - Custom Icon font builder https://icomoon.io/app 378 | 379 | #### REGULAR FONTS 380 | 381 | - Google Noto Fonts (worldwide languages) https://www.google.com/get/noto/ 382 | - Open Sans Fonts https://fonts.google.com/specimen/Open+Sans 383 | - (Japanese) M+ fonts by Coji Morishita http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html 384 | 385 | #### MONOSPACE FONTS 386 | 387 | Pixel Perfect: 388 | - Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperbounds.net 389 | - Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font (also include an .inl file to use directly in dear imgui.) 390 | 391 | Regular: 392 | - Google Noto Mono Fonts https://www.google.com/get/noto/ 393 | - Typefaces for source code beautification https://github.com/chrissimpkins/codeface 394 | - Programmation fonts http://s9w.github.io/font_compare/ 395 | - Inconsolata http://www.levien.com/type/myfonts/inconsolata.html 396 | - Adobe Source Code Pro: Monospaced font family for ui & coding environments https://github.com/adobe-fonts/source-code-pro 397 | - Monospace/Fixed Width Programmer's Fonts http://www.lowing.org/fonts/ 398 | 399 | Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing). 400 | 401 | ##### [Return to Index](#index) 402 | --------------------------------------------------------------------------------