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