/*
 *  $Id: wfr_synth.c 24450 2021-11-01 14:32:53Z yeti-dn $
 *  Copyright (C) 2024 David Necas (Yeti).
 *  E-mail: yeti@gwyddion.net.
 *
 *  This program 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.
 *
 *  This program 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 this program; if not, write to the
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include <glib/gi18n-lib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <gwy.h>
#include "preview.h"
#include "libgwyddion/omp.h"

#define RUN_MODES (GWY_RUN_IMMEDIATE | GWY_RUN_INTERACTIVE)

enum {
    PARAM_COVERAGE,
    PARAM_HEIGHT,
    PARAM_EDGE_WIDTH,
    PARAM_PNEW,
    PARAM_RMIN,
    PARAM_RMAX,
    PARAM_RPOWER,
    PARAM_SEED,
    PARAM_RANDOMIZE,
    PARAM_UPDATE,
    PARAM_ACTIVE_PAGE,
    BUTTON_LIKE_CURRENT_IMAGE,

    PARAM_DIMS0
};

typedef enum {
    RNG_SIZE,
    RNG_OLD,
    RNG_NEW,
    RNG_NRNGS
} ResidueSynthRng;

enum {
    OUTSIDE = 0,
    EDGE = 1,
    INSIDE = 2,
};

/* Positions are relative to the cente (of the disc or whatever we have). */
typedef struct {
    gint ypos;
    gint xstart;
    gint xend; /* inclusive */
} LineSegment;

typedef struct {
    gint nedge;
    gint ninner;
    LineSegment *edge;
    LineSegment *inner;
} SegmentLists;

typedef struct {
    GwyParams *params;
    GwyField *field;
    GwyField *result;
    /* Cached input image parameters. */
    gdouble zscale;  /* Negative value means there is no input image. */
} ModuleArgs;

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GwyParamTable *table_dimensions;
    GwyParamTable *table_generator;
    GwyField *template_;
} ModuleGUI;

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);
static void             execute             (ModuleArgs *args);
static GwyDialogOutcome run_gui             (ModuleArgs *args,
                                             GwyFile *data,
                                             gint id);
static GtkWidget*       dimensions_tab_new  (ModuleGUI *gui);
static GtkWidget*       generator_tab_new   (ModuleGUI *gui);
static void             param_changed       (ModuleGUI *gui,
                                             gint id);
static void             dialog_response     (ModuleGUI *gui,
                                             gint response);
static void             preview             (gpointer user_data);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Generates images by simulating residue of film removal."),
    "Yeti <yeti@gwyddion.net>",
    "1.0",
    "David Nečas (Yeti)",
    "2024",
};

GWY_MODULE_QUERY2(module_info, residue)

static gboolean
module_register(void)
{
    gwy_synth_func_register("residue",
                            module_main,
                            N_("/_Deposition/_Residue..."),
                            NULL,
                            RUN_MODES,
                            N_("Generate image of film residue"));

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, gwy_synth_func_current());
    gwy_param_def_add_double(paramdef, PARAM_COVERAGE, "coverage", _("Co_verage"), 1e-5, 0.999, 0.4);
    gwy_param_def_add_double(paramdef, PARAM_HEIGHT, "height", _("_Height scale"), 1e-4, 1000.0, 1.0);
    gwy_param_def_add_double(paramdef, PARAM_EDGE_WIDTH, "edge_width", _("_Edge width"), 0.1, 20.0, 3.0);
    gwy_param_def_add_double(paramdef, PARAM_PNEW, "pnew", _("_Probability of a new location"), 0.0, 1.0, 0.3);
    gwy_param_def_add_int(paramdef, PARAM_RMIN, "rmin", _("_Minimum radius"), 1, 100, 3);
    gwy_param_def_add_int(paramdef, PARAM_RMAX, "rmax", _("Ma_ximum radius"), 1, 100, 25);
    gwy_param_def_add_double(paramdef, PARAM_RPOWER, "rpower", _("Size power _law"), 0.0, 10.0, 2.0);
    gwy_param_def_add_seed(paramdef, PARAM_SEED, "seed", NULL);
    gwy_param_def_add_randomize(paramdef, PARAM_RANDOMIZE, PARAM_SEED, "randomize", NULL, TRUE);
    gwy_param_def_add_instant_updates(paramdef, PARAM_UPDATE, "update", NULL, TRUE);
    gwy_param_def_add_active_page(paramdef, PARAM_ACTIVE_PAGE, "active_page", NULL);

    gwy_synth_define_dimensions_params(paramdef, PARAM_DIMS0);
    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    ModuleArgs args;
    GwyField *field;
    gint id;

    g_return_if_fail(mode & RUN_MODES);
    gwy_clear1(args);
    gwy_data_browser_get_current(GWY_APP_FIELD, &field,
                                 GWY_APP_FIELD_ID, &id,
                                 0);
    args.field = field;
    args.zscale = field ? gwy_field_rms(field) : -1.0;

    args.params = gwy_params_new_from_settings(define_module_params());
    gwy_synth_sanitise_params(args.params, PARAM_DIMS0, field);
    if (mode == GWY_RUN_INTERACTIVE) {
        outcome = run_gui(&args, data, id);
        gwy_params_save_to_settings(args.params);
        if (outcome == GWY_DIALOG_CANCEL)
            goto end;
    }
    args.result = gwy_synth_make_result_field((args.field = field), args.params, FALSE);
    execute(&args);
    gwy_synth_add_image_to_file(args.result, data, id, args.params);

end:
    g_clear_object(&args.result);
    g_object_unref(args.params);
}

static GwyDialogOutcome
run_gui(ModuleArgs *args, GwyFile *data, gint id)
{
    GwyDialogOutcome outcome;
    GwyDialog *dialog;
    GtkWidget *hbox, *dataview;
    GtkNotebook *notebook;
    ModuleGUI gui;

    gwy_clear1(gui);
    gui.args = args;
    gui.template_ = args->field;

    if (gui.template_)
        args->field = gwy_synth_make_preview_field(gui.template_, PREVIEW_SIZE);
    else
        args->field = gwy_field_new(PREVIEW_SIZE, PREVIEW_SIZE, PREVIEW_SIZE, PREVIEW_SIZE, TRUE);
    args->result = gwy_synth_make_result_field(args->field, args->params, TRUE);

    gui.dialog = gwy_dialog_new(_("Residue"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_UPDATE, GWY_STOCK_RESET, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    dataview = gwy_create_preview(args->result, NULL, PREVIEW_SIZE);
    gwy_setup_data_view(GWY_DATA_VIEW(dataview), data, GWY_FILE_IMAGE, id, GWY_FILE_ITEM_PALETTE);
    if (gui.template_)
        gwy_setup_data_view(GWY_DATA_VIEW(dataview), data, GWY_FILE_IMAGE, id, GWY_FILE_ITEM_PALETTE);
    hbox = gwy_create_dialog_preview_hbox(GTK_DIALOG(dialog), GWY_DATA_VIEW(dataview), FALSE);

    notebook = GTK_NOTEBOOK(gtk_notebook_new());
    gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(notebook), TRUE, TRUE, 0);

    gtk_notebook_append_page(notebook, dimensions_tab_new(&gui), gtk_label_new(_("Dimensions")));
    gtk_notebook_append_page(notebook, generator_tab_new(&gui), gtk_label_new(_("Generator")));
    gwy_param_active_page_link_to_notebook(args->params, PARAM_ACTIVE_PAGE, notebook);

    g_signal_connect_swapped(gui.table_dimensions, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_swapped(gui.table_generator, "param-changed", G_CALLBACK(param_changed), &gui);
    g_signal_connect_swapped(dialog, "response", G_CALLBACK(dialog_response), &gui);
    gwy_dialog_set_preview_func(dialog, GWY_PREVIEW_IMMEDIATE, preview, &gui, NULL);

    outcome = gwy_dialog_run(dialog);

    g_clear_object(&args->field);
    g_clear_object(&args->result);

    return outcome;
}

static GtkWidget*
dimensions_tab_new(ModuleGUI *gui)
{
    gui->table_dimensions = gwy_param_table_new(gui->args->params);
    gwy_synth_append_dimensions_to_param_table(gui->table_dimensions, 0);

    return gwy_param_table_widget(gui->table_dimensions);
}

static GtkWidget*
generator_tab_new(ModuleGUI *gui)
{
    GwyParamTable *table;

    table = gui->table_generator = gwy_param_table_new(gui->args->params);

    gwy_param_table_append_header(table, -1, _("Generator"));
    gwy_param_table_append_slider(table, PARAM_COVERAGE);
    gwy_param_table_append_slider(table, PARAM_PNEW);
    gwy_param_table_append_slider(table, PARAM_RMIN);
    gwy_param_table_slider_add_alt(table, PARAM_RMIN);
    gwy_param_table_append_slider(table, PARAM_RMAX);
    gwy_param_table_slider_add_alt(table, PARAM_RMAX);
    gwy_param_table_append_slider(table, PARAM_RPOWER);

    gwy_param_table_append_header(table, -1, _("Output"));
    gwy_param_table_append_slider(table, PARAM_HEIGHT);
    gwy_param_table_slider_set_mapping(table, PARAM_HEIGHT, GWY_SCALE_MAPPING_LOG);
    if (gui->template_) {
        gwy_param_table_append_button(table, BUTTON_LIKE_CURRENT_IMAGE, -1, GWY_RESPONSE_SYNTH_INIT_Z,
                                      _("_Like Current Image"));
    }
    gwy_param_table_append_slider(table, PARAM_EDGE_WIDTH);

    gwy_param_table_append_header(table, -1, _("Options"));
    gwy_param_table_append_seed(table, PARAM_SEED);
    gwy_param_table_append_checkbox(table, PARAM_RANDOMIZE);
    gwy_param_table_append_separator(table);
    gwy_param_table_append_checkbox(table, PARAM_UPDATE);


    return gwy_param_table_widget(table);
}

static void
param_changed(ModuleGUI *gui, gint id)
{
    GwyParamTable *table = gui->table_generator;
    GwyParams *params = gui->args->params;

    if (gwy_synth_handle_param_changed(gui->table_dimensions, id))
        id = -1;

    if (id < 0 || id == PARAM_DIMS0 + GWY_DIMS_PARAM_ZUNIT) {
        static const gint zids[] = { PARAM_HEIGHT };

        gwy_synth_update_value_unitstrs(table, zids, G_N_ELEMENTS(zids));
        gwy_synth_update_like_current_button_sensitivity(table, BUTTON_LIKE_CURRENT_IMAGE);
    }
    if (id < 0
        || id == PARAM_DIMS0 + GWY_DIMS_PARAM_XYUNIT
        || id == PARAM_DIMS0 + GWY_DIMS_PARAM_XRES
        || id == PARAM_DIMS0 + GWY_DIMS_PARAM_XREAL) {
        static const gint xyids[] = { PARAM_RMIN, PARAM_RMAX };

        gwy_synth_update_lateral_alts(table, xyids, G_N_ELEMENTS(xyids));
    }
    if (id < 0 || id == PARAM_RMIN || id == PARAM_RMAX) {
        gint rmin = gwy_params_get_int(params, PARAM_RMIN);
        gint rmax = gwy_params_get_int(params, PARAM_RMAX);
        if (rmin > rmax) {
            if (id == PARAM_RMIN)
                gwy_param_table_set_int(table, PARAM_RMAX, rmin);
            else if (id == PARAM_RMAX)
                gwy_param_table_set_int(table, PARAM_RMIN, rmax);
            else {
                gwy_param_table_set_int(table, PARAM_RMIN, (rmin + rmax)/2);
                gwy_param_table_set_int(table, PARAM_RMAX, (rmin + rmax)/2);
            }
        }
    }
    if ((id < PARAM_DIMS0 || id == PARAM_DIMS0 + GWY_DIMS_PARAM_INITIALIZE)
        && id != PARAM_UPDATE && id != PARAM_RANDOMIZE)
        gwy_dialog_invalidate(GWY_DIALOG(gui->dialog));
}

static void
dialog_response(ModuleGUI *gui, gint response)
{
    ModuleArgs *args = gui->args;

    if (response == GWY_RESPONSE_SYNTH_INIT_Z) {
        gdouble zscale = args->zscale;
        gint power10z;

        if (zscale > 0.0) {
            gwy_params_get_unit(args->params, PARAM_DIMS0 + GWY_DIMS_PARAM_ZUNIT, &power10z);
            gwy_param_table_set_double(gui->table_generator, PARAM_HEIGHT, zscale/gwy_exp10(power10z));
        }
    }
    else if (response == GWY_RESPONSE_SYNTH_TAKE_DIMS) {
        gwy_synth_use_dimensions_template(gui->table_dimensions);
    }
}

static void
preview(gpointer user_data)
{
    ModuleGUI *gui = (ModuleGUI*)user_data;

    execute(gui->args);
    gwy_field_data_changed(gui->args->result);
}

/* Render in fact outer circle with r+1/2 and inner with r-1/2 because these are ‘nice’. */
static void
render_disc(SegmentLists *sls, gint r,
            GArray *edgebuf, GArray *innerbuf)
{
    gdouble r2outer = r*r + r + 0.25, r2inner = r*r - r + 0.25;
    gint ypos;

    g_array_set_size(edgebuf, 0);
    g_array_set_size(innerbuf, 0);
    for (ypos = -r; ypos <= r; ypos++) {
        gint y2 = ypos*ypos;
        gint jouter = (gint)floor(sqrt(r2outer - y2));
        LineSegment ls;

        ls.ypos = ypos;
        if (y2 <= r2inner) {
            gint jinner = (gint)floor(sqrt(r2inner - y2));
            /* XXX: This should always hold. Can rounding error break it? */
            if (jouter > jinner) {
                ls.xstart = -jouter;
                ls.xend = -jinner-1;
                g_array_append_val(edgebuf, ls);
                ls.xstart = jinner+1;
                ls.xend = jouter;
                g_array_append_val(edgebuf, ls);
            }
            ls.xstart = -jinner;
            ls.xend = jinner;
            g_array_append_val(innerbuf, ls);
        }
        else {
            ls.xstart = -jouter;
            ls.xend = jouter;
            g_array_append_val(edgebuf, ls);
        }
    }

    sls->ninner = innerbuf->len;
    sls->inner = g_memdup(innerbuf->data, innerbuf->len*sizeof(LineSegment));

    sls->nedge = edgebuf->len;
    sls->edge = g_memdup(edgebuf->data, edgebuf->len*sizeof(LineSegment));
}

/* TODO: Add some resistance to etching – initialised either randomly or using the input field. */
static void
process_circle(gint8 *stage, gint xres, gint yres, gint col, gint row,
               const SegmentLists *sls,
               gint *queue, gint *ninq, gint *still_free)
{
    guint m;

    for (m = 0; m < sls->ninner; m++) {
        LineSegment ls = sls->inner[m];
        gint i = (row + yres + ls.ypos) % yres;
        gint8 *srow = stage + i*xres;
        gint j;

        //g_printerr("I%d [%d..%d]\n", i, ls.xstart, ls.xend);
        for (j = ls.xstart; j <= ls.xend; j++) {
            gint k = (col + xres + j) % xres;

            /* Do not do anything with the queue here. We only remove elements when as hit them. */
            if (srow[k] != INSIDE)
                (*still_free)--;
            srow[k] = INSIDE;
        }
    }
    for (m = 0; m < sls->nedge; m++) {
        LineSegment ls = sls->edge[m];
        gint i = (row + yres + ls.ypos) % yres;
        gint8 *srow = stage + i*xres;
        gint j;

        //g_printerr("E%d [%d..%d]\n", i, ls.xstart, ls.xend);
        for (j = ls.xstart; j <= ls.xend; j++) {
            gint k = (col + xres + j) % xres;

            if (srow[k] == OUTSIDE) {
                queue[(*ninq)++] = i*xres + k;
                srow[k] = EDGE;
            }
        }
    }
}

static void
prepare_discs(gint rmin, gint rmax, gdouble rpower,
              SegmentLists **pseglists, gdouble **prcdf)
{
    GArray *innerbuf, *edgebuf;
    SegmentLists *seglists;
    gdouble *rcdf;
    gint r;

    /* Cumulative distribution function for choosing radii with the selected probability. */
    rcdf = g_new0(gdouble, rmax+1);
    for (r = rmin; r <= rmax; r++)
        rcdf[r] = rcdf[r-1] + 1.0/pow(r, rpower);
    for (r = rmin; r <= rmax; r++)
        rcdf[r] /= rcdf[rmax];

    /* Precalculated shapes & their boundaries. */
    innerbuf = g_array_new(FALSE, FALSE, sizeof(LineSegment));
    edgebuf = g_array_new(FALSE, FALSE, sizeof(LineSegment));
    seglists = g_new0(SegmentLists, rmax+1);
    for (r = 1; r <= rmax; r++)
        render_disc(seglists+r, r, edgebuf, innerbuf);
    g_array_free(innerbuf, TRUE);
    g_array_free(edgebuf, TRUE);

    *pseglists = seglists;
    *prcdf = rcdf;
}

static void
free_prepared_discs(gint rmax, SegmentLists *seglists, gdouble *rcdf)
{
    gint r;

    if (seglists) {
        for (r = 1; r <= rmax; r++) {
            g_free(seglists[r].inner);
            g_free(seglists[r].edge);
        }
        g_free(seglists);
    }
    g_free(rcdf);
}

static inline gint
choose_radius_bisect(gint rmin, gint rmax, const gdouble *rcdf, GRand *rng)
{
    gdouble u = g_rand_double(rng);
    gint a = rmin, b = rmax;

    while (b > a+1) {
        gint r = (a + b)/2;
        if (rcdf[r] < u)
            a = r;
        else
            b = r;
    }

    return (rcdf[a] >= u ? a : b);
}

/* TODO: Seed some initial new points uniformly? */
static void
execute(ModuleArgs *args)
{
    GwyParams *params = args->params;
    gboolean do_initialise = gwy_params_get_boolean(params, PARAM_DIMS0 + GWY_DIMS_PARAM_INITIALIZE);
    gdouble height = gwy_params_get_double(params, PARAM_HEIGHT);
    gdouble edge_width = gwy_params_get_double(params, PARAM_EDGE_WIDTH);
    gdouble coverage = gwy_params_get_double(params, PARAM_COVERAGE);
    gdouble pnew = gwy_params_get_double(params, PARAM_PNEW);
    gint rmin = gwy_params_get_int(params, PARAM_RMIN);
    gint rmax = gwy_params_get_int(params, PARAM_RMAX);
    gdouble rpower = gwy_params_get_double(params, PARAM_RPOWER);
    GwyField *field = args->field, *result = args->result;
    gint xres = gwy_field_get_xres(result), yres = gwy_field_get_yres(result);

    GwyRandGenSet *rngset = gwy_rand_gen_set_new(RNG_NRNGS);
    gwy_rand_gen_set_init(rngset, gwy_params_get_int(params, PARAM_SEED));
    /* We do not use the distributions, but we would still like to have independent random number streams. */
    GRand *rng_r = gwy_rand_gen_set_rng(rngset, RNG_SIZE);
    GRand *rng_old = gwy_rand_gen_set_rng(rngset, RNG_OLD);
    GRand *rng_new = gwy_rand_gen_set_rng(rngset, RNG_NEW);

    gint power10z;
    gwy_params_get_unit(params, PARAM_DIMS0 + GWY_DIMS_PARAM_ZUNIT, &power10z);
    height *= gwy_exp10(power10z);

    /* When the disc wraps around the image twice some indices can become negative because (i + res) % res no longer
     * saves us. Just silently descrease the maximum size. */
    rmax = MIN(rmax, MIN(xres, yres));

    gdouble *rcdf;
    SegmentLists *seglists = NULL;
    prepare_discs(rmin, rmax, rpower, &seglists, &rcdf);

    gwy_field_clear(result);
    gint n = xres*yres;
    gint ninq = 0;
    gint *queue = g_new(guint, n);
    gint8 *stage = g_new0(gint8, n);

    gint still_free = n;
    gint target_n = GWY_ROUND(coverage*n);
    while (n - still_free < target_n) {
        gint k, r = choose_radius_bisect(rmin, rmax, rcdf, rng_r);
        if (!ninq || g_rand_double(rng_new) < pnew) {
            k = g_rand_int_range(rng_new, 0, n);
        }
        else {
            while (ninq) {
                gint m = g_rand_int_range(rng_old, 0, ninq);
                k = queue[m];
                if (stage[k] == EDGE)
                    break;
                /* The queue can contain no longer valid items because we do not bother handling them when filling new
                 * discs. Remove them as we hit them. */
                queue[m] = queue[ninq-1];
                ninq--;
            }
            /* We should terminate because still_free = 0, not here. */
            g_assert(ninq);
        }
        gint i = k/xres;
        gint j = k % xres;

        process_circle(stage, xres, yres, j, i, seglists + r, queue, &ninq, &still_free);
    }

    GwyNield *mask = gwy_field_new_nield_alike(result);
    gint *md = gwy_nield_get_data(mask);
    for (gint k = 0; k < n; k++)
        md[k] = (stage[k] == OUTSIDE);

    GwyNield *extmask = gwy_nield_extend(mask, xres/4, xres/4, yres/4, yres/4, GWY_EXTERIOR_PERIODIC, 0);
    g_object_unref(mask);
    gint extxres = gwy_nield_get_xres(extmask), extyres = gwy_nield_get_yres(extmask);
    GwyField *extfield = gwy_field_new(extxres, extyres, extxres, extyres, FALSE);
    gwy_nield_distance_transform(extmask, extfield, GWY_DISTANCE_TRANSFORM_EUCLIDEAN, TRUE, FALSE);
    g_object_unref(extmask);
    gwy_field_area_copy(extfield, result, xres/4, yres/4, xres, yres, 0, 0);
    g_object_unref(extfield);

    gdouble *d = gwy_field_get_data(result);
    for (gint k = 0; k < n; k++) {
        if (stage[k] == OUTSIDE) {
            gdouble t = (d[k] + 1)/edge_width;
            d[k] = height*(1.0 - exp(-0.5*t*t));
        }
        else
            d[k] = 0.0;
    }

    if (field && do_initialise)
        gwy_field_sum_fields(result, field, result);

    gwy_rand_gen_set_free(rngset);
    free_prepared_discs(rmax, seglists, rcdf);
    g_free(stage);
    g_free(queue);
}

/* vim: set cin columns=120 tw=118 et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */
