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