/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  lebiniou is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include "context.h"


uint32_t version = 0;
uint32_t options = BO_GFX | BO_UNIQUE | BO_NORANDOM;
char desc[] = "Cellular automaton";
char dname[] = "Life";


void
run(Context_t *ctx)
{
  uint16_t i, j;
  const Buffer8_t *src = active_buffer(ctx);
  Buffer8_t *dst = passive_buffer(ctx);
  Pixel_t c;

  for (j = 0; j < HEIGHT; j++)
    for (i = 0; i < WIDTH; i++) {
      uint8_t count = 0;

      /* C macros are sooo handy */
#define LIFE(dx, dy) {                            \
        short xdx, ydy;                           \
        xdx = dx;                                 \
        ydy = dy;                                 \
        if (xdx < 0) xdx = MAXX;                  \
        else if (xdx > MAXX) xdx = 0;             \
        if (ydy < 0) ydy = MAXY;                  \
        else if (ydy > MAXY) ydy = 0;             \
        if (get_pixel_nc(src, xdx, ydy)) count++; \
      }

      LIFE(i-1, j-1);
      LIFE(i-1, j+0);
      LIFE(i-1, j+1);
      LIFE(i+0, j-1);
      LIFE(i+0, j+1);
      LIFE(i+1, j-1);
      LIFE(i+1, j+0);
      LIFE(i+1, j+1);

      if ((c = get_pixel_nc(src, i, j)) && ((count == 2) || (count == 3))) {
        // Any live cell with two or three live neighbours survives.
        set_pixel_nc(dst, i, j, c);
      } else {
        // Any dead cell with three live neighbours becomes a live cell.
        if (!get_pixel_nc(src, i, j) && (count == 3)) {
          set_pixel_nc(dst, i, j, b_rand_uint32_range(128, 255));
        } else {
          // All other live cells die in the next generation. Similarly, all other dead cells stay dead.
          set_pixel_nc(dst, i, j, 0);
        }
      }
    }
}
