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