Compare commits

..

251 Commits

Author SHA1 Message Date
e0a2729572 Update .github/workflows/ci.yml
Some checks failed
ContinuousIntegration / linux (push) Successful in 12m5s
ContinuousDelivery / linux-ubuntu (push) Failing after 12m55s
ContinuousDelivery / windows (push) Has been cancelled
ContinuousDelivery / windows-asan (push) Has been cancelled
ContinuousIntegration / macos (push) Has been cancelled
ContinuousIntegration / windows (push) Has been cancelled
ContinuousDelivery / release (push) Has been cancelled
2024-05-29 00:22:19 +02:00
fc62be8b5d [skip ci] 2024-05-29 00:21:38 +02:00
5f186ac1d2 Update .github/workflows/cd.yml
Some checks failed
ContinuousDelivery / linux-ubuntu (push) Failing after 24s
ContinuousDelivery / windows (push) Has been cancelled
ContinuousDelivery / windows-asan (push) Has been cancelled
ContinuousDelivery / release (push) Has been cancelled
ContinuousIntegration / linux (push) Has been cancelled
ContinuousIntegration / macos (push) Has been cancelled
ContinuousIntegration / windows (push) Has been cancelled
2024-05-29 00:15:55 +02:00
1cc0c275ab Update CMakeLists.txt
Some checks failed
ContinuousDelivery / linux-ubuntu (push) Has been cancelled
ContinuousDelivery / windows (push) Has been cancelled
ContinuousDelivery / windows-asan (push) Has been cancelled
ContinuousDelivery / release (push) Has been cancelled
ContinuousIntegration / linux (push) Has been cancelled
ContinuousIntegration / macos (push) Has been cancelled
ContinuousIntegration / windows (push) Has been cancelled
2024-05-29 00:14:42 +02:00
cfb0c1fee0
improve windows debug conformity 2024-05-28 22:59:17 +02:00
2d4729a877
update sdl and sdl_image 2024-05-28 17:58:24 +02:00
8cf1f97ac4
changes for imgui update 2024-05-28 17:17:57 +02:00
0e8c752df8
Merge commit '293f4fd0a04156ee8bd279df3b9443df6c75bbd5' 2024-05-28 17:12:43 +02:00
293f4fd0a0 Squashed 'external/imgui/imgui/' changes from 6ccc561a2ab..00ad3c65bc2
00ad3c65bc2 Version 1.90.7
f814ef816fb Commented out CaptureKeyboardFromApp(), CaptureMouseFromApp(). Commented out obsolete IsKeyPressedMap() from imgui_internal.h (can call IsKeyPressed). Comments
b9084949bd7 Fixed typo in IsMouseDragging and GetMouseDragDelta's documentation. (#7620)
86931393a36 Shortcuts: Revert "SetShortcutRouting: require explicit routing. (#456)
7832e6a70e6 Shortcuts: Routing: fixed mixed keys<>chars filtering not applying on global routes. (#456, #7618)
85d982011e9 Shortcuts: fixed priority of route calculation (higher first). (#456, #7618)
ce4e210dcb6 Shotcuts: renamed ImGuiInputFlags_RouteGlobalOverFocused -> ImGuiInputFlags_RouteOverFocused, ImGuiInputFlags_RouteGlobalOverActive -> ImGuiInputFlags_RouteOverActive in previsiion of using them with a Hovered route. (#456)
5ce3d299555 Shortcuts: rename ImGuiInputFlags_RouteGlobalHighest to ImGuiInputFlags_RouteGlobalOverActive, made ImGuiInputFlags_RouteGlobalOverFocused and ImGuiInputFlags_RouteGlobalOverActive flags. (#456)
650cb51bf10 Shortcuts: renamed ImGuiInputFlags_RouteActiveItem to ImGuiInputFlags_RouteActive. (#456, #7618)
ef9d525f02c Shortcuts: added ImGuiInputFlags_RouteActiveItem. (#456, #7618) + rearrange Changelog
16b72f2d210 Comments
29439bdd27c Windows: BeginChild(): fixed auto-fit calculation when using either (not both) ResizeX/ResizeY and double-clicking on a border. (#1710)
374b9a7fb43 Demo: Documents: refactor + add Renaming option. (#7233)
c150ad50c46 Shortcuts: claim mods ownership once pressed. (#456, #2637, #2620, #2891, #3370, #3724, #4828, #5108, #5242, #5641)
1002cfa6d2d Demo, Shortcut(): amend Shortcuts demo. (#456)
7c71e66370d Shortcuts, SetShortcutRouting: move ImGuiInputFlags_RouteFromRootWindow evaluation to SetShortcutRouting() for now. (#456)
d5a600e9c64 Shortcuts, SetShortcutRouting: added ImGuiInputFlags_RouteFromRootWindow. Made it possible for SetShortcutRouting() to query for another location.
0eb025f4847 Internals: move ItemHandleShortcut() next to Shortcut(), it's calling it anyhow. (#456)
a689fa262ae SetShortcutRouting: require explicit routing. (#456)
c06e6340cde Shortcuts: added ImGuiInputFlags_Tooltip. (#456)
77e41718940 Shortcuts: added flags to SetNextItemShortcut(). (#456)
197f8904fe8 Shortcuts, Nav: make SetNextItemShortcut() work when another item is active. Made NavCalcPreferredRefPos() take account for remote activation. (#456)
dc5caa483cd Demo: added "Shortcuts" section. (#456, #2637)
fc512a24741 Inputs: Added Shortcut(), SetNextItemShortcut(). Added ImGuiInputFlags, ImGuiInputFlags_RouteXXXX. (#456, #2637)
85513de2476 Internals, Inputs: *Breaking* Swapped parameter order of owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(). (#456)
900b29055c5 Internals, Inputs: *Breaking* Swapped parameter order of Shortcut(). (#456)
55748cdbe12 Internals, Inputs: *Breaking* Renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner: avoid confusion with non zero value, makes IsKeyPressed() calls using ImGuiKeyOwner_NoOwner more explicit.
ec1d2be96f3 Examples: Win32+DX9,DX10,DX11,DX12: rework main loop to handle minimization and screen locking. (#2496, #3907, #6308, #7615)
6d1a6f1c748 Internals, Inputs: Comments, alignment.
4c3eac2c10e Backends: OpenGL3: Fixed zealous warning by initializing last_pixel_unpack_buffer. (#7614)
a1566c5e1ba Tables: fixed 28a283b breaking PageDown on tables with no interactive items.
aa725ca79dc Inputs: moving ImGuiInputFlags_RouteAlways into ImGuiInputFlags_RouteTypeMask_
cd48059dc53 Tables: comments about skipping access to table data in coarse clipping path.
28a283b4603 Windows: BeginChild(), Tables:fixed visibility of fully clipped child windows and tables to Test Engine.
aa5a6098ee2 Fixed typos in comments (#7599)
d39ca33b63a Fixed false positive with PVS-Studio.
ae8218a3eaf Inputs, Shortcut: fixes some edge cases for GetKeyChordName(), clarify that it is aimed at display. (#456)
25e279ee73f Inputs: Treat ctrl-left-click as right click when ConfigMacOSXBehaviors is set. (#2343)
b4f564c1ed7 Internals: Shortcuts: *Breaking* : rename ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest (#456)
5107e58b0f3 Inputs: amend changelog and clarify how the swap might be a breaking change for a minority of users. (#2343)
8bd5d1d42f0 Inputs: Fixed swapping of keys associated to mods. Fixed warnings. (#2343, #4084, #5923, #456)
77471066471 Inputs: swap Ctrl and Cmd on macOS X, remove ImGuiMod_Shortcut. (#2343, #4084, #5923, #456)
07dbcf1f70d Fixed typos. (#7593)
93daf232233 Examples: SDL3: updates for latest SDL3 API changes.
e45efa9951a Backends: SDL3: Rename SDLK_QUOTE and SDLK_BACKQUOTE to SDLK_APOSTROPHE and SDLK_GRAVE. (#7580)
5d973a87d45 Backends: SDL_Renderer2/SDL_Renderer3: and ImGui_ImplSDLRenderer2_RenderDrawData() and ImGui_ImplSDLRenderer3_RenderDrawData() now takes a SDL_Renderer* parameter.
af2fbf043df Backends/Internals: Don't use IME and clipboard default win32 functions when WINAPI_FAMILY_GAMES (#7585)
e4576914cb9 Internals: amend f806c76 to better match docking + fixed unused static forward declaration warning.
d0524df8879 Internals: slight refactor FindHoveredWindow() -> FindHoveredWindowEx() toward reducing far-away code duplication.
f806c76e97b Tables, Dpi: added dummy g.DpiScale storage (to be altered in docking), using to scale tables border hit thickness.
f0912833ba9 Update FAQ.md (#7581)
ac90e1bd5bd Backends: Win32: replace bd != nullptr assert with early out. (#6275)
0a5d40a0161 Update FAQ.md
d06b8b58d84 Nav: fixed holding Ctrl or gamepad L1 from not slowing down keyboard/gamepad tweak speed.
5e236804541 Backends: all backends + demo now call IMGUI_CHECKVERSION() to verify ABI compatibility between caller code and compiled version of dear imgui. (#7568)
510eb8f4801 Tables: fixed cell background of fully clipped row overlapping with header. (#7575, #7041)
f48aae600a2 Version 1.90.7 WIP

git-subtree-dir: external/imgui/imgui
git-subtree-split: 00ad3c65bc256a16521288505f26fb335440f8f5
2024-05-28 17:12:43 +02:00
a5ec166794
fix lock recursion (on eg windows) 2024-05-28 15:09:37 +02:00
35a0d97170
only build tomato and its dependencies 2024-05-28 09:07:58 +02:00
d0ab985349
manually update vcpkg 2024-05-28 08:55:45 +02:00
b65b9b284b
make the window default to 720p 2024-05-28 08:35:11 +02:00
18db2e3aaa
forgot message3 2024-05-26 21:45:07 +02:00
46ceb2cd61
file2 refactor and tox filetransfer ported to file2 2024-05-26 21:40:15 +02:00
979fd10b08
drive letter handling for file urls 2024-05-25 14:06:57 +02:00
5f3bdde2dc
update to newer toxcore interface 2024-05-24 00:06:00 +02:00
22e97063ec
unread icon in contact list 2024-05-22 22:23:55 +02:00
1ffee9933a
improve plugin api further 2024-05-22 16:22:24 +02:00
aaa23194c5
provide imgui allocator to plugins 2024-05-22 15:19:50 +02:00
013d1fef3b
error message on plugin load fail 2024-05-18 14:04:43 +02:00
35026dfa0f
try improve entt across-boundry support 2024-05-18 12:29:45 +02:00
2095bc6889
update sdl 2024-05-15 14:06:31 +02:00
634bc92665
update sdl_image 2024-05-15 13:54:06 +02:00
0e1b1703f6 Squashed 'external/imgui/imgui/' changes from b475309fa1e..6ccc561a2ab
6ccc561a2ab Version 1.90.6
0d483a1c89f Backends: OpenGL3: Update loader for Linux to support EGL/GLVND. (#7562)
92df32d3390 Backends: OpenGL3: minor update of generated loader to match latest downloaded glcorearb.h/khrplatform.h files.
1ab1af80c74 Backends: Win32: Facepalm revert part of d15574c + additional commentary (#6275)
d15574ce2a5 Backends: Win32: Removed silent return when calling ImGui_ImplWin32_WndProcHandler() with no active context! (#6275)
d4495446d53 Windows, Internal: added experimental SkipRefresh mode. (#3515, #4763, #7556, #5116 , #4076, #2749, #2268)
0b309471f2e Windows: Changed default ClipRect to extend to windows' left and right borders. (#3312, #7540, #3756, #6170, #6365)
0c9c12c1bb9 InnerClipRect use ImFloor() matching docking branch (fix c41868531 for #6861, #2884, followed by rename 94da5842)
6ebbecc6a08 Realign assignments.
fc4d818e170 Tables: Angled headers: added TableAngledHeadersTextAlign, ImGuiStyleVar_TableAngledHeadersTextAlign. (#6917)
4bb75671414 Tables: Angled headers: fixed multi-line label display when angle is flipped. (#6917)
b30df8890de Table: Angled Headers: internal refactor to facilitate changing angled header bg and text colors per column. (#6917)
558c57a086c Fixed static analyzer warning "Pointer to local array 'overlay_buf' is stored outside the scope". Technically not used outside that scope, but best to play nice.
50b2ff0bf03 ImGuiIO: moved IMGUI_DISABLE_OBSOLETE_KEYIO block lower in the structure so other fields layout are not affected by it (#7534)
6ef4f67fa94 ImDrawList: moved cold fields lower in the structure so hot fields are closer to each others + better packed ImGuiNavItemData
a60387a3c25 Backends: GLFW: Add define guards for glfw native defines. (#7536)
913151caa89 Demo: move progress bars to their own section.
c895e987adf ProgressBar: added indeterminate mode by passing an animated negative value. (#5316, #5370, #1901)
b8a44b198c9 TreeNode: added ImGuiTreeNodeFlags_SpanTextWidth. (#6937)
baaaaea9e91 Demo: tweak TreeNode demo.
da18fcb7aed Internals: ensure ButtonBehavior() is called with non 0 id.
b720c0f541c Backends: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define. (#6582, #4854)
07e8ff9a8d4 Backends: Win32: Fixed a warning + moved header cruft below Changelog.
fa0120ea5ea Windows: Fixed subsequent Begin() append calls from setting last item information for title-bar. (#7506, #823)
361432a0bb2 TreeNode: fixed layout so that TreeNode("") or TreeNode("##HiddenLabel") may properly be used with SameLine(0,0). (#7505, #282)
eba46cb0d22 Drag and Drop: assert when nesting  BeginDragDropSource() and BeginDragDropTarget() (#7504) + update Gallery links
9ec299ebe31 Backends: OpenGL: Detect ES3 contexts on desktop based on version string, (#7447)
7b8107e7c84 Examples: GLFW+WebGPU: Rename example_emscripten_wgpu/ to example_glfw_wgpu/ (#7435, #7132)
648278cd62f Examples: GLFW+WebGPU: Amends. (#7435, #7132)
80a5fdb1089 Examples: GLFW+WebGPU: Fixed condition for when to recreate swapchain. (#7435, #7132)
f9df6bf6622 Examples: GLFW+WebGPU: added support for WebGPU-native/Dawn (#7435, #7132)

git-subtree-dir: external/imgui/imgui
git-subtree-split: 6ccc561a2ab497ad4ae6ee1dbd3b992ffada35cb
2024-05-15 13:22:13 +02:00
fc2a10eb6a
update imgui, back to releases Merge commit '0e1b1703f68766c55445e7e3e439035bed6d559c' 2024-05-15 13:22:13 +02:00
ab1c6c4749
use better contact in forward list 2024-04-27 14:04:13 +02:00
06d7148408
add fallback to dynamic toxcore 2024-04-27 13:56:06 +02:00
33875cb58b
string cant be empty 2024-04-27 13:53:26 +02:00
07070dd2d4
update sdl dep 2024-04-27 13:44:34 +02:00
c3a7d1521a
switched from own cmake to toxcore provided cmake 2024-04-25 22:38:23 +02:00
fc994ab758
fix wrongly serialized comp 2024-04-23 15:43:52 +02:00
605a730b59
add status text to tooltip, contact as a single item (group) 2024-04-23 11:57:56 +02:00
3e15798afc
more spacing tuning 2024-04-23 11:24:24 +02:00
cf697622cb
allow toxidenticons for everyone with ID, avatar in chat log 2024-04-23 10:52:57 +02:00
05b0a2f514
only render avatars if visible 2024-04-23 10:38:42 +02:00
c887fdac8a
small contact list and status text 2024-04-22 22:31:17 +02:00
4b0d9595ac
move icon out of avatar, use for small list 2024-04-22 12:46:01 +02:00
5ac318d1bf
fix cast 2024-04-22 00:20:13 +02:00
eaa8f1dd16
contact line hight and refactor avatar and add connection overlay 2024-04-21 20:24:01 +02:00
b88fffd959
refactor big contact 2024-04-21 14:17:50 +02:00
858b9dfcfa
add tooltip to contact 2024-04-20 23:16:18 +02:00
bc8b631b84
make choosing a name for new tox profiles possible 2024-04-20 19:53:41 +02:00
52278f6726
prep for chat_gui refactor 2024-04-20 17:57:11 +02:00
29fd1bfb62
comp name changes and small behavior changes 2024-04-20 15:24:58 +02:00
998000aa3a
work on receive state and prep for pers 2024-04-19 11:51:20 +02:00
e66f4651d0
disable stb_image image loading
its still around since we use it for image writing, which is fine for now.
2024-04-17 15:57:36 +02:00
854d09f05c
windows ci 2024-04-17 12:41:02 +02:00
2d6a9acbb6
enable avif in flake 2024-04-16 10:30:13 +02:00
b7f0ad6c9a
enable sdl_image image_loader (animated gif works) 2024-04-16 10:23:17 +02:00
43f8c22570
add sdl_image image_loader (untested) 2024-04-16 00:45:12 +02:00
3c7bd2e2cb
add sdl_image dep 2024-04-15 19:37:29 +02:00
5dd9834009 Squashed 'external/imgui/imgui/' changes from d6cb3c923d2..b475309fa1e
b475309fa1e Fonts: Fixed font ascent and descent calculation when a font hits exact integer values. (#7399, #7404)
daecfffefbc Text, DrawList: Improved handling of long single-line wrapped text. (#7496, #5720)
fab96a6e593 Backends: SDL3: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput(). (#7452, #6306, #6071, #1953)
dad1689bf7b Examples: SDL3: amend for removal of SDL_RENDERER_ACCELERATED.
3caa79c8a53 Version 1.90.6 WIP
76bc1b825e6 Extracted part of NewFrame() into SetupDrawListSharedData() for documentation purpose. (#7495, #6406)
f790d516652 Silent zealous/stupid warning introduced by Clang 16 (shipping with VS2022) with -Weverything. Pointers are now illegal!
231cbee0fc4 Version 1.90.5
4f9ba19e520 Drags, Sliders, Inputs: Reactivated decimal point replacement for SliderScalar and DragScalar. (#7389, #6719, #2278)
e7712ff103d Out of courtesy/consistency move all the DebugHookIdInfo compares into ifndef block.
f959c417fec Refactor moving ID stack functions to their own section (part 2)
0bf134a8e2e Refactor moving ID stack functions to their own section.
9a2b598ec1e ListBox: Fixed text-baseline offset when using SameLine()+Text() after a labeled ListBox().
d3c3514a59b Tables: Fixed auto-width columns when using synced-instances of same table. (#7218)
25a492f3307 ProgressBar: Fixed passing fraction==NaN from leading to a crash. (#7451)
9638c2839a1 Internals: adding ImGuiNavMoveFlags_NoClearActiveId even though there's currently no satisfying way to take advantage of it. (#1418)
742e53434f4 Child Windows: adjust resizing limits to match window padding rather than inner clipping rectangle. (#7440)
515b437c084 Child windows: look at the parent window's flags to decide whether to clamp child resizes. (#7440, #1710)
976dc239656 Windows: extend outer resize borders to the edges when there are no corner grips. (#7440, #1710)
37b37fc2a3e DrawList: Allow AddText() to accept null ranges. (#3615, 7391)
5c5ae806aa1 Comments
cf4c10bef74 Style: added ImGuiStyleVar_TabBorderSize, ImGuiStyleVar_TableAngledHeadersAngle. (#7411)
f0802287db5 Tables: Angled headers: fixed table contents overflowing when a list clipper is used. (#7416)
29ff159f941 Tables: Angled headers: fixed borders not moving back up after TableAngleHeadersRow stops being called. (#7416)
38ddfb24f09 Tables: Angled headers: fixed border hit box extending beyond non-scrollable tables. (#7416)
8be48a44f78 Backends: WebGPU: Avoid using -1u literal (#7436)
868facff9de ImDrawList: (Breaking) merge float radius_x/radius_y parameters into ImVec2 radius in PathEllipticalArcTo(), AddEllipse(), AddEllipseFilled(). (#2743, #7417)
0a1f5b94e31 Demo: Two minor fixes (unchecked BeginTooltip + incorrect height constraint) (#7410)l
40df3db1a2a Tweaking terminology
da29b776eed Backends: SDL3: Fix leak of SDL_GetGamepads() return value (#7381)
3c435c02978 Inputs: (Breaking) More formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. (#4921)
286cd5bd41e Internals, InputText: removed ImGuiInputSource_Clipboard. (#4005)
fc570ac9225 Examples: WGPU: fixed initialization of WGPURenderPassColorAttachment (#7371)
65dc67f63c6 Windows: Double-click to collapse may be disabled via key-ownership mechanism. (#7369)
6b7358e9f36 InputText: adding clarifying note about ImGuiInputTextCallbackData::Buf. (#7363)
fbf45ad149b ImDrawList: add PathFillConcave(), AddConcavePolyFilled(): amends (#760)
1ff90c52d5f ImDrawList: add PathFillConcave(), AddConcavePolyFilled() (#760)
04f40014a62 Docs: added a mini wiki index in main source files.
c6236699671 Added link to crawlable wiki
0573513d6df Windows: Scrollbar visibility decision uses current size when both size and contents size are submitted by API. (#7252)
44c7dfca030 Menus, Popup: Amend c3f8f4d for static analyzer warning ("condition always true"). (#7325)
c3f8f4de257 Menus, Popups: Fixed an issue where sibling menu popups re-opening in successive frames would erroneously close the window. (#7325, #7287, #7063)
98779417751 Popups, Menus: rename ImGuiPopupData::BackupNavWindow > RestoreNavWindow and minor tweaks. Should be functionally a no-op.
725f91922d5 Tables: fixed TableGetHoveredRow() with overlapping frozen rows (#7350, #6588, #6347, #6250)
e46d1e69ac3 Version 1.90.5 WIP
277ae93c413 Version 1.90.4
f5be90523d6 Nav: Fixed SetKeyboardFocusHere() or programmatic tabbing API from not working on windows with the ImGuiWindowFlags_NoNavInputs flag.
13d91ff9188 Nav: Fixed SetKeyboardFocusHere() or programmatic tabbing API from not working on windows with the ImGuiWindowFlags_NoNavInputs flag.
34965cf23a7 Modals: Temporary changes of ImGuiCol_ModalWindowDimBg are properly handled by BeginPopupModal(). (#7340)
659fb41d0a2 Debug Tools: moved DebugStartItemPicker() to public API. Added to Demo->Tools menu. (#2673)
198c38f0b11 Demo: Custom Rendering: better demonstrate PathArcTo(), PathBezierQuadraticCurveTo(), PathBezierCubicCurveTo(), PathStroke(), PathFillConvex() functions.
3b6d924acd0 ProgressBar: Fixed a minor tesselation issue when rendering rounded progress bars.
d3f1a7165cb Popups: allow Child Popups to be resizable if not explicitly disabling.
e78ce72eb6d Popups: Fixed resizable popup minimum size being too small. Standardized CalcWindowMinSize() logic a bit more. (#73290
014e0ac8c92 Menus, Popups: Fixed an issue where hovering a parent-menu upward would erroneously close the window. (#7325, #7287, #7063)
c16043c1d58 Tables: Angled headers: improve clipping of text since multi-line labels makes clipping issues visible. (#6917)
405e54ebd50 Tables: Angled Headers: fixed support for multi-line labels. various padding/layout fixes. (#6917)
6655ab2e43f Tables: Angled Headers: fixed TableAngledHeadersRow() incorrect background fill drawn too low. Fixed row geometry with non-small values of CellPadding. (#6917)
9159cd7b4ac Updated invalid documentation link (#7331)
ccc5347e451 Fix typos (#7332)
8a14b71f228 Version 1.90.4 WIP
b19a4c5f2b3 Backends: OSX: remove legacy clearing of io.NavInputs in ImGui_ImplOSX_UpdateGamepads(). (#7320)
5b6f03213dd Version 1.90.3
f80e65a4068 Backends:,Examples: Vulkan: moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. (#7308)
829f45df994 Backends: SDL2: removed obsolete ImGui_ImplSDL2_NewFrame(SDL_Window*) signature which was obsoleted in 1.84..
3cc37170ca7 Examples: GLFW+Metal: Add -I and -L paths for MacPorts.
891b81fc5d7 Backends: SDL3: Fixed gamepad. Added support for disconnection. Added support for multiple gamepads. Added ImGui_ImplSDL3_SetGamepadMode(). (#7180, #3884, #6559, #6890)
262e30e3001 Backends: SDL2: rework new API as ImGui_ImplSDL2_SetGamepadMode(). (#3884, #6559, #6890, #7180)
9dfa2397deb Internals: Fixed ImFileOpen not working before context is created. (#7314, #7315)
d15e4100b83 Backends: SDL2: Amend new API, all support for multiple gamepads. (#3884, #6559, #6890)
f966da1f8fb Backends: SDL2: Gamepad handlng: amend bf1c96d. (#3884, #6559, #6890)
bf1c96d4fa2 Backends: SDL2: Handle gamepad disconnection + fixed increasing refcount. Added  ImGui_ImplSDL2_SelectGamepadAuto()/ImGui_ImplSDL2_SelectGamepadExplicit(). (#3884, #6559, #6890)
fd8d6dc5d19 Backends: SDL2,SDL3: tidying up.
e0ba0d0433a Backends: Vulkan: Fixes for building with pre Vulkan 1.3. Amend 8901931. (#7166)
11d73f03ee5 Backends: Vulkan: Fix/amend 8901931
89019319ddb Backends: Vulkan: use PipelineRenderingCreateInfo for dynamic rendering (#7166, #6855, #5446, #5037)
1d6f0cea0e6 Backends: DX9: use RGBA texture to avoid conversion if supported
3af739a2d17 Menus, Popups: fixed menus and popups with child window flag erroneously not displaying a scrollbar when contents is over parent viewport size. (#7287, #7063)
2af01baffd1 Backends: SDLRenderer3: query newly added SDL_RenderViewportSet() to not restore a wrong viewport if none was initially set.
915c6393ad7 Version 1.90.3 WIP
536090303a8 Version 1.90.2
7b5357d817e Debug Tools: Metrics: Improved Monitors and Viewports minimap display. Highlight on hover.
70aa717a8e1 Combo: Fixed not reusing windows optimally when used inside a popup stack.
5cdc4a2a413 Demo: use ImGui::MemAlloc/MemFree for consistency. (#7300)
76e09c4b0fa ClosePopupsOverWindow(): amend to remove _ChildWindow test.
3a078466a7a Nav: ImGuiWindowFlags_NoNavInputs is tested during scoring so NavFlattened windows can use it.
7d67623d15b InputText: Internal: ReloadUserBufXXX functions don't override revert value. (#2890) fix accidental comment.
a5e0e90c16a Nav: tweak RenderNavHighlight() syntax. ImGuiNavHighlightFlags_TypeThin -> ImGuiNavHighlightFlags_Compact.
1e8fc01ddd7 InputText: Internal: ReloadUserBufXXX functions don't override revert value. (#2890) + rename
a06dd7a27b6 OpenPopup(): Added ImGuiPopupFlags_NoReopen. Nav, Menus: Fixed click on a BeginMenu() followed by right-arrow. (#1497, #1533)
f104967c68f Comments
06ce312745e InputText: Internal: added reload from user-buf feature. (#2890)
f50ddc431e3 Fixed some typos. (#7282)
6172c22c5dc CI: Update to `actions/checkout` `v4` from `v3`. (#7281)
96839b445e3 Nav: Improve handling of Alt key to toggle menu so that key ownership may be claimed on indiviudal left/right alt key without intefering with the other.
71947563709 Shortcut: fixed single mod-key Shortcut from working e.g. Shortcut(ImGuiKey_LeftCtrl)
f1960b60c1a Added "nop" to IM_DEBUG_BREAK macro on GCC to work around GDB bug (#7266)
8491cf36adb Inputs: g.ActiveIdUsingManyKeys[] prevent routes from being claimed.
9176eedf240 Internals: SetShortcutRouting() move code so next commit is easier to read. Should be no-op.
1509842107d Backends: OpenGL3: Shallow tweak of compile-time extensions detection.
1ce41f6218d Backends: OpenGL3: Backup and restore GL_PIXEL_UNPACK_BUFFER. (#7253)
81e0be856a6 Fixed strict-aliasing violation in FormatTextureIDForDebugDisplay(). (#7090, #7256)
a201af73544 Added SetNextItemShortcut() wip function. (#456)
4c2c09450a6 Nav: keyboard/gamepad activation feedback properly timed instead of frame buffer. (#456)
5b5e9bd0cb3 Internals: Tweak shallow compaction as Clang complains about MS ABI signage of enums.
7c3fa7d049a Refactor: moved section in imgui_internal.h
9266c0d2d13 Backends: WebGPU: Avoid leaking pipeline layout. (#7245)
595eb86624d Changelog, comment, minor data compaction
6850194f60a CI: Fixes WGPU example build.
5fc0a361b24 Backends: WebGPU: added ImGui_ImplWGPU_InitInfo::PipelineMultisampleState. (#7240)
831d42c1ab3 Backends: WebGPU: ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes. (#7240)
e3c7ff944d5 Examples: Emscripten+WebGPU: slightly refactor like other Emscripten compatible Desktop examples, as aiming to make this suppot desktop eventually.
15908502ed6 Backends: Vulkan: Define NOMINMAX when VK_USE_PLATFORM_WIN32_KHR is defined. (#7250)
788747f8635 Examples: Emscripten+WebGPU: Remove use of deprecated ObjectBase<...>::Release in favor of ::MoveToCHandle (#7251)
763100b3858 Nav: Fixed pressing Escape while in a child window with _NavFlattened flag. (#7237)
c7edb446caa Shortcut(): always test ownership.
1844f903d55 Nav: space/enter poll check ownership. InputText: declare ownership of Enter key as it doesn't go through Shortcut
5ddfbb80d86 Backends: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236)
2f483373355 Examples: Vulkan: Rename compile-time defies for the examples to remove misleading IMGUI_ prefixes.
d7c2a0e38f4 Shortcut(): fixed 8323a06 adding _Repeat to all Shortcut() calls.
3b828d3701e Refactor: moving ItemAdd() into a section abote ItemSize(). No logic change (part 2)
ff5f3aa38b5 Refactor: moving ItemAdd() into a section abote ItemSize(). No logic change (part 1)
1a48a634466 Enclosed a few more remaining sections in ifndef IMGUI_DISABLE_DEBUG_TOOLS for completeness.
33fabdf392d Scrollbar() doesn't forcefully mark itself as hovered when held.
d431d85839b Internals: removed obsolete ImPool::GetSize() (last used by implot 0.10, changed in implot 0.11)
f0d1f61fa51 Internals: commented out long-time obsoleted FocusableItemRegister()/FocusableItemUnregister() documentaton-only leftovers. +
095665977f6 Nav: marking NavId as hovered in ButtonBehavior() doesn't check for ActiveId.
d10641b04a3 Nav: keyboard/gamepad activation mark widgets as held to give better visual feedback.
03417cc77d1 Backends: WebGPU: Filling all WGPUDepthStencilState fields explicitly as a recent Dawn update stopped setting default values. (#7232)
5fdcdf7080a Shortcut: ImGuiInputFlags_RouteFocused policy can filter Shortcuts conflicting with character input when an item is active. (#456)
80d5cb1ab1f Comments around ImGuiInputFlags.
1cc0eb4d322 Internals: Rename NavFocusScopePath to NavFocusRoute + fixed a static analyzer warning.
46e5f44ec8c Shortcut()/SetShortcutRouting(): use mixed current window focus scope + ParentWindowForFocusRoute. (#6798, #2637, #456)
e0c8c80adaa Shortcut()/SetShortcutRouting(): focus route testing now use ParentWindowForFocusRoute. Automatically set on child-window, manually configurable otherwise. (#6798, #2637, #456)
4b20a0217eb Internals: add window to FocusScopeStack. (#6798)
2156db7a075 Debug Log: added InputRouting logging. Made GetKeyChordName() use its own buffer. Fixed debug break in SetShortcutRouting(). (#6798, #2637, #456)
dd0efdc6371 Fixed SetKeyboardFocusHere() not working when current nav focus is in different scope. (#7226)
8a3dfda8d08 Commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
6228c2e1ec7 Backends: Vulkan: moved ImGui_ImplVulkanH_DestroyFrameRenderBuffers/ImGui_ImplVulkanH_DestroyWindowRenderBuffers as they are always used in a state where backend data is available.
70bb6d1e790 Backends: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size. (#3957)
82df7c8bf41 Backends: Vulkan: Fixed handling of ImGui_ImplVulkan_InitInfo::MinAllocationSize field. (#7189, #4238)
29809d72202 Version 1.90.2 WIP
db049db8608 Docs: tweak, fixed misplaced changelog entry. (#7084)

git-subtree-dir: external/imgui/imgui
git-subtree-split: b475309fa1e9d7a91825a169e243f9c4fa085f71
2024-04-15 18:19:01 +02:00
dadc72c8e0
Merge commit '5dd98340099b3f44e06208a3124182bcf818a77e' into refact_and_update_sdl_imgui 2024-04-15 18:19:01 +02:00
7ee4ed0020
sdl renamed "RW" to "IO" 2024-04-15 18:13:12 +02:00
3d557f91d8
remove sdl subtree and update 2024-04-15 18:12:55 +02:00
85edd0eab6
forgot one 2024-04-15 01:29:55 +02:00
cedb63b87a
disable a bunch of libwebp stuff 2024-04-15 01:22:24 +02:00
14f1d1d37f
remove webp from source tree and fix some bugs 2024-04-15 01:10:15 +02:00
Erik Scholz
8c24234126
Merge pull request #8 from Green-Sky/fragment_store
ObjectStore backed MessageFragments
2024-04-14 14:38:49 +02:00
e0d873d41c
Merge branch 'master' into fragment_store 2024-04-14 14:32:31 +02:00
5728432b76
everything put into their respective repos 2024-04-14 14:30:42 +02:00
0030487613
move converter tool and pics out 2024-04-14 14:16:53 +02:00
f932f5ffb4
mfs and ms moved to their own repo, now only a few files left to clean up 2024-04-14 13:58:31 +02:00
da83065024
make sure we have the right json version in the flake 2024-04-14 12:03:58 +02:00
a6614e76ce
move cursers to public api 2024-04-14 11:13:05 +02:00
cdd67f4779
fix flake and pull in os zstd fixes 2024-04-14 10:57:07 +02:00
a845609660
actually allow loading v2 and enable in converter 2024-04-14 10:23:13 +02:00
de3b8f059e
import os and zstdfile2 bugfixes 2024-04-13 21:06:51 +02:00
7b4af58544
prep convert tool for msgpack transition 2024-04-13 19:47:28 +02:00
f287348550
introduce message fragments version 2 (msgpack)
more smaller refactors
2024-04-13 19:13:18 +02:00
498b4435c7
refactor message contexts 2024-04-13 11:38:13 +02:00
a5e67d0ee8
move uuid gen to util 2024-04-12 19:44:24 +02:00
9e30983b22
Merge branch 'master' into fragment_store 2024-04-12 19:24:20 +02:00
195a87b8ab
add object store and expose to plugins 2024-04-12 19:03:30 +02:00
dfbb1dea68
move os and backend to sub 2024-04-12 13:42:08 +02:00
2597edd579
new messages objcomp names 2024-04-12 13:42:08 +02:00
85a29372f4
adding message frag object version and conversion work, but comp name changes incoming 2024-04-12 13:42:07 +02:00
a9f6a5d763
move mfs to os, works, convert tool still incomplete 2024-04-12 13:42:07 +02:00
73180195fe
some more backend interface changes i realized i had to do 2024-04-12 13:42:07 +02:00
10b689ca95
refactor the serializer again 2024-04-12 13:42:07 +02:00
3796841961
conversion improvements 2024-04-12 13:42:07 +02:00
854ed851b4
fixes missing comps and conversion tool is almost working (most of meta is transfered) 2024-04-12 13:42:07 +02:00
5c3b797a99
new object (os + fsb mostly done) 2024-04-12 13:42:06 +02:00
8a580e2fbb
backend fs read 2024-04-12 13:42:06 +02:00
3cede91aa0
more work on backend and moving frags to objs 2024-04-12 13:42:06 +02:00
0610a6a64a
continue os refactor, start with fs backend 2024-04-12 13:42:06 +02:00
26d07b06db
start refactoring in the name of object store 2024-04-12 13:42:06 +02:00
fd0b210bbb
fragment store fully file2 zstd. no more zstd.h in fragment store 2024-04-12 13:42:06 +02:00
268cbe137e
move file stack creation to separate file, removing some scope 2024-04-12 13:42:05 +02:00
31bb0d3e61
refactor meta data decompression using file2 and mem 2024-04-12 13:42:05 +02:00
248f68f6a2
minimal stack creation refactor (wip) 2024-04-12 13:42:05 +02:00
3b010bd16f
catch write errors (eg unsanitzed strings) 2024-04-12 13:42:05 +02:00
7e285290fe
test in memory comp 2024-04-12 13:42:05 +02:00
5767834f71
since its working, remove old commented code 2024-04-12 13:42:05 +02:00
53ce292e82
fix stack overflow (i am stupid) and some file stack error handling 2024-04-12 13:42:04 +02:00
84bd24807d
small change to flush work space. writing new frags is broken rn 2024-04-12 13:42:04 +02:00
8d0518c2e3
harden against some parsing exceptions
(by disabling them, since the error case is already handled)
2024-04-12 13:42:04 +02:00
6d150ba441
roll back meta comp (did it wrong) and enable data comp 2024-04-12 13:42:04 +02:00
c737715c66
more refactor and transition meta write 2024-04-12 13:42:04 +02:00
b640b5a06b
variant to span helper 2024-04-12 13:42:04 +02:00
1b9363e7b5
tested and works, cleaning up commented code 2024-04-12 13:42:03 +02:00
16d2238f35
fixes for ci 2024-04-12 13:42:03 +02:00
19844a9423
use file2 zstd wrapper to read frag data (untested) 2024-04-12 13:42:03 +02:00
19fd99f713
refactor out uuidgenerator 2024-04-12 13:42:03 +02:00
f22f523774
minor frag store refactor 2024-04-12 13:42:03 +02:00
8b17ed195f
more testing and file2 zstd now passes tests with varying frame sizes
and 1.5gig files
2024-04-12 13:42:03 +02:00
def7fc1959
add file2 impl for zstd (lightly tested and not integrated yet) 2024-04-12 13:42:02 +02:00
318be9cd62
throw update 2024-04-12 13:42:02 +02:00
2772c8ee69
reduce excessive message frag saving (queue dedup + waiting 10sec)
prepare for frag updates
2024-04-12 13:42:02 +02:00
eac2927379
try to tame log spam 2024-04-12 13:42:02 +02:00
77a0ae6acd
fix accel structure being wrong and mark empty frags and dont count them 2024-04-12 13:42:02 +02:00
7879a0927b
combat memory leaks with smart pointers 2024-04-12 13:42:02 +02:00
88ea3e177d
refactor saving and save on exit 2024-04-12 13:42:01 +02:00
bc22451524
dirty frag on message updates (if still open) 2024-04-12 13:42:01 +02:00
7b8e93eec3
refactor message fuid -> fid
save alot of memory by using fid instead of fuid
2024-04-12 13:42:01 +02:00
71be5c3c6e
reduce log spam 2024-04-12 13:42:01 +02:00
2b8cee6a29
remove old code 2024-04-12 13:42:01 +02:00
5bf4640d61
forgot to throw update on read 2024-04-12 13:42:01 +02:00
0e0e81720b
dont sync messages we dont know enough about 2024-04-12 13:42:00 +02:00
592a4cb9cf
make adjacency loading work, extend range and use loops 2024-04-12 13:42:00 +02:00
93f60bd073
replace old bad prev/next code with way better code 2024-04-12 13:42:00 +02:00
6a6de77ae9
smaller contact frag fixes 2024-04-12 13:42:00 +02:00
89f065a610
impl new acceleration structure for components, not exploited yet
disable funky load at first msg
2024-04-12 13:42:00 +02:00
52e95ca654
forgot to check contact 2024-04-12 13:41:59 +02:00
eaa316a2aa
rework cursers for cg, keep views between switching. will be refactored later 2024-04-12 13:41:59 +02:00
bdf4e60f2f
fix one inverted comparator 2024-04-12 13:41:59 +02:00
2e3c779bec
stop ignoring mfs interval and sort after 2024-04-12 13:41:59 +02:00
461a4f1aa7
make inital curser a range 2024-04-12 13:41:59 +02:00
78488daa9b
loading logic implemented but broken (very funky and sometimes even out of contact) 2024-04-12 13:41:59 +02:00
22f2c8f514
load based on view cursers (untested and not used yet) 2024-04-12 13:41:58 +02:00
e442191aad
msg frag before and after helper 2024-04-12 13:41:58 +02:00
795ab2d4e1
fix potential tsrange errors and deduplicate state 2024-04-12 13:41:58 +02:00
0896038dd6
make writing safe (by using a tmp file and moving to actual location) 2024-04-12 13:41:58 +02:00
67c6f9adb0
make empty contacts from ids on message load 2024-04-12 13:41:58 +02:00
6aac44cda9
change binary meta format and add zstd to metadata 2024-04-12 13:41:58 +02:00
4fb2b51b7d
switch to streaming compressor for data to drastically improve ratio.
would still benefit from a abstract file refactor
2024-04-12 13:41:57 +02:00
182d844e32
update fs readme a little 2024-04-12 13:41:57 +02:00
6f511016bc
save msg json zstd compressed (3x compression) 2024-04-12 13:41:57 +02:00
fb885b5c21
simplify array cast a little 2024-04-12 13:41:57 +02:00
527a7c63f6
add zstd dep 2024-04-12 13:41:57 +02:00
d21dbb43e2
comp refactor and make groups work 2024-04-12 13:41:57 +02:00
7ac62274f4
move json around and disable files for now 2024-04-12 13:41:56 +02:00
4ec87337c8
reverse message write order 2024-04-12 13:41:56 +02:00
20f7c6d011
add dup check, would work for ngc if we saved tox group msg id yet 2024-04-12 13:41:56 +02:00
24dc5a03f3
fix dup on write 2024-04-12 13:41:56 +02:00
3d0863ff9a
basically working, but some dup glitch is still there 2024-04-12 13:41:56 +02:00
97aedca844
scan laters 2024-04-12 13:41:56 +02:00
2e7d5538d1
fragment events + 256bit uuids 2024-04-12 13:41:55 +02:00
1bfd04680e
refactor message serializer to allow access to eg contacts 2024-04-12 13:41:55 +02:00
73d1d65142
further serializer refactoring 2024-04-12 13:41:55 +02:00
f6e55851cc
improve deserialization and provide message comp deserl 2024-04-12 13:41:55 +02:00
0b0245d844
loading fragments mostly working (not notifying anyone yet) 2024-04-12 13:41:55 +02:00
d278391528
add contact id to meta 2024-04-12 13:41:55 +02:00
aa7a5d6013
more comps 2024-04-12 13:41:54 +02:00
84987216cb
handle empty type 2024-04-12 13:41:54 +02:00
58e9fd5514
dump messages to data (some comps) 2024-04-12 13:41:54 +02:00
3d41eedf48
message fragment meta is saved, but still empty data 2024-04-12 13:41:54 +02:00
2bc30ffcdc
start with messages (no fragments get created yet) 2024-04-12 13:41:54 +02:00
e67d7d37b5
refactoring, add to mainscreen 2024-04-12 13:41:54 +02:00
98ab974515
random ids 2024-04-12 13:41:53 +02:00
267f8dffc1
working prototpying code 2024-04-12 13:41:53 +02:00
b38a1a2507
better github cd 2024-04-12 13:40:58 +02:00
ee87dbc532
update utils 2024-04-12 13:40:35 +02:00
78c7ef5b46
fix main screen destruction order,
so plugins can cleanup before their facilities get destroyed
2024-04-06 11:59:05 +02:00
95ec596cfd
Merge commit '47ad96e2b6c5704872b3615a160cd78d29b46b21' toxcore v0.2.19 2024-03-28 16:13:51 +01:00
47ad96e2b6 Squashed 'external/toxcore/c-toxcore/' changes from 3e05824b80..da438763d5
da438763d5 chore: Release 0.2.19
f90417987c chore: Add cmake flag to disable unit tests.
7df3f99417 docs: Document that group topic lock is default on.
9e9ed77390 docs: Add missing param docs for callbacks.
0ec4978de5 refactor: Don't expose Tox_System in the public API
a3d1b8595c docs: Public headers, Core/toxcore -> Tox/the Tox library
f78d0f3f39 docs: Public headers, events_alloc -> internal
817518949e docs: Public headers, NULL-terminated -> NUL-terminated
be085db191 docs: Public headers, spellcheck
4c902955f3 docs: Public headers, 80 column width comments
be8a82a818 docs: Public headers, null -> NULL
419d783d95 docs: Public headers, tox -> Tox
5c8aa65e41 docs: Update user data API explanation
ad4921dbaa cleanup: A more descriptive error for group invite accept function

git-subtree-dir: external/toxcore/c-toxcore
git-subtree-split: da438763d5b8e071de6e061a1dcaddd2177dff7d
2024-03-28 16:13:51 +01:00
396477f66b
update utils 2024-03-28 16:11:26 +01:00
01edf9e76e
cleanup 2024-03-16 16:43:45 +01:00
bde0f2c7c3
imgui debug stuff 2024-03-15 13:02:49 +01:00
83bbac2cd1
proper cleanup procedure for main 2024-03-15 13:02:37 +01:00
d5dede5a61
properly cleanup in main 2024-03-12 18:43:36 +01:00
719400068a
cache the localtime result in the message
localtime uses global state AND spams allocations like cazy
2024-03-12 18:09:42 +01:00
aaf8c6adc1
save cooldown for tox profile (10sec after last) and save on exit 2024-03-12 18:09:21 +01:00
dc081ae2aa
fix webp mem leak 2024-03-11 20:46:28 +01:00
3cf3097094
toxcore update + private interface update 2024-03-11 11:46:18 +01:00
a5093c4aa3 Squashed 'external/toxcore/c-toxcore/' changes from b03b571272..3e05824b80
3e05824b80 refactor: Rename `out` parameters to `out_$something`.
0199c0f17f cleanup: apply the same scheme to types
aebbfabe26 cleanup: event length naming inconsistencies
2457125aa8 cleanup: align group send err enum order

git-subtree-dir: external/toxcore/c-toxcore
git-subtree-split: 3e05824b80eb9bee33e8254cba0780d84c522182
2024-03-11 11:34:13 +01:00
e801626232
Merge commit 'a5093c4aa36d66049b6b5ca94e3b17412e77391b' 2024-03-11 11:34:13 +01:00
c311bb5c95
update tox interface 2024-03-10 20:50:13 +01:00
887705969f
make texture streaming actually work 2024-03-09 16:26:35 +01:00
316871523d
update nixos target 2024-03-09 11:50:55 +01:00
a3d193516c
add updating to textures 2024-03-08 22:04:58 +01:00
6709dba0e7
remove old test 2024-03-08 12:29:48 +01:00
a8d8613f2c
adopt to new toxcore master 2024-03-08 10:50:58 +01:00
aae086cc65 Squashed 'external/toxcore/c-toxcore/' changes from e2c01e457b..b03b571272
b03b571272 fix: flaky tcp test This only fixes the symptoms, not the real problem. Sometimes or consistently on some platforms a socket might need a moment before it can be written to.
32e67ab4c2 cleanup: use typedef for private message ID's in callback
7b1db6adc1 feat: add message IDs to private group messages
99e0bcc27d refactor: Observers/ignored peers can now send and receive custom packets
b3c3c49d26 fix: Disable IPv6 in Windows cross-compilation tests
e742deddff feat: Check hashes of Windows dependencies when cross-compiling
dfb9a0b02b fix: Test the current Windows Dockerfile, not an old Dockerhub image
14de93ccec chore: Use WineHQ's Wine as Debian Bookworm's crashes
ed37616249 docs: Update the Windows cross-compilation section
9bb79c174f cleanup: Remove a couple of unnecessary misc_tools dependencies
19475adb70 chore: Statically link OpenMP into the cracker fun util on Windows
1be311e51f feat: Build the fun utils when cross-compiling to Windows
88133f8446 chore: Strip Windows binaries
3cc0ae7535 refactor: Copy over all of the required static dependencies
c4fa8f7fb1 feat: Generate .def, .exp and .lib files when building for Windows
74bbac5363 feat: Let CMake create the dll instead of doing so ourselves
246642e9ae feat: Harden Windows cross-compilation
8d431c0d11 chore: Bump Windows build dependency versions
e519f7998b fix: Remove unnecessary wsock32 dependency on Windows
ed2b60c217 chore: Use a specific non-broken slimcc version.
d7f21010a1 chore: Update github actions.
e71a68b7f2 docs: Update the list of CMake options
77e08876ff chore: Remove mod and founder from group API naming scheme
12bc042767 docs: add the experimental api build option to INSTALL.md
e1fa5cae96 refactor: Rename Queries to Query to align with other enums.
be82a3ea30 fix: Correct type for conference offline peer numbers.
0627c36716 test: Add pkgsrc build.
92578afe4b test: Add FreeBSD VM action on GitHub.
52ece0f57b test: Build toxcore on NetBSD (VM).
3fe8ee2c11 chore: Only install tox_private.h on request.
9a8dfa06ab fix: save_compatibility_test failing on big-endian systems
86f5e55578 fix: Don't serve files from websockify.
710eb674a5 fix: Correctly pass extended public keys to group moderation code.
021db7031c refactor: Use `struct`s for extended public/secret keys.
a1e999fd80 chore: Compile libsodium reference implementation with compcert.
fbe3c19cf5 cleanup: correct a few nullable annotations
623e3ee5c3 cleanup: Don't use `memcpy` to cast arbitrary `struct`s to `uint8_t[]`.
c71567dc18 fix: Pass array, not array pointer, to `memcmp`.
9b46a08144 cleanup: Never pass `void*` directly to `memcpy`.
5d7b7a7bbc refactor: Use tox rng to seed the keypair generation.
961891d568 cleanup: Small improvements found by PVS Studio.
8201019f0d chore: Disable NGC saving by default, enable through Tox_Options.
5dd9ee3f65 cleanup: Replace pointer arithmetic with explicit `&arr[i]`.
ca4606d49d refactor: Use strong typedef for NGC peer id.
442213b722 cleanup: Simplify custom packet length check in NGC.
08d3393def fix: Correct a few potential null derefs in bootstrap daemon.
b9877b32b0 fix: Add missing memunlock of local variable when it goes out of scope.
dab5fe44b9 fix: Zero out stack-allocated secret key before return.
f058103299 refactor: Make prune_gc_sanctions_list more obviously correct.
3ba7a0dec9 docs: Add static analysis tool list to README.
8d0811a0f3 docs: Run prettier-markdown on markdown files.
969e3a2bfc refactor: Fix network test not using the strong typedef
93c83fbc7c refactor: Use strong typedef instead of struct for `Socket`.
9fe18b176f fix: Fix some false positive from PVS Studio.
7c44379ccb cleanup: Check that WINXP macro exists before comparing it.
5c93231bef refactor: Make tox mutex non-recursive.
aacff73939 docs: Fix up doxyfile.
d55fc85ff5 docs: Add more documentation to crypto_core.
5bdaaaedb6 refactor: Remove `Tox *` from `tox_dispatch`.
e202341e76 refactor: Don't rely on tox_dispatch passing tox in tests.
34df938f52 chore: Use C++ mode for clang-tidy.
8b05296a78 chore: Check that both gtest and gmock exist for tests.
42010660e1 test: Add slimcc compiler compatibility test.
b473630321 chore: Add some comments to the astyle config.
b7404f24f6 cleanup: Remove implicit bool conversions.
4e2dba4d9f chore: Reformat sources with astyle.
4359e3a6bc chore: Rename C++ headers to .hh suffixes.
0c05566e58 cleanup: Further `#include` cleanups.
8d29935b7a chore: Only check the bootstrap daemon checksum on release.
f70e588bc6 cleanup: Add more `const` where possible.
511bfe39c8 cleanup: Use Bazel modules to enforce proper `#include` hygiene.
1710a0d091 refactor: Move pack/unpack `IP_Port` from DHT into network module.
a975943564 chore: Really fix coverage docker image build.
c08409390f chore: Fix post-submit coverage image.
39aadf8922 fix: Don't use `memcmp` to compare `IP_Port`s.
d94246a906 fix: partially fix a bug that prevented group part messages from sending.
eeaa039222 chore: Fix rpm build; add a CI check for it.
8328449c1a chore: Speed up docker builds a bit by reducing layer count.
d6d67d56f3 cleanup: Add `const` where possible in auto tests.
6aa9e6850d cleanup: Minor cleanup of event unpack code.
bdf460a3a9 refactor: Rename `system_{memory,...}` to `os_{memory,...}`.
203e1af81e fix: a few off by one errors in group autotests
5c093c4888 cleanup: Remove all uses of `SIZEOF_VLA`.
662c2140f3 test: Add goblint static analyser.
8f07755834 cleanup: Use `memzero(x, s)` instead of `memset(x, 0, s)`.
a7258e40cf cleanup: Use explicit 0 instead of `PACKET_ID_PADDING`.
6370d0f15d cleanup: Expand the `Tox_Options` accessor macros.
14a1a0b9bd cleanup: Remove plan9 support.
a05dccad13 test: Add a simple new/delete test for Tox.
1cdcf938b9 cleanup: Add comment after every `#endif`.
ba99d4dc4b test: Fix comment I broke in the events test PR.
e07248debb refactor: Migrate auto_tests to new events API.
bdd42b5452 refactor: Add common msgpack array packer with callback.
3c659f5288 cleanup: Rename group to conference in groupav documentation.
89957be230 cleanup: Ensure handler params are named after callback params.
c650d9d345 refactor: Pass `this` pointer as first param to s11n callbacks.
e7fb91ddb8 refactor: Allow NULL pointers for byte arrays in events.
5e2c8cabc1 cleanup: make some improvements to group moderation test
259de4867e cleanup: Remove `bin_pack_{new,free}`.
21a8ff5895 cleanup: skip a do_gc iteration before removing peers marked for deletion
16809dc36e feat: Add dht_get_nodes_response event to the events system.

git-subtree-dir: external/toxcore/c-toxcore
git-subtree-split: b03b5712720de9a9901ea12fd741f177327a7021
2024-03-07 23:12:55 +01:00
6ec6fe96e4
Merge commit 'aae086cc650e42eec1eea8db28cd01fa868d7f90' 2024-03-07 23:12:55 +01:00
2d31b57097
update msg 2024-03-07 23:08:26 +01:00
b1d4848b81 Merge commit '3678301916cce063f95c3f525d82e21c2a382cd6' as 'external/qoi/qoi' 2024-03-06 01:04:41 +01:00
3678301916 Squashed 'external/qoi/qoi/' content from commit 30d15d79b7
git-subtree-dir: external/qoi/qoi
git-subtree-split: 30d15d79b7726b977cd889151cc5cd6b17742f8f
2024-03-06 01:04:41 +01:00
459ccf7d6b
print sdl render 2024-03-06 01:02:59 +01:00
db54afd180
full on qoi 2024-03-06 01:02:59 +01:00
f4fe94dfe6
qoi lib 2024-03-06 01:02:59 +01:00
28b92b0f4c
prep qoi 2024-03-04 12:38:39 +01:00
c966fc6954
update sub changes coming from fs/os research 2024-03-04 11:28:51 +01:00
d0761bf60e
revert crop by default (did not work as intended) 2024-02-29 19:15:33 +01:00
0f41ee6a2e
add screencap to readme 2024-02-23 11:20:49 +01:00
0aeafec019
fix month starting at 0 2024-02-15 15:34:44 +01:00
9a0df4f577
date change 2024-02-15 15:29:01 +01:00
61714836bb
typos 2024-02-12 14:13:57 +01:00
cff0c100ec
add fragment store draft doc 2024-02-11 19:01:48 +01:00
010c49d100
stable names 2024-02-10 12:23:40 +01:00
ff5dbaffc0
fix some file selector glitches 2024-02-08 18:11:51 +01:00
b56d581e4b
fix normal feeling sluggish 2024-02-05 16:15:10 +01:00
aa661aaaa7
default to normal fps mode again 2024-02-05 16:10:30 +01:00
cc3f430bab
rework tc and move tcs out of cg into main screen, rework render pp
now respecting animation timing
2024-02-05 16:06:12 +01:00
139db5b03b
faster texture cache loading in low fps modes 2024-02-05 12:50:36 +01:00
7d0e5c80bd
lil dep update 2024-02-04 12:48:04 +01:00
f716ad9dd1
limit max main loop sleep 2024-02-03 20:49:52 +01:00
671772a20e
min fps for inactive reduced now 1fps 2024-02-03 19:07:14 +01:00
b0173f6d68
tox iterate interval pow(1.6)
fix faux offline inbetween timer
crop by default
2024-02-03 15:00:32 +01:00
3da5872df8
fix tffom and have it actually functioning 2024-02-03 01:05:50 +01:00
3deb6e8469
fix using bool for timestamps (oops) 2024-02-02 20:55:20 +01:00
0c674e0137
add tox friend faux offline message (still wonky) + small file copy error handling 2024-02-02 20:26:50 +01:00
7948d820c3
fix filepaths on windows 2024-01-30 15:16:01 +01:00
5aac3422aa
allow "copy file" which sets the text/uri-list with the file path 2024-01-30 11:58:01 +01:00
e8eaa7a232
Merge commit '04b33820291e8574ea2618aead9cd0be6a4df56b' 2024-01-27 13:03:42 +01:00
04b3382029 Squashed 'external/stb/stb/' changes from c39c7023eb..f4a71b1337
f4a71b1337 README.md: tweak credits
a8a25e17b5 update readme version numbers
0bc88af4de stb_image: optimizations
0ca75da4ec stb_image_resize2: remove whitespace
9d924f8a47 stb_image_resize: 2.04
4da08a1dbd stb_image: create_png_image_raw restructuring
c6d7c32e5d stb_image: Two warning fixes
07268cbf36 stb_image: New Paeth filter
ed64333410 tests: test_png_regress
45eb4ac158 global: very basic .gitignore for object files
e5f0e18d0f stb_image: Small PNG filter simplification
d373674115 stb_image: Fix zlib decoder end-of-stream handling
03f50e343d security notice
1d878bd2a3 security notice
beebb24b94 README.md: fix reference to stb_image_resize2.h
e81f294b16 stb_image_resize: switch GNU/clang from "asm" to "__asm__" for -c99 compatibility
c4bbb6e75f stb_image_resize2.h 2.00
REVERT: c39c7023eb stb_image: create_png_image_raw restructuring
REVERT: 8c3aa05487 stb_image: Two warning fixes
REVERT: 3aa1744a29 stb_image: New Paeth filter
REVERT: 2f3b7e47fa tests: test_png_regress
REVERT: d647af9ad2 global: very basic .gitignore for object files
REVERT: 5a44133dc5 stb_image: Small PNG filter simplification
REVERT: 9f1776a36d stb_image: Fix zlib decoder end-of-stream handling

git-subtree-dir: external/stb/stb
git-subtree-split: f4a71b13373436a2866c5d68f8f80ac6f0bc1ffe
2024-01-27 13:03:42 +01:00
7fe6df5889
update deps (fix uppercase hex and others) 2024-01-27 12:27:55 +01:00
2647c85323
add imgui stylign window + change how texture filters are applied 2024-01-21 20:20:32 +01:00
93140231c6
theme according to system 2024-01-21 14:28:56 +01:00
e76e56e025
larger font hack + linear texture filter for images 2024-01-21 13:58:22 +01:00
b1062e701e
make primary selection pasting work
it is also bugged, as SDL misses large parts of selection sources (terminals etc) but browers work
2024-01-20 18:06:58 +01:00
e72aebc043
add auto release 2024-01-19 16:53:13 +01:00
865dfa994f
make invisible images not render 2024-01-18 23:44:38 +01:00
25be42e308
correct imgui version and add vid 2024-01-18 18:36:29 +01:00
c6a0df409d
interface versions 2024-01-18 00:32:11 +01:00
a15a9af2b3
adopt code to new imgui and new sdl 2024-01-17 22:39:51 +01:00
ca6909b64a
imgui v1.90.1 Merge commit '5af8cfa8799b54f7549f6d730d498ecb42964032' 2024-01-17 21:11:13 +01:00
5af8cfa879 Squashed 'external/imgui/imgui/' changes from d4ddc46e77..d6cb3c923d
d6cb3c923d Version 1.90.1
6470e2279e Debug Tools: DebugRenderKeyboardPreview() scales better.
fdf8d02be1 Debug Tools: Added io.ConfigDebugIsDebuggerPresent and Debug Break buttons. (#2673)
788bb58b6b Metrics: Tweak, reorganize tools menu.
a5dec42866 Debug Tools: Debug Log: Clicking any filter with SHIFT held enables it for 2 frames only. (#5855)
a3eea8a75a Backends: OpenGL3: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink. (#6983)
69bf3291df Internals, Inputs: Fix for ImGuiInputFlags_RepeatUntilXXX logic when #ifdef IMGUI_DISABLE_OBSOLETE_KEYIO is not set.
af00b182e3 Examples: SDL3: Minor fixes following changes to API (SDL_WindowFlags -> Uint32).
fc2e532f99 Shortcut: do not return true on mods changes. Internals: added ImGuiInputFlags_RepeatUntilKeyModsChange, ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone, ImGuiInputFlags_RepeatUntilOtherKeyPress. (#456, #2637)
8323a06e6d Inputs: passing ImGuiInputFlags_RepeatXXX options automatically adds ImGuiInputFlags_Repeat.
58261dbe9a Internals: alter ImGuiInputFlags values to leave room + indent.
f1ae47c4b9 Docs: update links to Proggy Fonts. (#7211)
7f9533b840 ColorPicker: Fixed saturation/value cursor radius not scaling properly.
27e83c2953 Add comment about how ImGuiKey values are named after US keyboard keys. (#7205)
278cf1a7bc Readme: updated binaries. (#7193)
edeb8ee3ab More compact issue_template.yml
c6716f5e9f Fixed typo (#7197)
a1b06823fe Windows: BeginChild(): Resize borders rendered even when ImGuiWindowFlags_NoBackground is specified. (#1710, #7194)
0461ade24b Reworked issue template (amends) (#5927, #5915)
c528b688cf Reworked issue template. (#5927, #5915)
26eef4df87 Update issue_template.md
7938550d52 Comments and some extra line-wrapping in demo (#3193)
4758f74676 imgui_freetype: fix nullptr to ImTextureID cast (#7192)
6f10cef2a1 Backends: Vulkan: moved structure declarations.
33d18c580b Misc: During shutdown, check that io.BackendPlatformUserData and io.BackendRendererUserData are NULL. (#7175)
0ea99132c8 Backends: Vulkan: Stop creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT as we don't reset them.
4778560e66 Backends: Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous validation layer. (#7189, #4238)
e8dd47effa Backends: WebGPU: Fixing an issue when opening a popup in the wgpu backend (#7191)
718fa0eec6 Happy new year!
240ab5890b Backends: GLFW, Input: Use Unicode version of WndProc for get correct input for text in utf-8 code page. (#7174)
4a2426449a Drags, Sliders, Inputs: removed all attempts to filter non-numerical characters during text editing. (#6810, #7096)
f039e69b9c Settings: Fixed an issue marking settings as dirty when merely clicking on a border or resize grip without moving it.
8340a30d27 Debug: move debug assertion in post-clip code to reduce overhead. (#4796 and more).
1e1013085b Debug Tools: Debug Log: Hide its own clipper log to reduce noise in the output.
036a6c875e ColorEdit4: Further tweaks for very small sizes. (#7120, #7121)
0bd6489721 DragScalarN, SliderScalarN, InputScalarN, PushMultiItemsWidths: fixed multi-components width in tight space (#7120, #7121)
0000739c08 Internals: Fixed function name typo.
33d426842d Backends: Vulkan: ImGui_ImplVulkan_CreateFontsTexture() calls vkQueueWaitIdle() instead of vkDeviceWaitIdle(). (#7148, #6943, #6715, #6327, #3743, #4618)
3cb805489b Backends: GLFW, Emscripten: fixes for canvas resizing, amends. (#6751)
22a7d241ff Backends: GLFW, Emscripten: fixes for canvas resizing. (#6751)
b4c5a83cfe Commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter. (#2625, #7143)
70f2aaff43 Nav: tabbing happen within FocusScope. ImGuiWindowFlags_NavFlattened make window inherit focus scope from parent.
55073aa7a3 Examples; SDL: added missing return values checks from SDL_CreateWindow() calls. (#7147)
8764a1b7c4 Backends: Vulkan: free FontCommandBuffer explicitely (not actually required in normal code path, unless ImGui_ImplVulkan_DestroyDeviceObjects is declared directly). (#7104)
089ed30323 Replace usages of ImGuiKey_KeyPadEnter with ImGuiKey_KeypadEnter. (#7143)
e265610a0c Fixes for MSVC code analyzer.
f59b54c6f4 Nav: Activation can also be performed with Keypad Enter. (#5606)
0d582dabf3 Fixed warning (amend 54c1bde)
6cfe3ddf52 InputTextMultiline: Tabbing through a multi-line text editor using ImGuiInputTextFlags_AllowTabInput doesn't activate it. (#3092, #5759, #787)
54c1bdeceb Internals: removed unused ImGuiItemStatusFlags_FocusedByTabbing. (#4449)
4afffa36e9 InputTextMultiline: Fixed Tab character input not repeating
f6836ff37f Misc: Rework debug display of texture id in Metrics window (amend) (#7090)
07dbd46ddd Misc: Rework debug display of texture id in Metrics window to avoid compile-error when ImTextureID is defined to be larger than 64-bits. (#7090)
34646627aa ColorEdit4: improve components width computation to better distribute the error (#7120) (#7123)
86512eac06 DragScalarN, SliderScalarN, InputScalarN, PushMultiItemsWidths: improve multi-components width computation to better distribute the error. (#7120, #7121)
03298fe875 Windows: Fixed some auto-resizing path using style.WindowMinSize.x (instead of x/y).  (#7106)
69f524ba95 DragScalarN, SliderScalarN, InputScalarN, PushMultiItemsWidths: Added when component <= 0. (#7095)
9d8de45313 Image(): comment and minor refactor to resurface the fact that a border size may be added. (#2118)
5366bd09bf Scrolling: internal scrolling value is rounded instead of truncated. (#6677)
c58d2c89c3 Tabs: Added ImGuiTabItemFlags_NoAssumedClosure to enable app to react on closure attempt. (#7084)
1fade35159 DragScalarN, SliderScalarN, InputScalarN, PushMultiItemsWidths: Fixed incorrect pushes into ItemWidth stack when number of components is 1. [#7095]
58ca5f6424 Shortcut(): clearer early out in SetShortcutRouting() -> CalcRoutingScore() path.
d72e1563d4 Removed CalcListClipping() marked obsolete in 1.86. (#3841) + comments
9a2985611c Backend: Android: Remove Redundant Check (#7093)
0b77980cab Moved Tables API related declarations to their own section in imgui.h
aaf157cfdd Commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. Commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted in 1.80.
1fd5ff7152 Avoid C++26 removed deprecated arithmetic conversion on enumerations. (#7088, #7089. #2983, #3040)
52886872f1 Misc: Added IMGUI_USER_H_FILENAME to change the path included when using IMGUI_INCLUDE_IMGUI_USER_H. (#7039)
5768de79e2 InputText, ColorEdit, ColorPicker: better support for undocumented ImGuiItemFlags_ReadOnly flag. (#7079, #211)
b112d73edb Menus: amend to clarify/fix static analyzer warning.  (#6671, #6926)
2ee40d3cf9 Menus: Tweaked hover slack logic, adding a timer to avoid situations where a slow vertical movements toward another parent BeginMenu() can keep the wrong child menu open. (#6671, #6926)
b4b864e40a Backends: Vulkan: Fixed mismatching allocator passed to vkCreateCommandPool() vs vkDestroyCommandPool(). (#7075)
d2b0167610 Fixed link error when using IMGUI_DISABLE_DEBUG_TOOLS
7965494ff3 Debug Tools: Added DebugFlashStyleColor() to identify a style color. Added to Style Editor.
c1a3c7f445 Fixed Clang zealous warnings
c6ec69c7c1 Using nullptr in remaining examples/backends locations. (#6313, #7071, #4537)
888834c636 Backends: Android: Fixed build breaking typo. (#7060)
077e4db772 Misc: Added extra courtesy ==/!= operators when IMGUI_DEFINE_MATH_OPERATORS is defined.
6f171a066d Nav, IO: SetNextFrameWantCaptureKeyboard(false) calls are not overrided back to true when navigation is enabled. (#6997)
1f3090a48d Backends: SDL3: Fix indent (#7062)
86891b0986 Backends: Android: ImGui_ImplAndroid_HandleInputEvent() takes a const AInputEvent* (#7060)
f37f6f67f6  Windows: BeginChild(): Fixed auto-resizing erroneously limiting size to host viewport minus padding. (#7063)
bce4db00bc Drag and Drop: Fixed drop target highlight on items temporarily pushing a widened clip rect. (#7049, #4281, #3272)
65a10410e3 Docs: Add suggestion to turn of char8_t behavior for C++20 (#7025)
61b8197942 Misc: Renamed some defines in imstb_textedit.h to avoid conflicts when using unity/jumbo builds.
3733b5064e Backends: SDL3: Fixed unused variable warning on master on some targets. (#7000)
c5c1c4134b Backends: OpenGL3: imgui_impl_opengl3_loader.h: change #define ARRAY_SIZE to GL3W_ARRAY_SIZE to avoid external conflicts (#7017, #7018)
7bb0a525c3 Fixed text functions fast-path for handling "%s" and "%.*s" to handle null pointers gracefully. (#7016, #3466, #6846)
3d083dbe1a Version 1.90.1 WIP
b81bd7ed98 Version 1.90.0
623bff23ce Windows: WindowMinSize not applied on AlwaysAutoResize window. (amend e2035a5)
f298491a8a Docs: amend/tweak details about using io.WantCaptureMouse. (#7012)
5de1312e1c SplitterBehavior: tweak to not assert due to floating point precision.
afadf74a53 BeginChild: undo child name simplification as it reveal an issue with handling of ### in child names.
46843b683b Fonts: minor/shallow amends (#6925)
ade4d0e08a Fonts: added support for RasterizerDensity to FreeType based atlas generator. (#6925)
ed29ff08ba Fonts: added support for RasterizerDensity in built-in atlas generator. (#6925)
abfb9269b5 Fonts: added RasterizerDensity to ImFontConfig. (#6925)
add915bdc4 Backends: SDL3: Updates for recent API changes. (#7000)
4ad5817aac Update backends/language lists
75c46a3930 Demo: Partly fix resizing constraint demo. (#6210, #5627)
fe6544622b SetNextWindowSizeConstraints() clarified parameters, fixed comments. (#1139, #3186, #3270)
454f36d2af Removed 'bool border' legacy versions of BeginChild() as they seemingly have no value other than confusing user and IDE.
44dbad64d7 Backends: Vulkan: Fixes for VK_NO_PROTOTYPES.
79a9e2fdfb Backends: Vulkan: (Breaking) full font upload is performed by ImGui_ImplVulkan_CreateFontsTexture(), no need for user code to create or provide a command-buffer. Removed ImGui_ImplVulkan_DestroyFontUploadObjects(). (#6943, #6715, #6327, #3743, #4618)
6e7b43b6c7 Backends: Vulkan: Added ImGui_ImplVulkan_DestroyFontsTexture(), made ImGui_ImplVulkan_CreateFontsTexture() destroy previous one. (#6943, #6715, #6327, #3743, #4618)
d0da79c572 Defining IMGUI_DISABLE_OBSOLETE_FUNCTIONS now automaticaly define IMGUI_DISABLE_OBSOLETE_KEYIO. (#4921)
ab522dd18c Removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define. (#4537)
0f50b52da4 Backends: OpenGL3: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead of "libGL.so.1". (#6983)
5170a9d6dc Tables: Internals: renamed TableDrawContextMenu() to TableDrawDefaultContextMenu() for clarify.
fea52e29aa Tables: added flags to TableDrawContextMenu() in order to display selected sections + added internal table->DisableDefaultContextMenu = true way to submit your own contents.
0d3b468cb3 BeginChild(): added ImGuiChildFlags_AutoResizeX, ImGuiChildFlags_AutoResizeY, ImGuiChildFlags_AlwaysAutoResize + support for SetNextWindowSizeConstraints(). (#1666, #1395, #1496, #1710) + Demo
44345c2108 Better documented the difference between BeginListBox() and BeginChild() w/ ImGuiChildFlags_FrameStyle.
fa4c49b4a7 BeginChild(): resizing is only clamped on axis where there's no scrollbar. Added an extra ResizeX in Demo->Simple Layout.
cdbc21a191 BeginChild(): Added ImGuiChildFlags_FrameStyle as a replacement for BeginChildFrame(). (#1666, #1496, #1395, #1710, #462, #503, #263)
ab47efd9a0 Bits / comments
561af15d67 Internal: Added owner aware variant of IsMouseDoubleClicked() for consistency.
376035fd01 Nav: fixed programmatic nav calls (e.g. SetKeyboardFocusHere() from storing io.KeyMods)
cfc71ab7c5 Made ImDrawCallback_ResetRenderState special value -8 instead of -1 so it is pointer aligned (#6969)
1ab63d925f Undid some of the changes done by c95fbb4 because they are not compatible with docking code.
c0bc43ccff Offset values for ImGuiWindowFlags_NoNavInputs, ImGuiWindowFlags_NoNavFocus, ImGuiWindowFlags_UnsavedDocument.
f1d1a8d32b Windows: use relative mouse movement for border resize when the border geometry has moved. (#1710)
9235352400 BeginChild: Added ImGuiChildFlags_ResizeX and ImGuiChildFlags_ResizeY. (#1710)
34a0bc456e BeginChild: Added ImGuiChildFlags_AlwaysUseWindowPadding, obsoleted ImGuiWindowFlags_AlwaysUseWindowPadding. (#462, (toward #1666, #1496, #1395, #1710)
7713c29258 BeginChild: Upgraded 'bool border = true' parameter to use a ImGuiChildFlags type and the ImGuiChildFlags_Border value. (toward #1666, #1496, #1395, #1710)
88fec09715 ColorPicker4(): Fixed ImGuiColorEditFlags_NoTooltip when ImGuiColorEditFlags_NoSidePreview is also set. (#6957)
313676d200 Settings: omit outputing Collapsed=0 in .ini file. Changelog + docs tweaks
8ee85137d8 BeginChild(): Internal name used by child windows now omits the hash/id if the child window is submitted in root of id stack of parent window.
4e4042bc33 Windows: tidying up skipitems logic at end of Begin(), normally should be no meaningful side-effect.
bc3c6e74e6 Windows: fixed double-clicked border from showing highlighted at the new position.
e2035a514c Windows: shared code for CalcWindowMinSize().
c95fbb4464 Windows: Double-clicking bottom or right window border auto-resize on a singles axis.
ade2acfd1d Inputs: Added IsKeyChordPressed() public helper function.
1b9cb52d7b BeginChild(): rename parameters to reduce diff of upcoming patches.
f8dc03d702 Windows: Can also auto-resize by double-clicking lower-left resize grip (not only lower-right one).
56f7e853be Demo: expose more Combo flags + misc tidying up.
9a5da23553 Changelog formatting
d6d00b4fcf Moved BeginChild() above BeginChildEx() as it is more readable.
99913b5051 Internals: added IsKeyChordPressed() for consistency.
a8bdbfddf9 Tables: Fixed top-most and left-most outer border overlapping inner clip-rect when scrolling. (#6765)
8db02ef8df Tables: Fixed an issue with ScrollX enabled where an extraneous draw command would be created.
947255c3da Tooltips: made it possible to use ImGuiHoveredFlags_ForTooltip + a ImGuiHoveredFlags_DelayXXXX override. (#1485)
0b8c6b9bce Internals: removed seemingly unused AutoFitChildAxises.
12a3c77c2f Demo: Minor tweak to angled headers demo.
f96c5443b1 Tables: fixed angled headers with frozen columns.
32228d8add Tables: added Angled headers support. Added ImGuiTableColumnFlags_AngledHeader, ImGui::TableHeadersAngledRow(), style.TableAngledHeadersAngle. (#2957)
9f851ebfe4 Tables: added ImGuiTableFlags_HighlightHoveredColumn.
be1311cfc1 Tables: fixed double-clicking on a column from clearing HoveredColumnBorder for a frame.
08606714a3 Fixed incorrect assert in FocusTopMostWindowUnderOne() preventing child+popup from being used. (#6915, #718)
5053d79a24 Tables: Internal: rework so stacked headers height may be used.
b9ebb8e06f Tables: fixed right-clicking right-most section (past right-most column) from highlighting right-most column.
feddcf3030 Combo: amends for ImGuiComboFlags_WidthFitPreview. (#6881)
112d8fc41d Combo: added ImGuiComboFlags_WidthFitPreview. (#6881)
001f102f38 IO, Backends: added ImGuiKey_AppBack, ImGuiKey_AppForward. (#6891, #4921)
7bbd758681 Backends: Win32: revert oops chunk.
b0758c86d8 Backends: Added support for extra ImGuiKey values: F13 to F24 function keys. (#6891, #4921)
73346e4341 IO: Add extra keys to ImGuiKey enumerator: ImGuiKey_F13 to ImGuiKey_F24. (#6891, #4921)
0312a29e4c ImageButton(): clarify purpose of size. (#6901, #5533, #4471, #2464, #1390).
1107bffe84 Popups: clarified meaning of 'p_open != NULL' in BeginPopupModal() + set back user value to false when popup is closed in ways other than clicking the close button. (#6900)
2c07d581de TreeNode: Added ImGuiTreeNodeFlags_SpanAllColumns for use in tables. (#3151, #3565, #2451, #2438)
085ed7bfbe Drag and Drop: Rework drop target highlight. (#4281, #3272)
0dd756bceb Moved GetCursorScreenPos/SetCursorScreenPos on top of its section.
a63e2f0a33 Drag and Drop: Fixed submitting a tooltip from drop target location. Added demo.
64b1aeebf5 Backends: OpenGL3: rename gl3w's loader symbols to allow LTO compilation with another copy of gl3w. (#6875, #6668, #4445)
28b237f94d Separator(): Altered end-points to use more standard boundaries. (#205, #4787, #1643, #759)
330d763477 Separator: clarified setting the ImGuiSeparatorFlags_SpanAllColumns flag. (#759)
a61438740d Debug Tools: Metrics: Added "Show groups rectangles" in tools.
701a047ac0 Fonts: Fix clang compiling warning & error with freetype + lunasvg (#6873, #6842, #6591)
03e2a7f584 Debug Tools: Rename ShowIdStackToolWindow() -> ShowIDStackToolWindow(). (#4631)
c21278eeae Debug Tools: Rename ShowIdStackToolWindow() -> ShowIDStackToolWindow(). (#4631)
2f431a948c IO: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics.
f1519efb16 BeginGroup(): fix/amend 9ece0bd.
456aa3bc0a Menus: Fixed a bug where activating an item in a child-menu and dragging mouse over the parent-menu would erroneously close the child-menu. (#6869)
9ece0bdc02 BeginGroup(): Fixed a bug pushing line lower extent too far down when called after a call to SameLine() followed by manual cursor manipulation.
8175a47881 Debug Tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIdStackToolWindow() ("ID Stack Tool"). (#4631)
204ae8a407 Internals: added ImRect::ContainsWithPad()
94da5842ef Renamed ImFloor() to ImTrunc(). Renamed ImFloorSigned() to ImFloor(). (#6861)
e5ca5351d5 TabBar: Fixed position of unsaved document marker (ImGuiTabItemFlags_UnsavedDocument) which was accidentally offset in 1.89.9. (#6862)
72ae6f5200 Fixed MousePosPrev with has never been valid outside of NewFrame().
12ee2dd789 Backends: Win32: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it. (#6859)
d4869207e3 Misc: Most text functions also treat "%.*s" (along with "%s") specially to avoid formatting. (#3466, #6846)
f4790f6f66 BeginItemTooltip: Rename flag in comment (#6853)
daf49e9d82 Made ImFileOpen reuse a memory buffer so .ini saving doesn't allocate once every time. Added commented out MemAlloc/MemFree debug log.
d6360c1ba9 Fonts, imgui_freetype: Fixed a warning and leak in IMGUI_ENABLE_FREETYPE_LUNASVG support. (#6842, #6591)
6c022f9bf1 IO, Inputs: rename SetMousePos() to TeleportMousePos(). (#6837, #228)
ff36fe365e IO, Inputs: setting io.WantSetMousePos ignores incoming MousePos events. (#6837, #228)
ef8ff1b5d8 TabBar, Style: added style.TabBarBorderSize and associated ImGuiStyleVar_TabBarBorderSize. (#6820, #4859, #5022, #5239)
6addf28c4b Fonts: Ensure calling AddFontXXX function doesn't invalidates ImFont's ConfigData pointers prior to building again. (#6825)
b101cf46b6 ListBox, Combo: Changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis.
8a2cd81091 TypingSelect: always enable nav highlight.
223b19f116 Fixed warning when builidng with IMGUI_DISABLE_DEBUG_TOOLS.
779568bb38 TypingSelect: tidy up some more + split ino functions to make reuse simpler.
661a70fc79 TypingSelect: fast switch between characters in + debug, internal renames.
32171a8b0c Fonts: Better assert during load when passing truncated font data or wrong data size. (#6822)
c32db3c72b Tables: Fixed an edge-case when no columns are visible + table scrollbar is visible + user code is always testing return value of TableSetColumnIndex() to coarse clip.
c86ce70968 Internal: Nav,MultiSelect: import ImGuiSelectionUserData, SetNextItemSelectionUserData() from MultiSelect. Track NavLastValidSelectionUserData as a convenience.
f336e639e9 TypingSelect: rework GetTypingSelectRequest(), provide TypingSelectFindResult().
9714594c35 Tooltips: made using SetItemTooltip()/IsItemHovered(ImGuiHoveredFlags_ForTooltip) defaults to activate tooltips on disabled items.. (#1485)
6eb2681c09 Internals: InitOrLoadWindowSettings() clear Size again for better data nuking in tests. Debug Log: added ImGuiDebugLogFlags_OutputToTestEngine flag.
bed492da70 Tables: amend support for auto-resize. (#6807)
556a1397a9 Tables: Remove comment referencing removed field SortSign (#6807)
3aceb61059 Tables: Request user to submit contents when outer host-window is requesting auto-resize. (#6510)
da21b74313 Tables: Fixed subtle drawing overlap between borders in some situations. (#2957, #6765)
5a483c2ffb Tables: Fixed top-most outer border being drawn with both TableBorderLight and TableBorderStrong in some situations, causing the earlier to be visible underneath when alpha is not 1.0f.
a34071876f Tables: Fixed bottom-most and right-most outer border offset by one. (#6765, #3752)
357f752bed Docs: add more links to the top of every examples and backends files.
b9ab6e2019 Nav: Tabbing always enable nav highlight when ImGuiConfigFlags_NavEnableKeyboard is set. (#6802, #3092, #5759, #787)
0e1ce76ea8 InputTextMultiline: Fixed Tabbing cycle leading to a situation where Enter key wouldn't be accepted by the widget when navigation highlight is visible. (#6802, #3092, #5759, #787)
bd63a9f056 Fonts: 'float size_pixels' passed to AddFontXXX() functions is now rounded to lowest integer. (#3164, #3309, #6800)
0962c9fb72 TypingSelect: Added first version of GetTypingSelectRequest() API.
7812039402 ImVector: Added find_index() helper.
44a6b493ee Commented out obsolete ImDrawCornerFlags_XXX. Commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded()
becd75676f Commented out obsolete redirecting function: GetWindowContentRegionWidth().
727c462069 Internals: Added ImTextFindPreviousUtf8Codepoint() helper + comments.
c9d3c29aa3 Backend: Win32: support keyboard codepage conversion for when compiling in MBCS mode and creating a non-Unicode window. (#6785, #6782, #5725)
e3d9b875c9 ImDrawList: added PathEllipticalArcTo(), AddEllipse(), AddEllipseFilled(). (#2743)
fa2e5710ac MenuBar: Fixed an issue where layouting an item in the menu-bar would erroneously egister contents size. (#6789)
56a7b8b724 Backends: GLFW: Clear emscripten's MouseWheel callback before shutdown. (#6790, #6096, #4019)
d8ef864b02 InputTextMultiline: Fixed a crash pressing Down on last empty line of a multiline buffer. (#6783, #6000)
cf1c4a0cb1 BeginListBox(): fixed not consuming SetNextWindowXXX data when returning false.
fb9b006865 Version 1.90 WIP
f24387fa2b Version 1.89.9 (fixed changelog header)
c4dc8fd101 Docs: Update FONTS.md (#6781, #6632, #6339, #5763, #5330, #2234, #2042, #1259, #951, #220)
c6e0284ac5 Fixed minor warning.
fef3389157 Version 1.89.9
7b5fb33296 Tables: Internals: renamed CellPaddingY to RowCellPaddingY.
bdc4dfebf5 Tables: Amend support for cross-cell SameLine() for first column. Amend 9a93fb5 + 8f5ce73.
9a93fb5716 Tables: Fixed support for cross-cell SameLine() by preserving Line Y1 position. Amend 8f5ce73.
e8a5c9e1b8 Tables: Made it possible to change style.CellPadding.y between rows. Added demo.
3816d478df ImDrawList: small debug-mode optimization when calling AddRect() without rounding + Selectable: small debug-mode optimization.
8c497793f9 Demo: Tweak table sorting demo code.
303dc091b4 Revert "IO: ImGuiMod_Shortcut (Ctrl/Cmd depending on platform) is reflected in io.KeyMods. (#5923, #456)"
b8f93a8fe0 IO: ImGuiMod_Shortcut (Ctrl/Cmd depending on platform) is reflected in io.KeyMods. (#5923, #456)
a066074054 Clipper: Fixed a bug if attempt to force-include a range which matches an already included range. (#3841)
bdd9b96fa3 Demo: Reorganized "Examples" menu. Tweak Property Editor.
08b3a1a34a ImDrawList: Automatically calling ChannelsMerge() if not done after a split.
f93d0befaf Slider: fixed support for ImGuiItemFlags_ReadOnly/ImGuiSliderFlags_ReadOnly although it is technically unused/undocumented. (#6758)
d6e9fad60e Tables: Fix typo in TableGetSortSpecs comment + amend comment. (#6755)
82d177ccbd Using range-based for where it makes sense. (#4537)
33ea1e8b78 ColorEdit, ColorPicker: Manipulating options popup don't mark item as edited. (#6722)
f617fe7890 Clipper: Renamed IncludeRangeByIndices()/ForceDisplayRangeByIndices() to IncludeItemsByIndex(). (#6424, #3841)
200053771a Clipper: Added IncludeIndex() helper to include a single item. (#6424, #3841)
4a7810e992 Update README.md
981abb4612 Examples: Emscripten+webgpu: Fixed WGPUInstance creation process + use preferred framebuffer format. (#6640, #6748)
4a81424492 CloseButton, CollapseButton: don't include FramePadding into size. Use ItemInnerSpacing.x between title bar buttons. (#6749)
b41811a68c CollapseButton: handle clipping better + align circle like in docking branch.
040e818d72 Fix typo in SameLine comment (#6745)
162f8e01aa Backends: SDL3: fixed typo in 1e17d59 (#6735)
ba1fa904a9 IO: Exposed io.PlatformLocaleDecimalPoint to configure decimal point ('.' or ','). (#6719, #2278)
a1a7a1bc03 InputFloat, SliderFloat, DragFloat: always turn both '.' and ',' into the current decimal point character. (#6719, #2278)
a6857ede03 IO: fix writing to incorrect union section for MouseSource in AddMousePosEvent and AddMouseButtonEvent. (#6727, #2702)
c06c796242 TreeNode: added note about ImGuiTreeNodeFlags_Bullet.
1e17d59965 Backends: SDL2,SDL3: added ImGui_ImplSDL2_InitForOther() / ImGui_ImplSDL3_InitForOther().
983b95bc87 Demo: tweak explanation about static keyword. (#6718)
d2c7cbcbf9 Misc: Made multiple calls to Render() during the same frame early out faster.
ac64b65634 Render: draw dimmed background earlier to match docking code. (#6716)
8f5ce73140 Tables: Made it possible to use SameLine(0,0) after TableNextColumn() or TableSetColumnIndex() in order to reuse line height from previous cell.
1362fc0c56 Debug, Internals: Added DebugDrawCursorPos(), DebugDrawLineExtents() helpers.
bc3c0ce772 Nav, TreeNode: Pressing Left with ImGuiTreeNodeFlags_NavLeftJumpsBackHere now goes through proper navigation logic: honor scrolling and selection. (#1079, #1131)
edebb90a9a Demo: amend/fix for MinGW
4d6fbaff11 Demo: define standard PRI names we use (if missing) instead of defininig IM_PRId64, IM_PRIu64.
226923fa7e Metrics: Fixed "Drawlists" section and per-viewport equivalent appearing empty (regression from c649aca).
2b1fc6f765 Demo: Demonstrate out-of-order rendering using ImDrawListSplitter.
cf3726bcbc Internals: rename bg/fg drawlist holders in structs to reduce confusion.
52587c28d6 ImDrawList: Fixed OOB access in _CalcCircleAutoSegmentCount when passing excessively large radius to AddCircle(). (#6657, #5317)
f8c768760b Typo fix: _NoHostExtenY -> _NoHostExtendY (#6687)
c00e68102c Docs: update CONTRIBUTING.md
b7a7d673b9 Fixed an integer overflow and div-by-zero in SliderInt() when v_max is INT_MAX (#6675, #6679)
d6d94d90bf Version 1.89.9 WIP
f7eea63872 Version v1.89.8
ab490dc7b8 Fonts: Amends for support for OpenType SVG fonts using lunasvg (#6591, #6607)
2ad8c60abc Fonts: Added support for OpenType SVG fonts using lunasvg (#6591, #6607)
19ae142bdd Mark alternative ImColor constructors as constexpr, second attempt (#6656)
dc2b0a2823 Disable -Wreserved-identifier warning on Clang (applying to member fields seems excessively weird).
88a330ebef Revert "Mark alternative ImColor constructors as constexpr (#6656)"
fa2f1bfbb0 Examples: Vulkan: Fixed Vulkan descriptor pools. (#6642)
7c5b0e8292 Mark alternative ImColor constructors as constexpr (#6656)
eefc9035f0 Fonts: ImFontConfig::OversampleH now defaults to 2 instead of 3.
c87b9fdb15 Docs update. Improved Fonts troubleshooting section.
556ce9f543 imgui_stdlib: Fix warning (#6658)
79d6f4e211 Misc: Avoid stb_textedit.h reincluding string.h while in a namespace. (#6653, #4791)
f1781c20a3 Added IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION config macro to disable stb_sprintf implementation (#6626)
1109de3827 Tooltips: fixed ImGuiHoveredFlags_ForTooltip conflicting with ImGuiHoveredFlags_NoNavOverride since 10c7709f. (#6622, #1485)
db66e33e9e Tables: fixed GetContentRegionAvail().y report not taking account of lower cell padding or of using ImGuiTableFlags_NoHostExtendY. (#6619)
2bc5d17ac3 Tables: fixed calculation of multi-instance shared decoration/scrollbar width of scrolling tables. (#5920, #6619)
e5977f05d8 Backends: GLFW: revert support for GLFW_CURSOR_DISABLED, let user use ImGuiConfigFlags_NoMouse. (#5625, #6609)
d342ec10cc Overlap, IsItemHovered: clarification on using IsItemHovered() on a non-reactive item after a reactive overlappable one. (#6610)
52125a54a5 Tables: added TableGetHoveredRow() in imgui_internal.h. (#6250, #6347, #6588, #3740)
77eba4d0d1 CI: resume using latest Emscripten
3dc3aef8a4 Backends: WebGPU: fix webgpu changes for Dawn. (#6602, #6188)
0e8eb8c48e Removed _MSC_VER <= 1500 checks for Visual Studio 2008 or earlier.
863ac31f01 Doc: various tweaks + tweak imconfig comments.
33e13c85e1 Backends: Made all backends sources files support global IMGUI_DISABLE. (#6601)
6888e6cdff ImDrawData: call _PopUnusedDrawCmd() later. as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch). (#6406, #4879, #1878)
dbeeeae593 ImDrawData: Slight refactor so internal logic uses same logic as AddDrawList().  (#6406, #4879, #1878)
1a9ddd2396 ImDrawData: added AddDrawList() helper function. (#6406, #4879, #1878)
c649aca20a ImDrawData: changed CmdLists from raw array to ImVector<> owned by ImDrawData itself. Faclitate user-manipulation of the array (#6406, #4879, #1878) + deep swap. (#6597, #6475, #6167, #5776, #5109, #4763, #3515, #1860)
cc4c37dbac Nav: PageUp/PageDown always set NavJustMovedTo even when landing on same spot (which can trigger a selection).
b7cdb5a31e Scrollbar: layout needs to take account of window border size, so a border size will slightly reduce scrollbar size. (#2522)
5ce636b0ba Tweak to accomodate for build* directories anywhere.
140726d23f Fixed CTRL+Tab dimming background assert when target window has a callback in the last ImDrawCmd. (#4857, #5937)
b32ef809c3 InputText: Fixed a case where deactivation frame would write to underlying buffer or call CallbackResize although unnecessary, in a frame where the return value was false.
3349296370 InputText: Tweak ImGuiInputTextFlags_EscapeClearsAll handling so decision is taken on input buffer + Showcase a few more InputText() flags. (#5688, #2620)
6aa408c6af IO: Added io.ClearEventsQueue(). Obsoleted io.ClearInputCharacters(). (#4921)
9a15730c2a Demo: better showcase use of SetNextItemAllowOverlap(). (#6574, #6512, #3909, #517)
3fe4319314 Version 1.89.8 WIP

git-subtree-dir: external/imgui/imgui
git-subtree-split: d6cb3c923d28dcebb2d8d9605ccc7229ccef19eb
2024-01-17 20:29:18 +01:00
f701b7d2f8
Merge commit '852f2a6343518919e5ca8d3c1bbcab9f493e3cd8' 2024-01-17 17:02:59 +01:00
852f2a6343 Squashed 'external/sdl/SDL/' changes from 399bc709b7..0d7df16812
0d7df16812 Timers are a required platform feature
518b070aa9 Fixed drop event coordinate conversion
3ca8cee874 Sync SDL3 wiki -> header
8bf74280e0 docs: Note SDL_UpdateWindowSurfaceRects can update beyond specified areas.
9408299bad Set the number of audio devices to 0 if audio hasn't been initialized
be0ba78c56 Convert the coordinates in drop events as well (thanks @Dragon-Baroque!)
e6c8872fdc Fixed bug #7614: Segmentation Fault in SDL_BlitSurface
ce0e0675de Fixed bug #8301 - Software renderer draws long lines incorrectly / SDL_RENDERLINEMETHOD_GEOMETRY
6e48d4532c Added raw input device handle for WM_INPUT mouse button handling
cf5e0637b5 Touchpads already have their right/left buttons swapped in raw input
fb2d7ed83e Restore window minimum and maximum size if it is recreated
915afae514 Remove force using one thread
64a3e2d17d Remove ps2_driver from workflow
464a41411e Sync SDL3 wiki -> header
4f3d4bd110 wayland: Add the ability to import and wrap external surfaces
99f6bcf504 Sync SDL3 wiki -> header
3a4ac15a27 Make Xbox GDK code public (and fix some GDK code rot) (#8844)
649556befa win32: Let windows manage the floating state unless explicitly overridden
d4a9748740 win32: Fix test failures
101f903bb1 testgeometry: allow to use arrows to move the triangle
4033a0a83b Prevent ASAN warning: like SDL_triangle.c:305:30: runtime error: left shift of negative value -672 (even if the value was correctly computed)
f0b9c7f0f0 Let Windows track floating window state
98be55894e Moved window state change handling from WM_WINDOWPOSCHANGING to WM_WINDOWPOSCHANGED
7efeb36131 Pass the frame DPI to WIN_AdjustWindowRectForHWND()
e4ee1cade7 Revert "SDL_windowsevents.c: fixed -Werror=unused-variable"
f8cce4ead4 SDL_windowsevents.c: fixed -Werror=unused-variable
277fded7ba Refactor AdjustWindowRectEx() into WIN_AdjustWindowRectForHWND()
312160935d Removed deprecated use of __IPHONEOS__ (thanks @Dragon-Baroque!)
483155bbf9 Fixed borderless window client area calculation
cf0d1d7234 Fixed ASAN warning, runtime error: left shift of 160 by 24 places cannot be represented in type 'int'
0c6b070761 Capture debug macros off by default
b5bc64aa55 Fixed pause key on Windows (thanks Mikhail!)
d766f68cb3 Fix compile error with XInputOnGameInput.h
ec2159d492 tests: Clean up the window creation properties in the Wayland custom surface example
9a77813df0 WinMain is specified by the Win32 API as having extern "C" linkage
6407e0cc37 Added attribution for GIP protocol handling (thanks @medusalix!)
3a219caf3d wayland: Restore accidentally removed line of code
ccae9c1ef6 Only initialize audio drivers that have been requested
590d0bec6f Revert "Make sure new windows have mouse and keyboard focus if there's no windowing system"
5948ea997f Make sure new windows have mouse and keyboard focus if there's no windowing system
05d18aab1c Sync SDL3 wiki -> header
4b6df89238 wayland: Add a property to allow creation of a wl_egl_window object even if OpenGL is not enabled
f7dd0f9491 wayland: Allow the creation of roleless window surfaces for custom application use
4417250d0d wayland: Remove the registry from the window properties
392796e49c wayland: Eliminate redundant protocol checks
82f2c4d581 render: Renamed SDL_GetTextureRenderer to SDL_GetRendererFromTexture.
95066ce2a0 Sync SDL3 wiki -> header
df438a3170 opengl: OpenGL renderers need to support texture target in properties.
8e7c0b34d7 test: If SDL_CreateRenderer() fails, say why
022ff075b9 test: When listing test-cases, say which ones are disabled
44adab7dfd Sync SDL3 wiki -> header
059fb560ba gamepad: Clarify range and direction of axes
4942027117 Sync SDL3 wiki -> header
e056f52f7d include: Remove string literals from properties documentation.
e8c595af5c Sync SDL3 wiki -> header
adef35b9ec include: Attempt to make new properties documentation wiki bridge friendly.
4ffec098b7 Sync SDL3 wiki -> header
9bc7cfc755 render: Added SDL_GetTextureRenderer().
7eae08cfc4 Removed SDL_GL_BindTexture() and SDL_GL_UnbindTexture()
4d5bffc323 Sync SDL3 wiki -> header
1a13dae219 Added constant definitions for SDL properties
3deefa6b43 Updated documentation for SDL_HINT_SHUTDOWN_DBUS_ON_QUIT
2348e8b6a2 Add hint to make SDL handle dbus_shutdown()
d3daba791a Don't try to send the PS third-party feature request to the Logitech G815 keyboard
014a63b4b5 Renamed ShowTextInput/HideTextInput to ShowScreenKeyboard/HideScreenKeyboard on Android
3a9a52fe6c updateKeyboard should use the SDL window's screen instead of the view window's screen, which may be nil.
e100992c17 Added mapping for the RX Gamepad, e.g. Pandora Box 7
139a0931a3 Fix memory barriers on ARMv5
21c80ac843 Added a practical example of confirm/cancel gamepad button handling
787a15f760 Fix Mac child windows that are created hidden showing if their parent window is shown
d6b1fc9576 Add SDL_MAC_REGISTER_ACTIVATION_HANDLERS hint to allow disabling the normal application startup/activation/deactivation handlers
7c5e694022 Ignore a new warning in Visual Studio 2022
73d02184d7 docs: Add Wayland to the SysWM migration example
c03c01e9b2 Make sure we get mouse events as soon as possible
5cbdeab799 Rename SDL_mslibc_x64.asm -> SDL_mslibc_x64.masm
ed62d6e7de cocoa: Set the titled flag on fullscreen space windows
b4b5dbd92f testcontroller.c: fixed warnings.
31851a50d2 Fixed dropping raw input because of mixing GetRawInputBuffer() and WM_INPUT handling
987744aae8 Fix Duplicated includes
2b369a14ab Fixed allocation and alignment of raw input buffers
bec1b8f849 Add basic rumble support to Steam Deck
8fe4a45edf Use GetRawInputBuffer() instead processing raw input one at a time
87b8f09657 Fixed warning: no previous prototype for function 'SDL_PrivateGetGamepadButtonFromString' [-Wmissing-prototypes]
c2951655ff Fixed warning: missing field 'window' initializer [-Wmissing-field-initializers]
5b3ee51c6c Updated copyright for 2024
a7b79c483c Remove unused 'window' variable from -[Cocoa_WindowListener windowWillExitFullScreen]
dd2d809407 AndroidShowToast: make OneShotTask members private final
44c2f344d6 Fixed build
2faae8457d The C standard defines a boolean expression as a signed integer value.
e3d50619f8 Fixed fatal error: SDL_pen.h: No such file or directory
dfe1a37bab Fixed error: 'static' is not at beginning of declaration [-Werror=old-style-declaration]
423b1fafcd Fixed warning C4047: 'function': '__x_ABI_CWindows_CGaming_CInput_CIRawGameController **' differs in levels of indirection from '__x_ABI_CWindows_CGaming_CInput_CIRawGameController *'
7681695875 Revert "Fixed signed/unsigned warnings with Visual Studio when comparing SDL_bool with boolean expressions"
8f94102b04 tests: Use unsigned format specifiers for printing flags
5d0c893723 wayland: Remove bitfield specifiers from boolean values
530b41d531 Fixed warnings in SDL_pen.c
9906d6d3bc Fixed warning C4244: '=': conversion from 'SDL_bool' to 'Uint8', possible loss of data
ebd7f9adbd Fixed warning C4245: 'initializing': conversion from 'int' to 'Uint32', signed/unsigned mismatch in SDL_video.c
dc1c27885e Fixed warning C4389: '!=': signed/unsigned mismatch in SDL_blit.c
e813c72b3c Fixed warning C4245: 'return': conversion from 'int' to 'SDL_JoystickID', signed/unsigned mismatch
dce626f469 Fixed warning C4244: 'function': conversion from 'int' to 'Uint16', possible loss of data
7f376277e5 Fixed warning C4244: 'initializing': conversion from 'SDL_bool' to 'Uint8', possible loss of data
61db102da9 Fixed signed/unsigned warnings with Visual Studio when comparing SDL_bool with boolean expressions
d71454da17 Store the surface properties in the reserved pointer of a surface
b6a92c113f wayland: Don't apply old libdecor window dimensions
39e24e52c8 Fixed example of creating a window with properties
dc450ba908 Added an example of creating a window with position
ce4fe32ce3 Added documentation for getting the X11 display from an SDL window
327d31a5d9 Added documentation for getting the NSWindow from an SDL window
3976bbef2a Added documentation for getting the X11 window from an SDL window
ffb8515c21 Use the Valve code name for the Steam Deck controller
43c40d30a2 Added comment for the BDA Pro Ex controller
61704b5862 Removed an assertion it's possible to hit
c24b33d8d9 Fixed building with older Windows SDK
70ba3f2830 Report the D-Pad for HIDAPI gamepads as a hat
ce329d60e4 Added support for alpha blending using palette alpha
9c3e831e33 uikit: Send fullscreen enter/leave events
5df3eac925 Sync SDL3 wiki -> header
0dfdf1f3f2 Fixed crash if joystick functions are passed a NULL joystick
4ce935b910 Fix static build with libdecor 0.2.0
5d6d149862 Allow passing in `extrainfo` value to `GetMouseMessageSource()`
e0df963ef0 Fix wrong bit count in comment
c2a55cd2c5 Add missing `(void)` in functions params
a3c8f2f6cb Consolidate mouse-touch event checking logic
d747daf03d Use correct touch check flag
a961066d0b Add basic touch/finger support to `testpen.c`
a3b5eb07b2 Removed extern "C" linkage from main() declaration
50e309bb17 Include SDL_events.h in SDL_main.h
cae657140c Add Access Controller
74418e1aa8 Made the cursor list check a compile time assert instead of a runtime one
d6fb0d91d8 Added testpen to the Visual Studio solution
bbdd41f287 Fix windows touch using wrong axis for normalisation
a28ac29aa0 Add missing cursor types
6daf2e943f Try SDL_UDEV_deviceclass to detect joysticks even if in a container
1bf78ed544 We get a resize event when the view enters fullscreen mode on iOS
e3b5999bb4 Use the application requested size to determine automatic orientation on iOS
278e3f9184 Whoops, fixed setting fullscreen flag
69e60e0f1b Fixed setting fullscreen mode on iOS
0e5ea3cc4b Fixed infinite recursion when adding an accelerometer as joystick on iOS
c3d84c3342 Record the initial input report mode and only restore simple mode if that's what we started with
10a8b750a0 Use common generic syscond for platforms with no cond implementation
4914e5bb78 PS2 use WaitSemaEx for waiting for semaphore with timeout
bb0e0ae080 Added a runtime check for BLUETOOTH_CONNECT in addition to BLUETOOTH (thanks @perepujal!)
312f98c2a1 Make sure the string is terminated, fixed invalid read in SDL_PrivateParseGamepadConfigString()
199f7cc3b1 x11: Ignore border extents when the border hint is unset
07e9603398 Sync SDL3 wiki -> header
ffd82fb7c4 Add scaleMode to SDL_SoftStretch(), remove SDL_SoftStretchLinear().
5dba04b29b Remove SDL_{Set,Get}SurfaceScale(). Add Scale parameter to SDL_BlitSurfaceScaled() and SDL_BlitSurfaceScaledUnchecked() (see #8732)
e66896406d cocoa: Set appropriate flags on fullscreen spaces windows
57fcb9044c video: Remove more assumptions about window state in the video layer
cb90653695 win32: use USER_DEFAULT_SCREEN_DPI instead of explicit 96 value
a2e05480d6 Use crc16 return value when calculating GUID
2ad50e9675 Make the SDL3 surface ABI compatible with SDL2
f72d6a7fd9 Use more verbose names for properties, to match upcoming public property names
1f1ee6f77c Use the original manufacturer and product strings for the joystick CRC
4bb5e1f0f9 Added migration notes for migrating Steam Input support from SDL2 to SDL3
56f111dffc Fix compilation / same as sdl2-compat
72c366bf3d Fixed whitespace
3152b98e87 win32: minor fixup in WIN_UpdateKeymap()
2c4360ce8f Sync SDL3 wiki -> header
c981a597dc Added Steam Input API support for game controllers
a8f4f40d08 Sync more Steam Controller header definitions for the Steam Deck
e6e54b22c8 Ignore all surface comparison output files in the testautomation directory
9d13be743b Make sure we're rendering whenever the activity might be visible, even if we don't have focus.
69ec0322d3 win32: Make leaving fullscreen when the window already isn't fullscreen a no-op
8f79e0b7f8 win32: Fix high-DPI debug logging
a4496f7dcf Update doc: SDL_SoftStretch() and SDL_SoftStretchLinear() #8667
43309d38ed joystick: Extract 0x02a9 and 0x0291 PIDs into separate defines.
84a0d5f623 Added SDL_SetSurfaceScaleMode() and SDL_GetSurfaceScaleMode() to control scale mode using SDL_BlitSurfaceScaled()
4d5949dcf6 Added a controller name for the Steam virtual gamepad
695846f2ed Pass through the name of the controller for the XInput mapping
1745289b1b x11: Don't move the window when restoring and ensure that resize and position events are sent when entering or leaving fullscreen
08a7ca4d53 XInput: Use XInputGetCapabilitiesEx instead of fragile GuessXInputDevice
7f75178908 Verify that the %p format specifier works for 64-bit pointers
72b7acfe8a Don't create a TLS error buffer if we're just clearing the error
240e7747c8 Fix #8702: Add SDL_hidapi_steamdeck.c to Xcode target
b937c54b66 win32: Set all size and position variables for external windows
8c285828e5 Fixed return value for SDL_UDEV_AddCallback()
cbf9012c74 Fixed build
5547007915 Added test for inverted cursor
0ab13f2498 joystick: fixup for Wireless Xbox 360 Controller VID/PID detection in WGI backend.
627d134b9e Add support for monochrome cursors with inverted pixels under Windows.
21879faf48 wayland: Handle mouse focus when receiving touch events
58a5f5cbe8 Allow sendCommand() to be overridden by derived classes
e6d8ef1a5b Revert "Back out Steam virtual gamepad changes"
b0e7b7db6f Don't unload graphics libraries until after the window has been destroyed.
69288038ed Refactor away some additional integer types.
f3048e3cd2 Add new file to vcxproj files.
5a21febecb Add new steam deck HIDAPI controller to controller database.
67d44c1017 Disable lizard mode while steam deck HID device is opened.
6dd6827343 Translate steam deck HID reports to SDL events.
94f621e030 Implement steam deck HIDAPI initialization.
c1a7d0f96e Add steam deck detection and HIDAPI driver scaffold.
0baee3e676 Reversed test to be easier to read, more efficient, and match other code
bddbd1e317 cocoa: Check the resizable flag along with zoomed status when resizing
835c733f4d video: Only sync when programmatically entering/exiting fullscreen
c790572674 Use existing XUSB driver software PID 0x02a1 instead of PID 0x02fe
581d1cab25 You should call present when using a software renderer as well.
5173b0c2cc Make built-in joystick device lists extendable by using hints
34eb24ebc4 Back out Steam virtual gamepad changes
7529d25b2b Use the Steam virtual gamepad slot as the gamepad player index
445f08a0fb Print the gamepad player index when opening a gamepad
17723381da Sort Steam virtual gamepads by Steam controller slot
f3d8a2def5 audio: Fixed resource leak in unlikely failure case during device add.
63ae84e140 x11: Improve sync algorithm
7e5511d3cd x11: Move unrelated variables out of XFixes #ifdef
3c5e9e6112 We can wait up to 500ms in onNativeSurfaceDestroyed(), so wait at least that long in onDestroy()
53cda988f4 Clear any errors from a previous run
a197efe3a7 pen: fix leak caused by pen subsystem
fbb0914b78 wayland+x11: free system cursors when quiting video
7484d02a2e testshape: use SDL_test to create multiple windows
20250aecc5 Sync SDL3 wiki -> header
4fd778119b video: Implement asynchronous windowing
ace385a134 Revert "Fixed warning C33010: Unchecked lower bound for enum scancode used as index."
e482f00a17 SDL_string.c (SDL_vsscanf): fix gcc build
f00ecf5f19 Fixed building with older Windows SDK
7ca43995a1 Fixed warning C4028: formal parameter 1 different from declaration
aab7432f5f Fixed analyze warnings for SDL_dynapi_procs.h
c484140f56 Fixed warning C33010: Unchecked lower bound for enum scancode used as index.
02a116217d Fixed Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '-' to avoid overflow (io.2).
91da942b33 Fixed warning C28251: Inconsistent annotation for 'SDL_RWvprintf_REAL': this instance has no annotations.
b8840801cc Fixed analyze warnings in SDL_xinputhaptic.c
8e0d728c67 Fixed warning C26451: Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '-' to avoid overflow (io.2).
6a736d7766 Fixed warning C6340: Mismatch on sign: 'unsigned char' passed as _Param_(2) when some signed type is required in call to 'SDL_SetError_REAL'.
1fcc75ba81 Fixed warning C6340: Mismatch on sign: 'unsigned char' passed as _Param_(4) when some signed type is required in call to 'SDL_snprintf_REAL'.
7f2e16db8b Fixed warning C6340: Mismatch on sign: 'const unsigned short' passed as _Param_(2) when some signed type is required in call to 'SDL_SetError_REAL'.
163de8e697 Fixed warning C6001: Using uninitialized memory 'rdi'.
e29393e407 Fixed warning C6001: Using uninitialized memory 'devName'.
0f34ca2e71 Fixed analyze warnings in SDL_xinputjoystick.c
2b5c7db645 Fixed analyze warnings in SDL_render_d3d12.c
a28769759b Fixed warning C26052: Potentially unconstrained access using expression '(signed char *)info'
6ee34380f4 Fixed warning C6011: Dereferencing NULL pointer 'viewport'.
230581f4a8 Fixed warning C26451: Arithmetic overflow: Using operator '+' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '+' to avoid overflow (io.2).
3775d9be4b Fixed warning C28251: Inconsistent annotation for 'SDL_LogMessageV_REAL': this instance has no annotations.
b512182222 Fixed warning C6340: Mismatch on sign: 'unsigned int' passed as _Param_(2) when some signed type is required in call to 'SDL_SetError_REAL'.
8a82f7e837 Fixed warning C33005: VARIANT '&valueX' was provided as an _In_ or _InOut_ parameter but was not initialized
fda039e6f8 Fixed analyzer warnings for SDL_string.c
22f44aefe7 Fixed warning C6340: Mismatch on sign: 'int' passed as _Param_(3) when some unsigned type is required in call to 'SDL_sscanf_REAL'.
eab2d97d07 Fixed warning C26451: Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '*' to avoid overflow (io.2).
41bfcad5d7 Fixed warning C6340: Mismatch on sign: 'unsigned short' passed as _Param_(2) when some signed type is required in call to 'SDL_SetError_REAL'.
54dc73aa88 Fixed warning C6386: Buffer overrun while writing to 'palette_saved_alpha':  the writable size is 'sizeof(Uint8)*((palette_saved_alpha_ncolors))' bytes, but '2' bytes might be written.
0dad56354c Fixed warning C6326: Potential comparison of a constant with another constant.
c9b243fb56 Fixed warning C6263: Using _alloca in a loop: this can quickly overflow stack.
4ccc53edfe Fixed warning C6011: Dereferencing NULL pointer 'display'.
3db4695ac7 warning C6340: Mismatch on sign: 'unsigned int' passed as _Param_(3) when some signed type is required in call to 'SDL_LogDebug_REAL'.
c7d81d936a Fixed warning C6031: Return value ignored: 'GetKeyboardState'.
69b9d44bdc Fixed warning C26451: Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '-' to avoid overflow (io.2).
a9b87ee201 Fixed warning C28159: Consider using 'GetTickCount64' instead of 'GetTickCount'. Reason: GetTickCount overflows roughly every 49 days.  Code that does not take that into account can loop indefinitely.  GetTickCount64 operates on 64 bit values and does not have that problem
21f273ecc7 Fixed warning C6255: _alloca indicates failure by raising a stack overflow exception. Consider using _malloca instead.
0c4cb3d153 Fixed warning C26451: Arithmetic overflow: Using operator '<<' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '<<' to avoid overflow (io.2).
06f8f9a891 Fixed warning C6326: Potential comparison of a constant with another constant.
3e54061fa8 Fixed warning C6011: Dereferencing NULL pointer 'SDL_disabled_events[hi]'.
226f8fde09 Fixed warning C28182: Dereferencing NULL pointer. 'streams[j]' contains the same NULL value as 'stream' did.
fe6b3ab0b0 Fixed warning C6031: Return value ignored: 'CLSIDFromString'.
f3b0149756 Fixed warning C26451: Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '*' to avoid overflow (io.2).
6cfce101fb Don't call the property cleanup function if setting the property fails
14380ec48a Fixed signed/unsigned comparison warning
ac0751a652 Added SDL_strnstr()
7c71e72193 SDL_render: Call InvalidateCachedState to initialise some of driverdata values (eg '*_dirty' to 1). At the earliest place, immediatly after driverdata is set. (Doing it in SDL_render.c, after creation, would be too late, because there're renderers that already use/change those values in the CreateRender() function).
058213366b Make sure we use alpha of 0 when clearing a transparent window with no content
ecd56bb8f0 Removed SDL_GetErrorMsg(), trivially implemented in application code
66e532fa61 Handle out of memory errors without any allocation
579681a372 fixed SDL_SCANCODE_LEFT array position in scancodes_windows.h
675423f096 Sync SDL3 wiki -> header
744a29b88f WGI: Cleanup code a bit (#8647)
e4582e6edc Sync SDL3 wiki -> header
df0fd55891 wikiheaders.pl: README files are no longer in Windows endline format.
1072b6e86e docs: fixed typo
f184dea16c uikit: Patched to compile.
447b508a77 error: SDL's allocators now call SDL_OutOfMemory on error.
70b65d4170 cocoa: Resync modifier keypressed on NSEventTypeFlagsChanged event.
d1b831e232 include: Clarified documentation for two functions.
daa38dc793 touch: Replace GetNumTouchDevices/GetTouchDevice with a single function.
dd47da8a5c gamepad: Replace GetNumMappings/GetMappingByIndex with a single function.
dfee3f9e92 render: Replaced SDL_RenderFlush with SDL_FlushRenderer.
eef5c53668 docs: Moved CREDITS and INSTALL to markdown format.
f32575dfab docs: Convert everything to Unix-style endlines.
c5daf8adb1 testcontroller: Don't query the mapping list until after they are available.
df05d5eff4 Fix scroll wheel handling in testmouse
63d4bd4e57 SDL_SendKeyboardText: remove workaround from 1e12d7c, fix use of iscntrl
fea6e7afb1 cmake: copy sources to binary directory in separate target
9faa7977bd UWP: Add support for supplementary Unicode characters input
7b628ea4d5 Win32: Simplify Unicode text input code
411c70abb1 Fix the target membership of SDL_pen.h (thanks kanjitalk755!)
3e6513c773 document the purpose of SDL_SetTextInputRect
1e12d7cfb6 Make sure we don't pass UTF-8 to SDL_iscntrl()
9a206adbee UWP: Use Windows.UI.Core.CoreDispatcher.AcceleratorKeyActivated event for keyboard
309ea2d5f9 UWP: Simplify Win32 scan code to SDL scan code mapping
acc5bb89f8 [Win32] Better keyboard button mapping to SDL scan codes
6b28065e9e Reformat Win32 scan code table
7e86b6aef2 Win32: Fix keymap for keyboard layouts that can print UTF-16 surrogates and ligatures
08c6ac1b16 test: SDLTest_PrintEvent now reports key event mod state.
571e9796b9 Fixed the GameCube HIDAPI controller mapping
dd984dcd9f Removed HIDAPI controller mappings
3817f5126e cocoa: Use `-[NSApplicationDelegate applicationSupportsSecureRestorableState]`.
c5b0ff77d7 test: testwm2 now displays keyboard mod state.
5772e00c3f cmake: disable oss by default on OpenBSD, not FreeBSD
ceac93ade2 Set framebuffer_srgb_capable to the actual value obtained (#8634)
ed3fad1880 cmake: disable oss by default on Linux, NetBSD and FreeBSD
6bb40f1d8d SDL_VideoCapture: allow add/remove device at runtime on linux
f0e47f8ee0 Added support for the NACON Revolution 5 Pro controller
2f806c89b5 initial import of hidapi netbsd uhid native backend from mainstream
1b284cd415 X11 pen detection: fix misclassification due to improper init
c4ca64deaf ci: do 'brew update' & don't run dependent checks on installed things
d486de6349 cmake: fixed iconv detection test program
42a8139fd6 render: Clip bresenham lines against a real viewport thing.
4a40a272bd render: Patched to compile.
983f178b7d render: Clip lines before Bresenham algorithm generates points.
db7f6425d0 rect: Avoid numeric overflow on massive lines in SDL_IntersectRectAndLine.
e548044a82 ci: add NetBSD to test matrix
dd5b8db3a6 SDL_hidapi requires libusb >= 1.0.16
6ba90f7775 render: Batching is always enabled now!
b24d6bd59a opengl: Creating a texture trashes the cached `texturing` state, fix it.
dcf04559db render: GL-based renderers should treat adaptive vsync as vsync being enabled.
74a2542564 x11: Deal with difference in GLX_EXT_swap_control_tear behavior.
08fac5b1b2 SDL_PenModifyForWacomID: return zero as axis_flags upon failure.
aaba01aee4 hidapi: syncing with mainstream:
5730eb67f0 add HAVE_GCC_DIAGNOSTIC_PRAGMA to SDL_internal.h, use it
42c8366fdc revise iconv detection:
a45b371de0 cmake: create and install SDL3::Jar target for Android
53544cabaa psp: fix copy/paste error from SDL2 in PSP_VideoQuit().
6cde96f9a0 psp: Hook up event subsystem init/quit.
e9659f5738 Removed some function declarations that don't actually exist.
3264e64738 SDL_RunApp: Make sure argc/argv are stable if the caller didn't define them.
eca79e38db Removed test shape images
81fc7ded78 Removed the window shape API for SDL 3.0
45938bbfa5 Corrected comment
059e550e98 Fix 3DS Analog Values (#8581)
dbf14df80f Fix joysticks returning invalid device IDs
d2db3f3993 ci: cache android ndk archive
d6291d4d42 alloca: use alloca from <stdlib.h> on NetBSD
f26a93211f SDL_bsdjoystick: fix -Wundef warning on FreeBSD
d1def7f033 cmake: add openbsd wscons sources to build, if supported
86d77bbcc5 kmsdrm: restrict KMSDRM_ReleaseVT/KMSDRM_AcquireVT to SDL_INPUT_LINUXEV
94ad1a4ae4 SDL_bsdjoystick.c: fix -Wundef warning.
e761770c24 No, this wasn't right
b7d7e54895 Fixed uninitialized variable
119e02f314 Always use 'm' for controllers provided by the MFI joystick driver
75df4cc5c2 Don't tickle PS4 Bluetooth controllers in simple mode
0d431015bf Extract BMP magic into separate define
0413f6fc49 Use SDL_iscntrl() call instead of manual code that is doing the same (#8593)
fd91178d7f Make size cursors be double arrows on Wayland
5e9b0820f3 Add cursors for X11/Wayland window resizing
91e122316c Use SDL_small_alloc() instead of SDL_stack_alloc() in CreateMaskBitmap()
b76f8de298 Hit testing tweaks for X11 and Wayland (#8582)
5b1c68c2f3 testshader: Don't make local variables with the same name as GL entry points.
30a2291d59 Fixed compatibility with sdl2-compat (thanks @sezero!)
49d58bc73a Cleanup WIN_CreateCursor() code a bit
4722269fb6 tests: Print window occluded log events
5db781cc3d Use the correct pixel formats for OpenGL ES on big endian
05e7dcf8f8 Support returning <8bpp surfaces in SDL_LoadBMP_RW
773ec1cfcb Extend blitting support for all <8bpp formats
753bbd199e Add SDL_PIXELFORMAT_INDEX2LSB and SDL_PIXELFORMAT_INDEX2MSB
fda69e5e79 Test both MSB and LSB indexed surfaces in testautomation
39870031d1 use format string attributes for functions accepting va_list params, too
666301f9f9 Fixed build with older macOS SDK
238987df3b Always use physicalInputProfile on OS versions that support it
e424dcca4b More fixing the build with older macOS SDKs
4ebb0c6dac Revert "Fixed build"
7abacc9f9f Fixed build
ac1f896f89 Fixed building with older macOS SDK
8043dad369 Fixed build warning
5c8c3931f2 Removed outdated information about SDL_GetWindowWMInfo()
e0d0d140b2 Fixed SDL_GetWindowWMInfo() code example
f61c0f3dc1 SDL_HINT_TV_REMOTE_AS_JOYSTICK should only affect Siri Remotes on Apple TV
51fc134cad Added support for the second generation Siri Remote on Apple TV
bfba9de43a Revert "Map Siri Remote touchpad to D-Pad for consistency with physicalInputProfile mapping"
f2c12fe5f3 Removed TODO.txt
d4448fe3d2 Update virtual joystick test now that we're just using abxy for mappings, for compatibility
f40f272107 Fixed build
34bdd321bf Improved navigation while setting up controller mapping
57e5c7f6ee We'll just use the legacy names for face buttons in the mappings
051ed397d1 Removed testautomation_syswm.c from the Xcode project
fb08c22abf Disable controller state debug messages
2999634f29 Map Siri Remote touchpad to D-Pad for consistency with physicalInputProfile mapping
2ff9255f29 Print the GUID for controllers that don't have a mapping
64939d3586 Switch the menu button on the Apple TV remote to the B button to match UI guidelines
0fe5713964 Improved GCController handling on Apple platforms
aaf54b09a1 Revert "Cleanup WIN_CreateCursor() code a bit"
e923a458ea audio: Protect against race conditions when closing a physical device.
8fa0746d4a audio: Fix postmix state when migrating to new default devices.
078995bbe0 x11: Set the skip taskbar and skip pager atoms on utility windows
a58af6d0d1 wasapi: Reference devices when proxying to management thread.
34392db9c3 Fixed IOS_SupportedHIDDevice() returning SDL_FALSE before initialization
708f18d49e Added SDL_HINT_JOYSTICK_IOKIT and SDL_HINT_JOYSTICK_MFI to control whether the IOKit and GCController drivers should be used for joystick support.
bd4966999b Replacing SDL_SCANCODE_AUDIOMUTE by SDL_SCANCODE_MUTE on Windows
15504da0b8 Fixed mouse wheel scrolling direction on iOS
f5600fd9f4 Fall back to using the physical profile for Apple controllers if they don't match a standard profile
924de4df48 Enable transparent windows when using the D3D11 renderer
1c64366b80 Added SDL_CreateRendererWithProperties() and SDL_CreateTextureWithProperties()
7203641597 Note that the SDL window properties are read-only
e0c45c6c98 Renamed SDL_WINDOW_FOREIGN to SDL_WINDOW_EXTERNAL
229b7b9d50 SDL_CreateWindowWithPosition() and SDL_CreateWindowFrom() have been replaced with SDL_CreateWindowWithProperties()
2c1fbe1967 Revert "Check to make sure the Windows joystick device has buttons and axes"
edd044e901 Fixed the ROG PUGIO II showing up as a game controller
861b1ebd12 properties: Use a mutex instead of an RWLock to guard the hash table
dd8ab67bd9 Sync wiki -> headers.
91460fc13d include: Fixed up documentation in SDL_pen.h
876c97454a Cleanup WIN_CreateCursor() code a bit
8766aa39d6 Sync wiki -> headers.
e5ffd6d8eb include: Removed `\link` and `\endlink` Doxygen tags.
1c4723ac66 SDL_CreateWindowFrom() now takes a set of properties that describe the native window and options.
6afae6681b Allow casting properties of different types
bd269b0f41 Added SDL_SetBooleanProperty() and SDL_GetBooleanProperty()
c47ac5b2df include: Fixed copy/paste error
0efb3d90e0 audio: removed a fixed FIXME comment.
69cae07cc1 cpuinfo: Fix detection of physical memory above 2GB on NetBSD
45fc828c95 move SDL_EVENT_WINDOW_PEN_ENTER and SDL_EVENT_WINDOW_PEN_LEAVE down
0907f345cb Added property types: pointer, string, number, float
7c80ac6df7 API for pressure-sensitive pens + XInput2/Wayland
d3e43668d0 Revert "Sync SDL3 wiki -> header"
43571769f1 Sync SDL3 wiki -> header
843873626c Handle window resizing on the render thread in D3D11 and D3D12
f66f61de01 Fixed missing "0" in the button list
04b6b2979f Re-add SDL_assert() with non boolean ptr syntax (#8530)
b374105975 Replaced SDL_GetTextureDXGIResource() with texture properties
09d1e9defb Only update the battery status for Bluetooth Switch Pro controllers
87794d03ad Added shortened name for "Nintendo Co., Ltd."
fbb6934905 Added support for the Dragonrise GameCube adapter with VID 0x1843
d98e1bdfe1 Use the standard gamepad type for Switch Pro controllers using the GameCube form factor
a5a47d3bee Fixed crash if there is no controller mapping
312faf9305 Updated documentation for the controller face buttons
2991b9f6ac SDL now represents gamepad buttons as positional elements with a separate label
8708ba7393 Don't leak if realloc fails
36b2d2e463 Fix memory leak in SDL_SendDrop()
dfb87e1099 Fix uninitialised variable 'properties'
e54c5e0204 Fix condition in SDLTest_TrackAllocations()
89408a9705 wasapi: ResetWasapiDevice no longer blocks on management thread.
aa7baf63aa Sync wiki -> headers.
74f3643bfa wayland: Add missing break to switch statement
2d6bae70b4 Older gcc does not support #pragma GCC diagnostic inside functions
d8600f717e  Pointer as bool (libsdl-org#7214)
23db971681 x11: Ignore deprecated declaration of XKeycodeToKeysym
61c39ce848 ci: re-enable Intel compilers on ci
4ac3f5c07e Updated Xcode project with the video capture API
59f93e20a7 Add SDL Video Capture, with back-end for linux/macos/ios/android
3ab98a3572 Removed debug print statements (thanks @stsp!)
f4b61fff30 Implemented VT switching for KMSDRM on Linux
391a3d23d0 cmake: the compile-time pdb does not have a suffix, if set
a6541166bc cmake: also install pdb files of static libraries
2e3f574f8f cmake: don't add the C runtime library to the .obj file (when using MSVC)
bea34c5380 Fixed a memory leak at window creation.
b5347c3364 Fixed emscripten and iOS builds
02f356439d Allow the application to draw while Windows is in a modal move/resize loop
1934417b4d Show the existing mapping when a controller is connected
407a3cb4e0 Fixed infinite recursion initializing properties
979214363f Added SDL_GetGlobalProperties()
151cdfa99f Added the "SDL.window.wayland.registry" property
6c91b28e71 Added the "SDL.renderer.d3d12.command_queue" property
4e8d1ec983 Fixed crash trying to create a metal view with the dummy driver
fd4a2cce9e SDL_syswm.h has been removed and replaced with window properties
aea6e6de6f Simplified SDL_SetProperty() and added SDL_SetPropertyWithCleanup()
a1941fad6c Replaced SDL_RenderGetD3D11Device(), SDL_RenderGetD3D12Device(), and SDL_RenderGetD3D9Device() with renderer properties.
0cd4b7d3e3 Added display properties
a02afbaea5 Clean up window properties when the window is destroyed
8668943746 Standardized property names for internal SDL properties
a4c6b38fef Fixed FreeBSD build
d9e6dcc650 Fixed FreeBSD build
7cc3e94eb2 Store the requested muted state
ce9e1bd324 Don't mute the console input if we can't read the keyboard
0a1b6b270f sdlchecks.cmake: Clarified the reason why shared X11 mode doesn't work
80b2bbad21 Removed useless branch test
15bc12165a Actually we need to enumerate the 8BitDo Xbox SKUs
8049af3355 Assume all 8BitDo Xbox controllers have a share button
ed1e0c1530 Make sure joysticks are locked when adding and removing them
415283ef38 Fixed checking for linux/input.h
fea2504a37 Prioritize the pipewire audio driver over ALSA
04e98d2236 Added missing calls to SDL_InvalidParamError("surface")
521bbcc15e Destroy the window surface if we've created it for the software renderer
28e623c504 Added a mapping for the Atari VCS controller connected over Bluetooth (thanks @WizzardSK!)
4106697774 Make sure we include the null terminator in XLookupStringAsUTF8()
b5057edf29 Remove unused SDL_TextureModulate enum
9458cbf75e Removed unused SDL_OSEvent
1a57f6bb29 wayland: Remove QtWayland extensions
5f920d6639 fix emscripten build after commit 07cb7c10
22016b4eae Enable the 5th player LED on the DualSense controller
66cf30c2de Removed misleading comment
dbcd390cdf Log drag and drop position updates in SDL test programs
07cb7c10a1 Fixed connecting and disconnecting real-joysticks closing virtual joysticks in Emscripten (thanks David!)
869257a5c1 SDL_migration.cocci: Added a thing for SDL_Vulkan_CreateSurface.
c6d9fb1ad7 hidapi: Avoid memcpy'ing to NULL.
4d1aecc225 vulkan: Patched to compile on iOS.
fccec65afe Sync SDL3 wiki -> header
2f92807087 vulkan: SDL_Vulkan_CreateSurface now accepts an app-provided allocator.
c53843a961 docs: Remove Doxygen `\brief` tags.
c132295ad7 SDL_FlushEventMemory is not a public procedure.
7ac281f800 Sync wiki -> headers.
f7d40b7594 Added 10-bit pixel formats in addition to SDL_PIXELFORMAT_ARGB2101010
3e4d7e48b0 Fixed memory leak in XInput code
bc3d9e99f3 Only save ibus_addr_file after we've successfully read an address from it.
04dfca958a Added a note to events indicating that memory is owned by SDL
20cd789bab Improved migration documentation for the event memory change.
459f17257c cmake: fix MSVC unrecognized option link warning
761390b62f cmake: detect linker id, and assume MSVC does not support version scripts
d2e005ee13 dynapi: remove duplicated SDL_LoadWAV entries
21ff699251 test: Fix popup test crash on exit
70c149c88f Automatically clean up memory associated with events
1a83bf2399 fix a possible memory leak in SDL_vasprintf()
59b37d0e5b cmake: fix Windows unrecognized option link warning
9302d7732d Fixed touch normalized coordinates
ff3c20a799 Sync SDL3 wiki -> header
17a0fe3a0c Sync SDL3 wiki -> header
14d2471a8f Sync SDL3 wiki -> header
2ad22eeeb5 Sync SDL3 wiki -> header
930438dfb7 Added note that the #ifdef is for !__IOS__
c56583fe45 Fix duplicate symbol on iOS/tvOS
2b62f25a6f Add SDL_sysmain_callbacks.c to the Xcode project
4ab31ca678 Fix dropping file event
5dce4bc716 Makes SDLInputConnection and DummyEdit public classes (thanks Cole!)
d3f2eb2aba Use XINPUT_STATE instead of XINPUT_STATE_EX (thanks Andrew!)
3a482ebae0 Add createSDLMainRunnable() to SDLActivity (thanks Cole!)
b9784feb24 Fixed potential uninitialized memory access (thanks Mathieu!)
75ea3a8d32 Dynamically allocate long text for SDL_EVENT_TEXT_INPUT events
2a1660ab51 Additional cleanup for SDL_RWprintf() (thanks @sezero!)
e5f2cea234 Sync wiki -> headers
ad842dd5ad Fixed a typo in SDL_log.h
f9d11807c0 Added SDL_RWprintf() and SDL_RWvprintf() to do formatted printing to an SDL_rwops stream
52c4e3eab3 events: Update self-referential pointers when copying event objects
91f0456391 Add the source application for drag and drop events (thanks Nathan!)
1a8bf31a69 include: Fixing whitespace on SDL_MixAudioFormat.
d07a264a9b Use the default UCS2/UCS4 conversion rather than non-portable INTERNAL encoding
780b6612a9 wayland: Wayland_Vulkan_GetInstanceExtensions didn't set the count variable.
46b940d571 Updated documentation to note that the event callback is called on the same thread as the main iteration callback
4481754359 Make sure we only dispatch events on the main thread when using application callbacks
274da8561c Updated the migration guide to note that you can check the return value of SDL_AddEventWatch()
ad9dcdbbce Clarify that you should use the other field when reading the event
a19029e3c1 docs: Updated README-main-functions.md based on feedback.
019468dc59 main: Check for SDL_AddEventWatch failure, now that it can report it.
7e445da569 Added SDL_CleanupEvent()
c4bf05fd9d Added subsystem refcount tests to testautomation
7f65ed6461 Handle subsystem dependencies recursively
a6b85c81cc Fixed build
3ab6670cb1 Sync SDL3 wiki -> header
f439ccfc1a Updated return values for SDL event functions
e0379c3b37 Grab events in large chunks in SDL_IterateMainCallbacks()
ad5264e54f Don't run SDL_IterateMainCallbacks() if the init call returns an exit code
dad1a84be4 Fixed building Vivante video driver
fe175d025f Fixed building Vivante video driver
0b460f34ba The HP HyperX controllers have a share button
f3261fedcc Code cleanup now that SDL_bool is equivalent to a C boolean expression
a76d8e39aa Changed SDL_bool from an enum to unsigned int
cf7e5bd0e8 Sync SDL3 wiki -> header
853c28e624 docs: Added first draft of README-main-functions.md
70d75b4a23 Sync wiki -> headers
ea02630143 More audio migration clarification
14980b25a8 Clarify documentation for audio callback migration
6cf84e2c5b cmake: fold HAVE_INPUT_EVENTS into HAVE_LINUX_INPUT_H
5e869d1b35 fix Cocoa_Vulkan_GetInstanceExtensions prototype for Mac
07a776f255 include: Fixed documentation for SDL_Vulkan_GetInstanceExtensions.
5b3a2c6df6 docs: Updated SDL_Vulkan_GetInstanceExtensions info in README-migration.md.
9224a0a2d8 Fix emscripten, android, uikit and windows
d0d8b28df1 Change SDL_Vulkan_GetInstanceExtensions
338974bb29 SDL_test_memory.c: fix build against older windows SDKs.
618d15bce6 Fixed typo
ad0af48883 Check to make sure the Windows joystick device has buttons and axes
ac6b32bb02 gendynapi.py: Discard SDLMAIN_DECLSPEC functions.
9c664b0062 main: Added _optional_ callback entry points.
9323417e9c Fixed gendyapi.py parsing of SDL_RELEASE_GENERIC
759cdf6159 audio: Fixed GetFirstAudioDeviceAdded().
0e614d9179 audio: Massive reworking on thread locking.
40fb76196c audio: Don't let simplified audio streams bind to new devices.
24e3328cca audio: Don't reset device ID counter on subsystem init/quit.
5d95cbde37 cmake: reset check state before testing -fobjc-arc
f18120c83c cmake: check -fobjc-arc compiler flag on Apple platforms
4aacc4b92e cmake: file(RELATIVE_PATH) needs 2 absolute paths
dcc8805c21 testaudio: Fixed compiler warning on Visual Studio.
9cb259e865 audio: Never SDL_PushEvent from anywhere but SDL_UpdateAudio().
875e45e70b wayland: Sanity check pointers and protocols before confining
0e87b71d08 wayland: Check the relative pointer handle before destroying
6127ac0871 Use SDL_DISABLE_ALLOCA instead of HAVE_ALLOCA in SDL_stdinc.h
552bee47cb Clear any previous errors if we successfully show a message box
343da852a6 Don't try to use the Wayland messagebox if we're not in Wayland
f63e9a8a3f wasapi: Handle disconnected devices that get reconnected.
5fa7b291d4 wasapi: Fixed memory leak if new audio devices fail to add.
468c386686 wasapi: Handle disconnect notifications from the management thread, too.
ce3be02b48 wasapi: If device is marked as a zombie, don't try to resuscitate it.
85923049a6 wasapi: Patched to compile.
9bec57309c wasapi: Proxy default device change handling to management thread.
c45b5121ce audio: Fixed potential race condition.
8b6da3c701 Fixed making the EGL context current when resuming on Android
2e9eb1073d Sync SDL3 wiki -> header
e6116d399a mutex: Removed SDL_MUTEX_MAXWAIT.
82f48be3ef Sync SDL3 wiki -> header
899eb0d042 thread: Locking mutexes and rwlocks are now void functions.
082ef41566 alsa: Fix crash from invalid handle pointer
a9aa15c792 CI: change FreeBSD CI runner to cross-platform-actions.
23ceae94c9 Fixed Xbox 360 Controller support using libusb on Linux
ace0c2c297 mutex: Fixed bug where generic SDL_TryLockMutex would incorrectly block.
f52b330ed8 Added support for the HP HyperX Clutch Gladiate controller
b61706373c n3ds: Check that audio thread name starts with "SDLAudioP"
6827b3331d n3ds systhread - use 80kb thread stack size as default, remove hard cap
e4cd1d4059 n3ds systhread - prefer to put audio thread on system core
1023d8ec84 SDL_n3dsaudio.c - don't risk leaving current_priority uninitialized
07171be596 SDL_n3dsaudio.h: use triple buffering
6efe957159 SDL_n3dsaudio.c: separate mixer locks from audio device locks
39a961ba41 Added support for "%[]" sscanf syntax
124a0050b6 Fixed warning: no previous prototype for function 'SDL_UpdateAudio'
b16165a33f rwlock: SDL_UnlockRWLock was incorrectly tagged with SDL_RELEASE_SHARED.
865dd04068 pulseaudio: Don't use a hash for device change detection.
b8cc51875a Fixed build
0413e21e54 Fixed audio device removed events for ALSA
5ba03d377a Revert "Fixed audio device removed events for ALSA"
a774694be0 pulseaudio: Simplified default device change detection code.
e57fef8f0b Fixed audio device removed events for ALSA
4280d4b359 Fixed warning C4210: nonstandard extension used: function given file scope
182cfc3265 pulseaudio: Rework how we manage default devices and hotplug.
b2ae1e835f pulseaudio: Change debug printf calls to use SDL_Log instead.
38afd48daf Added a single source of SDL object IDs
e07f6c0a17 SDL_IsJoystickProductWheel() returns SDL_TRUE for Asetek wheelbases (thanks @IOBYTE!)
c98a14fdeb Renamed display added/removed events for consistency with the rest of the API
c2a3112b6f Added "--substring" to the help for rename_symbols.py
a844d90942 Add missing error reporting in Android_JNI_FileOpen()
4ac38d13dd alsa: Don't touch free'd memory in hotplug thread.
43d41c9dcb audio: Another attempt to make device add/remove work vs event watchers.
9abc692156 audio: Another attempt to deal with device destruction from device thread.
33c9eeec7c Revert "audio: Device threads don't increment physical device refcounts."
e5a15f94e2 Revert "Check to make sure the Windows joystick device has buttons and axes"
70fd8e2ba2 Lock joysticks when adding gamepad mappings
76f81797b7 audio: Device threads don't increment physical device refcounts.
594fda4120 Sync SDL3 wiki -> header
0d7c5a2c56 Updated Android API documentation
0df888c584 Moved Android low latency audio behind a hint "SDL_ANDROID_LOW_LATENCY_AUDIO"
142366c837 Sync SDL3 wiki -> header
3a4c9d6990 Fixed build error when API logging is enabled
1f8f82b379 Removed redundant thread-safety information
a6edc75fe7 Sync SDL3 wiki -> header
3c8edeb79b Clarified SDL property thread-safety information
4fa821cb3e Sync SDL3 wiki -> header
1c70760c0b Added thread-safety information for the new SDL properties API
15533dce05 Cleaned up warnings from check_stdlib_usage.py
bf269571fc jack: Removed FIXME comment that has since been fixed.
797b70877d audio: Remove stub header SDL_audio_c.h.
9d7c57234a audio: Cleaned out most remaining `/* */` comments for `//` style.
0ff67dc21b video: Fix compiler warning about SDL_ReadSurfacePixel not being declared.
81c77396af opensles: Patched to compile.
442e84916a opensles: Fixed capitalization to match other SDL backends.
34914bfb49 alsa: Clean up device handles, now that hotplug thread cleanup is in place.
48d80efb51 Fixed warning C4701: potentially uninitialized local variable 'props' used
f7dc63bcc3 audio: another windows wasapi build fix.
dd98330076 audio: fix windows wasapi build.
7a52f7b3fd audio: Split Deinitialize into two stages.
e55e556f32 alsa: Fixed minor memory leak.
b45a0d9016 Updated the documentation for SDL_LoadWAV_RW()
435e7ce663 Check for device disconnection in HIDAPI_JoystickOpen()
b733adb503 audio: Fix device refcounting vs ProvidesOwnCallbackThread backends.
c6f08c2553 testaudio: Removed debugging code.
d5dac0ad27 testaudio: Deal with a texture being unexpectedly NULL when scaling.
b19e68c8ec testaudio: Properly display playback progress, regardless of data source.
8c39269279 audio: Fix audio stream format when binding to a capture device.
f26b838a3e jack: Check for sample rate and buffer size changes from the server.
063cb0df6b audio: Fixed comment typo. "deref" should be "unref"
354611a0c6 testaudio: Fixed some bugs Valgrind pointed out.
a17f3ba916 audio: Reworked audio device disconnect management.
6ddd96a4d0 Fix some wrong gamepad/controller event enums
8df68b4120 hashtable: Moved over to single-line comments.
1c6d996108 testaudio: if the SDL_Renderer is already gone, don't destroy SDL_Textures.
b22ffb9797 audio: Fix some logic errors in the new device hashtable code.
e526dc64bd Don't set unused variable
6664437748 hashtable: Don't rearrange bucket elements during SDL_FindInHashTable.
8ac5c84ad1 audio: device thread shouldn't touch `thread_alive` after object is free'd.
b17151eb16 testaudio: Don't crash if renderer is NULL (happens during shutdown).
7f408e57ee audio: Keep all available devices in a hashtable instead of linked lists.
0aba2c97db hashtable: SDL_IterateHashTable might as well provide both key and value.
95a9271dbf audio: Never lock a device while holding the device_list_lock.
9aeabb0b05 Fix macOS build error by #8269
382751c4b5 testffmpeg: print usage of options to change audio/video codec
f91bde64d5 testffmpeg: Only enable blending if we're using a texture format that supports it
516d6f9efc testffmpeg: added support for YUVA formats using swscale
ac71831350 Sync wiki -> headers
d18f910248 testffmpeg: added the ability to specify audio and video codecs
72034b9a07 wayland: Fix primary selection handling when the protocol isn't supported
e152129787 Fixes #8190. From #7249, reverted the hunks other than #7239.
b79db0a6ea Fixed potential wraparound issue with property IDs
c9ccf0670c Add unsupported functions to dynapi
25ce87979d Always provide an implementation for all SDL3 symbols
3a36433a3c cmake: test -Wl,--version-script with minimal version script
0efa196989 dynapi: implement SDL_DYNAPI_entry even when building SDL without dynapi support
bf64fecf19 testffmpeg: allow resizing of the video window
efa9a45048 Clarified that testffmpeg will resize the window to the video size
4368f70ff9 Added properties to various SDL objects
973c8b3273 Added SDL properties API
2bca4671a6 audio: Allow audio streams to be created when the subsystem isn't initialized.
1ae33f6751 cmake: optionally install pdb's
0d5cad91b1 We need audio converters initialized in SDL_InitAudio()
1c3a0ade74 audio: Whoops, this stream format change is only for capture devices.
10fab3a39e pulseaudio: Stop the threaded mainloop before destroying the context.
0b71898cb1 Make it clear that the string comparison isn't a boolean check
6c8ad975c7 Like mutexes, operations on NULL rwlocks are no-ops
c552cc6847 We don't require the audio system to be initialized for audio format conversion
9a5f7b17c6 Use SDL wrapped getenv function
044046bc50 audio: Fixed assertions when capture devices have wrong audio formats.
bb2f767f5d testaudio: Make program usable without a 3-button mouse.
321fc18417 README-migration.md: Added note about SDL_HasRDTSC removal.
82f54af617 x11: Properly check for XInput2 support before using it.
b654427537 Added support for the PowerA Nintendo Switch Nano Wired Controller
dc2a5f6ab2 Fixed error C2054: expected '(' to follow 'inline'
a7ae1de9a6 Fixed warning C4028: formal parameter different from declaration
3a47fb7208 The sensor and joystick instance ID generator isn't guarded by a lock.
aee4862958 ci: stop FreeBSD job after 30 minutes
99fa0d6cae Disable low latency audio by default when using AAudio on Android
ebfbd7327b testffmpeg: use SDL_test to parse arguments and track memory
ee53e4d319 cmake: check ffmpeg capability instead of version
2d62c65a75 Fixed build warning
bf72704bfd audio: Disable NEON sample conversion until test failures are fixed
0fe95cfba3 Sync wiki -> header
adcace6f95 Added a "--software" option to testffmpeg
86ada8a9f0 fix testffmpeg.c build.
303f4e965c testffmpeg works with ffmpeg 5.1.3 and newer
2bd478ae65 Added SDL_GetTextureDXGIResource() to get the DXGI resource associated with a render texture.
a842446f62 Added support for 0-copy decode and display using D3D11
d830cd140b Added support for 0-copy decode and display using Apple VideoToolbox
1bf913b29a Added support for 0-copy decode and display using VAAPI and EGL
ce8161e0cf Make sure we're building with ffmpeg 6.0 or newer
ed6381b68d Allow setting any number of sprites over the video
ebf5e08fa1 cmake: use *_STATIC_* variables when linking to a static ffmpeg
88f2fb9dcf Added an example of video decoding with ffmpeg
d88bf687a8 surface: Document the in-memory layout of the pixels
3698630bbc pixels: Document the naming convention
04edb38cdf shape: Use SDL[Test]_ReadSurfacePixel
f5745c3a67 surface: Add a private SDL_ReadSurfacePixel
0d68f45879 test: Extract SDLTest_ReadSurfacePixel
55a1458ed0 audio: Changes to one logical device must update all sibling logical devices.
8e03ea4383 hashtable: Use Create/Destroy naming, in the SDL3 style.
568902b64e hashtable: Added src/SDL_hashtable.[ch].
8745a9949b add-source-to-projects.pl: Fix adding files in the base src dir.
836927edf8 wayland: Try to skip the Wayland driver if not connecting to or in a Wayland session
2a9480c815 wayland: Add null check for zenity version string
f30392da5b Fix assertion in LINUX_JoystickSetSensorsEnabled()
4e59bf6cb9 SDLTest_CompareSurfaces: Output RGBA values of first differing pixel
b2ddfbbec3 SDLTest_CompareSurfaces: If surfaces differ, log their formats
b028fd9604 SDLTest_CompareSurfaces: Log better messages if NULL or different sizes
183606d3d4 testdrawchessboard: clean up renderer and window
4f0642bf47 triangle: don't read destination pixel when you're going to discard it anyways
4cd0c13823 blit_slow: don't read destination pixel when you're going to discard it anyways
49abb9c1fa aaudio: Fixed a comment.
0eb8651d5e Do not report gyro/accelerometer if we can't read axes info
ff57867516 audio: Fixed copy/paste error that was checking wrong variable.
d2d4914ac3 audio: WaitDevice/WaitCaptureDevice now returns a result.
a0820ed833 directsound: Cleaned up WaitDevice.
6c33a05bdb audio: Removed unused AllowsArbitraryDeviceNames variable.
f1fc198278 audio: Destroy the logical audio device before sending DEVICE_REMOVED event.
64ec208479 Fix log message spelling
9111c5e178 tests: Disable mouse warp test under Wayland
de5068f4e4 audio: Commented out a currently-incorrect assert.
3abb464f10 ci: disable Intel compilers
251f8fa272 Revert "Do a better job of finding default ALSA devices"
8857b0f13a Use the device audio format for the lowest latency
806e11ac00 Update sample processing bookkeeping when recovering the AAudio audio device
482c238953 aaudio: Deal with device recovery.
a8813b58a6 aaudio: Change an int to an SDL_bool.
8923305f34 We don't need to wait a full 10 ms, just delay a bit
6a152676bb Wait a bit when snd_pcm_avail() returns 0
b4372de186 alsa: Cleaned up remaining debug logging.
a063c943dc pulseaudio: Use pa_stream_begin_write to avoid an extra buffer copy.
0471a93706 alsa: Simplified PlayDevice and CaptureFromDevice.
776d9d0ee3 alsa: Convert `/* */` comments to `//` comments.
64fee85c69 alsa: More efficient audio thread iteration.
47cba08259 VisualC/pkg-support/cmake: remove subdir from public header include path
61e9a9dd56 pulseaudio: Just feed the device whenever it asks for any amount of data.
4f76f9b0a7 pulseaudio: Use correct buffer size of stream, wait less between fills.
d95d2d7051 SDLTest_CompareSurfaces: Decode pixels correctly on big-endian platforms
d65861f049 Do a better job of finding default ALSA devices
ba65ef5ce7 Recover from -EPIPE in snd_pcm_avail()
5be5000fa1 cmake: make HEADERS_DIR a required argument of SDL_generate_manpages
5c1a91a4e1 ci: make sure perl is installed + build docs with MSVC toolchain
6248472c0c test: Accept small numerical differences in more mathematical tests
a2c5dc6507 pulseaudio: Added typedef needed for compat with ancient Pulse installs.
f24551f6d1 pulseaudio: More workarounds for extremely old Pulse installs.
441a5b707b audio: Adjusted const/static fields on some variables.
280c2c1d7d pulseaudio: Revert "pulseaudio: Require PulseAudio 5.0 or later for SDL3."
4db2b968af audio: simple-copy path should check if device is paused.
505dc4c39c wasapi: Deal with device failures when we aren't holding the device lock.
ea5f59c234 Removed unused code
a6854098f7 Fixed stuttering on Android when using the AAudio driver
a5175e5ed0 audio: Fixed bug when setting up mixing formats.
9667aa18e6 wayland: Check that the data device supports the release method before calling it
4454dc400b wayland: Null all Wayland manager objects after freeing
e1789b320e video: Streamline a little deinit code.
2a1058713c Bump libdecor feature check to look for 0.2.0
f5886f11d0 cmake: let every test depends on pretest
f45761908a Move check for SDL_Delay upper bounds to testtimer
a84389f6bb libm: use union for infinity
474c8d0073 testautomation: don't do float equality tests
a6bc6b882c ci: always upload the artifacts
85e3099ba4 testautomation: only require accelated renderer with non-dummy video driver
26fd231151 ci: run tests on msvc workflow
0e955a9127 cmake: run testautomation with CTest
1375d2049d SDL_iconv_string() defaults to UTF-8
70a1bc6973 Check for NULL before dereferencing newly allocated memory
752f14e5a6 wayland: Convert some memcpy calls to copyp
9284a03053 wayland: Remove some unnecessary helper functions

git-subtree-dir: external/sdl/SDL
git-subtree-split: 0d7df16812c75c4a587d7d2673e3d1a5f2c2879b
2024-01-17 16:26:06 +01:00
7359e30c3e
adjust cmake for new toxcore files 2024-01-15 23:43:47 +01:00
61accfe184 Squashed 'external/toxcore/c-toxcore/' changes from 73d9b845a3..e2c01e457b
e2c01e457b refactor: Use enum-specific pack functions for enum values.
afc472402b refactor: Factor out union pack switch from event packer.
6caa7ce4b1 cleanup: Move the 2-element array pack out of individual events.
687af81f20 cleanup: Remove empty test doing nothing.
fcf5882428 test: Add printf log statement to group_moderation_test.
b4d8826228 cleanup: Remove old type-ordered event getters.
8c35e0fefb feat: add ngc events
97bdd83937 refactor: Make event dispatch ordered by receive time.
001d00ab30 fix: dont resolve to ipv6 addresses when its disabled
d3b935f63f fix(test): tests use ipv6 by default, even with USE_IPV6 set to 0
29fc5ea1f7 chore: add clangd files to .gitignore
d30c81acbc refactor: Move file streaming test to its own file.
acdc67387b fix(ci): window builds now build in parallel
REVERT: 73d9b845a3 cleanup: Remove old type-ordered event getters.
REVERT: b0840cc02d feat: add ngc events
REVERT: 7df9a51349 refactor: Make event dispatch ordered by receive time.

git-subtree-dir: external/toxcore/c-toxcore
git-subtree-split: e2c01e457bfb8a59537175c8fe17ca9ab1c9e3e1
2024-01-15 23:32:23 +01:00
5effe64474
Merge commit '61accfe1846e1f857fcdf84d27fb3d6e78fb46a3' 2024-01-15 23:32:23 +01:00
b1fe064484 Squashed 'external/toxcore/c-toxcore/' changes from 6d634674a9..73d9b845a3
73d9b845a3 cleanup: Remove old type-ordered event getters.
b0840cc02d feat: add ngc events
7df9a51349 refactor: Make event dispatch ordered by receive time.
bcb6592af5 test: Add C++ classes wrapping system interfaces.
4cea4f9ca4 fix: Make all the fuzzers work again, and add a test for protodump.
c4e209ea1d refactor: Factor out malloc+memcpy into memdup.
87bcc4322d fix: Remove fatal error for non-erroneous case
REVERT: 6d634674a9 cleanup: Remove old type-ordered event getters.
REVERT: d1d48d1dfc feat: add ngc events
REVERT: 994ffecc6b refactor: Make event dispatch ordered by receive time.

git-subtree-dir: external/toxcore/c-toxcore
git-subtree-split: 73d9b845a310c3f56d2d6d77ed56b93d84256d6e
2024-01-14 21:51:01 +01:00
2f44996edc
Merge commit 'b1fe0644843f5d08cd203bb5d4cdb923172f247b' 2024-01-14 21:51:01 +01:00
18ca88a0d4
asan in flake 2024-01-14 21:48:41 +01:00
565aa4b7eb
update deps and adopt 2024-01-14 18:50:23 +01:00
b117da5ccf
add compute powersave extreme 2024-01-13 18:38:12 +01:00
8eb4892b49 Squashed 'external/toxcore/c-toxcore/' changes from 8f0d505f9a..6d634674a9
6d634674a9 cleanup: Remove old type-ordered event getters.
d1d48d1dfc feat: add ngc events
994ffecc6b refactor: Make event dispatch ordered by receive time.
812f931d5f fix: Make sure there's enough space for CONSUME1 in fuzzers.
50f1b30fa9 test: Add fuzz tests to the coverage run.
df76f5cf47 chore: Move from gcov to llvm source-based coverage.
072e3beb3f fix: issues with packet broadcast error reporting
6b6718e4d2 cleanup: Make group packet entry creation less error-prone
5b9c420ce1 refactor: packet broadcast functions now return errors
af4cb31028 refactor: Use `operator==` for equality tests of `Node_format`.
9592d590cf refactor(test): Slightly nicer C++ interface to tox Random.
c66e10fb7a refactor: Minor refactoring of get_close_nodes functions.
ebc9643862 fix: don't pass garbage data buffer to packet send functions
32b68cffca cleanup: Some more test cleanups, removing overly smart code.
0426624dcb refactor: Assign malloc return to a local variable first.
afc38f2458 test: Add more unit tests for `add_to_list`.
05ce5c1ab9 test: Add "infer" CI check to github, remove from circle.
REVERT: 8f0d505f9a feat: add ngc events
REVERT: 9b8216e70c refactor: Make event dispatch ordered by receive time.

git-subtree-dir: external/toxcore/c-toxcore
git-subtree-split: 6d634674a929edb0ab70689dcbcb195b3547be13
2024-01-12 21:30:48 +01:00
82fe4c3dd7
Merge commit '8eb4892b4976e82e020d0e30dcf8f0705b76bb4e' 2024-01-12 21:30:48 +01:00
78b0e9a77f
more small fixes 2024-01-12 19:04:50 +01:00
7fa6aa7ac2
forgot to update plugin 2024-01-12 18:51:29 +01:00
20b4cdc5f1
sync and delivery (and unused read) states and other smaller refactors 2024-01-12 16:45:52 +01:00
7c576dd4d0
make fade less noticable 2024-01-10 14:17:29 +01:00
f6cda522ca
correct message order 2024-01-09 22:38:13 +01:00
3d2f5b644b
make toxcore work 2024-01-09 20:36:06 +01:00
9ace11a0e2 Squashed 'external/toxcore/c-toxcore/' changes from f1df709b87..8f0d505f9a
8f0d505f9a feat: add ngc events
9b8216e70c refactor: Make event dispatch ordered by receive time.
814c12a6f4 cleanup: Add dynamically derived array sizes to the API.
226b23be12 cleanup: Add explicit array sizes to toxencryptsave.
ef33cb4de0 cleanup: Add Toxav alias for ToxAV.
1da723b34d cleanup: Make Tox_Options a typedef.
b148a2afff chore: Simplify msvc build using vcpkg.
5cac6d7eb1 cleanup: Move `tox_get_system` out of the public API.
c9ca4007e3 refactor: Align group message sending with other send functions.
6c6c0b1b1b cleanup: Make setters take non-const `Tox *`.
a76f758d70 cleanup: Mark arrays in the tox API as `[]` instead of `*`.
baf6d1f6cf cleanup: Make array params in toxav `[]` instead of `*`.
79f55bd06a cleanup: Put the size of fixed arrays into the API types.
1e73698db2 cleanup: Add typedefs for public API int identifiers.
cac074c57f chore: Add fetch-sha256 script to update bootstrap node hash.
32576656bb Make the comment capitalization uniform
aff4dda17c Spellcheck tox-bootstrapd
40b5fbbe9d chore: Remove settings.yml in favour of hs-github-tools.
ebafd51be7 chore: Use GPL license with https.
0e42752f0f cleanup: Move all vptr-to-ptr casts to the beginning of a function.
5407384211 cleanup: Use github actions matrix to simplify CI.
82d8265688 fix: Use QueryPerformanceCounter on windows for monotonic time.
1224e656e3 chore: Add `net_(new|kill)_strerror` to cppcheck's allocators.
6a90ddfe4e cleanup: Run clang-tidy on headers, as well.
bd930cc80a cleanup: Make TCP connection failures a warning instead of error.
fad6e4e173 cleanup: Make all .c files include the headers they need.
ef4897a898 cleanup: Upgrade to clang-tidy-17 and fix some warnings.
REVERT: f1df709b87 feat: add ngc events
REVERT: 1b6c907235 refactor: Make event dispatch ordered by receive time.

git-subtree-dir: external/toxcore/c-toxcore
git-subtree-split: 8f0d505f9a598cc41c682178e1589bcc01efe9cb
2024-01-09 16:39:05 +01:00
6104d3b6d1
Merge commit '9ace11a0e2843cbde4af2b6ff7b49bcc6d429f78' 2024-01-09 16:39:05 +01:00
f637c7c942
make fade respect fps 2024-01-09 16:30:27 +01:00
afb886ea7c
default to reduced fps 2024-01-09 15:57:20 +01:00
2613 changed files with 43015 additions and 757580 deletions

View File

@ -7,37 +7,54 @@ on:
branches: [ master ] branches: [ master ]
env: env:
BUILD_TYPE: Release BUILD_TYPE: RelWithDebInfo
BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
jobs: jobs:
linux-ubuntu: linux-ubuntu:
timeout-minutes: 10 timeout-minutes: 10
runs-on: ubuntu-20.04 runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
- name: Install Dependencies - name: Install Dependencies
run: sudo apt update && sudo apt -y install libsodium-dev run: sudo apt update && sudo apt -y install libsodium-dev cmake
- name: Configure CMake - name: Configure CMake
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build - name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 -t tomato
- name: temp test - name: Determine tag name
run: ${{github.workspace}}/build/bin/mono_time_test id: tag
shell: bash
# taken from llama.cpp
run: |
SHORT_HASH="$(git rev-parse --short=7 HEAD)"
if [[ "${{ env.BRANCH_NAME }}" == "master" ]]; then
echo "name=dev-${SHORT_HASH}" >> $GITHUB_OUTPUT
else
SAFE_NAME=$(echo "${{ env.BRANCH_NAME }}" | tr '/' '-')
echo "name=dev-${SAFE_NAME}-${SHORT_HASH}" >> $GITHUB_OUTPUT
fi
- uses: actions/upload-artifact@v3 - name: Compress artifacts
shell: bash
run: |
tar -czvf ${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-ubuntu20.04-x86_64.tar.gz -C ${{github.workspace}}/build/bin/ .
- uses: actions/upload-artifact@v4
with: with:
name: ${{ github.event.repository.name }}-ubuntu20.04-x86_64 # TODO: simpler name?
name: ${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-ubuntu20.04-x86_64
# TODO: do propper packing # TODO: do propper packing
path: | path: |
${{github.workspace}}/build/bin/ ${{github.workspace}}/${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-ubuntu20.04-x86_64.tar.gz
windows: windows:
@ -46,34 +63,59 @@ jobs:
runs-on: windows-2019 runs-on: windows-2019
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
- name: update vcpkg
shell: bash
run: |
cd C:/vcpkg
git pull
- name: Install Dependencies - name: Install Dependencies
run: vcpkg install libsodium:x64-windows-static pthreads:x64-windows-static run: vcpkg install libsodium:x64-windows-static pthreads:x64-windows-static pkgconf:x64-windows
# setup vs env # setup vs env
- uses: ilammy/msvc-dev-cmd@v1 - uses: ilammy/msvc-dev-cmd@v1
with: with:
arch: amd64 arch: amd64
## sdl_image vendored needs nasm for dav1d
#- uses: ilammy/setup-nasm@v1
- name: Configure CMake - name: Configure CMake
run: cmake -G Ninja -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static run: cmake -G Ninja -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static -DSDL3IMAGE_VENDORED=ON -DSDL3IMAGE_DEPS_SHARED=ON -DSDL3IMAGE_JXL=OFF -DSDL3IMAGE_AVIF=OFF -DPKG_CONFIG_EXECUTABLE=C:/vcpkg/installed/x64-windows/tools/pkgconf/pkgconf.exe
- name: Build - name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -t tomato
- name: temp test - name: Determine tag name
run: ${{github.workspace}}/build/bin/mono_time_test.exe id: tag
shell: bash
# taken from llama.cpp
run: |
SHORT_HASH="$(git rev-parse --short=7 HEAD)"
if [[ "${{ env.BRANCH_NAME }}" == "master" ]]; then
echo "name=dev-${SHORT_HASH}" >> $GITHUB_OUTPUT
else
SAFE_NAME=$(echo "${{ env.BRANCH_NAME }}" | tr '/' '-')
echo "name=dev-${SAFE_NAME}-${SHORT_HASH}" >> $GITHUB_OUTPUT
fi
- uses: actions/upload-artifact@v3 - name: Compress artifacts
if: success() || failure() shell: powershell
run: |
Compress-Archive -Path ${{github.workspace}}/build/bin/* -Destination ${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-msvc-x86_64.zip
- uses: actions/upload-artifact@v4
with: with:
name: ${{ github.event.repository.name }}-windows-msvc-x86_64 # TODO: simpler name?
name: ${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-msvc-x86_64
# TODO: do propper packing # TODO: do propper packing
path: | path: |
${{github.workspace}}/build/bin/ ${{github.workspace}}/${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-msvc-x86_64.zip
windows-asan: windows-asan:
timeout-minutes: 15 timeout-minutes: 15
@ -81,33 +123,115 @@ jobs:
runs-on: windows-2019 runs-on: windows-2019
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
- name: update vcpkg
shell: bash
run: |
cd C:/vcpkg
git pull
- name: Install Dependencies - name: Install Dependencies
run: vcpkg install libsodium:x64-windows-static pthreads:x64-windows-static run: vcpkg install libsodium:x64-windows-static pthreads:x64-windows-static pkgconf:x64-windows
# setup vs env # setup vs env
- uses: ilammy/msvc-dev-cmd@v1 - uses: ilammy/msvc-dev-cmd@v1
with: with:
arch: amd64 arch: amd64
## sdl_image vendored needs nasm for dav1d
#- uses: ilammy/setup-nasm@v1
- name: Configure CMake - name: Configure CMake
run: cmake -G Ninja -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static -DTOMATO_ASAN=ON -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded run: cmake -G Ninja -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static -DTOMATO_ASAN=ON -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded -DSDL3IMAGE_VENDORED=ON -DSDL3IMAGE_DEPS_SHARED=ON -DSDL3IMAGE_JXL=OFF -DSDL3IMAGE_AVIF=OFF -DPKG_CONFIG_EXECUTABLE=C:/vcpkg/installed/x64-windows/tools/pkgconf/pkgconf.exe
- name: Build - name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 -t tomato
- name: temp test - name: Determine tag name
run: ${{github.workspace}}/build/bin/mono_time_test.exe id: tag
shell: bash
# taken from llama.cpp
run: |
SHORT_HASH="$(git rev-parse --short=7 HEAD)"
if [[ "${{ env.BRANCH_NAME }}" == "master" ]]; then
echo "name=dev-${SHORT_HASH}" >> $GITHUB_OUTPUT
else
SAFE_NAME=$(echo "${{ env.BRANCH_NAME }}" | tr '/' '-')
echo "name=dev-${SAFE_NAME}-${SHORT_HASH}" >> $GITHUB_OUTPUT
fi
- uses: actions/upload-artifact@v3 - name: Compress artifacts
if: success() || failure() shell: powershell
run: |
Compress-Archive -Path ${{github.workspace}}/build/bin/* -Destination ${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-msvc-asan-x86_64.zip
- uses: actions/upload-artifact@v4
with: with:
name: ${{ github.event.repository.name }}-windows-msvc-asan-x86_64 # TODO: simpler name?
name: ${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-msvc-asan-x86_64
# TODO: do propper packing # TODO: do propper packing
# TODO: also switch to asan dlls
path: | path: |
${{github.workspace}}/build/bin/ ${{github.workspace}}/${{ github.event.repository.name }}-${{ steps.tag.outputs.name }}-${{ runner.os }}-msvc-asan-x86_64.zip
release:
if: ${{ ( github.event_name == 'push' && github.ref == 'refs/heads/master' ) }}
runs-on: ubuntu-latest
needs:
- linux-ubuntu
- windows
- windows-asan
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Determine tag name
id: tag
shell: bash
# taken from llama.cpp
run: |
SHORT_HASH="$(git rev-parse --short=7 HEAD)"
if [[ "${{ env.BRANCH_NAME }}" == "master" ]]; then
echo "name=dev-${SHORT_HASH}" >> $GITHUB_OUTPUT
else
SAFE_NAME=$(echo "${{ env.BRANCH_NAME }}" | tr '/' '-')
echo "name=dev-${SAFE_NAME}-${SHORT_HASH}" >> $GITHUB_OUTPUT
fi
- name: Download artifacts
id: download-artifact
uses: actions/download-artifact@v4
with:
path: ./artifacts/
- name: Create release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ steps.tag.outputs.name }}
shell: bash
run: |
gh release create "$tag" \
--repo="$GITHUB_REPOSITORY" \
--title="${tag#v}" \
--notes="preview build of the latest commit" \
--prerelease
- name: Upload artifacts
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ steps.tag.outputs.name }}
shell: bash
run: |
ls -laR ./artifacts
gh release upload "$tag" ./artifacts/*/* \
--repo="$GITHUB_REPOSITORY"

View File

@ -16,21 +16,18 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
- name: Install Dependencies - name: Install Dependencies
run: sudo apt update && sudo apt -y install libsodium-dev run: sudo apt update && sudo apt -y install libsodium-dev cmake
- name: Configure CMake - name: Configure CMake
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build - name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 -t tomato
- name: temp test
run: ${{github.workspace}}/build/bin/mono_time_test
macos: macos:
timeout-minutes: 10 timeout-minutes: 10
@ -38,7 +35,7 @@ jobs:
runs-on: macos-latest runs-on: macos-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
@ -49,32 +46,39 @@ jobs:
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build - name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 -t tomato
windows: windows:
timeout-minutes: 10 timeout-minutes: 15
runs-on: windows-latest runs-on: windows-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
- name: update vcpkg
shell: bash
run: |
cd C:/vcpkg
git pull
- name: Install Dependencies - name: Install Dependencies
run: vcpkg install libsodium:x64-windows-static pthreads:x64-windows-static run: vcpkg install libsodium:x64-windows-static pthreads:x64-windows-static pkgconf:x64-windows
# setup vs env # setup vs env
- uses: ilammy/msvc-dev-cmd@v1 - uses: ilammy/msvc-dev-cmd@v1
with: with:
arch: amd64 arch: amd64
## sdl_image vendored needs nasm for dav1d
#- uses: ilammy/setup-nasm@v1
- name: Configure CMake - name: Configure CMake
run: cmake -G Ninja -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static run: cmake -G Ninja -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static -DSDL3IMAGE_VENDORED=ON -DSDL3IMAGE_DEPS_SHARED=ON -DSDL3IMAGE_JXL=OFF -DSDL3IMAGE_AVIF=OFF -DPKG_CONFIG_EXECUTABLE=C:/vcpkg/installed/x64-windows/tools/pkgconf/pkgconf.exe
- name: Build - name: Build
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -j 4 -t tomato
- name: temp test
run: ${{github.workspace}}/build/bin/mono_time_test.exe

6
.gitmodules vendored
View File

@ -20,3 +20,9 @@
[submodule "external/solanaceae_plugin"] [submodule "external/solanaceae_plugin"]
path = external/solanaceae_plugin path = external/solanaceae_plugin
url = https://github.com/Green-Sky/solanaceae_plugin.git url = https://github.com/Green-Sky/solanaceae_plugin.git
[submodule "external/solanaceae_object_store"]
path = external/solanaceae_object_store
url = https://github.com/Green-Sky/solanaceae_object_store.git
[submodule "external/solanaceae_message_serializer"]
path = external/solanaceae_message_serializer
url = https://github.com/Green-Sky/solanaceae_message_serializer.git

View File

@ -1,5 +1,7 @@
cmake_minimum_required(VERSION 3.14...3.24 FATAL_ERROR) cmake_minimum_required(VERSION 3.14...3.24 FATAL_ERROR)
#pingpong
# cmake setup begin # cmake setup begin
project(tomato) project(tomato)
@ -23,8 +25,8 @@ option(TOMATO_ASAN "Build tomato with asan (gcc/clang/msvc)" OFF)
if (TOMATO_ASAN) if (TOMATO_ASAN)
if (${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU" OR ${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang") if (${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU" OR ${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang")
if (NOT WIN32) # exclude mingw if (NOT WIN32) # exclude mingw
link_libraries(-fsanitize=address) #link_libraries(-fsanitize=address)
#link_libraries(-fsanitize=address,undefined) link_libraries(-fsanitize=address,undefined)
#link_libraries(-fsanitize=undefined) #link_libraries(-fsanitize=undefined)
message("II enabled ASAN") message("II enabled ASAN")
else() else()
@ -38,6 +40,10 @@ if (TOMATO_ASAN)
endif() endif()
endif() endif()
# uggly, but it needs to be defined for all of tomato.
# but this also means that we can not compile tomato in the same cmake as plugins
add_compile_definitions(ENTT_API_EXPORT)
# external libs # external libs
add_subdirectory(./external) # before increasing warn levels, sad :( add_subdirectory(./external) # before increasing warn levels, sad :(

View File

@ -2,3 +2,7 @@
![tomato](res/icon/tomato_v1_256.png) ![tomato](res/icon/tomato_v1_256.png)
## Highly experimental solanaceae client with Tox built-in
![group chat](res/tomato_screenshot_group_bot_text_23-02-2024.png)

View File

@ -1,10 +1,11 @@
cmake_minimum_required(VERSION 3.9 FATAL_ERROR) cmake_minimum_required(VERSION 3.14...3.24 FATAL_ERROR)
add_subdirectory(./entt) add_subdirectory(./entt)
add_subdirectory(./solanaceae_util) add_subdirectory(./solanaceae_util)
add_subdirectory(./solanaceae_contact) add_subdirectory(./solanaceae_contact)
add_subdirectory(./solanaceae_message3) add_subdirectory(./solanaceae_message3)
add_subdirectory(./solanaceae_message_serializer)
add_subdirectory(./solanaceae_plugin) add_subdirectory(./solanaceae_plugin)
@ -12,9 +13,13 @@ add_subdirectory(./toxcore)
add_subdirectory(./solanaceae_toxcore) add_subdirectory(./solanaceae_toxcore)
add_subdirectory(./solanaceae_tox) add_subdirectory(./solanaceae_tox)
add_subdirectory(./solanaceae_object_store)
add_subdirectory(./sdl) add_subdirectory(./sdl)
add_subdirectory(./imgui) add_subdirectory(./imgui)
add_subdirectory(./stb) add_subdirectory(./stb)
add_subdirectory(./libwebp) add_subdirectory(./libwebp)
add_subdirectory(./qoi)
add_subdirectory(./sdl_image)

View File

@ -0,0 +1 @@
blank_issues_enabled: false

View File

@ -0,0 +1,90 @@
name: "Ask a question, report a bug, request a feature, etc."
description: "Ask any question, discuss best practices, report a bug, request a feature."
body:
- type: markdown
attributes:
value: |
FOR FIRST-TIME USERS ISSUES COMPILING/LINKING/RUNNING or LOADING FONTS, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions)
For anything else: we are happy to use 'GitHub Issues' for many types of open-ended questions. We are encouraging 'Issues' becoming a large, centralized and cross-referenced database of Dear ImGui contents.
Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users.
- type: markdown
attributes:
value: |
**Prerequisites:**
- I have read [Frequently Asked Questions](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md).
- I have read [Contributing Guidelines -> General Advices](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md#getting-started--general-advice).
- I have read [Contributing Guidelines -> How to open an Issue](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md#how-to-open-an-issue).
- I have searched [Github Issues and PR](https://github.com/ocornut/imgui/issues?q=) for discussion of similar topics.
----
- type: input
id: specs_version
attributes:
label: "Version/Branch of Dear ImGui:"
description: "(please specify if you have made substantial modifications to your copy)"
value: "Version 1.XX, Branch: XXX (master/docking/etc.)"
placeholder: "Version 1.XX, Branch: XXX (master/docking/etc.)"
validations:
required: true
- type: input
id: specs_backend
attributes:
label: "Back-ends:"
description: (or specify when using custom engine/back-ends)
value: "imgui_impl_XXX.cpp + imgui_impl_XXX.cpp"
placeholder: "imgui_impl_XXX.cpp + imgui_impl_XXX.cpp or n/a"
validations:
required: true
- type: input
id: specs_compiler_os
attributes:
label: "Compiler, OS:"
placeholder: "e.g. Windows 11 + MSVC 2022, macOS + Clang 12, Linux + GCC etc."
validations:
required: true
- type: textarea
id: specs_full
attributes:
label: "Full config/build information:"
placeholder: |
(If you can run, you may go to 'Demo->Tools->About Dear ImGui->Config/Build Info' to obtain detailed information that you can paste here)
validations:
required: false
- type: textarea
id: issue_description
attributes:
label: "Details:"
description: "Try to be explicit with your goals, your expectations and what you have tried. Be mindful of [The XY Problem](https://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. If you are reporting a bug, explain what's the bug, how does it occur, etc. If you are reporting a crash, please include a debugger callstack."
value: |
**My Issue/Question:**
XXX _(please provide as much context as possible)_
validations:
required: true
- type: textarea
id: screenshots
attributes:
label: "Screenshots/Video:"
description: "Attach screenshots or gif/videos to clarify the context. They often convey useful information that is omitted by the description."
placeholder: "(You can drag files here)"
validations:
required: false
- type: textarea
id: repro_code
attributes:
label: "Minimal, Complete and Verifiable Example code:"
description: "Provide an [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 the 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, explain it and fix it. Please test your shortened code to ensure it exhibits the problem. Often while creating the MCVE you will solve 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."
value: |
```cpp
// Here's some code anyone can copy and paste to reproduce your issue
ImGui::Begin("Example Bug");
MoreCodeToExplainMyIssue();
ImGui::End();
```
validations:
required: false
- type: markdown
attributes:
value: |
Thank you for taking the time to read prerequisites, filling this template and double-checking your message and your code!

View File

@ -1,46 +0,0 @@
(Click "Preview" above ^ to turn URL into clickable links)
1. FOR FIRST-TIME USERS ISSUES COMPILING/LINKING/RUNNING or LOADING FONTS, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions).
2. PLEASE CAREFULLY READ: [FAQ](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md)
3. PLEASE CAREFULLY READ: [Contributing Guidelines](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md)
4. PLEASE MAKE SURE that you have: read the FAQ; explored the contents of `ShowDemoWindow()` including the Examples menu; searched among Issues; used your IDE to search for keywords in all sources and text files; and read the links above.
5. Be mindful that messages are being sent to the e-mail box of "Watching" users. Try to proof-read your messages before sending them. Edits are not seen by those users.
6. Delete points 1-6 and PLEASE FILL THE TEMPLATE BELOW before submitting your issue.
Thank you!
----
_(you may also go to Demo>About Window, and click "Config/Build Information" to obtain a bunch of detailed information that you can paste here)_
**Version/Branch of Dear ImGui:**
Version: XXX
Branch: XXX _(master/viewport/docking/etc.)_
**Back-end/Renderer/Compiler/OS**
Back-ends: imgui_impl_XXX.cpp + imgui_impl_XXX.cpp _(or specify if using a custom engine/back-end)_
Compiler: XXX _(if the question is related to building or platform specific features)_
Operating System: XXX
**My Issue/Question:**
XXX _(please provide as much context as possible)_
**Screenshots/Video**
XXX _(you can drag files here)_
**Standalone, minimal, complete and verifiable example:** _(see https://github.com/ocornut/imgui/issues/2261)_
```
// Here's some code anyone can copy and paste to reproduce your issue
ImGui::Begin("Example Bug");
MoreCodeToExplainMyIssue();
ImGui::End();
```

View File

@ -21,7 +21,7 @@ jobs:
VS_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\ VS_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\
MSBUILD_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\ MSBUILD_PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- name: Install Dependencies - name: Install Dependencies
shell: powershell shell: powershell
@ -209,7 +209,7 @@ jobs:
Linux: Linux:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- name: Install Dependencies - name: Install Dependencies
run: | run: |
@ -402,7 +402,7 @@ jobs:
MacOS: MacOS:
runs-on: macos-latest runs-on: macos-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- name: Install Dependencies - name: Install Dependencies
run: | run: |
@ -462,7 +462,7 @@ jobs:
iOS: iOS:
runs-on: macos-latest runs-on: macos-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- name: Build example_apple_metal - name: Build example_apple_metal
run: | run: |
@ -472,15 +472,15 @@ jobs:
Emscripten: Emscripten:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- name: Install Dependencies - name: Install Dependencies
run: | run: |
wget -q https://github.com/emscripten-core/emsdk/archive/master.tar.gz wget -q https://github.com/emscripten-core/emsdk/archive/master.tar.gz
tar -xvf master.tar.gz tar -xvf master.tar.gz
emsdk-master/emsdk update emsdk-master/emsdk update
emsdk-master/emsdk install 3.1.37 emsdk-master/emsdk install latest
emsdk-master/emsdk activate 3.1.37 emsdk-master/emsdk activate latest
- name: Build example_sdl2_opengl3 with Emscripten - name: Build example_sdl2_opengl3 with Emscripten
run: | run: |
@ -489,17 +489,17 @@ jobs:
popd popd
make -C examples/example_sdl2_opengl3 -f Makefile.emscripten make -C examples/example_sdl2_opengl3 -f Makefile.emscripten
- name: Build example_emscripten_wgpu - name: Build example_glfw_wgpu
run: | run: |
pushd emsdk-master pushd emsdk-master
source ./emsdk_env.sh source ./emsdk_env.sh
popd popd
make -C examples/example_emscripten_wgpu make -C examples/example_glfw_wgpu -f Makefile.emscripten
Android: Android:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- name: Build example_android_opengl3 - name: Build example_android_opengl3
run: | run: |

View File

@ -12,7 +12,7 @@ jobs:
PVS-Studio: PVS-Studio:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
fetch-depth: 1 fetch-depth: 1

View File

@ -8,7 +8,6 @@ imgui.ini
*.o *.o
*.obj *.obj
*.exe *.exe
examples/build/*
examples/*/Debug/* examples/*/Debug/*
examples/*/Release/* examples/*/Release/*
examples/*/x64/* examples/*/x64/*
@ -30,7 +29,7 @@ ipch
JSON/ JSON/
## Commonly used CMake directories ## Commonly used CMake directories
/build*/ build*/
## Xcode artifacts ## Xcode artifacts
project.xcworkspace project.xcworkspace
@ -41,8 +40,9 @@ examples/*.o.tmp
examples/*.out.js examples/*.out.js
examples/*.out.wasm examples/*.out.wasm
examples/example_glfw_opengl3/web/* examples/example_glfw_opengl3/web/*
examples/example_glfw_wgpu/web/*
examples/example_glfw_wgpu/external/*
examples/example_sdl2_opengl3/web/* examples/example_sdl2_opengl3/web/*
examples/example_emscripten_wgpu/web/*
## JetBrains IDE artifacts ## JetBrains IDE artifacts
.idea .idea

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2014-2023 Omar Cornut Copyright (c) 2014-2024 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -12,8 +12,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
@ -24,7 +27,7 @@
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
// 2022-01-17: Inputs: always calling io.AddKeyModsEvent() next and before key event (not in NewFrame) to fix input queue with very low framerates. // 2022-01-17: Inputs: always calling io.AddKeyModsEvent() next and before key event (not in NewFrame) to fix input queue with very low framerates.
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
// 2021-12-08: Renderer: 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. // 2021-12-08: Renderer: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86.
// 2021-08-17: Calling io.AddFocusEvent() on ALLEGRO_EVENT_DISPLAY_SWITCH_OUT/ALLEGRO_EVENT_DISPLAY_SWITCH_IN events. // 2021-08-17: Calling io.AddFocusEvent() on ALLEGRO_EVENT_DISPLAY_SWITCH_OUT/ALLEGRO_EVENT_DISPLAY_SWITCH_IN events.
// 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). // 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).
// 2021-05-19: Renderer: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-05-19: Renderer: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
@ -47,10 +50,11 @@
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_allegro5.h"
#include <stdint.h> // uint64_t #include <stdint.h> // uint64_t
#include <cstring> // memcpy #include <cstring> // memcpy
#include "imgui.h"
#include "imgui_impl_allegro5.h"
// Allegro // Allegro
#include <allegro5/allegro.h> #include <allegro5/allegro.h>
@ -419,6 +423,7 @@ static ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code)
bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display) bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
@ -434,9 +439,9 @@ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display)
// We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion. // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion.
ALLEGRO_VERTEX_ELEMENT elems[] = ALLEGRO_VERTEX_ELEMENT elems[] =
{ {
{ ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, pos) }, { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, pos) },
{ ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, IM_OFFSETOF(ImDrawVertAllegro, uv) }, { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, uv) },
{ ALLEGRO_PRIM_COLOR_ATTR, 0, IM_OFFSETOF(ImDrawVertAllegro, col) }, { ALLEGRO_PRIM_COLOR_ATTR, 0, offsetof(ImDrawVertAllegro, col) },
{ 0, 0, 0 } { 0, 0, 0 }
}; };
bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro)); bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro));
@ -486,8 +491,9 @@ static void ImGui_ImplAllegro5_UpdateKeyModifiers()
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev) bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev)
{ {
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
ImGuiIO& io = ImGui::GetIO();
switch (ev->type) switch (ev->type)
{ {
@ -582,7 +588,7 @@ static void ImGui_ImplAllegro5_UpdateMouseCursor()
void ImGui_ImplAllegro5_NewFrame() void ImGui_ImplAllegro5_NewFrame()
{ {
ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData(); ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplAllegro5_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
if (!bd->Texture) if (!bd->Texture)
ImGui_ImplAllegro5_CreateDeviceObjects(); ImGui_ImplAllegro5_CreateDeviceObjects();
@ -603,3 +609,7 @@ void ImGui_ImplAllegro5_NewFrame()
// Setup mouse cursor shape // Setup mouse cursor shape
ImGui_ImplAllegro5_UpdateMouseCursor(); ImGui_ImplAllegro5_UpdateMouseCursor();
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -12,11 +12,15 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct ALLEGRO_DISPLAY; struct ALLEGRO_DISPLAY;
union ALLEGRO_EVENT; union ALLEGRO_EVENT;
@ -30,3 +34,5 @@ IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event);
// Use if you want to reset your rendering device without losing Dear ImGui state. // Use if you want to reset your rendering device without losing Dear ImGui state.
IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -15,8 +15,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
@ -27,6 +30,7 @@
// 2021-03-04: Initial version. // 2021-03-04: Initial version.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_android.h" #include "imgui_impl_android.h"
#include <time.h> #include <time.h>
#include <android/native_window.h> #include <android/native_window.h>
@ -152,7 +156,7 @@ static ImGuiKey ImGui_ImplAndroid_KeyCodeToImGuiKey(int32_t key_code)
} }
} }
int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event) int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
int32_t event_type = AInputEvent_getType(input_event); int32_t event_type = AInputEvent_getType(input_event);
@ -179,7 +183,7 @@ int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event)
case AKEY_EVENT_ACTION_UP: case AKEY_EVENT_ACTION_UP:
{ {
ImGuiKey key = ImGui_ImplAndroid_KeyCodeToImGuiKey(event_key_code); ImGuiKey key = ImGui_ImplAndroid_KeyCodeToImGuiKey(event_key_code);
if (key != ImGuiKey_None && (event_action == AKEY_EVENT_ACTION_DOWN || event_action == AKEY_EVENT_ACTION_UP)) if (key != ImGuiKey_None)
{ {
io.AddKeyEvent(key, event_action == AKEY_EVENT_ACTION_DOWN); io.AddKeyEvent(key, event_action == AKEY_EVENT_ACTION_DOWN);
io.SetKeyEventNativeData(key, event_key_code, event_scan_code); io.SetKeyEventNativeData(key, event_key_code, event_scan_code);
@ -217,25 +221,27 @@ int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event)
{ {
case AMOTION_EVENT_ACTION_DOWN: case AMOTION_EVENT_ACTION_DOWN:
case AMOTION_EVENT_ACTION_UP: case AMOTION_EVENT_ACTION_UP:
{
// Physical mouse buttons (and probably other physical devices) also invoke the actions AMOTION_EVENT_ACTION_DOWN/_UP, // Physical mouse buttons (and probably other physical devices) also invoke the actions AMOTION_EVENT_ACTION_DOWN/_UP,
// but we have to process them separately to identify the actual button pressed. This is done below via // but we have to process them separately to identify the actual button pressed. This is done below via
// AMOTION_EVENT_ACTION_BUTTON_PRESS/_RELEASE. Here, we only process "FINGER" input (and "UNKNOWN", as a fallback). // AMOTION_EVENT_ACTION_BUTTON_PRESS/_RELEASE. Here, we only process "FINGER" input (and "UNKNOWN", as a fallback).
if((AMotionEvent_getToolType(input_event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_FINGER) int tool_type = AMotionEvent_getToolType(input_event, event_pointer_index);
|| (AMotionEvent_getToolType(input_event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_UNKNOWN)) if (tool_type == AMOTION_EVENT_TOOL_TYPE_FINGER || tool_type == AMOTION_EVENT_TOOL_TYPE_UNKNOWN)
{ {
io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index));
io.AddMouseButtonEvent(0, event_action == AMOTION_EVENT_ACTION_DOWN); io.AddMouseButtonEvent(0, event_action == AMOTION_EVENT_ACTION_DOWN);
} }
break; break;
}
case AMOTION_EVENT_ACTION_BUTTON_PRESS: case AMOTION_EVENT_ACTION_BUTTON_PRESS:
case AMOTION_EVENT_ACTION_BUTTON_RELEASE: case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
{ {
int32_t button_state = AMotionEvent_getButtonState(input_event); int32_t button_state = AMotionEvent_getButtonState(input_event);
io.AddMouseButtonEvent(0, (button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0); io.AddMouseButtonEvent(0, (button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0);
io.AddMouseButtonEvent(1, (button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0); io.AddMouseButtonEvent(1, (button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0);
io.AddMouseButtonEvent(2, (button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0); io.AddMouseButtonEvent(2, (button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0);
}
break; break;
}
case AMOTION_EVENT_ACTION_HOVER_MOVE: // Hovering: Tool moves while NOT pressed (such as a physical mouse) case AMOTION_EVENT_ACTION_HOVER_MOVE: // Hovering: Tool moves while NOT pressed (such as a physical mouse)
case AMOTION_EVENT_ACTION_MOVE: // Touch pointer moves while DOWN case AMOTION_EVENT_ACTION_MOVE: // Touch pointer moves while DOWN
io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index)); io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index));
@ -257,6 +263,8 @@ int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event)
bool ImGui_ImplAndroid_Init(ANativeWindow* window) bool ImGui_ImplAndroid_Init(ANativeWindow* window)
{ {
IMGUI_CHECKVERSION();
g_Window = window; g_Window = window;
g_Time = 0.0; g_Time = 0.0;
@ -294,3 +302,7 @@ void ImGui_ImplAndroid_NewFrame()
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
g_Time = current_time; g_Time = current_time;
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -15,15 +15,22 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct ANativeWindow; struct ANativeWindow;
struct AInputEvent; struct AInputEvent;
IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window); IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window);
IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event); IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event);
IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown(); IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown();
IMGUI_IMPL_API void ImGui_ImplAndroid_NewFrame(); IMGUI_IMPL_API void ImGui_ImplAndroid_NewFrame();
#endif // #ifndef IMGUI_DISABLE

View File

@ -7,8 +7,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
@ -30,6 +33,7 @@
// 2016-05-07: DirectX10: Disabling depth-write. // 2016-05-07: DirectX10: Disabling depth-write.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_dx10.h" #include "imgui_impl_dx10.h"
// DirectX // DirectX
@ -410,9 +414,9 @@ bool ImGui_ImplDX10_CreateDeviceObjects()
// Create the input layout // Create the input layout
D3D10_INPUT_ELEMENT_DESC local_layout[] = D3D10_INPUT_ELEMENT_DESC local_layout[] =
{ {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
}; };
if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK) if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
{ {
@ -530,6 +534,7 @@ void ImGui_ImplDX10_InvalidateDeviceObjects()
bool ImGui_ImplDX10_Init(ID3D10Device* device) bool ImGui_ImplDX10_Init(ID3D10Device* device)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
@ -574,8 +579,12 @@ void ImGui_ImplDX10_Shutdown()
void ImGui_ImplDX10_NewFrame() void ImGui_ImplDX10_NewFrame()
{ {
ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData(); ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX10_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?");
if (!bd->pFontSampler) if (!bd->pFontSampler)
ImGui_ImplDX10_CreateDeviceObjects(); ImGui_ImplDX10_CreateDeviceObjects();
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -7,11 +7,15 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct ID3D10Device; struct ID3D10Device;
@ -23,3 +27,5 @@ IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data);
// Use if you want to reset your rendering device without losing Dear ImGui state. // Use if you want to reset your rendering device without losing Dear ImGui state.
IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects();
IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -7,8 +7,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
@ -31,6 +34,7 @@
// 2016-05-07: DirectX11: Disabling depth-write. // 2016-05-07: DirectX11: Disabling depth-write.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_dx11.h" #include "imgui_impl_dx11.h"
// DirectX // DirectX
@ -422,9 +426,9 @@ bool ImGui_ImplDX11_CreateDeviceObjects()
// Create the input layout // Create the input layout
D3D11_INPUT_ELEMENT_DESC local_layout[] = D3D11_INPUT_ELEMENT_DESC local_layout[] =
{ {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
}; };
if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK) if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
{ {
@ -542,6 +546,7 @@ void ImGui_ImplDX11_InvalidateDeviceObjects()
bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
@ -590,8 +595,12 @@ void ImGui_ImplDX11_Shutdown()
void ImGui_ImplDX11_NewFrame() void ImGui_ImplDX11_NewFrame()
{ {
ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX11_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX11_Init()?");
if (!bd->pFontSampler) if (!bd->pFontSampler)
ImGui_ImplDX11_CreateDeviceObjects(); ImGui_ImplDX11_CreateDeviceObjects();
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -7,11 +7,15 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct ID3D11Device; struct ID3D11Device;
struct ID3D11DeviceContext; struct ID3D11DeviceContext;
@ -24,3 +28,5 @@ IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data);
// Use if you want to reset your rendering device without losing Dear ImGui state. // Use if you want to reset your rendering device without losing Dear ImGui state.
IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects();
IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -15,8 +15,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
@ -39,6 +42,7 @@
// 2018-02-22: Merged into master with all Win32 code synchronized to other examples. // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_dx12.h" #include "imgui_impl_dx12.h"
// DirectX // DirectX
@ -588,9 +592,9 @@ bool ImGui_ImplDX12_CreateDeviceObjects()
// Create the input layout // Create the input layout
static D3D12_INPUT_ELEMENT_DESC local_layout[] = static D3D12_INPUT_ELEMENT_DESC local_layout[] =
{ {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
}; };
psoDesc.InputLayout = { local_layout, 3 }; psoDesc.InputLayout = { local_layout, 3 };
} }
@ -698,6 +702,7 @@ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FO
D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle) D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
@ -746,8 +751,12 @@ void ImGui_ImplDX12_Shutdown()
void ImGui_ImplDX12_NewFrame() void ImGui_ImplDX12_NewFrame()
{ {
ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData(); ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX12_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
if (!bd->pPipelineState) if (!bd->pPipelineState)
ImGui_ImplDX12_CreateDeviceObjects(); ImGui_ImplDX12_CreateDeviceObjects();
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -10,11 +10,15 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
#include <dxgiformat.h> // DXGI_FORMAT #include <dxgiformat.h> // DXGI_FORMAT
struct ID3D12Device; struct ID3D12Device;
@ -36,3 +40,5 @@ IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3
// Use if you want to reset your rendering device without losing Dear ImGui state. // Use if you want to reset your rendering device without losing Dear ImGui state.
IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects();
IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -7,11 +7,15 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575)
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 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). // 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).
// 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1. // 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1.
@ -32,6 +36,7 @@
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_dx9.h" #include "imgui_impl_dx9.h"
// DirectX // DirectX
@ -280,6 +285,7 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
bool ImGui_ImplDX9_Init(IDirect3DDevice9* device) bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
@ -308,6 +314,24 @@ void ImGui_ImplDX9_Shutdown()
IM_DELETE(bd); IM_DELETE(bd);
} }
static bool ImGui_ImplDX9_CheckFormatSupport(IDirect3DDevice9* pDevice, D3DFORMAT format)
{
IDirect3D9* pd3d = nullptr;
if (pDevice->GetDirect3D(&pd3d) != D3D_OK)
return false;
D3DDEVICE_CREATION_PARAMETERS param = {};
D3DDISPLAYMODE mode = {};
if (pDevice->GetCreationParameters(&param) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK)
{
pd3d->Release();
return false;
}
// Font texture should support linear filter, color blend and write to render-target
bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK;
pd3d->Release();
return support;
}
static bool ImGui_ImplDX9_CreateFontsTexture() static bool ImGui_ImplDX9_CreateFontsTexture()
{ {
// Build texture atlas // Build texture atlas
@ -319,18 +343,21 @@ static bool ImGui_ImplDX9_CreateFontsTexture()
// Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices) // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
#ifndef IMGUI_USE_BGRA_PACKED_COLOR #ifndef IMGUI_USE_BGRA_PACKED_COLOR
if (io.Fonts->TexPixelsUseColors) const bool rgba_support = ImGui_ImplDX9_CheckFormatSupport(bd->pd3dDevice, D3DFMT_A8B8G8R8);
if (!rgba_support && io.Fonts->TexPixelsUseColors)
{ {
ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel); ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel);
for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++) for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++)
*dst = IMGUI_COL_TO_DX9_ARGB(*src); *dst = IMGUI_COL_TO_DX9_ARGB(*src);
pixels = (unsigned char*)dst_start; pixels = (unsigned char*)dst_start;
} }
#else
const bool rgba_support = false;
#endif #endif
// Upload texture to graphics system // Upload texture to graphics system
bd->FontTexture = nullptr; bd->FontTexture = nullptr;
if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0) if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, rgba_support ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0)
return false; return false;
D3DLOCKED_RECT tex_locked_rect; D3DLOCKED_RECT tex_locked_rect;
if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK) if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK)
@ -343,7 +370,7 @@ static bool ImGui_ImplDX9_CreateFontsTexture()
io.Fonts->SetTexID((ImTextureID)bd->FontTexture); io.Fonts->SetTexID((ImTextureID)bd->FontTexture);
#ifndef IMGUI_USE_BGRA_PACKED_COLOR #ifndef IMGUI_USE_BGRA_PACKED_COLOR
if (io.Fonts->TexPixelsUseColors) if (!rgba_support && io.Fonts->TexPixelsUseColors)
ImGui::MemFree(pixels); ImGui::MemFree(pixels);
#endif #endif
@ -373,8 +400,12 @@ void ImGui_ImplDX9_InvalidateDeviceObjects()
void ImGui_ImplDX9_NewFrame() void ImGui_ImplDX9_NewFrame()
{ {
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData(); ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX9_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX9_Init()?");
if (!bd->FontTexture) if (!bd->FontTexture)
ImGui_ImplDX9_CreateDeviceObjects(); ImGui_ImplDX9_CreateDeviceObjects();
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -7,11 +7,15 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct IDirect3DDevice9; struct IDirect3DDevice9;
@ -23,3 +27,5 @@ IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data);
// Use if you want to reset your rendering device without losing Dear ImGui state. // Use if you want to reset your rendering device without losing Dear ImGui state.
IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -12,11 +12,17 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window.
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys.
// 2023-07-18: Inputs: Revert ignoring mouse data on GLFW_CURSOR_DISABLED as it can be used differently. User may set ImGuiConfigFLags_NoMouse if desired. (#5625, #6609)
// 2023-06-12: Accept glfwGetTime() not returning a monotonically increasing value. This seems to happens on some Windows setup when peripherals disconnect, and is likely to also happen on browser + Emscripten. (#6491) // 2023-06-12: Accept glfwGetTime() not returning a monotonically increasing value. This seems to happens on some Windows setup when peripherals disconnect, and is likely to also happen on browser + Emscripten. (#6491)
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen on Windows ONLY, using a custom WndProc hook. (#2702) // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen on Windows ONLY, using a custom WndProc hook. (#2702)
// 2023-03-16: Inputs: Fixed key modifiers handling on secondary viewports (docking branch). Broken on 2023/01/04. (#6248, #6034) // 2023-03-16: Inputs: Fixed key modifiers handling on secondary viewports (docking branch). Broken on 2023/01/04. (#6248, #6034)
@ -27,7 +33,7 @@
// 2022-10-18: Perform a dummy glfwGetError() read to cancel missing mouse cursors errors. Using GLFW_VERSION_COMBINED directly. (#5785) // 2022-10-18: Perform a dummy glfwGetError() read to cancel missing mouse cursors errors. Using GLFW_VERSION_COMBINED directly. (#5785)
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
// 2022-09-01: Inputs: Honor GLFW_CURSOR_DISABLED by not setting mouse position. // 2022-09-01: Inputs: Honor GLFW_CURSOR_DISABLED by not setting mouse position *EDIT* Reverted 2023-07-18.
// 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX. // 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX.
// 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11. // 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11.
// 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend. // 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend.
@ -64,6 +70,7 @@
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_glfw.h" #include "imgui_impl_glfw.h"
// Clang warnings with -Weverything // Clang warnings with -Weverything
@ -78,11 +85,15 @@
#ifdef _WIN32 #ifdef _WIN32
#undef APIENTRY #undef APIENTRY
#ifndef GLFW_EXPOSE_NATIVE_WIN32
#define GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WIN32
#endif
#include <GLFW/glfw3native.h> // for glfwGetWin32Window() #include <GLFW/glfw3native.h> // for glfwGetWin32Window()
#endif #endif
#ifdef __APPLE__ #ifdef __APPLE__
#ifndef GLFW_EXPOSE_NATIVE_COCOA
#define GLFW_EXPOSE_NATIVE_COCOA #define GLFW_EXPOSE_NATIVE_COCOA
#endif
#include <GLFW/glfw3native.h> // for glfwGetCocoaWindow() #include <GLFW/glfw3native.h> // for glfwGetCocoaWindow()
#endif #endif
@ -107,7 +118,7 @@ enum GlfwClientApi
{ {
GlfwClientApi_Unknown, GlfwClientApi_Unknown,
GlfwClientApi_OpenGL, GlfwClientApi_OpenGL,
GlfwClientApi_Vulkan GlfwClientApi_Vulkan,
}; };
struct ImGui_ImplGlfw_Data struct ImGui_ImplGlfw_Data
@ -120,6 +131,9 @@ struct ImGui_ImplGlfw_Data
ImVec2 LastValidMousePos; ImVec2 LastValidMousePos;
bool InstalledCallbacks; bool InstalledCallbacks;
bool CallbacksChainForAllWindows; bool CallbacksChainForAllWindows;
#ifdef __EMSCRIPTEN__
const char* CanvasSelector;
#endif
// Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any. // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
GLFWwindowfocusfun PrevUserCallbackWindowFocus; GLFWwindowfocusfun PrevUserCallbackWindowFocus;
@ -269,6 +283,18 @@ static ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int key)
case GLFW_KEY_F10: return ImGuiKey_F10; case GLFW_KEY_F10: return ImGuiKey_F10;
case GLFW_KEY_F11: return ImGuiKey_F11; case GLFW_KEY_F11: return ImGuiKey_F11;
case GLFW_KEY_F12: return ImGuiKey_F12; case GLFW_KEY_F12: return ImGuiKey_F12;
case GLFW_KEY_F13: return ImGuiKey_F13;
case GLFW_KEY_F14: return ImGuiKey_F14;
case GLFW_KEY_F15: return ImGuiKey_F15;
case GLFW_KEY_F16: return ImGuiKey_F16;
case GLFW_KEY_F17: return ImGuiKey_F17;
case GLFW_KEY_F18: return ImGuiKey_F18;
case GLFW_KEY_F19: return ImGuiKey_F19;
case GLFW_KEY_F20: return ImGuiKey_F20;
case GLFW_KEY_F21: return ImGuiKey_F21;
case GLFW_KEY_F22: return ImGuiKey_F22;
case GLFW_KEY_F23: return ImGuiKey_F23;
case GLFW_KEY_F24: return ImGuiKey_F24;
default: return ImGuiKey_None; default: return ImGuiKey_None;
} }
} }
@ -385,8 +411,6 @@ void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y)
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackCursorPos(window, x, y); bd->PrevUserCallbackCursorPos(window, x, y);
if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
return;
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
io.AddMousePosEvent((float)x, (float)y); io.AddMousePosEvent((float)x, (float)y);
@ -400,8 +424,6 @@ void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered)
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window)) if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
bd->PrevUserCallbackCursorEnter(window, entered); bd->PrevUserCallbackCursorEnter(window, entered);
if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
return;
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
if (entered) if (entered)
@ -475,7 +497,7 @@ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wPara
ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo()); ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo());
break; break;
} }
return ::CallWindowProc(bd->GlfwWndProc, hWnd, msg, wParam, lParam); return ::CallWindowProcW(bd->GlfwWndProc, hWnd, msg, wParam, lParam);
} }
#endif #endif
@ -534,6 +556,7 @@ void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows)
static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api) static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
//printf("GLFW_VERSION: %d.%d.%d (%d)", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION, GLFW_VERSION_COMBINED); //printf("GLFW_VERSION: %d.%d.%d (%d)", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION, GLFW_VERSION_COMBINED);
@ -599,9 +622,9 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw
// Windows: register a WndProc hook so we can intercept some messages. // Windows: register a WndProc hook so we can intercept some messages.
#ifdef _WIN32 #ifdef _WIN32
bd->GlfwWndProc = (WNDPROC)::GetWindowLongPtr((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC); bd->GlfwWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC);
IM_ASSERT(bd->GlfwWndProc != nullptr); IM_ASSERT(bd->GlfwWndProc != nullptr);
::SetWindowLongPtr((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc);
#endif #endif
bd->ClientApi = client_api; bd->ClientApi = client_api;
@ -631,6 +654,9 @@ void ImGui_ImplGlfw_Shutdown()
if (bd->InstalledCallbacks) if (bd->InstalledCallbacks)
ImGui_ImplGlfw_RestoreCallbacks(bd->Window); ImGui_ImplGlfw_RestoreCallbacks(bd->Window);
#ifdef __EMSCRIPTEN__
emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, nullptr, false, nullptr);
#endif
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
glfwDestroyCursor(bd->MouseCursors[cursor_n]); glfwDestroyCursor(bd->MouseCursors[cursor_n]);
@ -638,7 +664,7 @@ void ImGui_ImplGlfw_Shutdown()
// Windows: register a WndProc hook so we can intercept some messages. // Windows: register a WndProc hook so we can intercept some messages.
#ifdef _WIN32 #ifdef _WIN32
ImGuiViewport* main_viewport = ImGui::GetMainViewport(); ImGuiViewport* main_viewport = ImGui::GetMainViewport();
::SetWindowLongPtr((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->GlfwWndProc); ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->GlfwWndProc);
bd->GlfwWndProc = nullptr; bd->GlfwWndProc = nullptr;
#endif #endif
@ -653,16 +679,9 @@ static void ImGui_ImplGlfw_UpdateMouseData()
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
if (glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
{
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
return;
}
// (those braces are here to reduce diff with multi-viewports support in 'docking' branch) // (those braces are here to reduce diff with multi-viewports support in 'docking' branch)
{ {
GLFWwindow* window = bd->Window; GLFWwindow* window = bd->Window;
#ifdef __EMSCRIPTEN__ #ifdef __EMSCRIPTEN__
const bool is_window_focused = true; const bool is_window_focused = true;
#else #else
@ -769,7 +788,7 @@ void ImGui_ImplGlfw_NewFrame()
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData(); ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplGlfw_InitForXXX()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?");
// Setup display size (every frame to accommodate for window resizing) // Setup display size (every frame to accommodate for window resizing)
int w, h; int w, h;
@ -795,6 +814,46 @@ void ImGui_ImplGlfw_NewFrame()
ImGui_ImplGlfw_UpdateGamepads(); ImGui_ImplGlfw_UpdateGamepads();
} }
#ifdef __EMSCRIPTEN__
static EM_BOOL ImGui_ImplGlfw_OnCanvasSizeChange(int event_type, const EmscriptenUiEvent* event, void* user_data)
{
ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
double canvas_width, canvas_height;
emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height);
glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height);
return true;
}
static EM_BOOL ImGui_ImplEmscripten_FullscreenChangeCallback(int event_type, const EmscriptenFullscreenChangeEvent* event, void* user_data)
{
ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
double canvas_width, canvas_height;
emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height);
glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height);
return true;
}
// 'canvas_selector' is a CSS selector. The event listener is applied to the first element that matches the query.
// STRING MUST PERSIST FOR THE APPLICATION DURATION. PLEASE USE A STRING LITERAL OR ENSURE POINTER WILL STAY VALID.
void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector)
{
IM_ASSERT(canvas_selector != nullptr);
ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?");
bd->CanvasSelector = canvas_selector;
emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, bd, false, ImGui_ImplGlfw_OnCanvasSizeChange);
emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, bd, false, ImGui_ImplEmscripten_FullscreenChangeCallback);
// Change the size of the GLFW window according to the size of the canvas
ImGui_ImplGlfw_OnCanvasSizeChange(EMSCRIPTEN_EVENT_RESIZE, {}, bd);
}
#endif
//-----------------------------------------------------------------------------
#if defined(__clang__) #if defined(__clang__)
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -11,11 +11,15 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct GLFWwindow; struct GLFWwindow;
struct GLFWmonitor; struct GLFWmonitor;
@ -26,6 +30,11 @@ IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool ins
IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown(); IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown();
IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame(); IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame();
// Emscripten related initialization phase methods
#ifdef __EMSCRIPTEN__
IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector);
#endif
// GLFW callbacks install // GLFW callbacks install
// - 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. // - 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.
// - 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. // - 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.
@ -45,3 +54,5 @@ IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double
IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c);
IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event); IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event);
#endif // #ifndef IMGUI_DISABLE

View File

@ -16,8 +16,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
@ -32,6 +35,7 @@
// 2018-03-22: Added GLUT Platform binding. // 2018-03-22: Added GLUT Platform binding.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_glut.h" #include "imgui_impl_glut.h"
#define GL_SILENCE_DEPRECATION #define GL_SILENCE_DEPRECATION
#ifdef __APPLE__ #ifdef __APPLE__
@ -163,6 +167,7 @@ static ImGuiKey ImGui_ImplGLUT_KeyToImGuiKey(int key)
bool ImGui_ImplGLUT_Init() bool ImGui_ImplGLUT_Init()
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
#ifdef FREEGLUT #ifdef FREEGLUT
io.BackendPlatformName = "imgui_impl_glut (freeglut)"; io.BackendPlatformName = "imgui_impl_glut (freeglut)";
@ -298,3 +303,7 @@ void ImGui_ImplGLUT_MotionFunc(int x, int y)
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
io.AddMousePosEvent((float)x, (float)y); io.AddMousePosEvent((float)x, (float)y);
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -16,10 +16,14 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#ifndef IMGUI_DISABLE
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
IMGUI_IMPL_API bool ImGui_ImplGLUT_Init(); IMGUI_IMPL_API bool ImGui_ImplGLUT_Init();
@ -29,7 +33,7 @@ IMGUI_IMPL_API void ImGui_ImplGLUT_NewFrame();
// You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically, // You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically,
// or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency.. // or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency..
//---------------------------------------- GLUT name --------------------------------------------- Decent Name --------- //------------------------------------ GLUT name ---------------------------------------------- Decent Name ---------
IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc
IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc
IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc
@ -38,3 +42,5 @@ IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int
IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc
IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc
IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc
#endif // #ifndef IMGUI_DISABLE

View File

@ -7,10 +7,14 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// ObjC API // ObjC API
@ -62,3 +66,7 @@ IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects();
#endif #endif
#endif #endif
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -7,8 +7,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
@ -30,6 +33,7 @@
// 2018-07-05: Metal: Added new Metal backend implementation. // 2018-07-05: Metal: Added new Metal backend implementation.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_metal.h" #include "imgui_impl_metal.h"
#import <time.h> #import <time.h>
#import <Metal/Metal.h> #import <Metal/Metal.h>
@ -75,7 +79,6 @@ struct ImGui_ImplMetal_Data
ImGui_ImplMetal_Data() { memset(this, 0, sizeof(*this)); } ImGui_ImplMetal_Data() { memset(this, 0, sizeof(*this)); }
}; };
static ImGui_ImplMetal_Data* ImGui_ImplMetal_CreateBackendData() { return IM_NEW(ImGui_ImplMetal_Data)(); }
static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; }
static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); } static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); }
@ -121,8 +124,11 @@ bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device)
bool ImGui_ImplMetal_Init(id<MTLDevice> device) bool ImGui_ImplMetal_Init(id<MTLDevice> device)
{ {
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_CreateBackendData();
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
ImGui_ImplMetal_Data* bd = IM_NEW(ImGui_ImplMetal_Data)();
io.BackendRendererUserData = (void*)bd; io.BackendRendererUserData = (void*)bd;
io.BackendRendererName = "imgui_impl_metal"; io.BackendRendererName = "imgui_impl_metal";
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
@ -149,7 +155,7 @@ void ImGui_ImplMetal_Shutdown()
void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor) void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor)
{ {
ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
IM_ASSERT(bd->SharedMetalContext != nil && "No Metal context. Did you call ImGui_ImplMetal_Init() ?"); IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?");
bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor];
if (bd->SharedMetalContext.depthStencilState == nil) if (bd->SharedMetalContext.depthStencilState == nil)
@ -543,13 +549,13 @@ void ImGui_ImplMetal_DestroyDeviceObjects()
} }
MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor]; MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor];
vertexDescriptor.attributes[0].offset = IM_OFFSETOF(ImDrawVert, pos); vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos);
vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position
vertexDescriptor.attributes[0].bufferIndex = 0; vertexDescriptor.attributes[0].bufferIndex = 0;
vertexDescriptor.attributes[1].offset = IM_OFFSETOF(ImDrawVert, uv); vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv);
vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords
vertexDescriptor.attributes[1].bufferIndex = 0; vertexDescriptor.attributes[1].bufferIndex = 0;
vertexDescriptor.attributes[2].offset = IM_OFFSETOF(ImDrawVert, col); vertexDescriptor.attributes[2].offset = offsetof(ImDrawVert, col);
vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color
vertexDescriptor.attributes[2].bufferIndex = 0; vertexDescriptor.attributes[2].bufferIndex = 0;
vertexDescriptor.layouts[0].stepRate = 1; vertexDescriptor.layouts[0].stepRate = 1;
@ -580,3 +586,7 @@ void ImGui_ImplMetal_DestroyDeviceObjects()
} }
@end @end
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -6,8 +6,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
// **Prefer using the code in imgui_impl_opengl3.cpp** // **Prefer using the code in imgui_impl_opengl3.cpp**
@ -20,7 +23,7 @@
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 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. // 2021-12-08: OpenGL: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86.
// 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). // 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).
// 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
// 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. // 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.
@ -37,12 +40,9 @@
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle. // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_opengl2.h" #include "imgui_impl_opengl2.h"
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t #include <stdint.h> // intptr_t
#endif
// Clang/GCC warnings with -Weverything // Clang/GCC warnings with -Weverything
#if defined(__clang__) #if defined(__clang__)
@ -83,6 +83,7 @@ static ImGui_ImplOpenGL2_Data* ImGui_ImplOpenGL2_GetBackendData()
bool ImGui_ImplOpenGL2_Init() bool ImGui_ImplOpenGL2_Init()
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
@ -108,7 +109,7 @@ void ImGui_ImplOpenGL2_Shutdown()
void ImGui_ImplOpenGL2_NewFrame() void ImGui_ImplOpenGL2_NewFrame()
{ {
ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData(); ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplOpenGL2_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL2_Init()?");
if (!bd->FontTexture) if (!bd->FontTexture)
ImGui_ImplOpenGL2_CreateDeviceObjects(); ImGui_ImplOpenGL2_CreateDeviceObjects();
@ -191,9 +192,9 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data)
const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos))); glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, pos)));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv))); glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, uv)));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col))); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, col)));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{ {
@ -293,6 +294,10 @@ void ImGui_ImplOpenGL2_DestroyDeviceObjects()
ImGui_ImplOpenGL2_DestroyFontsTexture(); ImGui_ImplOpenGL2_DestroyFontsTexture();
} }
//-----------------------------------------------------------------------------
#if defined(__clang__) #if defined(__clang__)
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -6,8 +6,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
// **Prefer using the code in imgui_impl_opengl3.cpp** // **Prefer using the code in imgui_impl_opengl3.cpp**
@ -19,6 +22,7 @@
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
IMGUI_IMPL_API bool ImGui_ImplOpenGL2_Init(); IMGUI_IMPL_API bool ImGui_ImplOpenGL2_Init();
IMGUI_IMPL_API void ImGui_ImplOpenGL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_Shutdown();
@ -30,3 +34,5 @@ IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyFontsTexture(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -14,11 +14,19 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562)
// 2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447)
// 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink.
// 2023-11-08: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983)
// 2023-10-05: OpenGL: Rename symbols in our internal loader so that LTO compilation with another copy of gl3w is possible. (#6875, #6668, #4445)
// 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333) // 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333)
// 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375) // 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375)
// 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333) // 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333)
@ -104,13 +112,10 @@
#endif #endif
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_opengl3.h" #include "imgui_impl_opengl3.h"
#include <stdio.h> #include <stdio.h>
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t #include <stdint.h> // intptr_t
#endif
#if defined(__APPLE__) #if defined(__APPLE__)
#include <TargetConditionals.h> #include <TargetConditionals.h>
#endif #endif
@ -173,9 +178,21 @@
#define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES #define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES
#endif #endif
// Desktop GL 2.0+ has glPolygonMode() which GL ES and WebGL don't have. // Desktop GL 2.0+ has extension and glPolygonMode() which GL ES and WebGL don't have..
#ifdef GL_POLYGON_MODE // A desktop ES context can technically compile fine with our loader, so we also perform a runtime checks
#define IMGUI_IMPL_HAS_POLYGON_MODE #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
#define IMGUI_IMPL_OPENGL_HAS_EXTENSIONS // has glGetIntegerv(GL_NUM_EXTENSIONS)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE // may have glPolygonMode()
#endif
// Desktop GL 2.1+ and GL ES 3.0+ have glBindBuffer() with GL_PIXEL_UNPACK_BUFFER target.
#if !defined(IMGUI_IMPL_OPENGL_ES2)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
#endif
// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
#endif #endif
// Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have. // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
@ -188,16 +205,6 @@
#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
#endif #endif
// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
#endif
// Desktop GL use extension detection
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
#endif
// [Debugging] // [Debugging]
//#define IMGUI_IMPL_OPENGL_DEBUG //#define IMGUI_IMPL_OPENGL_DEBUG
#ifdef IMGUI_IMPL_OPENGL_DEBUG #ifdef IMGUI_IMPL_OPENGL_DEBUG
@ -226,6 +233,7 @@ struct ImGui_ImplOpenGL3_Data
unsigned int VboHandle, ElementsHandle; unsigned int VboHandle, ElementsHandle;
GLsizeiptr VertexBufferSize; GLsizeiptr VertexBufferSize;
GLsizeiptr IndexBufferSize; GLsizeiptr IndexBufferSize;
bool HasPolygonMode;
bool HasClipOrigin; bool HasClipOrigin;
bool UseBufferSubData; bool UseBufferSubData;
@ -267,6 +275,7 @@ struct ImGui_ImplOpenGL3_VtxAttribState
bool ImGui_ImplOpenGL3_Init(const char* glsl_version) bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Initialize our loader // Initialize our loader
@ -290,16 +299,13 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
bd->GlProfileIsES2 = true; bd->GlProfileIsES2 = true;
#else #else
// Desktop or GLES 3 // Desktop or GLES 3
const char* gl_version_str = (const char*)glGetString(GL_VERSION);
GLint major = 0; GLint major = 0;
GLint minor = 0; GLint minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor); glGetIntegerv(GL_MINOR_VERSION, &minor);
if (major == 0 && minor == 0) if (major == 0 && minor == 0)
{ sscanf(gl_version_str, "%d.%d", &major, &minor); // Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
const char* gl_version = (const char*)glGetString(GL_VERSION);
sscanf(gl_version, "%d.%d", &major, &minor);
}
bd->GlVersion = (GLuint)(major * 100 + minor * 10); bd->GlVersion = (GLuint)(major * 100 + minor * 10);
#if defined(GL_CONTEXT_PROFILE_MASK) #if defined(GL_CONTEXT_PROFILE_MASK)
if (bd->GlVersion >= 320) if (bd->GlVersion >= 320)
@ -309,6 +315,9 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
#if defined(IMGUI_IMPL_OPENGL_ES3) #if defined(IMGUI_IMPL_OPENGL_ES3)
bd->GlProfileIsES3 = true; bd->GlProfileIsES3 = true;
#else
if (strncmp(gl_version_str, "OpenGL ES 3", 11) == 0)
bd->GlProfileIsES3 = true;
#endif #endif
bd->UseBufferSubData = false; bd->UseBufferSubData = false;
@ -323,7 +332,7 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
#endif #endif
#ifdef IMGUI_IMPL_OPENGL_DEBUG #ifdef IMGUI_IMPL_OPENGL_DEBUG
printf("GlVersion = %d\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2 = %d, GlProfileIsES3 = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG] printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2 = %d, GlProfileIsES3 = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG]
#endif #endif
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
@ -355,8 +364,11 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture); glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
// Detect extensions we support // Detect extensions we support
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
bd->HasPolygonMode = (!bd->GlProfileIsES2 && !bd->GlProfileIsES3);
#endif
bd->HasClipOrigin = (bd->GlVersion >= 450); bd->HasClipOrigin = (bd->GlVersion >= 450);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS #ifdef IMGUI_IMPL_OPENGL_HAS_EXTENSIONS
GLint num_extensions = 0; GLint num_extensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions); glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions);
for (GLint i = 0; i < num_extensions; i++) for (GLint i = 0; i < num_extensions; i++)
@ -386,7 +398,7 @@ void ImGui_ImplOpenGL3_Shutdown()
void ImGui_ImplOpenGL3_NewFrame() void ImGui_ImplOpenGL3_NewFrame()
{ {
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplOpenGL3_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL3_Init()?");
if (!bd->ShaderHandle) if (!bd->ShaderHandle)
ImGui_ImplOpenGL3_CreateDeviceObjects(); ImGui_ImplOpenGL3_CreateDeviceObjects();
@ -408,8 +420,9 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid
if (bd->GlVersion >= 310) if (bd->GlVersion >= 310)
glDisable(GL_PRIMITIVE_RESTART); glDisable(GL_PRIMITIVE_RESTART);
#endif #endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if (bd->HasPolygonMode)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif #endif
// Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
@ -460,9 +473,9 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos)); GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos));
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV)); GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV));
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor)); GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos))); GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos)));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv))); GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv)));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col))); GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col)));
} }
// OpenGL3 Render function. // OpenGL3 Render function.
@ -497,8 +510,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object); GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
#endif #endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); GLint last_polygon_mode[2]; if (bd->HasPolygonMode) { glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); }
#endif #endif
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
@ -636,18 +649,10 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); } if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); }
#endif #endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
// Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons // Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons
if (bd->GlVersion <= 310 || bd->GlProfileIsCompat) if (bd->HasPolygonMode) { if (bd->GlVersion <= 310 || bd->GlProfileIsCompat) { glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]); } else { glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); } }
{ #endif // IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]);
glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
}
#endif // IMGUI_IMPL_HAS_POLYGON_MODE
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
@ -744,6 +749,10 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects()
GLint last_texture, last_array_buffer; GLint last_texture, last_array_buffer;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
GLint last_pixel_unpack_buffer = 0;
if (bd->GlVersion >= 210) { glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &last_pixel_unpack_buffer); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); }
#endif
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GLint last_vertex_array; GLint last_vertex_array;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
@ -917,6 +926,9 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects()
// Restore modified GL state // Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture); glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
if (bd->GlVersion >= 210) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, last_pixel_unpack_buffer); }
#endif
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(last_vertex_array); glBindVertexArray(last_vertex_array);
#endif #endif
@ -933,9 +945,13 @@ void ImGui_ImplOpenGL3_DestroyDeviceObjects()
ImGui_ImplOpenGL3_DestroyFontsTexture(); ImGui_ImplOpenGL3_DestroyFontsTexture();
} }
//-----------------------------------------------------------------------------
#if defined(__GNUC__) #if defined(__GNUC__)
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif
#if defined(__clang__) #if defined(__clang__)
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -14,8 +14,11 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// About GLSL version: // About GLSL version:
// The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string. // The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string.
@ -24,6 +27,7 @@
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
// Backend API // Backend API
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr); IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr);
@ -37,9 +41,9 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
// Specific OpenGL ES versions // Configuration flags to add in your imconfig file:
//#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten //#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten)
//#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android //#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android)
// 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. // 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.
#if !defined(IMGUI_IMPL_OPENGL_ES2) \ #if !defined(IMGUI_IMPL_OPENGL_ES2) \
@ -58,3 +62,5 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
#endif #endif
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -10,7 +10,7 @@
// THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE. // THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE.
// //
// IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions): // IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions):
// IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCUDING 'imgui_impl_opengl3_loader.h' // IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCLUDING 'imgui_impl_opengl3_loader.h'
// IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER. // IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER.
// (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS) // (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS)
// YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT. // YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT.
@ -18,7 +18,7 @@
// WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT. // WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT.
// //
// Regenerate with: // Regenerate with:
// python gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt // python3 gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
// //
// More info: // More info:
// https://github.com/dearimgui/gl3w_stripped // https://github.com/dearimgui/gl3w_stripped
@ -346,6 +346,10 @@ GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean
GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#endif #endif
#endif /* GL_VERSION_2_0 */ #endif /* GL_VERSION_2_0 */
#ifndef GL_VERSION_2_1
#define GL_PIXEL_UNPACK_BUFFER 0x88EC
#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF
#endif /* GL_VERSION_2_1 */
#ifndef GL_VERSION_3_0 #ifndef GL_VERSION_3_0
typedef khronos_uint16_t GLhalf; typedef khronos_uint16_t GLhalf;
#define GL_MAJOR_VERSION 0x821B #define GL_MAJOR_VERSION 0x821B
@ -467,7 +471,7 @@ GL3W_API int imgl3wIsSupported(int major, int minor);
GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc); GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc);
/* gl3w internal state */ /* gl3w internal state */
union GL3WProcs { union ImGL3WProcs {
GL3WglProc ptr[59]; GL3WglProc ptr[59];
struct { struct {
PFNGLACTIVETEXTUREPROC ActiveTexture; PFNGLACTIVETEXTUREPROC ActiveTexture;
@ -532,7 +536,7 @@ union GL3WProcs {
} gl; } gl;
}; };
GL3W_API extern union GL3WProcs imgl3wProcs; GL3W_API extern union ImGL3WProcs imgl3wProcs;
/* OpenGL functions */ /* OpenGL functions */
#define glActiveTexture imgl3wProcs.gl.ActiveTexture #define glActiveTexture imgl3wProcs.gl.ActiveTexture
@ -608,7 +612,7 @@ extern "C" {
#include <stdlib.h> #include <stdlib.h>
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#if defined(_WIN32) #if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN #ifndef WIN32_LEAN_AND_MEAN
@ -661,26 +665,123 @@ static GL3WglProc get_proc(const char *proc)
#else #else
#include <dlfcn.h> #include <dlfcn.h>
static void *libgl; static void* libgl; // OpenGL library
static GL3WglProc (*glx_get_proc_address)(const GLubyte *); static void* libglx; // GLX library
static void* libegl; // EGL library
static GL3WGetProcAddressProc gl_get_proc_address;
static void close_libgl(void)
{
if (libgl) {
dlclose(libgl);
libgl = NULL;
}
if (libegl) {
dlclose(libegl);
libegl = NULL;
}
if (libglx) {
dlclose(libglx);
libglx = NULL;
}
}
static int is_library_loaded(const char* name, void** lib)
{
*lib = dlopen(name, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
return *lib != NULL;
}
static int open_libs(void)
{
// On Linux we have two APIs to get process addresses: EGL and GLX.
// EGL is supported under both X11 and Wayland, whereas GLX is X11-specific.
libgl = NULL;
libegl = NULL;
libglx = NULL;
// First check what's already loaded, the windowing library might have
// already loaded either EGL or GLX and we want to use the same one.
if (is_library_loaded("libEGL.so.1", &libegl) ||
is_library_loaded("libGLX.so.0", &libglx)) {
libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL);
if (libgl)
return GL3W_OK;
else
close_libgl();
}
if (is_library_loaded("libGL.so", &libgl))
return GL3W_OK;
if (is_library_loaded("libGL.so.1", &libgl))
return GL3W_OK;
if (is_library_loaded("libGL.so.3", &libgl))
return GL3W_OK;
// Neither is already loaded, so we have to load one. Try EGL first
// because it is supported under both X11 and Wayland.
// Load OpenGL + EGL
libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL);
libegl = dlopen("libEGL.so.1", RTLD_LAZY | RTLD_LOCAL);
if (libgl && libegl)
return GL3W_OK;
else
close_libgl();
// Fall back to legacy libGL, which includes GLX
// While most systems use libGL.so.1, NetBSD seems to use that libGL.so.3. See https://github.com/ocornut/imgui/issues/6983
libgl = dlopen("libGL.so", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
libgl = dlopen("libGL.so.3", RTLD_LAZY | RTLD_LOCAL);
if (libgl)
return GL3W_OK;
return GL3W_ERROR_LIBRARY_OPEN;
}
static int open_libgl(void) static int open_libgl(void)
{ {
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL); int res = open_libs();
if (!libgl) if (res)
return res;
if (libegl)
*(void**)(&gl_get_proc_address) = dlsym(libegl, "eglGetProcAddress");
else if (libglx)
*(void**)(&gl_get_proc_address) = dlsym(libglx, "glXGetProcAddressARB");
else
*(void**)(&gl_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
if (!gl_get_proc_address) {
close_libgl();
return GL3W_ERROR_LIBRARY_OPEN; return GL3W_ERROR_LIBRARY_OPEN;
*(void **)(&glx_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB"); }
return GL3W_OK; return GL3W_OK;
} }
static void close_libgl(void) { dlclose(libgl); } static GL3WglProc get_proc(const char* proc)
static GL3WglProc get_proc(const char *proc)
{ {
GL3WglProc res; GL3WglProc res = NULL;
res = glx_get_proc_address((const GLubyte *)proc);
// Before EGL version 1.5, eglGetProcAddress doesn't support querying core
// functions and may return a dummy function if we try, so try to load the
// function from the GL library directly first.
if (libegl)
*(void**)(&res) = dlsym(libgl, proc);
if (!res) if (!res)
*(void **)(&res) = dlsym(libgl, proc); res = gl_get_proc_address(proc);
if (!libegl && !res)
*(void**)(&res) = dlsym(libgl, proc);
return res; return res;
} }
#endif #endif
@ -794,12 +895,12 @@ static const char *proc_names[] = {
"glViewport", "glViewport",
}; };
GL3W_API union GL3WProcs imgl3wProcs; GL3W_API union ImGL3WProcs imgl3wProcs;
static void load_procs(GL3WGetProcAddressProc proc) static void load_procs(GL3WGetProcAddressProc proc)
{ {
size_t i; size_t i;
for (i = 0; i < ARRAY_SIZE(proc_names); i++) for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++)
imgl3wProcs.ptr[i] = proc(proc_names[i]); imgl3wProcs.ptr[i] = proc(proc_names[i]);
} }

View File

@ -13,10 +13,14 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
#ifdef __OBJC__ #ifdef __OBJC__
@ -43,3 +47,5 @@ IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view);
#endif #endif
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -13,10 +13,14 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#import "imgui.h" #import "imgui.h"
#ifndef IMGUI_DISABLE
#import "imgui_impl_osx.h" #import "imgui_impl_osx.h"
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h> #import <Carbon/Carbon.h>
@ -25,6 +29,7 @@
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen.
// 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen. // 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen.
// 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mices). // 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mices).
// 2022-11-02: Fixed mouse coordinates before clicking the host window. // 2022-11-02: Fixed mouse coordinates before clicking the host window.
@ -79,7 +84,6 @@ struct ImGui_ImplOSX_Data
ImGui_ImplOSX_Data() { memset(this, 0, sizeof(*this)); } ImGui_ImplOSX_Data() { memset(this, 0, sizeof(*this)); }
}; };
static ImGui_ImplOSX_Data* ImGui_ImplOSX_CreateBackendData() { return IM_NEW(ImGui_ImplOSX_Data)(); }
static ImGui_ImplOSX_Data* ImGui_ImplOSX_GetBackendData() { return (ImGui_ImplOSX_Data*)ImGui::GetIO().BackendPlatformUserData; } static ImGui_ImplOSX_Data* ImGui_ImplOSX_GetBackendData() { return (ImGui_ImplOSX_Data*)ImGui::GetIO().BackendPlatformUserData; }
static void ImGui_ImplOSX_DestroyBackendData() { IM_DELETE(ImGui_ImplOSX_GetBackendData()); } static void ImGui_ImplOSX_DestroyBackendData() { IM_DELETE(ImGui_ImplOSX_GetBackendData()); }
@ -333,36 +337,36 @@ static ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code)
case kVK_RightOption: return ImGuiKey_RightAlt; case kVK_RightOption: return ImGuiKey_RightAlt;
case kVK_RightCommand: return ImGuiKey_RightSuper; case kVK_RightCommand: return ImGuiKey_RightSuper;
// case kVK_Function: return ImGuiKey_; // case kVK_Function: return ImGuiKey_;
// case kVK_F17: return ImGuiKey_;
// case kVK_VolumeUp: return ImGuiKey_; // case kVK_VolumeUp: return ImGuiKey_;
// case kVK_VolumeDown: return ImGuiKey_; // case kVK_VolumeDown: return ImGuiKey_;
// case kVK_Mute: return ImGuiKey_; // case kVK_Mute: return ImGuiKey_;
// case kVK_F18: return ImGuiKey_; case kVK_F1: return ImGuiKey_F1;
// case kVK_F19: return ImGuiKey_; case kVK_F2: return ImGuiKey_F2;
// case kVK_F20: return ImGuiKey_; case kVK_F3: return ImGuiKey_F3;
case kVK_F4: return ImGuiKey_F4;
case kVK_F5: return ImGuiKey_F5; case kVK_F5: return ImGuiKey_F5;
case kVK_F6: return ImGuiKey_F6; case kVK_F6: return ImGuiKey_F6;
case kVK_F7: return ImGuiKey_F7; case kVK_F7: return ImGuiKey_F7;
case kVK_F3: return ImGuiKey_F3;
case kVK_F8: return ImGuiKey_F8; case kVK_F8: return ImGuiKey_F8;
case kVK_F9: return ImGuiKey_F9; case kVK_F9: return ImGuiKey_F9;
case kVK_F11: return ImGuiKey_F11;
case kVK_F13: return ImGuiKey_PrintScreen;
// case kVK_F16: return ImGuiKey_;
// case kVK_F14: return ImGuiKey_;
case kVK_F10: return ImGuiKey_F10; case kVK_F10: return ImGuiKey_F10;
case 0x6E: return ImGuiKey_Menu; case kVK_F11: return ImGuiKey_F11;
case kVK_F12: return ImGuiKey_F12; case kVK_F12: return ImGuiKey_F12;
// case kVK_F15: return ImGuiKey_; case kVK_F13: return ImGuiKey_F13;
case kVK_F14: return ImGuiKey_F14;
case kVK_F15: return ImGuiKey_F15;
case kVK_F16: return ImGuiKey_F16;
case kVK_F17: return ImGuiKey_F17;
case kVK_F18: return ImGuiKey_F18;
case kVK_F19: return ImGuiKey_F19;
case kVK_F20: return ImGuiKey_F20;
case 0x6E: return ImGuiKey_Menu;
case kVK_Help: return ImGuiKey_Insert; case kVK_Help: return ImGuiKey_Insert;
case kVK_Home: return ImGuiKey_Home; case kVK_Home: return ImGuiKey_Home;
case kVK_PageUp: return ImGuiKey_PageUp; case kVK_PageUp: return ImGuiKey_PageUp;
case kVK_ForwardDelete: return ImGuiKey_Delete; case kVK_ForwardDelete: return ImGuiKey_Delete;
case kVK_F4: return ImGuiKey_F4;
case kVK_End: return ImGuiKey_End; case kVK_End: return ImGuiKey_End;
case kVK_F2: return ImGuiKey_F2;
case kVK_PageDown: return ImGuiKey_PageDown; case kVK_PageDown: return ImGuiKey_PageDown;
case kVK_F1: return ImGuiKey_F1;
case kVK_LeftArrow: return ImGuiKey_LeftArrow; case kVK_LeftArrow: return ImGuiKey_LeftArrow;
case kVK_RightArrow: return ImGuiKey_RightArrow; case kVK_RightArrow: return ImGuiKey_RightArrow;
case kVK_DownArrow: return ImGuiKey_DownArrow; case kVK_DownArrow: return ImGuiKey_DownArrow;
@ -387,13 +391,15 @@ IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view) {
bool ImGui_ImplOSX_Init(NSView* view) bool ImGui_ImplOSX_Init(NSView* view)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_CreateBackendData(); IMGUI_CHECKVERSION();
io.BackendPlatformUserData = (void*)bd; IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
ImGui_ImplOSX_Data* bd = IM_NEW(ImGui_ImplOSX_Data)();
io.BackendPlatformUserData = (void*)bd;
io.BackendPlatformName = "imgui_impl_osx";
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
//io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) //io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
io.BackendPlatformName = "imgui_impl_osx";
bd->Observer = [ImGuiObserver new]; bd->Observer = [ImGuiObserver new];
@ -529,7 +535,6 @@ static void ImGui_ImplOSX_UpdateMouseCursor()
static void ImGui_ImplOSX_UpdateGamepads() static void ImGui_ImplOSX_UpdateGamepads()
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
memset(io.NavInputs, 0, sizeof(io.NavInputs));
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
return; return;
@ -596,6 +601,7 @@ static void ImGui_ImplOSX_UpdateImePosWithView(NSView* view)
void ImGui_ImplOSX_NewFrame(NSView* view) void ImGui_ImplOSX_NewFrame(NSView* view)
{ {
ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData(); ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOSX_Init()?");
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
// Setup display size // Setup display size
@ -801,3 +807,7 @@ static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view)
return event; return event;
}]; }];
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -13,11 +13,16 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode().
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) // 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702) // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644) // 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644)
@ -73,6 +78,7 @@
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers. // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_sdl2.h" #include "imgui_impl_sdl2.h"
// Clang warnings with -Weverything // Clang warnings with -Weverything
@ -98,16 +104,23 @@
// SDL Data // SDL Data
struct ImGui_ImplSDL2_Data struct ImGui_ImplSDL2_Data
{ {
SDL_Window* Window; SDL_Window* Window;
SDL_Renderer* Renderer; SDL_Renderer* Renderer;
Uint64 Time; Uint64 Time;
Uint32 MouseWindowID; char* ClipboardTextData;
int MouseButtonsDown;
SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; // Mouse handling
SDL_Cursor* LastMouseCursor; Uint32 MouseWindowID;
int PendingMouseLeaveFrame; int MouseButtonsDown;
char* ClipboardTextData; SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
bool MouseCanUseGlobalState; SDL_Cursor* MouseLastCursor;
int MouseLastLeaveFrame;
bool MouseCanUseGlobalState;
// Gamepad handling
ImVector<SDL_GameController*> Gamepads;
ImGui_ImplSDL2_GamepadMode GamepadMode;
bool WantUpdateGamepadsList;
ImGui_ImplSDL2_Data() { memset((void*)this, 0, sizeof(*this)); } ImGui_ImplSDL2_Data() { memset((void*)this, 0, sizeof(*this)); }
}; };
@ -259,6 +272,20 @@ static ImGuiKey ImGui_ImplSDL2_KeycodeToImGuiKey(int keycode)
case SDLK_F10: return ImGuiKey_F10; case SDLK_F10: return ImGuiKey_F10;
case SDLK_F11: return ImGuiKey_F11; case SDLK_F11: return ImGuiKey_F11;
case SDLK_F12: return ImGuiKey_F12; case SDLK_F12: return ImGuiKey_F12;
case SDLK_F13: return ImGuiKey_F13;
case SDLK_F14: return ImGuiKey_F14;
case SDLK_F15: return ImGuiKey_F15;
case SDLK_F16: return ImGuiKey_F16;
case SDLK_F17: return ImGuiKey_F17;
case SDLK_F18: return ImGuiKey_F18;
case SDLK_F19: return ImGuiKey_F19;
case SDLK_F20: return ImGuiKey_F20;
case SDLK_F21: return ImGuiKey_F21;
case SDLK_F22: return ImGuiKey_F22;
case SDLK_F23: return ImGuiKey_F23;
case SDLK_F24: return ImGuiKey_F24;
case SDLK_AC_BACK: return ImGuiKey_AppBack;
case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
} }
return ImGuiKey_None; return ImGuiKey_None;
} }
@ -279,8 +306,9 @@ static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. // If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.
bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
{ {
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
ImGuiIO& io = ImGui::GetIO();
switch (event->type) switch (event->type)
{ {
@ -349,16 +377,22 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
if (window_event == SDL_WINDOWEVENT_ENTER) if (window_event == SDL_WINDOWEVENT_ENTER)
{ {
bd->MouseWindowID = event->window.windowID; bd->MouseWindowID = event->window.windowID;
bd->PendingMouseLeaveFrame = 0; bd->MouseLastLeaveFrame = 0;
} }
if (window_event == SDL_WINDOWEVENT_LEAVE) if (window_event == SDL_WINDOWEVENT_LEAVE)
bd->PendingMouseLeaveFrame = ImGui::GetFrameCount() + 1; bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;
if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED) if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)
io.AddFocusEvent(true); io.AddFocusEvent(true);
else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST) else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)
io.AddFocusEvent(false); io.AddFocusEvent(false);
return true; return true;
} }
case SDL_CONTROLLERDEVICEADDED:
case SDL_CONTROLLERDEVICEREMOVED:
{
bd->WantUpdateGamepadsList = true;
return true;
}
} }
return false; return false;
} }
@ -366,6 +400,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer) static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
// Check and store if we are on a SDL backend that supports global mouse position // Check and store if we are on a SDL backend that supports global mouse position
@ -395,6 +430,10 @@ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer)
io.ClipboardUserData = nullptr; io.ClipboardUserData = nullptr;
io.SetPlatformImeDataFn = ImGui_ImplSDL2_SetPlatformImeData; io.SetPlatformImeDataFn = ImGui_ImplSDL2_SetPlatformImeData;
// Gamepad handling
bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst;
bd->WantUpdateGamepadsList = true;
// Load mouse cursors // Load mouse cursors
bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
@ -477,6 +516,13 @@ bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* rendere
return ImGui_ImplSDL2_Init(window, renderer); return ImGui_ImplSDL2_Init(window, renderer);
} }
bool ImGui_ImplSDL2_InitForOther(SDL_Window* window)
{
return ImGui_ImplSDL2_Init(window, nullptr);
}
static void ImGui_ImplSDL2_CloseGamepads();
void ImGui_ImplSDL2_Shutdown() void ImGui_ImplSDL2_Shutdown()
{ {
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
@ -487,7 +533,7 @@ void ImGui_ImplSDL2_Shutdown()
SDL_free(bd->ClipboardTextData); SDL_free(bd->ClipboardTextData);
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
SDL_FreeCursor(bd->MouseCursors[cursor_n]); SDL_FreeCursor(bd->MouseCursors[cursor_n]);
bd->LastMouseCursor = nullptr; ImGui_ImplSDL2_CloseGamepads();
io.BackendPlatformName = nullptr; io.BackendPlatformName = nullptr;
io.BackendPlatformUserData = nullptr; io.BackendPlatformUserData = nullptr;
@ -543,65 +589,124 @@ static void ImGui_ImplSDL2_UpdateMouseCursor()
{ {
// Show OS mouse cursor // Show OS mouse cursor
SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
if (bd->LastMouseCursor != expected_cursor) if (bd->MouseLastCursor != expected_cursor)
{ {
SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113) SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
bd->LastMouseCursor = expected_cursor; bd->MouseLastCursor = expected_cursor;
} }
SDL_ShowCursor(SDL_TRUE); SDL_ShowCursor(SDL_TRUE);
} }
} }
static void ImGui_ImplSDL2_CloseGamepads()
{
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
if (bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual)
for (SDL_GameController* gamepad : bd->Gamepads)
SDL_GameControllerClose(gamepad);
bd->Gamepads.resize(0);
}
void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array, int manual_gamepads_count)
{
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
ImGui_ImplSDL2_CloseGamepads();
if (mode == ImGui_ImplSDL2_GamepadMode_Manual)
{
IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0);
for (int n = 0; n < manual_gamepads_count; n++)
bd->Gamepads.push_back(manual_gamepads_array[n]);
}
else
{
IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0);
bd->WantUpdateGamepadsList = true;
}
bd->GamepadMode = mode;
}
static void ImGui_ImplSDL2_UpdateGamepadButton(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerButton button_no)
{
bool merged_value = false;
for (SDL_GameController* gamepad : bd->Gamepads)
merged_value |= SDL_GameControllerGetButton(gamepad, button_no) != 0;
io.AddKeyEvent(key, merged_value);
}
static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
static void ImGui_ImplSDL2_UpdateGamepadAnalog(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerAxis axis_no, float v0, float v1)
{
float merged_value = 0.0f;
for (SDL_GameController* gamepad : bd->Gamepads)
{
float vn = Saturate((float)(SDL_GameControllerGetAxis(gamepad, axis_no) - v0) / (float)(v1 - v0));
if (merged_value < vn)
merged_value = vn;
}
io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value);
}
static void ImGui_ImplSDL2_UpdateGamepads() static void ImGui_ImplSDL2_UpdateGamepads()
{ {
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
return;
// Get gamepad // Update list of controller(s) to use
if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual)
{
ImGui_ImplSDL2_CloseGamepads();
int joystick_count = SDL_NumJoysticks();
for (int n = 0; n < joystick_count; n++)
if (SDL_IsGameController(n))
if (SDL_GameController* gamepad = SDL_GameControllerOpen(n))
{
bd->Gamepads.push_back(gamepad);
if (bd->GamepadMode == ImGui_ImplSDL2_GamepadMode_AutoFirst)
break;
}
bd->WantUpdateGamepadsList = false;
}
// FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
SDL_GameController* game_controller = SDL_GameControllerOpen(0); if (bd->Gamepads.Size == 0)
if (!game_controller)
return; return;
io.BackendFlags |= ImGuiBackendFlags_HasGamepad; io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
// Update gamepad inputs // Update gamepad inputs
#define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value.
#define MAP_BUTTON(KEY_NO, BUTTON_NO) { io.AddKeyEvent(KEY_NO, SDL_GameControllerGetButton(game_controller, BUTTON_NO) != 0); } ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_CONTROLLER_BUTTON_START);
#define MAP_ANALOG(KEY_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GameControllerGetAxis(game_controller, AXIS_NO) - V0) / (float)(V1 - V0); vn = IM_SATURATE(vn); io.AddKeyAnalogEvent(KEY_NO, vn > 0.1f, vn); } ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_CONTROLLER_BUTTON_BACK);
const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value. ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_CONTROLLER_BUTTON_X); // Xbox X, PS Square
MAP_BUTTON(ImGuiKey_GamepadStart, SDL_CONTROLLER_BUTTON_START); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_CONTROLLER_BUTTON_B); // Xbox B, PS Circle
MAP_BUTTON(ImGuiKey_GamepadBack, SDL_CONTROLLER_BUTTON_BACK); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_CONTROLLER_BUTTON_Y); // Xbox Y, PS Triangle
MAP_BUTTON(ImGuiKey_GamepadFaceLeft, SDL_CONTROLLER_BUTTON_X); // Xbox X, PS Square ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_CONTROLLER_BUTTON_A); // Xbox A, PS Cross
MAP_BUTTON(ImGuiKey_GamepadFaceRight, SDL_CONTROLLER_BUTTON_B); // Xbox B, PS Circle ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
MAP_BUTTON(ImGuiKey_GamepadFaceUp, SDL_CONTROLLER_BUTTON_Y); // Xbox Y, PS Triangle ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
MAP_BUTTON(ImGuiKey_GamepadFaceDown, SDL_CONTROLLER_BUTTON_A); // Xbox A, PS Cross ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP);
MAP_BUTTON(ImGuiKey_GamepadDpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
MAP_BUTTON(ImGuiKey_GamepadDpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_CONTROLLER_BUTTON_LEFTSHOULDER);
MAP_BUTTON(ImGuiKey_GamepadDpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
MAP_BUTTON(ImGuiKey_GamepadDpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 0.0f, 32767);
MAP_BUTTON(ImGuiKey_GamepadL1, SDL_CONTROLLER_BUTTON_LEFTSHOULDER); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 0.0f, 32767);
MAP_BUTTON(ImGuiKey_GamepadR1, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_CONTROLLER_BUTTON_LEFTSTICK);
MAP_ANALOG(ImGuiKey_GamepadL2, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 0.0f, 32767); ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_CONTROLLER_BUTTON_RIGHTSTICK);
MAP_ANALOG(ImGuiKey_GamepadR2, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 0.0f, 32767); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768);
MAP_BUTTON(ImGuiKey_GamepadL3, SDL_CONTROLLER_BUTTON_LEFTSTICK); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767);
MAP_BUTTON(ImGuiKey_GamepadR3, SDL_CONTROLLER_BUTTON_RIGHTSTICK); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadLStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadLStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_CONTROLLER_AXIS_RIGHTX, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadLStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32768); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_CONTROLLER_AXIS_RIGHTX, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadLStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_CONTROLLER_AXIS_RIGHTY, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadRStickLeft, SDL_CONTROLLER_AXIS_RIGHTX, -thumb_dead_zone, -32768); ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadRStickRight, SDL_CONTROLLER_AXIS_RIGHTX, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadRStickUp, SDL_CONTROLLER_AXIS_RIGHTY, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767);
#undef MAP_BUTTON
#undef MAP_ANALOG
} }
void ImGui_ImplSDL2_NewFrame() void ImGui_ImplSDL2_NewFrame()
{ {
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData(); ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDL2_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing) // Setup display size (every frame to accommodate for window resizing)
@ -627,10 +732,10 @@ void ImGui_ImplSDL2_NewFrame()
io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
bd->Time = current_time; bd->Time = current_time;
if (bd->PendingMouseLeaveFrame && bd->PendingMouseLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0) if (bd->MouseLastLeaveFrame && bd->MouseLastLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
{ {
bd->MouseWindowID = 0; bd->MouseWindowID = 0;
bd->PendingMouseLeaveFrame = 0; bd->MouseLastLeaveFrame = 0;
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
} }
@ -641,6 +746,10 @@ void ImGui_ImplSDL2_NewFrame()
ImGui_ImplSDL2_UpdateGamepads(); ImGui_ImplSDL2_UpdateGamepads();
} }
//-----------------------------------------------------------------------------
#if defined(__clang__) #if defined(__clang__)
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -12,14 +12,19 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct SDL_Window; struct SDL_Window;
struct SDL_Renderer; struct SDL_Renderer;
struct _SDL_GameController;
typedef union SDL_Event SDL_Event; typedef union SDL_Event SDL_Event;
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context);
@ -27,10 +32,14 @@ IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOther(SDL_Window* window);
IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown();
IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame();
IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event); IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event);
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this.
static inline void ImGui_ImplSDL2_NewFrame(SDL_Window*) { ImGui_ImplSDL2_NewFrame(); } // 1.84: removed unnecessary parameter // When using manual mode, caller is responsible for opening/closing gamepad.
#endif enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual };
IMGUI_IMPL_API void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = NULL, int manual_gamepads_count = -1);
#endif // #ifndef IMGUI_DISABLE

View File

@ -10,15 +10,22 @@
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// Missing features: // Missing features:
// [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()!. // [ ] Platform: IME SUPPORT IS BROKEN IN SDL3 BECAUSE INPUTS GETS SENT TO BOTH APP AND IME + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2024-04-15: Inputs: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput() as SDL3 no longer enables it by default and should play nicer with IME.
// 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode().
// 2023-11-13: Updated for recent SDL3 API changes.
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
// 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391) // 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391)
// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306) // 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702) // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
@ -26,6 +33,7 @@
// 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog. // 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_sdl3.h" #include "imgui_impl_sdl3.h"
// Clang warnings with -Weverything // Clang warnings with -Weverything
@ -36,10 +44,15 @@
// SDL // SDL
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <SDL3/SDL_syswm.h>
#if defined(__APPLE__) #if defined(__APPLE__)
#include <TargetConditionals.h> #include <TargetConditionals.h>
#endif #endif
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#endif
#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__) #if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1 #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
@ -47,19 +60,34 @@
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0 #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0
#endif #endif
// FIXME-LEGACY: remove when SDL 3.1.3 preview is released.
#ifndef SDLK_APOSTROPHE
#define SDLK_APOSTROPHE SDLK_QUOTE
#endif
#ifndef SDLK_GRAVE
#define SDLK_GRAVE SDLK_BACKQUOTE
#endif
// SDL Data // SDL Data
struct ImGui_ImplSDL3_Data struct ImGui_ImplSDL3_Data
{ {
SDL_Window* Window; SDL_Window* Window;
SDL_Renderer* Renderer; SDL_Renderer* Renderer;
Uint64 Time; Uint64 Time;
Uint32 MouseWindowID; char* ClipboardTextData;
int MouseButtonsDown;
SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT]; // Mouse handling
SDL_Cursor* LastMouseCursor; Uint32 MouseWindowID;
int PendingMouseLeaveFrame; int MouseButtonsDown;
char* ClipboardTextData; SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
bool MouseCanUseGlobalState; SDL_Cursor* MouseLastCursor;
int MousePendingLeaveFrame;
bool MouseCanUseGlobalState;
// Gamepad handling
ImVector<SDL_Gamepad*> Gamepads;
ImGui_ImplSDL3_GamepadMode GamepadMode;
bool WantUpdateGamepadsList;
ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); } ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); }
}; };
@ -98,6 +126,11 @@ static void ImGui_ImplSDL3_SetPlatformImeData(ImGuiViewport*, ImGuiPlatformImeDa
r.w = 1; r.w = 1;
r.h = (int)data->InputLineHeight; r.h = (int)data->InputLineHeight;
SDL_SetTextInputRect(&r); SDL_SetTextInputRect(&r);
SDL_StartTextInput();
}
else
{
SDL_StopTextInput();
} }
} }
@ -120,7 +153,7 @@ static ImGuiKey ImGui_ImplSDL3_KeycodeToImGuiKey(int keycode)
case SDLK_SPACE: return ImGuiKey_Space; case SDLK_SPACE: return ImGuiKey_Space;
case SDLK_RETURN: return ImGuiKey_Enter; case SDLK_RETURN: return ImGuiKey_Enter;
case SDLK_ESCAPE: return ImGuiKey_Escape; case SDLK_ESCAPE: return ImGuiKey_Escape;
case SDLK_QUOTE: return ImGuiKey_Apostrophe; case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe;
case SDLK_COMMA: return ImGuiKey_Comma; case SDLK_COMMA: return ImGuiKey_Comma;
case SDLK_MINUS: return ImGuiKey_Minus; case SDLK_MINUS: return ImGuiKey_Minus;
case SDLK_PERIOD: return ImGuiKey_Period; case SDLK_PERIOD: return ImGuiKey_Period;
@ -130,7 +163,7 @@ static ImGuiKey ImGui_ImplSDL3_KeycodeToImGuiKey(int keycode)
case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket; case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
case SDLK_BACKSLASH: return ImGuiKey_Backslash; case SDLK_BACKSLASH: return ImGuiKey_Backslash;
case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket; case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent; case SDLK_GRAVE: return ImGuiKey_GraveAccent;
case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
@ -210,6 +243,20 @@ static ImGuiKey ImGui_ImplSDL3_KeycodeToImGuiKey(int keycode)
case SDLK_F10: return ImGuiKey_F10; case SDLK_F10: return ImGuiKey_F10;
case SDLK_F11: return ImGuiKey_F11; case SDLK_F11: return ImGuiKey_F11;
case SDLK_F12: return ImGuiKey_F12; case SDLK_F12: return ImGuiKey_F12;
case SDLK_F13: return ImGuiKey_F13;
case SDLK_F14: return ImGuiKey_F14;
case SDLK_F15: return ImGuiKey_F15;
case SDLK_F16: return ImGuiKey_F16;
case SDLK_F17: return ImGuiKey_F17;
case SDLK_F18: return ImGuiKey_F18;
case SDLK_F19: return ImGuiKey_F19;
case SDLK_F20: return ImGuiKey_F20;
case SDLK_F21: return ImGuiKey_F21;
case SDLK_F22: return ImGuiKey_F22;
case SDLK_F23: return ImGuiKey_F23;
case SDLK_F24: return ImGuiKey_F24;
case SDLK_AC_BACK: return ImGuiKey_AppBack;
case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
} }
return ImGuiKey_None; return ImGuiKey_None;
} }
@ -230,8 +277,9 @@ static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field. // If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.
bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event) bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
{ {
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?");
ImGuiIO& io = ImGui::GetIO();
switch (event->type) switch (event->type)
{ {
@ -287,7 +335,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
case SDL_EVENT_WINDOW_MOUSE_ENTER: case SDL_EVENT_WINDOW_MOUSE_ENTER:
{ {
bd->MouseWindowID = event->window.windowID; bd->MouseWindowID = event->window.windowID;
bd->PendingMouseLeaveFrame = 0; bd->MousePendingLeaveFrame = 0;
return true; return true;
} }
// - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late, // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,
@ -296,7 +344,7 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
// FIXME: Unconfirmed whether this is still needed with SDL3. // FIXME: Unconfirmed whether this is still needed with SDL3.
case SDL_EVENT_WINDOW_MOUSE_LEAVE: case SDL_EVENT_WINDOW_MOUSE_LEAVE:
{ {
bd->PendingMouseLeaveFrame = ImGui::GetFrameCount() + 1; bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1;
return true; return true;
} }
case SDL_EVENT_WINDOW_FOCUS_GAINED: case SDL_EVENT_WINDOW_FOCUS_GAINED:
@ -305,14 +353,33 @@ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
case SDL_EVENT_WINDOW_FOCUS_LOST: case SDL_EVENT_WINDOW_FOCUS_LOST:
io.AddFocusEvent(false); io.AddFocusEvent(false);
return true; return true;
case SDL_EVENT_GAMEPAD_ADDED:
case SDL_EVENT_GAMEPAD_REMOVED:
{
bd->WantUpdateGamepadsList = true;
return true;
}
} }
return false; return false;
} }
static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer) static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window)
{
IM_UNUSED(window);
viewport->PlatformHandleRaw = nullptr;
#if defined(__WIN32__) && !defined(__WINRT__)
viewport->PlatformHandleRaw = (HWND)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.win32.hwnd", nullptr);
#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
viewport->PlatformHandleRaw = (void*)SDL_GetProperty(SDL_GetWindowProperties(window), "SDL.window.cocoa.window", nullptr);
#endif
}
static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
IM_UNUSED(sdl_gl_context); // Unused in this branch
// Check and store if we are on a SDL backend that supports global mouse position // Check and store if we are on a SDL backend that supports global mouse position
// ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list) // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
@ -341,6 +408,10 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer)
io.ClipboardUserData = nullptr; io.ClipboardUserData = nullptr;
io.SetPlatformImeDataFn = ImGui_ImplSDL3_SetPlatformImeData; io.SetPlatformImeDataFn = ImGui_ImplSDL3_SetPlatformImeData;
// Gamepad handling
bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst;
bd->WantUpdateGamepadsList = true;
// Load mouse cursors // Load mouse cursors
bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM); bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
@ -355,16 +426,7 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer)
// Set platform dependent data in viewport // Set platform dependent data in viewport
// Our mouse update function expect PlatformHandle to be filled for the main viewport // Our mouse update function expect PlatformHandle to be filled for the main viewport
ImGuiViewport* main_viewport = ImGui::GetMainViewport(); ImGuiViewport* main_viewport = ImGui::GetMainViewport();
main_viewport->PlatformHandleRaw = nullptr; ImGui_ImplSDL3_SetupPlatformHandles(main_viewport, window);
SDL_SysWMinfo info;
if (SDL_GetWindowWMInfo(window, &info, SDL_SYSWM_CURRENT_VERSION) == 0)
{
#if defined(SDL_ENABLE_SYSWM_WINDOWS)
main_viewport->PlatformHandleRaw = (void*)info.info.win.window;
#elif defined(__APPLE__) && defined(SDL_ENABLE_SYSWM_COCOA)
main_viewport->PlatformHandleRaw = (void*)info.info.cocoa.window;
#endif
}
// From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event. // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event.
// Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered. // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered.
@ -386,12 +448,12 @@ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer)
bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context) bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
{ {
IM_UNUSED(sdl_gl_context); // Viewport branch will need this. IM_UNUSED(sdl_gl_context); // Viewport branch will need this.
return ImGui_ImplSDL3_Init(window, nullptr); return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context);
} }
bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window) bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window)
{ {
return ImGui_ImplSDL3_Init(window, nullptr); return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
} }
bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window) bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window)
@ -399,19 +461,26 @@ bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window)
#if !defined(_WIN32) #if !defined(_WIN32)
IM_ASSERT(0 && "Unsupported"); IM_ASSERT(0 && "Unsupported");
#endif #endif
return ImGui_ImplSDL3_Init(window, nullptr); return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
} }
bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window) bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window)
{ {
return ImGui_ImplSDL3_Init(window, nullptr); return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
} }
bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer) bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer)
{ {
return ImGui_ImplSDL3_Init(window, renderer); return ImGui_ImplSDL3_Init(window, renderer, nullptr);
} }
bool ImGui_ImplSDL3_InitForOther(SDL_Window* window)
{
return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
}
static void ImGui_ImplSDL3_CloseGamepads();
void ImGui_ImplSDL3_Shutdown() void ImGui_ImplSDL3_Shutdown()
{ {
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
@ -422,7 +491,7 @@ void ImGui_ImplSDL3_Shutdown()
SDL_free(bd->ClipboardTextData); SDL_free(bd->ClipboardTextData);
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++) for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
SDL_DestroyCursor(bd->MouseCursors[cursor_n]); SDL_DestroyCursor(bd->MouseCursors[cursor_n]);
bd->LastMouseCursor = nullptr; ImGui_ImplSDL3_CloseGamepads();
io.BackendPlatformName = nullptr; io.BackendPlatformName = nullptr;
io.BackendPlatformUserData = nullptr; io.BackendPlatformUserData = nullptr;
@ -481,65 +550,125 @@ static void ImGui_ImplSDL3_UpdateMouseCursor()
{ {
// Show OS mouse cursor // Show OS mouse cursor
SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]; SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
if (bd->LastMouseCursor != expected_cursor) if (bd->MouseLastCursor != expected_cursor)
{ {
SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113) SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
bd->LastMouseCursor = expected_cursor; bd->MouseLastCursor = expected_cursor;
} }
SDL_ShowCursor(); SDL_ShowCursor();
} }
} }
static void ImGui_ImplSDL3_CloseGamepads()
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
if (bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual)
for (SDL_Gamepad* gamepad : bd->Gamepads)
SDL_CloseGamepad(gamepad);
bd->Gamepads.resize(0);
}
void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count)
{
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
ImGui_ImplSDL3_CloseGamepads();
if (mode == ImGui_ImplSDL3_GamepadMode_Manual)
{
IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0);
for (int n = 0; n < manual_gamepads_count; n++)
bd->Gamepads.push_back(manual_gamepads_array[n]);
}
else
{
IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0);
bd->WantUpdateGamepadsList = true;
}
bd->GamepadMode = mode;
}
static void ImGui_ImplSDL3_UpdateGamepadButton(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadButton button_no)
{
bool merged_value = false;
for (SDL_Gamepad* gamepad : bd->Gamepads)
merged_value |= SDL_GetGamepadButton(gamepad, button_no) != 0;
io.AddKeyEvent(key, merged_value);
}
static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
static void ImGui_ImplSDL3_UpdateGamepadAnalog(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadAxis axis_no, float v0, float v1)
{
float merged_value = 0.0f;
for (SDL_Gamepad* gamepad : bd->Gamepads)
{
float vn = Saturate((float)(SDL_GetGamepadAxis(gamepad, axis_no) - v0) / (float)(v1 - v0));
if (merged_value < vn)
merged_value = vn;
}
io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value);
}
static void ImGui_ImplSDL3_UpdateGamepads() static void ImGui_ImplSDL3_UpdateGamepads()
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
return;
// Get gamepad // Update list of gamepads to use
if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual)
{
ImGui_ImplSDL3_CloseGamepads();
int sdl_gamepads_count = 0;
SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count);
for (int n = 0; n < sdl_gamepads_count; n++)
if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n]))
{
bd->Gamepads.push_back(gamepad);
if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst)
break;
}
SDL_free(sdl_gamepads);
bd->WantUpdateGamepadsList = false;
}
// FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
return;
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
SDL_Gamepad* gamepad = SDL_OpenGamepad(0); if (bd->Gamepads.Size == 0)
if (!gamepad)
return; return;
io.BackendFlags |= ImGuiBackendFlags_HasGamepad; io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
// Update gamepad inputs // Update gamepad inputs
#define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) const int thumb_dead_zone = 8000; // SDL_gamepad.h suggests using this value.
#define MAP_BUTTON(KEY_NO, BUTTON_NO) { io.AddKeyEvent(KEY_NO, SDL_GetGamepadButton(gamepad, BUTTON_NO) != 0); } ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START);
#define MAP_ANALOG(KEY_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GetGamepadAxis(gamepad, AXIS_NO) - V0) / (float)(V1 - V0); vn = IM_SATURATE(vn); io.AddKeyAnalogEvent(KEY_NO, vn > 0.1f, vn); } ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK);
const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value. ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_WEST); // Xbox X, PS Square
MAP_BUTTON(ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_EAST); // Xbox B, PS Circle
MAP_BUTTON(ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_NORTH); // Xbox Y, PS Triangle
MAP_BUTTON(ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_X); // Xbox X, PS Square ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_SOUTH); // Xbox A, PS Cross
MAP_BUTTON(ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_B); // Xbox B, PS Circle ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT);
MAP_BUTTON(ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_Y); // Xbox Y, PS Triangle ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
MAP_BUTTON(ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_A); // Xbox A, PS Cross ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP);
MAP_BUTTON(ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN);
MAP_BUTTON(ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);
MAP_BUTTON(ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
MAP_BUTTON(ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767);
MAP_BUTTON(ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767);
MAP_BUTTON(ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK);
MAP_ANALOG(ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767); ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK);
MAP_ANALOG(ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768);
MAP_BUTTON(ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767);
MAP_BUTTON(ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768); ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767);
#undef MAP_BUTTON
#undef MAP_ANALOG
} }
void ImGui_ImplSDL3_NewFrame() void ImGui_ImplSDL3_NewFrame()
{ {
ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData(); ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDL3_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?");
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing) // Setup display size (every frame to accommodate for window resizing)
@ -562,10 +691,10 @@ void ImGui_ImplSDL3_NewFrame()
io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f); io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
bd->Time = current_time; bd->Time = current_time;
if (bd->PendingMouseLeaveFrame && bd->PendingMouseLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0) if (bd->MousePendingLeaveFrame && bd->MousePendingLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
{ {
bd->MouseWindowID = 0; bd->MouseWindowID = 0;
bd->PendingMouseLeaveFrame = 0; bd->MousePendingLeaveFrame = 0;
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
} }
@ -576,7 +705,10 @@ void ImGui_ImplSDL3_NewFrame()
ImGui_ImplSDL3_UpdateGamepads(); ImGui_ImplSDL3_UpdateGamepads();
} }
//-----------------------------------------------------------------------------
#if defined(__clang__) #if defined(__clang__)
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -10,18 +10,23 @@
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// Missing features: // Missing features:
// [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()!. // [ ] Platform: IME SUPPORT IS BROKEN IN SDL3 BECAUSE INPUTS GETS SENT TO BOTH APP AND IME + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct SDL_Window; struct SDL_Window;
struct SDL_Renderer; struct SDL_Renderer;
struct SDL_Gamepad;
typedef union SDL_Event SDL_Event; typedef union SDL_Event SDL_Event;
IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context);
@ -29,6 +34,14 @@ IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer); IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer);
IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOther(SDL_Window* window);
IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame();
IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event); IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event);
// Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this.
// When using manual mode, caller is responsible for opening/closing gamepad.
enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual };
IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = NULL, int manual_gamepads_count = -1);
#endif // #ifndef IMGUI_DISABLE

View File

@ -12,10 +12,15 @@
// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter.
// 2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3. // 2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3.
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 2021-12-21: Update SDL_RenderGeometryRaw() format to work with SDL 2.0.19. // 2021-12-21: Update SDL_RenderGeometryRaw() format to work with SDL 2.0.19.
@ -24,12 +29,9 @@
// 2021-09-21: Initial version. // 2021-09-21: Initial version.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_sdlrenderer2.h" #include "imgui_impl_sdlrenderer2.h"
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t #include <stdint.h> // intptr_t
#endif
// Clang warnings with -Weverything // Clang warnings with -Weverything
#if defined(__clang__) #if defined(__clang__)
@ -46,9 +48,9 @@
// SDL_Renderer data // SDL_Renderer data
struct ImGui_ImplSDLRenderer2_Data struct ImGui_ImplSDLRenderer2_Data
{ {
SDL_Renderer* SDLRenderer; SDL_Renderer* Renderer; // Main viewport's renderer
SDL_Texture* FontTexture; SDL_Texture* FontTexture;
ImGui_ImplSDLRenderer2_Data() { memset((void*)this, 0, sizeof(*this)); } ImGui_ImplSDLRenderer2_Data() { memset((void*)this, 0, sizeof(*this)); }
}; };
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
@ -62,6 +64,7 @@ static ImGui_ImplSDLRenderer2_Data* ImGui_ImplSDLRenderer2_GetBackendData()
bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer) bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!"); IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!");
@ -71,7 +74,7 @@ bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer)
io.BackendRendererName = "imgui_impl_sdlrenderer2"; io.BackendRendererName = "imgui_impl_sdlrenderer2";
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
bd->SDLRenderer = renderer; bd->Renderer = renderer;
return true; return true;
} }
@ -90,35 +93,31 @@ void ImGui_ImplSDLRenderer2_Shutdown()
IM_DELETE(bd); IM_DELETE(bd);
} }
static void ImGui_ImplSDLRenderer2_SetupRenderState() static void ImGui_ImplSDLRenderer2_SetupRenderState(SDL_Renderer* renderer)
{ {
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
// Clear out any viewports and cliprect set by the user // Clear out any viewports and cliprect set by the user
// FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
SDL_RenderSetViewport(bd->SDLRenderer, nullptr); SDL_RenderSetViewport(renderer, nullptr);
SDL_RenderSetClipRect(bd->SDLRenderer, nullptr); SDL_RenderSetClipRect(renderer, nullptr);
} }
void ImGui_ImplSDLRenderer2_NewFrame() void ImGui_ImplSDLRenderer2_NewFrame()
{ {
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData(); ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDLRenderer2_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer2_Init()?");
if (!bd->FontTexture) if (!bd->FontTexture)
ImGui_ImplSDLRenderer2_CreateDeviceObjects(); ImGui_ImplSDLRenderer2_CreateDeviceObjects();
} }
void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data) void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer)
{ {
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
// If there's a scale factor set by the user, use that instead // If there's a scale factor set by the user, use that instead
// If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass
// to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here.
float rsx = 1.0f; float rsx = 1.0f;
float rsy = 1.0f; float rsy = 1.0f;
SDL_RenderGetScale(bd->SDLRenderer, &rsx, &rsy); SDL_RenderGetScale(renderer, &rsx, &rsy);
ImVec2 render_scale; ImVec2 render_scale;
render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
@ -137,16 +136,16 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data)
SDL_Rect ClipRect; SDL_Rect ClipRect;
}; };
BackupSDLRendererState old = {}; BackupSDLRendererState old = {};
old.ClipEnabled = SDL_RenderIsClipEnabled(bd->SDLRenderer) == SDL_TRUE; old.ClipEnabled = SDL_RenderIsClipEnabled(renderer) == SDL_TRUE;
SDL_RenderGetViewport(bd->SDLRenderer, &old.Viewport); SDL_RenderGetViewport(renderer, &old.Viewport);
SDL_RenderGetClipRect(bd->SDLRenderer, &old.ClipRect); SDL_RenderGetClipRect(renderer, &old.ClipRect);
// Will project scissor/clipping rectangles into framebuffer space // Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = render_scale; ImVec2 clip_scale = render_scale;
// Render command lists // Render command lists
ImGui_ImplSDLRenderer2_SetupRenderState(); ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
for (int n = 0; n < draw_data->CmdListsCount; n++) for (int n = 0; n < draw_data->CmdListsCount; n++)
{ {
const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawList* cmd_list = draw_data->CmdLists[n];
@ -161,7 +160,7 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data)
// User callback, registered via ImDrawList::AddCallback() // User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplSDLRenderer2_SetupRenderState(); ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
else else
pcmd->UserCallback(cmd_list, pcmd); pcmd->UserCallback(cmd_list, pcmd);
} }
@ -178,19 +177,19 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data)
continue; continue;
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) }; 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) };
SDL_RenderSetClipRect(bd->SDLRenderer, &r); SDL_RenderSetClipRect(renderer, &r);
const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, pos)); const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos));
const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, uv)); const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv));
#if SDL_VERSION_ATLEAST(2,0,19) #if SDL_VERSION_ATLEAST(2,0,19)
const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, col)); // SDL 2.0.19+ const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+
#else #else
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 const int* color = (const int*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.17 and 2.0.18
#endif #endif
// Bind texture, Draw // Bind texture, Draw
SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
SDL_RenderGeometryRaw(bd->SDLRenderer, tex, SDL_RenderGeometryRaw(renderer, tex,
xy, (int)sizeof(ImDrawVert), xy, (int)sizeof(ImDrawVert),
color, (int)sizeof(ImDrawVert), color, (int)sizeof(ImDrawVert),
uv, (int)sizeof(ImDrawVert), uv, (int)sizeof(ImDrawVert),
@ -201,8 +200,8 @@ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data)
} }
// Restore modified SDL_Renderer state // Restore modified SDL_Renderer state
SDL_RenderSetViewport(bd->SDLRenderer, &old.Viewport); SDL_RenderSetViewport(renderer, &old.Viewport);
SDL_RenderSetClipRect(bd->SDLRenderer, old.ClipEnabled ? &old.ClipRect : nullptr); SDL_RenderSetClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr);
} }
// Called by Init/NewFrame/Shutdown // Called by Init/NewFrame/Shutdown
@ -218,7 +217,7 @@ bool ImGui_ImplSDLRenderer2_CreateFontsTexture()
// Upload texture to graphics system // Upload texture to graphics system
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height);
if (bd->FontTexture == nullptr) if (bd->FontTexture == nullptr)
{ {
SDL_Log("error creating texture"); SDL_Log("error creating texture");
@ -256,6 +255,10 @@ void ImGui_ImplSDLRenderer2_DestroyDeviceObjects()
ImGui_ImplSDLRenderer2_DestroyFontsTexture(); ImGui_ImplSDLRenderer2_DestroyFontsTexture();
} }
//-----------------------------------------------------------------------------
#if defined(__clang__) #if defined(__clang__)
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -11,7 +11,16 @@
// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#ifndef IMGUI_DISABLE
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
struct SDL_Renderer; struct SDL_Renderer;
@ -19,10 +28,12 @@ struct SDL_Renderer;
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer); IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer);
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_Shutdown();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer);
// Called by Init/NewFrame/Shutdown // Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyFontsTexture(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -12,19 +12,22 @@
// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter.
// 2024-02-12: Amend to query SDL_RenderViewportSet() and restore viewport accordingly.
// 2023-05-30: Initial version. // 2023-05-30: Initial version.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_sdlrenderer3.h" #include "imgui_impl_sdlrenderer3.h"
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t #include <stdint.h> // intptr_t
#endif
// Clang warnings with -Weverything // Clang warnings with -Weverything
#if defined(__clang__) #if defined(__clang__)
@ -41,9 +44,9 @@
// SDL_Renderer data // SDL_Renderer data
struct ImGui_ImplSDLRenderer3_Data struct ImGui_ImplSDLRenderer3_Data
{ {
SDL_Renderer* SDLRenderer; SDL_Renderer* Renderer; // Main viewport's renderer
SDL_Texture* FontTexture; SDL_Texture* FontTexture;
ImGui_ImplSDLRenderer3_Data() { memset((void*)this, 0, sizeof(*this)); } ImGui_ImplSDLRenderer3_Data() { memset((void*)this, 0, sizeof(*this)); }
}; };
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
@ -57,6 +60,7 @@ static ImGui_ImplSDLRenderer3_Data* ImGui_ImplSDLRenderer3_GetBackendData()
bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer) bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!"); IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!");
@ -66,7 +70,7 @@ bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer)
io.BackendRendererName = "imgui_impl_sdlrenderer3"; io.BackendRendererName = "imgui_impl_sdlrenderer3";
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
bd->SDLRenderer = renderer; bd->Renderer = renderer;
return true; return true;
} }
@ -85,35 +89,31 @@ void ImGui_ImplSDLRenderer3_Shutdown()
IM_DELETE(bd); IM_DELETE(bd);
} }
static void ImGui_ImplSDLRenderer3_SetupRenderState() static void ImGui_ImplSDLRenderer3_SetupRenderState(SDL_Renderer* renderer)
{ {
ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData();
// Clear out any viewports and cliprect set by the user // Clear out any viewports and cliprect set by the user
// FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process. // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
SDL_SetRenderViewport(bd->SDLRenderer, nullptr); SDL_SetRenderViewport(renderer, nullptr);
SDL_SetRenderClipRect(bd->SDLRenderer, nullptr); SDL_SetRenderClipRect(renderer, nullptr);
} }
void ImGui_ImplSDLRenderer3_NewFrame() void ImGui_ImplSDLRenderer3_NewFrame()
{ {
ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData(); ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDLRenderer3_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer3_Init()?");
if (!bd->FontTexture) if (!bd->FontTexture)
ImGui_ImplSDLRenderer3_CreateDeviceObjects(); ImGui_ImplSDLRenderer3_CreateDeviceObjects();
} }
void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data) void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer)
{ {
ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData();
// If there's a scale factor set by the user, use that instead // If there's a scale factor set by the user, use that instead
// If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass
// to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here. // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here.
float rsx = 1.0f; float rsx = 1.0f;
float rsy = 1.0f; float rsy = 1.0f;
SDL_GetRenderScale(bd->SDLRenderer, &rsx, &rsy); SDL_GetRenderScale(renderer, &rsx, &rsy);
ImVec2 render_scale; ImVec2 render_scale;
render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f; render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f; render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
@ -128,20 +128,22 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data)
struct BackupSDLRendererState struct BackupSDLRendererState
{ {
SDL_Rect Viewport; SDL_Rect Viewport;
bool ViewportEnabled;
bool ClipEnabled; bool ClipEnabled;
SDL_Rect ClipRect; SDL_Rect ClipRect;
}; };
BackupSDLRendererState old = {}; BackupSDLRendererState old = {};
old.ClipEnabled = SDL_RenderClipEnabled(bd->SDLRenderer) == SDL_TRUE; old.ViewportEnabled = SDL_RenderViewportSet(renderer) == SDL_TRUE;
SDL_GetRenderViewport(bd->SDLRenderer, &old.Viewport); old.ClipEnabled = SDL_RenderClipEnabled(renderer) == SDL_TRUE;
SDL_GetRenderClipRect(bd->SDLRenderer, &old.ClipRect); SDL_GetRenderViewport(renderer, &old.Viewport);
SDL_GetRenderClipRect(renderer, &old.ClipRect);
// Will project scissor/clipping rectangles into framebuffer space // Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = render_scale; ImVec2 clip_scale = render_scale;
// Render command lists // Render command lists
ImGui_ImplSDLRenderer3_SetupRenderState(); ImGui_ImplSDLRenderer3_SetupRenderState(renderer);
for (int n = 0; n < draw_data->CmdListsCount; n++) for (int n = 0; n < draw_data->CmdListsCount; n++)
{ {
const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawList* cmd_list = draw_data->CmdLists[n];
@ -156,7 +158,7 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data)
// User callback, registered via ImDrawList::AddCallback() // User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplSDLRenderer3_SetupRenderState(); ImGui_ImplSDLRenderer3_SetupRenderState(renderer);
else else
pcmd->UserCallback(cmd_list, pcmd); pcmd->UserCallback(cmd_list, pcmd);
} }
@ -173,19 +175,15 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data)
continue; continue;
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) }; 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) };
SDL_SetRenderClipRect(bd->SDLRenderer, &r); SDL_SetRenderClipRect(renderer, &r);
const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, pos)); const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos));
const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, uv)); const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv));
#if SDL_VERSION_ATLEAST(2,0,19) const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+
const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + IM_OFFSETOF(ImDrawVert, col)); // SDL 2.0.19+
#else
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
#endif
// Bind texture, Draw // Bind texture, Draw
SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID(); SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
SDL_RenderGeometryRaw(bd->SDLRenderer, tex, SDL_RenderGeometryRaw(renderer, tex,
xy, (int)sizeof(ImDrawVert), xy, (int)sizeof(ImDrawVert),
color, (int)sizeof(ImDrawVert), color, (int)sizeof(ImDrawVert),
uv, (int)sizeof(ImDrawVert), uv, (int)sizeof(ImDrawVert),
@ -196,8 +194,8 @@ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data)
} }
// Restore modified SDL_Renderer state // Restore modified SDL_Renderer state
SDL_SetRenderViewport(bd->SDLRenderer, &old.Viewport); SDL_SetRenderViewport(renderer, old.ViewportEnabled ? &old.Viewport : nullptr);
SDL_SetRenderClipRect(bd->SDLRenderer, old.ClipEnabled ? &old.ClipRect : nullptr); SDL_SetRenderClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr);
} }
// Called by Init/NewFrame/Shutdown // Called by Init/NewFrame/Shutdown
@ -213,7 +211,7 @@ bool ImGui_ImplSDLRenderer3_CreateFontsTexture()
// Upload texture to graphics system // Upload texture to graphics system
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
bd->FontTexture = SDL_CreateTexture(bd->SDLRenderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height); bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height);
if (bd->FontTexture == nullptr) if (bd->FontTexture == nullptr)
{ {
SDL_Log("error creating texture"); SDL_Log("error creating texture");
@ -251,6 +249,10 @@ void ImGui_ImplSDLRenderer3_DestroyDeviceObjects()
ImGui_ImplSDLRenderer3_DestroyFontsTexture(); ImGui_ImplSDLRenderer3_DestroyFontsTexture();
} }
//-----------------------------------------------------------------------------
#if defined(__clang__) #if defined(__clang__)
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -11,18 +11,29 @@
// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID! // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
// [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices.
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
struct SDL_Renderer; struct SDL_Renderer;
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer); IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer);
IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_Shutdown(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_NewFrame(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_NewFrame();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer);
// Called by Init/NewFrame/Shutdown // Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateFontsTexture(); IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyFontsTexture(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -13,14 +13,17 @@
// - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!) // - [Solution 3] IDE/msbuild: edit imconfig.h and add '#define ImTextureID ImU64' (prefer solution 2 to create your own config file!)
// - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in our batch files) // - [Solution 4] command-line: add '/D ImTextureID=ImU64' to your cl.exe command-line (this is what we do in our batch files)
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
// You will use those if you want to use this rendering backend in your engine/app. // You will use those if you want to use this rendering backend in your engine/app.
@ -30,10 +33,23 @@
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2024-04-19: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define (you can also use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().)
// 2024-02-14: *BREAKING CHANGE*: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering.
// 2024-02-12: *BREAKING CHANGE*: Dynamic rendering now require filling PipelineRenderingCreateInfo structure.
// 2024-01-19: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236)
// 2024-01-11: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size (#3957). Fixed MinAllocationSize handing (#7189).
// 2024-01-03: Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous "best practice" validation layer. (#7189, #4238)
// 2024-01-03: Vulkan: Stopped creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT as we don't reset them.
// 2023-11-29: Vulkan: Fixed mismatching allocator passed to vkCreateCommandPool() vs vkDestroyCommandPool(). (#7075)
// 2023-11-10: *BREAKING CHANGE*: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own command-buffer to upload fonts.
// *BREAKING CHANGE*: Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unnecessary as we create and destroy those objects in the backend.
// ImGui_ImplVulkan_CreateFontsTexture() is automatically called by NewFrame() the first time.
// You can call ImGui_ImplVulkan_CreateFontsTexture() again to recreate the font atlas texture.
// Added ImGui_ImplVulkan_DestroyFontsTexture() but you probably never need to call this.
// 2023-07-04: Vulkan: Added optional support for VK_KHR_dynamic_rendering. User needs to set init_info->UseDynamicRendering = true and init_info->ColorAttachmentFormat. // 2023-07-04: Vulkan: Added optional support for VK_KHR_dynamic_rendering. User needs to set init_info->UseDynamicRendering = true and init_info->ColorAttachmentFormat.
// 2023-01-02: Vulkan: Fixed sampler passed to ImGui_ImplVulkan_AddTexture() not being honored + removed a bunch of duplicate code. // 2023-01-02: Vulkan: Fixed sampler passed to ImGui_ImplVulkan_AddTexture() not being honored + removed a bunch of duplicate code.
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 2022-10-04: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symetry. (#914, #5738). // 2022-10-04: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symmetry. (#914, #5738).
// 2022-01-20: Vulkan: Added support for ImTextureID as VkDescriptorSet. User need to call ImGui_ImplVulkan_AddTexture(). Building for 32-bit targets requires '#define ImTextureID ImU64'. (#914). // 2022-01-20: Vulkan: Added support for ImTextureID as VkDescriptorSet. User need to call ImGui_ImplVulkan_AddTexture(). Building for 32-bit targets requires '#define ImTextureID ImU64'. (#914).
// 2021-10-15: Vulkan: Call vkCmdSetScissor() at the end of render a full-viewport to reduce likehood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame. // 2021-10-15: Vulkan: Call vkCmdSetScissor() at the end of render a full-viewport to reduce likehood of issues with people using VK_DYNAMIC_STATE_SCISSOR in their app without calling vkCmdSetScissor() explicitly every frame.
// 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). // 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).
@ -66,90 +82,45 @@
// 2016-10-18: Vulkan: Add location decorators & change to use structs as in/out in glsl, update embedded spv (produced with glslangValidator -x). Null the released resources. // 2016-10-18: Vulkan: Add location decorators & change to use structs as in/out in glsl, update embedded spv (produced with glslangValidator -x). Null the released resources.
// 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active. // 2016-08-27: Vulkan: Fix Vulkan example for use when a depth buffer is active.
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_vulkan.h" #include "imgui_impl_vulkan.h"
#include <stdio.h> #include <stdio.h>
#ifndef IM_MAX
#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B))
#endif
// Visual Studio warnings // Visual Studio warnings
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4127) // condition expression is constant
#endif #endif
// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData()
// [Please zero-clear before use!]
struct ImGui_ImplVulkanH_FrameRenderBuffers
{
VkDeviceMemory VertexBufferMemory;
VkDeviceMemory IndexBufferMemory;
VkDeviceSize VertexBufferSize;
VkDeviceSize IndexBufferSize;
VkBuffer VertexBuffer;
VkBuffer IndexBuffer;
};
// Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers
// [Please zero-clear before use!]
struct ImGui_ImplVulkanH_WindowRenderBuffers
{
uint32_t Index;
uint32_t Count;
ImGui_ImplVulkanH_FrameRenderBuffers* FrameRenderBuffers;
};
// Vulkan data
struct ImGui_ImplVulkan_Data
{
ImGui_ImplVulkan_InitInfo VulkanInitInfo;
VkRenderPass RenderPass;
VkDeviceSize BufferMemoryAlignment;
VkPipelineCreateFlags PipelineCreateFlags;
VkDescriptorSetLayout DescriptorSetLayout;
VkPipelineLayout PipelineLayout;
VkPipeline Pipeline;
uint32_t Subpass;
VkShaderModule ShaderModuleVert;
VkShaderModule ShaderModuleFrag;
// Font data
VkSampler FontSampler;
VkDeviceMemory FontMemory;
VkImage FontImage;
VkImageView FontView;
VkDescriptorSet FontDescriptorSet;
VkDeviceMemory UploadBufferMemory;
VkBuffer UploadBuffer;
// Render buffers for main window
ImGui_ImplVulkanH_WindowRenderBuffers MainWindowRenderBuffers;
ImGui_ImplVulkan_Data()
{
memset((void*)this, 0, sizeof(*this));
BufferMemoryAlignment = 256;
}
};
// Forward Declarations // Forward Declarations
struct ImGui_ImplVulkan_FrameRenderBuffers;
struct ImGui_ImplVulkan_WindowRenderBuffers;
bool ImGui_ImplVulkan_CreateDeviceObjects(); bool ImGui_ImplVulkan_CreateDeviceObjects();
void ImGui_ImplVulkan_DestroyDeviceObjects(); void ImGui_ImplVulkan_DestroyDeviceObjects();
void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator);
void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator);
void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrame(VkDevice device, ImGui_ImplVulkanH_Frame* fd, const VkAllocationCallbacks* allocator);
void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH_FrameSemaphores* fsd, const VkAllocationCallbacks* allocator);
void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator);
void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator);
void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count); void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count);
void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator); void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator);
// Vulkan prototypes for use with custom loaders // Vulkan prototypes for use with custom loaders
// (see description of IMGUI_IMPL_VULKAN_NO_PROTOTYPES in imgui_impl_vulkan.h // (see description of IMGUI_IMPL_VULKAN_NO_PROTOTYPES in imgui_impl_vulkan.h
#ifdef VK_NO_PROTOTYPES #if defined(VK_NO_PROTOTYPES) && !defined(VOLK_H_)
#define IMGUI_IMPL_VULKAN_USE_LOADER
static bool g_FunctionsLoaded = false; static bool g_FunctionsLoaded = false;
#else #else
static bool g_FunctionsLoaded = true; static bool g_FunctionsLoaded = true;
#endif #endif
#ifdef VK_NO_PROTOTYPES #ifdef IMGUI_IMPL_VULKAN_USE_LOADER
#define IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_MAP_MACRO) \ #define IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_MAP_MACRO) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateCommandBuffers) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateCommandBuffers) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateDescriptorSets) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkAllocateMemory) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkBeginCommandBuffer) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindBufferMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindBufferMemory) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindImageMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkBindImageMemory) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkCmdBindDescriptorSets) \
@ -192,6 +163,7 @@ static bool g_FunctionsLoaded = true;
IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySurfaceKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySurfaceKHR) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySwapchainKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDestroySwapchainKHR) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkDeviceWaitIdle) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkDeviceWaitIdle) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkEndCommandBuffer) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkFlushMappedMemoryRanges) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFlushMappedMemoryRanges) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeCommandBuffers) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeCommandBuffers) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeDescriptorSets) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkFreeDescriptorSets) \
@ -204,6 +176,9 @@ static bool g_FunctionsLoaded = true;
IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfacePresentModesKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetPhysicalDeviceSurfacePresentModesKHR) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetSwapchainImagesKHR) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkGetSwapchainImagesKHR) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkMapMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkMapMemory) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueSubmit) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkQueueWaitIdle) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkResetCommandPool) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkUnmapMemory) \ IMGUI_VULKAN_FUNC_MAP_MACRO(vkUnmapMemory) \
IMGUI_VULKAN_FUNC_MAP_MACRO(vkUpdateDescriptorSets) IMGUI_VULKAN_FUNC_MAP_MACRO(vkUpdateDescriptorSets)
@ -211,19 +186,70 @@ static bool g_FunctionsLoaded = true;
#define IMGUI_VULKAN_FUNC_DEF(func) static PFN_##func func; #define IMGUI_VULKAN_FUNC_DEF(func) static PFN_##func func;
IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_DEF) IMGUI_VULKAN_FUNC_MAP(IMGUI_VULKAN_FUNC_DEF)
#undef IMGUI_VULKAN_FUNC_DEF #undef IMGUI_VULKAN_FUNC_DEF
#endif // VK_NO_PROTOTYPES #endif // IMGUI_IMPL_VULKAN_USE_LOADER
#if defined(VK_VERSION_1_3) || defined(VK_KHR_dynamic_rendering) #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
#define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
static PFN_vkCmdBeginRenderingKHR ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR; static PFN_vkCmdBeginRenderingKHR ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR;
static PFN_vkCmdEndRenderingKHR ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR; static PFN_vkCmdEndRenderingKHR ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR;
#endif #endif
// Reusable buffers used for rendering 1 current in-flight frame, for ImGui_ImplVulkan_RenderDrawData()
// [Please zero-clear before use!]
struct ImGui_ImplVulkan_FrameRenderBuffers
{
VkDeviceMemory VertexBufferMemory;
VkDeviceMemory IndexBufferMemory;
VkDeviceSize VertexBufferSize;
VkDeviceSize IndexBufferSize;
VkBuffer VertexBuffer;
VkBuffer IndexBuffer;
};
// Each viewport will hold 1 ImGui_ImplVulkanH_WindowRenderBuffers
// [Please zero-clear before use!]
struct ImGui_ImplVulkan_WindowRenderBuffers
{
uint32_t Index;
uint32_t Count;
ImGui_ImplVulkan_FrameRenderBuffers* FrameRenderBuffers;
};
// Vulkan data
struct ImGui_ImplVulkan_Data
{
ImGui_ImplVulkan_InitInfo VulkanInitInfo;
VkDeviceSize BufferMemoryAlignment;
VkPipelineCreateFlags PipelineCreateFlags;
VkDescriptorSetLayout DescriptorSetLayout;
VkPipelineLayout PipelineLayout;
VkPipeline Pipeline;
VkShaderModule ShaderModuleVert;
VkShaderModule ShaderModuleFrag;
// Font data
VkSampler FontSampler;
VkDeviceMemory FontMemory;
VkImage FontImage;
VkImageView FontView;
VkDescriptorSet FontDescriptorSet;
VkCommandPool FontCommandPool;
VkCommandBuffer FontCommandBuffer;
// Render buffers for main window
ImGui_ImplVulkan_WindowRenderBuffers MainWindowRenderBuffers;
ImGui_ImplVulkan_Data()
{
memset((void*)this, 0, sizeof(*this));
BufferMemoryAlignment = 256;
}
};
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// SHADERS // SHADERS
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// glsl_shader.vert, compiled with: // backends/vulkan/glsl_shader.vert, compiled with:
// # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert // # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
/* /*
#version 450 core #version 450 core
@ -287,7 +313,7 @@ static uint32_t __glsl_shader_vert_spv[] =
0x0000002d,0x0000002c,0x000100fd,0x00010038 0x0000002d,0x0000002c,0x000100fd,0x00010038
}; };
// glsl_shader.frag, compiled with: // backends/vulkan/glsl_shader.frag, compiled with:
// # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag // # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
/* /*
#version 450 core #version 450 core
@ -362,7 +388,13 @@ static void check_vk_result(VkResult err)
v->CheckVkResultFn(err); v->CheckVkResultFn(err);
} }
static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& p_buffer_size, size_t new_size, VkBufferUsageFlagBits usage) // Same as IM_MEMALIGN(). 'alignment' must be a power of two.
static inline VkDeviceSize AlignBufferSize(VkDeviceSize size, VkDeviceSize alignment)
{
return (size + alignment - 1) & ~(alignment - 1);
}
static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory, VkDeviceSize& buffer_size, size_t new_size, VkBufferUsageFlagBits usage)
{ {
ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
@ -372,10 +404,10 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory
if (buffer_memory != VK_NULL_HANDLE) if (buffer_memory != VK_NULL_HANDLE)
vkFreeMemory(v->Device, buffer_memory, v->Allocator); vkFreeMemory(v->Device, buffer_memory, v->Allocator);
VkDeviceSize vertex_buffer_size_aligned = ((new_size - 1) / bd->BufferMemoryAlignment + 1) * bd->BufferMemoryAlignment; VkDeviceSize buffer_size_aligned = AlignBufferSize(IM_MAX(v->MinAllocationSize, new_size), bd->BufferMemoryAlignment);
VkBufferCreateInfo buffer_info = {}; VkBufferCreateInfo buffer_info = {};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = vertex_buffer_size_aligned; buffer_info.size = buffer_size_aligned;
buffer_info.usage = usage; buffer_info.usage = usage;
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &buffer); err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &buffer);
@ -393,10 +425,10 @@ static void CreateOrResizeBuffer(VkBuffer& buffer, VkDeviceMemory& buffer_memory
err = vkBindBufferMemory(v->Device, buffer, buffer_memory, 0); err = vkBindBufferMemory(v->Device, buffer, buffer_memory, 0);
check_vk_result(err); check_vk_result(err);
p_buffer_size = req.size; buffer_size = buffer_size_aligned;
} }
static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkanH_FrameRenderBuffers* rb, int fb_width, int fb_height) static void ImGui_ImplVulkan_SetupRenderState(ImDrawData* draw_data, VkPipeline pipeline, VkCommandBuffer command_buffer, ImGui_ImplVulkan_FrameRenderBuffers* rb, int fb_width, int fb_height)
{ {
ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
@ -455,23 +487,23 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
pipeline = bd->Pipeline; pipeline = bd->Pipeline;
// Allocate array to store enough vertex/index buffers // Allocate array to store enough vertex/index buffers
ImGui_ImplVulkanH_WindowRenderBuffers* wrb = &bd->MainWindowRenderBuffers; ImGui_ImplVulkan_WindowRenderBuffers* wrb = &bd->MainWindowRenderBuffers;
if (wrb->FrameRenderBuffers == nullptr) if (wrb->FrameRenderBuffers == nullptr)
{ {
wrb->Index = 0; wrb->Index = 0;
wrb->Count = v->ImageCount; wrb->Count = v->ImageCount;
wrb->FrameRenderBuffers = (ImGui_ImplVulkanH_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count); wrb->FrameRenderBuffers = (ImGui_ImplVulkan_FrameRenderBuffers*)IM_ALLOC(sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count);
memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkanH_FrameRenderBuffers) * wrb->Count); memset(wrb->FrameRenderBuffers, 0, sizeof(ImGui_ImplVulkan_FrameRenderBuffers) * wrb->Count);
} }
IM_ASSERT(wrb->Count == v->ImageCount); IM_ASSERT(wrb->Count == v->ImageCount);
wrb->Index = (wrb->Index + 1) % wrb->Count; wrb->Index = (wrb->Index + 1) % wrb->Count;
ImGui_ImplVulkanH_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index]; ImGui_ImplVulkan_FrameRenderBuffers* rb = &wrb->FrameRenderBuffers[wrb->Index];
if (draw_data->TotalVtxCount > 0) if (draw_data->TotalVtxCount > 0)
{ {
// Create or resize the vertex/index buffers // Create or resize the vertex/index buffers
size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert); size_t vertex_size = AlignBufferSize(draw_data->TotalVtxCount * sizeof(ImDrawVert), bd->BufferMemoryAlignment);
size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx); size_t index_size = AlignBufferSize(draw_data->TotalIdxCount * sizeof(ImDrawIdx), bd->BufferMemoryAlignment);
if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size) if (rb->VertexBuffer == VK_NULL_HANDLE || rb->VertexBufferSize < vertex_size)
CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); CreateOrResizeBuffer(rb->VertexBuffer, rb->VertexBufferMemory, rb->VertexBufferSize, vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size) if (rb->IndexBuffer == VK_NULL_HANDLE || rb->IndexBufferSize < index_size)
@ -480,9 +512,9 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
// Upload vertex/index data into a single contiguous GPU buffer // Upload vertex/index data into a single contiguous GPU buffer
ImDrawVert* vtx_dst = nullptr; ImDrawVert* vtx_dst = nullptr;
ImDrawIdx* idx_dst = nullptr; ImDrawIdx* idx_dst = nullptr;
VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, rb->VertexBufferSize, 0, (void**)(&vtx_dst)); VkResult err = vkMapMemory(v->Device, rb->VertexBufferMemory, 0, vertex_size, 0, (void**)&vtx_dst);
check_vk_result(err); check_vk_result(err);
err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, rb->IndexBufferSize, 0, (void**)(&idx_dst)); err = vkMapMemory(v->Device, rb->IndexBufferMemory, 0, index_size, 0, (void**)&idx_dst);
check_vk_result(err); check_vk_result(err);
for (int n = 0; n < draw_data->CmdListsCount; n++) for (int n = 0; n < draw_data->CmdListsCount; n++)
{ {
@ -582,19 +614,55 @@ void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer comm
vkCmdSetScissor(command_buffer, 0, 1, &scissor); vkCmdSetScissor(command_buffer, 0, 1, &scissor);
} }
bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer) bool ImGui_ImplVulkan_CreateFontsTexture()
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
VkResult err;
// Destroy existing texture (if any)
if (bd->FontView || bd->FontImage || bd->FontMemory || bd->FontDescriptorSet)
{
vkQueueWaitIdle(v->Queue);
ImGui_ImplVulkan_DestroyFontsTexture();
}
// Create command pool/buffer
if (bd->FontCommandPool == VK_NULL_HANDLE)
{
VkCommandPoolCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
info.flags = 0;
info.queueFamilyIndex = v->QueueFamily;
vkCreateCommandPool(v->Device, &info, v->Allocator, &bd->FontCommandPool);
}
if (bd->FontCommandBuffer == VK_NULL_HANDLE)
{
VkCommandBufferAllocateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
info.commandPool = bd->FontCommandPool;
info.commandBufferCount = 1;
err = vkAllocateCommandBuffers(v->Device, &info, &bd->FontCommandBuffer);
check_vk_result(err);
}
// Start command buffer
{
err = vkResetCommandPool(v->Device, bd->FontCommandPool, 0);
check_vk_result(err);
VkCommandBufferBeginInfo begin_info = {};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
err = vkBeginCommandBuffer(bd->FontCommandBuffer, &begin_info);
check_vk_result(err);
}
unsigned char* pixels; unsigned char* pixels;
int width, height; int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
size_t upload_size = width * height * 4 * sizeof(char); size_t upload_size = width * height * 4 * sizeof(char);
VkResult err;
// Create the Image: // Create the Image:
{ {
VkImageCreateInfo info = {}; VkImageCreateInfo info = {};
@ -617,7 +685,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
vkGetImageMemoryRequirements(v->Device, bd->FontImage, &req); vkGetImageMemoryRequirements(v->Device, bd->FontImage, &req);
VkMemoryAllocateInfo alloc_info = {}; VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = req.size; alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size);
alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits); alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, req.memoryTypeBits);
err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &bd->FontMemory); err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &bd->FontMemory);
check_vk_result(err); check_vk_result(err);
@ -643,40 +711,42 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
bd->FontDescriptorSet = (VkDescriptorSet)ImGui_ImplVulkan_AddTexture(bd->FontSampler, bd->FontView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); bd->FontDescriptorSet = (VkDescriptorSet)ImGui_ImplVulkan_AddTexture(bd->FontSampler, bd->FontView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
// Create the Upload Buffer: // Create the Upload Buffer:
VkDeviceMemory upload_buffer_memory;
VkBuffer upload_buffer;
{ {
VkBufferCreateInfo buffer_info = {}; VkBufferCreateInfo buffer_info = {};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = upload_size; buffer_info.size = upload_size;
buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &bd->UploadBuffer); err = vkCreateBuffer(v->Device, &buffer_info, v->Allocator, &upload_buffer);
check_vk_result(err); check_vk_result(err);
VkMemoryRequirements req; VkMemoryRequirements req;
vkGetBufferMemoryRequirements(v->Device, bd->UploadBuffer, &req); vkGetBufferMemoryRequirements(v->Device, upload_buffer, &req);
bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment; bd->BufferMemoryAlignment = (bd->BufferMemoryAlignment > req.alignment) ? bd->BufferMemoryAlignment : req.alignment;
VkMemoryAllocateInfo alloc_info = {}; VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = req.size; alloc_info.allocationSize = IM_MAX(v->MinAllocationSize, req.size);
alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits); alloc_info.memoryTypeIndex = ImGui_ImplVulkan_MemoryType(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &bd->UploadBufferMemory); err = vkAllocateMemory(v->Device, &alloc_info, v->Allocator, &upload_buffer_memory);
check_vk_result(err); check_vk_result(err);
err = vkBindBufferMemory(v->Device, bd->UploadBuffer, bd->UploadBufferMemory, 0); err = vkBindBufferMemory(v->Device, upload_buffer, upload_buffer_memory, 0);
check_vk_result(err); check_vk_result(err);
} }
// Upload to Buffer: // Upload to Buffer:
{ {
char* map = nullptr; char* map = nullptr;
err = vkMapMemory(v->Device, bd->UploadBufferMemory, 0, upload_size, 0, (void**)(&map)); err = vkMapMemory(v->Device, upload_buffer_memory, 0, upload_size, 0, (void**)(&map));
check_vk_result(err); check_vk_result(err);
memcpy(map, pixels, upload_size); memcpy(map, pixels, upload_size);
VkMappedMemoryRange range[1] = {}; VkMappedMemoryRange range[1] = {};
range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range[0].memory = bd->UploadBufferMemory; range[0].memory = upload_buffer_memory;
range[0].size = upload_size; range[0].size = upload_size;
err = vkFlushMappedMemoryRanges(v->Device, 1, range); err = vkFlushMappedMemoryRanges(v->Device, 1, range);
check_vk_result(err); check_vk_result(err);
vkUnmapMemory(v->Device, bd->UploadBufferMemory); vkUnmapMemory(v->Device, upload_buffer_memory);
} }
// Copy to Image: // Copy to Image:
@ -692,7 +762,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copy_barrier[0].subresourceRange.levelCount = 1; copy_barrier[0].subresourceRange.levelCount = 1;
copy_barrier[0].subresourceRange.layerCount = 1; copy_barrier[0].subresourceRange.layerCount = 1;
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier); vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, copy_barrier);
VkBufferImageCopy region = {}; VkBufferImageCopy region = {};
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
@ -700,7 +770,7 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
region.imageExtent.width = width; region.imageExtent.width = width;
region.imageExtent.height = height; region.imageExtent.height = height;
region.imageExtent.depth = 1; region.imageExtent.depth = 1;
vkCmdCopyBufferToImage(command_buffer, bd->UploadBuffer, bd->FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region); vkCmdCopyBufferToImage(bd->FontCommandBuffer, upload_buffer, bd->FontImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
VkImageMemoryBarrier use_barrier[1] = {}; VkImageMemoryBarrier use_barrier[1] = {};
use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
@ -714,15 +784,50 @@ bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer)
use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
use_barrier[0].subresourceRange.levelCount = 1; use_barrier[0].subresourceRange.levelCount = 1;
use_barrier[0].subresourceRange.layerCount = 1; use_barrier[0].subresourceRange.layerCount = 1;
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier); vkCmdPipelineBarrier(bd->FontCommandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, use_barrier);
} }
// Store our identifier // Store our identifier
io.Fonts->SetTexID((ImTextureID)bd->FontDescriptorSet); io.Fonts->SetTexID((ImTextureID)bd->FontDescriptorSet);
// End command buffer
VkSubmitInfo end_info = {};
end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
end_info.commandBufferCount = 1;
end_info.pCommandBuffers = &bd->FontCommandBuffer;
err = vkEndCommandBuffer(bd->FontCommandBuffer);
check_vk_result(err);
err = vkQueueSubmit(v->Queue, 1, &end_info, VK_NULL_HANDLE);
check_vk_result(err);
err = vkQueueWaitIdle(v->Queue);
check_vk_result(err);
vkDestroyBuffer(v->Device, upload_buffer, v->Allocator);
vkFreeMemory(v->Device, upload_buffer_memory, v->Allocator);
return true; return true;
} }
// You probably never need to call this, as it is called by ImGui_ImplVulkan_CreateFontsTexture() and ImGui_ImplVulkan_Shutdown().
void ImGui_ImplVulkan_DestroyFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
if (bd->FontDescriptorSet)
{
ImGui_ImplVulkan_RemoveTexture(bd->FontDescriptorSet);
bd->FontDescriptorSet = VK_NULL_HANDLE;
io.Fonts->SetTexID(0);
}
if (bd->FontView) { vkDestroyImageView(v->Device, bd->FontView, v->Allocator); bd->FontView = VK_NULL_HANDLE; }
if (bd->FontImage) { vkDestroyImage(v->Device, bd->FontImage, v->Allocator); bd->FontImage = VK_NULL_HANDLE; }
if (bd->FontMemory) { vkFreeMemory(v->Device, bd->FontMemory, v->Allocator); bd->FontMemory = VK_NULL_HANDLE; }
}
static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator) static void ImGui_ImplVulkan_CreateShaderModules(VkDevice device, const VkAllocationCallbacks* allocator)
{ {
// Create the shader modules // Create the shader modules
@ -770,15 +875,15 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC
attribute_desc[0].location = 0; attribute_desc[0].location = 0;
attribute_desc[0].binding = binding_desc[0].binding; attribute_desc[0].binding = binding_desc[0].binding;
attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT; attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos); attribute_desc[0].offset = offsetof(ImDrawVert, pos);
attribute_desc[1].location = 1; attribute_desc[1].location = 1;
attribute_desc[1].binding = binding_desc[0].binding; attribute_desc[1].binding = binding_desc[0].binding;
attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT; attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv); attribute_desc[1].offset = offsetof(ImDrawVert, uv);
attribute_desc[2].location = 2; attribute_desc[2].location = 2;
attribute_desc[2].binding = binding_desc[0].binding; attribute_desc[2].binding = binding_desc[0].binding;
attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM; attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col); attribute_desc[2].offset = offsetof(ImDrawVert, col);
VkPipelineVertexInputStateCreateInfo vertex_info = {}; VkPipelineVertexInputStateCreateInfo vertex_info = {};
vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
@ -849,13 +954,11 @@ static void ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAllocationC
info.subpass = subpass; info.subpass = subpass;
#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
VkPipelineRenderingCreateInfoKHR pipelineRenderingCreateInfo = {};
pipelineRenderingCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR;
pipelineRenderingCreateInfo.colorAttachmentCount = 1;
pipelineRenderingCreateInfo.pColorAttachmentFormats = &bd->VulkanInitInfo.ColorAttachmentFormat;
if (bd->VulkanInitInfo.UseDynamicRendering) if (bd->VulkanInitInfo.UseDynamicRendering)
{ {
info.pNext = &pipelineRenderingCreateInfo; IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.sType == VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR && "PipelineRenderingCreateInfo sType must be VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR");
IM_ASSERT(bd->VulkanInitInfo.PipelineRenderingCreateInfo.pNext == nullptr && "PipelineRenderingCreateInfo pNext must be NULL");
info.pNext = &bd->VulkanInitInfo.PipelineRenderingCreateInfo;
info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr. info.renderPass = VK_NULL_HANDLE; // Just make sure it's actually nullptr.
} }
#endif #endif
@ -920,39 +1023,22 @@ bool ImGui_ImplVulkan_CreateDeviceObjects()
check_vk_result(err); check_vk_result(err);
} }
ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, bd->RenderPass, v->MSAASamples, &bd->Pipeline, bd->Subpass); ImGui_ImplVulkan_CreatePipeline(v->Device, v->Allocator, v->PipelineCache, v->RenderPass, v->MSAASamples, &bd->Pipeline, v->Subpass);
return true; return true;
} }
void ImGui_ImplVulkan_DestroyFontUploadObjects()
{
ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
if (bd->UploadBuffer)
{
vkDestroyBuffer(v->Device, bd->UploadBuffer, v->Allocator);
bd->UploadBuffer = VK_NULL_HANDLE;
}
if (bd->UploadBufferMemory)
{
vkFreeMemory(v->Device, bd->UploadBufferMemory, v->Allocator);
bd->UploadBufferMemory = VK_NULL_HANDLE;
}
}
void ImGui_ImplVulkan_DestroyDeviceObjects() void ImGui_ImplVulkan_DestroyDeviceObjects()
{ {
ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator);
ImGui_ImplVulkan_DestroyFontUploadObjects(); ImGui_ImplVulkan_DestroyFontsTexture();
if (bd->FontCommandBuffer) { vkFreeCommandBuffers(v->Device, bd->FontCommandPool, 1, &bd->FontCommandBuffer); bd->FontCommandBuffer = VK_NULL_HANDLE; }
if (bd->FontCommandPool) { vkDestroyCommandPool(v->Device, bd->FontCommandPool, v->Allocator); bd->FontCommandPool = VK_NULL_HANDLE; }
if (bd->ShaderModuleVert) { vkDestroyShaderModule(v->Device, bd->ShaderModuleVert, v->Allocator); bd->ShaderModuleVert = VK_NULL_HANDLE; } if (bd->ShaderModuleVert) { vkDestroyShaderModule(v->Device, bd->ShaderModuleVert, v->Allocator); bd->ShaderModuleVert = VK_NULL_HANDLE; }
if (bd->ShaderModuleFrag) { vkDestroyShaderModule(v->Device, bd->ShaderModuleFrag, v->Allocator); bd->ShaderModuleFrag = VK_NULL_HANDLE; } if (bd->ShaderModuleFrag) { vkDestroyShaderModule(v->Device, bd->ShaderModuleFrag, v->Allocator); bd->ShaderModuleFrag = VK_NULL_HANDLE; }
if (bd->FontView) { vkDestroyImageView(v->Device, bd->FontView, v->Allocator); bd->FontView = VK_NULL_HANDLE; }
if (bd->FontImage) { vkDestroyImage(v->Device, bd->FontImage, v->Allocator); bd->FontImage = VK_NULL_HANDLE; }
if (bd->FontMemory) { vkFreeMemory(v->Device, bd->FontMemory, v->Allocator); bd->FontMemory = VK_NULL_HANDLE; }
if (bd->FontSampler) { vkDestroySampler(v->Device, bd->FontSampler, v->Allocator); bd->FontSampler = VK_NULL_HANDLE; } if (bd->FontSampler) { vkDestroySampler(v->Device, bd->FontSampler, v->Allocator); bd->FontSampler = VK_NULL_HANDLE; }
if (bd->DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; } if (bd->DescriptorSetLayout) { vkDestroyDescriptorSetLayout(v->Device, bd->DescriptorSetLayout, v->Allocator); bd->DescriptorSetLayout = VK_NULL_HANDLE; }
if (bd->PipelineLayout) { vkDestroyPipelineLayout(v->Device, bd->PipelineLayout, v->Allocator); bd->PipelineLayout = VK_NULL_HANDLE; } if (bd->PipelineLayout) { vkDestroyPipelineLayout(v->Device, bd->PipelineLayout, v->Allocator); bd->PipelineLayout = VK_NULL_HANDLE; }
@ -964,8 +1050,8 @@ bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const ch
// Load function pointers // Load function pointers
// You can use the default Vulkan loader using: // You can use the default Vulkan loader using:
// ImGui_ImplVulkan_LoadFunctions([](const char* function_name, void*) { return vkGetInstanceProcAddr(your_vk_isntance, function_name); }); // ImGui_ImplVulkan_LoadFunctions([](const char* function_name, void*) { return vkGetInstanceProcAddr(your_vk_isntance, function_name); });
// But this would be equivalent to not setting VK_NO_PROTOTYPES. // But this would be roughly equivalent to not setting VK_NO_PROTOTYPES.
#ifdef VK_NO_PROTOTYPES #ifdef IMGUI_IMPL_VULKAN_USE_LOADER
#define IMGUI_VULKAN_FUNC_LOAD(func) \ #define IMGUI_VULKAN_FUNC_LOAD(func) \
func = reinterpret_cast<decltype(func)>(loader_func(#func, user_data)); \ func = reinterpret_cast<decltype(func)>(loader_func(#func, user_data)); \
if (func == nullptr) \ if (func == nullptr) \
@ -987,14 +1073,14 @@ bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const ch
return true; return true;
} }
bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass) bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info)
{ {
IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!");
if (info->UseDynamicRendering) if (info->UseDynamicRendering)
{ {
#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
#ifndef VK_NO_PROTOTYPES #ifndef IMGUI_IMPL_VULKAN_USE_LOADER
ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast<PFN_vkCmdBeginRenderingKHR>(vkGetInstanceProcAddr(info->Instance, "vkCmdBeginRenderingKHR")); ImGuiImplVulkanFuncs_vkCmdBeginRenderingKHR = reinterpret_cast<PFN_vkCmdBeginRenderingKHR>(vkGetInstanceProcAddr(info->Instance, "vkCmdBeginRenderingKHR"));
ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast<PFN_vkCmdEndRenderingKHR>(vkGetInstanceProcAddr(info->Instance, "vkCmdEndRenderingKHR")); ImGuiImplVulkanFuncs_vkCmdEndRenderingKHR = reinterpret_cast<PFN_vkCmdEndRenderingKHR>(vkGetInstanceProcAddr(info->Instance, "vkCmdEndRenderingKHR"));
#endif #endif
@ -1006,6 +1092,7 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend
} }
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
@ -1022,11 +1109,9 @@ bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass rend
IM_ASSERT(info->MinImageCount >= 2); IM_ASSERT(info->MinImageCount >= 2);
IM_ASSERT(info->ImageCount >= info->MinImageCount); IM_ASSERT(info->ImageCount >= info->MinImageCount);
if (info->UseDynamicRendering == false) if (info->UseDynamicRendering == false)
IM_ASSERT(render_pass != VK_NULL_HANDLE); IM_ASSERT(info->RenderPass != VK_NULL_HANDLE);
bd->VulkanInitInfo = *info; bd->VulkanInitInfo = *info;
bd->RenderPass = render_pass;
bd->Subpass = info->Subpass;
ImGui_ImplVulkan_CreateDeviceObjects(); ImGui_ImplVulkan_CreateDeviceObjects();
@ -1049,8 +1134,10 @@ void ImGui_ImplVulkan_Shutdown()
void ImGui_ImplVulkan_NewFrame() void ImGui_ImplVulkan_NewFrame()
{ {
ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData(); ImGui_ImplVulkan_Data* bd = ImGui_ImplVulkan_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplVulkan_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplVulkan_Init()?");
IM_UNUSED(bd);
if (!bd->FontDescriptorSet)
ImGui_ImplVulkan_CreateFontsTexture();
} }
void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count) void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count)
@ -1063,7 +1150,7 @@ void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count)
ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo; ImGui_ImplVulkan_InitInfo* v = &bd->VulkanInitInfo;
VkResult err = vkDeviceWaitIdle(v->Device); VkResult err = vkDeviceWaitIdle(v->Device);
check_vk_result(err); check_vk_result(err);
ImGui_ImplVulkanH_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator); ImGui_ImplVulkan_DestroyWindowRenderBuffers(v->Device, &bd->MainWindowRenderBuffers, v->Allocator);
bd->VulkanInitInfo.MinImageCount = min_image_count; bd->VulkanInitInfo.MinImageCount = min_image_count;
} }
@ -1110,6 +1197,26 @@ void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set)
vkFreeDescriptorSets(v->Device, v->DescriptorPool, 1, &descriptor_set); vkFreeDescriptorSets(v->Device, v->DescriptorPool, 1, &descriptor_set);
} }
void ImGui_ImplVulkan_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkan_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator)
{
if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; }
if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; }
if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; }
if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; }
buffers->VertexBufferSize = 0;
buffers->IndexBufferSize = 0;
}
void ImGui_ImplVulkan_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkan_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator)
{
for (uint32_t n = 0; n < buffers->Count; n++)
ImGui_ImplVulkan_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator);
IM_FREE(buffers->FrameRenderBuffers);
buffers->FrameRenderBuffers = nullptr;
buffers->Index = 0;
buffers->Count = 0;
}
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Internal / Miscellaneous Vulkan Helpers // Internal / Miscellaneous Vulkan Helpers
// (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.) // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own app.)
@ -1197,19 +1304,17 @@ VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_d
void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator) void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator)
{ {
IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE); IM_ASSERT(physical_device != VK_NULL_HANDLE && device != VK_NULL_HANDLE);
(void)physical_device; IM_UNUSED(physical_device);
(void)allocator;
// Create Command Buffers // Create Command Buffers
VkResult err; VkResult err;
for (uint32_t i = 0; i < wd->ImageCount; i++) for (uint32_t i = 0; i < wd->ImageCount; i++)
{ {
ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i]; ImGui_ImplVulkanH_Frame* fd = &wd->Frames[i];
ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i];
{ {
VkCommandPoolCreateInfo info = {}; VkCommandPoolCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; info.flags = 0;
info.queueFamilyIndex = queue_family; info.queueFamilyIndex = queue_family;
err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool); err = vkCreateCommandPool(device, &info, allocator, &fd->CommandPool);
check_vk_result(err); check_vk_result(err);
@ -1230,6 +1335,11 @@ void ImGui_ImplVulkanH_CreateWindowCommandBuffers(VkPhysicalDevice physical_devi
err = vkCreateFence(device, &info, allocator, &fd->Fence); err = vkCreateFence(device, &info, allocator, &fd->Fence);
check_vk_result(err); check_vk_result(err);
} }
}
for (uint32_t i = 0; i < wd->SemaphoreCount; i++)
{
ImGui_ImplVulkanH_FrameSemaphores* fsd = &wd->FrameSemaphores[i];
{ {
VkSemaphoreCreateInfo info = {}; VkSemaphoreCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
@ -1265,10 +1375,9 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V
// We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one. // We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one.
// Destroy old Framebuffer // Destroy old Framebuffer
for (uint32_t i = 0; i < wd->ImageCount; i++) for (uint32_t i = 0; i < wd->ImageCount; i++)
{
ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator);
for (uint32_t i = 0; i < wd->SemaphoreCount; i++)
ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator);
}
IM_FREE(wd->Frames); IM_FREE(wd->Frames);
IM_FREE(wd->FrameSemaphores); IM_FREE(wd->FrameSemaphores);
wd->Frames = nullptr; wd->Frames = nullptr;
@ -1327,11 +1436,12 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V
err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers); err = vkGetSwapchainImagesKHR(device, wd->Swapchain, &wd->ImageCount, backbuffers);
check_vk_result(err); check_vk_result(err);
IM_ASSERT(wd->Frames == nullptr); IM_ASSERT(wd->Frames == nullptr && wd->FrameSemaphores == nullptr);
wd->SemaphoreCount = wd->ImageCount + 1;
wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount); wd->Frames = (ImGui_ImplVulkanH_Frame*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_Frame) * wd->ImageCount);
wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->ImageCount); wd->FrameSemaphores = (ImGui_ImplVulkanH_FrameSemaphores*)IM_ALLOC(sizeof(ImGui_ImplVulkanH_FrameSemaphores) * wd->SemaphoreCount);
memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount); memset(wd->Frames, 0, sizeof(wd->Frames[0]) * wd->ImageCount);
memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->ImageCount); memset(wd->FrameSemaphores, 0, sizeof(wd->FrameSemaphores[0]) * wd->SemaphoreCount);
for (uint32_t i = 0; i < wd->ImageCount; i++) for (uint32_t i = 0; i < wd->ImageCount; i++)
wd->Frames[i].Backbuffer = backbuffers[i]; wd->Frames[i].Backbuffer = backbuffers[i];
} }
@ -1377,7 +1487,7 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V
// We do not create a pipeline by default as this is also used by examples' main.cpp, // We do not create a pipeline by default as this is also used by examples' main.cpp,
// but secondary viewport in multi-viewport mode may want to create one with: // but secondary viewport in multi-viewport mode may want to create one with:
//ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, bd->Subpass); //ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, wd->RenderPass, VK_SAMPLE_COUNT_1_BIT, &wd->Pipeline, v->Subpass);
} }
// Create The Image Views // Create The Image Views
@ -1438,10 +1548,9 @@ void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui
//vkQueueWaitIdle(bd->Queue); //vkQueueWaitIdle(bd->Queue);
for (uint32_t i = 0; i < wd->ImageCount; i++) for (uint32_t i = 0; i < wd->ImageCount; i++)
{
ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator); ImGui_ImplVulkanH_DestroyFrame(device, &wd->Frames[i], allocator);
for (uint32_t i = 0; i < wd->SemaphoreCount; i++)
ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator); ImGui_ImplVulkanH_DestroyFrameSemaphores(device, &wd->FrameSemaphores[i], allocator);
}
IM_FREE(wd->Frames); IM_FREE(wd->Frames);
IM_FREE(wd->FrameSemaphores); IM_FREE(wd->FrameSemaphores);
wd->Frames = nullptr; wd->Frames = nullptr;
@ -1474,22 +1583,6 @@ void ImGui_ImplVulkanH_DestroyFrameSemaphores(VkDevice device, ImGui_ImplVulkanH
fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE; fsd->ImageAcquiredSemaphore = fsd->RenderCompleteSemaphore = VK_NULL_HANDLE;
} }
void ImGui_ImplVulkanH_DestroyFrameRenderBuffers(VkDevice device, ImGui_ImplVulkanH_FrameRenderBuffers* buffers, const VkAllocationCallbacks* allocator) //-----------------------------------------------------------------------------
{
if (buffers->VertexBuffer) { vkDestroyBuffer(device, buffers->VertexBuffer, allocator); buffers->VertexBuffer = VK_NULL_HANDLE; }
if (buffers->VertexBufferMemory) { vkFreeMemory(device, buffers->VertexBufferMemory, allocator); buffers->VertexBufferMemory = VK_NULL_HANDLE; }
if (buffers->IndexBuffer) { vkDestroyBuffer(device, buffers->IndexBuffer, allocator); buffers->IndexBuffer = VK_NULL_HANDLE; }
if (buffers->IndexBufferMemory) { vkFreeMemory(device, buffers->IndexBufferMemory, allocator); buffers->IndexBufferMemory = VK_NULL_HANDLE; }
buffers->VertexBufferSize = 0;
buffers->IndexBufferSize = 0;
}
void ImGui_ImplVulkanH_DestroyWindowRenderBuffers(VkDevice device, ImGui_ImplVulkanH_WindowRenderBuffers* buffers, const VkAllocationCallbacks* allocator) #endif // #ifndef IMGUI_DISABLE
{
for (uint32_t n = 0; n < buffers->Count; n++)
ImGui_ImplVulkanH_DestroyFrameRenderBuffers(device, &buffers->FrameRenderBuffers[n], allocator);
IM_FREE(buffers->FrameRenderBuffers);
buffers->FrameRenderBuffers = nullptr;
buffers->Index = 0;
buffers->Count = 0;
}

View File

@ -8,14 +8,17 @@
// Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'. // Important: on 32-bit systems, user texture binding is only supported if your imconfig file has '#define ImTextureID ImU64'.
// See imgui_impl_vulkan.cpp file for details. // See imgui_impl_vulkan.cpp file for details.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification. // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
// IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/ // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
// You will use those if you want to use this rendering backend in your engine/app. // You will use those if you want to use this rendering backend in your engine/app.
@ -24,6 +27,7 @@
// Read comments in imgui_impl_vulkan.h. // Read comments in imgui_impl_vulkan.h.
#pragma once #pragma once
#ifndef IMGUI_DISABLE
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
// [Configuration] in order to use a custom Vulkan function loader: // [Configuration] in order to use a custom Vulkan function loader:
@ -38,13 +42,31 @@
// If you have no idea what this is, leave it alone! // If you have no idea what this is, leave it alone!
//#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES //#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES
// Vulkan includes // Convenience support for Volk
// (you can also technically use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().)
//#define IMGUI_IMPL_VULKAN_USE_VOLK
#if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES) #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES)
#define VK_NO_PROTOTYPES #define VK_NO_PROTOTYPES
#endif #endif
#if defined(VK_USE_PLATFORM_WIN32_KHR) && !defined(NOMINMAX)
#define NOMINMAX
#endif
// Vulkan includes
#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
#include <Volk/volk.h>
#else
#include <vulkan/vulkan.h> #include <vulkan/vulkan.h>
#endif
#if defined(VK_VERSION_1_3) || defined(VK_KHR_dynamic_rendering)
#define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
#endif
// Initialization data, for ImGui_ImplVulkan_Init() // Initialization data, for ImGui_ImplVulkan_Init()
// - VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
// and must contain a pool size large enough to hold an ImGui VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptor.
// - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure.
// [Please zero-clear before use!] // [Please zero-clear before use!]
struct ImGui_ImplVulkan_InitInfo struct ImGui_ImplVulkan_InitInfo
{ {
@ -53,29 +75,36 @@ struct ImGui_ImplVulkan_InitInfo
VkDevice Device; VkDevice Device;
uint32_t QueueFamily; uint32_t QueueFamily;
VkQueue Queue; VkQueue Queue;
VkDescriptorPool DescriptorPool; // See requirements in note above
VkRenderPass RenderPass; // Ignored if using dynamic rendering
uint32_t MinImageCount; // >= 2
uint32_t ImageCount; // >= MinImageCount
VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT
// (Optional)
VkPipelineCache PipelineCache; VkPipelineCache PipelineCache;
VkDescriptorPool DescriptorPool;
uint32_t Subpass; uint32_t Subpass;
uint32_t MinImageCount; // >= 2
uint32_t ImageCount; // >= MinImageCount
VkSampleCountFlagBits MSAASamples; // >= VK_SAMPLE_COUNT_1_BIT (0 -> default to VK_SAMPLE_COUNT_1_BIT)
// Dynamic Rendering (Optional) // (Optional) Dynamic Rendering
bool UseDynamicRendering; // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3. // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3.
VkFormat ColorAttachmentFormat; // Required for dynamic rendering bool UseDynamicRendering;
#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo;
#endif
// Allocation, Debugging // (Optional) Allocation, Debugging
const VkAllocationCallbacks* Allocator; const VkAllocationCallbacks* Allocator;
void (*CheckVkResultFn)(VkResult err); void (*CheckVkResultFn)(VkResult err);
VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory.
}; };
// Called by user code // Called by user code
IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info, VkRenderPass render_pass); IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info);
IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown(); IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown();
IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame(); IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame();
IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE); IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE);
IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture(VkCommandBuffer command_buffer); IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontUploadObjects(); IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontsTexture();
IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated) IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated)
// Register a texture (VkDescriptorSet == ImTextureID) // Register a texture (VkDescriptorSet == ImTextureID)
@ -150,6 +179,7 @@ struct ImGui_ImplVulkanH_Window
VkClearValue ClearValue; VkClearValue ClearValue;
uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount) uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount)
uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count) uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count)
uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR
uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data) uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data)
ImGui_ImplVulkanH_Frame* Frames; ImGui_ImplVulkanH_Frame* Frames;
ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores; ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores;
@ -162,3 +192,4 @@ struct ImGui_ImplVulkanH_Window
} }
}; };
#endif // #ifndef IMGUI_DISABLE

View File

@ -8,11 +8,19 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
// 2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
// 2024-01-22: Fixed pipeline layout leak. (#7245)
// 2024-01-17: Explicitly fill all of WGPUDepthStencilState since standard removed defaults.
// 2023-07-13: Use WGPUShaderModuleWGSLDescriptor's code instead of source. use WGPUMipmapFilterMode_Linear instead of WGPUFilterMode_Linear. (#6602)
// 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V. // 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V.
// 2023-04-11: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). // 2023-04-11: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
// 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470) // 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470)
@ -28,6 +36,7 @@
// 2021-01-28: Initial version. // 2021-01-28: Initial version.
#include "imgui.h" #include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_wgpu.h" #include "imgui_impl_wgpu.h"
#include <limits.h> #include <limits.h>
#include <webgpu/webgpu.h> #include <webgpu/webgpu.h>
@ -67,16 +76,17 @@ struct Uniforms
struct ImGui_ImplWGPU_Data struct ImGui_ImplWGPU_Data
{ {
WGPUDevice wgpuDevice = nullptr; ImGui_ImplWGPU_InitInfo initInfo;
WGPUQueue defaultQueue = nullptr; WGPUDevice wgpuDevice = nullptr;
WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined; WGPUQueue defaultQueue = nullptr;
WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined; WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined;
WGPURenderPipeline pipelineState = nullptr; WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined;
WGPURenderPipeline pipelineState = nullptr;
RenderResources renderResources; RenderResources renderResources;
FrameResources* pFrameResources = nullptr; FrameResources* pFrameResources = nullptr;
unsigned int numFramesInFlight = 0; unsigned int numFramesInFlight = 0;
unsigned int frameIndex = UINT_MAX; unsigned int frameIndex = UINT_MAX;
}; };
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
@ -174,6 +184,12 @@ static void SafeRelease(WGPUBuffer& res)
wgpuBufferRelease(res); wgpuBufferRelease(res);
res = nullptr; res = nullptr;
} }
static void SafeRelease(WGPUPipelineLayout& res)
{
if (res)
wgpuPipelineLayoutRelease(res);
res = nullptr;
}
static void SafeRelease(WGPURenderPipeline& res) static void SafeRelease(WGPURenderPipeline& res)
{ {
if (res) if (res)
@ -230,7 +246,7 @@ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const c
WGPUShaderModuleWGSLDescriptor wgsl_desc = {}; WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor; wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
wgsl_desc.source = wgsl_source; wgsl_desc.code = wgsl_source;
WGPUShaderModuleDescriptor desc = {}; WGPUShaderModuleDescriptor desc = {};
desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgsl_desc); desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgsl_desc);
@ -324,7 +340,9 @@ static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPas
void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder) void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
{ {
// Avoid rendering when minimized // Avoid rendering when minimized
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0)
return; return;
// FIXME: Assuming that this only gets called once per frame! // FIXME: Assuming that this only gets called once per frame!
@ -443,6 +461,12 @@ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder
// Project scissor/clipping rectangles into framebuffer space // Project scissor/clipping rectangles into framebuffer space
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
// Clamp to viewport as wgpuRenderPassEncoderSetScissorRect() won't accept values that are off bounds
if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
continue; continue;
@ -511,7 +535,7 @@ static void ImGui_ImplWGPU_CreateFontsTexture()
WGPUSamplerDescriptor sampler_desc = {}; WGPUSamplerDescriptor sampler_desc = {};
sampler_desc.minFilter = WGPUFilterMode_Linear; sampler_desc.minFilter = WGPUFilterMode_Linear;
sampler_desc.magFilter = WGPUFilterMode_Linear; sampler_desc.magFilter = WGPUFilterMode_Linear;
sampler_desc.mipmapFilter = WGPUFilterMode_Linear; sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear;
sampler_desc.addressModeU = WGPUAddressMode_Repeat; sampler_desc.addressModeU = WGPUAddressMode_Repeat;
sampler_desc.addressModeV = WGPUAddressMode_Repeat; sampler_desc.addressModeV = WGPUAddressMode_Repeat;
sampler_desc.addressModeW = WGPUAddressMode_Repeat; sampler_desc.addressModeW = WGPUAddressMode_Repeat;
@ -552,9 +576,7 @@ bool ImGui_ImplWGPU_CreateDeviceObjects()
graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined; graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW; graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None; graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
graphics_pipeline_desc.multisample.count = 1; graphics_pipeline_desc.multisample = bd->initInfo.PipelineMultisampleState;
graphics_pipeline_desc.multisample.mask = UINT_MAX;
graphics_pipeline_desc.multisample.alphaToCoverageEnabled = false;
// Bind group layouts // Bind group layouts
WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {}; WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {};
@ -596,9 +618,9 @@ bool ImGui_ImplWGPU_CreateDeviceObjects()
// Vertex input configuration // Vertex input configuration
WGPUVertexAttribute attribute_desc[] = WGPUVertexAttribute attribute_desc[] =
{ {
{ WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, pos), 0 }, { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
{ WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, uv), 1 }, { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
{ WGPUVertexFormat_Unorm8x4, (uint64_t)IM_OFFSETOF(ImDrawVert, col), 2 }, { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
}; };
WGPUVertexBufferLayout buffer_layouts[1]; WGPUVertexBufferLayout buffer_layouts[1];
@ -641,7 +663,13 @@ bool ImGui_ImplWGPU_CreateDeviceObjects()
depth_stencil_state.depthWriteEnabled = false; depth_stencil_state.depthWriteEnabled = false;
depth_stencil_state.depthCompare = WGPUCompareFunction_Always; depth_stencil_state.depthCompare = WGPUCompareFunction_Always;
depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always; depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always;
depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep;
depth_stencil_state.stencilFront.depthFailOp = WGPUStencilOperation_Keep;
depth_stencil_state.stencilFront.passOp = WGPUStencilOperation_Keep;
depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always; depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always;
depth_stencil_state.stencilBack.failOp = WGPUStencilOperation_Keep;
depth_stencil_state.stencilBack.depthFailOp = WGPUStencilOperation_Keep;
depth_stencil_state.stencilBack.passOp = WGPUStencilOperation_Keep;
// Configure disabled depth-stencil state // Configure disabled depth-stencil state
graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state; graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state;
@ -671,6 +699,7 @@ bool ImGui_ImplWGPU_CreateDeviceObjects()
SafeRelease(vertex_shader_desc.module); SafeRelease(vertex_shader_desc.module);
SafeRelease(pixel_shader_desc.module); SafeRelease(pixel_shader_desc.module);
SafeRelease(graphics_pipeline_desc.layout);
SafeRelease(bg_layouts[0]); SafeRelease(bg_layouts[0]);
return true; return true;
@ -692,9 +721,10 @@ void ImGui_ImplWGPU_InvalidateDeviceObjects()
SafeRelease(bd->pFrameResources[i]); SafeRelease(bd->pFrameResources[i]);
} }
bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format, WGPUTextureFormat depth_format) bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Setup backend capabilities flags // Setup backend capabilities flags
@ -703,11 +733,12 @@ bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextur
io.BackendRendererName = "imgui_impl_webgpu"; io.BackendRendererName = "imgui_impl_webgpu";
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
bd->wgpuDevice = device; bd->initInfo = *init_info;
bd->wgpuDevice = init_info->Device;
bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice); bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice);
bd->renderTargetFormat = rt_format; bd->renderTargetFormat = init_info->RenderTargetFormat;
bd->depthStencilFormat = depth_format; bd->depthStencilFormat = init_info->DepthStencilFormat;
bd->numFramesInFlight = num_frames_in_flight; bd->numFramesInFlight = init_info->NumFramesInFlight;
bd->frameIndex = UINT_MAX; bd->frameIndex = UINT_MAX;
bd->renderResources.FontTexture = nullptr; bd->renderResources.FontTexture = nullptr;
@ -720,8 +751,8 @@ bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextur
bd->renderResources.ImageBindGroupLayout = nullptr; bd->renderResources.ImageBindGroupLayout = nullptr;
// Create buffers with a default size (they will later be grown as needed) // Create buffers with a default size (they will later be grown as needed)
bd->pFrameResources = new FrameResources[num_frames_in_flight]; bd->pFrameResources = new FrameResources[bd->numFramesInFlight];
for (int i = 0; i < num_frames_in_flight; i++) for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
{ {
FrameResources* fr = &bd->pFrameResources[i]; FrameResources* fr = &bd->pFrameResources[i];
fr->IndexBuffer = nullptr; fr->IndexBuffer = nullptr;
@ -761,3 +792,7 @@ void ImGui_ImplWGPU_NewFrame()
if (!bd->pipelineState) if (!bd->pipelineState)
ImGui_ImplWGPU_CreateDeviceObjects(); ImGui_ImplWGPU_CreateDeviceObjects();
} }
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE

View File

@ -8,14 +8,36 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
#include <webgpu/webgpu.h> #include <webgpu/webgpu.h>
IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format, WGPUTextureFormat depth_format = WGPUTextureFormat_Undefined); // Initialization data, for ImGui_ImplWGPU_Init()
struct ImGui_ImplWGPU_InitInfo
{
WGPUDevice Device;
int NumFramesInFlight = 3;
WGPUTextureFormat RenderTargetFormat = WGPUTextureFormat_Undefined;
WGPUTextureFormat DepthStencilFormat = WGPUTextureFormat_Undefined;
WGPUMultisampleState PipelineMultisampleState = {};
ImGui_ImplWGPU_InitInfo()
{
PipelineMultisampleState.count = 1;
PipelineMultisampleState.mask = UINT32_MAX;
PipelineMultisampleState.alphaToCoverageEnabled = false;
}
};
IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info);
IMGUI_IMPL_API void ImGui_ImplWGPU_Shutdown(); IMGUI_IMPL_API void ImGui_ImplWGPU_Shutdown();
IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame(); IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame();
IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder); IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder);
@ -23,3 +45,5 @@ IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURen
// Use if you want to reset your rendering device without losing Dear ImGui state. // Use if you want to reset your rendering device without losing Dear ImGui state.
IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects(); IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects();
IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects(); IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects();
#endif // #ifndef IMGUI_DISABLE

View File

@ -10,31 +10,20 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" // Configuration flags to add in your imconfig file:
#include "imgui_impl_win32.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <windowsx.h> // GET_X_LPARAM(), GET_Y_LPARAM()
#include <tchar.h>
#include <dwmapi.h>
// Configuration flags to add in your imconfig.h file:
//#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less relevant. //#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less relevant.
// Using XInput for gamepad (will load DLL dynamically)
#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
#include <xinput.h>
typedef DWORD (WINAPI *PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*);
typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*);
#endif
// CHANGELOG // CHANGELOG
// (minor and older changes stripped away, please see git history for details) // (minor and older changes stripped away, please see git history for details)
// 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
// 2023-09-25: Inputs: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it (same behavior as GLFW/SDL).
// 2023-09-07: Inputs: Added support for keyboard codepage conversion for when application is compiled in MBCS mode and using a non-Unicode window.
// 2023-04-19: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw Win32/Winapi with OpenGL. (#3218) // 2023-04-19: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw Win32/Winapi with OpenGL. (#3218)
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen. (#2702) // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen. (#2702)
// 2023-02-15: Inputs: Use WM_NCMOUSEMOVE / WM_NCMOUSELEAVE to track mouse position over non-client area (e.g. OS decorations) when app is not focused. (#6045, #6162) // 2023-02-15: Inputs: Use WM_NCMOUSEMOVE / WM_NCMOUSELEAVE to track mouse position over non-client area (e.g. OS decorations) when app is not focused. (#6045, #6162)
@ -84,6 +73,34 @@ typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*);
// 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging. // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
// 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set. // 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set.
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_win32.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <windowsx.h> // GET_X_LPARAM(), GET_Y_LPARAM()
#include <tchar.h>
#include <dwmapi.h>
// Using XInput for gamepad (will load DLL dynamically)
#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
#include <xinput.h>
typedef DWORD(WINAPI* PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*);
typedef DWORD(WINAPI* PFN_XInputGetState)(DWORD, XINPUT_STATE*);
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
#endif
struct ImGui_ImplWin32_Data struct ImGui_ImplWin32_Data
{ {
HWND hWnd; HWND hWnd;
@ -93,6 +110,7 @@ struct ImGui_ImplWin32_Data
INT64 Time; INT64 Time;
INT64 TicksPerSecond; INT64 TicksPerSecond;
ImGuiMouseCursor LastMouseCursor; ImGuiMouseCursor LastMouseCursor;
UINT32 KeyboardCodePage;
#ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
bool HasGamepad; bool HasGamepad;
@ -115,9 +133,20 @@ static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData()
} }
// Functions // Functions
static void ImGui_ImplWin32_UpdateKeyboardCodePage()
{
// Retrieve keyboard code page, required for handling of non-Unicode Windows.
ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
HKL keyboard_layout = ::GetKeyboardLayout(0);
LCID keyboard_lcid = MAKELCID(HIWORD(keyboard_layout), SORT_DEFAULT);
if (::GetLocaleInfoA(keyboard_lcid, (LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE), (LPSTR)&bd->KeyboardCodePage, sizeof(bd->KeyboardCodePage)) == 0)
bd->KeyboardCodePage = CP_ACP; // Fallback to default ANSI code page when fails.
}
static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
IMGUI_CHECKVERSION();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
INT64 perf_frequency, perf_counter; INT64 perf_frequency, perf_counter;
@ -137,6 +166,7 @@ static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc)
bd->TicksPerSecond = perf_frequency; bd->TicksPerSecond = perf_frequency;
bd->Time = perf_counter; bd->Time = perf_counter;
bd->LastMouseCursor = ImGuiMouseCursor_COUNT; bd->LastMouseCursor = ImGuiMouseCursor_COUNT;
ImGui_ImplWin32_UpdateKeyboardCodePage();
// Set platform dependent data in viewport // Set platform dependent data in viewport
ImGui::GetMainViewport()->PlatformHandleRaw = (void*)hwnd; ImGui::GetMainViewport()->PlatformHandleRaw = (void*)hwnd;
@ -353,9 +383,9 @@ static void ImGui_ImplWin32_UpdateGamepads()
void ImGui_ImplWin32_NewFrame() void ImGui_ImplWin32_NewFrame()
{ {
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplWin32_Init()?"); IM_ASSERT(bd != nullptr && "Context or backend not initialized? Did you call ImGui_ImplWin32_Init()?");
ImGuiIO& io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing) // Setup display size (every frame to accommodate for window resizing)
RECT rect = { 0, 0, 0, 0 }; RECT rect = { 0, 0, 0, 0 };
@ -498,6 +528,20 @@ static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam)
case VK_F10: return ImGuiKey_F10; case VK_F10: return ImGuiKey_F10;
case VK_F11: return ImGuiKey_F11; case VK_F11: return ImGuiKey_F11;
case VK_F12: return ImGuiKey_F12; case VK_F12: return ImGuiKey_F12;
case VK_F13: return ImGuiKey_F13;
case VK_F14: return ImGuiKey_F14;
case VK_F15: return ImGuiKey_F15;
case VK_F16: return ImGuiKey_F16;
case VK_F17: return ImGuiKey_F17;
case VK_F18: return ImGuiKey_F18;
case VK_F19: return ImGuiKey_F19;
case VK_F20: return ImGuiKey_F20;
case VK_F21: return ImGuiKey_F21;
case VK_F22: return ImGuiKey_F22;
case VK_F23: return ImGuiKey_F23;
case VK_F24: return ImGuiKey_F24;
case VK_BROWSER_BACK: return ImGuiKey_AppBack;
case VK_BROWSER_FORWARD: return ImGuiKey_AppForward;
default: return ImGuiKey_None; default: return ImGuiKey_None;
} }
} }
@ -537,11 +581,12 @@ static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo()
IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{ {
if (ImGui::GetCurrentContext() == nullptr) // Most backends don't have silent checks like this one, but we need it because WndProc are called early in CreateWindow().
return 0; // We silently allow both context or just only backend data to be nullptr.
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
if (bd == nullptr)
return 0;
ImGuiIO& io = ImGui::GetIO();
switch (msg) switch (msg)
{ {
@ -563,10 +608,10 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
} }
POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) }; POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) };
if (msg == WM_NCMOUSEMOVE && ::ScreenToClient(hwnd, &mouse_pos) == FALSE) // WM_NCMOUSEMOVE are provided in absolute coordinates. if (msg == WM_NCMOUSEMOVE && ::ScreenToClient(hwnd, &mouse_pos) == FALSE) // WM_NCMOUSEMOVE are provided in absolute coordinates.
break; return 0;
io.AddMouseSourceEvent(mouse_source); io.AddMouseSourceEvent(mouse_source);
io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y);
break; return 0;
} }
case WM_MOUSELEAVE: case WM_MOUSELEAVE:
case WM_NCMOUSELEAVE: case WM_NCMOUSELEAVE:
@ -579,7 +624,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
bd->MouseTrackedArea = 0; bd->MouseTrackedArea = 0;
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
} }
break; return 0;
} }
case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
@ -639,10 +684,14 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
int vk = (int)wParam; int vk = (int)wParam;
if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED)) if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED))
vk = IM_VK_KEYPAD_ENTER; vk = IM_VK_KEYPAD_ENTER;
// Submit key event
const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk); const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk);
const int scancode = (int)LOBYTE(HIWORD(lParam)); const int scancode = (int)LOBYTE(HIWORD(lParam));
// Special behavior for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit the key down event.
if (key == ImGuiKey_PrintScreen && !is_key_down)
ImGui_ImplWin32_AddKeyEvent(key, true, vk, scancode);
// Submit key event
if (key != ImGuiKey_None) if (key != ImGuiKey_None)
ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode); ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode);
@ -670,6 +719,9 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
case WM_KILLFOCUS: case WM_KILLFOCUS:
io.AddFocusEvent(msg == WM_SETFOCUS); io.AddFocusEvent(msg == WM_SETFOCUS);
return 0; return 0;
case WM_INPUTLANGCHANGE:
ImGui_ImplWin32_UpdateKeyboardCodePage();
return 0;
case WM_CHAR: case WM_CHAR:
if (::IsWindowUnicode(hwnd)) if (::IsWindowUnicode(hwnd))
{ {
@ -680,7 +732,7 @@ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARA
else else
{ {
wchar_t wch = 0; wchar_t wch = 0;
::MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1); ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1);
io.AddInputCharacter(wch); io.AddInputCharacter(wch);
} }
return 0; return 0;
@ -859,3 +911,12 @@ void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd)
} }
//--------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif // #ifndef IMGUI_DISABLE

View File

@ -10,11 +10,15 @@
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. // Learn about Dear ImGui:
// Read online: https://github.com/ocornut/imgui/tree/master/docs // - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#pragma once #pragma once
#include "imgui.h" // IMGUI_IMPL_API #include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd);
IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd); IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd);
@ -44,3 +48,5 @@ IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); //
// - Use to enable alpha compositing transparency with the desktop. // - Use to enable alpha compositing transparency with the desktop.
// - Use together with e.g. clearing your framebuffer with zero-alpha. // - Use together with e.g. clearing your framebuffer with zero-alpha.
IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd
#endif // #ifndef IMGUI_DISABLE

View File

@ -63,7 +63,7 @@ List of Platforms Backends:
imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/ imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/
imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends) imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends)
imgui_impl_sdl2.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org imgui_impl_sdl2.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org
imgui_impl_sdl3.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org (*EXPERIMENTAL*) imgui_impl_sdl3.cpp ; SDL3 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org (*EXPERIMENTAL UNTIL SDL3 IS RELEASED*)
imgui_impl_win32.cpp ; Win32 native API (Windows) imgui_impl_win32.cpp ; Win32 native API (Windows)
imgui_impl_glut.cpp ; GLUT/FreeGLUT (this is prehistoric software and absolutely not recommended today!) imgui_impl_glut.cpp ; GLUT/FreeGLUT (this is prehistoric software and absolutely not recommended today!)
@ -79,14 +79,14 @@ List of Renderer Backends:
imgui_impl_sdlrenderer2.cpp ; SDL_Renderer (optional component of SDL2 available from SDL 2.0.18+) imgui_impl_sdlrenderer2.cpp ; SDL_Renderer (optional component of SDL2 available from SDL 2.0.18+)
imgui_impl_sdlrenderer3.cpp ; SDL_Renderer (optional component of SDL3 available from SDL 3.0.0+) imgui_impl_sdlrenderer3.cpp ; SDL_Renderer (optional component of SDL3 available from SDL 3.0.0+)
imgui_impl_vulkan.cpp ; Vulkan imgui_impl_vulkan.cpp ; Vulkan
imgui_impl_wgpu.cpp ; WebGPU imgui_impl_wgpu.cpp ; WebGPU (web and desktop)
List of high-level Frameworks Backends (combining Platform + Renderer): List of high-level Frameworks Backends (combining Platform + Renderer):
imgui_impl_allegro5.cpp imgui_impl_allegro5.cpp
Emscripten is also supported! Emscripten is also supported!
The SDL+GL, GLFW+GL and SDL+WebGPU examples are all ready to build and run with Emscripten. The SDL+GL, GLFW+GL and GLFW+WebGPU examples are all ready to build and run with Emscripten.
### Backends for third-party frameworks, graphics API or other languages ### Backends for third-party frameworks, graphics API or other languages

View File

@ -5,31 +5,815 @@ This document holds the user-facing changelog that we also use in release notes.
We generally fold multiple commits pertaining to the same topic as a single entry. We generally fold multiple commits pertaining to the same topic as a single entry.
Changes to backends are also included within the individual .cpp files of each backend. Changes to backends are also included within the individual .cpp files of each backend.
RELEASE NOTES: https://github.com/ocornut/imgui/releases
REPORT ISSUES: https://github.com/ocornut/imgui/issues
DISCUSS, ASK QUESTIONS: https://github.com/ocornut/imgui/discussions
WIKI https://github.com/ocornut/imgui/wiki
FAQ https://www.dearimgui.com/faq/ FAQ https://www.dearimgui.com/faq/
RELEASE NOTES: https://github.com/ocornut/imgui/releases
WIKI https://github.com/ocornut/imgui/wiki
GETTING STARTED https://github.com/ocornut/imgui/wiki/Getting-Started
GLOSSARY https://github.com/ocornut/imgui/wiki/Glossary
ISSUES & SUPPORT https://github.com/ocornut/imgui/issues
WHEN TO UPDATE? WHEN TO UPDATE?
- Keeping your copy of Dear ImGui updated regularly is recommended. - Keeping your copy of Dear ImGui updated regularly is recommended.
- It is generally safe to sync to the latest commit in master or docking branches - It is generally safe and recommended to sync to the latest commit in 'master' or 'docking'
The library is fairly stable and regressions tends to be fixed fast when reported. branches. The library is fairly stable and regressions tends to be fixed fast when reported.
HOW TO UPDATE? HOW TO UPDATE?
- Overwrite every file except imconfig.h (if you have modified it). - Update submodule or copy/overwrite every file.
- You may also locally branch to modify imconfig.h and merge latest into your branch. - About imconfig.h:
- You may modify your copy of imconfig.h, in this case don't overwrite it.
- or you may locally branch to modify imconfig.h and merge/rebase latest.
- or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
specify a custom path for your imconfig.h file and instead not have to modify the default one.
- Read the `Breaking Changes` section (in imgui.cpp or here in the Changelog). - Read the `Breaking Changes` section (in imgui.cpp or here in the Changelog).
- If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it. - If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it.
- If you are dropping this repository in your codebase, please leave the demo and text files in there, they will be useful. - If you are copying this repository in your codebase, please leave the demo and documentations files in there, they will be useful.
- You may diff your previous Changelog with the one you just copied and read that diff. - You may diff your previous Changelog with the one you just copied and read that diff.
- You may enable `IMGUI_DISABLE_OBSOLETE_FUNCTIONS` in imconfig.h to forcefully disable legacy names and symbols. - You may enable `IMGUI_DISABLE_OBSOLETE_FUNCTIONS` in imconfig.h to forcefully disable legacy names and symbols.
Doing it every once in a while is a good way to make sure you are not using obsolete symbols. Dear ImGui is in active development, Doing it every once in a while is a good way to make sure you are not using obsolete symbols. Dear ImGui is in active development,
and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users. and API updates have been a little more frequent lately. They are documented below and in imgui.cpp and should not affect all users.
- Please report any issue! - Please report any issue!
-----------------------------------------------------------------------
VERSION 1.90.7 (Released 2024-05-27)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.7
Breaking changes:
- Inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent(),
as this naturally align with how macOS X uses those keys. (#2343, #4084, #5923, #456)
- Effectively it means that e.g. ImGuiMod_Ctrl | ImGuiKey_C is a valid idiomatic shortcut
for both Windows and Mac style users.
- It shouldn't really affect your code unless you had explicit/custom shortcut swapping in
place for macOS X apps in your input logic.
- Removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super.
It is now unnecessary to specific cross-platform idiomatic shortcuts.
Kept symbols redirecting ImGuiMod_Shortcut to ImGuiMod_Ctrl (will obsolete).
- Commented out obsolete symbols renamed in 1.88 (May 2022):
CaptureKeyboardFromApp() -> SetNextFrameWantCaptureKeyboard()
CaptureMouseFromApp() -> SetNextFrameWantCaptureMouse()
- Backends: SDL_Renderer2/SDL_Renderer3: ImGui_ImplSDLRenderer2_RenderDrawData() and
ImGui_ImplSDLRenderer3_RenderDrawData() now takes a SDL_Renderer* parameter. This was previously
overlooked from the API but it will allow eventual support for multi-viewports.
Other changes:
- Windows: BeginChild(): fixed visibility of fully clipped child windows and tables to Test Engine.
- Windows: BeginChild(): fixed auto-fit calculation when using either (not both) ResizeX/ResizeY
and double-clicking on a border. Calculation incorrectly didn't always account for scrollbar as
it assumed the other axis would also be auto-fit. (#1710)
- Inputs: added shortcut and routing system in public API. (#456, #2637) [BETA]
- The general idea is that several callers may register interest in a shortcut, and only one owner gets it.
- in Parent: call Shortcut(Ctrl+S) // When Parent is focused, Parent gets the shortcut.
- in Child1: call Shortcut(Ctrl+S) // When Child1 is focused, Child1 gets the shortcut (Child1 overrides Parent shortcuts)
- in Child2: no call // When Child2 is focused, Parent gets the shortcut.
The whole system is order independent, so if Child1 makes its calls before Parent, results will be identical.
This is an important property as it facilitate working with foreign code or larger codebase.
- Added Shortcut() function:
e.g. Using ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_C); with default policy:
- checks that CTRL+C is pressed,
- and that current window is in focus stack,
- and that no other requests for CTRL+C have been made from higher priority locations
(e.g. deeper in the window/item stack).
- Added SetNextItemShortcut() to set a shortcut to locally or remotely press or activate
an item (depending on specified routing policy: using ImGuiInputFlags_RouteGlobal the item
shortcut may be executed even if its window is not in focus stack).
Items like buttons are not fully activated, in the sense that they get pressed but another
active item, e.g. InputText() won't be deactivated.
- Added routing policies for Shortcut(), SetNextItemShortcut(): (#456, #2637)
- ImGuiInputFlags_RouteFocused: focus stack route (default)
- ImGuiInputFlags_RouteActive: only route to active item
- ImGuiInputFlags_RouteGlobal: route globally, unless a focus route claim shame shortcut.
- ImGuiInputFlags_RouteAlways: no routing submission, no routing check.
- Added other shortcut/routing options: (#456, #2637)
- ImGuiInputFlags_Repeat: for use by Shortcut() and by upcoming rework of various
input functions (which are still internal for now).
- ImGuiInputFlags_Tooltip: for SetNextItemShortcut() to show a tooltip when hovering item.
- ImGuiInputFlags_RouteOverFocused: global route takes priority over focus route.
- ImGuiInputFlags_RouteOverActive: global route takes priority over active item.
- ImGuiInputFlags_RouteUnlessBgFocused: global route disabled if no imgui window focused.
- ImGuiInputFlags_RouteFromRootWindow: route evaluated from the point of view of root window rather than current window.
- Inputs: (OSX) Fixes variety of code which inconsistently required using Ctrl instead of Cmd.
- e.g. Drags/Sliders now use Cmd+Click to input a value. (#4084)
- Some shortcuts still uses Ctrl on Mac: e.g. Ctrl+Tab to switch windows. (#4828)
- Inputs: (OSX) Ctrl+Left Click alias as a Right click. (#2343) [@haldean, @ocornut]
- Inputs: Fixed ImGui::GetKeyName(ImGuiKey_None) from returning "N/A" or "None" depending
on value of IMGUI_DISABLE_OBSOLETE_KEYIO. It always returns "None".
- Nav: fixed holding Ctrl or gamepad L1 from not slowing down keyboard/gamepad tweak speed.
Broken during a refactor refactor for 1.89. Holding Shift/R1 to speed up wasn't broken.
- Tables: fixed cell background of fully clipped row overlapping with header. (#7575, #7041) [@prabuinet]
- Demo: Added "Inputs & Focus -> Shortcuts" section. (#456, #2637)
- Demo: Documents: Added shortcuts and renaming tabs/documents. (#7233)
- Examples: Win32+DX9,DX10,DX11,DX12: rework main loop to handle minimization and screen
locking without burning resources by running unthrottled code. (#2496, #3907, #6308, #7615)
- Backends: all backends + demo now call IMGUI_CHECKVERSION() to verify ABI compatibility between caller
code and compiled version of Dear ImGui. If you get an assert it most likely mean you have a build issue,
read comments near the assert. (#7568)
- Backends: Win32: undo an assert introduced in 1.90.6 which didn't allow WndProc
handler to be called before backend initialization. Because of how ::CreateWindow()
calls in WndProc this is facilitating. (#6275) [@MennoVink]
- Backends, Examples: SDL3: updates for latest SDL3 API changes. (#7580) [@kuvaus, @ocornut]
Breaking changes IF you were using imgui_internal.h versions of Shortcut() or owner-aware
versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked() prior to this version:
- Inputs (Internals): Renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more
explicit and reduce confusion with the fact it is a non-zero value and cannot be a default.
- Inputs (Internals): Renamed symbols global routes:
Renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal (this is the suggested global route)
Renamed ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
Renamed ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive
- Inputs (Internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order
in function signatures:
Before: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
After: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
- Inputs (Internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked():
swapped last two parameters order in function signatures:
Before: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
After: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
Before: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
After: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
- For several reasons those changes makes sense. They were all made before making some of
those API public. Only past users of imgui_internal.h with the extra parameters will be affected.
Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
-----------------------------------------------------------------------
VERSION 1.90.6 (Released 2024-05-08)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.6
Breaking changes:
- TreeNode: Fixed a layout inconsistency when using a empty/hidden label followed
by a SameLine() call. (#7505, #282)
Before: TreeNode("##Hidden"); SameLine(); Text("Hello");
// This was actually incorrect! BUT appeared to look ok with the default style
// where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
After: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello");
// This is correct for all values in style.
With the fix, IF you were successfully using TreeNode("")+SameLine(); you will now
have extra spacing between your TreeNode and the following item. You'll need to change
the SameLine() call to SameLine(0,0) to remove this extraneous spacing.
This seemed like the more sensible fix that's not making things less consistent.
(Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
Other changes:
- Windows: Changed default ClipRect to extend to windows' left and right borders,
instead of adding arbitrary WindowPadding.x * 0.5f space on left and right.
That ClipRect half-padding was arbitrary/confusing and inconsistent with Y axis.
It also made it harder to draw items covering whole window without pushing an
extended ClipRect. Some items near windows left and right edge that used to be clipped
may be partly more visible. (#3312, #7540, #3756, #6170, #6365)
- Windows: Fixed subsequent Begin() append calls from setting last item information
for title bar, making it impossible to use IsItemHovered() on a Begin()-to-append,
and causing issue bypassing hover detection on collapsed windows. (#7506, #823)
- Fonts: Fixed font ascent and descent calculation when a font hits exact integer values.
It is possible that some prior manual use of ImFontConfig::GlyphOffset may become
duplicate with this fix. (#7399, #7404) [@GamingMinds-DanielC]
- TreeNode: Added ImGuiTreeNodeFlags_SpanTextWidth to make hitbox and highlight only
cover the label. (#6937) [@dimateos]
- Tables: Angled headers: fixed multi-line label display when angle is flipped. (#6917)
- Tables: Angled headers: added style.TableAngledHeadersTextAlign and corresponding
ImGuiStyleVar_TableAngledHeadersTextAlign variable. Default to horizontal center. (#6917)
[@thedmd, @ocornut]
- ProgressBar: Added support for indeterminate progress bar by passing an animated
negative fraction, e.g. ProgressBar(-1.0f * GetTime()). (#5316, #5370, #1901)[@gan74]
- Text, DrawList: Improved handling of long single-line wrapped text. Faster and
mitigate issues with reading vertex indexing limits with 16-bit indices. (#7496, #5720)
- Backends: OpenGL3: Detect ES3 contexts on desktop based on version string,
to e.g. avoid calling glPolygonMode() on them. (#7447) [@afraidofdark, @ocornut]
- Backends: OpenGL3: Update loader for Linux to support EGL/GLVND. (#7562) [@ShadowNinja, @vanfanel]
- Backends: Vulkan: Added convenience support for Volk via IMGUI_IMPL_VULKAN_USE_VOLK define.
(you could always use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + ImGui_ImplVulkan_LoadFunctions() as well).
(#6582, #4854) [@adalsteinnh, @kennyalive, @ocornut]
- Backends: SDL3: Fixed text inputs. Re-enable calling SDL_StartTextInput()/SDL_StopTextInput()
as SDL3 no longer enables it by default. (#7452, #6306, #6071, #1953) [@Green-Sky]
- Examples: GLFW+Vulkan, SDL+Vulkan: Added optional support for Volk. (#6582, #4854)
- Examples: GLFW+WebGPU: Added support for WebGPU-native/Dawn (#7435, #7132) [@eliasdaler, @Zelif]
- Examples: GLFW+WebGPU: Renamed example_emscripten_wgpu/ to example_glfw_wgpu/. (#7435, #7132)
-----------------------------------------------------------------------
VERSION 1.90.5 (Released 2024-04-11)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.5
Breaking changes:
- More formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set.
It has been unnecessary and a no-op since 1.87 (it returns the same value as passed
when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
- IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) --> IsKeyPressed(ImGuiKey_XXX)
- ImDrawList: Merged the radius_x/radius_y parameters in AddEllipse(), AddEllipseFilled()
and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those
functions were added recently in 1.90, we are not adding inline redirection functions.
The transition is easy and should affect few users. (#2743, #7417) [@cfillion]
Other changes:
- Windows: Scrollbar visibility decision uses current size when both size and contents
size are submitted by API. (#7252)
- Windows: Double-click to collapse may be disabled via key-ownership mechanism. (#7369)
- Windows: BeginChild(): Extend outer resize borders to the edges when there are no corner
grips. Essentially affects resizable child windows. (#7440, #1710) [@cfillion]
- Windows: BeginChild(): Resizing logic for child windows evaluates whether per-axis clamping
should be applied based on parent scrollbars, not child scrollbars. (#7440, #1710) [@cfillion]
Adjust those resizing limits to match window padding rather than inner clipping rectangle.
- Tables: Fixed auto-width columns when using synced-instances of same table, width of
one instance would bleed into next one instead of sharing their widths. (#7218)
- Tables: Angled headers: fixed border hit box extending beyond when used within
non-scrollable tables. (#7416) [@cfillion]
- Tables: Angled headers: fixed borders not moving back up after TableAngleHeadersRow()
stops being called. (#7416) [@cfillion]
- Tables: Angled headers: rounding header size to nearest integers, fixes some issues
when using clipper.
- Menus, Popups: Fixed an issue where sibling menu popups re-opening in successive
frames would erroneously close the window. While it is technically a popup issue
it would generally manifest when fast moving the mouse bottom to top in a sub-menu.
(#7325, #7287, #7063)
- ProgressBar: Fixed passing fraction==NaN from leading to a crash. (#7451)
- ListBox: Fixed text-baseline offset when using SameLine()+Text() after a labeled ListBox().
- Drags, Sliders, Inputs: Fixed io.PlatformLocaleDecimalPoint decimal point localization
feature not working regression from 1.90.1. (#7389, #6719, #2278) [@GamingMinds-DanielC]
- Style: Added ImGuiStyleVar_TabBorderSize, ImGuiStyleVar_TableAngledHeadersAngle for
consistency. (#7411) [@cfillion]
- DrawList: Added AddConcavePolyFilled(), PathFillConcave() concave filling. (#760) [@thedmd]
Note that only simple polygons (no self-intersections, no holes) are supported.
- DrawList: Allow AddText() to accept null ranges. (#3615, 7391)
- Docs: added more wiki links to headers of imgui.h/imgui.cpp to facilitate discovery
of interesting resources, because github doesn't allow Wiki to be crawled by search engines.
- This is the main wiki: https://github.com/ocornut/imgui/wiki
- This is the crawlable version: https://github-wiki-see.page/m/ocornut/imgui/wiki
Adding a link to the crawlable version, even though it is not intended for humans,
to increase its search rank.
-----------------------------------------------------------------------
VERSION 1.90.4 (Released 2024-02-22)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.4
Other changes:
- Nav: Fixed SetKeyboardFocusHere() or programmatic tabbing API from not working on
windows with the ImGuiWindowFlags_NoNavInputs flag (regression in 1.90.2, which
among other things broke imgui_memory_editor).
- Menus, Popups: Fixed an issue where hovering a parent-menu upward would
erroneously close the window. (#7325, #7287, #7063)
- Popups: Fixed resizable popup minimum size being too small. Standardized minimum
size logic. (#7329).
- Modals: Temporary changes of ImGuiCol_ModalWindowDimBg are properly handled by
BeginPopupModal(). (#7340)
- Tables: Angled headers: fixed support for multi-line labels. (#6917)
- Tables: Angled headers: various fixes to accurately handle CellPadding changes. (#6917)
- Tables: Angled headers: properly registers horizontal component of angled headers
for auto-resizing of columns. (#6917)
- Tables: Angled headers: fixed TableAngledHeadersRow() incorrect background fill
drawn too low, particularly visible with tables that have no scrolling. (#6917)
- ProgressBar: Fixed a minor tessellation issue when rendering rounded progress bars,
where in some situations the rounded section wouldn't follow regular tessellation rules.
- Debug Tools: Item Picker: Promoted ImGui::DebugStartItemPicker() to public API. (#2673)
- Debug Tools: Item Picker: Menu entry visible in Demo->Tools but greyed out unless
io.ConfigDebugIsDebuggerPresent is set. (#2673)
- Misc: Added optional alpha multiplier parameter to GetColorU32(ImU32) variant.
- Demo: Custom Rendering: better demonstrate PathArcTo(), PathBezierQuadraticCurveTo(),
PathBezierCubicCurveTo(), PathStroke(), PathFillConvex() functions.
-----------------------------------------------------------------------
VERSION 1.90.3 (Released 2024-02-14)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.3
Breaking changes:
- Backends: SDL2: Removed obsolete ImGui_ImplSDL2_NewFrame(SDL_Window*) signature which
was obsoleted in 1.84. Calling ImGui_ImplSDL2_NewFrame() is fine.
- Backends: Vulkan: Moved RenderPass parameter from ImGui_ImplVulkan_Init() function to
ImGui_ImplVulkan_InitInfo structure. Not required when using dynamic rendering. (#7308) [@shawnhatori]
- Backends: Vulkan: Using dynamic rendering now require filling the PipelineRenderingCreateInfo
structure in ImGui_ImplVulkan_InitInfo, allowing to configure color/depth/stencil formats.
Removed ColorAttachmentFormat field previously provided for dynamic rendering.
(#7166, #6855, #5446, #5037) [@shawnhatori]
Other changes:
- Menus, Popups: Fixed menus and popups with ChildWindow flag erroneously not displaying
a scrollbar when contents is over parent viewport size. (#7287, #7063) [@ZingBallyhoo]
- Backends: SDL2, SDL3: Handle gamepad disconnection + fixed increasing gamepad reference
counter continuously. Added support for multiple simultaneous gamepads.
Added ImGui_ImplSDL2_SetGamepadMode()) function to select whether to automatically pick
first available gamepad, all gamepads, or specific gamepads.
(#3884, #6559, #6890, #7180) [@ocornut, @lethal-guitar, @wn2000, @bog-dan-ro]
- Backends: SDL3: Fixed gamepad handling. (#7180) [@bog-dan-ro]
- Backends: SDLRenderer3: query newly added SDL_RenderViewportSet() to not restore
a wrong viewport if none was initially set.
- Backends: DirectX9: Using RGBA format when allowed by the driver to avoid CPU side
conversion. (#6575) [@Demonese]
- Internals: Fixed ImFileOpen not working before context is created, preventing creation
of a font atlas before main context creation. (#7314, #7315) [@PathogenDavid, @ocornut]
-----------------------------------------------------------------------
VERSION 1.90.2 (Released 2024-02-09)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.2
Breaking changes:
- Commented out ImGuiIO::ImeWindowHandle obsoleted in 1.87 in favor of writing
to 'void* ImGuiViewport::PlatformHandleRaw'.
- Backends: WebGPU: ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure
instead of variety of parameters, allowing for easier further changes. (#7240)
Other changes:
- Nav: keyboard/gamepad activation mark widgets as held to give better visual feedback.
- Nav: tweak to logic marking navigated item as hovered when using keyboard, allowing
the hover highlight to stay even while another item is activated.
- Nav: Fixed SetKeyboardFocusHere() not working when current nav focus is in different scope,
regression from 1.90.1 related to code scoping Tab presses to local scope. (#7226) [@bratpilz]
- Nav: Fixed pressing Escape while in a child window with _NavFlattened flag. (#7237)
- Nav: Improve handling of Alt key to toggle menu so that key ownership may be claimed on
individual left/right alt key without interfering with the other.
- Nav, Menus: Fixed click on a BeginMenu() followed by right-arrow from making the child menu
reopen and flicker (using ImGuiPopupFlags_NoReopen).
- Nav: ImGuiWindowFlags_NoNavInputs is tested during scoring so NavFlattened windows can use it.
- Popups: OpenPopup(): added ImGuiPopupFlags_NoReopen flag to specifically not close and reopen
a popup when it is already open. (#1497, #1533)
(Note that this differs from specific handling we already have in place for the case of calling
OpenPopup() repeatedly every frame: we already didn't reopen in that specific situation, otherwise
the effect would be very disastrous in term of confusion, as reopening would steal focus).
- Popups: Slight change to popup closing logic (e.g. after focusing another window) which skipped
over popups that are also child windows.
- Combo: Fixed not reusing windows optimally when used inside a popup stack.
- Debug Tools: Metrics: Fixed debug break in SetShortcutRouting() not handling ImGuiMod_Shortcut redirect.
- Debug Tools: Metrics: Improved Monitors and Viewports minimap display. Highlight on hover.
- Debug Tools: Debug Log: Added "Input Routing" logging.
- Debug Tools: Added "nop" to IM_DEBUG_BREAK macro on GCC to work around GDB bug (#7266) [@Peter0x44]
- Backends: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by
allocating one extra semaphore than in-flight frames. (#7236) [@mklefrancois]
- Backends: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size. (#3957)
- Backends: Vulkan: Fixed handling of ImGui_ImplVulkan_InitInfo::MinAllocationSize field. (#7189, #4238)
- Backends: WebGPU: Added ImGui_ImplWGPU_InitInfo::PipelineMultisampleState. (#7240)
- Backends: WebGPU: Filling all WGPUDepthStencilState fields explicitly as a recent Dawn
update stopped setting default values. (#7232) [@GrigoryGraborenko]
- Backends: WebGPU: Fixed pipeline layout leak. (#7245) [@rajveermalviya]
- Backends: OpenGL3: Backup and restore GL_PIXEL_UNPACK_BUFFER. (#7253)
- Internals: Many improvements related to yet unpublicized shortcut routing and input ownership systems.
- Internals: InputText: Added internal helpers to force reload of user-buf when active. (#2890) [@kudaba, @ocornut]
Often requested in some form (#6962, #5219, #3290, #4627, #5054, #3878, #2881, #1506, #1216, #968),
and useful for interactive completion/suggestions popups (#2057, #718)
-----------------------------------------------------------------------
VERSION 1.90.1 (Released 2024-01-10)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90.1
Breaking changes:
- imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81.
Prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
- Removed CalcListClipping() marked obsolete in 1.86. (#3841)
Prefer using ImGuiListClipper which can return non-contiguous ranges.
- Internals, Columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting
to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
- Commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter. (#2625, #7143)
Other changes:
- Windows:
- BeginChild(): Fixed auto-resizing erroneously limiting size to host viewport
minus padding. There are no limit to a child width/height. (#7063) [@Devyre]
- BeginChild(): Resize borders rendered even when ImGuiWindowFlags_NoBackground
is specified. (#1710, #7194)
- Fixed some auto-resizing path using style.WindowMinSize.x (instead of x/y)
for both axises since 1.90. (#7106) [@n0bodysec]
- Scrolling: internal scrolling value is rounded instead of truncated, as a way to reduce
speed asymmetry when (incorrectly) attempting to scroll by non-integer amount. (#6677)
- Navigation (Keyboard/gamepad):
- Nav, IO: SetNextFrameWantCaptureKeyboard(false) calls are not overridden back to true when
navigation is enabled. SetNextFrameWantCaptureKeyboard() is always higher priority. (#6997)
- Nav: Activation can also be performed with Keypad Enter. (#5606)
- Drag and Drop:
- Fixed drop target highlight on items temporarily pushing a widened clip rect
(namely Selectables and Treenodes using SpanAllColumn flag) so the highlight properly covers
all columns. (#7049, #4281, #3272)
- InputText:
- InputTextMultiline: Fixed Tab character input not repeating (1.89.4 regression).
- InputTextMultiline: Tabbing through a multi-line text editor which allows Tab character inputs
(using the ImGuiInputTextFlags_AllowTabInput flag) doesn't automatically activate it, in order
to allow passing through multiple widgets easily. (#3092, #5759, #787)
- Drags, Sliders, Inputs:
- DragScalarN, SliderScalarN, InputScalarN: Fixed incorrect pushes into ItemWidth
stack when number of components is 1. [#7095] [@Nahor]
- Drags, Sliders, Inputs: removed all attempts to filter non-numerical characters during text
editing. Invalid inputs not applied to value, visibly reverted after validation. (#6810, #7096)
- Drags, Sliders, Inputs: removal of filter means that "nan" and "inf" values may be input. (#7096)
- DragScalarN, SliderScalarN, InputScalarN, PushMultiItemsWidths: improve multi-components
width computation to better distribute the error. (#7120, #7121) [@Nahor]
- Menus:
- Tweaked hover slack logic, adding an extra timeout to avoid situations where a slow vertical
movements toward another parent BeginMenu() can keep the wrong child menu open. (#6671, #6926)
- Color Editors:
- ColorEdit: Layout tweaks for very small sizes. (#7120, #7121)
- ColorPicker: Fixed saturation/value cursor radius not scaling properly.
- Tabs: Added ImGuiTabItemFlags_NoAssumedClosure to enable app to react on closure attempt,
without having to draw an unsaved document marker (ImGuiTabItemFlags_UnsavedDocument sets
_NoAssumedClosure automatically). (#7084)
- Debug Tools:
- Added io.ConfigDebugIsDebuggerPresent option. When enabled, this adds buttons in various
locations of Metrics/Debugger to manually request a debugger break:
- Request a debug break in a Begin() call.
- Request a debug break in a ItemAdd() call via debug log and hovering 0xXXXXXX identifiers.
- Request a debug break in a BeginTable() call.
- Request a debug break in a SetShortcutRouting()/Shortcut() call. [Internal]
- Metrics: Reorganize Tools menu.
- Added DebugFlashStyleColor() to identify a style color. Added to Style Editor.
- Debug Log: Hide its own clipper log to reduce noise in the output. (#5855)
- Debug Log: Clicking any filter with SHIFT held enables it for 2 frames only,
making it easier when dealing with spammy logs. (#5855)
- Settings: Fixed an issue marking settings as dirty when merely clicking on a border or resize
grip without moving it.
- Misc: Added IMGUI_USER_H_FILENAME to change the path included when using
IMGUI_INCLUDE_IMGUI_USER_H. (#7039) [@bryceberger]
- Misc: Rework debug display of texture id in Metrics window to avoid compile-error when
ImTextureID is defined to be larger than 64-bits. (#7090)
- Misc: Added extra courtesy ==/!= operators when IMGUI_DEFINE_MATH_OPERATORS is defined.
- Misc: Fixed text functions fast-path for handling "%s" and "%.*s" to handle null pointers gracefully,
like most printf implementations. (#7016, #3466, #6846) [@codefrog2002]
- Misc: Renamed some defines in imstb_textedit.h to avoid conflicts when using unity/jumbo builds
on a codebase where another copy of the library is used.
- Misc: During shutdown, check that io.BackendPlatformUserData and io.BackendRendererUserData are NULL
in order to catch cases where backend was not shut down. (#7175)
- Misc: Reworked Issue Template to a shinier and better form. (#5927) [@Panquesito7, @PathogenDavid, @ocornut]
- Backends:
- GLFW, Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to
register canvas selector and auto-resize GLFW window. (#6751) [@Traveller23, @ypujante]
- GLFW: Fixed Windows specific hooks to use Unicode version of WndProc even when
compiling in MBCS mode. (#7174) [@kimidaisuki22]
- OpenGL3: Update GL3W based imgui_impl_opengl3_loader.h to load libGL.so variants in
case of missing symlink. Fix 1.90 regression for some distros. (#6983)
- Vulkan: Fixed mismatching allocator passed to vkCreateCommandPool() vs
vkDestroyCommandPool(). (#7075) [@FoonTheRaccoon]
- Vulkan: Added MinAllocationSize field in ImGui_ImplVulkan_InitInfo to workaround zealous
"best practice" validation layer. (#7189, #4238) [@philae-ael]
- Vulkan: Stopped creating command pools with VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT
as we don't reset them.
- WebGPU: Fixed wgpuRenderPassEncoderSetScissorRect() crash when rendering modal window's
dimming layer, which has an unclipped value in ImDrawCmd::ClipRect. (#7191) [@aparis69]
- Examples:
- Examples: GLFW+Emscripten: Fixed examples not consistently resizing according to host canvas.
(#6751) [@Traveller23, @ypujante]
- Examples: SDL3: Minor fixes following recent SDL3 in-progress development.
-----------------------------------------------------------------------
VERSION 1.90.0 (Released 2023-11-15)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.90
Breaking changes:
- BeginChild(): Upgraded 'bool border = false' parameter to 'ImGuiChildFlags flags = 0'.
Added ImGuiChildFlags_Border value. As with our prior "bool-to-flags" API updates,
the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a
smoother transition, meaning all existing calls will still work.
If you want to neatly transition your call sites:
Before: BeginChild("Name", size, true)
After: BeginChild("Name", size, ImGuiChildFlags_Border)
Before: BeginChild("Name", size, false)
After: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
Existing code will still work as 'ImGuiChildFlags_Border == true', but you are encouraged to update call sites.
- BeginChild(): Added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for
the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense
for use with BeginChild() anyhow, passing it to Begin() had no effect. Now that we accept
child-flags we are moving it there. (#462)
Before: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
After: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
Kept inline redirection enum (will obsolete later) so existing code will work.
- BeginChildFrame()/EndChildFrame(): removed functions in favor of using BeginChild() with
the ImGuiChildFlags_FrameStyle flag. Kept inline redirection function (will obsolete).
Those functions were merely PushStyle/PopStyle helpers and custom versions are easy to create.
(The removal isn't so much motivated by needing to add the feature in BeginChild(), but by the
necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.)
- Debug Tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"),
as earlier name was misleading. Kept inline redirection function. (#4631)
- IO: Removed io.MetricsActiveAllocations introduced in 1.63, was displayed in Metrics and unlikely to
be accessed by end-user. Value still visible in the UI and easily to recompute from a delta.
- Defining IMGUI_DISABLE_OBSOLETE_FUNCTIONS now automatically defines IMGUI_DISABLE_OBSOLETE_KEYIO. (#4921)
- Removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define. (#4537)
- ListBox, Combo: Changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis.
Before:
getter type: bool (*getter)(void* user_data, int idx, const char** out_text)
function: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...);
function: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
After:
getter type: const char* (*getter)(void* user_data, int idx)
function: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
function: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
Old type was unnecessarily complex and harder to wrap in e.g. a lambda. Kept inline redirection function (will obsolete).
- Commented out obsolete redirecting enums/functions that were marked obsolete two years ago:
- GetWindowContentRegionWidth() -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x.
Consider that generally 'GetContentRegionAvail().x' is often more correct and more useful.
- ImDrawCornerFlags_XXX -> use ImDrawFlags_RoundCornersXXX names.
Read 1.82 changelog for details + grep commented names in sources.
- Commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for
AddRect()/AddRectFilled()/PathRect()/AddImageRounded(). -> Use ImDrawFlags_RoundCornersXXX flags.
Read 1.82 changelog for details.
- Backends: Vulkan: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own
command-buffer to upload fonts. Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unnecessary.
No need to call ImGui_ImplVulkan_CreateFontsTexture() as it is done automatically in ImGui_ImplVulkan_NewFrame().
You can call ImGui_ImplVulkan_CreateFontsTexture() manually if you need to reload the font atlas texture.
(#6943, #6715, #6327, #3743, #4618)
Other changes:
- Windows:
- BeginChild(): Added ImGuiChildFlags_ResizeX and ImGuiChildFlags_ResizeY to allow resizing
child windows from the bottom/right border (toward layout direction). Resized child windows
settings are saved and persistent in .ini file. (#1710)
- BeginChild(): Added ImGuiChildFlags_Border as a replacement for 'bool border = true' parameter.
- BeginChild(): Added ImGuiChildFlags_AutoResizeX and ImGuiChildFlags_AutoResizeY to auto-resize
on one axis, while generally providing a size on the other axis. (#1666, #1395, #1496, #1710)
e.g. BeginChild("name", {-FLT_MIN, 0.0f}, ImGuiChildFlags_AutoResizeY);
- Size is only reevaluated if the child window is within visible boundaries or just appearing.
This allows coarse clipping to be performed and auto-resizing childs to return false when
hidden because of being scrolled out.
- Combining this with also specifying ImGuiChildFlags_AlwaysAutoResize disables
this optimization, meaning child contents will never be clipped (not recommended).
- Please be considerate that child are full windows and carry significant overhead:
combining auto-resizing for both axises to create a non-scrolling child to merely draw
a border would be better more optimally using BeginGroup(). (see #1496)
(until we come up with new helpers for framed groups and work-rect adjustments).
- BeginChild(): made it possible to use SetNextWindowSizeConstraints() rectangle, often
useful when ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY. (#1666, #1395, #1496)
Custom constraint callback are not supported with child window.
- BeginChild(): Added ImGuiChildFlags_FrameStyle as a replacement for BeginChildFrame(),
use it to make child window use FrameBg, FrameRounding, FrameBorderSize, FramePadding
instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding.
- Popups: clarified meaning of 'p_open != NULL' in BeginPopupModal() + set back user value
to false when popup is closed in ways other than clicking the close button. (#6900)
- Double-clicking lower-left resize grip auto-resize (like lower-right one).
- Double-clicking bottom or right window border auto-resize on a singles axis.
- Use relative mouse movement for border resize when the border geometry has moved
(e.g. resizing a child window triggering parent scroll) in order to avoid resizing
feedback loops. Unless manually mouse-wheeling while border resizing. (#1710)
- Separators:
- Altered end-points to use more standard boundaries. (#205, #4787, #1643)
Left position is always current cursor X position, right position is always work-rect
rightmost edge. It effectively means that:
- A separator in the root of a window will end up a little more distant from edges
than previously (essentially following WindowPadding instead of clipping edges).
- A separator inside a table cell end up a little distance from edges instead of
touching them (essentially following CellPadding instead of clipping edges).
- Matches tree indentation (was not the case before).
- Matches SeparatorText(). (#1643)
- Makes things correct inside groups without specific/hard-coded handling. (#205)
- Support legacy behavior when used inside old Columns(), as we favored that idiom back then,
only different is left position follows indentation level, to match calling a Separator()
inside or outside Columns().
- Tooltips:
- Made using SetItemTooltip()/IsItemHovered(ImGuiHoveredFlags_ForTooltip) defaults to
activate tooltips on disabled items. This is done by adding ImGuiHoveredFlags_AllowWhenDisabled
to the default value of style.HoverFlagsForTooltipMouse/HoverFlagsForTooltipNav. (#1485)
- Made is possible to combine ImGuiHoveredFlags_ForTooltip with a ImGuiHoveredFlags_DelayXXX
override. (#1485)
- Drag and Drop:
- Reworked drop target highlight: reduce rectangle to its visible portion, and then expand
slightly. A full rectangle is always visible and it may protrude slightly. (#4281, #3272)
- Fixed submitting a tooltip from drop target location when using AcceptDragDropPayload()
with ImGuiDragDropFlags_AcceptNoPreviewTooltip and submitting a tooltip manually.
- Tables:
- Added angled headers support. You need to set ImGuiTableColumnFlags_AngledHeader on selected
columns and call TableAngledHeadersRow(). Added style.TableAngledHeadersAngle style option. (#6917)
- Added ImGuiTableFlags_HighlightHoveredColumn flag, currently highlighting column header.
- Fixed an edge-case when no columns are visible + table scrollbar is visible + user
code is always testing return value of TableSetColumnIndex() to coarse clip. With an active
clipper it would have asserted. Without a clipper, the scrollbar range would be wrong.
- Request user to submit contents when outer host-window is requesting auto-resize,
so a scrolling table can contribute to initial window size. (#6510)
- Fixed subtle drawing overlap between borders in some situations.
- Fixed bottom-most and right-most outer border offset by one. (#6765, #3752) [@v-ein]
- Fixed top-most and left-most outer border overlapping inner clip-rect when scrolling. (#6765)
- Fixed top-most outer border being drawn with both TableBorderLight and TableBorderStrong
in some situations, causing the earlier to be visible underneath when alpha is not 1.0f.
- Fixed right-clicking right-most section (past right-most column) from highlighting a column.
- Fixed an issue with ScrollX enabled where an extraneous draw command would be created.
- Menus:
- Menus: Fixed a bug where activating an item in a child-menu and dragging mouse over the
parent-menu would erroneously close the child-menu. (Regression from 1.88). (#6869)
- MenuBar: Fixed an issue where layouting an item in the menu-bar would erroneously
register contents size in a way that would affect the scrolling layer.
Was most often noticeable when using an horizontal scrollbar. (#6789)
- InputText:
- InputTextMultiline: Fixed a crash pressing Down on last empty line of a multi-line buffer.
(regression from 1.89.2, only happened in some states). (#6783, #6000)
- InputTextMultiline: Fixed Tabbing cycle leading to a situation where Enter key wouldn't
be accepted by the widget when navigation highlight is visible. (#6802, #3092, #5759, #787)
- Nav: Tabbing always enable nav highlight when ImGuiConfigFlags_NavEnableKeyboard is set.
Previously was inconsistent and only enabled when stepping through a non-input item.
(#6802, #3092, #5759, #787)
- TreeNode: Added ImGuiTreeNodeFlags_SpanAllColumns for use in tables. (#3151, #3565, #2451, #2438)
- TabBar: Fixed position of unsaved document marker (ImGuiTabItemFlags_UnsavedDocument) which was
accidentally offset in 1.89.9. (#6862) [@alektron]
- ColorPicker4(): Fixed ImGuiColorEditFlags_NoTooltip not being forwarded to individual DragFloat3
sub-widgets which have a visible color preview when ImGuiColorEditFlags_NoSidePreview is also set. (#6957)
- BeginGroup(): Fixed a bug pushing line lower extent too far down when called after a call
to SameLine() followed by manual cursor manipulation.
- BeginCombo(): Added ImGuiComboFlags_WidthFitPreview flag. (#6881) [@mpv-enjoyer]
- BeginListBox(): Fixed not consuming SetNextWindowXXX() data when returning false.
- Fonts:
- Argument 'float size_pixels' passed to AddFontXXX() functions is now rounded to lowest integer.
This is because our layout/font system currently doesn't fully support non-integer sizes. Until
it does, this has been a common pitfall leading to more or less subtle issues. (#3164, #3309, #6800)
- Better assert during load when passing truncated font data or wrong data size. (#6822)
- Ensure calling AddFontXXX function doesn't invalidates ImFont's ConfigData pointers
prior to building again. (#6825)
- Added ImFontConfig::RasterizerDensity field to increase texture size of rendered glyphs
without altering other metrics. Among other things, this makes it easier to have zooming code
swapping between 2 fonts (e.g. a 100% and a 400% fonts) depending on current scale. (#6925) [@thedmd]
Important: if you increase this it is expected that you would render the font with a scale of
similar value or magnitude. Merely increasing this without increasing scale may lower quality.
- imgui_freetype: Added support for RasterizerDensity. (#6925) [@thedmd]
- imgui_freetype: Fixed a warning and leak in IMGUI_ENABLE_FREETYPE_LUNASVG support. (#6842, #6591)
- Inputs: Added IsKeyChordPressed() helper function e.g. IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_S).
(note that ImGuiMod_Shortcut may be used as an alias for Cmd on OSX and Ctrl on other systems).
- Misc: Most text functions also treat "%.*s" (along with "%s") specially to bypass formatting. (#3466, #6846)
- IO: Add extra keys to ImGuiKey enum: ImGuiKey_F13 to ImGuiKey_F24. (#6891, #4921)
- IO: Add extra keys to ImGuiKey enum: ImGuiKey_AppBack, ImGuiKey_AppForward. (#4921)
- IO: Setting io.WantSetMousePos ignores incoming MousePos events. (#6837, #228) [@bertaye]
- Debug Tools: Metrics: Added log of recent alloc/free calls.
- Debug Tools: Metrics: Added "Show groups rectangles" in tools.
- ImDrawList: Added AddEllipse(), AddEllipseFilled(), PathEllipticalArcTo(). (#2743) [@Doohl]
- ImVector: Added find_index() helper.
- Demo: Added "Drag and Drop -> Tooltip at target location" demo.
- Demo: Added "Layout -> Child Windows -> Manual-resize" demo. (#1710)
- Demo: Added "Layout -> Child Windows -> Auto-resize with constraints" demo. (#1666, #1395, #1496, #1710)
- Demo: Partly fixed "Examples -> Constrained-resizing window" custom constrains demo. (#6210) [@cfillion]
- Backends: Vulkan: Removed parameter from ImGui_ImplVulkan_CreateFontsTexture(): backend now creates its own
command-buffer to upload fonts. Removed ImGui_ImplVulkan_DestroyFontUploadObjects() which is now unnecessary.
No need to call ImGui_ImplVulkan_CreateFontsTexture() as it is done automatically in ImGui_ImplVulkan_NewFrame().
You can call ImGui_ImplVulkan_CreateFontsTexture() manually if you need to reload font atlas texture.
Fixed leaks, and added ImGui_ImplVulkan_DestroyFontsTexture() (probably no need to call this directly).
(#6943, #6715, #6327, #3743, #4618)
[@helynranta, @thomasherzog, @guybrush77, @albin-johansson, @MiroKaku, @benbatya-fb, @ocornut]
- Backends: GLFW: Clear emscripten's MouseWheel callback before shutdown. (#6790, #6096, #4019) [@halx99]
- Backends: GLFW: Added support for F13 to F24 function keys. (#6891)
- Backends: SDL2, SDL3: Added support for F13 to F24 function keys, AppBack, AppForward. (#6891)
- Backends: SDL3: Updates for recent API changes. (#7000, #6974)
- Backends: Win32: Added support for F13 to F24 function keys, AppBack, AppForward. (#6891)
- Backends: Win32: Added support for keyboard codepage conversion for when application
is compiled in MBCS mode and using a non-Unicode window. (#6785, #6782, #5725, #5961) [@sneakyevil]
- Backends: Win32: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows
doesn't emit it (same behavior as GLFW/SDL). (#6859) [@thedmd, @SuperWangKai]
- Backends: OpenGL3: rename symbols in our internal loader so that LTO compilation with another
copy of gl3w becomes possible. (#6875, #6668, #4445) [@nicolasnoble]
- Backends: OpenGL3: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead
of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983)
- Backends: OSX: Added support for F13 to F20 function keys. Support mapping F13 to PrintScreen. (#6891)
- Examples: GLFW+Vulkan, SDL+Vulkan: Simplified and removed code due to backend improvements.
- Internals: Renamed ImFloor() to ImTrunc(). Renamed ImFloorSigned() to ImFloor(). (#6861)
-----------------------------------------------------------------------
VERSION 1.89.9 (Released 2023-09-04)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.9
Breaking changes:
- Clipper: Renamed IncludeRangeByIndices(), also called ForceDisplayRangeByIndices()
before 1.89.6, to IncludeItemsByIndex(). Kept inline redirection function. (#6424, #3841)
Other changes:
- Tables: Made it possible to use SameLine(0,0) after TableNextColumn() or
TableSetColumnIndex() in order to reuse line pos/height from previous cell. (#3740)
- Tables: Made it possible to change style.CellPadding.y between rows. (#3740)
- Nav, TreeNode: Pressing Left with ImGuiTreeNodeFlags_NavLeftJumpsBackHere now goes
through proper navigation logic: honor scrolling and selection. (#1079, #1131)
- Sliders: Fixed an integer overflow and div-by-zero in SliderInt() when
v_max=INT_MAX (#6675, #6679) [@jbarthelmes]
- Windows: Layout of Close/Collapse buttons uses style.ItemInnerSpacing.x between items,
stopped incorrectly using FramePadding in a way where hit-boxes could overlap when
setting large values. (#6749)
- TabBar, Style: added style.TabBarBorderSize and associated ImGuiStyleVar_TabBarBorderSize.
Tweaked rendering of that separator to allow thicker values. (#6820, #4859, #5022, #5239)
- InputFloat, SliderFloat, DragFloat: always turn both '.' and ',' into the current decimal
point character when using Decimal/Scientific character filter. (#6719, #2278) [@adamsepp]
- ColorEdit, ColorPicker: Manipulating options popup don't mark item as edited. (#6722)
(Note that they may still be marked as Active/Hovered.)
- Clipper: Added IncludeItemByIndex() helper to include a single item. (#6424, #3841)
- Clipper: Fixed a bug if attempt to force-include a range which matches an already
included range, clipper would end earlier. (#3841)
- ImDrawData: Fixed an issue where TotalVtxCount/TotalIdxCount does not match the sum
of individual ImDrawList's buffer sizes when a dimming/modal background is rendered. (#6716)
- ImDrawList: Automatically calling ChannelsMerge() if not done after a split.
- ImDrawList: Fixed OOB access in _CalcCircleAutoSegmentCount when passing excessively
large radius to AddCircle(). (#6657, #5317) [@EggsyCRO, @jdpatdiscord]
- IO: Exposed io.PlatformLocaleDecimalPoint to configure decimal point ('.' or ',') for
languages needing it. Should ideally be set to the value of '*localeconv()->decimal_point'
but our backends don't do it yet. (#6719, #2278)
- IO: Fixed io.AddMousePosEvent() and io.AddMouseButtonEvent() writing MouseSource to
wrong union section. Was semantically incorrect and accidentally had no side-effects
with default compiler alignment settings. (#6727) [@RickHuang2001]
- Misc: Made multiple calls to Render() during the same frame early out faster.
- Debug Tools: Metrics: Fixed "Drawlists" section and per-viewport equivalent
appearing empty (regression in 1.89.8).
- Demo: Reorganized "Examples" menu.
- Demo: Tables: Demonstrate using SameLine() between cells. (#3740)
- Demo: Tables: Demonstrate altering CellPadding.y between rows. (#3740)
- Demo: Custom Rendering: Demonstrate out-of-order rendering using ImDrawListSplitter.
- Backends: SDL2,SDL3: added ImGui_ImplSDL2_InitForOther()/ImGui_ImplSDL3_InitForOther()
for consistency (matching GLFW backend) and as most initialization paths don't actually
need to care about rendering backend.
- Examples: Emscripten+WebGPU: Fixed WGPUInstance creation process + use preferred
framebuffer format. (#6640, #6748) [@smileorigin]
-----------------------------------------------------------------------
VERSION 1.89.8 (Released 2023-08-01)
-----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.89.8
Breaking changes:
- IO: Obsoleted io.ClearInputCharacters() (added in 1.47) as it now ambiguous
and often incorrect/misleading considering the existence of a higher-level
input queue. This is automatically cleared by io.ClearInputsKeys(). (#4921)
- ImDrawData: CmdLists[] array is now owned, changed from 'ImDrawList**' to
'ImVector<ImDrawList*>'. Majority of users shouldn't be affected, but you
cannot compare to NULL nor reassign manually anymore.
Instead use AddDrawList(). Allocation count are identical. (#6406, #4879, #1878)
Other changes:
- Fonts: ImFontConfig::OversampleH now defaults to 2 instead of 3, since the
quality increase is largely minimal.
- Fonts, imgui_freetype: Added support to render OpenType SVG fonts using lunasvg.
Requires enabling IMGUI_ENABLE_FREETYPE_LUNASVG along with IMGUI_ENABLE_FREETYPE,
and providing headers/libraries for lunasvg. (#6591, #6607) [@sakiodre]
- ImDrawData: CmdLists[] array is now an ImVector<> owned by ImDrawData rather
than a pointer to internal state.
- This makes it easier for user to create their own or append to an existing draw data.
Added a ImDrawData::AddDrawList() helper function to do that. (#6406, #4879, #1878)
- This makes it easier to perform a deep-swap instead of a deep-copy, as array
ownership is now clear. (#6597, #6475, #6167, #5776, #5109, #4763, #3515, #1860)
- Syntax and allocation count are otherwise identical.
- Fixed CTRL+Tab dimming background assert when target window has a callback
in the last ImDrawCmd. (#4857, #5937)
- IsItemHovered: Fixed ImGuiHoveredFlags_ForTooltip for Keyboard/Gamepad navigation,
got broken prior to 1.89.7 due to an unrelated change making flags conflict. (#6622, #1485)
- InputText: Fixed a case where deactivation frame would write to underlying
buffer or call CallbackResize although unnecessary, in a frame where the
return value was false.
- Tables: fixed GetContentRegionAvail().y report not taking account of lower cell
padding or of using ImGuiTableFlags_NoHostExtendY. Not taking it into account
would make the idiom of creating vertically bottom-aligned content (e.g. a child
window) inside a table make the parent window erroneously have a scrollbar. (#6619)
- Tables: fixed calculation of multi-instance shared decoration/scrollbar width of
scrolling tables, to avoid flickering width variation when resizing down a table
hosting a child window. (#5920, #6619)
- Scrollbar: layout needs to take account of window border size, so a border size
will slightly reduce scrollbar size. Generally we tried to make it that window
border size has no incidence on layout but this can't work with thick borders. (#2522)
- IO: Added io.ClearEventsQueue() to clear incoming inputs events. (#4921)
May be useful in conjunction with io.ClearInputsKeys() if you need to clear
both current inputs state and queued events (e.g. when using blocking native
dialogs such as Windows's ::MessageBox() or ::GetOpenFileName()).
- IO: Changed io.ClearInputsKeys() specs to also clear current frame character buffer
(what now obsoleted io.ClearInputCharacters() did), as this is effectively the
desirable behavior.
- Misc: Added IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION config macro to disable
stb_sprintf implementation when using IMGUI_USE_STB_SPRINTF. (#6626) [@septag]
- Misc: Avoid stb_textedit.h reincluding string.h while in a namespace, which
messes up with building with Clang Modules. (#6653, #4791) [@JohelEGP]
- Demo: Better showcase use of SetNextItemAllowOverlap(). (#6574, #6512, #3909, #517)
- Demo: Showcase a few more InputText() flags.
- Backends: Made all backends sources files support global IMGUI_DISABLE. (#6601)
- Backends: GLFW: Revert ignoring mouse data on GLFW_CURSOR_DISABLED as it can be used
differently. User may set ImGuiConfigFlags_NoMouse if desired. (#5625, #6609) [@scorpion-26]
- Backends: WebGPU: Update for changes in Dawn. (#6602, #6188) [@williamhCode]
- Examples: Vulkan: Creating minimal descriptor pools to fit only what is needed by
example. (#6642) [@SaschaWillem]
----------------------------------------------------------------------- -----------------------------------------------------------------------
VERSION 1.89.7 (Released 2023-07-04) VERSION 1.89.7 (Released 2023-07-04)
----------------------------------------------------------------------- -----------------------------------------------------------------------
@ -48,6 +832,11 @@ Breaking changes:
legacy 'SetItemAllowOverlap()' call (public API) + ImGuiButtonFlags_AllowOverlap (internal). legacy 'SetItemAllowOverlap()' call (public API) + ImGuiButtonFlags_AllowOverlap (internal).
- Obsoleted 'SetItemAllowOverlap()': it didn't and couldn't work reliably since 1.89 (2022-11-15), - Obsoleted 'SetItemAllowOverlap()': it didn't and couldn't work reliably since 1.89 (2022-11-15),
and relied on ambiguously defined design. Use 'SetNextItemAllowOverlap()' before item instead. and relied on ambiguously defined design. Use 'SetNextItemAllowOverlap()' before item instead.
- Selectable, TreeNode: When using ImGuiSelectableFlags_AllowOverlap/ImGuiTreeNodeFlags_AllowOverlap
and holding item held, overlapping widgets won't appear as hovered. (#6512, #3909)
While this fixes a common small visual issue, it also means that calling IsItemHovered()
after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't
use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
- Renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap'. - Renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap'.
- Renamed 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap' - Renamed 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'
- Kept redirecting enums (will obsolete). - Kept redirecting enums (will obsolete).
@ -83,8 +872,6 @@ Other changes:
- Fixed first frame of an overlap highlighting underlying item if previous frame didn't hover anything. - Fixed first frame of an overlap highlighting underlying item if previous frame didn't hover anything.
- IsItemHovered: Changed to return false when querying an item using AllowOverlap mode which - IsItemHovered: Changed to return false when querying an item using AllowOverlap mode which
is being overlapped. Added ImGuiHoveredFlags_AllowWhenOverlappedByItem to opt-out. (#6512, #3909, #517) is being overlapped. Added ImGuiHoveredFlags_AllowWhenOverlappedByItem to opt-out. (#6512, #3909, #517)
- Selectable, TreeNode: When using ImGuiSelectableFlags_AllowOverlap/ImGuiTreeNodeFlags_AllowOverlap
and holding item held, overlapping widgets won't appear as hovered. (#6512, #3909)
- IsWindowHovered: Added support for ImGuiHoveredFlags_Stationary. - IsWindowHovered: Added support for ImGuiHoveredFlags_Stationary.
- IsWindowHovered, IsItemHovered: Assert when passed any unsupported flags. - IsWindowHovered, IsItemHovered: Assert when passed any unsupported flags.
- Tables: Fixed a regression in 1.89.6 leading to the first column of tables with either - Tables: Fixed a regression in 1.89.6 leading to the first column of tables with either
@ -139,7 +926,7 @@ Breaking changes:
- ListBoxFooter() -> use EndListBox() - ListBoxFooter() -> use EndListBox()
- Note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for refeence. - Note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for refeence.
- Backends: SDL_Renderer: Renamed 'imgui_impl_sdlrenderer.h/cpp' to 'imgui_impl_sdlrenderer2.h/cpp', - Backends: SDL_Renderer: Renamed 'imgui_impl_sdlrenderer.h/cpp' to 'imgui_impl_sdlrenderer2.h/cpp',
in order to accomodate for upcoming SDL3 and change in its SDL_Renderer API. (#6286) in order to accommodate for upcoming SDL3 and change in its SDL_Renderer API. (#6286)
- Backends: GLUT: Removed call to ImGui::NewFrame() from ImGui_ImplGLUT_NewFrame(). - Backends: GLUT: Removed call to ImGui::NewFrame() from ImGui_ImplGLUT_NewFrame().
It needs to be called from the main app loop, like with every other backends. (#6337) [@GereonV] It needs to be called from the main app loop, like with every other backends. (#6337) [@GereonV]
@ -702,7 +1489,7 @@ Other Changes:
- Backends: Metal: Use __bridge for ARC based systems. (#5403) [@stack] - Backends: Metal: Use __bridge for ARC based systems. (#5403) [@stack]
- Backends: Metal: Add dispatch synchronization. (#5447) [@luigifcruz] - Backends: Metal: Add dispatch synchronization. (#5447) [@luigifcruz]
- Backends: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. (#5603) [@dcvz] - Backends: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. (#5603) [@dcvz]
- Backends: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symetry. (#914, #5738). - Backends: Vulkan: Added experimental ImGui_ImplVulkan_RemoveTexture() for api symmetry. (#914, #5738).
- Backends: WebGPU: fixed rendering when a depth buffer is enabled. (#5869) [@brainlag] - Backends: WebGPU: fixed rendering when a depth buffer is enabled. (#5869) [@brainlag]
@ -1202,7 +1989,7 @@ Breaking Changes:
- Commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019): - Commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
- ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList() - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
- ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder - ImFont::GlyphRangesBuilder -> use ImFontGlyphRangesBuilder
- Backends: OpenGL3: added a third source file "imgui_impl_opengl3_loader.h". [@rokups] - Backends: OpenGL3: added a third source file "imgui_impl_opengl3_loader.h". (#4445) [@rokups]
- Backends: GLFW: backend now uses glfwSetCursorEnterCallback(). (#3751, #4377, #2445) - Backends: GLFW: backend now uses glfwSetCursorEnterCallback(). (#3751, #4377, #2445)
- Backends: GLFW: backend now uses glfwSetWindowFocusCallback(). (#4388) [@thedmd] - Backends: GLFW: backend now uses glfwSetWindowFocusCallback(). (#4388) [@thedmd]
- If calling ImGui_ImplGlfw_InitXXX with install_callbacks=true: this is already done for you. - If calling ImGui_ImplGlfw_InitXXX with install_callbacks=true: this is already done for you.
@ -1291,7 +2078,7 @@ Other Changes:
about building on 32-bit systems. (#4225) [@kingofthebongo2008] about building on 32-bit systems. (#4225) [@kingofthebongo2008]
- Backends: OpenGL3: Embed our own minimal GL headers/loader (imgui_impl_opengl3_loader.h) based on gl3w. - Backends: OpenGL3: Embed our own minimal GL headers/loader (imgui_impl_opengl3_loader.h) based on gl3w.
Reduces the frequent issues and confusion coming from having to support multiple loaders and requiring users to use and Reduces the frequent issues and confusion coming from having to support multiple loaders and requiring users to use and
initialize the same loader as the backend. [@rokups] initialize the same loader as the backend. (#4445) [@rokups]
Removed support for gl3w, glew, glad, glad2, glbinding2, glbinding3 (all now unnecessary). Removed support for gl3w, glew, glad, glad2, glbinding2, glbinding3 (all now unnecessary).
- Backends: OpenGL3: Handle GL_CLIP_ORIGIN on <4.5 contexts if "GL_ARB_clip_control" extension is detected. (#4170, #3998) - Backends: OpenGL3: Handle GL_CLIP_ORIGIN on <4.5 contexts if "GL_ARB_clip_control" extension is detected. (#4170, #3998)
- Backends: OpenGL3: Destroy vertex/fragment shader objects right after they are linked into main shader. (#4244) [@Crowbarous] - Backends: OpenGL3: Destroy vertex/fragment shader objects right after they are linked into main shader. (#4244) [@Crowbarous]
@ -1475,7 +2262,7 @@ Other Changes:
alpha compositing and transparent windows. (#2766, #3447 etc.). alpha compositing and transparent windows. (#2766, #3447 etc.).
- Backends: OpenGL, Vulkan, DX9, DX10, DX11, DX12, Metal, WebGPU, Allegro: Rework blending equation to - Backends: OpenGL, Vulkan, DX9, DX10, DX11, DX12, Metal, WebGPU, Allegro: Rework blending equation to
preserve alpha in output buffer (using SrcBlendAlpha = ONE, DstBlendAlpha = ONE_MINUS_SRC_ALPHA consistently preserve alpha in output buffer (using SrcBlendAlpha = ONE, DstBlendAlpha = ONE_MINUS_SRC_ALPHA consistently
accross all backends), facilitating compositing of the output buffer with another buffer. across all backends), facilitating compositing of the output buffer with another buffer.
(#2693, #2764, #2766, #2873, #3447, #3813, #3816) [@ocornut, @thedmd, @ShawnM427, @Ubpa, @aiekick] (#2693, #2764, #2766, #2873, #3447, #3813, #3816) [@ocornut, @thedmd, @ShawnM427, @Ubpa, @aiekick]
- Backends: DX9: Fix to support IMGUI_USE_BGRA_PACKED_COLOR. (#3844) [@Xiliusha] - Backends: DX9: Fix to support IMGUI_USE_BGRA_PACKED_COLOR. (#3844) [@Xiliusha]
- Backends: DX9: Fix to support colored glyphs, using newly introduced 'TexPixelsUseColors' info. (#3844) - Backends: DX9: Fix to support colored glyphs, using newly introduced 'TexPixelsUseColors' info. (#3844)
@ -4884,7 +5671,7 @@ Other Changes:
VERSION 1.08 (2014-08-25) VERSION 1.08 (2014-08-25)
----------------------------------------------------------------------- -----------------------------------------------------------------------
Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.09 Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.08
- Fixed ImGuiTextFilter trimming of leading/trailing blanks. - Fixed ImGuiTextFilter trimming of leading/trailing blanks.
- Fixed file descriptor leak on LoadSettings() failure. - Fixed file descriptor leak on LoadSettings() failure.

View File

@ -12,26 +12,29 @@
- Article: [How To Ask Good Questions](https://bit.ly/3nwRnx1). - Article: [How To Ask Good Questions](https://bit.ly/3nwRnx1).
- Please browse the [Wiki](https://github.com/ocornut/imgui/wiki) to find code snippets, links and other resources (e.g. [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started), [Useful extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions)). - Please browse the [Wiki](https://github.com/ocornut/imgui/wiki) to find code snippets, links and other resources (e.g. [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started), [Useful extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions)).
- Please read [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) if your question relates to setting up Dear ImGui.
- Please read [docs/FAQ.md](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md). - Please read [docs/FAQ.md](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md).
- Please read [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) if your question relates to fonts or text. - Please read [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) if your question relates to fonts or text.
- Please read one of the [examples/](https://github.com/ocornut/imgui/tree/master/examples) application if your question relates to setting up Dear ImGui.
- Please run `ImGui::ShowDemoWindow()` to explore the demo and its sources. - Please run `ImGui::ShowDemoWindow()` to explore the demo and its sources.
- Please use the search function of your IDE to search in for comments related to your situation. - Please use the search function of your IDE to search for symbols and comments related to your situation.
- Please use the search function of GitHub to look for similar issues. You may [browse issues by Labels](https://github.com/ocornut/imgui/labels). - Please use the search function of GitHub to look for similar topics (always include 'Closed' issues/pr in your search).
- You may [browse issues by Labels](https://github.com/ocornut/imgui/labels).
- Please use a web search engine to look for similar issues. - Please use a web search engine to look for similar issues.
- If you get a crash or assert, use a debugger to locate the line triggering it and read the comments around. - If you get a crash or assert, use a debugger to locate the line triggering it and read the comments around.
- Please don't be a [Help Vampire](https://slash7.com/2006/12/22/vampires/). - Please don't be a [Help Vampire](https://slash7.com/2006/12/22/vampires/).
## Issues vs Discussions ## 'Issues' vs 'Discussions'
If you: We are happy to use 'Issues' for many type of open-ended questions. We are encouraging 'Issues' becoming an enormous, centralized and cross-referenced database of Dear ImGui contents.
Only if you:
- Cannot BUILD or LINK examples. - Cannot BUILD or LINK examples.
- Cannot BUILD, or LINK, or RUN Dear ImGui in your application or custom engine. - Cannot BUILD, or LINK, or RUN Dear ImGui in your application or custom engine.
- Cannot LOAD a font. - Cannot LOAD a font.
Then please [use the Discussions forums](https://github.com/ocornut/imgui/discussions) instead of opening an issue. Then please [use the Discussions forums](https://github.com/ocornut/imgui/discussions) instead of opening an issue.
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. 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.
## How to open an issue ## How to open an issue
@ -46,16 +49,16 @@ Steps:
- Article: [How To Ask Good Questions](https://bit.ly/3nwRnx1). - Article: [How To Ask Good Questions](https://bit.ly/3nwRnx1).
- **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. - **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.
- **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. - **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.
- **Please INCLUDE CODE. 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, explain it and fix it**. Please test your shortened code to ensure it exhibits the problem. **Often while creating the MCVE you will solve 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.
- **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. - **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.
- **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. - **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.
- **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. - **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.
- **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.
- Please state if you have made substantial modifications to your copy of Dear ImGui or the back-end. - Please state if you have made substantial modifications to your copy of Dear ImGui or the back-end.
- If you are not calling Dear ImGui directly from C++, please provide information about your Language and the wrapper/binding you are using. - If you are not calling Dear ImGui directly from C++, please provide information about your Language and the wrapper/binding you are using.
- 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. - 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.
**Some unfortunate words of warning** **Some unfortunate words of warning**
- 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. - If you are involved in cheating schemes (e.g. DLL injection) for competitive online multiplayer games, please don't post 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 protect our time and sanity.
- 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. - 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.
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. 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.
@ -63,15 +66,13 @@ If you have been using Dear ImGui for a while or have been using C/C++ for sever
## How to open a Pull Request ## How to open a Pull Request
- **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. - **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.
- 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. - 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 pointing toward a problem, and 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.
- **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/). - **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/).
- **When fixing a warning or compilation problem,** please post the compiler log and specify the compiler version and platform you are using. - **When fixing a warning or compilation problem,** please post the compiler log and specify the compiler version and platform you are using.
- **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). - **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).
- **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). - **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).
- **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). - **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).
Thank you for reading!
## Copyright / Contributor License Agreement ## Copyright / Contributor License Agreement
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. 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.

View File

@ -10,7 +10,7 @@ integrating Dear ImGui in your own application/game/engine.
**Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.** **Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.**
You can find Windows binaries for some of those example applications at: You can find Windows binaries for some of those example applications at:
http://www.dearimgui.com/binaries https://www.dearimgui.com/binaries
### Getting Started ### Getting Started
@ -74,7 +74,7 @@ ImGui::DestroyContext();
Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase. Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
Please read the comments and instruction at the top of each file. Please read the comments and instruction at the top of each file.
Please read FAQ at http://www.dearimgui.com/faq Please read FAQ at https://www.dearimgui.com/faq
If you are using any of the backends provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h) If you are using any of the backends provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h)
files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with its own individual files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with its own individual
@ -104,8 +104,8 @@ OSX + OpenGL2 example. <BR>
(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends. (NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends.
You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.) You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.)
[example_emscripten_wgpu/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten_wgpu/) <BR> [example_glfw_wgpu/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_wgpu/) <BR>
Emcripten + GLFW + WebGPU example. <BR> GLFW + WebGPU example. Supports Emscripten (web) or Dawn (desktop) <BR>
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_wgpu.cpp = main.cpp + imgui_impl_glfw.cpp + imgui_impl_wgpu.cpp
Note that the 'example_glfw_opengl3' and 'example_sdl2_opengl3' examples also supports Emscripten! Note that the 'example_glfw_opengl3' and 'example_sdl2_opengl3' examples also supports Emscripten!
@ -126,7 +126,7 @@ state, and might confuse your GPU driver. One star, not recommended.
GLFW (Win32, Mac, Linux) + OpenGL3+/ES2/ES3 example (modern, programmable pipeline). <BR> GLFW (Win32, Mac, Linux) + OpenGL3+/ES2/ES3 example (modern, programmable pipeline). <BR>
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp <BR> = main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp <BR>
This uses more modern GL calls and custom shaders.<BR> This uses more modern GL calls and custom shaders.<BR>
This support building with Emscripten and targetting WebGL.<BR> This support building with Emscripten and targeting WebGL.<BR>
Prefer using that if you are using modern GL or WebGL in your application. Prefer using that if you are using modern GL or WebGL in your application.
[example_glfw_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/) <BR> [example_glfw_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/) <BR>
@ -168,7 +168,7 @@ state, and might confuse your GPU driver. One star, not recommended.
SDL2 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example. <BR> SDL2 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example. <BR>
= main.cpp + imgui_impl_sdl2.cpp + imgui_impl_opengl3.cpp <BR> = main.cpp + imgui_impl_sdl2.cpp + imgui_impl_opengl3.cpp <BR>
This uses more modern GL calls and custom shaders. <BR> This uses more modern GL calls and custom shaders. <BR>
This support building with Emscripten and targetting WebGL.<BR> This support building with Emscripten and targeting WebGL.<BR>
Prefer using that if you are using modern GL or WebGL in your application. Prefer using that if you are using modern GL or WebGL in your application.
[example_sdl2_sdlrenderer2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_sdlrenderer2/) <BR> [example_sdl2_sdlrenderer2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl2_sdlrenderer2/) <BR>

View File

@ -23,7 +23,7 @@ or view this file with any Markdown viewer.
| [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) | | [I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-clipping-or-disappearing-when-i-move-windows-around) |
| [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) | | [I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...](#q-i-integrated-dear-imgui-in-my-engine-and-some-elements-are-displaying-outside-their-expected-windows-boundaries) |
| **Q&A: Usage** | | **Q&A: Usage** |
| **[About the ID Stack system..<br>Why is my widget not reacting when I click on it?<br>How can I have widgets with an empty label?<br>How can I have multiple widgets with the same label?<br>How can I have multiple windows with the same label?](#q-about-the-id-stack-system)** | | **[About the ID Stack system..<br>Why is my widget not reacting when I click on it?<br>Why is the wrong widget reacting when I click on one?<br>How can I have widgets with an empty label?<br>How can I have multiple widgets with the same label?<br>How can I have multiple windows with the same label?](#q-about-the-id-stack-system)** |
| [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)| | [How can I display an image? What is ImTextureID, how does it work?](#q-how-can-i-display-an-image-what-is-imtextureid-how-does-it-work)|
| [How can I use maths operators with ImVec2?](#q-how-can-i-use-maths-operators-with-imvec2) | | [How can I use maths operators with ImVec2?](#q-how-can-i-use-maths-operators-with-imvec2) |
| [How can I use my own maths types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-maths-types-instead-of-imvec2imvec4) | | [How can I use my own maths types instead of ImVec2/ImVec4?](#q-how-can-i-use-my-own-maths-types-instead-of-imvec2imvec4) |
@ -91,6 +91,7 @@ Many projects are using this branch and it is kept in sync with master regularly
### Q: How to get started? ### Q: How to get started?
Read [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started). <BR>
Read [EXAMPLES.md](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md). <BR> Read [EXAMPLES.md](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md). <BR>
Read [BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md). <BR> Read [BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md). <BR>
Read `PROGRAMMER GUIDE` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp). <BR> Read `PROGRAMMER GUIDE` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp). <BR>
@ -124,13 +125,8 @@ void MyLowLevelMouseButtonHandler(int button, bool down)
} }
``` ```
**Note:** The `io.WantCaptureMouse` is more correct that any manual attempt to "check if the mouse is hovering a window" (don't do that!). It handles mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs. **Note:** The `io.WantCaptureMouse` is more correct that any manual attempt to "check if the mouse is hovering a window" (don't do that!). It handles mouse dragging correctly (both dragging that started over your application or over a Dear ImGui window) and handle e.g. popup and modal windows blocking inputs.
**Note:** Those flags are updated by `ImGui::NewFrame()`. However it is generally more correct and easier that you poll flags from the previous frame, then submit your inputs, then call `NewFrame()`. If you attempt to do the opposite (which is generally harder) you are likely going to submit your inputs after `NewFrame()`, and therefore too late.
**Note:** If you are using a touch device, you may find use for an early call to `UpdateHoveredWindowAndCaptureFlags()` to correctly dispatch your initial touch. We will work on better out-of-the-box touch support in the future.
**Note:** Text input widget releases focus on the "KeyDown" event of the Return key, so the subsequent "KeyUp" event that your application receive will typically have `io.WantCaptureKeyboard == false`. Depending on your application logic it may or not be inconvenient to receive that KeyUp event. You might want to track which key-downs were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.) **Note:** Text input widget releases focus on the "KeyDown" event of the Return key, so the subsequent "KeyUp" event that your application receive will typically have `io.WantCaptureKeyboard == false`. Depending on your application logic it may or not be inconvenient to receive that KeyUp event. You might want to track which key-downs were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
##### [Return to Index](#index) ##### [Return to Index](#index)
@ -141,7 +137,7 @@ void MyLowLevelMouseButtonHandler(int button, bool down)
- The gamepad/keyboard navigation is fairly functional and keeps being improved. The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable. Gamepad support is particularly useful to use Dear ImGui on a game console (e.g. PS4, Switch, XB1) without a mouse connected! - The gamepad/keyboard navigation is fairly functional and keeps being improved. The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable. Gamepad support is particularly useful to use Dear ImGui on a game console (e.g. PS4, Switch, XB1) without a mouse connected!
- Keyboard: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard` to enable. - Keyboard: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard` to enable.
- Gamepad: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad` to enable (with a supporting backend). - Gamepad: set `io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad` to enable (with a supporting backend).
- See [Control Sheets for Gamepads](http://www.dearimgui.com/controls_sheets) (reference PNG/PSD for PS4, XB1, Switch gamepads). - See [Control Sheets for Gamepads](https://www.dearimgui.com/controls_sheets) (reference PNG/PSD for PS4, XB1, Switch gamepads).
- See `USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp) for more details. - See `USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS` section of [imgui.cpp](https://github.com/ocornut/imgui/blob/master/imgui.cpp) for more details.
##### [Return to Index](#index) ##### [Return to Index](#index)
@ -164,8 +160,8 @@ Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-lik
--- ---
### Q: I integrated Dear ImGui in my engine and little squares are showing instead of text... ### Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
Your renderer is not using the font texture correctly or it hasn't been uploaded to the GPU. Your renderer backend is not using the font texture correctly or it hasn't been uploaded to the GPU.
- If this happens using the standard backends: A) have you modified the font atlas after `ImGui_ImplXXX_NewFrame()`? B) maybe the texture failed to upload, which could happens if for some reason your texture is too big. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md). - If this happens using the standard backends: A) have you modified the font atlas after `ImGui_ImplXXX_NewFrame()`? B) maybe the texture failed to upload, which **can if your texture atlas is too big**. Also see [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md).
- If this happens with a custom backend: make sure you have uploaded the font texture to the GPU, that all shaders are rendering states are setup properly (e.g. texture is bound). Compare your code to existing backends and use a graphics debugger such as [RenderDoc](https://renderdoc.org) to debug your rendering states. - If this happens with a custom backend: make sure you have uploaded the font texture to the GPU, that all shaders are rendering states are setup properly (e.g. texture is bound). Compare your code to existing backends and use a graphics debugger such as [RenderDoc](https://renderdoc.org) to debug your rendering states.
##### [Return to Index](#index) ##### [Return to Index](#index)
@ -203,10 +199,42 @@ ctx->RSSetScissorRects(1, &r);
### Q: About the ID Stack system... ### Q: About the ID Stack system...
### Q: Why is my widget not reacting when I click on it? ### Q: Why is my widget not reacting when I click on it?
### Q: Why is the wrong widget reacting when I click on one?
### Q: How can I have widgets with an empty label? ### Q: How can I have widgets with an empty label?
### Q: How can I have multiple widgets with the same label? ### Q: How can I have multiple widgets with the same label?
### Q: How can I have multiple windows with the same label? ### Q: How can I have multiple windows with the same label?
**USING THE SAME LABEL+ID IS THE MOST COMMON USER MISTAKE:**
<table>
<tr>
<td><img src="https://github.com/ocornut/imgui/assets/8225057/76eb9467-74d1-4e95-9f56-be81c6dd029d"></td>
<td>
<pre lang="cpp">
ImGui::Begin("Incorrect!");
ImGui::DragFloat2("My value", &objects[0]->pos.x);
ImGui::DragFloat2("My value", &objects[1]->pos.x);
ImGui::DragFloat2("My value", &objects[2]->pos.x);
ImGui::End();
&nbsp;
ImGui::Begin("Correct!");
ImGui::DragFloat2("My value", &objects[0]->pos.x);
ImGui::DragFloat2("My value##2", &objects[1]->pos.x);
ImGui::DragFloat2("My value##3", &objects[2]->pos.x);
ImGui::End();
&nbsp;
ImGui::Begin("Also Correct!");
for (int n = 0; n < 3; n++)
{
ImGui::PushID(n);
ImGui::DragFloat2("My value", &objects[n]->pos.x);
ImGui::PopID();
}
ImGui::End();
</pre>
</td>
</tr>
</table>
A primer on labels and the ID Stack... A primer on labels and the ID Stack...
Dear ImGui internally needs to uniquely identify UI elements. Dear ImGui internally needs to uniquely identify UI elements.
@ -216,7 +244,7 @@ Interactive widgets (such as calls to Button buttons) need a unique ID.
**Unique IDs are used internally to track active widgets and occasionally associate state to widgets.<BR> **Unique IDs are used internally to track active widgets and occasionally associate state to widgets.<BR>
Unique IDs are implicitly built from the hash of multiple elements that identify the "path" to the UI element.** Unique IDs are implicitly built from the hash of multiple elements that identify the "path" to the UI element.**
Since Dear ImGui 1.85, you can use `Demo>Tools>Stack Tool` or call `ImGui::ShowStackToolWindow()`. The tool display intermediate values leading to the creation of a unique ID, making things easier to debug and understand. Since Dear ImGui 1.85, you can use `Demo>Tools>ID Stack Tool` or call `ImGui::ShowIDStackToolWindow()`. The tool display intermediate values leading to the creation of a unique ID, making things easier to debug and understand.
![Stack tool](https://user-images.githubusercontent.com/8225057/136235657-a0ea5665-dcd1-423f-9be6-dc3f8ced8f12.png) ![Stack tool](https://user-images.githubusercontent.com/8225057/136235657-a0ea5665-dcd1-423f-9be6-dc3f8ced8f12.png)
@ -430,7 +458,7 @@ Finally, you may call `ImGui::ShowMetricsWindow()` to explore/visualize/understa
### Q: How can I use maths operators with ImVec2? ### Q: How can I use maths operators with ImVec2?
We do not export maths operators by default in imgui.h in order to not conflict with the use of your own maths types and maths operators. As a convenience, you may use `#defne IMGUI_DEFINE_MATH_OPERATORS` + `#include "imgui.h"` to access our basic maths operators. We do not export maths operators by default in imgui.h in order to not conflict with the use of your own maths types and maths operators. As a convenience, you may use `#define IMGUI_DEFINE_MATH_OPERATORS` + `#include "imgui.h"` to access our basic maths operators.
##### [Return to Index](#index) ##### [Return to Index](#index)
@ -569,44 +597,15 @@ io.Fonts->AddFontFromFileTTF("MyFolder/MyFont.ttf", size); // ALSO CORRECT
### Q: How can I easily use icons in my application? ### Q: How can I easily use icons in my application?
The most convenient and practical way is to merge an icon font such as FontAwesome inside your The most convenient and practical way is to merge an icon font such as FontAwesome inside your
main font. Then you can refer to icons within your strings. main font. Then you can refer to icons within your strings.
You may want to see `ImFontConfig::GlyphMinAdvanceX` to make your icon look monospace to facilitate alignment. Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file for more details about icons font loading.
(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file for more details about icons font loading.)
With some extra effort, you may use colorful icons by registering custom rectangle space inside the font atlas,
and copying your own graphics data into it. See docs/FONTS.md about using the AddCustomRectFontGlyph API.
##### [Return to Index](#index) ##### [Return to Index](#index)
--- ---
### Q: How can I load multiple fonts? ### Q: How can I load multiple fonts?
Use the font atlas to pack them into a single texture:
(Read the [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) file and the code in ImFontAtlas for more details.)
```cpp Use the font atlas to pack them into a single texture. Read [docs/FONTS.md](https://github.com/ocornut/imgui/blob/master/docs/FONTS.md) for more details.
ImGuiIO& io = ImGui::GetIO();
ImFont* font0 = io.Fonts->AddFontDefault();
ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
// the first loaded font gets used by default
// use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
// Options
ImFontConfig config;
config.OversampleH = 2;
config.OversampleV = 1;
config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixel up
config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config);
// Combine multiple fonts into one (e.g. for icon fonts)
static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
ImFontConfig config;
config.MergeMode = true;
io.Fonts->AddFontDefault();
io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, nullptr, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
```
##### [Return to Index](#index) ##### [Return to Index](#index)
@ -654,8 +653,8 @@ You may take a look at:
- [Quotes](https://github.com/ocornut/imgui/wiki/Quotes) - [Quotes](https://github.com/ocornut/imgui/wiki/Quotes)
- [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui)
- [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) - [Funding & Sponsors](https://github.com/ocornut/imgui/wiki/Funding)
- [Gallery](https://github.com/ocornut/imgui/issues/6478) - [Gallery](https://github.com/ocornut/imgui/issues/7503)
##### [Return to Index](#index) ##### [Return to Index](#index)
@ -697,11 +696,11 @@ There is an auto-generated [c-api for Dear ImGui (cimgui)](https://github.com/ci
# Q&A: Community # Q&A: Community
### Q: How can I help? ### Q: How can I help?
- Businesses: please reach out to `contact AT dearimgui.com` if you work in a place using Dear ImGui! We can discuss ways for your company to fund development via invoiced technical support, maintenance, or sponsoring contacts. This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people to work on this project. - Businesses: please reach out to `omar AT dearimgui.com` if you work in a place using Dear ImGui! We can discuss ways for your company to fund development via invoiced technical support, maintenance, or sponsoring contacts. This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people to work on this project. Please see [Funding](https://github.com/ocornut/imgui/wiki/Funding) page.
- Individuals: you can support continued maintenance and development via PayPal donations. See [README](https://github.com/ocornut/imgui/blob/master/docs/README.md). - Individuals: you can support continued maintenance and development via PayPal donations. See [README](https://github.com/ocornut/imgui/blob/master/docs/README.md).
- If you are experienced with Dear ImGui and C++, look at [GitHub Issues](https://github.com/ocornut/imgui/issues), [GitHub Discussions](https://github.com/ocornut/imgui/discussions), the [Wiki](https://github.com/ocornut/imgui/wiki), read [docs/TODO.txt](https://github.com/ocornut/imgui/blob/master/docs/TODO.txt), and see how you want to help and can help! - If you are experienced with Dear ImGui and C++, look at [GitHub Issues](https://github.com/ocornut/imgui/issues), [GitHub Discussions](https://github.com/ocornut/imgui/discussions), the [Wiki](https://github.com/ocornut/imgui/wiki), read [docs/TODO.txt](https://github.com/ocornut/imgui/blob/master/docs/TODO.txt), and see how you want to help and can help!
- Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere, etc. - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere, etc.
You may post screenshots or links in the [gallery threads](https://github.com/ocornut/imgui/issues/6478). Visuals are ideal as they inspire other programmers. Disclosing your use of Dear ImGui helps the library grow credibility, and helps other teams and programmers with taking decisions. You may post screenshots or links in the [gallery threads](https://github.com/ocornut/imgui/issues/7503). Visuals are ideal as they inspire other programmers. Disclosing your use of Dear ImGui helps the library grow credibility, and helps other teams and programmers with taking decisions.
- If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues or sometimes incomplete PR. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues or sometimes incomplete PR.
##### [Return to Index](#index) ##### [Return to Index](#index)

View File

@ -11,118 +11,58 @@ In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) fo
**Also read the FAQ:** https://www.dearimgui.com/faq (there is a Fonts section!) **Also read the FAQ:** https://www.dearimgui.com/faq (there is a Fonts section!)
## Index ## Index
- [Readme First](#readme-first) - [Troubleshooting](#troubleshooting)
- [About Filenames](#about-filenames)
- [About UTF-8 Encoding](#about-utf-8-encoding)
- [Debug Tools](#debug-tools)
- [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application) - [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application)
- [Fonts Loading Instructions](#fonts-loading-instructions) - [Fonts Loading Instructions](#fonts-loading-instructions)
- [Loading Font Data from Memory](#loading-font-data-from-memory)
- [Loading Font Data Embedded In Source Code](#loading-font-data-embedded-in-source-code)
- [Using Icon Fonts](#using-icon-fonts) - [Using Icon Fonts](#using-icon-fonts)
- [Using FreeType Rasterizer (imgui_freetype)](#using-freetype-rasterizer-imgui_freetype) - [Using FreeType Rasterizer (imgui_freetype)](#using-freetype-rasterizer-imgui_freetype)
- [Using Colorful Glyphs/Emojis](#using-colorful-glyphsemojis) - [Using Colorful Glyphs/Emojis](#using-colorful-glyphsemojis)
- [Using Custom Glyph Ranges](#using-custom-glyph-ranges) - [Using Custom Glyph Ranges](#using-custom-glyph-ranges)
- [Using Custom Colorful Icons](#using-custom-colorful-icons) - [Using Custom Colorful Icons](#using-custom-colorful-icons)
- [Using Font Data Embedded In Source Code](#using-font-data-embedded-in-source-code) - [About Filenames](#about-filenames)
- [About UTF-8 Encoding](#about-utf-8-encoding)
- [Debug Tools](#debug-tools)
- [Credits/Licenses For Fonts Included In Repository](#creditslicenses-for-fonts-included-in-repository) - [Credits/Licenses For Fonts Included In Repository](#creditslicenses-for-fonts-included-in-repository)
- [Font Links](#font-links) - [Font Links](#font-links)
--------------------------------------- ---------------------------------------
## Readme First ## Troubleshooting
**A vast majority of font and text related issues encountered comes from 3 things:** **A vast majority of font and text related issues encountered comes from 4 things:**
- Invalid filename due to use of `\` or unexpected working directory. See [About Filenames](#about-filenames). AddFontXXX functions should assert if the filename is incorrect.
- Invalid UTF-8 encoding of your non-ASCII strings. See [About UTF-8 Encoding](#about-utf-8-encoding). Use the encoding viewer to confirm yours is correct.
- You need to load a font with explicit glyph ranges if you want to use non-ASCII characters. See [Fonts Loading Instructions](#fonts-loading-instructions). Use Metrics/Debugger->Fonts to confirm loaded fonts and loaded glyph ranges.
The third point is a current constraint of Dear ImGui (which we will lift in the future): when loading a font you need to specify which characters glyphs to load. ### (1) Invalid filename due to use of `\` or unexpected working directory.
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. This is generally called by the Renderer backend, e.g. `ImGui_ImplDX11_NewFrame()` calls it.
**If you use custom glyphs ranges, make sure the array is persistent** and available during the calls to `GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build()`. See [About Filenames](#about-filenames). AddFontXXX functions should assert if the filename is incorrect.
##### [Return to Index](#index) ### (2) Invalid UTF-8 encoding of your non-ASCII strings.
## About Filenames See [About UTF-8 Encoding](#about-utf-8-encoding). Use the encoding viewer to confirm encoding of string literal in your source code is correct.
**Please note that many new C/C++ users have issues loading their files _because the filename they provide is wrong_ due to incorrect assumption of what is the current directory.** ### (3) Missing glyph ranges.
Two things to watch for: You need to load a font with explicit glyph ranges if you want to use non-ASCII characters. See [Fonts Loading Instructions](#fonts-loading-instructions). Use [Debug Tools](#debug-tools) confirm loaded fonts and loaded glyph ranges.
(1) 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. This is a current constraint of Dear ImGui (which we will lift in the future): when loading a font you need to specify which characters glyphs to load.
```cpp 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. This is generally called by the Renderer backend, e.g. `ImGui_ImplDX11_NewFrame()` calls it. **If you use custom glyphs ranges, make sure the array is persistent** and available during the calls to `GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build()`.
io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!!
io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT ### (4) Font atlas texture fails to upload to GPU.
```
In some situations, you may also use `/` path separator under Windows. This is often of byproduct of point 3. If you have 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 or everything appears as empty black or white rectangle.** 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.
(2) Make sure your IDE/debugger settings starts your executable from the right working (current) 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. Some solutions:
```cpp - You may reduce oversampling, e.g. `font_config.OversampleH = 1`, this will half your texture size for a quality loss.
io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...); // Relative filename depends on your Working Directory when running your program! Note that while OversampleH = 2 looks visibly very close to 3 in most situations, with OversampleH = 1 the quality drop will be noticeable. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample).
io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...); // Load from the parent folder of your Working Directory - Reduce glyphs ranges by calculating them from source localization data.
``` 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!
##### [Return to Index](#index) - Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two.
- Set `io.Fonts.TexDesiredWidth` to specify a texture width to reduce maximum texture height (see comment in `ImFontAtlas::Build()` function).
## About UTF-8 Encoding
**For non-ASCII characters display, a common user issue is not passing correctly UTF-8 encoded strings.**
(1) We provide a function `ImGui::DebugTextEncoding(const char* text)` which you can call to verify the content of your UTF-8 strings.
This is a convenient way to confirm that your encoding is correct.
```cpp
ImGui::SeparatorText("CORRECT");
ImGui::DebugTextEncoding(u8"こんにちは");
ImGui::SeparatorText("INCORRECT");
ImGui::DebugTextEncoding("こんにちは");
```
![UTF-8 Encoding viewer](https://github.com/ocornut/imgui/assets/8225057/61c1696a-9a94-46c5-9627-cf91211111f0)
You can also find this tool under `Metrics/Debuggers->Tools->UTF-8 Encoding viewer` if you want to paste from clipboard, but this won't validate the UTF-8 encoding done by your compiler.
(2) To encode in UTF-8:
There are also compiler-specific ways to enforce UTF-8 encoding by default:
- Visual Studio compiler: `/utf-8` command-line flag.
- Visual Studio compiler: `#pragma execution_character_set("utf-8")` inside your code.
- Since May 2023 we have changed the Visual Studio projects of all our examples to use `/utf-8` ([see commit](https://github.com/ocornut/imgui/commit/513af1efc9080857bbd10000d98f98f2a0c96803)).
Or, since C++11, you can use the `u8"my text"` syntax to encode literal strings as UTF-8. e.g.:
```cpp
ImGui::Text(u8"hello");
ImGui::Text(u8"こんにちは"); // this will always be encoded as UTF-8
ImGui::Text("こんにちは"); // the encoding of this is depending on compiler settings/flags and may be incorrect.
```
Since C++20, because the C++ committee hate its users, they decided to change the `u8""` syntax to not return `const char*` but a new type `const char_t*` which doesn't cast to `const char*`.
Because of type usage of `u8""` in C++20 is a little more tedious:
```cpp
ImGui::Text((const char*)u8"こんにちは");
```
We suggest using a macro in your codebase:
```cpp
#define U8(_S) (const char*)u8##_S
ImGui::Text(U8("こんにちは"));
```
##### [Return to Index](#index)
## Debug Tools
#### Metrics/Debugger->Fonts
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.
![Fonts debugging](https://user-images.githubusercontent.com/8225057/135429892-0e41ef8d-33c5-4991-bcf6-f997a0bcfd6b.png)
#### UTF-8 Encoding Viewer**
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.
![UTF-8 Encoding viewer](https://user-images.githubusercontent.com/8225057/166505963-8a0d7899-8ee8-4558-abb2-1ae523dc02f9.png)
##### [Return to Index](#index) ##### [Return to Index](#index)
---------------------------------------
## How should I handle DPI in my application? ## How should I handle DPI in my application?
@ -130,6 +70,7 @@ See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-s
##### [Return to Index](#index) ##### [Return to Index](#index)
---------------------------------------
## Fonts Loading Instructions ## Fonts Loading Instructions
@ -144,7 +85,7 @@ io.Fonts->AddFontDefault();
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
``` ```
If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read "[About filenames](#about-filenames)" carefully. If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read [About filenames](#about-filenames) carefully.
**Load multiple fonts:** **Load multiple fonts:**
```cpp ```cpp
@ -153,8 +94,9 @@ ImGuiIO& io = ImGui::GetIO();
ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels); ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels);
``` ```
In your application loop, select which font to use:
```cpp ```cpp
// In application loop: select font at runtime
ImGui::Text("Hello"); // use the default font (which is the first loaded font) ImGui::Text("Hello"); // use the default font (which is the first loaded font)
ImGui::PushFont(font2); ImGui::PushFont(font2);
ImGui::Text("Hello with another font"); ImGui::Text("Hello with another font");
@ -200,7 +142,6 @@ io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyp
``` ```
See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges. See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges.
**Example loading and using a Japanese font:** **Example loading and using a Japanese font:**
```cpp ```cpp
@ -220,24 +161,50 @@ ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png) ![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png)
<br>_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_ <br>_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_
**Font Atlas too large?** ##### [Return to Index](#index)
- 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. ---------------------------------------
- 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.
Some solutions: ## Loading Font Data from Memory
1. Reduce glyphs ranges by calculating them from source localization data. ```cpp
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! ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, ...);
2. You may reduce oversampling, e.g. `font_config.OversampleH = 2`, this will largely reduce your texture size. ```
Note that while OversampleH = 2 looks visibly very close to 3 in most situations, with OversampleH = 1 the quality drop will be noticeable.
3. Set `io.Fonts.TexDesiredWidth` to specify a texture width to minimize texture height (see comment in `ImFontAtlas::Build()` function). IMPORTANT: `AddFontFromMemoryTTF()` by default transfer ownership of the data buffer to the font atlas, which will attempt to free it on destruction.
4. Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two. This was to avoid an unnecessary copy, and is perhaps not a good API (a future version will redesign it).
5. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample). If you want to keep ownership of the data and free it yourself, you need to clear the `FontDataOwnedByAtlas` field:
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`.
```cpp
ImFontConfig font_cfg;
font_cfg.FontDataOwnedByAtlas = false;
ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg);
```
##### [Return to Index](#index) ##### [Return to Index](#index)
---------------------------------------
## Loading Font Data Embedded In Source Code
- 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.
- 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.
- 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)).
- 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.
Then load the font with:
```cpp
ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...);
```
or
```cpp
ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...);
```
##### [Return to Index](#index)
---------------------------------------
## Using Icon Fonts ## Using Icon Fonts
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. 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.
@ -270,11 +237,19 @@ ImGui::Button(ICON_FA_SEARCH " Search");
``` ```
See Links below for other icons fonts and related tools. See Links below for other icons fonts and related tools.
**Monospace Icons?**
To make your icon look more monospace and facilitate alignment, you may want to set the ImFontConfig::GlyphMinAdvanceX value when loading an icon font.
**Screenshot**
Here's an application using icons ("Avoyd", https://www.avoyd.com): Here's an application using icons ("Avoyd", https://www.avoyd.com):
![avoyd](https://user-images.githubusercontent.com/8225057/81696852-c15d9e80-9464-11ea-9cab-2a4d4fc84396.jpg) ![avoyd](https://user-images.githubusercontent.com/8225057/81696852-c15d9e80-9464-11ea-9cab-2a4d4fc84396.jpg)
##### [Return to Index](#index) ##### [Return to Index](#index)
---------------------------------------
## Using FreeType Rasterizer (imgui_freetype) ## Using FreeType Rasterizer (imgui_freetype)
- 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. - 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.
@ -285,9 +260,11 @@ Here's an application using icons ("Avoyd", https://www.avoyd.com):
##### [Return to Index](#index) ##### [Return to Index](#index)
---------------------------------------
## Using Colorful Glyphs/Emojis ## Using Colorful Glyphs/Emojis
- Rendering of colored emojis is only supported by imgui_freetype with FreeType 2.10+. - Rendering of colored emojis is supported by imgui_freetype with FreeType 2.10+.
- You will need to load fonts with the `ImGuiFreeTypeBuilderFlags_LoadColor` flag. - You will need to load fonts with the `ImGuiFreeTypeBuilderFlags_LoadColor` flag.
- Emojis are frequently encoded in upper Unicode layers (character codes >0x10000) and will need dear imgui compiled with `IMGUI_USE_WCHAR32`. - Emojis are frequently encoded in upper Unicode layers (character codes >0x10000) and will need dear imgui compiled with `IMGUI_USE_WCHAR32`.
- Not all types of color fonts are supported by FreeType at the moment. - Not all types of color fonts are supported by FreeType at the moment.
@ -307,6 +284,8 @@ io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg, ra
##### [Return to Index](#index) ##### [Return to Index](#index)
---------------------------------------
## Using Custom Glyph Ranges ## Using Custom Glyph Ranges
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. 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.
@ -324,6 +303,8 @@ io.Fonts->Build(); // Build the atlas while
##### [Return to Index](#index) ##### [Return to Index](#index)
---------------------------------------
## Using Custom Colorful Icons ## Using Custom Colorful Icons
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)** 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)**
@ -366,24 +347,89 @@ for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++)
##### [Return to Index](#index) ##### [Return to Index](#index)
## Using Font Data Embedded In Source Code ---------------------------------------
- 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. ## About Filenames
- 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.
- 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)).
- 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.
Then load the font with: **Please note that many new C/C++ users have issues loading their files _because the filename they provide is wrong_ due to incorrect assumption of what is the current directory.**
Two things to watch for:
(1) 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.
```cpp ```cpp
ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...); io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!!
io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT
``` ```
or In some situations, you may also use `/` path separator under Windows.
(2) Make sure your IDE/debugger settings starts your executable from the right working (current) 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.
```cpp ```cpp
ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...); io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...); // Relative filename depends on your Working Directory when running your program!
io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...); // Load from the parent folder of your Working Directory
``` ```
##### [Return to Index](#index)
---------------------------------------
## About UTF-8 Encoding
**For non-ASCII characters display, a common user issue is not passing correctly UTF-8 encoded strings.**
(1) We provide a function `ImGui::DebugTextEncoding(const char* text)` which you can call to verify the content of your UTF-8 strings.
This is a convenient way to confirm that your encoding is correct.
```cpp
ImGui::SeparatorText("CORRECT");
ImGui::DebugTextEncoding(u8"こんにちは");
ImGui::SeparatorText("INCORRECT");
ImGui::DebugTextEncoding("こんにちは");
```
![UTF-8 Encoding viewer](https://github.com/ocornut/imgui/assets/8225057/61c1696a-9a94-46c5-9627-cf91211111f0)
You can also find this tool under `Metrics/Debuggers->Tools->UTF-8 Encoding viewer` if you want to paste from clipboard, but this won't validate the UTF-8 encoding done by your compiler.
(2) To encode in UTF-8:
There are also compiler-specific ways to enforce UTF-8 encoding by default:
- Visual Studio compiler: `/utf-8` command-line flag.
- Visual Studio compiler: `#pragma execution_character_set("utf-8")` inside your code.
- Since May 2023 we have changed the Visual Studio projects of all our examples to use `/utf-8` ([see commit](https://github.com/ocornut/imgui/commit/513af1efc9080857bbd10000d98f98f2a0c96803)).
Or, since C++11, you can use the `u8"my text"` syntax to encode literal strings as UTF-8. e.g.:
```cpp
ImGui::Text(u8"hello");
ImGui::Text(u8"こんにちは"); // this will always be encoded as UTF-8
ImGui::Text("こんにちは"); // the encoding of this is depending on compiler settings/flags and may be incorrect.
```
Since C++20, because the C++ committee hate its users, they decided to change the `u8""` syntax to not return `const char*` but a new type `const char8_t*` which doesn't cast to `const char*`.
Because of type usage of `u8""` in C++20 is a little more tedious:
```cpp
ImGui::Text((const char*)u8"こんにちは");
```
However, you can disable this behavior completely using the compiler option [`/Zc:char8_t-`](https://learn.microsoft.com/en-us/cpp/build/reference/zc-char8-t?view=msvc-170) for MSVC and [`-fno-char8_t`](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1423r3.html) for Clang and GCC.
##### [Return to Index](#index)
---------------------------------------
## Debug Tools
#### Metrics/Debugger->Fonts
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.
![Fonts debugging](https://user-images.githubusercontent.com/8225057/135429892-0e41ef8d-33c5-4991-bcf6-f997a0bcfd6b.png)
#### UTF-8 Encoding Viewer**
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.
![UTF-8 Encoding viewer](https://user-images.githubusercontent.com/8225057/166505963-8a0d7899-8ee8-4558-abb2-1ae523dc02f9.png)
##### [Return to Index](#index) ##### [Return to Index](#index)
---------------------------------------
## Credits/Licenses For Fonts Included In Repository ## Credits/Licenses For Fonts Included In Repository
Some fonts files are available in the `misc/fonts/` folder: Some fonts files are available in the `misc/fonts/` folder:
@ -436,7 +482,7 @@ Some fonts files are available in the `misc/fonts/` folder:
#### MONOSPACE FONTS #### MONOSPACE FONTS
Pixel Perfect: Pixel Perfect:
- Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperbounds.net - Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php
- 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.) - 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.)
Regular: Regular:

View File

@ -11,12 +11,12 @@ Dear ImGui
Businesses: support continued development and maintenance via invoiced sponsoring/support contracts: Businesses: support continued development and maintenance via invoiced sponsoring/support contracts:
<br>&nbsp;&nbsp;_E-mail: contact @ dearimgui dot com_ <br>&nbsp;&nbsp;_E-mail: contact @ dearimgui dot com_
<br>Individuals: support continued development and maintenance [here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). Also see [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) page. <br>Individuals: support continued development and maintenance [here](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WGHNC6MBFLZ2S). Also see [Funding](https://github.com/ocornut/imgui/wiki/Funding) page.
| [The Pitch](#the-pitch) - [Usage](#usage) - [How it works](#how-it-works) - [Releases & Changelogs](#releases--changelogs) - [Demo](#demo) - [Integration](#integration) | | [The Pitch](#the-pitch) - [Usage](#usage) - [How it works](#how-it-works) - [Releases & Changelogs](#releases--changelogs) - [Demo](#demo) - [Integration](#integration) |
:----------------------------------------------------------: | :----------------------------------------------------------: |
| [Gallery](#gallery) - [Support, FAQ](#support-frequently-asked-questions-faq) - [How to help](#how-to-help) - [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors) - [Credits](#credits) - [License](#license) | | [Gallery](#gallery) - [Support, FAQ](#support-frequently-asked-questions-faq) - [How to help](#how-to-help) - **[Funding & Sponsors](https://github.com/ocornut/imgui/wiki/Funding)** - [Credits](#credits) - [License](#license) |
| [Wiki](https://github.com/ocornut/imgui/wiki) - [Languages & frameworks backends/bindings](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) | | [Wiki](https://github.com/ocornut/imgui/wiki) - [Extensions](https://github.com/ocornut/imgui/wiki/Useful-Extensions) - [Languages bindings & frameworks backends](https://github.com/ocornut/imgui/wiki/Bindings) - [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) - [User quotes](https://github.com/ocornut/imgui/wiki/Quotes) |
### The Pitch ### The Pitch
@ -27,7 +27,7 @@ Dear ImGui is designed to **enable fast iterations** and to **empower programmer
Dear ImGui is particularly suited to integration in game engines (for tooling), real-time 3D applications, fullscreen applications, embedded applications, or any applications on console platforms where operating system features are non-standard. Dear ImGui is particularly suited to integration in game engines (for tooling), real-time 3D applications, fullscreen applications, embedded applications, or any applications on console platforms where operating system features are non-standard.
- Minimize state synchronization. - Minimize state synchronization.
- Minimize state storage on user side. - Minimize UI-related state storage on user side.
- Minimize setup and maintenance. - Minimize setup and maintenance.
- Easy to use to create dynamic UI which are the reflection of a dynamic data set. - Easy to use to create dynamic UI which are the reflection of a dynamic data set.
- Easy to use to create code-driven and data-driven tools. - Easy to use to create code-driven and data-driven tools.
@ -39,9 +39,11 @@ Dear ImGui is particularly suited to integration in game engines (for tooling),
### Usage ### Usage
**The core of Dear ImGui is self-contained within a few platform-agnostic files** which you can easily compile in your application/engine. They are all the files in the root folder of the repository (imgui*.cpp, imgui*.h). **No specific build process is required**. You can add the .cpp files into your existing project. See [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started). **The core of Dear ImGui is self-contained within a few platform-agnostic files** which you can easily compile in your application/engine. They are all the files in the root folder of the repository (imgui*.cpp, imgui*.h). **No specific build process is required**. You can add the .cpp files into your existing project.
**Backends for a variety of graphics API and rendering platforms** are provided in the [backends/](https://github.com/ocornut/imgui/tree/master/backends) folder, along with example applications in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder. See the [Integration](#integration) section of this document for details. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui. **Backends for a variety of graphics API and rendering platforms** are provided in the [backends/](https://github.com/ocornut/imgui/tree/master/backends) folder, along with example applications in the [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder. You may also create your own backend. Anywhere where you can render textured triangles, you can render Dear ImGui.
See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide and [Integration](#integration) section of this document for more details.
After Dear ImGui is set up in your application, you can use it from \_anywhere\_ in your program loop: After Dear ImGui is set up in your application, you can use it from \_anywhere\_ in your program loop:
```cpp ```cpp
@ -108,15 +110,17 @@ Reading the changelogs is a good way to keep up to date with the things Dear ImG
Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing a variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. [Here's how the demo looks](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png). Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcasing a variety of features and examples. The code is always available for reference in `imgui_demo.cpp`. [Here's how the demo looks](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v167/v167-misc.png).
You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here: You should be able to build the examples from sources. If you don't, let us know! If you want to have a quick look at some Dear ImGui features, you can download Windows binaries of the demo app here:
- [imgui-demo-binaries-20230704.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20230704.zip) (Windows, 1.89.7, built 2023/07/04, master) or [older binaries](https://www.dearimgui.com/binaries). - [imgui-demo-binaries-20240105.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20240105.zip) (Windows, 1.90.1 WIP, built 2024/01/05, master) or [older binaries](https://www.dearimgui.com/binaries).
The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at a different scale and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.com/faq)). The demo applications are not DPI aware so expect some blurriness on a 4K screen. For DPI awareness in your application, you can load/reload your font at a different scale and scale your style with `style.ScaleAllSizes()` (see [FAQ](https://www.dearimgui.com/faq)).
### Integration ### Integration
See the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide for details.
On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/backends) backends without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more imgui_impl_xxxx files instead of rewriting them: this will be less work for you, and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so. On most platforms and when using C++, **you should be able to use a combination of the [imgui_impl_xxxx](https://github.com/ocornut/imgui/tree/master/backends) backends without modification** (e.g. `imgui_impl_win32.cpp` + `imgui_impl_dx11.cpp`). If your engine supports multiple platforms, consider using more imgui_impl_xxxx files instead of rewriting them: this will be less work for you, and you can get Dear ImGui running immediately. You can _later_ decide to rewrite a custom backend using your custom engine functions if you wish so.
See [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started). Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading a texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles, which is essentially what Backends are doing. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that: setting up a window and using backends. If you follow [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) it should in theory takes you less than an hour to integrate Dear ImGui. **Make sure to spend time reading the [FAQ](https://www.dearimgui.com/faq), comments, and the examples applications!** Integrating Dear ImGui within your custom engine is a matter of 1) wiring mouse/keyboard/gamepad inputs 2) uploading a texture to your GPU/render engine 3) providing a render function that can bind textures and render textured triangles, which is essentially what Backends are doing. The [examples/](https://github.com/ocornut/imgui/tree/master/examples) folder is populated with applications doing just that: setting up a window and using backends. If you follow the [Getting Started](https://github.com/ocornut/imgui/wiki/Getting-Started) guide it should in theory takes you less than an hour to integrate Dear ImGui. **Make sure to spend time reading the [FAQ](https://www.dearimgui.com/faq), comments, and the examples applications!**
Officially maintained backends/bindings (in repository): Officially maintained backends/bindings (in repository):
- Renderers: DirectX9, DirectX10, DirectX11, DirectX12, Metal, OpenGL/ES/ES2, SDL_Renderer, Vulkan, WebGPU. - Renderers: DirectX9, DirectX10, DirectX11, DirectX12, Metal, OpenGL/ES/ES2, SDL_Renderer, Vulkan, WebGPU.
@ -124,18 +128,20 @@ Officially maintained backends/bindings (in repository):
- Frameworks: Allegro5, Emscripten. - Frameworks: Allegro5, Emscripten.
[Third-party backends/bindings](https://github.com/ocornut/imgui/wiki/Bindings) wiki page: [Third-party backends/bindings](https://github.com/ocornut/imgui/wiki/Bindings) wiki page:
- Languages: C, C# and: Beef, ChaiScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lobster, Lua, Odin, Pascal, PureBasic, Python, Ruby, Rust, Swift... - Languages: C, C# and: Beef, ChaiScript, CovScript, Crystal, D, Go, Haskell, Haxe/hxcpp, Java, JavaScript, Julia, Kotlin, Lobster, Lua, Nim, Odin, Pascal, PureBasic, Python, ReaScript, Ruby, Rust, Swift, Zig...
- Frameworks: AGS/Adventure Game Studio, Amethyst, Blender, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium, GML/Game Maker Studio2, GLEQ, Godot, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, Monogame, NanoRT, nCine, Nim Game Lib, Nintendo 3DS & Switch (homebrew), Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, SDL_Renderer, SFML, Sokol, Unity, Unreal Engine 4, vtk, VulkanHpp, VulkanSceneGraph, Win32 GDI, WxWidgets. - Frameworks: AGS/Adventure Game Studio, Amethyst, Blender, bsf, Cinder, Cocos2d-x, Defold, Diligent Engine, Ebiten, Flexium, GML/Game Maker Studio, GLEQ, Godot, GTK3, Irrlicht Engine, JUCE, LÖVE+LUA, Mach Engine, Magnum, Marmalade, Monogame, NanoRT, nCine, Nim Game Lib, Nintendo 3DS/Switch/WiiU (homebrew), Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, Photoshop, px_render, Qt/QtDirect3D, raylib, SFML, Sokol, Unity, Unreal Engine 4/5, UWP, vtk, VulkanHpp, VulkanSceneGraph, Win32 GDI, WxWidgets.
- Many bindings are auto-generated (by good old [cimgui](https://github.com/cimgui/cimgui) or newer/experimental [dear_bindings](https://github.com/dearimgui/dear_bindings)), you can use their metadata output to generate bindings for other languages. - Many bindings are auto-generated (by good old [cimgui](https://github.com/cimgui/cimgui) or newer/experimental [dear_bindings](https://github.com/dearimgui/dear_bindings)), you can use their metadata output to generate bindings for other languages.
[Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page: [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page:
- Automation/testing, Text editors, node editors, timeline editors, plotting, software renderers, remote network access, memory editors, gizmos, etc. One of the most notable and well supported extension is [ImPlot](https://github.com/epezent/implot). - Automation/testing, Text editors, node editors, timeline editors, plotting, software renderers, remote network access, memory editors, gizmos, etc. Notable and well supported extensions include [ImPlot](https://github.com/epezent/implot) and [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine).
Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas. Also see [Wiki](https://github.com/ocornut/imgui/wiki) for more links and ideas.
### Gallery ### Gallery
For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues/6478)! Examples projects using Dear ImGui: [Tracy](https://github.com/wolfpld/tracy) (profiler), [ImHex](https://github.com/WerWolv/ImHex) (hex editor/data analysis), [RemedyBG](https://remedybg.itch.io/remedybg) (debugger) and [hundreds of others](https://github.com/ocornut/imgui/wiki/Software-using-Dear-ImGui).
For more user-submitted screenshots of projects using Dear ImGui, check out the [Gallery Threads](https://github.com/ocornut/imgui/issues/7503)!
For a list of third-party widgets and extensions, check out the [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page. For a list of third-party widgets and extensions, check out the [Useful Extensions/Widgets](https://github.com/ocornut/imgui/wiki/Useful-Extensions) wiki page.
@ -156,7 +162,9 @@ See: [Upcoming Changes](https://github.com/ocornut/imgui/wiki/Upcoming-Changes).
See: [Dear ImGui Test Engine + Test Suite](https://github.com/ocornut/imgui_test_engine) for Automation & Testing. See: [Dear ImGui Test Engine + Test Suite](https://github.com/ocornut/imgui_test_engine) for Automation & Testing.
Getting started? For first-time users having issues compiling/linking/running or issues loading fonts, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions). For other questions, bug reports, requests, feedback, you may post on [GitHub Issues](https://github.com/ocornut/imgui/issues). Please read and fill the New Issue template carefully. For the purposes of getting search engines to crawl the wiki, here's a link to the [Crawable Wiki](https://github-wiki-see.page/m/ocornut/imgui/wiki) (not for humans, [here's why](https://github-wiki-see.page/)).
Getting started? For first-time users having issues compiling/linking/running or issues loading fonts, please use [GitHub Discussions](https://github.com/ocornut/imgui/discussions). For ANY other questions, bug reports, requests, feedback, please post on [GitHub Issues](https://github.com/ocornut/imgui/issues). Please read and fill the New Issue template carefully.
Private support is available for paying business customers (E-mail: _contact @ dearimgui dot com_). Private support is available for paying business customers (E-mail: _contact @ dearimgui dot com_).
@ -166,23 +174,23 @@ We occasionally tag [Releases](https://github.com/ocornut/imgui/releases) (with
**Who uses Dear ImGui?** **Who uses Dear ImGui?**
See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes), [Sponsors](https://github.com/ocornut/imgui/wiki/Sponsors), and [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also, see the [Gallery Threads](https://github.com/ocornut/imgui/issues/6478)! See the [Quotes](https://github.com/ocornut/imgui/wiki/Quotes), [Funding & Sponsors](https://github.com/ocornut/imgui/wiki/Funding), and [Software using Dear ImGui](https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for an idea of who is using Dear ImGui. Please add your game/software if you can! Also, see the [Gallery Threads](https://github.com/ocornut/imgui/issues/7503)!
How to help How to help
----------- -----------
**How can I help?** **How can I help?**
- See [GitHub Forum/Issues](https://github.com/ocornut/imgui/issues) and [GitHub Discussions](https://github.com/ocornut/imgui/discussions). - See [GitHub Forum/Issues](https://github.com/ocornut/imgui/issues).
- You may help with development and submit pull requests! 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 forever. PR should be crafted both in the interest of the end-users and also to ease the maintainer into understanding and accepting it. - You may help with development and submit pull requests! 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 forever. PR should be crafted both in the interest of the end-users and also to ease the maintainer into understanding and accepting it.
- See [Help wanted](https://github.com/ocornut/imgui/wiki/Help-Wanted) on the [Wiki](https://github.com/ocornut/imgui/wiki/) for some more ideas. - See [Help wanted](https://github.com/ocornut/imgui/wiki/Help-Wanted) on the [Wiki](https://github.com/ocornut/imgui/wiki/) for some more ideas.
- Have your company financially support this project with invoiced sponsoring/support contracts or by buying a license for [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine) (please reach out: contact at dearimgui dot com). - Be a [Funding Supporter](https://github.com/ocornut/imgui/wiki/Funding)! Have your company financially support this project via invoiced sponsors/maintenance or by buying a license for [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine) (please reach out: omar AT dearimgui DOT com).
Sponsors Sponsors
-------- --------
Ongoing Dear ImGui development is and has been financially supported by users and private sponsors. Ongoing Dear ImGui development is and has been financially supported by users and private sponsors.
<BR>Please see the **[detailed list of current and past Dear ImGui supporters](https://github.com/ocornut/imgui/wiki/Sponsors)** for details. <BR>Please see the **[detailed list of current and past Dear ImGui funding supporters and sponsors](https://github.com/ocornut/imgui/wiki/Funding)** for details.
<BR>From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations. <BR>From November 2014 to December 2019, ongoing development has also been financially supported by its users on Patreon and through individual donations.
**THANK YOU to all past and present supporters for helping to keep this project alive and thriving!** **THANK YOU to all past and present supporters for helping to keep this project alive and thriving!**
@ -197,13 +205,13 @@ Credits
Developed by [Omar Cornut](https://www.miracleworld.net) and every direct or indirect [contributors](https://github.com/ocornut/imgui/graphs/contributors) to the GitHub. The early version of this library was developed with the support of [Media Molecule](https://www.mediamolecule.com) and first used internally on the game [Tearaway](https://tearaway.mediamolecule.com) (PS Vita). Developed by [Omar Cornut](https://www.miracleworld.net) and every direct or indirect [contributors](https://github.com/ocornut/imgui/graphs/contributors) to the GitHub. The early version of this library was developed with the support of [Media Molecule](https://www.mediamolecule.com) and first used internally on the game [Tearaway](https://tearaway.mediamolecule.com) (PS Vita).
Recurring contributors (2022): Omar Cornut [@ocornut](https://github.com/ocornut), Rokas Kupstys [@rokups](https://github.com/rokups) (a good portion of work on automation system and regression tests now available in [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine)). Recurring contributors include Rokas Kupstys [@rokups](https://github.com/rokups) (2020-2022): a good portion of work on automation system and regression tests now available in [Dear ImGui Test Engine](https://github.com/ocornut/imgui_test_engine).
Sponsoring, support contracts and other B2B transactions are hosted and handled by [Disco Hello](https://www.discohello.com). Maintenance/support contracts, sponsoring invoices and other B2B transactions are hosted and handled by [Disco Hello](https://www.discohello.com).
Omar: "I first discovered the IMGUI paradigm at [Q-Games](https://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it." Omar: "I first discovered the IMGUI paradigm at [Q-Games](https://www.q-games.com) where Atman Binstock had dropped his own simple implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating and improving it."
Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license). Embeds [ProggyClean.ttf](https://www.proggyfonts.net) font by Tristan Grimmer (MIT license).
<br>Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). <br>Embeds [stb_textedit.h, stb_truetype.h, stb_rect_pack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain).
Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Also thank you to everyone posting feedback, questions and patches on GitHub. Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. Also thank you to everyone posting feedback, questions and patches on GitHub.

View File

@ -126,7 +126,7 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
- separator: expose flags (#759) - separator: expose flags (#759)
- separator: take indent into consideration (optional) - separator: take indent into consideration (optional)
- separator: width, thickness, centering (#1643) - separator: width, thickness, centering (#1643, #2657)
- splitter: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - splitter: formalize the splitter idiom into an official api (we want to handle n-way split) (#319)
- docking: merge docking branch (#2109) - docking: merge docking branch (#2109)
@ -175,6 +175,8 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
- tooltip: drag tooltip hovering over source widget with IsItemHovered/SetTooltip flickers (WIP branch) - tooltip: drag tooltip hovering over source widget with IsItemHovered/SetTooltip flickers (WIP branch)
- status-bar: add a per-window status bar helper similar to what menu-bar does. generalize concept of layer0 rect in window (can make _MenuBar window flag obsolete too). - status-bar: add a per-window status bar helper similar to what menu-bar does. generalize concept of layer0 rect in window (can make _MenuBar window flag obsolete too).
- shortcuts: store multiple keychords in ImGuiKeyChord
- shortcuts: Hovered route (lower than Focused, higher than Global)
- shortcuts: local-style shortcut api, e.g. parse "&Save" - shortcuts: local-style shortcut api, e.g. parse "&Save"
- shortcuts,menus: global-style shortcut api e.g. "Save (CTRL+S)" -> explicit flag for recursing into closed menu - shortcuts,menus: global-style shortcut api e.g. "Save (CTRL+S)" -> explicit flag for recursing into closed menu
- shortcuts: programmatically access shortcuts "Focus("&Save")) - shortcuts: programmatically access shortcuts "Focus("&Save"))
@ -187,7 +189,6 @@ It's mostly a bunch of personal notes, probably incomplete. Feel free to query i
- tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer)
- tree node: tweak color scheme to distinguish headers from selected tree node (#581) - tree node: tweak color scheme to distinguish headers from selected tree node (#581)
- tree node: leaf/non-leaf highlight mismatch. - tree node: leaf/non-leaf highlight mismatch.
- tree node: flag to disable formatting and/or detect "%s"
- tree node/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height? format only %s/%c to be able to count height?) - tree node/opt: could avoid formatting when clipped (flag assuming we don't care about width/height, assume single line height? format only %s/%c to be able to count height?)
- settings: write more decent code to allow saving/loading new fields: columns, selected tree nodes? - settings: write more decent code to allow saving/loading new fields: columns, selected tree nodes?

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for Allegro 5 // Dear ImGui: standalone example application for Allegro 5
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// On Windows, you can install Allegro5 using vcpkg: // On Windows, you can install Allegro5 using vcpkg:
// git clone https://github.com/Microsoft/vcpkg // git clone https://github.com/Microsoft/vcpkg

View File

@ -1,5 +1,10 @@
// dear imgui: standalone example application for Android + OpenGL ES 3 // dear imgui: standalone example application for Android + OpenGL ES 3
// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_android.h" #include "imgui_impl_android.h"
@ -156,7 +161,7 @@ void Init(struct android_app* app)
// We load the default font with increased size to improve readability on many devices with "high" DPI. // We load the default font with increased size to improve readability on many devices with "high" DPI.
// FIXME: Put some effort into DPI awareness. // FIXME: Put some effort into DPI awareness.
// Important: when calling AddFontFromMemoryTTF(), ownership of font_data is transfered by Dear ImGui by default (deleted is handled by Dear ImGui), unless we set FontDataOwnedByAtlas=false in ImFontConfig // Important: when calling AddFontFromMemoryTTF(), ownership of font_data is transferred by Dear ImGui by default (deleted is handled by Dear ImGui), unless we set FontDataOwnedByAtlas=false in ImFontConfig
ImFontConfig font_cfg; ImFontConfig font_cfg;
font_cfg.SizePixels = 22.0f; font_cfg.SizePixels = 22.0f;
io.Fonts->AddFontDefault(&font_cfg); io.Fonts->AddFontDefault(&font_cfg);

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for OSX + Metal. // Dear ImGui: standalone example application for OSX + Metal.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for OSX + OpenGL2, using legacy fixed pipeline // Dear ImGui: standalone example application for OSX + OpenGL2, using legacy fixed pipeline
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#import <OpenGL/gl.h> #import <OpenGL/gl.h>

View File

@ -1,246 +0,0 @@
// Dear ImGui: standalone example application for Emscripten, using GLFW + WebGPU
// (Emscripten is a C++-to-javascript compiler, used to publish executables for the web. See https://emscripten.org/)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_wgpu.h"
#include <stdio.h>
#include <emscripten.h>
#include <emscripten/html5.h>
#include <emscripten/html5_webgpu.h>
#include <GLFW/glfw3.h>
#include <webgpu/webgpu.h>
#include <webgpu/webgpu_cpp.h>
// Global WebGPU required states
static WGPUDevice wgpu_device = nullptr;
static WGPUSurface wgpu_surface = nullptr;
static WGPUSwapChain wgpu_swap_chain = nullptr;
static int wgpu_swap_chain_width = 0;
static int wgpu_swap_chain_height = 0;
// Forward declarations
static void MainLoopStep(void* window);
static bool InitWGPU();
static void print_glfw_error(int error, const char* description);
static void print_wgpu_error(WGPUErrorType error_type, const char* message, void*);
// Main code
int main(int, char**)
{
glfwSetErrorCallback(print_glfw_error);
if (!glfwInit())
return 1;
// Make sure GLFW does not initialize any graphics context.
// This needs to be done explicitly later.
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+WebGPU example", nullptr, nullptr);
if (!window)
{
glfwTerminate();
return 1;
}
// Initialize the WebGPU environment
if (!InitWGPU())
{
if (window)
glfwDestroyWindow(window);
glfwTerminate();
return 1;
}
glfwShowWindow(window);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
// You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
io.IniFilename = nullptr;
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsLight();
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOther(window, true);
ImGui_ImplWGPU_Init(wgpu_device, 3, WGPUTextureFormat_RGBA8Unorm, WGPUTextureFormat_Undefined);
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
// - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details.
//io.Fonts->AddFontDefault();
#ifndef IMGUI_DISABLE_FILE_FUNCTIONS
//io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf", 18.0f);
io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != nullptr);
#endif
// This function will directly return and exit the main function.
// Make sure that no required objects get cleaned up.
// This way we can use the browsers 'requestAnimationFrame' to control the rendering.
emscripten_set_main_loop_arg(MainLoopStep, window, 0, false);
return 0;
}
static bool InitWGPU()
{
wgpu_device = emscripten_webgpu_get_device();
if (!wgpu_device)
return false;
wgpuDeviceSetUncapturedErrorCallback(wgpu_device, print_wgpu_error, nullptr);
// Use C++ wrapper due to misbehavior in Emscripten.
// Some offset computation for wgpuInstanceCreateSurface in JavaScript
// seem to be inline with struct alignments in the C++ structure
wgpu::SurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {};
html_surface_desc.selector = "#canvas";
wgpu::SurfaceDescriptor surface_desc = {};
surface_desc.nextInChain = &html_surface_desc;
// Use 'null' instance
wgpu::Instance instance = {};
wgpu_surface = instance.CreateSurface(&surface_desc).Release();
return true;
}
static void MainLoopStep(void* window)
{
ImGuiIO& io = ImGui::GetIO();
glfwPollEvents();
int width, height;
glfwGetFramebufferSize((GLFWwindow*)window, &width, &height);
// React to changes in screen size
if (width != wgpu_swap_chain_width && height != wgpu_swap_chain_height)
{
ImGui_ImplWGPU_InvalidateDeviceObjects();
if (wgpu_swap_chain)
wgpuSwapChainRelease(wgpu_swap_chain);
wgpu_swap_chain_width = width;
wgpu_swap_chain_height = height;
WGPUSwapChainDescriptor swap_chain_desc = {};
swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment;
swap_chain_desc.format = WGPUTextureFormat_RGBA8Unorm;
swap_chain_desc.width = width;
swap_chain_desc.height = height;
swap_chain_desc.presentMode = WGPUPresentMode_Fifo;
wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc);
ImGui_ImplWGPU_CreateDeviceObjects();
}
// Start the Dear ImGui frame
ImGui_ImplWGPU_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// Our state
// (we use static, which essentially makes the variable globals, as a convenience to keep the example code easy to follow)
static bool show_demo_window = true;
static bool show_another_window = false;
static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
ImGui::Checkbox("Another Window", &show_another_window);
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::End();
}
// 3. Show another simple window.
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
show_another_window = false;
ImGui::End();
}
// Rendering
ImGui::Render();
WGPURenderPassColorAttachment color_attachments = {};
color_attachments.loadOp = WGPULoadOp_Clear;
color_attachments.storeOp = WGPUStoreOp_Store;
color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain);
WGPURenderPassDescriptor render_pass_desc = {};
render_pass_desc.colorAttachmentCount = 1;
render_pass_desc.colorAttachments = &color_attachments;
render_pass_desc.depthStencilAttachment = nullptr;
WGPUCommandEncoderDescriptor enc_desc = {};
WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc);
WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass);
wgpuRenderPassEncoderEnd(pass);
WGPUCommandBufferDescriptor cmd_buffer_desc = {};
WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc);
WGPUQueue queue = wgpuDeviceGetQueue(wgpu_device);
wgpuQueueSubmit(queue, 1, &cmd_buffer);
}
static void print_glfw_error(int error, const char* description)
{
printf("GLFW Error %d: %s\n", error, description);
}
static void print_wgpu_error(WGPUErrorType error_type, const char* message, void*)
{
const char* error_type_lbl = "";
switch (error_type)
{
case WGPUErrorType_Validation: error_type_lbl = "Validation"; break;
case WGPUErrorType_OutOfMemory: error_type_lbl = "Out of memory"; break;
case WGPUErrorType_Unknown: error_type_lbl = "Unknown"; break;
case WGPUErrorType_DeviceLost: error_type_lbl = "Device lost"; break;
default: error_type_lbl = "Unknown";
}
printf("%s error: %s\n", error_type_lbl, message);
}

View File

@ -14,10 +14,10 @@ SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui
OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES)))) OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES))))
LIBS = -framework Metal -framework MetalKit -framework Cocoa -framework IOKit -framework CoreVideo -framework QuartzCore LIBS = -framework Metal -framework MetalKit -framework Cocoa -framework IOKit -framework CoreVideo -framework QuartzCore
LIBS += -L/usr/local/lib -L/opt/homebrew/lib LIBS += -L/usr/local/lib -L/opt/homebrew/lib -L/opt/local/lib
LIBS += -lglfw LIBS += -lglfw
CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/local/include -I/opt/homebrew/include CXXFLAGS = -std=c++11 -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends -I/usr/local/include -I/opt/homebrew/include -I/opt/local/include
CXXFLAGS += -Wall -Wformat CXXFLAGS += -Wall -Wformat
CFLAGS = $(CXXFLAGS) CFLAGS = $(CXXFLAGS)

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for GLFW + Metal, using programmable pipeline // Dear ImGui: standalone example application for GLFW + Metal, using programmable pipeline
// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_glfw.h" #include "imgui_impl_glfw.h"

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for GLFW + OpenGL2, using legacy fixed pipeline // Dear ImGui: standalone example application for GLFW + OpenGL2, using legacy fixed pipeline
// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
// **Prefer using the code in the example_glfw_opengl2/ folder** // **Prefer using the code in the example_glfw_opengl2/ folder**

View File

@ -59,7 +59,7 @@ endif
CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends
#CPPFLAGS += -g #CPPFLAGS += -g
CPPFLAGS += -Wall -Wformat -Os $(EMS) CPPFLAGS += -Wall -Wformat -Os $(EMS)
# LDFLAGS += --shell-file ../libs/emscripten/shell_minimal.html LDFLAGS += --shell-file ../libs/emscripten/shell_minimal.html
LDFLAGS += $(EMS) LDFLAGS += $(EMS)
##--------------------------------------------------------------------- ##---------------------------------------------------------------------

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for GLFW + OpenGL 3, using programmable pipeline // Dear ImGui: standalone example application for GLFW + OpenGL 3, using programmable pipeline
// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_glfw.h" #include "imgui_impl_glfw.h"
@ -80,6 +84,9 @@ int main(int, char**)
// Setup Platform/Renderer backends // Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplGlfw_InitForOpenGL(window, true);
#ifdef __EMSCRIPTEN__
ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas");
#endif
ImGui_ImplOpenGL3_Init(glsl_version); ImGui_ImplOpenGL3_Init(glsl_version);
// Load Fonts // Load Fonts

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for Glfw + Vulkan // Dear ImGui: standalone example application for Glfw + Vulkan
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
@ -17,8 +21,12 @@
#define GLFW_INCLUDE_NONE #define GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_VULKAN #define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
#include <vulkan/vulkan.h>
//#include <vulkan/vulkan_beta.h> // Volk headers
#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
#define VOLK_IMPLEMENTATION
#include <Volk/volk.h>
#endif
// [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers. // [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers.
// To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma. // To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma.
@ -27,9 +35,9 @@
#pragma comment(lib, "legacy_stdio_definitions") #pragma comment(lib, "legacy_stdio_definitions")
#endif #endif
//#define IMGUI_UNLIMITED_FRAME_RATE //#define APP_USE_UNLIMITED_FRAME_RATE
#ifdef _DEBUG #ifdef _DEBUG
#define IMGUI_VULKAN_DEBUG_REPORT #define APP_USE_VULKAN_DEBUG_REPORT
#endif #endif
// Data // Data
@ -60,14 +68,14 @@ static void check_vk_result(VkResult err)
abort(); abort();
} }
#ifdef IMGUI_VULKAN_DEBUG_REPORT #ifdef APP_USE_VULKAN_DEBUG_REPORT
static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData)
{ {
(void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments
fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage);
return VK_FALSE; return VK_FALSE;
} }
#endif // IMGUI_VULKAN_DEBUG_REPORT #endif // APP_USE_VULKAN_DEBUG_REPORT
static bool IsExtensionAvailable(const ImVector<VkExtensionProperties>& properties, const char* extension) static bool IsExtensionAvailable(const ImVector<VkExtensionProperties>& properties, const char* extension)
{ {
@ -109,6 +117,9 @@ static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice()
static void SetupVulkan(ImVector<const char*> instance_extensions) static void SetupVulkan(ImVector<const char*> instance_extensions)
{ {
VkResult err; VkResult err;
#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
volkInitialize();
#endif
// Create Vulkan Instance // Create Vulkan Instance
{ {
@ -135,7 +146,7 @@ static void SetupVulkan(ImVector<const char*> instance_extensions)
#endif #endif
// Enabling validation layers // Enabling validation layers
#ifdef IMGUI_VULKAN_DEBUG_REPORT #ifdef APP_USE_VULKAN_DEBUG_REPORT
const char* layers[] = { "VK_LAYER_KHRONOS_validation" }; const char* layers[] = { "VK_LAYER_KHRONOS_validation" };
create_info.enabledLayerCount = 1; create_info.enabledLayerCount = 1;
create_info.ppEnabledLayerNames = layers; create_info.ppEnabledLayerNames = layers;
@ -147,17 +158,20 @@ static void SetupVulkan(ImVector<const char*> instance_extensions)
create_info.ppEnabledExtensionNames = instance_extensions.Data; create_info.ppEnabledExtensionNames = instance_extensions.Data;
err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); err = vkCreateInstance(&create_info, g_Allocator, &g_Instance);
check_vk_result(err); check_vk_result(err);
#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
volkLoadInstance(g_Instance);
#endif
// Setup the debug report callback // Setup the debug report callback
#ifdef IMGUI_VULKAN_DEBUG_REPORT #ifdef APP_USE_VULKAN_DEBUG_REPORT
auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT"); auto f_vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT");
IM_ASSERT(vkCreateDebugReportCallbackEXT != nullptr); IM_ASSERT(f_vkCreateDebugReportCallbackEXT != nullptr);
VkDebugReportCallbackCreateInfoEXT debug_report_ci = {}; VkDebugReportCallbackCreateInfoEXT debug_report_ci = {};
debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
debug_report_ci.pfnCallback = debug_report; debug_report_ci.pfnCallback = debug_report;
debug_report_ci.pUserData = nullptr; debug_report_ci.pUserData = nullptr;
err = vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport); err = f_vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport);
check_vk_result(err); check_vk_result(err);
#endif #endif
} }
@ -215,25 +229,17 @@ static void SetupVulkan(ImVector<const char*> instance_extensions)
} }
// Create Descriptor Pool // Create Descriptor Pool
// The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that)
// If you wish to load e.g. additional textures you may need to alter pools sizes.
{ {
VkDescriptorPoolSize pool_sizes[] = VkDescriptorPoolSize pool_sizes[] =
{ {
{ VK_DESCRIPTOR_TYPE_SAMPLER, 1000 }, { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 },
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
{ VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
{ VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 }
}; };
VkDescriptorPoolCreateInfo pool_info = {}; VkDescriptorPoolCreateInfo pool_info = {};
pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
pool_info.maxSets = 1000 * IM_ARRAYSIZE(pool_sizes); pool_info.maxSets = 1;
pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes);
pool_info.pPoolSizes = pool_sizes; pool_info.pPoolSizes = pool_sizes;
err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool);
@ -262,7 +268,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface
wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace);
// Select Present Mode // Select Present Mode
#ifdef IMGUI_UNLIMITED_FRAME_RATE #ifdef APP_USE_UNLIMITED_FRAME_RATE
VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR };
#else #else
VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR };
@ -279,11 +285,11 @@ static void CleanupVulkan()
{ {
vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator);
#ifdef IMGUI_VULKAN_DEBUG_REPORT #ifdef APP_USE_VULKAN_DEBUG_REPORT
// Remove the debug report callback // Remove the debug report callback
auto vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT"); auto f_vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT");
vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator); f_vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator);
#endif // IMGUI_VULKAN_DEBUG_REPORT #endif // APP_USE_VULKAN_DEBUG_REPORT
vkDestroyDevice(g_Device, g_Allocator); vkDestroyDevice(g_Device, g_Allocator);
vkDestroyInstance(g_Instance, g_Allocator); vkDestroyInstance(g_Instance, g_Allocator);
@ -380,7 +386,7 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd)
return; return;
} }
check_vk_result(err); check_vk_result(err);
wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores
} }
// Main code // Main code
@ -438,13 +444,14 @@ int main(int, char**)
init_info.Queue = g_Queue; init_info.Queue = g_Queue;
init_info.PipelineCache = g_PipelineCache; init_info.PipelineCache = g_PipelineCache;
init_info.DescriptorPool = g_DescriptorPool; init_info.DescriptorPool = g_DescriptorPool;
init_info.RenderPass = wd->RenderPass;
init_info.Subpass = 0; init_info.Subpass = 0;
init_info.MinImageCount = g_MinImageCount; init_info.MinImageCount = g_MinImageCount;
init_info.ImageCount = wd->ImageCount; init_info.ImageCount = wd->ImageCount;
init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT;
init_info.Allocator = g_Allocator; init_info.Allocator = g_Allocator;
init_info.CheckVkResultFn = check_vk_result; init_info.CheckVkResultFn = check_vk_result;
ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); ImGui_ImplVulkan_Init(&init_info);
// Load Fonts // Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
@ -462,36 +469,6 @@ int main(int, char**)
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != nullptr); //IM_ASSERT(font != nullptr);
// Upload Fonts
{
// Use any command queue
VkCommandPool command_pool = wd->Frames[wd->FrameIndex].CommandPool;
VkCommandBuffer command_buffer = wd->Frames[wd->FrameIndex].CommandBuffer;
err = vkResetCommandPool(g_Device, command_pool, 0);
check_vk_result(err);
VkCommandBufferBeginInfo begin_info = {};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
err = vkBeginCommandBuffer(command_buffer, &begin_info);
check_vk_result(err);
ImGui_ImplVulkan_CreateFontsTexture(command_buffer);
VkSubmitInfo end_info = {};
end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
end_info.commandBufferCount = 1;
end_info.pCommandBuffers = &command_buffer;
err = vkEndCommandBuffer(command_buffer);
check_vk_result(err);
err = vkQueueSubmit(g_Queue, 1, &end_info, VK_NULL_HANDLE);
check_vk_result(err);
err = vkDeviceWaitIdle(g_Device);
check_vk_result(err);
ImGui_ImplVulkan_DestroyFontUploadObjects();
}
// Our state // Our state
bool show_demo_window = true; bool show_demo_window = true;
bool show_another_window = false; bool show_another_window = false;

View File

@ -0,0 +1,100 @@
# Building for desktop (WebGPU-native) with Dawn:
# 1. git clone https://github.com/google/dawn dawn
# 2. cmake -B build -DIMGUI_DAWN_DIR=dawn
# 3. cmake --build build
# The resulting binary will be found at one of the following locations:
# * build/Debug/example_glfw_wgpu[.exe]
# * build/example_glfw_wgpu[.exe]
# Building for Emscripten:
# 1. Install Emscripten SDK following the instructions: https://emscripten.org/docs/getting_started/downloads.html
# 2. Install Ninja build system
# 3. emcmake cmake -G Ninja -B build
# 3. cmake --build build
# 4. emrun build/index.html
cmake_minimum_required(VERSION 3.10.2)
project(imgui_example_glfw_wgpu C CXX)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE)
endif()
set(CMAKE_CXX_STANDARD 17) # Dawn requires C++17
# Dear ImGui
set(IMGUI_DIR ../../)
# Libraries
if(EMSCRIPTEN)
set(LIBRARIES glfw)
add_compile_options(-sDISABLE_EXCEPTION_CATCHING=1 -DIMGUI_DISABLE_FILE_FUNCTIONS=1)
else()
# Dawn wgpu desktop
set(DAWN_FETCH_DEPENDENCIES ON)
set(IMGUI_DAWN_DIR CACHE PATH "Path to Dawn repository")
if (NOT IMGUI_DAWN_DIR)
message(FATAL_ERROR "Please specify the Dawn repository by setting IMGUI_DAWN_DIR")
endif()
option(DAWN_FETCH_DEPENDENCIES "Use fetch_dawn_dependencies.py as an alternative to using depot_tools" ON)
# Dawn builds many things by default - disable things we don't need
option(DAWN_BUILD_SAMPLES "Enables building Dawn's samples" OFF)
option(TINT_BUILD_CMD_TOOLS "Build the Tint command line tools" OFF)
option(TINT_BUILD_DOCS "Build documentation" OFF)
option(TINT_BUILD_TESTS "Build tests" OFF)
if (NOT APPLE)
option(TINT_BUILD_MSL_WRITER "Build the MSL output writer" OFF)
endif()
if(WIN32)
option(TINT_BUILD_SPV_READER "Build the SPIR-V input reader" OFF)
option(TINT_BUILD_WGSL_READER "Build the WGSL input reader" ON)
option(TINT_BUILD_GLSL_WRITER "Build the GLSL output writer" OFF)
option(TINT_BUILD_GLSL_VALIDATOR "Build the GLSL output validator" OFF)
option(TINT_BUILD_SPV_WRITER "Build the SPIR-V output writer" OFF)
option(TINT_BUILD_WGSL_WRITER "Build the WGSL output writer" ON)
endif()
add_subdirectory("${IMGUI_DAWN_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/dawn" EXCLUDE_FROM_ALL)
set(LIBRARIES webgpu_dawn webgpu_cpp webgpu_glfw glfw)
endif()
add_executable(example_glfw_wgpu
main.cpp
# backend files
${IMGUI_DIR}/backends/imgui_impl_glfw.cpp
${IMGUI_DIR}/backends/imgui_impl_wgpu.cpp
# Dear ImGui files
${IMGUI_DIR}/imgui.cpp
${IMGUI_DIR}/imgui_draw.cpp
${IMGUI_DIR}/imgui_demo.cpp
${IMGUI_DIR}/imgui_tables.cpp
${IMGUI_DIR}/imgui_widgets.cpp
)
target_include_directories(example_glfw_wgpu PUBLIC
${IMGUI_DIR}
${IMGUI_DIR}/backends
)
target_link_libraries(example_glfw_wgpu PUBLIC ${LIBRARIES})
# Emscripten settings
if(EMSCRIPTEN)
target_link_options(example_glfw_wgpu PRIVATE
"-sUSE_WEBGPU=1"
"-sUSE_GLFW=3"
"-sWASM=1"
"-sALLOW_MEMORY_GROWTH=1"
"-sNO_EXIT_RUNTIME=0"
"-sASSERTIONS=1"
"-sDISABLE_EXCEPTION_CATCHING=1"
"-sNO_FILESYSTEM=1"
)
set_target_properties(example_glfw_wgpu PROPERTIES OUTPUT_NAME "index")
# copy our custom index.html to build directory
add_custom_command(TARGET example_glfw_wgpu POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_LIST_DIR}/web/index.html" $<TARGET_FILE_DIR:example_glfw_wgpu>
)
endif()

View File

@ -6,7 +6,7 @@
- You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup. - You may also refer to our [Continuous Integration setup](https://github.com/ocornut/imgui/tree/master/.github/workflows) for Emscripten setup.
- Then build using `make` while in the `example_emscripten_wgpu/` directory. - Then build using `make -f Makefile.emscripten` while in the `example_glfw_wgpu/` directory.
- Requires recent Emscripten as WGPU is still a work-in-progress API. - Requires recent Emscripten as WGPU is still a work-in-progress API.
@ -18,7 +18,7 @@ To run on a local machine:
- Otherwise, generally you will need a local webserver: - Otherwise, generally you will need a local webserver:
- Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):<br> - Quoting [https://emscripten.org/docs/getting_started](https://emscripten.org/docs/getting_started/Tutorial.html#generating-html):<br>
_"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and cant load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers youll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_ _"Unfortunately several browsers (including Chrome, Safari, and Internet Explorer) do not support file:// [XHR](https://emscripten.org/docs/site/glossary.html#term-xhr) requests, and cant load extra files needed by the HTML (like a .wasm file, or packaged file data as mentioned lower down). For these browsers youll need to serve the files using a [local webserver](https://emscripten.org/docs/getting_started/FAQ.html#faq-local-webserver) and then open http://localhost:8000/hello.html."_
- Emscripten SDK has a handy `emrun` command: `emrun web/example_emscripten_opengl3.html --browser firefox` which will spawn a temporary local webserver (in Firefox). See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details. - Emscripten SDK has a handy `emrun` command: `emrun web/example_glfw_wgpu.html --browser firefox` which will spawn a temporary local webserver (in Firefox). See https://emscripten.org/docs/compiling/Running-html-files-with-emrun.html for details.
- You may use Python 3 builtin webserver: `python -m http.server -d web` (this is what `make serve` uses). - You may use Python 3 builtin webserver: `python -m http.server -d web` (this is what `make serve` uses).
- You may use Python 2 builtin webserver: `cd web && python -m SimpleHTTPServer`. - You may use Python 2 builtin webserver: `cd web && python -m SimpleHTTPServer`.
- If you are accessing the files over a network, certain browsers, such as Firefox, will restrict Gamepad API access to secure contexts only (e.g. https only). - If you are accessing the files over a network, certain browsers, such as Firefox, will restrict Gamepad API access to secure contexts only (e.g. https only).

View File

@ -0,0 +1,345 @@
// Dear ImGui: standalone example application for using GLFW + WebGPU
// - Emscripten is supported for publishing on web. See https://emscripten.org.
// - Dawn is used as a WebGPU implementation on desktop.
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_wgpu.h"
#include <stdio.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <emscripten/html5.h>
#include <emscripten/html5_webgpu.h>
#else
#include <webgpu/webgpu_glfw.h>
#endif
#include <GLFW/glfw3.h>
#include <webgpu/webgpu.h>
#include <webgpu/webgpu_cpp.h>
// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details.
#ifdef __EMSCRIPTEN__
#include "../libs/emscripten/emscripten_mainloop_stub.h"
#endif
// Global WebGPU required states
static WGPUInstance wgpu_instance = nullptr;
static WGPUDevice wgpu_device = nullptr;
static WGPUSurface wgpu_surface = nullptr;
static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm;
static WGPUSwapChain wgpu_swap_chain = nullptr;
static int wgpu_swap_chain_width = 1280;
static int wgpu_swap_chain_height = 720;
// Forward declarations
static bool InitWGPU(GLFWwindow* window);
static void CreateSwapChain(int width, int height);
static void glfw_error_callback(int error, const char* description)
{
printf("GLFW Error %d: %s\n", error, description);
}
static void wgpu_error_callback(WGPUErrorType error_type, const char* message, void*)
{
const char* error_type_lbl = "";
switch (error_type)
{
case WGPUErrorType_Validation: error_type_lbl = "Validation"; break;
case WGPUErrorType_OutOfMemory: error_type_lbl = "Out of memory"; break;
case WGPUErrorType_Unknown: error_type_lbl = "Unknown"; break;
case WGPUErrorType_DeviceLost: error_type_lbl = "Device lost"; break;
default: error_type_lbl = "Unknown";
}
printf("%s error: %s\n", error_type_lbl, message);
}
// Main code
int main(int, char**)
{
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
return 1;
// Make sure GLFW does not initialize any graphics context.
// This needs to be done explicitly later.
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(wgpu_swap_chain_width, wgpu_swap_chain_height, "Dear ImGui GLFW+WebGPU example", nullptr, nullptr);
if (window == nullptr)
return 1;
// Initialize the WebGPU environment
if (!InitWGPU(window))
{
if (window)
glfwDestroyWindow(window);
glfwTerminate();
return 1;
}
CreateSwapChain(wgpu_swap_chain_width, wgpu_swap_chain_height);
glfwShowWindow(window);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsLight();
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOther(window, true);
#ifdef __EMSCRIPTEN__
ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback("#canvas");
#endif
ImGui_ImplWGPU_InitInfo init_info;
init_info.Device = wgpu_device;
init_info.NumFramesInFlight = 3;
init_info.RenderTargetFormat = wgpu_preferred_fmt;
init_info.DepthStencilFormat = WGPUTextureFormat_Undefined;
ImGui_ImplWGPU_Init(&init_info);
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
// - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details.
//io.Fonts->AddFontDefault();
#ifndef IMGUI_DISABLE_FILE_FUNCTIONS
//io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf", 18.0f);
//io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != nullptr);
#endif
// Our state
bool show_demo_window = true;
bool show_another_window = false;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
#ifdef __EMSCRIPTEN__
// For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
// You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
io.IniFilename = nullptr;
EMSCRIPTEN_MAINLOOP_BEGIN
#else
while (!glfwWindowShouldClose(window))
#endif
{
// Poll and handle events (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
glfwPollEvents();
// React to changes in screen size
int width, height;
glfwGetFramebufferSize((GLFWwindow*)window, &width, &height);
if (width != wgpu_swap_chain_width || height != wgpu_swap_chain_height)
{
ImGui_ImplWGPU_InvalidateDeviceObjects();
CreateSwapChain(width, height);
ImGui_ImplWGPU_CreateDeviceObjects();
}
// Start the Dear ImGui frame
ImGui_ImplWGPU_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
ImGui::Checkbox("Another Window", &show_another_window);
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::End();
}
// 3. Show another simple window.
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
show_another_window = false;
ImGui::End();
}
// Rendering
ImGui::Render();
#ifndef __EMSCRIPTEN__
// Tick needs to be called in Dawn to display validation errors
wgpuDeviceTick(wgpu_device);
#endif
WGPURenderPassColorAttachment color_attachments = {};
color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
color_attachments.loadOp = WGPULoadOp_Clear;
color_attachments.storeOp = WGPUStoreOp_Store;
color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain);
WGPURenderPassDescriptor render_pass_desc = {};
render_pass_desc.colorAttachmentCount = 1;
render_pass_desc.colorAttachments = &color_attachments;
render_pass_desc.depthStencilAttachment = nullptr;
WGPUCommandEncoderDescriptor enc_desc = {};
WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc);
WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass);
wgpuRenderPassEncoderEnd(pass);
WGPUCommandBufferDescriptor cmd_buffer_desc = {};
WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc);
WGPUQueue queue = wgpuDeviceGetQueue(wgpu_device);
wgpuQueueSubmit(queue, 1, &cmd_buffer);
#ifndef __EMSCRIPTEN__
wgpuSwapChainPresent(wgpu_swap_chain);
#endif
wgpuTextureViewRelease(color_attachments.view);
wgpuRenderPassEncoderRelease(pass);
wgpuCommandEncoderRelease(encoder);
wgpuCommandBufferRelease(cmd_buffer);
}
#ifdef __EMSCRIPTEN__
EMSCRIPTEN_MAINLOOP_END;
#endif
// Cleanup
ImGui_ImplWGPU_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
#ifndef __EMSCRIPTEN__
static WGPUAdapter RequestAdapter(WGPUInstance instance)
{
auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* message, void* pUserData)
{
if (status == WGPURequestAdapterStatus_Success)
*(WGPUAdapter*)(pUserData) = adapter;
else
printf("Could not get WebGPU adapter: %s\n", message);
};
WGPUAdapter adapter;
wgpuInstanceRequestAdapter(instance, nullptr, onAdapterRequestEnded, (void*)&adapter);
return adapter;
}
static WGPUDevice RequestDevice(WGPUAdapter& adapter)
{
auto onDeviceRequestEnded = [](WGPURequestDeviceStatus status, WGPUDevice device, const char* message, void* pUserData)
{
if (status == WGPURequestDeviceStatus_Success)
*(WGPUDevice*)(pUserData) = device;
else
printf("Could not get WebGPU device: %s\n", message);
};
WGPUDevice device;
wgpuAdapterRequestDevice(adapter, nullptr, onDeviceRequestEnded, (void*)&device);
return device;
}
#endif
static bool InitWGPU(GLFWwindow* window)
{
wgpu::Instance instance = wgpuCreateInstance(nullptr);
#ifdef __EMSCRIPTEN__
wgpu_device = emscripten_webgpu_get_device();
if (!wgpu_device)
return false;
#else
WGPUAdapter adapter = RequestAdapter(instance.Get());
if (!adapter)
return false;
wgpu_device = RequestDevice(adapter);
#endif
#ifdef __EMSCRIPTEN__
wgpu::SurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {};
html_surface_desc.selector = "#canvas";
wgpu::SurfaceDescriptor surface_desc = {};
surface_desc.nextInChain = &html_surface_desc;
wgpu::Surface surface = instance.CreateSurface(&surface_desc);
wgpu::Adapter adapter = {};
wgpu_preferred_fmt = (WGPUTextureFormat)surface.GetPreferredFormat(adapter);
#else
wgpu::Surface surface = wgpu::glfw::CreateSurfaceForWindow(instance, window);
if (!surface)
return false;
wgpu_preferred_fmt = WGPUTextureFormat_BGRA8Unorm;
#endif
wgpu_instance = instance.MoveToCHandle();
wgpu_surface = surface.MoveToCHandle();
wgpuDeviceSetUncapturedErrorCallback(wgpu_device, wgpu_error_callback, nullptr);
return true;
}
static void CreateSwapChain(int width, int height)
{
if (wgpu_swap_chain)
wgpuSwapChainRelease(wgpu_swap_chain);
wgpu_swap_chain_width = width;
wgpu_swap_chain_height = height;
WGPUSwapChainDescriptor swap_chain_desc = {};
swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment;
swap_chain_desc.format = wgpu_preferred_fmt;
swap_chain_desc.width = width;
swap_chain_desc.height = height;
swap_chain_desc.presentMode = WGPUPresentMode_Fifo;
wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc);
}

View File

@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"/> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"/>
<title>Dear ImGui Emscripten+WebGPU example</title> <title>Dear ImGui Emscripten+GLFW+WebGPU example</title>
<style> <style>
body { margin: 0; background-color: black } body { margin: 0; background-color: black }
.emscripten { .emscripten {
@ -63,6 +63,10 @@
// Initialize the graphics adapter // Initialize the graphics adapter
{ {
if (!navigator.gpu) {
throw Error("WebGPU not supported.");
}
const adapter = await navigator.gpu.requestAdapter(); const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice(); const device = await adapter.requestDevice();
Module.preinitializedWebGPUDevice = device; Module.preinitializedWebGPUDevice = device;

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for GLUT/FreeGLUT + OpenGL2, using legacy fixed pipeline // Dear ImGui: standalone example application for GLUT/FreeGLUT + OpenGL2, using legacy fixed pipeline
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!! // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!!
// !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!! // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!!

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for SDL2 + DirectX 11 // Dear ImGui: standalone example application for SDL2 + DirectX 11
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_sdl2.h" #include "imgui_impl_sdl2.h"
@ -43,6 +47,12 @@ int main(int, char**)
// Setup window // Setup window
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+DirectX11 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
if (window == nullptr)
{
printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
return -1;
}
SDL_SysWMinfo wmInfo; SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version); SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(window, &wmInfo); SDL_GetWindowWMInfo(window, &wmInfo);

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for SDL2 + Metal // Dear ImGui: standalone example application for SDL2 + Metal
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_sdl2.h" #include "imgui_impl_sdl2.h"

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for SDL2 + OpenGL // Dear ImGui: standalone example application for SDL2 + OpenGL
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
// **Prefer using the code in the example_sdl2_opengl3/ folder** // **Prefer using the code in the example_sdl2_opengl3/ folder**
@ -37,6 +41,12 @@ int main(int, char**)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
if (window == nullptr)
{
printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
return -1;
}
SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GLContext gl_context = SDL_GL_CreateContext(window);
SDL_GL_MakeCurrent(window, gl_context); SDL_GL_MakeCurrent(window, gl_context);
SDL_GL_SetSwapInterval(1); // Enable vsync SDL_GL_SetSwapInterval(1); // Enable vsync

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for SDL2 + OpenGL // Dear ImGui: standalone example application for SDL2 + OpenGL
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_sdl2.h" #include "imgui_impl_sdl2.h"
@ -64,6 +68,12 @@ int main(int, char**)
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL3 example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
if (window == nullptr)
{
printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
return -1;
}
SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GLContext gl_context = SDL_GL_CreateContext(window);
SDL_GL_MakeCurrent(window, gl_context); SDL_GL_MakeCurrent(window, gl_context);
SDL_GL_SetSwapInterval(1); // Enable vsync SDL_GL_SetSwapInterval(1); // Enable vsync

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for SDL2 + SDL_Renderer // Dear ImGui: standalone example application for SDL2 + SDL_Renderer
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// Important to understand: SDL_Renderer is an _optional_ component of SDL2. // Important to understand: SDL_Renderer is an _optional_ component of SDL2.
// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
@ -34,6 +38,11 @@ int main(int, char**)
// Create window with SDL_Renderer graphics context // Create window with SDL_Renderer graphics context
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+SDL_Renderer example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+SDL_Renderer example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
if (window == nullptr)
{
printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
return -1;
}
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);
if (renderer == nullptr) if (renderer == nullptr)
{ {
@ -146,7 +155,7 @@ int main(int, char**)
SDL_RenderSetScale(renderer, io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); SDL_RenderSetScale(renderer, io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
SDL_SetRenderDrawColor(renderer, (Uint8)(clear_color.x * 255), (Uint8)(clear_color.y * 255), (Uint8)(clear_color.z * 255), (Uint8)(clear_color.w * 255)); SDL_SetRenderDrawColor(renderer, (Uint8)(clear_color.x * 255), (Uint8)(clear_color.y * 255), (Uint8)(clear_color.z * 255), (Uint8)(clear_color.w * 255));
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
ImGui_ImplSDLRenderer2_RenderDrawData(ImGui::GetDrawData()); ImGui_ImplSDLRenderer2_RenderDrawData(ImGui::GetDrawData(), renderer);
SDL_RenderPresent(renderer); SDL_RenderPresent(renderer);
} }

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for SDL2 + Vulkan // Dear ImGui: standalone example application for SDL2 + Vulkan
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app. // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
// - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h. // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
@ -16,12 +20,16 @@
#include <stdlib.h> // abort #include <stdlib.h> // abort
#include <SDL.h> #include <SDL.h>
#include <SDL_vulkan.h> #include <SDL_vulkan.h>
#include <vulkan/vulkan.h>
//#include <vulkan/vulkan_beta.h>
//#define IMGUI_UNLIMITED_FRAME_RATE // Volk headers
#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
#define VOLK_IMPLEMENTATION
#include <Volk/volk.h>
#endif
//#define APP_USE_UNLIMITED_FRAME_RATE
#ifdef _DEBUG #ifdef _DEBUG
#define IMGUI_VULKAN_DEBUG_REPORT #define APP_USE_VULKAN_DEBUG_REPORT
#endif #endif
// Data // Data
@ -48,14 +56,14 @@ static void check_vk_result(VkResult err)
abort(); abort();
} }
#ifdef IMGUI_VULKAN_DEBUG_REPORT #ifdef APP_USE_VULKAN_DEBUG_REPORT
static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData) static VKAPI_ATTR VkBool32 VKAPI_CALL debug_report(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage, void* pUserData)
{ {
(void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments (void)flags; (void)object; (void)location; (void)messageCode; (void)pUserData; (void)pLayerPrefix; // Unused arguments
fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage); fprintf(stderr, "[vulkan] Debug report from ObjectType: %i\nMessage: %s\n\n", objectType, pMessage);
return VK_FALSE; return VK_FALSE;
} }
#endif // IMGUI_VULKAN_DEBUG_REPORT #endif // APP_USE_VULKAN_DEBUG_REPORT
static bool IsExtensionAvailable(const ImVector<VkExtensionProperties>& properties, const char* extension) static bool IsExtensionAvailable(const ImVector<VkExtensionProperties>& properties, const char* extension)
{ {
@ -97,6 +105,9 @@ static VkPhysicalDevice SetupVulkan_SelectPhysicalDevice()
static void SetupVulkan(ImVector<const char*> instance_extensions) static void SetupVulkan(ImVector<const char*> instance_extensions)
{ {
VkResult err; VkResult err;
#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
volkInitialize();
#endif
// Create Vulkan Instance // Create Vulkan Instance
{ {
@ -123,7 +134,7 @@ static void SetupVulkan(ImVector<const char*> instance_extensions)
#endif #endif
// Enabling validation layers // Enabling validation layers
#ifdef IMGUI_VULKAN_DEBUG_REPORT #ifdef APP_USE_VULKAN_DEBUG_REPORT
const char* layers[] = { "VK_LAYER_KHRONOS_validation" }; const char* layers[] = { "VK_LAYER_KHRONOS_validation" };
create_info.enabledLayerCount = 1; create_info.enabledLayerCount = 1;
create_info.ppEnabledLayerNames = layers; create_info.ppEnabledLayerNames = layers;
@ -135,17 +146,20 @@ static void SetupVulkan(ImVector<const char*> instance_extensions)
create_info.ppEnabledExtensionNames = instance_extensions.Data; create_info.ppEnabledExtensionNames = instance_extensions.Data;
err = vkCreateInstance(&create_info, g_Allocator, &g_Instance); err = vkCreateInstance(&create_info, g_Allocator, &g_Instance);
check_vk_result(err); check_vk_result(err);
#ifdef IMGUI_IMPL_VULKAN_USE_VOLK
volkLoadInstance(g_Instance);
#endif
// Setup the debug report callback // Setup the debug report callback
#ifdef IMGUI_VULKAN_DEBUG_REPORT #ifdef APP_USE_VULKAN_DEBUG_REPORT
auto vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT"); auto f_vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkCreateDebugReportCallbackEXT");
IM_ASSERT(vkCreateDebugReportCallbackEXT != nullptr); IM_ASSERT(f_vkCreateDebugReportCallbackEXT != nullptr);
VkDebugReportCallbackCreateInfoEXT debug_report_ci = {}; VkDebugReportCallbackCreateInfoEXT debug_report_ci = {};
debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debug_report_ci.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; debug_report_ci.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
debug_report_ci.pfnCallback = debug_report; debug_report_ci.pfnCallback = debug_report;
debug_report_ci.pUserData = nullptr; debug_report_ci.pUserData = nullptr;
err = vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport); err = f_vkCreateDebugReportCallbackEXT(g_Instance, &debug_report_ci, g_Allocator, &g_DebugReport);
check_vk_result(err); check_vk_result(err);
#endif #endif
} }
@ -203,25 +217,17 @@ static void SetupVulkan(ImVector<const char*> instance_extensions)
} }
// Create Descriptor Pool // Create Descriptor Pool
// The example only requires a single combined image sampler descriptor for the font image and only uses one descriptor set (for that)
// If you wish to load e.g. additional textures you may need to alter pools sizes.
{ {
VkDescriptorPoolSize pool_sizes[] = VkDescriptorPoolSize pool_sizes[] =
{ {
{ VK_DESCRIPTOR_TYPE_SAMPLER, 1000 }, { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 },
{ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000 },
{ VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000 },
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000 },
{ VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000 },
{ VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000 }
}; };
VkDescriptorPoolCreateInfo pool_info = {}; VkDescriptorPoolCreateInfo pool_info = {};
pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
pool_info.maxSets = 1000 * IM_ARRAYSIZE(pool_sizes); pool_info.maxSets = 1;
pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes); pool_info.poolSizeCount = (uint32_t)IM_ARRAYSIZE(pool_sizes);
pool_info.pPoolSizes = pool_sizes; pool_info.pPoolSizes = pool_sizes;
err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool); err = vkCreateDescriptorPool(g_Device, &pool_info, g_Allocator, &g_DescriptorPool);
@ -250,7 +256,7 @@ static void SetupVulkanWindow(ImGui_ImplVulkanH_Window* wd, VkSurfaceKHR surface
wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace); wd->SurfaceFormat = ImGui_ImplVulkanH_SelectSurfaceFormat(g_PhysicalDevice, wd->Surface, requestSurfaceImageFormat, (size_t)IM_ARRAYSIZE(requestSurfaceImageFormat), requestSurfaceColorSpace);
// Select Present Mode // Select Present Mode
#ifdef IMGUI_UNLIMITED_FRAME_RATE #ifdef APP_UNLIMITED_FRAME_RATE
VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR }; VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_KHR };
#else #else
VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR }; VkPresentModeKHR present_modes[] = { VK_PRESENT_MODE_FIFO_KHR };
@ -267,11 +273,11 @@ static void CleanupVulkan()
{ {
vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator); vkDestroyDescriptorPool(g_Device, g_DescriptorPool, g_Allocator);
#ifdef IMGUI_VULKAN_DEBUG_REPORT #ifdef APP_USE_VULKAN_DEBUG_REPORT
// Remove the debug report callback // Remove the debug report callback
auto vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT"); auto f_vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(g_Instance, "vkDestroyDebugReportCallbackEXT");
vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator); f_vkDestroyDebugReportCallbackEXT(g_Instance, g_DebugReport, g_Allocator);
#endif // IMGUI_VULKAN_DEBUG_REPORT #endif // APP_USE_VULKAN_DEBUG_REPORT
vkDestroyDevice(g_Device, g_Allocator); vkDestroyDevice(g_Device, g_Allocator);
vkDestroyInstance(g_Instance, g_Allocator); vkDestroyInstance(g_Instance, g_Allocator);
@ -368,7 +374,7 @@ static void FramePresent(ImGui_ImplVulkanH_Window* wd)
return; return;
} }
check_vk_result(err); check_vk_result(err);
wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->ImageCount; // Now we can use the next set of semaphores wd->SemaphoreIndex = (wd->SemaphoreIndex + 1) % wd->SemaphoreCount; // Now we can use the next set of semaphores
} }
// Main code // Main code
@ -389,6 +395,11 @@ int main(int, char**)
// Create window with Vulkan graphics context // Create window with Vulkan graphics context
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+Vulkan example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
if (window == nullptr)
{
printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
return -1;
}
ImVector<const char*> extensions; ImVector<const char*> extensions;
uint32_t extensions_count = 0; uint32_t extensions_count = 0;
@ -433,13 +444,14 @@ int main(int, char**)
init_info.Queue = g_Queue; init_info.Queue = g_Queue;
init_info.PipelineCache = g_PipelineCache; init_info.PipelineCache = g_PipelineCache;
init_info.DescriptorPool = g_DescriptorPool; init_info.DescriptorPool = g_DescriptorPool;
init_info.RenderPass = wd->RenderPass;
init_info.Subpass = 0; init_info.Subpass = 0;
init_info.MinImageCount = g_MinImageCount; init_info.MinImageCount = g_MinImageCount;
init_info.ImageCount = wd->ImageCount; init_info.ImageCount = wd->ImageCount;
init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT;
init_info.Allocator = g_Allocator; init_info.Allocator = g_Allocator;
init_info.CheckVkResultFn = check_vk_result; init_info.CheckVkResultFn = check_vk_result;
ImGui_ImplVulkan_Init(&init_info, wd->RenderPass); ImGui_ImplVulkan_Init(&init_info);
// Load Fonts // Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
@ -457,36 +469,6 @@ int main(int, char**)
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != nullptr); //IM_ASSERT(font != nullptr);
// Upload Fonts
{
// Use any command queue
VkCommandPool command_pool = wd->Frames[wd->FrameIndex].CommandPool;
VkCommandBuffer command_buffer = wd->Frames[wd->FrameIndex].CommandBuffer;
err = vkResetCommandPool(g_Device, command_pool, 0);
check_vk_result(err);
VkCommandBufferBeginInfo begin_info = {};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags |= VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
err = vkBeginCommandBuffer(command_buffer, &begin_info);
check_vk_result(err);
ImGui_ImplVulkan_CreateFontsTexture(command_buffer);
VkSubmitInfo end_info = {};
end_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
end_info.commandBufferCount = 1;
end_info.pCommandBuffers = &command_buffer;
err = vkEndCommandBuffer(command_buffer);
check_vk_result(err);
err = vkQueueSubmit(g_Queue, 1, &end_info, VK_NULL_HANDLE);
check_vk_result(err);
err = vkDeviceWaitIdle(g_Device);
check_vk_result(err);
ImGui_ImplVulkan_DestroyFontUploadObjects();
}
// Our state // Our state
bool show_demo_window = true; bool show_demo_window = true;
bool show_another_window = false; bool show_another_window = false;

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for SDL3 + OpenGL // Dear ImGui: standalone example application for SDL3 + OpenGL
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_sdl3.h" #include "imgui_impl_sdl3.h"
@ -60,7 +64,7 @@ int main(int, char**)
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN); Uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN;
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", 1280, 720, window_flags); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+OpenGL3 example", 1280, 720, window_flags);
if (window == nullptr) if (window == nullptr)
{ {

View File

@ -1,7 +1,11 @@
// Dear ImGui: standalone example application for SDL3 + SDL_Renderer // Dear ImGui: standalone example application for SDL3 + SDL_Renderer
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.) // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// Important to understand: SDL_Renderer is an _optional_ component of SDL3. // Important to understand: SDL_Renderer is an _optional_ component of SDL3.
// For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX. // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
@ -31,19 +35,20 @@ int main(int, char**)
SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1"); SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
// Create window with SDL_Renderer graphics context // Create window with SDL_Renderer graphics context
SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN); Uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN;
SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", 1280, 720, window_flags); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+SDL_Renderer example", 1280, 720, window_flags);
if (window == nullptr) if (window == nullptr)
{ {
printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError()); printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
return -1; return -1;
} }
SDL_Renderer* renderer = SDL_CreateRenderer(window, NULL, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); SDL_Renderer* renderer = SDL_CreateRenderer(window, nullptr);
SDL_SetRenderVSync(renderer, 1);
if (renderer == nullptr) if (renderer == nullptr)
{ {
SDL_Log("Error: SDL_CreateRenderer(): %s\n", SDL_GetError()); SDL_Log("Error: SDL_CreateRenderer(): %s\n", SDL_GetError());
return -1; return -1;
} }
SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
SDL_ShowWindow(window); SDL_ShowWindow(window);
@ -157,7 +162,7 @@ int main(int, char**)
//SDL_RenderSetScale(renderer, io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y); //SDL_RenderSetScale(renderer, io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
SDL_SetRenderDrawColor(renderer, (Uint8)(clear_color.x * 255), (Uint8)(clear_color.y * 255), (Uint8)(clear_color.z * 255), (Uint8)(clear_color.w * 255)); SDL_SetRenderDrawColor(renderer, (Uint8)(clear_color.x * 255), (Uint8)(clear_color.y * 255), (Uint8)(clear_color.z * 255), (Uint8)(clear_color.w * 255));
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData()); ImGui_ImplSDLRenderer3_RenderDrawData(ImGui::GetDrawData(), renderer);
SDL_RenderPresent(renderer); SDL_RenderPresent(renderer);
} }

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for DirectX 10 // Dear ImGui: standalone example application for DirectX 10
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_win32.h" #include "imgui_impl_win32.h"
@ -12,6 +16,7 @@
// Data // Data
static ID3D10Device* g_pd3dDevice = nullptr; static ID3D10Device* g_pd3dDevice = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr; static IDXGISwapChain* g_pSwapChain = nullptr;
static bool g_SwapChainOccluded = false;
static UINT g_ResizeWidth = 0, g_ResizeHeight = 0; static UINT g_ResizeWidth = 0, g_ResizeHeight = 0;
static ID3D10RenderTargetView* g_mainRenderTargetView = nullptr; static ID3D10RenderTargetView* g_mainRenderTargetView = nullptr;
@ -96,6 +101,14 @@ int main(int, char**)
if (done) if (done)
break; break;
// Handle window being minimized or screen locked
if (g_SwapChainOccluded && g_pSwapChain->Present(0, DXGI_PRESENT_TEST) == DXGI_STATUS_OCCLUDED)
{
::Sleep(10);
continue;
}
g_SwapChainOccluded = false;
// Handle window resize (we don't resize directly in the WM_SIZE handler) // Handle window resize (we don't resize directly in the WM_SIZE handler)
if (g_ResizeWidth != 0 && g_ResizeHeight != 0) if (g_ResizeWidth != 0 && g_ResizeHeight != 0)
{ {
@ -154,10 +167,13 @@ int main(int, char**)
g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha); g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha);
ImGui_ImplDX10_RenderDrawData(ImGui::GetDrawData()); ImGui_ImplDX10_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0); // Present with vsync // Present
//g_pSwapChain->Present(0, 0); // Present without vsync HRESULT hr = g_pSwapChain->Present(1, 0); // Present with vsync
//HRESULT hr = g_pSwapChain->Present(0, 0); // Present without vsync
g_SwapChainOccluded = (hr == DXGI_STATUS_OCCLUDED);
} }
// Cleanup
ImGui_ImplDX10_Shutdown(); ImGui_ImplDX10_Shutdown();
ImGui_ImplWin32_Shutdown(); ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext(); ImGui::DestroyContext();

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for DirectX 11 // Dear ImGui: standalone example application for DirectX 11
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_win32.h" #include "imgui_impl_win32.h"
@ -12,6 +16,7 @@
static ID3D11Device* g_pd3dDevice = nullptr; static ID3D11Device* g_pd3dDevice = nullptr;
static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr; static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr; static IDXGISwapChain* g_pSwapChain = nullptr;
static bool g_SwapChainOccluded = false;
static UINT g_ResizeWidth = 0, g_ResizeHeight = 0; static UINT g_ResizeWidth = 0, g_ResizeHeight = 0;
static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr; static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr;
@ -96,6 +101,14 @@ int main(int, char**)
if (done) if (done)
break; break;
// Handle window being minimized or screen locked
if (g_SwapChainOccluded && g_pSwapChain->Present(0, DXGI_PRESENT_TEST) == DXGI_STATUS_OCCLUDED)
{
::Sleep(10);
continue;
}
g_SwapChainOccluded = false;
// Handle window resize (we don't resize directly in the WM_SIZE handler) // Handle window resize (we don't resize directly in the WM_SIZE handler)
if (g_ResizeWidth != 0 && g_ResizeHeight != 0) if (g_ResizeWidth != 0 && g_ResizeHeight != 0)
{ {
@ -154,8 +167,10 @@ int main(int, char**)
g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha); g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, clear_color_with_alpha);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0); // Present with vsync // Present
//g_pSwapChain->Present(0, 0); // Present without vsync HRESULT hr = g_pSwapChain->Present(1, 0); // Present with vsync
//HRESULT hr = g_pSwapChain->Present(0, 0); // Present without vsync
g_SwapChainOccluded = (hr == DXGI_STATUS_OCCLUDED);
} }
// Cleanup // Cleanup

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for DirectX 12 // Dear ImGui: standalone example application for DirectX 12
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// Important: to compile on 32-bit systems, the DirectX12 backend requires code to be compiled with '#define ImTextureID ImU64'. // Important: to compile on 32-bit systems, the DirectX12 backend requires code to be compiled with '#define ImTextureID ImU64'.
// This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*. // This is because we need ImTextureID to carry a 64-bit value and by default ImTextureID is defined as void*.
@ -22,6 +26,8 @@
#pragma comment(lib, "dxguid.lib") #pragma comment(lib, "dxguid.lib")
#endif #endif
#include "imgui_internal.h"
struct FrameContext struct FrameContext
{ {
ID3D12CommandAllocator* CommandAllocator; ID3D12CommandAllocator* CommandAllocator;
@ -43,6 +49,7 @@ static ID3D12Fence* g_fence = nullptr;
static HANDLE g_fenceEvent = nullptr; static HANDLE g_fenceEvent = nullptr;
static UINT64 g_fenceLastSignaledValue = 0; static UINT64 g_fenceLastSignaledValue = 0;
static IDXGISwapChain3* g_pSwapChain = nullptr; static IDXGISwapChain3* g_pSwapChain = nullptr;
static bool g_SwapChainOccluded = false;
static HANDLE g_hSwapChainWaitableObject = nullptr; static HANDLE g_hSwapChainWaitableObject = nullptr;
static ID3D12Resource* g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {}; static ID3D12Resource* g_mainRenderTargetResource[NUM_BACK_BUFFERS] = {};
static D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {}; static D3D12_CPU_DESCRIPTOR_HANDLE g_mainRenderTargetDescriptor[NUM_BACK_BUFFERS] = {};
@ -133,6 +140,14 @@ int main(int, char**)
if (done) if (done)
break; break;
// Handle window screen locked
if (g_SwapChainOccluded && g_pSwapChain->Present(0, DXGI_PRESENT_TEST) == DXGI_STATUS_OCCLUDED)
{
::Sleep(10);
continue;
}
g_SwapChainOccluded = false;
// Start the Dear ImGui frame // Start the Dear ImGui frame
ImGui_ImplDX12_NewFrame(); ImGui_ImplDX12_NewFrame();
ImGui_ImplWin32_NewFrame(); ImGui_ImplWin32_NewFrame();
@ -205,8 +220,10 @@ int main(int, char**)
g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&g_pd3dCommandList); g_pd3dCommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&g_pd3dCommandList);
g_pSwapChain->Present(1, 0); // Present with vsync // Present
//g_pSwapChain->Present(0, 0); // Present without vsync HRESULT hr = g_pSwapChain->Present(1, 0); // Present with vsync
//HRESULT hr = g_pSwapChain->Present(0, 0); // Present without vsync
g_SwapChainOccluded = (hr == DXGI_STATUS_OCCLUDED);
UINT64 fenceValue = g_fenceLastSignaledValue + 1; UINT64 fenceValue = g_fenceLastSignaledValue + 1;
g_pd3dCommandQueue->Signal(g_fence, fenceValue); g_pd3dCommandQueue->Signal(g_fence, fenceValue);

View File

@ -1,6 +1,10 @@
// Dear ImGui: standalone example application for DirectX 9 // Dear ImGui: standalone example application for DirectX 9
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_dx9.h" #include "imgui_impl_dx9.h"
@ -11,6 +15,7 @@
// Data // Data
static LPDIRECT3D9 g_pD3D = nullptr; static LPDIRECT3D9 g_pD3D = nullptr;
static LPDIRECT3DDEVICE9 g_pd3dDevice = nullptr; static LPDIRECT3DDEVICE9 g_pd3dDevice = nullptr;
static bool g_DeviceLost = false;
static UINT g_ResizeWidth = 0, g_ResizeHeight = 0; static UINT g_ResizeWidth = 0, g_ResizeHeight = 0;
static D3DPRESENT_PARAMETERS g_d3dpp = {}; static D3DPRESENT_PARAMETERS g_d3dpp = {};
@ -94,6 +99,20 @@ int main(int, char**)
if (done) if (done)
break; break;
// Handle lost D3D9 device
if (g_DeviceLost)
{
HRESULT hr = g_pd3dDevice->TestCooperativeLevel();
if (hr == D3DERR_DEVICELOST)
{
::Sleep(10);
continue;
}
if (hr == D3DERR_DEVICENOTRESET)
ResetDevice();
g_DeviceLost = false;
}
// Handle window resize (we don't resize directly in the WM_SIZE handler) // Handle window resize (we don't resize directly in the WM_SIZE handler)
if (g_ResizeWidth != 0 && g_ResizeHeight != 0) if (g_ResizeWidth != 0 && g_ResizeHeight != 0)
{ {
@ -159,12 +178,11 @@ int main(int, char**)
g_pd3dDevice->EndScene(); g_pd3dDevice->EndScene();
} }
HRESULT result = g_pd3dDevice->Present(nullptr, nullptr, nullptr, nullptr); HRESULT result = g_pd3dDevice->Present(nullptr, nullptr, nullptr, nullptr);
if (result == D3DERR_DEVICELOST)
// Handle loss of D3D9 device g_DeviceLost = true;
if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
ResetDevice();
} }
// Cleanup
ImGui_ImplDX9_Shutdown(); ImGui_ImplDX9_Shutdown();
ImGui_ImplWin32_Shutdown(); ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext(); ImGui::DestroyContext();

View File

@ -1,8 +1,12 @@
// Dear ImGui: standalone example application for Win32 + OpenGL 3 // Dear ImGui: standalone example application for Win32 + OpenGL 3
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// This is provided for completeness, however it is strogly recommended you use OpenGL with SDL or GLFW. // Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// This is provided for completeness, however it is strongly recommended you use OpenGL with SDL or GLFW.
#include "imgui.h" #include "imgui.h"
#include "imgui_impl_opengl3.h" #include "imgui_impl_opengl3.h"
@ -34,9 +38,9 @@ int main(int, char**)
{ {
// Create application window // Create application window
//ImGui_ImplWin32_EnableDpiAwareness(); //ImGui_ImplWin32_EnableDpiAwareness();
WNDCLASSEXW wc = { sizeof(wc), CS_OWNDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, L"ImGui Example", NULL }; WNDCLASSEXW wc = { sizeof(wc), CS_OWNDC, WndProc, 0L, 0L, GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, L"ImGui Example", nullptr };
::RegisterClassExW(&wc); ::RegisterClassExW(&wc);
HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+OpenGL3 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); HWND hwnd = ::CreateWindowW(wc.lpszClassName, L"Dear ImGui Win32+OpenGL3 Example", WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, nullptr, nullptr, wc.hInstance, nullptr);
// Initialize OpenGL // Initialize OpenGL
if (!CreateDeviceWGL(hwnd, &g_MainWindow)) if (!CreateDeviceWGL(hwnd, &g_MainWindow))
@ -70,7 +74,7 @@ int main(int, char**)
// Load Fonts // Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
// - Read 'docs/FONTS.md' for more instructions and details. // - Read 'docs/FONTS.md' for more instructions and details.
@ -80,8 +84,8 @@ int main(int, char**)
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != NULL); //IM_ASSERT(font != nullptr);
// Our state // Our state
bool show_demo_window = true; bool show_demo_window = true;
@ -95,7 +99,7 @@ int main(int, char**)
// Poll and handle messages (inputs, window resize, etc.) // Poll and handle messages (inputs, window resize, etc.)
// See the WndProc() function below for our to dispatch events to the Win32 backend. // See the WndProc() function below for our to dispatch events to the Win32 backend.
MSG msg; MSG msg;
while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) while (::PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE))
{ {
::TranslateMessage(&msg); ::TranslateMessage(&msg);
::DispatchMessage(&msg); ::DispatchMessage(&msg);
@ -196,7 +200,7 @@ bool CreateDeviceWGL(HWND hWnd, WGL_WindowData* data)
void CleanupDeviceWGL(HWND hWnd, WGL_WindowData* data) void CleanupDeviceWGL(HWND hWnd, WGL_WindowData* data)
{ {
wglMakeCurrent(NULL, NULL); wglMakeCurrent(nullptr, nullptr);
::ReleaseDC(hWnd, data->hDC); ::ReleaseDC(hWnd, data->hDC);
} }

View File

@ -200,7 +200,7 @@ typedef void (*uSynergySleepFunc)(uSynergyCookie cookie, int timeMs);
@brief Get time function @brief Get time function
This function is called when uSynergy needs to know the current time. This is used to determine when timeouts This function is called when uSynergy needs to know the current time. This is used to determine when timeouts
have occured. The time base should be a cyclic millisecond time value. have occurred. The time base should be a cyclic millisecond time value.
@returns Time value in milliseconds @returns Time value in milliseconds
**/ **/

View File

@ -1,5 +1,5 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// COMPILE-TIME OPTIONS FOR DEAR IMGUI // DEAR IMGUI COMPILE-TIME OPTIONS
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -9,7 +9,7 @@
// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp // You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. // files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// 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. // Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#pragma once #pragma once
@ -26,21 +26,21 @@
//#define IMGUI_API __declspec( dllexport ) //#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport ) //#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names. //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//#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. //#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87+ disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This is automatically done by IMGUI_DISABLE_OBSOLETE_FUNCTIONS.
//---- Disable all of Dear ImGui or don't implement standard windows/tools. //---- Disable all of Dear ImGui or don't implement standard windows/tools.
// 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. // 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.
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. //#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. //#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
//#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). //#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty.
//---- Don't implement some functions to reduce linkage requirements. //---- Don't implement some functions to reduce linkage requirements.
//#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) //#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)
//#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) //#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)
//#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) //#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)
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME).
//#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). //#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).
//#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) //#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)
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
@ -50,21 +50,24 @@
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
//---- Include imgui_user.h at the end of imgui.h as a convenience //---- Include imgui_user.h at the end of imgui.h as a convenience
// May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included.
//#define IMGUI_INCLUDE_IMGUI_USER_H //#define IMGUI_INCLUDE_IMGUI_USER_H
//#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h"
//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
//#define IMGUI_USE_BGRA_PACKED_COLOR //#define IMGUI_USE_BGRA_PACKED_COLOR
//---- 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...) //---- 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...)
//#define IMGUI_USE_WCHAR32 //#define IMGUI_USE_WCHAR32
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if enabled //#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined.
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined.
//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) //---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
// 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. // 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.
@ -75,6 +78,12 @@
// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. // On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
//#define IMGUI_ENABLE_FREETYPE //#define IMGUI_ENABLE_FREETYPE
//---- Use FreeType+lunasvg library to render OpenType SVG fonts (SVGinOT)
// Requires lunasvg headers to be available in the include path + program to be linked with the lunasvg library (not provided).
// Only works in combination with IMGUI_ENABLE_FREETYPE.
// (implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
//#define IMGUI_ENABLE_FREETYPE_LUNASVG
//---- Use stb_truetype to build and rasterize the font atlas (default) //---- Use stb_truetype to build and rasterize the font atlas (default)
// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
//#define IMGUI_ENABLE_STB_TRUETYPE //#define IMGUI_ENABLE_STB_TRUETYPE
@ -105,7 +114,7 @@
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
//#define ImDrawCallback MyImDrawCallback //#define ImDrawCallback MyImDrawCallback
//---- Debug Tools: Macro to break in Debugger //---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase)
// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) // (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
//#define IM_DEBUG_BREAK IM_ASSERT(0) //#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak() //#define IM_DEBUG_BREAK __debugbreak()
@ -113,10 +122,10 @@
//---- Debug Tools: Enable slower asserts //---- Debug Tools: Enable slower asserts
//#define IMGUI_DEBUG_PARANOID //#define IMGUI_DEBUG_PARANOID
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. //---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files)
/* /*
namespace ImGui namespace ImGui
{ {
void MyFunction(const char* name, const MyMatrix44& v); void MyFunction(const char* name, MyMatrix44* mtx);
} }
*/ */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
// dear imgui, v1.89.7 // dear imgui, v1.90.7
// (drawing and font code) // (drawing and font code)
/* /*
@ -8,6 +8,7 @@ Index of this file:
// [SECTION] STB libraries implementation // [SECTION] STB libraries implementation
// [SECTION] Style functions // [SECTION] Style functions
// [SECTION] ImDrawList // [SECTION] ImDrawList
// [SECTION] ImTriangulator, ImDrawList concave polygon fill
// [SECTION] ImDrawListSplitter // [SECTION] ImDrawListSplitter
// [SECTION] ImDrawData // [SECTION] ImDrawData
// [SECTION] Helpers ShadeVertsXXX functions // [SECTION] Helpers ShadeVertsXXX functions
@ -63,6 +64,8 @@ Index of this file:
#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#pragma clang diagnostic ignored "-Wreserved-identifier" // warning: identifier '_Xxx' is reserved because it starts with '_' followed by a capital letter
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
#elif defined(__GNUC__) #elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
@ -134,7 +137,7 @@ namespace IMGUI_STB_NAMESPACE
#define STBTT_sqrt(x) ImSqrt(x) #define STBTT_sqrt(x) ImSqrt(x)
#define STBTT_pow(x,y) ImPow(x,y) #define STBTT_pow(x,y) ImPow(x,y)
#define STBTT_fabs(x) ImFabs(x) #define STBTT_fabs(x) ImFabs(x)
#define STBTT_ifloor(x) ((int)ImFloorSigned(x)) #define STBTT_ifloor(x) ((int)ImFloor(x))
#define STBTT_iceil(x) ((int)ImCeil(x)) #define STBTT_iceil(x) ((int)ImCeil(x))
#define STBTT_STATIC #define STBTT_STATIC
#define STB_TRUETYPE_IMPLEMENTATION #define STB_TRUETYPE_IMPLEMENTATION
@ -382,12 +385,13 @@ void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error)
} }
// Initialize before use in a new frame. We always have a command ready in the buffer. // Initialize before use in a new frame. We always have a command ready in the buffer.
// In the majority of cases, you would want to call PushClipRect() and PushTextureID() after this.
void ImDrawList::_ResetForNewFrame() void ImDrawList::_ResetForNewFrame()
{ {
// Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory. // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory.
IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, ClipRect) == 0); IM_STATIC_ASSERT(offsetof(ImDrawCmd, ClipRect) == 0);
IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, TextureId) == sizeof(ImVec4)); IM_STATIC_ASSERT(offsetof(ImDrawCmd, TextureId) == sizeof(ImVec4));
IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID)); IM_STATIC_ASSERT(offsetof(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID));
if (_Splitter._Count > 1) if (_Splitter._Count > 1)
_Splitter.Merge(this); _Splitter.Merge(this);
@ -474,7 +478,7 @@ void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data)
} }
// Compare ClipRect, TextureId and VtxOffset with a single memcmp() // Compare ClipRect, TextureId and VtxOffset with a single memcmp()
#define ImDrawCmd_HeaderSize (IM_OFFSETOF(ImDrawCmd, VtxOffset) + sizeof(unsigned int)) #define ImDrawCmd_HeaderSize (offsetof(ImDrawCmd, VtxOffset) + sizeof(unsigned int))
#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TextureId, VtxOffset #define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TextureId, VtxOffset
#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TextureId, VtxOffset #define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TextureId, VtxOffset
#define ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) (CMD_0->IdxOffset + CMD_0->ElemCount == CMD_1->IdxOffset) #define ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) (CMD_0->IdxOffset + CMD_0->ElemCount == CMD_1->IdxOffset)
@ -560,7 +564,7 @@ int ImDrawList::_CalcCircleAutoSegmentCount(float radius) const
{ {
// Automatic segment count // Automatic segment count
const int radius_idx = (int)(radius + 0.999999f); // ceil to never reduce accuracy const int radius_idx = (int)(radius + 0.999999f); // ceil to never reduce accuracy
if (radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts)) if (radius_idx >= 0 && radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts))
return _Data->CircleSegmentCounts[radius_idx]; // Use cached value return _Data->CircleSegmentCounts[radius_idx]; // Use cached value
else else
return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError); return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError);
@ -640,7 +644,7 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count)
_IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size; _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size;
} }
// Release the a number of reserved vertices/indices from the end of the last reservation made with PrimReserve(). // Release the number of reserved vertices/indices from the end of the last reservation made with PrimReserve().
void ImDrawList::PrimUnreserve(int idx_count, int vtx_count) void ImDrawList::PrimUnreserve(int idx_count, int vtx_count)
{ {
IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0);
@ -1190,8 +1194,8 @@ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, floa
const float a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0f); const float a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0f);
const float a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0f); const float a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0f);
const int a_min_sample = a_is_reverse ? (int)ImFloorSigned(a_min_sample_f) : (int)ImCeil(a_min_sample_f); const int a_min_sample = a_is_reverse ? (int)ImFloor(a_min_sample_f) : (int)ImCeil(a_min_sample_f);
const int a_max_sample = a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloorSigned(a_max_sample_f); const int a_max_sample = a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloor(a_max_sample_f);
const int a_mid_samples = a_is_reverse ? ImMax(a_min_sample - a_max_sample, 0) : ImMax(a_max_sample - a_min_sample, 0); const int a_mid_samples = a_is_reverse ? ImMax(a_min_sample - a_max_sample, 0) : ImMax(a_max_sample - a_min_sample, 0);
const float a_min_segment_angle = a_min_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX; const float a_min_segment_angle = a_min_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
@ -1216,6 +1220,26 @@ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, floa
} }
} }
void ImDrawList::PathEllipticalArcTo(const ImVec2& center, const ImVec2& radius, float rot, float a_min, float a_max, int num_segments)
{
if (num_segments <= 0)
num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here.
_Path.reserve(_Path.Size + (num_segments + 1));
const float cos_rot = ImCos(rot);
const float sin_rot = ImSin(rot);
for (int i = 0; i <= num_segments; i++)
{
const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min);
ImVec2 point(ImCos(a) * radius.x, ImSin(a) * radius.y);
const ImVec2 rel((point.x * cos_rot) - (point.y * sin_rot), (point.x * sin_rot) + (point.y * cos_rot));
point.x = rel.x + center.x;
point.y = rel.y + center.y;
_Path.push_back(point);
}
}
ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t) ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t)
{ {
float u = 1.0f - t; float u = 1.0f - t;
@ -1311,33 +1335,22 @@ void ImDrawList::PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3,
} }
} }
IM_STATIC_ASSERT(ImDrawFlags_RoundCornersTopLeft == (1 << 4));
static inline ImDrawFlags FixRectCornerFlags(ImDrawFlags flags) static inline ImDrawFlags FixRectCornerFlags(ImDrawFlags flags)
{ {
/*
IM_STATIC_ASSERT(ImDrawFlags_RoundCornersTopLeft == (1 << 4));
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// Obsoleted in 1.82 (from February 2021) // Obsoleted in 1.82 (from February 2021). This code was stripped/simplified and mostly commented in 1.90 (from September 2023)
// Legacy Support for hard coded ~0 (used to be a suggested equivalent to ImDrawCornerFlags_All) // - Legacy Support for hard coded ~0 (used to be a suggested equivalent to ImDrawCornerFlags_All)
// ~0 --> ImDrawFlags_RoundCornersAll or 0 if (flags == ~0) { return ImDrawFlags_RoundCornersAll; }
if (flags == ~0) // - Legacy Support for hard coded 0x01 to 0x0F (matching 15 out of 16 old flags combinations). Read details in older version of this code.
return ImDrawFlags_RoundCornersAll; if (flags >= 0x01 && flags <= 0x0F) { return (flags << 4); }
// Legacy Support for hard coded 0x01 to 0x0F (matching 15 out of 16 old flags combinations)
// 0x01 --> ImDrawFlags_RoundCornersTopLeft (VALUE 0x01 OVERLAPS ImDrawFlags_Closed but ImDrawFlags_Closed is never valid in this path!)
// 0x02 --> ImDrawFlags_RoundCornersTopRight
// 0x03 --> ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight
// 0x04 --> ImDrawFlags_RoundCornersBotLeft
// 0x05 --> ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBotLeft
// ...
// 0x0F --> ImDrawFlags_RoundCornersAll or 0
// (See all values in ImDrawCornerFlags_)
if (flags >= 0x01 && flags <= 0x0F)
return (flags << 4);
// We cannot support hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundCornersNone or use 'float rounding = 0.0f' // We cannot support hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundCornersNone or use 'float rounding = 0.0f'
#endif #endif
*/
// If this triggers, please update your code replacing hardcoded values with new ImDrawFlags_RoundCorners* values. // If this assert triggers, please update your code replacing hardcoded values with new ImDrawFlags_RoundCorners* values.
// Note that ImDrawFlags_Closed (== 0x01) is an invalid flag for AddRect(), AddRectFilled(), PathRect() etc... // Note that ImDrawFlags_Closed (== 0x01) is an invalid flag for AddRect(), AddRectFilled(), PathRect() etc. anyway.
// See details in 1.82 Changelog as well as 2021/03/12 and 2023/09/08 entries in "API BREAKING CHANGES" section.
IM_ASSERT((flags & 0x0F) == 0 && "Misuse of legacy hardcoded ImDrawCornerFlags values!"); IM_ASSERT((flags & 0x0F) == 0 && "Misuse of legacy hardcoded ImDrawCornerFlags values!");
if ((flags & ImDrawFlags_RoundCornersMask_) == 0) if ((flags & ImDrawFlags_RoundCornersMask_) == 0)
@ -1348,10 +1361,12 @@ static inline ImDrawFlags FixRectCornerFlags(ImDrawFlags flags)
void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDrawFlags flags) void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDrawFlags flags)
{ {
flags = FixRectCornerFlags(flags); if (rounding >= 0.5f)
rounding = ImMin(rounding, ImFabs(b.x - a.x) * ( ((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f ) - 1.0f); {
rounding = ImMin(rounding, ImFabs(b.y - a.y) * ( ((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f ) - 1.0f); flags = FixRectCornerFlags(flags);
rounding = ImMin(rounding, ImFabs(b.x - a.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f);
rounding = ImMin(rounding, ImFabs(b.y - a.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f);
}
if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone)
{ {
PathLineTo(a); PathLineTo(a);
@ -1544,6 +1559,35 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in
PathFillConvex(col); PathFillConvex(col);
} }
// Ellipse
void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments, float thickness)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
if (num_segments <= 0)
num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here.
// Because we are filling a closed shape we remove 1 from the count of segments/points
const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments;
PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1);
PathStroke(col, true, thickness);
}
void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
if (num_segments <= 0)
num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here.
// Because we are filling a closed shape we remove 1 from the count of segments/points
const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments;
PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1);
PathFillConvex(col);
}
// Cubic Bezier takes 4 controls points // Cubic Bezier takes 4 controls points
void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments) void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments)
{ {
@ -1571,10 +1615,11 @@ void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos,
if ((col & IM_COL32_A_MASK) == 0) if ((col & IM_COL32_A_MASK) == 0)
return; return;
// Accept null ranges
if (text_begin == text_end || text_begin[0] == 0)
return;
if (text_end == NULL) if (text_end == NULL)
text_end = text_begin + strlen(text_begin); text_end = text_begin + strlen(text_begin);
if (text_begin == text_end)
return;
// Pull default font/size from the shared ImDrawListSharedData instance // Pull default font/size from the shared ImDrawListSharedData instance
if (font == NULL) if (font == NULL)
@ -1658,6 +1703,316 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi
PopTextureID(); PopTextureID();
} }
//-----------------------------------------------------------------------------
// [SECTION] ImTriangulator, ImDrawList concave polygon fill
//-----------------------------------------------------------------------------
// Triangulate concave polygons. Based on "Triangulation by Ear Clipping" paper, O(N^2) complexity.
// Reference: https://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
// Provided as a convenience for user but not used by main library.
//-----------------------------------------------------------------------------
// - ImTriangulator [Internal]
// - AddConcavePolyFilled()
//-----------------------------------------------------------------------------
enum ImTriangulatorNodeType
{
ImTriangulatorNodeType_Convex,
ImTriangulatorNodeType_Ear,
ImTriangulatorNodeType_Reflex
};
struct ImTriangulatorNode
{
ImTriangulatorNodeType Type;
int Index;
ImVec2 Pos;
ImTriangulatorNode* Next;
ImTriangulatorNode* Prev;
void Unlink() { Next->Prev = Prev; Prev->Next = Next; }
};
struct ImTriangulatorNodeSpan
{
ImTriangulatorNode** Data = NULL;
int Size = 0;
void push_back(ImTriangulatorNode* node) { Data[Size++] = node; }
void find_erase_unsorted(int idx) { for (int i = Size - 1; i >= 0; i--) if (Data[i]->Index == idx) { Data[i] = Data[Size - 1]; Size--; return; } }
};
struct ImTriangulator
{
static int EstimateTriangleCount(int points_count) { return (points_count < 3) ? 0 : points_count - 2; }
static int EstimateScratchBufferSize(int points_count) { return sizeof(ImTriangulatorNode) * points_count + sizeof(ImTriangulatorNode*) * points_count * 2; }
void Init(const ImVec2* points, int points_count, void* scratch_buffer);
void GetNextTriangle(unsigned int out_triangle[3]); // Return relative indexes for next triangle
// Internal functions
void BuildNodes(const ImVec2* points, int points_count);
void BuildReflexes();
void BuildEars();
void FlipNodeList();
bool IsEar(int i0, int i1, int i2, const ImVec2& v0, const ImVec2& v1, const ImVec2& v2) const;
void ReclassifyNode(ImTriangulatorNode* node);
// Internal members
int _TrianglesLeft = 0;
ImTriangulatorNode* _Nodes = NULL;
ImTriangulatorNodeSpan _Ears;
ImTriangulatorNodeSpan _Reflexes;
};
// Distribute storage for nodes, ears and reflexes.
// FIXME-OPT: if everything is convex, we could report it to caller and let it switch to an convex renderer
// (this would require first building reflexes to bail to convex if empty, without even building nodes)
void ImTriangulator::Init(const ImVec2* points, int points_count, void* scratch_buffer)
{
IM_ASSERT(scratch_buffer != NULL && points_count >= 3);
_TrianglesLeft = EstimateTriangleCount(points_count);
_Nodes = (ImTriangulatorNode*)scratch_buffer; // points_count x Node
_Ears.Data = (ImTriangulatorNode**)(_Nodes + points_count); // points_count x Node*
_Reflexes.Data = (ImTriangulatorNode**)(_Nodes + points_count) + points_count; // points_count x Node*
BuildNodes(points, points_count);
BuildReflexes();
BuildEars();
}
void ImTriangulator::BuildNodes(const ImVec2* points, int points_count)
{
for (int i = 0; i < points_count; i++)
{
_Nodes[i].Type = ImTriangulatorNodeType_Convex;
_Nodes[i].Index = i;
_Nodes[i].Pos = points[i];
_Nodes[i].Next = _Nodes + i + 1;
_Nodes[i].Prev = _Nodes + i - 1;
}
_Nodes[0].Prev = _Nodes + points_count - 1;
_Nodes[points_count - 1].Next = _Nodes;
}
void ImTriangulator::BuildReflexes()
{
ImTriangulatorNode* n1 = _Nodes;
for (int i = _TrianglesLeft; i >= 0; i--, n1 = n1->Next)
{
if (ImTriangleIsClockwise(n1->Prev->Pos, n1->Pos, n1->Next->Pos))
continue;
n1->Type = ImTriangulatorNodeType_Reflex;
_Reflexes.push_back(n1);
}
}
void ImTriangulator::BuildEars()
{
ImTriangulatorNode* n1 = _Nodes;
for (int i = _TrianglesLeft; i >= 0; i--, n1 = n1->Next)
{
if (n1->Type != ImTriangulatorNodeType_Convex)
continue;
if (!IsEar(n1->Prev->Index, n1->Index, n1->Next->Index, n1->Prev->Pos, n1->Pos, n1->Next->Pos))
continue;
n1->Type = ImTriangulatorNodeType_Ear;
_Ears.push_back(n1);
}
}
void ImTriangulator::GetNextTriangle(unsigned int out_triangle[3])
{
if (_Ears.Size == 0)
{
FlipNodeList();
ImTriangulatorNode* node = _Nodes;
for (int i = _TrianglesLeft; i >= 0; i--, node = node->Next)
node->Type = ImTriangulatorNodeType_Convex;
_Reflexes.Size = 0;
BuildReflexes();
BuildEars();
// If we still don't have ears, it means geometry is degenerated.
if (_Ears.Size == 0)
{
// Return first triangle available, mimicking the behavior of convex fill.
IM_ASSERT(_TrianglesLeft > 0); // Geometry is degenerated
_Ears.Data[0] = _Nodes;
_Ears.Size = 1;
}
}
ImTriangulatorNode* ear = _Ears.Data[--_Ears.Size];
out_triangle[0] = ear->Prev->Index;
out_triangle[1] = ear->Index;
out_triangle[2] = ear->Next->Index;
ear->Unlink();
if (ear == _Nodes)
_Nodes = ear->Next;
ReclassifyNode(ear->Prev);
ReclassifyNode(ear->Next);
_TrianglesLeft--;
}
void ImTriangulator::FlipNodeList()
{
ImTriangulatorNode* prev = _Nodes;
ImTriangulatorNode* temp = _Nodes;
ImTriangulatorNode* current = _Nodes->Next;
prev->Next = prev;
prev->Prev = prev;
while (current != _Nodes)
{
temp = current->Next;
current->Next = prev;
prev->Prev = current;
_Nodes->Next = current;
current->Prev = _Nodes;
prev = current;
current = temp;
}
_Nodes = prev;
}
// A triangle is an ear is no other vertex is inside it. We can test reflexes vertices only (see reference algorithm)
bool ImTriangulator::IsEar(int i0, int i1, int i2, const ImVec2& v0, const ImVec2& v1, const ImVec2& v2) const
{
ImTriangulatorNode** p_end = _Reflexes.Data + _Reflexes.Size;
for (ImTriangulatorNode** p = _Reflexes.Data; p < p_end; p++)
{
ImTriangulatorNode* reflex = *p;
if (reflex->Index != i0 && reflex->Index != i1 && reflex->Index != i2)
if (ImTriangleContainsPoint(v0, v1, v2, reflex->Pos))
return false;
}
return true;
}
void ImTriangulator::ReclassifyNode(ImTriangulatorNode* n1)
{
// Classify node
ImTriangulatorNodeType type;
const ImTriangulatorNode* n0 = n1->Prev;
const ImTriangulatorNode* n2 = n1->Next;
if (!ImTriangleIsClockwise(n0->Pos, n1->Pos, n2->Pos))
type = ImTriangulatorNodeType_Reflex;
else if (IsEar(n0->Index, n1->Index, n2->Index, n0->Pos, n1->Pos, n2->Pos))
type = ImTriangulatorNodeType_Ear;
else
type = ImTriangulatorNodeType_Convex;
// Update lists when a type changes
if (type == n1->Type)
return;
if (n1->Type == ImTriangulatorNodeType_Reflex)
_Reflexes.find_erase_unsorted(n1->Index);
else if (n1->Type == ImTriangulatorNodeType_Ear)
_Ears.find_erase_unsorted(n1->Index);
if (type == ImTriangulatorNodeType_Reflex)
_Reflexes.push_back(n1);
else if (type == ImTriangulatorNodeType_Ear)
_Ears.push_back(n1);
n1->Type = type;
}
// Use ear-clipping algorithm to triangulate a simple polygon (no self-interaction, no holes).
// (Reminder: we don't perform any coarse clipping/culling in ImDrawList layer!
// It is up to caller to ensure not making costly calls that will be outside of visible area.
// As concave fill is noticeably more expensive than other primitives, be mindful of this...
// Caller can build AABB of points, and avoid filling if 'draw_list->_CmdHeader.ClipRect.Overlays(points_bb) == false')
void ImDrawList::AddConcavePolyFilled(const ImVec2* points, const int points_count, ImU32 col)
{
if (points_count < 3 || (col & IM_COL32_A_MASK) == 0)
return;
const ImVec2 uv = _Data->TexUvWhitePixel;
ImTriangulator triangulator;
unsigned int triangle[3];
if (Flags & ImDrawListFlags_AntiAliasedFill)
{
// Anti-aliased Fill
const float AA_SIZE = _FringeScale;
const ImU32 col_trans = col & ~IM_COL32_A_MASK;
const int idx_count = (points_count - 2) * 3 + points_count * 6;
const int vtx_count = (points_count * 2);
PrimReserve(idx_count, vtx_count);
// Add indexes for fill
unsigned int vtx_inner_idx = _VtxCurrentIdx;
unsigned int vtx_outer_idx = _VtxCurrentIdx + 1;
_Data->TempBuffer.reserve_discard((ImTriangulator::EstimateScratchBufferSize(points_count) + sizeof(ImVec2)) / sizeof(ImVec2));
triangulator.Init(points, points_count, _Data->TempBuffer.Data);
while (triangulator._TrianglesLeft > 0)
{
triangulator.GetNextTriangle(triangle);
_IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (triangle[0] << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (triangle[1] << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (triangle[2] << 1));
_IdxWritePtr += 3;
}
// Compute normals
_Data->TempBuffer.reserve_discard(points_count);
ImVec2* temp_normals = _Data->TempBuffer.Data;
for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++)
{
const ImVec2& p0 = points[i0];
const ImVec2& p1 = points[i1];
float dx = p1.x - p0.x;
float dy = p1.y - p0.y;
IM_NORMALIZE2F_OVER_ZERO(dx, dy);
temp_normals[i0].x = dy;
temp_normals[i0].y = -dx;
}
for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++)
{
// Average normals
const ImVec2& n0 = temp_normals[i0];
const ImVec2& n1 = temp_normals[i1];
float dm_x = (n0.x + n1.x) * 0.5f;
float dm_y = (n0.y + n1.y) * 0.5f;
IM_FIXNORMAL2F(dm_x, dm_y);
dm_x *= AA_SIZE * 0.5f;
dm_y *= AA_SIZE * 0.5f;
// Add vertices
_VtxWritePtr[0].pos.x = (points[i1].x - dm_x); _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner
_VtxWritePtr[1].pos.x = (points[i1].x + dm_x); _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer
_VtxWritePtr += 2;
// Add indexes for fringes
_IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1));
_IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1));
_IdxWritePtr += 6;
}
_VtxCurrentIdx += (ImDrawIdx)vtx_count;
}
else
{
// Non Anti-aliased Fill
const int idx_count = (points_count - 2) * 3;
const int vtx_count = points_count;
PrimReserve(idx_count, vtx_count);
for (int i = 0; i < vtx_count; i++)
{
_VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col;
_VtxWritePtr++;
}
_Data->TempBuffer.reserve_discard((ImTriangulator::EstimateScratchBufferSize(points_count) + sizeof(ImVec2)) / sizeof(ImVec2));
triangulator.Init(points, points_count, _Data->TempBuffer.Data);
while (triangulator._TrianglesLeft > 0)
{
triangulator.GetNextTriangle(triangle);
_IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx + triangle[0]); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + triangle[1]); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + triangle[2]);
_IdxWritePtr += 3;
}
_VtxCurrentIdx += (ImDrawIdx)vtx_count;
}
}
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// [SECTION] ImDrawListSplitter // [SECTION] ImDrawListSplitter
@ -1808,6 +2163,63 @@ void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx)
// [SECTION] ImDrawData // [SECTION] ImDrawData
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
void ImDrawData::Clear()
{
Valid = false;
CmdListsCount = TotalIdxCount = TotalVtxCount = 0;
CmdLists.resize(0); // The ImDrawList are NOT owned by ImDrawData but e.g. by ImGuiContext, so we don't clear them.
DisplayPos = DisplaySize = FramebufferScale = ImVec2(0.0f, 0.0f);
OwnerViewport = NULL;
}
// Important: 'out_list' is generally going to be draw_data->CmdLists, but may be another temporary list
// as long at it is expected that the result will be later merged into draw_data->CmdLists[].
void ImGui::AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.Size == 0)
return;
if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
return;
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
// May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
// - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
// Be mindful that the lower-level ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
// - If you want large meshes with more than 64K vertices, you can either:
// (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
// Most example backends already support this from 1.71. Pre-1.71 backends won't.
// Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
// (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
// Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes.
// 2 and 4 bytes indices are generally supported by most graphics API.
// - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
// the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
// Add to output list + records state in ImDrawData
out_list->push_back(draw_list);
draw_data->CmdListsCount++;
draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
}
void ImDrawData::AddDrawList(ImDrawList* draw_list)
{
IM_ASSERT(CmdLists.Size == CmdListsCount);
draw_list->_PopUnusedDrawCmd();
ImGui::AddDrawListToDrawDataEx(this, &CmdLists, draw_list);
}
// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! // For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
void ImDrawData::DeIndexAllBuffers() void ImDrawData::DeIndexAllBuffers()
{ {
@ -1832,15 +2244,9 @@ void ImDrawData::DeIndexAllBuffers()
// or if there is a difference between your window resolution and framebuffer resolution. // or if there is a difference between your window resolution and framebuffer resolution.
void ImDrawData::ScaleClipRects(const ImVec2& fb_scale) void ImDrawData::ScaleClipRects(const ImVec2& fb_scale)
{ {
for (int i = 0; i < CmdListsCount; i++) for (ImDrawList* draw_list : CmdLists)
{ for (ImDrawCmd& cmd : draw_list->CmdBuffer)
ImDrawList* cmd_list = CmdLists[i]; cmd.ClipRect = ImVec4(cmd.ClipRect.x * fb_scale.x, cmd.ClipRect.y * fb_scale.y, cmd.ClipRect.z * fb_scale.x, cmd.ClipRect.w * fb_scale.y);
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i];
cmd->ClipRect = ImVec4(cmd->ClipRect.x * fb_scale.x, cmd->ClipRect.y * fb_scale.y, cmd->ClipRect.z * fb_scale.x, cmd->ClipRect.w * fb_scale.y);
}
}
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -1896,6 +2302,14 @@ void ImGui::ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int ve
} }
} }
void ImGui::ShadeVertsTransformPos(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& pivot_in, float cos_a, float sin_a, const ImVec2& pivot_out)
{
ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx;
ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx;
for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex)
vertex->pos = ImRotate(vertex->pos- pivot_in, cos_a, sin_a) + pivot_out;
}
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// [SECTION] ImFontConfig // [SECTION] ImFontConfig
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -1904,10 +2318,11 @@ ImFontConfig::ImFontConfig()
{ {
memset(this, 0, sizeof(*this)); memset(this, 0, sizeof(*this));
FontDataOwnedByAtlas = true; FontDataOwnedByAtlas = true;
OversampleH = 3; // FIXME: 2 may be a better default? OversampleH = 2;
OversampleV = 1; OversampleV = 1;
GlyphMaxAdvanceX = FLT_MAX; GlyphMaxAdvanceX = FLT_MAX;
RasterizerMultiply = 1.0f; RasterizerMultiply = 1.0f;
RasterizerDensity = 1.0f;
EllipsisChar = (ImWchar)-1; EllipsisChar = (ImWchar)-1;
} }
@ -1981,19 +2396,19 @@ ImFontAtlas::~ImFontAtlas()
void ImFontAtlas::ClearInputData() void ImFontAtlas::ClearInputData()
{ {
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
for (int i = 0; i < ConfigData.Size; i++) for (ImFontConfig& font_cfg : ConfigData)
if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) if (font_cfg.FontData && font_cfg.FontDataOwnedByAtlas)
{ {
IM_FREE(ConfigData[i].FontData); IM_FREE(font_cfg.FontData);
ConfigData[i].FontData = NULL; font_cfg.FontData = NULL;
} }
// When clearing this we lose access to the font name and other information used to build the font. // When clearing this we lose access to the font name and other information used to build the font.
for (int i = 0; i < Fonts.Size; i++) for (ImFont* font : Fonts)
if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) if (font->ConfigData >= ConfigData.Data && font->ConfigData < ConfigData.Data + ConfigData.Size)
{ {
Fonts[i]->ConfigData = NULL; font->ConfigData = NULL;
Fonts[i]->ConfigDataCount = 0; font->ConfigDataCount = 0;
} }
ConfigData.clear(); ConfigData.clear();
CustomRects.clear(); CustomRects.clear();
@ -2090,6 +2505,8 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
if (new_font_cfg.DstFont->EllipsisChar == (ImWchar)-1) if (new_font_cfg.DstFont->EllipsisChar == (ImWchar)-1)
new_font_cfg.DstFont->EllipsisChar = font_cfg->EllipsisChar; new_font_cfg.DstFont->EllipsisChar = font_cfg->EllipsisChar;
ImFontAtlasUpdateConfigDataPointers(this);
// Invalidate texture // Invalidate texture
TexReady = false; TexReady = false;
ClearTexData(); ClearTexData();
@ -2126,7 +2543,7 @@ ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
if (font_cfg.Name[0] == '\0') if (font_cfg.Name[0] == '\0')
ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels); ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels);
font_cfg.EllipsisChar = (ImWchar)0x0085; font_cfg.EllipsisChar = (ImWchar)0x0085;
font_cfg.GlyphOffset.y = 1.0f * IM_FLOOR(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units font_cfg.GlyphOffset.y = 1.0f * IM_TRUNC(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units
const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();
const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault(); const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault();
@ -2156,13 +2573,14 @@ ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels,
} }
// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). // NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build().
ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* font_data, int font_data_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
{ {
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!"); IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
IM_ASSERT(font_cfg.FontData == NULL); IM_ASSERT(font_cfg.FontData == NULL);
font_cfg.FontData = ttf_data; IM_ASSERT(font_data_size > 100 && "Incorrect value for font_data_size!"); // Heuristic to prevent accidentally passing a wrong value to font_data_size.
font_cfg.FontDataSize = ttf_size; font_cfg.FontData = font_data;
font_cfg.FontDataSize = font_data_size;
font_cfg.SizePixels = size_pixels > 0.0f ? size_pixels : font_cfg.SizePixels; font_cfg.SizePixels = size_pixels > 0.0f ? size_pixels : font_cfg.SizePixels;
if (glyph_ranges) if (glyph_ranges)
font_cfg.GlyphRanges = glyph_ranges; font_cfg.GlyphRanges = glyph_ranges;
@ -2377,7 +2795,10 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo);
IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found."); IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found.");
if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset))
{
IM_ASSERT(0 && "stbtt_InitFont(): failed to parse FontData. It is correct and complete? Check FontDataSize.");
return false; return false;
}
// Measure highest codepoints // Measure highest codepoints
ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex]; ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
@ -2459,7 +2880,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
// Convert our ranges in the format stb_truetype wants // Convert our ranges in the format stb_truetype wants
ImFontConfig& cfg = atlas->ConfigData[src_i]; ImFontConfig& cfg = atlas->ConfigData[src_i];
src_tmp.PackRange.font_size = cfg.SizePixels; src_tmp.PackRange.font_size = cfg.SizePixels * cfg.RasterizerDensity;
src_tmp.PackRange.first_unicode_codepoint_in_range = 0; src_tmp.PackRange.first_unicode_codepoint_in_range = 0;
src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data; src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data;
src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size; src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size;
@ -2468,7 +2889,7 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
src_tmp.PackRange.v_oversample = (unsigned char)cfg.OversampleV; src_tmp.PackRange.v_oversample = (unsigned char)cfg.OversampleV;
// Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects) // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects)
const float scale = (cfg.SizePixels > 0) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels); const float scale = (cfg.SizePixels > 0.0f) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels * cfg.RasterizerDensity) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels * cfg.RasterizerDensity);
const int padding = atlas->TexGlyphPadding; const int padding = atlas->TexGlyphPadding;
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++) for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
{ {
@ -2564,12 +2985,14 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
int unscaled_ascent, unscaled_descent, unscaled_line_gap; int unscaled_ascent, unscaled_descent, unscaled_line_gap;
stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap);
const float ascent = ImFloor(unscaled_ascent * font_scale + ((unscaled_ascent > 0.0f) ? +1 : -1)); const float ascent = ImCeil(unscaled_ascent * font_scale);
const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1)); const float descent = ImFloor(unscaled_descent * font_scale);
ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent); ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
const float font_off_x = cfg.GlyphOffset.x; const float font_off_x = cfg.GlyphOffset.x;
const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent); const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
const float inv_rasterization_scale = 1.0f / cfg.RasterizerDensity;
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++) for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
{ {
// Register glyph // Register glyph
@ -2578,7 +3001,11 @@ static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
stbtt_aligned_quad q; stbtt_aligned_quad q;
float unused_x = 0.0f, unused_y = 0.0f; float unused_x = 0.0f, unused_y = 0.0f;
stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0); stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0);
dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance); float x0 = q.x0 * inv_rasterization_scale + font_off_x;
float y0 = q.y0 * inv_rasterization_scale + font_off_y;
float x1 = q.x1 * inv_rasterization_scale + font_off_x;
float y1 = q.y1 * inv_rasterization_scale + font_off_y;
dst_font->AddGlyph(&cfg, (ImWchar)codepoint, x0, y0, x1, y1, q.s0, q.t0, q.s1, q.t1, pc.xadvance * inv_rasterization_scale);
} }
} }
@ -2598,19 +3025,31 @@ const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype()
#endif // IMGUI_ENABLE_STB_TRUETYPE #endif // IMGUI_ENABLE_STB_TRUETYPE
void ImFontAtlasUpdateConfigDataPointers(ImFontAtlas* atlas)
{
for (ImFontConfig& font_cfg : atlas->ConfigData)
{
ImFont* font = font_cfg.DstFont;
if (!font_cfg.MergeMode)
{
font->ConfigData = &font_cfg;
font->ConfigDataCount = 0;
}
font->ConfigDataCount++;
}
}
void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent) void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent)
{ {
if (!font_config->MergeMode) if (!font_config->MergeMode)
{ {
font->ClearOutputData(); font->ClearOutputData();
font->FontSize = font_config->SizePixels; font->FontSize = font_config->SizePixels;
font->ConfigData = font_config; IM_ASSERT(font->ConfigData == font_config);
font->ConfigDataCount = 0;
font->ContainerAtlas = atlas; font->ContainerAtlas = atlas;
font->Ascent = ascent; font->Ascent = ascent;
font->Descent = descent; font->Descent = descent;
} }
font->ConfigDataCount++;
} }
void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque) void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque)
@ -2757,6 +3196,13 @@ static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas)
// Note: this is called / shared by both the stb_truetype and the FreeType builder // Note: this is called / shared by both the stb_truetype and the FreeType builder
void ImFontAtlasBuildInit(ImFontAtlas* atlas) void ImFontAtlasBuildInit(ImFontAtlas* atlas)
{ {
// Round font size
// - We started rounding in 1.90 WIP (18991) as our layout system currently doesn't support non-rounded font size well yet.
// - Note that using io.FontGlobalScale or SetWindowFontScale(), with are legacy-ish, partially supported features, can still lead to unrounded sizes.
// - We may support it better later and remove this rounding.
for (ImFontConfig& cfg : atlas->ConfigData)
cfg.SizePixels = ImTrunc(cfg.SizePixels);
// Register texture region for mouse cursors or standard white pixels // Register texture region for mouse cursors or standard white pixels
if (atlas->PackIdMouseCursors < 0) if (atlas->PackIdMouseCursors < 0)
{ {
@ -2798,9 +3244,9 @@ void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
} }
// Build all fonts lookup tables // Build all fonts lookup tables
for (int i = 0; i < atlas->Fonts.Size; i++) for (ImFont* font : atlas->Fonts)
if (atlas->Fonts[i]->DirtyLookupTables) if (font->DirtyLookupTables)
atlas->Fonts[i]->BuildLookupTable(); font->BuildLookupTable();
atlas->TexReady = true; atlas->TexReady = true;
} }
@ -3165,6 +3611,7 @@ void ImFont::BuildLookupTable()
max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint);
// Build lookup table // Build lookup table
IM_ASSERT(Glyphs.Size > 0 && "Font has not loaded glyph!");
IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved
IndexAdvanceX.clear(); IndexAdvanceX.clear();
IndexLookup.clear(); IndexLookup.clear();
@ -3281,7 +3728,7 @@ void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, floa
advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX); advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX);
if (advance_x != advance_x_original) if (advance_x != advance_x_original)
{ {
float char_off_x = cfg->PixelSnapH ? ImFloor((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f; float char_off_x = cfg->PixelSnapH ? ImTrunc((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f;
x0 += char_off_x; x0 += char_off_x;
x1 += char_off_x; x1 += char_off_x;
} }
@ -3549,8 +3996,8 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, Im
if (glyph->Colored) if (glyph->Colored)
col |= ~IM_COL32_A_MASK; col |= ~IM_COL32_A_MASK;
float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f;
float x = IM_FLOOR(pos.x); float x = IM_TRUNC(pos.x);
float y = IM_FLOOR(pos.y); float y = IM_TRUNC(pos.y);
draw_list->PrimReserve(6, 4); draw_list->PrimReserve(6, 4);
draw_list->PrimRectUV(ImVec2(x + glyph->X0 * scale, y + glyph->Y0 * scale), ImVec2(x + glyph->X1 * scale, y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); draw_list->PrimRectUV(ImVec2(x + glyph->X0 * scale, y + glyph->Y0 * scale), ImVec2(x + glyph->X1 * scale, y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);
} }
@ -3562,8 +4009,8 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls. text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls.
// Align to be pixel perfect // Align to be pixel perfect
float x = IM_FLOOR(pos.x); float x = IM_TRUNC(pos.x);
float y = IM_FLOOR(pos.y); float y = IM_TRUNC(pos.y);
if (y > clip_rect.w) if (y > clip_rect.w)
return; return;
@ -3634,6 +4081,8 @@ void ImFont::RenderText(ImDrawList* draw_list, float size, const ImVec2& pos, Im
{ {
x = start_x; x = start_x;
y += line_height; y += line_height;
if (y > clip_rect.w)
break; // break out of main loop
word_wrap_eol = NULL; word_wrap_eol = NULL;
s = CalcWordWrapNextLineStartA(s, text_end); // Wrapping skips upcoming blanks s = CalcWordWrapNextLineStartA(s, text_end); // Wrapping skips upcoming blanks
continue; continue;
@ -3863,8 +4312,8 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im
} }
else else
{ {
draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b); // BL
draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e); // TR
} }
if (p1.x > rect.Min.x + rounding) if (p1.x > rect.Min.x + rounding)
{ {
@ -3883,8 +4332,8 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im
} }
else else
{ {
draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b); // TR
draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e); // BR
} }
} }
draw_list->PathFillConvex(col); draw_list->PathFillConvex(col);
@ -4071,8 +4520,8 @@ static unsigned int stb_decompress(unsigned char *output, const unsigned char *i
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// ProggyClean.ttf // ProggyClean.ttf
// Copyright (c) 2004, 2005 Tristan Grimmer // Copyright (c) 2004, 2005 Tristan Grimmer
// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) // MIT license (see License.txt in http://www.proggyfonts.net/index.php?menu=download)
// Download and more information at http://upperbounds.net // Download and more information at http://www.proggyfonts.net or http://upperboundsinteractive.com/fonts.php
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// File: 'ProggyClean.ttf' (41208 bytes) // File: 'ProggyClean.ttf' (41208 bytes)
// Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding). // Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding).

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -2,8 +2,9 @@
// This is a slightly modified version of stb_textedit.h 1.14. // This is a slightly modified version of stb_textedit.h 1.14.
// Those changes would need to be pushed into nothings/stb: // Those changes would need to be pushed into nothings/stb:
// - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321)
// - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000) // - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783)
// Grep for [DEAR IMGUI] to find the changes. // Grep for [DEAR IMGUI] to find the changes.
// - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_*
// stb_textedit.h - v1.14 - public domain - Sean Barrett // stb_textedit.h - v1.14 - public domain - Sean Barrett
// Development of this library was sponsored by RAD Game Tools // Development of this library was sponsored by RAD Game Tools
@ -30,7 +31,7 @@
// DEPENDENCIES // DEPENDENCIES
// //
// Uses the C runtime function 'memmove', which you can override // Uses the C runtime function 'memmove', which you can override
// by defining STB_TEXTEDIT_memmove before the implementation. // by defining IMSTB_TEXTEDIT_memmove before the implementation.
// Uses no other functions. Performs no runtime allocations. // Uses no other functions. Performs no runtime allocations.
// //
// //
@ -40,7 +41,7 @@
// 1.13 (2019-02-07) fix bug in undo size management // 1.13 (2019-02-07) fix bug in undo size management
// 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash // 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash
// 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield // 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield
// 1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual // 1.10 (2016-10-25) suppress warnings about casting away const with -Wcast-qual
// 1.9 (2016-08-27) customizable move-by-word // 1.9 (2016-08-27) customizable move-by-word
// 1.8 (2016-04-02) better keyboard handling when mouse button is down // 1.8 (2016-04-02) better keyboard handling when mouse button is down
// 1.7 (2015-09-13) change y range handling in case baseline is non-0 // 1.7 (2015-09-13) change y range handling in case baseline is non-0
@ -274,8 +275,8 @@
//// ////
//// ////
#ifndef INCLUDE_STB_TEXTEDIT_H #ifndef INCLUDE_IMSTB_TEXTEDIT_H
#define INCLUDE_STB_TEXTEDIT_H #define INCLUDE_IMSTB_TEXTEDIT_H
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
// //
@ -286,33 +287,33 @@
// and undo state. // and undo state.
// //
#ifndef STB_TEXTEDIT_UNDOSTATECOUNT #ifndef IMSTB_TEXTEDIT_UNDOSTATECOUNT
#define STB_TEXTEDIT_UNDOSTATECOUNT 99 #define IMSTB_TEXTEDIT_UNDOSTATECOUNT 99
#endif #endif
#ifndef STB_TEXTEDIT_UNDOCHARCOUNT #ifndef IMSTB_TEXTEDIT_UNDOCHARCOUNT
#define STB_TEXTEDIT_UNDOCHARCOUNT 999 #define IMSTB_TEXTEDIT_UNDOCHARCOUNT 999
#endif #endif
#ifndef STB_TEXTEDIT_CHARTYPE #ifndef IMSTB_TEXTEDIT_CHARTYPE
#define STB_TEXTEDIT_CHARTYPE int #define IMSTB_TEXTEDIT_CHARTYPE int
#endif #endif
#ifndef STB_TEXTEDIT_POSITIONTYPE #ifndef IMSTB_TEXTEDIT_POSITIONTYPE
#define STB_TEXTEDIT_POSITIONTYPE int #define IMSTB_TEXTEDIT_POSITIONTYPE int
#endif #endif
typedef struct typedef struct
{ {
// private data // private data
STB_TEXTEDIT_POSITIONTYPE where; IMSTB_TEXTEDIT_POSITIONTYPE where;
STB_TEXTEDIT_POSITIONTYPE insert_length; IMSTB_TEXTEDIT_POSITIONTYPE insert_length;
STB_TEXTEDIT_POSITIONTYPE delete_length; IMSTB_TEXTEDIT_POSITIONTYPE delete_length;
int char_storage; int char_storage;
} StbUndoRecord; } StbUndoRecord;
typedef struct typedef struct
{ {
// private data // private data
StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT]; StbUndoRecord undo_rec [IMSTB_TEXTEDIT_UNDOSTATECOUNT];
STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; IMSTB_TEXTEDIT_CHARTYPE undo_char[IMSTB_TEXTEDIT_UNDOCHARCOUNT];
short undo_point, redo_point; short undo_point, redo_point;
int undo_char_point, redo_char_point; int undo_char_point, redo_char_point;
} StbUndoState; } StbUndoState;
@ -371,7 +372,7 @@ typedef struct
float ymin,ymax; // height of row above and below baseline float ymin,ymax; // height of row above and below baseline
int num_chars; int num_chars;
} StbTexteditRow; } StbTexteditRow;
#endif //INCLUDE_STB_TEXTEDIT_H #endif //INCLUDE_IMSTB_TEXTEDIT_H
//////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////
@ -384,11 +385,11 @@ typedef struct
// implementation isn't include-guarded, since it might have indirectly // implementation isn't include-guarded, since it might have indirectly
// included just the "header" portion // included just the "header" portion
#ifdef STB_TEXTEDIT_IMPLEMENTATION #ifdef IMSTB_TEXTEDIT_IMPLEMENTATION
#ifndef STB_TEXTEDIT_memmove #ifndef IMSTB_TEXTEDIT_memmove
#include <string.h> #include <string.h>
#define STB_TEXTEDIT_memmove memmove #define IMSTB_TEXTEDIT_memmove memmove
#endif #endif
@ -398,7 +399,7 @@ typedef struct
// //
// traverse the layout to locate the nearest character to a display position // traverse the layout to locate the nearest character to a display position
static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) static int stb_text_locate_coord(IMSTB_TEXTEDIT_STRING *str, float x, float y)
{ {
StbTexteditRow r; StbTexteditRow r;
int n = STB_TEXTEDIT_STRINGLEN(str); int n = STB_TEXTEDIT_STRINGLEN(str);
@ -458,7 +459,7 @@ static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y)
} }
// API click: on mouse down, move the cursor to the clicked location, and reset the selection // API click: on mouse down, move the cursor to the clicked location, and reset the selection
static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) static void stb_textedit_click(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
{ {
// In single-line mode, just always make y = 0. This lets the drag keep working if the mouse // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse
// goes off the top or bottom of the text // goes off the top or bottom of the text
@ -476,7 +477,7 @@ static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *stat
} }
// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location // API drag: on mouse drag, move the cursor and selection endpoint to the clicked location
static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) static void stb_textedit_drag(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)
{ {
int p = 0; int p = 0;
@ -502,11 +503,11 @@ static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state
// //
// forward declarations // forward declarations
static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state);
static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state);
static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); static void stb_text_makeundo_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length);
static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length);
static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); static void stb_text_makeundo_replace(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length);
typedef struct typedef struct
{ {
@ -518,7 +519,7 @@ typedef struct
// find the x/y location of a character, and remember info about the previous row in // find the x/y location of a character, and remember info about the previous row in
// case we get a move-up event (for page up, we'll have to rescan) // case we get a move-up event (for page up, we'll have to rescan)
static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line) static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING *str, int n, int single_line)
{ {
StbTexteditRow r; StbTexteditRow r;
int prev_start = 0; int prev_start = 0;
@ -549,7 +550,10 @@ static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *s
i += r.num_chars; i += r.num_chars;
find->y += r.baseline_y_delta; find->y += r.baseline_y_delta;
if (i == z) // [DEAR IMGUI] if (i == z) // [DEAR IMGUI]
{
r.num_chars = 0; // [DEAR IMGUI]
break; // [DEAR IMGUI] break; // [DEAR IMGUI]
}
} }
find->first_char = first = i; find->first_char = first = i;
@ -566,7 +570,7 @@ static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *s
#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) #define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end)
// make the selection/cursor state valid if client altered the string // make the selection/cursor state valid if client altered the string
static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) static void stb_textedit_clamp(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{ {
int n = STB_TEXTEDIT_STRINGLEN(str); int n = STB_TEXTEDIT_STRINGLEN(str);
if (STB_TEXT_HAS_SELECTION(state)) { if (STB_TEXT_HAS_SELECTION(state)) {
@ -580,7 +584,7 @@ static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *stat
} }
// delete characters while updating undo // delete characters while updating undo
static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) static void stb_textedit_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len)
{ {
stb_text_makeundo_delete(str, state, where, len); stb_text_makeundo_delete(str, state, where, len);
STB_TEXTEDIT_DELETECHARS(str, where, len); STB_TEXTEDIT_DELETECHARS(str, where, len);
@ -588,7 +592,7 @@ static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *sta
} }
// delete the section // delete the section
static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) static void stb_textedit_delete_selection(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{ {
stb_textedit_clamp(str, state); stb_textedit_clamp(str, state);
if (STB_TEXT_HAS_SELECTION(state)) { if (STB_TEXT_HAS_SELECTION(state)) {
@ -625,7 +629,7 @@ static void stb_textedit_move_to_first(STB_TexteditState *state)
} }
// move cursor to last character of selection // move cursor to last character of selection
static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) static void stb_textedit_move_to_last(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{ {
if (STB_TEXT_HAS_SELECTION(state)) { if (STB_TEXT_HAS_SELECTION(state)) {
stb_textedit_sortselection(state); stb_textedit_sortselection(state);
@ -637,13 +641,13 @@ static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditStat
} }
#ifdef STB_TEXTEDIT_IS_SPACE #ifdef STB_TEXTEDIT_IS_SPACE
static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx ) static int is_word_boundary( IMSTB_TEXTEDIT_STRING *str, int idx )
{ {
return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1;
} }
#ifndef STB_TEXTEDIT_MOVEWORDLEFT #ifndef STB_TEXTEDIT_MOVEWORDLEFT
static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c ) static int stb_textedit_move_to_word_previous( IMSTB_TEXTEDIT_STRING *str, int c )
{ {
--c; // always move at least one character --c; // always move at least one character
while( c >= 0 && !is_word_boundary( str, c ) ) while( c >= 0 && !is_word_boundary( str, c ) )
@ -658,7 +662,7 @@ static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c )
#endif #endif
#ifndef STB_TEXTEDIT_MOVEWORDRIGHT #ifndef STB_TEXTEDIT_MOVEWORDRIGHT
static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c ) static int stb_textedit_move_to_word_next( IMSTB_TEXTEDIT_STRING *str, int c )
{ {
const int len = STB_TEXTEDIT_STRINGLEN(str); const int len = STB_TEXTEDIT_STRINGLEN(str);
++c; // always move at least one character ++c; // always move at least one character
@ -685,7 +689,7 @@ static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state)
} }
// API cut: delete selection // API cut: delete selection
static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) static int stb_textedit_cut(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{ {
if (STB_TEXT_HAS_SELECTION(state)) { if (STB_TEXT_HAS_SELECTION(state)) {
stb_textedit_delete_selection(str,state); // implicitly clamps stb_textedit_delete_selection(str,state); // implicitly clamps
@ -696,7 +700,7 @@ static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
} }
// API paste: replace existing selection with passed-in text // API paste: replace existing selection with passed-in text
static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE *text, int len)
{ {
// if there's a selection, the paste should delete it // if there's a selection, the paste should delete it
stb_textedit_clamp(str, state); stb_textedit_clamp(str, state);
@ -717,14 +721,14 @@ static int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditSta
#endif #endif
// API key: process a keyboard input // API key: process a keyboard input
static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)
{ {
retry: retry:
switch (key) { switch (key) {
default: { default: {
int c = STB_TEXTEDIT_KEYTOTEXT(key); int c = STB_TEXTEDIT_KEYTOTEXT(key);
if (c > 0) { if (c > 0) {
STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c; IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE) c;
// can't add newline in single-line mode // can't add newline in single-line mode
if (c == '\n' && state->single_line) if (c == '\n' && state->single_line)
@ -889,8 +893,8 @@ retry:
x = row.x0; x = row.x0;
for (i=0; i < row.num_chars; ++i) { for (i=0; i < row.num_chars; ++i) {
float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); float dx = STB_TEXTEDIT_GETWIDTH(str, start, i);
#ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE
if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE)
break; break;
#endif #endif
x += dx; x += dx;
@ -951,8 +955,8 @@ retry:
x = row.x0; x = row.x0;
for (i=0; i < row.num_chars; ++i) { for (i=0; i < row.num_chars; ++i) {
float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i);
#ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE #ifdef IMSTB_TEXTEDIT_GETWIDTH_NEWLINE
if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) if (dx == IMSTB_TEXTEDIT_GETWIDTH_NEWLINE)
break; break;
#endif #endif
x += dx; x += dx;
@ -1109,8 +1113,8 @@ retry:
static void stb_textedit_flush_redo(StbUndoState *state) static void stb_textedit_flush_redo(StbUndoState *state)
{ {
state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; state->redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT;
state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; state->redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT;
} }
// discard the oldest entry in the undo list // discard the oldest entry in the undo list
@ -1122,13 +1126,13 @@ static void stb_textedit_discard_undo(StbUndoState *state)
int n = state->undo_rec[0].insert_length, i; int n = state->undo_rec[0].insert_length, i;
// delete n characters from all other records // delete n characters from all other records
state->undo_char_point -= n; state->undo_char_point -= n;
STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); IMSTB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(IMSTB_TEXTEDIT_CHARTYPE)));
for (i=0; i < state->undo_point; ++i) for (i=0; i < state->undo_point; ++i)
if (state->undo_rec[i].char_storage >= 0) if (state->undo_rec[i].char_storage >= 0)
state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it
} }
--state->undo_point; --state->undo_point;
STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0]))); IMSTB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0])));
} }
} }
@ -1138,7 +1142,7 @@ static void stb_textedit_discard_undo(StbUndoState *state)
// fill up even though the undo buffer didn't // fill up even though the undo buffer didn't
static void stb_textedit_discard_redo(StbUndoState *state) static void stb_textedit_discard_redo(StbUndoState *state)
{ {
int k = STB_TEXTEDIT_UNDOSTATECOUNT-1; int k = IMSTB_TEXTEDIT_UNDOSTATECOUNT-1;
if (state->redo_point <= k) { if (state->redo_point <= k) {
// if the k'th undo state has characters, clean those up // if the k'th undo state has characters, clean those up
@ -1146,7 +1150,7 @@ static void stb_textedit_discard_redo(StbUndoState *state)
int n = state->undo_rec[k].insert_length, i; int n = state->undo_rec[k].insert_length, i;
// move the remaining redo character data to the end of the buffer // move the remaining redo character data to the end of the buffer
state->redo_char_point += n; state->redo_char_point += n;
STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); IMSTB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((IMSTB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(IMSTB_TEXTEDIT_CHARTYPE)));
// adjust the position of all the other records to account for above memmove // adjust the position of all the other records to account for above memmove
for (i=state->redo_point; i < k; ++i) for (i=state->redo_point; i < k; ++i)
if (state->undo_rec[i].char_storage >= 0) if (state->undo_rec[i].char_storage >= 0)
@ -1154,12 +1158,12 @@ static void stb_textedit_discard_redo(StbUndoState *state)
} }
// now move all the redo records towards the end of the buffer; the first one is at 'redo_point' // now move all the redo records towards the end of the buffer; the first one is at 'redo_point'
// [DEAR IMGUI] // [DEAR IMGUI]
size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0])); size_t move_size = (size_t)((IMSTB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0]));
const char* buf_begin = (char*)state->undo_rec; (void)buf_begin; const char* buf_begin = (char*)state->undo_rec; (void)buf_begin;
const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end; const char* buf_end = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end;
IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin); IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin);
IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end); IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end);
STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size); IMSTB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size);
// now move redo_point to point to the new one // now move redo_point to point to the new one
++state->redo_point; ++state->redo_point;
@ -1173,32 +1177,32 @@ static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numch
// if we have no free records, we have to make room, by sliding the // if we have no free records, we have to make room, by sliding the
// existing records down // existing records down
if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) if (state->undo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT)
stb_textedit_discard_undo(state); stb_textedit_discard_undo(state);
// if the characters to store won't possibly fit in the buffer, we can't undo // if the characters to store won't possibly fit in the buffer, we can't undo
if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { if (numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT) {
state->undo_point = 0; state->undo_point = 0;
state->undo_char_point = 0; state->undo_char_point = 0;
return NULL; return NULL;
} }
// if we don't have enough free characters in the buffer, we have to make room // if we don't have enough free characters in the buffer, we have to make room
while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) while (state->undo_char_point + numchars > IMSTB_TEXTEDIT_UNDOCHARCOUNT)
stb_textedit_discard_undo(state); stb_textedit_discard_undo(state);
return &state->undo_rec[state->undo_point++]; return &state->undo_rec[state->undo_point++];
} }
static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) static IMSTB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len)
{ {
StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); StbUndoRecord *r = stb_text_create_undo_record(state, insert_len);
if (r == NULL) if (r == NULL)
return NULL; return NULL;
r->where = pos; r->where = pos;
r->insert_length = (STB_TEXTEDIT_POSITIONTYPE) insert_len; r->insert_length = (IMSTB_TEXTEDIT_POSITIONTYPE) insert_len;
r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) delete_len; r->delete_length = (IMSTB_TEXTEDIT_POSITIONTYPE) delete_len;
if (insert_len == 0) { if (insert_len == 0) {
r->char_storage = -1; r->char_storage = -1;
@ -1210,7 +1214,7 @@ static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos,
} }
} }
static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{ {
StbUndoState *s = &state->undostate; StbUndoState *s = &state->undostate;
StbUndoRecord u, *r; StbUndoRecord u, *r;
@ -1237,7 +1241,7 @@ static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
// characters stored for *undoing* don't leave room for redo // characters stored for *undoing* don't leave room for redo
// if the last is true, we have to bail // if the last is true, we have to bail
if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) { if (s->undo_char_point + u.delete_length >= IMSTB_TEXTEDIT_UNDOCHARCOUNT) {
// the undo records take up too much character space; there's no space to store the redo characters // the undo records take up too much character space; there's no space to store the redo characters
r->insert_length = 0; r->insert_length = 0;
} else { } else {
@ -1246,7 +1250,7 @@ static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
// there's definitely room to store the characters eventually // there's definitely room to store the characters eventually
while (s->undo_char_point + u.delete_length > s->redo_char_point) { while (s->undo_char_point + u.delete_length > s->redo_char_point) {
// should never happen: // should never happen:
if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) if (s->redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT)
return; return;
// there's currently not enough room, so discard a redo record // there's currently not enough room, so discard a redo record
stb_textedit_discard_redo(s); stb_textedit_discard_redo(s);
@ -1278,11 +1282,11 @@ static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)
s->redo_point--; s->redo_point--;
} }
static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state)
{ {
StbUndoState *s = &state->undostate; StbUndoState *s = &state->undostate;
StbUndoRecord *u, r; StbUndoRecord *u, r;
if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) if (s->redo_point == IMSTB_TEXTEDIT_UNDOSTATECOUNT)
return; return;
// we need to do two things: apply the redo record, and create an undo record // we need to do two things: apply the redo record, and create an undo record
@ -1334,20 +1338,20 @@ static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int le
stb_text_createundo(&state->undostate, where, 0, length); stb_text_createundo(&state->undostate, where, 0, length);
} }
static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) static void stb_text_makeundo_delete(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length)
{ {
int i; int i;
STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); IMSTB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0);
if (p) { if (p) {
for (i=0; i < length; ++i) for (i=0; i < length; ++i)
p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);
} }
} }
static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) static void stb_text_makeundo_replace(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length)
{ {
int i; int i;
STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); IMSTB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length);
if (p) { if (p) {
for (i=0; i < old_length; ++i) for (i=0; i < old_length; ++i)
p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);
@ -1359,8 +1363,8 @@ static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_lin
{ {
state->undostate.undo_point = 0; state->undostate.undo_point = 0;
state->undostate.undo_char_point = 0; state->undostate.undo_char_point = 0;
state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; state->undostate.redo_point = IMSTB_TEXTEDIT_UNDOSTATECOUNT;
state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; state->undostate.redo_char_point = IMSTB_TEXTEDIT_UNDOCHARCOUNT;
state->select_end = state->select_start = 0; state->select_end = state->select_start = 0;
state->cursor = 0; state->cursor = 0;
state->has_preferred_x = 0; state->has_preferred_x = 0;
@ -1383,16 +1387,16 @@ static void stb_textedit_initialize_state(STB_TexteditState *state, int is_singl
#pragma GCC diagnostic ignored "-Wcast-qual" #pragma GCC diagnostic ignored "-Wcast-qual"
#endif #endif
static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len) static int stb_textedit_paste(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE const *ctext, int len)
{ {
return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len); return stb_textedit_paste_internal(str, state, (IMSTB_TEXTEDIT_CHARTYPE *) ctext, len);
} }
#if defined(__GNUC__) || defined(__clang__) #if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#endif #endif
#endif//STB_TEXTEDIT_IMPLEMENTATION #endif//IMSTB_TEXTEDIT_IMPLEMENTATION
/* /*
------------------------------------------------------------------------------ ------------------------------------------------------------------------------

Some files were not shown because too many files have changed in this diff Show More