Grease Pencil: Drawing Improvements
[blender.git] / source / blender / editors / gpencil / gpencil_paint.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2008, Blender Foundation, Joshua Leung
21  * This is a new part of Blender
22  *
23  * Contributor(s): Joshua Leung
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <stdio.h>
29 #include <stddef.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <math.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_blenlib.h"
37 #include "BLI_arithb.h"
38
39 #include "BKE_gpencil.h"
40 #include "BKE_context.h"
41 #include "BKE_global.h"
42 #include "BKE_report.h"
43 #include "BKE_utildefines.h"
44
45 #include "DNA_gpencil_types.h"
46 #include "DNA_action_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_screen_types.h"
50 #include "DNA_space_types.h"
51 #include "DNA_view2d_types.h"
52 #include "DNA_view3d_types.h"
53 #include "DNA_windowmanager_types.h"
54
55 #include "UI_view2d.h"
56
57 #include "ED_armature.h"
58 #include "ED_gpencil.h"
59 #include "ED_sequencer.h"
60 #include "ED_screen.h"
61 #include "ED_view3d.h"
62
63 #include "RNA_access.h"
64
65 #include "RNA_define.h"
66 #include "WM_api.h"
67 #include "WM_types.h"
68
69 #include "gpencil_intern.h"
70
71 /* ******************************************* */
72 /* 'Globals' and Defines */
73
74 /* Temporary 'Stroke' Operation data */
75 typedef struct tGPsdata {
76         Scene *scene;       /* current scene from context */
77         ScrArea *sa;            /* area where painting originated */
78         ARegion *ar;        /* region where painting originated */
79         View2D *v2d;            /* needed for GP_STROKE_2DSPACE */
80         
81 #if 0 // XXX review this 2d image stuff...
82         ImBuf *ibuf;            /* needed for GP_STROKE_2DIMAGE */
83         struct IBufViewSettings {
84                 int offsx, offsy;                       /* offsets */
85                 int sizex, sizey;                       /* dimensions to use as scale-factor */
86         } im2d_settings;        /* needed for GP_STROKE_2DIMAGE */
87 #endif
88         
89         bGPdata *gpd;           /* gp-datablock layer comes from */
90         bGPDlayer *gpl;         /* layer we're working on */
91         bGPDframe *gpf;         /* frame we're working on */
92         
93         short status;           /* current status of painting */
94         short paintmode;        /* mode for painting */
95         
96         int mval[2];            /* current mouse-position */
97         int mvalo[2];           /* previous recorded mouse-position */
98         
99         float pressure;         /* current stylus pressure */
100         float opressure;        /* previous stylus pressure */
101         
102         short radius;           /* radius of influence for eraser */
103         short flags;            /* flags that can get set during runtime */
104 } tGPsdata;
105
106 /* values for tGPsdata->status */
107 enum {
108         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
109         GP_STATUS_PAINTING,             /* a stroke is in progress */
110         GP_STATUS_ERROR,                /* something wasn't correctly set up */
111         GP_STATUS_DONE                  /* painting done */
112 };
113
114 /* Return flags for adding points to stroke buffer */
115 enum {
116         GP_STROKEADD_INVALID    = -2,           /* error occurred - insufficient info to do so */
117         GP_STROKEADD_OVERFLOW   = -1,           /* error occurred - cannot fit any more points */
118         GP_STROKEADD_NORMAL,                            /* point was successfully added */
119         GP_STROKEADD_FULL                                       /* cannot add any more points to buffer */
120 };
121
122 /* Runtime flags */
123 enum {
124         GP_PAINTFLAG_FIRSTRUN           = (1<<0),       /* operator just started */
125 };
126
127 /* ------ */
128
129 /* maximum sizes of gp-session buffer */
130 #define GP_STROKE_BUFFER_MAX    5000
131
132 /* Macros for accessing sensitivity thresholds... */
133         /* minimum number of pixels mouse should move before new point created */
134 #define MIN_MANHATTEN_PX        (U.gp_manhattendist)
135         /* minimum length of new segment before new point can be added */
136 #define MIN_EUCLIDEAN_PX        (U.gp_euclideandist)
137
138 /* ------ */
139 /* Forward defines for some functions... */
140
141 static void gp_session_validatebuffer(tGPsdata *p);
142
143 /* ******************************************* */
144 /* Context Wrangling... */
145
146 /* check if context is suitable for drawing */
147 static int gpencil_draw_poll (bContext *C)
148 {
149         /* check if current context can support GPencil data */
150         return (gpencil_data_get_pointers(C, NULL) != NULL);
151 }
152
153 /* ******************************************* */
154 /* Calculations/Conversions */
155
156 /* Stroke Editing ---------------------------- */
157
158 /* check if the current mouse position is suitable for adding a new point */
159 static short gp_stroke_filtermval (tGPsdata *p, int mval[2], int pmval[2])
160 {
161         int dx= abs(mval[0] - pmval[0]);
162         int dy= abs(mval[1] - pmval[1]);
163         
164         /* check if mouse moved at least certain distance on both axes (best case) */
165         if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
166                 return 1;
167         
168         /* check if the distance since the last point is significant enough */
169         // future optimisation: sqrt here may be too slow?
170         else if (sqrt(dx*dx + dy*dy) > MIN_EUCLIDEAN_PX)
171                 return 1;
172         
173         /* mouse 'didn't move' */
174         else
175                 return 0;
176 }
177
178 /* convert screen-coordinates to buffer-coordinates */
179 // XXX this method needs a total overhaul!
180 static void gp_stroke_convertcoords (tGPsdata *p, short mval[], float out[])
181 {
182         bGPdata *gpd= p->gpd;
183         
184         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
185         if (gpd->sbuffer_sflag & GP_STROKE_3DSPACE) {
186                 View3D *v3d= p->sa->spacedata.first;
187                 const short mx=mval[0], my=mval[1];
188                 float *fp= give_cursor(p->scene, v3d);
189                 float dvec[3];
190                 
191                 /* Current method just converts each point in screen-coordinates to 
192                  * 3D-coordinates using the 3D-cursor as reference. In general, this 
193                  * works OK, but it could of course be improved.
194                  *
195                  * TODO:
196                  *      - investigate using nearest point(s) on a previous stroke as
197                  *        reference point instead or as offset, for easier stroke matching
198                  *      - investigate projection onto geometry (ala retopo)
199                  */
200                 
201                 /* method taken from editview.c - mouse_cursor() */
202                 project_short_noclip(p->ar, fp, mval);
203                 window_to_3d_delta(p->ar, dvec, mval[0]-mx, mval[1]-my);
204                 VecSubf(out, fp, dvec);
205         }
206         
207         /* 2d - on 'canvas' (assume that p->v2d is set) */
208         else if ((gpd->sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
209                 float x, y;
210                 
211                 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &x, &y);
212                 
213                 out[0]= x;
214                 out[1]= y;
215         }
216         
217 #if 0
218         /* 2d - on image 'canvas' (assume that p->v2d is set) */
219         else if (gpd->sbuffer_sflag & GP_STROKE_2DIMAGE) {
220                 int sizex, sizey, offsx, offsy;
221                 
222                 /* get stored settings 
223                  *      - assume that these have been set already (there are checks that set sane 'defaults' just in case)
224                  */
225                 sizex= p->im2d_settings.sizex;
226                 sizey= p->im2d_settings.sizey;
227                 offsx= p->im2d_settings.offsx;
228                 offsy= p->im2d_settings.offsy;
229                 
230                 /* calculate new points */
231                 out[0]= (float)(mval[0] - offsx) / (float)sizex;
232                 out[1]= (float)(mval[1] - offsy) / (float)sizey;
233         }
234 #endif
235         
236         /* 2d - relative to screen (viewport area) */
237         else {
238                 out[0] = (float)(mval[0]) / (float)(p->sa->winx) * 100;
239                 out[1] = (float)(mval[1]) / (float)(p->sa->winy) * 100;
240         }
241 }
242
243 /* add current stroke-point to buffer (returns whether point was successfully added) */
244 static short gp_stroke_addpoint (tGPsdata *p, int mval[2], float pressure)
245 {
246         bGPdata *gpd= p->gpd;
247         tGPspoint *pt;
248         
249         /* check painting mode */
250         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
251                 /* straight lines only - i.e. only store start and end point in buffer */
252                 if (gpd->sbuffer_size == 0) {
253                         /* first point in buffer (start point) */
254                         pt= (tGPspoint *)(gpd->sbuffer);
255                         
256                         /* store settings */
257                         pt->x= mval[0];
258                         pt->y= mval[1];
259                         pt->pressure= pressure;
260                         
261                         /* increment buffer size */
262                         gpd->sbuffer_size++;
263                 }
264                 else {
265                         /* normally, we just reset the endpoint to the latest value 
266                          *      - assume that pointers for this are always valid...
267                          */
268                         pt= ((tGPspoint *)(gpd->sbuffer) + 1);
269                         
270                         /* store settings */
271                         pt->x= mval[0];
272                         pt->y= mval[1];
273                         pt->pressure= pressure;
274                         
275                         /* if this is just the second point we've added, increment the buffer size
276                          * so that it will be drawn properly...
277                          * otherwise, just leave it alone, otherwise we get problems
278                          */
279                         if (gpd->sbuffer_size != 2)
280                                 gpd->sbuffer_size= 2;
281                 }
282                 
283                 /* can keep carrying on this way :) */
284                 return GP_STROKEADD_NORMAL;
285         }
286         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
287                 /* check if still room in buffer */
288                 if (gpd->sbuffer_size >= GP_STROKE_BUFFER_MAX)
289                         return GP_STROKEADD_OVERFLOW;
290                 
291                 /* get pointer to destination point */
292                 pt= ((tGPspoint *)(gpd->sbuffer) + gpd->sbuffer_size);
293                 
294                 /* store settings */
295                 pt->x= mval[0];
296                 pt->y= mval[1];
297                 pt->pressure= pressure;
298                 
299                 /* increment counters */
300                 gpd->sbuffer_size++;
301                 
302                 /* check if another operation can still occur */
303                 if (gpd->sbuffer_size == GP_STROKE_BUFFER_MAX)
304                         return GP_STROKEADD_FULL;
305                 else
306                         return GP_STROKEADD_NORMAL;
307         }
308         
309         /* just say it's normal for now, since we don't have another state... */
310         return GP_STROKEADD_NORMAL;
311 }
312
313 /* smooth a stroke (in buffer) before storing it */
314 static void gp_stroke_smooth (tGPsdata *p)
315 {
316         bGPdata *gpd= p->gpd;
317         int i=0, cmx=gpd->sbuffer_size;
318         
319         /* only smooth if smoothing is enabled, and we're not doing a straight line */
320         if (!(U.gp_settings & GP_PAINT_DOSMOOTH) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
321                 return;
322         
323         /* don't try if less than 2 points in buffer */
324         if ((cmx <= 2) || (gpd->sbuffer == NULL))
325                 return;
326         
327         /* apply weighting-average (note doing this along path sequentially does introduce slight error) */
328         for (i=0; i < gpd->sbuffer_size; i++) {
329                 tGPspoint *pc= (((tGPspoint *)gpd->sbuffer) + i);
330                 tGPspoint *pb= (i-1 > 0)?(pc-1):(pc);
331                 tGPspoint *pa= (i-2 > 0)?(pc-2):(pb);
332                 tGPspoint *pd= (i+1 < cmx)?(pc+1):(pc);
333                 tGPspoint *pe= (i+2 < cmx)?(pc+2):(pd);
334                 
335                 pc->x= (short)(0.1*pa->x + 0.2*pb->x + 0.4*pc->x + 0.2*pd->x + 0.1*pe->x);
336                 pc->y= (short)(0.1*pa->y + 0.2*pb->y + 0.4*pc->y + 0.2*pd->y + 0.1*pe->y);
337         }
338 }
339
340 /* simplify a stroke (in buffer) before storing it 
341  *      - applies a reverse Chaikin filter
342  *      - code adapted from etch-a-ton branch (editarmature_sketch.c)
343  */
344 static void gp_stroke_simplify (tGPsdata *p)
345 {
346         bGPdata *gpd= p->gpd;
347         tGPspoint *old_points= (tGPspoint *)gpd->sbuffer;
348         short num_points= gpd->sbuffer_size;
349         short flag= gpd->sbuffer_sflag;
350         short i, j;
351         
352         /* only simplify if simlification is enabled, and we're not doing a straight line */
353         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
354                 return;
355         
356         /* don't simplify if less than 4 points in buffer */
357         if ((num_points <= 2) || (old_points == NULL))
358                 return;
359                 
360         /* clear buffer (but don't free mem yet) so that we can write to it 
361          *      - firstly set sbuffer to NULL, so a new one is allocated
362          *      - secondly, reset flag after, as it gets cleared auto
363          */
364         gpd->sbuffer= NULL;
365         gp_session_validatebuffer(p);
366         gpd->sbuffer_sflag = flag;
367         
368 /* macro used in loop to get position of new point
369  *      - used due to the mixture of datatypes in use here
370  */
371 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
372         { \
373                 co[0] += (float)(old_points[offs].x * sfac); \
374                 co[1] += (float)(old_points[offs].y * sfac); \
375                 pressure += old_points[offs].pressure * sfac; \
376         }
377         
378         for (i = 0, j = 0; i < num_points; i++)
379         {
380                 if (i - j == 3)
381                 {
382                         float co[2], pressure;
383                         int mco[2];
384                         
385                         /* initialise values */
386                         co[0]= 0;
387                         co[1]= 0;
388                         pressure = 0;
389                         
390                         /* using macro, calculate new point */
391                         GP_SIMPLIFY_AVPOINT(j, -0.25f);
392                         GP_SIMPLIFY_AVPOINT(j+1, 0.75f);
393                         GP_SIMPLIFY_AVPOINT(j+2, 0.75f);
394                         GP_SIMPLIFY_AVPOINT(j+3, -0.25f);
395                         
396                         /* set values for adding */
397                         mco[0]= (int)co[0];
398                         mco[1]= (int)co[1];
399                         
400                         /* ignore return values on this... assume to be ok for now */
401                         gp_stroke_addpoint(p, mco, pressure);
402                         
403                         j += 2;
404                 }
405         } 
406         
407         /* free old buffer */
408         MEM_freeN(old_points);
409 }
410
411
412 /* make a new stroke from the buffer data */
413 static void gp_stroke_newfrombuffer (tGPsdata *p)
414 {
415         bGPdata *gpd= p->gpd;
416         bGPDstroke *gps;
417         bGPDspoint *pt;
418         tGPspoint *ptc;
419         int i, totelem;
420         
421         /* get total number of points to allocate space for 
422          *      - drawing straight-lines only requires the endpoints
423          */
424         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
425                 totelem = (gpd->sbuffer_size >= 2) ? 2: gpd->sbuffer_size;
426         else
427                 totelem = gpd->sbuffer_size;
428         
429         /* exit with error if no valid points from this stroke */
430         if (totelem == 0) {
431                 if (G.f & G_DEBUG) 
432                         printf("Error: No valid points in stroke buffer to convert (tot=%d) \n", gpd->sbuffer_size);
433                 return;
434         }
435         
436         /* allocate memory for a new stroke */
437         gps= MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
438         
439         /* allocate enough memory for a continuous array for storage points */
440         pt= gps->points= MEM_callocN(sizeof(bGPDspoint)*totelem, "gp_stroke_points");
441         
442         /* copy appropriate settings for stroke */
443         gps->totpoints= totelem;
444         gps->thickness= p->gpl->thickness;
445         gps->flag= gpd->sbuffer_sflag;
446         
447         /* copy points from the buffer to the stroke */
448         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
449                 /* straight lines only -> only endpoints */
450                 {
451                         /* first point */
452                         ptc= gpd->sbuffer;
453                         
454                         /* convert screen-coordinates to appropriate coordinates (and store them) */
455                         gp_stroke_convertcoords(p, &ptc->x, &pt->x);
456                         
457                         /* copy pressure */
458                         pt->pressure= ptc->pressure;
459                         
460                         pt++;
461                 }
462                         
463                 if (totelem == 2) {
464                         /* last point if applicable */
465                         ptc= ((tGPspoint *)gpd->sbuffer) + (gpd->sbuffer_size - 1);
466                         
467                         /* convert screen-coordinates to appropriate coordinates (and store them) */
468                         gp_stroke_convertcoords(p, &ptc->x, &pt->x);
469                         
470                         /* copy pressure */
471                         pt->pressure= ptc->pressure;
472                 }
473         }
474         else {
475                 /* convert all points (normal behaviour) */
476                 for (i=0, ptc=gpd->sbuffer; i < gpd->sbuffer_size && ptc; i++, ptc++) {
477                         /* convert screen-coordinates to appropriate coordinates (and store them) */
478                         gp_stroke_convertcoords(p, &ptc->x, &pt->x);
479                         
480                         /* copy pressure */
481                         pt->pressure= ptc->pressure;
482                         
483                         pt++;
484                 }
485         }
486         
487         /* add stroke to frame */
488         BLI_addtail(&p->gpf->strokes, gps);
489 }
490
491 /* --- 'Eraser' for 'Paint' Tool ------ */
492
493 /* eraser tool - remove segment from stroke/split stroke (after lasso inside) */
494 static short gp_stroke_eraser_splitdel (bGPDframe *gpf, bGPDstroke *gps, int i)
495 {
496         bGPDspoint *pt_tmp= gps->points;
497         bGPDstroke *gsn = NULL;
498
499         /* if stroke only had two points, get rid of stroke */
500         if (gps->totpoints == 2) {
501                 /* free stroke points, then stroke */
502                 MEM_freeN(pt_tmp);
503                 BLI_freelinkN(&gpf->strokes, gps);
504                 
505                 /* nothing left in stroke, so stop */
506                 return 1;
507         }
508
509         /* if last segment, just remove segment from the stroke */
510         else if (i == gps->totpoints - 2) {
511                 /* allocate new points array, and assign most of the old stroke there */
512                 gps->totpoints--;
513                 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
514                 memcpy(gps->points, pt_tmp, sizeof(bGPDspoint)*gps->totpoints);
515                 
516                 /* free temp buffer */
517                 MEM_freeN(pt_tmp);
518                 
519                 /* nothing left in stroke, so stop */
520                 return 1;
521         }
522
523         /* if first segment, just remove segment from the stroke */
524         else if (i == 0) {
525                 /* allocate new points array, and assign most of the old stroke there */
526                 gps->totpoints--;
527                 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
528                 memcpy(gps->points, pt_tmp + 1, sizeof(bGPDspoint)*gps->totpoints);
529                 
530                 /* free temp buffer */
531                 MEM_freeN(pt_tmp);
532                 
533                 /* no break here, as there might still be stuff to remove in this stroke */
534                 return 0;
535         }
536
537         /* segment occurs in 'middle' of stroke, so split */
538         else {
539                 /* duplicate stroke, and assign 'later' data to that stroke */
540                 gsn= MEM_dupallocN(gps);
541                 gsn->prev= gsn->next= NULL;
542                 BLI_insertlinkafter(&gpf->strokes, gps, gsn);
543                 
544                 gsn->totpoints= gps->totpoints - i;
545                 gsn->points= MEM_callocN(sizeof(bGPDspoint)*gsn->totpoints, "gp_stroke_points");
546                 memcpy(gsn->points, pt_tmp + i, sizeof(bGPDspoint)*gsn->totpoints);
547                 
548                 /* adjust existing stroke  */
549                 gps->totpoints= i;
550                 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
551                 memcpy(gps->points, pt_tmp, sizeof(bGPDspoint)*i);
552                 
553                 /* free temp buffer */
554                 MEM_freeN(pt_tmp);
555                 
556                 /* nothing left in stroke, so stop */
557                 return 1;
558         }
559 }
560
561 /* eraser tool - check if part of stroke occurs within last segment drawn by eraser */
562 static short gp_stroke_eraser_strokeinside (int mval[], int mvalo[], short rad, short x0, short y0, short x1, short y1)
563 {
564         /* simple within-radius check for now */
565         if (edge_inside_circle(mval[0], mval[1], rad, x0, y0, x1, y1))
566                 return 1;
567         
568         /* not inside */
569         return 0;
570
571
572 /* eraser tool - evaluation per stroke */
573 // TODO: this could really do with some optimisation (KD-Tree/BVH?)
574 static void gp_stroke_eraser_dostroke (tGPsdata *p, int mval[], int mvalo[], short rad, rcti *rect, bGPDframe *gpf, bGPDstroke *gps)
575 {
576         bGPDspoint *pt1, *pt2;
577         int x0=0, y0=0, x1=0, y1=0;
578         short xyval[2];
579         int i;
580         
581         if (gps->totpoints == 0) {
582                 /* just free stroke */
583                 if (gps->points) 
584                         MEM_freeN(gps->points);
585                 BLI_freelinkN(&gpf->strokes, gps);
586         }
587         else if (gps->totpoints == 1) {
588                 /* get coordinates */
589                 if (gps->flag & GP_STROKE_3DSPACE) {
590                         project_short(p->ar, &gps->points->x, xyval);
591                         x0= xyval[0];
592                         y0= xyval[1];
593                 }
594                 else if (gps->flag & GP_STROKE_2DSPACE) {                       
595                         UI_view2d_view_to_region(p->v2d, gps->points->x, gps->points->y, &x0, &y0);
596                 }
597 #if 0
598                 else if (gps->flag & GP_STROKE_2DIMAGE) {                       
599                         int offsx, offsy, sizex, sizey;
600                         
601                         /* get stored settings */
602                         sizex= p->im2d_settings.sizex;
603                         sizey= p->im2d_settings.sizey;
604                         offsx= p->im2d_settings.offsx;
605                         offsy= p->im2d_settings.offsy;
606                         
607                         /* calculate new points */
608                         x0= (int)((gps->points->x * sizex) + offsx);
609                         y0= (int)((gps->points->y * sizey) + offsy);
610                 }
611 #endif
612                 else {
613                         x0= (int)(gps->points->x / 100 * p->sa->winx);
614                         y0= (int)(gps->points->y / 100 * p->sa->winy);
615                 }
616                 
617                 /* do boundbox check first */
618                 if (BLI_in_rcti(rect, x0, y0)) {
619                         /* only check if point is inside */
620                         if ( ((x0-mval[0])*(x0-mval[0]) + (y0-mval[1])*(y0-mval[1])) <= rad*rad ) {
621                                 /* free stroke */
622                                 MEM_freeN(gps->points);
623                                 BLI_freelinkN(&gpf->strokes, gps);
624                         }
625                 }
626         }
627         else {  
628                 /* loop over the points in the stroke, checking for intersections 
629                  *      - an intersection will require the stroke to be split
630                  */
631                 for (i=0; (i+1) < gps->totpoints; i++) {
632                         /* get points to work with */
633                         pt1= gps->points + i;
634                         pt2= gps->points + i + 1;
635                         
636                         /* get coordinates */
637                         if (gps->flag & GP_STROKE_3DSPACE) {
638                                 project_short(p->ar, &pt1->x, xyval);
639                                 x0= xyval[0];
640                                 y0= xyval[1];
641                                 
642                                 project_short(p->ar, &pt2->x, xyval);
643                                 x1= xyval[0];
644                                 y1= xyval[1];
645                         }
646                         else if (gps->flag & GP_STROKE_2DSPACE) {
647                                 UI_view2d_view_to_region(p->v2d, pt1->x, pt1->y, &x0, &y0);
648                                 
649                                 UI_view2d_view_to_region(p->v2d, pt2->x, pt2->y, &x1, &y1);
650                         }
651 #if 0
652                         else if (gps->flag & GP_STROKE_2DIMAGE) {
653                                 int offsx, offsy, sizex, sizey;
654                                 
655                                 /* get stored settings */
656                                 sizex= p->im2d_settings.sizex;
657                                 sizey= p->im2d_settings.sizey;
658                                 offsx= p->im2d_settings.offsx;
659                                 offsy= p->im2d_settings.offsy;
660                                 
661                                 /* calculate new points */
662                                 x0= (int)((pt1->x * sizex) + offsx);
663                                 y0= (int)((pt1->y * sizey) + offsy);
664                                 
665                                 x1= (int)((pt2->x * sizex) + offsx);
666                                 y1= (int)((pt2->y * sizey) + offsy);
667                         }
668 #endif
669                         else {
670                                 x0= (int)(pt1->x / 100 * p->sa->winx);
671                                 y0= (int)(pt1->y / 100 * p->sa->winy);
672                                 x1= (int)(pt2->x / 100 * p->sa->winx);
673                                 y1= (int)(pt2->y / 100 * p->sa->winy);
674                         }
675                         
676                         /* check that point segment of the boundbox of the eraser stroke */
677                         if (BLI_in_rcti(rect, x0, y0) || BLI_in_rcti(rect, x1, y1)) {
678                                 /* check if point segment of stroke had anything to do with
679                                  * eraser region  (either within stroke painted, or on its lines)
680                                  *      - this assumes that linewidth is irrelevant
681                                  */
682                                 if (gp_stroke_eraser_strokeinside(mval, mvalo, rad, x0, y0, x1, y1)) {
683                                         /* if function returns true, break this loop (as no more point to check) */
684                                         if (gp_stroke_eraser_splitdel(gpf, gps, i))
685                                                 break;
686                                 }
687                         }
688                 }
689         }
690 }
691
692 /* erase strokes which fall under the eraser strokes */
693 static void gp_stroke_doeraser (tGPsdata *p)
694 {
695         bGPDframe *gpf= p->gpf;
696         bGPDstroke *gps, *gpn;
697         rcti rect;
698         
699         /* rect is rectangle of eraser */
700         rect.xmin= p->mval[0] - p->radius;
701         rect.ymin= p->mval[1] - p->radius;
702         rect.xmax= p->mval[0] + p->radius;
703         rect.ymax= p->mval[1] + p->radius;
704         
705         /* loop over strokes, checking segments for intersections */
706         for (gps= gpf->strokes.first; gps; gps= gpn) {
707                 gpn= gps->next;
708                 gp_stroke_eraser_dostroke(p, p->mval, p->mvalo, p->radius, &rect, gpf, gps);
709         }
710 }
711
712 /* ******************************************* */
713 /* Sketching Operator */
714
715 /* clear the session buffers (call this before AND after a paint operation) */
716 static void gp_session_validatebuffer (tGPsdata *p)
717 {
718         bGPdata *gpd= p->gpd;
719         
720         /* clear memory of buffer (or allocate it if starting a new session) */
721         if (gpd->sbuffer)
722                 memset(gpd->sbuffer, 0, sizeof(tGPspoint)*GP_STROKE_BUFFER_MAX);
723         else
724                 gpd->sbuffer= MEM_callocN(sizeof(tGPspoint)*GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
725         
726         /* reset indices */
727         gpd->sbuffer_size = 0;
728         
729         /* reset flags */
730         gpd->sbuffer_sflag= 0;
731 }
732
733 /* init new painting session */
734 static tGPsdata *gp_session_initpaint (bContext *C)
735 {
736         tGPsdata *p = NULL;
737         bGPdata **gpd_ptr = NULL;
738         ScrArea *curarea= CTX_wm_area(C);
739         ARegion *ar= CTX_wm_region(C);
740         
741         /* make sure the active view (at the starting time) is a 3d-view */
742         if (curarea == NULL) {
743                 if (G.f & G_DEBUG) 
744                         printf("Error: No active view for painting \n");
745                 return NULL;
746         }
747         
748         /* create new context data */
749         p= MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
750         
751         /* pass on current scene */
752         p->scene= CTX_data_scene(C);
753         
754         switch (curarea->spacetype) {
755                 /* supported views first */
756                 case SPACE_VIEW3D:
757                 {
758                         //View3D *v3d= curarea->spacedata.first;
759                         
760                         /* set current area 
761                          *      - must verify that region data is 3D-view (and not something else)
762                          */
763                         p->sa= curarea;
764                         p->ar= ar;
765                         
766                         if (ar->regiondata == NULL) {
767                                 p->status= GP_STATUS_ERROR;
768                                 if (G.f & G_DEBUG)
769                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable \n");
770                                 return p;
771                         }
772                         
773 #if 0 // XXX will this sort of antiquated stuff be restored?
774                         /* check that gpencil data is allowed to be drawn */
775                         if ((v3d->flag2 & V3D_DISPGP)==0) {
776                                 p->status= GP_STATUS_ERROR;
777                                 if (G.f & G_DEBUG) 
778                                         printf("Error: In active view, Grease Pencil not shown \n");
779                                 return p;
780                         }
781 #endif
782                 }
783                         break;
784 #if 0 // XXX these other spaces will come over time...
785                 case SPACE_NODE:
786                 {
787                         SpaceNode *snode= curarea->spacedata.first;
788                         
789                         /* set current area */
790                         p->sa= curarea;
791                         p->ar= ar;
792                         p->v2d= &ar->v2d;
793                         
794                         /* check that gpencil data is allowed to be drawn */
795                         if ((snode->flag & SNODE_DISPGP)==0) {
796                                 p->status= GP_STATUS_ERROR;
797                                 if (G.f & G_DEBUG) 
798                                         printf("Error: In active view, Grease Pencil not shown \n");
799                                 return;
800                         }
801                 }
802                         break;
803                 case SPACE_SEQ:
804                 {
805                         SpaceSeq *sseq= curarea->spacedata.first;
806                         
807                         /* set current area */
808                         p->sa= curarea;
809                         p->ar= ar;
810                         p->v2d= &ar->v2d;
811                         
812                         /* check that gpencil data is allowed to be drawn */
813                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
814                                 p->status= GP_STATUS_ERROR;
815                                 if (G.f & G_DEBUG) 
816                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil \n");
817                                 return;
818                         }
819                         if ((sseq->flag & SEQ_DRAW_GPENCIL)==0) {
820                                 p->status= GP_STATUS_ERROR;
821                                 if (G.f & G_DEBUG) 
822                                         printf("Error: In active view, Grease Pencil not shown \n");
823                                 return;
824                         }
825                 }
826                         break;  
827                 case SPACE_IMAGE:
828                 {
829                         SpaceImage *sima= curarea->spacedata.first;
830                         
831                         /* set the current area */
832                         p->sa= curarea;
833                         p->ar= ar;
834                         p->v2d= &ar->v2d;
835                         p->ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
836                         
837                         /* check that gpencil data is allowed to be drawn */
838                         if ((sima->flag & SI_DISPGP)==0) {
839                                 p->status= GP_STATUS_ERROR;
840                                 if (G.f & G_DEBUG)
841                                         printf("Error: In active view, Grease Pencil not shown \n");
842                                 return;
843                         }
844                 }
845                         break;
846 #endif
847                 /* unsupported views */
848                 default:
849                 {
850                         p->status= GP_STATUS_ERROR;
851                         if (G.f & G_DEBUG) 
852                                 printf("Error: Active view not appropriate for Grease Pencil drawing \n");
853                         return p;
854                 }
855                         break;
856         }
857         
858         /* get gp-data */
859         gpd_ptr= gpencil_data_get_pointers(C, NULL);
860         if (gpd_ptr == NULL) {
861                 p->status= GP_STATUS_ERROR;
862                 if (G.f & G_DEBUG)
863                         printf("Error: Current context doesn't allow for any Grease Pencil data \n");
864                 return p;
865         }
866         else {
867                 /* if no existing GPencil block exists, add one */
868                 if (*gpd_ptr == NULL)
869                         *gpd_ptr= gpencil_data_addnew("GPencil");
870                 p->gpd= *gpd_ptr;
871         }
872         
873         /* set edit flags - so that buffer will get drawn */
874         G.f |= G_GREASEPENCIL;
875         
876         /* set initial run flag */
877         p->flags |= GP_PAINTFLAG_FIRSTRUN;
878         
879         /* clear out buffer (stored in gp-data), in case something contaminated it */
880         gp_session_validatebuffer(p);
881         
882 #if 0
883         /* set 'default' im2d_settings just in case something that uses this doesn't set it */
884         p->im2d_settings.sizex= 1;
885         p->im2d_settings.sizey= 1;
886 #endif
887         
888         /* return context data for running paint operator */
889         return p;
890 }
891
892 /* cleanup after a painting session */
893 static void gp_session_cleanup (tGPsdata *p)
894 {
895         bGPdata *gpd= (p) ? p->gpd : NULL;
896         
897         /* error checking */
898         if (gpd == NULL)
899                 return;
900         
901         /* free stroke buffer */
902         if (gpd->sbuffer) {
903                 MEM_freeN(gpd->sbuffer);
904                 gpd->sbuffer= NULL;
905         }
906         
907         /* clear flags */
908         gpd->sbuffer_size= 0;
909         gpd->sbuffer_sflag= 0;
910 }
911
912 /* init new stroke */
913 static void gp_paint_initstroke (tGPsdata *p, short paintmode)
914 {       
915         /* get active layer (or add a new one if non-existent) */
916         p->gpl= gpencil_layer_getactive(p->gpd);
917         if (p->gpl == NULL)
918                 p->gpl= gpencil_layer_addnew(p->gpd);
919         if (p->gpl->flag & GP_LAYER_LOCKED) {
920                 p->status= GP_STATUS_ERROR;
921                 if (G.f & G_DEBUG)
922                         printf("Error: Cannot paint on locked layer \n");
923                 return;
924         }
925                 
926         /* get active frame (add a new one if not matching frame) */
927         p->gpf= gpencil_layer_getframe(p->gpl, p->scene->r.cfra, 1);
928         if (p->gpf == NULL) {
929                 p->status= GP_STATUS_ERROR;
930                 if (G.f & G_DEBUG) 
931                         printf("Error: No frame created (gpencil_paint_init) \n");
932                 return;
933         }
934         else
935                 p->gpf->flag |= GP_FRAME_PAINT;
936         
937         /* set 'eraser' for this stroke if using eraser */
938         p->paintmode= paintmode;
939         if (p->paintmode == GP_PAINTMODE_ERASER)
940                 p->gpd->sbuffer_sflag |= GP_STROKE_ERASER;
941         
942         /* check if points will need to be made in view-aligned space */
943         // XXX this should be the default? this is something that needs review
944         /*if (p->gpd->flag & GP_DATA_VIEWALIGN)*/ {
945                 switch (p->sa->spacetype) {
946                         case SPACE_VIEW3D:
947                         {
948                                 View3D *v3d= (View3D *)p->sa->spacedata.first;
949                                 RegionView3D *rv3d= p->ar->regiondata;
950                                 
951                                 // TODO: this should only happen for scene... otherwise apply correction for object center!
952                                 float *fp= give_cursor(p->scene, v3d);
953                                 initgrabz(rv3d, fp[0], fp[1], fp[2]);
954                                 
955                                 p->gpd->sbuffer_sflag |= GP_STROKE_3DSPACE;
956                         }
957                                 break;
958 #if 0 // XXX other spacetypes to be restored in due course
959                         case SPACE_NODE:
960                         {
961                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
962                         }
963                                 break;
964                         case SPACE_SEQ:
965                         {
966                                 SpaceSeq *sseq= (SpaceSeq *)p->sa->spacedata.first;
967                                 int rectx, recty;
968                                 float zoom, zoomx, zoomy;
969                                 
970                                 /* set draw 2d-stroke flag */
971                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DIMAGE;
972                                 
973                                 /* calculate zoom factor */
974                                 zoom= (float)(SEQ_ZOOM_FAC(sseq->zoom));
975                                 if (sseq->mainb == SEQ_DRAW_IMG_IMBUF) {
976                                         zoomx = zoom * ((float)p->scene->r.xasp / (float)p->scene->r.yasp);
977                                         zoomy = zoom;
978                                 } 
979                                 else
980                                         zoomx = zoomy = zoom;
981                                 
982                                 /* calculate rect size to use to calculate the size of the drawing area
983                                  *      - We use the size of the output image not the size of the ibuf being shown
984                                  *        as it is too messy getting the ibuf (and could be too slow). This should be
985                                  *        a reasonable for most cases anyway.
986                                  */
987                                 rectx= (p->scene->r.size * p->scene->r.xsch) / 100;
988                                 recty= (p->scene->r.size * p->scene->r.ysch) / 100; 
989                                 
990                                 /* set offset and scale values for opertations to use */
991                                 p->im2d_settings.sizex= (int)(zoomx * rectx);
992                                 p->im2d_settings.sizey= (int)(zoomy * recty);
993                                 p->im2d_settings.offsx= (int)((p->sa->winx-p->im2d_settings.sizex)/2 + sseq->xof);
994                                 p->im2d_settings.offsy= (int)((p->sa->winy-p->im2d_settings.sizey)/2 + sseq->yof);
995                         }
996                                 break;
997                         case SPACE_IMAGE:
998                         {
999                                 /* check if any ibuf available */
1000                                 if (p->ibuf)
1001                                         p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1002                         }
1003                                 break;
1004 #endif
1005                 }
1006         }
1007 }
1008
1009 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1010 static void gp_paint_strokeend (tGPsdata *p)
1011 {
1012         /* check if doing eraser or not */
1013         if ((p->gpd->sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1014                 /* smooth stroke before transferring? */
1015                 gp_stroke_smooth(p);
1016                 
1017                 /* simplify stroke before transferring? */
1018                 gp_stroke_simplify(p);
1019                 
1020                 /* transfer stroke to frame */
1021                 gp_stroke_newfrombuffer(p);
1022         }
1023         
1024         /* clean up buffer now */
1025         gp_session_validatebuffer(p);
1026 }
1027
1028 /* finish off stroke painting operation */
1029 static void gp_paint_cleanup (tGPsdata *p)
1030 {
1031         /* finish off a stroke */
1032         gp_paint_strokeend(p);
1033         
1034         /* "unlock" frame */
1035         p->gpf->flag &= ~GP_FRAME_PAINT;
1036 }
1037
1038 /* ------------------------------- */
1039
1040
1041 static int gpencil_draw_init (bContext *C, wmOperator *op)
1042 {
1043         tGPsdata *p;
1044         int paintmode= RNA_enum_get(op->ptr, "mode");
1045         
1046         /* check context */
1047         p= op->customdata= gp_session_initpaint(C);
1048         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1049                 /* something wasn't set correctly in context */
1050                 gp_session_cleanup(p);
1051                 return 0;
1052         }
1053         
1054         /* init painting data */
1055         gp_paint_initstroke(p, paintmode);
1056         if (p->status == GP_STATUS_ERROR) {
1057                 gp_session_cleanup(p);
1058                 return 0;
1059         }
1060         
1061         /* radius for eraser circle is defined in userprefs now */
1062         p->radius= U.gp_eraser;
1063         
1064         /* everything is now setup ok */
1065         return 1;
1066 }
1067
1068 /* ------------------------------- */
1069
1070 static void gpencil_draw_exit (bContext *C, wmOperator *op)
1071 {
1072         tGPsdata *p= op->customdata;
1073         
1074         /* clear edit flags */
1075         G.f &= ~G_GREASEPENCIL;
1076         
1077         /* restore cursor to indicate end of drawing */
1078         WM_cursor_restore(CTX_wm_window(C));
1079         
1080         /* check size of buffer before cleanup, to determine if anything happened here */
1081         if (p->paintmode == GP_PAINTMODE_ERASER) {
1082                 // TODO clear radial cursor thing
1083                 // XXX draw_sel_circle(NULL, p.mvalo, 0, p.radius, 0);
1084         }
1085         
1086         /* cleanup */
1087         gp_paint_cleanup(p);
1088         gp_session_cleanup(p);
1089         
1090         /* finally, free the temp data */
1091         MEM_freeN(p);
1092         op->customdata= NULL;
1093 }
1094
1095 static int gpencil_draw_cancel (bContext *C, wmOperator *op)
1096 {
1097         /* this is just a wrapper around exit() */
1098         gpencil_draw_exit(C, op);
1099         return OPERATOR_CANCELLED;
1100 }
1101
1102 /* ------------------------------- */
1103
1104 /* create a new stroke point at the point indicated by the painting context */
1105 static void gpencil_draw_apply (bContext *C, wmOperator *op, tGPsdata *p)
1106 {
1107         /* handle drawing/erasing -> test for erasing first */
1108         if (p->paintmode == GP_PAINTMODE_ERASER) {
1109                 /* do 'live' erasing now */
1110                 gp_stroke_doeraser(p);
1111                 
1112                 /* store used values */
1113                 p->mvalo[0]= p->mval[0];
1114                 p->mvalo[1]= p->mval[1];
1115                 p->opressure= p->pressure;
1116         }
1117         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
1118         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
1119                 /* try to add point */
1120                 short ok= gp_stroke_addpoint(p, p->mval, p->pressure);
1121                 
1122                 /* handle errors while adding point */
1123                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
1124                         /* finish off old stroke */
1125                         gp_paint_strokeend(p);
1126                         
1127                         /* start a new stroke, starting from previous point */
1128                         gp_stroke_addpoint(p, p->mvalo, p->opressure);
1129                         ok= gp_stroke_addpoint(p, p->mval, p->pressure);
1130                 }
1131                 else if (ok == GP_STROKEADD_INVALID) {
1132                         /* the painting operation cannot continue... */
1133                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
1134                         p->status = GP_STATUS_ERROR;
1135                         
1136                         if (G.f & G_DEBUG) 
1137                                 printf("Error: Grease-Pencil Paint - Add Point Invalid \n");
1138                         // XXX break!
1139                 }
1140                 
1141                 /* store used values */
1142                 p->mvalo[0]= p->mval[0];
1143                 p->mvalo[1]= p->mval[1];
1144                 p->opressure= p->pressure;
1145         }
1146 }
1147
1148 /* handle draw event */
1149 static void gpencil_draw_apply_event (bContext *C, wmOperator *op, wmEvent *event)
1150 {
1151         tGPsdata *p= op->customdata;
1152         ARegion *ar= p->ar;
1153         //PointerRNA itemptr;
1154         //float mousef[2];
1155         int tablet=0;
1156
1157         /* convert from window-space to area-space mouse coordintes */
1158         // NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
1159         p->mval[0]= event->x - ar->winrct.xmin + 1;
1160         p->mval[1]= event->y - ar->winrct.ymin + 1;
1161         
1162         /* handle pressure sensitivity (which is supplied by tablets) */
1163         if (event->custom == EVT_DATA_TABLET) {
1164                 wmTabletData *wmtab= event->customdata;
1165                 
1166                 tablet= (wmtab->Active != EVT_TABLET_NONE);
1167                 p->pressure= wmtab->Pressure;
1168                 //if (wmtab->Active == EVT_TABLET_ERASER)
1169                         // TODO... this should get caught by the keymaps which call drawing in the first place
1170         }
1171         else
1172                 p->pressure= 1.0f;
1173         
1174         /* special exception for start of strokes (i.e. maybe for just a dot) */
1175         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1176                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1177                 
1178                 p->mvalo[0]= p->mval[0];
1179                 p->mvalo[1]= p->mval[1];
1180                 p->opressure= p->pressure;
1181                 
1182                 /* special exception here for too high pressure values on first touch in
1183                  *  windows for some tablets, then we just skip first touch ..  
1184                  */
1185                 if (tablet && (p->pressure >= 0.99f))
1186                         return;
1187         }
1188         
1189 #if 0 // NOTE: disabled for now, since creating this data is currently useless anyways (and slows things down)
1190         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
1191         RNA_collection_add(op->ptr, "stroke", &itemptr);
1192
1193         mousef[0]= p->mval[0];
1194         mousef[1]= p->mval[1];
1195         RNA_float_set_array(&itemptr, "mouse", mousef);
1196         RNA_float_set(&itemptr, "pressure", p->pressure);
1197 #endif 
1198         
1199         /* apply the current latest drawing point */
1200         gpencil_draw_apply(C, op, p);
1201         
1202         /* force refresh */
1203         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1204 }
1205
1206 /* ------------------------------- */
1207
1208 /* operator 'redo' (i.e. after changing some properties) */
1209 static int gpencil_draw_exec (bContext *C, wmOperator *op)
1210 {
1211         tGPsdata *p = NULL;
1212         
1213         printf("GPencil - Starting Re-Drawing \n");
1214         
1215         /* try to initialise context data needed while drawing */
1216         if (!gpencil_draw_init(C, op)) {
1217                 if (op->customdata) MEM_freeN(op->customdata);
1218                 printf("\tGP - no valid data \n");
1219                 return OPERATOR_CANCELLED;
1220         }
1221         else
1222                 p= op->customdata;
1223         
1224         printf("\tGP - Start redrawing stroke \n");
1225         
1226         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
1227          * setting the relevant values in context at each step, then applying
1228          */
1229         RNA_BEGIN(op->ptr, itemptr, "stroke") 
1230         {
1231                 float mousef[2];
1232                 
1233                 printf("\t\tGP - stroke elem \n");
1234                 
1235                 /* get relevant data for this point from stroke */
1236                 RNA_float_get_array(&itemptr, "mouse", mousef);
1237                 p->mval[0] = (short)mousef[0];
1238                 p->mval[1] = (short)mousef[1];
1239                 p->pressure= RNA_float_get(&itemptr, "pressure");
1240                 
1241                 /* if first run, set previous data too */
1242                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1243                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1244                         
1245                         p->mvalo[0]= p->mval[0];
1246                         p->mvalo[1]= p->mval[1];
1247                         p->opressure= p->pressure;
1248                 }
1249                 
1250                 /* apply this data as necessary now (as per usual) */
1251                 gpencil_draw_apply(C, op, p);
1252         }
1253         RNA_END;
1254         
1255         printf("\tGP - done \n");
1256         
1257         /* cleanup */
1258         gpencil_draw_exit(C, op);
1259         
1260         /* refreshes */
1261         WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL); // XXX need a nicer one that will work  
1262         
1263         /* done */
1264         return OPERATOR_FINISHED;
1265 }
1266
1267 /* ------------------------------- */
1268
1269 /* start of interactive drawing part of operator */
1270 static int gpencil_draw_invoke (bContext *C, wmOperator *op, wmEvent *event)
1271 {
1272         tGPsdata *p = NULL;
1273         wmWindow *win= CTX_wm_window(C);
1274         
1275         printf("GPencil - Starting Drawing \n");
1276         
1277         /* try to initialise context data needed while drawing */
1278         if (!gpencil_draw_init(C, op)) {
1279                 if (op->customdata) MEM_freeN(op->customdata);
1280                 printf("\tGP - no valid data \n");
1281                 return OPERATOR_CANCELLED;
1282         }
1283         else
1284                 p= op->customdata;
1285         
1286         // TODO: set any additional settings that we can take from the events?
1287         // TODO? if tablet is erasing, force eraser to be on?
1288         
1289         /* if eraser is on, draw radial aid */
1290         if (p->paintmode == GP_PAINTMODE_ERASER) {
1291                 // TODO: this involves mucking around with radial control, so we leave this for now..
1292         }
1293         
1294         /* set cursor */
1295         if (p->paintmode == GP_PAINTMODE_ERASER)
1296                 WM_cursor_modal(win, BC_CROSSCURSOR); // XXX need a better cursor
1297         else
1298                 WM_cursor_modal(win, BC_PAINTBRUSHCURSOR);
1299         
1300         /* special hack: if there was an initial event, then we were invoked via a hotkey, and 
1301          * painting should start immediately. Otherwise, this was called from a toolbar, in which
1302          * case we should wait for the mouse to be clicked.
1303          */
1304         if (event->type) {
1305                 /* hotkey invoked - start drawing */
1306                 printf("\tGP - set first spot\n");
1307                 p->status= GP_STATUS_PAINTING;
1308                 
1309                 /* handle the initial drawing - i.e. for just doing a simple dot */
1310                 gpencil_draw_apply_event(C, op, event);
1311         }
1312         else {
1313                 /* toolbar invoked - don't start drawing yet... */
1314                 printf("\tGP - hotkey invoked... waiting for click-drag\n");
1315         }
1316         
1317         /* add a modal handler for this operator, so that we can then draw continuous strokes */
1318         WM_event_add_modal_handler(C, &CTX_wm_window(C)->handlers, op);
1319         return OPERATOR_RUNNING_MODAL;
1320 }
1321
1322 /* events handling during interactive drawing part of operator */
1323 static int gpencil_draw_modal (bContext *C, wmOperator *op, wmEvent *event)
1324 {
1325         tGPsdata *p= op->customdata;
1326         
1327         printf("\tGP - handle modal event...\n");
1328         
1329         switch (event->type) {
1330                 /* end of stroke -> ONLY when a mouse-button release occurs 
1331                  * otherwise, carry on to mouse-move...
1332                  */
1333                 case LEFTMOUSE:
1334                 case RIGHTMOUSE: 
1335                         /* if painting, end stroke */
1336                         if (p->status == GP_STATUS_PAINTING) {
1337                                 /* basically, this should be mouse-button up */
1338                                 printf("\t\tGP - end of stroke \n");
1339                                 gpencil_draw_exit(C, op);
1340                                 
1341                                 /* one last flush before we're done */
1342                                 WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL); // XXX need a nicer one that will work  
1343                                 
1344                                 return OPERATOR_FINISHED;
1345                         }
1346                         else {
1347                                 /* not painting, so start stroke (this should be mouse-button down) */
1348                                 printf("\t\tGP - start stroke \n");
1349                                 p->status= GP_STATUS_PAINTING;
1350                                 /* no break now, since we should immediately start painting */
1351                         }
1352                 
1353                 /* moving mouse - assumed that mouse button is down if in painting status */
1354                 case MOUSEMOVE:
1355                         /* check if we're currently painting */
1356                         if (p->status == GP_STATUS_PAINTING) {
1357                                 /* handle drawing event */
1358                                 printf("\t\tGP - add point\n");
1359                                 gpencil_draw_apply_event(C, op, event);
1360                                 
1361                                 /* finish painting operation if anything went wrong just now */
1362                                 if (p->status == GP_STATUS_ERROR) {
1363                                         printf("\t\t\tGP - error done! \n");
1364                                         gpencil_draw_exit(C, op);
1365                                         return OPERATOR_CANCELLED;
1366                                 }
1367                         }
1368                         break;
1369                 
1370                 /* scrolling mouse-wheel increases radius of eraser 
1371                  *      - though this is quite a difficult action to perform
1372                  */
1373                 // XXX this stuff doesn't work
1374                 case WHEELUPMOUSE:
1375                         p->radius += 1.5f;
1376                         break;
1377                 case WHEELDOWNMOUSE:
1378                         p->radius -= 1.5f;
1379                         break;
1380                 
1381                 default:
1382                         printf("\t\tGP unknown event - %d \n", event->type);
1383                         break;
1384         }
1385         
1386         return OPERATOR_RUNNING_MODAL;
1387 }
1388
1389 /* ------------------------------- */
1390
1391 static EnumPropertyItem prop_gpencil_drawmodes[] = {
1392         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", ""},
1393         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", ""},
1394         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", ""},
1395         {0, NULL, 0, NULL, NULL}
1396 };
1397
1398 void GPENCIL_OT_draw (wmOperatorType *ot)
1399 {
1400         /* identifiers */
1401         ot->name= "Grease Pencil Draw";
1402         ot->idname= "GPENCIL_OT_draw";
1403         ot->description= "Make annotations on the active data.";
1404         
1405         /* api callbacks */
1406         ot->exec= gpencil_draw_exec;
1407         ot->invoke= gpencil_draw_invoke;
1408         ot->modal= gpencil_draw_modal;
1409         ot->cancel= gpencil_draw_cancel;
1410         ot->poll= gpencil_draw_poll;
1411         
1412         /* flags */
1413         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1414         
1415         /* settings for drawing */
1416         RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to intepret mouse movements.");
1417                 // xxx the stuff below is used only for redo operator, but is not really working
1418         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1419 }