4 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
20 * The Original Code is Copyright (C) 2008, Blender Foundation, Joshua Leung
21 * This is a new part of Blender
23 * Contributor(s): Joshua Leung
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/editors/gpencil/gpencil_paint.c
39 #include "MEM_guardedalloc.h"
41 #include "BLI_blenlib.h"
43 #include "BLI_utildefines.h"
45 #include "BKE_gpencil.h"
46 #include "BKE_context.h"
47 #include "BKE_global.h"
48 #include "BKE_report.h"
50 #include "DNA_object_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_gpencil_types.h"
53 #include "DNA_windowmanager_types.h"
55 #include "UI_view2d.h"
57 #include "ED_gpencil.h"
58 #include "ED_screen.h"
59 #include "ED_view3d.h"
61 #include "RNA_access.h"
63 #include "RNA_define.h"
67 #include "gpencil_intern.h"
69 /* ******************************************* */
70 /* 'Globals' and Defines */
72 /* Temporary 'Stroke' Operation data */
73 typedef struct tGPsdata {
74 Scene *scene; /* current scene from context */
76 wmWindow *win; /* window where painting originated */
77 ScrArea *sa; /* area where painting originated */
78 ARegion *ar; /* region where painting originated */
79 View2D *v2d; /* needed for GP_STROKE_2DSPACE */
80 rctf *subrect; /* for using the camera rect within the 3d view */
84 #if 0 // XXX review this 2d image stuff...
85 ImBuf *ibuf; /* needed for GP_STROKE_2DIMAGE */
86 struct IBufViewSettings {
87 int offsx, offsy; /* offsets */
88 int sizex, sizey; /* dimensions to use as scale-factor */
89 } im2d_settings; /* needed for GP_STROKE_2DIMAGE */
92 PointerRNA ownerPtr;/* pointer to owner of gp-datablock */
93 bGPdata *gpd; /* gp-datablock layer comes from */
94 bGPDlayer *gpl; /* layer we're working on */
95 bGPDframe *gpf; /* frame we're working on */
97 short status; /* current status of painting */
98 short paintmode; /* mode for painting */
100 int mval[2]; /* current mouse-position */
101 int mvalo[2]; /* previous recorded mouse-position */
103 float pressure; /* current stylus pressure */
104 float opressure; /* previous stylus pressure */
106 short radius; /* radius of influence for eraser */
107 short flags; /* flags that can get set during runtime */
110 /* values for tGPsdata->status */
112 GP_STATUS_IDLING = 0, /* stroke isn't in progress yet */
113 GP_STATUS_PAINTING, /* a stroke is in progress */
114 GP_STATUS_ERROR, /* something wasn't correctly set up */
115 GP_STATUS_DONE /* painting done */
118 /* Return flags for adding points to stroke buffer */
120 GP_STROKEADD_INVALID = -2, /* error occurred - insufficient info to do so */
121 GP_STROKEADD_OVERFLOW = -1, /* error occurred - cannot fit any more points */
122 GP_STROKEADD_NORMAL, /* point was successfully added */
123 GP_STROKEADD_FULL /* cannot add any more points to buffer */
128 GP_PAINTFLAG_FIRSTRUN = (1<<0), /* operator just started */
133 /* maximum sizes of gp-session buffer */
134 #define GP_STROKE_BUFFER_MAX 5000
136 /* Macros for accessing sensitivity thresholds... */
137 /* minimum number of pixels mouse should move before new point created */
138 #define MIN_MANHATTEN_PX (U.gp_manhattendist)
139 /* minimum length of new segment before new point can be added */
140 #define MIN_EUCLIDEAN_PX (U.gp_euclideandist)
143 /* Forward defines for some functions... */
145 static void gp_session_validatebuffer(tGPsdata *p);
147 /* ******************************************* */
148 /* Context Wrangling... */
150 /* check if context is suitable for drawing */
151 static int gpencil_draw_poll (bContext *C)
153 if (ED_operator_regionactive(C)) {
154 /* check if current context can support GPencil data */
155 if (gpencil_data_get_pointers(C, NULL) != NULL) {
156 /* check if Grease Pencil isn't already running */
157 if ((G.f & G_GREASEPENCIL) == 0)
160 CTX_wm_operator_poll_msg_set(C, "Grease Pencil operator is already active");
163 CTX_wm_operator_poll_msg_set(C, "Failed to find Grease Pencil data to draw into");
167 CTX_wm_operator_poll_msg_set(C, "Active region not set");
173 /* check if projecting strokes into 3d-geometry in the 3D-View */
174 static int gpencil_project_check (tGPsdata *p)
176 bGPdata *gpd= p->gpd;
177 return ((gpd->sbuffer_sflag & GP_STROKE_3DSPACE) && (p->gpd->flag & (GP_DATA_DEPTH_VIEW | GP_DATA_DEPTH_STROKE)));
180 /* ******************************************* */
181 /* Calculations/Conversions */
183 /* Utilities --------------------------------- */
185 /* get the reference point for stroke-point conversions */
186 static void gp_get_3d_reference (tGPsdata *p, float *vec)
188 View3D *v3d= p->sa->spacedata.first;
189 float *fp= give_cursor(p->scene, v3d);
191 /* the reference point used depends on the owner... */
192 #if 0 // XXX: disabled for now, since we can't draw relative to the owner yet
193 if (p->ownerPtr.type == &RNA_Object)
195 Object *ob= (Object *)p->ownerPtr.data;
198 * - use relative distance of 3D-cursor from object center
200 sub_v3_v3v3(vec, fp, ob->loc);
210 /* Stroke Editing ---------------------------- */
212 /* check if the current mouse position is suitable for adding a new point */
213 static short gp_stroke_filtermval (tGPsdata *p, int mval[2], int pmval[2])
215 int dx= abs(mval[0] - pmval[0]);
216 int dy= abs(mval[1] - pmval[1]);
218 /* if buffer is empty, just let this go through (i.e. so that dots will work) */
219 if (p->gpd->sbuffer_size == 0)
222 /* check if mouse moved at least certain distance on both axes (best case)
223 * - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
225 else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
228 /* check if the distance since the last point is significant enough
229 * - prevents points being added too densely
230 * - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
232 else if ((dx*dx + dy*dy) > MIN_EUCLIDEAN_PX*MIN_EUCLIDEAN_PX)
235 /* mouse 'didn't move' */
240 /* convert screen-coordinates to buffer-coordinates */
241 // XXX this method needs a total overhaul!
242 static void gp_stroke_convertcoords (tGPsdata *p, short mval[2], float out[3], float *depth)
244 bGPdata *gpd= p->gpd;
246 /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
247 if (gpd->sbuffer_sflag & GP_STROKE_3DSPACE) {
248 if (gpencil_project_check(p) && (view_autodist_simple(p->ar, mval, out, 0, depth))) {
249 /* projecting onto 3D-Geometry
250 * - nothing more needs to be done here, since view_autodist_simple() has already done it
254 const short mx=mval[0], my=mval[1];
255 float rvec[3], dvec[3];
257 /* Current method just converts each point in screen-coordinates to
258 * 3D-coordinates using the 3D-cursor as reference. In general, this
259 * works OK, but it could of course be improved.
262 * - investigate using nearest point(s) on a previous stroke as
263 * reference point instead or as offset, for easier stroke matching
266 gp_get_3d_reference(p, rvec);
268 /* method taken from editview.c - mouse_cursor() */
269 project_short_noclip(p->ar, rvec, mval);
270 window_to_3d_delta(p->ar, dvec, mval[0]-mx, mval[1]-my);
271 sub_v3_v3v3(out, rvec, dvec);
275 /* 2d - on 'canvas' (assume that p->v2d is set) */
276 else if ((gpd->sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
279 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &x, &y);
286 /* 2d - on image 'canvas' (assume that p->v2d is set) */
287 else if (gpd->sbuffer_sflag & GP_STROKE_2DIMAGE) {
288 int sizex, sizey, offsx, offsy;
290 /* get stored settings
291 * - assume that these have been set already (there are checks that set sane 'defaults' just in case)
293 sizex= p->im2d_settings.sizex;
294 sizey= p->im2d_settings.sizey;
295 offsx= p->im2d_settings.offsx;
296 offsy= p->im2d_settings.offsy;
298 /* calculate new points */
299 out[0]= (float)(mval[0] - offsx) / (float)sizex;
300 out[1]= (float)(mval[1] - offsy) / (float)sizey;
304 /* 2d - relative to screen (viewport area) */
306 if (p->subrect == NULL) { /* normal 3D view */
307 out[0] = (float)(mval[0]) / (float)(p->ar->winx) * 100;
308 out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
310 else { /* camera view, use subrect */
311 out[0]= ((mval[0] - p->subrect->xmin) / ((p->subrect->xmax - p->subrect->xmin))) * 100;
312 out[1]= ((mval[1] - p->subrect->ymin) / ((p->subrect->ymax - p->subrect->ymin))) * 100;
317 /* add current stroke-point to buffer (returns whether point was successfully added) */
318 static short gp_stroke_addpoint (tGPsdata *p, int mval[2], float pressure)
320 bGPdata *gpd= p->gpd;
323 /* check painting mode */
324 if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
325 /* straight lines only - i.e. only store start and end point in buffer */
326 if (gpd->sbuffer_size == 0) {
327 /* first point in buffer (start point) */
328 pt= (tGPspoint *)(gpd->sbuffer);
333 pt->pressure= pressure;
335 /* increment buffer size */
339 /* normally, we just reset the endpoint to the latest value
340 * - assume that pointers for this are always valid...
342 pt= ((tGPspoint *)(gpd->sbuffer) + 1);
347 pt->pressure= pressure;
349 /* if this is just the second point we've added, increment the buffer size
350 * so that it will be drawn properly...
351 * otherwise, just leave it alone, otherwise we get problems
353 if (gpd->sbuffer_size != 2)
354 gpd->sbuffer_size= 2;
357 /* can keep carrying on this way :) */
358 return GP_STROKEADD_NORMAL;
360 else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
361 /* check if still room in buffer */
362 if (gpd->sbuffer_size >= GP_STROKE_BUFFER_MAX)
363 return GP_STROKEADD_OVERFLOW;
365 /* get pointer to destination point */
366 pt= ((tGPspoint *)(gpd->sbuffer) + gpd->sbuffer_size);
371 pt->pressure= pressure;
373 /* increment counters */
376 /* check if another operation can still occur */
377 if (gpd->sbuffer_size == GP_STROKE_BUFFER_MAX)
378 return GP_STROKEADD_FULL;
380 return GP_STROKEADD_NORMAL;
383 /* return invalid state for now... */
384 return GP_STROKEADD_INVALID;
388 /* temp struct for gp_stroke_smooth() */
389 typedef struct tGpSmoothCo {
394 /* smooth a stroke (in buffer) before storing it */
395 static void gp_stroke_smooth (tGPsdata *p)
397 bGPdata *gpd= p->gpd;
398 tGpSmoothCo *smoothArray, *spc;
399 int i=0, cmx=gpd->sbuffer_size;
401 /* only smooth if smoothing is enabled, and we're not doing a straight line */
402 if (!(U.gp_settings & GP_PAINT_DOSMOOTH) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
405 /* don't try if less than 2 points in buffer */
406 if ((cmx <= 2) || (gpd->sbuffer == NULL))
409 /* create a temporary smoothing coordinates buffer, use to store calculated values to prevent sequential error */
410 smoothArray = MEM_callocN(sizeof(tGpSmoothCo)*cmx, "gp_stroke_smooth smoothArray");
412 /* first pass: calculate smoothing coordinates using weighted-averages */
413 for (i=0, spc=smoothArray; i < gpd->sbuffer_size; i++, spc++) {
414 const tGPspoint *pc= (((tGPspoint *)gpd->sbuffer) + i);
415 const tGPspoint *pb= (i-1 > 0)?(pc-1):(pc);
416 const tGPspoint *pa= (i-2 > 0)?(pc-2):(pb);
417 const tGPspoint *pd= (i+1 < cmx)?(pc+1):(pc);
418 const tGPspoint *pe= (i+2 < cmx)?(pc+2):(pd);
420 spc->x= (short)(0.1*pa->x + 0.2*pb->x + 0.4*pc->x + 0.2*pd->x + 0.1*pe->x);
421 spc->y= (short)(0.1*pa->y + 0.2*pb->y + 0.4*pc->y + 0.2*pd->y + 0.1*pe->y);
424 /* second pass: apply smoothed coordinates */
425 for (i=0, spc=smoothArray; i < gpd->sbuffer_size; i++, spc++) {
426 tGPspoint *pc= (((tGPspoint *)gpd->sbuffer) + i);
432 /* free temp array */
433 MEM_freeN(smoothArray);
436 /* simplify a stroke (in buffer) before storing it
437 * - applies a reverse Chaikin filter
438 * - code adapted from etch-a-ton branch (editarmature_sketch.c)
440 static void gp_stroke_simplify (tGPsdata *p)
442 bGPdata *gpd= p->gpd;
443 tGPspoint *old_points= (tGPspoint *)gpd->sbuffer;
444 short num_points= gpd->sbuffer_size;
445 short flag= gpd->sbuffer_sflag;
448 /* only simplify if simplification is enabled, and we're not doing a straight line */
449 if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
452 /* don't simplify if less than 4 points in buffer */
453 if ((num_points <= 4) || (old_points == NULL))
456 /* clear buffer (but don't free mem yet) so that we can write to it
457 * - firstly set sbuffer to NULL, so a new one is allocated
458 * - secondly, reset flag after, as it gets cleared auto
461 gp_session_validatebuffer(p);
462 gpd->sbuffer_sflag = flag;
464 /* macro used in loop to get position of new point
465 * - used due to the mixture of datatypes in use here
467 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
469 co[0] += (float)(old_points[offs].x * sfac); \
470 co[1] += (float)(old_points[offs].y * sfac); \
471 pressure += old_points[offs].pressure * sfac; \
474 for (i = 0, j = 0; i < num_points; i++)
478 float co[2], pressure;
481 /* initialise values */
486 /* using macro, calculate new point */
487 GP_SIMPLIFY_AVPOINT(j, -0.25f);
488 GP_SIMPLIFY_AVPOINT(j+1, 0.75f);
489 GP_SIMPLIFY_AVPOINT(j+2, 0.75f);
490 GP_SIMPLIFY_AVPOINT(j+3, -0.25f);
492 /* set values for adding */
496 /* ignore return values on this... assume to be ok for now */
497 gp_stroke_addpoint(p, mco, pressure);
503 /* free old buffer */
504 MEM_freeN(old_points);
508 /* make a new stroke from the buffer data */
509 static void gp_stroke_newfrombuffer (tGPsdata *p)
511 bGPdata *gpd= p->gpd;
516 /* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
517 int depth_margin = (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 4 : 0;
519 /* get total number of points to allocate space for
520 * - drawing straight-lines only requires the endpoints
522 if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
523 totelem = (gpd->sbuffer_size >= 2) ? 2: gpd->sbuffer_size;
525 totelem = gpd->sbuffer_size;
527 /* exit with error if no valid points from this stroke */
530 printf("Error: No valid points in stroke buffer to convert (tot=%d) \n", gpd->sbuffer_size);
534 /* allocate memory for a new stroke */
535 gps= MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
537 /* allocate enough memory for a continuous array for storage points */
538 pt= gps->points= MEM_callocN(sizeof(bGPDspoint)*totelem, "gp_stroke_points");
540 /* copy appropriate settings for stroke */
541 gps->totpoints= totelem;
542 gps->thickness= p->gpl->thickness;
543 gps->flag= gpd->sbuffer_sflag;
545 /* copy points from the buffer to the stroke */
546 if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
547 /* straight lines only -> only endpoints */
552 /* convert screen-coordinates to appropriate coordinates (and store them) */
553 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
556 pt->pressure= ptc->pressure;
562 /* last point if applicable */
563 ptc= ((tGPspoint *)gpd->sbuffer) + (gpd->sbuffer_size - 1);
565 /* convert screen-coordinates to appropriate coordinates (and store them) */
566 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
569 pt->pressure= ptc->pressure;
573 float *depth_arr= NULL;
575 /* get an array of depths, far depths are blended */
576 if (gpencil_project_check(p)) {
577 short mval[2], mval_prev[2]= {0};
578 int interp_depth = 0;
581 depth_arr= MEM_mallocN(sizeof(float) * gpd->sbuffer_size, "depth_points");
583 for (i=0, ptc=gpd->sbuffer; i < gpd->sbuffer_size; i++, ptc++, pt++) {
584 mval[0]= ptc->x; mval[1]= ptc->y;
586 if ((view_autodist_depth(p->ar, mval, depth_margin, depth_arr+i) == 0) &&
587 (i && (view_autodist_depth_segment(p->ar, mval, mval_prev, depth_margin + 1, depth_arr+i) == 0))
595 VECCOPY2D(mval_prev, mval);
598 if (found_depth == FALSE) {
599 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
600 for (i=gpd->sbuffer_size-1; i >= 0; i--)
601 depth_arr[i] = 0.9999f;
604 if (p->gpd->flag & GP_DATA_DEPTH_STROKE_ENDPOINTS) {
605 /* remove all info between the valid endpoints */
609 for (i=0; i < gpd->sbuffer_size; i++) {
610 if (depth_arr[i] != FLT_MAX)
615 for (i=gpd->sbuffer_size-1; i >= 0; i--) {
616 if (depth_arr[i] != FLT_MAX)
621 /* invalidate non-endpoints, so only blend between first and last */
622 for (i=first_valid+1; i < last_valid; i++)
623 depth_arr[i]= FLT_MAX;
629 interp_sparse_array(depth_arr, gpd->sbuffer_size, FLT_MAX);
637 /* convert all points (normal behaviour) */
638 for (i=0, ptc=gpd->sbuffer; i < gpd->sbuffer_size && ptc; i++, ptc++, pt++) {
639 /* convert screen-coordinates to appropriate coordinates (and store them) */
640 gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr+i:NULL);
643 pt->pressure= ptc->pressure;
647 MEM_freeN(depth_arr);
650 /* add stroke to frame */
651 BLI_addtail(&p->gpf->strokes, gps);
654 /* --- 'Eraser' for 'Paint' Tool ------ */
656 /* eraser tool - remove segment from stroke/split stroke (after lasso inside) */
657 static short gp_stroke_eraser_splitdel (bGPDframe *gpf, bGPDstroke *gps, int i)
659 bGPDspoint *pt_tmp= gps->points;
660 bGPDstroke *gsn = NULL;
662 /* if stroke only had two points, get rid of stroke */
663 if (gps->totpoints == 2) {
664 /* free stroke points, then stroke */
666 BLI_freelinkN(&gpf->strokes, gps);
668 /* nothing left in stroke, so stop */
672 /* if last segment, just remove segment from the stroke */
673 else if (i == gps->totpoints - 2) {
674 /* allocate new points array, and assign most of the old stroke there */
676 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
677 memcpy(gps->points, pt_tmp, sizeof(bGPDspoint)*gps->totpoints);
679 /* free temp buffer */
682 /* nothing left in stroke, so stop */
686 /* if first segment, just remove segment from the stroke */
688 /* allocate new points array, and assign most of the old stroke there */
690 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
691 memcpy(gps->points, pt_tmp + 1, sizeof(bGPDspoint)*gps->totpoints);
693 /* free temp buffer */
696 /* no break here, as there might still be stuff to remove in this stroke */
700 /* segment occurs in 'middle' of stroke, so split */
702 /* duplicate stroke, and assign 'later' data to that stroke */
703 gsn= MEM_dupallocN(gps);
704 gsn->prev= gsn->next= NULL;
705 BLI_insertlinkafter(&gpf->strokes, gps, gsn);
707 gsn->totpoints= gps->totpoints - i;
708 gsn->points= MEM_callocN(sizeof(bGPDspoint)*gsn->totpoints, "gp_stroke_points");
709 memcpy(gsn->points, pt_tmp + i, sizeof(bGPDspoint)*gsn->totpoints);
711 /* adjust existing stroke */
713 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
714 memcpy(gps->points, pt_tmp, sizeof(bGPDspoint)*i);
716 /* free temp buffer */
719 /* nothing left in stroke, so stop */
724 /* eraser tool - check if part of stroke occurs within last segment drawn by eraser */
725 static short gp_stroke_eraser_strokeinside (int mval[], int UNUSED(mvalo[]), short rad, short x0, short y0, short x1, short y1)
727 /* simple within-radius check for now */
728 if (edge_inside_circle(mval[0], mval[1], rad, x0, y0, x1, y1))
735 /* eraser tool - evaluation per stroke */
736 // TODO: this could really do with some optimisation (KD-Tree/BVH?)
737 static void gp_stroke_eraser_dostroke (tGPsdata *p, int mval[], int mvalo[], short rad, rcti *rect, bGPDframe *gpf, bGPDstroke *gps)
739 bGPDspoint *pt1, *pt2;
740 int x0=0, y0=0, x1=0, y1=0;
744 if (gps->totpoints == 0) {
745 /* just free stroke */
747 MEM_freeN(gps->points);
748 BLI_freelinkN(&gpf->strokes, gps);
750 else if (gps->totpoints == 1) {
751 /* get coordinates */
752 if (gps->flag & GP_STROKE_3DSPACE) {
753 project_short(p->ar, &gps->points->x, xyval);
757 else if (gps->flag & GP_STROKE_2DSPACE) {
758 UI_view2d_view_to_region(p->v2d, gps->points->x, gps->points->y, &x0, &y0);
761 else if (gps->flag & GP_STROKE_2DIMAGE) {
762 int offsx, offsy, sizex, sizey;
764 /* get stored settings */
765 sizex= p->im2d_settings.sizex;
766 sizey= p->im2d_settings.sizey;
767 offsx= p->im2d_settings.offsx;
768 offsy= p->im2d_settings.offsy;
770 /* calculate new points */
771 x0= (int)((gps->points->x * sizex) + offsx);
772 y0= (int)((gps->points->y * sizey) + offsy);
776 if (p->subrect == NULL) { /* normal 3D view */
777 x0= (int)(gps->points->x / 100 * p->ar->winx);
778 y0= (int)(gps->points->y / 100 * p->ar->winy);
780 else { /* camera view, use subrect */
781 x0= (int)((gps->points->x / 100) * (p->subrect->xmax - p->subrect->xmin)) + p->subrect->xmin;
782 y0= (int)((gps->points->y / 100) * (p->subrect->ymax - p->subrect->ymin)) + p->subrect->ymin;
786 /* do boundbox check first */
787 if (BLI_in_rcti(rect, x0, y0)) {
788 /* only check if point is inside */
789 if ( ((x0-mval[0])*(x0-mval[0]) + (y0-mval[1])*(y0-mval[1])) <= rad*rad ) {
791 MEM_freeN(gps->points);
792 BLI_freelinkN(&gpf->strokes, gps);
797 /* loop over the points in the stroke, checking for intersections
798 * - an intersection will require the stroke to be split
800 for (i=0; (i+1) < gps->totpoints; i++) {
801 /* get points to work with */
802 pt1= gps->points + i;
803 pt2= gps->points + i + 1;
805 /* get coordinates */
806 if (gps->flag & GP_STROKE_3DSPACE) {
807 project_short(p->ar, &pt1->x, xyval);
811 project_short(p->ar, &pt2->x, xyval);
815 else if (gps->flag & GP_STROKE_2DSPACE) {
816 UI_view2d_view_to_region(p->v2d, pt1->x, pt1->y, &x0, &y0);
818 UI_view2d_view_to_region(p->v2d, pt2->x, pt2->y, &x1, &y1);
821 else if (gps->flag & GP_STROKE_2DIMAGE) {
822 int offsx, offsy, sizex, sizey;
824 /* get stored settings */
825 sizex= p->im2d_settings.sizex;
826 sizey= p->im2d_settings.sizey;
827 offsx= p->im2d_settings.offsx;
828 offsy= p->im2d_settings.offsy;
830 /* calculate new points */
831 x0= (int)((pt1->x * sizex) + offsx);
832 y0= (int)((pt1->y * sizey) + offsy);
834 x1= (int)((pt2->x * sizex) + offsx);
835 y1= (int)((pt2->y * sizey) + offsy);
839 if(p->subrect == NULL) { /* normal 3D view */
840 x0= (int)(pt1->x / 100 * p->ar->winx);
841 y0= (int)(pt1->y / 100 * p->ar->winy);
842 x1= (int)(pt2->x / 100 * p->ar->winx);
843 y1= (int)(pt2->y / 100 * p->ar->winy);
845 else { /* camera view, use subrect */
846 x0= (int)((pt1->x / 100) * (p->subrect->xmax - p->subrect->xmin)) + p->subrect->xmin;
847 y0= (int)((pt1->y / 100) * (p->subrect->ymax - p->subrect->ymin)) + p->subrect->ymin;
848 x1= (int)((pt2->x / 100) * (p->subrect->xmax - p->subrect->xmin)) + p->subrect->xmin;
849 y1= (int)((pt2->y / 100) * (p->subrect->ymax - p->subrect->ymin)) + p->subrect->ymin;
853 /* check that point segment of the boundbox of the eraser stroke */
854 if (BLI_in_rcti(rect, x0, y0) || BLI_in_rcti(rect, x1, y1)) {
855 /* check if point segment of stroke had anything to do with
856 * eraser region (either within stroke painted, or on its lines)
857 * - this assumes that linewidth is irrelevant
859 if (gp_stroke_eraser_strokeinside(mval, mvalo, rad, x0, y0, x1, y1)) {
860 /* if function returns true, break this loop (as no more point to check) */
861 if (gp_stroke_eraser_splitdel(gpf, gps, i))
869 /* erase strokes which fall under the eraser strokes */
870 static void gp_stroke_doeraser (tGPsdata *p)
872 bGPDframe *gpf= p->gpf;
873 bGPDstroke *gps, *gpn;
876 /* rect is rectangle of eraser */
877 rect.xmin= p->mval[0] - p->radius;
878 rect.ymin= p->mval[1] - p->radius;
879 rect.xmax= p->mval[0] + p->radius;
880 rect.ymax= p->mval[1] + p->radius;
882 /* loop over strokes, checking segments for intersections */
883 for (gps= gpf->strokes.first; gps; gps= gpn) {
885 gp_stroke_eraser_dostroke(p, p->mval, p->mvalo, p->radius, &rect, gpf, gps);
889 /* ******************************************* */
890 /* Sketching Operator */
892 /* clear the session buffers (call this before AND after a paint operation) */
893 static void gp_session_validatebuffer (tGPsdata *p)
895 bGPdata *gpd= p->gpd;
897 /* clear memory of buffer (or allocate it if starting a new session) */
899 memset(gpd->sbuffer, 0, sizeof(tGPspoint)*GP_STROKE_BUFFER_MAX);
901 gpd->sbuffer= MEM_callocN(sizeof(tGPspoint)*GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
904 gpd->sbuffer_size = 0;
907 gpd->sbuffer_sflag= 0;
910 /* init new painting session */
911 static tGPsdata *gp_session_initpaint (bContext *C)
914 bGPdata **gpd_ptr = NULL;
915 ScrArea *curarea= CTX_wm_area(C);
916 ARegion *ar= CTX_wm_region(C);
918 /* make sure the active view (at the starting time) is a 3d-view */
919 if (curarea == NULL) {
921 printf("Error: No active view for painting \n");
925 /* create new context data */
926 p= MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
928 /* pass on current scene and window */
929 p->scene= CTX_data_scene(C);
930 p->win= CTX_wm_window(C);
932 switch (curarea->spacetype) {
933 /* supported views first */
936 // View3D *v3d= curarea->spacedata.first;
937 // RegionView3D *rv3d= ar->regiondata;
940 * - must verify that region data is 3D-view (and not something else)
945 if (ar->regiondata == NULL) {
946 p->status= GP_STATUS_ERROR;
948 printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable \n");
952 #if 0 // XXX will this sort of antiquated stuff be restored?
953 /* check that gpencil data is allowed to be drawn */
954 if ((v3d->flag2 & V3D_DISPGP)==0) {
955 p->status= GP_STATUS_ERROR;
957 printf("Error: In active view, Grease Pencil not shown \n");
966 //SpaceNode *snode= curarea->spacedata.first;
968 /* set current area */
973 #if 0 // XXX will this sort of antiquated stuff be restored?
974 /* check that gpencil data is allowed to be drawn */
975 if ((snode->flag & SNODE_DISPGP)==0) {
976 p->status= GP_STATUS_ERROR;
978 printf("Error: In active view, Grease Pencil not shown \n");
984 #if 0 // XXX these other spaces will come over time...
987 SpaceSeq *sseq= curarea->spacedata.first;
989 /* set current area */
994 /* check that gpencil data is allowed to be drawn */
995 if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
996 p->status= GP_STATUS_ERROR;
998 printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil \n");
1001 if ((sseq->flag & SEQ_DRAW_GPENCIL)==0) {
1002 p->status= GP_STATUS_ERROR;
1004 printf("Error: In active view, Grease Pencil not shown \n");
1012 //SpaceImage *sima= curarea->spacedata.first;
1014 /* set the current area */
1018 //p->ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1020 #if 0 // XXX disabled for now
1021 /* check that gpencil data is allowed to be drawn */
1022 if ((sima->flag & SI_DISPGP)==0) {
1023 p->status= GP_STATUS_ERROR;
1025 printf("Error: In active view, Grease Pencil not shown \n");
1032 /* unsupported views */
1035 p->status= GP_STATUS_ERROR;
1037 printf("Error: Active view not appropriate for Grease Pencil drawing \n");
1044 gpd_ptr= gpencil_data_get_pointers(C, &p->ownerPtr);
1045 if (gpd_ptr == NULL) {
1046 p->status= GP_STATUS_ERROR;
1048 printf("Error: Current context doesn't allow for any Grease Pencil data \n");
1052 /* if no existing GPencil block exists, add one */
1053 if (*gpd_ptr == NULL)
1054 *gpd_ptr= gpencil_data_addnew("GPencil");
1058 /* set edit flags - so that buffer will get drawn */
1059 G.f |= G_GREASEPENCIL;
1061 /* clear out buffer (stored in gp-data), in case something contaminated it */
1062 gp_session_validatebuffer(p);
1065 /* set 'default' im2d_settings just in case something that uses this doesn't set it */
1066 p->im2d_settings.sizex= 1;
1067 p->im2d_settings.sizey= 1;
1070 /* return context data for running paint operator */
1074 /* cleanup after a painting session */
1075 static void gp_session_cleanup (tGPsdata *p)
1077 bGPdata *gpd= (p) ? p->gpd : NULL;
1079 /* error checking */
1083 /* free stroke buffer */
1085 MEM_freeN(gpd->sbuffer);
1090 gpd->sbuffer_size= 0;
1091 gpd->sbuffer_sflag= 0;
1094 /* init new stroke */
1095 static void gp_paint_initstroke (tGPsdata *p, short paintmode)
1097 /* get active layer (or add a new one if non-existent) */
1098 p->gpl= gpencil_layer_getactive(p->gpd);
1100 p->gpl= gpencil_layer_addnew(p->gpd);
1101 if (p->gpl->flag & GP_LAYER_LOCKED) {
1102 p->status= GP_STATUS_ERROR;
1104 printf("Error: Cannot paint on locked layer \n");
1108 /* get active frame (add a new one if not matching frame) */
1109 p->gpf= gpencil_layer_getframe(p->gpl, p->scene->r.cfra, 1);
1110 if (p->gpf == NULL) {
1111 p->status= GP_STATUS_ERROR;
1113 printf("Error: No frame created (gpencil_paint_init) \n");
1117 p->gpf->flag |= GP_FRAME_PAINT;
1119 /* set 'eraser' for this stroke if using eraser */
1120 p->paintmode= paintmode;
1121 if (p->paintmode == GP_PAINTMODE_ERASER)
1122 p->gpd->sbuffer_sflag |= GP_STROKE_ERASER;
1124 /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1125 p->flags |= GP_PAINTFLAG_FIRSTRUN;
1128 /* when drawing in the camera view, in 2D space, set the subrect */
1129 if (!(p->gpd->flag & GP_DATA_VIEWALIGN)) {
1130 if (p->sa->spacetype == SPACE_VIEW3D) {
1131 View3D *v3d= p->sa->spacedata.first;
1132 RegionView3D *rv3d= p->ar->regiondata;
1134 /* for camera view set the subrect */
1135 if (rv3d->persp == RV3D_CAMOB) {
1136 view3d_calc_camera_border(p->scene, p->ar, NULL, v3d, &p->subrect_data, -1); /* negative shift */
1137 p->subrect= &p->subrect_data;
1142 /* check if points will need to be made in view-aligned space */
1143 if (p->gpd->flag & GP_DATA_VIEWALIGN) {
1144 switch (p->sa->spacetype) {
1147 View3D *v3d= p->sa->spacedata.first;
1148 RegionView3D *rv3d= p->ar->regiondata;
1151 /* for camera view set the subrect */
1152 if (rv3d->persp == RV3D_CAMOB) {
1153 view3d_calc_camera_border(p->scene, p->ar, NULL, v3d, &p->subrect_data, -1); /* negative shift */
1154 p->subrect= &p->subrect_data;
1157 /* get reference point for 3d space placement */
1158 gp_get_3d_reference(p, rvec);
1159 initgrabz(rv3d, rvec[0], rvec[1], rvec[2]);
1161 p->gpd->sbuffer_sflag |= GP_STROKE_3DSPACE;
1167 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1170 #if 0 // XXX other spacetypes to be restored in due course
1173 SpaceSeq *sseq= (SpaceSeq *)p->sa->spacedata.first;
1175 float zoom, zoomx, zoomy;
1177 /* set draw 2d-stroke flag */
1178 p->gpd->sbuffer_sflag |= GP_STROKE_2DIMAGE;
1180 /* calculate zoom factor */
1181 zoom= (float)(SEQ_ZOOM_FAC(sseq->zoom));
1182 if (sseq->mainb == SEQ_DRAW_IMG_IMBUF) {
1183 zoomx = zoom * (p->scene->r.xasp / p->scene->r.yasp);
1187 zoomx = zoomy = zoom;
1189 /* calculate rect size to use to calculate the size of the drawing area
1190 * - We use the size of the output image not the size of the ibuf being shown
1191 * as it is too messy getting the ibuf (and could be too slow). This should be
1192 * a reasonable for most cases anyway.
1194 rectx= (p->scene->r.size * p->scene->r.xsch) / 100;
1195 recty= (p->scene->r.size * p->scene->r.ysch) / 100;
1197 /* set offset and scale values for opertations to use */
1198 p->im2d_settings.sizex= (int)(zoomx * rectx);
1199 p->im2d_settings.sizey= (int)(zoomy * recty);
1200 p->im2d_settings.offsx= (int)((p->sa->winx-p->im2d_settings.sizex)/2 + sseq->xof);
1201 p->im2d_settings.offsy= (int)((p->sa->winy-p->im2d_settings.sizey)/2 + sseq->yof);
1207 SpaceImage *sima= (SpaceImage *)p->sa->spacedata.first;
1209 /* only set these flags if the image editor doesn't have an image active,
1210 * otherwise user will be confused by strokes not appearing after they're drawn
1212 * Admittedly, this is a bit hacky, but it works much nicer from an ergonomic standpoint!
1214 if ELEM(NULL, sima, sima->image) {
1215 /* make strokes be drawn in screen space */
1216 p->gpd->sbuffer_sflag &= ~GP_STROKE_2DSPACE;
1217 p->gpd->flag &= ~GP_DATA_VIEWALIGN;
1220 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1227 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1228 static void gp_paint_strokeend (tGPsdata *p)
1230 /* for surface sketching, need to set the right OpenGL context stuff so that
1231 * the conversions will project the values correctly...
1233 if (gpencil_project_check(p)) {
1234 View3D *v3d= p->sa->spacedata.first;
1236 /* need to restore the original projection settings before packing up */
1237 view3d_region_operator_needs_opengl(p->win, p->ar);
1238 view_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1:0);
1241 /* check if doing eraser or not */
1242 if ((p->gpd->sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1243 /* smooth stroke before transferring? */
1244 gp_stroke_smooth(p);
1246 /* simplify stroke before transferring? */
1247 gp_stroke_simplify(p);
1249 /* transfer stroke to frame */
1250 gp_stroke_newfrombuffer(p);
1253 /* clean up buffer now */
1254 gp_session_validatebuffer(p);
1257 /* finish off stroke painting operation */
1258 static void gp_paint_cleanup (tGPsdata *p)
1260 /* finish off a stroke */
1261 gp_paint_strokeend(p);
1263 /* "unlock" frame */
1265 p->gpf->flag &= ~GP_FRAME_PAINT;
1268 /* ------------------------------- */
1270 static void gpencil_draw_exit (bContext *C, wmOperator *op)
1272 tGPsdata *p= op->customdata;
1274 /* clear edit flags */
1275 G.f &= ~G_GREASEPENCIL;
1277 /* restore cursor to indicate end of drawing */
1278 WM_cursor_restore(CTX_wm_window(C));
1280 /* don't assume that operator data exists at all */
1282 /* check size of buffer before cleanup, to determine if anything happened here */
1283 if (p->paintmode == GP_PAINTMODE_ERASER) {
1284 // TODO clear radial cursor thing
1285 // XXX draw_sel_circle(NULL, p.mvalo, 0, p.radius, 0);
1289 gp_paint_cleanup(p);
1290 gp_session_cleanup(p);
1292 /* finally, free the temp data */
1296 op->customdata= NULL;
1299 static int gpencil_draw_cancel (bContext *C, wmOperator *op)
1301 /* this is just a wrapper around exit() */
1302 gpencil_draw_exit(C, op);
1303 return OPERATOR_CANCELLED;
1306 /* ------------------------------- */
1309 static int gpencil_draw_init (bContext *C, wmOperator *op)
1312 int paintmode= RNA_enum_get(op->ptr, "mode");
1315 p= op->customdata= gp_session_initpaint(C);
1316 if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1317 /* something wasn't set correctly in context */
1318 gpencil_draw_exit(C, op);
1322 /* init painting data */
1323 gp_paint_initstroke(p, paintmode);
1324 if (p->status == GP_STATUS_ERROR) {
1325 gpencil_draw_exit(C, op);
1329 /* radius for eraser circle is defined in userprefs now */
1330 p->radius= U.gp_eraser;
1332 /* everything is now setup ok */
1336 /* ------------------------------- */
1338 /* update UI indicators of status, including cursor and header prints */
1339 static void gpencil_draw_status_indicators (tGPsdata *p)
1342 switch (p->status) {
1343 case GP_STATUS_PAINTING:
1344 /* only print this for paint-sessions, otherwise it gets annoying */
1345 if (GPENCIL_SKETCH_SESSIONS_ON(p->scene))
1346 ED_area_headerprint(p->sa, "Grease Pencil: Drawing/erasing stroke... Release to end stroke");
1349 case GP_STATUS_IDLING:
1350 /* print status info */
1351 switch (p->paintmode) {
1352 case GP_PAINTMODE_ERASER:
1353 ED_area_headerprint(p->sa, "Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | ESC/Enter to end");
1355 case GP_PAINTMODE_DRAW_STRAIGHT:
1356 ED_area_headerprint(p->sa, "Grease Pencil Line Session: Hold and drag LMB to draw | ESC/Enter to end");
1358 case GP_PAINTMODE_DRAW:
1359 ED_area_headerprint(p->sa, "Grease Pencil Freehand Session: Hold and drag LMB to draw | ESC/Enter to end");
1362 default: /* unhandled future cases */
1363 ED_area_headerprint(p->sa, "Grease Pencil Session: ESC/Enter to end");
1368 case GP_STATUS_ERROR:
1369 case GP_STATUS_DONE:
1370 /* clear status string */
1371 ED_area_headerprint(p->sa, NULL);
1376 /* ------------------------------- */
1378 /* create a new stroke point at the point indicated by the painting context */
1379 static void gpencil_draw_apply (wmOperator *op, tGPsdata *p)
1381 /* handle drawing/erasing -> test for erasing first */
1382 if (p->paintmode == GP_PAINTMODE_ERASER) {
1383 /* do 'live' erasing now */
1384 gp_stroke_doeraser(p);
1386 /* store used values */
1387 p->mvalo[0]= p->mval[0];
1388 p->mvalo[1]= p->mval[1];
1389 p->opressure= p->pressure;
1391 /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
1392 else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
1393 /* try to add point */
1394 short ok= gp_stroke_addpoint(p, p->mval, p->pressure);
1396 /* handle errors while adding point */
1397 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
1398 /* finish off old stroke */
1399 gp_paint_strokeend(p);
1401 /* start a new stroke, starting from previous point */
1402 gp_stroke_addpoint(p, p->mvalo, p->opressure);
1403 ok= gp_stroke_addpoint(p, p->mval, p->pressure);
1405 else if (ok == GP_STROKEADD_INVALID) {
1406 /* the painting operation cannot continue... */
1407 BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
1408 p->status = GP_STATUS_ERROR;
1411 printf("Error: Grease-Pencil Paint - Add Point Invalid \n");
1415 /* store used values */
1416 p->mvalo[0]= p->mval[0];
1417 p->mvalo[1]= p->mval[1];
1418 p->opressure= p->pressure;
1422 /* handle draw event */
1423 static void gpencil_draw_apply_event (wmOperator *op, wmEvent *event)
1425 tGPsdata *p= op->customdata;
1431 /* convert from window-space to area-space mouse coordintes */
1432 // NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
1433 p->mval[0]= event->x - ar->winrct.xmin + 1;
1434 p->mval[1]= event->y - ar->winrct.ymin + 1;
1436 /* handle pressure sensitivity (which is supplied by tablets) */
1437 if (event->custom == EVT_DATA_TABLET) {
1438 wmTabletData *wmtab= event->customdata;
1440 tablet= (wmtab->Active != EVT_TABLET_NONE);
1441 p->pressure= wmtab->Pressure;
1443 //if (wmtab->Active == EVT_TABLET_ERASER)
1444 // TODO... this should get caught by the keymaps which call drawing in the first place
1449 /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
1450 RNA_collection_add(op->ptr, "stroke", &itemptr);
1452 mousef[0]= p->mval[0];
1453 mousef[1]= p->mval[1];
1454 RNA_float_set_array(&itemptr, "mouse", mousef);
1455 RNA_float_set(&itemptr, "pressure", p->pressure);
1456 RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN));
1458 /* special exception for start of strokes (i.e. maybe for just a dot) */
1459 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1460 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1462 p->mvalo[0]= p->mval[0];
1463 p->mvalo[1]= p->mval[1];
1464 p->opressure= p->pressure;
1466 /* special exception here for too high pressure values on first touch in
1467 * windows for some tablets, then we just skip first touch ..
1469 if (tablet && (p->pressure >= 0.99f))
1473 /* apply the current latest drawing point */
1474 gpencil_draw_apply(op, p);
1477 ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1480 /* ------------------------------- */
1482 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
1483 static int gpencil_draw_exec (bContext *C, wmOperator *op)
1487 //printf("GPencil - Starting Re-Drawing \n");
1489 /* try to initialise context data needed while drawing */
1490 if (!gpencil_draw_init(C, op)) {
1491 if (op->customdata) MEM_freeN(op->customdata);
1492 //printf("\tGP - no valid data \n");
1493 return OPERATOR_CANCELLED;
1498 //printf("\tGP - Start redrawing stroke \n");
1500 /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
1501 * setting the relevant values in context at each step, then applying
1503 RNA_BEGIN(op->ptr, itemptr, "stroke")
1507 //printf("\t\tGP - stroke elem \n");
1509 /* get relevant data for this point from stroke */
1510 RNA_float_get_array(&itemptr, "mouse", mousef);
1511 p->mval[0] = (short)mousef[0];
1512 p->mval[1] = (short)mousef[1];
1513 p->pressure= RNA_float_get(&itemptr, "pressure");
1515 if (RNA_boolean_get(&itemptr, "is_start")) {
1516 /* if first-run flag isn't set already (i.e. not true first stroke),
1517 * then we must terminate the previous one first before continuing
1519 if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
1520 // TODO: both of these ops can set error-status, but we probably don't need to worry
1521 gp_paint_strokeend(p);
1522 gp_paint_initstroke(p, p->paintmode);
1526 /* if first run, set previous data too */
1527 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1528 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1530 p->mvalo[0]= p->mval[0];
1531 p->mvalo[1]= p->mval[1];
1532 p->opressure= p->pressure;
1535 /* apply this data as necessary now (as per usual) */
1536 gpencil_draw_apply(op, p);
1540 //printf("\tGP - done \n");
1543 gpencil_draw_exit(C, op);
1546 WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL); // XXX need a nicer one that will work
1549 return OPERATOR_FINISHED;
1552 /* ------------------------------- */
1554 /* start of interactive drawing part of operator */
1555 static int gpencil_draw_invoke (bContext *C, wmOperator *op, wmEvent *event)
1558 wmWindow *win= CTX_wm_window(C);
1561 printf("GPencil - Starting Drawing \n");
1563 /* try to initialise context data needed while drawing */
1564 if (!gpencil_draw_init(C, op)) {
1566 MEM_freeN(op->customdata);
1568 printf("\tGP - no valid data \n");
1569 return OPERATOR_CANCELLED;
1574 // TODO: set any additional settings that we can take from the events?
1575 // TODO? if tablet is erasing, force eraser to be on?
1577 // TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway...
1579 /* if eraser is on, draw radial aid */
1580 if (p->paintmode == GP_PAINTMODE_ERASER) {
1581 // TODO: this involves mucking around with radial control, so we leave this for now..
1585 if (p->paintmode == GP_PAINTMODE_ERASER)
1586 WM_cursor_modal(win, BC_CROSSCURSOR); // XXX need a better cursor
1588 WM_cursor_modal(win, BC_PAINTBRUSHCURSOR);
1590 /* special hack: if there was an initial event, then we were invoked via a hotkey, and
1591 * painting should start immediately. Otherwise, this was called from a toolbar, in which
1592 * case we should wait for the mouse to be clicked.
1595 /* hotkey invoked - start drawing */
1596 //printf("\tGP - set first spot\n");
1597 p->status= GP_STATUS_PAINTING;
1599 /* handle the initial drawing - i.e. for just doing a simple dot */
1600 gpencil_draw_apply_event(op, event);
1603 /* toolbar invoked - don't start drawing yet... */
1604 //printf("\tGP - hotkey invoked... waiting for click-drag\n");
1607 /* add a modal handler for this operator, so that we can then draw continuous strokes */
1608 WM_event_add_modal_handler(C, op);
1609 return OPERATOR_RUNNING_MODAL;
1612 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1613 static int gpencil_area_exists(bContext *C, ScrArea *satest)
1615 bScreen *sc= CTX_wm_screen(C);
1618 for(sa= sc->areabase.first; sa; sa= sa->next)
1624 /* events handling during interactive drawing part of operator */
1625 static int gpencil_draw_modal (bContext *C, wmOperator *op, wmEvent *event)
1627 tGPsdata *p= op->customdata;
1628 int estate = OPERATOR_PASS_THROUGH; /* default exit state - not handled, so let others have a share of the pie */
1630 //printf("\tGP - handle modal event...\n");
1632 /* exit painting mode (and/or end current stroke) */
1633 if (ELEM4(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY)) {
1634 /* exit() ends the current stroke before cleaning up */
1635 //printf("\t\tGP - end of paint op + end of stroke\n");
1636 p->status= GP_STATUS_DONE;
1637 estate = OPERATOR_FINISHED;
1640 /* toggle painting mode upon mouse-button movement */
1641 if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE)) {
1642 /* if painting, end stroke */
1643 if (p->status == GP_STATUS_PAINTING) {
1644 /* basically, this should be mouse-button up = end stroke
1645 * BUT what happens next depends on whether we 'painting sessions' is enabled
1647 if (GPENCIL_SKETCH_SESSIONS_ON(p->scene)) {
1648 /* end stroke only, and then wait to resume painting soon */
1649 //printf("\t\tGP - end stroke only\n");
1650 gp_paint_cleanup(p);
1651 p->status= GP_STATUS_IDLING;
1653 /* we've just entered idling state, so this event was processed (but no others yet) */
1654 estate = OPERATOR_RUNNING_MODAL;
1657 //printf("\t\tGP - end of stroke + op\n");
1658 p->status= GP_STATUS_DONE;
1659 estate = OPERATOR_FINISHED;
1663 /* not painting, so start stroke (this should be mouse-button down) */
1665 /* we must check that we're still within the area that we're set up to work from
1666 * otherwise we could crash (see bug #20586)
1668 if (CTX_wm_area(C) != p->sa) {
1669 //printf("\t\t\tGP - wrong area execution abort! \n");
1670 p->status= GP_STATUS_ERROR;
1671 estate = OPERATOR_CANCELLED;
1674 //printf("\t\tGP - start stroke \n");
1675 p->status= GP_STATUS_PAINTING;
1677 /* we may need to set up paint env again if we're resuming */
1678 // XXX: watch it with the paintmode! in future, it'd be nice to allow changing paint-mode when in sketching-sessions
1679 // XXX: with tablet events, we may event want to check for eraser here, for nicer tablet support
1680 gp_paint_initstroke(p, p->paintmode);
1682 if (p->status == GP_STATUS_ERROR) {
1683 estate = OPERATOR_CANCELLED;
1691 /* handle mode-specific events */
1692 if (p->status == GP_STATUS_PAINTING) {
1693 /* handle painting mouse-movements? */
1694 if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (p->flags & GP_PAINTFLAG_FIRSTRUN))
1696 /* handle drawing event */
1697 //printf("\t\tGP - add point\n");
1698 gpencil_draw_apply_event(op, event);
1700 /* finish painting operation if anything went wrong just now */
1701 if (p->status == GP_STATUS_ERROR) {
1702 //printf("\t\t\t\tGP - add error done! \n");
1703 estate = OPERATOR_CANCELLED;
1706 /* event handled, so just tag as running modal */
1707 //printf("\t\t\t\tGP - add point handled!\n");
1708 estate = OPERATOR_RUNNING_MODAL;
1711 /* there shouldn't be any other events, but just in case there are, let's swallow them
1712 * (i.e. to prevent problems with with undo)
1715 /* swallow event to save ourselves trouble */
1716 estate = OPERATOR_RUNNING_MODAL;
1719 else if (p->status == GP_STATUS_IDLING) {
1720 /* standard undo/redo shouldn't be allowed to execute or else it causes crashes, so catch it here */
1721 // FIXME: this is a hardcoded hotkey that can't be changed
1722 // TODO: catch redo as well, but how?
1723 if (event->type == ZKEY) {
1724 /* oskey = cmd key on macs as they seem to use cmd-z for undo as well? */
1725 if ((event->ctrl) || (event->oskey)) {
1726 /* just delete last stroke, which will look like undo to the end user */
1727 //printf("caught attempted undo event... deleting last stroke \n");
1728 gpencil_frame_delete_laststroke(p->gpl, p->gpf);
1730 /* event handled, so force refresh */
1731 ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1732 estate = OPERATOR_RUNNING_MODAL;
1737 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1738 if(0==gpencil_area_exists(C, p->sa))
1739 estate= OPERATOR_CANCELLED;
1741 /* update status indicators - cursor, header, etc. */
1742 gpencil_draw_status_indicators(p);
1744 /* process last operations before exiting */
1746 case OPERATOR_FINISHED:
1747 /* one last flush before we're done */
1748 gpencil_draw_exit(C, op);
1749 WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL); // XXX need a nicer one that will work
1752 case OPERATOR_CANCELLED:
1753 gpencil_draw_exit(C, op);
1756 case OPERATOR_RUNNING_MODAL|OPERATOR_PASS_THROUGH:
1757 /* event doesn't need to be handled */
1758 //printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n", event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
1762 /* return status code */
1766 /* ------------------------------- */
1768 static EnumPropertyItem prop_gpencil_drawmodes[] = {
1769 {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", ""},
1770 {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", ""},
1771 {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", ""},
1772 {0, NULL, 0, NULL, NULL}
1775 void GPENCIL_OT_draw (wmOperatorType *ot)
1778 ot->name= "Grease Pencil Draw";
1779 ot->idname= "GPENCIL_OT_draw";
1780 ot->description= "Make annotations on the active data";
1783 ot->exec= gpencil_draw_exec;
1784 ot->invoke= gpencil_draw_invoke;
1785 ot->modal= gpencil_draw_modal;
1786 ot->cancel= gpencil_draw_cancel;
1787 ot->poll= gpencil_draw_poll;
1790 ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1792 /* settings for drawing */
1793 RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to intepret mouse movements.");
1795 RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");