forked from SFML/imgui-sfml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imgui-SFML.cpp
1360 lines (1180 loc) · 49.5 KB
/
imgui-SFML.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
#include "imgui-SFML.h"
#include <imgui.h>
#include <SFML/Config.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderTexture.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/Window/Clipboard.hpp>
#include <SFML/Window/Cursor.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Touch.hpp>
#include <SFML/Window/Window.hpp>
#include <cassert>
#include <cmath> // abs
#include <cstddef> // offsetof, nullptr, size_t
#include <cstdint> // uint8_t
#include <cstring> // memcpy
#include <algorithm>
#include <memory>
#include <vector>
#if defined(__APPLE__)
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#ifdef ANDROID
#ifdef USE_JNI
#include <SFML/System/NativeActivity.hpp>
#include <android/native_activity.h>
#include <jni.h>
int openKeyboardIME() {
ANativeActivity* activity = sf::getNativeActivity();
JavaVM* vm = activity->vm;
JNIEnv* env = activity->env;
JavaVMAttachArgs attachargs;
attachargs.version = JNI_VERSION_1_6;
attachargs.name = "NativeThread";
attachargs.group = nullptr;
jint res = vm->AttachCurrentThread(&env, &attachargs);
if (res == JNI_ERR) return EXIT_FAILURE;
jclass natact = env->FindClass("android/app/NativeActivity");
jclass context = env->FindClass("android/content/Context");
jfieldID fid = env->GetStaticFieldID(context, "INPUT_METHOD_SERVICE", "Ljava/lang/String;");
jobject svcstr = env->GetStaticObjectField(context, fid);
jmethodID getss =
env->GetMethodID(natact, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
jobject imm_obj = env->CallObjectMethod(activity->clazz, getss, svcstr);
jclass imm_cls = env->GetObjectClass(imm_obj);
jmethodID toggleSoftInput = env->GetMethodID(imm_cls, "toggleSoftInput", "(II)V");
env->CallVoidMethod(imm_obj, toggleSoftInput, 2, 0);
env->DeleteLocalRef(imm_obj);
env->DeleteLocalRef(imm_cls);
env->DeleteLocalRef(svcstr);
env->DeleteLocalRef(context);
env->DeleteLocalRef(natact);
vm->DetachCurrentThread();
return EXIT_SUCCESS;
}
int closeKeyboardIME() {
ANativeActivity* activity = sf::getNativeActivity();
JavaVM* vm = activity->vm;
JNIEnv* env = activity->env;
JavaVMAttachArgs attachargs;
attachargs.version = JNI_VERSION_1_6;
attachargs.name = "NativeThread";
attachargs.group = nullptr;
jint res = vm->AttachCurrentThread(&env, &attachargs);
if (res == JNI_ERR) return EXIT_FAILURE;
jclass natact = env->FindClass("android/app/NativeActivity");
jclass context = env->FindClass("android/content/Context");
jfieldID fid = env->GetStaticFieldID(context, "INPUT_METHOD_SERVICE", "Ljava/lang/String;");
jobject svcstr = env->GetStaticObjectField(context, fid);
jmethodID getss =
env->GetMethodID(natact, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
jobject imm_obj = env->CallObjectMethod(activity->clazz, getss, svcstr);
jclass imm_cls = env->GetObjectClass(imm_obj);
jmethodID toggleSoftInput = env->GetMethodID(imm_cls, "toggleSoftInput", "(II)V");
env->CallVoidMethod(imm_obj, toggleSoftInput, 1, 0);
env->DeleteLocalRef(imm_obj);
env->DeleteLocalRef(imm_cls);
env->DeleteLocalRef(svcstr);
env->DeleteLocalRef(context);
env->DeleteLocalRef(natact);
vm->DetachCurrentThread();
return EXIT_SUCCESS;
}
#endif
#endif
static_assert(sizeof(GLuint) <= sizeof(ImTextureID),
"ImTextureID is not large enough to fit GLuint.");
namespace {
// various helper functions
ImColor toImColor(sf::Color c);
ImVec2 getTopLeftAbsolute(const sf::FloatRect& rect);
ImVec2 getDownRightAbsolute(const sf::FloatRect& rect);
ImTextureID convertGLTextureHandleToImTextureID(GLuint glTextureHandle);
GLuint convertImTextureIDToGLTextureHandle(ImTextureID textureID);
void RenderDrawLists(ImDrawData* draw_data); // rendering callback function prototype
// Default mapping is XInput gamepad mapping
void initDefaultJoystickMapping();
// Returns first id of connected joystick
unsigned int getConnectedJoystickId();
void updateJoystickButtonState(ImGuiIO& io);
void updateJoystickDPadState(ImGuiIO& io);
void updateJoystickAxisState(ImGuiIO& io);
// clipboard functions
void setClipboardText(void* userData, const char* text);
const char* getClipboardText(void* userData);
std::string s_clipboardText;
// mouse cursors
void loadMouseCursor(ImGuiMouseCursor imguiCursorType, sf::Cursor::Type sfmlCursorType);
void updateMouseCursor(sf::Window& window);
// Key mappings
ImGuiKey keycodeToImGuiKey(sf::Keyboard::Key code);
ImGuiKey keycodeToImGuiMod(sf::Keyboard::Key code);
// data
constexpr unsigned int NULL_JOYSTICK_ID = sf::Joystick::Count;
struct StickInfo {
sf::Joystick::Axis xAxis{sf::Joystick::X};
sf::Joystick::Axis yAxis{sf::Joystick::Y};
bool xInverted{false};
bool yInverted{false};
float threshold{15};
};
struct TriggerInfo {
sf::Joystick::Axis axis{sf::Joystick::Z};
float threshold{0};
};
struct WindowContext {
const sf::Window* window;
ImGuiContext* imContext{ImGui::CreateContext()};
sf::Texture fontTexture; // internal font atlas which is used if user doesn't set a custom
// sf::Texture.
bool windowHasFocus;
bool mouseMoved{false};
bool mousePressed[3] = {false};
ImGuiMouseCursor lastCursor{ImGuiMouseCursor_COUNT};
bool touchDown[3] = {false};
sf::Vector2i touchPos;
unsigned int joystickId{getConnectedJoystickId()};
ImGuiKey joystickMapping[sf::Joystick::ButtonCount] = {ImGuiKey_None};
StickInfo dPadInfo;
StickInfo lStickInfo;
StickInfo rStickInfo;
TriggerInfo lTriggerInfo;
TriggerInfo rTriggerInfo;
sf::Cursor mouseCursors[ImGuiMouseCursor_COUNT];
bool mouseCursorLoaded[ImGuiMouseCursor_COUNT] = {ImGuiKey_None};
#ifdef ANDROID
#ifdef USE_JNI
bool wantTextInput{false};
#endif
#endif
WindowContext(const sf::Window* w) : window(w), windowHasFocus(window->hasFocus()) {}
~WindowContext() { ImGui::DestroyContext(imContext); }
WindowContext(const WindowContext&) = delete; // non construction-copyable
WindowContext& operator=(const WindowContext&) = delete; // non copyable
};
std::vector<std::unique_ptr<WindowContext>> s_windowContexts;
WindowContext* s_currWindowCtx = nullptr;
} // end of anonymous namespace
namespace ImGui {
namespace SFML {
bool Init(sf::RenderWindow& window, bool loadDefaultFont) {
return Init(window, window, loadDefaultFont);
}
bool Init(sf::Window& window, sf::RenderTarget& target, bool loadDefaultFont) {
return Init(window, sf::Vector2f(target.getSize()), loadDefaultFont);
}
bool Init(sf::Window& window, const sf::Vector2f& displaySize, bool loadDefaultFont) {
s_windowContexts.emplace_back(new WindowContext(&window));
s_currWindowCtx = s_windowContexts.back().get();
ImGui::SetCurrentContext(s_currWindowCtx->imContext);
ImGuiIO& io = ImGui::GetIO();
// tell ImGui which features we support
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;
io.BackendPlatformName = "imgui_impl_sfml";
s_currWindowCtx->joystickId = getConnectedJoystickId();
initDefaultJoystickMapping();
// init rendering
io.DisplaySize = ImVec2(displaySize.x, displaySize.y);
// clipboard
io.SetClipboardTextFn = setClipboardText;
io.GetClipboardTextFn = getClipboardText;
// load mouse cursors
loadMouseCursor(ImGuiMouseCursor_Arrow, sf::Cursor::Arrow);
loadMouseCursor(ImGuiMouseCursor_TextInput, sf::Cursor::Text);
loadMouseCursor(ImGuiMouseCursor_ResizeAll, sf::Cursor::SizeAll);
loadMouseCursor(ImGuiMouseCursor_ResizeNS, sf::Cursor::SizeVertical);
loadMouseCursor(ImGuiMouseCursor_ResizeEW, sf::Cursor::SizeHorizontal);
loadMouseCursor(ImGuiMouseCursor_ResizeNESW, sf::Cursor::SizeBottomLeftTopRight);
loadMouseCursor(ImGuiMouseCursor_ResizeNWSE, sf::Cursor::SizeTopLeftBottomRight);
loadMouseCursor(ImGuiMouseCursor_Hand, sf::Cursor::Hand);
if (loadDefaultFont) {
// this will load default font automatically
// No need to call AddDefaultFont
return UpdateFontTexture();
}
return true;
}
void SetCurrentWindow(const sf::Window& window) {
auto found = std::find_if(s_windowContexts.begin(), s_windowContexts.end(),
[&](std::unique_ptr<WindowContext>& ctx) {
return ctx->window->getSystemHandle() == window.getSystemHandle();
});
assert(found != s_windowContexts.end() &&
"Failed to find the window. Forgot to call ImGui::SFML::Init for the window?");
s_currWindowCtx = found->get();
ImGui::SetCurrentContext(s_currWindowCtx->imContext);
}
void ProcessEvent(const sf::Window& window, const sf::Event& event) {
SetCurrentWindow(window);
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
ProcessEvent(event);
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
}
void ProcessEvent(const sf::Event& event) {
assert(s_currWindowCtx && "No current window is set - forgot to call ImGui::SFML::Init?");
ImGuiIO& io = ImGui::GetIO();
if (s_currWindowCtx->windowHasFocus) {
switch (event.type) {
case sf::Event::Resized:
io.DisplaySize =
ImVec2(static_cast<float>(event.size.width), static_cast<float>(event.size.height));
break;
case sf::Event::MouseMoved:
io.AddMousePosEvent(static_cast<float>(event.mouseMove.x),
static_cast<float>(event.mouseMove.y));
s_currWindowCtx->mouseMoved = true;
break;
case sf::Event::MouseButtonPressed: // fall-through
case sf::Event::MouseButtonReleased: {
const int button = event.mouseButton.button;
if (button >= 0 && button < 3) {
if (event.type == sf::Event::MouseButtonPressed) {
s_currWindowCtx->mousePressed[event.mouseButton.button] = true;
io.AddMouseButtonEvent(button, true);
} else {
io.AddMouseButtonEvent(button, false);
}
}
} break;
case sf::Event::TouchBegan: // fall-through
case sf::Event::TouchEnded: {
s_currWindowCtx->mouseMoved = false;
const unsigned int button = event.touch.finger;
if (event.type == sf::Event::TouchBegan && button < 3) {
s_currWindowCtx->touchDown[event.touch.finger] = true;
}
} break;
case sf::Event::MouseWheelScrolled:
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel ||
(event.mouseWheelScroll.wheel == sf::Mouse::HorizontalWheel && io.KeyShift)) {
io.AddMouseWheelEvent(0, event.mouseWheelScroll.delta);
} else if (event.mouseWheelScroll.wheel == sf::Mouse::HorizontalWheel) {
io.AddMouseWheelEvent(event.mouseWheelScroll.delta, 0);
}
break;
case sf::Event::KeyPressed: // fall-through
case sf::Event::KeyReleased: {
const bool down = (event.type == sf::Event::KeyPressed);
const ImGuiKey mod = keycodeToImGuiMod(event.key.code);
// The modifier booleans are not reliable when it's the modifier
// itself that's being pressed. Detect these presses directly.
if (mod != ImGuiKey_None) {
io.AddKeyEvent(mod, down);
} else {
io.AddKeyEvent(ImGuiKey_ModCtrl, event.key.control);
io.AddKeyEvent(ImGuiKey_ModShift, event.key.shift);
io.AddKeyEvent(ImGuiKey_ModAlt, event.key.alt);
io.AddKeyEvent(ImGuiKey_ModSuper, event.key.system);
}
const ImGuiKey key = keycodeToImGuiKey(event.key.code);
io.AddKeyEvent(key, down);
io.SetKeyEventNativeData(key, event.key.code, -1);
} break;
case sf::Event::TextEntered:
// Don't handle the event for unprintable characters
if (event.text.unicode < ' ' || event.text.unicode == 127) {
break;
}
io.AddInputCharacter(event.text.unicode);
break;
case sf::Event::JoystickConnected:
if (s_currWindowCtx->joystickId == NULL_JOYSTICK_ID) {
s_currWindowCtx->joystickId = event.joystickConnect.joystickId;
}
break;
case sf::Event::JoystickDisconnected:
if (s_currWindowCtx->joystickId == event.joystickConnect.joystickId) { // used gamepad
// was
// disconnected
s_currWindowCtx->joystickId = getConnectedJoystickId();
}
break;
default:
break;
}
}
switch (event.type) {
case sf::Event::LostFocus: {
io.AddFocusEvent(false);
s_currWindowCtx->windowHasFocus = false;
} break;
case sf::Event::GainedFocus:
io.AddFocusEvent(true);
s_currWindowCtx->windowHasFocus = true;
break;
default:
break;
}
}
void Update(sf::RenderWindow& window, sf::Time dt) {
Update(window, window, dt);
}
void Update(sf::Window& window, sf::RenderTarget& target, sf::Time dt) {
SetCurrentWindow(window);
assert(s_currWindowCtx);
// Update OS/hardware mouse cursor if imgui isn't drawing a software cursor
const ImGuiMouseCursor mouse_cursor =
ImGui::GetIO().MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
if (s_currWindowCtx->lastCursor != mouse_cursor) {
s_currWindowCtx->lastCursor = mouse_cursor;
updateMouseCursor(window);
}
if (!s_currWindowCtx->mouseMoved) {
if (sf::Touch::isDown(0)) s_currWindowCtx->touchPos = sf::Touch::getPosition(0, window);
Update(s_currWindowCtx->touchPos, sf::Vector2f(target.getSize()), dt);
} else {
Update(sf::Mouse::getPosition(window), sf::Vector2f(target.getSize()), dt);
}
}
void Update(const sf::Vector2i& mousePos, const sf::Vector2f& displaySize, sf::Time dt) {
assert(s_currWindowCtx && "No current window is set - forgot to call ImGui::SFML::Init?");
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2(displaySize.x, displaySize.y);
io.DeltaTime = dt.asSeconds();
if (s_currWindowCtx->windowHasFocus) {
if (io.WantSetMousePos) {
const sf::Vector2i newMousePos(static_cast<int>(io.MousePos.x),
static_cast<int>(io.MousePos.y));
sf::Mouse::setPosition(newMousePos);
} else {
io.MousePos = ImVec2(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y));
}
for (unsigned int i = 0; i < 3; i++) {
io.MouseDown[i] = s_currWindowCtx->touchDown[i] || sf::Touch::isDown(i) ||
s_currWindowCtx->mousePressed[i] ||
sf::Mouse::isButtonPressed((sf::Mouse::Button)i);
s_currWindowCtx->mousePressed[i] = false;
s_currWindowCtx->touchDown[i] = false;
}
}
#ifdef ANDROID
#ifdef USE_JNI
if (io.WantTextInput && !s_currWindowCtx->wantTextInput) {
openKeyboardIME();
s_currWindowCtx->wantTextInput = true;
}
if (!io.WantTextInput && s_currWindowCtx->wantTextInput) {
closeKeyboardIME();
s_currWindowCtx->wantTextInput = false;
}
#endif
#endif
assert(io.Fonts->Fonts.Size > 0); // You forgot to create and set up font
// atlas (see createFontTexture)
// gamepad navigation
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) &&
s_currWindowCtx->joystickId != NULL_JOYSTICK_ID) {
updateJoystickButtonState(io);
updateJoystickDPadState(io);
updateJoystickAxisState(io);
}
ImGui::NewFrame();
}
void Render(sf::RenderWindow& window) {
SetCurrentWindow(window);
Render(static_cast<sf::RenderTarget&>(window));
}
void Render(sf::RenderTarget& target) {
target.resetGLStates();
target.pushGLStates();
ImGui::Render();
RenderDrawLists(ImGui::GetDrawData());
target.popGLStates();
}
void Render() {
ImGui::Render();
RenderDrawLists(ImGui::GetDrawData());
}
void Shutdown(const sf::Window& window) {
const bool needReplacement =
(s_currWindowCtx->window->getSystemHandle() == window.getSystemHandle());
// remove window's context
auto found = std::find_if(s_windowContexts.begin(), s_windowContexts.end(),
[&](std::unique_ptr<WindowContext>& ctx) {
return ctx->window->getSystemHandle() == window.getSystemHandle();
});
assert(found != s_windowContexts.end() &&
"Window wasn't inited properly: forgot to call ImGui::SFML::Init(window)?");
s_windowContexts.erase(found); // s_currWindowCtx can become invalid here!
// set current context to some window for convenience if needed
if (needReplacement) {
auto it = s_windowContexts.begin();
if (it != s_windowContexts.end()) {
// set to some other window
s_currWindowCtx = it->get();
ImGui::SetCurrentContext(s_currWindowCtx->imContext);
} else {
// no alternatives...
s_currWindowCtx = nullptr;
ImGui::SetCurrentContext(nullptr);
}
}
}
void Shutdown() {
s_currWindowCtx = nullptr;
ImGui::SetCurrentContext(nullptr);
s_windowContexts.clear();
}
bool UpdateFontTexture() {
assert(s_currWindowCtx);
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels = nullptr;
int width = 0;
int height = 0;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
sf::Texture& texture = s_currWindowCtx->fontTexture;
if (!texture.create(static_cast<unsigned>(width), static_cast<unsigned>(height))) {
return false;
}
texture.update(pixels);
ImTextureID texID = convertGLTextureHandleToImTextureID(texture.getNativeHandle());
io.Fonts->SetTexID(texID);
return true;
}
sf::Texture& GetFontTexture() {
assert(s_currWindowCtx);
return s_currWindowCtx->fontTexture;
}
void SetActiveJoystickId(unsigned int joystickId) {
assert(s_currWindowCtx);
assert(joystickId < sf::Joystick::Count);
s_currWindowCtx->joystickId = joystickId;
}
void SetJoystickDPadThreshold(float threshold) {
assert(s_currWindowCtx);
assert(threshold >= 0.f && threshold <= 100.f);
s_currWindowCtx->dPadInfo.threshold = threshold;
}
void SetJoystickLStickThreshold(float threshold) {
assert(s_currWindowCtx);
assert(threshold >= 0.f && threshold <= 100.f);
s_currWindowCtx->lStickInfo.threshold = threshold;
}
void SetJoystickRStickThreshold(float threshold) {
assert(s_currWindowCtx);
assert(threshold >= 0.f && threshold <= 100.f);
s_currWindowCtx->rStickInfo.threshold = threshold;
}
void SetJoystickLTriggerThreshold(float threshold) {
assert(s_currWindowCtx);
assert(threshold >= -100.f && threshold <= 100.f);
s_currWindowCtx->lTriggerInfo.threshold = threshold;
}
void SetJoystickRTriggerThreshold(float threshold) {
assert(s_currWindowCtx);
assert(threshold >= -100.f && threshold <= 100.f);
s_currWindowCtx->rTriggerInfo.threshold = threshold;
}
void SetJoystickMapping(int key, unsigned int joystickButton) {
assert(s_currWindowCtx);
// This function now expects ImGuiKey_* values.
// For partial backwards compatibility, also expect some ImGuiNavInput_* values.
ImGuiKey finalKey{};
switch (key) {
case ImGuiNavInput_Activate:
finalKey = ImGuiKey_GamepadFaceDown;
break;
case ImGuiNavInput_Cancel:
finalKey = ImGuiKey_GamepadFaceRight;
break;
case ImGuiNavInput_Input:
finalKey = ImGuiKey_GamepadFaceUp;
break;
case ImGuiNavInput_Menu:
finalKey = ImGuiKey_GamepadFaceLeft;
break;
case ImGuiNavInput_FocusPrev:
case ImGuiNavInput_TweakSlow:
finalKey = ImGuiKey_GamepadL1;
break;
case ImGuiNavInput_FocusNext:
case ImGuiNavInput_TweakFast:
finalKey = ImGuiKey_GamepadR1;
break;
default:
assert(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END);
finalKey = static_cast<ImGuiKey>(key);
}
assert(joystickButton < sf::Joystick::ButtonCount);
s_currWindowCtx->joystickMapping[joystickButton] = finalKey;
}
void SetDPadXAxis(sf::Joystick::Axis dPadXAxis, bool inverted) {
assert(s_currWindowCtx);
s_currWindowCtx->dPadInfo.xAxis = dPadXAxis;
s_currWindowCtx->dPadInfo.xInverted = inverted;
}
void SetDPadYAxis(sf::Joystick::Axis dPadYAxis, bool inverted) {
assert(s_currWindowCtx);
s_currWindowCtx->dPadInfo.yAxis = dPadYAxis;
s_currWindowCtx->dPadInfo.yInverted = inverted;
}
void SetLStickXAxis(sf::Joystick::Axis lStickXAxis, bool inverted) {
assert(s_currWindowCtx);
s_currWindowCtx->lStickInfo.xAxis = lStickXAxis;
s_currWindowCtx->lStickInfo.xInverted = inverted;
}
void SetLStickYAxis(sf::Joystick::Axis lStickYAxis, bool inverted) {
assert(s_currWindowCtx);
s_currWindowCtx->lStickInfo.yAxis = lStickYAxis;
s_currWindowCtx->lStickInfo.yInverted = inverted;
}
void SetRStickXAxis(sf::Joystick::Axis rStickXAxis, bool inverted) {
assert(s_currWindowCtx);
s_currWindowCtx->rStickInfo.xAxis = rStickXAxis;
s_currWindowCtx->rStickInfo.xInverted = inverted;
}
void SetRStickYAxis(sf::Joystick::Axis rStickYAxis, bool inverted) {
assert(s_currWindowCtx);
s_currWindowCtx->rStickInfo.yAxis = rStickYAxis;
s_currWindowCtx->rStickInfo.yInverted = inverted;
}
void SetLTriggerAxis(sf::Joystick::Axis lTriggerAxis) {
assert(s_currWindowCtx);
s_currWindowCtx->rTriggerInfo.axis = lTriggerAxis;
}
void SetRTriggerAxis(sf::Joystick::Axis rTriggerAxis) {
assert(s_currWindowCtx);
s_currWindowCtx->rTriggerInfo.axis = rTriggerAxis;
}
} // end of namespace SFML
/////////////// Image Overloads for sf::Texture
void Image(const sf::Texture& texture, const sf::Color& tintColor, const sf::Color& borderColor) {
Image(texture, sf::Vector2f(texture.getSize()), tintColor, borderColor);
}
void Image(const sf::Texture& texture, const sf::Vector2f& size, const sf::Color& tintColor,
const sf::Color& borderColor) {
ImTextureID textureID = convertGLTextureHandleToImTextureID(texture.getNativeHandle());
ImGui::Image(textureID, ImVec2(size.x, size.y), ImVec2(0, 0), ImVec2(1, 1),
toImColor(tintColor), toImColor(borderColor));
}
/////////////// Image Overloads for sf::RenderTexture
void Image(const sf::RenderTexture& texture, const sf::Color& tintColor,
const sf::Color& borderColor) {
Image(texture, sf::Vector2f(texture.getSize()), tintColor, borderColor);
}
void Image(const sf::RenderTexture& texture, const sf::Vector2f& size, const sf::Color& tintColor,
const sf::Color& borderColor) {
ImTextureID textureID =
convertGLTextureHandleToImTextureID(texture.getTexture().getNativeHandle());
ImGui::Image(textureID, ImVec2(size.x, size.y), ImVec2(0, 1),
ImVec2(1, 0), // flipped vertically, because textures in sf::RenderTexture are
// stored this way
toImColor(tintColor), toImColor(borderColor));
}
/////////////// Image Overloads for sf::Sprite
void Image(const sf::Sprite& sprite, const sf::Color& tintColor, const sf::Color& borderColor) {
const sf::FloatRect bounds = sprite.getGlobalBounds();
Image(sprite, sf::Vector2f(bounds.width, bounds.height), tintColor, borderColor);
}
void Image(const sf::Sprite& sprite, const sf::Vector2f& size, const sf::Color& tintColor,
const sf::Color& borderColor) {
const sf::Texture* texturePtr = sprite.getTexture();
// sprite without texture cannot be drawn
if (!texturePtr) {
return;
}
const sf::Texture& texture = *texturePtr;
const sf::Vector2f textureSize(texture.getSize());
const sf::FloatRect textureRect(sprite.getTextureRect());
const ImVec2 uv0(textureRect.left / textureSize.x, textureRect.top / textureSize.y);
const ImVec2 uv1((textureRect.left + textureRect.width) / textureSize.x,
(textureRect.top + textureRect.height) / textureSize.y);
ImTextureID textureID = convertGLTextureHandleToImTextureID(texture.getNativeHandle());
ImGui::Image(textureID, ImVec2(size.x, size.y), uv0, uv1, toImColor(tintColor),
toImColor(borderColor));
}
/////////////// Image Button Overloads for sf::Texture
bool ImageButton(const char* id, const sf::Texture& texture, const sf::Vector2f& size,
const sf::Color& bgColor, const sf::Color& tintColor) {
ImTextureID textureID = convertGLTextureHandleToImTextureID(texture.getNativeHandle());
return ImGui::ImageButton(id, textureID, ImVec2(size.x, size.y), ImVec2(0, 0), ImVec2(1, 1),
toImColor(bgColor), toImColor(tintColor));
}
/////////////// Image Button Overloads for sf::RenderTexture
bool ImageButton(const char* id, const sf::RenderTexture& texture, const sf::Vector2f& size,
const sf::Color& bgColor, const sf::Color& tintColor) {
ImTextureID textureID =
convertGLTextureHandleToImTextureID(texture.getTexture().getNativeHandle());
return ImGui::ImageButton(id, textureID, ImVec2(size.x, size.y), ImVec2(0, 1),
ImVec2(1, 0), // flipped vertically, because textures in
// sf::RenderTexture are stored this way
toImColor(bgColor), toImColor(tintColor));
}
/////////////// Image Button Overloads for sf::Sprite
bool ImageButton(const char* id, const sf::Sprite& sprite, const sf::Vector2f& size,
const sf::Color& bgColor, const sf::Color& tintColor) {
const sf::Texture* texturePtr = sprite.getTexture();
// sprite without texture cannot be drawn
if (!texturePtr) {
return false;
}
const sf::Texture& texture = *texturePtr;
const sf::Vector2f textureSize(texture.getSize());
const sf::FloatRect textureRect(sprite.getTextureRect());
const ImVec2 uv0(textureRect.left / textureSize.x, textureRect.top / textureSize.y);
const ImVec2 uv1((textureRect.left + textureRect.width) / textureSize.x,
(textureRect.top + textureRect.height) / textureSize.y);
ImTextureID textureID = convertGLTextureHandleToImTextureID(texture.getNativeHandle());
return ImGui::ImageButton(id, textureID, ImVec2(size.x, size.y), uv0, uv1, toImColor(bgColor),
toImColor(tintColor));
}
/////////////// Draw_list Overloads
void DrawLine(const sf::Vector2f& a, const sf::Vector2f& b, const sf::Color& color,
float thickness) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
const ImVec2 pos = ImGui::GetCursorScreenPos();
draw_list->AddLine(ImVec2(a.x + pos.x, a.y + pos.y), ImVec2(b.x + pos.x, b.y + pos.y),
ColorConvertFloat4ToU32(toImColor(color)), thickness);
}
void DrawRect(const sf::FloatRect& rect, const sf::Color& color, float rounding,
int rounding_corners, float thickness) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRect(getTopLeftAbsolute(rect), getDownRightAbsolute(rect),
ColorConvertFloat4ToU32(toImColor(color)), rounding, rounding_corners,
thickness);
}
void DrawRectFilled(const sf::FloatRect& rect, const sf::Color& color, float rounding,
int rounding_corners) {
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRectFilled(getTopLeftAbsolute(rect), getDownRightAbsolute(rect),
ColorConvertFloat4ToU32(toImColor(color)), rounding, rounding_corners);
}
} // end of namespace ImGui
namespace {
ImColor toImColor(sf::Color c) {
return {static_cast<int>(c.r), static_cast<int>(c.g), static_cast<int>(c.b),
static_cast<int>(c.a)};
}
ImVec2 getTopLeftAbsolute(const sf::FloatRect& rect) {
const ImVec2 pos = ImGui::GetCursorScreenPos();
return {rect.left + pos.x, rect.top + pos.y};
}
ImVec2 getDownRightAbsolute(const sf::FloatRect& rect) {
const ImVec2 pos = ImGui::GetCursorScreenPos();
return {rect.left + rect.width + pos.x, rect.top + rect.height + pos.y};
}
ImTextureID convertGLTextureHandleToImTextureID(GLuint glTextureHandle) {
ImTextureID textureID = nullptr;
std::memcpy(&textureID, &glTextureHandle, sizeof(GLuint));
return textureID;
}
GLuint convertImTextureIDToGLTextureHandle(ImTextureID textureID) {
GLuint glTextureHandle = 0;
std::memcpy(&glTextureHandle, &textureID, sizeof(GLuint));
return glTextureHandle;
}
// copied from imgui/backends/imgui_impl_opengl2.cpp
void SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height) {
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor
// enabled, vertex/texcoord/color pointers, polygon fill.
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); //
// In order to composite our output buffer we need to preserve alpha
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_SCISSOR_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glEnable(GL_TEXTURE_2D);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glShadeModel(GL_SMOOTH);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to
// draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single
// viewport apps.
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
#ifdef GL_VERSION_ES_CL_1_1
glOrthof(draw_data->DisplayPos.x, draw_data->DisplayPos.x + draw_data->DisplaySize.x,
draw_data->DisplayPos.y + draw_data->DisplaySize.y, draw_data->DisplayPos.y, -1.0f,
+1.0f);
#else
glOrtho(draw_data->DisplayPos.x, draw_data->DisplayPos.x + draw_data->DisplaySize.x,
draw_data->DisplayPos.y + draw_data->DisplaySize.y, draw_data->DisplayPos.y, -1.0f,
+1.0f);
#endif
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
// Rendering callback
void RenderDrawLists(ImDrawData* draw_data) {
ImGui::GetDrawData();
if (draw_data->CmdListsCount == 0) {
return;
}
const ImGuiIO& io = ImGui::GetIO();
assert(io.Fonts->TexID != (ImTextureID) nullptr); // You forgot to create and set font texture
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates !=
// framebuffer coordinates)
const int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
const int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width == 0 || fb_height == 0) return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Backup GL state
// Backup GL state
GLint last_texture = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_polygon_mode[2];
glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
GLint last_viewport[4];
glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4];
glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLint last_shade_model = 0;
glGetIntegerv(GL_SHADE_MODEL, &last_shade_model);
GLint last_tex_env_mode = 0;
glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &last_tex_env_mode);
#ifdef GL_VERSION_ES_CL_1_1
GLint last_array_buffer;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer;
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
#else
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
#endif
// Setup desired GL state
SetupRenderState(draw_data, fb_width, fb_height);
// Will project scissor/clipping rectangles into framebuffer space
const ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
const ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display
// which are often (2,2)
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++) {
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.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)));
glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert),
(const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert),
(const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) {
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback) {
// 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.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
SetupRenderState(draw_data, fb_width, fb_height);
else
pcmd->UserCallback(cmd_list, pcmd);
} else {
// Project scissor/clipping rectangles into framebuffer space
ImVec4 clip_rect;
clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
if (clip_rect.x < static_cast<float>(fb_width) &&
clip_rect.y < static_cast<float>(fb_height) && clip_rect.z >= 0.0f &&
clip_rect.w >= 0.0f) {
// Apply scissor/clipping rectangle
glScissor((int)clip_rect.x, (int)(static_cast<float>(fb_height) - clip_rect.w),
(int)(clip_rect.z - clip_rect.x), (int)(clip_rect.w - clip_rect.y));
// Bind texture, Draw
const GLuint textureHandle =
convertImTextureIDToGLTextureHandle(pcmd->TextureId);
glBindTexture(GL_TEXTURE_2D, textureHandle);
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount,
sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT,
idx_buffer + pcmd->IdxOffset);
}
}
}
}
// Restore modified GL state
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]);
glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
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]);
glShadeModel((GLenum)last_shade_model);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, last_tex_env_mode);
#ifdef GL_VERSION_ES_CL_1_1
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
glDisable(GL_SCISSOR_TEST);
#endif
}
unsigned int getConnectedJoystickId() {
for (unsigned int i = 0; i < (unsigned int)sf::Joystick::Count; ++i) {
if (sf::Joystick::isConnected(i)) return i;
}
return NULL_JOYSTICK_ID;
}
void initDefaultJoystickMapping() {