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