Skip to content

Instantly share code, notes, and snippets.

@seibe
Last active August 29, 2015 14:20
Show Gist options
  • Save seibe/fe2beebcdc4ca3e866a0 to your computer and use it in GitHub Desktop.
Save seibe/fe2beebcdc4ca3e866a0 to your computer and use it in GitHub Desktop.
「uGUI/Texture2Dで描画するリアルタイム流体計算」 最終的なソースコード (http://tasogare-games.hatenablog.jp/entry/20150428/1430203599)
using UnityEngine;
using UnityEngine.UI;
public class Main : MonoBehaviour
{
public RawImage raw;
public int N = 64;
public float diff = 0.0f;
public float visc = 0.0f;
public float force = 5.0f;
public float source = 100.0f;
private Texture2D _tex;
private Color[] _colors;
private Vector3 _pos0;
private float[] _u, _u0, _v, _v0, _dens, _dens0;
void Start()
{
if ((N & (N - 1)) != 0) Debug.LogError("定数Nは2の累乗にしてください");
if (!raw) Debug.LogError("RawImageを指定してください");
ClearData();
_tex = new Texture2D(N, N, TextureFormat.RGB24, false);
raw.color = Color.white;
raw.texture = _tex;
}
void Update()
{
float dt = Time.deltaTime * 10f;
GetFromUI(_dens0, _u0, _v0);
FluidMath.VelStep(N, ref _u, ref _v, ref _u0, ref _v0, visc, dt);
FluidMath.DensStep(N, ref _dens, ref _dens0, ref _u, ref _v, diff, dt);
DrawDensity();
}
void ClearData()
{
int size = (N + 2) * (N + 2);
_u = new float[size];
_u0 = new float[size];
_v = new float[size];
_v0 = new float[size];
_dens = new float[size];
_dens0 = new float[size];
_pos0 = Vector3.zero;
_colors = new Color[N * N];
for (int i = 0; i < size; i++)
{
_u[i] = _u0[i] = _v[i] = _v0[i] = _dens[i] = _dens0[i] = 0.0f;
}
}
void GetFromUI(float[] d, float[] u, float[] v)
{
int i, j, k;
int size = (N + 2) * (N + 2);
for (i = 0; i < size; i++)
{
u[i] = v[i] = d[i] = 0;
}
if (Input.GetKeyDown("c")) ClearData();
if (!Input.GetMouseButton(0) && !Input.GetMouseButton(1)) return;
Vector3 pos = raw.transform.InverseTransformPoint(Input.mousePosition);
i = Mathf.CeilToInt(pos.x + N * 0.5f);
j = Mathf.CeilToInt(pos.y + N * 0.5f);
if (i < 0 || i >= N || j < 0 || j >= N) return;
k = FluidMath.IX(N, i, j);
if (Input.GetMouseButton(0))
{
if (Input.GetMouseButtonDown(0))
{
_pos0 = pos;
return;
}
u[k] = force * (pos.x - _pos0.x);
v[k] = force * (pos.y - _pos0.y);
}
if (Input.GetMouseButton(1))
{
d[k] = source;
}
_pos0 = pos;
}
void DrawDensity()
{
float d;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
d = _dens[FluidMath.IX(N, i + 1, j + 1)];
_colors[i + N * j] = new Color(d, d, d);
}
}
_tex.SetPixels(_colors);
_tex.Apply();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment