forked from ocornut/imgui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imgui.cpp
5934 lines (5125 loc) · 203 KB
/
imgui.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ImGui library
// See ImGui::ShowTestWindow() for sample code.
// Read 'Programmer guide' below for notes on how to setup ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
/*
MISSION STATEMENT
- easy to use to create code-driven and data-driven tools
- easy to use to create adhoc short-lived tools and long-lived, more elaborate tools
- easy to hack and improve
- minimize screen real-estate usage
- minimize setup and maintainance
- minimize state storage on user side
- portable, minimize dependencies, run on target (consoles, etc.)
- efficient runtime (nb- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything)
- read about immediate-mode GUI principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- doesn't look fancy, doesn't animate
- limited layout features, intricate layouts are typically crafted in code
- assume ASCII text, using strlen() and [] operators, etc
- occasionally use statically sized buffers for string manipulations - won't crash, but some long text may be clipped
USER GUIDE
- double-click title bar to collapse window
- click upper right corner to close a window, available when 'bool* open' is passed to ImGui::Begin()
- click and drag on lower right corner to resize window
- click and drag on any empty space to move window
- double-click/double-tap on lower right corner grip to auto-fit to content
- TAB/SHIFT+TAB to cycle through keyboard editable fields
- use mouse wheel to scroll
- use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true)
- CTRL+Click on a slider to input value as text
- text editor:
- Hold SHIFT or use mouse to select text.
- CTRL+Left/Right to word jump
- CTRL+Shift+Left/Right to select words
- CTRL+A our Double-Click to select all
- CTRL+X,CTRL+C,CTRL+V to use OS clipboard
- CTRL+Z,CTRL+Y to undo/redo
- ESCAPE to revert text to its original value
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
PROGRAMMER GUIDE
- your code creates the UI, if your code doesn't run the UI is gone! == dynamic UI, no construction step, less data retention on your side, no state duplication, less sync, less errors.
- see ImGui::ShowTestWindow() for user-side sample code
- getting started:
- initialisation: call ImGui::GetIO() and fill the 'Settings' data.
- every frame:
1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the 'Input' data, then call ImGui::NewFrame().
2/ use any ImGui function you want between NewFrame() and Render()
3/ ImGui::Render() to render all the accumulated command-lists. it will cack your RenderDrawListFn handler set in the IO structure.
- all rendering information are stored into command-lists until ImGui::Render() is called.
- effectively it means you can create widgets at any time in your code, regardless of "update" vs "render" considerations.
- a typical application skeleton may be:
// Application init
// TODO: Fill all 'Settings' fields of the io structure
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize.x = 1920.0f;
io.DisplaySize.y = 1280.0f;
io.DeltaTime = 1.0f/60.0f;
io.IniFilename = "imgui.ini";
// Application mainloop
while (true)
{
// 1/ get low-level input
// e.g. on Win32, GetKeyboardState(), or poll your events, etc.
// 2/ TODO: Fill all 'Input' fields of io structure and call NewFrame
ImGuiIO& io = ImGui::GetIO();
io.MousePos = ...
io.KeysDown[i] = ...
ImGui::NewFrame();
// 3/ most of your application code here - you can use any of ImGui::* functions between NewFrame() and Render() calls
GameUpdate();
GameRender();
// 4/ render & swap video buffers
ImGui::Render();
// swap video buffer, etc.
}
- some widgets carry state and requires an unique ID to do so.
- unique ID are typically derived from a string label, an indice or a pointer.
- use PushID/PopID to easily create scopes and avoid ID conflicts. A Window is also an implicit scope.
- when creating trees, ID are particularly important because you want to preserve the opened/closed state of tree nodes.
depending on your use cases you may want to use strings, indices or pointers as ID. experiment and see what makes more sense!
e.g. When displaying a single object, using a static string as ID will preserve your node open/closed state when the targetted object change
e.g. When displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state per object
- when passing a label you can optionally specify extra unique ID information within the same string using "##". This helps solving the simpler collision cases.
e.g. "Label" display "Label" and uses "Label" as ID
e.g. "Label##Foobar" display "Label" and uses "Label##Foobar" as ID
e.g. "##Foobar" display an empty label and uses "##Foobar" as ID
- if you want to use a different font than the default
- create bitmap font data using BMFont. allocate ImGui::GetIO().Font and use ->LoadFromFile()/LoadFromMemory(), set ImGui::GetIO().FontHeight
- load your texture yourself. texture *MUST* have white pixel at UV coordinate 'IMDRAW_TEX_UV_FOR_WHITE' (you can #define it in imconfig.h), this is used by solid objects.
- tip: the construct 'if (IMGUI_ONCE_UPON_A_FRAME)' will evaluate to true only once a frame, you can use it to add custom UI in the middle of a deep nested inner loop in your code.
- tip: you can call Render() multiple times (e.g for VR renders), up to you to communicate the extra state to your RenderDrawListFn function.
- tip: you can create widgets without a Begin/End block, they will go in an implicit window called "Debug"
ISSUES AND TODO-LIST
- misc: merge ImVec4 / ImGuiAabb, they are essentially duplicate containers
- window: autofit is losing its purpose when user relies on any dynamic layout (window width multiplier, column). maybe just discard autofit?
- window: support horizontal scroll
- window: fix resize grip scaling along with Rounding style setting
- window/style: add global alpha modifier (not just "fill_alpha")
- widgets: switching from "widget-label" to "label-widget" would make it more convenient to integrate widgets in trees
- widgets: clip text? hover clipped text shows it in a tooltip or in-place overlay
- main: make IsHovered() more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes
- main: make IsHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode?
- scrollbar: use relative mouse movement when first-clicking inside of scroll grab box.
- input number: optional range min/max
- input number: holding [-]/[+] buttons should increase the step non-linearly
- input number: rename Input*() to Input(), Slider*() to Slider() ?
- layout: clean up the InputFloat3/SliderFloat3/ColorEdit4 horrible layout code. item width should include frame padding, then we can have a generic horizontal layout helper.
- add input4 helper (once above layout helpers are in they'll be smaller)
- columns: declare column set (each column: fixed size, %, fill, distribute default size among fills)
- columns: columns header to act as button (~sort op) and allow resize/reorder
- columns: user specify columns size
- combo: turn child handling code into popup helper
- list selection, concept of a selectable "block" (that can be multiple widgets)
- menubar, menus
- plot: add a stride parameter?
- plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID)
- file selection widget -> build the tool in our codebase to improve model-dialog idioms (may or not lead to ImGui changes)
- slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt()
- slider: initial absolute click is unprecise. change to relative movement slider? hide mouse cursor, allow more precise input using less screen-space.
- text edit: centered text for slider or input text to it matches typical positionning.
- text edit: flag to disable live update of the user buffer.
- text edit: field resize behaviour - field could stretch when being edited? hover tooltip shows more text?
- text edit: pasting text into a number box should filter the characters the same way direct input does
- text edit: allow code to catch user pressing Return (perhaps through disable live edit? so only Return apply the final value, also allow catching Return if value didn't changed)
- settings: write more decent code to allow saving/loading new fields
- log: be able to right-click and log a window or tree-node into tty/file/clipboard?
- filters: set a current filter that tree node can automatically query to hide themselves
- filters: handle wildcards (with implicit leading/trailing *), regexps
- shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus)
- keyboard: full keyboard navigation and focus
- clipboard: add a default "local" implementation of clipboard functions (user will only need to override them to connect to OS clipboard)
- misc: not thread-safe
- optimisation/render: use indexed rendering
- optimisation/render: move clip-rect to vertex data? would allow merging all commands
- optimisation/render: merge command-list of all windows into one command-list?
- optimisation: turn some the various stack vectors into statically-sized arrays
- optimisation: better clipping for multi-component widgets
- optimisation: specialize for height based clipping first (assume widgets never go up + height tests before width tests?)
- optimisation/portability: provide ImVector style implementation
- optimisation/portability: remove dependency on <algorithm>
*/
#include "imgui.h"
#include <ctype.h> // toupper
#include <math.h> // sqrt
#include <stdint.h> // intptr_t
#include <stdio.h> // vsnprintf
#include <string.h> // memset
#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
//-------------------------------------------------------------------------
// Forward Declarations
//-------------------------------------------------------------------------
namespace ImGui
{
static bool ButtonBehaviour(const ImGuiAabb& bb, const ImGuiID& id, bool* out_hovered = NULL, bool* out_held = NULL, bool repeat = false);
static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);
static void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, const bool hide_text_after_hash = true);
static ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, const bool hide_text_after_hash = true);
static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL);
static void ItemSize(ImVec2 size, ImVec2* adjust_start_offset = NULL);
static void ItemSize(const ImGuiAabb& aabb, ImVec2* adjust_start_offset = NULL);
static void PushColumnClipRect(int column_index = -1);
static bool IsClipped(const ImGuiAabb& aabb);
static bool ClipAdvance(const ImGuiAabb& aabb);
static bool IsMouseHoveringBox(const ImGuiAabb& box);
static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
static bool CloseWindowButton(bool* open = NULL);
static void FocusWindow(ImGuiWindow* window);
static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs);
}; // namespace ImGui
//-----------------------------------------------------------------------------
// Platform dependant helpers
//-----------------------------------------------------------------------------
#ifdef _MSC_VER
#ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS
static const char* GetClipboardTextFn_DefaultImplWindows();
static void SetClipboardTextFn_DefaultImplWindows(const char* text, const char* text_end);
#endif
#endif
//-----------------------------------------------------------------------------
// User facing structures
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
WindowPadding = ImVec2(8,8); // Padding within a window
WindowMinSize = ImVec2(48,48); // Minimum window size
FramePadding = ImVec2(5,4); // Padding within a framed rectangle (used by most widgets)
ItemSpacing = ImVec2(10,5); // Horizontal and vertical spacing between widgets
ItemInnerSpacing = ImVec2(5,5); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand bounding box for touch-based system where touch position is not accurate enough (unnecessary for mouse inputs). Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget running. So dont grow this too much!
AutoFitPadding = ImVec2(8,8); // Extra space after auto-fit (double-clicking on resize grip)
WindowFillAlphaDefault = 0.70f;
WindowRounding = 10.0f;
TreeNodeSpacing = 22.0f;
ColumnsMinSpacing = 6.0f; // Minimum space between two columns
ScrollBarWidth = 16.0f;
Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
Colors[ImGuiCol_Border] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f);
Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input
Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f);
Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.40f, 0.40f, 0.80f, 0.15f);
Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);
Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f);
Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f);
Colors[ImGuiCol_CheckHovered] = ImVec4(0.60f, 0.40f, 0.40f, 0.45f);
Colors[ImGuiCol_CheckActive] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);
Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f);
Colors[ImGuiCol_ButtonHovered] = ImVec4(0.60f, 0.40f, 0.40f, 1.00f);
Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);
Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);
Colors[ImGuiCol_HeaderActive] = ImVec4(0.60f, 0.60f, 0.80f, 1.00f);
Colors[ImGuiCol_Column] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
Colors[ImGuiCol_ColumnHovered] = ImVec4(0.60f, 0.40f, 0.40f, 1.00f);
Colors[ImGuiCol_ColumnActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f);
Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);
Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f);
Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f);
Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f);
Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f);
Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f);
Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
Colors[ImGuiCol_TooltipBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f);
}
ImGuiIO::ImGuiIO()
{
memset(this, 0, sizeof(*this));
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
Font = NULL;
FontAllowScaling = false;
PixelCenterOffset = 0.5f;
MousePos = ImVec2(-1,-1);
MousePosPrev = ImVec2(-1,-1);
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
// Platform dependant default implementations
#ifdef _MSC_VER
#ifndef IMGUI_DONT_IMPLEMENT_WINDOWS_CLIPBOARD_FUNCTIONS
GetClipboardTextFn = GetClipboardTextFn_DefaultImplWindows;
SetClipboardTextFn = SetClipboardTextFn_DefaultImplWindows;
#endif
#endif
}
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the VM_CHAR message
void ImGuiIO::AddInputCharacter(char c)
{
const size_t n = strlen(InputCharacters);
if (n < sizeof(InputCharacters) / sizeof(InputCharacters[0]))
{
InputCharacters[n] = c;
InputCharacters[n+1] = 0;
}
}
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR)))
#undef PI
const float PI = 3.14159265358979323846f;
#ifdef INT_MAX
#define IM_INT_MAX INT_MAX
#else
#define IM_INT_MAX 2147483647
#endif
// Math bits
// We are keeping those static in the .cpp file so as not to leak them outside, in the case the user has implicit cast operators between ImVec2 and its own types.
static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); }
static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); }
static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); }
static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); }
static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); }
static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); }
static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }
static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }
static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; }
static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; }
static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; }
static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; }
static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; }
static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; }
static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); }
static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); }
static inline float ImClamp(float f, float mn, float mx) { return (f < mn) ? mn : (f > mx) ? mx : f; }
static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); }
static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }
static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; }
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t) { return a + (b - a) * t; }
static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); }
static inline float ImLength(const ImVec2& lhs) { return sqrt(lhs.x*lhs.x + lhs.y*lhs.y); }
static int ImStricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
return d;
}
static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end)
{
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = (char)toupper(*needle);
while (*haystack)
{
if (toupper(*haystack) == un0)
{
const char* b = needle + 1;
for (const char* a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
static ImU32 crc32(const void* data, size_t data_size, ImU32 seed = 0)
{
static ImU32 crc32_lut[256] = { 0 };
if (!crc32_lut[1])
{
const ImU32 polynomial = 0xEDB88320;
for (ImU32 i = 0; i < 256; i++)
{
ImU32 crc = i;
for (ImU32 j = 0; j < 8; j++)
crc = (crc >> 1) ^ (-int(crc & 1) & polynomial);
crc32_lut[i] = crc;
}
}
ImU32 crc = ~seed;
const unsigned char* current = (const unsigned char*)data;
while (data_size--)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
return ~crc;
}
static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
int w = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
buf[buf_size-1] = 0;
if (w == -1) w = (int)buf_size;
return w;
}
static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
int w = vsnprintf(buf, buf_size, fmt, args);
buf[buf_size-1] = 0;
if (w == -1) w = (int)buf_size;
return w;
}
static ImU32 ImConvertColorFloat4ToU32(const ImVec4& in)
{
ImU32 out = ((ImU32)(ImSaturate(in.x)*255.f));
out |= ((ImU32)(ImSaturate(in.y)*255.f) << 8);
out |= ((ImU32)(ImSaturate(in.z)*255.f) << 16);
out |= ((ImU32)(ImSaturate(in.w)*255.f) << 24);
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
static void ImConvertColorRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
{
float K = 0.f;
if (g < b)
{
const float tmp = g; g = b; b = tmp;
K = -1.f;
}
if (r < g)
{
const float tmp = r; r = g; g = tmp;
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
static void ImConvertColorHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
{
if (s == 0.0f)
{
// gray
out_r = out_g = out_b = v;
return;
}
h = fmodf(h, 1.0f) / (60.0f/360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i)
{
case 0: out_r = v; out_g = t; out_b = p; break;
case 1: out_r = q; out_g = v; out_b = p; break;
case 2: out_r = p; out_g = v; out_b = t; break;
case 3: out_r = p; out_g = q; out_b = v; break;
case 4: out_r = t; out_g = p; out_b = v; break;
case 5: default: out_r = v; out_g = p; out_b = q; break;
}
}
//-----------------------------------------------------------------------------
struct ImGuiColMod // Color/style modifier, backup of modified data so we can restore it
{
ImGuiCol Col;
ImVec4 PreviousValue;
};
struct ImGuiAabb // 2D axis aligned bounding-box
{
ImVec2 Min;
ImVec2 Max;
ImGuiAabb() { Min = ImVec2(FLT_MAX,FLT_MAX); Max = ImVec2(-FLT_MAX,-FLT_MAX); }
ImGuiAabb(const ImVec2& min, const ImVec2& max) { Min = min; Max = max; }
ImGuiAabb(const ImVec4& v) { Min.x = v.x; Min.y = v.y; Max.x = v.z; Max.y = v.w; }
ImGuiAabb(float x1, float y1, float x2, float y2) { Min.x = x1; Min.y = y1; Max.x = x2; Max.y = y2; }
ImVec2 GetCenter() const { return Min + (Max-Min)*0.5f; }
ImVec2 GetSize() const { return Max-Min; }
float GetWidth() const { return (Max-Min).x; }
float GetHeight() const { return (Max-Min).y; }
ImVec2 GetTL() const { return Min; }
ImVec2 GetTR() const { return ImVec2(Max.x,Min.y); }
ImVec2 GetBL() const { return ImVec2(Min.x,Max.y); }
ImVec2 GetBR() const { return Max; }
bool Contains(ImVec2 p) const { return p.x >= Min.x && p.y >= Min.y && p.x <= Max.x && p.y <= Max.y; }
bool Contains(const ImGuiAabb& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; }
bool Overlaps(const ImGuiAabb& r) const { return r.Min.y <= Max.y && r.Max.y >= Min.y && r.Min.x <= Max.x && r.Max.x >= Min.x; }
void Expand(ImVec2 sz) { Min -= sz; Max += sz; }
void Clip(const ImGuiAabb& clip) { Min.x = ImMax(Min.x, clip.Min.x); Min.y = ImMax(Min.y, clip.Min.y); Max.x = ImMin(Max.x, clip.Max.x); Max.y = ImMin(Max.y, clip.Max.y); }
};
// Temporary per-window data, reset at the beginning of the frame
struct ImGuiDrawContext
{
ImVec2 CursorPos;
ImVec2 CursorPosPrevLine;
ImVec2 CursorStartPos;
float CurrentLineHeight;
float PrevLineHeight;
float LogLineHeight;
int TreeDepth;
ImGuiAabb LastItemAabb;
bool LastItemHovered;
ImVector<ImGuiWindow*> ChildWindows;
ImVector<bool> AllowKeyboardFocus;
ImVector<float> ItemWidth;
ImVector<ImGuiColMod> ColorModifiers;
ImGuiColorEditMode ColorEditMode;
ImGuiStorage* StateStorage;
int OpenNextNode;
float ColumnStartX;
int ColumnCurrent;
int ColumnsCount;
bool ColumnsShowBorders;
ImVec2 ColumnsStartCursorPos;
ImGuiID ColumnsSetID;
ImGuiDrawContext()
{
CursorPos = CursorPosPrevLine = CursorStartPos = ImVec2(0.0f, 0.0f);
CurrentLineHeight = PrevLineHeight = 0.0f;
LogLineHeight = -1.0f;
TreeDepth = 0;
LastItemAabb = ImGuiAabb(0.0f,0.0f,0.0f,0.0f);
LastItemHovered = false;
StateStorage = NULL;
OpenNextNode = -1;
ColumnStartX = 0.0f;
ColumnCurrent = 0;
ColumnsCount = 1;
ColumnsShowBorders = true;
ColumnsStartCursorPos = ImVec2(0,0);
}
};
struct ImGuiTextEditState;
#define STB_TEXTEDIT_STRING ImGuiTextEditState
#define STB_TEXTEDIT_CHARTYPE char
#include "stb_textedit.h"
// State of the currently focused/edited text input box
struct ImGuiTextEditState
{
char Text[1024]; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so own buffer.
char InitialText[1024]; // backup of end-user buffer at focusing time, to ESC key can do a revert. Also used for arithmetic operations (but could use a pre-parsed float there).
size_t BufSize; // end-user buffer size, <= 1024 (or increase above)
float Width; // widget width
float ScrollX;
STB_TexteditState StbState;
float CursorAnim;
bool SelectedAllMouseLock;
ImFont Font;
float FontSize;
ImGuiTextEditState() { memset(this, 0, sizeof(*this)); }
void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
bool CursorIsVisible() const { return CursorAnim <= 0.0f || fmodf(CursorAnim, 1.20f) <= 0.80f; } // Blinking
bool HasSelection() const { return StbState.select_start != StbState.select_end; }
void SelectAll() { StbState.select_start = 0; StbState.select_end = (int)strlen(Text); StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; }
void OnKeyboardPressed(int key);
void UpdateScrollOffset();
ImVec2 CalcDisplayOffsetFromCharIdx(int i) const;
// Static functions because they are used to render non-focused instances of a text input box
static const char* GetTextPointerClipped(ImFont font, float font_size, const char* text, float width, ImVec2* out_text_size = NULL);
static void RenderTextScrolledClipped(ImFont font, float font_size, const char* text, ImVec2 pos_base, float width, float scroll_x);
};
struct ImGuiIniData
{
char* Name;
ImVec2 Pos;
ImVec2 Size;
bool Collapsed;
ImGuiIniData() { memset(this, 0, sizeof(*this)); }
~ImGuiIniData() { if (Name) { free(Name); Name = NULL; } }
};
struct ImGuiState
{
bool Initialized;
ImGuiIO IO;
ImGuiStyle Style;
float Time;
int FrameCount;
int FrameCountRendered;
ImVector<ImGuiWindow*> Windows;
ImGuiWindow* CurrentWindow; // Being drawn into
ImVector<ImGuiWindow*> CurrentWindowStack;
ImGuiWindow* FocusedWindow; // Will catch keyboard inputs
ImGuiWindow* HoveredWindow; // Will catch mouse inputs
ImGuiWindow* HoveredWindowExcludingChilds; // Will catch mouse inputs (for focus/move only)
ImGuiID HoveredId;
ImGuiID ActiveId;
ImGuiID ActiveIdPreviousFrame;
bool ActiveIdIsAlive;
float SettingsDirtyTimer;
ImVector<ImGuiIniData*> Settings;
ImVec2 NewWindowDefaultPos;
// Render
ImVector<ImDrawList*> RenderDrawLists;
// Widget state
ImGuiTextEditState InputTextState;
ImGuiID SliderAsInputTextId;
ImGuiStorage ColorEditModeStorage; // for user selection
ImGuiID ActiveComboID;
char Tooltip[1024];
// Logging
bool LogEnabled;
FILE* LogFile;
ImGuiTextBuffer LogClipboard;
int LogAutoExpandMaxDepth;
ImGuiState()
{
Initialized = false;
Time = 0.0f;
FrameCount = 0;
FrameCountRendered = -1;
CurrentWindow = NULL;
FocusedWindow = NULL;
HoveredWindow = NULL;
HoveredWindowExcludingChilds = NULL;
ActiveIdIsAlive = false;
SettingsDirtyTimer = 0.0f;
NewWindowDefaultPos = ImVec2(60, 60);
SliderAsInputTextId = 0;
ActiveComboID = 0;
memset(Tooltip, 0, sizeof(Tooltip));
LogEnabled = false;
LogFile = NULL;
LogAutoExpandMaxDepth = 2;
}
};
static ImGuiState GImGui;
struct ImGuiWindow
{
char* Name;
ImGuiID ID;
ImGuiWindowFlags Flags;
ImVec2 PosFloat;
ImVec2 Pos; // Position rounded-up to nearest pixel
ImVec2 Size; // Current size (==SizeFull or collapsed title bar size)
ImVec2 SizeFull; // Size when non collapsed
ImVec2 SizeContentsFit; // Size of contents (extents reach by the drawing cursor) - may not fit within Size.
float ScrollY;
float NextScrollY;
bool ScrollbarY;
bool Visible;
bool Collapsed;
bool Accessed;
int AutoFitFrames;
ImGuiDrawContext DC;
ImVector<ImGuiID> IDStack;
ImVector<ImVec4> ClipRectStack;
int LastFrameDrawn;
float ItemWidthDefault;
ImGuiStorage StateStorage;
float FontScale;
int FocusIdxCounter; // Start at -1 and increase as assigned via FocusItemRegister()
int FocusIdxRequestCurrent; // Item being requested for focus, rely on layout to be stable between the frame pressing TAB and the next frame
int FocusIdxRequestNext; // Item being requested for focus, for next update
ImDrawList* DrawList;
public:
ImGuiWindow(const char* name, ImVec2 default_pos, ImVec2 default_size);
~ImGuiWindow();
ImGuiID GetID(const char* str);
ImGuiID GetID(const void* ptr);
void AddToRenderList();
bool FocusItemRegister(bool is_active, int* out_idx = NULL); // Return TRUE if focus is requested
void FocusItemUnregister();
ImGuiAabb Aabb() const { return ImGuiAabb(Pos, Pos+Size); }
ImFont Font() const { return GImGui.IO.Font; }
float FontSize() const { return GImGui.IO.FontHeight * FontScale; }
ImVec2 CursorPos() const { return DC.CursorPos; }
float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0 : FontSize() + GImGui.Style.FramePadding.y * 2.0f; }
ImGuiAabb TitleBarAabb() const { return ImGuiAabb(Pos, Pos + ImVec2(SizeFull.x, TitleBarHeight())); }
ImVec2 WindowPadding() const { return ((Flags & ImGuiWindowFlags_ChildWindow) && !(Flags & ImGuiWindowFlags_ShowBorders)) ? ImVec2(1,1) : GImGui.Style.WindowPadding; }
ImU32 Color(ImGuiCol idx, float a=1.f) const { ImVec4 c = GImGui.Style.Colors[idx]; c.w *= a; return ImConvertColorFloat4ToU32(c); }
};
static ImGuiWindow* GetCurrentWindow()
{
IM_ASSERT(GImGui.CurrentWindow != NULL); // ImGui::NewFrame() hasn't been called yet?
GImGui.CurrentWindow->Accessed = true;
return GImGui.CurrentWindow;
}
static void RegisterAliveId(const ImGuiID& id)
{
if (GImGui.ActiveId == id)
GImGui.ActiveIdIsAlive = true;
}
//-----------------------------------------------------------------------------
void ImGuiStorage::Clear()
{
Data.clear();
}
// std::lower_bound but without the bullshit
static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImU32 key)
{
ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
ImVector<ImGuiStorage::Pair>::iterator last = data.end();
int count = (int)(last - first);
while (count > 0)
{
int count2 = count / 2;
ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
int* ImGuiStorage::Find(ImU32 key)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end())
return NULL;
if (it->key != key)
return NULL;
return &it->val;
}
int ImGuiStorage::GetInt(ImU32 key, int default_val)
{
int* pval = Find(key);
if (!pval)
return default_val;
return *pval;
}
// FIXME-OPT: We are wasting time because all SetInt() are preceeded by GetInt() calls so we should have the result from lower_bound already in place.
// However we only use SetInt() on explicit user action (so that's maximum once a frame) so the optimisation isn't much needed.
void ImGuiStorage::SetInt(ImU32 key, int val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it != Data.end() && it->key == key)
{
it->val = val;
}
else
{
Pair pair_key;
pair_key.key = key;
pair_key.val = val;
Data.insert(it, pair_key);
}
}
void ImGuiStorage::SetAllInt(int v)
{
for (size_t i = 0; i < Data.size(); i++)
Data[i].val = v;
}
//-----------------------------------------------------------------------------
ImGuiTextFilter::ImGuiTextFilter()
{
InputBuf[0] = 0;
CountGrep = 0;
}
void ImGuiTextFilter::Draw(const char* label, float width)
{
ImGuiWindow* window = GetCurrentWindow();
if (width < 0.0f)
{
ImVec2 label_size = ImGui::CalcTextSize(label, NULL);
width = ImMax(window->Pos.x + ImGui::GetWindowContentRegionMax().x - window->DC.CursorPos.x - (label_size.x + GImGui.Style.ItemSpacing.x*4), 10.0f);
}
ImGui::PushItemWidth(width);
ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
ImGui::PopItemWidth();
Build();
}
void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out)
{
out.resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out.push_back(TextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out.push_back(TextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', Filters);
CountGrep = 0;
for (size_t i = 0; i != Filters.size(); i++)
{
Filters[i].trim_blanks();
if (Filters[i].empty())
continue;
if (Filters[i].front() != '-')
CountGrep += 1;
}
}
bool ImGuiTextFilter::PassFilter(const char* val) const
{
if (Filters.empty())
return true;
if (val == NULL)
val = "";
for (size_t i = 0; i != Filters.size(); i++)
{
const TextRange& f = Filters[i];
if (f.empty())
continue;
if (f.front() == '-')
{
// Subtract
if (ImStristr(val, f.begin()+1, f.end()) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(val, f.begin(), f.end()) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
void ImGuiTextBuffer::append(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
int len = vsnprintf(NULL, 0, fmt, args);
va_end(args);
if (len <= 0)
return;
const size_t write_off = Buf.size();
if (write_off + len >= Buf.capacity())
Buf.reserve(Buf.capacity() * 2);
Buf.resize(write_off + (size_t)len);
va_start(args, fmt);
ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
ImGuiWindow::ImGuiWindow(const char* name, ImVec2 default_pos, ImVec2 default_size)
{
Name = strdup(name);
ID = GetID(name);
IDStack.push_back(ID);
PosFloat = default_pos;
Pos = ImVec2((float)(int)PosFloat.x, (float)(int)PosFloat.y);
Size = SizeFull = default_size;
SizeContentsFit = ImVec2(0.0f, 0.0f);
ScrollY = 0.0f;
NextScrollY = 0.0f;
ScrollbarY = false;
Visible = false;
Collapsed = false;
AutoFitFrames = -1;
LastFrameDrawn = -1;
ItemWidthDefault = 0.0f;
FontScale = 1.0f;
if (ImLength(Size) < 0.001f)
AutoFitFrames = 3;
FocusIdxCounter = -1;
FocusIdxRequestCurrent = IM_INT_MAX;
FocusIdxRequestNext = IM_INT_MAX;
DrawList = new ImDrawList();
}
ImGuiWindow::~ImGuiWindow()
{
delete DrawList;
DrawList = NULL;
free(Name);
Name = NULL;
}
ImGuiID ImGuiWindow::GetID(const char* str)
{
const ImGuiID seed = IDStack.empty() ? 0 : IDStack.back();
const ImGuiID id = crc32(str, strlen(str), seed);
RegisterAliveId(id);
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
const ImGuiID seed = IDStack.empty() ? 0 : IDStack.back();
const ImGuiID id = crc32(&ptr, sizeof(void*), seed);
RegisterAliveId(id);
return id;
}
bool ImGuiWindow::FocusItemRegister(bool is_active, int* out_idx)
{
FocusIdxCounter++;
if (out_idx)
*out_idx = FocusIdxCounter;
ImGuiState& g = GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (!window->DC.AllowKeyboardFocus.back())
return false;
// Process input at this point: TAB, Shift-TAB switch focus
if (FocusIdxRequestNext == IM_INT_MAX && is_active && ImGui::IsKeyPressedMap(ImGuiKey_Tab))
{
// Modulo on index will be applied at the end of frame once we've got the total counter of items.
FocusIdxRequestNext = FocusIdxCounter + (g.IO.KeyShift ? -1 : +1);
}
const bool focus_requested = (FocusIdxCounter == FocusIdxRequestCurrent);
return focus_requested;
}
void ImGuiWindow::FocusItemUnregister()
{
FocusIdxCounter--;
}
void ImGuiWindow::AddToRenderList()
{
ImGuiState& g = GImGui;