/*
 *  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"
#include "parameters.h"

uint32_t version = 0;
uint32_t options = BO_SFX | BO_SCHEMES;
char dname[] = "Spiral pulsing";
enum LayerMode mode = LM_OVERLAY;
char desc[] = "Pulsing spiral";

static double volume_scale = 1;


json_t *
get_parameters(const uint8_t fetch_all)
{
  json_t *params = json_object();

  plugin_parameters_add_double(params, BPP_VOLUME_SCALE, volume_scale, 0.1, 10, 0.1, "Volume scale");

  return params;
}


void
set_parameters(const Context_t *ctx, const json_t *in_parameters)
{
  plugin_parameter_parse_double_range(in_parameters, BPP_VOLUME_SCALE, &volume_scale);
}


json_t *
parameters(const Context_t *ctx, const json_t *in_parameters, const uint8_t fetch_all)
{
  if (NULL != in_parameters) {
    set_parameters(ctx, in_parameters);
  }

  return get_parameters(fetch_all);
}


void
on_switch_on(Context_t *ctx)
{
  /* Initialize parameters */
  volume_scale = 1;
}


void
run(Context_t *ctx)
{
  static Pixel_t c = 0;
  int i, j;
  float x, y, /*z,*/ theta, phi, r, d, x1, x2, x3 = 5;
  Buffer8_t *dst = passive_buffer(ctx);

  Buffer8_clear(dst);

  x1 = Input_get_volume(ctx->input) * WIDTH * volume_scale; /* Nb of pts per segment */
  x2 = 0.3 + ctx->input->data[A_MONO][((int)x1 % ctx->input->size)];

  for (i = 0; i < WIDTH; i++) {
    theta = i / 20.0;   /* Rotation angle */

    r = expf(theta*x2); /* Distance from axis  */
    d = 0.33 * r;       /* Radius relative to r (involute/evolute) */
    /* For ornament, add a periodic function to d */
    for (j = 0; j < 30; j++) {
      phi = 2.0 * M_PI *j / x3;
      x = d * cosf(phi) *cosf(theta);
      y = d * cosf(phi) *sinf(theta);
      x += (r * cosf(theta)) + HWIDTH;
      y += (r * sinf(theta)) + HHEIGHT;
      set_pixel(dst, x, y,  c);
      c++;
      c &= 255;
    }
  }
}
