87866f764bc136c5901fbc8d16c83e491aa247d1
[blender.git] / source / blender / editors / sculpt_paint / paint_image.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * along with this program; if not, write to the Free Software Foundation,
15  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16  *
17  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
18  * All rights reserved.
19  *
20  * The Original Code is: some of this file.
21  *
22  * Contributor(s): Jens Ole Wund (bjornmose), Campbell Barton (ideasman42)
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/sculpt_paint/paint_image.c
28  *  \ingroup edsculpt
29  *  \brief Functions to paint images in 2D and 3D.
30  */
31
32 #include <float.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #ifdef WIN32
40 #  include "BLI_winstuff.h"
41 #endif
42
43 #include "BLI_math.h"
44 #include "BLI_blenlib.h"
45 #include "BLI_utildefines.h"
46 #include "BLI_threads.h"
47
48 #include "PIL_time.h"
49
50 #include "IMB_imbuf.h"
51 #include "IMB_imbuf_types.h"
52
53 #include "DNA_brush_types.h"
54 #include "DNA_mesh_types.h"
55 #include "DNA_node_types.h"
56 #include "DNA_object_types.h"
57
58 #include "BKE_context.h"
59 #include "BKE_depsgraph.h"
60 #include "BKE_brush.h"
61 #include "BKE_image.h"
62 #include "BKE_main.h"
63 #include "BKE_material.h"
64 #include "BKE_mesh.h"
65 #include "BKE_node.h"
66 #include "BKE_paint.h"
67 #include "BKE_report.h"
68 #include "BKE_scene.h"
69 #include "BKE_texture.h"
70 #include "BKE_colortools.h"
71
72 #include "BKE_editmesh.h"
73
74 #include "UI_view2d.h"
75
76 #include "ED_image.h"
77 #include "ED_object.h"
78 #include "ED_paint.h"
79 #include "ED_screen.h"
80 #include "ED_view3d.h"
81
82 #include "WM_api.h"
83 #include "WM_types.h"
84
85 #include "RNA_access.h"
86 #include "RNA_define.h"
87 #include "RNA_enum_types.h"
88
89 #include "GPU_draw.h"
90
91 #include "BIF_gl.h"
92 #include "BIF_glutil.h"
93
94 #include "IMB_colormanagement.h"
95
96 #include "paint_intern.h"
97
98 typedef struct UndoImageTile {
99         struct UndoImageTile *next, *prev;
100
101         char idname[MAX_ID_NAME];  /* name instead of pointer*/
102         char ibufname[IB_FILENAME_SIZE];
103
104         union {
105                 float        *fp;
106                 unsigned int *uint;
107                 void         *pt;
108         } rect;
109
110         unsigned short *mask;
111
112         int x, y;
113
114         Image *ima;
115         short source, use_float;
116         char gen_type;
117         bool valid;
118 } UndoImageTile;
119
120 /* this is a static resource for non-globality,
121  * Maybe it should be exposed as part of the
122  * paint operation, but for now just give a public interface */
123 static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
124 static SpinLock undolock;
125
126 void image_undo_init_locks(void)
127 {
128         BLI_spin_init(&undolock);
129 }
130
131 void image_undo_end_locks(void)
132 {
133         BLI_spin_end(&undolock);
134 }
135
136 ImagePaintPartialRedraw *get_imapaintpartial(void)
137 {
138         return &imapaintpartial;
139 }
140
141 void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr)
142 {
143         imapaintpartial = *ippr;
144 }
145
146 /* UNDO */
147 typedef enum {
148         COPY = 0,
149         RESTORE = 1,
150         RESTORE_COPY = 2
151 } CopyMode;
152
153 static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, CopyMode mode)
154 {
155         if (mode == COPY) {
156                 /* copy or swap contents of tile->rect and region in ibuf->rect */
157                 IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
158                             tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
159
160                 if (ibuf->rect_float) {
161                         SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
162                 }
163                 else {
164                         SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
165                 }
166         }
167         else {
168                 if (mode == RESTORE_COPY)
169                         IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
170                                 tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
171                 /* swap to the tmpbuf for easy copying */
172                 if (ibuf->rect_float) {
173                         SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
174                 }
175                 else {
176                         SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
177                 }
178
179                 IMB_rectcpy(ibuf, tmpibuf, tile->x * IMAPAINT_TILE_SIZE,
180                             tile->y * IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
181
182                 if (mode == RESTORE) {
183                         if (ibuf->rect_float) {
184                                 SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
185                         }
186                         else {
187                                 SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
188                         }
189                 }
190         }
191 }
192
193 void *image_undo_find_tile(Image *ima, ImBuf *ibuf, int x_tile, int y_tile, unsigned short **mask, bool validate)
194 {
195         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
196         UndoImageTile *tile;
197         short use_float = ibuf->rect_float ? 1 : 0;
198
199         for (tile = lb->first; tile; tile = tile->next) {
200                 if (tile->x == x_tile && tile->y == y_tile && ima->gen_type == tile->gen_type && ima->source == tile->source) {
201                         if (tile->use_float == use_float) {
202                                 if (strcmp(tile->idname, ima->id.name) == 0 && strcmp(tile->ibufname, ibuf->name) == 0) {
203                                         if (mask) {
204                                                 /* allocate mask if requested */
205                                                 if (!tile->mask) {
206                                                         tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE,
207                                                                                  "UndoImageTile.mask");
208                                                 }
209
210                                                 *mask = tile->mask;
211                                         }
212                                         if (validate)
213                                                 tile->valid = true;
214
215                                         return tile->rect.pt;
216                                 }
217                         }
218                 }
219         }
220         
221         return NULL;
222 }
223
224 void *image_undo_push_tile(Image *ima, ImBuf *ibuf, ImBuf **tmpibuf, int x_tile, int y_tile, unsigned short **mask, bool **valid, bool proj)
225 {
226         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
227         UndoImageTile *tile;
228         int allocsize;
229         short use_float = ibuf->rect_float ? 1 : 0;
230         void *data;
231
232         /* check if tile is already pushed */
233
234         /* in projective painting we keep accounting of tiles, so if we need one pushed, just push! */
235         if (!proj) {
236                 data = image_undo_find_tile(ima, ibuf, x_tile, y_tile, mask, true);
237                 if (data)
238                         return data;
239         }
240
241         if (*tmpibuf == NULL)
242                 *tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, IB_rectfloat | IB_rect);
243         
244         tile = MEM_callocN(sizeof(UndoImageTile), "UndoImageTile");
245         BLI_strncpy(tile->idname, ima->id.name, sizeof(tile->idname));
246         tile->x = x_tile;
247         tile->y = y_tile;
248
249         /* add mask explicitly here */
250         if (mask)
251                 *mask = tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE,
252                                          "UndoImageTile.mask");
253
254         allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
255         allocsize *= (ibuf->rect_float) ? sizeof(float) : sizeof(char);
256         tile->rect.pt = MEM_mapallocN(allocsize, "UndeImageTile.rect");
257
258         BLI_strncpy(tile->ibufname, ibuf->name, sizeof(tile->ibufname));
259
260         tile->gen_type = ima->gen_type;
261         tile->source = ima->source;
262         tile->use_float = use_float;
263         tile->valid = true;
264         tile->ima = ima;
265
266         if (valid)
267                 *valid = &tile->valid;
268
269         undo_copy_tile(tile, *tmpibuf, ibuf, COPY);
270
271         if (proj)
272                 BLI_spin_lock(&undolock);
273
274         undo_paint_push_count_alloc(UNDO_PAINT_IMAGE, allocsize);
275         BLI_addtail(lb, tile);
276
277         if (proj)
278                 BLI_spin_unlock(&undolock);
279
280         return tile->rect.pt;
281 }
282
283 void image_undo_remove_masks(void)
284 {
285         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
286         UndoImageTile *tile;
287
288         for (tile = lb->first; tile; tile = tile->next) {
289                 if (tile->mask) {
290                         MEM_freeN(tile->mask);
291                         tile->mask = NULL;
292                 }
293         }
294 }
295
296 static void image_undo_restore_runtime(ListBase *lb)
297 {
298         ImBuf *ibuf, *tmpibuf;
299         UndoImageTile *tile;
300
301         tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
302                                  IB_rectfloat | IB_rect);
303
304         for (tile = lb->first; tile; tile = tile->next) {
305                 Image *ima = tile->ima;
306                 ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
307
308                 undo_copy_tile(tile, tmpibuf, ibuf, RESTORE);
309
310                 GPU_free_image(ima); /* force OpenGL reload (maybe partial update will operate better?) */
311                 if (ibuf->rect_float)
312                         ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
313                 if (ibuf->mipmap[0])
314                         ibuf->userflags |= IB_MIPMAP_INVALID;  /* force mipmap recreatiom */
315                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
316
317                 BKE_image_release_ibuf(ima, ibuf, NULL);
318         }
319
320         IMB_freeImBuf(tmpibuf);
321 }
322
323 void ED_image_undo_restore(bContext *C, ListBase *lb)
324 {
325         Main *bmain = CTX_data_main(C);
326         Image *ima = NULL;
327         ImBuf *ibuf, *tmpibuf;
328         UndoImageTile *tile;
329
330         tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
331                                  IB_rectfloat | IB_rect);
332
333         for (tile = lb->first; tile; tile = tile->next) {
334                 short use_float;
335
336                 /* find image based on name, pointer becomes invalid with global undo */
337                 if (ima && strcmp(tile->idname, ima->id.name) == 0) {
338                         /* ima is valid */
339                 }
340                 else {
341                         ima = BLI_findstring(&bmain->image, tile->idname, offsetof(ID, name));
342                 }
343
344                 ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
345
346                 if (ima && ibuf && strcmp(tile->ibufname, ibuf->name) != 0) {
347                         /* current ImBuf filename was changed, probably current frame
348                          * was changed when painting on image sequence, rather than storing
349                          * full image user (which isn't so obvious, btw) try to find ImBuf with
350                          * matched file name in list of already loaded images */
351
352                         BKE_image_release_ibuf(ima, ibuf, NULL);
353
354                         ibuf = BKE_image_get_ibuf_with_name(ima, tile->ibufname);
355                 }
356
357                 if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) {
358                         BKE_image_release_ibuf(ima, ibuf, NULL);
359                         continue;
360                 }
361
362                 if (ima->gen_type != tile->gen_type || ima->source != tile->source) {
363                         BKE_image_release_ibuf(ima, ibuf, NULL);
364                         continue;
365                 }
366
367                 use_float = ibuf->rect_float ? 1 : 0;
368
369                 if (use_float != tile->use_float) {
370                         BKE_image_release_ibuf(ima, ibuf, NULL);
371                         continue;
372                 }
373
374                 undo_copy_tile(tile, tmpibuf, ibuf, RESTORE_COPY);
375
376                 GPU_free_image(ima); /* force OpenGL reload */
377                 if (ibuf->rect_float)
378                         ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
379                 if (ibuf->mipmap[0])
380                         ibuf->userflags |= IB_MIPMAP_INVALID;  /* force mipmap recreatiom */
381                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
382
383                 DAG_id_tag_update(&ima->id, 0);
384
385                 BKE_image_release_ibuf(ima, ibuf, NULL);
386         }
387
388         IMB_freeImBuf(tmpibuf);
389 }
390
391 void ED_image_undo_free(ListBase *lb)
392 {
393         UndoImageTile *tile;
394
395         for (tile = lb->first; tile; tile = tile->next)
396                 MEM_freeN(tile->rect.pt);
397 }
398
399 static void image_undo_end(void)
400 {
401         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
402         UndoImageTile *tile;
403         int deallocsize = 0;
404         int allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
405
406         /* first dispose of invalid tiles (may happen due to drag dot for instance) */
407         for (tile = lb->first; tile;) {
408                 if (!tile->valid) {
409                         UndoImageTile *tmp_tile = tile->next;
410                         deallocsize += allocsize * ((tile->use_float) ? sizeof(float) : sizeof(char));
411                         MEM_freeN(tile->rect.pt);
412                         BLI_freelinkN (lb, tile);
413                         tile = tmp_tile;
414                 }
415                 else {
416                         tile = tile->next;
417                 }
418         }
419
420         /* don't forget to remove the size of deallocated tiles */
421         undo_paint_push_count_alloc(UNDO_PAINT_IMAGE, -deallocsize);
422
423         ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
424 }
425
426 static void image_undo_invalidate(void)
427 {
428         UndoImageTile *tile;
429         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
430
431         for (tile = lb->first; tile; tile = tile->next)
432                 tile->valid = false;
433 }
434
435 /* Imagepaint Partial Redraw & Dirty Region */
436
437 void ED_imapaint_clear_partial_redraw(void)
438 {
439         memset(&imapaintpartial, 0, sizeof(imapaintpartial));
440 }
441
442 void imapaint_region_tiles(ImBuf *ibuf, int x, int y, int w, int h, int *tx, int *ty, int *tw, int *th)
443 {
444         int srcx = 0, srcy = 0;
445
446         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
447
448         *tw = ((x + w - 1) >> IMAPAINT_TILE_BITS);
449         *th = ((y + h - 1) >> IMAPAINT_TILE_BITS);
450         *tx = (x >> IMAPAINT_TILE_BITS);
451         *ty = (y >> IMAPAINT_TILE_BITS);
452 }
453
454 void ED_imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h)
455 {
456         ImBuf *tmpibuf = NULL;
457         int tilex, tiley, tilew, tileh, tx, ty;
458         int srcx = 0, srcy = 0;
459
460         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
461
462         if (w == 0 || h == 0)
463                 return;
464         
465         if (!imapaintpartial.enabled) {
466                 imapaintpartial.x1 = x;
467                 imapaintpartial.y1 = y;
468                 imapaintpartial.x2 = x + w;
469                 imapaintpartial.y2 = y + h;
470                 imapaintpartial.enabled = 1;
471         }
472         else {
473                 imapaintpartial.x1 = min_ii(imapaintpartial.x1, x);
474                 imapaintpartial.y1 = min_ii(imapaintpartial.y1, y);
475                 imapaintpartial.x2 = max_ii(imapaintpartial.x2, x + w);
476                 imapaintpartial.y2 = max_ii(imapaintpartial.y2, y + h);
477         }
478
479         imapaint_region_tiles(ibuf, x, y, w, h, &tilex, &tiley, &tilew, &tileh);
480
481         for (ty = tiley; ty <= tileh; ty++)
482                 for (tx = tilex; tx <= tilew; tx++)
483                         image_undo_push_tile(ima, ibuf, &tmpibuf, tx, ty, NULL, NULL, false);
484
485         ibuf->userflags |= IB_BITMAPDIRTY;
486         
487         if (tmpibuf)
488                 IMB_freeImBuf(tmpibuf);
489 }
490
491 void imapaint_image_update(SpaceImage *sima, Image *image, ImBuf *ibuf, short texpaint)
492 {
493         if (imapaintpartial.x1 != imapaintpartial.x2 &&
494             imapaintpartial.y1 != imapaintpartial.y2)
495         {
496                 IMB_partial_display_buffer_update_delayed(ibuf, imapaintpartial.x1, imapaintpartial.y1,
497                                                           imapaintpartial.x2, imapaintpartial.y2);
498         }
499         
500         if (ibuf->mipmap[0])
501                 ibuf->userflags |= IB_MIPMAP_INVALID;
502
503         /* todo: should set_tpage create ->rect? */
504         if (texpaint || (sima && sima->lock)) {
505                 int w = imapaintpartial.x2 - imapaintpartial.x1;
506                 int h = imapaintpartial.y2 - imapaintpartial.y1;
507                 /* Testing with partial update in uv editor too */
508                 GPU_paint_update_image(image, imapaintpartial.x1, imapaintpartial.y1, w, h); //!texpaint);
509         }
510 }
511
512 /* paint blur kernels. Projective painting enforces use of a 2x2 kernel due to lagging */
513 BlurKernel *paint_new_blur_kernel(Brush *br, bool proj)
514 {
515         int i, j;
516         BlurKernel *kernel = MEM_mallocN(sizeof(BlurKernel), "blur kernel");
517         float radius;
518         int side;
519         BlurKernelType type = br->blur_mode;
520
521         if (proj) {
522                 radius = 0.5f;
523                 
524                 side = kernel->side = 2;
525                 kernel->side_squared = kernel->side * kernel->side;
526                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
527                 kernel->pixel_len = radius;
528         }
529         else {
530                 if (br->blur_kernel_radius <= 0)
531                         br->blur_kernel_radius = 1;
532                 
533                 radius = br->blur_kernel_radius;
534                                         
535                 side = kernel->side = radius * 2 + 1;
536                 kernel->side_squared = kernel->side * kernel->side;
537                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
538                 kernel->pixel_len = br->blur_kernel_radius;
539         }
540         
541         switch (type) {
542                 case KERNEL_BOX:
543                         for (i = 0; i < kernel->side_squared; i++)
544                                 kernel->wdata[i] = 1.0;
545                         break;
546
547                 case KERNEL_GAUSSIAN:
548                 {
549                         /* at 3.0 standard deviations distance, kernel is about zero */                 
550                         float standard_dev = radius / 3.0f; 
551                         
552                         /* make the necessary adjustment to the value for use in the normal distribution formula */
553                         standard_dev = -standard_dev * standard_dev * 2;
554
555                         for (i = 0; i < side; i++) {
556                                 for (j = 0; j < side; j++) {
557                                         float idist = radius - i;
558                                         float jdist = radius - j;
559                                         float value = exp((idist * idist + jdist * jdist) / standard_dev);
560                                         
561                                         kernel->wdata[i + j * side] = value;
562                                 }
563                         }
564
565                         break;
566                 }
567
568                 default:
569                         printf("unidentified kernel type, aborting\n");
570                         MEM_freeN(kernel->wdata);
571                         MEM_freeN(kernel);
572                         return NULL;
573                         break;
574         }
575
576         return kernel;
577 }
578
579 void paint_delete_blur_kernel(BlurKernel *kernel)
580 {
581         if (kernel->wdata)
582                 MEM_freeN(kernel->wdata);
583 }
584
585 /************************ image paint poll ************************/
586
587 static Brush *image_paint_brush(bContext *C)
588 {
589         Scene *scene = CTX_data_scene(C);
590         ToolSettings *settings = scene->toolsettings;
591
592         return BKE_paint_brush(&settings->imapaint.paint);
593 }
594
595 static int image_paint_poll(bContext *C)
596 {
597         Object *obact;
598
599         if (!image_paint_brush(C))
600                 return 0;
601
602         obact = CTX_data_active_object(C);
603         if ((obact && obact->mode & OB_MODE_TEXTURE_PAINT) && CTX_wm_region_view3d(C)) {
604                 return 1;
605         }
606         else {
607                 SpaceImage *sima = CTX_wm_space_image(C);
608
609                 if (sima) {
610                         ARegion *ar = CTX_wm_region(C);
611
612                         if ((sima->mode == SI_MODE_PAINT) && ar->regiontype == RGN_TYPE_WINDOW) {
613                                 return 1;
614                         }
615                 }
616         }
617
618         return 0;
619 }
620
621 static int image_paint_2d_clone_poll(bContext *C)
622 {
623         Brush *brush = image_paint_brush(C);
624
625         if (!CTX_wm_region_view3d(C) && image_paint_poll(C))
626                 if (brush && (brush->imagepaint_tool == PAINT_TOOL_CLONE))
627                         if (brush->clone.image)
628                                 return 1;
629         
630         return 0;
631 }
632
633 /************************ paint operator ************************/
634 typedef enum TexPaintMode {
635         PAINT_MODE_2D,
636         PAINT_MODE_3D_PROJECT
637 } TexPaintMode;
638
639 typedef struct PaintOperation {
640         TexPaintMode mode;
641
642         void *custom_paint;
643
644         float prevmouse[2];
645         float startmouse[2];
646         double starttime;
647
648         void *cursor;
649         ViewContext vc;
650 } PaintOperation;
651
652 bool paint_use_opacity_masking(Brush *brush)
653 {
654         return (brush->flag & BRUSH_AIRBRUSH) ||
655                (brush->flag & BRUSH_DRAG_DOT) ||
656                (brush->flag & BRUSH_ANCHORED) ||
657                (brush->imagepaint_tool == PAINT_TOOL_SMEAR) ||
658                (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) ||
659                (brush->imagepaint_tool == PAINT_TOOL_FILL) ||
660                (brush->flag & BRUSH_USE_GRADIENT) ||
661                    (brush->mtex.tex && !ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)) ?
662                     false : true;
663 }
664
665 void paint_brush_color_get(struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance,
666                            float pressure, float color[3], struct ColorManagedDisplay *display)
667 {
668         if (invert)
669                 copy_v3_v3(color, BKE_brush_secondary_color_get(scene, br));
670         else {
671                 if (br->flag & BRUSH_USE_GRADIENT) {
672                         switch (br->gradient_stroke_mode) {
673                                 case BRUSH_GRADIENT_PRESSURE:
674                                         do_colorband(br->gradient, pressure, color);
675                                         break;
676                                 case BRUSH_GRADIENT_SPACING_REPEAT:
677                                 {
678                                         float coord = fmod(distance / br->gradient_spacing, 1.0);
679                                         do_colorband(br->gradient, coord, color);
680                                         break;
681                                 }
682                                 case BRUSH_GRADIENT_SPACING_CLAMP:
683                                 {
684                                         do_colorband(br->gradient, distance / br->gradient_spacing, color);
685                                         break;
686                                 }
687                         }
688                 }
689                 else
690                         copy_v3_v3(color, BKE_brush_color_get(scene, br));
691         }
692         if (color_correction)
693                 IMB_colormanagement_display_to_scene_linear_v3(color, display);
694 }
695
696 void paint_brush_init_tex(Brush *brush)
697 {
698         /* init mtex nodes */
699         if (brush) {
700                 MTex *mtex = &brush->mtex;
701                 if (mtex->tex && mtex->tex->nodetree)
702                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
703                 mtex = &brush->mask_mtex;
704                 if (mtex->tex && mtex->tex->nodetree)
705                         ntreeTexBeginExecTree(mtex->tex->nodetree);
706         }
707 }
708
709 void paint_brush_exit_tex(Brush *brush)
710 {
711         if (brush) {
712                 MTex *mtex = &brush->mtex;
713                 if (mtex->tex && mtex->tex->nodetree)
714                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
715                 mtex = &brush->mask_mtex;
716                 if (mtex->tex && mtex->tex->nodetree)
717                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
718         }
719 }
720
721 static void gradient_draw_line(bContext *UNUSED(C), int x, int y, void *customdata)
722 {
723         PaintOperation *pop = (PaintOperation *)customdata;
724
725         if (pop) {
726                 glEnable(GL_LINE_SMOOTH);
727                 glEnable(GL_BLEND);
728
729                 glLineWidth(4.0);
730                 glColor4ub(0, 0, 0, 255);
731                 sdrawline(x, y, pop->startmouse[0], pop->startmouse[1]);
732                 glLineWidth(2.0);
733                 glColor4ub(255, 255, 255, 255);
734                 sdrawline(x, y, pop->startmouse[0], pop->startmouse[1]);
735                 glLineWidth(1.0);
736
737                 glDisable(GL_BLEND);
738                 glDisable(GL_LINE_SMOOTH);
739         }
740 }
741
742
743 static PaintOperation *texture_paint_init(bContext *C, wmOperator *op, const float mouse[2])
744 {
745         Scene *scene = CTX_data_scene(C);
746         ToolSettings *settings = scene->toolsettings;
747         PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
748         Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
749         int mode = RNA_enum_get(op->ptr, "mode");
750         view3d_set_viewcontext(C, &pop->vc);
751
752         copy_v2_v2(pop->prevmouse, mouse);
753         copy_v2_v2(pop->startmouse, mouse);
754
755         if ((brush->imagepaint_tool == PAINT_TOOL_FILL) && (brush->flag & BRUSH_USE_GRADIENT)) {
756                 pop->cursor = WM_paint_cursor_activate(CTX_wm_manager(C), image_paint_poll, gradient_draw_line, pop);
757         }
758
759         /* initialize from context */
760         if (CTX_wm_region_view3d(C)) {
761                 Object *ob = OBACT;
762                 paint_proj_mesh_data_ensure(C, ob, op);
763                 pop->mode = PAINT_MODE_3D_PROJECT;
764                 pop->custom_paint = paint_proj_new_stroke(C, ob, mouse, mode);
765         }
766         else {
767                 pop->mode = PAINT_MODE_2D;
768                 pop->custom_paint = paint_2d_new_stroke(C, op, mode);
769         }
770
771         if (!pop->custom_paint) {
772                 MEM_freeN(pop);
773                 return NULL;
774         }
775
776         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
777         ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
778                                  ED_image_undo_restore, ED_image_undo_free, NULL);
779
780         return pop;
781 }
782
783 /* restore painting image to previous state. Used for anchored and drag-dot style brushes*/
784 static void paint_stroke_restore(void)
785 {
786         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
787         image_undo_restore_runtime(lb);
788         image_undo_invalidate();
789 }
790
791 static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
792 {
793         PaintOperation *pop = paint_stroke_mode_data(stroke);
794         Scene *scene = CTX_data_scene(C);
795         ToolSettings *toolsettings = CTX_data_tool_settings(C);
796         UnifiedPaintSettings *ups = &toolsettings->unified_paint_settings;
797         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
798
799         float alphafac = (brush->flag & BRUSH_ACCUMULATE) ? ups->overlap_factor : 1.0f;
800
801         /* initial brush values. Maybe it should be considered moving these to stroke system */
802         float startalpha = BKE_brush_alpha_get(scene, brush);
803
804         float mouse[2];
805         float pressure;
806         float size;
807         float distance = paint_stroke_distance_get(stroke);
808         int eraser;
809
810         RNA_float_get_array(itemptr, "mouse", mouse);
811         pressure = RNA_float_get(itemptr, "pressure");
812         eraser = RNA_boolean_get(itemptr, "pen_flip");
813         size = max_ff(1.0f, RNA_float_get(itemptr, "size"));
814
815         /* stroking with fill tool only acts on stroke end */
816         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
817                 copy_v2_v2(pop->prevmouse, mouse);
818                 return;
819         }
820
821         if (BKE_brush_use_alpha_pressure(scene, brush))
822                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * pressure * alphafac));
823         else
824                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * alphafac));
825
826         if ((brush->flag & BRUSH_DRAG_DOT) || (brush->flag & BRUSH_ANCHORED)) {
827                 paint_stroke_restore();
828         }
829
830         if (pop->mode == PAINT_MODE_3D_PROJECT) {
831                 paint_proj_stroke(C, pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
832         }
833         else {
834                 paint_2d_stroke(pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
835         }
836
837         copy_v2_v2(pop->prevmouse, mouse);
838
839         /* restore brush values */
840         BKE_brush_alpha_set(scene, brush, startalpha);
841 }
842
843 static void paint_stroke_redraw(const bContext *C, struct PaintStroke *stroke, bool final)
844 {
845         PaintOperation *pop = paint_stroke_mode_data(stroke);
846
847         if (pop->mode == PAINT_MODE_3D_PROJECT) {
848                 paint_proj_redraw(C, pop->custom_paint, final);
849         }
850         else {
851                 paint_2d_redraw(C, pop->custom_paint, final);
852         }
853 }
854
855 static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke)
856 {
857         Scene *scene = CTX_data_scene(C);
858         ToolSettings *toolsettings = scene->toolsettings;
859         PaintOperation *pop = paint_stroke_mode_data(stroke);
860         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
861
862         toolsettings->imapaint.flag &= ~IMAGEPAINT_DRAWING;
863
864         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
865                 if (brush->flag & BRUSH_USE_GRADIENT) {
866                         if (pop->mode == PAINT_MODE_2D) {
867                                 paint_2d_gradient_fill(C, brush, pop->startmouse, pop->prevmouse, pop->custom_paint);
868                         }
869                         else {
870                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
871                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
872                                 /* two redraws, one for GPU update, one for notification */
873                                 paint_proj_redraw(C, pop->custom_paint, false);
874                                 paint_proj_redraw(C, pop->custom_paint, true);
875                         }
876                 }
877                 else {
878                         if (pop->mode == PAINT_MODE_2D) {
879                                 float color[3];
880
881                                 srgb_to_linearrgb_v3_v3(color, BKE_brush_color_get(scene, brush));
882                                 paint_2d_bucket_fill(C, color, brush, pop->prevmouse, pop->custom_paint);
883                         }
884                         else {
885                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
886                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
887                                 /* two redraws, one for GPU update, one for notification */
888                                 paint_proj_redraw(C, pop->custom_paint, false);
889                                 paint_proj_redraw(C, pop->custom_paint, true);
890                         }
891                 }
892         }
893         if (pop->mode == PAINT_MODE_3D_PROJECT) {
894                 paint_proj_stroke_done(pop->custom_paint);
895         }
896         else {
897                 paint_2d_stroke_done(pop->custom_paint);
898         }
899
900         if (pop->cursor) {
901                 WM_paint_cursor_end(CTX_wm_manager(C), pop->cursor);
902         }
903
904         image_undo_end();
905
906         /* duplicate warning, see texpaint_init */
907 #if 0
908         if (pop->s.warnmultifile)
909                 BKE_reportf(op->reports, RPT_WARNING, "Image requires 4 color channels to paint: %s", pop->s.warnmultifile);
910         if (pop->s.warnpackedfile)
911                 BKE_reportf(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted: %s", pop->s.warnpackedfile);
912 #endif
913         MEM_freeN(pop);
914 }
915
916 static bool paint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
917 {
918         PaintOperation *pop;
919
920         /* TODO Should avoid putting this here. Instead, last position should be requested
921          * from stroke system. */
922
923         if (!(pop = texture_paint_init(C, op, mouse))) {
924                 return false;
925         }
926
927         paint_stroke_set_mode_data(op->customdata, pop);
928
929         return true;
930 }
931
932
933 static int paint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
934 {
935         int retval;
936
937         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
938                                           paint_stroke_update_step,
939                                           paint_stroke_redraw,
940                                           paint_stroke_done, event->type);
941
942         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
943                 paint_stroke_data_free(op);
944                 return OPERATOR_FINISHED;
945         }
946         /* add modal handler */
947         WM_event_add_modal_handler(C, op);
948
949         OPERATOR_RETVAL_CHECK(retval);
950         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
951
952         return OPERATOR_RUNNING_MODAL;
953 }
954
955 static int paint_exec(bContext *C, wmOperator *op)
956 {
957         PaintOperation *pop;
958         PropertyRNA *strokeprop;
959         PointerRNA firstpoint;
960         float mouse[2];
961
962         strokeprop = RNA_struct_find_property(op->ptr, "stroke");
963
964         if (!RNA_property_collection_lookup_int(op->ptr, strokeprop, 0, &firstpoint))
965                 return OPERATOR_CANCELLED;
966
967         RNA_float_get_array(&firstpoint, "mouse", mouse);
968
969         if (!(pop = texture_paint_init(C, op, mouse))) {
970                 return OPERATOR_CANCELLED;
971         }
972
973         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
974                                           paint_stroke_update_step,
975                                           paint_stroke_redraw,
976                                           paint_stroke_done, 0);
977         /* frees op->customdata */
978         paint_stroke_exec(C, op);
979
980         return OPERATOR_FINISHED;
981 }
982
983 void PAINT_OT_image_paint(wmOperatorType *ot)
984 {
985         /* identifiers */
986         ot->name = "Image Paint";
987         ot->idname = "PAINT_OT_image_paint";
988         ot->description = "Paint a stroke into the image";
989
990         /* api callbacks */
991         ot->invoke = paint_invoke;
992         ot->modal = paint_stroke_modal;
993         ot->exec = paint_exec;
994         ot->poll = image_paint_poll;
995         ot->cancel = paint_stroke_cancel;
996
997         /* flags */
998         ot->flag = OPTYPE_BLOCKING;
999
1000         paint_stroke_operator_properties(ot);
1001 }
1002
1003
1004 int get_imapaint_zoom(bContext *C, float *zoomx, float *zoomy)
1005 {
1006         RegionView3D *rv3d = CTX_wm_region_view3d(C);
1007
1008         if (!rv3d) {
1009                 SpaceImage *sima = CTX_wm_space_image(C);
1010
1011                 if (sima->mode == SI_MODE_PAINT) {
1012                         ARegion *ar = CTX_wm_region(C);
1013                         ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
1014
1015                         return 1;
1016                 }
1017         }
1018
1019         *zoomx = *zoomy = 1;
1020
1021         return 0;
1022 }
1023
1024 /************************ cursor drawing *******************************/
1025
1026 static void toggle_paint_cursor(bContext *C, int enable)
1027 {
1028         wmWindowManager *wm = CTX_wm_manager(C);
1029         Scene *scene = CTX_data_scene(C);
1030         ToolSettings *settings = scene->toolsettings;
1031
1032         if (settings->imapaint.paintcursor && !enable) {
1033                 WM_paint_cursor_end(wm, settings->imapaint.paintcursor);
1034                 settings->imapaint.paintcursor = NULL;
1035                 paint_cursor_delete_textures();
1036         }
1037         else if (enable)
1038                 paint_cursor_start(C, image_paint_poll);
1039 }
1040
1041 /* enable the paint cursor if it isn't already.
1042  *
1043  * purpose is to make sure the paint cursor is shown if paint
1044  * mode is enabled in the image editor. the paint poll will
1045  * ensure that the cursor is hidden when not in paint mode */
1046 void ED_space_image_paint_update(wmWindowManager *wm, ToolSettings *settings)
1047 {
1048         wmWindow *win;
1049         ScrArea *sa;
1050         ImagePaintSettings *imapaint = &settings->imapaint;
1051         bool enabled = false;
1052
1053         for (win = wm->windows.first; win; win = win->next)
1054                 for (sa = win->screen->areabase.first; sa; sa = sa->next)
1055                         if (sa->spacetype == SPACE_IMAGE)
1056                                 if (((SpaceImage *)sa->spacedata.first)->mode == SI_MODE_PAINT)
1057                                         enabled = true;
1058
1059         if (enabled) {
1060                 BKE_paint_init(&imapaint->paint, PAINT_CURSOR_TEXTURE_PAINT);
1061
1062                 paint_cursor_start_explicit(&imapaint->paint, wm, image_paint_poll);
1063         }
1064         else {
1065                 paint_cursor_delete_textures();
1066         }
1067 }
1068
1069 /************************ grab clone operator ************************/
1070
1071 typedef struct GrabClone {
1072         float startoffset[2];
1073         int startx, starty;
1074 } GrabClone;
1075
1076 static void grab_clone_apply(bContext *C, wmOperator *op)
1077 {
1078         Brush *brush = image_paint_brush(C);
1079         float delta[2];
1080
1081         RNA_float_get_array(op->ptr, "delta", delta);
1082         add_v2_v2(brush->clone.offset, delta);
1083         ED_region_tag_redraw(CTX_wm_region(C));
1084 }
1085
1086 static int grab_clone_exec(bContext *C, wmOperator *op)
1087 {
1088         grab_clone_apply(C, op);
1089
1090         return OPERATOR_FINISHED;
1091 }
1092
1093 static int grab_clone_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1094 {
1095         Brush *brush = image_paint_brush(C);
1096         GrabClone *cmv;
1097
1098         cmv = MEM_callocN(sizeof(GrabClone), "GrabClone");
1099         copy_v2_v2(cmv->startoffset, brush->clone.offset);
1100         cmv->startx = event->x;
1101         cmv->starty = event->y;
1102         op->customdata = cmv;
1103
1104         WM_event_add_modal_handler(C, op);
1105
1106         return OPERATOR_RUNNING_MODAL;
1107 }
1108
1109 static int grab_clone_modal(bContext *C, wmOperator *op, const wmEvent *event)
1110 {
1111         Brush *brush = image_paint_brush(C);
1112         ARegion *ar = CTX_wm_region(C);
1113         GrabClone *cmv = op->customdata;
1114         float startfx, startfy, fx, fy, delta[2];
1115         int xmin = ar->winrct.xmin, ymin = ar->winrct.ymin;
1116
1117         switch (event->type) {
1118                 case LEFTMOUSE:
1119                 case MIDDLEMOUSE:
1120                 case RIGHTMOUSE: // XXX hardcoded
1121                         MEM_freeN(op->customdata);
1122                         return OPERATOR_FINISHED;
1123                 case MOUSEMOVE:
1124                         /* mouse moved, so move the clone image */
1125                         UI_view2d_region_to_view(&ar->v2d, cmv->startx - xmin, cmv->starty - ymin, &startfx, &startfy);
1126                         UI_view2d_region_to_view(&ar->v2d, event->x - xmin, event->y - ymin, &fx, &fy);
1127
1128                         delta[0] = fx - startfx;
1129                         delta[1] = fy - startfy;
1130                         RNA_float_set_array(op->ptr, "delta", delta);
1131
1132                         copy_v2_v2(brush->clone.offset, cmv->startoffset);
1133
1134                         grab_clone_apply(C, op);
1135                         break;
1136         }
1137
1138         return OPERATOR_RUNNING_MODAL;
1139 }
1140
1141 static void grab_clone_cancel(bContext *UNUSED(C), wmOperator *op)
1142 {
1143         MEM_freeN(op->customdata);
1144 }
1145
1146 void PAINT_OT_grab_clone(wmOperatorType *ot)
1147 {
1148         /* identifiers */
1149         ot->name = "Grab Clone";
1150         ot->idname = "PAINT_OT_grab_clone";
1151         ot->description = "Move the clone source image";
1152         
1153         /* api callbacks */
1154         ot->exec = grab_clone_exec;
1155         ot->invoke = grab_clone_invoke;
1156         ot->modal = grab_clone_modal;
1157         ot->cancel = grab_clone_cancel;
1158         ot->poll = image_paint_2d_clone_poll;
1159
1160         /* flags */
1161         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
1162
1163         /* properties */
1164         RNA_def_float_vector(ot->srna, "delta", 2, NULL, -FLT_MAX, FLT_MAX, "Delta", "Delta offset of clone image in 0.0..1.0 coordinates", -1.0f, 1.0f);
1165 }
1166
1167 /******************** sample color operator ********************/
1168 typedef struct {
1169         bool show_cursor;
1170         short event_type;
1171         float initcolor[3];
1172         bool sample_palette;
1173 }       SampleColorData;
1174
1175
1176 static void sample_color_update_header(SampleColorData *data, bContext *C)
1177 {
1178 #define HEADER_LENGTH 150
1179         char msg[HEADER_LENGTH];
1180         ScrArea *sa = CTX_wm_area(C);
1181
1182         if (sa) {
1183                 BLI_snprintf(msg, HEADER_LENGTH,
1184                              "Sample color for %s",
1185                              !data->sample_palette ?
1186                              "Brush. Use Left Click to sample for palette instead" :
1187                              "Palette. Use Left Click to sample more colors");
1188                 ED_area_headerprint(sa, msg);
1189         }
1190
1191 #undef HEADER_LENGTH
1192 }
1193
1194 static int sample_color_exec(bContext *C, wmOperator *op)
1195 {
1196         Paint *paint = BKE_paint_get_active_from_context(C);
1197         Brush *brush = BKE_paint_brush(paint);
1198         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1199         ARegion *ar = CTX_wm_region(C);
1200         wmWindow *win = CTX_wm_window(C);
1201         bool show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
1202         int location[2];
1203         bool use_palette;
1204         paint->flags &= ~PAINT_SHOW_BRUSH;
1205
1206         /* force redraw without cursor */
1207         WM_paint_cursor_tag_redraw(win, ar);
1208         WM_redraw_windows(C);
1209
1210         RNA_int_get_array(op->ptr, "location", location);
1211         use_palette = RNA_boolean_get(op->ptr, "palette");
1212
1213         paint_sample_color(C, ar, location[0], location[1], mode == PAINT_TEXTURE_PROJECTIVE, use_palette);
1214
1215         if (show_cursor) {
1216                 paint->flags |= PAINT_SHOW_BRUSH;
1217         }
1218
1219         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1220         
1221         return OPERATOR_FINISHED;
1222 }
1223
1224 static int sample_color_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1225 {
1226         Scene *scene = CTX_data_scene(C);
1227         Paint *paint = BKE_paint_get_active_from_context(C);
1228         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1229         Brush *brush = BKE_paint_brush(paint);
1230         SampleColorData *data = MEM_mallocN(sizeof(SampleColorData), "sample color custom data");
1231         ARegion *ar = CTX_wm_region(C);
1232         wmWindow *win = CTX_wm_window(C);
1233
1234         data->event_type = event->type;
1235         data->show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
1236         copy_v3_v3(data->initcolor, BKE_brush_color_get(scene, brush));
1237         data->sample_palette = false;
1238         op->customdata = data;
1239         paint->flags &= ~PAINT_SHOW_BRUSH;
1240
1241         sample_color_update_header(data, C);
1242
1243         WM_event_add_modal_handler(C, op);
1244
1245         /* force redraw without cursor */
1246         WM_paint_cursor_tag_redraw(win, ar);
1247         WM_redraw_windows(C);
1248
1249         RNA_int_set_array(op->ptr, "location", event->mval);
1250
1251         paint_sample_color(C, ar, event->mval[0], event->mval[1], mode == PAINT_TEXTURE_PROJECTIVE, false);
1252         WM_cursor_modal_set(win, BC_EYEDROPPER_CURSOR);
1253
1254         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1255
1256         return OPERATOR_RUNNING_MODAL;
1257 }
1258
1259 static int sample_color_modal(bContext *C, wmOperator *op, const wmEvent *event)
1260 {
1261         Scene *scene = CTX_data_scene(C);
1262         SampleColorData *data = op->customdata;
1263         Paint *paint = BKE_paint_get_active_from_context(C);
1264         Brush *brush = BKE_paint_brush(paint);
1265         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1266
1267         if ((event->type == data->event_type) && (event->val == KM_RELEASE)) {
1268                 ScrArea *sa = CTX_wm_area(C);
1269
1270                 if (data->show_cursor) {
1271                         paint->flags |= PAINT_SHOW_BRUSH;
1272                 }
1273
1274                 if (data->sample_palette) {
1275                         BKE_brush_color_set(scene, brush, data->initcolor);
1276                         RNA_boolean_set(op->ptr, "palette", true);
1277                 }
1278                 WM_cursor_modal_restore(CTX_wm_window(C));
1279                 MEM_freeN(data);
1280                 ED_area_headerprint(sa, NULL);
1281
1282                 return OPERATOR_FINISHED;
1283         }
1284
1285         switch (event->type) {
1286                 case MOUSEMOVE:
1287                 {
1288                         ARegion *ar = CTX_wm_region(C);
1289                         RNA_int_set_array(op->ptr, "location", event->mval);
1290                         paint_sample_color(C, ar, event->mval[0], event->mval[1], mode == PAINT_TEXTURE_PROJECTIVE, false);
1291                         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1292                         break;
1293                 }
1294
1295                 case LEFTMOUSE:
1296                         if (event->val == KM_PRESS) {
1297                                 ARegion *ar = CTX_wm_region(C);
1298                                 RNA_int_set_array(op->ptr, "location", event->mval);
1299                                 paint_sample_color(C, ar, event->mval[0], event->mval[1], mode == PAINT_TEXTURE_PROJECTIVE, true);
1300                                 if (!data->sample_palette) {
1301                                         data->sample_palette = true;
1302                                         sample_color_update_header(data, C);
1303                                 }
1304                         }
1305                         break;
1306         }
1307
1308         return OPERATOR_RUNNING_MODAL;
1309 }
1310
1311 static int sample_color_poll(bContext *C)
1312 {
1313         return (image_paint_poll(C) || vertex_paint_poll(C));
1314 }
1315
1316 void PAINT_OT_sample_color(wmOperatorType *ot)
1317 {
1318         /* identifiers */
1319         ot->name = "Sample Color";
1320         ot->idname = "PAINT_OT_sample_color";
1321         ot->description = "Use the mouse to sample a color in the image";
1322         
1323         /* api callbacks */
1324         ot->exec = sample_color_exec;
1325         ot->invoke = sample_color_invoke;
1326         ot->modal = sample_color_modal;
1327         ot->poll = sample_color_poll;
1328
1329         /* flags */
1330         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1331
1332         /* properties */
1333         RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "Cursor location in region coordinates", 0, 16384);
1334         RNA_def_boolean(ot->srna, "palette", 0, "Palette", "Add color to palette");
1335 }
1336
1337 /******************** texture paint toggle operator ********************/
1338
1339 static int texture_paint_toggle_poll(bContext *C)
1340 {
1341         Object *ob = CTX_data_active_object(C);
1342         if (ob == NULL || ob->type != OB_MESH)
1343                 return 0;
1344         if (!ob->data || ((ID *)ob->data)->lib)
1345                 return 0;
1346         if (CTX_data_edit_object(C))
1347                 return 0;
1348
1349         return 1;
1350 }
1351
1352 static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
1353 {
1354         Scene *scene = CTX_data_scene(C);
1355         Object *ob = CTX_data_active_object(C);
1356         const int mode_flag = OB_MODE_TEXTURE_PAINT;
1357         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1358
1359         if (!is_mode_set) {
1360                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1361                         return OPERATOR_CANCELLED;
1362                 }
1363         }
1364
1365         if (ob->mode & mode_flag) {
1366                 ob->mode &= ~mode_flag;
1367
1368                 if (U.glreslimit != 0)
1369                         GPU_free_images();
1370                 GPU_paint_set_mipmap(1);
1371
1372                 toggle_paint_cursor(C, 0);
1373         }
1374         else {
1375                 bScreen *sc;
1376                 Main *bmain = CTX_data_main(C);
1377                 Image *ima = NULL;
1378                 ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
1379
1380                 /* This has to stay here to regenerate the texture paint
1381                  * cache in case we are loading a file */
1382                 BKE_texpaint_slots_refresh_object(scene, ob);
1383
1384                 paint_proj_mesh_data_ensure(C, ob, op);
1385
1386                 /* entering paint mode also sets image to editors */
1387                 if (imapaint->mode == IMAGEPAINT_MODE_MATERIAL) {
1388                         Material *ma = give_current_material(ob, ob->actcol); /* set the current material active paint slot on image editor */
1389
1390                         if (ma->texpaintslot)
1391                                 ima = ma->texpaintslot[ma->paint_active_slot].ima;
1392                 }
1393                 else if (imapaint->mode == IMAGEPAINT_MODE_MATERIAL) {
1394                         ima = imapaint->canvas;
1395                 }       
1396                 
1397                 for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1398                         ScrArea *sa;
1399                         for (sa = sc->areabase.first; sa; sa = sa->next) {
1400                                 SpaceLink *sl;
1401                                 for (sl = sa->spacedata.first; sl; sl = sl->next) {
1402                                         if (sl->spacetype == SPACE_IMAGE) {
1403                                                 SpaceImage *sima = (SpaceImage *)sl;
1404                                                 
1405                                                 if (!sima->pin)
1406                                                         ED_space_image_set(sima, scene, scene->obedit, ima);
1407                                         }
1408                                 }
1409                         }
1410                 }
1411                 
1412                 ob->mode |= mode_flag;
1413
1414                 BKE_paint_init(&scene->toolsettings->imapaint.paint, PAINT_CURSOR_TEXTURE_PAINT);
1415
1416                 if (U.glreslimit != 0)
1417                         GPU_free_images();
1418                 GPU_paint_set_mipmap(0);
1419
1420                 toggle_paint_cursor(C, 1);
1421         }
1422
1423         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1424         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1425
1426         return OPERATOR_FINISHED;
1427 }
1428
1429 void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
1430 {
1431         /* identifiers */
1432         ot->name = "Texture Paint Toggle";
1433         ot->idname = "PAINT_OT_texture_paint_toggle";
1434         ot->description = "Toggle texture paint mode in 3D view";
1435         
1436         /* api callbacks */
1437         ot->exec = texture_paint_toggle_exec;
1438         ot->poll = texture_paint_toggle_poll;
1439
1440         /* flags */
1441         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1442 }
1443
1444
1445 static int brush_colors_flip_exec(bContext *C, wmOperator *UNUSED(op))
1446 {
1447         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1448         Brush *br = image_paint_brush(C);
1449         if (ups->flag & UNIFIED_PAINT_COLOR) {
1450                 swap_v3_v3(ups->rgb, ups->secondary_rgb);
1451         }
1452         else if (br) {
1453                 swap_v3_v3(br->rgb, br->secondary_rgb);
1454         }
1455         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, br);
1456
1457         return OPERATOR_FINISHED;
1458 }
1459
1460 static int brush_colors_flip_poll(bContext *C)
1461 {
1462         if (image_paint_poll(C)) {
1463                 Brush *br = image_paint_brush(C);
1464                 if (br->imagepaint_tool == PAINT_TOOL_DRAW)
1465                         return 1;
1466         }
1467
1468         return 0;
1469 }
1470
1471 void PAINT_OT_brush_colors_flip(wmOperatorType *ot)
1472 {
1473         /* identifiers */
1474         ot->name = "Brush Colors Flip";
1475         ot->idname = "PAINT_OT_brush_colors_flip";
1476         ot->description = "Toggle foreground and background brush colors";
1477
1478         /* api callbacks */
1479         ot->exec = brush_colors_flip_exec;
1480         ot->poll = brush_colors_flip_poll;
1481
1482         /* flags */
1483         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1484 }
1485
1486
1487 void ED_imapaint_bucket_fill(struct bContext *C, float color[3], wmOperator *op)
1488 {
1489         SpaceImage *sima = CTX_wm_space_image(C);
1490         Image *ima = sima->image;
1491
1492         ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
1493                               ED_image_undo_restore, ED_image_undo_free, NULL);
1494
1495         paint_2d_bucket_fill(C, color, NULL, NULL, NULL);
1496
1497         ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
1498
1499         DAG_id_tag_update(&ima->id, 0);
1500 }
1501
1502
1503 static int texture_paint_poll(bContext *C)
1504 {
1505         if (texture_paint_toggle_poll(C))
1506                 if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT)
1507                         return 1;
1508         
1509         return 0;
1510 }
1511
1512 int image_texture_paint_poll(bContext *C)
1513 {
1514         return (texture_paint_poll(C) || image_paint_poll(C));
1515 }
1516
1517 int facemask_paint_poll(bContext *C)
1518 {
1519         return BKE_paint_select_face_test(CTX_data_active_object(C));
1520 }
1521
1522 int vert_paint_poll(bContext *C)
1523 {
1524         return BKE_paint_select_vert_test(CTX_data_active_object(C));
1525 }
1526
1527 int mask_paint_poll(bContext *C)
1528 {
1529         return BKE_paint_select_elem_test(CTX_data_active_object(C));
1530 }
1531