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 ddc->has_dilated = false;
216 }
218 static void
219 sp_dyna_draw_context_dispose(GObject *object)
220 {
221 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
223 if (ddc->hatch_area) {
224 gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
225 ddc->hatch_area = NULL;
226 }
228 if (ddc->dilate_area) {
229 gtk_object_destroy(GTK_OBJECT(ddc->dilate_area));
230 ddc->dilate_area = NULL;
231 }
233 if (ddc->accumulated) {
234 ddc->accumulated = sp_curve_unref(ddc->accumulated);
235 }
237 while (ddc->segments) {
238 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
239 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
240 }
242 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
243 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
244 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
246 if (ddc->currentshape) {
247 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
248 ddc->currentshape = NULL;
249 }
251 if (ddc->_message_context) {
252 delete ddc->_message_context;
253 }
255 G_OBJECT_CLASS(parent_class)->dispose(object);
257 ddc->hatch_pointer_past.~list();
258 ddc->hatch_nearest_past.~list();
259 }
261 static void
262 sp_dyna_draw_context_setup(SPEventContext *ec)
263 {
264 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
266 if (((SPEventContextClass *) parent_class)->setup)
267 ((SPEventContextClass *) parent_class)->setup(ec);
269 ddc->accumulated = sp_curve_new_sized(32);
270 ddc->currentcurve = sp_curve_new_sized(4);
272 ddc->cal1 = sp_curve_new_sized(32);
273 ddc->cal2 = sp_curve_new_sized(32);
275 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
276 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
277 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
278 /* fixme: Cannot we cascade it to root more clearly? */
279 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
281 {
282 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
283 ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
284 sp_curve_unref(c);
285 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
286 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
287 sp_canvas_item_hide(ddc->hatch_area);
288 }
290 {
291 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
292 ddc->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
293 sp_curve_unref(c);
294 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->dilate_area), 0x00000000,(SPWindRule)0);
295 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
296 sp_canvas_item_hide(ddc->dilate_area);
297 }
299 sp_event_context_read(ec, "mass");
300 sp_event_context_read(ec, "wiggle");
301 sp_event_context_read(ec, "angle");
302 sp_event_context_read(ec, "width");
303 sp_event_context_read(ec, "thinning");
304 sp_event_context_read(ec, "tremor");
305 sp_event_context_read(ec, "flatness");
306 sp_event_context_read(ec, "tracebackground");
307 sp_event_context_read(ec, "usepressure");
308 sp_event_context_read(ec, "usetilt");
309 sp_event_context_read(ec, "abs_width");
310 sp_event_context_read(ec, "keep_selected");
311 sp_event_context_read(ec, "cap_rounding");
313 ddc->is_drawing = false;
315 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
316 }
318 static void
319 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
320 {
321 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
323 if (!strcmp(key, "mass")) {
324 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
325 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
326 } else if (!strcmp(key, "wiggle")) {
327 double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
328 ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
329 } else if (!strcmp(key, "angle")) {
330 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
331 ddc->angle = CLAMP (dval, -90, 90);
332 } else if (!strcmp(key, "width")) {
333 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
334 ddc->width = CLAMP(dval, -1000.0, 1000.0);
335 } else if (!strcmp(key, "thinning")) {
336 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
337 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
338 } else if (!strcmp(key, "tremor")) {
339 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
340 ddc->tremor = CLAMP(dval, 0.0, 1.0);
341 } else if (!strcmp(key, "flatness")) {
342 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
343 ddc->flatness = CLAMP(dval, 0, 1.0);
344 } else if (!strcmp(key, "tracebackground")) {
345 ddc->trace_bg = (val && strcmp(val, "0"));
346 } else if (!strcmp(key, "usepressure")) {
347 ddc->usepressure = (val && strcmp(val, "0"));
348 } else if (!strcmp(key, "usetilt")) {
349 ddc->usetilt = (val && strcmp(val, "0"));
350 } else if (!strcmp(key, "abs_width")) {
351 ddc->abs_width = (val && strcmp(val, "0"));
352 } else if (!strcmp(key, "keep_selected")) {
353 ddc->keep_selected = (val && strcmp(val, "0"));
354 } else if (!strcmp(key, "cap_rounding")) {
355 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
356 }
358 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
359 }
361 static double
362 flerp(double f0, double f1, double p)
363 {
364 return f0 + ( f1 - f0 ) * p;
365 }
367 /* Get normalized point */
368 static NR::Point
369 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
370 {
371 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
372 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
373 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
374 }
376 /* Get view point */
377 static NR::Point
378 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
379 {
380 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
381 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
382 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
383 }
385 static void
386 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
387 {
388 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
389 dc->vel = NR::Point(0,0);
390 dc->vel_max = 0;
391 dc->acc = NR::Point(0,0);
392 dc->ang = NR::Point(0,0);
393 dc->del = NR::Point(0,0);
394 }
396 static void
397 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
398 {
399 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
400 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
401 else
402 dc->pressure = DDC_DEFAULT_PRESSURE;
404 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
405 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
406 else
407 dc->xtilt = DDC_DEFAULT_TILT;
409 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
410 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
411 else
412 dc->ytilt = DDC_DEFAULT_TILT;
413 }
416 static gboolean
417 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
418 {
419 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
421 /* Calculate mass and drag */
422 double const mass = flerp(1.0, 160.0, dc->mass);
423 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
425 /* Calculate force and acceleration */
426 NR::Point force = n - dc->cur;
428 // If force is below the absolute threshold DYNA_EPSILON,
429 // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
430 // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
431 // discard this move.
432 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
433 // especially bothersome at the start of the stroke where we don't yet have the inertia to
434 // smooth them out.
435 if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
436 return FALSE;
437 }
439 dc->acc = force / mass;
441 /* Calculate new velocity */
442 dc->vel += dc->acc;
444 if (NR::L2(dc->vel) > dc->vel_max)
445 dc->vel_max = NR::L2(dc->vel);
447 /* Calculate angle of drawing tool */
449 double a1;
450 if (dc->usetilt) {
451 // 1a. calculate nib angle from input device tilt:
452 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
454 if (length > 0) {
455 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
456 a1 = atan2(ang1);
457 }
458 else
459 a1 = 0.0;
460 }
461 else {
462 // 1b. fixed dc->angle (absolutely flat nib):
463 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
464 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
465 a1 = atan2(ang1);
466 }
468 // 2. perpendicular to dc->vel (absolutely non-flat nib):
469 gdouble const mag_vel = NR::L2(dc->vel);
470 if ( mag_vel < DYNA_EPSILON ) {
471 return FALSE;
472 }
473 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
475 // 3. Average them using flatness parameter:
476 // calculate angles
477 double a2 = atan2(ang2);
478 // flip a2 to force it to be in the same half-circle as a1
479 bool flipped = false;
480 if (fabs (a2-a1) > 0.5*M_PI) {
481 a2 += M_PI;
482 flipped = true;
483 }
484 // normalize a2
485 if (a2 > M_PI)
486 a2 -= 2*M_PI;
487 if (a2 < -M_PI)
488 a2 += 2*M_PI;
489 // find the flatness-weighted bisector angle, unflip if a2 was flipped
490 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
491 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
493 // Try to detect a sudden flip when the new angle differs too much from the previous for the
494 // current velocity; in that case discard this move
495 double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
496 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
497 return FALSE;
498 }
500 // convert to point
501 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
503 // 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);
505 /* Apply drag */
506 dc->vel *= 1.0 - drag;
508 /* Update position */
509 dc->last = dc->cur;
510 dc->cur += dc->vel;
512 return TRUE;
513 }
515 static void
516 sp_dyna_draw_brush(SPDynaDrawContext *dc)
517 {
518 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
520 // How much velocity thins strokestyle
521 double vel_thin = flerp (0, 160, dc->vel_thin);
523 // Influence of pressure on thickness
524 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
526 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
527 // drag)
528 NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
529 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
531 double trace_thick = 1;
532 if (dc->trace_bg) {
533 // pick single pixel
534 NRPixBlock pb;
535 int x = (int) floor(brush_w[NR::X]);
536 int y = (int) floor(brush_w[NR::Y]);
537 nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
538 sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
539 const unsigned char *s = NR_PIXBLOCK_PX(&pb);
540 double R = s[0] / 255.0;
541 double G = s[1] / 255.0;
542 double B = s[2] / 255.0;
543 double A = s[3] / 255.0;
544 double max = MAX (MAX (R, G), B);
545 double min = MIN (MIN (R, G), B);
546 double L = A * (max + min)/2 + (1 - A); // blend with white bg
547 trace_thick = 1 - L;
548 //g_print ("L %g thick %g\n", L, trace_thick);
549 }
551 double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
553 double tremble_left = 0, tremble_right = 0;
554 if (dc->tremor > 0) {
555 // obtain two normally distributed random variables, using polar Box-Muller transform
556 double x1, x2, w, y1, y2;
557 do {
558 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
559 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
560 w = x1 * x1 + x2 * x2;
561 } while ( w >= 1.0 );
562 w = sqrt( (-2.0 * log( w ) ) / w );
563 y1 = x1 * w;
564 y2 = x2 * w;
566 // deflect both left and right edges randomly and independently, so that:
567 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
568 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
569 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
570 // comparatively smooth and slow ones excessively jittery
571 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
572 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
573 }
575 if ( width < 0.02 * dc->width ) {
576 width = 0.02 * dc->width;
577 }
579 double dezoomify_factor = 0.05 * 1000;
580 if (!dc->abs_width) {
581 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
582 }
584 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
585 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
587 dc->point1[dc->npoints] = brush + del_left;
588 dc->point2[dc->npoints] = brush - del_right;
590 dc->del = 0.5*(del_left + del_right);
592 dc->npoints++;
593 }
595 double
596 get_dilate_radius (SPDynaDrawContext *dc)
597 {
598 // 10 times the pen width:
599 return 500 * dc->width/SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
600 }
602 double
603 get_dilate_force (SPDynaDrawContext *dc)
604 {
605 double force = 4 * dc->pressure/SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
606 if (force > 3) {
607 force += 8 * (force - 3);
608 }
609 return force;
610 }
612 bool
613 sp_ddc_dilate_recursive (SPItem *item, NR::Point p, bool expand, double radius, double offset)
614 {
615 bool did = false;
617 if (SP_IS_GROUP(item)) {
618 for (SPObject *child = sp_object_first_child(SP_OBJECT(item)) ; child != NULL; child = SP_OBJECT_NEXT(child) ) {
619 if (SP_IS_ITEM(child)) {
620 if (sp_ddc_dilate_recursive (SP_ITEM(child), p, expand, radius, offset))
621 did = true;
622 }
623 }
625 } else if (SP_IS_PATH(item)) {
627 SPCurve *curve = NULL;
628 curve = sp_shape_get_curve(SP_SHAPE(item));
629 if (curve == NULL)
630 return false;
632 // skip those paths whose bboxes are entirely out of reach with our radius
633 NR::Maybe<NR::Rect> bbox = item->getBounds(sp_item_i2doc_affine(item));
634 if (bbox) {
635 bbox->growBy(radius);
636 if (!bbox->contains(p)) {
637 return false;
638 }
639 }
641 Path *orig = Path_for_item(item, false);
642 if (orig == NULL) {
643 sp_curve_unref(curve);
644 return false;
645 }
646 Path *res = new Path;
647 res->SetBackData(false);
649 Shape *theShape = new Shape;
650 Shape *theRes = new Shape;
652 orig->ConvertWithBackData(0.05);
653 orig->Fill(theShape, 0);
655 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
656 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
657 if (val && strcmp(val, "nonzero") == 0)
658 {
659 theRes->ConvertToShape(theShape, fill_nonZero);
660 }
661 else if (val && strcmp(val, "evenodd") == 0)
662 {
663 theRes->ConvertToShape(theShape, fill_oddEven);
664 }
665 else
666 {
667 theRes->ConvertToShape(theShape, fill_nonZero);
668 }
670 bool did_this = false;
671 NR::Matrix i2doc(sp_item_i2doc_affine(item));
672 if (theShape->MakeOffset(theRes,
673 expand? offset : -offset,
674 join_straight, butt_straight,
675 true, p[NR::X], p[NR::Y], radius, &i2doc) == 0) // 0 means the shape was actually changed
676 did_this = true;
678 // the rest only makes sense if we actually changed the path
679 if (did_this) {
680 theRes->ConvertToShape(theShape, fill_positive);
682 res->Reset();
683 theRes->ConvertToForme(res);
685 if (offset >= 0.5)
686 {
687 res->ConvertEvenLines(0.5);
688 res->Simplify(0.5);
689 }
690 else
691 {
692 res->ConvertEvenLines(0.5*offset);
693 res->Simplify(0.5 * offset);
694 }
696 sp_curve_unref(curve);
697 if (res->descr_cmd.size() > 1) {
698 gchar *str = res->svg_dump_path();
699 SP_OBJECT_REPR(item)->setAttribute("d", str);
700 g_free(str);
701 } else {
702 // TODO: if there's 0 or 1 node left, delete this path altogether
703 }
704 }
706 delete theShape;
707 delete theRes;
708 delete orig;
709 delete res;
711 if (did_this)
712 did = true;
713 }
715 return did;
716 }
719 bool
720 sp_ddc_dilate (SPDynaDrawContext *dc, NR::Point p, bool expand)
721 {
722 Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(dc)->desktop);
724 if (selection->isEmpty()) {
725 return false;
726 }
728 bool did = false;
729 double radius = get_dilate_radius(dc);
730 double offset = get_dilate_force(dc);
731 if (radius == 0 || offset == 0) {
732 return false;
733 }
735 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
736 items != NULL;
737 items = items->next) {
739 SPItem *item = (SPItem *) items->data;
741 if (sp_ddc_dilate_recursive (item, p, expand, radius, offset))
742 did = true;
744 }
746 return did;
747 }
749 void
750 sp_ddc_update_cursors (SPDynaDrawContext *dc)
751 {
752 if (dc->is_dilating) {
753 double radius = get_dilate_radius(dc);
754 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(SP_EVENT_CONTEXT(dc)->desktop->point()));
755 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
756 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
757 sp_canvas_item_show(dc->dilate_area);
758 }
759 }
761 void
762 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
763 {
764 desktop->setToolboxAdjustmentValue (id, value);
765 }
767 static void
768 calligraphic_cancel(SPDynaDrawContext *dc)
769 {
770 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
771 dc->dragging = FALSE;
772 dc->is_drawing = false;
773 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
774 /* Remove all temporary line segments */
775 while (dc->segments) {
776 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
777 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
778 }
779 /* reset accumulated curve */
780 sp_curve_reset(dc->accumulated);
781 clear_current(dc);
782 if (dc->repr) {
783 dc->repr = NULL;
784 }
785 }
788 gint
789 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
790 GdkEvent *event)
791 {
792 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
793 SPDesktop *desktop = event_context->desktop;
795 gint ret = FALSE;
797 switch (event->type) {
798 case GDK_BUTTON_PRESS:
799 if ( event->button.button == 1 ) {
801 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
803 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
804 return TRUE;
805 }
807 NR::Point const button_w(event->button.x,
808 event->button.y);
809 NR::Point const button_dt(desktop->w2d(button_w));
810 sp_dyna_draw_reset(dc, button_dt);
811 sp_dyna_draw_extinput(dc, event);
812 sp_dyna_draw_apply(dc, button_dt);
813 sp_curve_reset(dc->accumulated);
814 if (dc->repr) {
815 dc->repr = NULL;
816 }
818 /* initialize first point */
819 dc->npoints = 0;
821 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
822 ( GDK_KEY_PRESS_MASK |
823 GDK_BUTTON_RELEASE_MASK |
824 GDK_POINTER_MOTION_MASK |
825 GDK_BUTTON_PRESS_MASK ),
826 NULL,
827 event->button.time);
829 ret = TRUE;
831 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
832 dc->is_drawing = true;
833 if (event->button.state & GDK_MOD1_MASK) {
834 dc->is_dilating = true;
835 dc->has_dilated = false;
836 }
837 }
838 break;
839 case GDK_MOTION_NOTIFY:
840 {
841 NR::Point const motion_w(event->motion.x,
842 event->motion.y);
843 NR::Point motion_dt(desktop->w2d(motion_w));
844 sp_dyna_draw_extinput(dc, event);
846 // draw the dilating cursor
847 if (event->motion.state & GDK_MOD1_MASK) {
848 double radius = get_dilate_radius(dc);
849 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(desktop->w2d(motion_w)));
850 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
851 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
852 sp_canvas_item_show(dc->dilate_area);
854 guint num = 0;
855 if (!desktop->selection->isEmpty()) {
856 num = g_slist_length((GSList *) desktop->selection->itemList());
857 }
858 if (num == 0) {
859 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select paths</b> to thin or thicken"));
860 } else {
861 dc->_message_context->setF(Inkscape::NORMAL_MESSAGE,
862 event->motion.state & GDK_SHIFT_MASK?
863 _("<b>Thickening %d</b> selected objects; without <b>Shift</b> to thin") :
864 _("<b>Thinning %d</b> selected objects; with <b>Shift</b> to thicken"), num);
865 }
867 } else {
868 dc->_message_context->clear();
869 sp_canvas_item_hide(dc->dilate_area);
870 }
872 // dilating:
873 if (dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) && event->motion.state & GDK_MOD1_MASK) {
874 sp_ddc_dilate (dc, desktop->dt2doc(motion_dt), event->motion.state & GDK_SHIFT_MASK? true : false);
875 dc->has_dilated = true;
876 // it's slow, so prevent clogging up with events
877 gobble_motion_events(GDK_BUTTON1_MASK);
878 return TRUE;
879 }
882 // for hatching:
883 double hatch_dist = 0;
884 NR::Point hatch_unit_vector(0,0);
885 NR::Point nearest(0,0);
886 NR::Point pointer(0,0);
887 NR::Matrix motion_to_curve(NR::identity());
889 if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
891 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
892 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
893 // One item selected, and it's a path;
894 // let's try to track it as a guide
896 if (selected != dc->hatch_item) {
897 dc->hatch_item = selected;
898 if (dc->hatch_livarot_path)
899 delete dc->hatch_livarot_path;
900 dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
901 dc->hatch_livarot_path->ConvertWithBackData(0.01);
902 }
904 // calculate pointer point in the guide item's coords
905 motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
906 pointer = motion_dt * motion_to_curve;
908 // calculate the nearest point on the guide path
909 NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
910 nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
913 // distance from pointer to nearest
914 hatch_dist = NR::L2(pointer - nearest);
915 // unit-length vector
916 hatch_unit_vector = (pointer - nearest)/hatch_dist;
918 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
919 } else {
920 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
921 }
922 }
924 if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
925 dc->dragging = TRUE;
927 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
929 #define SPEED_ELEMENTS 12
930 #define SPEED_MIN 0.12
931 #define SPEED_NORMAL 0.65
933 // speed is the movement of the nearest point along the guide path, divided by
934 // the movement of the pointer at the same period; it is averaged for the last
935 // SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed
936 // is about 1, i.e. the nearest point on the path is moved by about the same
937 // distance as the pointer. If the speed starts to decrease, we are losing
938 // contact with the guide; if it drops below SPEED_MIN, we are on our own and
939 // not attracted to guide anymore. Most often this happens when you have
940 // tracked to the end of a guide calligraphic stroke and keep moving
941 // further. We try to handle this situation gracefully: not stick with the
942 // guide forever but let go of it smoothly and without sharp jerks (non-zero
943 // mass recommended; with zero mass, jerks are still quite noticeable).
945 double speed = 1;
946 if (NR::L2(dc->hatch_last_nearest) != 0) {
947 // the distance nearest moved since the last motion event
948 double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
949 // the distance pointer moved since the last motion event
950 double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
951 // store them in stacks limited to SPEED_ELEMENTS
952 dc->hatch_nearest_past.push_front(nearest_moved);
953 if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
954 dc->hatch_nearest_past.pop_back();
955 dc->hatch_pointer_past.push_front(pointer_moved);
956 if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
957 dc->hatch_pointer_past.pop_back();
959 // If the stacks are full,
960 if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
961 // calculate the sums of all stored movements
962 double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
963 double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
964 // and divide to get the speed
965 speed = nearest_sum/pointer_sum;
966 //g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed);
967 }
968 }
970 if ( dc->hatch_escaped // already escaped, do not reattach
971 || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
972 || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
973 ) {
974 // We are NOT attracted to the guide!
976 //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);
978 // Remember hatch_escaped so we don't get
979 // attracted again until the end of this stroke
980 dc->hatch_escaped = true;
982 } else {
984 // Calculate angle cosine of this vector-to-guide and all past vectors
985 // summed, to detect if we accidentally flipped to the other side of the
986 // guide
987 double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
988 dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
990 if (dc->hatch_spacing != 0) { // spacing was already set
991 double target;
992 if (speed > SPEED_NORMAL) {
993 // all ok, strictly obey the spacing
994 target = dc->hatch_spacing;
995 } else {
996 // looks like we're starting to lose speed,
997 // so _gradually_ let go attraction to prevent jerks
998 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
999 }
1000 if (!isNaN(dot) && dot < -0.5) {// flip
1001 target = -target;
1002 }
1004 // This is the track pointer that we will use instead of the real one
1005 NR::Point new_pointer = nearest + target * hatch_unit_vector;
1007 // some limited feedback: allow persistent pulling to slightly change
1008 // the spacing
1009 dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
1011 // return it to the desktop coords
1012 motion_dt = new_pointer * motion_to_curve.inverse();
1014 } else {
1015 // this is the first motion event, set the dist
1016 dc->hatch_spacing = hatch_dist;
1017 }
1019 // remember last points
1020 dc->hatch_last_pointer = pointer;
1021 dc->hatch_last_nearest = nearest;
1022 dc->hatch_vector_accumulated += (pointer - nearest);
1023 }
1025 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
1027 } else {
1028 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
1029 }
1031 if (!sp_dyna_draw_apply(dc, motion_dt)) {
1032 ret = TRUE;
1033 break;
1034 }
1036 if ( dc->cur != dc->last ) {
1037 sp_dyna_draw_brush(dc);
1038 g_assert( dc->npoints > 0 );
1039 fit_and_split(dc, FALSE);
1040 }
1041 ret = TRUE;
1042 }
1044 // Draw the hatching circle if necessary
1045 if (event->motion.state & GDK_CONTROL_MASK) {
1046 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
1047 // Haven't set spacing yet: gray, center free, update radius live
1048 NR::Point c = desktop->w2d(motion_w);
1049 NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * 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), 0x7f7f7fff, 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: green, center snapped, fixed radius
1055 NR::Point c = motion_dt;
1056 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1057 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1058 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1059 sp_canvas_item_show(dc->hatch_area);
1060 } else if (dc->dragging && dc->hatch_escaped) {
1061 // Tracking escaped: red, center free, fixed radius
1062 NR::Point c = desktop->w2d(motion_w);
1063 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1065 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1066 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1067 sp_canvas_item_show(dc->hatch_area);
1068 } else {
1069 // Not drawing but spacing set: gray, center snapped, fixed radius
1070 NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
1071 if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
1072 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1073 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1074 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1075 sp_canvas_item_show(dc->hatch_area);
1076 }
1077 }
1078 } else {
1079 sp_canvas_item_hide(dc->hatch_area);
1080 }
1081 }
1082 break;
1085 case GDK_BUTTON_RELEASE:
1086 {
1087 NR::Point const motion_w(event->button.x, event->button.y);
1088 NR::Point const motion_dt(desktop->w2d(motion_w));
1090 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
1091 sp_canvas_end_forced_full_redraws(desktop->canvas);
1092 dc->is_drawing = false;
1094 if ( dc->is_dilating && event->button.button == 1 ) {
1095 if (!dc->has_dilated) {
1096 // if we did not rub, do a light tap
1097 dc->pressure = 0.03;
1098 sp_ddc_dilate (dc, desktop->dt2doc(motion_dt), event->button.state & GDK_SHIFT_MASK? true : false);
1099 }
1100 dc->is_dilating = false;
1101 dc->has_dilated = false;
1102 sp_document_done(sp_desktop_document(SP_EVENT_CONTEXT(dc)->desktop),
1103 SP_VERB_CONTEXT_CALLIGRAPHIC,
1104 (event->button.state & GDK_SHIFT_MASK ? _("Thicken paths") : _("Thin paths")));
1105 ret = TRUE;
1107 } else if ( dc->dragging && event->button.button == 1 ) {
1108 dc->dragging = FALSE;
1110 sp_dyna_draw_apply(dc, motion_dt);
1112 /* Remove all temporary line segments */
1113 while (dc->segments) {
1114 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
1115 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
1116 }
1118 /* Create object */
1119 fit_and_split(dc, TRUE);
1120 accumulate_calligraphic(dc);
1121 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
1123 /* reset accumulated curve */
1124 sp_curve_reset(dc->accumulated);
1126 clear_current(dc);
1127 if (dc->repr) {
1128 dc->repr = NULL;
1129 }
1131 if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
1132 if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
1133 dc->hatch_last_nearest = NR::Point(0,0);
1134 dc->hatch_last_pointer = NR::Point(0,0);
1135 dc->hatch_vector_accumulated = NR::Point(0,0);
1136 dc->hatch_escaped = false;
1137 dc->hatch_item = NULL;
1138 dc->hatch_livarot_path = NULL;
1140 if (dc->hatch_spacing != 0 && !dc->keep_selected) {
1141 // we do not select the newly drawn path, so increase spacing by step
1142 if (dc->hatch_spacing_step == 0) {
1143 dc->hatch_spacing_step = dc->hatch_spacing;
1144 }
1145 dc->hatch_spacing += dc->hatch_spacing_step;
1146 }
1148 dc->_message_context->clear();
1149 ret = TRUE;
1150 }
1151 break;
1152 }
1154 case GDK_KEY_PRESS:
1155 switch (get_group0_keyval (&event->key)) {
1156 case GDK_Up:
1157 case GDK_KP_Up:
1158 if (!MOD__CTRL_ONLY) {
1159 dc->angle += 5.0;
1160 if (dc->angle > 90.0)
1161 dc->angle = 90.0;
1162 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1163 ret = TRUE;
1164 }
1165 break;
1166 case GDK_Down:
1167 case GDK_KP_Down:
1168 if (!MOD__CTRL_ONLY) {
1169 dc->angle -= 5.0;
1170 if (dc->angle < -90.0)
1171 dc->angle = -90.0;
1172 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1173 ret = TRUE;
1174 }
1175 break;
1176 case GDK_Right:
1177 case GDK_KP_Right:
1178 if (!MOD__CTRL_ONLY) {
1179 dc->width += 0.01;
1180 if (dc->width > 1.0)
1181 dc->width = 1.0;
1182 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
1183 sp_ddc_update_cursors(dc);
1184 ret = TRUE;
1185 }
1186 break;
1187 case GDK_Left:
1188 case GDK_KP_Left:
1189 if (!MOD__CTRL_ONLY) {
1190 dc->width -= 0.01;
1191 if (dc->width < 0.01)
1192 dc->width = 0.01;
1193 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1194 sp_ddc_update_cursors(dc);
1195 ret = TRUE;
1196 }
1197 break;
1198 case GDK_Home:
1199 case GDK_KP_Home:
1200 dc->width = 0.01;
1201 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1202 sp_ddc_update_cursors(dc);
1203 ret = TRUE;
1204 break;
1205 case GDK_End:
1206 case GDK_KP_End:
1207 dc->width = 1.0;
1208 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1209 sp_ddc_update_cursors(dc);
1210 ret = TRUE;
1211 break;
1212 case GDK_x:
1213 case GDK_X:
1214 if (MOD__ALT_ONLY) {
1215 desktop->setToolboxFocusTo ("altx-calligraphy");
1216 ret = TRUE;
1217 }
1218 break;
1219 case GDK_Escape:
1220 if (dc->is_drawing) {
1221 // if drawing, cancel, otherwise pass it up for deselecting
1222 calligraphic_cancel (dc);
1223 ret = TRUE;
1224 }
1225 break;
1226 case GDK_z:
1227 case GDK_Z:
1228 if (MOD__CTRL_ONLY && dc->is_drawing) {
1229 // if drawing, cancel, otherwise pass it up for undo
1230 calligraphic_cancel (dc);
1231 ret = TRUE;
1232 }
1233 break;
1234 case GDK_Meta_L:
1235 case GDK_Meta_R:
1236 event_context->cursor_shape = cursor_thicken_xpm;
1237 sp_event_context_update_cursor(event_context);
1238 break;
1239 case GDK_Alt_L:
1240 case GDK_Alt_R:
1241 if (MOD__SHIFT) {
1242 event_context->cursor_shape = cursor_thicken_xpm;
1243 sp_event_context_update_cursor(event_context);
1244 } else {
1245 event_context->cursor_shape = cursor_thin_xpm;
1246 sp_event_context_update_cursor(event_context);
1247 }
1248 break;
1249 case GDK_Shift_L:
1250 case GDK_Shift_R:
1251 if (MOD__ALT) {
1252 event_context->cursor_shape = cursor_thicken_xpm;
1253 sp_event_context_update_cursor(event_context);
1254 }
1255 break;
1256 default:
1257 break;
1258 }
1259 break;
1261 case GDK_KEY_RELEASE:
1262 switch (get_group0_keyval(&event->key)) {
1263 case GDK_Control_L:
1264 case GDK_Control_R:
1265 dc->_message_context->clear();
1266 dc->hatch_spacing = 0;
1267 dc->hatch_spacing_step = 0;
1268 break;
1269 case GDK_Alt_L:
1270 case GDK_Alt_R:
1271 event_context->cursor_shape = cursor_calligraphy_xpm;
1272 sp_event_context_update_cursor(event_context);
1273 break;
1274 case GDK_Shift_L:
1275 case GDK_Shift_R:
1276 if (MOD__ALT) {
1277 event_context->cursor_shape = cursor_thin_xpm;
1278 sp_event_context_update_cursor(event_context);
1279 }
1280 break;
1281 case GDK_Meta_L:
1282 case GDK_Meta_R:
1283 event_context->cursor_shape = cursor_calligraphy_xpm;
1284 sp_event_context_update_cursor(event_context);
1285 break;
1286 default:
1287 break;
1288 }
1290 default:
1291 break;
1292 }
1294 if (!ret) {
1295 if (((SPEventContextClass *) parent_class)->root_handler) {
1296 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1297 }
1298 }
1300 return ret;
1301 }
1304 static void
1305 clear_current(SPDynaDrawContext *dc)
1306 {
1307 /* reset bpath */
1308 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1309 /* reset curve */
1310 sp_curve_reset(dc->currentcurve);
1311 sp_curve_reset(dc->cal1);
1312 sp_curve_reset(dc->cal2);
1313 /* reset points */
1314 dc->npoints = 0;
1315 }
1317 static void
1318 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1319 {
1320 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1322 if (!sp_curve_empty(dc->accumulated)) {
1323 NArtBpath *abp;
1324 gchar *str;
1326 if (!dc->repr) {
1327 /* Create object */
1328 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1329 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1331 /* Set style */
1332 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1334 dc->repr = repr;
1336 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1337 Inkscape::GC::release(dc->repr);
1338 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1339 item->updateRepr();
1340 }
1341 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1342 str = sp_svg_write_path(abp);
1343 g_assert( str != NULL );
1344 g_free(abp);
1345 dc->repr->setAttribute("d", str);
1346 g_free(str);
1348 if (unionize) {
1349 sp_desktop_selection(desktop)->add(dc->repr);
1350 sp_selected_path_union_skip_undo();
1351 } else {
1352 if (dc->keep_selected) {
1353 sp_desktop_selection(desktop)->set(dc->repr);
1354 }
1355 }
1357 } else {
1358 if (dc->repr) {
1359 sp_repr_unparent(dc->repr);
1360 }
1361 dc->repr = NULL;
1362 }
1364 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1365 _("Draw calligraphic stroke"));
1366 }
1368 static void
1369 add_cap(SPCurve *curve,
1370 NR::Point const &pre, NR::Point const &from,
1371 NR::Point const &to, NR::Point const &post,
1372 double rounding)
1373 {
1374 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1375 double mag = NR::L2(vel);
1377 NR::Point v_in = from - pre;
1378 double mag_in = NR::L2(v_in);
1379 if ( mag_in > DYNA_EPSILON ) {
1380 v_in = mag * v_in / mag_in;
1381 } else {
1382 v_in = NR::Point(0, 0);
1383 }
1385 NR::Point v_out = to - post;
1386 double mag_out = NR::L2(v_out);
1387 if ( mag_out > DYNA_EPSILON ) {
1388 v_out = mag * v_out / mag_out;
1389 } else {
1390 v_out = NR::Point(0, 0);
1391 }
1393 if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1394 sp_curve_curveto(curve, from + v_in, to + v_out, to);
1395 }
1396 }
1398 static void
1399 accumulate_calligraphic(SPDynaDrawContext *dc)
1400 {
1401 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1402 sp_curve_reset(dc->accumulated); /* Is this required ?? */
1403 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1405 g_assert(dc->cal1->end > 1);
1406 g_assert(rev_cal2->end > 1);
1407 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1408 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1409 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1410 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1411 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1412 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1414 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1416 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);
1418 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1420 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);
1422 sp_curve_closepath(dc->accumulated);
1424 sp_curve_unref(rev_cal2);
1426 sp_curve_reset(dc->cal1);
1427 sp_curve_reset(dc->cal2);
1428 }
1429 }
1431 static double square(double const x)
1432 {
1433 return x * x;
1434 }
1436 static void
1437 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1438 {
1439 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1441 #ifdef DYNA_DRAW_VERBOSE
1442 g_print("[F&S:R=%c]", release?'T':'F');
1443 #endif
1445 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1446 return; // just clicked
1448 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1449 #define BEZIER_SIZE 4
1450 #define BEZIER_MAX_BEZIERS 8
1451 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1453 #ifdef DYNA_DRAW_VERBOSE
1454 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1455 dc->npoints, release ? "TRUE" : "FALSE");
1456 #endif
1458 /* Current calligraphic */
1459 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1460 /* dc->npoints > 0 */
1461 /* g_print("calligraphics(1|2) reset\n"); */
1462 sp_curve_reset(dc->cal1);
1463 sp_curve_reset(dc->cal2);
1465 sp_curve_moveto(dc->cal1, dc->point1[0]);
1466 sp_curve_moveto(dc->cal2, dc->point2[0]);
1467 }
1469 NR::Point b1[BEZIER_MAX_LENGTH];
1470 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1471 tolerance_sq, BEZIER_MAX_BEZIERS);
1472 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1474 NR::Point b2[BEZIER_MAX_LENGTH];
1475 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1476 tolerance_sq, BEZIER_MAX_BEZIERS);
1477 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1479 if ( nb1 != -1 && nb2 != -1 ) {
1480 /* Fit and draw and reset state */
1481 #ifdef DYNA_DRAW_VERBOSE
1482 g_print("nb1:%d nb2:%d\n", nb1, nb2);
1483 #endif
1484 /* CanvasShape */
1485 if (! release) {
1486 sp_curve_reset(dc->currentcurve);
1487 sp_curve_moveto(dc->currentcurve, b1[0]);
1488 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1489 sp_curve_curveto(dc->currentcurve, bp1[1],
1490 bp1[2], bp1[3]);
1491 }
1492 sp_curve_lineto(dc->currentcurve,
1493 b2[BEZIER_SIZE*(nb2-1) + 3]);
1494 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1495 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1496 }
1497 // FIXME: dc->segments is always NULL at this point??
1498 if (!dc->segments) { // first segment
1499 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1500 }
1501 sp_curve_closepath(dc->currentcurve);
1502 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1503 }
1505 /* Current calligraphic */
1506 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1507 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1508 }
1509 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1510 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1511 }
1512 } else {
1513 /* fixme: ??? */
1514 #ifdef DYNA_DRAW_VERBOSE
1515 g_print("[fit_and_split] failed to fit-cubic.\n");
1516 #endif
1517 draw_temporary_box(dc);
1519 for (gint i = 1; i < dc->npoints; i++) {
1520 sp_curve_lineto(dc->cal1, dc->point1[i]);
1521 }
1522 for (gint i = 1; i < dc->npoints; i++) {
1523 sp_curve_lineto(dc->cal2, dc->point2[i]);
1524 }
1525 }
1527 /* Fit and draw and copy last point */
1528 #ifdef DYNA_DRAW_VERBOSE
1529 g_print("[%d]Yup\n", dc->npoints);
1530 #endif
1531 if (!release) {
1532 g_assert(!sp_curve_empty(dc->currentcurve));
1534 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1535 SP_TYPE_CANVAS_BPATH,
1536 NULL);
1537 SPCurve *curve = sp_curve_copy(dc->currentcurve);
1538 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1539 sp_curve_unref(curve);
1541 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1542 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1543 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1544 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1545 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1546 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1547 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1548 //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);
1549 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1550 /* fixme: Cannot we cascade it to root more clearly? */
1551 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1553 dc->segments = g_slist_prepend(dc->segments, cbp);
1554 }
1556 dc->point1[0] = dc->point1[dc->npoints - 1];
1557 dc->point2[0] = dc->point2[dc->npoints - 1];
1558 dc->npoints = 1;
1559 } else {
1560 draw_temporary_box(dc);
1561 }
1562 }
1564 static void
1565 draw_temporary_box(SPDynaDrawContext *dc)
1566 {
1567 sp_curve_reset(dc->currentcurve);
1569 sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1570 for (gint i = dc->npoints-2; i >= 0; i--) {
1571 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1572 }
1573 for (gint i = 0; i < dc->npoints; i++) {
1574 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1575 }
1576 if (dc->npoints >= 2) {
1577 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);
1578 }
1580 sp_curve_closepath(dc->currentcurve);
1581 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1582 }
1584 /*
1585 Local Variables:
1586 mode:c++
1587 c-file-style:"stroustrup"
1588 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1589 indent-tabs-mode:nil
1590 fill-column:99
1591 End:
1592 */
1593 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :