Code

remove thinning/thickening, now in tweak tool
[inkscape.git] / src / dyna-draw-context.cpp
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 "libnr/n-art-bpath.h"
50 #include "libnr/nr-path.h"
51 #include "libnr/nr-matrix-ops.h"
52 #include "libnr/nr-scale-translate-ops.h"
53 #include "xml/repr.h"
54 #include "context-fns.h"
55 #include "sp-item.h"
56 #include "inkscape.h"
57 #include "color.h"
58 #include "splivarot.h"
59 #include "sp-item-group.h"
60 #include "sp-shape.h"
61 #include "sp-path.h"
62 #include "sp-text.h"
63 #include "display/canvas-bpath.h"
64 #include "display/canvas-arena.h"
65 #include "livarot/Shape.h"
66 #include "isnan.h"
68 #include "dyna-draw-context.h"
70 #define DDC_RED_RGBA 0xff0000ff
72 #define TOLERANCE_CALLIGRAPHIC 0.1
74 #define DYNA_EPSILON 0.5e-6
75 #define DYNA_EPSILON_START 0.5e-2
76 #define DYNA_VEL_START 1e-5
78 #define DYNA_MIN_WIDTH 1.0e-6
80 #define DRAG_MIN 0.0
81 #define DRAG_DEFAULT 1.0
82 #define DRAG_MAX 1.0
84 // FIXME: move it to some shared file to be reused by both calligraphy and dropper
85 #define C1 0.552
86 static NArtBpath const hatch_area_circle[] = {
87     { NR_MOVETO, 0, 0, 0, 0, -1, 0 },
88     { NR_CURVETO, -1, C1, -C1, 1, 0, 1 },
89     { NR_CURVETO, C1, 1, 1, C1, 1, 0 },
90     { NR_CURVETO, 1, -C1, C1, -1, 0, -1 },
91     { NR_CURVETO, -C1, -1, -1, -C1, -1, 0 },
92     { NR_END, 0, 0, 0, 0, 0, 0 }
93 };
94 #undef C1
97 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
98 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
99 static void sp_dyna_draw_context_dispose(GObject *object);
101 static void sp_dyna_draw_context_setup(SPEventContext *ec);
102 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
103 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
105 static void clear_current(SPDynaDrawContext *dc);
106 static void set_to_accumulated(SPDynaDrawContext *dc, bool unionize);
107 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
108 static void accumulate_calligraphic(SPDynaDrawContext *dc);
110 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
112 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
113 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
114 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
115 static void draw_temporary_box(SPDynaDrawContext *dc);
118 static SPEventContextClass *parent_class;
120 GtkType
121 sp_dyna_draw_context_get_type(void)
123     static GType type = 0;
124     if (!type) {
125         GTypeInfo info = {
126             sizeof(SPDynaDrawContextClass),
127             NULL, NULL,
128             (GClassInitFunc) sp_dyna_draw_context_class_init,
129             NULL, NULL,
130             sizeof(SPDynaDrawContext),
131             4,
132             (GInstanceInitFunc) sp_dyna_draw_context_init,
133             NULL,   /* value_table */
134         };
135         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
136     }
137     return type;
140 static void
141 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
143     GObjectClass *object_class = (GObjectClass *) klass;
144     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
146     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
148     object_class->dispose = sp_dyna_draw_context_dispose;
150     event_context_class->setup = sp_dyna_draw_context_setup;
151     event_context_class->set = sp_dyna_draw_context_set;
152     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
155 static void
156 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
158     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
160     event_context->cursor_shape = cursor_calligraphy_xpm;
161     event_context->hot_x = 4;
162     event_context->hot_y = 4;
164     ddc->accumulated = NULL;
165     ddc->segments = NULL;
166     ddc->currentcurve = NULL;
167     ddc->currentshape = NULL;
168     ddc->npoints = 0;
169     ddc->cal1 = NULL;
170     ddc->cal2 = NULL;
171     ddc->repr = NULL;
173     /* DynaDraw values */
174     ddc->cur = NR::Point(0,0);
175     ddc->last = NR::Point(0,0);
176     ddc->vel = NR::Point(0,0);
177     ddc->vel_max = 0;
178     ddc->acc = NR::Point(0,0);
179     ddc->ang = NR::Point(0,0);
180     ddc->del = NR::Point(0,0);
182     /* attributes */
183     ddc->dragging = FALSE;
185     ddc->mass = 0.3;
186     ddc->drag = DRAG_DEFAULT;
187     ddc->angle = 30.0;
188     ddc->width = 0.2;
189     ddc->pressure = DDC_DEFAULT_PRESSURE;
191     ddc->vel_thin = 0.1;
192     ddc->flatness = 0.9;
193     ddc->cap_rounding = 0.0;
195     ddc->abs_width = false;
196     ddc->keep_selected = true;
198     ddc->hatch_spacing = 0;
199     ddc->hatch_spacing_step = 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;
213 static void
214 sp_dyna_draw_context_dispose(GObject *object)
216     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
218     if (ddc->hatch_area) {
219         gtk_object_destroy(GTK_OBJECT(ddc->hatch_area));
220         ddc->hatch_area = NULL;
221     }
223     if (ddc->accumulated) {
224         ddc->accumulated = sp_curve_unref(ddc->accumulated);
225     }
227     while (ddc->segments) {
228         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
229         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
230     }
232     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
233     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
234     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
236     if (ddc->currentshape) {
237         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
238         ddc->currentshape = NULL;
239     }
241     if (ddc->_message_context) {
242         delete ddc->_message_context;
243     }
245     G_OBJECT_CLASS(parent_class)->dispose(object);
247     ddc->hatch_pointer_past.~list();
248     ddc->hatch_nearest_past.~list();
251 static void
252 sp_dyna_draw_context_setup(SPEventContext *ec)
254     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
256     if (((SPEventContextClass *) parent_class)->setup)
257         ((SPEventContextClass *) parent_class)->setup(ec);
259     ddc->accumulated = sp_curve_new_sized(32);
260     ddc->currentcurve = sp_curve_new_sized(4);
262     ddc->cal1 = sp_curve_new_sized(32);
263     ddc->cal2 = sp_curve_new_sized(32);
265     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
266     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
267     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
268     /* fixme: Cannot we cascade it to root more clearly? */
269     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
271     {
272         SPCurve *c = sp_curve_new_from_foreign_bpath(hatch_area_circle);
273         ddc->hatch_area = sp_canvas_bpath_new(sp_desktop_controls(ec->desktop), c);
274         sp_curve_unref(c);
275         sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->hatch_area), 0x00000000,(SPWindRule)0);
276         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
277         sp_canvas_item_hide(ddc->hatch_area);
278     }
280     sp_event_context_read(ec, "mass");
281     sp_event_context_read(ec, "wiggle");
282     sp_event_context_read(ec, "angle");
283     sp_event_context_read(ec, "width");
284     sp_event_context_read(ec, "thinning");
285     sp_event_context_read(ec, "tremor");
286     sp_event_context_read(ec, "flatness");
287     sp_event_context_read(ec, "tracebackground");
288     sp_event_context_read(ec, "usepressure");
289     sp_event_context_read(ec, "usetilt");
290     sp_event_context_read(ec, "abs_width");
291     sp_event_context_read(ec, "keep_selected");
292     sp_event_context_read(ec, "cap_rounding");
294     ddc->is_drawing = false;
296     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
299 static void
300 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
302     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
304     if (!strcmp(key, "mass")) {
305         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
306         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
307     } else if (!strcmp(key, "wiggle")) {
308         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
309         ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
310     } else if (!strcmp(key, "angle")) {
311         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
312         ddc->angle = CLAMP (dval, -90, 90);
313     } else if (!strcmp(key, "width")) {
314         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
315         ddc->width = CLAMP(dval, -1000.0, 1000.0);
316     } else if (!strcmp(key, "thinning")) {
317         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
318         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
319     } else if (!strcmp(key, "tremor")) {
320         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
321         ddc->tremor = CLAMP(dval, 0.0, 1.0);
322     } else if (!strcmp(key, "flatness")) {
323         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
324         ddc->flatness = CLAMP(dval, 0, 1.0);
325     } else if (!strcmp(key, "tracebackground")) {
326         ddc->trace_bg = (val && strcmp(val, "0"));
327     } else if (!strcmp(key, "usepressure")) {
328         ddc->usepressure = (val && strcmp(val, "0"));
329     } else if (!strcmp(key, "usetilt")) {
330         ddc->usetilt = (val && strcmp(val, "0"));
331     } else if (!strcmp(key, "abs_width")) {
332         ddc->abs_width = (val && strcmp(val, "0"));
333     } else if (!strcmp(key, "keep_selected")) {
334         ddc->keep_selected = (val && strcmp(val, "0"));
335     } else if (!strcmp(key, "cap_rounding")) {
336         ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
337     }
339     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
342 static double
343 flerp(double f0, double f1, double p)
345     return f0 + ( f1 - f0 ) * p;
348 /* Get normalized point */
349 static NR::Point
350 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
352     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
353     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
354     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
357 /* Get view point */
358 static NR::Point
359 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
361     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
362     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
363     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
366 static void
367 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
369     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
370     dc->vel = NR::Point(0,0);
371     dc->vel_max = 0;
372     dc->acc = NR::Point(0,0);
373     dc->ang = NR::Point(0,0);
374     dc->del = NR::Point(0,0);
377 static void
378 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
380     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
381         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
382     else
383         dc->pressure = DDC_DEFAULT_PRESSURE;
385     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
386         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
387     else
388         dc->xtilt = DDC_DEFAULT_TILT;
390     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
391         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
392     else
393         dc->ytilt = DDC_DEFAULT_TILT;
397 static gboolean
398 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
400     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
402     /* Calculate mass and drag */
403     double const mass = flerp(1.0, 160.0, dc->mass);
404     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
406     /* Calculate force and acceleration */
407     NR::Point force = n - dc->cur;
409     // If force is below the absolute threshold DYNA_EPSILON,
410     // or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
411     // _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
412     // discard this move. 
413     // This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
414     // especially bothersome at the start of the stroke where we don't yet have the inertia to
415     // smooth them out.
416     if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
417         return FALSE;
418     }
420     dc->acc = force / mass;
422     /* Calculate new velocity */
423     dc->vel += dc->acc;
425     if (NR::L2(dc->vel) > dc->vel_max)
426         dc->vel_max = NR::L2(dc->vel);
428     /* Calculate angle of drawing tool */
430     double a1;
431     if (dc->usetilt) {
432         // 1a. calculate nib angle from input device tilt:
433         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
435         if (length > 0) {
436             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
437             a1 = atan2(ang1);
438         }
439         else
440             a1 = 0.0;
441     }
442     else {
443         // 1b. fixed dc->angle (absolutely flat nib):
444         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
445         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
446         a1 = atan2(ang1);
447     }
449     // 2. perpendicular to dc->vel (absolutely non-flat nib):
450     gdouble const mag_vel = NR::L2(dc->vel);
451     if ( mag_vel < DYNA_EPSILON ) {
452         return FALSE;
453     }
454     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
456     // 3. Average them using flatness parameter:
457     // calculate angles
458     double a2 = atan2(ang2);
459     // flip a2 to force it to be in the same half-circle as a1
460     bool flipped = false;
461     if (fabs (a2-a1) > 0.5*M_PI) {
462         a2 += M_PI;
463         flipped = true;
464     }
465     // normalize a2
466     if (a2 > M_PI)
467         a2 -= 2*M_PI;
468     if (a2 < -M_PI)
469         a2 += 2*M_PI;
470     // find the flatness-weighted bisector angle, unflip if a2 was flipped
471     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
472     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
474     // Try to detect a sudden flip when the new angle differs too much from the previous for the
475     // current velocity; in that case discard this move
476     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
477     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
478         return FALSE;
479     }
481     // convert to point
482     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
484 //    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);
486     /* Apply drag */
487     dc->vel *= 1.0 - drag;
489     /* Update position */
490     dc->last = dc->cur;
491     dc->cur += dc->vel;
493     return TRUE;
496 static void
497 sp_dyna_draw_brush(SPDynaDrawContext *dc)
499     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
501     // How much velocity thins strokestyle
502     double vel_thin = flerp (0, 160, dc->vel_thin);
504     // Influence of pressure on thickness
505     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
507     // get the real brush point, not the same as pointer (affected by hatch tracking and/or mass
508     // drag)
509     NR::Point brush = sp_dyna_draw_get_vpoint(dc, dc->cur);
510     NR::Point brush_w = SP_EVENT_CONTEXT(dc)->desktop->d2w(brush); 
512     double trace_thick = 1;
513     if (dc->trace_bg) {
514         // pick single pixel
515         NRPixBlock pb;
516         int x = (int) floor(brush_w[NR::X]);
517         int y = (int) floor(brush_w[NR::Y]);
518         nr_pixblock_setup_fast(&pb, NR_PIXBLOCK_MODE_R8G8B8A8P, x, y, x+1, y+1, TRUE);
519         sp_canvas_arena_render_pixblock(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), &pb);
520         const unsigned char *s = NR_PIXBLOCK_PX(&pb);
521         double R = s[0] / 255.0;
522         double G = s[1] / 255.0;
523         double B = s[2] / 255.0;
524         double A = s[3] / 255.0;
525         double max = MAX (MAX (R, G), B);
526         double min = MIN (MIN (R, G), B);
527         double L = A * (max + min)/2 + (1 - A); // blend with white bg
528         trace_thick = 1 - L;
529         //g_print ("L %g thick %g\n", L, trace_thick);
530     }
532     double width = (pressure_thick * trace_thick - vel_thin * NR::L2(dc->vel)) * dc->width;
534     double tremble_left = 0, tremble_right = 0;
535     if (dc->tremor > 0) {
536         // obtain two normally distributed random variables, using polar Box-Muller transform
537         double x1, x2, w, y1, y2;
538         do {
539             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
540             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
541             w = x1 * x1 + x2 * x2;
542         } while ( w >= 1.0 );
543         w = sqrt( (-2.0 * log( w ) ) / w );
544         y1 = x1 * w;
545         y2 = x2 * w;
547         // deflect both left and right edges randomly and independently, so that:
548         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
549         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
550         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
551         // comparatively smooth and slow ones excessively jittery
552         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
553         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
554     }
556     if ( width < 0.02 * dc->width ) {
557         width = 0.02 * dc->width;
558     }
560     double dezoomify_factor = 0.05 * 1000;
561     if (!dc->abs_width) {
562         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
563     }
565     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
566     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
568     dc->point1[dc->npoints] = brush + del_left;
569     dc->point2[dc->npoints] = brush - del_right;
571     dc->del = 0.5*(del_left + del_right);
573     dc->npoints++;
576 void
577 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
579     desktop->setToolboxAdjustmentValue (id, value);
582 static void
583 calligraphic_cancel(SPDynaDrawContext *dc)
585     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
586     dc->dragging = FALSE;
587     dc->is_drawing = false;
588     sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), 0);
589             /* Remove all temporary line segments */
590             while (dc->segments) {
591                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
592                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
593             }
594             /* reset accumulated curve */
595             sp_curve_reset(dc->accumulated);
596             clear_current(dc);
597             if (dc->repr) {
598                 dc->repr = NULL;
599             }
603 gint
604 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
605                                   GdkEvent *event)
607     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
608     SPDesktop *desktop = event_context->desktop;
610     gint ret = FALSE;
612     switch (event->type) {
613         case GDK_BUTTON_PRESS:
614             if (event->button.button == 1 && !event_context->space_panning) {
616                 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
618                 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
619                     return TRUE;
620                 }
622                 NR::Point const button_w(event->button.x,
623                                          event->button.y);
624                 NR::Point const button_dt(desktop->w2d(button_w));
625                 sp_dyna_draw_reset(dc, button_dt);
626                 sp_dyna_draw_extinput(dc, event);
627                 sp_dyna_draw_apply(dc, button_dt);
628                 sp_curve_reset(dc->accumulated);
629                 if (dc->repr) {
630                     dc->repr = NULL;
631                 }
633                 /* initialize first point */
634                 dc->npoints = 0;
636                 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
637                                     ( GDK_KEY_PRESS_MASK |
638                                       GDK_BUTTON_RELEASE_MASK |
639                                       GDK_POINTER_MOTION_MASK |
640                                       GDK_BUTTON_PRESS_MASK ),
641                                     NULL,
642                                     event->button.time);
644                 ret = TRUE;
646                 sp_canvas_force_full_redraw_after_interruptions(desktop->canvas, 3);
647                 dc->is_drawing = true;
648             }
649             break;
650         case GDK_MOTION_NOTIFY:
651         {
652             NR::Point const motion_w(event->motion.x,
653                                      event->motion.y);
654             NR::Point motion_dt(desktop->w2d(motion_w));
655             sp_dyna_draw_extinput(dc, event);
657             dc->_message_context->clear();
659             // for hatching:
660             double hatch_dist = 0;
661             NR::Point hatch_unit_vector(0,0);
662             NR::Point nearest(0,0);
663             NR::Point pointer(0,0);
664             NR::Matrix motion_to_curve(NR::identity());
666             if (event->motion.state & GDK_CONTROL_MASK) { // hatching - sense the item
668                 SPItem *selected = sp_desktop_selection(desktop)->singleItem();
669                 if (selected && (SP_IS_SHAPE(selected) || SP_IS_TEXT(selected))) {
670                     // One item selected, and it's a path;
671                     // let's try to track it as a guide
673                     if (selected != dc->hatch_item) {
674                         dc->hatch_item = selected;
675                         if (dc->hatch_livarot_path)
676                             delete dc->hatch_livarot_path;
677                         dc->hatch_livarot_path = Path_for_item (dc->hatch_item, true, true);
678                         dc->hatch_livarot_path->ConvertWithBackData(0.01);
679                     }
681                     // calculate pointer point in the guide item's coords
682                     motion_to_curve = sp_item_dt2i_affine(selected) * sp_item_i2doc_affine(selected);
683                     pointer = motion_dt * motion_to_curve;
685                     // calculate the nearest point on the guide path
686                     NR::Maybe<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
687                     nearest = get_point_on_Path(dc->hatch_livarot_path, position->piece, position->t);
690                     // distance from pointer to nearest
691                     hatch_dist = NR::L2(pointer - nearest);
692                     // unit-length vector
693                     hatch_unit_vector = (pointer - nearest)/hatch_dist;
695                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
696                 } else {
697                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
698                 }
699             } 
701             if ( dc->is_drawing && (event->motion.state & GDK_BUTTON1_MASK) && !event_context->space_panning) {
702                 dc->dragging = TRUE;
704                 if (event->motion.state & GDK_CONTROL_MASK && dc->hatch_item) { // hatching
706 #define SPEED_ELEMENTS 12
707 #define SPEED_MIN 0.12
708 #define SPEED_NORMAL 0.65
710                     // speed is the movement of the nearest point along the guide path, divided by
711                     // the movement of the pointer at the same period; it is averaged for the last
712                     // SPEED_ELEMENTS motion events.  Normally, as you track the guide path, speed
713                     // is about 1, i.e. the nearest point on the path is moved by about the same
714                     // distance as the pointer. If the speed starts to decrease, we are losing
715                     // contact with the guide; if it drops below SPEED_MIN, we are on our own and
716                     // not attracted to guide anymore. Most often this happens when you have
717                     // tracked to the end of a guide calligraphic stroke and keep moving
718                     // further. We try to handle this situation gracefully: not stick with the
719                     // guide forever but let go of it smoothly and without sharp jerks (non-zero
720                     // mass recommended; with zero mass, jerks are still quite noticeable).
722                     double speed = 1;
723                     if (NR::L2(dc->hatch_last_nearest) != 0) {
724                         // the distance nearest moved since the last motion event
725                         double nearest_moved = NR::L2(nearest - dc->hatch_last_nearest);
726                         // the distance pointer moved since the last motion event
727                         double pointer_moved = NR::L2(pointer - dc->hatch_last_pointer);
728                         // store them in stacks limited to SPEED_ELEMENTS
729                         dc->hatch_nearest_past.push_front(nearest_moved);
730                         if (dc->hatch_nearest_past.size() > SPEED_ELEMENTS)
731                             dc->hatch_nearest_past.pop_back();
732                         dc->hatch_pointer_past.push_front(pointer_moved);
733                         if (dc->hatch_pointer_past.size() > SPEED_ELEMENTS)
734                             dc->hatch_pointer_past.pop_back();
736                         // If the stacks are full,
737                         if (dc->hatch_nearest_past.size() == SPEED_ELEMENTS) {
738                             // calculate the sums of all stored movements
739                             double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
740                             double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
741                             // and divide to get the speed
742                             speed = nearest_sum/pointer_sum;
743                             //g_print ("nearest sum %g  pointer_sum %g  speed %g\n", nearest_sum, pointer_sum, speed);
744                         }
745                     }
747                     if (   dc->hatch_escaped  // already escaped, do not reattach
748                         || (speed < SPEED_MIN) // stuck; most likely reached end of traced stroke
749                         || (dc->hatch_spacing > 0 && hatch_dist > 50 * dc->hatch_spacing) // went too far from the guide
750                         ) {
751                         // We are NOT attracted to the guide!
753                         //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);
755                         // Remember hatch_escaped so we don't get
756                         // attracted again until the end of this stroke
757                         dc->hatch_escaped = true;
759                     } else {
761                         // Calculate angle cosine of this vector-to-guide and all past vectors
762                         // summed, to detect if we accidentally flipped to the other side of the
763                         // guide
764                         double dot = NR::dot (pointer - nearest, dc->hatch_vector_accumulated);
765                         dot /= NR::L2(pointer - nearest) * NR::L2(dc->hatch_vector_accumulated);
767                         if (dc->hatch_spacing != 0) { // spacing was already set
768                             double target;
769                             if (speed > SPEED_NORMAL) {
770                                 // all ok, strictly obey the spacing
771                                 target = dc->hatch_spacing;
772                             } else {
773                                 // looks like we're starting to lose speed,
774                                 // so _gradually_ let go attraction to prevent jerks
775                                 target = (dc->hatch_spacing * speed + hatch_dist * (SPEED_NORMAL - speed))/SPEED_NORMAL;                            
776                             }
777                             if (!isNaN(dot) && dot < -0.5) {// flip
778                                 target = -target;
779                             }
781                             // This is the track pointer that we will use instead of the real one
782                             NR::Point new_pointer = nearest + target * hatch_unit_vector;
784                             // some limited feedback: allow persistent pulling to slightly change
785                             // the spacing
786                             dc->hatch_spacing += (hatch_dist - dc->hatch_spacing)/3500;
788                             // return it to the desktop coords
789                             motion_dt = new_pointer * motion_to_curve.inverse();
791                         } else {
792                             // this is the first motion event, set the dist 
793                             dc->hatch_spacing = hatch_dist;
794                         }
796                         // remember last points
797                         dc->hatch_last_pointer = pointer;
798                         dc->hatch_last_nearest = nearest;
799                         dc->hatch_vector_accumulated += (pointer - nearest);
800                     }
802                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
804                 } else {
805                     dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drawing</b> a calligraphic stroke"));
806                 }
808                 if (!sp_dyna_draw_apply(dc, motion_dt)) {
809                     ret = TRUE;
810                     break;
811                 }
813                 if ( dc->cur != dc->last ) {
814                     sp_dyna_draw_brush(dc);
815                     g_assert( dc->npoints > 0 );
816                     fit_and_split(dc, FALSE);
817                 }
818                 ret = TRUE;
819             }
821             // Draw the hatching circle if necessary
822             if (event->motion.state & GDK_CONTROL_MASK) { 
823                 if (dc->hatch_spacing == 0 && hatch_dist != 0) { 
824                     // Haven't set spacing yet: gray, center free, update radius live
825                     NR::Point c = desktop->w2d(motion_w);
826                     NR::Matrix const sm (NR::scale(hatch_dist, hatch_dist) * NR::translate(c));
827                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
828                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
829                     sp_canvas_item_show(dc->hatch_area);
830                 } else if (dc->dragging && !dc->hatch_escaped) {
831                     // Tracking: green, center snapped, fixed radius
832                     NR::Point c = motion_dt;
833                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
834                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
835                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
836                     sp_canvas_item_show(dc->hatch_area);
837                 } else if (dc->dragging && dc->hatch_escaped) {
838                     // Tracking escaped: red, center free, fixed radius
839                     NR::Point c = desktop->w2d(motion_w);
840                     NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
842                     sp_canvas_item_affine_absolute(dc->hatch_area, sm);
843                     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
844                     sp_canvas_item_show(dc->hatch_area);
845                 } else {
846                     // Not drawing but spacing set: gray, center snapped, fixed radius
847                     NR::Point c = (nearest + dc->hatch_spacing * hatch_unit_vector) * motion_to_curve.inverse();
848                     if (!isNaN(c[NR::X]) && !isNaN(c[NR::Y])) {
849                         NR::Matrix const sm (NR::scale(dc->hatch_spacing, dc->hatch_spacing) * NR::translate(c));
850                         sp_canvas_item_affine_absolute(dc->hatch_area, sm);
851                         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
852                         sp_canvas_item_show(dc->hatch_area);
853                     }
854                 }
855             } else {
856                 sp_canvas_item_hide(dc->hatch_area);
857             }
858         }
859         break;
862     case GDK_BUTTON_RELEASE:
863     {
864         NR::Point const motion_w(event->button.x, event->button.y);
865         NR::Point const motion_dt(desktop->w2d(motion_w));
867         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
868         sp_canvas_end_forced_full_redraws(desktop->canvas);
869         dc->is_drawing = false;
871         if (dc->dragging && event->button.button == 1 && !event_context->space_panning) {
872             dc->dragging = FALSE;
874             sp_dyna_draw_apply(dc, motion_dt);
876             /* Remove all temporary line segments */
877             while (dc->segments) {
878                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
879                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
880             }
882             /* Create object */
883             fit_and_split(dc, TRUE);
884             accumulate_calligraphic(dc);
885             set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK); // performs document_done
887             /* reset accumulated curve */
888             sp_curve_reset(dc->accumulated);
890             clear_current(dc);
891             if (dc->repr) {
892                 dc->repr = NULL;
893             }
895             if (!dc->hatch_pointer_past.empty()) dc->hatch_pointer_past.clear();
896             if (!dc->hatch_nearest_past.empty()) dc->hatch_nearest_past.clear();
897             dc->hatch_last_nearest = NR::Point(0,0);
898             dc->hatch_last_pointer = NR::Point(0,0);
899             dc->hatch_vector_accumulated = NR::Point(0,0);
900             dc->hatch_escaped = false;
901             dc->hatch_item = NULL;
902             dc->hatch_livarot_path = NULL;
904             if (dc->hatch_spacing != 0 && !dc->keep_selected) { 
905                 // we do not select the newly drawn path, so increase spacing by step
906                 if (dc->hatch_spacing_step == 0) {
907                     dc->hatch_spacing_step = dc->hatch_spacing;
908                 }
909                 dc->hatch_spacing += dc->hatch_spacing_step;
910             }
912             dc->_message_context->clear();
913             ret = TRUE;
914         }
915         break;
916     }
918     case GDK_KEY_PRESS:
919         switch (get_group0_keyval (&event->key)) {
920         case GDK_Up:
921         case GDK_KP_Up:
922             if (!MOD__CTRL_ONLY) {
923                 dc->angle += 5.0;
924                 if (dc->angle > 90.0)
925                     dc->angle = 90.0;
926                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
927                 ret = TRUE;
928             }
929             break;
930         case GDK_Down:
931         case GDK_KP_Down:
932             if (!MOD__CTRL_ONLY) {
933                 dc->angle -= 5.0;
934                 if (dc->angle < -90.0)
935                     dc->angle = -90.0;
936                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
937                 ret = TRUE;
938             }
939             break;
940         case GDK_Right:
941         case GDK_KP_Right:
942             if (!MOD__CTRL_ONLY) {
943                 dc->width += 0.01;
944                 if (dc->width > 1.0)
945                     dc->width = 1.0;
946                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
947                 ret = TRUE;
948             }
949             break;
950         case GDK_Left:
951         case GDK_KP_Left:
952             if (!MOD__CTRL_ONLY) {
953                 dc->width -= 0.01;
954                 if (dc->width < 0.01)
955                     dc->width = 0.01;
956                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
957                 ret = TRUE;
958             }
959             break;
960         case GDK_Home:
961         case GDK_KP_Home:
962             dc->width = 0.01;
963             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
964             ret = TRUE;
965             break;
966         case GDK_End:
967         case GDK_KP_End:
968             dc->width = 1.0;
969             sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
970             ret = TRUE;
971             break;
972         case GDK_x:
973         case GDK_X:
974             if (MOD__ALT_ONLY) {
975                 desktop->setToolboxFocusTo ("altx-calligraphy");
976                 ret = TRUE;
977             }
978             break;
979         case GDK_Escape:
980             if (dc->is_drawing) {
981                 // if drawing, cancel, otherwise pass it up for deselecting
982                 calligraphic_cancel (dc);
983                 ret = TRUE;
984             }
985             break;
986         case GDK_z:
987         case GDK_Z:
988             if (MOD__CTRL_ONLY && dc->is_drawing) {
989                 // if drawing, cancel, otherwise pass it up for undo
990                 calligraphic_cancel (dc);
991                 ret = TRUE;
992             }
993             break;
994         default:
995             break;
996         }
997         break;
999     case GDK_KEY_RELEASE:
1000         switch (get_group0_keyval(&event->key)) {
1001             case GDK_Control_L:
1002             case GDK_Control_R:
1003                 dc->_message_context->clear();
1004                 dc->hatch_spacing = 0;
1005                 dc->hatch_spacing_step = 0;
1006                 break;
1007             default:
1008                 break;
1009         }
1011     default:
1012         break;
1013     }
1015     if (!ret) {
1016         if (((SPEventContextClass *) parent_class)->root_handler) {
1017             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
1018         }
1019     }
1021     return ret;
1025 static void
1026 clear_current(SPDynaDrawContext *dc)
1028     /* reset bpath */
1029     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
1030     /* reset curve */
1031     sp_curve_reset(dc->currentcurve);
1032     sp_curve_reset(dc->cal1);
1033     sp_curve_reset(dc->cal2);
1034     /* reset points */
1035     dc->npoints = 0;
1038 static void
1039 set_to_accumulated(SPDynaDrawContext *dc, bool unionize)
1041     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
1043     if (!sp_curve_empty(dc->accumulated)) {
1044         NArtBpath *abp;
1045         gchar *str;
1047         if (!dc->repr) {
1048             /* Create object */
1049             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
1050             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
1052             /* Set style */
1053             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
1055             dc->repr = repr;
1057             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
1058             Inkscape::GC::release(dc->repr);
1059             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
1060             item->updateRepr();
1061         }
1062         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
1063         str = sp_svg_write_path(abp);
1064         g_assert( str != NULL );
1065         g_free(abp);
1066         dc->repr->setAttribute("d", str);
1067         g_free(str);
1069         if (unionize) {
1070             sp_desktop_selection(desktop)->add(dc->repr);
1071             sp_selected_path_union_skip_undo();
1072         } else {
1073             if (dc->keep_selected) {
1074                 sp_desktop_selection(desktop)->set(dc->repr);
1075             } 
1076         }
1078     } else {
1079         if (dc->repr) {
1080             sp_repr_unparent(dc->repr);
1081         }
1082         dc->repr = NULL;
1083     }
1085     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
1086                      _("Draw calligraphic stroke"));
1089 static void
1090 add_cap(SPCurve *curve,
1091         NR::Point const &pre, NR::Point const &from,
1092         NR::Point const &to, NR::Point const &post,
1093         double rounding)
1095     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
1096     double mag = NR::L2(vel);
1098     NR::Point v_in = from - pre;
1099     double mag_in = NR::L2(v_in);
1100     if ( mag_in > DYNA_EPSILON ) {
1101         v_in = mag * v_in / mag_in;
1102     } else {
1103         v_in = NR::Point(0, 0);
1104     }
1106     NR::Point v_out = to - post;
1107     double mag_out = NR::L2(v_out);
1108     if ( mag_out > DYNA_EPSILON ) {
1109         v_out = mag * v_out / mag_out;
1110     } else {
1111         v_out = NR::Point(0, 0);
1112     }
1114     if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
1115         sp_curve_curveto(curve, from + v_in, to + v_out, to);
1116     }
1119 static void
1120 accumulate_calligraphic(SPDynaDrawContext *dc)
1122     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
1123         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
1124         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
1126         g_assert(dc->cal1->end > 1);
1127         g_assert(rev_cal2->end > 1);
1128         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
1129         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
1130         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
1131         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
1132         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
1133         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
1135         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
1137         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);
1139         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
1141         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);
1143         sp_curve_closepath(dc->accumulated);
1145         sp_curve_unref(rev_cal2);
1147         sp_curve_reset(dc->cal1);
1148         sp_curve_reset(dc->cal2);
1149     }
1152 static double square(double const x)
1154     return x * x;
1157 static void
1158 fit_and_split(SPDynaDrawContext *dc, gboolean release)
1160     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
1162 #ifdef DYNA_DRAW_VERBOSE
1163     g_print("[F&S:R=%c]", release?'T':'F');
1164 #endif
1166     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
1167         return; // just clicked
1169     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
1170 #define BEZIER_SIZE       4
1171 #define BEZIER_MAX_BEZIERS  8
1172 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
1174 #ifdef DYNA_DRAW_VERBOSE
1175         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
1176                 dc->npoints, release ? "TRUE" : "FALSE");
1177 #endif
1179         /* Current calligraphic */
1180         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
1181             /* dc->npoints > 0 */
1182             /* g_print("calligraphics(1|2) reset\n"); */
1183             sp_curve_reset(dc->cal1);
1184             sp_curve_reset(dc->cal2);
1186             sp_curve_moveto(dc->cal1, dc->point1[0]);
1187             sp_curve_moveto(dc->cal2, dc->point2[0]);
1188         }
1190         NR::Point b1[BEZIER_MAX_LENGTH];
1191         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
1192                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1193         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
1195         NR::Point b2[BEZIER_MAX_LENGTH];
1196         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
1197                                                tolerance_sq, BEZIER_MAX_BEZIERS);
1198         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
1200         if ( nb1 != -1 && nb2 != -1 ) {
1201             /* Fit and draw and reset state */
1202 #ifdef DYNA_DRAW_VERBOSE
1203             g_print("nb1:%d nb2:%d\n", nb1, nb2);
1204 #endif
1205             /* CanvasShape */
1206             if (! release) {
1207                 sp_curve_reset(dc->currentcurve);
1208                 sp_curve_moveto(dc->currentcurve, b1[0]);
1209                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1210                     sp_curve_curveto(dc->currentcurve, bp1[1],
1211                                      bp1[2], bp1[3]);
1212                 }
1213                 sp_curve_lineto(dc->currentcurve,
1214                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
1215                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
1216                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
1217                 }
1218                 // FIXME: dc->segments is always NULL at this point??
1219                 if (!dc->segments) { // first segment
1220                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
1221                 }
1222                 sp_curve_closepath(dc->currentcurve);
1223                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1224             }
1226             /* Current calligraphic */
1227             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
1228                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
1229             }
1230             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
1231                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
1232             }
1233         } else {
1234             /* fixme: ??? */
1235 #ifdef DYNA_DRAW_VERBOSE
1236             g_print("[fit_and_split] failed to fit-cubic.\n");
1237 #endif
1238             draw_temporary_box(dc);
1240             for (gint i = 1; i < dc->npoints; i++) {
1241                 sp_curve_lineto(dc->cal1, dc->point1[i]);
1242             }
1243             for (gint i = 1; i < dc->npoints; i++) {
1244                 sp_curve_lineto(dc->cal2, dc->point2[i]);
1245             }
1246         }
1248         /* Fit and draw and copy last point */
1249 #ifdef DYNA_DRAW_VERBOSE
1250         g_print("[%d]Yup\n", dc->npoints);
1251 #endif
1252         if (!release) {
1253             g_assert(!sp_curve_empty(dc->currentcurve));
1255             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
1256                                                    SP_TYPE_CANVAS_BPATH,
1257                                                    NULL);
1258             SPCurve *curve = sp_curve_copy(dc->currentcurve);
1259             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
1260             sp_curve_unref(curve);
1262             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1263             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1264             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
1265             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
1266             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
1267             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
1268             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
1269             //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);
1270             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
1271             /* fixme: Cannot we cascade it to root more clearly? */
1272             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
1274             dc->segments = g_slist_prepend(dc->segments, cbp);
1275         }
1277         dc->point1[0] = dc->point1[dc->npoints - 1];
1278         dc->point2[0] = dc->point2[dc->npoints - 1];
1279         dc->npoints = 1;
1280     } else {
1281         draw_temporary_box(dc);
1282     }
1285 static void
1286 draw_temporary_box(SPDynaDrawContext *dc)
1288     sp_curve_reset(dc->currentcurve);
1290     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
1291     for (gint i = dc->npoints-2; i >= 0; i--) {
1292         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
1293     }
1294     for (gint i = 0; i < dc->npoints; i++) {
1295         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
1296     }
1297     if (dc->npoints >= 2) {
1298         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);
1299     }
1301     sp_curve_closepath(dc->currentcurve);
1302     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
1305 /*
1306   Local Variables:
1307   mode:c++
1308   c-file-style:"stroustrup"
1309   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1310   indent-tabs-mode:nil
1311   fill-column:99
1312   End:
1313 */
1314 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :