iscissors.c 66.5 KB
Newer Older
Elliot Lee's avatar
Elliot Lee committed
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
/* The GIMP -- an image manipulation program
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
 * 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/* This tool is based on a paper from SIGGRAPH '95
 * thanks to Professor D. Forsyth for prompting us to implement this tool
 */

#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "appenv.h"
#include "bezier_selectP.h"
#include "draw_core.h"
29 30
#include "channel_pvt.h"
#include "drawable.h"
Elliot Lee's avatar
Elliot Lee committed
31 32 33 34 35 36 37 38 39
#include "errors.h"
#include "gdisplay.h"
#include "gimage_mask.h"
#include "interface.h"
#include "iscissors.h"
#include "edit_selection.h"
#include "paint_funcs.h"
#include "rect_select.h"
#include "temp_buf.h"
40
#include "tools.h"
Elliot Lee's avatar
Elliot Lee committed
41

Manish Singh's avatar
Manish Singh committed
42 43 44
#ifndef M_PI
#define M_PI    3.14159265358979323846
#endif /* M_PI */
Manish Singh's avatar
Manish Singh committed
45 46 47
#ifndef M_PI_4
#define M_PI_4  0.78539816339744830962
#endif /* M_PI_4 */
Manish Singh's avatar
Manish Singh committed
48

Elliot Lee's avatar
Elliot Lee committed
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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
/*  local structures  */

typedef struct _IScissorsOptions IScissorsOptions;

struct _IScissorsOptions
{
  int antialias;
  int feather;
  double feather_radius;
  double resolution;
  double threshold;
};

typedef struct _kink Kink;

struct _kink
{
  int             x, y;         /*  coordinates  */
  int             is_a_kink;    /*  is this a kink?  */
  double          normal[2];    /*  normal vector to kink  */
  double          kinkiness;    /*  kinkiness measure  */
};

typedef struct _point Point;

struct _point
{
  int             x, y;         /*  coordinates  */
  int             dir;          /*  direction  */
  int             kink;         /*  is it a kink?  */
  int             stable;       /*  is the point in a stable locale?  */
  double          dx, dy;       /*  moving coordinates  */
  double          normal[2];    /*  normal vector to kink  */
};

typedef struct _iscissors Iscissors;

struct _iscissors
{
  DrawCore *      core;         /*  Core select object               */
  int             x, y;         /*  upper left hand coordinate       */
  int             ix, iy;       /*  initial coordinates              */
  int             nx, ny;       /*  new coordinates                  */
  int             state;        /*  state of iscissors               */
  int             num_segs;     /*  number of points in the polygon  */
  int             num_pts;      /*  number of kinks in list          */
  int             num_kinks;    /*  number of kinks in list          */
  Channel *       mask;         /*  selection mask                   */
  Kink *          kinks;        /*  kinks in the object outline      */
  TempBuf *       edge_buf;     /*  edge map buffer                  */
};

typedef double BezierMatrix[4][4];
typedef double CRMatrix[4][4];

/**********************************************/
/*  Intelligent scissors selection apparatus  */

#define  IMAGE_COORDS      1
#define  AA_IMAGE_COORDS   2
#define  SCREEN_COORDS     3

#define  SUPERSAMPLE       3
#define  SUPERSAMPLE2      9

#define  FREE_SELECT_MODE  0
#define  BOUNDARY_MODE     1

#define  POINT_WIDTH       8
#define  POINT_HALFWIDTH   4

#define  DEFAULT_MAX_INC   1024
#define  EDGE_WIDTH        1
#define  LOCALIZE_RADIUS   24
#define  BLOCK_WIDTH       64
#define  BLOCK_HEIGHT      64
#define  CONV_WIDTH        BLOCK_WIDTH
#define  CONV_HEIGHT       BLOCK_HEIGHT

#define  HORIZONTAL        0
#define  VERTICAL          1

#define  SUBDIVIDE         1000
#define  EDGE_STRENGTH     255
#define  EPSILON           0.00001

#define  NO                0
#define  YES               1

/*  functional defines  */
139

Elliot Lee's avatar
Elliot Lee committed
140 141 142 143 144 145 146
#define  SQR(x)            ((x) * (x))
#define  BILINEAR(jk,j1k,jk1,j1k1,dx,dy) \
     ((1-dy) * ((1-dx)*jk + dx*j1k) + \
      dy  * ((1-dx)*jk1 + dx*j1k1))


/*  static variables  */
147
static Tool* last_tool;
Elliot Lee's avatar
Elliot Lee committed
148 149 150 151 152 153 154 155 156 157

/*  The global array of XSegments for drawing the polygon...  */
static GdkSegment *segs = NULL;
static int         max_segs = 0;
static Point *     pts = NULL;
static int         max_pts = 0;

/*  boundary resolution variables  */
static int         resolution = 20;     /* in pixels */
static int         threshold  = 15;     /* in intensity */
158
static double      elasticity = 0.30;   /* between 0.0 -> 1.0 */
Elliot Lee's avatar
Elliot Lee committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
static double      kink_thres = 0.33;   /* between 0.0 -> 1.0 */
static double      std_dev    = 1.0;    /* in pixels */
static int         miss_thres = 4;      /* in intensity */

/*  edge map blocks variables  */
static TempBuf **  edge_map_blocks = NULL;
static int         horz_blocks;
static int         vert_blocks;

/*  convolution and basis matrixes  */
static unsigned char  conv1 [CONV_WIDTH * CONV_HEIGHT * MAX_CHANNELS];
static unsigned char  conv2 [CONV_WIDTH * CONV_HEIGHT * MAX_CHANNELS];
static unsigned char  grad  [(CONV_WIDTH + 2) * (CONV_HEIGHT + 2)];

static CRMatrix CR_basis =
{
  { -0.5,  1.5, -1.5,  0.5 },
  {  1.0, -2.5,  2.0, -0.5 },
  { -0.5,  0.0,  0.5,  0.0 },
  {  0.0,  1.0,  0.0,  0.0 },
};

static CRMatrix CR_bezier_basis =
{
  {  0.0,  1.0,  0.0,  0.0 },
  { -0.16667, 1.0, 0.16667, 0.0 },
  {  0.0,  0.16667, 1.0, -0.16667 },
  {  0.0,  0.0,  1.0,  0.0 },
};

static IScissorsOptions *iscissors_options = NULL;

/***********************************************************************/


/*  Local function prototypes  */
195 196 197

static void   selection_to_bezier	    (GtkWidget* , gpointer);

Elliot Lee's avatar
Elliot Lee committed
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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
static void   iscissors_button_press    (Tool *, GdkEventButton *, gpointer);
static void   iscissors_button_release  (Tool *, GdkEventButton *, gpointer);
static void   iscissors_motion          (Tool *, GdkEventMotion *, gpointer);
static void   iscissors_control         (Tool *, int, gpointer);
static void   iscissors_reset           (Iscissors *);
static void   iscissors_draw            (Tool *);
static void   iscissors_draw_CR         (GDisplay *, Iscissors *,
					 Point *, int *, int);
static void   CR_compose                (CRMatrix, CRMatrix, CRMatrix);
static int    add_segment               (int *, int, int);
static int    add_point                 (int *, int, int, int, double *);

/*  boundary localization routines  */
static void   normalize                 (double *);
static double dotprod                   (double *, double *);
static Kink * get_kink                  (Kink *, int, int);
static int    find_next_kink            (Kink *, int, int);
static double find_distance             (Kink *, int, int);
static int    go_distance               (Kink *, int, double, double *, double *);
static int    travel_length             (Kink *, int, int, int, int);
static int    find_edge_xy              (TempBuf *, int, double, double, double *);
static void   find_boundary             (Tool *);
static void   shape_of_boundary         (Tool *);
static void   process_kinks             (Tool *);
static void   initial_boundary          (Tool *);
static void   edge_map_from_boundary    (Tool *);
static void   orient_boundary           (Tool *);
static void   reset_boundary            (Tool *);
static int    localize_boundary         (Tool *);
static void   post_process_boundary     (Tool *);
static void   bezierify_boundary        (Tool *);

/*  edge map buffer utility functions  */
static TempBuf *  calculate_edge_map    (GImage *, int, int, int, int);
static void   construct_edge_map        (Tool *, TempBuf *);

/*  edge map blocks utility functions  */
static void   set_edge_map_blocks       (void *, int, int, int, int);
static void   allocate_edge_map_blocks  (int, int, int, int);
static void   free_edge_map_blocks      (void);

/*  gaussian & 1st derivative  */
static void   gaussian_deriv            (PixelRegion *, PixelRegion *, int, double);
static void   make_curve                (int *, int *, double, int);
static void   make_curve_d              (int *, int *, double, int);

/*  Catmull-Rom boundary conversion  */
static void   CR_convert                (Iscissors * , GDisplay *, int);
static void   CR_convert_points         (GdkPoint *, int);
247 248
static void   CR_convert_line           (GSList **, int, int, int, int);
static GSList * CR_insert_in_list       (GSList *, int);
Elliot Lee's avatar
Elliot Lee committed
249 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


/*******************************************************/
/*  Selection options dialog--for all selection tools  */
/*******************************************************/

static void
selection_toggle_update (GtkWidget *w,
			 gpointer   data)
{
  int *toggle_val;

  toggle_val = (int *) data;

  if (GTK_TOGGLE_BUTTON (w)->active)
    *toggle_val = TRUE;
  else
    *toggle_val = FALSE;
}

static void
selection_scale_update (GtkAdjustment *adjustment,
			double        *scale_val)
{
  *scale_val = adjustment->value;
}

276 277 278 279 280 281 282 283
static void   
selection_to_bezier(GtkWidget *w, gpointer none)
{
   Iscissors *iscissors;
   if(last_tool) {
	iscissors = (Iscissors *) last_tool->private;
	last_tool->state = INACTIVE;
	bezierify_boundary (last_tool);
284
	tools_select(BEZIER_SELECT);
285 286
    }
   return;
Adrian Likins's avatar
Adrian Likins committed
287
}
288

Elliot Lee's avatar
Elliot Lee committed
289 290 291 292 293 294 295 296 297 298 299 300 301
static IScissorsOptions *
iscissors_selection_options (void)
{
  IScissorsOptions *options;
  GtkWidget *vbox;
  GtkWidget *hbox;
  GtkWidget *label;
  GtkWidget *antialias_toggle;
  GtkWidget *feather_toggle;
  GtkWidget *feather_scale;
  GtkObject *feather_scale_data;
  GtkWidget *resolution_scale;
  GtkObject *resolution_scale_data;
302 303
  GtkWidget *elasticity_scale;
  GtkObject *elasticity_scale_data;
Elliot Lee's avatar
Elliot Lee committed
304 305 306 307 308 309 310 311 312 313 314
  GtkWidget *threshold_scale;
  GtkWidget *convert_button;
  GtkObject *threshold_scale_data;

  /*  the new options structure  */
  options = (IScissorsOptions *) g_malloc (sizeof (IScissorsOptions));
  options->antialias = 1;
  options->feather = 0;
  options->feather_radius = 10.0;
  options->resolution = 40.0;
  options->threshold = 15.0;
315
  
Elliot Lee's avatar
Elliot Lee committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 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 361 362 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
  /*  the main vbox  */
  vbox = gtk_vbox_new (FALSE, 1);

  /*  the main label  */
  label = gtk_label_new ("Intelligent Scissors Options");

  gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  /*  the antialias toggle button  */
  antialias_toggle = gtk_check_button_new_with_label ("Antialiasing");
  gtk_box_pack_start (GTK_BOX (vbox), antialias_toggle, FALSE, FALSE, 0);
  gtk_signal_connect (GTK_OBJECT (antialias_toggle), "toggled",
		      (GtkSignalFunc) selection_toggle_update,
		      &options->antialias);
  gtk_widget_show (antialias_toggle);

  /*  the feather toggle button  */
  feather_toggle = gtk_check_button_new_with_label ("Feather");
  gtk_box_pack_start (GTK_BOX (vbox), feather_toggle, FALSE, FALSE, 0);
  gtk_signal_connect (GTK_OBJECT (feather_toggle), "toggled",
		      (GtkSignalFunc) selection_toggle_update,
		      &options->feather);
  gtk_widget_show (feather_toggle);

  /*  the feather radius scale  */
  hbox = gtk_hbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);

  label = gtk_label_new ("Feather Radius");
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  feather_scale_data = gtk_adjustment_new (10.0, 0.0, 100.0, 1.0, 1.0, 0.0);
  feather_scale = gtk_hscale_new (GTK_ADJUSTMENT (feather_scale_data));
  gtk_box_pack_start (GTK_BOX (hbox), feather_scale, TRUE, TRUE, 0);
  gtk_scale_set_value_pos (GTK_SCALE (feather_scale), GTK_POS_TOP);
  gtk_range_set_update_policy (GTK_RANGE (feather_scale), GTK_UPDATE_DELAYED);
  gtk_signal_connect (GTK_OBJECT (feather_scale_data), "value_changed",
		      (GtkSignalFunc) selection_scale_update,
		      &options->feather_radius);
  gtk_widget_show (feather_scale);
  gtk_widget_show (hbox);

  /*  the resolution scale  */
  hbox = gtk_hbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);

  label = gtk_label_new ("Curve Resolution");
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  resolution_scale_data = gtk_adjustment_new (4.0, 1.0, 200.0, 1.0, 1.0, 0.0);
  resolution_scale = gtk_hscale_new (GTK_ADJUSTMENT (resolution_scale_data));
  gtk_box_pack_start (GTK_BOX (hbox), resolution_scale, TRUE, TRUE, 0);
  gtk_scale_set_value_pos (GTK_SCALE (resolution_scale), GTK_POS_TOP);
  gtk_range_set_update_policy (GTK_RANGE (resolution_scale), GTK_UPDATE_DELAYED);
  gtk_signal_connect (GTK_OBJECT (resolution_scale_data), "value_changed",
		      (GtkSignalFunc) selection_scale_update,
		      &options->resolution);
  gtk_widget_show (resolution_scale);
  gtk_widget_show (hbox);

  /*  the threshold scale  */
  hbox = gtk_hbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);

  label = gtk_label_new ("Edge Detect Thresh.");
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  threshold_scale_data = gtk_adjustment_new (15.0, 1.0, 255.0, 1.0, 1.0, 0.0);
  threshold_scale = gtk_hscale_new (GTK_ADJUSTMENT (threshold_scale_data));
  gtk_box_pack_start (GTK_BOX (hbox), threshold_scale, TRUE, TRUE, 0);
  gtk_scale_set_value_pos (GTK_SCALE (threshold_scale), GTK_POS_TOP);
  gtk_range_set_update_policy (GTK_RANGE (threshold_scale), GTK_UPDATE_DELAYED);
  gtk_signal_connect (GTK_OBJECT (threshold_scale_data), "value_changed",
		      (GtkSignalFunc) selection_scale_update,
		      &options->threshold);
  gtk_widget_show (threshold_scale);
  gtk_widget_show (hbox);

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
  /*the elasticity scale  */
  hbox = gtk_hbox_new (FALSE, 1);
  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);

  label = gtk_label_new ("Elasticity.");
  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  elasticity_scale_data = gtk_adjustment_new (.01, 0.0, 1.0, 0.05, 0.05, 0.0);
  elasticity_scale = gtk_hscale_new (GTK_ADJUSTMENT (elasticity_scale_data));
  gtk_box_pack_start (GTK_BOX (hbox), elasticity_scale, TRUE, TRUE, 0);
  gtk_scale_set_value_pos (GTK_SCALE (elasticity_scale), GTK_POS_TOP);
  gtk_range_set_update_policy (GTK_RANGE (elasticity_scale), GTK_UPDATE_DELAYED);
  gtk_signal_connect (GTK_OBJECT (elasticity_scale_data), "value_changed",
		      (GtkSignalFunc) selection_scale_update,
		      &elasticity);
  gtk_widget_show (elasticity_scale);
  gtk_widget_show (hbox);


Elliot Lee's avatar
Elliot Lee committed
418 419 420
  /*  the convert to bezier button  */
  convert_button = gtk_button_new_with_label ("Convert to Bezier Curve");
  gtk_box_pack_start (GTK_BOX (vbox), convert_button, TRUE, TRUE, 0);
421 422 423
  gtk_signal_connect(GTK_OBJECT (convert_button) , "clicked",
			(GtkSignalFunc) selection_to_bezier,
			NULL);
Elliot Lee's avatar
Elliot Lee committed
424 425
  gtk_widget_show (convert_button);

426

Elliot Lee's avatar
Elliot Lee committed
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 453 454 455 456 457 458 459 460
  /*  Register this selection options widget with the main tools options dialog  */
  tools_register_options (ISCISSORS, vbox);

  return options;
}


Tool *
tools_new_iscissors ()
{
  Tool * tool;
  Iscissors * private;

  if (!iscissors_options)
    iscissors_options = iscissors_selection_options ();

  tool = (Tool *) g_malloc (sizeof (Tool));
  private = (Iscissors *) g_malloc (sizeof (Iscissors));

  private->core = draw_core_new (iscissors_draw);
  private->edge_buf = NULL;
  private->kinks = NULL;
  private->mask = NULL;

  tool->type = ISCISSORS;
  tool->state = INACTIVE;
  tool->scroll_lock = 0;  /*  Allow scrolling  */
  tool->private = (void *) private;
  tool->button_press_func = iscissors_button_press;
  tool->button_release_func = iscissors_button_release;
  tool->motion_func = iscissors_motion;
  tool->arrow_keys_func = standard_arrow_keys_func;
  tool->cursor_update_func = rect_select_cursor_update;
  tool->control_func = iscissors_control;
461 462 463
  
  last_tool = tool;
  
Elliot Lee's avatar
Elliot Lee committed
464
  iscissors_reset (private);
465
  
Elliot Lee's avatar
Elliot Lee committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
  return tool;
}

void
tools_free_iscissors (Tool *tool)
{
  Iscissors * iscissors;

  iscissors = (Iscissors *) tool->private;

  if (tool->state == ACTIVE)
    draw_core_stop (iscissors->core, tool);
  draw_core_free (iscissors->core);

  iscissors_reset (iscissors);

  g_free (iscissors);
}


/*  Local functions  */

static void
iscissors_button_press (Tool           *tool,
			GdkEventButton *bevent,
			gpointer        gdisp_ptr)
{
  GDisplay *gdisp;
494
  GimpDrawable *drawable;
Elliot Lee's avatar
Elliot Lee committed
495 496
  Iscissors *iscissors;
  int replace, op;
497
  int x, y;
Elliot Lee's avatar
Elliot Lee committed
498

499
  last_tool = tool;
Elliot Lee's avatar
Elliot Lee committed
500 501
  gdisp = (GDisplay *) gdisp_ptr;
  iscissors = (Iscissors *) tool->private;
502
  drawable = gimage_active_drawable (gdisp->gimage);
Elliot Lee's avatar
Elliot Lee committed
503

504 505 506
  /*message_box ("Intelligent Scissors is currently not enabled\nfor use with
  the tile-based GIMP\non anything but yosh's computer.",   NULL, NULL);*/
  /*  return;*/
507
  
Elliot Lee's avatar
Elliot Lee committed
508
  gdisplay_untransform_coords (gdisp, bevent->x, bevent->y,
509
			       &iscissors->x, &iscissors->y, FALSE, TRUE); 
Elliot Lee's avatar
Elliot Lee committed
510 511

  /*  If the tool was being used in another image...reset it  */
512

Elliot Lee's avatar
Elliot Lee committed
513 514 515 516 517 518 519 520 521 522
  if (tool->state == ACTIVE && gdisp_ptr != tool->gdisp_ptr)
    {
      draw_core_stop (iscissors->core, tool);
      iscissors_reset (iscissors);
    }

  switch (iscissors->state)
    {
    case FREE_SELECT_MODE:
      tool->state = ACTIVE;
523
      last_tool = NULL;
Elliot Lee's avatar
Elliot Lee committed
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
      tool->gdisp_ptr = gdisp_ptr;

      gdk_pointer_grab (gdisp->canvas->window, FALSE,
			(GDK_POINTER_MOTION_HINT_MASK |
			 GDK_BUTTON1_MOTION_MASK |
			 GDK_BUTTON_RELEASE_MASK),
			NULL, NULL, bevent->time);

      if (bevent->state & GDK_MOD1_MASK)
	{
	  init_edit_selection (tool, gdisp_ptr, bevent, MaskTranslate);
	  return;
	}
      else if (!(bevent->state & GDK_SHIFT_MASK) && !(bevent->state & GDK_CONTROL_MASK))
	if (! (layer_is_floating_sel (gimage_get_active_layer (gdisp->gimage))) &&
	    gdisplay_mask_value (gdisp, bevent->x, bevent->y) > HALF_WAY)
	  {
	    /*  Have to blank out the edge blocks since they might change  */
	    iscissors_reset (iscissors);

	    init_edit_selection (tool, gdisp_ptr, bevent, MaskToLayerTranslate);
	    return;
	  }

      /*  If the edge map blocks haven't been allocated, do so now  */
549
      if (!edge_map_blocks)
Elliot Lee's avatar
Elliot Lee committed
550
	allocate_edge_map_blocks (BLOCK_WIDTH, BLOCK_HEIGHT,
551 552
				  drawable_width(drawable),
				  drawable_height(drawable));
553
				  
Elliot Lee's avatar
Elliot Lee committed
554
      iscissors->num_segs = 0;
555 556
	x = bevent->x;
	y = bevent->y;
557 558
	
      add_segment (&(iscissors->num_segs), x, y);
Elliot Lee's avatar
Elliot Lee committed
559 560 561 562 563 564

      draw_core_start (iscissors->core,
		       gdisp->canvas->window,
		       tool);
      break;
    case BOUNDARY_MODE:
565
      if (/*channel_value (iscissors->mask, iscissors->x, iscissors->y)*/ TRUE)
Elliot Lee's avatar
Elliot Lee committed
566 567
	{
	  replace = 0;
568 569

	  if ((bevent->state & GDK_SHIFT_MASK) && !(bevent->state & GDK_CONTROL_MASK))
Elliot Lee's avatar
Elliot Lee committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
	    op = ADD;
	  else if ((bevent->state & GDK_CONTROL_MASK) && !(bevent->state & GDK_SHIFT_MASK))
	    op = SUB;
	  else if ((bevent->state & GDK_CONTROL_MASK) && (bevent->state & GDK_SHIFT_MASK))
	    op = INTERSECT;
	  else
	    {
	      op = ADD;
	      replace = 1;
	    }

	  tool->state = INACTIVE;

	  /*  If we're antialiased, then recompute the
	   *  mask...
	   */
	  if (iscissors_options->antialias)
	    CR_convert (iscissors, tool->gdisp_ptr, YES);

	  draw_core_stop (iscissors->core, tool);

	  if (replace)
	    gimage_mask_clear (gdisp->gimage);
	  else
	    gimage_mask_undo (gdisp->gimage);

	  if (iscissors_options->feather)
	    channel_feather (iscissors->mask,
			     gimage_get_mask (gdisp->gimage),
			     iscissors_options->feather_radius, op, 0, 0);
	  else
	    channel_combine_mask (gimage_get_mask (gdisp->gimage),
				  iscissors->mask, op, 0, 0);

	  iscissors_reset (iscissors);

	  gdisplays_flush ();
	}

      break;
    }
}

static void
iscissors_button_release (Tool           *tool,
			  GdkEventButton *bevent,
			  gpointer        gdisp_ptr)
{
  Iscissors *iscissors;
  GDisplay *gdisp;

  gdisp = (GDisplay *) gdisp_ptr;
  iscissors = (Iscissors *) tool->private;

624
  /*return;*/
625 626 627
  
  last_tool = tool;
  
Elliot Lee's avatar
Elliot Lee committed
628 629 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 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
  gdk_pointer_ungrab (bevent->time);
  gdk_flush ();

  draw_core_stop (iscissors->core, tool);

  /*  First take care of the case where the user "cancels" the action  */
  if (! (bevent->state & GDK_BUTTON3_MASK))
    {
      /*  Progress to the next stage of intelligent selection  */
      switch (iscissors->state)
	{
	case FREE_SELECT_MODE:
	  /*  Add one additional segment  */
	  add_segment (&(iscissors->num_segs), segs[0].x1, segs[0].y1);

	  if (iscissors->num_segs >= 3)
	    {
	      /*  Find the boundary  */
	      find_boundary (tool);

	      /*  Set the new state  */
	      iscissors->state = BOUNDARY_MODE;

	      /*  Start the draw core up again  */
	      draw_core_resume (iscissors->core, tool);

	      return;
	    }
	  break;
	case BOUNDARY_MODE:
	  iscissors->state = FREE_SELECT_MODE;
	  break;
	}
    }

  tool->state = INACTIVE;
}

static void
iscissors_motion (Tool           *tool,
		  GdkEventMotion *mevent,
		  gpointer        gdisp_ptr)
{
  Iscissors *iscissors;
  GDisplay *gdisp;
673 674
  int x, y;
  
Elliot Lee's avatar
Elliot Lee committed
675 676 677 678 679 680
  if (tool->state != ACTIVE)
    return;

  gdisp = (GDisplay *) gdisp_ptr;
  iscissors = (Iscissors *) tool->private;

681
  
Elliot Lee's avatar
Elliot Lee committed
682 683 684
  switch (iscissors->state)
    {
    case FREE_SELECT_MODE:
685 686 687
    	x = mevent->x;
	y = mevent->y;
      if (add_segment (&(iscissors->num_segs), x, y))
688
	
Elliot Lee's avatar
Elliot Lee committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 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
	gdk_draw_segments (iscissors->core->win, iscissors->core->gc,
			   segs + (iscissors->num_segs - 1), 1);
      break;
    case BOUNDARY_MODE:
      break;
    }
}

static void
iscissors_draw (Tool *tool)
{
  GDisplay *gdisp;
  Iscissors *iscissors;
  int indices[4];
  int i;

  gdisp = (GDisplay *) tool->gdisp_ptr;
  iscissors = (Iscissors *) tool->private;

  switch (iscissors->state)
    {
    case FREE_SELECT_MODE:
      gdk_draw_segments (iscissors->core->win, iscissors->core->gc,
			 segs, iscissors->num_segs);
      break;
    case BOUNDARY_MODE:
      for (i = 0; i < iscissors->num_pts; i ++)
	{
	  indices[0] = (i < 3) ? (iscissors->num_pts + i - 3) : (i - 3);
	  indices[1] = (i < 2) ? (iscissors->num_pts + i - 2) : (i - 2);
	  indices[2] = (i < 1) ? (iscissors->num_pts + i - 1) : (i - 1);
	  indices[3] = i;
	  iscissors_draw_CR (gdisp, iscissors, pts, indices, SCREEN_COORDS);
	}
      break;
    }
}

static void
iscissors_draw_CR (GDisplay  *gdisp,
		   Iscissors *iscissors,
		   Point     *pts,
		   int       *indices,
		   int        draw_type)
{
#define ROUND(x)  ((int) ((x) + 0.5))

  static GdkPoint gdk_points[256];
  static int npoints = 256;

  CRMatrix geometry;
  CRMatrix tmp1, tmp2;
  CRMatrix deltas;
  double x, dx, dx2, dx3;
  double y, dy, dy2, dy3;
  double d, d2, d3;
  int lastx, lasty;
  int newx, newy;
747
  int tx, ty;
Elliot Lee's avatar
Elliot Lee committed
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
  int index;
  int i;

  /* construct the geometry matrix from the segment */
  /* assumes that a valid segment containing 4 points is passed in */

  for (i = 0; i < 4; i++)
    {
      switch (draw_type)
	{
	case IMAGE_COORDS:
	  geometry[i][0] = pts[indices[i]].dx;
	  geometry[i][1] = pts[indices[i]].dy;
	  break;
	case AA_IMAGE_COORDS:
	  geometry[i][0] = pts[indices[i]].dx * SUPERSAMPLE;
	  geometry[i][1] = pts[indices[i]].dy * SUPERSAMPLE;
	  break;
	case SCREEN_COORDS:
Manish Singh's avatar
Manish Singh committed
767 768 769
	  geometry[i][0] = x;
	  geometry[i][1] = y;
	  /*g_print("%f %f\n", x, y);*/
Elliot Lee's avatar
Elliot Lee committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
	  break;
	}
      geometry[i][2] = 0;
      geometry[i][3] = 0;
    }

  /* subdivide the curve n times */
  /* n can be adjusted to give a finer or coarser curve */

  d = 1.0 / SUBDIVIDE;
  d2 = d * d;
  d3 = d * d * d;

  /* construct a temporary matrix for determining the forward differencing deltas */

  tmp2[0][0] = 0;     tmp2[0][1] = 0;     tmp2[0][2] = 0;    tmp2[0][3] = 1;
  tmp2[1][0] = d3;    tmp2[1][1] = d2;    tmp2[1][2] = d;    tmp2[1][3] = 0;
  tmp2[2][0] = 6*d3;  tmp2[2][1] = 2*d2;  tmp2[2][2] = 0;    tmp2[2][3] = 0;
  tmp2[3][0] = 6*d3;  tmp2[3][1] = 0;     tmp2[3][2] = 0;    tmp2[3][3] = 0;

  /* compose the basis and geometry matrices */
  CR_compose (CR_basis, geometry, tmp1);

  /* compose the above results to get the deltas matrix */
  CR_compose (tmp2, tmp1, deltas);

  /* extract the x deltas */
  x = deltas[0][0];
  dx = deltas[1][0];
  dx2 = deltas[2][0];
  dx3 = deltas[3][0];

  /* extract the y deltas */
  y = deltas[0][1];
  dy = deltas[1][1];
  dy2 = deltas[2][1];
  dy3 = deltas[3][1];

  lastx = x;
  lasty = y;

  gdk_points[0].x = lastx;
  gdk_points[0].y = lasty;
  index = 1;

  /* loop over the curve */
  for (i = 0; i < SUBDIVIDE; i++)
    {
      /* increment the x values */
      x += dx;
      dx += dx2;
      dx2 += dx3;

      /* increment the y values */
      y += dy;
      dy += dy2;
      dy2 += dy3;

828 829
      newx = ROUND(x);
      newy = ROUND(y);
Elliot Lee's avatar
Elliot Lee committed
830 831 832 833 834

      /* if this point is different than the last one...then draw it */
      if ((lastx != newx) || (lasty != newy))
	{
	  /* add the point to the point buffer */
835 836 837 838 839
		      	  
	  gdisplay_transform_coords (gdisp, newx, newy, &tx, &ty,1 );
	  gdk_points[index].x = tx;
	  gdk_points[index].y = ty;

Elliot Lee's avatar
Elliot Lee committed
840

841
	  index++;
Elliot Lee's avatar
Elliot Lee committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
	  /* if the point buffer is full put it to the screen and zero it out */
	  if (index >= npoints)
	    {
	      switch (draw_type)
		{
		case IMAGE_COORDS: case AA_IMAGE_COORDS:
		  CR_convert_points (gdk_points, index);
		  break;
		case SCREEN_COORDS:
		  gdk_draw_points (iscissors->core->win, iscissors->core->gc,
				   gdk_points, index);
		  break;
		}
	      index = 0;
	    }
	}

      lastx = newx;
      lasty = newy;
    }

  /* if there are points in the buffer, then put them on the screen */
  if (index)
    switch (draw_type)
      {
      case IMAGE_COORDS: case AA_IMAGE_COORDS:
	CR_convert_points (gdk_points, index);
	break;
      case SCREEN_COORDS:
	gdk_draw_points (iscissors->core->win, iscissors->core->gc,
			 gdk_points, index);
	break;
      }
}

static void
iscissors_control (Tool     *tool,
		   int       action,
		   gpointer  gdisp_ptr)
{
  Iscissors * iscissors;

  iscissors = (Iscissors *) tool->private;

  switch (action)
    {
    case PAUSE :
      draw_core_pause (iscissors->core, tool);
      break;
    case RESUME :
      draw_core_resume (iscissors->core, tool);
      break;
    case HALT :
      draw_core_stop (iscissors->core, tool);
      iscissors_reset (iscissors);
      break;
    }
}

static void
iscissors_reset (Iscissors *iscissors)
{
  /*  Reset the edge map blocks structure  */
  free_edge_map_blocks ();

  /*  free edge buffer  */
  if (iscissors->edge_buf)
    temp_buf_free (iscissors->edge_buf);

  /*  free mask  */
  if (iscissors->mask)
    channel_delete (iscissors->mask);

  /*  Free kinks  */
  if (iscissors->kinks)
    g_free (iscissors->kinks);

  iscissors->state = FREE_SELECT_MODE;
  iscissors->mask = NULL;
  iscissors->edge_buf = NULL;
  iscissors->kinks = NULL;
  iscissors->num_segs = 0;
  iscissors->num_pts = 0;
  iscissors->num_kinks = 0;
}

static int
add_segment (int *num_segs,
	     int  x,
	     int  y)
{
  static int first = 1;

  if (*num_segs >= max_segs)
    {
      max_segs += DEFAULT_MAX_INC;

      segs = (GdkSegment *) g_realloc ((void *) segs, sizeof (GdkSegment) * max_segs);

      if (!segs)
	fatal_error ("Unable to reallocate segment array in iscissors.");
    }

  if (*num_segs)
    {
      segs[*num_segs].x1 = segs[*num_segs - 1].x2;
      segs[*num_segs].y1 = segs[*num_segs - 1].y2;
    }
  else if (first)
    {
      segs[0].x1 = x;
      segs[0].y1 = y;
    }

  segs[*num_segs].x2 = x;
  segs[*num_segs].y2 = y;

  if (! *num_segs && first)
    first = 0;
  else
    {
      (*num_segs)++;
      first = 1;
    }

  return 1;
}

970

Elliot Lee's avatar
Elliot Lee committed
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
static int
add_point (int    *num_pts,
	   int     kink,
	   int     x,
	   int     y,
	   double *normal)
{
  if (*num_pts >= max_pts)
    {
      max_pts += DEFAULT_MAX_INC;

      pts = (Point *) g_realloc ((void *) pts, sizeof (Point) * max_pts);

      if (!pts)
	fatal_error ("Unable to reallocate points array in iscissors.");
    }

  pts[*num_pts].x = x;
  pts[*num_pts].y = y;
  pts[*num_pts].kink = kink;
  pts[*num_pts].normal[0] = normal[0];
  pts[*num_pts].normal[1] = normal[1];

  (*num_pts)++;

  return 1;
}

static void
CR_compose (CRMatrix a,
	    CRMatrix b,
	    CRMatrix ab)
{
  int i, j;

  for (i = 0; i < 4; i++)
    {
      for (j = 0; j < 4; j++)
        {
          ab[i][j] = (a[i][0] * b[0][j] +
                      a[i][1] * b[1][j] +
                      a[i][2] * b[2][j] +
                      a[i][3] * b[3][j]);
        }
    }
}

static void
normalize (double *vec)
{
  double length;

  length = sqrt (SQR (vec[0]) + SQR (vec[1]));
  if (length)
    {
      vec[0] /= length;
      vec[1] /= length;
    }
}

static double
dotprod (double *vec1,
	 double *vec2)
{
  double val;

  val = vec1[0] * vec2[0] + vec1[1] * vec2[1];

  return val;
}

static Kink *
get_kink (Kink *kinks,
	  int   index,
	  int   num_kinks)
{
  if (index >= 0 && index < num_kinks)
    return kinks + index;
  else if (index < 0)
    {
      while (index < 0)
	index += num_kinks;
      return kinks + index;
    }
  else
    {
      while (index >= num_kinks)
	index -= num_kinks;
      return kinks + index;
    }

1062
  /* I don't think it ever gets to this point -- Rockwalrus */
Elliot Lee's avatar
Elliot Lee committed
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
  return NULL;
}

static int
find_next_kink (Kink *kinks,
		int   num_kinks,
		int   this)
{
  if (this >= num_kinks)
    return 0;

  do {
    this++;
  } while (! kinks[this].is_a_kink);

  return this;
}

static double
find_distance (Kink *kinks,
	       int   this,
	       int   next)
{
  double dist = 0.0;
  double dx, dy;

  while (this != next)
    {
      dx = kinks[this].x - kinks[this + 1].x;
      dy = kinks[this].y - kinks[this + 1].y;

      dist += sqrt (SQR (dx) + SQR (dy));

      this ++;
    }

  return dist;
}

static int
go_distance (Kink   *kinks,
	     int     this,
	     double  dist,
	     double *x,
	     double *y)
{
  double dx, dy;
  double length = 0.0;
  double t = 2.0;

  dx = dy = 0.0;

  if (dist == 0.0)
    {
      *x = kinks[this].x;
      *y = kinks[this].y;
      return 1;
    }

  while (dist > 0.0)
    {
      dx = kinks[this + 1].x - kinks[this].x;
      dy = kinks[this + 1].y - kinks[this].y;
      length = sqrt (SQR (dx) + SQR (dy));
      dist -= length;

      if (dist > 0.0)
	this++;
    }

  t = (length + dist) / length;
  *x = kinks[this].x + t * dx;
  *y = kinks[this].y + t * dy;

  return this;
}

static int
travel_length (Kink *kinks,
	       int   num_kinks,
	       int   start,
	       int   dir,
	       int   dist)
{
  double dx, dy;
  Kink * k1, * k2;
  double distance = dist;
  int length = 0;

  while (distance > 0)
    {
      k1 = get_kink (kinks, start, num_kinks);
      k2 = get_kink (kinks, start+dir, num_kinks);
      dx = k2->x - k1->x;
      dy = k2->y - k1->y;
      distance -= sqrt (SQR (dx) + SQR (dy));

      start += dir;
      length += dir;
    }

  /*  backup one step and return value  */
  return length;
}

static int
find_edge_xy (TempBuf *edge_buf,
	      int      dir,
	      double   x,
	      double   y,
	      double  *edge)
{
  double dx, dy;
  int ix, iy;
  int xx, yy;
  int rowstride, bytes;
  int d11, d12, d21, d22;
  unsigned char * data;
  int b;

  bytes = edge_buf->bytes;
  rowstride = bytes * edge_buf->width;

  x -= edge_buf->x;
  y -= edge_buf->y;

  ix = (int) (x + 2) - 2;
  iy = (int) (y + 2) - 2;

  /*  If we're scouting out of bounds, return 0  */
  if (ix < 0 || ix >= edge_buf->width ||
      iy < 0 || iy >= edge_buf->height)
    {
      edge[0] = EDGE_STRENGTH;
      return 1;
    }

  if (dir > 0)
    {
      dx = x - ix;
      dy = y - iy;
    }
  else
    {
      dx = 1 - (x - ix);
      dy = 1 - (y - iy);
    }

  data = temp_buf_data (edge_buf) + iy * rowstride + ix * bytes;

  for (b = 0; b < bytes; b++)
    {
      if (dir > 0)
	{
	  xx = ((ix + 1) >= edge_buf->width) ? 0 : bytes;
	  yy = ((iy + 1) >= edge_buf->height) ? 0 : rowstride;
	}
      else
	{
	  xx = ((ix - 1) < 0) ? 0 : -bytes;
	  yy = ((iy - 1) < 0) ? 0 : -rowstride;
	}

      d11 = (data[0] > threshold) ? data[0] : 0;
      d12 = (data[xx] > threshold) ? data[xx] : 0;
      d21 = (data[yy] > threshold) ? data[yy] : 0;
      d22 = (data[xx + yy] > threshold) ? data[xx + yy] : 0;

      edge[b] = BILINEAR (d11, d12, d21, d22, dx, dy);
      data++;
    }

  if (edge[0] > 0.0)
    return 1;
  else
    return 0;
}

static void
find_boundary (Tool *tool)
{
1244
  
Elliot Lee's avatar
Elliot Lee committed
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
  /*  Find directional changes  */
  shape_of_boundary (tool);

  /*  Process the kinks  */
  process_kinks (tool);

  /*  Determine the initial boundary  */
  initial_boundary (tool);

  /*  Get the edge map from the boundary extents  */
  edge_map_from_boundary (tool);

  /*  Orient the boundary based on edge detection  */
  orient_boundary (tool);

  /*  Setup the points array for localization  */
  reset_boundary (tool);

  /*  Localize the boundary based on edge detection
   *  and inter-segment elasticity
   */
  while (localize_boundary (tool)) ;

  /*  Post process the points array to fit non-edge-seeking
   *  boundary points into the scheme of things
   */
  post_process_boundary (tool);

  /*  convert the boundary into a mask  */
  CR_convert ((Iscissors *) tool->private,
	      (GDisplay *) tool->gdisp_ptr, NO);
}

static void
shape_of_boundary (Tool *tool)
{
  Iscissors * iscissors;
  GDisplay * gdisp;
  Kink * kinks, * k;
  double vec1[2], vec2[2], vec[2];
  double std_dev;
  double weight;
  int left, right;
  int i, j;
1289
  int x, y;
Elliot Lee's avatar
Elliot Lee committed
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307

  /*  This function determines the kinkiness at each point in the
   *  original free-hand curve by finding the dotproduct between
   *  the two vectors formed at each point from that point to its
   *  immediate neighbors.  A smoothing function is applied to
   *  determine the vectors to ameliorate the otherwise excessive
   *  jitter associated with original selection.
   */

  gdisp = (GDisplay *) tool->gdisp_ptr;
  iscissors = (Iscissors *) tool->private;

  iscissors->num_kinks = iscissors->num_segs;
  if (iscissors->kinks)
    g_free (iscissors->kinks);
  kinks = iscissors->kinks = (Kink *) g_malloc (sizeof (Kink) *
					       (iscissors->num_kinks + 1));

1308
  for (i = 0,j=0; i < iscissors->num_kinks; i++)
Elliot Lee's avatar
Elliot Lee committed
1309
    {
1310 1311 1312 1313 1314
	/* untransform coords */
     gdisplay_untransform_coords (gdisp, segs[i].x1, segs[i].y1,
		       &kinks[j].x, &kinks[j].y, FALSE, TRUE);
	    
/*	   
1315 1316
      kinks[j].x = segs[i].x1;
      kinks[j].y = segs[i].y1;
1317
*/
1318 1319 1320 1321 1322
      
	if(j) {
	   if((kinks[i].x != kinks[j-1].x) || (kinks[j].y != kinks[j-1].y))
		++j;
	} else ++j;
Elliot Lee's avatar
Elliot Lee committed
1323 1324
    }

1325 1326
  iscissors->num_kinks = j;

Elliot Lee's avatar
Elliot Lee committed
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
  for (i = 0; i < iscissors->num_kinks; i++)
    {
      left = travel_length (kinks, iscissors->num_kinks, i, -1, resolution);
      right = travel_length (kinks, iscissors->num_kinks, i, 1, resolution);

      std_dev = sqrt (-(SQR (left)) / (2 * log (EPSILON)));
      if (fabs (std_dev) < EPSILON) std_dev = 1.0;

      vec1[0] = 0.0;
      vec1[1] = 0.0;
      for (j = left; j < 0; j++)
	{
	  k = get_kink (kinks, i+j, iscissors->num_kinks);
	  vec[0] = k->x - kinks[i].x;
	  vec[1] = k->y - kinks[i].y;
	  normalize (vec);

	  weight = exp (-SQR(j+1) / (2 * SQR (std_dev)));
	  vec1[0] += weight * vec[0];
	  vec1[1] += weight * vec[1];
	}
      normalize (vec1);

      std_dev = sqrt (-(SQR (right)) / (2 * log (EPSILON)));
      if (fabs (std_dev) < EPSILON) std_dev = 1.0;

      vec2[0] = 0.0;
      vec2[1] = 0.0;
      for (j = 1; j <= right; j++)
	{
	  k = get_kink (kinks, i+j, iscissors->num_kinks);
	  vec[0] = k->x - kinks[i].x;
	  vec[1] = k->y - kinks[i].y;
	  normalize (vec);

	  weight = exp (-SQR(j-1) / (2 * SQR (std_dev)));
	  vec2[0] += weight * vec[0];
	  vec2[1] += weight * vec[1];
	}
      normalize (vec2);

      /*  determine the kinkiness based on the two vectors  */
      kinks[i].kinkiness = (M_PI - acos (dotprod (vec1, vec2)))/ M_PI;

      kinks[i].normal[0] = (vec1[0] + vec2[0]) / 2.0;
      kinks[i].normal[1] = (vec1[1] + vec2[1]) / 2.0;

      /*  if the average vector is zero length...  */
      if (kinks[i].normal[0] < EPSILON && kinks[i].normal[1] < EPSILON)
	{
	  /*  normal = 90 degree rotation of vec1  */
	  kinks[i].normal[0] = -vec1[1];
	  kinks[i].normal[1] = vec1[0];
	}
      normalize (kinks[i].normal);
    }
}

static void
process_kinks (Tool *tool)
{
  Iscissors * iscissors;
  GDisplay * gdisp;
  Kink * kinks, * k_left, * k_right;
1391
  int x, y;
Elliot Lee's avatar
Elliot Lee committed
1392
  int i;
1393 1394
  GimpDrawable *drawable;

Elliot Lee's avatar
Elliot Lee committed
1395 1396

  gdisp = (GDisplay *) tool->gdisp_ptr;
1397
  drawable = gimage_active_drawable (gdisp->gimage);
Elliot Lee's avatar
Elliot Lee committed
1398 1399 1400 1401 1402
  iscissors = (Iscissors *) tool->private;
  kinks = iscissors->kinks;

  for (i = 0; i < iscissors->num_kinks; i++)
    {
1403

1404 1405 1406
      /*FIXME*/
      kinks[i].x = BOUNDS (kinks[i].x, 0, (drawable_width(drawable) - 1));
      kinks[i].y = BOUNDS (kinks[i].y, 0, (drawable_height(drawable) - 1));
Elliot Lee's avatar
Elliot Lee committed
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484

      /*  get local maximums  */
      k_left = get_kink (kinks, i-1, iscissors->num_kinks);
      k_right = get_kink (kinks, i+1, iscissors->num_kinks);

      if ((kinks[i].kinkiness > k_left->kinkiness) &&
	  (kinks[i].kinkiness >= k_right->kinkiness) &&
	  (kinks[i].kinkiness > kink_thres))
	kinks[i].is_a_kink = 1;
      else
	kinks[i].is_a_kink = 0;
    }
}

static void
initial_boundary (Tool *tool)
{
  Iscissors * iscissors;
  GDisplay * gdisp;
  Kink * kinks;
  double x, y;
  double dist;
  double res;
  int i, n, this, next, k;
  int num_pts = 0;

  gdisp = (GDisplay *) tool->gdisp_ptr;
  iscissors = (Iscissors *) tool->private;
  kinks = iscissors->kinks;

  /*  for a connected boundary, set up the last kink as the same
   *  x & y coordinates as the first
   */
  kinks[iscissors->num_kinks].x = kinks[0].x;
  kinks[iscissors->num_kinks].y = kinks[0].y;
  kinks[iscissors->num_kinks].is_a_kink = 1;

  this = 0;
  while ((next = find_next_kink (kinks, iscissors->num_kinks, this)))
    {
      /*  Find the distance in pixels from the current to
       *  the next kink
       */
      dist = find_distance (kinks, this, next);

      if (dist > 0.0)
	{
	  /*  Find the number of segments that should be created
	   *  to fill the void
	   */
	  n = (int) (dist / resolution);
	  res = dist / (double) (n + 1);

	  add_point (&num_pts, 1, kinks[this].x, kinks[this].y, kinks[this].normal);

	  for (i = 1; i <= n; i++)
	    {
	      k = go_distance (kinks, this, res * i, &x, &y);

	      add_point (&num_pts, 0, (int) x, (int) y, kinks[k].normal);
	    }
	}

      this = next;
    }

  iscissors->num_pts = num_pts;
}

static void
edge_map_from_boundary (Tool *tool)
{
  Iscissors * iscissors;
  GDisplay * gdisp;
  unsigned char black[EDGE_WIDTH] = { 0 };
  int x, y, w, h;
  int x1, y1, x2, y2;
  int i;
1485
  GimpDrawable *drawable;
Elliot Lee's avatar
Elliot Lee committed
1486

1487
  
Elliot Lee's avatar
Elliot Lee committed
1488
  gdisp = (GDisplay *) tool->gdisp_ptr;
1489
  drawable = gimage_active_drawable (gdisp->gimage);
Elliot Lee's avatar
Elliot Lee committed
1490 1491 1492 1493
  iscissors = (Iscissors *) tool->private;

  x = y = w = h = x1 = y1 = x2 = y2 = 0;
  
1494 1495
  x1 = drawable_width(drawable);
  y1 = drawable_height(drawable);
Elliot Lee's avatar
Elliot Lee committed
1496 1497 1498 1499

  /*  Find the edge map extents  */
  for (i = 0; i < iscissors->num_pts; i++)
    {
1500
      x = BOUNDS (pts[i].x - LOCALIZE_RADIUS, 0,
1501
		  drawable_width(drawable));
Elliot Lee's avatar
Elliot Lee committed
1502
      y = BOUNDS (pts[i].y - LOCALIZE_RADIUS, 0,
1503
		  drawable_height(drawable));
Elliot Lee's avatar
Elliot Lee committed
1504
      w = BOUNDS (pts[i].x + LOCALIZE_RADIUS, 0,
1505
		  drawable_width(drawable));
Elliot Lee's avatar
Elliot Lee committed
1506
      h = BOUNDS (pts[i].y + LOCALIZE_RADIUS, 0,
1507
		  drawable_height(drawable));
1508
		  
Elliot Lee's avatar
Elliot Lee committed
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
      w -= x;
      h -= y;

      set_edge_map_blocks (gdisp->gimage, x, y, w, h);

      if (x < x1)
	x1 = x;
      if (y < y1)
	y1 = y;
      if (x + w > x2)
	x2 = x + w;
      if (y + h > y2)
	y2 = y + h;
    }

1524

Elliot Lee's avatar
Elliot Lee committed
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
  /*  construct the edge map  */
  iscissors->edge_buf = temp_buf_new ((x2 - x1), (y2 - y1),
				      EDGE_WIDTH, x1, y1, black);
  construct_edge_map (tool, iscissors->edge_buf);
}

static void
orient_boundary (Tool *tool)
{
  Iscissors * iscissors;
  GDisplay * gdisp;
  int e1, e2;
  double dx1, dy1, dx2, dy2;
  double edge1[EDGE_WIDTH], edge2[EDGE_WIDTH];
  double max;
  double angle;
1541
  int dir = 0;
Elliot Lee's avatar
Elliot Lee committed
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
  int i, j;
  int max_dir;
  int max_orient;
  int found;

  max_dir = 0;
  max_orient = 0;

  gdisp = (GDisplay *) tool->gdisp_ptr;
  iscissors = (Iscissors *) tool->private;

  for (i = 0; i < iscissors->num_pts; i++)
    {
      /*  Search for the closest edge  */
      j = 0;
      max = 0.0;
      found = 0;

      angle = atan2 (pts[i].normal[1], pts[i].normal[0]);
      dir = ((angle > -3 * M_PI_4) && (angle < M_PI_4)) ? 1 : -1;

      while (j < LOCALIZE_RADIUS && !found)
	{
	  dx1 = pts[i].x + pts[i].normal[0] * j;
	  dy1 = pts[i].y + pts[i].normal[1] * j;
	  e1 = find_edge_xy (iscissors->edge_buf, dir, dx1, dy1, edge1);

	  dx2 = pts[i].x - pts[i].normal[0] * j;
	  dy2 = pts[i].y - pts[i].normal[1] * j;
	  e2 = find_edge_xy (iscissors->edge_buf, -dir, dx2, dy2, edge2);

	  e1 = e2 = 0;
	  if (e1 && e2)
	    {
	      if (edge1[0] > edge2[0])
		pts[i].dir = dir;
	      else
		{
		  pts[i].normal[0] *= -1;
		  pts[i].normal[1] *= -1;
		  pts[i].dir =