/*
 *  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 "translation.h"


uint32_t version = 0;
uint32_t options = BO_DISPLACE;
char dname[] = "Big half wheel";
char desc[] = "Translation effect";


/* Pour garder le centre de la translation bien visible dans le screen */
#define SHIFT_X (WIDTH / 10)
#define SHIFT_Y (HEIGHT / 10)

static Translation_t *t_bighalfwheel = NULL;

static int cx, cy;

const float q = M_PI / 2;
/* TODO check against original cthugha --oliv3 */
const float p = 45.0 / 180.0 * M_PI;


static Map_t
cth_bighalfwheel(const short in_x, const short in_y)
{
  const uint16_t i = in_x, j = in_y;
  int dx, dy;
  Map_t m;

  if (j==0 || j == HEIGHT) {
    dx = (float)(cx - i) * 0.75;
    dy = cy - j;
  } else {
    int dist;
    float ang;

    dist = sqrt((i-cx)*(i-cx) + (j-cy)*(j-cy));

    if (i==cx) {
      if (j>cx) {
        ang = q;
      } else {
        ang = -q;
      }
    } else {
      ang = atanf((float)(j-cy)/(i-cx));
    }

    if (i<cx) {
      ang += M_PI;
    }
    if (dist < HEIGHT) {
      dx = ceil(-sinf(ang-p)*dist/10.0);
      dy = ceil(cosf(ang-p)*dist/10.0);
    } else {
      if (i<cx) {
        dx = 3;
      } else {
        dx = -3;
      }
      dy = 0;
    }

    if (i==0 || i==WIDTH) {
      dx = cx - i;
      dy = (float)(cy - j) * 0.75;
    }
  }

  /* return abs(i+dx + ((j+dy)*WIDTH)) % BUFFSIZE; */
  m.map_x = abs((i+dx) % WIDTH);
  m.map_y = abs((j+dy) % HEIGHT);

  return m;
}


static void
init_params(void)
{
  cx = b_rand_uint32_range(SHIFT_X, (MAXX - SHIFT_X));
  cy = b_rand_uint32_range(SHIFT_Y, (MAXY - SHIFT_Y));
}


void
on_switch_on(Context_t *ctx)
{
  Translation_batch_init(t_bighalfwheel);
}


int8_t
create(Context_t *ctx)
{
  t_bighalfwheel = Translation_new(&cth_bighalfwheel, &init_params);

  return 1;
}


void
destroy(Context_t *ctx)
{
  Translation_delete(t_bighalfwheel);
}


void
run(Context_t *ctx)
{
  Translation_run(t_bighalfwheel, ctx);
}
