Repository navigation
Expand file tree
/
Copy pathSimFluid.cpp
More file actions
2007 lines (1748 loc) · 82.8 KB
/
Copy pathSimFluid.cpp
File metadata and controls
2007 lines (1748 loc) · 82.8 KB
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 "SimFluid.h"
int IMGUI_STYLE = 4;
void SwitchToFullScreen()
{
vkDeviceWaitIdle(g_Device->device);
static uint32_t oldWindowX;
static uint32_t oldWindowY;
static uint32_t oldWindowW;
static uint32_t oldWindowH;
if (!g_IsFullscreen) // -> Switch to fullscreen
{
// Storing the window position BEFORE fullscreen, glfwGetWindowPos returns the top-left corner of the client area
int wx, wy;
glfwGetWindowPos(g_hWindow, &wx, &wy);
oldWindowX = wx;
oldWindowY = wy;
oldWindowW = g_WindowW;
oldWindowH = g_WindowH;
GLFWmonitor* targetMonitor = get_current_monitor(g_hWindow);
const GLFWvidmode* mode = glfwGetVideoMode(targetMonitor);
glfwSetWindowMonitor(g_hWindow, targetMonitor, 0, 0, mode->width, mode->height, mode->refreshRate);
}
else
{
// Restoring directly with the saved coordinates without adjustment by GetWindowFrameSize (unreliable post-fullscreen)
glfwSetWindowMonitor(g_hWindow, nullptr, oldWindowX, oldWindowY, oldWindowW, oldWindowH, 0);
}
g_IsFullscreen = !g_IsFullscreen;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// Callback function for window resizing
if (width == 0 || height == 0) return;
if (g_IsRecreating) return;
g_WindowW = width;
g_WindowH = height;
g_WindowW_2 = width / 2;
g_WindowH_2 = height / 2;
g_Camera.SetViewportSize(g_WindowW, g_WindowH);
g_IsRecreating = true;
PartialRecreate();
g_IsRecreating = false;
}
void CursorPosCallback(GLFWwindow* window, double xposIn, double yposIn)
{
g_Camera.MousePosUpdate(xposIn, yposIn);
}
void MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
{
if (button == GLFW_MOUSE_BUTTON_RIGHT)
{
if (action == GLFW_RELEASE)
g_ForceActive = false;
else if (action == GLFW_PRESS && !ImGui::GetIO().WantCaptureMouse)
g_ForceActive = true;
g_ForceHasPrev = false;
return;
}
if (!ImGui::GetIO().WantCaptureMouse)
g_Camera.MouseButtonUpdate(button, action, mods);
}
void ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
vec2 mouse(mouseX, mouseY);
if (!ImGui::GetIO().WantCaptureMouse)
{
if (g_Camera.GetMode() == eCameraMode::ORBITAL)
g_Camera.AdjustOrbitRadius(-yoffset * 0.1f * g_Camera.GetOrbitRadius());
}
}
void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
g_Camera.KeyboardUpdate(key, scancode, action, mods);
if (action == GLFW_PRESS || action == GLFW_REPEAT)
{
switch (key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, true);
break;
// Pause
case GLFW_KEY_SPACE:
g_bPause = !g_bPause;
if (g_bPause) g_TimerScene.stop();
else g_TimerScene.start();
break;
case GLFW_KEY_G:
IMGUI_STYLE++;
ApplyTheme();
break;
case GLFW_KEY_I: // Cycle the interpolation function to the next type
{
int current = static_cast<int>(g_Camera.GetInterpolation());
int next = (current + 1) % static_cast<int>(eInterpolation::COUNT);
g_Camera.SetInterpolation(static_cast<eInterpolation>(next));
}
break;
case GLFW_KEY_F1:
g_bShowShortcuts = !g_bShowShortcuts;
break;
case GLFW_KEY_F2:
g_bShowSceneWindow = !g_bShowSceneWindow;
break;
case GLFW_KEY_F4:
g_bShowStatusBar = !g_bShowStatusBar;
break;
case GLFW_KEY_F8:
{
HWND hWnd = glfwGetWin32Window(g_hWindow);
g_CaptureName = SaveClientArea(hWnd);
g_CaptureDisplayTime = g_CaptureMaxTime;
}
break;
case GLFW_KEY_F11:
g_PendingFullscreen = true;
break;
}
}
else if (action == GLFW_RELEASE)
{
// A key has just been released
}
}
ImVec2 GetLeftAlignedTextPos(const char* text, ImVec2 box_left, float padding_x, float padding_y, ImFont* font)
{
ImGui::PushFont(font);
// Calculate text size
ImVec2 text_size = ImGui::CalcTextSize(text);
// Text position: left edge of the box + padding (left-aligned)
ImVec2 text_pos = ImVec2(box_left.x + padding_x, box_left.y - text_size.y * 0.5f);
ImGui::PopFont();
return text_pos;
}
ImVec2 GetCenteredTextPos(const char* text, ImVec2 box_center, float padding_x, float padding_y, ImFont* font)
{
ImGui::PushFont(font);
// Calculate text size
ImVec2 text_size = ImGui::CalcTextSize(text);
// Text position: center of the box - half text size
ImVec2 text_pos = ImVec2( box_center.x - text_size.x * 0.5f, box_center.y - text_size.y * 0.5f );
ImGui::PopFont();
return text_pos;
}
ImVec2 GetRightAlignedTextPos(const char* text, ImVec2 box_right, float padding_x, float padding_y, ImFont* font)
{
ImGui::PushFont(font);
// Calculate text size
ImVec2 text_size = ImGui::CalcTextSize(text);
// Text position: right edge of the box - text size (right-aligned)
ImVec2 text_pos = ImVec2(box_right.x - text_size.x - padding_x, box_right.y - text_size.y * 0.5f);
ImGui::PopFont();
return text_pos;
}
static bool CursorToWorld(vec3& outPoint)
{
double mx, my;
glfwGetCursorPos(g_hWindow, &mx, &my);
int ww, wh;
glfwGetWindowSize(g_hWindow, &ww, &wh);
if (ww <= 0 || wh <= 0)
return false;
// Ray through the pixel (two points of the ray, whatever the depth convention of the projection)
const float nx = 2.0f * (float)mx / (float)ww - 1.0f;
const float ny = 2.0f * (float)my / (float)wh - 1.0f;
const mat4 view = g_Camera.GetView();
const mat4 invVP = glm::inverse(g_Camera.GetProjection() * view);
const vec4 a = invVP * vec4(nx, ny, 0.0f, 1.0f);
const vec4 b = invVP * vec4(nx, ny, 1.0f, 1.0f);
const vec3 o = vec3(a) / a.w;
const vec3 dir = glm::normalize(vec3(b) / b.w - o);
// Plane perpendicular to the view direction, through the center of the tank
const vec3 fwd = -vec3(view[0][2], view[1][2], view[2][2]);
const vec3 center = 0.5f * (g_SphSolver.BoxMin() + g_SphSolver.BoxMax()) + fwd * g_ForceDepth;
const float denom = glm::dot(dir, fwd);
if (std::abs(denom) < 1e-4f)
return false;
const float t = glm::dot(center - o, fwd) / denom;
if (t < 0.0f)
return false;
outPoint = glm::clamp(o + t * dir, g_SphSolver.BoxMin(), g_SphSolver.BoxMax());
return true;
}
static void UpdateForceCursor(double dt)
{
vec3 p;
if (!g_ForceActive || dt <= 0.0 || !CursorToWorld(p))
{
g_SphSolver.ClearCursorForce();
g_ForceHasPrev = false;
g_ForceVel = vec3(0.0f);
return;
}
if (g_ForceHasPrev)
{
vec3 v = (p - g_ForcePrev) / (float)dt;
const float maxV = g_SphSolver.Params().maxSpeed;
const float sp = glm::length(v);
if (sp > maxV)
v *= maxV / sp;
g_ForceVel = glm::mix(g_ForceVel, v, 0.3f); // smoothing: mouse events are jerky
}
g_ForcePrev = p;
g_ForceHasPrev = true;
g_SphSolver.SetCursorForce(p, g_ForceRadius, g_ForceVel, g_ForceStiffness);
}
// Imgui
void RenderStatusbar()
{
if (!g_bShowStatusBar)
return;
ImGui::PushFont(g_FontArial16);
char text[256];
vec3 position = g_Camera.GetPosition();
float distCameraShip = glm::length(position);
vec2 lonlat = opengl_to_lonlat(position.x, position.z);
sprintf_s(text, "CAMERA x = %.2f y = %.2f z = %.2f Heading = %03d\xc2\xb0 Roll = %d\xc2\xb0 Pitch = %03d\xc2\xb0 Distance to centre = %d m",
position.x, position.y, position.z,
(int)g_Camera.GetNorthAngleDEG(), (int)g_Camera.GetAttitudeDEG(), (int)g_Camera.GetRollDEG(),
int(distCameraShip));
ImDrawList* draw_list = ImGui::GetBackgroundDrawList();
// White semi-transparent background rectangle (at the bottom of the screen)
draw_list->AddRectFilled(ImVec2(0, g_WindowH - 20), ImVec2(g_WindowW, g_WindowH), IM_COL32(255, 255, 255, 64));
// Black text vertically centered
ImVec2 box_left = ImVec2(0, g_WindowH - 20 + 10);
ImVec2 text_pos = GetLeftAlignedTextPos(text, box_left, 5.0f, 0.0f, g_FontArial16);
draw_list->AddText(text_pos, IM_COL32(0, 0, 0, 255), text);
ImGui::PopFont();
}
void RenderTitle()
{
float x = g_WindowW - 55.0f;
float y = g_WindowH - 45.0f;
ImGui::PushFont(g_FontCaveat36); // "Caveat" font equivalent
ImDrawList* draw_list = ImGui::GetBackgroundDrawList();
const char* text = "SimFluid";
// Adjust position according to alignment (simulates nvgTextAlign)
ImVec2 text_size = ImGui::CalcTextSize(text);
float textX = x;
textX -= text_size.x * 0.5f;
// White title
draw_list->AddText(ImVec2(textX, y), g_ColorWhite, text);
ImGui::PopFont();
}
void RenderInfo()
{
ImGui::PushFont(g_FontArial36);
ImDrawList* draw_list = ImGui::GetBackgroundDrawList();
// Screenshot name
if (g_CaptureName.length() > 0 && g_CaptureDisplayTime > 0.0f)
{
std::string s(g_CaptureName.begin(), g_CaptureName.end());
// Get viewport (window size)
const ImGuiViewport* viewport = ImGui::GetMainViewport();
ImVec2 window_center = viewport->GetCenter();
// Calculate text size for precise offset
ImVec2 text_size = ImGui::CalcTextSize(s.c_str());
// Final position: center - (text size / 2)
ImVec2 text_pos = ImVec2(window_center.x - text_size.x * 0.5f, window_center.y - text_size.y * 0.5f);
// Transparent black rectangle (padding 10px around text)
ImVec2 rect_min = ImVec2(text_pos.x - 10.0f, text_pos.y - 5.0f);
ImVec2 rect_max = ImVec2(text_pos.x + text_size.x + 10.0f, text_pos.y + text_size.y + 5.0f);
// Black color 70% transparent
draw_list->AddRectFilled(rect_min, rect_max, IM_COL32(0, 0, 0, 180), 4.0f);
// White text on top
draw_list->AddText(text_pos, g_ColorWhite, s.c_str());
g_CaptureDisplayTime -= ImGui::GetIO().DeltaTime;
}
ImGui::PopFont();
}
void RenderSphSolverInfo()
{
ImGui::PushFont(g_FontArial20);
ImDrawList* draw_list = ImGui::GetBackgroundDrawList();
if (g_SphSolverInfo.length() > 0)
{
std::string s(g_SphSolverInfo.begin(), g_SphSolverInfo.end());
const ImGuiViewport* viewport = ImGui::GetMainViewport();
// Marge depuis le bas de la fenêtre
const float bottom_margin = 40.0f;
ImVec2 text_size = ImGui::CalcTextSize(s.c_str());
// Centré horizontalement, proche du bas verticalement
float x = viewport->GetCenter().x - text_size.x * 0.5f;
float y = viewport->WorkPos.y + viewport->WorkSize.y
- bottom_margin - text_size.y;
ImVec2 text_pos = ImVec2(x, y);
// Rectangle de fond avec padding
ImVec2 rect_min = ImVec2(text_pos.x - 10.0f, text_pos.y - 5.0f);
ImVec2 rect_max = ImVec2(text_pos.x + text_size.x + 10.0f, text_pos.y + text_size.y + 5.0f);
draw_list->AddRectFilled(rect_min, rect_max, IM_COL32(0, 0, 0, 180), 4.0f);
draw_list->AddText(text_pos, g_ColorWhite, s.c_str());
}
ImGui::PopFont();
}
void RenderShortcuts()
{
if (!g_bShowShortcuts)
return;
ImGui::PushFont(g_FontArial20);
// Split : from "W" to "O" → left col
size_t splitIndex = 24;
float padding = 20.0f;
float lineHeight = 22.0f;
float boxWidth = 560.0f;
float boxHeight = lineHeight * std::max(22, (int)(vShortcuts.size() - 22)) + padding * 2;
// Center the box
float x = (g_WindowW - boxWidth) / 2.0f;
float y = (g_WindowH - boxHeight) / 2.0f;
ImDrawList* draw_list = ImGui::GetBackgroundDrawList();
ImVec2 pos = ImVec2(x, y);
// Semi-transparent background
draw_list->AddRectFilled(pos, ImVec2(x + boxWidth, y + boxHeight), IM_COL32(0, 0, 0, 160));
// Central dividing line
float separatorX = x + padding + (boxWidth - 2 * padding) * 0.5f;
draw_list->AddLine(ImVec2(separatorX, y + padding),
ImVec2(separatorX, y + boxHeight - padding),
IM_COL32(255, 255, 255, 180), 2.0f);
// Width of a column
float columnWidth = (boxWidth - 2 * padding) * 0.5f;
// Column positions
float colLeftXKey = x + padding;
float colLeftXDesc = x + padding + columnWidth - 20;
float colRightXKey = x + padding + columnWidth + 20;
float colRightXDesc = x + boxWidth - padding;
// Left column
float textYLeft = y + padding + lineHeight * 0.8f;
for (size_t i = 0; i <= splitIndex && i < vShortcuts.size(); ++i)
{
// Key (left-aligned)
draw_list->AddText(ImVec2(colLeftXKey, textYLeft), g_ColorWhite, vShortcuts[i].first.c_str());
// Description (right-aligned)
float descWidth = ImGui::CalcTextSize(vShortcuts[i].second.c_str()).x;
draw_list->AddText(ImVec2(colLeftXDesc - descWidth, textYLeft), g_ColorWhite, vShortcuts[i].second.c_str());
textYLeft += lineHeight;
}
// Right column
float textYRight = y + padding + lineHeight * 0.8f;
for (size_t i = splitIndex + 1; i < vShortcuts.size(); ++i)
{
// Key (left-aligned)
draw_list->AddText(ImVec2(colRightXKey, textYRight), g_ColorWhite, vShortcuts[i].first.c_str());
// Description (right-aligned)
float descWidth = ImGui::CalcTextSize(vShortcuts[i].second.c_str()).x;
draw_list->AddText(ImVec2(colRightXDesc - descWidth, textYRight), g_ColorWhite, vShortcuts[i].second.c_str());
textYRight += lineHeight;
}
ImGui::PopFont();
}
void RenderForceCursor()
{
if (!g_ForceActive || !g_ForceHasPrev)
return;
const mat4 proj = g_Camera.GetProjection();
const vec4 c = proj * g_Camera.GetView() * vec4(g_ForcePrev, 1.0f);
if (c.w <= 1e-3f)
return;
int ww, wh;
glfwGetWindowSize(g_hWindow, &ww, &wh);
double mx, my;
glfwGetCursorPos(g_hWindow, &mx, &my);
const float rpx = g_ForceRadius * std::abs(proj[1][1]) * (float)wh * 0.5f / c.w; // same formula as the point size
ImGui::GetBackgroundDrawList()->AddCircle(ImVec2((float)mx, (float)my), rpx, IM_COL32(255, 160, 30, 220), 48, 2.0f);
}
void FrameImGui(VkCommandBuffer commandBuffer)
{
auto RightAlignText = [&](const char* fmt, ...) {
char buf[64];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
float text_w = ImGui::CalcTextSize(buf).x;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetColumnWidth() - text_w - ImGui::GetStyle().ItemSpacing.x);
ImGui::Text("%s", buf);
};
ImGui_ImplVulkan_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
static string resultAnalyse;
static vector<vector<sResultData>> vResults;
#pragma region Scene F2
if (g_bShowSceneWindow)
{
// Fixed position at the bottom right of the window
ImVec2 window_size(300, 930);
ImVec2 window_pos(5, 5);
ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always);
ImGui::SetNextWindowSize(window_size, ImGuiCond_FirstUseEver);
/////////////////////////////////
if (ImGui::Begin("Scene [F2]", &g_bShowSceneWindow))
{
ImGui::Text("FPS = %d", g_nFps);
ImGui::SameLine();
double elapsed = glfwGetTime(); // seconds elapsed since the start of the program or ImGui
int hours = static_cast<int>(elapsed) / 3600;
int minutes = (static_cast<int>(elapsed) % 3600) / 60;
int seconds = static_cast<int>(elapsed) % 60;
char buffer[12];
snprintf(buffer, sizeof(buffer), " %02d:%02d:%02d", hours, minutes, seconds);
ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 255, 128, 255));
ImGui::SetWindowFontScale(1.5f);
ImGui::Text("%s", buffer);
ImGui::SetWindowFontScale(1.0f);
ImGui::PopStyleColor();
// ------------
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 0.0f, 1.0f));
// Camera type
switch (g_Camera.GetMode())
{
case eCameraMode::ORBITAL: ImGui::Text("[ ORBITAL ]"); break;
case eCameraMode::BRIDGE: ImGui::Text("[ BRIDGE ]"); break;
case eCameraMode::FPS: ImGui::Text("[ FPS ]"); break;
}
ImGui::SameLine();
// Interpolation function
switch (g_Camera.GetInterpolation())
{
case eInterpolation::Linear: ImGui::Text("( Linear )"); break;
case eInterpolation::SmoothStep:ImGui::Text("( SmoothStep )"); break;
case eInterpolation::EaseIn: ImGui::Text("( EaseIn )"); break;
case eInterpolation::EaseOut: ImGui::Text("( EaseOut )"); break;
case eInterpolation::EaseInOut: ImGui::Text("( EaseInOut )"); break;
}
ImGui::PopStyleColor(1);
// ------------
if (ImGui::Button(" PAUSE "))
{
g_bPause = !g_bPause;
if (g_bPause)
g_TimerScene.stop();
else
g_TimerScene.start();
}
ImGui::SameLine();
if (ImGui::Button(" FULLSCREEN "))
g_PendingFullscreen = true;
// ------------
if (ImGui::CollapsingHeader("OBJECTS", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Checkbox("Axis", &g_Axis->bVisible);
ImGui::SameLine();
ImGui::Checkbox("Bbox", &g_Bbox->bVisible);
ImGui::SameLine();
ImGui::Checkbox("Cyl", &g_Cylinder->bVisible);
}
// ------------
if (ImGui::CollapsingHeader("SPH SIMULATION", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 255, 0, 255));
if (ImGui::Button(" RESET SPH "))
g_PendingSphReset = true;
ImGui::PopStyleColor();
// ------------
bool usePcg = g_SphSolver.UsePcg();
if (ImGui::Checkbox("usePcg", &usePcg))
g_SphSolver.SetUsePcg(usePcg);
ImGui::SameLine();
bool bGravity = g_SphSolver.GravityEnabled();
if (ImGui::Checkbox("Gravity", &bGravity))
g_SphSolver.SetGravityEnabled(bGravity);
float tension = g_SphSolver.SurfaceTension();
if (ImGui::SliderFloat("Surface tension", &tension, 0.0f, 10.0f, "%.2f", ImGuiSliderFlags_Logarithmic))
g_SphSolver.SetSurfaceTension(tension);
// ------------
ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 0, 0, 255));
if (ImGui::Combo("Scenario", &g_Scenario, g_ScenarioNames, IM_ARRAYSIZE(g_ScenarioNames)))
g_PendingSphReset = true; // same path as the "Reset SPH" button
ImGui::PopStyleColor();
if (g_Scenario == (int)eScenario::WaveMaker)
{
bool changed = ImGui::SliderFloat("Stroke (m)", &g_WaveStroke, 0.05f, 0.8f, "%.1f");
changed |= ImGui::SliderFloat("Period (s)", &g_WavePeriod, 0.8f, 4.0f, "%.1f");
if (changed && g_SphSolver.WaveMakerEnabled())
g_SphSolver.SetWaveMaker(true, g_WaveStroke, g_WavePeriod); // live: no Reset needed
}
}
// ------------
if (ImGui::CollapsingHeader("RENDERING", ImGuiTreeNodeFlags_DefaultOpen))
{
// Pressure only exists with the PCG solver (warm[] is never written by the Jacobi solver)
const bool pcgOn = g_SphSolver.UsePcg();
const int pressureIdx = (int)SphSolver::ColorMode::Pressure;
int renderMode = g_SphSolver.RenderModeIndex();
ImGui::Text("Render");
ImGui::PushStyleColor(ImGuiCol_Text, IM_COL32(255, 255, 0, 255));
if (ImGui::RadioButton("Particles", &renderMode, 0))
g_SphSolver.SetRenderMode(0);
ImGui::SameLine();
if (ImGui::RadioButton("Surface", &renderMode, 1))
g_SphSolver.SetRenderMode(1);
ImGui::PopStyleColor();
ImGui::Separator();
// ------------
ImGui::Text("Surface");
SphSurface::Settings& s = g_SphSolver.SurfaceSettings();
ImGui::SliderFloat("Sphere radius", &s.radiusScale, 0.5f, 2.0f); // (x spacing)
ImGui::SliderInt("Blur iterations", &s.nBlurIterations, 1, 4);
ImGui::SliderFloat("Filter radius", &s.filterRadius, 0.5f, 6.0f);
ImGui::SliderFloat("Depth sigma", &s.depthSigma, 0.2f, 3.0f);
ImGui::SliderInt("Max filter (px)", &s.nMaxFilterPixels, 4, 48);
ImGui::ColorEdit3("Water color", &s.waterColor.x);
ImGui::SliderFloat("Absorption", &s.absorption, 0.0f, 10.0f);
ImGui::SliderFloat("Fresnel F0", &s.fresnelF0, 0.0f, 0.2f);
ImGui::SliderFloat("Specular power", &s.specularPower, 8.0f, 600.0f);
ImGui::SliderFloat("Light azimuth", &s.lightAzimuth, -180.0f, 180.0f);
ImGui::SliderFloat("Light elevation", &s.lightElevation, 5.0f, 90.0f);
ImGui::SliderFloat("Exposure", &s.exposure, 0.3f, 2.0f);
// ------------
ImGui::Separator();
ImGui::Text("Particles");
int colorMode = g_SphSolver.ColorModeIndex();
if (!pcgOn && colorMode == pressureIdx)
{
colorMode = (int)SphSolver::ColorMode::Density; // fall back to a mode that works
g_SphSolver.SetColorMode(colorMode);
}
// Combo built by hand to hide the unavailable entry
const char* const* names = SphSolver::ColorModeNames();
if (ImGui::BeginCombo("Color by", names[colorMode]))
{
for (int n = 0; n < SphSolver::ColorModeCount(); ++n)
{
if (n == pressureIdx && !pcgOn)
continue;
const bool selected = (n == colorMode);
if (ImGui::Selectable(names[n], selected))
g_SphSolver.SetColorMode(n); // also resets the range to a sensible default
if (selected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
float lo = g_SphSolver.ColorMin();
float hi = g_SphSolver.ColorMax();
const float step = std::max((hi - lo) * 0.005f, 1e-4f);
bool changed = ImGui::DragFloat("Min", &lo, step, 0.0f, 0.0f, "%.1f");
changed |= ImGui::DragFloat("Max", &hi, step, 0.0f, 0.0f, "%.1f");
if (changed)
g_SphSolver.SetColorRange(lo, hi);
if (ImGui::Button("Reset range"))
g_SphSolver.ResetColorRange();
// Legend (same ramp as sph.frag: blue -> cyan -> green -> yellow -> red)
{
ImVec2 p = ImGui::GetCursorScreenPos();
float w = ImGui::GetContentRegionAvail().x, bar = 12.0f;
ImDrawList* dl = ImGui::GetWindowDrawList();
const ImU32 stops[5] = {
IM_COL32(0, 0, 255, 255), // blue
IM_COL32(0, 255, 255, 255), // cyan
IM_COL32(0, 255, 0, 255), // green
IM_COL32(255, 255, 0, 255), // yellow
IM_COL32(255, 0, 0, 255) // red
};
const float seg = w * 0.25f;
for (int s = 0; s < 4; ++s)
{
ImVec2 a(p.x + seg * s, p.y), b(p.x + seg * (s + 1), p.y + bar);
dl->AddRectFilledMultiColor(a, b, stops[s], stops[s + 1], stops[s + 1], stops[s]);
}
ImGui::Dummy(ImVec2(w, bar));
ImGui::Text("%.0f", lo); ImGui::SameLine(w - 40.0f); ImGui::Text("%.0f", hi);
}
// ------------
float ps = g_SphSolver.PointScale();
if (ImGui::SliderFloat("Point size", &ps, 0.2f, 3.0f, "%0.1f"))
g_SphSolver.SetPointScale(ps);
}
// ------------
if (ImGui::CollapsingHeader("FORCE CURSOR", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Text("Force cursor (right mouse button)");
ImGui::SliderFloat("Radius", &g_ForceRadius, 0.1f, 1.5f, "%.1f");
ImGui::SliderFloat("Stiffness", &g_ForceStiffness, 0.0f, 80.0f, "%.1f");
ImGui::SliderFloat("Depth", &g_ForceDepth, -1.3f, 1.3f, "%.1f");
}
}
ImGui::End();
}
#pragma endregion
//RenderEnv(g_WindowW - 85, 5);
RenderSphSolverInfo();
RenderShortcuts(); // F1
RenderStatusbar(); // F4
RenderInfo();
RenderTitle();
RenderForceCursor();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
ImGui_ImplVulkan_RenderDrawData(draw_data, commandBuffer);
}
// Render
void FrameRender(VkCommandBuffer commandBuffer, uint32_t imageIndex)
{
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
// SPH compute: must be recorded outside the render pass (also handles the initial upload, even when paused with dt = 0)
float simDt = 0.0f;
if (g_SphDt >= 0.004f) // about maxDt: do not run the solver for tiny steps
{
simDt = g_SphDt;
g_SphDt = 0.0f;
}
g_SphSolver.Update(commandBuffer, g_iCurrentFrame, simDt);
g_SphSolver.RecordSurface(commandBuffer, g_iCurrentFrame, g_Camera);
float width = (float)g_SwapChain->extent.width;
float height = (float)g_SwapChain->extent.height;
VkViewport viewport{ 0, 0, width, height, 0, 1 };
vkCmdSetViewport(commandBuffer, 0, 1, &viewport);
VkRect2D scissor{ { 0, 0 }, g_SwapChain->extent };
vkCmdSetScissor(commandBuffer, 0, 1, &scissor);
// UBO updates must happen outside the render pass
g_Axis->UpdateMsUBOs(imageIndex, g_Camera, g_Sky.get(), mat4(1.0f));
// One entry per attachment up to the last one that is cleared (index 1); index 2 (swapchain) uses DONT_CARE so its value is ignored
VkClearValue clearValues[3]{};
clearValues[0].color = { { 0.25f, 0.25f, 0.25f, 1.0f } };
clearValues[1].depthStencil = { 1.0f, 0 };
VkRenderPassBeginInfo passInfo{};
passInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
passInfo.renderPass = g_RenderPass;
passInfo.framebuffer = g_vFramebuffersSwapChain[imageIndex];
passInfo.renderArea.offset = { 0, 0 };
passInfo.renderArea.extent = g_SwapChain->extent;
passInfo.clearValueCount = 3;
passInfo.pClearValues = clearValues;
vkCmdBeginRenderPass(commandBuffer, &passInfo, VK_SUBPASS_CONTENTS_INLINE);
// Subpass 0: MSAA scene
g_Axis->RenderMs(commandBuffer, g_iCurrentFrame);
g_Bbox->RenderBbox(commandBuffer, g_iCurrentFrame, g_Camera, mat4(1.0f), vec4(1.0f, 1.0f, 1.0f, 1.0f));
if (g_SphSolver.WaveMakerEnabled())
{
const float dx = g_SphSolver.PistonPosition() - g_SphSolver.BoxMin().x;
g_Piston->RenderBbox(commandBuffer, g_iCurrentFrame, g_Camera, glm::translate(mat4(1.0f), vec3(dx, 0.0f, 0.0f)), vec4(1.0f, 0.4f, 0.2f, 1.0f));
}
g_Cylinder->Render(commandBuffer, g_iCurrentFrame, g_Camera, mat4(1.0f), vec4(1.0f, 1.0f, 1.0f, 1.0f));
g_SphSolver.Render(commandBuffer, g_iCurrentFrame, g_Camera, 1.0f, 1.0f); // size = 1 x spacing
// Subpass 1: ImGui
vkCmdNextSubpass(commandBuffer, VK_SUBPASS_CONTENTS_INLINE);
FrameImGui(commandBuffer);
vkCmdEndRenderPass(commandBuffer);
vkEndCommandBuffer(commandBuffer);
}
void Render()
{
// Wait for the current frame's fence before reusing its resources
vkWaitForFences(g_Device->device, 1, &g_vImageFences[g_iCurrentFrame], VK_TRUE, UINT64_MAX);
// Acquire the next swapchain image; signal imageAvailable[currentFrame] when ready
uint32_t imageIndex;
VkResult result = vkAcquireNextImageKHR(g_Device->device, g_SwapChain->swapChain, UINT64_MAX, g_vImageAvailableSemaphores[g_iCurrentFrame], // indexed on currentFrame
VK_NULL_HANDLE, &imageIndex);
if (result == VK_ERROR_OUT_OF_DATE_KHR)
return; // Handle swapchain recreation here if needed
// Reset fence and command buffer only once we know this frame will be submitted
vkResetFences(g_Device->device, 1, &g_vImageFences[g_iCurrentFrame]);
vkResetCommandBuffer(g_vCommandBuffers[g_iCurrentFrame], 0);
// Record all rendering commands for this frame
FrameRender(g_vCommandBuffers[g_iCurrentFrame], imageIndex);
// ── Build wait semaphore list ────────────────────────────────────────
VkSemaphore waitSemaphores[3];
VkPipelineStageFlags waitStages[3];
uint32_t waitCount = 0;
// Always wait for the swapchain image to be available
waitSemaphores[waitCount] = g_vImageAvailableSemaphores[g_iCurrentFrame];
waitStages[waitCount] = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
waitCount++;
// ── Submit graphics command buffer ───────────────────────────────────
// Signal semaphore indexed on currentFrame (NOT imageIndex) to avoid signaling a semaphore still pending from a previous present cycle
VkSemaphore signalSemaphores[] = { g_vRenderFinishedSemaphores[g_iCurrentFrame] };
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.waitSemaphoreCount = waitCount;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &g_vCommandBuffers[g_iCurrentFrame];
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
// Fence signals when this frame's GPU work is complete
vkQueueSubmit(g_Device->graphicsQueue, 1, &submitInfo, g_vImageFences[g_iCurrentFrame]);
// ── Present ──────────────────────────────────────────────────────────
// Wait on the same renderFinished[currentFrame] semaphore before presenting
VkSwapchainKHR swapchains[] = { g_SwapChain->swapChain };
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores; // currentFrame ✅
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapchains;
presentInfo.pImageIndices = &imageIndex;
vkQueuePresentKHR(g_Device->presentQueue, &presentInfo);
g_FpsFrameCount++;
double currentTime = glfwGetTime();
if (currentTime - g_FpsTime >= 1.0)
{
g_nFps = static_cast<int>(g_FpsFrameCount / (currentTime - g_FpsTime));
g_FpsFrameCount = 0;
g_FpsTime = currentTime;
}
// Advance to the next frame slot (wraps around MAX_FRAMES_IN_FLIGHT)
g_iCurrentFrame = (g_iCurrentFrame + 1) % g_vImageFences.size();
}
// Initialization
void InitConsole()
{
// Create a Windows console attached to the process
// UTF-8 codepage for Windows console
SetConsoleOutputCP(65001);
SetConsoleCP(65001);
// Force UTF-16 for streams
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stderr), _O_U16TEXT);
// Locales + sync
ios::sync_with_stdio(false);
locale::global(locale(".65001")); // UTF-8 locale
// Fix wcout specific to Windows
wcout.imbue(locale(".65001"));
wcerr.imbue(locale(".65001"));
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
freopen("CONIN$", "r", stdin);
SetConsoleOutputCP(65001);
SetConsoleCP(65001);
SetConsoleTitle(L"SimFluid Console");
SetWindowPos(GetConsoleWindow(), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE);
}
void InitWindow()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
g_hWindow = glfwCreateWindow(g_WindowW, g_WindowH, "SimFluid (Vulkan)", nullptr, nullptr);
if (!g_hWindow)
throw runtime_error("Failed to create GLFW window");
// Center the window on the primary monitor
g_Monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* videoMode = glfwGetVideoMode(g_Monitor);
glfwSetWindowPos(g_hWindow, (videoMode->width - g_WindowW) / 2, (videoMode->height - g_WindowH) / 2);
glfwSetFramebufferSizeCallback(g_hWindow, framebuffer_size_callback);
glfwSetCursorPosCallback(g_hWindow, CursorPosCallback);
glfwSetScrollCallback(g_hWindow, ScrollCallback);
glfwSetMouseButtonCallback(g_hWindow, MouseButtonCallback);
glfwSetKeyCallback(g_hWindow, KeyCallback);
glfwShowWindow(g_hWindow);
}
void CreateInstance()
{
// Create a Vulkan instance (the global context)
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Vulkan";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 4, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 4, 0);
appInfo.apiVersion = VK_API_VERSION_1_4;
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
// Validation layers
if (g_bEnableValidationLayers)
{
if (!checkValidationLayerSupport())
throw runtime_error("Validation layers are not available!");
createInfo.enabledLayerCount = static_cast<uint32_t>(g_vValidationLayers.size());
createInfo.ppEnabledLayerNames = g_vValidationLayers.data();
#ifdef INFO_INIT // Structures.h
wcout << L"Validation layers enabled\n";
#endif
}
else
createInfo.enabledLayerCount = 0;
// Extensions
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
if (g_bEnableValidationLayers)
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
createInfo.ppEnabledExtensionNames = extensions.data();
if (vkCreateInstance(&createInfo, nullptr, &g_Instance) != VK_SUCCESS)
throw runtime_error("Vulkan instance creation failed");
if (g_bEnableValidationLayers)
setupDebugMessenger(g_Instance);
#ifdef INFO_INIT // Structures.h
wcout << L"Instance OK\n";
#endif
}
void CreateRenderPass()
{
VkFormat colorFormat = g_SwapChain->imageFormat;
VkFormat depthFormat = FindDepthFormat();
// Attachment 0: MSAA color (render target, never stored)
VkAttachmentDescription colorMsaa{};
colorMsaa.format = colorFormat;
colorMsaa.samples = g_Device->msaaSamples;
colorMsaa.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorMsaa.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorMsaa.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorMsaa.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorMsaa.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorMsaa.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// Attachment 1: MSAA depth (never stored)
VkAttachmentDescription depthMsaa{};
depthMsaa.format = depthFormat;
depthMsaa.samples = g_Device->msaaSamples;
depthMsaa.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthMsaa.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthMsaa.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthMsaa.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthMsaa.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depthMsaa.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
// Attachment 2: swapchain image (MSAA resolve target, then ImGui target)
VkAttachmentDescription swapchain{};
swapchain.format = colorFormat;
swapchain.samples = VK_SAMPLE_COUNT_1_BIT;
swapchain.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // fully overwritten by the resolve
swapchain.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
swapchain.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
swapchain.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
swapchain.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
swapchain.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
array<VkAttachmentDescription, 3> attachments = { colorMsaa, depthMsaa, swapchain };
VkAttachmentReference colorRef{ 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
VkAttachmentReference depthRef{ 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
VkAttachmentReference swapRef{ 2, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
VkSubpassDescription subpasses[2]{};
// Subpass 0: MSAA scene, resolved into the swapchain image at the end of the subpass
subpasses[0].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpasses[0].colorAttachmentCount = 1;
subpasses[0].pColorAttachments = &colorRef;
subpasses[0].pResolveAttachments = &swapRef;
subpasses[0].pDepthStencilAttachment = &depthRef;
// Subpass 1: ImGui, drawn 1x on top of the resolved image
subpasses[1].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpasses[1].colorAttachmentCount = 1;
subpasses[1].pColorAttachments = &swapRef;
VkSubpassDependency deps[2]{};
// External -> subpass 0: wait for swapchain acquire (imageAvailable semaphore)
deps[0].srcSubpass = VK_SUBPASS_EXTERNAL;
deps[0].dstSubpass = 0;
deps[0].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
deps[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
deps[0].srcAccessMask = 0;
deps[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
// Subpass 0 -> subpass 1: resolve must finish before ImGui blends over it
deps[1].srcSubpass = 0;
deps[1].dstSubpass = 1;
deps[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
deps[1].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
deps[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;