1 #define __SP_DYNA_DRAW_CONTEXT_C__
3 /*
4 * Handwriting-like drawing mode
5 *
6 * Authors:
7 * Mitsuru Oka <oka326@parkcity.ne.jp>
8 * Lauris Kaplinski <lauris@kaplinski.com>
9 * bulia byak <buliabyak@users.sf.net>
10 * MenTaLguY <mental@rydia.net>
11 *
12 * The original dynadraw code:
13 * Paul Haeberli <paul@sgi.com>
14 *
15 * Copyright (C) 1998 The Free Software Foundation
16 * Copyright (C) 1999-2005 authors
17 * Copyright (C) 2001-2002 Ximian, Inc.
18 * Copyright (C) 2005-2007 bulia byak
19 * Copyright (C) 2006 MenTaLguY
20 *
21 * Released under GNU GPL, read the file 'COPYING' for more information
22 */
24 #define noDYNA_DRAW_VERBOSE
26 #include "config.h"
28 #include <gtk/gtk.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <glibmm/i18n.h>
32 #include <numeric>
34 #include "svg/svg.h"
35 #include "display/canvas-bpath.h"
36 #include "display/bezier-utils.h"
38 #include <glib/gmem.h>
39 #include "macros.h"
40 #include "document.h"
41 #include "selection.h"
42 #include "desktop.h"
43 #include "desktop-events.h"
44 #include "desktop-handles.h"
45 #include "desktop-affine.h"
46 #include "desktop-style.h"
47 #include "message-context.h"
48 #include "pixmaps/cursor-calligraphy.xpm"
49 #include "pixmaps/cursor-thin.xpm"
50 #include "pixmaps/cursor-thicken.xpm"
51 #include "libnr/n-art-bpath.h"
52 #include "libnr/nr-path.h"
53 #include "libnr/nr-matrix-ops.h"
54 #include "libnr/nr-scale-translate-ops.h"
55 #include "xml/repr.h"
56 #include "context-fns.h"
57 #include "sp-item.h"
58 #include "inkscape.h"
59 #include "color.h"
60 #include "splivarot.h"
61 #include "sp-item-group.h"
62 #include "sp-shape.h"
63 #include "sp-path.h"
64 #include "sp-text.h"
65 #include "display/canvas-bpath.h"
66 #include "display/canvas-arena.h"
67 #include "livarot/Shape.h"
68 #include "isnan.h"
70 #include "dyna-draw-context.h"
72 #define DDC_RED_RGBA 0xff0000ff
74 #define TOLERANCE_CALLIGRAPHIC 0.1
76 #define DYNA_EPSILON 0.5e-6
77 #define DYNA_EPSILON_START 0.5e-2
78 #define DYNA_VEL_START 1e-5
80 #define DYNA_MIN_WIDTH 1.0e-6
82 #define DRAG_MIN 0.0
83 #define DRAG_DEFAULT 1.0
84 #define DRAG_MAX 1.0
86 // FIXME: move it to some shared file to be reused by both calligraphy and dropper
87 #define C1 0.552
88 static NArtBpath const hatch_area_circle[] = {
89 { NR_MOVETO, 0, 0, 0, 0, -1, 0 },
90 { NR_CURVETO, -1, C1, -C1, 1, 0, 1 },
91 { NR_CURVETO, C1, 1, 1, C1, 1, 0 },
92 { NR_CURVETO, 1, -C1, C1, -1, 0, -1 },
93 { NR_CURVETO, -C1, -1, -1, -C1, -1, 0 },
94 { NR_END, 0, 0, 0, 0, 0, 0 }
95 };
96 #undef C1
99 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
100 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
101 static void sp_dyna_draw_context_dispose(GObject *object);
103 static void sp_dyna_draw_context_setup(SPEventContext *ec);
104 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
105 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
107 static void clear_current(SPDynaDrawContext *dc);
108 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
109 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
110 static void accumulate_calligraphic(SPDynaDrawContext *dc);
112 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
114 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
115 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
116 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
117 static void draw_temporary_box(SPDynaDrawContext *dc);
120 static SPEventContextClass *parent_class;
122 GtkType
123 sp_dyna_draw_context_get_type(void)
124 {
125 static GType type = 0;
126 if (!type) {
127 GTypeInfo info = {
128 sizeof(SPDynaDrawContextClass),
129 NULL, NULL,
130 (GClassInitFunc) sp_dyna_draw_context_class_init,
131 NULL, NULL,
132 sizeof(SPDynaDrawContext),
133 4,
134 (GInstanceInitFunc) sp_dyna_draw_context_init,
135 NULL, /* value_table */
136 };
137 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
138 }
139 return type;
140 }
142 static void
143 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
144 {
145 GObjectClass *object_class = (GObjectClass *) klass;
146 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
148 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
150 object_class->dispose = sp_dyna_draw_context_dispose;
152 event_context_class->setup = sp_dyna_draw_context_setup;
153 event_context_class->set = sp_dyna_draw_context_set;
154 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
155 }
157 static void
158 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
159 {
160 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
162 event_context->cursor_shape = cursor_calligraphy_xpm;
163 event_context->hot_x = 4;
164 event_context->hot_y = 4;
166 ddc->accumulated = NULL;
167 ddc->segments = NULL;
168 ddc->currentcurve = NULL;
169 ddc->currentshape = NULL;
170 ddc->npoints = 0;
171 ddc->cal1 = NULL;
172 ddc->cal2 = NULL;
173 ddc->repr = NULL;
175 /* DynaDraw values */
176 ddc->cur = NR::Point(0,0);
177 ddc->last = NR::Point(0,0);
178 ddc->vel = NR::Point(0,0);
179 ddc->vel_max = 0;
180 ddc->acc = NR::Point(0,0);
181 ddc->ang = NR::Point(0,0);
182 ddc->del = NR::Point(0,0);
184 /* attributes */
185 ddc->dragging = FALSE;
187 ddc->mass = 0.3;
188 ddc->drag = DRAG_DEFAULT;
189 ddc->angle = 30.0;
190 ddc->width = 0.2;
191 ddc->pressure = DDC_DEFAULT_PRESSURE;
193 ddc->vel_thin = 0.1;
194 ddc->flatness = 0.9;
195 ddc->cap_rounding = 0.0;
197 ddc->abs_width = false;
198 ddc->keep_selected = true;
200 ddc->hatch_spacing = 0;
201 ddc->hatch_spacing_step = 0;
202 new (&ddc->hatch_pointer_past) std::list<double>();
203 new (&ddc->hatch_nearest_past) std::list<double>();
204 ddc->hatch_last_nearest = NR::Point(0,0);
205 ddc->hatch_last_pointer = NR::Point(0,0);
206 ddc->hatch_vector_accumulated = NR::Point(0,0);
207 ddc->hatch_escaped = false;
208 ddc->hatch_area = NULL;
209 ddc->hatch_item = NULL;
210 ddc->hatch_livarot_path = NULL;
212 ddc->trace_bg = false;
214 ddc->is_dilating = false;
215 }
217 static void
218 sp_dyna_draw_context_dispose(GObject *object)
219 {
220 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
222 if (ddc->hatch_area) {
223 gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
224 ddc->hatch_area = NULL;
225 }
227 if (ddc->dilate_area) {
228 gtk_object_destroy(GTK_OBJECT(ddc->dilate_area));
229 ddc->dilate_area = NULL;
230 }
232 if (ddc->accumulated) {
233 ddc->accumulated = sp_curve_unref(ddc->accumulated);
234 }
236 while (ddc->segments) {
237 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
238 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
239 }
241 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
242 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
243 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
245 if (ddc->currentshape) {
246 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
247 ddc->currentshape = NULL;
248 }
250 if (ddc->_message_context) {
251 delete ddc->_message_context;
252 }
254 G_OBJECT_CLASS(parent_class)->dispose(object);
256 ddc->hatch_pointer_past.~list();
257 ddc->hatch_nearest_past.~list();
258 }
260 static void
261 sp_dyna_draw_context_setup(SPEventContext *ec)
262 {
263 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
265 if (((SPEventContextClass *) parent_class)->setup)
266 ((SPEventContextClass *) parent_class)->setup(ec);
268 ddc->accumulated = sp_curve_new_sized(32);
269 ddc->currentcurve = sp_curve_new_sized(4);
271 ddc->cal1 = sp_curve_new_sized(32);
272 ddc->cal2 = sp_curve_new_sized(32);
274 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
275 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
276 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
277 /* fixme: Cannot we cascade it to root more clearly? */
278 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
280 {
281 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
282 ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
283 sp_curve_unref(c);
284 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
285 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
286 sp_canvas_item_hide(ddc->hatch_area);
287 }
289 {
290 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
291 ddc->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
292 sp_curve_unref(c);
293 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->dilate_area), 0x00000000,(SPWindRule)0);
294 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
295 sp_canvas_item_hide(ddc->dilate_area);
296 }
298 sp_event_context_read(ec, "mass");
299 sp_event_context_read(ec, "wiggle");
300 sp_event_context_read(ec, "angle");
301 sp_event_context_read(ec, "width");
302 sp_event_context_read(ec, "thinning");
303 sp_event_context_read(ec, "tremor");
304 sp_event_context_read(ec, "flatness");
305 sp_event_context_read(ec, "tracebackground");
306 sp_event_context_read(ec, "usepressure");
307 sp_event_context_read(ec, "usetilt");
308 sp_event_context_read(ec, "abs_width");
309 sp_event_context_read(ec, "keep_selected");
310 sp_event_context_read(ec, "cap_rounding");
312 ddc->is_drawing = false;
314 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
315 }
317 static void
318 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
319 {
320 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
322 if (!strcmp(key, "mass")) {
323 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
324 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
325 } else if (!strcmp(key, "wiggle")) {
326 double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
327 ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
328 } else if (!strcmp(key, "angle")) {
329 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
330 ddc->angle = CLAMP (dval, -90, 90);
331 } else if (!strcmp(key, "width")) {
332 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
333 ddc->width = CLAMP(dval, -1000.0, 1000.0);
334 } else if (!strcmp(key, "thinning")) {
335 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
336 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
337 } else if (!strcmp(key, "tremor")) {
338 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
339 ddc->tremor = CLAMP(dval, 0.0, 1.0);
340 } else if (!strcmp(key, "flatness")) {
341 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
342 ddc->flatness = CLAMP(dval, 0, 1.0);
343 } else if (!strcmp(key, "tracebackground")) {
344 ddc->trace_bg = (val && strcmp(val, "0"));
345 } else if (!strcmp(key, "usepressure")) {
346 ddc->usepressure = (val && strcmp(val, "0"));
347 } else if (!strcmp(key, "usetilt")) {
348 ddc->usetilt = (val && strcmp(val, "0"));
349 } else if (!strcmp(key, "abs_width")) {
350 ddc->abs_width = (val && strcmp(val, "0"));
351 } else if (!strcmp(key, "keep_selected")) {
352 ddc->keep_selected = (val && strcmp(val, "0"));
353 } else if (!strcmp(key, "cap_rounding")) {
354 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
355 }
357 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
358 }
360 static double
361 flerp(double f0, double f1, double p)
362 {
363 return f0 + ( f1 - f0 ) * p;
364 }
366 /* Get normalized point */
367 static NR::Point
368 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
369 {
370 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
371 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
372 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
373 }
375 /* Get view point */
376 static NR::Point
377 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
378 {
379 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
380 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
381 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
382 }
384 static void
385 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
386 {
387 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
388 dc->vel = NR::Point(0,0);
389 dc->vel_max = 0;
390 dc->acc = NR::Point(0,0);
391 dc->ang = NR::Point(0,0);
392 dc->del = NR::Point(0,0);
393 }
395 static void
396 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
397 {
398 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
399 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
400 else
401 dc->pressure = DDC_DEFAULT_PRESSURE;
403 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
404 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
405 else
406 dc->xtilt = DDC_DEFAULT_TILT;
408 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
409 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
410 else
411 dc->ytilt = DDC_DEFAULT_TILT;
412 }
415 static gboolean
416 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
417 {
418 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
420 /* Calculate mass and drag */
421 double const mass = flerp(1.0, 160.0, dc->mass);
422 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
424 /* Calculate force and acceleration */
425 NR::Point force = n - dc->cur;
427 // If force is below the absolute threshold DYNA_EPSILON,
428 // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
429 // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
430 // discard this move.
431 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
432 // especially bothersome at the start of the stroke where we don't yet have the inertia to
433 // smooth them out.
434 if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
435 return FALSE;
436 }
438 dc->acc = force / mass;
440 /* Calculate new velocity */
441 dc->vel += dc->acc;
443 if (NR::L2(dc->vel) > dc->vel_max)
444 dc->vel_max = NR::L2(dc->vel);
446 /* Calculate angle of drawing tool */
448 double a1;
449 if (dc->usetilt) {
450 // 1a. calculate nib angle from input device tilt:
451 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
453 if (length > 0) {
454 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
455 a1 = atan2(ang1);
456 }
457 else
458 a1 = 0.0;
459 }
460 else {
461 // 1b. fixed dc->angle (absolutely flat nib):
462 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
463 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
464 a1 = atan2(ang1);
465 }
467 // 2. perpendicular to dc->vel (absolutely non-flat nib):
468 gdouble const mag_vel = NR::L2(dc->vel);
469 if ( mag_vel < DYNA_EPSILON ) {
470 return FALSE;
471 }
472 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
474 // 3. Average them using flatness parameter:
475 // calculate angles
476 double a2 = atan2(ang2);
477 // flip a2 to force it to be in the same half-circle as a1
478 bool flipped = false;
479 if (fabs (a2-a1) > 0.5*M_PI) {
480 a2 += M_PI;
481 flipped = true;
482 }
483 // normalize a2
484 if (a2 > M_PI)
485 a2 -= 2*M_PI;
486 if (a2 < -M_PI)
487 a2 += 2*M_PI;
488 // find the flatness-weighted bisector angle, unflip if a2 was flipped
489 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
490 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
492 // Try to detect a sudden flip when the new angle differs too much from the previous for the
493 // current velocity; in that case discard this move
494 double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
495 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
496 return FALSE;
497 }
499 // convert to point
500 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
502 // g_print ("force %g acc %g vel_max %g vel %g a1 %g a2 %g new_ang %g\n", NR::L2(force), NR::L2(dc->acc), dc->vel_max, NR::L2(dc->vel), a1, a2, new_ang);
504 /* Apply drag */
505 dc->vel *= 1.0 - drag;
507 /* Update position */
508 dc->last = dc->cur;
509 dc->cur += dc->vel;
511 return TRUE;
512 }
514 static void
515 sp_dyna_draw_brush(SPDynaDrawContext *dc)
516 {
517 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
519 // How much velocity thins strokestyle
520 double vel_thin = flerp (0, 160, dc->vel_thin);
522 // Influence of pressure on thickness
523 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
525 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
526 // drag)
527 NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
528 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
530 double trace_thick = 1;
531 if (dc->trace_bg) {
532 // pick single pixel
533 NRPixBlock pb;
534 int x = (int) floor(brush_w[NR::X]);
535 int y = (int) floor(brush_w[NR::Y]);
536 nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
537 sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
538 const unsigned char *s = NR_PIXBLOCK_PX(&pb);
539 double R = s[0] / 255.0;
540 double G = s[1] / 255.0;
541 double B = s[2] / 255.0;
542 double A = s[3] / 255.0;
543 double max = MAX (MAX (R, G), B);
544 double min = MIN (MIN (R, G), B);
545 double L = A * (max + min)/2 + (1 - A); // blend with white bg
546 trace_thick = 1 - L;
547 //g_print ("L %g thick %g\n", L, trace_thick);
548 }
550 double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
552 double tremble_left = 0, tremble_right = 0;
553 if (dc->tremor > 0) {
554 // obtain two normally distributed random variables, using polar Box-Muller transform
555 double x1, x2, w, y1, y2;
556 do {
557 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
558 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
559 w = x1 * x1 + x2 * x2;
560 } while ( w >= 1.0 );
561 w = sqrt( (-2.0 * log( w ) ) / w );
562 y1 = x1 * w;
563 y2 = x2 * w;
565 // deflect both left and right edges randomly and independently, so that:
566 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
567 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
568 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
569 // comparatively smooth and slow ones excessively jittery
570 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
571 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
572 }
574 if ( width < 0.02 * dc->width ) {
575 width = 0.02 * dc->width;
576 }
578 double dezoomify_factor = 0.05 * 1000;
579 if (!dc->abs_width) {
580 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
581 }
583 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
584 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
586 dc->point1[dc->npoints] = brush + del_left;
587 dc->point2[dc->npoints] = brush - del_right;
589 dc->del = 0.5*(del_left + del_right);
591 dc->npoints++;
592 }
594 double
595 get_dilate_radius (SPDynaDrawContext *dc)
596 {
597 // 10 times the pen width:
598 return 500 * dc->width/SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
599 }
601 double
602 get_dilate_force (SPDynaDrawContext *dc)
603 {
604 double force = 4 * dc->pressure/SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
605 if (force > 3) {
606 force += 8 * (force - 3);
607 }
608 return force;
609 }
611 bool
612 sp_ddc_dilate_recursive (SPItem *item, NR::Point p, bool expand, double radius, double offset)
613 {
614 bool did = false;
616 if (SP_IS_GROUP(item)) {
617 for (SPObject *child = sp_object_first_child(SP_OBJECT(item)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
618 if (SP_IS_ITEM(child)) {
619 did = did || sp_ddc_dilate_recursive (SP_ITEM(child), p, expand, radius, offset);
620 }
621 }
623 } else if (SP_IS_PATH(item)) {
625 SPCurve *curve = NULL;
626 curve = sp_shape_get_curve(SP_SHAPE(item));
627 if (curve == NULL)
628 return false;
630 // skip those paths whose bboxes are entirely out of reach with our radius
631 NR::Maybe<NR::Rect> bbox = item->getBounds(sp_item_i2doc_affine(item));
632 if (bbox) {
633 bbox->growBy(radius);
634 if (!bbox->contains(p)) {
635 return false;
636 }
637 }
639 Path *orig = Path_for_item(item, false);
640 if (orig == NULL) {
641 sp_curve_unref(curve);
642 return false;
643 }
644 Path *res = new Path;
645 res->SetBackData(false);
647 Shape *theShape = new Shape;
648 Shape *theRes = new Shape;
650 orig->ConvertWithBackData(0.05);
651 orig->Fill(theShape, 0);
653 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
654 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
655 if (val && strcmp(val, "nonzero") == 0)
656 {
657 theRes->ConvertToShape(theShape, fill_nonZero);
658 }
659 else if (val && strcmp(val, "evenodd") == 0)
660 {
661 theRes->ConvertToShape(theShape, fill_oddEven);
662 }
663 else
664 {
665 theRes->ConvertToShape(theShape, fill_nonZero);
666 }
668 bool did_this = false;
669 NR::Matrix i2doc(sp_item_i2doc_affine(item));
670 if (theShape->MakeOffset(theRes,
671 expand? offset : -offset,
672 join_straight, butt_straight,
673 true, p[NR::X], p[NR::Y], radius, &i2doc) == 0) // 0 means the shape was actually changed
674 did_this = true;
676 // the rest only makes sense if we actually changed the path
677 if (did_this) {
678 theRes->ConvertToShape(theShape, fill_positive);
680 res->Reset();
681 theRes->ConvertToForme(res);
683 if (offset >= 0.5)
684 {
685 res->ConvertEvenLines(0.5);
686 res->Simplify(0.5);
687 }
688 else
689 {
690 res->ConvertEvenLines(0.5*offset);
691 res->Simplify(0.5 * offset);
692 }
694 sp_curve_unref(curve);
695 if (res->descr_cmd.size() > 1) {
696 gchar *str = res->svg_dump_path();
697 SP_OBJECT_REPR(item)->setAttribute("d", str);
698 g_free(str);
699 } else {
700 // TODO: if there's 0 or 1 node left, delete this path altogether
701 }
702 }
704 delete theShape;
705 delete theRes;
706 delete orig;
707 delete res;
709 if (did_this)
710 did = true;
711 }
713 return did;
714 }
717 bool
718 sp_ddc_dilate (SPDynaDrawContext *dc, NR::Point p, bool expand)
719 {
720 Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(dc)->desktop);
722 if (selection->isEmpty()) {
723 return false;
724 }
726 bool did = false;
727 double radius = get_dilate_radius(dc);
728 double offset = get_dilate_force(dc);
729 if (radius == 0 || offset == 0) {
730 return false;
731 }
733 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
734 items != NULL;
735 items = items->next) {
737 SPItem *item = (SPItem *) items->data;
739 did = did || sp_ddc_dilate_recursive (item, p, expand, radius, offset);
741 }
743 return did;
744 }
746 void
747 sp_ddc_update_cursors (SPDynaDrawContext *dc)
748 {
749 if (dc->is_dilating) {
750 double radius = get_dilate_radius(dc);
751 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(SP_EVENT_CONTEXT(dc)->desktop->point()));
752 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
753 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
754 sp_canvas_item_show(dc->dilate_area);
755 }
756 }
758 void
759 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
760 {
761 desktop->setToolboxAdjustmentValue (id, value);
762 }
764 static void
765 calligraphic_cancel(SPDynaDrawContext *dc)
766 {
767 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
768 dc->dragging = FALSE;
769 dc->is_drawing = false;
770 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
771 /* Remove all temporary line segments */
772 while (dc->segments) {
773 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
774 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
775 }
776 /* reset accumulated curve */
777 sp_curve_reset(dc->accumulated);
778 clear_current(dc);
779 if (dc->repr) {
780 dc->repr = NULL;
781 }
782 }
785 gint
786 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
787 GdkEvent *event)
788 {
789 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
790 SPDesktop *desktop = event_context->desktop;
792 gint ret = FALSE;
794 switch (event->type) {
795 case GDK_BUTTON_PRESS:
796 if ( event->button.button == 1 ) {
798 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
800 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
801 return TRUE;
802 }
804 NR::Point const button_w(event->button.x,
805 event->button.y);
806 NR::Point const button_dt(desktop->w2d(button_w));
807 sp_dyna_draw_reset(dc, button_dt);
808 sp_dyna_draw_extinput(dc, event);
809 sp_dyna_draw_apply(dc, button_dt);
810 sp_curve_reset(dc->accumulated);
811 if (dc->repr) {
812 dc->repr = NULL;
813 }
815 /* initialize first point */
816 dc->npoints = 0;
818 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
819 ( GDK_KEY_PRESS_MASK |
820 GDK_BUTTON_RELEASE_MASK |
821 GDK_POINTER_MOTION_MASK |
822 GDK_BUTTON_PRESS_MASK ),
823 NULL,
824 event->button.time);
826 ret = TRUE;
828 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
829 dc->is_drawing = true;
830 }
831 break;
832 case GDK_MOTION_NOTIFY:
833 {
834 NR::Point const motion_w(event->motion.x,
835 event->motion.y);
836 NR::Point motion_dt(desktop->w2d(motion_w));
837 sp_dyna_draw_extinput(dc, event);
839 // draw the dilating cursor
840 if (event->motion.state & GDK_MOD1_MASK) {
841 double radius = get_dilate_radius(dc);
842 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(desktop->w2d(motion_w)));
843 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
844 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
845 sp_canvas_item_show(dc->dilate_area);
847 guint num = 0;
848 if (!desktop->selection->isEmpty()) {
849 num = g_slist_length((GSList *) desktop->selection->itemList());
850 }
851 if (num == 0) {
852 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select paths</b> to thin or thicken"));
853 } else {
854 dc->_message_context->setF(Inkscape::NORMAL_MESSAGE,
855 event->motion.state & GDK_SHIFT_MASK?
856 _("<b>Thickening %d</b> selected objects; without <b>Shift</b> to thin") :
857 _("<b>Thinning %d</b> selected objects; with <b>Shift</b> to thicken"), num);
858 }
860 } else {
861 dc->_message_context->clear();
862 sp_canvas_item_hide(dc->dilate_area);
863 }
865 // dilating:
866 if (dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) && event->motion.state & GDK_MOD1_MASK) {
867 sp_ddc_dilate (dc, desktop->dt2doc(motion_dt), event->motion.state & GDK_SHIFT_MASK? true : false);
868 dc->is_dilating = true;
869 // it's slow, so prevent clogging up with events
870 gobble_motion_events(GDK_BUTTON1_MASK);
871 return TRUE;
872 }
875 // for hatching:
876 double hatch_dist = 0;
877 NR::Point hatch_unit_vector(0,0);
878 NR::Point nearest(0,0);
879 NR::Point pointer(0,0);
880 NR::Matrix motion_to_curve(NR::identity());
882 if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
884 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
885 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
886 // One item selected, and it's a path;
887 // let's try to track it as a guide
889 if (selected != dc->hatch_item) {
890 dc->hatch_item = selected;
891 if (dc->hatch_livarot_path)
892 delete dc->hatch_livarot_path;
893 dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
894 dc->hatch_livarot_path->ConvertWithBackData(0.01);
895 }
897 // calculate pointer point in the guide item's coords
898 motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
899 pointer = motion_dt * motion_to_curve;
901 // calculate the nearest point on the guide path
902 NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
903 nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
906 // distance from pointer to nearest
907 hatch_dist = NR::L2(pointer - nearest);
908 // unit-length vector
909 hatch_unit_vector = (pointer - nearest)/hatch_dist;
911 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
912 } else {
913 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
914 }
915 }
917 if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
918 dc->dragging = TRUE;
920 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
922 #define SPEED_ELEMENTS 12
923 #define SPEED_MIN 0.12
924 #define SPEED_NORMAL 0.65
926 // speed is the movement of the nearest point along the guide path, divided by
927 // the movement of the pointer at the same period; it is averaged for the last
928 // SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed
929 // is about 1, i.e. the nearest point on the path is moved by about the same
930 // distance as the pointer. If the speed starts to decrease, we are losing
931 // contact with the guide; if it drops below SPEED_MIN, we are on our own and
932 // not attracted to guide anymore. Most often this happens when you have
933 // tracked to the end of a guide calligraphic stroke and keep moving
934 // further. We try to handle this situation gracefully: not stick with the
935 // guide forever but let go of it smoothly and without sharp jerks (non-zero
936 // mass recommended; with zero mass, jerks are still quite noticeable).
938 double speed = 1;
939 if (NR::L2(dc->hatch_last_nearest) != 0) {
940 // the distance nearest moved since the last motion event
941 double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
942 // the distance pointer moved since the last motion event
943 double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
944 // store them in stacks limited to SPEED_ELEMENTS
945 dc->hatch_nearest_past.push_front(nearest_moved);
946 if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
947 dc->hatch_nearest_past.pop_back();
948 dc->hatch_pointer_past.push_front(pointer_moved);
949 if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
950 dc->hatch_pointer_past.pop_back();
952 // If the stacks are full,
953 if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
954 // calculate the sums of all stored movements
955 double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
956 double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
957 // and divide to get the speed
958 speed = nearest_sum/pointer_sum;
959 //g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed);
960 }
961 }
963 if ( dc->hatch_escaped // already escaped, do not reattach
964 || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
965 || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
966 ) {
967 // We are NOT attracted to the guide!
969 //g_print ("\nlast_nearest %g %g nearest %g %g pointer %g %g pos %d %g\n", dc->last_nearest[NR::X], dc->last_nearest[NR::Y], nearest[NR::X], nearest[NR::Y], pointer[NR::X], pointer[NR::Y], position->piece, position->t);
971 // Remember hatch_escaped so we don't get
972 // attracted again until the end of this stroke
973 dc->hatch_escaped = true;
975 } else {
977 // Calculate angle cosine of this vector-to-guide and all past vectors
978 // summed, to detect if we accidentally flipped to the other side of the
979 // guide
980 double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
981 dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
983 if (dc->hatch_spacing != 0) { // spacing was already set
984 double target;
985 if (speed > SPEED_NORMAL) {
986 // all ok, strictly obey the spacing
987 target = dc->hatch_spacing;
988 } else {
989 // looks like we're starting to lose speed,
990 // so _gradually_ let go attraction to prevent jerks
991 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
992 }
993 if (!isNaN(dot) && dot < -0.5) {// flip
994 target = -target;
995 }
997 // This is the track pointer that we will use instead of the real one
998 NR::Point new_pointer = nearest + target * hatch_unit_vector;
1000 // some limited feedback: allow persistent pulling to slightly change
1001 // the spacing
1002 dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
1004 // return it to the desktop coords
1005 motion_dt = new_pointer * motion_to_curve.inverse();
1007 } else {
1008 // this is the first motion event, set the dist
1009 dc->hatch_spacing = hatch_dist;
1010 }
1012 // remember last points
1013 dc->hatch_last_pointer = pointer;
1014 dc->hatch_last_nearest = nearest;
1015 dc->hatch_vector_accumulated += (pointer - nearest);
1016 }
1018 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
1020 } else {
1021 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
1022 }
1024 if (!sp_dyna_draw_apply(dc, motion_dt)) {
1025 ret = TRUE;
1026 break;
1027 }
1029 if ( dc->cur != dc->last ) {
1030 sp_dyna_draw_brush(dc);
1031 g_assert( dc->npoints > 0 );
1032 fit_and_split(dc, FALSE);
1033 }
1034 ret = TRUE;
1035 }
1037 // Draw the hatching circle if necessary
1038 if (event->motion.state & GDK_CONTROL_MASK) {
1039 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
1040 // Haven't set spacing yet: gray, center free, update radius live
1041 NR::Point c = desktop->w2d(motion_w);
1042 NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
1043 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1044 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1045 sp_canvas_item_show(dc->hatch_area);
1046 } else if (dc->dragging && !dc->hatch_escaped) {
1047 // Tracking: green, center snapped, fixed radius
1048 NR::Point c = motion_dt;
1049 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1050 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1051 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1052 sp_canvas_item_show(dc->hatch_area);
1053 } else if (dc->dragging && dc->hatch_escaped) {
1054 // Tracking escaped: red, center free, fixed radius
1055 NR::Point c = desktop->w2d(motion_w);
1056 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1058 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1059 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1060 sp_canvas_item_show(dc->hatch_area);
1061 } else {
1062 // Not drawing but spacing set: gray, center snapped, fixed radius
1063 NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
1064 if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
1065 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1066 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1067 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1068 sp_canvas_item_show(dc->hatch_area);
1069 }
1070 }
1071 } else {
1072 sp_canvas_item_hide(dc->hatch_area);
1073 }
1074 }
1075 break;
1078 case GDK_BUTTON_RELEASE:
1079 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
1080 sp_canvas_end_forced_full_redraws(desktop->canvas);
1081 dc->is_drawing = false;
1083 if ( dc->is_dilating && event->button.button == 1 ) {
1084 dc->is_dilating = false;
1085 sp_document_done(sp_desktop_document(SP_EVENT_CONTEXT(dc)->desktop),
1086 SP_VERB_CONTEXT_CALLIGRAPHIC,
1087 (event->button.state & GDK_SHIFT_MASK ? _("Thicken paths") : _("Thin paths")));
1088 ret = TRUE;
1089 } else if ( dc->dragging && event->button.button == 1 ) {
1090 dc->dragging = FALSE;
1092 NR::Point const motion_w(event->button.x, event->button.y);
1093 NR::Point const motion_dt(desktop->w2d(motion_w));
1094 sp_dyna_draw_apply(dc, motion_dt);
1096 /* Remove all temporary line segments */
1097 while (dc->segments) {
1098 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
1099 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
1100 }
1102 /* Create object */
1103 fit_and_split(dc, TRUE);
1104 accumulate_calligraphic(dc);
1105 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
1107 /* reset accumulated curve */
1108 sp_curve_reset(dc->accumulated);
1110 clear_current(dc);
1111 if (dc->repr) {
1112 dc->repr = NULL;
1113 }
1115 if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
1116 if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
1117 dc->hatch_last_nearest = NR::Point(0,0);
1118 dc->hatch_last_pointer = NR::Point(0,0);
1119 dc->hatch_vector_accumulated = NR::Point(0,0);
1120 dc->hatch_escaped = false;
1121 dc->hatch_item = NULL;
1122 dc->hatch_livarot_path = NULL;
1124 if (dc->hatch_spacing != 0 && !dc->keep_selected) {
1125 // we do not select the newly drawn path, so increase spacing by step
1126 if (dc->hatch_spacing_step == 0) {
1127 dc->hatch_spacing_step = dc->hatch_spacing;
1128 }
1129 dc->hatch_spacing += dc->hatch_spacing_step;
1130 }
1132 dc->_message_context->clear();
1133 ret = TRUE;
1134 }
1135 break;
1137 case GDK_KEY_PRESS:
1138 switch (get_group0_keyval (&event->key)) {
1139 case GDK_Up:
1140 case GDK_KP_Up:
1141 if (!MOD__CTRL_ONLY) {
1142 dc->angle += 5.0;
1143 if (dc->angle > 90.0)
1144 dc->angle = 90.0;
1145 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1146 ret = TRUE;
1147 }
1148 break;
1149 case GDK_Down:
1150 case GDK_KP_Down:
1151 if (!MOD__CTRL_ONLY) {
1152 dc->angle -= 5.0;
1153 if (dc->angle < -90.0)
1154 dc->angle = -90.0;
1155 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1156 ret = TRUE;
1157 }
1158 break;
1159 case GDK_Right:
1160 case GDK_KP_Right:
1161 if (!MOD__CTRL_ONLY) {
1162 dc->width += 0.01;
1163 if (dc->width > 1.0)
1164 dc->width = 1.0;
1165 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
1166 sp_ddc_update_cursors(dc);
1167 ret = TRUE;
1168 }
1169 break;
1170 case GDK_Left:
1171 case GDK_KP_Left:
1172 if (!MOD__CTRL_ONLY) {
1173 dc->width -= 0.01;
1174 if (dc->width < 0.01)
1175 dc->width = 0.01;
1176 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1177 sp_ddc_update_cursors(dc);
1178 ret = TRUE;
1179 }
1180 break;
1181 case GDK_Home:
1182 case GDK_KP_Home:
1183 dc->width = 0.01;
1184 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1185 sp_ddc_update_cursors(dc);
1186 ret = TRUE;
1187 break;
1188 case GDK_End:
1189 case GDK_KP_End:
1190 dc->width = 1.0;
1191 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1192 sp_ddc_update_cursors(dc);
1193 ret = TRUE;
1194 break;
1195 case GDK_x:
1196 case GDK_X:
1197 if (MOD__ALT_ONLY) {
1198 desktop->setToolboxFocusTo ("altx-calligraphy");
1199 ret = TRUE;
1200 }
1201 break;
1202 case GDK_Escape:
1203 if (dc->is_drawing) {
1204 // if drawing, cancel, otherwise pass it up for deselecting
1205 calligraphic_cancel (dc);
1206 ret = TRUE;
1207 }
1208 break;
1209 case GDK_z:
1210 case GDK_Z:
1211 if (MOD__CTRL_ONLY && dc->is_drawing) {
1212 // if drawing, cancel, otherwise pass it up for undo
1213 calligraphic_cancel (dc);
1214 ret = TRUE;
1215 }
1216 break;
1217 case GDK_Meta_L:
1218 case GDK_Meta_R:
1219 event_context->cursor_shape = cursor_thicken_xpm;
1220 sp_event_context_update_cursor(event_context);
1221 break;
1222 case GDK_Alt_L:
1223 case GDK_Alt_R:
1224 if (MOD__SHIFT) {
1225 event_context->cursor_shape = cursor_thicken_xpm;
1226 sp_event_context_update_cursor(event_context);
1227 } else {
1228 event_context->cursor_shape = cursor_thin_xpm;
1229 sp_event_context_update_cursor(event_context);
1230 }
1231 break;
1232 case GDK_Shift_L:
1233 case GDK_Shift_R:
1234 if (MOD__ALT) {
1235 event_context->cursor_shape = cursor_thicken_xpm;
1236 sp_event_context_update_cursor(event_context);
1237 }
1238 break;
1239 default:
1240 break;
1241 }
1242 break;
1244 case GDK_KEY_RELEASE:
1245 switch (get_group0_keyval(&event->key)) {
1246 case GDK_Control_L:
1247 case GDK_Control_R:
1248 dc->_message_context->clear();
1249 dc->hatch_spacing = 0;
1250 dc->hatch_spacing_step = 0;
1251 break;
1252 case GDK_Alt_L:
1253 case GDK_Alt_R:
1254 event_context->cursor_shape = cursor_calligraphy_xpm;
1255 sp_event_context_update_cursor(event_context);
1256 break;
1257 case GDK_Shift_L:
1258 case GDK_Shift_R:
1259 if (MOD__ALT) {
1260 event_context->cursor_shape = cursor_thin_xpm;
1261 sp_event_context_update_cursor(event_context);
1262 }
1263 break;
1264 case GDK_Meta_L:
1265 case GDK_Meta_R:
1266 event_context->cursor_shape = cursor_calligraphy_xpm;
1267 sp_event_context_update_cursor(event_context);
1268 break;
1269 default:
1270 break;
1271 }
1273 default:
1274 break;
1275 }
1277 if (!ret) {
1278 if (((SPEventContextClass *) parent_class)->root_handler) {
1279 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1280 }
1281 }
1283 return ret;
1284 }
1287 static void
1288 clear_current(SPDynaDrawContext *dc)
1289 {
1290 /* reset bpath */
1291 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1292 /* reset curve */
1293 sp_curve_reset(dc->currentcurve);
1294 sp_curve_reset(dc->cal1);
1295 sp_curve_reset(dc->cal2);
1296 /* reset points */
1297 dc->npoints = 0;
1298 }
1300 static void
1301 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1302 {
1303 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1305 if (!sp_curve_empty(dc->accumulated)) {
1306 NArtBpath *abp;
1307 gchar *str;
1309 if (!dc->repr) {
1310 /* Create object */
1311 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1312 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1314 /* Set style */
1315 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1317 dc->repr = repr;
1319 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1320 Inkscape::GC::release(dc->repr);
1321 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1322 item->updateRepr();
1323 }
1324 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1325 str = sp_svg_write_path(abp);
1326 g_assert( str != NULL );
1327 g_free(abp);
1328 dc->repr->setAttribute("d", str);
1329 g_free(str);
1331 if (unionize) {
1332 sp_desktop_selection(desktop)->add(dc->repr);
1333 sp_selected_path_union_skip_undo();
1334 } else {
1335 if (dc->keep_selected) {
1336 sp_desktop_selection(desktop)->set(dc->repr);
1337 }
1338 }
1340 } else {
1341 if (dc->repr) {
1342 sp_repr_unparent(dc->repr);
1343 }
1344 dc->repr = NULL;
1345 }
1347 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1348 _("Draw calligraphic stroke"));
1349 }
1351 static void
1352 add_cap(SPCurve *curve,
1353 NR::Point const &pre, NR::Point const &from,
1354 NR::Point const &to, NR::Point const &post,
1355 double rounding)
1356 {
1357 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1358 double mag = NR::L2(vel);
1360 NR::Point v_in = from - pre;
1361 double mag_in = NR::L2(v_in);
1362 if ( mag_in > DYNA_EPSILON ) {
1363 v_in = mag * v_in / mag_in;
1364 } else {
1365 v_in = NR::Point(0, 0);
1366 }
1368 NR::Point v_out = to - post;
1369 double mag_out = NR::L2(v_out);
1370 if ( mag_out > DYNA_EPSILON ) {
1371 v_out = mag * v_out / mag_out;
1372 } else {
1373 v_out = NR::Point(0, 0);
1374 }
1376 if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1377 sp_curve_curveto(curve, from + v_in, to + v_out, to);
1378 }
1379 }
1381 static void
1382 accumulate_calligraphic(SPDynaDrawContext *dc)
1383 {
1384 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1385 sp_curve_reset(dc->accumulated); /* Is this required ?? */
1386 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1388 g_assert(dc->cal1->end > 1);
1389 g_assert(rev_cal2->end > 1);
1390 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1391 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1392 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1393 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1394 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1395 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1397 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1399 add_cap(dc->accumulated, SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->c(2), SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->c(3), SP_CURVE_SEGMENT(rev_cal2, 0)->c(3), SP_CURVE_SEGMENT(rev_cal2, 1)->c(1), dc->cap_rounding);
1401 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1403 add_cap(dc->accumulated, SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->c(2), SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->c(3), SP_CURVE_SEGMENT(dc->cal1, 0)->c(3), SP_CURVE_SEGMENT(dc->cal1, 1)->c(1), dc->cap_rounding);
1405 sp_curve_closepath(dc->accumulated);
1407 sp_curve_unref(rev_cal2);
1409 sp_curve_reset(dc->cal1);
1410 sp_curve_reset(dc->cal2);
1411 }
1412 }
1414 static double square(double const x)
1415 {
1416 return x * x;
1417 }
1419 static void
1420 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1421 {
1422 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1424 #ifdef DYNA_DRAW_VERBOSE
1425 g_print("[F&S:R=%c]", release?'T':'F');
1426 #endif
1428 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1429 return; // just clicked
1431 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1432 #define BEZIER_SIZE 4
1433 #define BEZIER_MAX_BEZIERS 8
1434 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1436 #ifdef DYNA_DRAW_VERBOSE
1437 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1438 dc->npoints, release ? "TRUE" : "FALSE");
1439 #endif
1441 /* Current calligraphic */
1442 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1443 /* dc->npoints > 0 */
1444 /* g_print("calligraphics(1|2) reset\n"); */
1445 sp_curve_reset(dc->cal1);
1446 sp_curve_reset(dc->cal2);
1448 sp_curve_moveto(dc->cal1, dc->point1[0]);
1449 sp_curve_moveto(dc->cal2, dc->point2[0]);
1450 }
1452 NR::Point b1[BEZIER_MAX_LENGTH];
1453 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1454 tolerance_sq, BEZIER_MAX_BEZIERS);
1455 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1457 NR::Point b2[BEZIER_MAX_LENGTH];
1458 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1459 tolerance_sq, BEZIER_MAX_BEZIERS);
1460 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1462 if ( nb1 != -1 && nb2 != -1 ) {
1463 /* Fit and draw and reset state */
1464 #ifdef DYNA_DRAW_VERBOSE
1465 g_print("nb1:%d nb2:%d\n", nb1, nb2);
1466 #endif
1467 /* CanvasShape */
1468 if (! release) {
1469 sp_curve_reset(dc->currentcurve);
1470 sp_curve_moveto(dc->currentcurve, b1[0]);
1471 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1472 sp_curve_curveto(dc->currentcurve, bp1[1],
1473 bp1[2], bp1[3]);
1474 }
1475 sp_curve_lineto(dc->currentcurve,
1476 b2[BEZIER_SIZE*(nb2-1) + 3]);
1477 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1478 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1479 }
1480 // FIXME: dc->segments is always NULL at this point??
1481 if (!dc->segments) { // first segment
1482 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1483 }
1484 sp_curve_closepath(dc->currentcurve);
1485 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1486 }
1488 /* Current calligraphic */
1489 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1490 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1491 }
1492 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1493 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1494 }
1495 } else {
1496 /* fixme: ??? */
1497 #ifdef DYNA_DRAW_VERBOSE
1498 g_print("[fit_and_split] failed to fit-cubic.\n");
1499 #endif
1500 draw_temporary_box(dc);
1502 for (gint i = 1; i < dc->npoints; i++) {
1503 sp_curve_lineto(dc->cal1, dc->point1[i]);
1504 }
1505 for (gint i = 1; i < dc->npoints; i++) {
1506 sp_curve_lineto(dc->cal2, dc->point2[i]);
1507 }
1508 }
1510 /* Fit and draw and copy last point */
1511 #ifdef DYNA_DRAW_VERBOSE
1512 g_print("[%d]Yup\n", dc->npoints);
1513 #endif
1514 if (!release) {
1515 g_assert(!sp_curve_empty(dc->currentcurve));
1517 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1518 SP_TYPE_CANVAS_BPATH,
1519 NULL);
1520 SPCurve *curve = sp_curve_copy(dc->currentcurve);
1521 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1522 sp_curve_unref(curve);
1524 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1525 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1526 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1527 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1528 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1529 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1530 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1531 //sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), ((strokeColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*strokeOpacity)), 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1532 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1533 /* fixme: Cannot we cascade it to root more clearly? */
1534 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1536 dc->segments = g_slist_prepend(dc->segments, cbp);
1537 }
1539 dc->point1[0] = dc->point1[dc->npoints - 1];
1540 dc->point2[0] = dc->point2[dc->npoints - 1];
1541 dc->npoints = 1;
1542 } else {
1543 draw_temporary_box(dc);
1544 }
1545 }
1547 static void
1548 draw_temporary_box(SPDynaDrawContext *dc)
1549 {
1550 sp_curve_reset(dc->currentcurve);
1552 sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1553 for (gint i = dc->npoints-2; i >= 0; i--) {
1554 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1555 }
1556 for (gint i = 0; i < dc->npoints; i++) {
1557 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1558 }
1559 if (dc->npoints >= 2) {
1560 add_cap(dc->currentcurve, dc->point2[dc->npoints-2], dc->point2[dc->npoints-1], dc->point1[dc->npoints-1], dc->point1[dc->npoints-2], dc->cap_rounding);
1561 }
1563 sp_curve_closepath(dc->currentcurve);
1564 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1565 }
1567 /*
1568 Local Variables:
1569 mode:c++
1570 c-file-style:"stroustrup"
1571 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1572 indent-tabs-mode:nil
1573 fill-column:99
1574 End:
1575 */
1576 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :