Code

Added test script I thought was already added.
[inkscape.git] / src / pencil-context.cpp
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;
114 /**
115  * Callback to initialize SPPencilContext object.
116  */
117 static void
118 sp_pencil_context_init(SPPencilContext *pc)
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;
135 /**
136  * Callback to setup SPPencilContext object.
137  */
138 static void
139 sp_pencil_context_setup(SPEventContext *ec)
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;
156 static void
157 sp_pencil_context_dispose(GObject *object)
159     G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
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)
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     }
177 /**
178  * Callback for handling all pencil context events.
179  */
180 gint
181 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
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;
223 static gint
224 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
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);
258                                 sp_event_context_snap_window_open(event_context);
260                 if (anchor) {
261                     p = anchor->dp;
262                     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
263                 } else {
265                     if (!(bevent.state & GDK_SHIFT_MASK)) {
266                                                 // This is the first click of a new curve; deselect item so that
267                         // this curve is not combined with it (unless it is drawn from its
268                         // anchor, which is handled by the sibling branch above)
269                         selection->clear();
270                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
271                         m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p, Inkscape::SNAPSOURCE_HANDLE);
272                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
273                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
274                         m.freeSnapReturnByRef(Inkscape::SnapPreferences::SNAPPOINT_NODE, p, Inkscape::SNAPSOURCE_HANDLE);
275                     }
276                 }
277                 pc->sa = anchor;
278                 spdc_set_startpoint(pc, p);
279                 ret = TRUE;
280                 break;
281         }
283         pc->is_drawing = true;
284     }
285     return ret;
288 static gint
289 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
291         SPDesktop *const dt = pc->desktop;
293         if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
294         // mouse was accidentally moved during Ctrl+click;
295         // ignore the motion and create a single point
296         pc->is_drawing = false;
297         return TRUE;
298     }
299     gint ret = FALSE;
301     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
302     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
303         // allow scrolling
304         return FALSE;
305     }
307     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
308         /* Grab mouse, so release will not pass unnoticed */
309         pc->grab = SP_CANVAS_ITEM(dt->acetate);
310         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
311                                         GDK_BUTTON_RELEASE_MASK |
312                                         GDK_POINTER_MOTION_MASK  ),
313                             NULL, mevent.time);
314     }
316     /* Find desktop coordinates */
317     Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
319     /* Test whether we hit any anchor. */
320     SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
322     if (pencil_within_tolerance) {
323         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
324         gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
325         if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
326             return FALSE;   // Do not drag if we're within tolerance from origin.
327         }
328     }
330     // Once the user has moved farther than tolerance from the original location
331     // (indicating they intend to move the object, not click), then always process the
332     // motion notify coordinates as given (no snapping back to origin)
333     pencil_within_tolerance = false;
335     switch (pc->state) {
336         case SP_PENCIL_CONTEXT_ADDLINE:
337             /* Set red endpoint */
338             if (anchor) {
339                 p = anchor->dp;
340             } else {
341                 Geom::Point ptnr(p);
342                 spdc_endpoint_snap(pc, ptnr, mevent.state);
343                 p = ptnr;
344             }
345             spdc_set_endpoint(pc, p);
346             ret = TRUE;
347             break;
348         default:
349             /* We may be idle or already freehand */
350             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
351                 if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
352                         sp_event_context_snap_window_closed(event_context);
353                 }
354                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
356                 if ( !pc->sa && !pc->green_anchor ) {
357                     /* Create green anchor */
358                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
359                 }
360                 /** \todo
361                  * fixme: I am not sure whether we want to snap to anchors
362                  * in middle of freehand (Lauris)
363                  */
364                 if (anchor) {
365                     p = anchor->dp;
366                 }
368                 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
369                                         spdc_add_freehand_point(pc, p, mevent.state);
370                                         ret = TRUE;
371                 }
373                 if (anchor && !pc->anchor_statusbar) {
374                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
375                     pc->anchor_statusbar = true;
376                 } else if (!anchor && pc->anchor_statusbar) {
377                     pc->_message_context->clear();
378                     pc->anchor_statusbar = false;
379                 } else if (!anchor) {
380                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
381                 }
383             } else {
384                 if (anchor && !pc->anchor_statusbar) {
385                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
386                     pc->anchor_statusbar = true;
387                 } else if (!anchor && pc->anchor_statusbar) {
388                     pc->_message_context->clear();
389                     pc->anchor_statusbar = false;
390                 }
391             }
392             break;
393     }
394     return ret;
397 static gint
398 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
400     gint ret = FALSE;
402     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
403     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
404         SPDesktop *const dt = pc->desktop;
406         pc->is_drawing = false;
408         /* Find desktop coordinates */
409         Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
411         /* Test whether we hit any anchor. */
412         SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
413                                                               revent.y));
415         switch (pc->state) {
416             case SP_PENCIL_CONTEXT_IDLE:
417                 /* Releasing button in idle mode means single click */
418                 /* We have already set up start point/anchor in button_press */
419                 pc->state = SP_PENCIL_CONTEXT_ADDLINE;
420                 //sp_event_context_snap_window_open(dt->canvas);
421                 ret = TRUE;
422                 break;
423             case SP_PENCIL_CONTEXT_ADDLINE:
424                 /* Finish segment now */
425                 if (anchor) {
426                     p = anchor->dp;
427                 } else {
428                     spdc_endpoint_snap(pc, p, revent.state);
429                 }
430                 pc->ea = anchor;
431                 spdc_set_endpoint(pc, p);
432                 spdc_finish_endpoint(pc);
433                 pc->state = SP_PENCIL_CONTEXT_IDLE;
434                 sp_event_context_snap_window_closed(event_context);
435                 ret = TRUE;
436                 break;
437             case SP_PENCIL_CONTEXT_FREEHAND:
438                 if (revent.state & GDK_MOD1_MASK) {
439                     /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
441                     sketch_interpolate(pc);
443                     if (pc->green_anchor) {
444                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
445                     }
447                     pc->state = SP_PENCIL_CONTEXT_SKETCH;
448                     //sp_event_context_snap_window_open(dt->canvas);
449                 } else {
450                     /* Finish segment now */
451                     /// \todo fixme: Clean up what follows (Lauris)
452                     if (anchor) {
453                         p = anchor->dp;
454                     }
455                     pc->ea = anchor;
456                     /* Write curves to object */
458                     dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
460                     interpolate(pc);
461                     spdc_concat_colors_and_flush(pc, FALSE);
462                     pc->sa = NULL;
463                     pc->ea = NULL;
464                     if (pc->green_anchor) {
465                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
466                     }
467                     pc->state = SP_PENCIL_CONTEXT_IDLE;
468                     // sp_event_context_snap_window_closed(dt->canvas);
469                     // reset sketch mode too
470                     pc->sketch_n = 0;
471                 }
472                 ret = TRUE;
473                 break;
474             case SP_PENCIL_CONTEXT_SKETCH:
475             default:
476                 break;
477         }
479         if (pc->grab) {
480             /* Release grab now */
481             sp_canvas_item_ungrab(pc->grab, revent.time);
482             pc->grab = NULL;
483         }
485         ret = TRUE;
486     }
487     return ret;
490 static void
491 pencil_cancel (SPPencilContext *const pc)
493     if (pc->grab) {
494         /* Release grab now */
495         sp_canvas_item_ungrab(pc->grab, 0);
496         pc->grab = NULL;
497     }
499     pc->is_drawing = false;
500     pc->state = SP_PENCIL_CONTEXT_IDLE;
501     sp_event_context_snap_window_closed(SP_EVENT_CONTEXT(pc));
503     pc->red_curve->reset();
504     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
505     while (pc->green_bpaths) {
506         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
507         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
508     }
509     pc->green_curve->reset();
510     if (pc->green_anchor) {
511         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
512     }
514     pc->_message_context->clear();
515     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
517     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
520 static gint
521 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
523     gint ret = FALSE;
524     switch (keyval) {
525         case GDK_Up:
526         case GDK_Down:
527         case GDK_KP_Up:
528         case GDK_KP_Down:
529             // Prevent the zoom field from activation.
530             if (!mod_ctrl_only(state)) {
531                 ret = TRUE;
532             }
533             break;
534         case GDK_Escape:
535             if (pc->npoints != 0) {
536                 // if drawing, cancel, otherwise pass it up for deselecting
537                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
538                     pencil_cancel (pc);
539                     ret = TRUE;
540                 }
541             }
542             break;
543         case GDK_z:
544         case GDK_Z:
545             if (mod_ctrl_only(state) && pc->npoints != 0) {
546                 // if drawing, cancel, otherwise pass it up for undo
547                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
548                     pencil_cancel (pc);
549                     ret = TRUE;
550                 }
551             }
552             break;
553         case GDK_g:
554         case GDK_G:
555             if (mod_shift_only(state)) {
556                 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
557                 ret = true;
558             }
559             break;
560         case GDK_Alt_L:
561         case GDK_Alt_R:
562         case GDK_Meta_L:
563         case GDK_Meta_R:
564             if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
565                 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."));
566             }
567             break;
568         default:
569             break;
570     }
571     return ret;
574 static gint
575 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
577     gint ret = FALSE;
578     switch (keyval) {
579         case GDK_Alt_L:
580         case GDK_Alt_R:
581         case GDK_Meta_L:
582         case GDK_Meta_R:
583             if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
584                 spdc_concat_colors_and_flush(pc, FALSE);
585                 pc->sketch_n = 0;
586                 pc->sa = NULL;
587                 pc->ea = NULL;
588                 if (pc->green_anchor) {
589                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
590                 }
591                 pc->state = SP_PENCIL_CONTEXT_IDLE;
592                 sp_event_context_snap_window_closed(SP_EVENT_CONTEXT(pc));
593                 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
594                 ret = TRUE;
595             }
596             break;
597         default:
598             break;
599     }
600     return ret;
603 /**
604  * Reset points and set new starting point.
605  */
606 static void
607 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
609     pc->npoints = 0;
610     pc->red_curve_is_valid = false;
611     if (in_svg_plane(p)) {
612         pc->p[pc->npoints++] = p;
613     }
616 /**
617  * Change moving endpoint position.
618  * <ul>
619  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
620  * <li>Otherwise we snap freely to whatever attractors are available.
621  * </ul>
622  *
623  * Number of points is (re)set to 2 always, 2nd point is modified.
624  * We change RED curve.
625  */
626 static void
627 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
629     if (pc->npoints == 0) {
630         return;
631         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
632          * zoom setting).
633          */
634     }
635     g_return_if_fail( pc->npoints > 0 );
637     pc->red_curve->reset();
638     if ( ( p == pc->p[0] )
639          || !in_svg_plane(p) )
640     {
641         pc->npoints = 1;
642     } else {
643         pc->p[1] = p;
644         pc->npoints = 2;
646         pc->red_curve->moveto(pc->p[0]);
647         pc->red_curve->lineto(pc->p[1]);
648         pc->red_curve_is_valid = true;
650         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
651     }
654 /**
655  * Finalize addline.
656  *
657  * \todo
658  * fixme: I'd like remove red reset from concat colors (lauris).
659  * Still not sure, how it will make most sense.
660  */
661 static void
662 spdc_finish_endpoint(SPPencilContext *const pc)
664     if ( ( pc->red_curve->is_empty() )
665          || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point())   ) )
666     {
667         pc->red_curve->reset();
668         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
669     } else {
670         /* Write curves to object. */
671         spdc_concat_colors_and_flush(pc, FALSE);
672         pc->sa = NULL;
673         pc->ea = NULL;
674     }
678 static void
679 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
681     g_assert( pc->npoints > 0 );
682     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
684     if ( ( p != pc->p[ pc->npoints - 1 ] )
685          && in_svg_plane(p) )
686     {
687         pc->ps.push_back(p);
688         pc->p[pc->npoints++] = p;
689         fit_and_split(pc);
690     }
693 static inline double
694 square(double const x)
696     return x * x;
699 static void
700 interpolate(SPPencilContext *pc)
702     if ( pc->ps.size() <= 1 ) {
703         return;
704     }
706     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
707     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
708     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
709                                                tol) * exp(0.2*tol - 2);
711     g_assert(is_zero(pc->req_tangent)
712              || is_unit_vector(pc->req_tangent));
713     Geom::Point const tHatEnd(0, 0);
715     guint n_points  = pc->ps.size();
716     pc->green_curve->reset();
717     pc->red_curve->reset();
718     pc->red_curve_is_valid = false;
720     Geom::Point * b = g_new(Geom::Point, 4*n_points);
721     Geom::Point * points = g_new(Geom::Point, 4*n_points);
722     for (unsigned int i = 0; i < pc->ps.size(); i++) {
723         points[i] = pc->ps[i];
724     }
726     // worst case gives us a segment per point
727     int max_segs = 4*n_points;
729     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
730                                              tolerance_sq, max_segs);
732     if ( n_segs > 0)
733     {
734         /* Fit and draw and reset state */
735         pc->green_curve->moveto(b[0]);
736         for (int c = 0; c < n_segs; c++) {
737             pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
738         }
739         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
741         /* Fit and draw and copy last point */
742         g_assert(!pc->green_curve->is_empty());
744         /* Set up direction of next curve. */
745         {
746             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
747             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
748             pc->p[0] = last_seg->finalPoint();
749             pc->npoints = 1;
750             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
751             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
752                                 ? Geom::Point(0, 0)
753                                 : Geom::unit_vector(req_vec) );
754         }
755     }
756     g_free(b);
757     g_free(points);
758     pc->ps.clear();
762 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
763 static void
764 sketch_interpolate(SPPencilContext *pc)
766     if ( pc->ps.size() <= 1 ) {
767         return;
768     }
770     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
771     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
772     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() *
773                                                tol) * exp(0.2*tol - 2);
775     bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
777     g_assert(is_zero(pc->req_tangent)
778              || is_unit_vector(pc->req_tangent));
779     Geom::Point const tHatEnd(0, 0);
781     guint n_points  = pc->ps.size();
782     pc->red_curve->reset();
783     pc->red_curve_is_valid = false;
785     Geom::Point * b = g_new(Geom::Point, 4*n_points);
786     Geom::Point * points = g_new(Geom::Point, 4*n_points);
787     for (unsigned i = 0; i < pc->ps.size(); i++) {
788         points[i] = pc->ps[i];
789     }
791     // worst case gives us a segment per point
792     int max_segs = 4*n_points;
794     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
795                                              tolerance_sq, max_segs);
797     if ( n_segs > 0)
798     {
799         Geom::Path fit(b[0]);
800         for (int c = 0; c < n_segs; c++) {
801             fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
802         }
803         Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
805         double t =0.;
806         if ( pc->sketch_n > 0 ) {
807             if (average_all_sketches) {
808                 // Average = (sum of all) / n
809                 //         = (sum of all + new one) / n+1
810                 //         = ((old average)*n + new one) / n+1
811                 t = pc->sketch_n / (pc->sketch_n + 1.);
812             } else {
813                 t = 0.5;
814             }
815             pc->sketch_interpolation = Geom::lerp(t, fit_pwd2, pc->sketch_interpolation);
816             // simplify path, to eliminate small segments
817             Path *path = new Path;
818             path->LoadPathVector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
819             path->Simplify(0.5);
820             Geom::PathVector *pathv = path->MakePathVector();
821             pc->sketch_interpolation = (*pathv)[0].toPwSb();
822             delete path;
823             delete pathv;
824         } else {
825             pc->sketch_interpolation = fit_pwd2;
826         }
827         pc->sketch_n++;
829         pc->green_curve->reset();
830         pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
831         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
833         /* Fit and draw and copy last point */
834         g_assert(!pc->green_curve->is_empty());
836         /* Set up direction of next curve. */
837         {
838             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
839             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
840             pc->p[0] = last_seg->finalPoint();
841             pc->npoints = 1;
842             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
843             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
844                                 ? Geom::Point(0, 0)
845                                 : Geom::unit_vector(req_vec) );
846         }
847     }
848     g_free(b);
849     g_free(points);
850     pc->ps.clear();
853 static void
854 fit_and_split(SPPencilContext *pc)
856     g_assert( pc->npoints > 1 );
858     double const tolerance_sq = 0;
860     Geom::Point b[4];
861     g_assert(is_zero(pc->req_tangent)
862              || is_unit_vector(pc->req_tangent));
863     Geom::Point const tHatEnd(0, 0);
864     int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
865                                                 pc->req_tangent, tHatEnd,
866                                                 tolerance_sq, 1);
867     if ( n_segs > 0
868          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
869     {
870         /* Fit and draw and reset state */
871         pc->red_curve->reset();
872         pc->red_curve->moveto(b[0]);
873         pc->red_curve->curveto(b[1], b[2], b[3]);
874         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
875         pc->red_curve_is_valid = true;
876     } else {
877         /* Fit and draw and copy last point */
879         g_assert(!pc->red_curve->is_empty());
881         /* Set up direction of next curve. */
882         {
883             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
884             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
885             pc->p[0] = last_seg->finalPoint();
886             pc->npoints = 1;
887             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
888             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
889                                 ? Geom::Point(0, 0)
890                                 : Geom::unit_vector(req_vec) );
891         }
893         pc->green_curve->append_continuous(pc->red_curve, 0.0625);
894         SPCurve *curve = pc->red_curve->copy();
896         /// \todo fixme:
897         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
898         curve->unref();
899         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
901         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
903         pc->red_curve_is_valid = false;
904     }
908 /*
909   Local Variables:
910   mode:c++
911   c-file-style:"stroustrup"
912   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
913   indent-tabs-mode:nil
914   fill-column:99
915   End:
916 */
917 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :