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