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