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 "prefs-utils.h"
49 #include "pixmaps/cursor-calligraphy.xpm"
50 #include "libnr/n-art-bpath.h"
51 #include "libnr/nr-path.h"
52 #include "libnr/nr-matrix-ops.h"
53 #include "libnr/nr-scale-translate-ops.h"
54 #include "xml/repr.h"
55 #include "context-fns.h"
56 #include "sp-item.h"
57 #include "inkscape.h"
58 #include "color.h"
59 #include "splivarot.h"
60 #include "sp-item-group.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 ddc->hatch_spacing_step = 0;
201 new (&ddc->hatch_pointer_past) std::list<double>();
202 new (&ddc->hatch_nearest_past) std::list<double>();
203 ddc->hatch_last_nearest = NR::Point(0,0);
204 ddc->hatch_last_pointer = NR::Point(0,0);
205 ddc->hatch_vector_accumulated = NR::Point(0,0);
206 ddc->hatch_escaped = false;
207 ddc->hatch_area = NULL;
208 ddc->hatch_item = NULL;
209 ddc->hatch_livarot_path = NULL;
211 ddc->trace_bg = false;
212 }
214 static void
215 sp_dyna_draw_context_dispose(GObject *object)
216 {
217 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
219 if (ddc->hatch_area) {
220 gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
221 ddc->hatch_area = NULL;
222 }
224 if (ddc->accumulated) {
225 ddc->accumulated = sp_curve_unref(ddc->accumulated);
226 }
228 while (ddc->segments) {
229 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
230 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
231 }
233 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
234 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
235 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
237 if (ddc->currentshape) {
238 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
239 ddc->currentshape = NULL;
240 }
242 if (ddc->_message_context) {
243 delete ddc->_message_context;
244 }
246 G_OBJECT_CLASS(parent_class)->dispose(object);
248 ddc->hatch_pointer_past.~list();
249 ddc->hatch_nearest_past.~list();
250 }
252 static void
253 sp_dyna_draw_context_setup(SPEventContext *ec)
254 {
255 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
257 if (((SPEventContextClass *) parent_class)->setup)
258 ((SPEventContextClass *) parent_class)->setup(ec);
260 ddc->accumulated = sp_curve_new_sized(32);
261 ddc->currentcurve = sp_curve_new_sized(4);
263 ddc->cal1 = sp_curve_new_sized(32);
264 ddc->cal2 = sp_curve_new_sized(32);
266 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
267 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
268 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
269 /* fixme: Cannot we cascade it to root more clearly? */
270 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
272 {
273 SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
274 ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
275 sp_curve_unref(c);
276 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
277 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
278 sp_canvas_item_hide(ddc->hatch_area);
279 }
281 sp_event_context_read(ec, "mass");
282 sp_event_context_read(ec, "wiggle");
283 sp_event_context_read(ec, "angle");
284 sp_event_context_read(ec, "width");
285 sp_event_context_read(ec, "thinning");
286 sp_event_context_read(ec, "tremor");
287 sp_event_context_read(ec, "flatness");
288 sp_event_context_read(ec, "tracebackground");
289 sp_event_context_read(ec, "usepressure");
290 sp_event_context_read(ec, "usetilt");
291 sp_event_context_read(ec, "abs_width");
292 sp_event_context_read(ec, "keep_selected");
293 sp_event_context_read(ec, "cap_rounding");
295 ddc->is_drawing = false;
297 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
299 if (prefs_get_int_attribute("tools.calligraphic", "selcue", 0) != 0) {
300 ec->enableSelectionCue();
301 }
302 }
304 static void
305 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
306 {
307 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
309 if (!strcmp(key, "mass")) {
310 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
311 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
312 } else if (!strcmp(key, "wiggle")) {
313 double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
314 ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
315 } else if (!strcmp(key, "angle")) {
316 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
317 ddc->angle = CLAMP (dval, -90, 90);
318 } else if (!strcmp(key, "width")) {
319 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
320 ddc->width = CLAMP(dval, -1000.0, 1000.0);
321 } else if (!strcmp(key, "thinning")) {
322 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
323 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
324 } else if (!strcmp(key, "tremor")) {
325 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
326 ddc->tremor = CLAMP(dval, 0.0, 1.0);
327 } else if (!strcmp(key, "flatness")) {
328 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
329 ddc->flatness = CLAMP(dval, 0, 1.0);
330 } else if (!strcmp(key, "tracebackground")) {
331 ddc->trace_bg = (val && strcmp(val, "0"));
332 } else if (!strcmp(key, "usepressure")) {
333 ddc->usepressure = (val && strcmp(val, "0"));
334 } else if (!strcmp(key, "usetilt")) {
335 ddc->usetilt = (val && strcmp(val, "0"));
336 } else if (!strcmp(key, "abs_width")) {
337 ddc->abs_width = (val && strcmp(val, "0"));
338 } else if (!strcmp(key, "keep_selected")) {
339 ddc->keep_selected = (val && strcmp(val, "0"));
340 } else if (!strcmp(key, "cap_rounding")) {
341 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
342 }
344 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
345 }
347 static double
348 flerp(double f0, double f1, double p)
349 {
350 return f0 + ( f1 - f0 ) * p;
351 }
353 /* Get normalized point */
354 static NR::Point
355 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
356 {
357 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
358 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
359 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
360 }
362 /* Get view point */
363 static NR::Point
364 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
365 {
366 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
367 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
368 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
369 }
371 static void
372 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
373 {
374 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
375 dc->vel = NR::Point(0,0);
376 dc->vel_max = 0;
377 dc->acc = NR::Point(0,0);
378 dc->ang = NR::Point(0,0);
379 dc->del = NR::Point(0,0);
380 }
382 static void
383 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
384 {
385 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
386 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
387 else
388 dc->pressure = DDC_DEFAULT_PRESSURE;
390 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
391 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
392 else
393 dc->xtilt = DDC_DEFAULT_TILT;
395 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
396 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
397 else
398 dc->ytilt = DDC_DEFAULT_TILT;
399 }
402 static gboolean
403 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
404 {
405 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
407 /* Calculate mass and drag */
408 double const mass = flerp(1.0, 160.0, dc->mass);
409 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
411 /* Calculate force and acceleration */
412 NR::Point force = n - dc->cur;
414 // If force is below the absolute threshold DYNA_EPSILON,
415 // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
416 // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
417 // discard this move.
418 // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
419 // especially bothersome at the start of the stroke where we don't yet have the inertia to
420 // smooth them out.
421 if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
422 return FALSE;
423 }
425 dc->acc = force / mass;
427 /* Calculate new velocity */
428 dc->vel += dc->acc;
430 if (NR::L2(dc->vel) > dc->vel_max)
431 dc->vel_max = NR::L2(dc->vel);
433 /* Calculate angle of drawing tool */
435 double a1;
436 if (dc->usetilt) {
437 // 1a. calculate nib angle from input device tilt:
438 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
440 if (length > 0) {
441 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
442 a1 = atan2(ang1);
443 }
444 else
445 a1 = 0.0;
446 }
447 else {
448 // 1b. fixed dc->angle (absolutely flat nib):
449 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
450 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
451 a1 = atan2(ang1);
452 }
454 // 2. perpendicular to dc->vel (absolutely non-flat nib):
455 gdouble const mag_vel = NR::L2(dc->vel);
456 if ( mag_vel < DYNA_EPSILON ) {
457 return FALSE;
458 }
459 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
461 // 3. Average them using flatness parameter:
462 // calculate angles
463 double a2 = atan2(ang2);
464 // flip a2 to force it to be in the same half-circle as a1
465 bool flipped = false;
466 if (fabs (a2-a1) > 0.5*M_PI) {
467 a2 += M_PI;
468 flipped = true;
469 }
470 // normalize a2
471 if (a2 > M_PI)
472 a2 -= 2*M_PI;
473 if (a2 < -M_PI)
474 a2 += 2*M_PI;
475 // find the flatness-weighted bisector angle, unflip if a2 was flipped
476 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
477 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
479 // Try to detect a sudden flip when the new angle differs too much from the previous for the
480 // current velocity; in that case discard this move
481 double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
482 if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
483 return FALSE;
484 }
486 // convert to point
487 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
489 // 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);
491 /* Apply drag */
492 dc->vel *= 1.0 - drag;
494 /* Update position */
495 dc->last = dc->cur;
496 dc->cur += dc->vel;
498 return TRUE;
499 }
501 static void
502 sp_dyna_draw_brush(SPDynaDrawContext *dc)
503 {
504 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
506 // How much velocity thins strokestyle
507 double vel_thin = flerp (0, 160, dc->vel_thin);
509 // Influence of pressure on thickness
510 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
512 // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
513 // drag)
514 NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
515 NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush);
517 double trace_thick = 1;
518 if (dc->trace_bg) {
519 // pick single pixel
520 NRPixBlock pb;
521 int x = (int) floor(brush_w[NR::X]);
522 int y = (int) floor(brush_w[NR::Y]);
523 nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
524 sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
525 const unsigned char *s = NR_PIXBLOCK_PX(&pb);
526 double R = s[0] / 255.0;
527 double G = s[1] / 255.0;
528 double B = s[2] / 255.0;
529 double A = s[3] / 255.0;
530 double max = MAX (MAX (R, G), B);
531 double min = MIN (MIN (R, G), B);
532 double L = A * (max + min)/2 + (1 - A); // blend with white bg
533 trace_thick = 1 - L;
534 //g_print ("L %g thick %g\n", L, trace_thick);
535 }
537 double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
539 double tremble_left = 0, tremble_right = 0;
540 if (dc->tremor > 0) {
541 // obtain two normally distributed random variables, using polar Box-Muller transform
542 double x1, x2, w, y1, y2;
543 do {
544 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
545 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
546 w = x1 * x1 + x2 * x2;
547 } while ( w >= 1.0 );
548 w = sqrt( (-2.0 * log( w ) ) / w );
549 y1 = x1 * w;
550 y2 = x2 * w;
552 // deflect both left and right edges randomly and independently, so that:
553 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
554 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
555 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
556 // comparatively smooth and slow ones excessively jittery
557 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
558 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
559 }
561 if ( width < 0.02 * dc->width ) {
562 width = 0.02 * dc->width;
563 }
565 double dezoomify_factor = 0.05 * 1000;
566 if (!dc->abs_width) {
567 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
568 }
570 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
571 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
573 dc->point1[dc->npoints] = brush + del_left;
574 dc->point2[dc->npoints] = brush - del_right;
576 dc->del = 0.5*(del_left + del_right);
578 dc->npoints++;
579 }
581 void
582 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
583 {
584 desktop->setToolboxAdjustmentValue (id, value);
585 }
587 static void
588 calligraphic_cancel(SPDynaDrawContext *dc)
589 {
590 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
591 dc->dragging = FALSE;
592 dc->is_drawing = false;
593 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
594 /* Remove all temporary line segments */
595 while (dc->segments) {
596 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
597 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
598 }
599 /* reset accumulated curve */
600 sp_curve_reset(dc->accumulated);
601 clear_current(dc);
602 if (dc->repr) {
603 dc->repr = NULL;
604 }
605 }
608 gint
609 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
610 GdkEvent *event)
611 {
612 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
613 SPDesktop *desktop = event_context->desktop;
615 gint ret = FALSE;
617 switch (event->type) {
618 case GDK_BUTTON_PRESS:
619 if (event->button.button == 1 && !event_context->space_panning) {
621 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
623 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
624 return TRUE;
625 }
627 NR::Point const button_w(event->button.x,
628 event->button.y);
629 NR::Point const button_dt(desktop->w2d(button_w));
630 sp_dyna_draw_reset(dc, button_dt);
631 sp_dyna_draw_extinput(dc, event);
632 sp_dyna_draw_apply(dc, button_dt);
633 sp_curve_reset(dc->accumulated);
634 if (dc->repr) {
635 dc->repr = NULL;
636 }
638 /* initialize first point */
639 dc->npoints = 0;
641 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
642 ( GDK_KEY_PRESS_MASK |
643 GDK_BUTTON_RELEASE_MASK |
644 GDK_POINTER_MOTION_MASK |
645 GDK_BUTTON_PRESS_MASK ),
646 NULL,
647 event->button.time);
649 ret = TRUE;
651 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
652 dc->is_drawing = true;
653 }
654 break;
655 case GDK_MOTION_NOTIFY:
656 {
657 NR::Point const motion_w(event->motion.x,
658 event->motion.y);
659 NR::Point motion_dt(desktop->w2d(motion_w));
660 sp_dyna_draw_extinput(dc, event);
662 dc->_message_context->clear();
664 // for hatching:
665 double hatch_dist = 0;
666 NR::Point hatch_unit_vector(0,0);
667 NR::Point nearest(0,0);
668 NR::Point pointer(0,0);
669 NR::Matrix motion_to_curve(NR::identity());
671 if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
673 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
674 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
675 // One item selected, and it's a path;
676 // let's try to track it as a guide
678 if (selected != dc->hatch_item) {
679 dc->hatch_item = selected;
680 if (dc->hatch_livarot_path)
681 delete dc->hatch_livarot_path;
682 dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
683 dc->hatch_livarot_path->ConvertWithBackData(0.01);
684 }
686 // calculate pointer point in the guide item's coords
687 motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
688 pointer = motion_dt * motion_to_curve;
690 // calculate the nearest point on the guide path
691 NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
692 nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
695 // distance from pointer to nearest
696 hatch_dist = NR::L2(pointer - nearest);
697 // unit-length vector
698 hatch_unit_vector = (pointer - nearest)/hatch_dist;
700 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
701 } else {
702 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
703 }
704 }
706 if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
707 dc->dragging = TRUE;
709 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
711 #define SPEED_ELEMENTS 12
712 #define SPEED_MIN 0.12
713 #define SPEED_NORMAL 0.65
715 // speed is the movement of the nearest point along the guide path, divided by
716 // the movement of the pointer at the same period; it is averaged for the last
717 // SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed
718 // is about 1, i.e. the nearest point on the path is moved by about the same
719 // distance as the pointer. If the speed starts to decrease, we are losing
720 // contact with the guide; if it drops below SPEED_MIN, we are on our own and
721 // not attracted to guide anymore. Most often this happens when you have
722 // tracked to the end of a guide calligraphic stroke and keep moving
723 // further. We try to handle this situation gracefully: not stick with the
724 // guide forever but let go of it smoothly and without sharp jerks (non-zero
725 // mass recommended; with zero mass, jerks are still quite noticeable).
727 double speed = 1;
728 if (NR::L2(dc->hatch_last_nearest) != 0) {
729 // the distance nearest moved since the last motion event
730 double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
731 // the distance pointer moved since the last motion event
732 double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
733 // store them in stacks limited to SPEED_ELEMENTS
734 dc->hatch_nearest_past.push_front(nearest_moved);
735 if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
736 dc->hatch_nearest_past.pop_back();
737 dc->hatch_pointer_past.push_front(pointer_moved);
738 if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
739 dc->hatch_pointer_past.pop_back();
741 // If the stacks are full,
742 if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
743 // calculate the sums of all stored movements
744 double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
745 double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
746 // and divide to get the speed
747 speed = nearest_sum/pointer_sum;
748 //g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed);
749 }
750 }
752 if ( dc->hatch_escaped // already escaped, do not reattach
753 || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
754 || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
755 ) {
756 // We are NOT attracted to the guide!
758 //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);
760 // Remember hatch_escaped so we don't get
761 // attracted again until the end of this stroke
762 dc->hatch_escaped = true;
764 } else {
766 // Calculate angle cosine of this vector-to-guide and all past vectors
767 // summed, to detect if we accidentally flipped to the other side of the
768 // guide
769 double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
770 dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
772 if (dc->hatch_spacing != 0) { // spacing was already set
773 double target;
774 if (speed > SPEED_NORMAL) {
775 // all ok, strictly obey the spacing
776 target = dc->hatch_spacing;
777 } else {
778 // looks like we're starting to lose speed,
779 // so _gradually_ let go attraction to prevent jerks
780 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;
781 }
782 if (!isNaN(dot) && dot < -0.5) {// flip
783 target = -target;
784 }
786 // This is the track pointer that we will use instead of the real one
787 NR::Point new_pointer = nearest + target * hatch_unit_vector;
789 // some limited feedback: allow persistent pulling to slightly change
790 // the spacing
791 dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
793 // return it to the desktop coords
794 motion_dt = new_pointer * motion_to_curve.inverse();
796 } else {
797 // this is the first motion event, set the dist
798 dc->hatch_spacing = hatch_dist;
799 }
801 // remember last points
802 dc->hatch_last_pointer = pointer;
803 dc->hatch_last_nearest = nearest;
804 dc->hatch_vector_accumulated += (pointer - nearest);
805 }
807 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
809 } else {
810 dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
811 }
813 if (!sp_dyna_draw_apply(dc, motion_dt)) {
814 ret = TRUE;
815 break;
816 }
818 if ( dc->cur != dc->last ) {
819 sp_dyna_draw_brush(dc);
820 g_assert( dc->npoints > 0 );
821 fit_and_split(dc, FALSE);
822 }
823 ret = TRUE;
824 }
826 // Draw the hatching circle if necessary
827 if (event->motion.state & GDK_CONTROL_MASK) {
828 if (dc->hatch_spacing == 0 && hatch_dist != 0) {
829 // Haven't set spacing yet: gray, center free, update radius live
830 NR::Point c = desktop->w2d(motion_w);
831 NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
832 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
833 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
834 sp_canvas_item_show(dc->hatch_area);
835 } else if (dc->dragging && !dc->hatch_escaped) {
836 // Tracking: green, center snapped, fixed radius
837 NR::Point c = motion_dt;
838 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
839 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
840 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
841 sp_canvas_item_show(dc->hatch_area);
842 } else if (dc->dragging && dc->hatch_escaped) {
843 // Tracking escaped: red, center free, fixed radius
844 NR::Point c = desktop->w2d(motion_w);
845 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
847 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
848 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
849 sp_canvas_item_show(dc->hatch_area);
850 } else {
851 // Not drawing but spacing set: gray, center snapped, fixed radius
852 NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
853 if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
854 NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
855 sp_canvas_item_affine_absolute(dc->hatch_area, sm);
856 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
857 sp_canvas_item_show(dc->hatch_area);
858 }
859 }
860 } else {
861 sp_canvas_item_hide(dc->hatch_area);
862 }
863 }
864 break;
867 case GDK_BUTTON_RELEASE:
868 {
869 NR::Point const motion_w(event->button.x, event->button.y);
870 NR::Point const motion_dt(desktop->w2d(motion_w));
872 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
873 sp_canvas_end_forced_full_redraws(desktop->canvas);
874 dc->is_drawing = false;
876 if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
877 dc->dragging = FALSE;
879 sp_dyna_draw_apply(dc, motion_dt);
881 /* Remove all temporary line segments */
882 while (dc->segments) {
883 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
884 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
885 }
887 /* Create object */
888 fit_and_split(dc, TRUE);
889 accumulate_calligraphic(dc);
890 set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
892 /* reset accumulated curve */
893 sp_curve_reset(dc->accumulated);
895 clear_current(dc);
896 if (dc->repr) {
897 dc->repr = NULL;
898 }
900 if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
901 if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
902 dc->hatch_last_nearest = NR::Point(0,0);
903 dc->hatch_last_pointer = NR::Point(0,0);
904 dc->hatch_vector_accumulated = NR::Point(0,0);
905 dc->hatch_escaped = false;
906 dc->hatch_item = NULL;
907 dc->hatch_livarot_path = NULL;
909 if (dc->hatch_spacing != 0 && !dc->keep_selected) {
910 // we do not select the newly drawn path, so increase spacing by step
911 if (dc->hatch_spacing_step == 0) {
912 dc->hatch_spacing_step = dc->hatch_spacing;
913 }
914 dc->hatch_spacing += dc->hatch_spacing_step;
915 }
917 dc->_message_context->clear();
918 ret = TRUE;
919 }
920 break;
921 }
923 case GDK_KEY_PRESS:
924 switch (get_group0_keyval (&event->key)) {
925 case GDK_Up:
926 case GDK_KP_Up:
927 if (!MOD__CTRL_ONLY) {
928 dc->angle += 5.0;
929 if (dc->angle > 90.0)
930 dc->angle = 90.0;
931 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
932 ret = TRUE;
933 }
934 break;
935 case GDK_Down:
936 case GDK_KP_Down:
937 if (!MOD__CTRL_ONLY) {
938 dc->angle -= 5.0;
939 if (dc->angle < -90.0)
940 dc->angle = -90.0;
941 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
942 ret = TRUE;
943 }
944 break;
945 case GDK_Right:
946 case GDK_KP_Right:
947 if (!MOD__CTRL_ONLY) {
948 dc->width += 0.01;
949 if (dc->width > 1.0)
950 dc->width = 1.0;
951 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
952 ret = TRUE;
953 }
954 break;
955 case GDK_Left:
956 case GDK_KP_Left:
957 if (!MOD__CTRL_ONLY) {
958 dc->width -= 0.01;
959 if (dc->width < 0.01)
960 dc->width = 0.01;
961 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
962 ret = TRUE;
963 }
964 break;
965 case GDK_Home:
966 case GDK_KP_Home:
967 dc->width = 0.01;
968 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
969 ret = TRUE;
970 break;
971 case GDK_End:
972 case GDK_KP_End:
973 dc->width = 1.0;
974 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
975 ret = TRUE;
976 break;
977 case GDK_x:
978 case GDK_X:
979 if (MOD__ALT_ONLY) {
980 desktop->setToolboxFocusTo ("altx-calligraphy");
981 ret = TRUE;
982 }
983 break;
984 case GDK_Escape:
985 if (dc->is_drawing) {
986 // if drawing, cancel, otherwise pass it up for deselecting
987 calligraphic_cancel (dc);
988 ret = TRUE;
989 }
990 break;
991 case GDK_z:
992 case GDK_Z:
993 if (MOD__CTRL_ONLY && dc->is_drawing) {
994 // if drawing, cancel, otherwise pass it up for undo
995 calligraphic_cancel (dc);
996 ret = TRUE;
997 }
998 break;
999 default:
1000 break;
1001 }
1002 break;
1004 case GDK_KEY_RELEASE:
1005 switch (get_group0_keyval(&event->key)) {
1006 case GDK_Control_L:
1007 case GDK_Control_R:
1008 dc->_message_context->clear();
1009 dc->hatch_spacing = 0;
1010 dc->hatch_spacing_step = 0;
1011 break;
1012 default:
1013 break;
1014 }
1016 default:
1017 break;
1018 }
1020 if (!ret) {
1021 if (((SPEventContextClass *) parent_class)->root_handler) {
1022 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1023 }
1024 }
1026 return ret;
1027 }
1030 static void
1031 clear_current(SPDynaDrawContext *dc)
1032 {
1033 /* reset bpath */
1034 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1035 /* reset curve */
1036 sp_curve_reset(dc->currentcurve);
1037 sp_curve_reset(dc->cal1);
1038 sp_curve_reset(dc->cal2);
1039 /* reset points */
1040 dc->npoints = 0;
1041 }
1043 static void
1044 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1045 {
1046 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1048 if (!sp_curve_empty(dc->accumulated)) {
1049 NArtBpath *abp;
1050 gchar *str;
1052 if (!dc->repr) {
1053 /* Create object */
1054 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1055 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1057 /* Set style */
1058 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1060 dc->repr = repr;
1062 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1063 Inkscape::GC::release(dc->repr);
1064 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1065 item->updateRepr();
1066 }
1067 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1068 str = sp_svg_write_path(abp);
1069 g_assert( str != NULL );
1070 g_free(abp);
1071 dc->repr->setAttribute("d", str);
1072 g_free(str);
1074 if (unionize) {
1075 sp_desktop_selection(desktop)->add(dc->repr);
1076 sp_selected_path_union_skip_undo();
1077 } else {
1078 if (dc->keep_selected) {
1079 sp_desktop_selection(desktop)->set(dc->repr);
1080 }
1081 }
1083 } else {
1084 if (dc->repr) {
1085 sp_repr_unparent(dc->repr);
1086 }
1087 dc->repr = NULL;
1088 }
1090 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
1091 _("Draw calligraphic stroke"));
1092 }
1094 static void
1095 add_cap(SPCurve *curve,
1096 NR::Point const &pre, NR::Point const &from,
1097 NR::Point const &to, NR::Point const &post,
1098 double rounding)
1099 {
1100 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1101 double mag = NR::L2(vel);
1103 NR::Point v_in = from - pre;
1104 double mag_in = NR::L2(v_in);
1105 if ( mag_in > DYNA_EPSILON ) {
1106 v_in = mag * v_in / mag_in;
1107 } else {
1108 v_in = NR::Point(0, 0);
1109 }
1111 NR::Point v_out = to - post;
1112 double mag_out = NR::L2(v_out);
1113 if ( mag_out > DYNA_EPSILON ) {
1114 v_out = mag * v_out / mag_out;
1115 } else {
1116 v_out = NR::Point(0, 0);
1117 }
1119 if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1120 sp_curve_curveto(curve, from + v_in, to + v_out, to);
1121 }
1122 }
1124 static void
1125 accumulate_calligraphic(SPDynaDrawContext *dc)
1126 {
1127 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1128 sp_curve_reset(dc->accumulated); /* Is this required ?? */
1129 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1131 g_assert(dc->cal1->end > 1);
1132 g_assert(rev_cal2->end > 1);
1133 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1134 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1135 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1136 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1137 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1138 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1140 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1142 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);
1144 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1146 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);
1148 sp_curve_closepath(dc->accumulated);
1150 sp_curve_unref(rev_cal2);
1152 sp_curve_reset(dc->cal1);
1153 sp_curve_reset(dc->cal2);
1154 }
1155 }
1157 static double square(double const x)
1158 {
1159 return x * x;
1160 }
1162 static void
1163 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1164 {
1165 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1167 #ifdef DYNA_DRAW_VERBOSE
1168 g_print("[F&S:R=%c]", release?'T':'F');
1169 #endif
1171 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1172 return; // just clicked
1174 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1175 #define BEZIER_SIZE 4
1176 #define BEZIER_MAX_BEZIERS 8
1177 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1179 #ifdef DYNA_DRAW_VERBOSE
1180 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1181 dc->npoints, release ? "TRUE" : "FALSE");
1182 #endif
1184 /* Current calligraphic */
1185 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1186 /* dc->npoints > 0 */
1187 /* g_print("calligraphics(1|2) reset\n"); */
1188 sp_curve_reset(dc->cal1);
1189 sp_curve_reset(dc->cal2);
1191 sp_curve_moveto(dc->cal1, dc->point1[0]);
1192 sp_curve_moveto(dc->cal2, dc->point2[0]);
1193 }
1195 NR::Point b1[BEZIER_MAX_LENGTH];
1196 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1197 tolerance_sq, BEZIER_MAX_BEZIERS);
1198 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1200 NR::Point b2[BEZIER_MAX_LENGTH];
1201 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1202 tolerance_sq, BEZIER_MAX_BEZIERS);
1203 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1205 if ( nb1 != -1 && nb2 != -1 ) {
1206 /* Fit and draw and reset state */
1207 #ifdef DYNA_DRAW_VERBOSE
1208 g_print("nb1:%d nb2:%d\n", nb1, nb2);
1209 #endif
1210 /* CanvasShape */
1211 if (! release) {
1212 sp_curve_reset(dc->currentcurve);
1213 sp_curve_moveto(dc->currentcurve, b1[0]);
1214 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1215 sp_curve_curveto(dc->currentcurve, bp1[1],
1216 bp1[2], bp1[3]);
1217 }
1218 sp_curve_lineto(dc->currentcurve,
1219 b2[BEZIER_SIZE*(nb2-1) + 3]);
1220 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1221 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1222 }
1223 // FIXME: dc->segments is always NULL at this point??
1224 if (!dc->segments) { // first segment
1225 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1226 }
1227 sp_curve_closepath(dc->currentcurve);
1228 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1229 }
1231 /* Current calligraphic */
1232 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1233 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1234 }
1235 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1236 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1237 }
1238 } else {
1239 /* fixme: ??? */
1240 #ifdef DYNA_DRAW_VERBOSE
1241 g_print("[fit_and_split] failed to fit-cubic.\n");
1242 #endif
1243 draw_temporary_box(dc);
1245 for (gint i = 1; i < dc->npoints; i++) {
1246 sp_curve_lineto(dc->cal1, dc->point1[i]);
1247 }
1248 for (gint i = 1; i < dc->npoints; i++) {
1249 sp_curve_lineto(dc->cal2, dc->point2[i]);
1250 }
1251 }
1253 /* Fit and draw and copy last point */
1254 #ifdef DYNA_DRAW_VERBOSE
1255 g_print("[%d]Yup\n", dc->npoints);
1256 #endif
1257 if (!release) {
1258 g_assert(!sp_curve_empty(dc->currentcurve));
1260 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1261 SP_TYPE_CANVAS_BPATH,
1262 NULL);
1263 SPCurve *curve = sp_curve_copy(dc->currentcurve);
1264 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1265 sp_curve_unref(curve);
1267 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1268 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1269 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1270 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1271 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1272 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1273 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1274 //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);
1275 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1276 /* fixme: Cannot we cascade it to root more clearly? */
1277 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1279 dc->segments = g_slist_prepend(dc->segments, cbp);
1280 }
1282 dc->point1[0] = dc->point1[dc->npoints - 1];
1283 dc->point2[0] = dc->point2[dc->npoints - 1];
1284 dc->npoints = 1;
1285 } else {
1286 draw_temporary_box(dc);
1287 }
1288 }
1290 static void
1291 draw_temporary_box(SPDynaDrawContext *dc)
1292 {
1293 sp_curve_reset(dc->currentcurve);
1295 sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1296 for (gint i = dc->npoints-2; i >= 0; i--) {
1297 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1298 }
1299 for (gint i = 0; i < dc->npoints; i++) {
1300 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1301 }
1302 if (dc->npoints >= 2) {
1303 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);
1304 }
1306 sp_curve_closepath(dc->currentcurve);
1307 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1308 }
1310 /*
1311 Local Variables:
1312 mode:c++
1313 c-file-style:"stroustrup"
1314 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1315 indent-tabs-mode:nil
1316 fill-column:99
1317 End:
1318 */
1319 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :