-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLiquid.cs
More file actions
197 lines (179 loc) · 7.81 KB
/
Liquid.cs
File metadata and controls
197 lines (179 loc) · 7.81 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
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using static Liquish.Utils;
namespace Liquish;
public class LiquidManager {
public GraphicsDevice graphicsDevice;
public BasicEffect basicEffect;
public Dictionary<string,Liquid> liquids = [];
private readonly RasterizerState noCull = new() { CullMode = CullMode.None };
public VertexPositionColor[] vertexBuffer = [];
public int[] indexBuffer = [];
public LiquidManager(GraphicsDevice graphicsDevice) {
this.graphicsDevice = graphicsDevice;
basicEffect = new BasicEffect(graphicsDevice) {
VertexColorEnabled = true,
World = Matrix.Identity,
View = Matrix.CreateLookAt(new Vector3(0, 0, 1), Vector3.Zero, Vector3.Up),
Projection = Matrix.CreateOrthographicOffCenter(
0, graphicsDevice.Viewport.Width,
graphicsDevice.Viewport.Height, 0,
0, 1)
};
}
public void Add(string name, Liquid l) {
liquids.Add(name,l);
if (l.Points.Count > vertexBuffer.Length) {
vertexBuffer = new VertexPositionColor[l.Points.Count];
}
if (l.Indices.Count > indexBuffer.Length) {
indexBuffer = new int[l.Indices.Count];
}
}
public void Update(float dt) {
foreach (var l in liquids.Values) {
l.Update(dt);
}
}
public void Draw(Matrix tMatrix) { // tMatrix could be the spacetoscreen matrix of the camera that you'd pass to spritebatch.begin!
if (liquids.Count == 0) return;
graphicsDevice.RasterizerState = noCull;
foreach (var l in liquids.Values) {
basicEffect.World = l.matrix * tMatrix;
basicEffect.CurrentTechnique.Passes[0].Apply();
for (int i = 0 ; i < l.Points.Count; i++) {
vertexBuffer[i] = l.Points[i];
}
for (int i = 0; i < l.Indices.Count; i++) {
indexBuffer[i] = l.Indices[i];
}
graphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertexBuffer, 0, l.Points.Count, indexBuffer, 0, l.Indices.Count / 3);
}
}
}
public class Liquid {
// Configurable parameters
private float waveSpeedPixelsPerSecond;
private float damping;
// Dynamic state
public int currentNumPoints;
public float currentPointSpacing;
public Rectangle boundingBox;
public List<VertexPositionColor> Points = [];
public List<int> Indices = [];
public List<Disturbance> activeDisturbances = [];
public (float c, float p)[] Heights;
private (float c, float p)[] _heightsBuffer;
public Matrix matrix = Matrix.Identity; // could be used for moving/rotating/scaling without having to manually shift the vetices on CPU which is COSTY
public Color SurfaceColor;
public Color BodyColor;
public Liquid(Rectangle BBox, float Quality, float waveSpeedPixelsPerSecond, float damping, Color sC, Color bC) {
this.waveSpeedPixelsPerSecond = waveSpeedPixelsPerSecond;
this.damping = damping;
SurfaceColor = sC; BodyColor = bC;
ReinitializeSurface(BBox, Quality);
}
private void ReinitializeSurface(Rectangle BBox, float Quality) {
boundingBox = BBox;
currentNumPoints = (int)MathF.Ceiling(BBox.Width * Quality);
currentPointSpacing = BBox.Width / (float)(currentNumPoints - 1);
Heights = new (float c, float p)[currentNumPoints];
_heightsBuffer = new (float c, float p)[currentNumPoints];
Points.Clear();
Indices.Clear();
for (int i = 0; i < currentNumPoints; i++) {
float x = BBox.X + (i * currentPointSpacing);
Points.Add(new VertexPositionColor(new Vector3(x, BBox.Y, 0), SurfaceColor));
}
for (int i = 0; i < currentNumPoints; i++) {
float x = BBox.X + (i * currentPointSpacing);
Points.Add(new VertexPositionColor(new Vector3(x, BBox.Y + BBox.Height, 0), BodyColor));
}
for (int i = 0; i < currentNumPoints - 1; i++) {
int topLeft = i;
int topRight = i + 1;
int bottomLeft = i + currentNumPoints;
int bottomRight = i + currentNumPoints + 1;
Indices.Add(topLeft);
Indices.Add(bottomLeft);
Indices.Add(topRight);
Indices.Add(topRight);
Indices.Add(bottomLeft);
Indices.Add(bottomRight);
}
activeDisturbances.Clear();
}
public void CreateDisturbance(float xcenter, float radius, float duration, float magnitude) {
xcenter -= boundingBox.X;
activeDisturbances.Add(new Disturbance {
xCenter = xcenter,
Radius = radius,
TotalTime = duration,
TotalMagnitude = magnitude,
TimeElapsed = 0
});
}
public class Disturbance {
public float xCenter;
public float Radius;
public float TimeElapsed;
public float TotalTime;
public float TotalMagnitude;
}
public static float EaseOutExpo(float x) {
return x == 1f ? 1f : 1f - MathF.Pow(2f, -10f * x);
}
private void ApplyPendingDisturbances(float dT) {
for (int i = activeDisturbances.Count - 1; i >= 0; i--) {
Disturbance dist = activeDisturbances[i];
if (dist.TimeElapsed < dist.TotalTime) {
float tCurrentNorm = (dist.TimeElapsed + dT) / dist.TotalTime;
float tPreviousNorm = dist.TimeElapsed / dist.TotalTime;
float magnitudeToApplyThisFrame = (EaseOutExpo(tCurrentNorm) - EaseOutExpo(tPreviousNorm)) * dist.TotalMagnitude;
for (int j = 1; j < Heights.Length - 1; j++) {
float distance = MathF.Abs(j * currentPointSpacing - dist.xCenter);
float normalizedDistance = distance / dist.Radius;
normalizedDistance = MathF.Min(normalizedDistance, 1);
float spatialFalloff = MathF.Cos(normalizedDistance * MathF.PI / 2f);
float appliedMagnitude = magnitudeToApplyThisFrame * spatialFalloff;
Heights[j].c += appliedMagnitude;
Heights[j].p += appliedMagnitude;
}
dist.TimeElapsed += dT;
}
else {
activeDisturbances.RemoveAt(i);
}
}
}
public void Update(float dt) {
ApplyPendingDisturbances(dt);
Span<VertexPositionColor> PointsSpan = CollectionsMarshal.AsSpan(Points);
Array.Clear(_heightsBuffer);
float actualSpreadFactor = (waveSpeedPixelsPerSecond * dt) * (waveSpeedPixelsPerSecond * dt) / (currentPointSpacing * currentPointSpacing);
const float STABILITY_THRESHOLD = 0.95f;
actualSpreadFactor = (actualSpreadFactor >= STABILITY_THRESHOLD) ? STABILITY_THRESHOLD : actualSpreadFactor;
for (int i = 0; i < currentNumPoints; i++) {
float currentHeight = Heights[i].c;
float previousHeight = Heights[i].p;
float newHeight;
if (i > 0 && i < currentNumPoints - 1) {
float left = Heights[i - 1].c;
float right = Heights[i + 1].c;
float acceleration = (left + right - 2 * currentHeight);
newHeight = (currentHeight * 2 - previousHeight) + acceleration * actualSpreadFactor;
newHeight *= damping;
}
else {
newHeight = currentHeight * damping;
}
_heightsBuffer[i].c = newHeight;
_heightsBuffer[i].p = currentHeight;
PointsSpan[i].Position.Y = boundingBox.Top + newHeight;
}
Array.Copy(_heightsBuffer, Heights, Heights.Length);
}
}