Fluid simulation is a great example of simulating natural phenomena using a feedback system. It approximates complex phenomena represented by equations that are very challenging to solve by breaking them down into multiple relatively simple steps of approximations, resulting in intricate and elegant motion.

流体シミュレーションはフィードバックシステムを用いた自然現象のシミュレーションの良い例です。解くことが非常に難しい方程式で表された現象を、複数の比較的シンプルなステップに分解して近似することで、複雑で美しい動きを作り出すことができます。

https://codepen.io/kynd/pen/jOXZXWB

On this page, we will build a fluid simulation step by step. The demo above is written with GLSL shaders to ensure high performance. However, for learning purposes, we will create a miniature simulation using p5.js.

このページでは流体シミュレーションを、ステップに分けて組み立てます。上のデモはパフォーマンスのためにGLSLシェーダーで書かれていますが、学習用にはp5.jsを使っててミニチュアのシミュレーションを作成します。

Explaining fluid simulation can involve a lot of math and physics, but I will try to keep it at a high level and intuitive as much as possible. For more detailed explanation, I highly recommend reading Jamie Wong's article, "Fluid Simulation (with WebGL demo)”, which provides a more precise yet friendly breakdown of the topic.

流体シミュレーションを説明するにはかなりの数学と物理が必要ですが、ここではできるだけ直感的に説明しようと思います。より詳しく知りたい方は、Jamie Wongの記事「Fluid Simulation (with WebGL demo)」がとても正確かつ親切なのでオススメです。

Moving colors(paints)

色(絵の具)を動かす

First, we will define the space as a grid of cells. We want to smoothly move paints, or different colors, around in this space. To do this, we will use two maps, specifically two 2D arrays, to capture the information for each cell. The color map stores the color values of each cell, while the velocity map stores a vector that represents the velocity, i.e. the information about the speed and direction of the water flow in each cell.

まず枡目(セル)が並んだグリッドとして空間を定義します。この空間で絵の具、または異なる色をスムーズに移動させるために、各セルの情報をキャプチャするための2つのマップ、具体的には2つの2D配列を使います。カラーマップは各セルの色の値を保持し、速度マップは速度、つまり各セルの水の流れの速さと向きを表すベクトルを格納します。

To move the colors, we will add the opposite vector of the velocity to the position of each cell and sample the color from that point. The idea is that the color at the sampled point will move to the position of the cell in the next frame. Typically, the sampling point is located in the middle of four cells, so we will interpolate the colors between these cells. Also, for this implementation, we assume that the top edge and the bottom edge, as well as the left edge and the right edge, are connected. This means that the sampling position will wrap around to the opposite side of the canvas if it goes out of bounds.

色を移動するためには、各セルの位置に速度のベクトルを逆にしたものを加え、その点から色をサンプリングします。ここではサンプリングした場所の色が、次のフレームでセルの位置に移動するものと考えています。たいていサンプリングする点は四つのセルの間になるので、セル間の色を補間して色を求めます。この実装では、上端と下端、左端と右端が繋がっていると仮定しています。つまり、サンプリング位置がキャンバスの外に出た場合は、反対側に折り返します。

sampling.png