読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

拡散セルオートマトン

/**
* cell automaton for diffusion
*
* @author aa_debdeb
* @date 2016/07/02
*/

int cellNum = 50;
float cellSize = 10;
float[][] cells;

int[][] dir = {{0, -1, 0, 1, 1, 1, 0, -1, -1},
               {0, -1, -1, -1, 0, 1, 1, 1, 0}};
              
void setup(){
  size(500, 500);
  cells = new float[cellNum][cellNum];
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      cells[x][y] = 0.0;
    }
  }
  noStroke();
}


void draw(){
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      float gray = map(cells[x][y], 0, 1, 0, 255);
      fill(gray);
      rect(x * cellSize, y * cellSize, cellSize, cellSize);
    }
  }
  float[][] newCells = new float[cellNum][cellNum];
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      newCells[x][y] = 0.0;
    }
  }
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      float diffuse = cells[x][y] / 9;
      for(int d = 0; d < 9; d++){
        int xd = x + dir[0][d];
        int yd = y + dir[1][d];
        if(!(xd < 0 || cellNum - 1 < xd || yd < 0 || cellNum - 1 < yd)){
          newCells[xd][yd] += diffuse;
        }
      }
    }
  }
  cells = newCells;
  for(int x = 0; x < cellNum; x++){
    for(int y = 0; y < cellNum; y++){
      constrain(newCells[x][y], 0.0, 1.0);
    }
  }
  if(mousePressed){
    int x = int(mouseX / cellSize);
    int y = int(mouseY / cellSize);
    if(0 <= x && x < cellNum && 0 <= y && y < cellNum){ 
      cells[x][y] = 1.0;
    }
  }
}