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