4004efacadce5ae55ff3d19fd6ad9024b53cc769
[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
31 #include <stdio.h>
32 #include <stddef.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_utildefines.h"
42
43 #include "BKE_gpencil.h"
44 #include "BKE_context.h"
45 #include "BKE_global.h"
46 #include "BKE_report.h"
47 #include "BKE_tracking.h"
48
49 #include "DNA_object_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_gpencil_types.h"
52 #include "DNA_windowmanager_types.h"
53
54 #include "UI_view2d.h"
55
56 #include "ED_gpencil.h"
57 #include "ED_screen.h"
58 #include "ED_view3d.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) / ((p->subrect->xmax - p->subrect->xmin))) * 100;
303                         out[1] = ((mval[1] - p->subrect->ymin) / ((p->subrect->ymax - p->subrect->ymin))) * 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(int mval[], int UNUSED(mvalo[]), short rad, short x0, short y0, short x1, short y1)
781 {
782         /* simple within-radius check for now */
783         if (edge_inside_circle(mval[0], mval[1], rad, x0, y0, x1, y1))
784                 return 1;
785         
786         /* not inside */
787         return 0;
788
789
790 /* eraser tool - evaluation per stroke */
791 // TODO: this could really do with some optimization (KD-Tree/BVH?)
792 static void gp_stroke_eraser_dostroke(tGPsdata *p, int mval[], int mvalo[], short rad, rcti *rect, bGPDframe *gpf, bGPDstroke *gps)
793 {
794         bGPDspoint *pt1, *pt2;
795         int x0 = 0, y0 = 0, x1 = 0, y1 = 0;
796         int xyval[2];
797         int i;
798         
799         if (gps->totpoints == 0) {
800                 /* just free stroke */
801                 if (gps->points) 
802                         MEM_freeN(gps->points);
803                 BLI_freelinkN(&gpf->strokes, gps);
804         }
805         else if (gps->totpoints == 1) {
806                 /* get coordinates */
807                 if (gps->flag & GP_STROKE_3DSPACE) {
808                         project_int(p->ar, &gps->points->x, xyval);
809                         x0 = xyval[0];
810                         y0 = xyval[1];
811                 }
812                 else if (gps->flag & GP_STROKE_2DSPACE) {                       
813                         UI_view2d_view_to_region(p->v2d, gps->points->x, gps->points->y, &x0, &y0);
814                 }
815                 else {
816                         if (p->subrect == NULL) { /* normal 3D view */
817                                 x0 = (int)(gps->points->x / 100 * p->ar->winx);
818                                 y0 = (int)(gps->points->y / 100 * p->ar->winy);
819                         }
820                         else { /* camera view, use subrect */
821                                 x0 = (int)((gps->points->x / 100) * (p->subrect->xmax - p->subrect->xmin)) + p->subrect->xmin;
822                                 y0 = (int)((gps->points->y / 100) * (p->subrect->ymax - p->subrect->ymin)) + p->subrect->ymin;
823                         }
824                 }
825                 
826                 /* do boundbox check first */
827                 if (BLI_in_rcti(rect, x0, y0)) {
828                         /* only check if point is inside */
829                         if ( ((x0 - mval[0]) * (x0 - mval[0]) + (y0 - mval[1]) * (y0 - mval[1])) <= rad * rad) {
830                                 /* free stroke */
831                                 MEM_freeN(gps->points);
832                                 BLI_freelinkN(&gpf->strokes, gps);
833                         }
834                 }
835         }
836         else {  
837                 /* loop over the points in the stroke, checking for intersections 
838                  *  - an intersection will require the stroke to be split
839                  */
840                 for (i = 0; (i + 1) < gps->totpoints; i++) {
841                         /* get points to work with */
842                         pt1 = gps->points + i;
843                         pt2 = gps->points + i + 1;
844                         
845                         /* get coordinates */
846                         if (gps->flag & GP_STROKE_3DSPACE) {
847                                 project_int(p->ar, &pt1->x, xyval);
848                                 x0 = xyval[0];
849                                 y0 = xyval[1];
850                                 
851                                 project_int(p->ar, &pt2->x, xyval);
852                                 x1 = xyval[0];
853                                 y1 = xyval[1];
854                         }
855                         else if (gps->flag & GP_STROKE_2DSPACE) {
856                                 UI_view2d_view_to_region(p->v2d, pt1->x, pt1->y, &x0, &y0);
857                                 
858                                 UI_view2d_view_to_region(p->v2d, pt2->x, pt2->y, &x1, &y1);
859                         }
860                         else {
861                                 if (p->subrect == NULL) { /* normal 3D view */
862                                         x0 = (int)(pt1->x / 100 * p->ar->winx);
863                                         y0 = (int)(pt1->y / 100 * p->ar->winy);
864                                         x1 = (int)(pt2->x / 100 * p->ar->winx);
865                                         y1 = (int)(pt2->y / 100 * p->ar->winy);
866                                 }
867                                 else { /* camera view, use subrect */ 
868                                         x0 = (int)((pt1->x / 100) * (p->subrect->xmax - p->subrect->xmin)) + p->subrect->xmin;
869                                         y0 = (int)((pt1->y / 100) * (p->subrect->ymax - p->subrect->ymin)) + p->subrect->ymin;
870                                         x1 = (int)((pt2->x / 100) * (p->subrect->xmax - p->subrect->xmin)) + p->subrect->xmin;
871                                         y1 = (int)((pt2->y / 100) * (p->subrect->ymax - p->subrect->ymin)) + p->subrect->ymin;
872                                 }
873                         }
874                         
875                         /* check that point segment of the boundbox of the eraser stroke */
876                         if (BLI_in_rcti(rect, x0, y0) || BLI_in_rcti(rect, x1, y1)) {
877                                 /* check if point segment of stroke had anything to do with
878                                  * eraser region  (either within stroke painted, or on its lines)
879                                  *  - this assumes that linewidth is irrelevant
880                                  */
881                                 if (gp_stroke_eraser_strokeinside(mval, mvalo, rad, x0, y0, x1, y1)) {
882                                         /* if function returns true, break this loop (as no more point to check) */
883                                         if (gp_stroke_eraser_splitdel(gpf, gps, i))
884                                                 break;
885                                 }
886                         }
887                 }
888         }
889 }
890
891 /* erase strokes which fall under the eraser strokes */
892 static void gp_stroke_doeraser(tGPsdata *p)
893 {
894         bGPDframe *gpf = p->gpf;
895         bGPDstroke *gps, *gpn;
896         rcti rect;
897         
898         /* rect is rectangle of eraser */
899         rect.xmin = p->mval[0] - p->radius;
900         rect.ymin = p->mval[1] - p->radius;
901         rect.xmax = p->mval[0] + p->radius;
902         rect.ymax = p->mval[1] + p->radius;
903         
904         /* loop over strokes, checking segments for intersections */
905         for (gps = gpf->strokes.first; gps; gps = gpn) {
906                 gpn = gps->next;
907                 gp_stroke_eraser_dostroke(p, p->mval, p->mvalo, p->radius, &rect, gpf, gps);
908         }
909 }
910
911 /* ******************************************* */
912 /* Sketching Operator */
913
914 /* clear the session buffers (call this before AND after a paint operation) */
915 static void gp_session_validatebuffer(tGPsdata *p)
916 {
917         bGPdata *gpd = p->gpd;
918         
919         /* clear memory of buffer (or allocate it if starting a new session) */
920         if (gpd->sbuffer) {
921                 //printf("\t\tGP - reset sbuffer\n");
922                 memset(gpd->sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
923         }
924         else {
925                 //printf("\t\tGP - allocate sbuffer\n");
926                 gpd->sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
927         }
928         
929         /* reset indices */
930         gpd->sbuffer_size = 0;
931         
932         /* reset flags */
933         gpd->sbuffer_sflag = 0;
934 }
935
936 /* (re)init new painting data */
937 static int gp_session_initdata(bContext *C, tGPsdata *p)
938 {
939         bGPdata **gpd_ptr = NULL;
940         ScrArea *curarea = CTX_wm_area(C);
941         ARegion *ar = CTX_wm_region(C);
942         
943         /* make sure the active view (at the starting time) is a 3d-view */
944         if (curarea == NULL) {
945                 p->status = GP_STATUS_ERROR;
946                 if (G.debug & G_DEBUG)
947                         printf("Error: No active view for painting\n");
948                 return 0;
949         }
950         
951         /* pass on current scene and window */
952         p->scene = CTX_data_scene(C);
953         p->win = CTX_wm_window(C);
954
955         unit_m4(p->imat);
956         
957         switch (curarea->spacetype) {
958                 /* supported views first */
959                 case SPACE_VIEW3D:
960                 {
961                         // View3D *v3d= curarea->spacedata.first;
962                         // RegionView3D *rv3d= ar->regiondata;
963                         
964                         /* set current area 
965                          *      - must verify that region data is 3D-view (and not something else)
966                          */
967                         p->sa = curarea;
968                         p->ar = ar;
969                         
970                         if (ar->regiondata == NULL) {
971                                 p->status = GP_STATUS_ERROR;
972                                 if (G.debug & G_DEBUG)
973                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
974                                 return 0;
975                         }
976                 }
977                 break;
978
979                 case SPACE_NODE:
980                 {
981                         //SpaceNode *snode= curarea->spacedata.first;
982                         
983                         /* set current area */
984                         p->sa = curarea;
985                         p->ar = ar;
986                         p->v2d = &ar->v2d;
987                 }
988                 break;
989                 case SPACE_SEQ:
990                 {
991                         SpaceSeq *sseq = curarea->spacedata.first;
992                         
993                         /* set current area */
994                         p->sa = curarea;
995                         p->ar = ar;
996                         p->v2d = &ar->v2d;
997                         
998                         /* check that gpencil data is allowed to be drawn */
999                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
1000                                 p->status = GP_STATUS_ERROR;
1001                                 if (G.debug & G_DEBUG)
1002                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil\n");
1003                                 return 0;
1004                         }
1005                 }
1006                 break;
1007                 case SPACE_IMAGE:
1008                 {
1009                         //SpaceImage *sima= curarea->spacedata.first;
1010                         
1011                         /* set the current area */
1012                         p->sa = curarea;
1013                         p->ar = ar;
1014                         p->v2d = &ar->v2d;
1015                 }
1016                 break;
1017                 case SPACE_CLIP:
1018                 {
1019                         SpaceClip *sc = curarea->spacedata.first;
1020                         
1021                         /* set the current area */
1022                         p->sa = curarea;
1023                         p->ar = ar;
1024                         p->v2d = &ar->v2d;
1025                         
1026                         invert_m4_m4(p->imat, sc->unistabmat);
1027                         
1028                         /* custom color for new layer */
1029                         p->custom_color[0] = 1.0f;
1030                         p->custom_color[1] = 0.0f;
1031                         p->custom_color[2] = 0.5f;
1032                         p->custom_color[3] = 0.9f;
1033                         
1034                         if (sc->gpencil_src == SC_GPENCIL_SRC_TRACK) {
1035                                 int framenr = sc->user.framenr;
1036                                 MovieTrackingTrack *track = BKE_tracking_active_track(&sc->clip->tracking);
1037                                 MovieTrackingMarker *marker = BKE_tracking_exact_marker(track, framenr);
1038                                 
1039                                 p->imat[3][0] -= marker->pos[0];
1040                                 p->imat[3][1] -= marker->pos[1];
1041                         }
1042                 }
1043                 break;
1044                 
1045                 /* unsupported views */
1046                 default:
1047                 {
1048                         p->status = GP_STATUS_ERROR;
1049                         if (G.debug & G_DEBUG)
1050                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1051                         return 0;
1052                 }
1053                 break;
1054         }
1055         
1056         /* get gp-data */
1057         gpd_ptr = gpencil_data_get_pointers(C, &p->ownerPtr);
1058         if (gpd_ptr == NULL) {
1059                 p->status = GP_STATUS_ERROR;
1060                 if (G.debug & G_DEBUG)
1061                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1062                 return 0;
1063         }
1064         else {
1065                 /* if no existing GPencil block exists, add one */
1066                 if (*gpd_ptr == NULL)
1067                         *gpd_ptr = gpencil_data_addnew("GPencil");
1068                 p->gpd = *gpd_ptr;
1069         }
1070         
1071         if (ED_gpencil_session_active() == 0) {
1072                 /* initialize undo stack,
1073                  * also, existing undo stack would make buffer drawn */
1074                 gpencil_undo_init(p->gpd);
1075         }
1076         
1077         /* clear out buffer (stored in gp-data), in case something contaminated it */
1078         gp_session_validatebuffer(p);
1079         
1080         return 1;
1081 }
1082
1083 /* init new painting session */
1084 static tGPsdata *gp_session_initpaint(bContext *C)
1085 {
1086         tGPsdata *p = NULL;
1087
1088         /* create new context data */
1089         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
1090
1091         gp_session_initdata(C, p);
1092         
1093         /* return context data for running paint operator */
1094         return p;
1095 }
1096
1097 /* cleanup after a painting session */
1098 static void gp_session_cleanup(tGPsdata *p)
1099 {
1100         bGPdata *gpd = (p) ? p->gpd : NULL;
1101         
1102         /* error checking */
1103         if (gpd == NULL)
1104                 return;
1105         
1106         /* free stroke buffer */
1107         if (gpd->sbuffer) {
1108                 //printf("\t\tGP - free sbuffer\n");
1109                 MEM_freeN(gpd->sbuffer);
1110                 gpd->sbuffer = NULL;
1111         }
1112         
1113         /* clear flags */
1114         gpd->sbuffer_size = 0;
1115         gpd->sbuffer_sflag = 0;
1116 }
1117
1118 /* init new stroke */
1119 static void gp_paint_initstroke(tGPsdata *p, short paintmode)
1120 {       
1121         /* get active layer (or add a new one if non-existent) */
1122         p->gpl = gpencil_layer_getactive(p->gpd);
1123         if (p->gpl == NULL) {
1124                 p->gpl = gpencil_layer_addnew(p->gpd);
1125                 
1126                 if (p->custom_color[3])
1127                         copy_v3_v3(p->gpl->color, p->custom_color);
1128         }
1129         if (p->gpl->flag & GP_LAYER_LOCKED) {
1130                 p->status = GP_STATUS_ERROR;
1131                 if (G.debug & G_DEBUG)
1132                         printf("Error: Cannot paint on locked layer\n");
1133                 return;
1134         }
1135                 
1136         /* get active frame (add a new one if not matching frame) */
1137         p->gpf = gpencil_layer_getframe(p->gpl, p->scene->r.cfra, 1);
1138         if (p->gpf == NULL) {
1139                 p->status = GP_STATUS_ERROR;
1140                 if (G.debug & G_DEBUG)
1141                         printf("Error: No frame created (gpencil_paint_init)\n");
1142                 return;
1143         }
1144         else
1145                 p->gpf->flag |= GP_FRAME_PAINT;
1146         
1147         /* set 'eraser' for this stroke if using eraser */
1148         p->paintmode = paintmode;
1149         if (p->paintmode == GP_PAINTMODE_ERASER)
1150                 p->gpd->sbuffer_sflag |= GP_STROKE_ERASER;
1151                 
1152         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1153         p->flags |= GP_PAINTFLAG_FIRSTRUN;
1154         
1155
1156         /* when drawing in the camera view, in 2D space, set the subrect */
1157         if (!(p->gpd->flag & GP_DATA_VIEWALIGN)) {
1158                 if (p->sa->spacetype == SPACE_VIEW3D) {
1159                         View3D *v3d = p->sa->spacedata.first;
1160                         RegionView3D *rv3d = p->ar->regiondata;
1161                         
1162                         /* for camera view set the subrect */
1163                         if (rv3d->persp == RV3D_CAMOB) {
1164                                 ED_view3d_calc_camera_border(p->scene, p->ar, v3d, rv3d, &p->subrect_data, TRUE); /* no shift */
1165                                 p->subrect = &p->subrect_data;
1166                         }
1167                 }
1168         }
1169
1170         /* check if points will need to be made in view-aligned space */
1171         if (p->gpd->flag & GP_DATA_VIEWALIGN) {
1172                 switch (p->sa->spacetype) {
1173                         case SPACE_VIEW3D:
1174                         {
1175                                 RegionView3D *rv3d = p->ar->regiondata;
1176                                 float rvec[3];
1177                                 
1178                                 /* get reference point for 3d space placement */
1179                                 gp_get_3d_reference(p, rvec);
1180                                 initgrabz(rv3d, rvec[0], rvec[1], rvec[2]);
1181                                 
1182                                 p->gpd->sbuffer_sflag |= GP_STROKE_3DSPACE;
1183                         }
1184                         break;
1185                         
1186                         case SPACE_NODE:
1187                         {
1188                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1189                         }
1190                         break;
1191                         
1192                         case SPACE_SEQ:
1193                         {
1194                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1195                         }
1196                         break;
1197                         
1198                         case SPACE_IMAGE:
1199                         {
1200                                 SpaceImage *sima = (SpaceImage *)p->sa->spacedata.first;
1201                                 
1202                                 /* only set these flags if the image editor doesn't have an image active,
1203                                  * otherwise user will be confused by strokes not appearing after they're drawn
1204                                  *
1205                                  * Admittedly, this is a bit hacky, but it works much nicer from an ergonomic standpoint!
1206                                  */
1207                                 if (ELEM(NULL, sima, sima->image)) {
1208                                         /* make strokes be drawn in screen space */
1209                                         p->gpd->sbuffer_sflag &= ~GP_STROKE_2DSPACE;
1210                                         p->gpd->flag &= ~GP_DATA_VIEWALIGN;
1211                                 }       
1212                                 else
1213                                         p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1214                         }
1215                         break;
1216                                 
1217                         case SPACE_CLIP:
1218                         {
1219                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1220                         }
1221                         break;
1222                 }
1223         }
1224 }
1225
1226 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1227 static void gp_paint_strokeend(tGPsdata *p)
1228 {
1229         /* for surface sketching, need to set the right OpenGL context stuff so that 
1230          * the conversions will project the values correctly...
1231          */
1232         if (gpencil_project_check(p)) {
1233                 View3D *v3d = p->sa->spacedata.first;
1234                 
1235                 /* need to restore the original projection settings before packing up */
1236                 view3d_region_operator_needs_opengl(p->win, p->ar);
1237                 ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1 : 0);
1238         }
1239         
1240         /* check if doing eraser or not */
1241         if ((p->gpd->sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1242                 /* smooth stroke before transferring? */
1243                 gp_stroke_smooth(p);
1244                 
1245                 /* simplify stroke before transferring? */
1246                 gp_stroke_simplify(p);
1247                 
1248                 /* transfer stroke to frame */
1249                 gp_stroke_newfrombuffer(p);
1250         }
1251         
1252         /* clean up buffer now */
1253         gp_session_validatebuffer(p);
1254 }
1255
1256 /* finish off stroke painting operation */
1257 static void gp_paint_cleanup(tGPsdata *p)
1258 {
1259         /* p->gpd==NULL happens when stroke failed to initialize,
1260          * for example. when GP is hidden in current space (sergey) */
1261         if (p->gpd) {
1262                 /* finish off a stroke */
1263                 gp_paint_strokeend(p);
1264         }
1265         
1266         /* "unlock" frame */
1267         if (p->gpf)
1268                 p->gpf->flag &= ~GP_FRAME_PAINT;
1269 }
1270
1271 /* ------------------------------- */
1272
1273 /* Helper callback for drawing the cursor itself */
1274 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
1275 {
1276         tGPsdata *p = (tGPsdata *)p_ptr;
1277         
1278         if (p->paintmode == GP_PAINTMODE_ERASER) {
1279                 glPushMatrix();
1280                 
1281                 glTranslatef((float)x, (float)y, 0.0f);
1282                 
1283                 glColor4ub(255, 255, 255, 128);
1284                 
1285                 glEnable(GL_LINE_SMOOTH);
1286                 glEnable(GL_BLEND);
1287                 
1288                 glutil_draw_lined_arc(0.0, M_PI * 2.0, p->radius, 40);
1289                 
1290                 glDisable(GL_BLEND);
1291                 glDisable(GL_LINE_SMOOTH);
1292                 
1293                 glPopMatrix();
1294         }
1295 }
1296
1297 /* Turn brush cursor in 3D view on/off */
1298 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
1299 {
1300         if (p->erasercursor && !enable) {
1301                 /* clear cursor */
1302                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
1303                 p->erasercursor = NULL;
1304         }
1305         else if (enable) {
1306                 /* enable cursor */
1307                 p->erasercursor = WM_paint_cursor_activate(CTX_wm_manager(C), 
1308                                                            NULL, // XXX
1309                                                            gpencil_draw_eraser, p);
1310         }
1311 }
1312
1313 /* ------------------------------- */
1314
1315
1316 static void gpencil_draw_exit(bContext *C, wmOperator *op)
1317 {
1318         tGPsdata *p = op->customdata;
1319         
1320         /* clear undo stack */
1321         gpencil_undo_finish();
1322         
1323         /* restore cursor to indicate end of drawing */
1324         WM_cursor_restore(CTX_wm_window(C));
1325         
1326         /* don't assume that operator data exists at all */
1327         if (p) {
1328                 /* check size of buffer before cleanup, to determine if anything happened here */
1329                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1330                         /* turn off radial brush cursor */
1331                         gpencil_draw_toggle_eraser_cursor(C, p, FALSE);
1332                         
1333                         /* if successful, store the new eraser size to be used again next time */
1334                         if (p->status == GP_STATUS_DONE)
1335                                 U.gp_eraser = p->radius;
1336                 }
1337                 
1338                 /* cleanup */
1339                 gp_paint_cleanup(p);
1340                 gp_session_cleanup(p);
1341                 
1342                 /* finally, free the temp data */
1343                 MEM_freeN(p);   
1344         }
1345         
1346         op->customdata = NULL;
1347 }
1348
1349 static int gpencil_draw_cancel(bContext *C, wmOperator *op)
1350 {
1351         /* this is just a wrapper around exit() */
1352         gpencil_draw_exit(C, op);
1353         return OPERATOR_CANCELLED;
1354 }
1355
1356 /* ------------------------------- */
1357
1358
1359 static int gpencil_draw_init(bContext *C, wmOperator *op)
1360 {
1361         tGPsdata *p;
1362         int paintmode = RNA_enum_get(op->ptr, "mode");
1363         
1364         /* check context */
1365         p = op->customdata = gp_session_initpaint(C);
1366         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1367                 /* something wasn't set correctly in context */
1368                 gpencil_draw_exit(C, op);
1369                 return 0;
1370         }
1371         
1372         /* init painting data */
1373         gp_paint_initstroke(p, paintmode);
1374         if (p->status == GP_STATUS_ERROR) {
1375                 gpencil_draw_exit(C, op);
1376                 return 0;
1377         }
1378         
1379         /* radius for eraser circle is defined in userprefs now */
1380         p->radius = U.gp_eraser;
1381         
1382         /* everything is now setup ok */
1383         return 1;
1384 }
1385
1386
1387 /* ------------------------------- */
1388
1389 /* update UI indicators of status, including cursor and header prints */
1390 static void gpencil_draw_status_indicators(tGPsdata *p)
1391 {
1392         /* header prints */
1393         switch (p->status) {
1394                 case GP_STATUS_PAINTING:
1395                         /* only print this for paint-sessions, otherwise it gets annoying */
1396                         if (GPENCIL_SKETCH_SESSIONS_ON(p->scene))
1397                                 ED_area_headerprint(p->sa, "Grease Pencil: Drawing/erasing stroke... Release to end stroke");
1398                         break;
1399                 
1400                 case GP_STATUS_IDLING:
1401                         /* print status info */
1402                         switch (p->paintmode) {
1403                                 case GP_PAINTMODE_ERASER:
1404                                         ED_area_headerprint(p->sa, "Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | ESC/Enter to end");
1405                                         break;
1406                                 case GP_PAINTMODE_DRAW_STRAIGHT:
1407                                         ED_area_headerprint(p->sa, "Grease Pencil Line Session: Hold and drag LMB to draw | ESC/Enter to end");
1408                                         break;
1409                                 case GP_PAINTMODE_DRAW:
1410                                         ED_area_headerprint(p->sa, "Grease Pencil Freehand Session: Hold and drag LMB to draw | ESC/Enter to end");
1411                                         break;
1412                                         
1413                                 default: /* unhandled future cases */
1414                                         ED_area_headerprint(p->sa, "Grease Pencil Session: ESC/Enter to end");
1415                                         break;
1416                         }
1417                         break;
1418                         
1419                 case GP_STATUS_ERROR:
1420                 case GP_STATUS_DONE:
1421                         /* clear status string */
1422                         ED_area_headerprint(p->sa, NULL);
1423                         break;
1424         }
1425 }
1426
1427 /* ------------------------------- */
1428
1429 /* create a new stroke point at the point indicated by the painting context */
1430 static void gpencil_draw_apply(wmOperator *op, tGPsdata *p)
1431 {
1432         /* handle drawing/erasing -> test for erasing first */
1433         if (p->paintmode == GP_PAINTMODE_ERASER) {
1434                 /* do 'live' erasing now */
1435                 gp_stroke_doeraser(p);
1436                 
1437                 /* store used values */
1438                 p->mvalo[0] = p->mval[0];
1439                 p->mvalo[1] = p->mval[1];
1440                 p->opressure = p->pressure;
1441         }
1442         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
1443         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
1444                 /* try to add point */
1445                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure);
1446                 
1447                 /* handle errors while adding point */
1448                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
1449                         /* finish off old stroke */
1450                         gp_paint_strokeend(p);
1451                         
1452                         /* start a new stroke, starting from previous point */
1453                         gp_stroke_addpoint(p, p->mvalo, p->opressure);
1454                         gp_stroke_addpoint(p, p->mval, p->pressure);
1455                 }
1456                 else if (ok == GP_STROKEADD_INVALID) {
1457                         /* the painting operation cannot continue... */
1458                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
1459                         p->status = GP_STATUS_ERROR;
1460                         
1461                         if (G.debug & G_DEBUG)
1462                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
1463                         return;
1464                 }
1465                 
1466                 /* store used values */
1467                 p->mvalo[0] = p->mval[0];
1468                 p->mvalo[1] = p->mval[1];
1469                 p->opressure = p->pressure;
1470         }
1471 }
1472
1473 /* handle draw event */
1474 static void gpencil_draw_apply_event(wmOperator *op, wmEvent *event)
1475 {
1476         tGPsdata *p = op->customdata;
1477         PointerRNA itemptr;
1478         float mousef[2];
1479         int tablet = 0;
1480
1481         /* convert from window-space to area-space mouse coordintes 
1482          * NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding... 
1483          */
1484         p->mval[0] = event->mval[0] + 1;
1485         p->mval[1] = event->mval[1] + 1;
1486
1487         /* handle pressure sensitivity (which is supplied by tablets) */
1488         if (event->custom == EVT_DATA_TABLET) {
1489                 wmTabletData *wmtab = event->customdata;
1490                 
1491                 tablet = (wmtab->Active != EVT_TABLET_NONE);
1492                 p->pressure = wmtab->Pressure;
1493                 
1494                 //if (wmtab->Active == EVT_TABLET_ERASER)
1495                 // TODO... this should get caught by the keymaps which call drawing in the first place
1496         }
1497         else
1498                 p->pressure = 1.0f;
1499         
1500         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
1501         RNA_collection_add(op->ptr, "stroke", &itemptr);
1502         
1503         mousef[0] = p->mval[0];
1504         mousef[1] = p->mval[1];
1505         RNA_float_set_array(&itemptr, "mouse", mousef);
1506         RNA_float_set(&itemptr, "pressure", p->pressure);
1507         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN));
1508         
1509         /* special exception for start of strokes (i.e. maybe for just a dot) */
1510         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1511                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1512                 
1513                 p->mvalo[0] = p->mval[0];
1514                 p->mvalo[1] = p->mval[1];
1515                 p->opressure = p->pressure;
1516                 
1517                 /* special exception here for too high pressure values on first touch in
1518                  *  windows for some tablets, then we just skip first touch ..  
1519                  */
1520                 if (tablet && (p->pressure >= 0.99f))
1521                         return;
1522         }
1523         
1524         /* apply the current latest drawing point */
1525         gpencil_draw_apply(op, p);
1526         
1527         /* force refresh */
1528         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1529 }
1530
1531 /* ------------------------------- */
1532
1533 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
1534 static int gpencil_draw_exec(bContext *C, wmOperator *op)
1535 {
1536         tGPsdata *p = NULL;
1537         
1538         //printf("GPencil - Starting Re-Drawing\n");
1539         
1540         /* try to initialize context data needed while drawing */
1541         if (!gpencil_draw_init(C, op)) {
1542                 if (op->customdata) MEM_freeN(op->customdata);
1543                 //printf("\tGP - no valid data\n");
1544                 return OPERATOR_CANCELLED;
1545         }
1546         else
1547                 p = op->customdata;
1548         
1549         //printf("\tGP - Start redrawing stroke\n");
1550         
1551         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
1552          * setting the relevant values in context at each step, then applying
1553          */
1554         RNA_BEGIN(op->ptr, itemptr, "stroke")
1555         {
1556                 float mousef[2];
1557                 
1558                 //printf("\t\tGP - stroke elem\n");
1559                 
1560                 /* get relevant data for this point from stroke */
1561                 RNA_float_get_array(&itemptr, "mouse", mousef);
1562                 p->mval[0] = (int)mousef[0];
1563                 p->mval[1] = (int)mousef[1];
1564                 p->pressure = RNA_float_get(&itemptr, "pressure");
1565                 
1566                 if (RNA_boolean_get(&itemptr, "is_start")) {
1567                         /* if first-run flag isn't set already (i.e. not true first stroke),
1568                          * then we must terminate the previous one first before continuing
1569                          */
1570                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
1571                                 // TODO: both of these ops can set error-status, but we probably don't need to worry
1572                                 gp_paint_strokeend(p);
1573                                 gp_paint_initstroke(p, p->paintmode);
1574                         }
1575                 }
1576                 
1577                 /* if first run, set previous data too */
1578                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1579                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1580                         
1581                         p->mvalo[0] = p->mval[0];
1582                         p->mvalo[1] = p->mval[1];
1583                         p->opressure = p->pressure;
1584                 }
1585                 
1586                 /* apply this data as necessary now (as per usual) */
1587                 gpencil_draw_apply(op, p);
1588         }
1589         RNA_END;
1590         
1591         //printf("\tGP - done\n");
1592         
1593         /* cleanup */
1594         gpencil_draw_exit(C, op);
1595         
1596         /* refreshes */
1597         WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); // XXX need a nicer one that will work
1598         
1599         /* done */
1600         return OPERATOR_FINISHED;
1601 }
1602
1603 /* ------------------------------- */
1604
1605 /* start of interactive drawing part of operator */
1606 static int gpencil_draw_invoke(bContext *C, wmOperator *op, wmEvent *event)
1607 {
1608         tGPsdata *p = NULL;
1609         wmWindow *win = CTX_wm_window(C);
1610         
1611         if (G.debug & G_DEBUG)
1612                 printf("GPencil - Starting Drawing\n");
1613         
1614         /* try to initialize context data needed while drawing */
1615         if (!gpencil_draw_init(C, op)) {
1616                 if (op->customdata) 
1617                         MEM_freeN(op->customdata);
1618                 if (G.debug & G_DEBUG)
1619                         printf("\tGP - no valid data\n");
1620                 return OPERATOR_CANCELLED;
1621         }
1622         else
1623                 p = op->customdata;
1624         
1625         // TODO: set any additional settings that we can take from the events?
1626         // TODO? if tablet is erasing, force eraser to be on?
1627         
1628         // TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway...
1629         
1630         /* if eraser is on, draw radial aid */
1631         if (p->paintmode == GP_PAINTMODE_ERASER) {
1632                 gpencil_draw_toggle_eraser_cursor(C, p, TRUE);
1633         }
1634         
1635         /* set cursor */
1636         if (p->paintmode == GP_PAINTMODE_ERASER)
1637                 WM_cursor_modal(win, BC_CROSSCURSOR);  // XXX need a better cursor
1638         else
1639                 WM_cursor_modal(win, BC_PAINTBRUSHCURSOR);
1640         
1641         /* special hack: if there was an initial event, then we were invoked via a hotkey, and 
1642          * painting should start immediately. Otherwise, this was called from a toolbar, in which
1643          * case we should wait for the mouse to be clicked.
1644          */
1645         if (event->type) {
1646                 /* hotkey invoked - start drawing */
1647                 //printf("\tGP - set first spot\n");
1648                 p->status = GP_STATUS_PAINTING;
1649                 
1650                 /* handle the initial drawing - i.e. for just doing a simple dot */
1651                 gpencil_draw_apply_event(op, event);
1652         }
1653         else {
1654                 /* toolbar invoked - don't start drawing yet... */
1655                 //printf("\tGP - hotkey invoked... waiting for click-drag\n");
1656         }
1657         
1658         WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL, NULL);
1659         /* add a modal handler for this operator, so that we can then draw continuous strokes */
1660         WM_event_add_modal_handler(C, op);
1661         return OPERATOR_RUNNING_MODAL;
1662 }
1663
1664 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1665 static int gpencil_area_exists(bContext *C, ScrArea *sa_test)
1666 {
1667         bScreen *sc = CTX_wm_screen(C);
1668         ScrArea *sa;
1669         
1670         for (sa = sc->areabase.first; sa; sa = sa->next) {
1671                 if (sa == sa_test)
1672                         return 1;
1673         }
1674         
1675         return 0;
1676 }
1677
1678 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
1679 {
1680         tGPsdata *p = op->customdata;
1681
1682         /* we must check that we're still within the area that we're set up to work from
1683          * otherwise we could crash (see bug #20586)
1684          */
1685         if (CTX_wm_area(C) != p->sa) {
1686                 printf("\t\t\tGP - wrong area execution abort!\n");
1687                 p->status = GP_STATUS_ERROR;
1688         }
1689
1690         //printf("\t\tGP - start stroke\n");
1691
1692         /* we may need to set up paint env again if we're resuming */
1693         // XXX: watch it with the paintmode! in future, it'd be nice to allow changing paint-mode when in sketching-sessions
1694         // XXX: with tablet events, we may event want to check for eraser here, for nicer tablet support
1695
1696         if (gp_session_initdata(C, p))
1697                 gp_paint_initstroke(p, p->paintmode);
1698
1699         if (p->status != GP_STATUS_ERROR)
1700                 p->status = GP_STATUS_PAINTING;
1701
1702         return op->customdata;
1703 }
1704
1705 static void gpencil_stroke_end(wmOperator *op)
1706 {
1707         tGPsdata *p = op->customdata;
1708
1709         gp_paint_cleanup(p);
1710
1711         gpencil_undo_push(p->gpd);
1712
1713         gp_session_cleanup(p);
1714
1715         p->status = GP_STATUS_IDLING;
1716
1717         p->gpd = NULL;
1718         p->gpl = NULL;
1719         p->gpf = NULL;
1720 }
1721
1722 /* events handling during interactive drawing part of operator */
1723 static int gpencil_draw_modal(bContext *C, wmOperator *op, wmEvent *event)
1724 {
1725         tGPsdata *p = op->customdata;
1726         int estate = OPERATOR_PASS_THROUGH; /* default exit state - not handled, so let others have a share of the pie */
1727         
1728         // if (event->type == NDOF_MOTION)
1729         //      return OPERATOR_PASS_THROUGH;
1730         // -------------------------------
1731         // [mce] Not quite what I was looking
1732         // for, but a good start! GP continues to
1733         // draw on the screen while the 3D mouse
1734         // moves the viewpoint. Problem is that
1735         // the stroke is converted to 3D only after
1736         // it is finished. This approach should work
1737         // better in tools that immediately apply
1738         // in 3D space.
1739
1740         //printf("\tGP - handle modal event...\n");
1741         
1742         /* exit painting mode (and/or end current stroke) */
1743         if (ELEM5(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY, RIGHTMOUSE)) {
1744                 /* exit() ends the current stroke before cleaning up */
1745                 //printf("\t\tGP - end of paint op + end of stroke\n");
1746                 p->status = GP_STATUS_DONE;
1747                 estate = OPERATOR_FINISHED;
1748         }
1749         
1750         /* toggle painting mode upon mouse-button movement */
1751         if (event->type == LEFTMOUSE) {
1752                 /* if painting, end stroke */
1753                 if (p->status == GP_STATUS_PAINTING) {
1754                         int sketch = 0;
1755                         /* basically, this should be mouse-button up = end stroke 
1756                          * BUT what happens next depends on whether we 'painting sessions' is enabled
1757                          */
1758                         sketch |= GPENCIL_SKETCH_SESSIONS_ON(p->scene);
1759                         /* polyline drawing is also 'sketching' -- all knots should be added during one session */
1760                         sketch |= p->paintmode == GP_PAINTMODE_DRAW_POLY;
1761                         
1762                         if (sketch) {
1763                                 /* end stroke only, and then wait to resume painting soon */
1764                                 //printf("\t\tGP - end stroke only\n");
1765                                 gpencil_stroke_end(op);
1766                                 
1767                                 /* we've just entered idling state, so this event was processed (but no others yet) */
1768                                 estate = OPERATOR_RUNNING_MODAL;
1769                                 
1770                                 /* stroke could be smoothed, send notifier to refresh screen */
1771                                 WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL);
1772                         }
1773                         else {
1774                                 //printf("\t\tGP - end of stroke + op\n");
1775                                 p->status = GP_STATUS_DONE;
1776                                 estate = OPERATOR_FINISHED;
1777                         }
1778                 }
1779                 else if (event->val == KM_PRESS) {
1780                         /* not painting, so start stroke (this should be mouse-button down) */
1781                         p = gpencil_stroke_begin(C, op);
1782                         
1783                         if (p->status == GP_STATUS_ERROR) {
1784                                 estate = OPERATOR_CANCELLED;
1785                         }
1786                 } 
1787                 else {
1788                         p->status = GP_STATUS_IDLING;
1789                 }
1790         }
1791         
1792         /* handle mode-specific events */
1793         if (p->status == GP_STATUS_PAINTING) {
1794                 /* handle painting mouse-movements? */
1795                 if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (p->flags & GP_PAINTFLAG_FIRSTRUN)) {
1796                         /* handle drawing event */
1797                         //printf("\t\tGP - add point\n");
1798                         gpencil_draw_apply_event(op, event);
1799                         
1800                         /* finish painting operation if anything went wrong just now */
1801                         if (p->status == GP_STATUS_ERROR) {
1802                                 printf("\t\t\t\tGP - add error done!\n");
1803                                 estate = OPERATOR_CANCELLED;
1804                         }
1805                         else {
1806                                 /* event handled, so just tag as running modal */
1807                                 //printf("\t\t\t\tGP - add point handled!\n");
1808                                 estate = OPERATOR_RUNNING_MODAL;
1809                         }
1810                 }
1811                 /* eraser size */
1812                 else if ((p->paintmode == GP_PAINTMODE_ERASER) &&
1813                          ELEM4(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE, PADPLUSKEY, PADMINUS))
1814                 {
1815                         /* just resize the brush (local version)
1816                          * TODO: fix the hardcoded size jumps (set to make a visible difference) and hardcoded keys
1817                          */
1818                         //printf("\t\tGP - resize eraser\n");
1819                         switch (event->type) {
1820                                 case WHEELUPMOUSE: /* larger */
1821                                 case PADPLUSKEY:
1822                                         p->radius += 5;
1823                                         break;
1824                                         
1825                                 case WHEELDOWNMOUSE: /* smaller */
1826                                 case PADMINUS:
1827                                         p->radius -= 5;
1828                                         
1829                                         if (p->radius < 0) 
1830                                                 p->radius = 0;
1831                                         break;
1832                         }
1833                         
1834                         /* force refresh */
1835                         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1836                         
1837                         /* event handled, so just tag as running modal */
1838                         estate = OPERATOR_RUNNING_MODAL;
1839                 }
1840                 /* there shouldn't be any other events, but just in case there are, let's swallow them 
1841                  * (i.e. to prevent problems with undo)
1842                  */
1843                 else {
1844                         /* swallow event to save ourselves trouble */
1845                         estate = OPERATOR_RUNNING_MODAL;
1846                 }
1847         }
1848         
1849         /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1850         if (0 == gpencil_area_exists(C, p->sa))
1851                 estate = OPERATOR_CANCELLED;
1852         else
1853                 /* update status indicators - cursor, header, etc. */
1854                 gpencil_draw_status_indicators(p);
1855         
1856         /* process last operations before exiting */
1857         switch (estate) {
1858                 case OPERATOR_FINISHED:
1859                         /* one last flush before we're done */
1860                         gpencil_draw_exit(C, op);
1861                         WM_event_add_notifier(C, NC_SCREEN | ND_GPENCIL | NA_EDITED, NULL); // XXX need a nicer one that will work
1862                         break;
1863                         
1864                 case OPERATOR_CANCELLED:
1865                         gpencil_draw_exit(C, op);
1866                         break;
1867                 
1868                 case OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH:
1869                         /* event doesn't need to be handled */
1870                         //printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n", event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
1871                         break;
1872         }
1873         
1874         /* return status code */
1875         return estate;
1876 }
1877
1878 /* ------------------------------- */
1879
1880 static EnumPropertyItem prop_gpencil_drawmodes[] = {
1881         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", ""},
1882         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", ""},
1883         {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", ""},
1884         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", ""},
1885         {0, NULL, 0, NULL, NULL}
1886 };
1887
1888 void GPENCIL_OT_draw(wmOperatorType *ot)
1889 {
1890         /* identifiers */
1891         ot->name = "Grease Pencil Draw";
1892         ot->idname = "GPENCIL_OT_draw";
1893         ot->description = "Make annotations on the active data";
1894         
1895         /* api callbacks */
1896         ot->exec = gpencil_draw_exec;
1897         ot->invoke = gpencil_draw_invoke;
1898         ot->modal = gpencil_draw_modal;
1899         ot->cancel = gpencil_draw_cancel;
1900         ot->poll = gpencil_draw_poll;
1901         
1902         /* flags */
1903         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
1904         
1905         /* settings for drawing */
1906         RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
1907         
1908         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1909 }