Code

tweak parameters for more responsiveness
[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-2006 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 "svg/svg.h"
33 #include "display/canvas-bpath.h"
34 #include "display/bezier-utils.h"
36 #include <glib/gmem.h>
37 #include "macros.h"
38 #include "document.h"
39 #include "selection.h"
40 #include "desktop.h"
41 #include "desktop-events.h"
42 #include "desktop-handles.h"
43 #include "desktop-affine.h"
44 #include "desktop-style.h"
45 #include "message-context.h"
46 #include "pixmaps/cursor-calligraphy.xpm"
47 #include "dyna-draw-context.h"
48 #include "libnr/n-art-bpath.h"
49 #include "libnr/nr-path.h"
50 #include "xml/repr.h"
51 #include "context-fns.h"
52 #include "sp-item.h"
53 #include "inkscape.h"
54 #include "color.h"
56 #define DDC_RED_RGBA 0xff0000ff
58 #define SAMPLE_TIMEOUT 10
59 #define TOLERANCE_LINE 1.0
60 #define TOLERANCE_CALLIGRAPHIC 3.0
62 #define DYNA_EPSILON 0.5e-6
63 #define DYNA_EPSILON_START 0.5e-2
64 #define DYNA_VEL_START 1e-5
66 #define DYNA_MIN_WIDTH 1.0e-6
68 #define DRAG_MIN 0.0
69 #define DRAG_DEFAULT 1.0
70 #define DRAG_MAX 1.0
72 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
73 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
74 static void sp_dyna_draw_context_dispose(GObject *object);
76 static void sp_dyna_draw_context_setup(SPEventContext *ec);
77 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
78 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
80 static void clear_current(SPDynaDrawContext *dc);
81 static void set_to_accumulated(SPDynaDrawContext *dc);
82 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
83 static void accumulate_calligraphic(SPDynaDrawContext *dc);
85 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
87 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
88 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
89 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
90 static void draw_temporary_box(SPDynaDrawContext *dc);
93 static SPEventContextClass *parent_class;
95 GtkType
96 sp_dyna_draw_context_get_type(void)
97 {
98     static GType type = 0;
99     if (!type) {
100         GTypeInfo info = {
101             sizeof(SPDynaDrawContextClass),
102             NULL, NULL,
103             (GClassInitFunc) sp_dyna_draw_context_class_init,
104             NULL, NULL,
105             sizeof(SPDynaDrawContext),
106             4,
107             (GInstanceInitFunc) sp_dyna_draw_context_init,
108             NULL,   /* value_table */
109         };
110         type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
111     }
112     return type;
115 static void
116 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
118     GObjectClass *object_class = (GObjectClass *) klass;
119     SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
121     parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
123     object_class->dispose = sp_dyna_draw_context_dispose;
125     event_context_class->setup = sp_dyna_draw_context_setup;
126     event_context_class->set = sp_dyna_draw_context_set;
127     event_context_class->root_handler = sp_dyna_draw_context_root_handler;
130 static void
131 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
133     SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
135     event_context->cursor_shape = cursor_calligraphy_xpm;
136     event_context->hot_x = 4;
137     event_context->hot_y = 4;
139     ddc->accumulated = NULL;
140     ddc->segments = NULL;
141     ddc->currentcurve = NULL;
142     ddc->currentshape = NULL;
143     ddc->npoints = 0;
144     ddc->cal1 = NULL;
145     ddc->cal2 = NULL;
146     ddc->repr = NULL;
148     /* DynaDraw values */
149     ddc->cur = NR::Point(0,0);
150     ddc->last = NR::Point(0,0);
151     ddc->vel = NR::Point(0,0);
152     ddc->vel_max = 0;
153     ddc->acc = NR::Point(0,0);
154     ddc->ang = NR::Point(0,0);
155     ddc->del = NR::Point(0,0);
157     /* attributes */
158     ddc->dragging = FALSE;
160     ddc->mass = 0.3;
161     ddc->drag = DRAG_DEFAULT;
162     ddc->angle = 30.0;
163     ddc->width = 0.2;
165     ddc->vel_thin = 0.1;
166     ddc->flatness = 0.9;
167     ddc->cap_rounding = 0.0;
169     ddc->abs_width = false;
170     ddc->keep_selected = true;
173 static void
174 sp_dyna_draw_context_dispose(GObject *object)
176     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
178     if (ddc->accumulated) {
179         ddc->accumulated = sp_curve_unref(ddc->accumulated);
180     }
182     while (ddc->segments) {
183         gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
184         ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
185     }
187     if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
188     if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
189     if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
191     if (ddc->currentshape) {
192         gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
193         ddc->currentshape = NULL;
194     }
196     if (ddc->_message_context) {
197         delete ddc->_message_context;
198     }
200     G_OBJECT_CLASS(parent_class)->dispose(object);
203 static void
204 sp_dyna_draw_context_setup(SPEventContext *ec)
206     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
208     if (((SPEventContextClass *) parent_class)->setup)
209         ((SPEventContextClass *) parent_class)->setup(ec);
211     ddc->accumulated = sp_curve_new_sized(32);
212     ddc->currentcurve = sp_curve_new_sized(4);
214     ddc->cal1 = sp_curve_new_sized(32);
215     ddc->cal2 = sp_curve_new_sized(32);
217     ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
218     sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
219     sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
220     /* fixme: Cannot we cascade it to root more clearly? */
221     g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
223     sp_event_context_read(ec, "mass");
224     sp_event_context_read(ec, "wiggle");
225     sp_event_context_read(ec, "angle");
226     sp_event_context_read(ec, "width");
227     sp_event_context_read(ec, "thinning");
228     sp_event_context_read(ec, "tremor");
229     sp_event_context_read(ec, "flatness");
230     sp_event_context_read(ec, "usepressure");
231     sp_event_context_read(ec, "usetilt");
232     sp_event_context_read(ec, "abs_width");
233     sp_event_context_read(ec, "keep_selected");
234     sp_event_context_read(ec, "cap_rounding");
236     ddc->is_drawing = false;
238     ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
241 static void
242 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
244     SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
246     if (!strcmp(key, "mass")) {
247         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
248         ddc->mass = CLAMP(dval, -1000.0, 1000.0);
249     } else if (!strcmp(key, "wiggle")) {
250         double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
251         ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
252     } else if (!strcmp(key, "angle")) {
253         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
254         ddc->angle = CLAMP (dval, -90, 90);
255     } else if (!strcmp(key, "width")) {
256         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
257         ddc->width = CLAMP(dval, -1000.0, 1000.0);
258     } else if (!strcmp(key, "thinning")) {
259         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
260         ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
261     } else if (!strcmp(key, "tremor")) {
262         double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
263         ddc->tremor = CLAMP(dval, 0.0, 1.0);
264     } else if (!strcmp(key, "flatness")) {
265         double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
266         ddc->flatness = CLAMP(dval, 0, 1.0);
267     } else if (!strcmp(key, "usepressure")) {
268         ddc->usepressure = (val && strcmp(val, "0"));
269     } else if (!strcmp(key, "usetilt")) {
270         ddc->usetilt = (val && strcmp(val, "0"));
271     } else if (!strcmp(key, "abs_width")) {
272         ddc->abs_width = (val && strcmp(val, "0"));
273     } else if (!strcmp(key, "keep_selected")) {
274         ddc->keep_selected = (val && strcmp(val, "0"));
275     } else if (!strcmp(key, "cap_rounding")) {
276         ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
277     }
279     //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
282 static double
283 flerp(double f0, double f1, double p)
285     return f0 + ( f1 - f0 ) * p;
288 /* Get normalized point */
289 static NR::Point
290 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
292     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
293     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
294     return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max,  ( v[NR::Y] - drect.min()[NR::Y] ) / max);
297 /* Get view point */
298 static NR::Point
299 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
301     NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
302     double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
303     return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
306 static void
307 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
309     dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
310     dc->vel = NR::Point(0,0);
311     dc->vel_max = 0;
312     dc->acc = NR::Point(0,0);
313     dc->ang = NR::Point(0,0);
314     dc->del = NR::Point(0,0);
317 static void
318 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
320     if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
321         dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
322     else
323         dc->pressure = DDC_DEFAULT_PRESSURE;
325     if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
326         dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
327     else
328         dc->xtilt = DDC_DEFAULT_TILT;
330     if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
331         dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
332     else
333         dc->ytilt = DDC_DEFAULT_TILT;
337 static gboolean
338 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
340     NR::Point n = sp_dyna_draw_get_npoint(dc, p);
342     /* Calculate mass and drag */
343     double const mass = flerp(1.0, 160.0, dc->mass);
344     double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
346     /* Calculate force and acceleration */
347     NR::Point force = n - dc->cur;
348     if ( NR::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && NR::L2(force) < DYNA_EPSILON_START)) {
349         return FALSE;
350     }
352     dc->acc = force / mass;
354     /* Calculate new velocity */
355     dc->vel += dc->acc;
357     if (NR::L2(dc->vel) > dc->vel_max)
358         dc->vel_max = NR::L2(dc->vel);
360     /* Calculate angle of drawing tool */
362     double a1;
363     if (dc->usetilt) {
364         // 1a. calculate nib angle from input device tilt:
365         gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
367         if (length > 0) {
368             NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
369             a1 = atan2(ang1);
370         }
371         else
372             a1 = 0.0;
373     }
374     else {
375         // 1b. fixed dc->angle (absolutely flat nib):
376         double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
377         NR::Point ang1 = NR::Point(-sin(radians),  cos(radians));
378         a1 = atan2(ang1);
379     }
381     // 2. perpendicular to dc->vel (absolutely non-flat nib):
382     gdouble const mag_vel = NR::L2(dc->vel);
383     if ( mag_vel < DYNA_EPSILON ) {
384         return FALSE;
385     }
386     NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
388     // 3. Average them using flatness parameter:
389     // calculate angles
390     double a2 = atan2(ang2);
391     // flip a2 to force it to be in the same half-circle as a1
392     bool flipped = false;
393     if (fabs (a2-a1) > 0.5*M_PI) {
394         a2 += M_PI;
395         flipped = true;
396     }
397     // normalize a2
398     if (a2 > M_PI)
399         a2 -= 2*M_PI;
400     if (a2 < -M_PI)
401         a2 += 2*M_PI;
402     // find the flatness-weighted bisector angle, unflip if a2 was flipped
403     // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
404     double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
406     double angle_delta = NR::L2(NR::Point (cos (new_ang), sin (new_ang)) - dc->ang);
408     if ( angle_delta / NR::L2(dc->vel) > 4000 ) {
409         return FALSE;
410     }
412     // convert to point
413     dc->ang = NR::Point (cos (new_ang), sin (new_ang));
415 //    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);
417     /* Apply drag */
418     dc->vel *= 1.0 - drag;
420     /* Update position */
421     dc->last = dc->cur;
422     dc->cur += dc->vel;
424     return TRUE;
427 static void
428 sp_dyna_draw_brush(SPDynaDrawContext *dc)
430     g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
432     // How much velocity thins strokestyle
433     double vel_thin = flerp (0, 160, dc->vel_thin);
435     // Influence of pressure on thickness
436     double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
438     double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
440     double tremble_left = 0, tremble_right = 0;
441     if (dc->tremor > 0) {
442         // obtain two normally distributed random variables, using polar Box-Muller transform
443         double x1, x2, w, y1, y2;
444         do {
445             x1 = 2.0 * g_random_double_range(0,1) - 1.0;
446             x2 = 2.0 * g_random_double_range(0,1) - 1.0;
447             w = x1 * x1 + x2 * x2;
448         } while ( w >= 1.0 );
449         w = sqrt( (-2.0 * log( w ) ) / w );
450         y1 = x1 * w;
451         y2 = x2 * w;
453         // deflect both left and right edges randomly and independently, so that:
454         // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
455         // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
456         // (3) deflection somewhat depends on speed, to prevent fast strokes looking
457         // comparatively smooth and slow ones excessively jittery
458         tremble_left  = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
459         tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
460     }
462     if ( width < 0.02 * dc->width ) {
463         width = 0.02 * dc->width;
464     }
466     double dezoomify_factor = 0.05 * 1000;
467     if (!dc->abs_width) {
468         dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
469     }
471     NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
472     NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
474     NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
476     dc->point1[dc->npoints] = abs_middle + del_left;
477     dc->point2[dc->npoints] = abs_middle - del_right;
479     dc->del = 0.5*(del_left + del_right);
481     dc->npoints++;
484 void
485 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
487     desktop->setToolboxAdjustmentValue (id, value);
490 gint
491 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
492                                   GdkEvent *event)
494     SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
495     SPDesktop *desktop = event_context->desktop;
497     gint ret = FALSE;
499     switch (event->type) {
500     case GDK_BUTTON_PRESS:
501         if ( event->button.button == 1 ) {
503             SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
505             if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
506                 return TRUE;
507             }
509             NR::Point const button_w(event->button.x,
510                                      event->button.y);
511             NR::Point const button_dt(desktop->w2d(button_w));
512             sp_dyna_draw_reset(dc, button_dt);
513             sp_dyna_draw_extinput(dc, event);
514             sp_dyna_draw_apply(dc, button_dt);
515             sp_curve_reset(dc->accumulated);
516             if (dc->repr) {
517                 dc->repr = NULL;
518             }
520             /* initialize first point */
521             dc->npoints = 0;
523             sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
524                                 ( GDK_KEY_PRESS_MASK |
525                                   GDK_BUTTON_RELEASE_MASK |
526                                   GDK_POINTER_MOTION_MASK |
527                                   GDK_BUTTON_PRESS_MASK ),
528                                 NULL,
529                                 event->button.time);
531             ret = TRUE;
533             dc->is_drawing = true;
534         }
535         break;
536     case GDK_MOTION_NOTIFY:
537         if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
538             dc->dragging = TRUE;
540             NR::Point const motion_w(event->motion.x,
541                                      event->motion.y);
542             NR::Point const motion_dt(desktop->w2d(motion_w));
544             sp_dyna_draw_extinput(dc, event);
545             if (!sp_dyna_draw_apply(dc, motion_dt)) {
546                 ret = TRUE;
547                 break;
548             }
550             if ( dc->cur != dc->last ) {
551                 sp_dyna_draw_brush(dc);
552                 g_assert( dc->npoints > 0 );
553                 fit_and_split(dc, FALSE);
554             }
555             ret = TRUE;
556         }
557         break;
559     case GDK_BUTTON_RELEASE:
560         sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
561         dc->is_drawing = false;
563         if ( dc->dragging && event->button.button == 1 ) {
564             dc->dragging = FALSE;
566             NR::Point const motion_w(event->button.x, event->button.y);
567             NR::Point const motion_dt(desktop->w2d(motion_w));
568             sp_dyna_draw_apply(dc, motion_dt);
570             /* Remove all temporary line segments */
571             while (dc->segments) {
572                 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
573                 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
574             }
575             /* Create object */
576             fit_and_split(dc, TRUE);
577             accumulate_calligraphic(dc);
578             set_to_accumulated(dc); /* temporal implementation */
579             /* reset accumulated curve */
580             sp_curve_reset(dc->accumulated);
581             clear_current(dc);
582             if (dc->repr) {
583                 dc->repr = NULL;
584             }
585             ret = TRUE;
586         }
587         break;
588     case GDK_KEY_PRESS:
589         switch (get_group0_keyval (&event->key)) {
590         case GDK_Up:
591         case GDK_KP_Up:
592             if (!MOD__CTRL_ONLY) {
593                 dc->angle += 5.0;
594                 if (dc->angle > 90.0)
595                     dc->angle = 90.0;
596                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
597                 ret = TRUE;
598             }
599             break;
600         case GDK_Down:
601         case GDK_KP_Down:
602             if (!MOD__CTRL_ONLY) {
603                 dc->angle -= 5.0;
604                 if (dc->angle < -90.0)
605                     dc->angle = -90.0;
606                 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
607                 ret = TRUE;
608             }
609             break;
610         case GDK_Right:
611         case GDK_KP_Right:
612             if (!MOD__CTRL_ONLY) {
613                 dc->width += 0.01;
614                 if (dc->width > 1.0)
615                     dc->width = 1.0;
616                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
617                 ret = TRUE;
618             }
619             break;
620         case GDK_Left:
621         case GDK_KP_Left:
622             if (!MOD__CTRL_ONLY) {
623                 dc->width -= 0.01;
624                 if (dc->width < 0.01)
625                     dc->width = 0.01;
626                 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
627                 ret = TRUE;
628             }
629             break;
630         case GDK_x:
631         case GDK_X:
632             if (MOD__ALT_ONLY) {
633                 desktop->setToolboxFocusTo ("altx-calligraphy");
634                 ret = TRUE;
635             }
636             break;
637         case GDK_Escape:
638             sp_desktop_selection(desktop)->clear();
639             break;
641         default:
642             break;
643         }
644     default:
645         break;
646     }
648     if (!ret) {
649         if (((SPEventContextClass *) parent_class)->root_handler) {
650             ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
651         }
652     }
654     return ret;
658 static void
659 clear_current(SPDynaDrawContext *dc)
661     /* reset bpath */
662     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
663     /* reset curve */
664     sp_curve_reset(dc->currentcurve);
665     sp_curve_reset(dc->cal1);
666     sp_curve_reset(dc->cal2);
667     /* reset points */
668     dc->npoints = 0;
671 static void
672 set_to_accumulated(SPDynaDrawContext *dc)
674     SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
676     if (!sp_curve_empty(dc->accumulated)) {
677         NArtBpath *abp;
678         gchar *str;
680         if (!dc->repr) {
681             /* Create object */
682             Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
683             Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
685             /* Set style */
686             sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
688             dc->repr = repr;
690             SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
691             Inkscape::GC::release(dc->repr);
692             item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
693             item->updateRepr();
694             if (dc->keep_selected) {
695                 sp_desktop_selection(desktop)->set(dc->repr);
696             } else {
697                 sp_desktop_selection(desktop)->clear();
698             }
699         }
700         abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
701         str = sp_svg_write_path(abp);
702         g_assert( str != NULL );
703         g_free(abp);
704         dc->repr->setAttribute("d", str);
705         g_free(str);
706     } else {
707         if (dc->repr) {
708             sp_repr_unparent(dc->repr);
709         }
710         dc->repr = NULL;
711     }
713     sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC, 
714                      _("Create calligraphic stroke"));
717 static void
718 add_cap(SPCurve *curve,
719         NR::Point const &pre, NR::Point const &from,
720         NR::Point const &to, NR::Point const &post,
721         double rounding)
723     NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
724     double mag = NR::L2(vel);
726     NR::Point v_in = from - pre;
727     double mag_in = NR::L2(v_in);
728     if ( mag_in > DYNA_EPSILON ) {
729         v_in = mag * v_in / mag_in;
730     } else {
731         v_in = NR::Point(0, 0);
732     }
734     NR::Point v_out = to - post;
735     double mag_out = NR::L2(v_out);
736     if ( mag_out > DYNA_EPSILON ) {
737         v_out = mag * v_out / mag_out;
738     } else {
739         v_out = NR::Point(0, 0);
740     }
742     if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
743         sp_curve_curveto(curve, from + v_in, to + v_out, to);
744     }
747 static void
748 accumulate_calligraphic(SPDynaDrawContext *dc)
750     if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
751         sp_curve_reset(dc->accumulated); /*  Is this required ?? */
752         SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
754         g_assert(dc->cal1->end > 1);
755         g_assert(rev_cal2->end > 1);
756         g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
757         g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
758         g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
759         g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
760         g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
761         g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
763         sp_curve_append(dc->accumulated, dc->cal1, FALSE);
765         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);
767         sp_curve_append(dc->accumulated, rev_cal2, TRUE);
769         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);
771         sp_curve_closepath(dc->accumulated);
773         sp_curve_unref(rev_cal2);
775         sp_curve_reset(dc->cal1);
776         sp_curve_reset(dc->cal2);
777     }
780 static double square(double const x)
782     return x * x;
785 static void
786 fit_and_split(SPDynaDrawContext *dc, gboolean release)
788     double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
790 #ifdef DYNA_DRAW_VERBOSE
791     g_print("[F&S:R=%c]", release?'T':'F');
792 #endif
794     if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
795         return; // just clicked
797     if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
798 #define BEZIER_SIZE       4
799 #define BEZIER_MAX_BEZIERS  8
800 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
802 #ifdef DYNA_DRAW_VERBOSE
803         g_print("[F&S:#] dc->npoints:%d, release:%s\n",
804                 dc->npoints, release ? "TRUE" : "FALSE");
805 #endif
807         /* Current calligraphic */
808         if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
809             /* dc->npoints > 0 */
810             /* g_print("calligraphics(1|2) reset\n"); */
811             sp_curve_reset(dc->cal1);
812             sp_curve_reset(dc->cal2);
814             sp_curve_moveto(dc->cal1, dc->point1[0]);
815             sp_curve_moveto(dc->cal2, dc->point2[0]);
816         }
818         NR::Point b1[BEZIER_MAX_LENGTH];
819         gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
820                                                tolerance_sq, BEZIER_MAX_BEZIERS);
821         g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
823         NR::Point b2[BEZIER_MAX_LENGTH];
824         gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
825                                                tolerance_sq, BEZIER_MAX_BEZIERS);
826         g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
828         if ( nb1 != -1 && nb2 != -1 ) {
829             /* Fit and draw and reset state */
830 #ifdef DYNA_DRAW_VERBOSE
831             g_print("nb1:%d nb2:%d\n", nb1, nb2);
832 #endif
833             /* CanvasShape */
834             if (! release) {
835                 sp_curve_reset(dc->currentcurve);
836                 sp_curve_moveto(dc->currentcurve, b1[0]);
837                 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
838                     sp_curve_curveto(dc->currentcurve, bp1[1],
839                                      bp1[2], bp1[3]);
840                 }
841                 sp_curve_lineto(dc->currentcurve,
842                                 b2[BEZIER_SIZE*(nb2-1) + 3]);
843                 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
844                     sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
845                 }
846                 // FIXME: dc->segments is always NULL at this point??
847                 if (!dc->segments) { // first segment
848                     add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
849                 }
850                 sp_curve_closepath(dc->currentcurve);
851                 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
852             }
854             /* Current calligraphic */
855             for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
856                 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
857             }
858             for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
859                 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
860             }
861         } else {
862             /* fixme: ??? */
863 #ifdef DYNA_DRAW_VERBOSE
864             g_print("[fit_and_split] failed to fit-cubic.\n");
865 #endif
866             draw_temporary_box(dc);
868             for (gint i = 1; i < dc->npoints; i++) {
869                 sp_curve_lineto(dc->cal1, dc->point1[i]);
870             }
871             for (gint i = 1; i < dc->npoints; i++) {
872                 sp_curve_lineto(dc->cal2, dc->point2[i]);
873             }
874         }
876         /* Fit and draw and copy last point */
877 #ifdef DYNA_DRAW_VERBOSE
878         g_print("[%d]Yup\n", dc->npoints);
879 #endif
880         if (!release) {
881             g_assert(!sp_curve_empty(dc->currentcurve));
883             SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
884                                                    SP_TYPE_CANVAS_BPATH,
885                                                    NULL);
886             SPCurve *curve = sp_curve_copy(dc->currentcurve);
887             sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
888             sp_curve_unref(curve);
890             guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
891             //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
892             double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
893             double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
894             //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
895             sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
896             //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
897             //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);
898             sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
899             /* fixme: Cannot we cascade it to root more clearly? */
900             g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
902             dc->segments = g_slist_prepend(dc->segments, cbp);
903         }
905         dc->point1[0] = dc->point1[dc->npoints - 1];
906         dc->point2[0] = dc->point2[dc->npoints - 1];
907         dc->npoints = 1;
908     } else {
909         draw_temporary_box(dc);
910     }
913 static void
914 draw_temporary_box(SPDynaDrawContext *dc)
916     sp_curve_reset(dc->currentcurve);
918     sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
919     for (gint i = dc->npoints-2; i >= 0; i--) {
920         sp_curve_lineto(dc->currentcurve, dc->point1[i]);
921     }
922     for (gint i = 0; i < dc->npoints; i++) {
923         sp_curve_lineto(dc->currentcurve, dc->point2[i]);
924     }
925     if (dc->npoints >= 2) {
926         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);
927     }
929     sp_curve_closepath(dc->currentcurve);
930     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
933 /*
934   Local Variables:
935   mode:c++
936   c-file-style:"stroustrup"
937   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
938   indent-tabs-mode:nil
939   fill-column:99
940   End:
941 */
942 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :