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