/*
 *  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_FIRST | BO_SCHEMES;
enum LayerMode mode = LM_OVERLAY;
char desc[] = "Cellular automaton";
char dname[] = "Faders";

/*
 * Adapted from:
 * http://www.fourmilab.ch/cellab/manual/rules.html#Faders
 */

static Buffer8_t *game = NULL, *game2 = NULL;


static void
randomize(Buffer8_t *buff)
{
  Pixel_t *p = buff->buffer;

  for ( ; p < buff->buffer + BUFFSIZE*sizeof(Pixel_t); p++) {
    *p = b_rand_boolean() ? 0 : 255;
  }
}


int8_t
create(Context_t *ctx)
{
  game = Buffer8_new();
  game2 = Buffer8_new();
  randomize(game);

  return 1;
}


void
destroy(Context_t *ctx)
{
  Buffer8_delete(game);
  Buffer8_delete(game2);
}


void
on_switch_on(Context_t *ctx)
{
  randomize(game);
  Buffer8_average(game, active_buffer(ctx));
}


#define IS_FIRING(X, Y) (get_pixel_nc(game, X, Y) == 255)

static inline uint8_t
firing(const int x, const int y)
{
  uint16_t count = 0;

  count += IS_FIRING(x-1, y-1);
  count += IS_FIRING(x,   y-1);
  count += IS_FIRING(x+1, y-1);
  count += IS_FIRING(x-1, y);
  count += IS_FIRING(x+1, y);
  count += IS_FIRING(x-1, y+1);
  count += IS_FIRING(x,   y+1);
  count += IS_FIRING(x+1, y+1);

  return (count == 2);
}


void
run(Context_t *ctx)
{
  int i, j;
  Buffer8_t *dst = passive_buffer(ctx);
  Buffer8_t *tmp;

  Buffer8_clear(dst);

  for (j = 1; j < MAXY; j++)
    for (i = 1; i < MAXX; i++) {
      const Pixel_t old = get_pixel_nc(game, i, j);
      Pixel_t new;

      switch (old) {
        case 0:
          /* dead cell, becomes alive ? */
          new = firing(i, j) ? 255 : 0;
          break;

        case 255:
          /* firing cell, keeps firing ? */
          new = firing(i, j) ? 255 : 254;
          break;

        default:
          /* cell decays */
          new = old - 2;
          break;
      }

      set_pixel_nc(game2, i, j, new);
      set_pixel_nc(dst, i, j, new);
    }

  tmp = game;
  game = game2;
  game2 = tmp;
}
