gimplineart.c 66.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* GIMP - The GNU Image Manipulation Program
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
 * Copyright (C) 2017 Sébastien Fourey & David Tchumperlé
 * Copyright (C) 2018 Jehan
 *
 * 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 3 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, see <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#define GEGL_ITERATOR2_API
#include <gegl.h>

#include "libgimpmath/gimpmath.h"

#include "core-types.h"

#include "gimplineart.h"

static int DeltaX[4] = {+1, -1, 0, 0};
static int DeltaY[4] = {0, 0, +1, -1};

static const GimpVector2 Direction2Normal[4] =
{
    {  1.0f,  0.0f },
    { -1.0f,  0.0f },
    {  0.0f,  1.0f },
    {  0.0f, -1.0f }
};

typedef enum _Direction
{
  XPlusDirection  = 0,
  XMinusDirection = 1,
  YPlusDirection  = 2,
  YMinusDirection = 3
} Direction;

typedef GimpVector2 Pixel;

typedef struct _SplineCandidate
{
  Pixel p1;
  Pixel p2;
  float quality;
} SplineCandidate;

typedef struct _Edgel
{
  gint      x, y;
  Direction direction;

  gfloat    x_normal;
  gfloat    y_normal;
  gfloat    curvature;
  guint     next, previous;
} Edgel;

static void         gimp_lineart_denoise                    (GeglBuffer             *buffer,
                                                             int                     size);
static void         gimp_lineart_compute_normals_curvatures (GeglBuffer             *mask,
Jehan's avatar
Jehan committed
74
75
                                                             gfloat                 *normals,
                                                             gfloat                 *curvatures,
76
                                                             gfloat                 *smoothed_curvatures,
77
                                                             int                     normal_estimate_mask_size);
78
static gfloat *     gimp_lineart_get_smooth_curvatures      (GArray                 *edgelset);
Jehan's avatar
Jehan committed
79
static GArray     * gimp_lineart_curvature_extremums        (gfloat                 *curvatures,
80
                                                             gfloat                 *smoothed_curvatures,
81
82
83
84
85
                                                             gint                    curvatures_width,
                                                             gint                    curvatures_height);
static gint         gimp_spline_candidate_cmp               (const SplineCandidate  *a,
                                                             const SplineCandidate  *b,
                                                             gpointer                user_data);
Jehan's avatar
Jehan committed
86
87
88
89
90
static GList      * gimp_lineart_find_spline_candidates     (GArray                 *max_positions,
                                                             gfloat                 *normals,
                                                             gint                    width,
                                                             gint                    distance_threshold,
                                                             gfloat                  max_angle_deg);
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

static GArray     * gimp_lineart_discrete_spline            (Pixel                   p0,
                                                             GimpVector2             n0,
                                                             Pixel                   p1,
                                                             GimpVector2             n1);

static gint         gimp_number_of_transitions               (GArray                 *pixels,
                                                              GeglBuffer             *buffer,
                                                              gboolean                border_value);
static gboolean     gimp_lineart_curve_creates_region        (GeglBuffer             *mask,
                                                              GArray                 *pixels,
                                                              int                     lower_size_limit,
                                                              int                     upper_size_limit);
static GArray     * gimp_lineart_line_segment_until_hit      (const GeglBuffer       *buffer,
                                                              Pixel                   start,
                                                              GimpVector2             direction,
                                                              int                     size);
108
static gfloat     * gimp_lineart_estimate_strokes_radii      (GeglBuffer             *mask);
109
110
111
112
113
114
115
116
117
118
119

/* Some callback-type functions. */

static guint        visited_hash_fun                         (Pixel                  *key);
static gboolean     visited_equal_fun                        (Pixel                  *e1,
                                                              Pixel                  *e2);

static inline gboolean    border_in_direction (GeglBuffer *mask,
                                               Pixel       p,
                                               int         direction);
static inline GimpVector2 pair2normal         (Pixel       p,
Jehan's avatar
Jehan committed
120
121
                                               gfloat     *normals,
                                               gint        width);
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

/* Edgel */

static Edgel    * gimp_edgel_new                  (int                x,
                                                   int                y,
                                                   Direction          direction);
static void       gimp_edgel_init                 (Edgel             *edgel);
static void       gimp_edgel_clear                (Edgel            **edgel);
static int        gimp_edgel_cmp                  (const Edgel       *e1,
                                                   const Edgel       *e2);
static guint      edgel2index_hash_fun            (Edgel              *key);
static gboolean   edgel2index_equal_fun           (Edgel              *e1,
                                                   Edgel              *e2);

static glong      gimp_edgel_track_mark           (GeglBuffer         *mask,
                                                   Edgel               edgel,
                                                   long                size_limit);
static glong      gimp_edgel_region_area          (const GeglBuffer   *mask,
                                                   Edgel               starting_edgel);

/* Edgel set */

static GArray   * gimp_edgelset_new               (GeglBuffer          *buffer);
static void       gimp_edgelset_add               (GArray             *set,
                                                   int                 x,
                                                   int                 y,
                                                   Direction           direction,
                                                   GHashTable         *edgel2index);
static void       gimp_edgelset_init_normals      (GArray             *set);
static void       gimp_edgelset_smooth_normals    (GArray             *set,
                                                   int                 mask_size);
static void       gimp_edgelset_compute_curvature (GArray             *set);

static void       gimp_edgelset_build_graph       (GArray            *set,
                                                   GeglBuffer        *buffer,
                                                   GHashTable        *edgel2index);
static void       gimp_edgelset_next8             (const GeglBuffer  *buffer,
                                                   Edgel             *it,
                                                   Edgel             *n);

/* Public functions */

/**
 * gimp_lineart_close:
166
 * @line_art: the input #GeglBuffer.
167
168
169
170
 * @select_transparent: whether we binarize the alpha channel or the
 *                      luminosity.
 * @stroke_threshold: [0-1] threshold value for detecting stroke pixels
 *                    (higher values will detect more stroke pixels).
171
172
173
174
175
176
 * @erosion: size (in pixels) of the rectangular structure used to erode
 *           the stroke pixels. 0 means no erosion will be done, and a
 *           negative value will compute a median approximation of the
 *           stroke width, for base of erosion.
 * @minimal_lineart_area: the minimum size in number pixels for area to
 *                        be considered as line art.
177
 * @normal_estimate_mask_size:
178
179
180
181
182
183
 * @end_point_rate: threshold to estimate if a curvature is an end-point
 *                  in [0-1] range value.
 * @spline_max_length: the maximum length for creating splines between
 *                     end points.
 * @spline_max_angle: the maximum angle between end point normals for
 *                    creating splines between them.
184
185
 * @end_point_connectivity:
 * @spline_roundness:
186
187
 * @allow_self_intersections: whether to allow created splines and
 *                            segments to intersect.
188
189
190
 * @created_regions_significant_area:
 * @created_regions_minimum_area:
 * @small_segments_from_spline_sources:
191
192
193
 * @segments_max_length: the maximum length for creating segments
 *                       between end points. Unlike splines, segments
 *                       are straight lines.
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
 *
 * Creates a binarized version of the strokes of @line_art, detected either
 * with luminosity (light means background) or alpha values depending on
 * @select_transparent. This binary version of the strokes will have closed
 * regions allowing adequate selection of "nearly closed regions".
 * This algorithm is meant for digital painting (and in particular on the
 * sketch-only step), and therefore will likely produce unexpected results on
 * other types of input.
 *
 * The algorithm is the first step from the research paper "A Fast and
 * Efficient Semi-guided Algorithm for Flat Coloring Line-arts", by Sébastian
 * Fourey, David Tschumperlé, David Revoy.
 *
 * Returns: a new #GeglBuffer of format "Y u8" representing the
 *          binarized @line_art. A value of
 */
GeglBuffer *
gimp_lineart_close (GeglBuffer          *line_art,
                    gboolean             select_transparent,
                    gfloat               stroke_threshold,
                    gint                 erosion,
                    gint                 minimal_lineart_area,
                    gint                 normal_estimate_mask_size,
                    gfloat               end_point_rate,
                    gint                 spline_max_length,
                    gfloat               spline_max_angle,
                    gint                 end_point_connectivity,
                    gfloat               spline_roundness,
                    gboolean             allow_self_intersections,
                    gint                 created_regions_significant_area,
                    gint                 created_regions_minimum_area,
                    gboolean             small_segments_from_spline_sources,
                    gint                 segments_max_length)
{
Jehan's avatar
Jehan committed
228
229
230
  const Babl         *gray_format;
  gfloat             *normals;
  gfloat             *curvatures;
231
232
  gfloat             *smoothed_curvatures;
  gfloat             *radii;
Jehan's avatar
Jehan committed
233
234
235
236
237
238
239
240
241
242
243
244
245
  GeglBufferIterator *gi;
  GeglBuffer         *closed;
  GeglBuffer         *strokes;
  GHashTable         *visited;
  GArray             *keypoints;
  Pixel              *point;
  GList              *candidates;
  SplineCandidate    *candidate;
  guchar              max_value = 0;
  gfloat              threshold;
  gint                width  = gegl_buffer_get_width (line_art);
  gint                height = gegl_buffer_get_height (line_art);
  gint                i;
246

247
248
249
  normals             = g_new0 (gfloat, width * height * 2);
  curvatures          = g_new0 (gfloat, width * height);
  smoothed_curvatures = g_new0 (gfloat, width * height);
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309

  if (select_transparent)
    /* Keep alpha channel as gray levels */
    gray_format = babl_format ("A u8");
  else
    /* Keep luminance */
    gray_format = babl_format ("Y' u8");

  /* Transform the line art from any format to gray. */
  strokes = gegl_buffer_new (gegl_buffer_get_extent (line_art),
                             gray_format);
  gegl_buffer_copy (line_art, NULL, GEGL_ABYSS_NONE, strokes, NULL);
  gegl_buffer_set_format (strokes, babl_format ("Y' u8"));

  if (! select_transparent)
    {
      /* Compute the biggest value */
      gi = gegl_buffer_iterator_new (strokes, NULL, 0, NULL,
                                     GEGL_ACCESS_READ, GEGL_ABYSS_NONE, 1);
      while (gegl_buffer_iterator_next (gi))
        {
          guchar *data = (guchar*) gi->items[0].data;
          gint    k;

          for (k = 0; k < gi->length; k++)
            {
              if (*data > max_value)
                max_value = *data;
              data++;
            }
        }
    }

  /* Make the image binary: 1 is stroke, 0 background */
  gi = gegl_buffer_iterator_new (strokes, NULL, 0, NULL,
                                 GEGL_ACCESS_READWRITE, GEGL_ABYSS_NONE, 1);
  while (gegl_buffer_iterator_next (gi))
    {
      guchar *data = (guchar*) gi->items[0].data;
      gint    k;

      for (k = 0; k < gi->length; k++)
        {
          if (! select_transparent)
            /* Negate the value. */
            *data = max_value - *data;
          /* Apply a threshold. */
          if (*data > (guchar) (255.0f * (1.0f - stroke_threshold)))
            *data = 1;
          else
            *data = 0;
          data++;
        }
    }

  /* Denoise (remove small connected components) */
  gimp_lineart_denoise (strokes, minimal_lineart_area);

  /* Estimate normals & curvature */
  gimp_lineart_compute_normals_curvatures (strokes, normals, curvatures,
310
                                           smoothed_curvatures,
311
312
                                           normal_estimate_mask_size);

313
314
  radii = gimp_lineart_estimate_strokes_radii (strokes);
  threshold = MAX (0.25f, 1.0f - end_point_rate);
315
316
317
318
319
  for (i = 0; i < width; i++)
    {
      gint j;
      for (j = 0; j < height; j++)
        {
320
321
322
323
324
          if (smoothed_curvatures[i + j * width] >= (threshold / MAX (1.0f, radii[i + j * width])) ||
              curvatures[i + j * width] >= threshold)
            curvatures[i + j * width] = 1.0;
          else
            curvatures[i + j * width] = 0.0;
325
326
        }
    }
327
  g_free (radii);
328

329
330
  keypoints = gimp_lineart_curvature_extremums (curvatures, smoothed_curvatures,
                                                width, height);
Jehan's avatar
Jehan committed
331
  candidates = gimp_lineart_find_spline_candidates (keypoints, normals, width,
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
                                                    spline_max_length,
                                                    spline_max_angle);
  closed = gegl_buffer_dup (strokes);

  /* Draw splines */
  visited = g_hash_table_new_full ((GHashFunc) visited_hash_fun,
                                   (GEqualFunc) visited_equal_fun,
                                   (GDestroyNotify) g_free, NULL);
  while (candidates)
    {
      Pixel    *p1 = g_new (Pixel, 1);
      Pixel    *p2 = g_new (Pixel, 1);
      gboolean  inserted = FALSE;

      candidate = (SplineCandidate *) candidates->data;
      p1->x = candidate->p1.x;
      p1->y = candidate->p1.y;
      p2->x = candidate->p2.x;
      p2->y = candidate->p2.y;

      g_free (candidate);
      candidates = g_list_delete_link (candidates, candidates);

      if ((! g_hash_table_contains (visited, p1) ||
           GPOINTER_TO_INT (g_hash_table_lookup (visited, p1)) < end_point_connectivity) &&
          (! g_hash_table_contains (visited, p2) ||
           GPOINTER_TO_INT (g_hash_table_lookup (visited, p2)) < end_point_connectivity))
        {
          GArray      *discrete_curve;
Jehan's avatar
Jehan committed
361
362
          GimpVector2  vect1 = pair2normal (*p1, normals, width);
          GimpVector2  vect2 = pair2normal (*p2, normals, width);
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
          gfloat       distance = gimp_vector2_length_val (gimp_vector2_sub_val (*p1, *p2));
          gint         transitions;

          gimp_vector2_mul (&vect1, distance);
          gimp_vector2_mul (&vect1, spline_roundness);
          gimp_vector2_mul (&vect2, distance);
          gimp_vector2_mul (&vect2, spline_roundness);

          discrete_curve = gimp_lineart_discrete_spline (*p1, vect1, *p2, vect2);

          transitions = allow_self_intersections ?
                          gimp_number_of_transitions (discrete_curve, strokes, FALSE) :
                          gimp_number_of_transitions (discrete_curve, closed, FALSE);

          if (transitions == 2 &&
              ! gimp_lineart_curve_creates_region (closed, discrete_curve,
                                                   created_regions_significant_area,
                                                   created_regions_minimum_area - 1))
            {
              for (i = 0; i < discrete_curve->len; i++)
                {
                  Pixel p = g_array_index (discrete_curve, Pixel, i);

                  if (p.x >= 0 && p.x < gegl_buffer_get_width (closed) &&
                      p.y >= 0 && p.y < gegl_buffer_get_height (closed))
                    {
                      guchar val = 1;

                      gegl_buffer_set (closed, GEGL_RECTANGLE ((gint) p.x, (gint) p.y, 1, 1), 0,
                                       NULL, &val, GEGL_AUTO_ROWSTRIDE);
                    }
                }
              g_hash_table_replace (visited, p1,
                                    GINT_TO_POINTER (GPOINTER_TO_INT (g_hash_table_lookup (visited, p1)) + 1));
              g_hash_table_replace (visited, p2,
                                    GINT_TO_POINTER (GPOINTER_TO_INT (g_hash_table_lookup (visited, p2)) + 1));
              inserted = TRUE;
            }
          g_array_free (discrete_curve, TRUE);
        }
      if (! inserted)
        {
          g_free (p1);
          g_free (p2);
        }
    }

  /* Draw straight line segments */
  point = (Pixel *) keypoints->data;
  for (i = 0; i < keypoints->len; i++)
    {
      Pixel    *p = g_new (Pixel, 1);
      gboolean  inserted = FALSE;

      *p = *point;

      if (! g_hash_table_contains (visited, p) ||
          (small_segments_from_spline_sources &&
           GPOINTER_TO_INT (g_hash_table_lookup (visited, p)) < end_point_connectivity))
        {
          GArray *segment = gimp_lineart_line_segment_until_hit (closed, *point,
Jehan's avatar
Jehan committed
424
                                                                 pair2normal (*point, normals, width),
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
                                                                 segments_max_length);

          if (segment->len &&
              ! gimp_lineart_curve_creates_region (closed, segment,
                                                   created_regions_significant_area,
                                                   created_regions_minimum_area - 1))
            {
              gint j;

              for (j = 0; j < segment->len; j++)
                {
                  Pixel  p2 = g_array_index (segment, Pixel, j);
                  guchar val = 1;

                  gegl_buffer_set (closed, GEGL_RECTANGLE ((gint) p2.x, (gint) p2.y, 1, 1), 0,
                                   NULL, &val, GEGL_AUTO_ROWSTRIDE);
                }
              g_hash_table_replace (visited, p,
                                    GINT_TO_POINTER (GPOINTER_TO_INT (g_hash_table_lookup (visited, p)) + 1));
              inserted = TRUE;
            }
          g_array_free (segment, TRUE);
        }
      if (! inserted)
        g_free (p);
      point++;
    }

453
  g_hash_table_destroy (visited);
454
455
456
457
  g_array_free (keypoints, TRUE);
  g_object_unref (strokes);
  g_free (normals);
  g_free (curvatures);
458
  g_free (smoothed_curvatures);
459
460
461
462
463
464
465
466
467
468
469
470
471
  g_list_free_full (candidates, g_free);

  return closed;
}

/* Private functions */

static void
gimp_lineart_denoise (GeglBuffer *buffer,
                      int         minimum_area)
{
  /* Keep connected regions with significant area. */
  GArray   *region;
472
473
474
475
476
  GQueue   *q       = g_queue_new ();
  gint      width   = gegl_buffer_get_width (buffer);
  gint      height  = gegl_buffer_get_height (buffer);
  gboolean *visited = g_new0 (gboolean, width * height);
  gint      x, y;
477
478
479

  region = g_array_sized_new (TRUE, TRUE, sizeof (Pixel *), minimum_area);

480
481
  for (y = 0; y < height; ++y)
    for (x = 0; x < width; ++x)
482
483
484
485
486
      {
        guchar has_stroke;

        gegl_buffer_sample (buffer, x, y, NULL, &has_stroke, NULL,
                            GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
487
        if (has_stroke && ! visited[x + y * width])
488
489
          {
            Pixel *p = g_new (Pixel, 1);
490
            gint   regionSize = 0;
491
492
493
494
495

            p->x = x;
            p->y = y;

            g_queue_push_tail (q, p);
496
            visited[x + y * width] = TRUE;
497
498
499
500
501
502
503
504
505
506
507
508
509

            while (! g_queue_is_empty (q))
              {
                Pixel *p = (Pixel *) g_queue_pop_head (q);
                gint   p2x;
                gint   p2y;

                p2x = p->x + 1;
                p2y = p->y;
                if (p2x >= 0 && p2x < width && p2y >= 0 && p2y < height)
                  {
                    gegl_buffer_sample (buffer, p2x, p2y, NULL, &has_stroke, NULL,
                                        GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
510
                    if (has_stroke && ! visited[p2x + p2y * width])
511
512
513
514
515
516
                      {
                        Pixel *p2 = g_new (Pixel, 1);

                        p2->x = p2x;
                        p2->y = p2y;
                        g_queue_push_tail (q, p2);
517
                        visited[p2x +p2y * width] = TRUE;
518
519
520
521
522
523
524
525
                      }
                  }
                p2x = p->x - 1;
                p2y = p->y;
                if (p2x >= 0 && p2x < width && p2y >= 0 && p2y < height)
                  {
                    gegl_buffer_sample (buffer, p2x, p2y, NULL, &has_stroke, NULL,
                                        GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
526
                    if (has_stroke && ! visited[p2x + p2y * width])
527
528
529
530
531
532
                      {
                        Pixel *p2 = g_new (Pixel, 1);

                        p2->x = p2x;
                        p2->y = p2y;
                        g_queue_push_tail (q, p2);
533
                        visited[p2x + p2y * width] = TRUE;
534
535
536
537
538
539
540
541
                      }
                  }
                p2x = p->x;
                p2y = p->y - 1;
                if (p2x >= 0 && p2x < width && p2y >= 0 && p2y < height)
                  {
                    gegl_buffer_sample (buffer, p2x, p2y, NULL, &has_stroke, NULL,
                                        GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
542
                    if (has_stroke && ! visited[p2x + p2y * width])
543
544
545
546
547
548
                      {
                        Pixel *p2 = g_new (Pixel, 1);

                        p2->x = p2x;
                        p2->y = p2y;
                        g_queue_push_tail (q, p2);
549
                        visited[p2x + p2y * width] = TRUE;
550
551
552
553
554
555
556
557
                      }
                  }
                p2x = p->x;
                p2y = p->y + 1;
                if (p2x >= 0 && p2x < width && p2y >= 0 && p2y < height)
                  {
                    gegl_buffer_sample (buffer, p2x, p2y, NULL, &has_stroke, NULL,
                                        GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
558
                    if (has_stroke && ! visited[p2x + p2y * width])
559
560
561
562
563
564
                      {
                        Pixel *p2 = g_new (Pixel, 1);

                        p2->x = p2x;
                        p2->y = p2y;
                        g_queue_push_tail (q, p2);
565
                        visited[p2x + p2y * width] = TRUE;
566
567
568
569
570
571
572
573
                      }
                  }
                p2x = p->x + 1;
                p2y = p->y + 1;
                if (p2x >= 0 && p2x < width && p2y >= 0 && p2y < height)
                  {
                    gegl_buffer_sample (buffer, p2x, p2y, NULL, &has_stroke, NULL,
                                        GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
574
                    if (has_stroke && ! visited[p2x + p2y * width])
575
576
577
578
579
580
                      {
                        Pixel *p2 = g_new (Pixel, 1);

                        p2->x = p2x;
                        p2->y = p2y;
                        g_queue_push_tail (q, p2);
581
                        visited[p2x + p2y * width] = TRUE;
582
583
584
585
586
587
588
589
                      }
                  }
                p2x = p->x - 1;
                p2y = p->y - 1;
                if (p2x >= 0 && p2x < width && p2y >= 0 && p2y < height)
                  {
                    gegl_buffer_sample (buffer, p2x, p2y, NULL, &has_stroke, NULL,
                                        GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
590
                    if (has_stroke && ! visited[p2x + p2y * width])
591
592
593
594
595
596
                      {
                        Pixel *p2 = g_new (Pixel, 1);

                        p2->x = p2x;
                        p2->y = p2y;
                        g_queue_push_tail (q, p2);
597
                        visited[p2x + p2y * width] = TRUE;
598
599
600
601
602
603
604
605
                      }
                  }
                p2x = p->x - 1;
                p2y = p->y + 1;
                if (p2x >= 0 && p2x < width && p2y >= 0 && p2y < height)
                  {
                    gegl_buffer_sample (buffer, p2x, p2y, NULL, &has_stroke, NULL,
                                        GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
606
                    if (has_stroke && ! visited[p2x + p2y * width])
607
608
609
610
611
612
                      {
                        Pixel *p2 = g_new (Pixel, 1);

                        p2->x = p2x;
                        p2->y = p2y;
                        g_queue_push_tail (q, p2);
613
                        visited[p2x + p2y * width] = TRUE;
614
615
616
617
618
619
620
621
                      }
                  }
                p2x = p->x + 1;
                p2y = p->y - 1;
                if (p2x >= 0 && p2x < width && p2y >= 0 && p2y < height)
                  {
                    gegl_buffer_sample (buffer, p2x, p2y, NULL, &has_stroke, NULL,
                                        GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
622
                    if (has_stroke && ! visited[p2x + p2y * width])
623
624
625
626
627
628
                      {
                        Pixel *p2 = g_new (Pixel, 1);

                        p2->x = p2x;
                        p2->y = p2y;
                        g_queue_push_tail (q, p2);
629
                        visited[p2x + p2y * width] = TRUE;
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
                      }
                  }

                ++regionSize;
                if (regionSize < minimum_area)
                  g_array_append_val (region, *p);
                g_free (p);
              }
            if (regionSize < minimum_area)
              {
                Pixel *pixel = (Pixel *) region->data;
                gint   i = 0;

                for (; i < region->len; i++)
                  {
                    guchar val = 0;
                    gegl_buffer_set (buffer, GEGL_RECTANGLE (pixel->x, pixel->y, 1, 1), 0,
                                     NULL, &val, GEGL_AUTO_ROWSTRIDE);
                    pixel++;
                  }
              }
            g_array_remove_range (region, 0, region->len);
          }
      }
  g_array_free (region, TRUE);
  g_queue_free_full (q, g_free);
656
  g_free (visited);
657
658
659
}

static void
Jehan's avatar
Jehan committed
660
661
662
gimp_lineart_compute_normals_curvatures (GeglBuffer *mask,
                                         gfloat     *normals,
                                         gfloat     *curvatures,
663
                                         gfloat     *smoothed_curvatures,
Jehan's avatar
Jehan committed
664
                                         int         normal_estimate_mask_size)
665
{
666
667
  gfloat  *edgels_curvatures;
  gfloat  *smoothed_curvature;
Jehan's avatar
Jehan committed
668
669
670
  GArray  *es    = gimp_edgelset_new (mask);
  Edgel  **e     = (Edgel **) es->data;
  gint     width = gegl_buffer_get_width (mask);
671
672
673
674
675
676

  gimp_edgelset_smooth_normals (es, normal_estimate_mask_size);
  gimp_edgelset_compute_curvature (es);

  while (*e)
    {
677
678
      const float curvature = ((*e)->curvature > 0.0f) ? (*e)->curvature : 0.0f;
      const float w         = MAX (1e-8f, curvature * curvature);
679

Jehan's avatar
Jehan committed
680
681
      normals[((*e)->x + (*e)->y * width) * 2] += w * (*e)->x_normal;
      normals[((*e)->x + (*e)->y * width) * 2 + 1] += w * (*e)->y_normal;
682
      curvatures[(*e)->x + (*e)->y * width] = MAX (curvature,
Jehan's avatar
Jehan committed
683
                                                   curvatures[(*e)->x + (*e)->y * width]);
684
685
686
687
688
      e++;
    }
  for (int y = 0; y < gegl_buffer_get_height (mask); ++y)
    for (int x = 0; x < gegl_buffer_get_width (mask); ++x)
      {
Jehan's avatar
Jehan committed
689
690
691
692
        const float _angle = atan2f (normals[(x + y * width) * 2 + 1],
                                     normals[(x + y * width) * 2]);
        normals[(x + y * width) * 2] = cosf (_angle);
        normals[(x + y * width) * 2 + 1] = sinf (_angle);
693
      }
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711

  /* Smooth curvatures on edgels, then take maximum on each pixel. */
  edgels_curvatures = gimp_lineart_get_smooth_curvatures (es);
  smoothed_curvature = edgels_curvatures;

  e = (Edgel **) es->data;
  while (*e)
    {
      gfloat *pixel_curvature = &smoothed_curvatures[(*e)->x + (*e)->y * width];

      if (*pixel_curvature < *smoothed_curvature)
        *pixel_curvature = *smoothed_curvature;

      ++smoothed_curvature;
      e++;
    }
  g_free (edgels_curvatures);

712
713
714
  g_array_free (es, TRUE);
}

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
static gfloat *
gimp_lineart_get_smooth_curvatures (GArray *edgelset)
{
  Edgel  **e;
  gfloat  *smoothed_curvatures = g_new0 (gfloat, edgelset->len);
  gfloat   weights[9];
  gfloat   smoothed_curvature;
  gfloat   weights_sum;
  gint     idx = 0;

  weights[0] = 1.0f;
  for (int i = 1; i <= 8; ++i)
    weights[i] = expf (-(i * i) / 30.0f);

  e = (Edgel **) edgelset->data;
  while (*e)
    {
      Edgel *edgel_before = g_array_index (edgelset, Edgel*, (*e)->previous);
      Edgel *edgel_after  = g_array_index (edgelset, Edgel*, (*e)->next);
      int    n = 5;
      int    i = 1;

      smoothed_curvature = (*e)->curvature;
      weights_sum = weights[0];
      while (n-- && (edgel_after != edgel_before))
        {
          smoothed_curvature += weights[i] * edgel_before->curvature;
          smoothed_curvature += weights[i] * edgel_after->curvature;
          edgel_before = g_array_index (edgelset, Edgel*, edgel_before->previous);
          edgel_after  = g_array_index (edgelset, Edgel*, edgel_after->next);
          weights_sum += 2 * weights[i];
          i++;
        }
      smoothed_curvature /= weights_sum;
      smoothed_curvatures[idx++] = smoothed_curvature;

      e++;
    }

  return smoothed_curvatures;
}

757
758
759
760
/**
 * Keep one pixel per connected component of curvature extremums.
 */
static GArray *
Jehan's avatar
Jehan committed
761
gimp_lineart_curvature_extremums (gfloat *curvatures,
762
                                  gfloat *smoothed_curvatures,
Jehan's avatar
Jehan committed
763
764
                                  gint    width,
                                  gint    height)
765
{
766
767
  gboolean *visited = g_new0 (gboolean, width * height);
  GQueue   *q       = g_queue_new ();
768
769
770
771
772
773
774
  GArray   *max_positions;

  max_positions = g_array_new (FALSE, TRUE, sizeof (Pixel));

  for (int y = 0; y < height; ++y)
    for (int x = 0; x < width; ++x)
      {
Jehan's avatar
Jehan committed
775
        if ((curvatures[x + y * width] > 0.0) && ! visited[x + y * width])
776
          {
777
778
779
            Pixel  *p = g_new (Pixel, 1);
            Pixel   max_curvature_pixel = gimp_vector2_new (-1.0, -1.0);
            gfloat  max_curvature = 0.0f;
780
781
782
783

            p->x = x;
            p->y = y;
            g_queue_push_tail (q, p);
784
            visited[x + y * width] = TRUE;
785
786
787
788
789
790
791
792

            while (! g_queue_is_empty (q))
              {
                gfloat c;
                gint   p2x;
                gint   p2y;

                p = (Pixel *) g_queue_pop_head (q);
793
                c = smoothed_curvatures[(gint) p->x + (gint) p->y * width];
794

Jehan's avatar
Jehan committed
795
                curvatures[(gint) p->x + (gint) p->y * width] = 0.0f;
796
797
798
799
800

                p2x = (gint) p->x + 1;
                p2y = (gint) p->y;
                if (p2x >= 0 && p2x < width    &&
                    p2y >= 0 && p2y < height   &&
Jehan's avatar
Jehan committed
801
                    curvatures[p2x + p2y * width] > 0.0 &&
802
                    ! visited[p2x + p2y * width])
803
804
805
806
807
808
                  {
                    Pixel *p2 = g_new (Pixel, 1);

                    p2->x = p2x;
                    p2->y = p2y;
                    g_queue_push_tail (q, p2);
809
                    visited[p2x + p2y * width] = TRUE;
810
811
812
813
814
815
                  }

                p2x = p->x - 1;
                p2y = p->y;
                if (p2x >= 0 && p2x < width    &&
                    p2y >= 0 && p2y < height   &&
Jehan's avatar
Jehan committed
816
                    curvatures[p2x + p2y * width] > 0.0 &&
817
                    ! visited[p2x + p2y * width])
818
819
820
821
822
823
                  {
                    Pixel *p2 = g_new (Pixel, 1);

                    p2->x = p2x;
                    p2->y = p2y;
                    g_queue_push_tail (q, p2);
824
                    visited[p2x + p2y * width] = TRUE;
825
826
827
828
829
830
                  }

                p2x = p->x;
                p2y = p->y - 1;
                if (p2x >= 0 && p2x < width    &&
                    p2y >= 0 && p2y < height   &&
Jehan's avatar
Jehan committed
831
                    curvatures[p2x + p2y * width] > 0.0 &&
832
                    ! visited[p2x + p2y * width])
833
834
835
836
837
838
                  {
                    Pixel *p2 = g_new (Pixel, 1);

                    p2->x = p2x;
                    p2->y = p2y;
                    g_queue_push_tail (q, p2);
839
                    visited[p2x + p2y * width] = TRUE;
840
841
842
843
844
845
                  }

                p2x = p->x;
                p2y = p->y + 1;
                if (p2x >= 0 && p2x < width    &&
                    p2y >= 0 && p2y < height   &&
Jehan's avatar
Jehan committed
846
                    curvatures[p2x + p2y * width] > 0.0 &&
847
                    ! visited[p2x + p2y * width])
848
849
850
851
852
853
                  {
                    Pixel *p2 = g_new (Pixel, 1);

                    p2->x = p2x;
                    p2->y = p2y;
                    g_queue_push_tail (q, p2);
854
                    visited[p2x + p2y * width] = TRUE;
855
856
857
858
859
860
                  }

                p2x = p->x + 1;
                p2y = p->y + 1;
                if (p2x >= 0 && p2x < width    &&
                    p2y >= 0 && p2y < height   &&
Jehan's avatar
Jehan committed
861
                    curvatures[p2x + p2y * width] > 0.0 &&
862
                    ! visited[p2x + p2y * width])
863
864
865
866
867
868
                  {
                    Pixel *p2 = g_new (Pixel, 1);

                    p2->x = p2x;
                    p2->y = p2y;
                    g_queue_push_tail (q, p2);
869
                    visited[p2x + p2y * width] = TRUE;
870
871
872
873
874
875
                  }

                p2x = p->x - 1;
                p2y = p->y - 1;
                if (p2x >= 0 && p2x < width    &&
                    p2y >= 0 && p2y < height   &&
Jehan's avatar
Jehan committed
876
                    curvatures[p2x + p2y * width] > 0.0 &&
877
                    ! visited[p2x + p2y * width])
878
879
880
881
882
883
                  {
                    Pixel *p2 = g_new (Pixel, 1);

                    p2->x = p2x;
                    p2->y = p2y;
                    g_queue_push_tail (q, p2);
884
                    visited[p2x + p2y * width] = TRUE;
885
886
887
888
889
890
                  }

                p2x = p->x - 1;
                p2y = p->y + 1;
                if (p2x >= 0 && p2x < width    &&
                    p2y >= 0 && p2y < height   &&
Jehan's avatar
Jehan committed
891
                    curvatures[p2x + p2y * width] > 0.0 &&
892
                    ! visited[p2x + p2y * width])
893
894
895
896
897
898
                  {
                    Pixel *p2 = g_new (Pixel, 1);

                    p2->x = p2x;
                    p2->y = p2y;
                    g_queue_push_tail (q, p2);
899
                    visited[p2x + p2y * width] = TRUE;
900
901
902
903
904
905
                  }

                p2x = p->x + 1;
                p2y = p->y - 1;
                if (p2x >= 0 && p2x < width    &&
                    p2y >= 0 && p2y < height   &&
Jehan's avatar
Jehan committed
906
                    curvatures[p2x + p2y * width] > 0.0 &&
907
                    ! visited[p2x + p2y * width])
908
909
910
911
912
913
                  {
                    Pixel *p2 = g_new (Pixel, 1);

                    p2->x = p2x;
                    p2->y = p2y;
                    g_queue_push_tail (q, p2);
914
                    visited[p2x + p2y * width] = TRUE;
915
916
917
918
919
920
921
922
923
                  }

                if (c > max_curvature)
                  {
                    max_curvature_pixel = *p;
                    max_curvature = c;
                  }
                g_free (p);
              }
Jehan's avatar
Jehan committed
924
            curvatures[(gint) max_curvature_pixel.x + (gint) max_curvature_pixel.y * width] = max_curvature;
925
926
927
928
            g_array_append_val (max_positions, max_curvature_pixel);
          }
      }
  g_queue_free_full (q, g_free);
929
  g_free (visited);
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951

  return max_positions;
}

static gint
gimp_spline_candidate_cmp (const SplineCandidate *a,
                           const SplineCandidate *b,
                           gpointer               user_data)
{
  /* This comparison actually returns the opposite of common comparison
   * functions on purpose, as we want the first element on the list to
   * be the "bigger".
   */
  if (a->quality < b->quality)
    return 1;
  else if (a->quality > b->quality)
    return -1;
  else
    return 0;
}

static GList *
Jehan's avatar
Jehan committed
952
953
954
955
956
gimp_lineart_find_spline_candidates (GArray *max_positions,
                                     gfloat *normals,
                                     gint    width,
                                     gint    distance_threshold,
                                     gfloat  max_angle_deg)
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
{
  GList       *candidates = NULL;
  const float  CosMin     = cosf (M_PI * (max_angle_deg / 180.0));
  gint         i;

  for (i = 0; i < max_positions->len; i++)
    {
      Pixel p1 = g_array_index (max_positions, Pixel, i);
      gint  j;

      for (j = i + 1; j < max_positions->len; j++)
        {
          Pixel       p2 = g_array_index (max_positions, Pixel, j);
          const float distance = gimp_vector2_length_val (gimp_vector2_sub_val (p1, p2));

          if (distance <= distance_threshold)
            {
              GimpVector2 normalP1;
              GimpVector2 normalP2;
              GimpVector2 p1f;
              GimpVector2 p2f;
              GimpVector2 p1p2;
              float       cosN;
              float       qualityA;
              float       qualityB;
              float       qualityC;
              float       quality;

Jehan's avatar
Jehan committed
985
986
987
988
              normalP1 = gimp_vector2_new (normals[((gint) p1.x + (gint) p1.y * width) * 2],
                                           normals[((gint) p1.x + (gint) p1.y * width) * 2 + 1]);
              normalP2 = gimp_vector2_new (normals[((gint) p2.x + (gint) p2.y * width) * 2],
                                           normals[((gint) p2.x + (gint) p2.y * width) * 2 + 1]);
989
990
991
992
993
994
995
996
997
998
999
1000
              p1f = gimp_vector2_new (p1.x, p1.y);
              p2f = gimp_vector2_new (p2.x, p2.y);
              p1p2 = gimp_vector2_sub_val (p2f, p1f);

              cosN = gimp_vector2_inner_product_val (normalP1, (gimp_vector2_neg_val (normalP2)));
              qualityA = MAX (0.0f, 1 - distance / distance_threshold);
              qualityB = MAX (0.0f,
                              (float) (gimp_vector2_inner_product_val (normalP1, p1p2) - gimp_vector2_inner_product_val (normalP2, p1p2)) /
                              distance);
              qualityC = MAX (0.0f, cosN - CosMin);
              quality = qualityA * qualityB * qualityC;
              if (quality > 0)