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