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