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 *
11 * The original dynadraw code:
12 * Paul Haeberli <paul@sgi.com>
13 *
14 * Copyright (C) 1998 The Free Software Foundation
15 * Copyright (C) 1999-2005 authors
16 * Copyright (C) 2001-2002 Ximian, Inc.
17 *
18 * Released under GNU GPL, read the file 'COPYING' for more information
19 */
21 #define noDYNA_DRAW_VERBOSE
23 #include "config.h"
25 #include <gtk/gtk.h>
26 #include <gdk/gdkkeysyms.h>
28 #include "svg/svg.h"
29 #include "display/canvas-bpath.h"
30 #include "display/bezier-utils.h"
32 #include "macros.h"
33 #include "document.h"
34 #include "selection.h"
35 #include "desktop.h"
36 #include "desktop-events.h"
37 #include "desktop-handles.h"
38 #include "desktop-affine.h"
39 #include "desktop-style.h"
40 #include "message-context.h"
41 #include "pixmaps/cursor-calligraphy.xpm"
42 #include "dyna-draw-context.h"
43 #include "libnr/n-art-bpath.h"
44 #include "libnr/nr-path.h"
45 #include "xml/repr.h"
46 #include "context-fns.h"
47 #include "sp-item.h"
48 #include "inkscape.h"
50 #define DDC_RED_RGBA 0xff0000ff
52 #define SAMPLE_TIMEOUT 10
53 #define TOLERANCE_LINE 1.0
54 #define TOLERANCE_CALLIGRAPHIC 3.0
55 #define DYNA_EPSILON 1.0e-6
57 #define DYNA_MIN_WIDTH 1.0e-6
59 #define DRAG_MIN 0.0
60 #define DRAG_DEFAULT 1.0
61 #define DRAG_MAX 1.0
63 static void sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass);
64 static void sp_dyna_draw_context_init(SPDynaDrawContext *ddc);
65 static void sp_dyna_draw_context_dispose(GObject *object);
67 static void sp_dyna_draw_context_setup(SPEventContext *ec);
68 static void sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val);
69 static gint sp_dyna_draw_context_root_handler(SPEventContext *ec, GdkEvent *event);
71 static void clear_current(SPDynaDrawContext *dc);
72 static void set_to_accumulated(SPDynaDrawContext *dc);
73 static void accumulate_calligraphic(SPDynaDrawContext *dc);
75 static void fit_and_split(SPDynaDrawContext *ddc, gboolean release);
76 static void fit_and_split_calligraphics(SPDynaDrawContext *ddc, gboolean release);
78 static void sp_dyna_draw_reset(SPDynaDrawContext *ddc, NR::Point p);
79 static NR::Point sp_dyna_draw_get_npoint(SPDynaDrawContext const *ddc, NR::Point v);
80 static NR::Point sp_dyna_draw_get_vpoint(SPDynaDrawContext const *ddc, NR::Point n);
81 static void draw_temporary_box(SPDynaDrawContext *dc);
84 static SPEventContextClass *parent_class;
86 GtkType
87 sp_dyna_draw_context_get_type(void)
88 {
89 static GType type = 0;
90 if (!type) {
91 GTypeInfo info = {
92 sizeof(SPDynaDrawContextClass),
93 NULL, NULL,
94 (GClassInitFunc) sp_dyna_draw_context_class_init,
95 NULL, NULL,
96 sizeof(SPDynaDrawContext),
97 4,
98 (GInstanceInitFunc) sp_dyna_draw_context_init,
99 NULL, /* value_table */
100 };
101 type = g_type_register_static(SP_TYPE_EVENT_CONTEXT, "SPDynaDrawContext", &info, (GTypeFlags)0);
102 }
103 return type;
104 }
106 static void
107 sp_dyna_draw_context_class_init(SPDynaDrawContextClass *klass)
108 {
109 GObjectClass *object_class = (GObjectClass *) klass;
110 SPEventContextClass *event_context_class = (SPEventContextClass *) klass;
112 parent_class = (SPEventContextClass*)g_type_class_peek_parent(klass);
114 object_class->dispose = sp_dyna_draw_context_dispose;
116 event_context_class->setup = sp_dyna_draw_context_setup;
117 event_context_class->set = sp_dyna_draw_context_set;
118 event_context_class->root_handler = sp_dyna_draw_context_root_handler;
119 }
121 static void
122 sp_dyna_draw_context_init(SPDynaDrawContext *ddc)
123 {
124 SPEventContext *event_context = SP_EVENT_CONTEXT(ddc);
126 event_context->cursor_shape = cursor_calligraphy_xpm;
127 event_context->hot_x = 4;
128 event_context->hot_y = 4;
130 ddc->accumulated = NULL;
131 ddc->segments = NULL;
132 ddc->currentcurve = NULL;
133 ddc->currentshape = NULL;
134 ddc->npoints = 0;
135 ddc->cal1 = NULL;
136 ddc->cal2 = NULL;
137 ddc->repr = NULL;
139 /* DynaDraw values */
140 ddc->cur = NR::Point(0,0);
141 ddc->last = NR::Point(0,0);
142 ddc->vel = NR::Point(0,0);
143 ddc->acc = NR::Point(0,0);
144 ddc->ang = NR::Point(0,0);
145 ddc->del = NR::Point(0,0);
147 /* attributes */
148 ddc->dragging = FALSE;
150 ddc->mass = 0.3;
151 ddc->drag = DRAG_DEFAULT;
152 ddc->angle = 30.0;
153 ddc->width = 0.2;
155 ddc->vel_thin = 0.1;
156 ddc->flatness = 0.9;
158 ddc->abs_width = false;
159 }
161 static void
162 sp_dyna_draw_context_dispose(GObject *object)
163 {
164 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(object);
166 if (ddc->accumulated) {
167 ddc->accumulated = sp_curve_unref(ddc->accumulated);
168 }
170 while (ddc->segments) {
171 gtk_object_destroy(GTK_OBJECT(ddc->segments->data));
172 ddc->segments = g_slist_remove(ddc->segments, ddc->segments->data);
173 }
175 if (ddc->currentcurve) ddc->currentcurve = sp_curve_unref(ddc->currentcurve);
176 if (ddc->cal1) ddc->cal1 = sp_curve_unref(ddc->cal1);
177 if (ddc->cal2) ddc->cal2 = sp_curve_unref(ddc->cal2);
179 if (ddc->currentshape) {
180 gtk_object_destroy(GTK_OBJECT(ddc->currentshape));
181 ddc->currentshape = NULL;
182 }
184 if (ddc->_message_context) {
185 delete ddc->_message_context;
186 }
188 G_OBJECT_CLASS(parent_class)->dispose(object);
189 }
191 static void
192 sp_dyna_draw_context_setup(SPEventContext *ec)
193 {
194 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
196 if (((SPEventContextClass *) parent_class)->setup)
197 ((SPEventContextClass *) parent_class)->setup(ec);
199 ddc->accumulated = sp_curve_new_sized(32);
200 ddc->currentcurve = sp_curve_new_sized(4);
202 ddc->cal1 = sp_curve_new_sized(32);
203 ddc->cal2 = sp_curve_new_sized(32);
205 ddc->currentshape = sp_canvas_item_new(sp_desktop_sketch(ec->desktop), SP_TYPE_CANVAS_BPATH, NULL);
206 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(ddc->currentshape), DDC_RED_RGBA, SP_WIND_RULE_EVENODD);
207 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
208 /* fixme: Cannot we cascade it to root more clearly? */
209 g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
211 sp_event_context_read(ec, "mass");
212 sp_event_context_read(ec, "drag");
213 sp_event_context_read(ec, "angle");
214 sp_event_context_read(ec, "width");
215 sp_event_context_read(ec, "thinning");
216 sp_event_context_read(ec, "tremor");
217 sp_event_context_read(ec, "flatness");
218 sp_event_context_read(ec, "usepressure");
219 sp_event_context_read(ec, "usetilt");
220 sp_event_context_read(ec, "abs_width");
222 ddc->is_drawing = false;
224 ddc->_message_context = new Inkscape::MessageContext((ec->desktop)->messageStack());
225 }
227 static void
228 sp_dyna_draw_context_set(SPEventContext *ec, gchar const *key, gchar const *val)
229 {
230 SPDynaDrawContext *ddc = SP_DYNA_DRAW_CONTEXT(ec);
232 if (!strcmp(key, "mass")) {
233 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.2 );
234 ddc->mass = CLAMP(dval, -1000.0, 1000.0);
235 } else if (!strcmp(key, "drag")) {
236 double const dval = ( val ? g_ascii_strtod (val, NULL) : DRAG_DEFAULT );
237 ddc->drag = CLAMP(dval, DRAG_MIN, DRAG_MAX);
238 } else if (!strcmp(key, "angle")) {
239 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0);
240 ddc->angle = CLAMP (dval, -90, 90);
241 } else if (!strcmp(key, "width")) {
242 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
243 ddc->width = CLAMP(dval, -1000.0, 1000.0);
244 } else if (!strcmp(key, "thinning")) {
245 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.1 );
246 ddc->vel_thin = CLAMP(dval, -1.0, 1.0);
247 } else if (!strcmp(key, "tremor")) {
248 double const dval = ( val ? g_ascii_strtod (val, NULL) : 0.0 );
249 ddc->tremor = CLAMP(dval, 0.0, 1.0);
250 } else if (!strcmp(key, "flatness")) {
251 double const dval = ( val ? g_ascii_strtod (val, NULL) : 1.0 );
252 ddc->flatness = CLAMP(dval, 0, 1.0);
253 } else if (!strcmp(key, "usepressure")) {
254 ddc->usepressure = (val && strcmp(val, "0"));
255 } else if (!strcmp(key, "usetilt")) {
256 ddc->usetilt = (val && strcmp(val, "0"));
257 } else if (!strcmp(key, "abs_width")) {
258 ddc->abs_width = (val && strcmp(val, "0"));
259 }
261 //g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
262 }
264 static double
265 flerp(double f0, double f1, double p)
266 {
267 return f0 + ( f1 - f0 ) * p;
268 }
270 /* Get normalized point */
271 static NR::Point
272 sp_dyna_draw_get_npoint(SPDynaDrawContext const *dc, NR::Point v)
273 {
274 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
275 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
276 return NR::Point(( v[NR::X] - drect.min()[NR::X] ) / max, ( v[NR::Y] - drect.min()[NR::Y] ) / max);
277 }
279 /* Get view point */
280 static NR::Point
281 sp_dyna_draw_get_vpoint(SPDynaDrawContext const *dc, NR::Point n)
282 {
283 NR::Rect drect = SP_EVENT_CONTEXT(dc)->desktop->get_display_area();
284 double const max = MAX ( drect.dimensions()[NR::X], drect.dimensions()[NR::Y] );
285 return NR::Point(n[NR::X] * max + drect.min()[NR::X], n[NR::Y] * max + drect.min()[NR::Y]);
286 }
288 static void
289 sp_dyna_draw_reset(SPDynaDrawContext *dc, NR::Point p)
290 {
291 dc->last = dc->cur = sp_dyna_draw_get_npoint(dc, p);
292 dc->vel = NR::Point(0,0);
293 dc->acc = NR::Point(0,0);
294 dc->ang = NR::Point(0,0);
295 dc->del = NR::Point(0,0);
296 }
298 static void
299 sp_dyna_draw_extinput(SPDynaDrawContext *dc, GdkEvent *event)
300 {
301 if (gdk_event_get_axis (event, GDK_AXIS_PRESSURE, &dc->pressure))
302 dc->pressure = CLAMP (dc->pressure, DDC_MIN_PRESSURE, DDC_MAX_PRESSURE);
303 else
304 dc->pressure = DDC_DEFAULT_PRESSURE;
306 if (gdk_event_get_axis (event, GDK_AXIS_XTILT, &dc->xtilt))
307 dc->xtilt = CLAMP (dc->xtilt, DDC_MIN_TILT, DDC_MAX_TILT);
308 else
309 dc->xtilt = DDC_DEFAULT_TILT;
311 if (gdk_event_get_axis (event, GDK_AXIS_YTILT, &dc->ytilt))
312 dc->ytilt = CLAMP (dc->ytilt, DDC_MIN_TILT, DDC_MAX_TILT);
313 else
314 dc->ytilt = DDC_DEFAULT_TILT;
315 }
318 static gboolean
319 sp_dyna_draw_apply(SPDynaDrawContext *dc, NR::Point p)
320 {
321 NR::Point n = sp_dyna_draw_get_npoint(dc, p);
323 /* Calculate mass and drag */
324 double const mass = flerp(1.0, 160.0, dc->mass);
325 double const drag = flerp(0.0, 0.5, dc->drag * dc->drag);
327 /* Calculate force and acceleration */
328 NR::Point force = n - dc->cur;
329 if ( NR::L2(force) < DYNA_EPSILON ) {
330 return FALSE;
331 }
333 dc->acc = force / mass;
335 /* Calculate new velocity */
336 dc->vel += dc->acc;
338 /* Calculate angle of drawing tool */
340 double a1;
341 if (dc->usetilt) {
342 // 1a. calculate nib angle from input device tilt:
343 gdouble length = std::sqrt(dc->xtilt*dc->xtilt + dc->ytilt*dc->ytilt);;
345 if (length > 0) {
346 NR::Point ang1 = NR::Point(dc->ytilt/length, dc->xtilt/length);
347 a1 = atan2(ang1);
348 }
349 else
350 a1 = 0.0;
351 }
352 else {
353 // 1b. fixed dc->angle (absolutely flat nib):
354 double const radians = ( (dc->angle - 90) / 180.0 ) * M_PI;
355 NR::Point ang1 = NR::Point(-sin(radians), cos(radians));
356 a1 = atan2(ang1);
357 }
359 // 2. perpendicular to dc->vel (absolutely non-flat nib):
360 gdouble const mag_vel = NR::L2(dc->vel);
361 if ( mag_vel < DYNA_EPSILON ) {
362 return FALSE;
363 }
364 NR::Point ang2 = NR::rot90(dc->vel) / mag_vel;
366 // 3. Average them using flatness parameter:
367 // calculate angles
368 double a2 = atan2(ang2);
369 // flip a2 to force it to be in the same half-circle as a1
370 bool flipped = false;
371 if (fabs (a2-a1) > 0.5*M_PI) {
372 a2 += M_PI;
373 flipped = true;
374 }
375 // normalize a2
376 if (a2 > M_PI)
377 a2 -= 2*M_PI;
378 if (a2 < -M_PI)
379 a2 += 2*M_PI;
380 // find the flatness-weighted bisector angle, unflip if a2 was flipped
381 // FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
382 double new_ang = a1 + (1 - dc->flatness) * (a2 - a1) - (flipped? M_PI : 0);
383 // convert to point
384 dc->ang = NR::Point (cos (new_ang), sin (new_ang));
386 /* Apply drag */
387 dc->vel *= 1.0 - drag;
389 /* Update position */
390 dc->last = dc->cur;
391 dc->cur += dc->vel;
393 return TRUE;
394 }
396 static void
397 sp_dyna_draw_brush(SPDynaDrawContext *dc)
398 {
399 g_assert( dc->npoints >= 0 && dc->npoints < SAMPLING_SIZE );
401 // How much velocity thins strokestyle
402 double vel_thin = flerp (0, 160, dc->vel_thin);
404 // Influence of pressure on thickness
405 double pressure_thick = (dc->usepressure ? dc->pressure : 1.0);
407 double width = ( pressure_thick - vel_thin * NR::L2(dc->vel) ) * dc->width;
409 double tremble_left = 0, tremble_right = 0;
410 if (dc->tremor > 0) {
411 // obtain two normally distributed random variables, using polar Box-Muller transform
412 double x1, x2, w, y1, y2;
413 do {
414 x1 = 2.0 * g_random_double_range(0,1) - 1.0;
415 x2 = 2.0 * g_random_double_range(0,1) - 1.0;
416 w = x1 * x1 + x2 * x2;
417 } while ( w >= 1.0 );
418 w = sqrt( (-2.0 * log( w ) ) / w );
419 y1 = x1 * w;
420 y2 = x2 * w;
422 // deflect both left and right edges randomly and independently, so that:
423 // (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
424 // (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
425 // (3) deflection somewhat depends on speed, to prevent fast strokes looking
426 // comparatively smooth and slow ones excessively jittery
427 tremble_left = (y1)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
428 tremble_right = (y2)*dc->tremor * (0.15 + 0.8*width) * (0.35 + 14*NR::L2(dc->vel));
429 }
431 if ( width < 0.02 * dc->width ) {
432 width = 0.02 * dc->width;
433 }
435 double dezoomify_factor = 0.05 * 1000;
436 if (!dc->abs_width) {
437 dezoomify_factor /= SP_EVENT_CONTEXT(dc)->desktop->current_zoom();
438 }
440 NR::Point del_left = dezoomify_factor * (width + tremble_left) * dc->ang;
441 NR::Point del_right = dezoomify_factor * (width + tremble_right) * dc->ang;
443 NR::Point abs_middle = sp_dyna_draw_get_vpoint(dc, dc->cur);
445 dc->point1[dc->npoints] = abs_middle + del_left;
446 dc->point2[dc->npoints] = abs_middle - del_right;
448 dc->del = 0.5*(del_left + del_right);
450 dc->npoints++;
451 }
453 void
454 sp_ddc_update_toolbox (SPDesktop *desktop, const gchar *id, double value)
455 {
456 desktop->setToolboxAdjustmentValue (id, value);
457 }
459 gint
460 sp_dyna_draw_context_root_handler(SPEventContext *event_context,
461 GdkEvent *event)
462 {
463 SPDynaDrawContext *dc = SP_DYNA_DRAW_CONTEXT(event_context);
464 SPDesktop *desktop = event_context->desktop;
466 gint ret = FALSE;
468 switch (event->type) {
469 case GDK_BUTTON_PRESS:
470 if ( event->button.button == 1 ) {
472 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
474 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
475 return TRUE;
476 }
478 NR::Point const button_w(event->button.x,
479 event->button.y);
480 NR::Point const button_dt(desktop->w2d(button_w));
481 sp_dyna_draw_reset(dc, button_dt);
482 sp_dyna_draw_extinput(dc, event);
483 sp_dyna_draw_apply(dc, button_dt);
484 sp_curve_reset(dc->accumulated);
485 if (dc->repr) {
486 dc->repr = NULL;
487 }
489 /* initialize first point */
490 dc->npoints = 0;
492 sp_canvas_item_grab(SP_CANVAS_ITEM(desktop->acetate),
493 ( GDK_KEY_PRESS_MASK |
494 GDK_BUTTON_RELEASE_MASK |
495 GDK_POINTER_MOTION_MASK |
496 GDK_BUTTON_PRESS_MASK ),
497 NULL,
498 event->button.time);
500 ret = TRUE;
502 dc->is_drawing = true;
503 }
504 break;
505 case GDK_MOTION_NOTIFY:
506 if ( dc->is_drawing && ( event->motion.state & GDK_BUTTON1_MASK ) ) {
507 dc->dragging = TRUE;
509 NR::Point const motion_w(event->motion.x,
510 event->motion.y);
511 NR::Point const motion_dt(desktop->w2d(motion_w));
513 sp_dyna_draw_extinput(dc, event);
514 if (!sp_dyna_draw_apply(dc, motion_dt)) {
515 ret = TRUE;
516 break;
517 }
519 if ( dc->cur != dc->last ) {
520 sp_dyna_draw_brush(dc);
521 g_assert( dc->npoints > 0 );
522 fit_and_split(dc, FALSE);
523 }
524 ret = TRUE;
525 }
526 break;
528 case GDK_BUTTON_RELEASE:
529 sp_canvas_item_ungrab(SP_CANVAS_ITEM(desktop->acetate), event->button.time);
530 dc->is_drawing = false;
531 if ( dc->dragging && event->button.button == 1 ) {
532 dc->dragging = FALSE;
534 /* Remove all temporary line segments */
535 while (dc->segments) {
536 gtk_object_destroy(GTK_OBJECT(dc->segments->data));
537 dc->segments = g_slist_remove(dc->segments, dc->segments->data);
538 }
539 /* Create object */
540 fit_and_split(dc, TRUE);
541 accumulate_calligraphic(dc);
542 set_to_accumulated(dc); /* temporal implementation */
543 /* reset accumulated curve */
544 sp_curve_reset(dc->accumulated);
545 clear_current(dc);
546 if (dc->repr) {
547 dc->repr = NULL;
548 }
549 ret = TRUE;
550 }
551 break;
552 case GDK_KEY_PRESS:
553 switch (get_group0_keyval (&event->key)) {
554 case GDK_Up:
555 case GDK_KP_Up:
556 if (!MOD__CTRL_ONLY) {
557 dc->angle += 5.0;
558 if (dc->angle > 90.0)
559 dc->angle = 90.0;
560 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
561 ret = TRUE;
562 }
563 break;
564 case GDK_Down:
565 case GDK_KP_Down:
566 if (!MOD__CTRL_ONLY) {
567 dc->angle -= 5.0;
568 if (dc->angle < -90.0)
569 dc->angle = -90.0;
570 sp_ddc_update_toolbox (desktop, "calligraphy-angle", dc->angle);
571 ret = TRUE;
572 }
573 break;
574 case GDK_Right:
575 case GDK_KP_Right:
576 if (!MOD__CTRL_ONLY) {
577 dc->width += 0.01;
578 if (dc->width > 1.0)
579 dc->width = 1.0;
580 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
581 ret = TRUE;
582 }
583 break;
584 case GDK_Left:
585 case GDK_KP_Left:
586 if (!MOD__CTRL_ONLY) {
587 dc->width -= 0.01;
588 if (dc->width < 0.01)
589 dc->width = 0.01;
590 sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100);
591 ret = TRUE;
592 }
593 break;
594 case GDK_x:
595 case GDK_X:
596 if (MOD__ALT_ONLY) {
597 desktop->setToolboxFocusTo ("altx-calligraphy");
598 ret = TRUE;
599 }
600 break;
601 case GDK_Escape:
602 sp_desktop_selection(desktop)->clear();
603 break;
605 default:
606 break;
607 }
608 default:
609 break;
610 }
612 if (!ret) {
613 if (((SPEventContextClass *) parent_class)->root_handler) {
614 ret = ((SPEventContextClass *) parent_class)->root_handler(event_context, event);
615 }
616 }
618 return ret;
619 }
622 static void
623 clear_current(SPDynaDrawContext *dc)
624 {
625 /* reset bpath */
626 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), NULL);
627 /* reset curve */
628 sp_curve_reset(dc->currentcurve);
629 sp_curve_reset(dc->cal1);
630 sp_curve_reset(dc->cal2);
631 /* reset points */
632 dc->npoints = 0;
633 }
635 static void
636 set_to_accumulated(SPDynaDrawContext *dc)
637 {
638 SPDesktop *desktop = SP_EVENT_CONTEXT(dc)->desktop;
640 if (!sp_curve_empty(dc->accumulated)) {
641 NArtBpath *abp;
642 gchar *str;
644 if (!dc->repr) {
645 /* Create object */
646 Inkscape::XML::Node *repr = sp_repr_new("svg:path");
648 /* Set style */
649 sp_desktop_apply_style_tool (desktop, repr, "tools.calligraphic", false);
651 dc->repr = repr;
653 SPItem *item=SP_ITEM(desktop->currentLayer()->appendChildRepr(dc->repr));
654 Inkscape::GC::release(dc->repr);
655 item->transform = SP_ITEM(desktop->currentRoot())->getRelativeTransform(desktop->currentLayer());
656 item->updateRepr();
657 sp_desktop_selection(desktop)->set(dc->repr);
658 }
659 abp = nr_artpath_affine(sp_curve_first_bpath(dc->accumulated), sp_desktop_dt2root_affine(desktop));
660 str = sp_svg_write_path(abp);
661 g_assert( str != NULL );
662 nr_free(abp);
663 dc->repr->setAttribute("d", str);
664 g_free(str);
665 } else {
666 if (dc->repr) {
667 sp_repr_unparent(dc->repr);
668 }
669 dc->repr = NULL;
670 }
672 sp_document_done(sp_desktop_document(desktop));
673 }
675 static void
676 accumulate_calligraphic(SPDynaDrawContext *dc)
677 {
678 if ( !sp_curve_empty(dc->cal1) && !sp_curve_empty(dc->cal2) ) {
679 sp_curve_reset(dc->accumulated); /* Is this required ?? */
680 SPCurve *rev_cal2 = sp_curve_reverse(dc->cal2);
681 sp_curve_append(dc->accumulated, dc->cal1, FALSE);
682 sp_curve_append(dc->accumulated, rev_cal2, TRUE);
683 sp_curve_closepath(dc->accumulated);
685 sp_curve_unref(rev_cal2);
687 sp_curve_reset(dc->cal1);
688 sp_curve_reset(dc->cal2);
689 }
690 }
692 static void
693 fit_and_split(SPDynaDrawContext *dc,
694 gboolean release)
695 {
696 fit_and_split_calligraphics(dc, release);
697 }
699 static double square(double const x)
700 {
701 return x * x;
702 }
704 static void
705 fit_and_split_calligraphics(SPDynaDrawContext *dc, gboolean release)
706 {
707 double const tolerance_sq = square( NR::expansion(SP_EVENT_CONTEXT(dc)->desktop->w2d()) * TOLERANCE_CALLIGRAPHIC );
709 #ifdef DYNA_DRAW_VERBOSE
710 g_print("[F&S:R=%c]", release?'T':'F');
711 #endif
713 if (!( dc->npoints > 0 && dc->npoints < SAMPLING_SIZE ))
714 return; // just clicked
716 if ( dc->npoints == SAMPLING_SIZE - 1 || release ) {
717 #define BEZIER_SIZE 4
718 #define BEZIER_MAX_BEZIERS 8
719 #define BEZIER_MAX_LENGTH ( BEZIER_SIZE * BEZIER_MAX_BEZIERS )
721 #ifdef DYNA_DRAW_VERBOSE
722 g_print("[F&S:#] dc->npoints:%d, release:%s\n",
723 dc->npoints, release ? "TRUE" : "FALSE");
724 #endif
726 /* Current calligraphic */
727 if ( dc->cal1->end == 0 || dc->cal2->end == 0 ) {
728 /* dc->npoints > 0 */
729 /* g_print("calligraphics(1|2) reset\n"); */
730 sp_curve_reset(dc->cal1);
731 sp_curve_reset(dc->cal2);
733 sp_curve_moveto(dc->cal1, dc->point1[0]);
734 sp_curve_moveto(dc->cal2, dc->point2[0]);
735 }
737 NR::Point b1[BEZIER_MAX_LENGTH];
738 gint const nb1 = sp_bezier_fit_cubic_r(b1, dc->point1, dc->npoints,
739 tolerance_sq, BEZIER_MAX_BEZIERS);
740 g_assert( nb1 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b1)) );
742 NR::Point b2[BEZIER_MAX_LENGTH];
743 gint const nb2 = sp_bezier_fit_cubic_r(b2, dc->point2, dc->npoints,
744 tolerance_sq, BEZIER_MAX_BEZIERS);
745 g_assert( nb2 * BEZIER_SIZE <= gint(G_N_ELEMENTS(b2)) );
747 if ( nb1 != -1 && nb2 != -1 ) {
748 /* Fit and draw and reset state */
749 #ifdef DYNA_DRAW_VERBOSE
750 g_print("nb1:%d nb2:%d\n", nb1, nb2);
751 #endif
752 /* CanvasShape */
753 if (! release) {
754 sp_curve_reset(dc->currentcurve);
755 sp_curve_moveto(dc->currentcurve, b1[0]);
756 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
757 sp_curve_curveto(dc->currentcurve, bp1[1],
758 bp1[2], bp1[3]);
759 }
760 sp_curve_lineto(dc->currentcurve,
761 b2[BEZIER_SIZE*(nb2-1) + 3]);
762 for (NR::Point *bp2 = b2 + BEZIER_SIZE * ( nb2 - 1 ); bp2 >= b2; bp2 -= BEZIER_SIZE) {
763 sp_curve_curveto(dc->currentcurve, bp2[2], bp2[1], bp2[0]);
764 }
765 sp_curve_closepath(dc->currentcurve);
766 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
767 }
769 /* Current calligraphic */
770 for (NR::Point *bp1 = b1; bp1 < b1 + BEZIER_SIZE * nb1; bp1 += BEZIER_SIZE) {
771 sp_curve_curveto(dc->cal1, bp1[1], bp1[2], bp1[3]);
772 }
773 for (NR::Point *bp2 = b2; bp2 < b2 + BEZIER_SIZE * nb2; bp2 += BEZIER_SIZE) {
774 sp_curve_curveto(dc->cal2, bp2[1], bp2[2], bp2[3]);
775 }
776 } else {
777 /* fixme: ??? */
778 #ifdef DYNA_DRAW_VERBOSE
779 g_print("[fit_and_split_calligraphics] failed to fit-cubic.\n");
780 #endif
781 draw_temporary_box(dc);
783 for (gint i = 1; i < dc->npoints; i++) {
784 sp_curve_lineto(dc->cal1, dc->point1[i]);
785 }
786 for (gint i = 1; i < dc->npoints; i++) {
787 sp_curve_lineto(dc->cal2, dc->point2[i]);
788 }
789 }
791 /* Fit and draw and copy last point */
792 #ifdef DYNA_DRAW_VERBOSE
793 g_print("[%d]Yup\n", dc->npoints);
794 #endif
795 if (!release) {
796 g_assert(!sp_curve_empty(dc->currentcurve));
798 SPCanvasItem *cbp = sp_canvas_item_new(sp_desktop_sketch(SP_EVENT_CONTEXT(dc)->desktop),
799 SP_TYPE_CANVAS_BPATH,
800 NULL);
801 SPCurve *curve = sp_curve_copy(dc->currentcurve);
802 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH (cbp), curve);
803 sp_curve_unref(curve);
804 guint32 fillColor = sp_desktop_get_color_tool(SP_ACTIVE_DESKTOP, "tools.calligraphic", true);
805 sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), fillColor , SP_WIND_RULE_EVENODD);
807 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
808 /* fixme: Cannot we cascade it to root more clearly? */
809 g_signal_connect(G_OBJECT(cbp), "event", G_CALLBACK(sp_desktop_root_handler), SP_EVENT_CONTEXT(dc)->desktop);
811 dc->segments = g_slist_prepend(dc->segments, cbp);
812 }
814 dc->point1[0] = dc->point1[dc->npoints - 1];
815 dc->point2[0] = dc->point2[dc->npoints - 1];
816 dc->npoints = 1;
817 } else {
818 draw_temporary_box(dc);
819 }
820 }
822 static void
823 draw_temporary_box(SPDynaDrawContext *dc)
824 {
825 sp_curve_reset(dc->currentcurve);
826 sp_curve_moveto(dc->currentcurve, dc->point1[0]);
827 for (gint i = 1; i < dc->npoints; i++) {
828 sp_curve_lineto(dc->currentcurve, dc->point1[i]);
829 }
830 for (gint i = dc->npoints-1; i >= 0; i--) {
831 sp_curve_lineto(dc->currentcurve, dc->point2[i]);
832 }
833 sp_curve_closepath(dc->currentcurve);
834 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(dc->currentshape), dc->currentcurve);
835 }
837 /*
838 Local Variables:
839 mode:c++
840 c-file-style:"stroustrup"
841 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
842 indent-tabs-mode:nil
843 fill-column:99
844 End:
845 */
846 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :