7c1976df3e0eed3e439a0bab2a5482d0fee7e136
[blender.git] / source / blender / editors / gpencil / gpencil_paint.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008, Blender Foundation, Joshua Leung
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/gpencil/gpencil_paint.c
27  *  \ingroup edgpencil
28  */
29
30 #include <stdio.h>
31 #include <stddef.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <math.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_math.h"
40 #include "BLI_utildefines.h"
41
42 #include "BLF_translation.h"
43
44 #include "PIL_time.h"
45
46 #include "BKE_gpencil.h"
47 #include "BKE_context.h"
48 #include "BKE_global.h"
49 #include "BKE_report.h"
50 #include "BKE_tracking.h"
51
52 #include "DNA_object_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_gpencil_types.h"
55 #include "DNA_windowmanager_types.h"
56
57 #include "UI_view2d.h"
58
59 #include "ED_gpencil.h"
60 #include "ED_screen.h"
61 #include "ED_view3d.h"
62 #include "ED_clip.h"
63
64 #include "BIF_gl.h"
65 #include "BIF_glutil.h"
66
67 #include "RNA_access.h"
68 #include "RNA_define.h"
69
70 #include "WM_api.h"
71 #include "WM_types.h"
72
73 #include "gpencil_intern.h"
74
75 /* ******************************************* */
76 /* 'Globals' and Defines */
77
78 /* Temporary 'Stroke' Operation data */
79 typedef struct tGPsdata {
80         Scene *scene;       /* current scene from context */
81         
82         wmWindow *win;      /* window where painting originated */
83         ScrArea *sa;        /* area where painting originated */
84         ARegion *ar;        /* region where painting originated */
85         View2D *v2d;        /* needed for GP_STROKE_2DSPACE */
86         rctf *subrect;      /* for using the camera rect within the 3d view */
87         rctf subrect_data;
88         
89         PointerRNA ownerPtr; /* pointer to owner of gp-datablock */
90         bGPdata *gpd;       /* gp-datablock layer comes from */
91         bGPDlayer *gpl;     /* layer we're working on */
92         bGPDframe *gpf;     /* frame we're working on */
93
94         short status;       /* current status of painting */
95         short paintmode;    /* mode for painting */
96         
97         int mval[2];        /* current mouse-position */
98         int mvalo[2];       /* previous recorded mouse-position */
99         
100         float pressure;     /* current stylus pressure */
101         float opressure;    /* previous stylus pressure */
102         
103         short radius;       /* radius of influence for eraser */
104         short flags;        /* flags that can get set during runtime */
105         
106         /* These need to be doubles, as (at least under unix) they are in seconds since epoch,
107          * float (and its 7 digits precision) is definitively not enough here!
108          * double, with its 15 digits precision, ensures us millisecond precision for a few centuries at least.
109          */
110         double inittime;    /* Used when converting to path */
111         double curtime;     /* Used when converting to path */
112         double ocurtime;    /* Used when converting to path */
113
114         float imat[4][4];   /* inverted transformation matrix applying when converting coords from screen-space
115                              * to region space */
116         float mat[4][4];
117         
118         float custom_color[4]; /* custom color - hack for enforcing a particular color for track/mask editing */
119         
120         void *erasercursor; /* radial cursor data for drawing eraser */
121 } tGPsdata;
122
123 /* values for tGPsdata->status */
124 enum {
125         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
126         GP_STATUS_PAINTING,     /* a stroke is in progress */
127         GP_STATUS_ERROR,        /* something wasn't correctly set up */
128         GP_STATUS_DONE          /* painting done */
129 };
130
131 /* Return flags for adding points to stroke buffer */
132 enum {
133         GP_STROKEADD_INVALID    = -2,       /* error occurred - insufficient info to do so */
134         GP_STROKEADD_OVERFLOW   = -1,       /* error occurred - cannot fit any more points */
135         GP_STROKEADD_NORMAL,                /* point was successfully added */
136         GP_STROKEADD_FULL                   /* cannot add any more points to buffer */
137 };
138
139 /* Runtime flags */
140 enum {
141         GP_PAINTFLAG_FIRSTRUN       = (1 << 0),    /* operator just started */
142         GP_PAINTFLAG_STROKEADDED    = (1 << 1),
143         GP_PAINTFLAG_V3D_ERASER_DEPTH = (1 << 2)
144 };
145
146 /* ------ */
147
148 /* maximum sizes of gp-session buffer */
149 #define GP_STROKE_BUFFER_MAX    5000
150
151 /* Macros for accessing sensitivity thresholds... */
152 /* minimum number of pixels mouse should move before new point created */
153 #define MIN_MANHATTEN_PX    (U.gp_manhattendist)
154 /* minimum length of new segment before new point can be added */
155 #define MIN_EUCLIDEAN_PX    (U.gp_euclideandist)
156
157 static bool gp_stroke_added_check(tGPsdata *p)
158 {
159         return (p->gpf && p->gpf->strokes.last && p->flags & GP_PAINTFLAG_STROKEADDED);
160 }
161
162 static void gp_stroke_added_enable(tGPsdata *p)
163 {
164         BLI_assert(p->gpf->strokes.last != NULL);
165         p->flags |= GP_PAINTFLAG_STROKEADDED;
166 }
167
168 /* ------ */
169 /* Forward defines for some functions... */
170
171 static void gp_session_validatebuffer(tGPsdata *p);
172
173 /* ******************************************* */
174 /* Context Wrangling... */
175
176 /* check if context is suitable for drawing */
177 static int gpencil_draw_poll(bContext *C)
178 {
179         if (ED_operator_regionactive(C)) {
180                 /* check if current context can support GPencil data */
181                 if (ED_gpencil_data_get_pointers(C, NULL) != NULL) {
182                         /* check if Grease Pencil isn't already running */
183                         if (ED_gpencil_session_active() == 0)
184                                 return 1;
185                         else
186                                 CTX_wm_operator_poll_msg_set(C, "Grease Pencil operator is already active");
187                 }
188                 else {
189                         CTX_wm_operator_poll_msg_set(C, "Failed to find Grease Pencil data to draw into");
190                 }
191         }
192         else {
193                 CTX_wm_operator_poll_msg_set(C, "Active region not set");
194         }
195         
196         return 0;
197 }
198
199 /* check if projecting strokes into 3d-geometry in the 3D-View */
200 static bool gpencil_project_check(tGPsdata *p)
201 {
202         bGPdata *gpd = p->gpd;
203         return ((gpd->sbuffer_sflag & GP_STROKE_3DSPACE) && (p->gpd->flag & (GP_DATA_DEPTH_VIEW | GP_DATA_DEPTH_STROKE)));
204 }
205
206 /* ******************************************* */
207 /* Calculations/Conversions */
208
209 /* Utilities --------------------------------- */
210
211 /* get the reference point for stroke-point conversions */
212 static void gp_get_3d_reference(tGPsdata *p, float vec[3])
213 {
214         View3D *v3d = p->sa->spacedata.first;
215         const float *fp = ED_view3d_cursor3d_get(p->scene, v3d);
216         
217         /* the reference point used depends on the owner... */
218 #if 0 /* XXX: disabled for now, since we can't draw relative to the owner yet */
219         if (p->ownerPtr.type == &RNA_Object) {
220                 Object *ob = (Object *)p->ownerPtr.data;
221                 
222                 /* active Object 
223                  *  - use relative distance of 3D-cursor from object center
224                  */
225                 sub_v3_v3v3(vec, fp, ob->loc);
226         }
227         else
228 #endif
229         {
230                 /* use 3D-cursor */
231                 copy_v3_v3(vec, fp);
232         }
233 }
234
235 /* Stroke Editing ---------------------------- */
236
237 /* check if the current mouse position is suitable for adding a new point */
238 static bool gp_stroke_filtermval(tGPsdata *p, const int mval[2], int pmval[2])
239 {
240         int dx = abs(mval[0] - pmval[0]);
241         int dy = abs(mval[1] - pmval[1]);
242         
243         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
244         if (p->gpd->sbuffer_size == 0)
245                 return true;
246         
247         /* check if mouse moved at least certain distance on both axes (best case) 
248          *      - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
249          */
250         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
251                 return true;
252         
253         /* check if the distance since the last point is significant enough 
254          *      - prevents points being added too densely
255          *      - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
256          */
257         else if ((dx * dx + dy * dy) > MIN_EUCLIDEAN_PX * MIN_EUCLIDEAN_PX)
258                 return true;
259         
260         /* mouse 'didn't move' */
261         else
262                 return false;
263 }
264
265 /* convert screen-coordinates to buffer-coordinates */
266 /* XXX this method needs a total overhaul! */
267 static void gp_stroke_convertcoords(tGPsdata *p, const int mval[2], float out[3], float *depth)
268 {
269         bGPdata *gpd = p->gpd;
270         
271         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
272         if (gpd->sbuffer_sflag & GP_STROKE_3DSPACE) {
273                 if (gpencil_project_check(p) && (ED_view3d_autodist_simple(p->ar, mval, out, 0, depth))) {
274                         /* projecting onto 3D-Geometry
275                          *      - nothing more needs to be done here, since view_autodist_simple() has already done it
276                          */
277                 }
278                 else {
279                         float mval_prj[2];
280                         float rvec[3], dvec[3];
281                         float mval_f[2] = {UNPACK2(mval)};
282                         float zfac;
283                         
284                         /* Current method just converts each point in screen-coordinates to
285                          * 3D-coordinates using the 3D-cursor as reference. In general, this
286                          * works OK, but it could of course be improved.
287                          *
288                          * TODO:
289                          *      - investigate using nearest point(s) on a previous stroke as
290                          *        reference point instead or as offset, for easier stroke matching
291                          */
292                         
293                         gp_get_3d_reference(p, rvec);
294                         zfac = ED_view3d_calc_zfac(p->ar->regiondata, rvec, NULL);
295
296                         if (ED_view3d_project_float_global(p->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
297                                 sub_v2_v2v2(mval_f, mval_prj, mval_f);
298                                 ED_view3d_win_to_delta(p->ar, mval_f, dvec, zfac);
299                                 sub_v3_v3v3(out, rvec, dvec);
300                         }
301                         else {
302                                 zero_v3(out);
303                         }
304                 }
305         }
306         
307         /* 2d - on 'canvas' (assume that p->v2d is set) */
308         else if ((gpd->sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
309                 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &out[0], &out[1]);
310                 mul_v3_m4v3(out, p->imat, out);
311         }
312         
313         /* 2d - relative to screen (viewport area) */
314         else {
315                 if (p->subrect == NULL) { /* normal 3D view */
316                         out[0] = (float)(mval[0]) / (float)(p->ar->winx) * 100;
317                         out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
318                 }
319                 else { /* camera view, use subrect */
320                         out[0] = ((mval[0] - p->subrect->xmin) / BLI_rctf_size_x(p->subrect)) * 100;
321                         out[1] = ((mval[1] - p->subrect->ymin) / BLI_rctf_size_y(p->subrect)) * 100;
322                 }
323         }
324 }
325
326 /* add current stroke-point to buffer (returns whether point was successfully added) */
327 static short gp_stroke_addpoint(tGPsdata *p, const int mval[2], float pressure, double curtime)
328 {
329         bGPdata *gpd = p->gpd;
330         tGPspoint *pt;
331
332         /* check painting mode */
333         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
334                 /* straight lines only - i.e. only store start and end point in buffer */
335                 if (gpd->sbuffer_size == 0) {
336                         /* first point in buffer (start point) */
337                         pt = (tGPspoint *)(gpd->sbuffer);
338                         
339                         /* store settings */
340                         copy_v2_v2_int(&pt->x, mval);
341                         pt->pressure = pressure;
342                         pt->time = (float)(curtime - p->inittime);
343                         
344                         /* increment buffer size */
345                         gpd->sbuffer_size++;
346                 }
347                 else {
348                         /* normally, we just reset the endpoint to the latest value 
349                          *      - assume that pointers for this are always valid...
350                          */
351                         pt = ((tGPspoint *)(gpd->sbuffer) + 1);
352                         
353                         /* store settings */
354                         copy_v2_v2_int(&pt->x, mval);
355                         pt->pressure = pressure;
356                         pt->time = (float)(curtime - p->inittime);
357                         
358                         /* if this is just the second point we've added, increment the buffer size
359                          * so that it will be drawn properly...
360                          * otherwise, just leave it alone, otherwise we get problems
361                          */
362                         if (gpd->sbuffer_size != 2)
363                                 gpd->sbuffer_size = 2;
364                 }
365                 
366                 /* can keep carrying on this way :) */
367                 return GP_STROKEADD_NORMAL;
368         }
369         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
370                 /* check if still room in buffer */
371                 if (gpd->sbuffer_size >= GP_STROKE_BUFFER_MAX)
372                         return GP_STROKEADD_OVERFLOW;
373                 
374                 /* get pointer to destination point */
375                 pt = ((tGPspoint *)(gpd->sbuffer) + gpd->sbuffer_size);
376                 
377                 /* store settings */
378                 copy_v2_v2_int(&pt->x, mval);
379                 pt->pressure = pressure;
380                 pt->time = (float)(curtime - p->inittime);
381                 
382                 /* increment counters */
383                 gpd->sbuffer_size++;
384                 
385                 /* check if another operation can still occur */
386                 if (gpd->sbuffer_size == GP_STROKE_BUFFER_MAX)
387                         return GP_STROKEADD_FULL;
388                 else
389                         return GP_STROKEADD_NORMAL;
390         }
391         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
392                 /* get pointer to destination point */
393                 pt = (tGPspoint *)(gpd->sbuffer);
394                 
395                 /* store settings */
396                 copy_v2_v2_int(&pt->x, mval);
397                 pt->pressure = pressure;
398                 pt->time = (float)(curtime - p->inittime);
399                 
400                 /* if there's stroke for this poly line session add (or replace last) point
401                  * to stroke. This allows to draw lines more interactively (see new segment
402                  * during mouse slide, e.g.)
403                  */
404                 if (gp_stroke_added_check(p)) {
405                         bGPDstroke *gps = p->gpf->strokes.last;
406                         bGPDspoint *pts;
407                         
408                         /* first time point is adding to temporary buffer -- need to allocate new point in stroke */
409                         if (gpd->sbuffer_size == 0) {
410                                 gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1));
411                                 gps->totpoints++;
412                         }
413                         
414                         pts = &gps->points[gps->totpoints - 1];
415                         
416                         /* special case for poly lines: normally,
417                          * depth is needed only when creating new stroke from buffer,
418                          * but poly lines are converting to stroke instantly,
419                          * so initialize depth buffer before converting coordinates
420                          */
421                         if (gpencil_project_check(p)) {
422                                 View3D *v3d = p->sa->spacedata.first;
423                                 
424                                 view3d_region_operator_needs_opengl(p->win, p->ar);
425                                 ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1 : 0);
426                         }
427                         
428                         /* convert screen-coordinates to appropriate coordinates (and store them) */
429                         gp_stroke_convertcoords(p, &pt->x, &pts->x, NULL);
430                         
431                         /* copy pressure and time */
432                         pts->pressure = pt->pressure;
433                         pts->time = pt->time;
434                 }
435                 
436                 /* increment counters */
437                 if (gpd->sbuffer_size == 0)
438                         gpd->sbuffer_size++;
439                 
440                 return GP_STROKEADD_NORMAL;
441         }
442         
443         /* return invalid state for now... */
444         return GP_STROKEADD_INVALID;
445 }
446
447 /* smooth a stroke (in buffer) before storing it */
448 static void gp_stroke_smooth(tGPsdata *p)
449 {
450         bGPdata *gpd = p->gpd;
451         tGPspoint *spt, tmp_spt[3];
452         int i = 0, cmx = gpd->sbuffer_size;
453         
454         /* only smooth if smoothing is enabled, and we're not doing a straight line */
455         if (!(U.gp_settings & GP_PAINT_DOSMOOTH) || ELEM(p->paintmode, GP_PAINTMODE_DRAW_STRAIGHT, GP_PAINTMODE_DRAW_POLY))
456                 return;
457         
458         /* don't try if less than 2 points in buffer */
459         if ((cmx <= 2) || (gpd->sbuffer == NULL))
460                 return;
461         
462         /* Calculate smoothing coordinates using weighted-averages 
463          * WARNING: we do NOT smooth first and last points (to avoid shrinkage)
464          */
465         spt = (tGPspoint *)gpd->sbuffer;
466         
467         /* This (tmp_spt) small array stores the last two points' original coordinates, 
468          * as we don't want to use already averaged ones! It is used as a cyclic buffer...
469          */
470         tmp_spt[0] = *spt;
471         for (i = 1, spt++; i < cmx - 1; i++, spt++) {
472                 const tGPspoint *pc = spt;
473                 const tGPspoint *pb = &tmp_spt[(i - 1) % 3];
474                 const tGPspoint *pa = (i - 1 > 0) ? (&tmp_spt[(i - 2) % 3]) : (pb);
475                 const tGPspoint *pd = pc + 1;
476                 const tGPspoint *pe = (i + 2 < cmx) ? (pc + 2) : (pd);
477                 
478                 /* Store current point's original state for the two next points! */
479                 tmp_spt[i % 3] = *spt;
480                 
481                 spt->x = (int)(0.1 * pa->x + 0.2 * pb->x + 0.4 * pc->x + 0.2 * pd->x + 0.1 * pe->x);
482                 spt->y = (int)(0.1 * pa->y + 0.2 * pb->y + 0.4 * pc->y + 0.2 * pd->y + 0.1 * pe->y);
483         }
484 }
485
486 /* simplify a stroke (in buffer) before storing it 
487  *      - applies a reverse Chaikin filter
488  *      - code adapted from etch-a-ton branch (editarmature_sketch.c)
489  */
490 static void gp_stroke_simplify(tGPsdata *p)
491 {
492         bGPdata *gpd = p->gpd;
493         tGPspoint *old_points = (tGPspoint *)gpd->sbuffer;
494         short num_points = gpd->sbuffer_size;
495         short flag = gpd->sbuffer_sflag;
496         short i, j;
497         
498         /* only simplify if simplification is enabled, and we're not doing a straight line */
499         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
500                 return;
501         
502         /* don't simplify if less than 4 points in buffer */
503         if ((num_points <= 4) || (old_points == NULL))
504                 return;
505         
506         /* clear buffer (but don't free mem yet) so that we can write to it 
507          *      - firstly set sbuffer to NULL, so a new one is allocated
508          *      - secondly, reset flag after, as it gets cleared auto
509          */
510         gpd->sbuffer = NULL;
511         gp_session_validatebuffer(p);
512         gpd->sbuffer_sflag = flag;
513         
514 /* macro used in loop to get position of new point
515  *      - used due to the mixture of datatypes in use here
516  */
517 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
518         { \
519                 co[0] += (float)(old_points[offs].x * sfac); \
520                 co[1] += (float)(old_points[offs].y * sfac); \
521                 pressure += old_points[offs].pressure * sfac; \
522                 time += old_points[offs].time * sfac; \
523         } (void)0
524         
525         /* XXX Here too, do not lose start and end points! */
526         gp_stroke_addpoint(p, &old_points->x, old_points->pressure, p->inittime + (double)old_points->time);
527         for (i = 0, j = 0; i < num_points; i++) {
528                 if (i - j == 3) {
529                         float co[2], pressure, time;
530                         int mco[2];
531                         
532                         /* initialize values */
533                         co[0] = 0.0f;
534                         co[1] = 0.0f;
535                         pressure = 0.0f;
536                         time = 0.0f;
537                         
538                         /* using macro, calculate new point */
539                         GP_SIMPLIFY_AVPOINT(j, -0.25f);
540                         GP_SIMPLIFY_AVPOINT(j + 1, 0.75f);
541                         GP_SIMPLIFY_AVPOINT(j + 2, 0.75f);
542                         GP_SIMPLIFY_AVPOINT(j + 3, -0.25f);
543                         
544                         /* set values for adding */
545                         mco[0] = (int)co[0];
546                         mco[1] = (int)co[1];
547                         
548                         /* ignore return values on this... assume to be ok for now */
549                         gp_stroke_addpoint(p, mco, pressure, p->inittime + (double)time);
550                         
551                         j += 2;
552                 }
553         }
554         gp_stroke_addpoint(p, &old_points[num_points - 1].x, old_points[num_points - 1].pressure,
555                            p->inittime + (double)old_points[num_points - 1].time);
556         
557         /* free old buffer */
558         MEM_freeN(old_points);
559 }
560
561
562 /* make a new stroke from the buffer data */
563 static void gp_stroke_newfrombuffer(tGPsdata *p)
564 {
565         bGPdata *gpd = p->gpd;
566         bGPDstroke *gps;
567         bGPDspoint *pt;
568         tGPspoint *ptc;
569         int i, totelem;
570         /* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
571         int depth_margin = (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 4 : 0;
572         
573         /* get total number of points to allocate space for 
574          *      - drawing straight-lines only requires the endpoints
575          */
576         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
577                 totelem = (gpd->sbuffer_size >= 2) ? 2 : gpd->sbuffer_size;
578         else
579                 totelem = gpd->sbuffer_size;
580         
581         /* exit with error if no valid points from this stroke */
582         if (totelem == 0) {
583                 if (G.debug & G_DEBUG)
584                         printf("Error: No valid points in stroke buffer to convert (tot=%d)\n", gpd->sbuffer_size);
585                 return;
586         }
587         
588         /* special case for poly line -- for already added stroke during session
589          * coordinates are getting added to stroke immediately to allow more
590          * interactive behavior
591          */
592         if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
593                 if (gp_stroke_added_check(p)) {
594                         return;
595                 }
596         }
597         
598         /* allocate memory for a new stroke */
599         gps = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
600         
601         /* copy appropriate settings for stroke */
602         gps->totpoints = totelem;
603         gps->thickness = p->gpl->thickness;
604         gps->flag = gpd->sbuffer_sflag;
605         gps->inittime = p->inittime;
606         
607         /* allocate enough memory for a continuous array for storage points */
608         gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
609         
610         /* set pointer to first non-initialized point */
611         pt = gps->points + (gps->totpoints - totelem);
612         
613         /* copy points from the buffer to the stroke */
614         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
615                 /* straight lines only -> only endpoints */
616                 {
617                         /* first point */
618                         ptc = gpd->sbuffer;
619                         
620                         /* convert screen-coordinates to appropriate coordinates (and store them) */
621                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
622                         
623                         /* copy pressure and time */
624                         pt->pressure = ptc->pressure;
625                         pt->time = ptc->time;
626                         
627                         pt++;
628                 }
629                         
630                 if (totelem == 2) {
631                         /* last point if applicable */
632                         ptc = ((tGPspoint *)gpd->sbuffer) + (gpd->sbuffer_size - 1);
633                         
634                         /* convert screen-coordinates to appropriate coordinates (and store them) */
635                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
636                         
637                         /* copy pressure and time */
638                         pt->pressure = ptc->pressure;
639                         pt->time = ptc->time;
640                 }
641         }
642         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
643                 /* first point */
644                 ptc = gpd->sbuffer;
645                 
646                 /* convert screen-coordinates to appropriate coordinates (and store them) */
647                 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
648                 
649                 /* copy pressure and time */
650                 pt->pressure = ptc->pressure;
651                 pt->time = ptc->time;
652         }
653         else {
654                 float *depth_arr = NULL;
655                 
656                 /* get an array of depths, far depths are blended */
657                 if (gpencil_project_check(p)) {
658                         int mval[2], mval_prev[2] = {0};
659                         int interp_depth = 0;
660                         int found_depth = 0;
661                         
662                         depth_arr = MEM_mallocN(sizeof(float) * gpd->sbuffer_size, "depth_points");
663                         
664                         for (i = 0, ptc = gpd->sbuffer; i < gpd->sbuffer_size; i++, ptc++, pt++) {
665                                 copy_v2_v2_int(mval, &ptc->x);
666                                 
667                                 if ((ED_view3d_autodist_depth(p->ar, mval, depth_margin, depth_arr + i) == 0) &&
668                                     (i && (ED_view3d_autodist_depth_seg(p->ar, mval, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
669                                 {
670                                         interp_depth = true;
671                                 }
672                                 else {
673                                         found_depth = true;
674                                 }
675                                 
676                                 copy_v2_v2_int(mval_prev, mval);
677                         }
678                         
679                         if (found_depth == false) {
680                                 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
681                                 for (i = gpd->sbuffer_size - 1; i >= 0; i--)
682                                         depth_arr[i] = 0.9999f;
683                         }
684                         else {
685                                 if (p->gpd->flag & GP_DATA_DEPTH_STROKE_ENDPOINTS) {
686                                         /* remove all info between the valid endpoints */
687                                         int first_valid = 0;
688                                         int last_valid = 0;
689                                         
690                                         for (i = 0; i < gpd->sbuffer_size; i++) {
691                                                 if (depth_arr[i] != FLT_MAX)
692                                                         break;
693                                         }
694                                         first_valid = i;
695                                         
696                                         for (i = gpd->sbuffer_size - 1; i >= 0; i--) {
697                                                 if (depth_arr[i] != FLT_MAX)
698                                                         break;
699                                         }
700                                         last_valid = i;
701                                         
702                                         /* invalidate non-endpoints, so only blend between first and last */
703                                         for (i = first_valid + 1; i < last_valid; i++)
704                                                 depth_arr[i] = FLT_MAX;
705                                         
706                                         interp_depth = true;
707                                 }
708                                 
709                                 if (interp_depth) {
710                                         interp_sparse_array(depth_arr, gpd->sbuffer_size, FLT_MAX);
711                                 }
712                         }
713                 }
714                 
715                 
716                 pt = gps->points;
717                 
718                 /* convert all points (normal behavior) */
719                 for (i = 0, ptc = gpd->sbuffer; i < gpd->sbuffer_size && ptc; i++, ptc++, pt++) {
720                         /* convert screen-coordinates to appropriate coordinates (and store them) */
721                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr + i : NULL);
722                         
723                         /* copy pressure and time */
724                         pt->pressure = ptc->pressure;
725                         pt->time = ptc->time;
726                 }
727                 
728                 if (depth_arr)
729                         MEM_freeN(depth_arr);
730         }
731         
732         /* add stroke to frame */
733         BLI_addtail(&p->gpf->strokes, gps);
734         gp_stroke_added_enable(p);
735 }
736
737 /* --- 'Eraser' for 'Paint' Tool ------ */
738
739 /* eraser tool - remove segment from stroke/split stroke (after lasso inside) */
740 static short gp_stroke_eraser_splitdel(bGPDframe *gpf, bGPDstroke *gps, int i)
741 {
742         bGPDspoint *pt_tmp = gps->points;
743         bGPDstroke *gsn = NULL;
744         
745         /* if stroke only had two points, get rid of stroke */
746         if (gps->totpoints == 2) {
747                 /* free stroke points, then stroke */
748                 MEM_freeN(pt_tmp);
749                 BLI_freelinkN(&gpf->strokes, gps);
750                 
751                 /* nothing left in stroke, so stop */
752                 return 1;
753         }
754         
755         /* if last segment, just remove segment from the stroke */
756         else if (i == gps->totpoints - 2) {
757                 /* allocate new points array, and assign most of the old stroke there */
758                 gps->totpoints--;
759                 gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
760                 memcpy(gps->points, pt_tmp, sizeof(bGPDspoint) * gps->totpoints);
761                 
762                 /* free temp buffer */
763                 MEM_freeN(pt_tmp);
764                 
765                 /* nothing left in stroke, so stop */
766                 return 1;
767         }
768         
769         /* if first segment, just remove segment from the stroke */
770         else if (i == 0) {
771                 /* allocate new points array, and assign most of the old stroke there */
772                 gps->totpoints--;
773                 gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
774                 memcpy(gps->points, pt_tmp + 1, sizeof(bGPDspoint) * gps->totpoints);
775                 
776                 /* We must adjust timings!
777                  * Each point's timing data is a delta from stroke's inittime, so as we erase the first
778                  * point of the stroke, we have to offset this inittime and all remaining points' delta values.
779                  * This way we get a new stroke with exactly the same timing as if user had started drawing from
780                  * the second point...
781                  */
782                 {
783                         bGPDspoint *pts;
784                         float delta = pt_tmp[1].time;
785                         int j;
786                         
787                         gps->inittime += (double)delta;
788                         
789                         pts = gps->points;
790                         for (j = 0; j < gps->totpoints; j++, pts++) {
791                                 pts->time -= delta;
792                         }
793                 }
794                 
795                 /* free temp buffer */
796                 MEM_freeN(pt_tmp);
797                 
798                 /* no break here, as there might still be stuff to remove in this stroke */
799                 return 0;
800         }
801         
802         /* segment occurs in 'middle' of stroke, so split */
803         else {
804                 /* duplicate stroke, and assign 'later' data to that stroke */
805                 gsn = MEM_dupallocN(gps);
806                 gsn->prev = gsn->next = NULL;
807                 BLI_insertlinkafter(&gpf->strokes, gps, gsn);
808                 
809                 gsn->totpoints = gps->totpoints - i;
810                 gsn->points = MEM_callocN(sizeof(bGPDspoint) * gsn->totpoints, "gp_stroke_points");
811                 memcpy(gsn->points, pt_tmp + i, sizeof(bGPDspoint) * gsn->totpoints);
812                 
813                 /* We must adjust timings of this new stroke!
814                  * Each point's timing data is a delta from stroke's inittime, so as we erase the first
815                  * point of the stroke, we have to offset this inittime and all remaing points' delta values.
816                  * This way we get a new stroke with exactly the same timing as if user had started drawing from
817                  * the second point...
818                  */
819                 {
820                         bGPDspoint *pts;
821                         float delta = pt_tmp[i].time;
822                         int j;
823                         
824                         gsn->inittime += (double)delta;
825                         
826                         pts = gsn->points;
827                         for (j = 0; j < gsn->totpoints; j++, pts++) {
828                                 pts->time -= delta;
829                         }
830                 }
831                 
832                 /* adjust existing stroke  */
833                 gps->totpoints = i;
834                 gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
835                 memcpy(gps->points, pt_tmp, sizeof(bGPDspoint) * i);
836                 
837                 /* free temp buffer */
838                 MEM_freeN(pt_tmp);
839                 
840                 /* nothing left in stroke, so stop */
841                 return 1;
842         }
843 }
844
845 /* which which point is infront (result should only be used for comparison) */
846 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
847 {
848         if (rv3d->is_persp) {
849                 return ED_view3d_calc_zfac(rv3d, co, NULL);
850         }
851         else {
852                 return -dot_v3v3(rv3d->viewinv[2], co);
853         }
854 }
855
856 static bool gp_stroke_eraser_is_occluded(tGPsdata *p,
857                                          const bGPDspoint *pt, const int x, const int y)
858 {
859         if ((p->sa->spacetype == SPACE_VIEW3D) &&
860             (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH))
861         {
862                 RegionView3D *rv3d = p->ar->regiondata;
863                 const int mval[2] = {x, y};
864                 float mval_3d[3];
865
866                 if (ED_view3d_autodist_simple(p->ar, mval, mval_3d, 0, NULL)) {
867                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
868                         const float depth_pt   = view3d_point_depth(rv3d, &pt->x);
869
870                         if (depth_pt > depth_mval) {
871                                 return true;
872                         }
873                 }
874         }
875         return false;
876 }
877
878 /* eraser tool - check if part of stroke occurs within last segment drawn by eraser */
879 static short gp_stroke_eraser_strokeinside(const int mval[2], const int UNUSED(mvalo[2]),
880                                            int rad, int x0, int y0, int x1, int y1)
881 {
882         /* simple within-radius check for now */
883         const float mval_fl[2]     = {mval[0], mval[1]};
884         const float screen_co_a[2] = {x0, y0};
885         const float screen_co_b[2] = {x1, y1};
886         
887         if (edge_inside_circle(mval_fl, rad, screen_co_a, screen_co_b)) {
888                 return true;
889         }
890         
891         /* not inside */
892         return false;
893
894
895 static void gp_point_to_xy(tGPsdata *p, bGPDstroke *gps, bGPDspoint *pt,
896                            int *r_x, int *r_y)
897 {
898         ARegion *ar = p->ar;
899         View2D *v2d = p->v2d;
900         rctf *subrect = p->subrect;
901         int xyval[2];
902
903         if (gps->flag & GP_STROKE_3DSPACE) {
904                 if (ED_view3d_project_int_global(ar, &pt->x, xyval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
905                         *r_x = xyval[0];
906                         *r_y = xyval[1];
907                 }
908                 else {
909                         *r_x = V2D_IS_CLIPPED;
910                         *r_y = V2D_IS_CLIPPED;
911                 }
912         }
913         else if (gps->flag & GP_STROKE_2DSPACE) {
914                 float vec[3] = {pt->x, pt->y, 0.0f};
915                 mul_m4_v3(p->mat, vec);
916                 UI_view2d_view_to_region_clip(v2d, vec[0], vec[1], r_x, r_y);
917         }
918         else {
919                 if (subrect == NULL) { /* normal 3D view */
920                         *r_x = (int)(pt->x / 100 * ar->winx);
921                         *r_y = (int)(pt->y / 100 * ar->winy);
922                 }
923                 else { /* camera view, use subrect */
924                         *r_x = (int)((pt->x / 100) * BLI_rctf_size_x(subrect)) + subrect->xmin;
925                         *r_y = (int)((pt->y / 100) * BLI_rctf_size_y(subrect)) + subrect->ymin;
926                 }
927         }
928 }
929
930
931 /* eraser tool - evaluation per stroke */
932 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
933 static void gp_stroke_eraser_dostroke(tGPsdata *p,
934                                       const int mval[2], const int mvalo[2],
935                                       short rad, const rcti *rect, bGPDframe *gpf, bGPDstroke *gps)
936 {
937         bGPDspoint *pt1, *pt2;
938         int x0 = 0, y0 = 0, x1 = 0, y1 = 0;
939         int i;
940         
941         if (gps->totpoints == 0) {
942                 /* just free stroke */
943                 if (gps->points) 
944                         MEM_freeN(gps->points);
945                 BLI_freelinkN(&gpf->strokes, gps);
946         }
947         else if (gps->totpoints == 1) {
948                 gp_point_to_xy(p, gps, gps->points, &x0, &y0);
949                 
950                 /* do boundbox check first */
951                 if ((!ELEM(V2D_IS_CLIPPED, x0, y0)) && BLI_rcti_isect_pt(rect, x0, y0)) {
952                         /* only check if point is inside */
953                         if (((x0 - mval[0]) * (x0 - mval[0]) + (y0 - mval[1]) * (y0 - mval[1])) <= rad * rad) {
954                                 /* free stroke */
955                                 MEM_freeN(gps->points);
956                                 BLI_freelinkN(&gpf->strokes, gps);
957                         }
958                 }
959         }
960         else {
961                 /* loop over the points in the stroke, checking for intersections 
962                  *  - an intersection will require the stroke to be split
963                  */
964                 for (i = 0; (i + 1) < gps->totpoints; i++) {
965                         /* get points to work with */
966                         pt1 = gps->points + i;
967                         pt2 = gps->points + i + 1;
968                         
969                         gp_point_to_xy(p, gps, pt1, &x0, &y0);
970                         gp_point_to_xy(p, gps, pt2, &x1, &y1);
971                         
972                         /* check that point segment of the boundbox of the eraser stroke */
973                         if (((!ELEM(V2D_IS_CLIPPED, x0, y0)) && BLI_rcti_isect_pt(rect, x0, y0)) ||
974                             ((!ELEM(V2D_IS_CLIPPED, x1, y1)) && BLI_rcti_isect_pt(rect, x1, y1)))
975                         {
976                                 /* check if point segment of stroke had anything to do with
977                                  * eraser region  (either within stroke painted, or on its lines)
978                                  *  - this assumes that linewidth is irrelevant
979                                  */
980                                 if (gp_stroke_eraser_strokeinside(mval, mvalo, rad, x0, y0, x1, y1)) {
981                                         if ((gp_stroke_eraser_is_occluded(p, pt1, x0, y0) == false) ||
982                                             (gp_stroke_eraser_is_occluded(p, pt2, x1, y1) == false))
983                                         {
984                                                 /* if function returns true, break this loop (as no more point to check) */
985                                                 if (gp_stroke_eraser_splitdel(gpf, gps, i))
986                                                         break;
987                                         }
988                                 }
989                         }
990                 }
991         }
992 }
993
994 /* erase strokes which fall under the eraser strokes */
995 static void gp_stroke_doeraser(tGPsdata *p)
996 {
997         bGPDframe *gpf = p->gpf;
998         bGPDstroke *gps, *gpn;
999         rcti rect;
1000         
1001         /* rect is rectangle of eraser */
1002         rect.xmin = p->mval[0] - p->radius;
1003         rect.ymin = p->mval[1] - p->radius;
1004         rect.xmax = p->mval[0] + p->radius;
1005         rect.ymax = p->mval[1] + p->radius;
1006
1007         if (p->sa->spacetype == SPACE_VIEW3D) {
1008                 if (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH) {
1009                         View3D *v3d = p->sa->spacedata.first;
1010
1011                         view3d_region_operator_needs_opengl(p->win, p->ar);
1012                         ED_view3d_autodist_init(p->scene, p->ar, v3d, 0);
1013                 }
1014         }
1015
1016         /* loop over strokes, checking segments for intersections */
1017         for (gps = gpf->strokes.first; gps; gps = gpn) {
1018                 gpn = gps->next;
1019                 gp_stroke_eraser_dostroke(p, p->mval, p->mvalo, p->radius, &rect, gpf, gps);
1020         }
1021 }
1022
1023 /* ******************************************* */
1024 /* Sketching Operator */
1025
1026 /* clear the session buffers (call this before AND after a paint operation) */
1027 static void gp_session_validatebuffer(tGPsdata *p)
1028 {
1029         bGPdata *gpd = p->gpd;
1030         
1031         /* clear memory of buffer (or allocate it if starting a new session) */
1032         if (gpd->sbuffer) {
1033                 /* printf("\t\tGP - reset sbuffer\n"); */
1034                 memset(gpd->sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
1035         }
1036         else {
1037                 /* printf("\t\tGP - allocate sbuffer\n"); */
1038                 gpd->sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
1039         }
1040         
1041         /* reset indices */
1042         gpd->sbuffer_size = 0;
1043         
1044         /* reset flags */
1045         gpd->sbuffer_sflag = 0;
1046
1047         /* reset inittime */
1048         p->inittime = 0.0;
1049 }
1050
1051 /* (re)init new painting data */
1052 static int gp_session_initdata(bContext *C, tGPsdata *p)
1053 {
1054         bGPdata **gpd_ptr = NULL;
1055         ScrArea *curarea = CTX_wm_area(C);
1056         ARegion *ar = CTX_wm_region(C);
1057         
1058         /* make sure the active view (at the starting time) is a 3d-view */
1059         if (curarea == NULL) {
1060                 p->status = GP_STATUS_ERROR;
1061                 if (G.debug & G_DEBUG)
1062                         printf("Error: No active view for painting\n");
1063                 return 0;
1064         }
1065         
1066         /* pass on current scene and window */
1067         p->scene = CTX_data_scene(C);
1068         p->win = CTX_wm_window(C);
1069
1070         unit_m4(p->imat);
1071         
1072         switch (curarea->spacetype) {
1073                 /* supported views first */
1074                 case SPACE_VIEW3D:
1075                 {
1076                         /* View3D *v3d = curarea->spacedata.first; */
1077                         /* RegionView3D *rv3d = ar->regiondata; */
1078                         
1079                         /* set current area 
1080                          *      - must verify that region data is 3D-view (and not something else)
1081                          */
1082                         p->sa = curarea;
1083                         p->ar = ar;
1084                         
1085                         if (ar->regiondata == NULL) {
1086                                 p->status = GP_STATUS_ERROR;
1087                                 if (G.debug & G_DEBUG)
1088                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1089                                 return 0;
1090                         }
1091                         break;
1092                 }
1093                 case SPACE_NODE:
1094                 {
1095                         /* SpaceNode *snode = curarea->spacedata.first; */
1096                         
1097                         /* set current area */
1098                         p->sa = curarea;
1099                         p->ar = ar;
1100                         p->v2d = &ar->v2d;
1101                         break;
1102                 }
1103                 case SPACE_SEQ:
1104                 {
1105                         SpaceSeq *sseq = curarea->spacedata.first;
1106                         
1107                         /* set current area */
1108                         p->sa = curarea;
1109                         p->ar = ar;
1110                         p->v2d = &ar->v2d;
1111                         
1112                         /* check that gpencil data is allowed to be drawn */
1113                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
1114                                 p->status = GP_STATUS_ERROR;
1115                                 if (G.debug & G_DEBUG)
1116                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil\n");
1117                                 return 0;
1118                         }
1119                         break;
1120                 }
1121                 case SPACE_IMAGE:
1122                 {
1123                         /* SpaceImage *sima = curarea->spacedata.first; */
1124                         
1125                         /* set the current area */
1126                         p->sa = curarea;
1127                         p->ar = ar;
1128                         p->v2d = &ar->v2d;
1129                         break;
1130                 }
1131                 case SPACE_CLIP:
1132                 {
1133                         SpaceClip *sc = curarea->spacedata.first;
1134                         
1135                         /* set the current area */
1136                         p->sa = curarea;
1137                         p->ar = ar;
1138                         p->v2d = &ar->v2d;
1139                         
1140                         invert_m4_m4(p->imat, sc->unistabmat);
1141                         
1142                         /* custom color for new layer */
1143                         p->custom_color[0] = 1.0f;
1144                         p->custom_color[1] = 0.0f;
1145                         p->custom_color[2] = 0.5f;
1146                         p->custom_color[3] = 0.9f;
1147                         
1148                         if (sc->gpencil_src == SC_GPENCIL_SRC_TRACK) {
1149                                 MovieClip *clip = ED_space_clip_get_clip(sc);
1150                                 int framenr = ED_space_clip_get_clip_frame_number(sc);
1151                                 MovieTrackingTrack *track = BKE_tracking_track_get_active(&clip->tracking);
1152                                 MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
1153                                 
1154                                 p->imat[3][0] -= marker->pos[0];
1155                                 p->imat[3][1] -= marker->pos[1];
1156                         }
1157                         invert_m4_m4(p->mat, p->imat);
1158                         break;
1159                 }
1160                 /* unsupported views */
1161                 default:
1162                 {
1163                         p->status = GP_STATUS_ERROR;
1164                         if (G.debug & G_DEBUG)
1165                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1166                         return 0;
1167                 }
1168         }
1169         
1170         /* get gp-data */
1171         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1172         if (gpd_ptr == NULL) {
1173                 p->status = GP_STATUS_ERROR;
1174                 if (G.debug & G_DEBUG)
1175                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1176                 return 0;
1177         }
1178         else {
1179                 /* if no existing GPencil block exists, add one */
1180                 if (*gpd_ptr == NULL)
1181                         *gpd_ptr = gpencil_data_addnew("GPencil");
1182                 p->gpd = *gpd_ptr;
1183         }
1184         
1185         if (ED_gpencil_session_active() == 0) {
1186                 /* initialize undo stack,
1187                  * also, existing undo stack would make buffer drawn
1188                  */
1189                 gpencil_undo_init(p->gpd);
1190         }
1191         
1192         /* clear out buffer (stored in gp-data), in case something contaminated it */
1193         gp_session_validatebuffer(p);
1194         
1195         return 1;
1196 }
1197
1198 /* init new painting session */
1199 static tGPsdata *gp_session_initpaint(bContext *C)
1200 {
1201         tGPsdata *p = NULL;
1202
1203         /* create new context data */
1204         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
1205
1206         gp_session_initdata(C, p);
1207         
1208         /* return context data for running paint operator */
1209         return p;
1210 }
1211
1212 /* cleanup after a painting session */
1213 static void gp_session_cleanup(tGPsdata *p)
1214 {
1215         bGPdata *gpd = (p) ? p->gpd : NULL;
1216         
1217         /* error checking */
1218         if (gpd == NULL)
1219                 return;
1220         
1221         /* free stroke buffer */
1222         if (gpd->sbuffer) {
1223                 /* printf("\t\tGP - free sbuffer\n"); */
1224                 MEM_freeN(gpd->sbuffer);
1225                 gpd->sbuffer = NULL;
1226         }
1227         
1228         /* clear flags */
1229         gpd->sbuffer_size = 0;
1230         gpd->sbuffer_sflag = 0;
1231         p->inittime = 0.0;
1232 }
1233
1234 /* init new stroke */
1235 static void gp_paint_initstroke(tGPsdata *p, short paintmode)
1236 {       
1237         /* get active layer (or add a new one if non-existent) */
1238         p->gpl = gpencil_layer_getactive(p->gpd);
1239         if (p->gpl == NULL) {
1240                 p->gpl = gpencil_layer_addnew(p->gpd, "GP_Layer", 1);
1241                 
1242                 if (p->custom_color[3])
1243                         copy_v3_v3(p->gpl->color, p->custom_color);
1244         }
1245         if (p->gpl->flag & GP_LAYER_LOCKED) {
1246                 p->status = GP_STATUS_ERROR;
1247                 if (G.debug & G_DEBUG)
1248                         printf("Error: Cannot paint on locked layer\n");
1249                 return;
1250         }
1251                 
1252         /* get active frame (add a new one if not matching frame) */
1253         p->gpf = gpencil_layer_getframe(p->gpl, p->scene->r.cfra, 1);
1254         if (p->gpf == NULL) {
1255                 p->status = GP_STATUS_ERROR;
1256                 if (G.debug & G_DEBUG)
1257                         printf("Error: No frame created (gpencil_paint_init)\n");
1258                 return;
1259         }
1260         else
1261                 p->gpf->flag |= GP_FRAME_PAINT;
1262         
1263         /* set 'eraser' for this stroke if using eraser */
1264         p->paintmode = paintmode;
1265         if (p->paintmode == GP_PAINTMODE_ERASER) {
1266                 p->gpd->sbuffer_sflag |= GP_STROKE_ERASER;
1267
1268                 /* check if we should respect depth while erasing */
1269                 if (p->sa->spacetype == SPACE_VIEW3D) {
1270                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1271                                 p->flags |= GP_PAINTFLAG_V3D_ERASER_DEPTH;
1272                         }
1273                 }
1274         }
1275
1276         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1277         p->flags |= GP_PAINTFLAG_FIRSTRUN;
1278         
1279
1280         /* when drawing in the camera view, in 2D space, set the subrect */
1281         if (!(p->gpd->flag & GP_DATA_VIEWALIGN)) {
1282                 if (p->sa->spacetype == SPACE_VIEW3D) {
1283                         View3D *v3d = p->sa->spacedata.first;
1284                         RegionView3D *rv3d = p->ar->regiondata;
1285                         
1286                         /* for camera view set the subrect */
1287                         if (rv3d->persp == RV3D_CAMOB) {
1288                                 ED_view3d_calc_camera_border(p->scene, p->ar, v3d, rv3d, &p->subrect_data, true); /* no shift */
1289                                 p->subrect = &p->subrect_data;
1290                         }
1291                 }
1292         }
1293
1294         /* check if points will need to be made in view-aligned space */
1295         if (p->gpd->flag & GP_DATA_VIEWALIGN) {
1296                 switch (p->sa->spacetype) {
1297                         case SPACE_VIEW3D:
1298                         {
1299                                 p->gpd->sbuffer_sflag |= GP_STROKE_3DSPACE;
1300                                 break;
1301                         }
1302                         case SPACE_NODE:
1303                         {
1304                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1305                                 break;
1306                         }
1307                         case SPACE_SEQ:
1308                         {
1309                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1310                                 break;
1311                         }
1312                         case SPACE_IMAGE:
1313                         {
1314                                 SpaceImage *sima = (SpaceImage *)p->sa->spacedata.first;
1315                                 
1316                                 /* only set these flags if the image editor doesn't have an image active,
1317                                  * otherwise user will be confused by strokes not appearing after they're drawn
1318                                  *
1319                                  * Admittedly, this is a bit hacky, but it works much nicer from an ergonomic standpoint!
1320                                  */
1321                                 if (ELEM(NULL, sima, sima->image)) {
1322                                         /* make strokes be drawn in screen space */
1323                                         p->gpd->sbuffer_sflag &= ~GP_STROKE_2DSPACE;
1324                                         p->gpd->flag &= ~GP_DATA_VIEWALIGN;
1325                                 }
1326                                 else {
1327                                         p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1328                                 }
1329                                 break;
1330                         }
1331                         case SPACE_CLIP:
1332                         {
1333                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1334                                 break;
1335                         }
1336                 }
1337         }
1338 }
1339
1340 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1341 static void gp_paint_strokeend(tGPsdata *p)
1342 {
1343         /* for surface sketching, need to set the right OpenGL context stuff so that 
1344          * the conversions will project the values correctly...
1345          */
1346         if (gpencil_project_check(p)) {
1347                 View3D *v3d = p->sa->spacedata.first;
1348                 
1349                 /* need to restore the original projection settings before packing up */
1350                 view3d_region_operator_needs_opengl(p->win, p->ar);
1351                 ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1 : 0);
1352         }
1353         
1354         /* check if doing eraser or not */
1355         if ((p->gpd->sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1356                 /* smooth stroke before transferring? */
1357                 gp_stroke_smooth(p);
1358                 
1359                 /* simplify stroke before transferring? */
1360                 gp_stroke_simplify(p);
1361                 
1362                 /* transfer stroke to frame */
1363                 gp_stroke_newfrombuffer(p);
1364         }
1365         
1366         /* clean up buffer now */
1367         gp_session_validatebuffer(p);
1368 }
1369
1370 /* finish off stroke painting operation */
1371 static void gp_paint_cleanup(tGPsdata *p)
1372 {
1373         /* p->gpd==NULL happens when stroke failed to initialize,
1374          * for example when GP is hidden in current space (sergey)
1375          */
1376         if (p->gpd) {
1377                 /* finish off a stroke */
1378                 gp_paint_strokeend(p);
1379         }
1380         
1381         /* "unlock" frame */
1382         if (p->gpf)
1383                 p->gpf->flag &= ~GP_FRAME_PAINT;
1384 }
1385
1386 /* ------------------------------- */
1387
1388 /* Helper callback for drawing the cursor itself */
1389 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
1390 {
1391         tGPsdata *p = (tGPsdata *)p_ptr;
1392         
1393         if (p->paintmode == GP_PAINTMODE_ERASER) {
1394                 glPushMatrix();
1395                 
1396                 glTranslatef((float)x, (float)y, 0.0f);
1397                 
1398                 glColor4ub(255, 255, 255, 128);
1399                 
1400                 glEnable(GL_LINE_SMOOTH);
1401                 glEnable(GL_BLEND);
1402                 
1403                 glutil_draw_lined_arc(0.0, M_PI * 2.0, p->radius, 40);
1404                 
1405                 glDisable(GL_BLEND);
1406                 glDisable(GL_LINE_SMOOTH);
1407                 
1408                 glPopMatrix();
1409         }
1410 }
1411
1412 /* Turn brush cursor in 3D view on/off */
1413 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
1414 {
1415         if (p->erasercursor && !enable) {
1416                 /* clear cursor */
1417                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
1418                 p->erasercursor = NULL;
1419         }
1420         else if (enable) {
1421                 /* enable cursor */
1422                 p->erasercursor = WM_paint_cursor_activate(CTX_wm_manager(C), 
1423                                                            NULL, /* XXX */
1424                                                            gpencil_draw_eraser, p);
1425         }
1426 }
1427
1428 /* ------------------------------- */
1429
1430
1431 static void gpencil_draw_exit(bContext *C, wmOperator *op)
1432 {
1433         tGPsdata *p = op->customdata;
1434         
1435         /* clear undo stack */
1436         gpencil_undo_finish();
1437         
1438         /* restore cursor to indicate end of drawing */
1439         WM_cursor_modal_restore(CTX_wm_window(C));
1440         
1441         /* don't assume that operator data exists at all */
1442         if (p) {
1443                 /* check size of buffer before cleanup, to determine if anything happened here */
1444                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1445                         /* turn off radial brush cursor */
1446                         gpencil_draw_toggle_eraser_cursor(C, p, false);
1447                         
1448                         /* if successful, store the new eraser size to be used again next time */
1449                         if (p->status == GP_STATUS_DONE)
1450                                 U.gp_eraser = p->radius;
1451                 }
1452                 
1453                 /* cleanup */
1454                 gp_paint_cleanup(p);
1455                 gp_session_cleanup(p);
1456                 
1457                 /* finally, free the temp data */
1458                 MEM_freeN(p);
1459         }
1460         
1461         op->customdata = NULL;
1462 }
1463
1464 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
1465 {
1466         /* this is just a wrapper around exit() */
1467         gpencil_draw_exit(C, op);
1468 }
1469
1470 /* ------------------------------- */
1471
1472
1473 static int gpencil_draw_init(bContext *C, wmOperator *op)
1474 {
1475         tGPsdata *p;
1476         int paintmode = RNA_enum_get(op->ptr, "mode");
1477         
1478         /* check context */
1479         p = op->customdata = gp_session_initpaint(C);
1480         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1481                 /* something wasn't set correctly in context */
1482                 gpencil_draw_exit(C, op);
1483                 return 0;
1484         }
1485         
1486         /* init painting data */
1487         gp_paint_initstroke(p, paintmode);
1488         if (p->status == GP_STATUS_ERROR) {
1489                 gpencil_draw_exit(C, op);
1490                 return 0;
1491         }
1492         
1493         /* radius for eraser circle is defined in userprefs now */
1494         p->radius = U.gp_eraser;
1495         
1496         /* everything is now setup ok */
1497         return 1;
1498 }
1499
1500
1501 /* ------------------------------- */
1502
1503 /* update UI indicators of status, including cursor and header prints */
1504 static void gpencil_draw_status_indicators(tGPsdata *p)
1505 {
1506         /* header prints */
1507         switch (p->status) {
1508                 case GP_STATUS_PAINTING:
1509                         /* only print this for paint-sessions, otherwise it gets annoying */
1510                         if (GPENCIL_SKETCH_SESSIONS_ON(p->scene))
1511                                 ED_area_headerprint(p->sa, IFACE_("Grease Pencil: Drawing/erasing stroke... Release to end stroke"));
1512                         break;
1513                 
1514                 case GP_STATUS_IDLING:
1515                         /* print status info */
1516                         switch (p->paintmode) {
1517                                 case GP_PAINTMODE_ERASER:
1518                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Erase Session: Hold and drag LMB or RMB to erase |"
1519                                                                           " ESC/Enter to end"));
1520                                         break;
1521                                 case GP_PAINTMODE_DRAW_STRAIGHT:
1522                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Line Session: Hold and drag LMB to draw | "
1523                                                                           "ESC/Enter to end"));
1524                                         break;
1525                                 case GP_PAINTMODE_DRAW:
1526                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw | "
1527                                                                           "ESC/Enter to end"));
1528                                         break;
1529                                         
1530                                 default: /* unhandled future cases */
1531                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Session: ESC/Enter to end"));
1532                                         break;
1533                         }
1534                         break;
1535                         
1536                 case GP_STATUS_ERROR:
1537                 case GP_STATUS_DONE:
1538                         /* clear status string */
1539                         ED_area_headerprint(p->sa, NULL);
1540                         break;
1541         }
1542 }
1543
1544 /* ------------------------------- */
1545
1546 /* create a new stroke point at the point indicated by the painting context */
1547 static void gpencil_draw_apply(wmOperator *op, tGPsdata *p)
1548 {
1549         /* handle drawing/erasing -> test for erasing first */
1550         if (p->paintmode == GP_PAINTMODE_ERASER) {
1551                 /* do 'live' erasing now */
1552                 gp_stroke_doeraser(p);
1553                 
1554                 /* store used values */
1555                 p->mvalo[0] = p->mval[0];
1556                 p->mvalo[1] = p->mval[1];
1557                 p->opressure = p->pressure;
1558         }
1559         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
1560         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
1561                 /* try to add point */
1562                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
1563                 
1564                 /* handle errors while adding point */
1565                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
1566                         /* finish off old stroke */
1567                         gp_paint_strokeend(p);
1568                         /* And start a new one!!! Else, projection errors! */
1569                         gp_paint_initstroke(p, p->paintmode);
1570                         
1571                         /* start a new stroke, starting from previous point */
1572                         /* XXX Must manually reset inittime... */
1573                         /* XXX We only need to reuse previous point if overflow! */
1574                         if (ok == GP_STROKEADD_OVERFLOW) {
1575                                 p->inittime = p->ocurtime;
1576                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
1577                         }
1578                         else {
1579                                 p->inittime = p->curtime;
1580                         }
1581                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
1582                 }
1583                 else if (ok == GP_STROKEADD_INVALID) {
1584                         /* the painting operation cannot continue... */
1585                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
1586                         p->status = GP_STATUS_ERROR;
1587                         
1588                         if (G.debug & G_DEBUG)
1589                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
1590                         return;
1591                 }
1592                 
1593                 /* store used values */
1594                 p->mvalo[0] = p->mval[0];
1595                 p->mvalo[1] = p->mval[1];
1596                 p->opressure = p->pressure;
1597                 p->ocurtime = p->curtime;
1598         }
1599 }
1600
1601 /* handle draw event */
1602 static void gpencil_draw_apply_event(wmOperator *op, const wmEvent *event)
1603 {
1604         tGPsdata *p = op->customdata;
1605         PointerRNA itemptr;
1606         float mousef[2];
1607         int tablet = 0;
1608         
1609         /* convert from window-space to area-space mouse coordinates
1610          * NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
1611          */
1612         p->mval[0] = event->mval[0] + 1;
1613         p->mval[1] = event->mval[1] + 1;
1614         p->curtime = PIL_check_seconds_timer();
1615         
1616         /* handle pressure sensitivity (which is supplied by tablets) */
1617         if (event->tablet_data) {
1618                 wmTabletData *wmtab = event->tablet_data;
1619                 
1620                 tablet = (wmtab->Active != EVT_TABLET_NONE);
1621                 p->pressure = wmtab->Pressure;
1622                 
1623                 /* if (wmtab->Active == EVT_TABLET_ERASER) */
1624                 /* TODO... this should get caught by the keymaps which call drawing in the first place */
1625         }
1626         else
1627                 p->pressure = 1.0f;
1628         
1629         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
1630         RNA_collection_add(op->ptr, "stroke", &itemptr);
1631         
1632         mousef[0] = p->mval[0];
1633         mousef[1] = p->mval[1];
1634         RNA_float_set_array(&itemptr, "mouse", mousef);
1635         RNA_float_set(&itemptr, "pressure", p->pressure);
1636         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN));
1637         
1638         /* special exception for start of strokes (i.e. maybe for just a dot) */
1639         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1640                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1641                 
1642                 p->mvalo[0] = p->mval[0];
1643                 p->mvalo[1] = p->mval[1];
1644                 p->opressure = p->pressure;
1645                 p->inittime = p->ocurtime = p->curtime;
1646                 
1647                 /* special exception here for too high pressure values on first touch in
1648                  *  windows for some tablets, then we just skip first touch...
1649                  */
1650                 if (tablet && (p->pressure >= 0.99f))
1651                         return;
1652         }
1653         
1654         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
1655         
1656         /* apply the current latest drawing point */
1657         gpencil_draw_apply(op, p);
1658         
1659         /* force refresh */
1660         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1661 }
1662
1663 /* ------------------------------- */
1664
1665 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
1666 static int gpencil_draw_exec(bContext *C, wmOperator *op)
1667 {
1668         tGPsdata *p = NULL;
1669         
1670         /* printf("GPencil - Starting Re-Drawing\n"); */
1671         
1672         /* try to initialize context data needed while drawing */
1673         if (!gpencil_draw_init(C, op)) {
1674                 if (op->customdata) MEM_freeN(op->customdata);
1675                 /* printf("\tGP - no valid data\n"); */
1676                 return OPERATOR_CANCELLED;
1677         }
1678         else
1679                 p = op->customdata;
1680         
1681         /* printf("\tGP - Start redrawing stroke\n"); */
1682         
1683         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
1684          * setting the relevant values in context at each step, then applying
1685          */
1686         RNA_BEGIN (op->ptr, itemptr, "stroke")
1687         {
1688                 float mousef[2];
1689                 
1690                 /* printf("\t\tGP - stroke elem\n"); */
1691                 
1692                 /* get relevant data for this point from stroke */
1693                 RNA_float_get_array(&itemptr, "mouse", mousef);
1694                 p->mval[0] = (int)mousef[0];
1695                 p->mval[1] = (int)mousef[1];
1696                 p->pressure = RNA_float_get(&itemptr, "pressure");
1697                 p->curtime = (double)RNA_float_get(&itemptr, "time") + p->inittime;
1698                 
1699                 if (RNA_boolean_get(&itemptr, "is_start")) {
1700                         /* if first-run flag isn't set already (i.e. not true first stroke),
1701                          * then we must terminate the previous one first before continuing
1702                          */
1703                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
1704                                 /* TODO: both of these ops can set error-status, but we probably don't need to worry */
1705                                 gp_paint_strokeend(p);
1706                                 gp_paint_initstroke(p, p->paintmode);
1707                         }
1708                 }
1709                 
1710                 /* if first run, set previous data too */
1711                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1712                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1713                         
1714                         p->mvalo[0] = p->mval[0];
1715                         p->mvalo[1] = p->mval[1];
1716                         p->opressure = p->pressure;
1717                         p->ocurtime = p->curtime;
1718                 }
1719                 
1720                 /* apply this data as necessary now (as per usual) */
1721                 gpencil_draw_apply(op, p);
1722         }
1723         RNA_END;
1724         
1725         /* printf("\tGP - done\n"); */
1726         
1727         /* cleanup */
1728         gpencil_draw_exit(C, op);
1729         
1730         /* refreshes */
1731         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1732         
1733         /* done */
1734         return OPERATOR_FINISHED;
1735 }
1736
1737 /* ------------------------------- */
1738
1739 /* start of interactive drawing part of operator */
1740 static int gpencil_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1741 {
1742         tGPsdata *p = NULL;
1743         wmWindow *win = CTX_wm_window(C);
1744         
1745         if (G.debug & G_DEBUG)
1746                 printf("GPencil - Starting Drawing\n");
1747         
1748         /* try to initialize context data needed while drawing */
1749         if (!gpencil_draw_init(C, op)) {
1750                 if (op->customdata) 
1751                         MEM_freeN(op->customdata);
1752                 if (G.debug & G_DEBUG)
1753                         printf("\tGP - no valid data\n");
1754                 return OPERATOR_CANCELLED;
1755         }
1756         else
1757                 p = op->customdata;
1758
1759         /* TODO: set any additional settings that we can take from the events?
1760          * TODO? if tablet is erasing, force eraser to be on? */
1761
1762         /* TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway... */
1763
1764         /* if eraser is on, draw radial aid */
1765         if (p->paintmode == GP_PAINTMODE_ERASER) {
1766                 gpencil_draw_toggle_eraser_cursor(C, p, true);
1767         }
1768         
1769         /* set cursor */
1770         if (p->paintmode == GP_PAINTMODE_ERASER)
1771                 WM_cursor_modal_set(win, BC_CROSSCURSOR);  /* XXX need a better cursor */
1772         else
1773                 WM_cursor_modal_set(win, BC_PAINTBRUSHCURSOR);
1774         
1775         /* special hack: if there was an initial event, then we were invoked via a hotkey, and 
1776          * painting should start immediately. Otherwise, this was called from a toolbar, in which
1777          * case we should wait for the mouse to be clicked.
1778          */
1779         if (event->val == KM_PRESS) {
1780                 /* hotkey invoked - start drawing */
1781                 /* printf("\tGP - set first spot\n"); */
1782                 p->status = GP_STATUS_PAINTING;
1783                 
1784                 /* handle the initial drawing - i.e. for just doing a simple dot */
1785                 gpencil_draw_apply_event(op, event);
1786         }
1787         else {
1788                 /* toolbar invoked - don't start drawing yet... */
1789                 /* printf("\tGP - hotkey invoked... waiting for click-drag\n"); */
1790         }
1791         
1792         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1793         /* add a modal handler for this operator, so that we can then draw continuous strokes */
1794         WM_event_add_modal_handler(C, op);
1795         return OPERATOR_RUNNING_MODAL;
1796 }
1797
1798 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1799 static bool gpencil_area_exists(bContext *C, ScrArea *sa_test)
1800 {
1801         bScreen *sc = CTX_wm_screen(C);
1802         return (BLI_findindex(&sc->areabase, sa_test) != -1);
1803 }
1804
1805 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
1806 {
1807         tGPsdata *p = op->customdata;
1808         
1809         /* we must check that we're still within the area that we're set up to work from
1810          * otherwise we could crash (see bug #20586)
1811          */
1812         if (CTX_wm_area(C) != p->sa) {
1813                 printf("\t\t\tGP - wrong area execution abort!\n");
1814                 p->status = GP_STATUS_ERROR;
1815         }
1816         
1817         /* printf("\t\tGP - start stroke\n"); */
1818         
1819         /* we may need to set up paint env again if we're resuming */
1820         /* XXX: watch it with the paintmode! in future,
1821          *      it'd be nice to allow changing paint-mode when in sketching-sessions */
1822         /* XXX: with tablet events, we may event want to check for eraser here, for nicer tablet support */
1823         
1824         if (gp_session_initdata(C, p))
1825                 gp_paint_initstroke(p, p->paintmode);
1826         
1827         if (p->status != GP_STATUS_ERROR)
1828                 p->status = GP_STATUS_PAINTING;
1829         
1830         return op->customdata;
1831 }
1832
1833 static void gpencil_stroke_end(wmOperator *op)
1834 {
1835         tGPsdata *p = op->customdata;
1836
1837         gp_paint_cleanup(p);
1838
1839         gpencil_undo_push(p->gpd);
1840
1841         gp_session_cleanup(p);
1842
1843         p->status = GP_STATUS_IDLING;
1844
1845         p->gpd = NULL;
1846         p->gpl = NULL;
1847         p->gpf = NULL;
1848 }
1849
1850 /* events handling during interactive drawing part of operator */
1851 static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
1852 {
1853         tGPsdata *p = op->customdata;
1854         int estate = OPERATOR_PASS_THROUGH; /* default exit state - pass through to support MMB view nav, etc. */
1855         
1856         /* if (event->type == NDOF_MOTION)
1857          *    return OPERATOR_PASS_THROUGH;
1858          * -------------------------------
1859          * [mce] Not quite what I was looking
1860          * for, but a good start! GP continues to
1861          * draw on the screen while the 3D mouse
1862          * moves the viewpoint. Problem is that
1863          * the stroke is converted to 3D only after
1864          * it is finished. This approach should work
1865          * better in tools that immediately apply
1866          * in 3D space.
1867          */
1868
1869         /* we don't pass on key events, GP is used with key-modifiers - prevents Dkey to insert drivers */
1870         if (ISKEYBOARD(event->type)) {
1871                 if (ELEM(event->type, LEFTARROWKEY, DOWNARROWKEY, RIGHTARROWKEY, UPARROWKEY)) {
1872                         /* allow some keys - for frame changing: [#33412] */
1873                 }
1874                 else {
1875                         estate = OPERATOR_RUNNING_MODAL;
1876                 }
1877         }
1878         
1879         //printf("\tGP - handle modal event...\n");
1880         
1881         /* exit painting mode (and/or end current stroke) 
1882          * NOTE: cannot do RIGHTMOUSE (as is standard for canceling) as that would break polyline [#32647]
1883          */
1884         if (ELEM(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY)) {
1885                 /* exit() ends the current stroke before cleaning up */
1886                 /* printf("\t\tGP - end of paint op + end of stroke\n"); */
1887                 p->status = GP_STATUS_DONE;
1888                 estate = OPERATOR_FINISHED;
1889         }
1890         
1891         /* toggle painting mode upon mouse-button movement 
1892          *  - LEFTMOUSE  = standard drawing (all) / straight line drawing (all) / polyline (toolbox only)
1893          *  - RIGHTMOUSE = polyline (hotkey) / eraser (all)
1894          *    (Disabling RIGHTMOUSE case here results in bugs like [#32647])
1895          */
1896         if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE)) {
1897                 /* if painting, end stroke */
1898                 if (p->status == GP_STATUS_PAINTING) {
1899                         int sketch = 0;
1900                         
1901                         /* basically, this should be mouse-button up = end stroke 
1902                          * BUT what happens next depends on whether we 'painting sessions' is enabled
1903                          */
1904                         sketch |= GPENCIL_SKETCH_SESSIONS_ON(p->scene);
1905                         /* polyline drawing is also 'sketching' -- all knots should be added during one session */
1906                         sketch |= (p->paintmode == GP_PAINTMODE_DRAW_POLY);
1907                         
1908                         if (sketch) {
1909                                 /* end stroke only, and then wait to resume painting soon */
1910                                 /* printf("\t\tGP - end stroke only\n"); */
1911                                 gpencil_stroke_end(op);
1912                                 
1913                                 /* we've just entered idling state, so this event was processed (but no others yet) */
1914                                 estate = OPERATOR_RUNNING_MODAL;
1915                                 
1916                                 /* stroke could be smoothed, send notifier to refresh screen */
1917                                 WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1918                         }
1919                         else {
1920                                 /* printf("\t\tGP - end of stroke + op\n"); */
1921                                 p->status = GP_STATUS_DONE;
1922                                 estate = OPERATOR_FINISHED;
1923                         }
1924                 }
1925                 else if (event->val == KM_PRESS) {
1926                         /* not painting, so start stroke (this should be mouse-button down) */
1927                         p = gpencil_stroke_begin(C, op);
1928                         
1929                         if (p->status == GP_STATUS_ERROR) {
1930                                 estate = OPERATOR_CANCELLED;
1931                         }
1932                 }
1933                 else {
1934                         p->status = GP_STATUS_IDLING;
1935                 }
1936         }
1937         
1938         /* handle mode-specific events */
1939         if (p->status == GP_STATUS_PAINTING) {
1940                 /* handle painting mouse-movements? */
1941                 if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (p->flags & GP_PAINTFLAG_FIRSTRUN)) {
1942                         /* handle drawing event */
1943                         /* printf("\t\tGP - add point\n"); */
1944                         gpencil_draw_apply_event(op, event);
1945                         
1946                         /* finish painting operation if anything went wrong just now */
1947                         if (p->status == GP_STATUS_ERROR) {
1948                                 printf("\t\t\t\tGP - add error done!\n");
1949                                 estate = OPERATOR_CANCELLED;
1950                         }
1951                         else {
1952                                 /* event handled, so just tag as running modal */
1953                                 /* printf("\t\t\t\tGP - add point handled!\n"); */
1954                                 estate = OPERATOR_RUNNING_MODAL;
1955                         }
1956                 }
1957                 /* eraser size */
1958                 else if ((p->paintmode == GP_PAINTMODE_ERASER) &&
1959                          ELEM(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE, PADPLUSKEY, PADMINUS))
1960                 {
1961                         /* just resize the brush (local version)
1962                          * TODO: fix the hardcoded size jumps (set to make a visible difference) and hardcoded keys
1963                          */
1964                         /* printf("\t\tGP - resize eraser\n"); */
1965                         switch (event->type) {
1966                                 case WHEELDOWNMOUSE: /* larger */
1967                                 case PADPLUSKEY:
1968                                         p->radius += 5;
1969                                         break;
1970                                         
1971                                 case WHEELUPMOUSE: /* smaller */
1972                                 case PADMINUS:
1973                                         p->radius -= 5;
1974                                         
1975                                         if (p->radius < 0) 
1976                                                 p->radius = 0;
1977                                         break;
1978                         }
1979                         
1980                         /* force refresh */
1981                         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1982                         
1983                         /* event handled, so just tag as running modal */
1984                         estate = OPERATOR_RUNNING_MODAL;
1985                 }
1986                 /* there shouldn't be any other events, but just in case there are, let's swallow them 
1987                  * (i.e. to prevent problems with undo)
1988                  */
1989                 else {
1990                         /* swallow event to save ourselves trouble */
1991                         estate = OPERATOR_RUNNING_MODAL;
1992                 }
1993         }
1994         
1995         /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1996         if (0 == gpencil_area_exists(C, p->sa))
1997                 estate = OPERATOR_CANCELLED;
1998         else
1999                 /* update status indicators - cursor, header, etc. */
2000                 gpencil_draw_status_indicators(p);
2001         
2002         /* process last operations before exiting */
2003         switch (estate) {
2004                 case OPERATOR_FINISHED:
2005                         /* one last flush before we're done */
2006                         gpencil_draw_exit(C, op);
2007                         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2008                         break;
2009                         
2010                 case OPERATOR_CANCELLED:
2011                         gpencil_draw_exit(C, op);
2012                         break;
2013                 
2014                 case OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH:
2015                         /* event doesn't need to be handled */
2016 #if 0
2017                         printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n",
2018                                event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
2019 #endif
2020                         break;
2021         }
2022         
2023         /* return status code */
2024         return estate;
2025 }
2026
2027 /* ------------------------------- */
2028
2029 static EnumPropertyItem prop_gpencil_drawmodes[] = {
2030         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", "Draw freehand stroke(s)"},
2031         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", "Draw straight line segment(s)"},
2032         {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", "Click to place endpoints of straight line segments (connected)"},
2033         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", "Erase Grease Pencil strokes"},
2034         {0, NULL, 0, NULL, NULL}
2035 };
2036
2037 void GPENCIL_OT_draw(wmOperatorType *ot)
2038 {
2039         /* identifiers */
2040         ot->name = "Grease Pencil Draw";
2041         ot->idname = "GPENCIL_OT_draw";
2042         ot->description = "Make annotations on the active data";
2043         
2044         /* api callbacks */
2045         ot->exec = gpencil_draw_exec;
2046         ot->invoke = gpencil_draw_invoke;
2047         ot->modal = gpencil_draw_modal;
2048         ot->cancel = gpencil_draw_cancel;
2049         ot->poll = gpencil_draw_poll;
2050         
2051         /* flags */
2052         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2053         
2054         /* settings for drawing */
2055         ot->prop = RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
2056         
2057         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2058 }