-
Notifications
You must be signed in to change notification settings - Fork 17
/
gl_vk_bk3dthreaded.cpp
1284 lines (1226 loc) · 42.3 KB
/
gl_vk_bk3dthreaded.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
/*
* Copyright (c) 2016-2023, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: Copyright (c) 2016-2021 NVIDIA CORPORATION
* SPDX-License-Identifier: Apache-2.0
*/
#include <glm/gtc/type_ptr.hpp>
#define DEFAULT_RENDERER 2
#include "gl_vk_bk3dthreaded.h"
#include <imgui/backends/imgui_impl_gl.h>
#include <nvgl/contextwindow_gl.hpp>
//-----------------------------------------------------------------------------
// renderers
//-----------------------------------------------------------------------------
Renderer* g_renderers[10];
int g_numRenderers = 0;
static Renderer* s_pCurRenderer = NULL;
static int s_curRenderer = DEFAULT_RENDERER;
//-----------------------------------------------------------------------------
// timing/profiling
//-----------------------------------------------------------------------------
double g_statsCpuTime = 0;
double g_statsGpuTime = 0;
nvh::Profiler g_profiler;
//-----------------------------------------------------------------------------
// Toggles
//-----------------------------------------------------------------------------
bool g_bDisplayObject = true;
bool g_bRefreshCmdBuffers = true;
int g_bRefreshCmdBuffersCounter = 2;
bool g_bDisplayGrid = true;
bool g_bTopologyLines = true;
bool g_bTopologylinestrip = true;
bool g_bTopologytriangles = true;
bool g_bTopologytristrips = true;
bool g_bTopologytrifans = true;
int g_bUnsortedPrims = 0;
int g_MSAA = 8;
MatrixBufferGlobal g_globalMatrices;
//-----------------------------------------------------------------------------
// Static variables for setting up the scene...
//-----------------------------------------------------------------------------
std::vector<Bk3dModel*> g_bk3dModels;
static int s_curObject = 0;
template <typename T, size_t N>
inline size_t array_size(T (&x)[N])
{
return N;
}
//
// Camera animation: captured using '1' in the sample. Then copy and paste...
//
struct CameraAnim
{
glm::vec3 eye, focus;
float sleep;
};
static CameraAnim s_cameraAnim[] = {
// pos target time to wait
{glm::vec3(-0.43, -0.20, -0.01), glm::vec3(-0.14, -0.34, 0.40), 3.0},
{glm::vec3(0.00, -0.36, 0.15), glm::vec3(0.01, -0.40, 0.39), 2},
{glm::vec3(0.15, -0.38, 0.23), glm::vec3(0.16, -0.40, 0.38), 2},
{glm::vec3(0.30, -0.37, 0.22), glm::vec3(0.31, -0.39, 0.38), 2},
{glm::vec3(0.60, -0.37, 0.32), glm::vec3(0.35, -0.41, 0.41), 2},
{glm::vec3(0.24, -0.39, 0.26), glm::vec3(0.23, -0.40, 0.35), 2},
{glm::vec3(0.26, -0.41, 0.37), glm::vec3(0.23, -0.40, 0.37), 2},
{glm::vec3(0.09, -0.40, 0.36), glm::vec3(0.05, -0.40, 0.37), 2},
{glm::vec3(-0.01, -0.38, 0.39), glm::vec3(-0.07, -0.38, 0.39), 2},
{glm::vec3(-0.18, -0.38, 0.38), glm::vec3(-0.11, -0.38, 0.40), 2},
{glm::vec3(-0.12, -0.37, 0.41), glm::vec3(-0.06, -0.37, 0.43), 2},
{glm::vec3(-0.12, -0.29, 0.41), glm::vec3(-0.12, -0.30, 0.41), 1},
{glm::vec3(-0.25, -0.12, 0.25), glm::vec3(-0.11, -0.37, 0.40), 2},
};
static int s_cameraAnimItem = 0;
static int s_cameraAnimItems = array_size(s_cameraAnim);
static float s_cameraAnimIntervals = 0.1;
static bool s_bCameraAnim = true;
#define HELPDURATION 5.0
static float s_helpText = 0.0;
static bool s_bStats = true;
#ifdef USEWORKERS
//-----------------------------------------------------------------------------
// Stuff for Multi-threading, using 'Workers'
//-----------------------------------------------------------------------------
#include "mt/CThreadWork.h"
#define NUMTHREADS 8
ThreadWorkerPool* g_mainThreadPool = NULL;
CEvent g_dataReadyEvent;
TaskQueue* g_mainThreadQueue = NULL;
CCriticalSection* g_crs_bk3d = NULL; // for concurrent access on the model
CCriticalSection* g_crs_VK = NULL; // for concurrent access on Vulkan
CEvent* g_evt_cmdbuf = NULL;
bool g_useWorkers = false;
#endif
int g_numCmdBuffers = 16;
//-----------------------------------------------------------------------------
// forward declarations
//-----------------------------------------------------------------------------
void destroyCommandBuffers(bool bAll);
void releaseThreadLocalVars();
void initThreadLocalVars();
//-----------------------------------------------------------------------------
// Derive the Window for this sample
//-----------------------------------------------------------------------------
class MyWindow : public AppWindowCameraInertia
{
public:
ImGuiH::Registry m_guiRegistry;
nvgl::ContextWindow m_contextWindowGL;
MyWindow();
bool open(int posX, int posY, int width, int height, const char* title, const nvgl::ContextWindowCreateInfo& context);
void processUI(int width, int height, double dt);
virtual void onWindowClose() override;
virtual void onWindowResize(int w = 0, int h = 0) override;
//virtual void motion(int x, int y) override;
//virtual void mousewheel(short delta) override;
//virtual void mouse(NVPWindow::MouseButton button, ButtonAction action, int mods, int x, int y) override;
//virtual void menu(int m) override;
virtual void onKeyboard(MyWindow::KeyCode key, ButtonAction action, int mods, int x, int y) override;
virtual void onKeyboardChar(unsigned char key, int mods, int x, int y) override;
//virtual void idle() override;
virtual void onWindowRefresh() override;
};
MyWindow::MyWindow()
: AppWindowCameraInertia(glm::vec3(-0.43, -0.20, -0.01), glm::vec3(-0.14, -0.34, 0.40)
)
{
}
#ifdef USEWORKERS
void initThreads()
{
//
// Create a pool
//
g_mainThreadPool = new ThreadWorkerPool(NUMTHREADS, false, false, NWTPS_ROUND_ROBIN, std::string("Main Worker Pool"));
LOGI("Creating %d workers...\n", NUMTHREADS);
//
// Create a TaskBatch for this main thread
//
g_mainThreadQueue = new TaskQueue((NThreadID)0, &g_dataReadyEvent); // 0 means that the main thread handle will be taken
setCurrentTaskQueue(g_mainThreadQueue);
g_crs_bk3d = new CCriticalSection();
g_crs_VK = new CCriticalSection();
// create N events
g_evt_cmdbuf = new CEvent[g_bk3dModels.size() * MAXCMDBUFFERS];
}
void terminateThreads()
{
g_mainThreadPool->FlushTasks();
g_mainThreadPool->Terminate(); // issue with NWTPS_SHARED_QUEUE
delete g_mainThreadPool;
g_mainThreadPool = NULL;
delete g_mainThreadQueue;
g_mainThreadQueue = NULL;
delete g_crs_bk3d;
g_crs_bk3d = NULL;
delete g_crs_VK;
g_crs_VK = NULL;
}
#endif
//-----------------------------------------------------------------------------
// Help
//-----------------------------------------------------------------------------
static const char* s_sampleHelp =
"space: toggles continuous rendering\n"
"'c': use toggle command-buffer continuous refresh\n"
"'l': use glCallCommandListNV\n"
"'o': toggles object display\n"
"'g': toggles grid display\n"
"'s': toggle stats\n"
"'a': animate camera\n";
static const char* s_sampleHelpCmdLine =
"---------- Cmd-line arguments ----------\n"
"-v <VBO max Size>\n-m <bk3d model>\n"
"-c 0 or 1 : use command-lists\n"
"-o 0 or 1 : display meshes\n"
"-g 0 or 1 : display grid\n"
"-s 0 or 1 : stats\n"
"-a 0 or 1 : animate camera\n"
"-d 0 or 1 : debug stuff (ui)\n"
"-m <bk3d file> : load a specific model\n"
"<bk3d> : load a specific model\n"
"-q <msaa> : MSAA\n"
"----------------------------------------\n";
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
bool Bk3dModel::updateForChangedRenderTarget()
{
if(m_pRenderer)
return m_pRenderer->updateForChangedRenderTarget(this);
return false;
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
Bk3dModel::Bk3dModel(const char* name, glm::vec3* pPos, float* pScale)
{
assert(name);
m_name = std::string(name);
m_objectMatrices = NULL;
m_objectMatricesNItems = 0;
m_material = NULL;
m_materialNItems = 0;
m_meshFile = NULL;
m_posOffset = pPos ? *pPos : glm::vec3(0, 0, 0);
m_scale = pScale ? *pScale : 0.0f;
m_pRenderer = NULL;
}
Bk3dModel::~Bk3dModel()
{
delete[] m_objectMatrices;
delete[] m_material;
if(m_meshFile)
free(m_meshFile);
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
bool Bk3dModel::loadModel()
{
LOGI("Loading Mesh %s..\n", m_name.c_str());
std::vector<std::string> m_paths;
m_paths.push_back(m_name);
m_paths.push_back(std::string("media/") + m_name);
m_paths.push_back(std::string("downloaded_resources/") + m_name);
m_paths.push_back(std::string("../downloaded_resources/") + m_name);
m_paths.push_back(std::string("../../downloaded_resources/") + m_name);
m_paths.push_back(std::string("../../../downloaded_resources/") + m_name);
//paths.push_back(std::string(PROJECT_RELDIRECTORY) + name);
for(int i = 0; i < m_paths.size(); i++)
{
if((m_meshFile = bk3d::load(m_paths[i].c_str())))
{
break;
}
}
if(m_meshFile == NULL)
{
LOGE("error in loading mesh %s\n", m_name.c_str());
return false;
}
//
// Some adjustment for the display
//
if(m_scale <= 0.0)
{
float min[3] = {1000.0, 1000.0, 1000.0};
float max[3] = {-1000.0, -1000.0, -1000.0};
for(int i = 0; i < m_meshFile->pMeshes->n; i++)
{
bk3d::Mesh* pMesh = m_meshFile->pMeshes->p[i];
if(pMesh->aabbox.min[0] < min[0])
min[0] = pMesh->aabbox.min[0];
if(pMesh->aabbox.min[1] < min[1])
min[1] = pMesh->aabbox.min[1];
if(pMesh->aabbox.min[2] < min[2])
min[2] = pMesh->aabbox.min[2];
if(pMesh->aabbox.max[0] > max[0])
max[0] = pMesh->aabbox.max[0];
if(pMesh->aabbox.max[1] > max[1])
max[1] = pMesh->aabbox.max[1];
if(pMesh->aabbox.max[2] > max[2])
max[2] = pMesh->aabbox.max[2];
}
m_posOffset[0] = (max[0] + min[0]) * 0.5f;
m_posOffset[1] = (max[1] + min[1]) * 0.5f;
m_posOffset[2] = (max[2] + min[2]) * 0.5f;
float bigger = 0;
if((max[0] - min[0]) > bigger)
bigger = (max[0] - min[0]);
if((max[1] - min[1]) > bigger)
bigger = (max[1] - min[1]);
if((max[2] - min[2]) > bigger)
bigger = (max[2] - min[2]);
if((bigger) > 0.001)
{
m_scale = 1.0f / bigger;
PRINTF(("Scaling the model by %f...\n", m_scale));
}
m_posOffset *= m_scale;
}
//
// Allocate an array of transforms and materials for later use with APIs
//
//
// create Buffer Object for materials
//
if(m_meshFile->pMaterials && m_meshFile->pMaterials->nMaterials)
{
m_material = new MaterialBuffer[m_meshFile->pMaterials->nMaterials];
m_materialNItems = m_meshFile->pMaterials->nMaterials;
for(int i = 0; i < m_meshFile->pMaterials->nMaterials; i++)
{
// 256 bytes aligned...
// this is for now a fake material: very few items (diffuse)
// in a real application, material information could contain more
// we'd need 16 vec4 to fill 256 bytes
memcpy(glm::value_ptr(m_material[i].diffuse), m_meshFile->pMaterials->pMaterials[i]->Diffuse(), sizeof(glm::vec3));
//...
// hack for visual result...
if(length(m_material[i].diffuse) <= 0.1f)
m_material[i].diffuse = glm::vec3(1, 1, 1);
}
}
//
// create Buffer Object for Object-matrices
//
if(m_meshFile->pTransforms && m_meshFile->pTransforms->nBones)
{
m_objectMatrices = new MatrixBufferObject[m_meshFile->pTransforms->nBones];
m_objectMatricesNItems = m_meshFile->pTransforms->nBones;
for(int i = 0; i < m_meshFile->pTransforms->nBones; i++)
{
// 256 bytes aligned...
memcpy(glm::value_ptr(m_objectMatrices[i].mO), m_meshFile->pTransforms->pBones[i]->Matrix().m, sizeof(glm::mat4));
}
}
return true;
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void Bk3dModel::addStats(Stats& stats)
{
stats.primitives += m_stats.primitives;
stats.drawcalls += m_stats.drawcalls;
stats.attr_update += m_stats.attr_update;
stats.uniform_update += m_stats.uniform_update;
}
void Bk3dModel::printPosition()
{
LOGI("%f %f %f %f\n", m_posOffset[0], m_posOffset[1], m_posOffset[2], m_scale);
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
#define COMBO_MSAA 0
#define COMBO_SORT 1
#define COMBO_RENDERER 2
#define SCALAR_NCMDBUF 3
#define CHECK_WORKERS 4
void MyWindow::processUI(int width, int height, double dt)
{
// Update imgui configuration
auto& imgui_io = ImGui::GetIO();
imgui_io.DeltaTime = static_cast<float>(dt);
imgui_io.DisplaySize = ImVec2(width, height);
ImGui::NewFrame();
ImGui::SetNextWindowBgAlpha(0.5);
ImGui::SetNextWindowSize(ImVec2(450, 0), ImGuiCond_FirstUseEver);
if(ImGui::Begin("NVIDIA " PROJECT_NAME, nullptr))
{
m_guiRegistry.enumCombobox(COMBO_RENDERER, "Renderer", &s_curRenderer);
#ifdef USEWORKERS
m_guiRegistry.checkbox(CHECK_WORKERS, "UseWorkers", &g_useWorkers);
#endif
m_guiRegistry.inputIntClamped(SCALAR_NCMDBUF, "N Objs x&y", &g_numCmdBuffers, 1, MAXCMDBUFFERS);
ImGui::Separator();
m_guiRegistry.enumCombobox(COMBO_SORT, "Cmd-Buf style", &g_bUnsortedPrims);
m_guiRegistry.enumCombobox(COMBO_MSAA, "MSAA", &g_MSAA);
ImGui::Separator();
//CreateCtrlButton("CURPRINT", "Ouput Pos-scale", g_pTweakContainer)->Register(&eventUI2);
//CreateCtrlScalar("CURO", "Cur Object", g_pTweakContainer)->SetBounds(0.0, 10.)->SetIntMode()->Register(&eventUI2), &s_curObject);
//ImGui::InputFloat("CURX", v, 0.1f, 1.0f, 2);
// ...
//ImGui::Separator();
ImGui::Checkbox("command buffer continuous refresh\n", &g_bRefreshCmdBuffers);
ImGui::Checkbox("continuous rendering\n", &m_realtime.bNonStopRendering);
ImGui::Checkbox("object display\n", &g_bDisplayObject);
ImGui::Checkbox("grid display\n", &g_bDisplayGrid);
ImGui::Checkbox("stats\n", &s_bStats);
ImGui::Checkbox("animate camera\n", &s_bCameraAnim);
ImGui::Checkbox("Topology Lines\n", &g_bTopologyLines);
ImGui::Checkbox("Topology Line-Strip\n", &g_bTopologylinestrip);
ImGui::Checkbox("Topology Triangles\n", &g_bTopologytriangles);
ImGui::Checkbox("Topology Tri-Strips\n", &g_bTopologytristrips);
ImGui::Checkbox("Topology Tri-Fans\n", &g_bTopologytrifans);
ImGui::Separator();
ImGui::Text("('h' to toggle help)");
//if(s_bStats)
// h += m_oglTextBig.drawString(5, m_winSz[1]-h, hudStats.c_str(), 0, vec4f(0.8,0.8,1.0,0.5).vec_array);
if(s_helpText)
{
ImGui::BeginChild("Help", ImVec2(400, 110), true);
// camera help
//ImGui::SetNextWindowCollapsed(0);
const char* txt = getHelpText();
ImGui::Text("%s", txt);
ImGui::EndChild();
}
int avg = 10;
if(g_profiler.getTotalFrames() % avg == avg - 1)
{
nvh::Profiler::TimerInfo info;
g_profiler.getTimerInfo("scene", info);
g_statsCpuTime = info.cpu.average;
g_statsGpuTime = info.gpu.average;
}
float gpuTimeF = float(g_statsGpuTime);
float cpuTimeF = float(g_statsCpuTime);
float maxTimeF = std::max(std::max(cpuTimeF, gpuTimeF), 0.0001f);
ImGui::Text("Frame [ms]: %2.1f", dt * 1000.0f);
ImGui::Text("Scene GPU [ms]: %2.3f", gpuTimeF / 1000.0f);
ImGui::ProgressBar(gpuTimeF / maxTimeF, ImVec2(0.0f, 0.0f));
ImGui::Text("Scene CPU [ms]: %2.3f", cpuTimeF / 1000.0f);
ImGui::ProgressBar(cpuTimeF / maxTimeF, ImVec2(0.0f, 0.0f));
}
ImGui::End();
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
bool MyWindow::open(int posX, int posY, int width, int height, const char* title, const nvgl::ContextWindowCreateInfo& context)
{
if(!AppWindowCameraInertia::open(posX, posY, width, height, title, true))
return false;
m_contextWindowGL.init(&context, m_internal, title);
ImGui::InitGL();
//
// UI
//
auto& imgui_io = ImGui::GetIO();
imgui_io.IniFilename = nullptr;
m_guiRegistry.enumAdd(COMBO_MSAA, 1, "MSAA OFF");
m_guiRegistry.enumAdd(COMBO_MSAA, 4, "MSAA 4x");
m_guiRegistry.enumAdd(COMBO_MSAA, 8, "MSAA 8x");
m_guiRegistry.enumAdd(COMBO_SORT, 0, "Sort on primitive types");
m_guiRegistry.enumAdd(COMBO_SORT, 1, "Unsorted primitive types");
for(int i = 0; i < g_numRenderers; i++)
{
m_guiRegistry.enumAdd(COMBO_RENDERER, i, g_renderers[i]->getName());
}
m_guiRegistry.checkboxAdd(CHECK_WORKERS);
m_guiRegistry.inputIntAdd(SCALAR_NCMDBUF, g_numCmdBuffers);
return true;
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void MyWindow::onWindowClose()
{
AppWindowCameraInertia::onWindowClose();
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void MyWindow::onWindowResize(int w, int h)
{
if(w == 0)
w = getWidth();
if(h == 0)
h = getHeight();
AppWindowCameraInertia::onWindowResize(w, h);
if(s_pCurRenderer)
{
if(s_pCurRenderer->bFlipViewport())
{
m_projection *= glm::scale(glm::mat4(1), glm::vec3(1, -1, 1));
}
//
// update the token buffer in which the viewport setup happens for token rendering
//
s_pCurRenderer->updateViewport(0, 0, w, h);
//
// rebuild the main Command-buffer: size could have been hard-coded within
//
s_pCurRenderer->buildPrimaryCmdBuffer();
//
// the FBOs were destroyed and rebuilt
// associated 64 bits pointers (as resident resources) might have changed
// we need to rebuild the *command-lists*
//
FOREACHMODEL(updateForChangedRenderTarget());
}
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
#define KEYTAU 0.10f
void MyWindow::onKeyboard(NVPWindow::KeyCode key, MyWindow::ButtonAction action, int mods, int x, int y)
{
AppWindowCameraInertia::onKeyboard(key, action, mods, x, y);
if(action == MyWindow::BUTTON_RELEASE)
return;
switch(key)
{
case NVPWindow::KEY_F1:
LOGI("Camera: glm::vec3(%.2f,%.2f,%.2f), glm::vec3(%.2f,%.2f,%.2f)\n ", m_camera.eyePos.x, m_camera.eyePos.y,
m_camera.eyePos.z, m_camera.focusPos.x, m_camera.focusPos.y, m_camera.focusPos.z);
break;
//...
case NVPWindow::KEY_F12:
break;
}
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void MyWindow::onKeyboardChar(unsigned char key, int mods, int x, int y)
{
AppWindowCameraInertia::onKeyboardChar(key, mods, x, y);
switch(key)
{
case '1':
m_camera.print_look_at(true);
break;
case '2': // dumps the position and scale of current object
if(s_curObject >= g_bk3dModels.size())
break;
g_bk3dModels[s_curObject]->printPosition();
break;
case '0':
m_bAdjustTimeScale = true;
case 'h':
LOGI("%s", s_sampleHelpCmdLine);
s_helpText = HELPDURATION;
break;
}
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void resetCommandBuffersPool()
{
// here we reset the primary pool: what is from thread #0
s_pCurRenderer->resetCommandBuffersPool();
#ifdef USEWORKERS
if(g_useWorkers)
{
// here we reset the secondary pools: what is from thread #0
//---------------------------------------------------------------------
// Invoke a Task on all the threads to setup some thread-local variable
//
class TaskResetCommandBuffersPool : public TaskBase
{
private:
int m;
public:
TaskResetCommandBuffersPool(int _m)
: TaskBase()
{
m = _m;
}
void Invoke()
{ // We are now in the Thread : let's reset the command-buffers Pool
s_pCurRenderer->resetCommandBuffersPool();
g_evt_cmdbuf[m].Set();
}
};
//---------------------------------------------------------------------
// loop in each existing thread
for(unsigned int i = 0; i < g_mainThreadPool->getThreadCount(); i++)
{
// Call in // threads
TaskResetCommandBuffersPool* taskResetCommandBuffersPool;
taskResetCommandBuffersPool = new TaskResetCommandBuffersPool(i);
// explicitly choosing threads. Note: need to check how does it work with NWTPS_SHARED_QUEUE
g_mainThreadPool->getThreadWorker(i)->GetTaskQueue().pushTask(taskResetCommandBuffersPool);
}
// wait for all before continuing
{
//NXPROFILEFUNC("Wait for all");
for(unsigned int m = 0; m < g_mainThreadPool->getThreadCount(); m++)
{
//
// Wait for the worker to be done
//
g_evt_cmdbuf[m].WaitOnEvent();
g_evt_cmdbuf[m].Reset();
}
}
}
#endif
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void destroyCommandBuffers(bool bAll)
{
NXPROFILEFUNC(__FUNCTION__);
if(bAll)
{
// wait for the GPU to be done: we might erase commands that are still used by the GPU
s_pCurRenderer->waitForGPUIdle();
//
for(int m = 0; m < g_bk3dModels.size(); m++)
{
s_pCurRenderer->consolidateCmdBuffersModel(g_bk3dModels[m], 0);
}
}
#ifdef USEWORKERS
if(g_useWorkers)
{
//---------------------------------------------------------------------
// Invoke a Task on all the threads to setup some thread-local variable
//
class TaskDestroyCommandBuffers : public TaskBase
{
private:
int m;
bool bAll;
public:
TaskDestroyCommandBuffers(int _m, bool _bAll)
: TaskBase()
{
m = _m;
bAll = _bAll;
}
void Invoke()
{ // We are now in the Thread : let's delete the command-buffers pointed through TLS
s_pCurRenderer->destroyCommandBuffers(bAll);
//if(bAll)
g_evt_cmdbuf[m].Set();
}
};
//---------------------------------------------------------------------
for(unsigned int i = 0; i < g_mainThreadPool->getThreadCount(); i++)
{
// Call in // threads
TaskDestroyCommandBuffers* taskDestroyCommandBuffers;
taskDestroyCommandBuffers = new TaskDestroyCommandBuffers(i, bAll);
// explicitly choosing threads. Note: need to check how does it work with NWTPS_SHARED_QUEUE
g_mainThreadPool->getThreadWorker(i)->GetTaskQueue().pushTask(taskDestroyCommandBuffers);
//taskDestroyCommandBuffers->(&g_mainThreadPool->getThreadWorker(i)->GetTaskQueue());
}
// wait for completion before continuing
{
NXPROFILEFUNC("Wait for all");
for(unsigned int m = 0; m < g_mainThreadPool->getThreadCount(); m++)
{
//
// Wait for the worker to be done
//
g_evt_cmdbuf[m].WaitOnEvent();
g_evt_cmdbuf[m].Reset();
}
}
}
else
#endif
{
s_pCurRenderer->destroyCommandBuffers(bAll);
}
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void initThreadLocalVars()
{
#ifdef USEWORKERS
NXPROFILEFUNC(__FUNCTION__);
//---------------------------------------------------------------------
// Invoke a Task on all the threads to setup some thread-local variable
//
class SetThreadLocalVars : public TaskSyncCall
{
public:
void Invoke()
{ // We are now in the Thread : let's create the context, share it and make it current
int threadId = getThreadNumber() + 1;
s_pCurRenderer->initThreadLocalVars(threadId);
}
};
//---------------------------------------------------------------------
static SetThreadLocalVars setThreadLocalVars;
for(unsigned int i = 0; i < g_mainThreadPool->getThreadCount(); i++)
{
// we will wait for the tasks to be done before continuing (Call)
setThreadLocalVars.Call(&g_mainThreadPool->getThreadWorker(i)->GetTaskQueue());
}
#endif
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void releaseThreadLocalVars()
{
#ifdef USEWORKERS
NXPROFILEFUNC(__FUNCTION__);
//---------------------------------------------------------------------
// Invoke a Task on all the threads to setup some thread-local variable
//
class ReleaseThreadLocalVars : public TaskSyncCall
{
public:
void Invoke()
{ // We are now in the Thread : let's create the context, share it and make it current
s_pCurRenderer->releaseThreadLocalVars();
}
};
//---------------------------------------------------------------------
static ReleaseThreadLocalVars releaseThreadLocalVars;
for(unsigned int i = 0; i < g_mainThreadPool->getThreadCount(); i++)
{
// we will wait for the tasks to be done before continuing (Call)
releaseThreadLocalVars.Call(&g_mainThreadPool->getThreadWorker(i)->GetTaskQueue());
}
#endif
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
int refreshCmdBuffers()
{
int totalTasks = 0;
#ifdef USEWORKERS
//---------------------------------------------
// Worker for command-buffer update
//
class TskUpdateCommandBuffer : public TaskBase
{
private:
int m;
int cmdBufIdx;
int mstart, mend;
public:
//TskUpdateCommandBuffer() { }
TskUpdateCommandBuffer(int modelIndex, int cIdx, int ms, int me)
{
m = modelIndex;
mstart = ms;
mend = me;
cmdBufIdx = cIdx;
}
virtual void Invoke()
{
s_pCurRenderer->buildCmdBufferModel(g_bk3dModels[m], cmdBufIdx, mstart, mend);
g_evt_cmdbuf[m * MAXCMDBUFFERS + cmdBufIdx].Set();
}
//void Done() { /* FIXME: prevent delete to happen */ }
};
//---------------------------------------------
//---------------------------------------------
if(g_useWorkers)
{
for(int m = 0; m < g_bk3dModels.size(); m++)
{
int meshgroupsize = g_bk3dModels[m]->m_meshFile->pMeshes->n / g_numCmdBuffers;
int i = 0;
for(int n = 0; n < g_bk3dModels[m]->m_meshFile->pMeshes->n; n += meshgroupsize, i++)
{
// worker will be deleted by the default method Done()
if((i + 1) >= g_numCmdBuffers)
{
TskUpdateCommandBuffer* tskUpdateCommandBuffer =
new TskUpdateCommandBuffer(m, i, n, g_bk3dModels[m]->m_meshFile->pMeshes->n);
g_mainThreadPool->pushTask(tskUpdateCommandBuffer);
totalTasks++;
break;
}
TskUpdateCommandBuffer* tskUpdateCommandBuffer = new TskUpdateCommandBuffer(m, i, n, n + meshgroupsize);
g_mainThreadPool->pushTask(tskUpdateCommandBuffer);
totalTasks++;
}
}
} //if(g_useWorkers)
else
#endif
{
for(int m = 0; m < g_bk3dModels.size(); m++)
{
int meshgroupsize = 1 + (g_bk3dModels[m]->m_meshFile->pMeshes->n / g_numCmdBuffers);
int i = 0;
for(int n = 0; n < g_bk3dModels[m]->m_meshFile->pMeshes->n; n += meshgroupsize, i++)
{
if((i + 1) >= g_numCmdBuffers)
{
s_pCurRenderer->buildCmdBufferModel(g_bk3dModels[m], i, n, g_bk3dModels[m]->m_meshFile->pMeshes->n);
break;
}
s_pCurRenderer->buildCmdBufferModel(g_bk3dModels[m], i, n, n + meshgroupsize);
}
}
} //if(g_useWorkers)
return totalTasks;
}
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
#ifdef USEWORKERS
void waitRefreshCmdBuffersDone(int totalTasks)
{
//PROFILE_SECTION("waitRefreshCmdBuffersDone");
if(g_useWorkers)
{
for(int m = 0; m < totalTasks; m++)
{
//
// Wait for the worker to be done with command-buffer creation
//
g_evt_cmdbuf[m].WaitOnEvent();
g_evt_cmdbuf[m].Reset();
}
}
}
#endif
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void MyWindow::onWindowRefresh()
{
if(!s_pCurRenderer)
return;
if(g_bRefreshCmdBuffers || (g_bRefreshCmdBuffersCounter > 0))
resetCommandBuffersPool();
AppWindowCameraInertia::onWindowRefresh();
if(!s_pCurRenderer->valid())
{
glClearColor(0.5, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
m_contextWindowGL.swapBuffers();
return;
}
float dt = (float)m_realtime.getFrameDT();
//
// Simple camera change for animation
//
if(s_bCameraAnim)
{
if(s_cameraAnimItems == 0)
{
LOGE("NO Animation loaded (-i <file>)\n");
s_bCameraAnim = false;
}
s_cameraAnimIntervals -= dt;
if((m_camera.eyeD <= 0.01 /*m_camera.epsilon*/) && (m_camera.focusD <= 0.01 /*m_camera.epsilon*/)
&& (s_cameraAnimIntervals <= 0.0))
{
//LOGI("Anim step %d\n", s_cameraAnimItem);
s_cameraAnimIntervals = s_cameraAnim[s_cameraAnimItem].sleep;
m_camera.look_at(s_cameraAnim[s_cameraAnimItem].eye, s_cameraAnim[s_cameraAnimItem].focus);
m_camera.tau = 0.4f;
s_cameraAnimItem++;
if(s_cameraAnimItem >= s_cameraAnimItems)
s_cameraAnimItem = 0;
}
}
//
// render the scene
//
g_profiler.beginFrame();
{
PROFILE_SECTION("frame");
glm::mat4 mW(1);
// somehow a hack for the CAD models to be back on better scale and orientation
if(!g_bk3dModels.empty())
{
mW = glm::rotate(mW, -glm::radians(90.0f), glm::vec3(1, 0, 0));
mW = glm::translate(mW, -g_bk3dModels[0]->m_posOffset);
mW = glm::scale(mW, glm::vec3(g_bk3dModels[0]->m_scale));
}
{
//
// This might initiate a primary command-buffer (in Vulkan renderer)
//
{
s_pCurRenderer->displayStart(mW, m_camera, m_projection, m_timingGlitch);
}
//
// kick a bunch of workers to update the command-buffers
// AFTER displayStart: because displayStart alternate the ping-pong index needed below
//
int totalTasks = 0;
if(g_bDisplayObject)
{
PROFILE_SECTION("refresh CmdBuffers");
if(g_bRefreshCmdBuffers || (g_bRefreshCmdBuffersCounter > 0))
{
totalTasks = refreshCmdBuffers();
if(g_bRefreshCmdBuffersCounter > 0)
g_bRefreshCmdBuffersCounter--;
#ifdef USEWORKERS
// NOTE: we could do things in the meantime, rather than waiting...
waitRefreshCmdBuffersDone(totalTasks);
#endif
for(int m = 0; m < g_bk3dModels.size(); m++)
{
// set the # of command buffers used to display the model and possibly do some consolidation
s_pCurRenderer->consolidateCmdBuffersModel(g_bk3dModels[m], g_numCmdBuffers);
}
}
} //if(g_bDisplayObject)
//
// Grid floor: might append a sub-command to the primary command-buffer
//
if(g_bDisplayGrid)
{
s_pCurRenderer->displayGrid(m_camera, m_projection);
}
//
// Display Meshes: might append a sub-commands to the primary command-buffer
//
unsigned short topo = (g_bTopologyLines ? 1 : 0) | (g_bTopologylinestrip ? 2 : 0) | (g_bTopologytriangles ? 4 : 0)
| (g_bTopologytristrips ? 8 : 0) | (g_bTopologytrifans ? 0x10 : 0) | (g_bUnsortedPrims ? 0x20 : 0);
if(g_bDisplayObject)
{
for(int m = 0; m < g_bk3dModels.size(); m++)
{
//
// Then use it
//
s_pCurRenderer->displayBk3dModel(g_bk3dModels[m], m_camera.m4_view, m_projection, topo);
}
}
//
// This might finalize a primary command-buffer (Vulkan) referring to sub-commands (create in display..() )
//
{
s_pCurRenderer->displayEnd();
}
//
// copy FBO to backbuffer
//
s_pCurRenderer->blitToBackbuffer();
}
if(1 /*useUI*/)
{
int width = getWidth();
int height = getHeight();
processUI(width, height, dt);
ImDrawData* imguiDrawData;
ImGui::Render();
imguiDrawData = ImGui::GetDrawData();
ImGui::RenderDrawDataGL(imguiDrawData);
ImGui::EndFrame();
}
} //PROFILE_SECTION("frame");
m_contextWindowGL.swapBuffers();
g_profiler.endFrame();
}
//------------------------------------------------------------------------------
// Main initialization point
//------------------------------------------------------------------------------
void readConfigFile(const char* fname)
{
// FILE *fp = fopen(fname, "r");
// if(!fp)
// {
// std::string modelPathName;
// modelPathName = NVPSystem::exePath() + std::string(PROJECT_RELDIRECTORY) + std::string(fname);
// fp = fopen(modelPathName.c_str(), "r");
// if(!fp)
// {
// LOGE("Couldn't Load %s\n", fname);