dyna-draw-context.cpp revision 5ef24b8088d7de1d545e852c2de9e7f21e3a290e
/*
* Handwriting-like drawing mode
*
* Authors:
* Mitsuru Oka <oka326@parkcity.ne.jp>
* Lauris Kaplinski <lauris@kaplinski.com>
* bulia byak <buliabyak@users.sf.net>
* MenTaLguY <mental@rydia.net>
* Abhishek Sharma
* Jon A. Cruz <jon@joncruz.org>
*
* The original dynadraw code:
* Paul Haeberli <paul@sgi.com>
*
* Copyright (C) 1998 The Free Software Foundation
* Copyright (C) 1999-2005 authors
* Copyright (C) 2001-2002 Ximian, Inc.
* Copyright (C) 2005-2007 bulia byak
* Copyright (C) 2006 MenTaLguY
*
* Released under GNU GPL, read the file 'COPYING' for more information
*/
#define noDYNA_DRAW_VERBOSE
#include "config.h"
#include <gdk/gdkkeysyms.h>
#include <string>
#include <cstring>
#include <numeric>
#include "display/canvas-bpath.h"
#include "display/cairo-utils.h"
#include <glib.h>
#include "macros.h"
#include "document.h"
#include "document-undo.h"
#include "selection.h"
#include "desktop.h"
#include "desktop-events.h"
#include "desktop-handles.h"
#include "desktop-style.h"
#include "message-context.h"
#include "preferences.h"
#include "pixmaps/cursor-calligraphy.xpm"
#include "context-fns.h"
#include "sp-item.h"
#include "inkscape.h"
#include "color.h"
#include "splivarot.h"
#include "sp-item-group.h"
#include "sp-shape.h"
#include "sp-path.h"
#include "sp-text.h"
#include "display/sp-canvas.h"
#include "display/canvas-bpath.h"
#include "display/canvas-arena.h"
#include "verbs.h"
#include "dyna-draw-context.h"
using Inkscape::DocumentUndo;
#define DDC_RED_RGBA 0xff0000ff
#define TOLERANCE_CALLIGRAPHIC 0.1
#define DYNA_EPSILON 0.5e-6
#define DYNA_EPSILON_START 0.5e-2
#define DYNA_VEL_START 1e-5
#define DYNA_MIN_WIDTH 1.0e-6
static void add_cap(SPCurve *curve, Geom::Point const &from, Geom::Point const &to, double rounding);
#include "tool-factory.h"
namespace {
return new SPDynaDrawContext();
}
bool calligraphicContextRegistered = ToolFactory::instance().registerObject("/tools/calligraphic", createCalligraphicContext);
}
return SPDynaDrawContext::prefsPath;
}
SPDynaDrawContext* ddc = this;
ddc->keep_selected = true;
ddc->hatch_spacing = 0;
ddc->hatch_spacing_step = 0;
// new (&ddc->hatch_pointer_past) std::list<double>();
// new (&ddc->hatch_nearest_past) std::list<double>();
// new (&ddc->inertia_vectors) std::list<Geom::Point>();
// new (&ddc->hatch_vectors) std::list<Geom::Point>();
ddc->hatch_escaped = false;
ddc->just_started_drawing = false;
}
if (ddc->hatch_area) {
}
//G_OBJECT_CLASS(sp_dyna_draw_context_parent_class)->dispose(object);
// ddc->hatch_pointer_past.~list();
// ddc->hatch_nearest_past.~list();
// ddc->inertia_vectors.~list();
// ddc->hatch_vectors.~list();
}
void SPDynaDrawContext::setup() {
SPEventContext* ec = this;
// if ((SP_EVENT_CONTEXT_CLASS(sp_dyna_draw_context_parent_class))->setup)
// (SP_EVENT_CONTEXT_CLASS(sp_dyna_draw_context_parent_class))->setup(ec);
SPCommonContext::setup();
sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->currentshape), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
/* fixme: Cannot we cascade it to root more clearly? */
g_signal_connect(G_OBJECT(ddc->currentshape), "event", G_CALLBACK(sp_desktop_root_handler), ec->desktop);
{
/* TODO: this can be done either with an arcto, and should maybe also be put in a general file (other tools use this as well) */
const double C1 = 0.552;
c->moveto(-1,0);
c->closepath();
c->unref();
sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(ddc->hatch_area), 0x0000007f, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
}
ddc->is_drawing = false;
ec->enableSelectionCue();
}
}
SPEventContext* ec = this;
if (path == "tracebackground") {
} else if (path == "keep_selected") {
} else {
//pass on up to parent class to handle common attributes.
// if ( SP_COMMON_CONTEXT_CLASS(sp_dyna_draw_context_parent_class)->set ) {
// SP_COMMON_CONTEXT_CLASS(sp_dyna_draw_context_parent_class)->set(ec, val);
// }
}
//g_print("DDC: %g %g %g %g\n", ddc->mass, ddc->drag, ddc->angle, ddc->width);
}
static double
{
}
/* Get normalized point */
{
return Geom::Point(( v[Geom::X] - drect.min()[Geom::X] ) / max, ( v[Geom::Y] - drect.min()[Geom::Y] ) / max);
}
/* Get view point */
{
return Geom::Point(n[Geom::X] * max + drect.min()[Geom::X], n[Geom::Y] * max + drect.min()[Geom::Y]);
}
static void
{
}
static void
{
else
else
else
}
static gboolean
{
/* Calculate mass and drag */
/* Calculate force and acceleration */
// If force is below the absolute threshold DYNA_EPSILON,
// or we haven't yet reached DYNA_VEL_START (i.e. at the beginning of stroke)
// _and_ the force is below the (higher) DYNA_EPSILON_START threshold,
// discard this move.
// This prevents flips, blobs, and jerks caused by microscopic tremor of the tablet pen,
// especially bothersome at the start of the stroke where we don't yet have the inertia to
// smooth them out.
if ( Geom::L2(force) < DYNA_EPSILON || (dc->vel_max < DYNA_VEL_START && Geom::L2(force) < DYNA_EPSILON_START)) {
return FALSE;
}
/* Calculate new velocity */
/* Calculate angle of drawing tool */
double a1;
// 1a. calculate nib angle from input device tilt:
if (length > 0) {
}
else
a1 = 0.0;
}
else {
// 1b. fixed dc->angle (absolutely flat nib):
}
// 2. perpendicular to dc->vel (absolutely non-flat nib):
if ( mag_vel < DYNA_EPSILON ) {
return FALSE;
}
// 3. Average them using flatness parameter:
// calculate angles
// flip a2 to force it to be in the same half-circle as a1
bool flipped = false;
flipped = true;
}
// normalize a2
// find the flatness-weighted bisector angle, unflip if a2 was flipped
// FIXME: when dc->vel is oscillating around the fixed angle, the new_ang flips back and forth. How to avoid this?
// Try to detect a sudden flip when the new angle differs too much from the previous for the
// current velocity; in that case discard this move
return FALSE;
}
// convert to point
// g_print ("force %g acc %g vel_max %g vel %g a1 %g a2 %g new_ang %g\n", Geom::L2(force), Geom::L2(dc->acc), dc->vel_max, Geom::L2(dc->vel), a1, a2, new_ang);
/* Apply drag */
/* Update position */
return TRUE;
}
static void
{
// How much velocity thins strokestyle
// Influence of pressure on thickness
// drag)
double trace_thick = 1;
// pick single pixel
double R, G, B, A;
sp_canvas_arena_render_surface(SP_CANVAS_ARENA(sp_desktop_drawing(SP_EVENT_CONTEXT(dc)->desktop)), s, area);
ink_cairo_surface_average_color_premul(s, R, G, B, A);
trace_thick = 1 - L;
//g_print ("L %g thick %g\n", L, trace_thick);
}
double tremble_left = 0, tremble_right = 0;
// obtain two normally distributed random variables, using polar Box-Muller transform
do {
} while ( w >= 1.0 );
// deflect both left and right edges randomly and independently, so that:
// (1) dc->tremor=1 corresponds to sigma=1, decreasing dc->tremor narrows the bell curve;
// (2) deflection depends on width, but is upped for small widths for better visual uniformity across widths;
// (3) deflection somewhat depends on speed, to prevent fast strokes looking
// comparatively smooth and slow ones excessively jittery
}
}
}
}
static void
{
}
static void
{
dc->is_drawing = false;
/* Remove all temporary line segments */
}
/* reset accumulated curve */
}
}
SPEventContext* event_context = this;
case GDK_BUTTON_PRESS:
return TRUE;
}
}
/* initialize first point */
NULL,
dc->is_drawing = true;
dc->just_started_drawing = true;
}
break;
case GDK_MOTION_NOTIFY:
{
// for hatching:
double hatch_dist = 0;
// One item selected, and it's a path;
// let's try to track it as a guide
if (dc->hatch_livarot_path)
delete dc->hatch_livarot_path;
}
// calculate pointer point in the guide item's coords
// calculate the nearest point on the guide path
boost::optional<Path::cut_position> position = get_nearest_position_on_Path(dc->hatch_livarot_path, pointer);
// distance from pointer to nearest
// unit-length vector
dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Guide path selected</b>; start drawing along the guide with <b>Ctrl</b>"));
} else {
dc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Select a guide path</b> to track with <b>Ctrl</b>"));
}
}
#define HATCH_VECTOR_ELEMENTS 12
#define INERTIA_ELEMENTS 24
#define SPEED_ELEMENTS 12
#define SPEED_MIN 0.3
#define SPEED_NORMAL 0.35
#define INERTIA_FORCE 0.5
// speed is the movement of the nearest point along the guide path, divided by
// the movement of the pointer at the same period; it is averaged for the last
// SPEED_ELEMENTS motion events. Normally, as you track the guide path, speed
// is about 1, i.e. the nearest point on the path is moved by about the same
// distance as the pointer. If the speed starts to decrease, we are losing
// contact with the guide; if it drops below SPEED_MIN, we are on our own and
// not attracted to guide anymore. Most often this happens when you have
// tracked to the end of a guide calligraphic stroke and keep moving
// further. We try to handle this situation gracefully: not stick with the
// guide forever but let go of it smoothly and without sharp jerks (non-zero
// mass recommended; with zero mass, jerks are still quite noticeable).
double speed = 1;
// the distance nearest moved since the last motion event
// the distance pointer moved since the last motion event
// store them in stacks limited to SPEED_ELEMENTS
// If the stacks are full,
// calculate the sums of all stored movements
double nearest_sum = std::accumulate (dc->hatch_nearest_past.begin(), dc->hatch_nearest_past.end(), 0.0);
double pointer_sum = std::accumulate (dc->hatch_pointer_past.begin(), dc->hatch_pointer_past.end(), 0.0);
// and divide to get the speed
//g_print ("nearest sum %g pointer_sum %g speed %g\n", nearest_sum, pointer_sum, speed);
}
}
) {
// We are NOT attracted to the guide!
//g_print ("\nlast_nearest %g %g nearest %g %g pointer %g %g pos %d %g\n", dc->last_nearest[Geom::X], dc->last_nearest[Geom::Y], nearest[Geom::X], nearest[Geom::Y], pointer[Geom::X], pointer[Geom::Y], position->piece, position->t);
// Remember hatch_escaped so we don't get
// attracted again until the end of this stroke
dc->hatch_escaped = true;
if (dot > 0) { // mouse is still moving in approx the same direction
}
}
} else {
// Calculate angle cosine of this vector-to-guide and all past vectors
// summed, to detect if we accidentally flipped to the other side of the
// guide
double target;
if (speed > SPEED_NORMAL) {
// all ok, strictly obey the spacing
} else {
// looks like we're starting to lose speed,
// so _gradually_ let go attraction to prevent jerks
}
}
// This is the track pointer that we will use instead of the real one
// some limited feedback: allow persistent pulling to slightly change
// the spacing
// return it to the desktop coords
if (speed >= SPEED_NORMAL) {
}
} else {
// this is the first motion event, set the dist
}
// remember last points
}
dc->_message_context->set(Inkscape::NORMAL_MESSAGE, dc->hatch_escaped? _("Tracking: <b>connection to guide path lost!</b>") : _("<b>Tracking</b> a guide path"));
} else {
}
if (dc->just_started_drawing) {
dc->just_started_drawing = false;
}
break;
}
}
}
// Draw the hatching circle if necessary
// Haven't set spacing yet: gray, center free, update radius live
sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
// Tracking: green, center snapped, fixed radius
sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x00FF00ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
// Tracking escaped: red, center free, fixed radius
sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0xFF0000ff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
} else {
// Not drawing but spacing set: gray, center snapped, fixed radius
sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(dc->hatch_area), 0x7f7f7fff, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
}
}
} else {
}
}
break;
case GDK_BUTTON_RELEASE:
{
dc->is_drawing = false;
/* Remove all temporary line segments */
}
/* Create object */
if (accumulate_calligraphic(dc))
set_to_accumulated(dc, event->button.state & GDK_SHIFT_MASK, event->button.state & GDK_MOD1_MASK); // performs document_done
else
g_warning ("Failed to create path: invalid data in dc->cal1 or dc->cal2");
/* reset accumulated curve */
}
dc->hatch_escaped = false;
dc->just_started_drawing = false;
// we do not select the newly drawn path, so increase spacing by step
if (dc->hatch_spacing_step == 0) {
}
}
}
break;
}
case GDK_KEY_PRESS:
case GDK_KEY_Up:
case GDK_KEY_KP_Up:
if (!MOD__CTRL_ONLY) {
}
break;
case GDK_KEY_Down:
case GDK_KEY_KP_Down:
if (!MOD__CTRL_ONLY) {
}
break;
case GDK_KEY_Right:
case GDK_KEY_KP_Right:
if (!MOD__CTRL_ONLY) {
sp_ddc_update_toolbox (desktop, "altx-calligraphy", dc->width * 100); // the same spinbutton is for alt+x
}
break;
case GDK_KEY_Left:
case GDK_KEY_KP_Left:
if (!MOD__CTRL_ONLY) {
}
break;
case GDK_KEY_Home:
case GDK_KEY_KP_Home:
break;
case GDK_KEY_End:
case GDK_KEY_KP_End:
break;
case GDK_KEY_x:
case GDK_KEY_X:
if (MOD__ALT_ONLY) {
}
break;
case GDK_KEY_Escape:
if (dc->is_drawing) {
// if drawing, cancel, otherwise pass it up for deselecting
}
break;
case GDK_KEY_z:
case GDK_KEY_Z:
// if drawing, cancel, otherwise pass it up for undo
}
break;
default:
break;
}
break;
case GDK_KEY_RELEASE:
case GDK_KEY_Control_L:
case GDK_KEY_Control_R:
dc->hatch_spacing = 0;
dc->hatch_spacing_step = 0;
break;
default:
break;
}
default:
break;
}
if (!ret) {
// if ((SP_EVENT_CONTEXT_CLASS(sp_dyna_draw_context_parent_class))->root_handler) {
// ret = (SP_EVENT_CONTEXT_CLASS(sp_dyna_draw_context_parent_class))->root_handler(event_context, event);
// }
}
return ret;
}
static void
{
/* reset bpath */
/* reset curve */
/* reset points */
}
static void
{
/* Create object */
/* Set style */
item->updateRepr();
}
if (unionize) {
} else if (subtract) {
} else {
if (dc->keep_selected) {
}
}
} else {
}
}
_("Draw calligraphic stroke"));
}
static void
double rounding)
{
}
}
static bool
{
if (
) {
return false; // failure
}
if (
(rev_cal2->get_segment_count() <= 0) ||
) {
return false; // failure
}
add_cap(dc->accumulated, dc_cal1_lastseg->finalPoint(), rev_cal2_firstseg->initialPoint(), dc->cap_rounding);
add_cap(dc->accumulated, rev_cal2_lastseg->finalPoint(), dc_cal1_firstseg->initialPoint(), dc->cap_rounding);
return true; // success
}
static double square(double const x)
{
return x * x;
}
static void
{
#ifdef DYNA_DRAW_VERBOSE
#endif
return; // just clicked
#define BEZIER_SIZE 4
#define BEZIER_MAX_BEZIERS 8
#ifdef DYNA_DRAW_VERBOSE
g_print("[F&S:#] dc->npoints:%d, release:%s\n",
#endif
/* Current calligraphic */
/* dc->npoints > 0 */
/* g_print("calligraphics(1|2) reset\n"); */
}
/* Fit and draw and reset state */
#ifdef DYNA_DRAW_VERBOSE
#endif
/* CanvasShape */
if (! release) {
}
}
// FIXME: dc->segments is always NULL at this point??
}
}
/* Current calligraphic */
}
}
} else {
/* fixme: ??? */
#ifdef DYNA_DRAW_VERBOSE
g_print("[fit_and_split] failed to fit-cubic.\n");
#endif
}
}
}
/* Fit and draw and copy last point */
#ifdef DYNA_DRAW_VERBOSE
#endif
if (!release) {
NULL);
//guint32 strokeColor = sp_desktop_get_color_tool (desktop, "/tools/calligraphic", false);
//double strokeOpacity = sp_desktop_get_opacity_tool (desktop, "/tools/calligraphic", false);
sp_canvas_bpath_set_fill(SP_CANVAS_BPATH(cbp), ((fillColor & 0xffffff00) | SP_COLOR_F_TO_U(opacity*fillOpacity)), SP_WIND_RULE_EVENODD);
//on second thougtht don't do stroke yet because we don't have stoke-width yet and because stoke appears between segments while drawing
//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);
sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cbp), 0x00000000, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
/* fixme: Cannot we cascade it to root more clearly? */
}
} else {
}
}
static void
{
}
}
}
}
/*
Local Variables:
mode:c++
c-file-style:"stroustrup"
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
indent-tabs-mode:nil
fill-column:99
End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :