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