-
Notifications
You must be signed in to change notification settings - Fork 4
/
iagp.cpp
1141 lines (999 loc) · 42 KB
/
iagp.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
/*
MIT License
Copyright (c) 2021-2024 Stephane Cuillerdier (aka aiekick)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// This is an independent m_oject of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "iagp.h"
#include <cstdarg> /* va_list, va_start, va_arg, va_end */
#include <cmath>
#ifdef _MSC_VER
#include <Windows.h>
#define DEBUG_BREAK \
if (IsDebuggerPresent()) \
__debugbreak()
#else
#define DEBUG_BREAK
#endif
#ifndef IAGP_SUB_WINDOW_MIN_SIZE
#define IAGP_SUB_WINDOW_MIN_SIZE ImVec2(300, 100)
#endif // SUB_IAGP_WINDOW_MIN_SIZE
#ifndef IAGP_GPU_CONTEXT
#define IAGP_GPU_CONTEXT void*
#endif // GPU_CONTEXT
#ifndef IAGP_GET_CURRENT_CONTEXT
static IAGP_GPU_CONTEXT GetCurrentContext() {
DEBUG_BREAK; // you need to create your own function for get the opengl context
return nullptr;
}
#define IAGP_GET_CURRENT_CONTEXT GetCurrentContext
#endif // GET_CURRENT_CONTEXT
#ifndef IAGP_SET_CURRENT_CONTEXT
static void SetCurrentContext(GPU_CONTEXT vContextPtr) {
DEBUG_BREAK; // you need to create your own function for get the opengl context
}
#define SET_CURRENT_CONTEXT SetCurrentContext
#endif // GET_CURRENT_CONTEXT
#ifndef IAGP_LOG_ERROR_MESSAGE
static void LogError(const char* fmt, ...) {
DEBUG_BREAK; // you need to define your own function for get error messages
}
#define IAGP_LOG_ERROR_MESSAGE LogError
#endif // LOG_ERROR_MESSAGE
#ifndef IAGP_LOG_DEBUG_ERROR_MESSAGE
static void LogDebugError(const char* fmt, ...) {
DEBUG_BREAK; // you need to define your own function for get error messages in debug
}
#define IAGP_LOG_DEBUG_ERROR_MESSAGE LogDebugError
#endif // LOG_DEBUG_ERROR_MESSAGE
#ifndef IAGP_IMGUI_BUTTON
#define IAGP_IMGUI_BUTTON ImGui ::Button
#endif // IMGUI_BUTTON
#ifndef IAGP_IMGUI_PLAY_LABEL
#define IAGP_IMGUI_PLAY_LABEL "Play"
#endif
#ifndef IAGP_IMGUI_PAUSE_LABEL
#define IAGP_IMGUI_PAUSE_LABEL "Pause"
#endif
#ifndef IAGP_IMGUI_PLAY_PAUSE_HELP
#define IAGP_IMGUI_PLAY_PAUSE_HELP "Play/Pause Profiling"
#endif
#ifndef IAGP_IMGUI_PLAY_PAUSE_BUTTON
static bool PlayPauseButton(bool& vPlayPause) {
bool res = false;
const char* play_pause_label = IAGP_IMGUI_PAUSE_LABEL;
if (vPlayPause) {
play_pause_label = IAGP_IMGUI_PLAY_LABEL;
}
if (IAGP_IMGUI_BUTTON(play_pause_label)) {
vPlayPause = !vPlayPause;
res = true;
}
if (ImGui::IsItemHovered()) {
ImGui::SetTooltip(IAGP_IMGUI_PLAY_PAUSE_HELP);
}
return res;
}
#define IAGP_IMGUI_PLAY_PAUSE_BUTTON PlayPauseButton
#endif // LOG_DEBUG_ERROR_MESSAGE
#ifndef IAGP_DETAILS_TITLE
#define IAGP_DETAILS_TITLE "Profiler Details"
#endif // IAGP_DETAILS_TITLE
namespace iagp {
inline void checkGLErrors(const char* vFile, const char* vFunc, const int& vLine) {
#ifdef _DEBUG
const GLenum err(glGetError());
if (err != GL_NO_ERROR) {
std::string error;
switch (err) {
case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break;
case GL_INVALID_ENUM: error = "INVALID_ENUM"; break;
case GL_INVALID_VALUE: error = "INVALID_VALUE"; break;
case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break;
case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break;
case GL_STACK_UNDERFLOW: error = "GL_STACK_UNDERFLOW"; break;
case GL_STACK_OVERFLOW: error = "GL_STACK_OVERFLOW"; break;
}
printf("[%s][%s][%i] GL Errors : %s\n", vFile, vFunc, vLine, error.c_str());
//DEBUG_BREAK;
}
#endif
}
#define CheckGLErrors checkGLErrors(__FILE__, __FUNCTION__, __LINE__)
// contrast from 1 to 21
// https://www.w3.org/TR/WCAG20/#relativeluminancedef
static float CalcContrastRatio(const ImU32& backgroundColor, const ImU32& foreGroundColor) {
const float sa0 = (float)((backgroundColor >> IM_COL32_A_SHIFT) & 0xFF);
const float sa1 = (float)((foreGroundColor >> IM_COL32_A_SHIFT) & 0xFF);
static float sr = 0.2126f / 255.0f;
static float sg = 0.7152f / 255.0f;
static float sb = 0.0722f / 255.0f;
const float contrastRatio =
(sr * sa0 * ((backgroundColor >> IM_COL32_R_SHIFT) & 0xFF) + sg * sa0 * ((backgroundColor >> IM_COL32_G_SHIFT) & 0xFF) +
sb * sa0 * ((backgroundColor >> IM_COL32_B_SHIFT) & 0xFF) + 0.05f) /
(sr * sa1 * ((foreGroundColor >> IM_COL32_R_SHIFT) & 0xFF) + sg * sa1 * ((foreGroundColor >> IM_COL32_G_SHIFT) & 0xFF) +
sb * sa1 * ((foreGroundColor >> IM_COL32_B_SHIFT) & 0xFF) + 0.05f);
if (contrastRatio < 1.0f)
return 1.0f / contrastRatio;
return contrastRatio;
}
static bool PushStyleColorWithContrast(const ImU32& backGroundColor, const ImGuiCol& foreGroundColor, const ImVec4& invertedColor,
const float& maxContrastRatio) {
const float contrastRatio = CalcContrastRatio(backGroundColor, ImGui::GetColorU32(foreGroundColor));
if (contrastRatio < maxContrastRatio) {
ImGui::PushStyleColor(foreGroundColor, invertedColor);
return true;
}
return false;
}
static std::string toStr(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
char TempBuffer[1024 * 3 + 1];
const int w = vsnprintf(TempBuffer, 3072, fmt, args);
va_end(args);
if (w) {
return std::string(TempBuffer, (size_t)w);
}
return std::string();
}
////////////////////////////////////////////////////////////
/////////////////////// QUERY ZONE /////////////////////////
////////////////////////////////////////////////////////////
GLuint InAppGpuQueryZone::sMaxDepthToOpen = 100U; // the max by default
bool InAppGpuQueryZone::sShowLeafMode = false;
float InAppGpuQueryZone::sContrastRatio = 4.3f;
bool InAppGpuQueryZone::sActivateLogger = false;
std::vector<IAGPQueryZoneWeak> InAppGpuQueryZone::sTabbedQueryZones = {};
IAGPQueryZonePtr InAppGpuQueryZone::create(IAGP_GPU_CONTEXT vContext, const std::string& vName, const std::string& vSectionName,
const bool vIsRoot) {
auto res = std::make_shared<InAppGpuQueryZone>(vContext, vName, vSectionName, vIsRoot);
res->m_This = res;
return res;
}
InAppGpuQueryZone::circularSettings InAppGpuQueryZone::sCircularSettings;
InAppGpuQueryZone::InAppGpuQueryZone(IAGP_GPU_CONTEXT vContext, const std::string& vName, const std::string& vSectionName,
const bool vIsRoot)
: m_Context(vContext), m_IsRoot(vIsRoot), m_SectionName(vSectionName), name(vName) {
m_StartFrameId = 0;
m_EndFrameId = 0;
m_StartTimeStamp = 0;
m_EndTimeStamp = 0;
m_ElapsedTime = 0.0;
depth = InAppGpuScopedZone::sCurrentDepth;
imGuiLabel = vName + "##InAppGpuQueryZone_" + std::to_string((intptr_t)this);
IAGP_SET_CURRENT_CONTEXT(m_Context);
CheckGLErrors;
glGenQueries(2, ids);
CheckGLErrors;
}
InAppGpuQueryZone::~InAppGpuQueryZone() {
IAGP_SET_CURRENT_CONTEXT(m_Context);
CheckGLErrors;
glDeleteQueries(2, ids);
CheckGLErrors;
name.clear();
m_StartFrameId = 0;
m_EndFrameId = 0;
m_StartTimeStamp = 0;
m_EndTimeStamp = 0;
m_ElapsedTime = 0.0;
zonesOrdered.clear();
zonesDico.clear();
}
void InAppGpuQueryZone::Clear() {
m_StartFrameId = 0;
m_EndFrameId = 0;
m_StartTimeStamp = 0;
m_EndTimeStamp = 0;
m_ElapsedTime = 0.0;
}
void InAppGpuQueryZone::SetStartTimeStamp(const GLuint64& vValue) {
m_StartTimeStamp = vValue;
++m_StartFrameId;
}
void InAppGpuQueryZone::SetEndTimeStamp(const GLuint64& vValue) {
m_EndTimeStamp = vValue;
++m_EndFrameId;
#ifdef IAGP_DEBUG_MODE_LOGGING
IAGP_DEBUG_MODE_LOGGING("%*s end id retrieved : %u", depth, "", ids[1]);
#endif
// start computation of elapsed time
// no needed after
// will be used for Graph and labels
// so DrawMetricGraph must be the first
ComputeElapsedTime();
if (InAppGpuQueryZone::sActivateLogger && zonesOrdered.empty()) // only the leafs
{
/*double v = (double)vValue / 1e9;
LogVarLightInfo("<profiler section=\"%s\" epoch_time=\"%f\" name=\"%s\" render_time_ms=\"%f\">",
m_SectionName.c_str(), v, name.c_str(), m_ElapsedTime);*/
}
}
void InAppGpuQueryZone::ComputeElapsedTime() {
// we take the last frame
if (m_StartFrameId == m_EndFrameId) {
m_AverageStartValue.AddValue(m_StartTimeStamp); // ns to ms
m_AverageEndValue.AddValue(m_EndTimeStamp); // ns to ms
m_StartTime = (double)(m_AverageStartValue.GetAverage() * 1e-6);
m_EndTime = (double)(m_AverageEndValue.GetAverage() * 1e-6);
m_ElapsedTime = m_EndTime - m_StartTime;
}
}
void InAppGpuQueryZone::DrawDetails() {
if (m_StartFrameId) {
bool res = false;
ImGui::TableNextColumn(); // tree
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_DefaultOpen;
bool any_childs_to_show = false;
for (const auto& zone : zonesOrdered) {
if (zone != nullptr && zone->m_ElapsedTime > 0.0) {
any_childs_to_show = true;
break;
}
}
if (!any_childs_to_show) {
flags |= ImGuiTreeNodeFlags_Leaf;
}
if (m_Highlighted) {
flags |= ImGuiTreeNodeFlags_Framed;
}
const auto colorU32 = ImGui::ColorConvertFloat4ToU32(cv4);
const bool pushed = PushStyleColorWithContrast(colorU32, ImGuiCol_Text, ImVec4(0, 0, 0, 1), InAppGpuQueryZone::sContrastRatio);
ImGui::PushStyleColor(ImGuiCol_Header, cv4);
const auto hovered_color = ImVec4(cv4.x * 0.9f, cv4.y * 0.9f, cv4.z * 0.9f, 1.0f);
const auto active_color = ImVec4(cv4.x * 0.8f, cv4.y * 0.8f, cv4.z * 0.8f, 1.0f);
ImGui::PushStyleColor(ImGuiCol_HeaderHovered, hovered_color);
ImGui::PushStyleColor(ImGuiCol_HeaderActive, active_color);
if (m_IsRoot) {
res = ImGui::TreeNodeEx(this, flags, "%s : frame [%u]", name.c_str(), m_StartFrameId - 1U);
} else if (!m_SectionName.empty()) {
res = ImGui::TreeNodeEx(this, flags, "%s : %s", m_SectionName.c_str(), name.c_str());
} else {
res = ImGui::TreeNodeEx(this, flags, "%s", name.c_str());
}
ImGui::PopStyleColor(3);
if (pushed) {
ImGui::PopStyleColor();
}
if (ImGui::IsItemHovered()) {
m_Highlighted = true;
}
#ifdef IAGP_SHOW_COUNT
ImGui::TableNextColumn(); // Elapsed time
ImGui::Text("%u", last_count);
#endif
ImGui::TableNextColumn(); // Elapsed time
ImGui::Text("%.5f ms", m_ElapsedTime);
ImGui::TableNextColumn(); // Max fps
if (m_ElapsedTime > 0.0f) {
ImGui::Text("%.2f f/s", 1000.0f / m_ElapsedTime);
} else {
ImGui::Text("%s", "Infinite");
}
ImGui::TableNextColumn(); // start time
ImGui::Text("%.5f ms", m_StartTime);
ImGui::TableNextColumn(); // end time
ImGui::Text("%.5f", m_EndTime);
if (res) {
m_Expanded = true;
ImGui::Indent();
for (const auto& zone : zonesOrdered) {
if (zone != nullptr && zone->m_ElapsedTime > 0.0) {
zone->DrawDetails();
}
}
ImGui::Unindent();
} else {
m_Expanded = false;
}
}
}
bool InAppGpuQueryZone::DrawFlamGraph(InAppGpuGraphTypeEnum vGraphType, IAGPQueryZoneWeak& vOutSelectedQuery, IAGPQueryZoneWeak vParent,
uint32_t vDepth) {
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems) {
return false;
}
bool pressed = false;
switch (vGraphType) {
case InAppGpuGraphTypeEnum::IN_APP_GPU_HORIZONTAL: // horizontal flame graph (standard and legacy)
pressed = m_DrawHorizontalFlameGraph(m_This.lock(), vOutSelectedQuery, vParent, vDepth);
break;
case InAppGpuGraphTypeEnum::IN_APP_GPU_CIRCULAR: // circular flame graph
pressed = m_DrawCircularFlameGraph(m_This.lock(), vOutSelectedQuery, vParent, vDepth);
break;
case InAppGpuGraphTypeEnum::IN_APP_GPU_Count:
default: break;
}
return pressed;
}
void InAppGpuQueryZone::UpdateBreadCrumbTrail() {
if (parentPtr != nullptr) {
int32_t _depth = depth;
IAGPQueryZonePtr _parent_ptr = m_This.lock();
while (_parent_ptr != rootPtr) {
_parent_ptr = _parent_ptr->parentPtr;
if (_parent_ptr && _parent_ptr->depth == (_depth - 1U)) {
_depth = _parent_ptr->depth;
if (_depth < (int32_t)m_BreadCrumbTrail.size()) {
m_BreadCrumbTrail[_depth] = _parent_ptr;
} else {
DEBUG_BREAK;
// maybe you need to define greater value for RECURSIVE_LEVELS_COUNT
break;
}
}
}
// update the imgui title
imGuiTitle.clear();
for (GLuint idx = 0U; idx < depth; ++idx) {
if (idx < (GLuint)m_BreadCrumbTrail.size()) {
auto ptr = m_BreadCrumbTrail[idx].lock();
if (ptr != nullptr) {
if (idx > 0U) {
imGuiTitle += " > ";
}
imGuiTitle += ptr->name;
}
} else {
DEBUG_BREAK;
// maybe you need to define greater value for RECURSIVE_LEVELS_COUNT
break;
}
}
// add the current
imGuiTitle += " > " + name;
// add the unicity string
imGuiTitle += "##InAppGpuQueryZone_ " + std::to_string((intptr_t)this);
}
}
void InAppGpuQueryZone::DrawBreadCrumbTrail(IAGPQueryZoneWeak& vOutSelectedQuery) {
ImGui::PushID("DrawBreadCrumbTrail");
for (GLuint idx = 0U; idx < depth; ++idx) {
if (idx < m_BreadCrumbTrail.size()) {
auto ptr = m_BreadCrumbTrail[idx].lock();
if (ptr != nullptr) {
if (idx > 0U) {
ImGui::SameLine();
ImGui::Text("%s", ">");
ImGui::SameLine();
}
ImGui::PushID(ptr.get());
if (IAGP_IMGUI_BUTTON(ptr->imGuiLabel.c_str())) {
vOutSelectedQuery = m_BreadCrumbTrail[idx];
}
ImGui::PopID();
}
} else {
DEBUG_BREAK;
// maybe you need to define greater value for RECURSIVE_LEVELS_COUNT
break;
}
}
if (depth > 0) {
ImGui::SameLine();
ImGui::Text("> %s", name.c_str());
}
ImGui::PopID();
}
void InAppGpuQueryZone::m_DrawList_DrawBar(const char* vLabel, const ImRect& vRect, const ImVec4& vColor, const bool vHovered) {
const ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiStyle& style = g.Style;
const ImVec2 label_size = ImGui::CalcTextSize(vLabel, nullptr, true);
const auto colorU32 = ImGui::ColorConvertFloat4ToU32(vColor);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);
ImGui::RenderFrame(vRect.Min, vRect.Max, colorU32, true, 2.0f);
if (vHovered) {
const auto selectU32 = ImGui::ColorConvertFloat4ToU32(ImVec4(1.0f - cv4.x, 1.0f - cv4.y, 1.0f - cv4.z, 1.0f));
window->DrawList->AddRect(vRect.Min, vRect.Max, selectU32, true, 0, 2.0f);
}
ImGui::PopStyleVar();
const bool pushed = PushStyleColorWithContrast(colorU32, ImGuiCol_Text, ImVec4(0, 0, 0, 1), InAppGpuQueryZone::sContrastRatio);
ImGui::RenderTextClipped(vRect.Min + style.FramePadding, vRect.Max - style.FramePadding, //
vLabel, nullptr, &label_size, ImVec2(0.5f, 0.5f), &vRect);
if (pushed) {
ImGui::PopStyleColor();
}
}
bool InAppGpuQueryZone::m_ComputeRatios(IAGPQueryZonePtr vRoot, IAGPQueryZoneWeak vParent, uint32_t vDepth, float& vOutStartRatio,
float& vOutSizeRatio) {
if (depth > InAppGpuQueryZone::sMaxDepthToOpen) {
return false;
}
if (vRoot == nullptr) {
vRoot = m_This.lock();
}
if (vParent.expired()) {
vParent = m_This;
}
if (vRoot != nullptr && vRoot->m_ElapsedTime > 0.0) { // avoid div by zero
if (vDepth == 0) {
vOutStartRatio = 0.0f;
vOutSizeRatio = 1.0f;
if (rootPtr == nullptr) {
hsv = ImVec4((float)(0.5 - 0.5 * m_ElapsedTime / vRoot->m_ElapsedTime), 0.5f, 1.0f, 1.0f);
} else {
hsv = ImVec4((float)(0.5 - 0.5 * m_ElapsedTime / rootPtr->m_ElapsedTime), 0.5f, 1.0f, 1.0f);
}
} else {
auto parent_ptr = vParent.lock();
if (parent_ptr) {
if (parent_ptr->m_ElapsedTime > 0.0) { // avoid div by zero
////////////////////////////////////////////////////////
// for correct rounding isssue with average values
if (parent_ptr->m_StartTime > m_StartTime) {
m_StartTime = parent_ptr->m_StartTime;
}
if (parent_ptr->m_EndTime < m_EndTime) {
m_EndTime = parent_ptr->m_EndTime;
}
if (m_EndTime < m_StartTime) {
m_EndTime = m_StartTime;
}
m_ElapsedTime = m_EndTime - m_StartTime;
if (m_ElapsedTime < 0.0) {
DEBUG_BREAK;
}
if (m_ElapsedTime > parent_ptr->m_ElapsedTime) {
m_ElapsedTime = parent_ptr->m_ElapsedTime;
}
////////////////////////////////////////////////////////
vOutStartRatio = (float)((m_StartTime - vRoot->m_StartTime) / vRoot->m_ElapsedTime);
vOutSizeRatio = (float)(m_ElapsedTime / vRoot->m_ElapsedTime);
if (rootPtr == nullptr) {
hsv = ImVec4((float)(0.5 - 0.5 * m_ElapsedTime / vRoot->m_ElapsedTime), 0.5f, 1.0f, 1.0f);
} else {
hsv = ImVec4((float)(0.5 - 0.5 * m_ElapsedTime / rootPtr->m_ElapsedTime), 0.5f, 1.0f, 1.0f);
}
}
}
}
return true;
}
return false;
}
bool InAppGpuQueryZone::m_DrawHorizontalFlameGraph(IAGPQueryZonePtr vRoot, IAGPQueryZoneWeak& vOutSelectedQuery, IAGPQueryZoneWeak vParent,
uint32_t vDepth) {
bool pressed = false;
const ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float aw = ImGui::GetContentRegionAvail().x - style.FramePadding.x;
ImGuiWindow* window = ImGui::GetCurrentWindow();
float barStartRatio = 0.0f;
float barSizeRatio = 0.0f;
if (m_ComputeRatios(vRoot, vParent, vDepth, barStartRatio, barSizeRatio)) {
if (barSizeRatio > 0.0f) {
if ((zonesOrdered.empty() && InAppGpuQueryZone::sShowLeafMode) || !InAppGpuQueryZone::sShowLeafMode) {
ImGui::PushID(this);
m_BarLabel = toStr("%s (%.2f ms | %.2f f/s)", name.c_str(), m_ElapsedTime, 1000.0f / m_ElapsedTime);
const char* label = m_BarLabel.c_str();
const ImGuiID id = window->GetID(label);
ImGui::PopID();
float bar_start = aw * barStartRatio;
float bar_size = aw * barSizeRatio;
const ImVec2 label_size = ImGui::CalcTextSize(label, nullptr, true);
const float height = label_size.y + style.FramePadding.y * 2.0f;
const ImVec2 bPos = ImVec2(bar_start + style.FramePadding.x, vDepth * height + style.FramePadding.y);
const ImVec2 pos = window->DC.CursorPos + bPos;
const ImVec2 size = ImVec2(bar_size, height);
const ImRect bb(pos, pos + size);
bool hovered, held;
pressed =
ImGui::ButtonBehavior(bb, id, &hovered, &held, //
ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight);
if (pressed) {
if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
vOutSelectedQuery = m_This; // open in the main window
} else if (ImGui::IsMouseClicked(ImGuiMouseButton_Right) && rootPtr != nullptr) {
sTabbedQueryZones.push_back(m_This); // open new window
}
}
m_Highlighted = false;
if (hovered) {
ImGui::SetTooltip("Section : [%s : %s]\nElapsed time : %.5f ms\nElapsed FPS : %.5f f/s", //
m_SectionName.c_str(), name.c_str(), m_ElapsedTime, 1000.0f / m_ElapsedTime);
m_Highlighted = true; // to highlight label graph by this button
} else if (m_Highlighted) {
hovered = true; // highlight this button by the label graph
}
ImGui::ColorConvertHSVtoRGB(hsv.x, hsv.y, hsv.z, cv4.x, cv4.y, cv4.z);
cv4.w = 1.0f;
ImGui::RenderNavHighlight(bb, id);
m_DrawList_DrawBar(label, bb, cv4, hovered);
++vDepth;
}
// we dont show child if this one have elapsed time to 0.0
for (const auto& zone : zonesOrdered) {
if (zone != nullptr) {
pressed |= zone->m_DrawHorizontalFlameGraph(vRoot, vOutSelectedQuery, m_This, vDepth);
}
}
} else {
#ifdef IAGP_DEBUG_MODE_LOGGING
IAGP_DEBUG_MODE_LOGGING("Bar Ms not displayed", name.c_str());
#endif
}
}
if (depth == 0 && ((zonesOrdered.empty() && InAppGpuQueryZone::sShowLeafMode) || !InAppGpuQueryZone::sShowLeafMode)) {
const ImVec2 pos = window->DC.CursorPos;
const ImVec2 size = ImVec2(aw, ImGui::GetFrameHeight() * (InAppGpuScopedZone::sMaxDepth + 1U));
ImGui::ItemSize(size);
const ImRect bb(pos, pos + size);
const ImGuiID id = window->GetID((name + "##canvas").c_str());
if (!ImGui::ItemAdd(bb, id)) {
return pressed;
}
}
return pressed;
}
bool InAppGpuQueryZone::m_DrawCircularFlameGraph(IAGPQueryZonePtr vRoot, IAGPQueryZoneWeak& vOutSelectedQuery, IAGPQueryZoneWeak vParent,
uint32_t vDepth) {
bool pressed = false;
if (vDepth == 0U) {
if (ImGui::BeginMenuBar()) {
if (ImGui::BeginMenu("Settings")) {
ImGui::SliderFloat("count points", &sCircularSettings.count_point, 1.0f, 240.0f);
ImGui::SliderFloat("base_radius", &sCircularSettings.base_radius, 0.0f, 240.0f);
ImGui::SliderFloat("space", &sCircularSettings.space, 0.0f, 240.0f);
ImGui::SliderFloat("thick", &sCircularSettings.thick, 0.0f, 240.0f);
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
}
ImGuiWindow* window = ImGui::GetCurrentWindow();
float barStartRatio = 0.0f;
float barSizeRatio = 0.0f;
if (m_ComputeRatios(vRoot, vParent, vDepth, barStartRatio, barSizeRatio)) {
if (barSizeRatio > 0.0f) {
if ((zonesOrdered.empty() && InAppGpuQueryZone::sShowLeafMode) || !InAppGpuQueryZone::sShowLeafMode) {
ImVec2 center = window->DC.CursorPos + ImGui::GetContentRegionAvail() * 0.5f;
ImGui::ColorConvertHSVtoRGB(hsv.x, hsv.y, hsv.z, cv4.x, cv4.y, cv4.z);
cv4.w = 1.0f;
float min_radius = sCircularSettings.base_radius + sCircularSettings.space * vDepth + sCircularSettings.thick * vDepth;
float max_radius = sCircularSettings.base_radius + sCircularSettings.space * vDepth + sCircularSettings.thick * (vDepth + 1U);
auto draw_list_ptr = window->DrawList;
auto colU32 = ImGui::GetColorU32(cv4);
float full_length = _1PI_;
float full_offset = _1PI_;
float base_st = full_length / sCircularSettings.count_point;
float bar_start = full_length * barStartRatio;
float bar_size = full_length * (barStartRatio + barSizeRatio);
float st = bar_size / ImMax(floor(bar_size / base_st), 3.0f); // 2 points mini par barre
ImVector<ImVec2> path;
float co = 0.0f, si = 0.0f, ac = 0.0f, oc = 0.0f;
for (ac = bar_start; ac < bar_size; ac += st) {
ac = ImMin(ac, bar_size);
oc = ac + full_offset;
co = std::cos(oc) * sCircularSettings.scaleX;
si = std::sin(oc) * sCircularSettings.scaleY;
m_P0.x = co * min_radius + center.x;
m_P0.y = si * min_radius + center.y;
m_P1.x = co * max_radius + center.x;
m_P1.y = si * max_radius + center.y;
if (ac > bar_start) {
// draw_list_ptr->AddQuadFilled(m_P0, m_P1, m_LP1, m_LP0, colU32);
draw_list_ptr->AddQuad(m_P0, m_P1, m_LP1, m_LP0, colU32, 2.0f); // m_BlackU32
// draw_list_ptr->PathLineTo(m_P0);
// draw_list_ptr->PathLineTo(m_P1);
// draw_list_ptr->PathLineTo(m_LP1);
// draw_list_ptr->PathLineTo(m_LP0);
}
m_LP0 = m_P0;
m_LP1 = m_P1;
}
// draw_list_ptr->PathStroke(colU32, ImDrawFlags_Closed, 2.0f);
#ifdef _DEBUG
// draw_list_ptr->AddLine(center, center - ImVec2(0, 150.0f), colU32, 2.0f);
#endif
++vDepth;
}
// we dont show child if this one have elapsed time to 0.0
// childs
for (const auto& zone : zonesOrdered) {
if (zone != nullptr) {
pressed |= zone->m_DrawCircularFlameGraph(vRoot, vOutSelectedQuery, m_This, vDepth);
}
}
}
}
return pressed;
}
////////////////////////////////////////////////////////////
/////////////////////// GL CONTEXT /////////////////////////
////////////////////////////////////////////////////////////
IAGPContextPtr InAppGpuGLContext::create(IAGP_GPU_CONTEXT vContext) {
auto res = std::make_shared<InAppGpuGLContext>(vContext);
res->m_This = res;
return res;
}
InAppGpuGLContext::InAppGpuGLContext(IAGP_GPU_CONTEXT vContext) : m_Context(vContext) {
}
void InAppGpuGLContext::Clear() {
m_RootZone.reset();
m_PendingUpdate.clear();
m_QueryIDToZone.clear();
m_DepthToLastZone.clear();
}
void InAppGpuGLContext::Init() {
}
void InAppGpuGLContext::Unit() {
Clear();
}
void InAppGpuGLContext::Collect() {
#ifdef IAGP_DEBUG_MODE_LOGGING
IAGP_DEBUG_MODE_LOGGING("------ Collect Trhead (%i) -----", (intptr_t)m_Context);
#endif
auto it = m_PendingUpdate.begin();
while (!m_PendingUpdate.empty() && it != m_PendingUpdate.end()) {
GLuint id = *it;
GLuint value = 0;
glGetQueryObjectuiv(id, GL_QUERY_RESULT_AVAILABLE, &value);
const auto it_to_erase_eventually = it;
++it;
if (value == GL_TRUE /* || id == m_RootZone->ids[0] || id == m_RootZone->ids[1]*/) {
GLuint64 value64 = 0;
glGetQueryObjectui64v(id, GL_QUERY_RESULT, &value64);
if (m_QueryIDToZone.find(id) != m_QueryIDToZone.end()) {
auto ptr = m_QueryIDToZone[id];
if (ptr != nullptr) {
if (id == ptr->ids[0]) {
ptr->SetStartTimeStamp(value64);
} else if (id == ptr->ids[1]) {
ptr->last_count = ptr->current_count;
ptr->current_count = 0U;
ptr->SetEndTimeStamp(value64);
} else {
DEBUG_BREAK;
}
}
}
m_PendingUpdate.erase(it_to_erase_eventually);
} else {
auto ptr = m_QueryIDToZone[id];
if (ptr != nullptr) {
IAGP_LOG_ERROR_MESSAGE("%*s id not retrieved : %u", ptr->depth, "", id);
}
}
}
#ifdef IAGP_DEBUG_MODE_LOGGING
IAGP_DEBUG_MODE_LOGGING("------ End Frame -----");
#endif
}
void InAppGpuGLContext::DrawFlamGraph(const InAppGpuGraphTypeEnum& vGraphType) {
if (m_RootZone != nullptr) {
if (!m_SelectedQuery.expired()) {
auto ptr = m_SelectedQuery.lock();
if (ptr) {
ptr->DrawBreadCrumbTrail(m_SelectedQuery);
ptr->DrawFlamGraph(vGraphType, m_SelectedQuery);
}
} else {
m_RootZone->DrawFlamGraph(vGraphType, m_SelectedQuery);
}
}
}
void InAppGpuGLContext::DrawDetails() {
if (m_RootZone != nullptr) {
m_RootZone->DrawDetails();
}
}
IAGPQueryZonePtr InAppGpuGLContext::GetQueryZoneForName(const void* vPtr, const std::string& vName, const std::string& vSection,
const bool vIsRoot) {
IAGPQueryZonePtr res = nullptr;
/////////////////////////////////////////////
//////////////// CREATION ///////////////////
/////////////////////////////////////////////
// there is many link issues with 'max' in cross compilation so we dont using it
if (InAppGpuScopedZone::sCurrentDepth > InAppGpuScopedZone::sMaxDepth) {
InAppGpuScopedZone::sMaxDepth = InAppGpuScopedZone::sCurrentDepth;
}
if (InAppGpuScopedZone::sCurrentDepth == 0) { // root zone
#ifdef IAGP_DEBUG_MODE_LOGGING
IAGP_DEBUG_MODE_LOGGING("------ Start Frame -----");
#endif
m_DepthToLastZone.clear();
if (m_RootZone == nullptr) {
res = InAppGpuQueryZone::create(m_Context, vName, vSection, vIsRoot);
if (res != nullptr) {
res->depth = InAppGpuScopedZone::sCurrentDepth;
res->UpdateBreadCrumbTrail();
m_QueryIDToZone[res->ids[0]] = res;
m_QueryIDToZone[res->ids[1]] = res;
m_RootZone = res;
#ifdef IAGP_DEBUG_MODE_LOGGING
// IAGP_DEBUG_MODE_LOGGING("Profile : add zone %s at puDepth %u", vName.c_str(), InAppGpuScopedZone::sCurrentDepth);
#endif
}
} else {
res = m_RootZone;
}
} else { // else child zone
auto root = m_GetQueryZoneFromDepth(InAppGpuScopedZone::sCurrentDepth - 1U);
if (root != nullptr) {
bool found = false;
const auto& key_str = vSection + vName;
const auto& ptr_iter = root->zonesDico.find(vPtr);
if (ptr_iter == root->zonesDico.end()) { // not found
found = false;
} else { // found
found = (ptr_iter->second.find(key_str) != ptr_iter->second.end()); // not found
}
if (!found) { // not found
res = InAppGpuQueryZone::create(m_Context, vName, vSection, vIsRoot);
if (res != nullptr) {
res->parentPtr = root;
res->rootPtr = m_RootZone;
res->depth = InAppGpuScopedZone::sCurrentDepth;
res->UpdateBreadCrumbTrail();
m_QueryIDToZone[res->ids[0]] = res;
m_QueryIDToZone[res->ids[1]] = res;
root->zonesDico[vPtr][key_str] = res;
root->zonesOrdered.push_back(res);
#ifdef IAGP_DEBUG_MODE_LOGGING
// IAGP_DEBUG_MODE_LOGGING("Profile : add zone %s at puDepth %u", vName.c_str(), InAppGpuScopedZone::sCurrentDepth);
#endif
} else {
DEBUG_BREAK;
}
} else {
res = root->zonesDico[vPtr][key_str];
}
} else {
return res; // happen when profiling is activated inside a profiling zone
}
}
/////////////////////////////////////////////
//////////////// UTILISATION ////////////////
/////////////////////////////////////////////
if (res != nullptr) {
m_SetQueryZoneForDepth(res, InAppGpuScopedZone::sCurrentDepth);
if (res->name != vName) {
// at depth 0 there is only one frame
IAGP_LOG_DEBUG_ERROR_MESSAGE("was registerd at depth %u %s. but we got %s\nwe clear the profiler", //
InAppGpuScopedZone::sCurrentDepth, res->name.c_str(), vName.c_str());
// maybe the scoped frame is taken outside of the main frame
Clear();
}
m_PendingUpdate.emplace(res->ids[0]);
m_PendingUpdate.emplace(res->ids[1]);
}
return res;
}
void InAppGpuGLContext::m_SetQueryZoneForDepth(IAGPQueryZonePtr vInAppGpuQueryZone, GLuint vDepth) {
m_DepthToLastZone[vDepth] = vInAppGpuQueryZone;
}
IAGPQueryZonePtr InAppGpuGLContext::m_GetQueryZoneFromDepth(GLuint vDepth) {
IAGPQueryZonePtr res = nullptr;
if (m_DepthToLastZone.find(vDepth) != m_DepthToLastZone.end()) { // found
res = m_DepthToLastZone[vDepth];
}
return res;
}
////////////////////////////////////////////////////////////
/////////////////////// GL PROFILER ////////////////////////
////////////////////////////////////////////////////////////
bool InAppGpuProfiler::sIsActive = false;
bool InAppGpuProfiler::sIsPaused = false;
InAppGpuProfiler::InAppGpuProfiler() = default;
InAppGpuProfiler::InAppGpuProfiler(const InAppGpuProfiler&) = default;
InAppGpuProfiler& InAppGpuProfiler::operator=(const InAppGpuProfiler&) {
return *this;
};
InAppGpuProfiler::~InAppGpuProfiler() {
Clear();
};
void InAppGpuProfiler::Clear() {
m_Contexts.clear();
}
void InAppGpuProfiler::Collect() {
if (!sIsActive || sIsPaused) {
return;
}
glFinish();
for (const auto& con : m_Contexts) {
if (con.second != nullptr) {
con.second->Collect();
}
}
}
void InAppGpuProfiler::DrawFlamGraph(const char* vLabel, bool* pOpen, ImGuiWindowFlags vFlags) {
if (m_ImGuiBeginFunctor != nullptr && m_ImGuiBeginFunctor(vLabel, pOpen, vFlags | ImGuiWindowFlags_MenuBar)) {
DrawFlamGraphNoWin();
}
if (m_ImGuiEndFunctor != nullptr) {
m_ImGuiEndFunctor();
}
DrawFlamGraphChilds(vFlags);
DrawDetails(vFlags);
}
void InAppGpuProfiler::DrawFlamGraphNoWin() {
if (sIsActive) {
m_DrawMenuBar();
for (const auto& con : m_Contexts) {
if (con.second != nullptr) {
con.second->DrawFlamGraph(m_GraphType);
}
}
}
}
void InAppGpuProfiler::DrawFlamGraphChilds(ImGuiWindowFlags vFlags) {
m_SelectedQuery.reset();
m_QueryZoneToClose = -1;
for (size_t idx = 0U; idx < iagp::InAppGpuQueryZone::sTabbedQueryZones.size(); ++idx) {
auto ptr = iagp::InAppGpuQueryZone::sTabbedQueryZones[idx].lock();
if (ptr != nullptr) {
bool opened = true;
ImGui::SetNextWindowSizeConstraints(IAGP_SUB_WINDOW_MIN_SIZE, ImGui::GetIO().DisplaySize);
if (m_ImGuiBeginFunctor != nullptr && m_ImGuiBeginFunctor(ptr->imGuiTitle.c_str(), &opened, vFlags)) {
if (sIsActive) {
ptr->DrawFlamGraph(iagp::InAppGpuProfiler::Instance()->GetGraphTypeRef(), m_SelectedQuery);
}
}
if (m_ImGuiEndFunctor != nullptr) {
m_ImGuiEndFunctor();
}
if (!opened) {
m_QueryZoneToClose = (int32_t)idx;
}
}
}
if (m_QueryZoneToClose > -1) {
iagp::InAppGpuQueryZone::sTabbedQueryZones.erase( //
iagp::InAppGpuQueryZone::sTabbedQueryZones.begin() + m_QueryZoneToClose);
}
}
void InAppGpuProfiler::SetImGuiBeginFunctor(const ImGuiBeginFunctor& vImGuiBeginFunctor) {
m_ImGuiBeginFunctor = vImGuiBeginFunctor;
}
void InAppGpuProfiler::SetImGuiEndFunctor(const ImGuiEndFunctor& vImGuiEndFunctor) {
m_ImGuiEndFunctor = vImGuiEndFunctor;
}
void InAppGpuProfiler::m_DrawMenuBar() {
if (ImGui::BeginMenuBar()) {
if (InAppGpuScopedZone::sMaxDepth) {
InAppGpuQueryZone::sMaxDepthToOpen = InAppGpuScopedZone::sMaxDepth;
}
IAGP_IMGUI_PLAY_PAUSE_BUTTON(sIsPaused);
if (IAGP_IMGUI_BUTTON("Details")) {