Created
December 27, 2017 15:45
-
-
Save tuchella/0c64d2cba77615d618c39f322ca88c96 to your computer and use it in GitHub Desktop.
2D fluid height field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Wavey { | |
private static int DELTA_T = 1; | |
private static float speed = 0.01F; | |
private float[] u = new float[20]; | |
private float[] v = new float[u.length]; | |
private float h = 0.1F; | |
private int frame = 0; | |
private float damping = 0.99F; | |
public static void main(String[] args) { | |
new Wavey(); | |
} | |
private void render() { | |
float[] u_new = new float[u.length]; | |
for (int i = 0; i < u.length; i++) { | |
float f = speed * speed * (u(i - 1) + u(i + 1) - 2 * u(i)) / (h * h); | |
v[i] = damping * v[i] + f * DELTA_T; | |
u_new[i] = u[i] + v[i] * DELTA_T; | |
} | |
u = u_new; | |
clear(); | |
draw(); | |
waitForNextFrame(); | |
render(); | |
} | |
private float u(int i) { | |
int boundIndex = Math.min( | |
Math.max(i, 0), | |
u.length - 1); | |
return u[boundIndex]; | |
} | |
private void draw() { | |
StringBuilder s = new StringBuilder(); | |
for(float level = 1.0F; level >= 0.0; level -= 0.1) { | |
for (int i = 0; i < u.length; i++) { | |
if (u[i] >= level) { | |
s.append("#"); | |
} else { | |
s.append(" "); | |
} | |
} | |
s.append(System.lineSeparator()); | |
} | |
s.append("(Frame: " + frame + ")"); | |
System.out.println(s); | |
} | |
public Wavey() { | |
for (int i = 0; i < u.length; i++) { | |
u[i] = 0.5F; | |
} | |
u[4] = 0.7F; | |
u[5] = 0.8F; | |
u[6] = 0.7F; | |
draw(); | |
render(); | |
} | |
private void clear() { | |
for (int i = 0; i < 50; ++i) System.out.println(); | |
} | |
private void waitForNextFrame() { | |
try { | |
Thread.sleep(33); | |
frame++; | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment