-
Notifications
You must be signed in to change notification settings - Fork 100
/
main.cpp
3287 lines (2715 loc) · 92.8 KB
/
main.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
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2013-2020 NVIDIA Corporation. All rights reserved.
#include "../core/types.h"
#include "../core/maths.h"
#include "../core/platform.h"
#include "../core/mesh.h"
#include "../core/voxelize.h"
#include "../core/sdf.h"
#include "../core/pfm.h"
#include "../core/tga.h"
#include "../core/perlin.h"
#include "../core/convex.h"
#include "../core/cloth.h"
#include "../external/SDL2-2.0.4/include/SDL.h"
#include "../include/NvFlex.h"
#include "../include/NvFlexExt.h"
#include "../include/NvFlexDevice.h"
#include <iostream>
#include <map>
#include "shaders.h"
#include "imgui.h"
#include "shadersDemoContext.h"
#if FLEX_DX
#include "d3d\appGraphCtx.h"
#endif
#if ENABLE_AFTERMATH_SUPPORT
#include <external/GFSDK_Aftermath_v1.21/include/GFSDK_Aftermath.h>
#endif
SDL_Window* g_window; // window handle
unsigned int g_windowId; // window id
#define SDL_CONTROLLER_BUTTON_LEFT_TRIGGER (SDL_CONTROLLER_BUTTON_MAX + 1)
#define SDL_CONTROLLER_BUTTON_RIGHT_TRIGGER (SDL_CONTROLLER_BUTTON_MAX + 2)
int GetKeyFromGameControllerButton(SDL_GameControllerButton button)
{
switch (button)
{
case SDL_CONTROLLER_BUTTON_DPAD_UP: { return SDLK_q; } // -- camera translate up
case SDL_CONTROLLER_BUTTON_DPAD_DOWN: { return SDLK_z; } // -- camera translate down
case SDL_CONTROLLER_BUTTON_DPAD_LEFT: { return SDLK_h; } // -- hide GUI
case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: { return -1; } // -- unassigned
case SDL_CONTROLLER_BUTTON_START: { return SDLK_RETURN; } // -- start selected scene
case SDL_CONTROLLER_BUTTON_BACK: { return SDLK_ESCAPE; } // -- quit
case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: { return SDLK_UP; } // -- select prev scene
case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: { return SDLK_DOWN; } // -- select next scene
case SDL_CONTROLLER_BUTTON_A: { return SDLK_g; } // -- toggle gravity
case SDL_CONTROLLER_BUTTON_B: { return SDLK_p; } // -- pause
case SDL_CONTROLLER_BUTTON_X: { return SDLK_r; } // -- reset
case SDL_CONTROLLER_BUTTON_Y: { return SDLK_o; } // -- step sim
case SDL_CONTROLLER_BUTTON_RIGHT_TRIGGER: { return SDLK_SPACE; } // -- emit particles
default: { return -1; } // -- nop
};
};
//
// Gamepad thresholds taken from XINPUT API
//
#define XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE 7849
#define XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE 8689
#define XINPUT_GAMEPAD_TRIGGER_THRESHOLD 30
int deadzones[3] = { XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE, XINPUT_GAMEPAD_TRIGGER_THRESHOLD };
inline float joyAxisFilter(int value, int stick)
{
//clamp values in deadzone to zero, and remap rest of range so that it linearly rises in value from edge of deadzone toward max value.
if (value < -deadzones[stick])
return (value + deadzones[stick]) / (32768.0f - deadzones[stick]);
else if (value > deadzones[stick])
return (value - deadzones[stick]) / (32768.0f - deadzones[stick]);
else
return 0.0f;
}
SDL_GameController* g_gamecontroller = NULL;
using namespace std;
int g_screenWidth = 1280;
int g_screenHeight = 720;
int g_msaaSamples = 8;
int g_numSubsteps;
// a setting of -1 means Flex will use the device specified in the NVIDIA control panel
int g_device = -1;
char g_deviceName[256];
bool g_vsync = true;
bool g_benchmark = false;
bool g_extensions = true;
bool g_teamCity = false;
bool g_interop = true;
bool g_d3d12 = false;
bool g_useAsyncCompute = true;
bool g_increaseGfxLoadForAsyncComputeTesting = false;
int g_graphics = 0; // 0=ogl, 1=DX11, 2=DX12
FluidRenderer* g_fluidRenderer;
FluidRenderBuffers* g_fluidRenderBuffers;
DiffuseRenderBuffers* g_diffuseRenderBuffers;
NvFlexSolver* g_solver;
NvFlexSolverDesc g_solverDesc;
NvFlexLibrary* g_flexLib;
NvFlexParams g_params;
NvFlexTimers g_timers;
int g_numDetailTimers;
NvFlexDetailTimer * g_detailTimers;
int g_maxDiffuseParticles;
int g_maxNeighborsPerParticle;
int g_numExtraParticles;
int g_numExtraMultiplier = 1;
int g_maxContactsPerParticle;
// mesh used for deformable object rendering
Mesh* g_mesh;
vector<int> g_meshSkinIndices;
vector<float> g_meshSkinWeights;
vector<Point3> g_meshRestPositions;
const int g_numSkinWeights = 4;
// mapping of collision mesh to render mesh
std::map<NvFlexConvexMeshId, GpuMesh*> g_convexes;
std::map<NvFlexTriangleMeshId, GpuMesh*> g_meshes;
std::map<NvFlexDistanceFieldId, GpuMesh*> g_fields;
// flag to request collision shapes be updated
bool g_shapesChanged = false;
/* Note that this array of colors is altered by demo code, and is also read from global by graphics API impls */
Colour g_colors[] =
{
Colour(0.0f, 0.5f, 1.0f),
Colour(0.797f, 0.354f, 0.000f),
Colour(0.092f, 0.465f, 0.820f),
Colour(0.000f, 0.349f, 0.173f),
Colour(0.875f, 0.782f, 0.051f),
Colour(0.000f, 0.170f, 0.453f),
Colour(0.673f, 0.111f, 0.000f),
Colour(0.612f, 0.194f, 0.394f)
};
struct SimBuffers
{
NvFlexVector<Vec4> positions;
NvFlexVector<Vec4> restPositions;
NvFlexVector<Vec3> velocities;
NvFlexVector<int> phases;
NvFlexVector<float> densities;
NvFlexVector<Vec4> anisotropy1;
NvFlexVector<Vec4> anisotropy2;
NvFlexVector<Vec4> anisotropy3;
NvFlexVector<Vec4> normals;
NvFlexVector<Vec4> smoothPositions;
NvFlexVector<Vec4> diffusePositions;
NvFlexVector<Vec4> diffuseVelocities;
NvFlexVector<int> diffuseCount;
NvFlexVector<int> activeIndices;
// convexes
NvFlexVector<NvFlexCollisionGeometry> shapeGeometry;
NvFlexVector<Vec4> shapePositions;
NvFlexVector<Quat> shapeRotations;
NvFlexVector<Vec4> shapePrevPositions;
NvFlexVector<Quat> shapePrevRotations;
NvFlexVector<int> shapeFlags;
// rigids
NvFlexVector<int> rigidOffsets;
NvFlexVector<int> rigidIndices;
NvFlexVector<int> rigidMeshSize;
NvFlexVector<float> rigidCoefficients;
NvFlexVector<float> rigidPlasticThresholds;
NvFlexVector<float> rigidPlasticCreeps;
NvFlexVector<Quat> rigidRotations;
NvFlexVector<Vec3> rigidTranslations;
NvFlexVector<Vec3> rigidLocalPositions;
NvFlexVector<Vec4> rigidLocalNormals;
// inflatables
NvFlexVector<int> inflatableTriOffsets;
NvFlexVector<int> inflatableTriCounts;
NvFlexVector<float> inflatableVolumes;
NvFlexVector<float> inflatableCoefficients;
NvFlexVector<float> inflatablePressures;
// springs
NvFlexVector<int> springIndices;
NvFlexVector<float> springLengths;
NvFlexVector<float> springStiffness;
NvFlexVector<int> triangles;
NvFlexVector<Vec3> triangleNormals;
NvFlexVector<Vec3> uvs;
SimBuffers(NvFlexLibrary* l) :
positions(l), restPositions(l), velocities(l), phases(l), densities(l),
anisotropy1(l), anisotropy2(l), anisotropy3(l), normals(l), smoothPositions(l),
diffusePositions(l), diffuseVelocities(l), diffuseCount(l), activeIndices(l),
shapeGeometry(l), shapePositions(l), shapeRotations(l), shapePrevPositions(l),
shapePrevRotations(l), shapeFlags(l), rigidOffsets(l), rigidIndices(l), rigidMeshSize(l),
rigidCoefficients(l), rigidPlasticThresholds(l), rigidPlasticCreeps(l), rigidRotations(l), rigidTranslations(l),
rigidLocalPositions(l), rigidLocalNormals(l), inflatableTriOffsets(l),
inflatableTriCounts(l), inflatableVolumes(l), inflatableCoefficients(l),
inflatablePressures(l), springIndices(l), springLengths(l),
springStiffness(l), triangles(l), triangleNormals(l), uvs(l)
{}
};
SimBuffers* g_buffers;
void MapBuffers(SimBuffers* buffers)
{
buffers->positions.map();
buffers->restPositions.map();
buffers->velocities.map();
buffers->phases.map();
buffers->densities.map();
buffers->anisotropy1.map();
buffers->anisotropy2.map();
buffers->anisotropy3.map();
buffers->normals.map();
buffers->diffusePositions.map();
buffers->diffuseVelocities.map();
buffers->diffuseCount.map();
buffers->smoothPositions.map();
buffers->activeIndices.map();
// convexes
buffers->shapeGeometry.map();
buffers->shapePositions.map();
buffers->shapeRotations.map();
buffers->shapePrevPositions.map();
buffers->shapePrevRotations.map();
buffers->shapeFlags.map();
buffers->rigidOffsets.map();
buffers->rigidIndices.map();
buffers->rigidMeshSize.map();
buffers->rigidCoefficients.map();
buffers->rigidPlasticThresholds.map();
buffers->rigidPlasticCreeps.map();
buffers->rigidRotations.map();
buffers->rigidTranslations.map();
buffers->rigidLocalPositions.map();
buffers->rigidLocalNormals.map();
buffers->springIndices.map();
buffers->springLengths.map();
buffers->springStiffness.map();
// inflatables
buffers->inflatableTriOffsets.map();
buffers->inflatableTriCounts.map();
buffers->inflatableVolumes.map();
buffers->inflatableCoefficients.map();
buffers->inflatablePressures.map();
buffers->triangles.map();
buffers->triangleNormals.map();
buffers->uvs.map();
}
void UnmapBuffers(SimBuffers* buffers)
{
// particles
buffers->positions.unmap();
buffers->restPositions.unmap();
buffers->velocities.unmap();
buffers->phases.unmap();
buffers->densities.unmap();
buffers->anisotropy1.unmap();
buffers->anisotropy2.unmap();
buffers->anisotropy3.unmap();
buffers->normals.unmap();
buffers->diffusePositions.unmap();
buffers->diffuseVelocities.unmap();
buffers->diffuseCount.unmap();
buffers->smoothPositions.unmap();
buffers->activeIndices.unmap();
// convexes
buffers->shapeGeometry.unmap();
buffers->shapePositions.unmap();
buffers->shapeRotations.unmap();
buffers->shapePrevPositions.unmap();
buffers->shapePrevRotations.unmap();
buffers->shapeFlags.unmap();
// rigids
buffers->rigidOffsets.unmap();
buffers->rigidIndices.unmap();
buffers->rigidMeshSize.unmap();
buffers->rigidCoefficients.unmap();
buffers->rigidPlasticThresholds.unmap();
buffers->rigidPlasticCreeps.unmap();
buffers->rigidRotations.unmap();
buffers->rigidTranslations.unmap();
buffers->rigidLocalPositions.unmap();
buffers->rigidLocalNormals.unmap();
// springs
buffers->springIndices.unmap();
buffers->springLengths.unmap();
buffers->springStiffness.unmap();
// inflatables
buffers->inflatableTriOffsets.unmap();
buffers->inflatableTriCounts.unmap();
buffers->inflatableVolumes.unmap();
buffers->inflatableCoefficients.unmap();
buffers->inflatablePressures.unmap();
// triangles
buffers->triangles.unmap();
buffers->triangleNormals.unmap();
buffers->uvs.unmap();
}
SimBuffers* AllocBuffers(NvFlexLibrary* lib)
{
return new SimBuffers(lib);
}
void DestroyBuffers(SimBuffers* buffers)
{
// particles
buffers->positions.destroy();
buffers->restPositions.destroy();
buffers->velocities.destroy();
buffers->phases.destroy();
buffers->densities.destroy();
buffers->anisotropy1.destroy();
buffers->anisotropy2.destroy();
buffers->anisotropy3.destroy();
buffers->normals.destroy();
buffers->diffusePositions.destroy();
buffers->diffuseVelocities.destroy();
buffers->diffuseCount.destroy();
buffers->smoothPositions.destroy();
buffers->activeIndices.destroy();
// convexes
buffers->shapeGeometry.destroy();
buffers->shapePositions.destroy();
buffers->shapeRotations.destroy();
buffers->shapePrevPositions.destroy();
buffers->shapePrevRotations.destroy();
buffers->shapeFlags.destroy();
// rigids
buffers->rigidOffsets.destroy();
buffers->rigidIndices.destroy();
buffers->rigidMeshSize.destroy();
buffers->rigidCoefficients.destroy();
buffers->rigidPlasticThresholds.destroy();
buffers->rigidPlasticCreeps.destroy();
buffers->rigidRotations.destroy();
buffers->rigidTranslations.destroy();
buffers->rigidLocalPositions.destroy();
buffers->rigidLocalNormals.destroy();
// springs
buffers->springIndices.destroy();
buffers->springLengths.destroy();
buffers->springStiffness.destroy();
// inflatables
buffers->inflatableTriOffsets.destroy();
buffers->inflatableTriCounts.destroy();
buffers->inflatableVolumes.destroy();
buffers->inflatableCoefficients.destroy();
buffers->inflatablePressures.destroy();
// triangles
buffers->triangles.destroy();
buffers->triangleNormals.destroy();
buffers->uvs.destroy();
delete buffers;
}
Vec3 g_camPos(6.0f, 8.0f, 18.0f);
Vec3 g_camAngle(0.0f, -DegToRad(20.0f), 0.0f);
Vec3 g_camVel(0.0f);
Vec3 g_camSmoothVel(0.0f);
float g_camSpeed;
float g_camNear;
float g_camFar;
Vec3 g_lightPos;
Vec3 g_lightDir;
Vec3 g_lightTarget;
bool g_pause = false;
bool g_step = false;
bool g_capture = false;
bool g_showHelp = true;
bool g_tweakPanel = true;
bool g_fullscreen = false;
bool g_wireframe = false;
bool g_debug = false;
bool g_emit = false;
bool g_warmup = false;
float g_windTime = 0.0f;
float g_windFrequency = 0.1f;
float g_windStrength = 0.0f;
bool g_wavePool = false;
float g_waveTime = 0.0f;
float g_wavePlane;
float g_waveFrequency = 1.5f;
float g_waveAmplitude = 1.0f;
float g_waveFloorTilt = 0.0f;
Vec3 g_sceneLower;
Vec3 g_sceneUpper;
float g_blur;
float g_ior;
bool g_drawEllipsoids;
bool g_drawPoints;
bool g_drawMesh;
bool g_drawCloth;
float g_expandCloth; // amount to expand cloth along normal (to account for particle radius)
bool g_drawOpaque;
int g_drawSprings; // 0: no draw, 1: draw stretch 2: draw tether
bool g_drawBases = false;
bool g_drawContacts = false;
bool g_drawNormals = false;
bool g_drawDiffuse;
bool g_drawShapeGrid = false;
bool g_drawDensity = false;
bool g_drawRopes;
float g_pointScale;
float g_ropeScale;
float g_drawPlaneBias; // move planes along their normal for rendering
float g_diffuseScale;
float g_diffuseMotionScale;
bool g_diffuseShadow;
float g_diffuseInscatter;
float g_diffuseOutscatter;
float g_dt = 1.0f / 60.0f; // the time delta used for simulation
float g_realdt; // the real world time delta between updates
float g_waitTime; // the CPU time spent waiting for the GPU
float g_updateTime; // the CPU time spent on Flex
float g_renderTime; // the CPU time spent calling OpenGL to render the scene
// the above times don't include waiting for vsync
float g_simLatency; // the time the GPU spent between the first and last NvFlexUpdateSolver() operation. Because some GPUs context switch, this can include graphics time.
int g_scene = 0;
int g_selectedScene = g_scene;
int g_levelScroll; // offset for level selection scroll area
bool g_resetScene = false; //if the user clicks the reset button or presses the reset key this is set to true;
int g_frame = 0;
int g_numSolidParticles = 0;
int g_mouseParticle = -1;
float g_mouseT = 0.0f;
Vec3 g_mousePos;
float g_mouseMass;
bool g_mousePicked = false;
// mouse
int g_lastx;
int g_lasty;
int g_lastb = -1;
bool g_profile = false;
bool g_outputAllFrameTimes = false;
bool g_asyncComputeBenchmark = false;
ShadowMap* g_shadowMap;
Vec4 g_fluidColor;
Vec4 g_diffuseColor;
Vec3 g_meshColor;
Vec3 g_clearColor;
float g_lightDistance;
float g_fogDistance;
FILE* g_ffmpeg;
void DrawShapes();
class Scene;
vector<Scene*> g_scenes;
struct Emitter
{
Emitter() : mSpeed(0.0f), mEnabled(false), mLeftOver(0.0f), mWidth(8) {}
Vec3 mPos;
Vec3 mDir;
Vec3 mRight;
float mSpeed;
bool mEnabled;
float mLeftOver;
int mWidth;
};
vector<Emitter> g_emitters(1); // first emitter is the camera 'gun'
struct Rope
{
std::vector<int> mIndices;
};
vector<Rope> g_ropes;
inline float sqr(float x) { return x*x; }
#include "helpers.h"
#include "scenes.h"
#include "benchmark.h"
void Init(int scene, bool centerCamera = true)
{
RandInit();
if (g_solver)
{
if (g_buffers)
DestroyBuffers(g_buffers);
DestroyFluidRenderBuffers(g_fluidRenderBuffers);
DestroyDiffuseRenderBuffers(g_diffuseRenderBuffers);
for (auto& iter : g_meshes)
{
NvFlexDestroyTriangleMesh(g_flexLib, iter.first);
DestroyGpuMesh(iter.second);
}
for (auto& iter : g_fields)
{
NvFlexDestroyDistanceField(g_flexLib, iter.first);
DestroyGpuMesh(iter.second);
}
for (auto& iter : g_convexes)
{
NvFlexDestroyConvexMesh(g_flexLib, iter.first);
DestroyGpuMesh(iter.second);
}
g_fields.clear();
g_meshes.clear();
g_convexes.clear();
NvFlexDestroySolver(g_solver);
g_solver = NULL;
}
// alloc buffers
g_buffers = AllocBuffers(g_flexLib);
// map during initialization
MapBuffers(g_buffers);
g_buffers->positions.resize(0);
g_buffers->velocities.resize(0);
g_buffers->phases.resize(0);
g_buffers->rigidOffsets.resize(0);
g_buffers->rigidIndices.resize(0);
g_buffers->rigidMeshSize.resize(0);
g_buffers->rigidRotations.resize(0);
g_buffers->rigidTranslations.resize(0);
g_buffers->rigidCoefficients.resize(0);
g_buffers->rigidPlasticThresholds.resize(0);
g_buffers->rigidPlasticCreeps.resize(0);
g_buffers->rigidLocalPositions.resize(0);
g_buffers->rigidLocalNormals.resize(0);
g_buffers->springIndices.resize(0);
g_buffers->springLengths.resize(0);
g_buffers->springStiffness.resize(0);
g_buffers->triangles.resize(0);
g_buffers->triangleNormals.resize(0);
g_buffers->uvs.resize(0);
g_meshSkinIndices.resize(0);
g_meshSkinWeights.resize(0);
g_emitters.resize(1);
g_emitters[0].mEnabled = false;
g_emitters[0].mSpeed = 1.0f;
g_emitters[0].mLeftOver = 0.0f;
g_emitters[0].mWidth = 8;
g_buffers->shapeGeometry.resize(0);
g_buffers->shapePositions.resize(0);
g_buffers->shapeRotations.resize(0);
g_buffers->shapePrevPositions.resize(0);
g_buffers->shapePrevRotations.resize(0);
g_buffers->shapeFlags.resize(0);
g_ropes.resize(0);
// remove collision shapes
delete g_mesh; g_mesh = NULL;
g_frame = 0;
g_pause = false;
g_dt = 1.0f / 60.0f;
g_waveTime = 0.0f;
g_windTime = 0.0f;
g_windStrength = 1.0f;
g_blur = 1.0f;
g_fluidColor = Vec4(0.1f, 0.4f, 0.8f, 1.0f);
g_meshColor = Vec3(0.9f, 0.9f, 0.9f);
g_drawEllipsoids = false;
g_drawPoints = true;
g_drawCloth = true;
g_expandCloth = 0.0f;
g_drawOpaque = false;
g_drawSprings = false;
g_drawDiffuse = false;
g_drawMesh = true;
g_drawRopes = true;
g_drawDensity = false;
g_ior = 1.0f;
g_lightDistance = 2.0f;
g_fogDistance = 0.005f;
g_camSpeed = 0.075f;
g_camNear = 0.01f;
g_camFar = 1000.0f;
g_pointScale = 1.0f;
g_ropeScale = 1.0f;
g_drawPlaneBias = 0.0f;
// sim params
g_params.gravity[0] = 0.0f;
g_params.gravity[1] = -9.8f;
g_params.gravity[2] = 0.0f;
g_params.wind[0] = 0.0f;
g_params.wind[1] = 0.0f;
g_params.wind[2] = 0.0f;
g_params.radius = 0.15f;
g_params.viscosity = 0.0f;
g_params.dynamicFriction = 0.0f;
g_params.staticFriction = 0.0f;
g_params.particleFriction = 0.0f; // scale friction between particles by default
g_params.freeSurfaceDrag = 0.0f;
g_params.drag = 0.0f;
g_params.lift = 0.0f;
g_params.numIterations = 3;
g_params.fluidRestDistance = 0.0f;
g_params.solidRestDistance = 0.0f;
g_params.anisotropyScale = 1.0f;
g_params.anisotropyMin = 0.1f;
g_params.anisotropyMax = 2.0f;
g_params.smoothing = 1.0f;
g_params.dissipation = 0.0f;
g_params.damping = 0.0f;
g_params.particleCollisionMargin = 0.0f;
g_params.shapeCollisionMargin = 0.0f;
g_params.collisionDistance = 0.0f;
g_params.sleepThreshold = 0.0f;
g_params.shockPropagation = 0.0f;
g_params.restitution = 0.0f;
g_params.maxSpeed = FLT_MAX;
g_params.maxAcceleration = 100.0f; // approximately 10x gravity
g_params.relaxationMode = eNvFlexRelaxationLocal;
g_params.relaxationFactor = 1.0f;
g_params.solidPressure = 1.0f;
g_params.adhesion = 0.0f;
g_params.cohesion = 0.025f;
g_params.surfaceTension = 0.0f;
g_params.vorticityConfinement = 0.0f;
g_params.buoyancy = 1.0f;
g_params.diffuseThreshold = 100.0f;
g_params.diffuseBuoyancy = 1.0f;
g_params.diffuseDrag = 0.8f;
g_params.diffuseBallistic = 16;
g_params.diffuseLifetime = 2.0f;
g_numSubsteps = 2;
// planes created after particles
g_params.numPlanes = 1;
g_diffuseScale = 0.5f;
g_diffuseColor = 1.0f;
g_diffuseMotionScale = 1.0f;
g_diffuseShadow = false;
g_diffuseInscatter = 0.8f;
g_diffuseOutscatter = 0.53f;
// reset phase 0 particle color to blue
g_colors[0] = Colour(0.0f, 0.5f, 1.0f);
g_numSolidParticles = 0;
g_waveFrequency = 1.5f;
g_waveAmplitude = 1.5f;
g_waveFloorTilt = 0.0f;
g_emit = false;
g_warmup = false;
g_mouseParticle = -1;
g_maxDiffuseParticles = 0; // number of diffuse particles
g_maxNeighborsPerParticle = 96;
g_numExtraParticles = 0; // number of particles allocated but not made active
g_maxContactsPerParticle = 6;
g_sceneLower = FLT_MAX;
g_sceneUpper = -FLT_MAX;
// initialize solver desc
NvFlexSetSolverDescDefaults(&g_solverDesc);
// create scene
StartGpuWork();
g_scenes[g_scene]->Initialize();
EndGpuWork();
uint32_t numParticles = g_buffers->positions.size();
uint32_t maxParticles = numParticles + g_numExtraParticles*g_numExtraMultiplier;
if (g_params.solidRestDistance == 0.0f)
g_params.solidRestDistance = g_params.radius;
// if fluid present then we assume solid particles have the same radius
if (g_params.fluidRestDistance > 0.0f)
g_params.solidRestDistance = g_params.fluidRestDistance;
// set collision distance automatically based on rest distance if not alraedy set
if (g_params.collisionDistance == 0.0f)
g_params.collisionDistance = Max(g_params.solidRestDistance, g_params.fluidRestDistance)*0.5f;
// default particle friction to 10% of shape friction
if (g_params.particleFriction == 0.0f)
g_params.particleFriction = g_params.dynamicFriction*0.1f;
// add a margin for detecting contacts between particles and shapes
if (g_params.shapeCollisionMargin == 0.0f)
g_params.shapeCollisionMargin = g_params.collisionDistance*0.5f;
// calculate particle bounds
Vec3 particleLower, particleUpper;
GetParticleBounds(particleLower, particleUpper);
// accommodate shapes
Vec3 shapeLower, shapeUpper;
GetShapeBounds(shapeLower, shapeUpper);
// update bounds
g_sceneLower = Min(Min(g_sceneLower, particleLower), shapeLower);
g_sceneUpper = Max(Max(g_sceneUpper, particleUpper), shapeUpper);
g_sceneLower -= g_params.collisionDistance;
g_sceneUpper += g_params.collisionDistance;
// update collision planes to match flexs
Vec3 up = Normalize(Vec3(-g_waveFloorTilt, 1.0f, 0.0f));
(Vec4&)g_params.planes[0] = Vec4(up.x, up.y, up.z, 0.0f);
(Vec4&)g_params.planes[1] = Vec4(0.0f, 0.0f, 1.0f, -g_sceneLower.z);
(Vec4&)g_params.planes[2] = Vec4(1.0f, 0.0f, 0.0f, -g_sceneLower.x);
(Vec4&)g_params.planes[3] = Vec4(-1.0f, 0.0f, 0.0f, g_sceneUpper.x);
(Vec4&)g_params.planes[4] = Vec4(0.0f, 0.0f, -1.0f, g_sceneUpper.z);
(Vec4&)g_params.planes[5] = Vec4(0.0f, -1.0f, 0.0f, g_sceneUpper.y);
g_wavePlane = g_params.planes[2][3];
g_buffers->diffusePositions.resize(g_maxDiffuseParticles);
g_buffers->diffuseVelocities.resize(g_maxDiffuseParticles);
g_buffers->diffuseCount.resize(1, 0);
// for fluid rendering these are the Laplacian smoothed positions
g_buffers->smoothPositions.resize(maxParticles);
g_buffers->normals.resize(0);
g_buffers->normals.resize(maxParticles);
// initialize normals (just for rendering before simulation starts)
int numTris = g_buffers->triangles.size() / 3;
for (int i = 0; i < numTris; ++i)
{
Vec3 v0 = Vec3(g_buffers->positions[g_buffers->triangles[i * 3 + 0]]);
Vec3 v1 = Vec3(g_buffers->positions[g_buffers->triangles[i * 3 + 1]]);
Vec3 v2 = Vec3(g_buffers->positions[g_buffers->triangles[i * 3 + 2]]);
Vec3 n = Cross(v1 - v0, v2 - v0);
g_buffers->normals[g_buffers->triangles[i * 3 + 0]] += Vec4(n, 0.0f);
g_buffers->normals[g_buffers->triangles[i * 3 + 1]] += Vec4(n, 0.0f);
g_buffers->normals[g_buffers->triangles[i * 3 + 2]] += Vec4(n, 0.0f);
}
for (int i = 0; i < int(maxParticles); ++i)
g_buffers->normals[i] = Vec4(SafeNormalize(Vec3(g_buffers->normals[i]), Vec3(0.0f, 1.0f, 0.0f)), 0.0f);
// save mesh positions for skinning
if (g_mesh)
{
g_meshRestPositions = g_mesh->m_positions;
}
else
{
g_meshRestPositions.resize(0);
}
g_solverDesc.maxParticles = maxParticles;
g_solverDesc.maxDiffuseParticles = g_maxDiffuseParticles;
g_solverDesc.maxNeighborsPerParticle = g_maxNeighborsPerParticle;
g_solverDesc.maxContactsPerParticle = g_maxContactsPerParticle;
// main create method for the Flex solver
g_solver = NvFlexCreateSolver(g_flexLib, &g_solverDesc);
// give scene a chance to do some post solver initialization
g_scenes[g_scene]->PostInitialize();
// center camera on particles
if (centerCamera)
{
g_camPos = Vec3((g_sceneLower.x + g_sceneUpper.x)*0.5f, min(g_sceneUpper.y*1.25f, 6.0f), g_sceneUpper.z + min(g_sceneUpper.y, 6.0f)*2.0f);
g_camAngle = Vec3(0.0f, -DegToRad(15.0f), 0.0f);
// give scene a chance to modify camera position
g_scenes[g_scene]->CenterCamera();
}
// create active indices (just a contiguous block for the demo)
g_buffers->activeIndices.resize(g_buffers->positions.size());
for (int i = 0; i < g_buffers->activeIndices.size(); ++i)
g_buffers->activeIndices[i] = i;
// resize particle buffers to fit
g_buffers->positions.resize(maxParticles);
g_buffers->velocities.resize(maxParticles);
g_buffers->phases.resize(maxParticles);
g_buffers->densities.resize(maxParticles);
g_buffers->anisotropy1.resize(maxParticles);
g_buffers->anisotropy2.resize(maxParticles);
g_buffers->anisotropy3.resize(maxParticles);
// save rest positions
g_buffers->restPositions.resize(g_buffers->positions.size());
for (int i = 0; i < g_buffers->positions.size(); ++i)
g_buffers->restPositions[i] = g_buffers->positions[i];
// builds rigids constraints
if (g_buffers->rigidOffsets.size())
{
assert(g_buffers->rigidOffsets.size() > 1);
const int numRigids = g_buffers->rigidOffsets.size() - 1;
// If the centers of mass for the rigids are not yet computed, this is done here
// (If the CreateParticleShape method is used instead of the NvFlexExt methods, the centers of mass will be calculated here)
if (g_buffers->rigidTranslations.size() == 0)
{
g_buffers->rigidTranslations.resize(g_buffers->rigidOffsets.size() - 1, Vec3());
CalculateRigidCentersOfMass(&g_buffers->positions[0], g_buffers->positions.size(), &g_buffers->rigidOffsets[0], &g_buffers->rigidTranslations[0], &g_buffers->rigidIndices[0], numRigids);
}
// calculate local rest space positions
g_buffers->rigidLocalPositions.resize(g_buffers->rigidOffsets.back());
CalculateRigidLocalPositions(&g_buffers->positions[0], &g_buffers->rigidOffsets[0], &g_buffers->rigidTranslations[0], &g_buffers->rigidIndices[0], numRigids, &g_buffers->rigidLocalPositions[0]);
// set rigidRotations to correct length, probably NULL up until here
g_buffers->rigidRotations.resize(g_buffers->rigidOffsets.size() - 1, Quat());
}
// unmap so we can start transferring data to GPU
UnmapBuffers(g_buffers);
//-----------------------------
// Send data to Flex
NvFlexCopyDesc copyDesc;
copyDesc.dstOffset = 0;
copyDesc.srcOffset = 0;
copyDesc.elementCount = numParticles;
NvFlexSetParams(g_solver, &g_params);
NvFlexSetParticles(g_solver, g_buffers->positions.buffer, ©Desc);
NvFlexSetVelocities(g_solver, g_buffers->velocities.buffer, ©Desc);
NvFlexSetNormals(g_solver, g_buffers->normals.buffer, ©Desc);
NvFlexSetPhases(g_solver, g_buffers->phases.buffer, ©Desc);
NvFlexSetRestParticles(g_solver, g_buffers->restPositions.buffer, ©Desc);
NvFlexSetActive(g_solver, g_buffers->activeIndices.buffer, ©Desc);
NvFlexSetActiveCount(g_solver, numParticles);
// springs
if (g_buffers->springIndices.size())
{
assert((g_buffers->springIndices.size() & 1) == 0);
assert((g_buffers->springIndices.size() / 2) == g_buffers->springLengths.size());
NvFlexSetSprings(g_solver, g_buffers->springIndices.buffer, g_buffers->springLengths.buffer, g_buffers->springStiffness.buffer, g_buffers->springLengths.size());
}
// rigids
if (g_buffers->rigidOffsets.size())
{
NvFlexSetRigids(g_solver, g_buffers->rigidOffsets.buffer, g_buffers->rigidIndices.buffer, g_buffers->rigidLocalPositions.buffer, g_buffers->rigidLocalNormals.buffer, g_buffers->rigidCoefficients.buffer, g_buffers->rigidPlasticThresholds.buffer, g_buffers->rigidPlasticCreeps.buffer, g_buffers->rigidRotations.buffer, g_buffers->rigidTranslations.buffer, g_buffers->rigidOffsets.size() - 1, g_buffers->rigidIndices.size());
}
// inflatables
if (g_buffers->inflatableTriOffsets.size())
{
NvFlexSetInflatables(g_solver, g_buffers->inflatableTriOffsets.buffer, g_buffers->inflatableTriCounts.buffer, g_buffers->inflatableVolumes.buffer, g_buffers->inflatablePressures.buffer, g_buffers->inflatableCoefficients.buffer, g_buffers->inflatableTriOffsets.size());
}
// dynamic triangles
if (g_buffers->triangles.size())
{
NvFlexSetDynamicTriangles(g_solver, g_buffers->triangles.buffer, g_buffers->triangleNormals.buffer, g_buffers->triangles.size() / 3);
}
// collision shapes
if (g_buffers->shapeFlags.size())
{
NvFlexSetShapes(
g_solver,
g_buffers->shapeGeometry.buffer,
g_buffers->shapePositions.buffer,
g_buffers->shapeRotations.buffer,
g_buffers->shapePrevPositions.buffer,
g_buffers->shapePrevRotations.buffer,
g_buffers->shapeFlags.buffer,
int(g_buffers->shapeFlags.size()));
}
// create render buffers
g_fluidRenderBuffers = CreateFluidRenderBuffers(maxParticles, g_interop);
g_diffuseRenderBuffers = CreateDiffuseRenderBuffers(g_maxDiffuseParticles, g_interop);
// perform initial sim warm up
if (g_warmup)
{
printf("Warming up sim..\n");