1 /** \file
2 * Pencil event context implementation.
3 */
5 /*
6 * Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * bulia byak <buliabyak@users.sf.net>
9 *
10 * Copyright (C) 2000 Lauris Kaplinski
11 * Copyright (C) 2000-2001 Ximian, Inc.
12 * Copyright (C) 2002 Lauris Kaplinski
13 * Copyright (C) 2004 Monash University
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 #include <gdk/gdkkeysyms.h>
20 #include "pencil-context.h"
21 #include "desktop.h"
22 #include "desktop-handles.h"
23 #include "selection.h"
24 #include "selection-chemistry.h"
25 #include "draw-anchor.h"
26 #include "message-stack.h"
27 #include "message-context.h"
28 #include "modifier-fns.h"
29 #include "sp-path.h"
30 #include "preferences.h"
31 #include "snap.h"
32 #include "pixmaps/cursor-pencil.xpm"
33 #include <2geom/sbasis-to-bezier.h>
34 #include <2geom/bezier-utils.h>
35 #include "display/canvas-bpath.h"
36 #include <glibmm/i18n.h>
37 #include "libnr/in-svg-plane.h"
38 #include "context-fns.h"
39 #include "sp-namedview.h"
40 #include "xml/repr.h"
41 #include "document.h"
42 #include "desktop-style.h"
43 #include "macros.h"
44 #include "display/curve.h"
45 #include "livarot/Path.h"
47 static void sp_pencil_context_class_init(SPPencilContextClass *klass);
48 static void sp_pencil_context_init(SPPencilContext *pc);
49 static void sp_pencil_context_setup(SPEventContext *ec);
50 static void sp_pencil_context_dispose(GObject *object);
52 static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
53 static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
54 static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
55 static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
56 static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
57 static gint pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const state);
59 static void spdc_set_startpoint(SPPencilContext *pc, Geom::Point const p);
60 static void spdc_set_endpoint(SPPencilContext *pc, Geom::Point const p);
61 static void spdc_finish_endpoint(SPPencilContext *pc);
62 static void spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint state);
63 static void fit_and_split(SPPencilContext *pc);
64 static void interpolate(SPPencilContext *pc);
65 static void sketch_interpolate(SPPencilContext *pc);
67 static SPDrawContextClass *pencil_parent_class;
68 static Geom::Point pencil_drag_origin_w(0, 0);
69 static bool pencil_within_tolerance = false;
71 /**
72 * Register SPPencilContext class with Gdk and return its type number.
73 */
74 GType
75 sp_pencil_context_get_type()
76 {
77 static GType type = 0;
78 if (!type) {
79 GTypeInfo info = {
80 sizeof(SPPencilContextClass),
81 NULL, NULL,
82 (GClassInitFunc) sp_pencil_context_class_init,
83 NULL, NULL,
84 sizeof(SPPencilContext),
85 4,
86 (GInstanceInitFunc) sp_pencil_context_init,
87 NULL, /* value_table */
88 };
89 type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
90 }
91 return type;
92 }
94 /**
95 * Initialize SPPencilContext vtable.
96 */
97 static void
98 sp_pencil_context_class_init(SPPencilContextClass *klass)
99 {
100 GObjectClass *object_class;
101 SPEventContextClass *event_context_class;
103 object_class = (GObjectClass *) klass;
104 event_context_class = (SPEventContextClass *) klass;
106 pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
108 object_class->dispose = sp_pencil_context_dispose;
110 event_context_class->setup = sp_pencil_context_setup;
111 event_context_class->root_handler = sp_pencil_context_root_handler;
112 }
114 /**
115 * Callback to initialize SPPencilContext object.
116 */
117 static void
118 sp_pencil_context_init(SPPencilContext *pc)
119 {
120 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
122 event_context->cursor_shape = cursor_pencil_xpm;
123 event_context->hot_x = 4;
124 event_context->hot_y = 4;
126 pc->npoints = 0;
127 pc->state = SP_PENCIL_CONTEXT_IDLE;
128 pc->req_tangent = Geom::Point(0, 0);
130 // since SPPencilContext is not properly constructed...
131 pc->sketch_interpolation = Geom::Piecewise<Geom::D2<Geom::SBasis> >();
132 pc->sketch_n = 0;
133 }
135 /**
136 * Callback to setup SPPencilContext object.
137 */
138 static void
139 sp_pencil_context_setup(SPEventContext *ec)
140 {
141 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
142 if (prefs->getBool("/tools/freehand/pencil/selcue")) {
143 ec->enableSelectionCue();
144 }
146 if (((SPEventContextClass *) pencil_parent_class)->setup) {
147 ((SPEventContextClass *) pencil_parent_class)->setup(ec);
148 }
150 SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
151 pc->is_drawing = false;
153 pc->anchor_statusbar = false;
154 }
156 static void
157 sp_pencil_context_dispose(GObject *object)
158 {
159 G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
160 }
162 /** Snaps new node relative to the previous node. */
163 static void
164 spdc_endpoint_snap(SPPencilContext const *pc, Geom::Point &p, guint const state)
165 {
166 if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping
167 spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
168 } else {
169 if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above
170 //After all, the user explicitely asked for angular snapping by
171 //pressing CTRL
172 spdc_endpoint_snap_free(pc, p, state);
173 }
174 }
175 }
177 /**
178 * Callback for handling all pencil context events.
179 */
180 gint
181 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
182 {
183 SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
185 gint ret = FALSE;
187 switch (event->type) {
188 case GDK_BUTTON_PRESS:
189 ret = pencil_handle_button_press(pc, event->button);
190 break;
192 case GDK_MOTION_NOTIFY:
193 ret = pencil_handle_motion_notify(pc, event->motion);
194 break;
196 case GDK_BUTTON_RELEASE:
197 ret = pencil_handle_button_release(pc, event->button);
198 break;
200 case GDK_KEY_PRESS:
201 ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
202 break;
204 case GDK_KEY_RELEASE:
205 ret = pencil_handle_key_release(pc, get_group0_keyval (&event->key), event->key.state);
206 break;
208 default:
209 break;
210 }
212 if (!ret) {
213 gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
214 = ((SPEventContextClass *) pencil_parent_class)->root_handler;
215 if (parent_root_handler) {
216 ret = parent_root_handler(ec, event);
217 }
218 }
220 return ret;
221 }
223 static gint
224 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
225 {
226 gint ret = FALSE;
227 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
228 if ( bevent.button == 1 && !event_context->space_panning) {
230 SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
231 SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
232 Inkscape::Selection *selection = sp_desktop_selection(desktop);
234 if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
235 return TRUE;
236 }
238 Geom::Point const button_w(bevent.x, bevent.y);
240 /* Find desktop coordinates */
241 Geom::Point p = pc->desktop->w2d(button_w);
243 /* Test whether we hit any anchor. */
244 SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
246 pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
247 pencil_within_tolerance = true;
249 switch (pc->state) {
250 case SP_PENCIL_CONTEXT_ADDLINE:
251 /* Current segment will be finished with release */
252 ret = TRUE;
253 break;
254 default:
255 /* Set first point of sequence */
256 SnapManager &m = desktop->namedview->snap_manager;
257 m.setup(desktop);
259 if (bevent.state & GDK_CONTROL_MASK) {
260 if (!(bevent.state & GDK_SHIFT_MASK)) {
261 m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p, Inkscape::SNAPSOURCE_HANDLE);
262 }
263 spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state);
264 ret = true;
265 break;
266 }
267 if (anchor) {
268 p = anchor->dp;
269 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
270 } else {
272 if (!(bevent.state & GDK_SHIFT_MASK)) {
273 // This is the first click of a new curve; deselect item so that
274 // this curve is not combined with it (unless it is drawn from its
275 // anchor, which is handled by the sibling branch above)
276 selection->clear();
277 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
278 m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p, Inkscape::SNAPSOURCE_HANDLE);
279 } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
280 desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
281 m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p, Inkscape::SNAPSOURCE_HANDLE);
282 }
283 }
284 pc->sa = anchor;
285 spdc_set_startpoint(pc, p);
286 ret = TRUE;
287 break;
288 }
290 pc->is_drawing = true;
291 }
292 return ret;
293 }
295 static gint
296 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
297 {
298 SPDesktop *const dt = pc->desktop;
300 if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
301 // mouse was accidentally moved during Ctrl+click;
302 // ignore the motion and create a single point
303 pc->is_drawing = false;
304 return TRUE;
305 }
306 gint ret = FALSE;
308 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
309 if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
310 // allow scrolling
311 return FALSE;
312 }
314 if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
315 /* Grab mouse, so release will not pass unnoticed */
316 pc->grab = SP_CANVAS_ITEM(dt->acetate);
317 sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK |
318 GDK_BUTTON_RELEASE_MASK |
319 GDK_POINTER_MOTION_MASK ),
320 NULL, mevent.time);
321 }
323 /* Find desktop coordinates */
324 Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
326 /* Test whether we hit any anchor. */
327 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
329 if (pencil_within_tolerance) {
330 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
331 gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
332 if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
333 return FALSE; // Do not drag if we're within tolerance from origin.
334 }
335 }
337 // Once the user has moved farther than tolerance from the original location
338 // (indicating they intend to move the object, not click), then always process the
339 // motion notify coordinates as given (no snapping back to origin)
340 pencil_within_tolerance = false;
342 switch (pc->state) {
343 case SP_PENCIL_CONTEXT_ADDLINE:
344 /* Set red endpoint */
345 if (anchor) {
346 p = anchor->dp;
347 } else {
348 Geom::Point ptnr(p);
349 spdc_endpoint_snap(pc, ptnr, mevent.state);
350 p = ptnr;
351 }
352 spdc_set_endpoint(pc, p);
353 ret = TRUE;
354 break;
355 default:
356 /* We may be idle or already freehand */
357 if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
358 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
359 sp_event_context_discard_delayed_snap_event(event_context);
360 }
361 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
363 if ( !pc->sa && !pc->green_anchor ) {
364 /* Create green anchor */
365 pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
366 }
367 /** \todo
368 * fixme: I am not sure whether we want to snap to anchors
369 * in middle of freehand (Lauris)
370 */
371 if (anchor) {
372 p = anchor->dp;
373 }
375 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
376 spdc_add_freehand_point(pc, p, mevent.state);
377 ret = TRUE;
378 }
380 if (anchor && !pc->anchor_statusbar) {
381 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
382 pc->anchor_statusbar = true;
383 } else if (!anchor && pc->anchor_statusbar) {
384 pc->_message_context->clear();
385 pc->anchor_statusbar = false;
386 } else if (!anchor) {
387 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
388 }
390 } else {
391 if (anchor && !pc->anchor_statusbar) {
392 pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
393 pc->anchor_statusbar = true;
394 } else if (!anchor && pc->anchor_statusbar) {
395 pc->_message_context->clear();
396 pc->anchor_statusbar = false;
397 }
398 }
399 break;
400 }
401 return ret;
402 }
404 static gint
405 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
406 {
407 gint ret = FALSE;
409 SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
410 if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
411 SPDesktop *const dt = pc->desktop;
413 pc->is_drawing = false;
415 /* Find desktop coordinates */
416 Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
418 /* Test whether we hit any anchor. */
419 SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
420 revent.y));
422 switch (pc->state) {
423 case SP_PENCIL_CONTEXT_IDLE:
424 /* Releasing button in idle mode means single click */
425 /* We have already set up start point/anchor in button_press */
426 if (!(revent.state & GDK_CONTROL_MASK)) {
427 // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
428 pc->state = SP_PENCIL_CONTEXT_ADDLINE;
429 }
430 ret = TRUE;
431 break;
432 case SP_PENCIL_CONTEXT_ADDLINE:
433 /* Finish segment now */
434 if (anchor) {
435 p = anchor->dp;
436 } else {
437 spdc_endpoint_snap(pc, p, revent.state);
438 }
439 pc->ea = anchor;
440 spdc_set_endpoint(pc, p);
441 spdc_finish_endpoint(pc);
442 pc->state = SP_PENCIL_CONTEXT_IDLE;
443 sp_event_context_discard_delayed_snap_event(event_context);
444 ret = TRUE;
445 break;
446 case SP_PENCIL_CONTEXT_FREEHAND:
447 if (revent.state & GDK_MOD1_MASK) {
448 /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
450 sketch_interpolate(pc);
452 if (pc->green_anchor) {
453 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
454 }
456 pc->state = SP_PENCIL_CONTEXT_SKETCH;
457 } else {
458 /* Finish segment now */
459 /// \todo fixme: Clean up what follows (Lauris)
460 if (anchor) {
461 p = anchor->dp;
462 }
463 pc->ea = anchor;
464 /* Write curves to object */
466 dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
468 interpolate(pc);
469 spdc_concat_colors_and_flush(pc, FALSE);
470 pc->sa = NULL;
471 pc->ea = NULL;
472 if (pc->green_anchor) {
473 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
474 }
475 pc->state = SP_PENCIL_CONTEXT_IDLE;
476 // reset sketch mode too
477 pc->sketch_n = 0;
478 }
479 ret = TRUE;
480 break;
481 case SP_PENCIL_CONTEXT_SKETCH:
482 default:
483 break;
484 }
486 if (pc->grab) {
487 /* Release grab now */
488 sp_canvas_item_ungrab(pc->grab, revent.time);
489 pc->grab = NULL;
490 }
492 ret = TRUE;
493 }
494 return ret;
495 }
497 static void
498 pencil_cancel (SPPencilContext *const pc)
499 {
500 if (pc->grab) {
501 /* Release grab now */
502 sp_canvas_item_ungrab(pc->grab, 0);
503 pc->grab = NULL;
504 }
506 pc->is_drawing = false;
507 pc->state = SP_PENCIL_CONTEXT_IDLE;
508 sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
510 pc->red_curve->reset();
511 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
512 while (pc->green_bpaths) {
513 gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
514 pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
515 }
516 pc->green_curve->reset();
517 if (pc->green_anchor) {
518 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
519 }
521 pc->_message_context->clear();
522 pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
524 sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
525 }
527 static gint
528 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
529 {
530 gint ret = FALSE;
531 switch (keyval) {
532 case GDK_Up:
533 case GDK_Down:
534 case GDK_KP_Up:
535 case GDK_KP_Down:
536 // Prevent the zoom field from activation.
537 if (!mod_ctrl_only(state)) {
538 ret = TRUE;
539 }
540 break;
541 case GDK_Escape:
542 if (pc->npoints != 0) {
543 // if drawing, cancel, otherwise pass it up for deselecting
544 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
545 pencil_cancel (pc);
546 ret = TRUE;
547 }
548 }
549 break;
550 case GDK_z:
551 case GDK_Z:
552 if (mod_ctrl_only(state) && pc->npoints != 0) {
553 // if drawing, cancel, otherwise pass it up for undo
554 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
555 pencil_cancel (pc);
556 ret = TRUE;
557 }
558 }
559 break;
560 case GDK_g:
561 case GDK_G:
562 if (mod_shift_only(state)) {
563 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
564 ret = true;
565 }
566 break;
567 case GDK_Alt_L:
568 case GDK_Alt_R:
569 case GDK_Meta_L:
570 case GDK_Meta_R:
571 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
572 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("<b>Sketch mode</b>: holding <b>Alt</b> interpolates between sketched paths. Release <b>Alt</b> to finalize."));
573 }
574 break;
575 default:
576 break;
577 }
578 return ret;
579 }
581 static gint
582 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
583 {
584 gint ret = FALSE;
585 switch (keyval) {
586 case GDK_Alt_L:
587 case GDK_Alt_R:
588 case GDK_Meta_L:
589 case GDK_Meta_R:
590 if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
591 spdc_concat_colors_and_flush(pc, FALSE);
592 pc->sketch_n = 0;
593 pc->sa = NULL;
594 pc->ea = NULL;
595 if (pc->green_anchor) {
596 pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
597 }
598 pc->state = SP_PENCIL_CONTEXT_IDLE;
599 sp_event_context_discard_delayed_snap_event(SP_EVENT_CONTEXT(pc));
600 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
601 ret = TRUE;
602 }
603 break;
604 default:
605 break;
606 }
607 return ret;
608 }
610 /**
611 * Reset points and set new starting point.
612 */
613 static void
614 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
615 {
616 pc->npoints = 0;
617 pc->red_curve_is_valid = false;
618 if (in_svg_plane(p)) {
619 pc->p[pc->npoints++] = p;
620 }
621 }
623 /**
624 * Change moving endpoint position.
625 * <ul>
626 * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
627 * <li>Otherwise we snap freely to whatever attractors are available.
628 * </ul>
629 *
630 * Number of points is (re)set to 2 always, 2nd point is modified.
631 * We change RED curve.
632 */
633 static void
634 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
635 {
636 if (pc->npoints == 0) {
637 return;
638 /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
639 * zoom setting).
640 */
641 }
642 g_return_if_fail( pc->npoints > 0 );
644 pc->red_curve->reset();
645 if ( ( p == pc->p[0] )
646 || !in_svg_plane(p) )
647 {
648 pc->npoints = 1;
649 } else {
650 pc->p[1] = p;
651 pc->npoints = 2;
653 pc->red_curve->moveto(pc->p[0]);
654 pc->red_curve->lineto(pc->p[1]);
655 pc->red_curve_is_valid = true;
657 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
658 }
659 }
661 /**
662 * Finalize addline.
663 *
664 * \todo
665 * fixme: I'd like remove red reset from concat colors (lauris).
666 * Still not sure, how it will make most sense.
667 */
668 static void
669 spdc_finish_endpoint(SPPencilContext *const pc)
670 {
671 if ( ( pc->red_curve->is_empty() )
672 || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point()) ) )
673 {
674 pc->red_curve->reset();
675 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
676 } else {
677 /* Write curves to object. */
678 spdc_concat_colors_and_flush(pc, FALSE);
679 pc->sa = NULL;
680 pc->ea = NULL;
681 }
682 }
685 static void
686 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
687 {
688 g_assert( pc->npoints > 0 );
689 g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
691 if ( ( p != pc->p[ pc->npoints - 1 ] )
692 && in_svg_plane(p) )
693 {
694 pc->ps.push_back(p);
695 pc->p[pc->npoints++] = p;
696 fit_and_split(pc);
697 }
698 }
700 static inline double
701 square(double const x)
702 {
703 return x * x;
704 }
706 static void
707 interpolate(SPPencilContext *pc)
708 {
709 if ( pc->ps.size() <= 1 ) {
710 return;
711 }
713 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
714 double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
715 double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
716 tol) * exp(0.2*tol - 2);
718 g_assert(is_zero(pc->req_tangent)
719 || is_unit_vector(pc->req_tangent));
720 Geom::Point const tHatEnd(0, 0);
722 guint n_points = pc->ps.size();
723 pc->green_curve->reset();
724 pc->red_curve->reset();
725 pc->red_curve_is_valid = false;
727 Geom::Point * b = g_new(Geom::Point, 4*n_points);
728 Geom::Point * points = g_new(Geom::Point, 4*n_points);
729 for (unsigned int i = 0; i < pc->ps.size(); i++) {
730 points[i] = pc->ps[i];
731 }
733 // worst case gives us a segment per point
734 int max_segs = 4*n_points;
736 int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
737 tolerance_sq, max_segs);
739 if ( n_segs > 0)
740 {
741 /* Fit and draw and reset state */
742 pc->green_curve->moveto(b[0]);
743 for (int c = 0; c < n_segs; c++) {
744 pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
745 }
746 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
748 /* Fit and draw and copy last point */
749 g_assert(!pc->green_curve->is_empty());
751 /* Set up direction of next curve. */
752 {
753 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
754 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
755 pc->p[0] = last_seg->finalPoint();
756 pc->npoints = 1;
757 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
758 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
759 ? Geom::Point(0, 0)
760 : Geom::unit_vector(req_vec) );
761 }
762 }
763 g_free(b);
764 g_free(points);
765 pc->ps.clear();
766 }
769 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
770 static void
771 sketch_interpolate(SPPencilContext *pc)
772 {
773 if ( pc->ps.size() <= 1 ) {
774 return;
775 }
777 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
778 double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
779 double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
780 tol) * exp(0.2*tol - 2);
782 bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
784 g_assert(is_zero(pc->req_tangent)
785 || is_unit_vector(pc->req_tangent));
786 Geom::Point const tHatEnd(0, 0);
788 guint n_points = pc->ps.size();
789 pc->red_curve->reset();
790 pc->red_curve_is_valid = false;
792 Geom::Point * b = g_new(Geom::Point, 4*n_points);
793 Geom::Point * points = g_new(Geom::Point, 4*n_points);
794 for (unsigned i = 0; i < pc->ps.size(); i++) {
795 points[i] = pc->ps[i];
796 }
798 // worst case gives us a segment per point
799 int max_segs = 4*n_points;
801 int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
802 tolerance_sq, max_segs);
804 if ( n_segs > 0)
805 {
806 Geom::Path fit(b[0]);
807 for (int c = 0; c < n_segs; c++) {
808 fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
809 }
810 Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
812 double t =0.;
813 if ( pc->sketch_n > 0 ) {
814 if (average_all_sketches) {
815 // Average = (sum of all) / n
816 // = (sum of all + new one) / n+1
817 // = ((old average)*n + new one) / n+1
818 t = pc->sketch_n / (pc->sketch_n + 1.);
819 } else {
820 t = 0.5;
821 }
822 pc->sketch_interpolation = Geom::lerp(t, fit_pwd2, pc->sketch_interpolation);
823 // simplify path, to eliminate small segments
824 Path *path = new Path;
825 path->LoadPathVector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
826 path->Simplify(0.5);
827 Geom::PathVector *pathv = path->MakePathVector();
828 pc->sketch_interpolation = (*pathv)[0].toPwSb();
829 delete path;
830 delete pathv;
831 } else {
832 pc->sketch_interpolation = fit_pwd2;
833 }
834 pc->sketch_n++;
836 pc->green_curve->reset();
837 pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
838 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
840 /* Fit and draw and copy last point */
841 g_assert(!pc->green_curve->is_empty());
843 /* Set up direction of next curve. */
844 {
845 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
846 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
847 pc->p[0] = last_seg->finalPoint();
848 pc->npoints = 1;
849 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
850 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
851 ? Geom::Point(0, 0)
852 : Geom::unit_vector(req_vec) );
853 }
854 }
855 g_free(b);
856 g_free(points);
857 pc->ps.clear();
858 }
860 static void
861 fit_and_split(SPPencilContext *pc)
862 {
863 g_assert( pc->npoints > 1 );
865 double const tolerance_sq = 0;
867 Geom::Point b[4];
868 g_assert(is_zero(pc->req_tangent)
869 || is_unit_vector(pc->req_tangent));
870 Geom::Point const tHatEnd(0, 0);
871 int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
872 pc->req_tangent, tHatEnd,
873 tolerance_sq, 1);
874 if ( n_segs > 0
875 && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
876 {
877 /* Fit and draw and reset state */
878 pc->red_curve->reset();
879 pc->red_curve->moveto(b[0]);
880 pc->red_curve->curveto(b[1], b[2], b[3]);
881 sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
882 pc->red_curve_is_valid = true;
883 } else {
884 /* Fit and draw and copy last point */
886 g_assert(!pc->red_curve->is_empty());
888 /* Set up direction of next curve. */
889 {
890 Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
891 g_assert( last_seg ); // Relevance: validity of (*last_seg)[2]
892 pc->p[0] = last_seg->finalPoint();
893 pc->npoints = 1;
894 Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
895 pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
896 ? Geom::Point(0, 0)
897 : Geom::unit_vector(req_vec) );
898 }
900 pc->green_curve->append_continuous(pc->red_curve, 0.0625);
901 SPCurve *curve = pc->red_curve->copy();
903 /// \todo fixme:
904 SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
905 curve->unref();
906 sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
908 pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
910 pc->red_curve_is_valid = false;
911 }
912 }
915 /*
916 Local Variables:
917 mode:c++
918 c-file-style:"stroustrup"
919 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
920 indent-tabs-mode:nil
921 fill-column:99
922 End:
923 */
924 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :