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