-
Notifications
You must be signed in to change notification settings - Fork 0
/
Physics.cs
236 lines (194 loc) · 8.18 KB
/
Physics.cs
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
using Godot;
using System;
using System.Linq;
// Some variables are divided by 10000 internally because Godot rounds very small float values in the inspector.
public partial class Physics : Node
{
[Export]
public bool randomlyDistribute;
[Export]
// Wait a little while for the GPU to do its calculations before syncing. Increases framerate but decreases sim accuracy.
public bool inaccuratePhysics;
[Export]
public int inaccuracy = 10;
[Export]
public bool startWithRotation;
[Export]
public float rotationSpeed = 0.1f;
[Export]
// Distance between particles in units.
public float density = 1;
[Export]
public int particleCount = 18000;
[Export]
public bool disablePhysics;
[ExportGroup("Simulation parameters (*10000)")]
[Export]
// Gravitational constant. Higher = stronger gravity.
float gravityConstant; // divided by 10000.
[Export]
// Maximum impulse, maximum amount of force a particle can apply to another in one frame. Lower values usually create larger structures.
float maxImpulse = 0.00001f; // divided by 10000.
[Export]
// How much each particle is pushed away from the center of the screen.
float expansionFactor; // divided by 10000.
public Vector2Array positionArray;
Vector2Array velocityArray;
RenderingDevice renderingDevice;
Rid computeShader;
Rid velocityBufferRid;
int numFramesSinceUpdate;
byte[] paramBytes;
void InitParticles() {
// Create one particle for each game unit
int sqrSideLength = Mathf.CeilToInt(Mathf.Sqrt(particleCount));
GD.Print(sqrSideLength);
int index = 0;
for (int y = 0; y < sqrSideLength; y++) {
for (int x = 0; x < sqrSideLength; x++) {
if (index >= particleCount) { return; }
if (randomlyDistribute) {
positionArray[index] = new Vector2((float)GD.RandRange(-(float)sqrSideLength / 2 * density, sqrSideLength / 2 * density), (float)GD.RandRange(-(float)sqrSideLength / 2 * density, sqrSideLength / 2 * density));
}
else {
positionArray[index] = new Vector2((-sqrSideLength / 2 + x) * density, (sqrSideLength / 2 - y) * density);
}
index++;
}
}
}
void InitParticleVelocity() {
for (int i = 0; i < particleCount; i++) {
velocityArray[i] = positionArray[i].ToVector3().Cross(Vector3.Back).ToVector2().Normalized() * rotationSpeed;
}
}
public override void _Ready() {
// ensure particleCount is even
if (particleCount % 2 != 0) { particleCount -= 1; }
GD.Print("Simulation values:");
GD.Print($"Particle count: {particleCount}");
GD.Print($"Gravitational constant: {gravityConstant / 10000}");
GD.Print($"Max impulse: {maxImpulse / 10000}");
GD.Print($"Expansion factor: {expansionFactor / 10000}");
positionArray = new Vector2Array(particleCount);
velocityArray = new Vector2Array(particleCount);
paramBytes = new [] {
BitConverter.GetBytes(gravityConstant / 10000),
BitConverter.GetBytes(maxImpulse / 10000),
BitConverter.GetBytes(expansionFactor / 10000),
BitConverter.GetBytes(particleCount),
}.SelectMany(s => s).ToArray();
InitParticles();
if (startWithRotation) { InitParticleVelocity(); }
renderingDevice = RenderingServer.CreateLocalRenderingDevice();
// Load GLSL shader
RDShaderFile shaderFile = GD.Load<RDShaderFile>("res://compute.glsl");
RDShaderSpirV shaderBytecode = shaderFile.GetSpirV();
computeShader = renderingDevice.ShaderCreateFromSpirV(shaderBytecode);
//velocityArray[50] = new Vector2(100,100);
velocityBufferRid = ExecuteComputePipeline();
}
// https://docs.godotengine.org/en/stable/tutorials/shaders/compute_shaders.html
Rid ExecuteComputePipeline() {
byte[] positionBytes = new byte[positionArray.InternalArraySize * sizeof(float)];
byte[] velocityBytes = new byte[velocityArray.InternalArraySize * sizeof(float)];
Buffer.BlockCopy(positionArray._internalFloatArray, 0, positionBytes, 0, positionBytes.Length);
Buffer.BlockCopy(velocityArray._internalFloatArray, 0, velocityBytes, 0, velocityBytes.Length);
// Create storage buffers that can hold our float values.
Rid positionBuffer = renderingDevice.StorageBufferCreate((uint)positionBytes.Length, positionBytes);
Rid velocityBuffer = renderingDevice.StorageBufferCreate((uint)velocityBytes.Length, velocityBytes);
Rid paramBuffer = renderingDevice.StorageBufferCreate((uint)paramBytes.Length, paramBytes);
// Create a uniform to assign the position buffer to the rendering device
RDUniform positionArrayUniform = new RDUniform {
UniformType = RenderingDevice.UniformType.StorageBuffer,
Binding = 0
};
positionArrayUniform.AddId(positionBuffer);
// Create a uniform to assign the velocity buffer to the rendering device
RDUniform velocityArrayUniform = new RDUniform {
UniformType = RenderingDevice.UniformType.StorageBuffer,
Binding = 1
};
velocityArrayUniform.AddId(velocityBuffer);
// Create a uniform to assign the parameter buffer to the rendering device
RDUniform paramArrayUniform = new RDUniform {
UniformType = RenderingDevice.UniformType.StorageBuffer,
Binding = 2
};
paramArrayUniform.AddId(paramBuffer);
Rid uniformSet = renderingDevice.UniformSetCreate(new Godot.Collections.Array<RDUniform> { positionArrayUniform, velocityArrayUniform, paramArrayUniform }, computeShader, 0);
// Create a compute pipeline
Rid pipeline = renderingDevice.ComputePipelineCreate(computeShader);
long computeList = renderingDevice.ComputeListBegin();
renderingDevice.ComputeListBindComputePipeline(computeList, pipeline);
renderingDevice.ComputeListBindUniformSet(computeList, uniformSet, 0);
renderingDevice.ComputeListDispatch(computeList, xGroups: (uint)particleCount / 2, yGroups: 1, zGroups: 1);
renderingDevice.ComputeListEnd();
renderingDevice.Submit();
// The purpose of the compute shader is to recalculate velocities - we only want the velocities back
return velocityBuffer;
}
void CopyBytesToVelocityArray(byte[] bytes) {
Buffer.BlockCopy(bytes, 0, velocityArray._internalFloatArray, 0, bytes.Length);
}
public override void _Process(double delta) {
if (disablePhysics) { return; }
if (!inaccuratePhysics || numFramesSinceUpdate >= inaccuracy) {
numFramesSinceUpdate = 0;
renderingDevice.Sync();
byte[] outputBytes = renderingDevice.BufferGetData(velocityBufferRid);
CopyBytesToVelocityArray(outputBytes);
velocityBufferRid = ExecuteComputePipeline();
}
//GD.Print(positionArray[0]);
if (float.IsNaN(positionArray[0].X) || float.IsNaN(positionArray[0].Y)) {
GD.Print("Ruh roh, there's NaNs everywhere!!");
}
positionArray.AddArray(velocityArray);
numFramesSinceUpdate++;
}
/*
// Reimplementation of the compute shader on the cpu for testing
Vector2 GetVelocityVector(uint index) {
return new Vector2(velocityArray._internalFloatArray[index], velocityArray._internalFloatArray[index + N_PARTICLES]);
}
void AddVelocityVector(Vector2 value, uint index) {
velocityArray._internalFloatArray[index] += value.X;
velocityArray._internalFloatArray[index + N_PARTICLES] += value.Y;
}
Vector2 GetPositionVector(uint index) {
return new Vector2(positionArray._internalFloatArray[index], positionArray._internalFloatArray[index + N_PARTICLES]);
}
void GravityPhysicsTest() {
for (uint id = 0; id < N_PARTICLES; id++) {
Vector2 velocityVector = GetVelocityVector(id);
Vector2 position = GetPositionVector(id);
for (uint i = 0; i < N_PARTICLES; i++)
{
if (i == id) { continue; }
Vector2 otherPosition = GetPositionVector(i);
Vector2 displacement = otherPosition - position;
AddVelocityVector(0.001f / Mathf.Pow(displacement.Length(), 3) * displacement, id);
}
}
}
void GravityPhysicsTestAlt() {
for (uint id = 0; id < N_PARTICLES; id++) {
Vector2 velocityVector = GetVelocityVector(id);
Vector2 position = GetPositionVector(id);
for (uint i = 0; i < N_PARTICLES; i++)
{
if (i == id) { continue; }
Vector2 otherPosition = GetPositionVector(i);
// https://en.wikipedia.org/wiki/Newton's_law_of_universal_gravitation
Vector2 directionVec = otherPosition - position;
float distSqr = directionVec.Dot(directionVec);
Vector2 directionUnitVec = directionVec.Normalized();
float impulse = Mathf.Min(100, 10 / distSqr);
velocityVector += impulse * directionUnitVec;
}
AddVelocityVector(velocityVector, id);
}
}
*/
}