我一直在尝试在Unity中实现浅水方程,但是遇到了一个奇怪的bug。我的水面出现了奇怪的振荡波纹。我拍了一些截图:
这里有一个视频:https://www.youtube.com/watch?v=crXLrvETdjA
我的代码基于Xing Mei的论文Fast Hydraulic Erosion Simulation and Visualization on GPU。你可以在这里找到整个求解器的代码:http://pastebin.com/JktpizHW(或者见下文)。每次我使用论文中的公式时,我都会在注释中添加其编号。
我尝试了不同的时间步长,对于视频,我使用了0.02,将其降低只会使它振荡得更慢。我还尝试了更大的网格(视频使用100,我尝试了200,但水波纹只是更小了)。我多次检查了所有公式,但没有发现任何错误。
有人能找出问题出在哪里吗?
额外信息:
如您在pastebin中所见,我使用C#编写了此程序。我使用Unity作为可视化引擎,并且只是使用网格网格来可视化水。我更改网格的顶点y分量以匹配我计算的高度。DoUpdate方法获取一个float [][] lowerLayersHeight参数,基本上是水下地形的高度。在视频中,它只是所有0。
public override void DoUpdate(float dt, float dx, float[][] lowerLayersHeight) {
int x, y;
float totalHeight, dhL, dhR, dhT, dhB;
float dt_A_g_l = dt * _A * g / dx; //all constants for equation 2
float K; // scaling factor for the outflow flux
float dV;
for (x=1 ; x <= N ; x++ ) {
for (y=1 ; y <= N ; y++ ) {
//
// 3.2.1 Outflow Flux Computation
// --------------------------------------------------------------
totalHeight = lowerLayersHeight[x][y] + _height[x][y];
dhL = totalHeight - lowerLayersHeight[x-1][y] - _height[x-1][y]; //(3)
dhR = totalHeight - lowerLayersHeight[x+1][y] - _height[x+1][y];
dhT = totalHeight - lowerLayersHeight[x][y+1] - _height[x][y+1];
dhB = totalHeight - lowerLayersHeight[x][y-1] - _height[x][y-1];
_tempFlux[x][y].left = Mathf.Max(0.0f, _flux[x][y].left + dt_A_g_l * dhL ); //(2)
_tempFlux[x][y].right = Mathf.Max(0.0f, _flux[x][y].right + dt_A_g_l * dhR );
_tempFlux[x][y].top = Mathf.Max(0.0f, _flux[x][y].top + dt_A_g_l * dhT );
_tempFlux[x][y].bottom = Mathf.Max(0.0f, _flux[x][y].bottom + dt_A_g_l * dhB );
float totalFlux = _tempFlux[x][y].left + _tempFlux[x][y].right + _tempFlux[x][y].top + _tempFlux[x][y].bottom;
if (totalFlux > 0) {
K = Mathf.Min(1.0f, _height[x][y] * dx * dx / totalFlux / dt); //(4)
_tempFlux[x][y].left = K * _tempFlux[x][y].left; //(5)
_tempFlux[x][y].right = K * _tempFlux[x][y].right;
_tempFlux[x][y].top = K * _tempFlux[x][y].top;
_tempFlux[x][y].bottom = K * _tempFlux[x][y].bottom;
}
//swap temp and the real one after the for-loops
//
// 3.2.2 Water Surface
// ----------------------------------------------------------------------------------------
dV = dt * (
//sum in
_tempFlux[x-1][y].right + _tempFlux[x][y-1].top + _tempFlux[x+1][y].left + _tempFlux[x][y+1].bottom
//minus sum out
- _tempFlux[x][y].right - _tempFlux[x][y].top - _tempFlux[x][y].left - _tempFlux[x][y].bottom
); //(6)
_tempHeight[x][y] = _height[x][y] + dV / (dx*dx); //(7)
//swap temp and the real one after the for-loops
}
}
Helpers.Swap(ref _tempFlux, ref _flux);
Helpers.Swap(ref _tempHeight, ref _height);
}