3b5e94d2846245ec1182b3b2dbc44b42c0e4c306
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-shape.h"
62 #include "sp-path.h"
63 #include "sp-text.h"
64 #include "display/canvas-bpath.h"
65 #include "display/canvas-arena.h"
66 #include "livarot/Shape.h"
67 #include "isnan.h"
69 #include "dyna-draw-context.h"
71 #define DDC_RED_RGBA 0xff0000ff
73 #define TOLERANCE_CALLIGRAPHIC 0.1
75 #define DYNA_EPSILON 0.5e-6
76 #define DYNA_EPSILON_START 0.5e-2
77 #define DYNA_VEL_START 1e-5
79 #define DYNA_MIN_WIDTH 1.0e-6
81 #define DRAG_MIN 0.0
82 #define DRAG_DEFAULT 1.0
83 #define DRAG_MAX 1.0
85 // FIXME: move it to some shared file to be reused by both calligraphy and dropper
86 #define C1 0.552
87 static NArtBpath const hatch_area_circle[] = {
88 { NR_MOVETO, 0, 0, 0, 0, -1, 0 },
89 { NR_CURVETO, -1, C1, -C1, 1, 0, 1 },
90 { NR_CURVETO, C1, 1, 1, C1, 1, 0 },
91 { NR_CURVETO, 1, -C1, C1, -1, 0, -1 },
92 { NR_CURVETO, -C1, -1, -1, -C1, -1, 0 },
93 { NR_END, 0, 0, 0, 0, 0, 0 }
94 };
95 #undef C1
98 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
99 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
100 static void sp_dyna_draw_context_dispose(GObject *object);
102 static void sp_dyna_draw_context_setup(SPEventContext *ec);
103 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
104 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
106 static void clear_current(SPDynaDrawContext *dc);
107 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
108 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
109 static void accumulate_calligraphic(SPDynaDrawContext *dc);
111 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
113 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
114 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
115 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
116 static void draw_temporary_box(SPDynaDrawContext *dc);
119 static SPEventContextClass *parent_class;
121 GtkType
122 sp_dyna_draw_context_get_type(void)
123 {
124 static GType type = 0;
125 if (!type) {
126 GTypeInfo info = {
127 sizeof(SPDynaDrawContextClass),
128 NULL, NULL,
129 (GClassInitFunc) sp_dyna_draw_context_class_init,
130 NULL, NULL,
131 sizeof(SPDynaDrawContext),
132 4,
133 (GInstanceInitFunc) sp_dyna_draw_context_init,
134 NULL, /* value_table */
135 };
136 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
137 }
138 return type;
139 }
141 static void
142 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
143 {
144 GObjectClass *object_class = (GObjectClass *) klass;
145 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
147 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
149 object_class->dispose = sp_dyna_draw_context_dispose;
151 event_context_class->setup = sp_dyna_draw_context_setup;
152 event_context_class->set = sp_dyna_draw_context_set;
153 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
154 }
156 static void
157 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
158 {
159 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
161 event_context->cursor_shape = cursor_calligraphy_xpm;
162 event_context->hot_x = 4;
163 event_context->hot_y = 4;
165 ddc->accumulated = NULL;
166 ddc->segments = NULL;
167 ddc->currentcurve = NULL;
168 ddc->currentshape = NULL;
169 ddc->npoints = 0;
170 ddc->cal1 = NULL;
171 ddc->cal2 = NULL;
172 ddc->repr = NULL;
174 /* DynaDraw values */
175 ddc->cur = NR::Point(0,0);
176 ddc->last = NR::Point(0,0);
177 ddc->vel = NR::Point(0,0);
178 ddc->vel_max = 0;
179 ddc->acc = NR::Point(0,0);
180 ddc->ang = NR::Point(0,0);
181 ddc->del = NR::Point(0,0);
183 /* attributes */
184 ddc->dragging = FALSE;
186 ddc->mass = 0.3;
187 ddc->drag = DRAG_DEFAULT;
188 ddc->angle = 30.0;
189 ddc->width = 0.2;
190 ddc->pressure = DDC_DEFAULT_PRESSURE;
192 ddc->vel_thin = 0.1;
193 ddc->flatness = 0.9;
194 ddc->cap_rounding = 0.0;
196 ddc->abs_width = false;
197 ddc->keep_selected = true;
199 ddc->hatch_spacing = 0;
200 new (&ddc->hatch_pointer_past) std::list<double>();
201 new (&ddc->hatch_nearest_past) std::list<double>();
202 ddc->hatch_last_nearest = NR::Point(0,0);
203 ddc->hatch_last_pointer = NR::Point(0,0);
204 ddc->hatch_vector_accumulated = NR::Point(0,0);
205 ddc->hatch_escaped = false;
206 ddc->hatch_area = NULL;
207 ddc->hatch_item = NULL;
208 ddc->hatch_livarot_path = NULL;
210 ddc->trace_bg = false;
212 ddc->is_dilating = false;
213 }
215 static void
216 sp_dyna_draw_context_dispose(GObject *object)
217 {
218 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
220 if (ddc->hatch_area) {
221 gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
222 ddc->hatch_area = NULL;
223 }
225 if (ddc->dilate_area) {
226 gtk_object_destroy(GTK_OBJECT(ddc->dilate_area));
227 ddc->dilate_area = NULL;
228 }
230 if (ddc->accumulated) {
231 ddc->accumulated = sp_curve_unref(ddc->accumulated);
232 }
234 while (ddc->segments) {
235 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
236 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
237 }
239 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
240 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
241 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
243 if (ddc->currentshape) {
244 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
245 ddc->currentshape = NULL;
246 }
248 if (ddc->_message_context) {
249 delete ddc->_message_context;
250 }
252 G_OBJECT_CLASS(parent_class)->dispose(object);
254 ddc->hatch_pointer_past.~list();
255 ddc->hatch_nearest_past.~list();
256 }
258 static void
259 sp_dyna_draw_context_setup(SPEventContext *ec)
260 {
261 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
263 if (((SPEventContextClass *) parent_class)->setup)
264 ((SPEventContextClass *) parent_class)->setup(ec);
266 ddc->accumulated = sp_curve_new_sized(32);
267 ddc->currentcurve = sp_curve_new_sized(4);
269 ddc->cal1 = sp_curve_new_sized(32);
270 ddc->cal2 = sp_curve_new_sized(32);
272 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
273 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
274 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
275 /* fixme: Cannot we cascade it to root more clearly? */
276 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
278 {
279 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
280 ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
281 sp_curve_unref(c);
282 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
283 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
284 sp_canvas_item_hide(ddc->hatch_area);
285 }
287 {
288 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
289 ddc->dilate_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
290 sp_curve_unref(c);
291 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->dilate_area), 0x00000000,(SPWindRule)0);
292 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->dilate_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
293 sp_canvas_item_hide(ddc->dilate_area);
294 }
296 sp_event_context_read(ec, "mass");
297 sp_event_context_read(ec, "wiggle");
298 sp_event_context_read(ec, "angle");
299 sp_event_context_read(ec, "width");
300 sp_event_context_read(ec, "thinning");
301 sp_event_context_read(ec, "tremor");
302 sp_event_context_read(ec, "flatness");
303 sp_event_context_read(ec, "tracebackground");
304 sp_event_context_read(ec, "usepressure");
305 sp_event_context_read(ec, "usetilt");
306 sp_event_context_read(ec, "abs_width");
307 sp_event_context_read(ec, "keep_selected");
308 sp_event_context_read(ec, "cap_rounding");
310 ddc->is_drawing = false;
312 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
313 }
315 static void
316 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
317 {
318 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
320 if (!strcmp(key, "mass")) {
321 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
322 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
323 } else if (!strcmp(key, "wiggle")) {
324 double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
325 ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
326 } else if (!strcmp(key, "angle")) {
327 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
328 ddc->angle = CLAMP (dval, -90, 90);
329 } else if (!strcmp(key, "width")) {
330 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
331 ddc->width = CLAMP(dval, -1000.0, 1000.0);
332 } else if (!strcmp(key, "thinning")) {
333 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
334 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
335 } else if (!strcmp(key, "tremor")) {
336 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
337 ddc->tremor = CLAMP(dval, 0.0, 1.0);
338 } else if (!strcmp(key, "flatness")) {
339 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
340 ddc->flatness = CLAMP(dval, 0, 1.0);
341 } else if (!strcmp(key, "tracebackground")) {
342 ddc->trace_bg = (val && strcmp(val, "0"));
343 } else if (!strcmp(key, "usepressure")) {
344 ddc->usepressure = (val && strcmp(val, "0"));
345 } else if (!strcmp(key, "usetilt")) {
346 ddc->usetilt = (val && strcmp(val, "0"));
347 } else if (!strcmp(key, "abs_width")) {
348 ddc->abs_width = (val && strcmp(val, "0"));
349 } else if (!strcmp(key, "keep_selected")) {
350 ddc->keep_selected = (val && strcmp(val, "0"));
351 } else if (!strcmp(key, "cap_rounding")) {
352 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
353 }
355 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
356 }
358 static double
359 flerp(double f0, double f1, double p)
360 {
361 return f0 + ( f1 - f0 ) * p;
362 }
364 /* Get normalized point */
365 static NR::Point
366 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
367 {
368 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
369 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
370 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
371 }
373 /* Get view point */
374 static NR::Point
375 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
376 {
377 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
378 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
379 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
380 }
382 static void
383 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
384 {
385 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
386 dc->vel = NR::Point(0,0);
387 dc->vel_max = 0;
388 dc->acc = NR::Point(0,0);
389 dc->ang = NR::Point(0,0);
390 dc->del = NR::Point(0,0);
391 }
393 static void
394 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
395 {
396 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
397 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
398 else
399 dc->pressure = DDC_DEFAULT_PRESSURE;
401 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
402 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
403 else
404 dc->xtilt = DDC_DEFAULT_TILT;
406 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
407 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
408 else
409 dc->ytilt = DDC_DEFAULT_TILT;
410 }
413 static gboolean
414 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
415 {
416 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
418 /* Calculate mass and drag */
419 double const mass = flerp(1.0, 160.0, dc->mass);
420 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
422 /* Calculate force and acceleration */
423 NR::Point force = n - dc->cur;
425 // If force is below the absolute threshold DYNA_EPSILON,
426 // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
427 // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
428 // discard this move.
429 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
430 // especially bothersome at the start of the stroke where we don't yet have the inertia to
431 // smooth them out.
432 if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
433 return FALSE;
434 }
436 dc->acc = force / mass;
438 /* Calculate new velocity */
439 dc->vel += dc->acc;
441 if (NR::L2(dc->vel) > dc->vel_max)
442 dc->vel_max = NR::L2(dc->vel);
444 /* Calculate angle of drawing tool */
446 double a1;
447 if (dc->usetilt) {
448 // 1a. calculate nib angle from input device tilt:
449 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
451 if (length > 0) {
452 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
453 a1 = atan2(ang1);
454 }
455 else
456 a1 = 0.0;
457 }
458 else {
459 // 1b. fixed dc->angle (absolutely flat nib):
460 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
461 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
462 a1 = atan2(ang1);
463 }
465 // 2. perpendicular to dc->vel (absolutely non-flat nib):
466 gdouble const mag_vel = NR::L2(dc->vel);
467 if ( mag_vel < DYNA_EPSILON ) {
468 return FALSE;
469 }
470 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
472 // 3. Average them using flatness parameter:
473 // calculate angles
474 double a2 = atan2(ang2);
475 // flip a2 to force it to be in the same half-circle as a1
476 bool flipped = false;
477 if (fabs (a2-a1) > 0.5*M_PI) {
478 a2 += M_PI;
479 flipped = true;
480 }
481 // normalize a2
482 if (a2 > M_PI)
483 a2 -= 2*M_PI;
484 if (a2 < -M_PI)
485 a2 += 2*M_PI;
486 // find the flatness-weighted bisector angle, unflip if a2 was flipped
487 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
488 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
490 // Try to detect a sudden flip when the new angle differs too much from the previous for the
491 // current velocity; in that case discard this move
492 double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
493 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
494 return FALSE;
495 }
497 // convert to point
498 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
500 // 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);
502 /* Apply drag */
503 dc->vel *= 1.0 - drag;
505 /* Update position */
506 dc->last = dc->cur;
507 dc->cur += dc->vel;
509 return TRUE;
510 }
512 static void
513 sp_dyna_draw_brush(SPDynaDrawContext *dc)
514 {
515 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
517 // How much velocity thins strokestyle
518 double vel_thin = flerp (0, 160, dc->vel_thin);
520 // Influence of pressure on thickness
521 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
523 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
524 // drag)
525 NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
526 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
528 double trace_thick = 1;
529 if (dc->trace_bg) {
530 // pick single pixel
531 NRPixBlock pb;
532 int x = (int) floor(brush_w[NR::X]);
533 int y = (int) floor(brush_w[NR::Y]);
534 nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
535 sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
536 const unsigned char *s = NR_PIXBLOCK_PX(&pb);
537 double R = s[0] / 255.0;
538 double G = s[1] / 255.0;
539 double B = s[2] / 255.0;
540 double A = s[3] / 255.0;
541 double max = MAX (MAX (R, G), B);
542 double min = MIN (MIN (R, G), B);
543 double L = A * (max + min)/2 + (1 - A); // blend with white bg
544 trace_thick = 1 - L;
545 //g_print ("L %g thick %g\n", L, trace_thick);
546 }
548 double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
550 double tremble_left = 0, tremble_right = 0;
551 if (dc->tremor > 0) {
552 // obtain two normally distributed random variables, using polar Box-Muller transform
553 double x1, x2, w, y1, y2;
554 do {
555 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
556 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
557 w = x1 * x1 + x2 * x2;
558 } while ( w >= 1.0 );
559 w = sqrt( (-2.0 * log( w ) ) / w );
560 y1 = x1 * w;
561 y2 = x2 * w;
563 // deflect both left and right edges randomly and independently, so that:
564 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
565 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
566 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
567 // comparatively smooth and slow ones excessively jittery
568 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
569 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
570 }
572 if ( width < 0.02 * dc->width ) {
573 width = 0.02 * dc->width;
574 }
576 double dezoomify_factor = 0.05 * 1000;
577 if (!dc->abs_width) {
578 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
579 }
581 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
582 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
584 dc->point1[dc->npoints] = brush + del_left;
585 dc->point2[dc->npoints] = brush - del_right;
587 dc->del = 0.5*(del_left + del_right);
589 dc->npoints++;
590 }
592 double
593 get_dilate_radius (SPDynaDrawContext *dc)
594 {
595 // 10 times the pen width:
596 return 500 * dc->width/SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
597 }
599 double
600 get_dilate_force (SPDynaDrawContext *dc)
601 {
602 double force = 4 * dc->pressure/SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
603 if (force > 3) {
604 force += 8 * (force - 3);
605 }
606 return force;
607 }
609 bool
610 sp_ddc_dilate (SPDynaDrawContext *dc, NR::Point p, bool expand)
611 {
612 Inkscape::Selection *selection = sp_desktop_selection(SP_EVENT_CONTEXT(dc)->desktop);
614 if (selection->isEmpty()) {
615 return false;
616 }
618 bool did = false;
619 double radius = get_dilate_radius(dc);
620 double offset = get_dilate_force(dc);
621 if (radius == 0 || offset == 0) {
622 return false;
623 }
625 for (GSList *items = g_slist_copy((GSList *) selection->itemList());
626 items != NULL;
627 items = items->next) {
629 SPItem *item = (SPItem *) items->data;
631 // only paths
632 if (!SP_IS_PATH(item))
633 continue;
635 SPCurve *curve = NULL;
636 curve = sp_shape_get_curve(SP_SHAPE(item));
637 if (curve == NULL)
638 continue;
640 // skip those paths whose bboxes are entirely out of reach with our radius
641 NR::Maybe<NR::Rect> bbox = item->getBounds(sp_item_i2doc_affine(item));
642 if (bbox) {
643 bbox->growBy(radius);
644 if (!bbox->contains(p)) {
645 continue;
646 }
647 }
649 Path *orig = Path_for_item(item, false);
650 if (orig == NULL) {
651 sp_curve_unref(curve);
652 continue;
653 }
654 Path *res = new Path;
655 res->SetBackData(false);
657 Shape *theShape = new Shape;
658 Shape *theRes = new Shape;
660 orig->ConvertWithBackData(0.05);
661 orig->Fill(theShape, 0);
663 SPCSSAttr *css = sp_repr_css_attr(SP_OBJECT_REPR(item), "style");
664 gchar const *val = sp_repr_css_property(css, "fill-rule", NULL);
665 if (val && strcmp(val, "nonzero") == 0)
666 {
667 theRes->ConvertToShape(theShape, fill_nonZero);
668 }
669 else if (val && strcmp(val, "evenodd") == 0)
670 {
671 theRes->ConvertToShape(theShape, fill_oddEven);
672 }
673 else
674 {
675 theRes->ConvertToShape(theShape, fill_nonZero);
676 }
678 bool did_this = false;
679 NR::Matrix i2doc(sp_item_i2doc_affine(item));
680 if (theShape->MakeOffset(theRes,
681 expand? offset : -offset,
682 join_straight, butt_straight,
683 true, p[NR::X], p[NR::Y], radius, &i2doc) == 0) // 0 means the shape was actually changed
684 did_this = true;
686 // the rest only makes sense if we actually changed the path
687 if (did_this) {
688 theRes->ConvertToShape(theShape, fill_positive);
690 res->Reset();
691 theRes->ConvertToForme(res);
693 if (offset >= 0.5)
694 {
695 res->ConvertEvenLines(0.5);
696 res->Simplify(0.5);
697 }
698 else
699 {
700 res->ConvertEvenLines(0.5*offset);
701 res->Simplify(0.5 * offset);
702 }
704 sp_curve_unref(curve);
705 if (res->descr_cmd.size() > 1) {
706 gchar *str = res->svg_dump_path();
707 SP_OBJECT_REPR(item)->setAttribute("d", str);
708 g_free(str);
709 } else {
710 // TODO: if there's 0 or 1 node left, delete this path altogether
711 }
712 }
714 delete theShape;
715 delete theRes;
716 delete orig;
717 delete res;
719 if (did_this)
720 did = true;
721 }
723 return did;
724 }
726 void
727 sp_ddc_update_cursors (SPDynaDrawContext *dc)
728 {
729 if (dc->is_dilating) {
730 double radius = get_dilate_radius(dc);
731 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(SP_EVENT_CONTEXT(dc)->desktop->point()));
732 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
733 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
734 sp_canvas_item_show(dc->dilate_area);
735 }
736 }
738 void
739 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
740 {
741 desktop->setToolboxAdjustmentValue (id, value);
742 }
744 static void
745 calligraphic_cancel(SPDynaDrawContext *dc)
746 {
747 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
748 dc->dragging = FALSE;
749 dc->is_drawing = false;
750 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
751 /* Remove all temporary line segments */
752 while (dc->segments) {
753 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
754 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
755 }
756 /* reset accumulated curve */
757 sp_curve_reset(dc->accumulated);
758 clear_current(dc);
759 if (dc->repr) {
760 dc->repr = NULL;
761 }
762 }
765 gint
766 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
767 GdkEvent *event)
768 {
769 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
770 SPDesktop *desktop = event_context->desktop;
772 gint ret = FALSE;
774 switch (event->type) {
775 case GDK_BUTTON_PRESS:
776 if ( event->button.button == 1 ) {
778 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
780 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
781 return TRUE;
782 }
784 NR::Point const button_w(event->button.x,
785 event->button.y);
786 NR::Point const button_dt(desktop->w2d(button_w));
787 sp_dyna_draw_reset(dc, button_dt);
788 sp_dyna_draw_extinput(dc, event);
789 sp_dyna_draw_apply(dc, button_dt);
790 sp_curve_reset(dc->accumulated);
791 if (dc->repr) {
792 dc->repr = NULL;
793 }
795 /* initialize first point */
796 dc->npoints = 0;
798 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
799 ( GDK_KEY_PRESS_MASK |
800 GDK_BUTTON_RELEASE_MASK |
801 GDK_POINTER_MOTION_MASK |
802 GDK_BUTTON_PRESS_MASK ),
803 NULL,
804 event->button.time);
806 ret = TRUE;
808 dc->is_drawing = true;
809 }
810 break;
811 case GDK_MOTION_NOTIFY:
812 {
813 NR::Point const motion_w(event->motion.x,
814 event->motion.y);
815 NR::Point motion_dt(desktop->w2d(motion_w));
816 sp_dyna_draw_extinput(dc, event);
818 // draw the dilating cursor
819 if (event->motion.state & GDK_MOD1_MASK) {
820 double radius = get_dilate_radius(dc);
821 NR::Matrix const sm (NR::scale(radius, radius) * NR::translate(desktop->w2d(motion_w)));
822 sp_canvas_item_affine_absolute(dc->dilate_area, sm);
823 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xff9900ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
824 sp_canvas_item_show(dc->dilate_area);
826 guint num = 0;
827 if (!desktop->selection->isEmpty()) {
828 num = g_slist_length((GSList *) desktop->selection->itemList());
829 }
830 if (num == 0) {
831 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select paths</b> to thin or thicken"));
832 } else {
833 dc->_message_context->setF(Inkscape::NORMAL_MESSAGE,
834 event->motion.state & GDK_SHIFT_MASK?
835 _("<b>Thickening %d</b> selected paths; without <b>Shift</b> to thin") :
836 _("<b>Thinning %d</b> selected paths; with <b>Shift</b> to thicken"), num);
837 }
839 } else {
840 dc->_message_context->clear();
841 sp_canvas_item_hide(dc->dilate_area);
842 }
844 // dilating:
845 if (dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) && event->motion.state & GDK_MOD1_MASK) {
846 sp_ddc_dilate (dc, desktop->dt2doc(motion_dt), event->motion.state & GDK_SHIFT_MASK? true : false);
847 dc->is_dilating = true;
848 // it's slow, so prevent clogging up with events
849 gobble_motion_events(GDK_BUTTON1_MASK);
850 return TRUE;
851 }
854 // for hatching:
855 double hatch_dist = 0;
856 NR::Point hatch_unit_vector(0,0);
857 NR::Point nearest(0,0);
858 NR::Point pointer(0,0);
859 NR::Matrix motion_to_curve(NR::identity());
861 if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
863 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
864 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
865 // One item selected, and it's a path;
866 // let's try to track it as a guide
868 if (selected != dc->hatch_item) {
869 dc->hatch_item = selected;
870 if (dc->hatch_livarot_path)
871 delete dc->hatch_livarot_path;
872 dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
873 dc->hatch_livarot_path->ConvertWithBackData(0.01);
874 }
876 // calculate pointer point in the guide item's coords
877 motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
878 pointer = motion_dt * motion_to_curve;
880 // calculate the nearest point on the guide path
881 NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
882 nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
885 // distance from pointer to nearest
886 hatch_dist = NR::L2(pointer - nearest);
887 // unit-length vector
888 hatch_unit_vector = (pointer - nearest)/hatch_dist;
890 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
891 } else {
892 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
893 }
894 }
896 if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
897 dc->dragging = TRUE;
899 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
901 #define SPEED_ELEMENTS 12
902 #define SPEED_MIN 0.12
903 #define SPEED_NORMAL 0.65
905 // speed is the movement of the nearest point along the guide path, divided by
906 // the movement of the pointer at the same period; it is averaged for the last
907 // SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed
908 // is about 1, i.e. the nearest point on the path is moved by about the same
909 // distance as the pointer. If the speed starts to decrease, we are losing
910 // contact with the guide; if it drops below SPEED_MIN, we are on our own and
911 // not attracted to guide anymore. Most often this happens when you have
912 // tracked to the end of a guide calligraphic stroke and keep moving
913 // further. We try to handle this situation gracefully: not stick with the
914 // guide forever but let go of it smoothly and without sharp jerks (non-zero
915 // mass recommended; with zero mass, jerks are still quite noticeable).
917 double speed = 1;
918 if (NR::L2(dc->hatch_last_nearest) != 0) {
919 // the distance nearest moved since the last motion event
920 double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
921 // the distance pointer moved since the last motion event
922 double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
923 // store them in stacks limited to SPEED_ELEMENTS
924 dc->hatch_nearest_past.push_front(nearest_moved);
925 if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
926 dc->hatch_nearest_past.pop_back();
927 dc->hatch_pointer_past.push_front(pointer_moved);
928 if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
929 dc->hatch_pointer_past.pop_back();
931 // If the stacks are full,
932 if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
933 // calculate the sums of all stored movements
934 double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
935 double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
936 // and divide to get the speed
937 speed = nearest_sum/pointer_sum;
938 //g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed);
939 }
940 }
942 if ( dc->hatch_escaped // already escaped, do not reattach
943 || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
944 || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
945 ) {
946 // We are NOT attracted to the guide!
948 //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);
950 // Remember hatch_escaped so we don't get
951 // attracted again until the end of this stroke
952 dc->hatch_escaped = true;
954 } else {
956 // Calculate angle cosine of this vector-to-guide and all past vectors
957 // summed, to detect if we accidentally flipped to the other side of the
958 // guide
959 double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
960 dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
962 if (dc->hatch_spacing != 0) { // spacing was already set
963 double target;
964 if (speed > SPEED_NORMAL) {
965 // all ok, strictly obey the spacing
966 target = dc->hatch_spacing;
967 } else {
968 // looks like we're starting to lose speed,
969 // so _gradually_ let go attraction to prevent jerks
970 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
971 }
972 if (!isNaN(dot) && dot < -0.5) {// flip
973 target = -target;
974 }
976 // This is the track pointer that we will use instead of the real one
977 NR::Point new_pointer = nearest + target * hatch_unit_vector;
979 // some limited feedback: allow persistent pulling to slightly change
980 // the spacing
981 dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
983 // return it to the desktop coords
984 motion_dt = new_pointer * motion_to_curve.inverse();
986 } else {
987 // this is the first motion event, set the dist
988 dc->hatch_spacing = hatch_dist;
989 }
991 // remember last points
992 dc->hatch_last_pointer = pointer;
993 dc->hatch_last_nearest = nearest;
994 dc->hatch_vector_accumulated += (pointer - nearest);
995 }
997 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
999 } else {
1000 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
1001 }
1003 if (!sp_dyna_draw_apply(dc, motion_dt)) {
1004 ret = TRUE;
1005 break;
1006 }
1008 if ( dc->cur != dc->last ) {
1009 sp_dyna_draw_brush(dc);
1010 g_assert( dc->npoints > 0 );
1011 fit_and_split(dc, FALSE);
1012 }
1013 ret = TRUE;
1014 }
1016 // Draw the hatching circle if necessary
1017 if (event->motion.state & GDK_CONTROL_MASK) {
1018 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
1019 // Haven't set spacing yet: gray, center free, update radius live
1020 NR::Point c = desktop->w2d(motion_w);
1021 NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
1022 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1023 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1024 sp_canvas_item_show(dc->hatch_area);
1025 } else if (dc->dragging && !dc->hatch_escaped) {
1026 // Tracking: green, center snapped, fixed radius
1027 NR::Point c = motion_dt;
1028 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1029 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1030 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1031 sp_canvas_item_show(dc->hatch_area);
1032 } else if (dc->dragging && dc->hatch_escaped) {
1033 // Tracking escaped: red, center free, fixed radius
1034 NR::Point c = desktop->w2d(motion_w);
1035 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1037 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1038 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1039 sp_canvas_item_show(dc->hatch_area);
1040 } else {
1041 // Not drawing but spacing set: gray, center snapped, fixed radius
1042 NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
1043 if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
1044 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
1045 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
1046 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1047 sp_canvas_item_show(dc->hatch_area);
1048 }
1049 }
1050 } else {
1051 sp_canvas_item_hide(dc->hatch_area);
1052 }
1053 }
1054 break;
1057 case GDK_BUTTON_RELEASE:
1058 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
1059 dc->is_drawing = false;
1061 if ( dc->is_dilating && event->button.button == 1 ) {
1062 dc->is_dilating = false;
1063 sp_document_done(sp_desktop_document(SP_EVENT_CONTEXT(dc)->desktop),
1064 SP_VERB_CONTEXT_CALLIGRAPHIC,
1065 (event->button.state & GDK_SHIFT_MASK ? _("Thicken paths") : _("Thin paths")));
1066 ret = TRUE;
1067 } else if ( dc->dragging && event->button.button == 1 ) {
1068 dc->dragging = FALSE;
1070 NR::Point const motion_w(event->button.x, event->button.y);
1071 NR::Point const motion_dt(desktop->w2d(motion_w));
1072 sp_dyna_draw_apply(dc, motion_dt);
1074 /* Remove all temporary line segments */
1075 while (dc->segments) {
1076 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
1077 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
1078 }
1080 /* Create object */
1081 fit_and_split(dc, TRUE);
1082 accumulate_calligraphic(dc);
1083 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
1085 /* reset accumulated curve */
1086 sp_curve_reset(dc->accumulated);
1088 clear_current(dc);
1089 if (dc->repr) {
1090 dc->repr = NULL;
1091 }
1093 if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
1094 if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
1095 dc->hatch_last_nearest = NR::Point(0,0);
1096 dc->hatch_last_pointer = NR::Point(0,0);
1097 dc->hatch_vector_accumulated = NR::Point(0,0);
1098 dc->hatch_escaped = false;
1099 dc->hatch_item = NULL;
1100 dc->hatch_livarot_path = NULL;
1102 dc->_message_context->clear();
1103 ret = TRUE;
1104 }
1105 break;
1107 case GDK_KEY_PRESS:
1108 switch (get_group0_keyval (&event->key)) {
1109 case GDK_Up:
1110 case GDK_KP_Up:
1111 if (!MOD__CTRL_ONLY) {
1112 dc->angle += 5.0;
1113 if (dc->angle > 90.0)
1114 dc->angle = 90.0;
1115 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1116 ret = TRUE;
1117 }
1118 break;
1119 case GDK_Down:
1120 case GDK_KP_Down:
1121 if (!MOD__CTRL_ONLY) {
1122 dc->angle -= 5.0;
1123 if (dc->angle < -90.0)
1124 dc->angle = -90.0;
1125 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
1126 ret = TRUE;
1127 }
1128 break;
1129 case GDK_Right:
1130 case GDK_KP_Right:
1131 if (!MOD__CTRL_ONLY) {
1132 dc->width += 0.01;
1133 if (dc->width > 1.0)
1134 dc->width = 1.0;
1135 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
1136 sp_ddc_update_cursors(dc);
1137 ret = TRUE;
1138 }
1139 break;
1140 case GDK_Left:
1141 case GDK_KP_Left:
1142 if (!MOD__CTRL_ONLY) {
1143 dc->width -= 0.01;
1144 if (dc->width < 0.01)
1145 dc->width = 0.01;
1146 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1147 sp_ddc_update_cursors(dc);
1148 ret = TRUE;
1149 }
1150 break;
1151 case GDK_Home:
1152 case GDK_KP_Home:
1153 dc->width = 0.01;
1154 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1155 sp_ddc_update_cursors(dc);
1156 ret = TRUE;
1157 break;
1158 case GDK_End:
1159 case GDK_KP_End:
1160 dc->width = 1.0;
1161 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
1162 sp_ddc_update_cursors(dc);
1163 ret = TRUE;
1164 break;
1165 case GDK_x:
1166 case GDK_X:
1167 if (MOD__ALT_ONLY) {
1168 desktop->setToolboxFocusTo ("altx-calligraphy");
1169 ret = TRUE;
1170 }
1171 break;
1172 case GDK_Escape:
1173 if (dc->is_drawing) {
1174 // if drawing, cancel, otherwise pass it up for deselecting
1175 calligraphic_cancel (dc);
1176 ret = TRUE;
1177 }
1178 break;
1179 case GDK_z:
1180 case GDK_Z:
1181 if (MOD__CTRL_ONLY && dc->is_drawing) {
1182 // if drawing, cancel, otherwise pass it up for undo
1183 calligraphic_cancel (dc);
1184 ret = TRUE;
1185 }
1186 break;
1187 case GDK_Meta_L:
1188 case GDK_Meta_R:
1189 event_context->cursor_shape = cursor_thicken_xpm;
1190 sp_event_context_update_cursor(event_context);
1191 break;
1192 case GDK_Alt_L:
1193 case GDK_Alt_R:
1194 if (MOD__SHIFT) {
1195 event_context->cursor_shape = cursor_thicken_xpm;
1196 sp_event_context_update_cursor(event_context);
1197 } else {
1198 event_context->cursor_shape = cursor_thin_xpm;
1199 sp_event_context_update_cursor(event_context);
1200 }
1201 break;
1202 case GDK_Shift_L:
1203 case GDK_Shift_R:
1204 if (MOD__ALT) {
1205 event_context->cursor_shape = cursor_thicken_xpm;
1206 sp_event_context_update_cursor(event_context);
1207 }
1208 break;
1209 default:
1210 break;
1211 }
1212 break;
1214 case GDK_KEY_RELEASE:
1215 switch (get_group0_keyval(&event->key)) {
1216 case GDK_Control_L:
1217 case GDK_Control_R:
1218 dc->_message_context->clear();
1219 dc->hatch_spacing = 0;
1220 break;
1221 case GDK_Alt_L:
1222 case GDK_Alt_R:
1223 event_context->cursor_shape = cursor_calligraphy_xpm;
1224 sp_event_context_update_cursor(event_context);
1225 break;
1226 case GDK_Shift_L:
1227 case GDK_Shift_R:
1228 if (MOD__ALT) {
1229 event_context->cursor_shape = cursor_thin_xpm;
1230 sp_event_context_update_cursor(event_context);
1231 }
1232 break;
1233 case GDK_Meta_L:
1234 case GDK_Meta_R:
1235 event_context->cursor_shape = cursor_calligraphy_xpm;
1236 sp_event_context_update_cursor(event_context);
1237 break;
1238 default:
1239 break;
1240 }
1242 default:
1243 break;
1244 }
1246 if (!ret) {
1247 if (((SPEventContextClass *) parent_class)->root_handler) {
1248 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1249 }
1250 }
1252 return ret;
1253 }
1256 static void
1257 clear_current(SPDynaDrawContext *dc)
1258 {
1259 /* reset bpath */
1260 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1261 /* reset curve */
1262 sp_curve_reset(dc->currentcurve);
1263 sp_curve_reset(dc->cal1);
1264 sp_curve_reset(dc->cal2);
1265 /* reset points */
1266 dc->npoints = 0;
1267 }
1269 static void
1270 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1271 {
1272 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1274 if (!sp_curve_empty(dc->accumulated)) {
1275 NArtBpath *abp;
1276 gchar *str;
1278 if (!dc->repr) {
1279 /* Create object */
1280 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1281 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1283 /* Set style */
1284 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1286 dc->repr = repr;
1288 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1289 Inkscape::GC::release(dc->repr);
1290 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1291 item->updateRepr();
1292 }
1293 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1294 str = sp_svg_write_path(abp);
1295 g_assert( str != NULL );
1296 g_free(abp);
1297 dc->repr->setAttribute("d", str);
1298 g_free(str);
1300 if (unionize) {
1301 sp_desktop_selection(desktop)->add(dc->repr);
1302 sp_selected_path_union_skip_undo();
1303 } else {
1304 if (dc->keep_selected) {
1305 sp_desktop_selection(desktop)->set(dc->repr);
1306 } else {
1307 sp_desktop_selection(desktop)->clear();
1308 }
1309 }
1311 } else {
1312 if (dc->repr) {
1313 sp_repr_unparent(dc->repr);
1314 }
1315 dc->repr = NULL;
1316 }
1318 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1319 _("Draw calligraphic stroke"));
1320 }
1322 static void
1323 add_cap(SPCurve *curve,
1324 NR::Point const &pre, NR::Point const &from,
1325 NR::Point const &to, NR::Point const &post,
1326 double rounding)
1327 {
1328 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1329 double mag = NR::L2(vel);
1331 NR::Point v_in = from - pre;
1332 double mag_in = NR::L2(v_in);
1333 if ( mag_in > DYNA_EPSILON ) {
1334 v_in = mag * v_in / mag_in;
1335 } else {
1336 v_in = NR::Point(0, 0);
1337 }
1339 NR::Point v_out = to - post;
1340 double mag_out = NR::L2(v_out);
1341 if ( mag_out > DYNA_EPSILON ) {
1342 v_out = mag * v_out / mag_out;
1343 } else {
1344 v_out = NR::Point(0, 0);
1345 }
1347 if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1348 sp_curve_curveto(curve, from + v_in, to + v_out, to);
1349 }
1350 }
1352 static void
1353 accumulate_calligraphic(SPDynaDrawContext *dc)
1354 {
1355 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1356 sp_curve_reset(dc->accumulated); /* Is this required ?? */
1357 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1359 g_assert(dc->cal1->end > 1);
1360 g_assert(rev_cal2->end > 1);
1361 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1362 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1363 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1364 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1365 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1366 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1368 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1370 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);
1372 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1374 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);
1376 sp_curve_closepath(dc->accumulated);
1378 sp_curve_unref(rev_cal2);
1380 sp_curve_reset(dc->cal1);
1381 sp_curve_reset(dc->cal2);
1382 }
1383 }
1385 static double square(double const x)
1386 {
1387 return x * x;
1388 }
1390 static void
1391 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1392 {
1393 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1395 #ifdef DYNA_DRAW_VERBOSE
1396 g_print("[F&S:R=%c]", release?'T':'F');
1397 #endif
1399 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1400 return; // just clicked
1402 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1403 #define BEZIER_SIZE 4
1404 #define BEZIER_MAX_BEZIERS 8
1405 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1407 #ifdef DYNA_DRAW_VERBOSE
1408 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1409 dc->npoints, release ? "TRUE" : "FALSE");
1410 #endif
1412 /* Current calligraphic */
1413 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1414 /* dc->npoints > 0 */
1415 /* g_print("calligraphics(1|2) reset\n"); */
1416 sp_curve_reset(dc->cal1);
1417 sp_curve_reset(dc->cal2);
1419 sp_curve_moveto(dc->cal1, dc->point1[0]);
1420 sp_curve_moveto(dc->cal2, dc->point2[0]);
1421 }
1423 NR::Point b1[BEZIER_MAX_LENGTH];
1424 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1425 tolerance_sq, BEZIER_MAX_BEZIERS);
1426 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1428 NR::Point b2[BEZIER_MAX_LENGTH];
1429 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1430 tolerance_sq, BEZIER_MAX_BEZIERS);
1431 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1433 if ( nb1 != -1 && nb2 != -1 ) {
1434 /* Fit and draw and reset state */
1435 #ifdef DYNA_DRAW_VERBOSE
1436 g_print("nb1:%d nb2:%d\n", nb1, nb2);
1437 #endif
1438 /* CanvasShape */
1439 if (! release) {
1440 sp_curve_reset(dc->currentcurve);
1441 sp_curve_moveto(dc->currentcurve, b1[0]);
1442 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1443 sp_curve_curveto(dc->currentcurve, bp1[1],
1444 bp1[2], bp1[3]);
1445 }
1446 sp_curve_lineto(dc->currentcurve,
1447 b2[BEZIER_SIZE*(nb2-1) + 3]);
1448 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1449 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1450 }
1451 // FIXME: dc->segments is always NULL at this point??
1452 if (!dc->segments) { // first segment
1453 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1454 }
1455 sp_curve_closepath(dc->currentcurve);
1456 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1457 }
1459 /* Current calligraphic */
1460 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1461 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1462 }
1463 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1464 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1465 }
1466 } else {
1467 /* fixme: ??? */
1468 #ifdef DYNA_DRAW_VERBOSE
1469 g_print("[fit_and_split] failed to fit-cubic.\n");
1470 #endif
1471 draw_temporary_box(dc);
1473 for (gint i = 1; i < dc->npoints; i++) {
1474 sp_curve_lineto(dc->cal1, dc->point1[i]);
1475 }
1476 for (gint i = 1; i < dc->npoints; i++) {
1477 sp_curve_lineto(dc->cal2, dc->point2[i]);
1478 }
1479 }
1481 /* Fit and draw and copy last point */
1482 #ifdef DYNA_DRAW_VERBOSE
1483 g_print("[%d]Yup\n", dc->npoints);
1484 #endif
1485 if (!release) {
1486 g_assert(!sp_curve_empty(dc->currentcurve));
1488 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1489 SP_TYPE_CANVAS_BPATH,
1490 NULL);
1491 SPCurve *curve = sp_curve_copy(dc->currentcurve);
1492 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1493 sp_curve_unref(curve);
1495 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1496 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1497 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1498 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1499 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1500 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1501 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1502 //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);
1503 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1504 /* fixme: Cannot we cascade it to root more clearly? */
1505 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1507 dc->segments = g_slist_prepend(dc->segments, cbp);
1508 }
1510 dc->point1[0] = dc->point1[dc->npoints - 1];
1511 dc->point2[0] = dc->point2[dc->npoints - 1];
1512 dc->npoints = 1;
1513 } else {
1514 draw_temporary_box(dc);
1515 }
1516 }
1518 static void
1519 draw_temporary_box(SPDynaDrawContext *dc)
1520 {
1521 sp_curve_reset(dc->currentcurve);
1523 sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1524 for (gint i = dc->npoints-2; i >= 0; i--) {
1525 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1526 }
1527 for (gint i = 0; i < dc->npoints; i++) {
1528 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1529 }
1530 if (dc->npoints >= 2) {
1531 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);
1532 }
1534 sp_curve_closepath(dc->currentcurve);
1535 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1536 }
1538 /*
1539 Local Variables:
1540 mode:c++
1541 c-file-style:"stroustrup"
1542 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1543 indent-tabs-mode:nil
1544 fill-column:99
1545 End:
1546 */
1547 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :