5c60eeb412ba2ff508ce6e1ef2ada80d0179834c
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
61 #define DYNA_EPSILON 0.5e-2
63 #define DYNA_MIN_WIDTH 1.0e-6
65 #define DRAG_MIN 0.0
66 #define DRAG_DEFAULT 1.0
67 #define DRAG_MAX 1.0
69 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
70 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
71 static void sp_dyna_draw_context_dispose(GObject *object);
73 static void sp_dyna_draw_context_setup(SPEventContext *ec);
74 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
75 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
77 static void clear_current(SPDynaDrawContext *dc);
78 static void set_to_accumulated(SPDynaDrawContext *dc);
79 static void add_cap(SPCurve *curve, NR::Point const &pre, NR::Point const &from, NR::Point const &to, NR::Point const &post, double rounding);
80 static void accumulate_calligraphic(SPDynaDrawContext *dc);
82 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
84 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
85 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
86 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
87 static void draw_temporary_box(SPDynaDrawContext *dc);
90 static SPEventContextClass *parent_class;
92 GtkType
93 sp_dyna_draw_context_get_type(void)
94 {
95 static GType type = 0;
96 if (!type) {
97 GTypeInfo info = {
98 sizeof(SPDynaDrawContextClass),
99 NULL, NULL,
100 (GClassInitFunc) sp_dyna_draw_context_class_init,
101 NULL, NULL,
102 sizeof(SPDynaDrawContext),
103 4,
104 (GInstanceInitFunc) sp_dyna_draw_context_init,
105 NULL, /* value_table */
106 };
107 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
108 }
109 return type;
110 }
112 static void
113 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
114 {
115 GObjectClass *object_class = (GObjectClass *) klass;
116 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
118 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
120 object_class->dispose = sp_dyna_draw_context_dispose;
122 event_context_class->setup = sp_dyna_draw_context_setup;
123 event_context_class->set = sp_dyna_draw_context_set;
124 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
125 }
127 static void
128 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
129 {
130 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
132 event_context->cursor_shape = cursor_calligraphy_xpm;
133 event_context->hot_x = 4;
134 event_context->hot_y = 4;
136 ddc->accumulated = NULL;
137 ddc->segments = NULL;
138 ddc->currentcurve = NULL;
139 ddc->currentshape = NULL;
140 ddc->npoints = 0;
141 ddc->cal1 = NULL;
142 ddc->cal2 = NULL;
143 ddc->repr = NULL;
145 /* DynaDraw values */
146 ddc->cur = NR::Point(0,0);
147 ddc->last = NR::Point(0,0);
148 ddc->vel = NR::Point(0,0);
149 ddc->acc = NR::Point(0,0);
150 ddc->ang = NR::Point(0,0);
151 ddc->del = NR::Point(0,0);
153 /* attributes */
154 ddc->dragging = FALSE;
156 ddc->mass = 0.3;
157 ddc->drag = DRAG_DEFAULT;
158 ddc->angle = 30.0;
159 ddc->width = 0.2;
161 ddc->vel_thin = 0.1;
162 ddc->flatness = 0.9;
163 ddc->cap_rounding = 0.0;
165 ddc->abs_width = false;
166 ddc->keep_selected = true;
167 }
169 static void
170 sp_dyna_draw_context_dispose(GObject *object)
171 {
172 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
174 if (ddc->accumulated) {
175 ddc->accumulated = sp_curve_unref(ddc->accumulated);
176 }
178 while (ddc->segments) {
179 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
180 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
181 }
183 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
184 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
185 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
187 if (ddc->currentshape) {
188 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
189 ddc->currentshape = NULL;
190 }
192 if (ddc->_message_context) {
193 delete ddc->_message_context;
194 }
196 G_OBJECT_CLASS(parent_class)->dispose(object);
197 }
199 static void
200 sp_dyna_draw_context_setup(SPEventContext *ec)
201 {
202 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
204 if (((SPEventContextClass *) parent_class)->setup)
205 ((SPEventContextClass *) parent_class)->setup(ec);
207 ddc->accumulated = sp_curve_new_sized(32);
208 ddc->currentcurve = sp_curve_new_sized(4);
210 ddc->cal1 = sp_curve_new_sized(32);
211 ddc->cal2 = sp_curve_new_sized(32);
213 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
214 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
215 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
216 /* fixme: Cannot we cascade it to root more clearly? */
217 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
219 sp_event_context_read(ec, "mass");
220 sp_event_context_read(ec, "wiggle");
221 sp_event_context_read(ec, "angle");
222 sp_event_context_read(ec, "width");
223 sp_event_context_read(ec, "thinning");
224 sp_event_context_read(ec, "tremor");
225 sp_event_context_read(ec, "flatness");
226 sp_event_context_read(ec, "usepressure");
227 sp_event_context_read(ec, "usetilt");
228 sp_event_context_read(ec, "abs_width");
229 sp_event_context_read(ec, "keep_selected");
230 sp_event_context_read(ec, "cap_rounding");
232 ddc->is_drawing = false;
234 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
235 }
237 static void
238 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
239 {
240 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
242 if (!strcmp(key, "mass")) {
243 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
244 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
245 } else if (!strcmp(key, "wiggle")) {
246 double const dval = ( val ? g_ascii_strtod (val, NULL) : (1 - DRAG_DEFAULT));
247 ddc->drag = CLAMP((1 - dval), DRAG_MIN, DRAG_MAX); // drag is inverse to wiggle
248 } else if (!strcmp(key, "angle")) {
249 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
250 ddc->angle = CLAMP (dval, -90, 90);
251 } else if (!strcmp(key, "width")) {
252 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
253 ddc->width = CLAMP(dval, -1000.0, 1000.0);
254 } else if (!strcmp(key, "thinning")) {
255 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
256 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
257 } else if (!strcmp(key, "tremor")) {
258 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
259 ddc->tremor = CLAMP(dval, 0.0, 1.0);
260 } else if (!strcmp(key, "flatness")) {
261 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
262 ddc->flatness = CLAMP(dval, 0, 1.0);
263 } else if (!strcmp(key, "usepressure")) {
264 ddc->usepressure = (val && strcmp(val, "0"));
265 } else if (!strcmp(key, "usetilt")) {
266 ddc->usetilt = (val && strcmp(val, "0"));
267 } else if (!strcmp(key, "abs_width")) {
268 ddc->abs_width = (val && strcmp(val, "0"));
269 } else if (!strcmp(key, "keep_selected")) {
270 ddc->keep_selected = (val && strcmp(val, "0"));
271 } else if (!strcmp(key, "cap_rounding")) {
272 ddc->cap_rounding = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
273 }
275 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
276 }
278 static double
279 flerp(double f0, double f1, double p)
280 {
281 return f0 + ( f1 - f0 ) * p;
282 }
284 /* Get normalized point */
285 static NR::Point
286 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
287 {
288 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
289 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
290 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
291 }
293 /* Get view point */
294 static NR::Point
295 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
296 {
297 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
298 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
299 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
300 }
302 static void
303 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
304 {
305 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
306 dc->vel = NR::Point(0,0);
307 dc->acc = NR::Point(0,0);
308 dc->ang = NR::Point(0,0);
309 dc->del = NR::Point(0,0);
310 }
312 static void
313 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
314 {
315 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
316 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
317 else
318 dc->pressure = DDC_DEFAULT_PRESSURE;
320 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
321 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
322 else
323 dc->xtilt = DDC_DEFAULT_TILT;
325 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
326 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
327 else
328 dc->ytilt = DDC_DEFAULT_TILT;
329 }
332 static gboolean
333 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
334 {
335 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
337 /* Calculate mass and drag */
338 double const mass = flerp(1.0, 160.0, dc->mass);
339 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
341 /* Calculate force and acceleration */
342 NR::Point force = n - dc->cur;
343 if ( NR::L2(force) < DYNA_EPSILON ) {
344 return FALSE;
345 }
347 dc->acc = force / mass;
349 /* Calculate new velocity */
350 dc->vel += dc->acc;
352 /* Calculate angle of drawing tool */
354 double a1;
355 if (dc->usetilt) {
356 // 1a. calculate nib angle from input device tilt:
357 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
359 if (length > 0) {
360 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
361 a1 = atan2(ang1);
362 }
363 else
364 a1 = 0.0;
365 }
366 else {
367 // 1b. fixed dc->angle (absolutely flat nib):
368 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
369 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
370 a1 = atan2(ang1);
371 }
373 // 2. perpendicular to dc->vel (absolutely non-flat nib):
374 gdouble const mag_vel = NR::L2(dc->vel);
375 if ( mag_vel < DYNA_EPSILON ) {
376 return FALSE;
377 }
378 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
380 // 3. Average them using flatness parameter:
381 // calculate angles
382 double a2 = atan2(ang2);
383 // flip a2 to force it to be in the same half-circle as a1
384 bool flipped = false;
385 if (fabs (a2-a1) > 0.5*M_PI) {
386 a2 += M_PI;
387 flipped = true;
388 }
389 // normalize a2
390 if (a2 > M_PI)
391 a2 -= 2*M_PI;
392 if (a2 < -M_PI)
393 a2 += 2*M_PI;
394 // find the flatness-weighted bisector angle, unflip if a2 was flipped
395 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
396 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
397 // convert to point
398 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
400 /* Apply drag */
401 dc->vel *= 1.0 - drag;
403 /* Update position */
404 dc->last = dc->cur;
405 dc->cur += dc->vel;
407 return TRUE;
408 }
410 static void
411 sp_dyna_draw_brush(SPDynaDrawContext *dc)
412 {
413 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
415 // How much velocity thins strokestyle
416 double vel_thin = flerp (0, 160, dc->vel_thin);
418 // Influence of pressure on thickness
419 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
421 double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
423 double tremble_left = 0, tremble_right = 0;
424 if (dc->tremor > 0) {
425 // obtain two normally distributed random variables, using polar Box-Muller transform
426 double x1, x2, w, y1, y2;
427 do {
428 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
429 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
430 w = x1 * x1 + x2 * x2;
431 } while ( w >= 1.0 );
432 w = sqrt( (-2.0 * log( w ) ) / w );
433 y1 = x1 * w;
434 y2 = x2 * w;
436 // deflect both left and right edges randomly and independently, so that:
437 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
438 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
439 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
440 // comparatively smooth and slow ones excessively jittery
441 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
442 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
443 }
445 if ( width < 0.02 * dc->width ) {
446 width = 0.02 * dc->width;
447 }
449 double dezoomify_factor = 0.05 * 1000;
450 if (!dc->abs_width) {
451 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
452 }
454 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
455 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
457 NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
459 dc->point1[dc->npoints] = abs_middle + del_left;
460 dc->point2[dc->npoints] = abs_middle - del_right;
462 dc->del = 0.5*(del_left + del_right);
464 dc->npoints++;
465 }
467 void
468 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
469 {
470 desktop->setToolboxAdjustmentValue (id, value);
471 }
473 gint
474 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
475 GdkEvent *event)
476 {
477 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
478 SPDesktop *desktop = event_context->desktop;
480 gint ret = FALSE;
482 switch (event->type) {
483 case GDK_BUTTON_PRESS:
484 if ( event->button.button == 1 ) {
486 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
488 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
489 return TRUE;
490 }
492 NR::Point const button_w(event->button.x,
493 event->button.y);
494 NR::Point const button_dt(desktop->w2d(button_w));
495 sp_dyna_draw_reset(dc, button_dt);
496 sp_dyna_draw_extinput(dc, event);
497 sp_dyna_draw_apply(dc, button_dt);
498 sp_curve_reset(dc->accumulated);
499 if (dc->repr) {
500 dc->repr = NULL;
501 }
503 /* initialize first point */
504 dc->npoints = 0;
506 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
507 ( GDK_KEY_PRESS_MASK |
508 GDK_BUTTON_RELEASE_MASK |
509 GDK_POINTER_MOTION_MASK |
510 GDK_BUTTON_PRESS_MASK ),
511 NULL,
512 event->button.time);
514 ret = TRUE;
516 dc->is_drawing = true;
517 }
518 break;
519 case GDK_MOTION_NOTIFY:
520 if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
521 dc->dragging = TRUE;
523 NR::Point const motion_w(event->motion.x,
524 event->motion.y);
525 NR::Point const motion_dt(desktop->w2d(motion_w));
527 sp_dyna_draw_extinput(dc, event);
528 if (!sp_dyna_draw_apply(dc, motion_dt)) {
529 ret = TRUE;
530 break;
531 }
533 if ( dc->cur != dc->last ) {
534 sp_dyna_draw_brush(dc);
535 g_assert( dc->npoints > 0 );
536 fit_and_split(dc, FALSE);
537 }
538 ret = TRUE;
539 }
540 break;
542 case GDK_BUTTON_RELEASE:
543 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
544 dc->is_drawing = false;
546 if ( dc->dragging && event->button.button == 1 ) {
547 dc->dragging = FALSE;
549 NR::Point const motion_w(event->button.x, event->button.y);
550 NR::Point const motion_dt(desktop->w2d(motion_w));
551 sp_dyna_draw_apply(dc, motion_dt);
553 /* Remove all temporary line segments */
554 while (dc->segments) {
555 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
556 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
557 }
558 /* Create object */
559 fit_and_split(dc, TRUE);
560 accumulate_calligraphic(dc);
561 set_to_accumulated(dc); /* temporal implementation */
562 /* reset accumulated curve */
563 sp_curve_reset(dc->accumulated);
564 clear_current(dc);
565 if (dc->repr) {
566 dc->repr = NULL;
567 }
568 ret = TRUE;
569 }
570 break;
571 case GDK_KEY_PRESS:
572 switch (get_group0_keyval (&event->key)) {
573 case GDK_Up:
574 case GDK_KP_Up:
575 if (!MOD__CTRL_ONLY) {
576 dc->angle += 5.0;
577 if (dc->angle > 90.0)
578 dc->angle = 90.0;
579 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
580 ret = TRUE;
581 }
582 break;
583 case GDK_Down:
584 case GDK_KP_Down:
585 if (!MOD__CTRL_ONLY) {
586 dc->angle -= 5.0;
587 if (dc->angle < -90.0)
588 dc->angle = -90.0;
589 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
590 ret = TRUE;
591 }
592 break;
593 case GDK_Right:
594 case GDK_KP_Right:
595 if (!MOD__CTRL_ONLY) {
596 dc->width += 0.01;
597 if (dc->width > 1.0)
598 dc->width = 1.0;
599 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
600 ret = TRUE;
601 }
602 break;
603 case GDK_Left:
604 case GDK_KP_Left:
605 if (!MOD__CTRL_ONLY) {
606 dc->width -= 0.01;
607 if (dc->width < 0.01)
608 dc->width = 0.01;
609 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
610 ret = TRUE;
611 }
612 break;
613 case GDK_x:
614 case GDK_X:
615 if (MOD__ALT_ONLY) {
616 desktop->setToolboxFocusTo ("altx-calligraphy");
617 ret = TRUE;
618 }
619 break;
620 case GDK_Escape:
621 sp_desktop_selection(desktop)->clear();
622 break;
624 default:
625 break;
626 }
627 default:
628 break;
629 }
631 if (!ret) {
632 if (((SPEventContextClass *) parent_class)->root_handler) {
633 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
634 }
635 }
637 return ret;
638 }
641 static void
642 clear_current(SPDynaDrawContext *dc)
643 {
644 /* reset bpath */
645 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
646 /* reset curve */
647 sp_curve_reset(dc->currentcurve);
648 sp_curve_reset(dc->cal1);
649 sp_curve_reset(dc->cal2);
650 /* reset points */
651 dc->npoints = 0;
652 }
654 static void
655 set_to_accumulated(SPDynaDrawContext *dc)
656 {
657 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
659 if (!sp_curve_empty(dc->accumulated)) {
660 NArtBpath *abp;
661 gchar *str;
663 if (!dc->repr) {
664 /* Create object */
665 Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
666 Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");
668 /* Set style */
669 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
671 dc->repr = repr;
673 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
674 Inkscape::GC::release(dc->repr);
675 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
676 item->updateRepr();
677 if (dc->keep_selected) {
678 sp_desktop_selection(desktop)->set(dc->repr);
679 } else {
680 sp_desktop_selection(desktop)->clear();
681 }
682 }
683 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
684 str = sp_svg_write_path(abp);
685 g_assert( str != NULL );
686 g_free(abp);
687 dc->repr->setAttribute("d", str);
688 g_free(str);
689 } else {
690 if (dc->repr) {
691 sp_repr_unparent(dc->repr);
692 }
693 dc->repr = NULL;
694 }
696 sp_document_done(sp_desktop_document(desktop), SP_VERB_CONTEXT_CALLIGRAPHIC,
697 _("Create calligraphic stroke"));
698 }
700 static void
701 add_cap(SPCurve *curve,
702 NR::Point const &pre, NR::Point const &from,
703 NR::Point const &to, NR::Point const &post,
704 double rounding)
705 {
706 NR::Point vel = rounding * NR::rot90( to - from ) / sqrt(2.0);
707 double mag = NR::L2(vel);
709 NR::Point v_in = from - pre;
710 double mag_in = NR::L2(v_in);
711 if ( mag_in > DYNA_EPSILON ) {
712 v_in = mag * v_in / mag_in;
713 } else {
714 v_in = NR::Point(0, 0);
715 }
717 NR::Point v_out = to - post;
718 double mag_out = NR::L2(v_out);
719 if ( mag_out > DYNA_EPSILON ) {
720 v_out = mag * v_out / mag_out;
721 } else {
722 v_out = NR::Point(0, 0);
723 }
725 if ( NR::L2(v_in) > DYNA_EPSILON || NR::L2(v_out) > DYNA_EPSILON ) {
726 sp_curve_curveto(curve, from + v_in, to + v_out, to);
727 }
728 }
730 static void
731 accumulate_calligraphic(SPDynaDrawContext *dc)
732 {
733 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
734 sp_curve_reset(dc->accumulated); /* Is this required ?? */
735 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
737 g_assert(dc->cal1->end > 1);
738 g_assert(rev_cal2->end > 1);
739 g_assert(SP_CURVE_SEGMENT(dc->cal1, 0)->code == NR_MOVETO_OPEN);
740 g_assert(SP_CURVE_SEGMENT(rev_cal2, 0)->code == NR_MOVETO_OPEN);
741 g_assert(SP_CURVE_SEGMENT(dc->cal1, 1)->code == NR_CURVETO);
742 g_assert(SP_CURVE_SEGMENT(rev_cal2, 1)->code == NR_CURVETO);
743 g_assert(SP_CURVE_SEGMENT(dc->cal1, dc->cal1->end-1)->code == NR_CURVETO);
744 g_assert(SP_CURVE_SEGMENT(rev_cal2, rev_cal2->end-1)->code == NR_CURVETO);
746 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
748 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);
750 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
752 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);
754 sp_curve_closepath(dc->accumulated);
756 sp_curve_unref(rev_cal2);
758 sp_curve_reset(dc->cal1);
759 sp_curve_reset(dc->cal2);
760 }
761 }
763 static double square(double const x)
764 {
765 return x * x;
766 }
768 static void
769 fit_and_split(SPDynaDrawContext *dc, gboolean release)
770 {
771 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
773 #ifdef DYNA_DRAW_VERBOSE
774 g_print("[F&S:R=%c]", release?'T':'F');
775 #endif
777 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
778 return; // just clicked
780 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
781 #define BEZIER_SIZE 4
782 #define BEZIER_MAX_BEZIERS 8
783 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
785 #ifdef DYNA_DRAW_VERBOSE
786 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
787 dc->npoints, release ? "TRUE" : "FALSE");
788 #endif
790 /* Current calligraphic */
791 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
792 /* dc->npoints > 0 */
793 /* g_print("calligraphics(1|2) reset\n"); */
794 sp_curve_reset(dc->cal1);
795 sp_curve_reset(dc->cal2);
797 sp_curve_moveto(dc->cal1, dc->point1[0]);
798 sp_curve_moveto(dc->cal2, dc->point2[0]);
799 }
801 NR::Point b1[BEZIER_MAX_LENGTH];
802 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
803 tolerance_sq, BEZIER_MAX_BEZIERS);
804 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
806 NR::Point b2[BEZIER_MAX_LENGTH];
807 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
808 tolerance_sq, BEZIER_MAX_BEZIERS);
809 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
811 if ( nb1 != -1 && nb2 != -1 ) {
812 /* Fit and draw and reset state */
813 #ifdef DYNA_DRAW_VERBOSE
814 g_print("nb1:%d nb2:%d\n", nb1, nb2);
815 #endif
816 /* CanvasShape */
817 if (! release) {
818 sp_curve_reset(dc->currentcurve);
819 sp_curve_moveto(dc->currentcurve, b1[0]);
820 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
821 sp_curve_curveto(dc->currentcurve, bp1[1],
822 bp1[2], bp1[3]);
823 }
824 sp_curve_lineto(dc->currentcurve,
825 b2[BEZIER_SIZE*(nb2-1) + 3]);
826 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
827 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
828 }
829 // FIXME: dc->segments is always NULL at this point??
830 if (!dc->segments) { // first segment
831 add_cap(dc->currentcurve, b2[1], b2[0], b1[0], b1[1], dc->cap_rounding);
832 }
833 sp_curve_closepath(dc->currentcurve);
834 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
835 }
837 /* Current calligraphic */
838 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
839 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
840 }
841 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
842 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
843 }
844 } else {
845 /* fixme: ??? */
846 #ifdef DYNA_DRAW_VERBOSE
847 g_print("[fit_and_split] failed to fit-cubic.\n");
848 #endif
849 draw_temporary_box(dc);
851 for (gint i = 1; i < dc->npoints; i++) {
852 sp_curve_lineto(dc->cal1, dc->point1[i]);
853 }
854 for (gint i = 1; i < dc->npoints; i++) {
855 sp_curve_lineto(dc->cal2, dc->point2[i]);
856 }
857 }
859 /* Fit and draw and copy last point */
860 #ifdef DYNA_DRAW_VERBOSE
861 g_print("[%d]Yup\n", dc->npoints);
862 #endif
863 if (!release) {
864 g_assert(!sp_curve_empty(dc->currentcurve));
866 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
867 SP_TYPE_CANVAS_BPATH,
868 NULL);
869 SPCurve *curve = sp_curve_copy(dc->currentcurve);
870 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
871 sp_curve_unref(curve);
873 guint32 fillColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
874 //guint32 strokeColor = sp_desktop_get_color_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
875 double opacity = sp_desktop_get_master_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic");
876 double fillOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
877 //double strokeOpacity = sp_desktop_get_opacity_tool (SP_ACTIVE_DESKTOP, "tools.calligraphic", false);
878 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
879 //on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
880 //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);
881 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
882 /* fixme: Cannot we cascade it to root more clearly? */
883 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
885 dc->segments = g_slist_prepend(dc->segments, cbp);
886 }
888 dc->point1[0] = dc->point1[dc->npoints - 1];
889 dc->point2[0] = dc->point2[dc->npoints - 1];
890 dc->npoints = 1;
891 } else {
892 draw_temporary_box(dc);
893 }
894 }
896 static void
897 draw_temporary_box(SPDynaDrawContext *dc)
898 {
899 sp_curve_reset(dc->currentcurve);
901 sp_curve_moveto(dc->currentcurve, dc->point1[dc->npoints-1]);
902 for (gint i = dc->npoints-2; i >= 0; i--) {
903 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
904 }
905 for (gint i = 0; i < dc->npoints; i++) {
906 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
907 }
908 if (dc->npoints >= 2) {
909 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);
910 }
912 sp_curve_closepath(dc->currentcurve);
913 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
914 }
916 /*
917 Local Variables:
918 mode:c++
919 c-file-style:"stroustrup"
920 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
921 indent-tabs-mode:nil
922 fill-column:99
923 End:
924 */
925 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :