f0c9c023876b249c23e937e506bfe8d90ee2b7b9
[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                         break;
568         }
569
570         return kernel;
571 }
572
573 void paint_delete_blur_kernel(BlurKernel *kernel)
574 {
575         if (kernel->wdata)
576                 MEM_freeN(kernel->wdata);
577 }
578
579 /************************ image paint poll ************************/
580
581 static Brush *image_paint_brush(bContext *C)
582 {
583         Scene *scene = CTX_data_scene(C);
584         ToolSettings *settings = scene->toolsettings;
585
586         return BKE_paint_brush(&settings->imapaint.paint);
587 }
588
589 static int image_paint_poll(bContext *C)
590 {
591         Object *obact;
592
593         if (!image_paint_brush(C))
594                 return 0;
595
596         obact = CTX_data_active_object(C);
597         if ((obact && obact->mode & OB_MODE_TEXTURE_PAINT) && CTX_wm_region_view3d(C)) {
598                 return 1;
599         }
600         else {
601                 SpaceImage *sima = CTX_wm_space_image(C);
602
603                 if (sima) {
604                         ARegion *ar = CTX_wm_region(C);
605
606                         if ((sima->mode == SI_MODE_PAINT) && ar->regiontype == RGN_TYPE_WINDOW) {
607                                 return 1;
608                         }
609                 }
610         }
611
612         return 0;
613 }
614
615 static int image_paint_2d_clone_poll(bContext *C)
616 {
617         Brush *brush = image_paint_brush(C);
618
619         if (!CTX_wm_region_view3d(C) && image_paint_poll(C))
620                 if (brush && (brush->imagepaint_tool == PAINT_TOOL_CLONE))
621                         if (brush->clone.image)
622                                 return 1;
623         
624         return 0;
625 }
626
627 /************************ paint operator ************************/
628 typedef enum TexPaintMode {
629         PAINT_MODE_2D,
630         PAINT_MODE_3D_PROJECT
631 } TexPaintMode;
632
633 typedef struct PaintOperation {
634         TexPaintMode mode;
635
636         void *custom_paint;
637
638         float prevmouse[2];
639         float startmouse[2];
640         double starttime;
641
642         void *cursor;
643         ViewContext vc;
644 } PaintOperation;
645
646 bool paint_use_opacity_masking(Brush *brush)
647 {
648         return (brush->flag & BRUSH_AIRBRUSH) ||
649                (brush->flag & BRUSH_DRAG_DOT) ||
650                (brush->flag & BRUSH_ANCHORED) ||
651                (brush->imagepaint_tool == PAINT_TOOL_SMEAR) ||
652                (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) ||
653                (brush->imagepaint_tool == PAINT_TOOL_FILL) ||
654                (brush->flag & BRUSH_USE_GRADIENT) ||
655                    (brush->mtex.tex && !ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)) ?
656                     false : true;
657 }
658
659 void paint_brush_color_get(struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance,
660                            float pressure, float color[3], struct ColorManagedDisplay *display)
661 {
662         if (invert)
663                 copy_v3_v3(color, BKE_brush_secondary_color_get(scene, br));
664         else {
665                 if (br->flag & BRUSH_USE_GRADIENT) {
666                         float color_gr[4];
667                         switch (br->gradient_stroke_mode) {
668                                 case BRUSH_GRADIENT_PRESSURE:
669                                         do_colorband(br->gradient, pressure, color_gr);
670                                         break;
671                                 case BRUSH_GRADIENT_SPACING_REPEAT:
672                                 {
673                                         float coord = fmod(distance / br->gradient_spacing, 1.0);
674                                         do_colorband(br->gradient, coord, color_gr);
675                                         break;
676                                 }
677                                 case BRUSH_GRADIENT_SPACING_CLAMP:
678                                 {
679                                         do_colorband(br->gradient, distance / br->gradient_spacing, color_gr);
680                                         break;
681                                 }
682                         }
683                         copy_v3_v3(color, color_gr);
684                 }
685                 else
686                         copy_v3_v3(color, BKE_brush_color_get(scene, br));
687         }
688         if (color_correction)
689                 IMB_colormanagement_display_to_scene_linear_v3(color, display);
690 }
691
692 void paint_brush_init_tex(Brush *brush)
693 {
694         /* init mtex nodes */
695         if (brush) {
696                 MTex *mtex = &brush->mtex;
697                 if (mtex->tex && mtex->tex->nodetree)
698                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
699                 mtex = &brush->mask_mtex;
700                 if (mtex->tex && mtex->tex->nodetree)
701                         ntreeTexBeginExecTree(mtex->tex->nodetree);
702         }
703 }
704
705 void paint_brush_exit_tex(Brush *brush)
706 {
707         if (brush) {
708                 MTex *mtex = &brush->mtex;
709                 if (mtex->tex && mtex->tex->nodetree)
710                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
711                 mtex = &brush->mask_mtex;
712                 if (mtex->tex && mtex->tex->nodetree)
713                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
714         }
715 }
716
717 static void gradient_draw_line(bContext *UNUSED(C), int x, int y, void *customdata)
718 {
719         PaintOperation *pop = (PaintOperation *)customdata;
720
721         if (pop) {
722                 glEnable(GL_LINE_SMOOTH);
723                 glEnable(GL_BLEND);
724
725                 glLineWidth(4.0);
726                 glColor4ub(0, 0, 0, 255);
727                 sdrawline(x, y, pop->startmouse[0], pop->startmouse[1]);
728                 glLineWidth(2.0);
729                 glColor4ub(255, 255, 255, 255);
730                 sdrawline(x, y, pop->startmouse[0], pop->startmouse[1]);
731                 glLineWidth(1.0);
732
733                 glDisable(GL_BLEND);
734                 glDisable(GL_LINE_SMOOTH);
735         }
736 }
737
738
739 static PaintOperation *texture_paint_init(bContext *C, wmOperator *op, const float mouse[2])
740 {
741         Scene *scene = CTX_data_scene(C);
742         ToolSettings *settings = scene->toolsettings;
743         PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
744         Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
745         int mode = RNA_enum_get(op->ptr, "mode");
746         view3d_set_viewcontext(C, &pop->vc);
747
748         copy_v2_v2(pop->prevmouse, mouse);
749         copy_v2_v2(pop->startmouse, mouse);
750
751         /* initialize from context */
752         if (CTX_wm_region_view3d(C)) {
753                 Object *ob = OBACT;
754                 bool uvs, mat, tex, stencil;
755                 if (!BKE_paint_proj_mesh_data_check(scene, ob, &uvs, &mat, &tex, &stencil)) {
756                         BKE_paint_data_warning(op->reports, uvs, mat, tex, stencil);
757                         MEM_freeN(pop);
758                         WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);
759                         return NULL;                    
760                 }
761                 pop->mode = PAINT_MODE_3D_PROJECT;
762                 pop->custom_paint = paint_proj_new_stroke(C, ob, mouse, mode);
763         }
764         else {
765                 pop->mode = PAINT_MODE_2D;
766                 pop->custom_paint = paint_2d_new_stroke(C, op, mode);
767         }
768
769         if (!pop->custom_paint) {
770                 MEM_freeN(pop);
771                 return NULL;
772         }
773
774         if ((brush->imagepaint_tool == PAINT_TOOL_FILL) && (brush->flag & BRUSH_USE_GRADIENT)) {
775                 pop->cursor = WM_paint_cursor_activate(CTX_wm_manager(C), image_paint_poll, gradient_draw_line, pop);
776         }
777         
778         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
779         ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
780                                  ED_image_undo_restore, ED_image_undo_free, NULL);
781
782         return pop;
783 }
784
785 /* restore painting image to previous state. Used for anchored and drag-dot style brushes*/
786 static void paint_stroke_restore(void)
787 {
788         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
789         image_undo_restore_runtime(lb);
790         image_undo_invalidate();
791 }
792
793 static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
794 {
795         PaintOperation *pop = paint_stroke_mode_data(stroke);
796         Scene *scene = CTX_data_scene(C);
797         ToolSettings *toolsettings = CTX_data_tool_settings(C);
798         UnifiedPaintSettings *ups = &toolsettings->unified_paint_settings;
799         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
800
801         float alphafac = (brush->flag & BRUSH_ACCUMULATE) ? ups->overlap_factor : 1.0f;
802
803         /* initial brush values. Maybe it should be considered moving these to stroke system */
804         float startalpha = BKE_brush_alpha_get(scene, brush);
805
806         float mouse[2];
807         float pressure;
808         float size;
809         float distance = paint_stroke_distance_get(stroke);
810         int eraser;
811
812         RNA_float_get_array(itemptr, "mouse", mouse);
813         pressure = RNA_float_get(itemptr, "pressure");
814         eraser = RNA_boolean_get(itemptr, "pen_flip");
815         size = max_ff(1.0f, RNA_float_get(itemptr, "size"));
816
817         /* stroking with fill tool only acts on stroke end */
818         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
819                 copy_v2_v2(pop->prevmouse, mouse);
820                 return;
821         }
822
823         if (BKE_brush_use_alpha_pressure(scene, brush))
824                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * pressure * alphafac));
825         else
826                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * alphafac));
827
828         if ((brush->flag & BRUSH_DRAG_DOT) || (brush->flag & BRUSH_ANCHORED)) {
829                 paint_stroke_restore();
830         }
831
832         if (pop->mode == PAINT_MODE_3D_PROJECT) {
833                 paint_proj_stroke(C, pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
834         }
835         else {
836                 paint_2d_stroke(pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
837         }
838
839         copy_v2_v2(pop->prevmouse, mouse);
840
841         /* restore brush values */
842         BKE_brush_alpha_set(scene, brush, startalpha);
843 }
844
845 static void paint_stroke_redraw(const bContext *C, struct PaintStroke *stroke, bool final)
846 {
847         PaintOperation *pop = paint_stroke_mode_data(stroke);
848
849         if (pop->mode == PAINT_MODE_3D_PROJECT) {
850                 paint_proj_redraw(C, pop->custom_paint, final);
851         }
852         else {
853                 paint_2d_redraw(C, pop->custom_paint, final);
854         }
855 }
856
857 static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke)
858 {
859         Scene *scene = CTX_data_scene(C);
860         ToolSettings *toolsettings = scene->toolsettings;
861         PaintOperation *pop = paint_stroke_mode_data(stroke);
862         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
863
864         toolsettings->imapaint.flag &= ~IMAGEPAINT_DRAWING;
865
866         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
867                 if (brush->flag & BRUSH_USE_GRADIENT) {
868                         if (pop->mode == PAINT_MODE_2D) {
869                                 paint_2d_gradient_fill(C, brush, pop->startmouse, pop->prevmouse, pop->custom_paint);
870                         }
871                         else {
872                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
873                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
874                                 /* two redraws, one for GPU update, one for notification */
875                                 paint_proj_redraw(C, pop->custom_paint, false);
876                                 paint_proj_redraw(C, pop->custom_paint, true);
877                         }
878                 }
879                 else {
880                         if (pop->mode == PAINT_MODE_2D) {
881                                 float color[3];
882
883                                 srgb_to_linearrgb_v3_v3(color, BKE_brush_color_get(scene, brush));
884                                 paint_2d_bucket_fill(C, color, brush, pop->prevmouse, pop->custom_paint);
885                         }
886                         else {
887                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
888                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
889                                 /* two redraws, one for GPU update, one for notification */
890                                 paint_proj_redraw(C, pop->custom_paint, false);
891                                 paint_proj_redraw(C, pop->custom_paint, true);
892                         }
893                 }
894         }
895         if (pop->mode == PAINT_MODE_3D_PROJECT) {
896                 paint_proj_stroke_done(pop->custom_paint);
897         }
898         else {
899                 paint_2d_stroke_done(pop->custom_paint);
900         }
901
902         if (pop->cursor) {
903                 WM_paint_cursor_end(CTX_wm_manager(C), pop->cursor);
904         }
905
906         image_undo_end();
907
908         /* duplicate warning, see texpaint_init */
909 #if 0
910         if (pop->s.warnmultifile)
911                 BKE_reportf(op->reports, RPT_WARNING, "Image requires 4 color channels to paint: %s", pop->s.warnmultifile);
912         if (pop->s.warnpackedfile)
913                 BKE_reportf(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted: %s", pop->s.warnpackedfile);
914 #endif
915         MEM_freeN(pop);
916 }
917
918 static bool paint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
919 {
920         PaintOperation *pop;
921
922         /* TODO Should avoid putting this here. Instead, last position should be requested
923          * from stroke system. */
924
925         if (!(pop = texture_paint_init(C, op, mouse))) {
926                 return false;
927         }
928
929         paint_stroke_set_mode_data(op->customdata, pop);
930
931         return true;
932 }
933
934
935 static int paint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
936 {
937         int retval;
938
939         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
940                                           paint_stroke_update_step,
941                                           paint_stroke_redraw,
942                                           paint_stroke_done, event->type);
943
944         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
945                 paint_stroke_data_free(op);
946                 return OPERATOR_FINISHED;
947         }
948         /* add modal handler */
949         WM_event_add_modal_handler(C, op);
950
951         OPERATOR_RETVAL_CHECK(retval);
952         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
953
954         return OPERATOR_RUNNING_MODAL;
955 }
956
957 static int paint_exec(bContext *C, wmOperator *op)
958 {
959         PaintOperation *pop;
960         PropertyRNA *strokeprop;
961         PointerRNA firstpoint;
962         float mouse[2];
963
964         strokeprop = RNA_struct_find_property(op->ptr, "stroke");
965
966         if (!RNA_property_collection_lookup_int(op->ptr, strokeprop, 0, &firstpoint))
967                 return OPERATOR_CANCELLED;
968
969         RNA_float_get_array(&firstpoint, "mouse", mouse);
970
971         if (!(pop = texture_paint_init(C, op, mouse))) {
972                 return OPERATOR_CANCELLED;
973         }
974
975         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
976                                           paint_stroke_update_step,
977                                           paint_stroke_redraw,
978                                           paint_stroke_done, 0);
979         /* frees op->customdata */
980         paint_stroke_exec(C, op);
981
982         return OPERATOR_FINISHED;
983 }
984
985 void PAINT_OT_image_paint(wmOperatorType *ot)
986 {
987         /* identifiers */
988         ot->name = "Image Paint";
989         ot->idname = "PAINT_OT_image_paint";
990         ot->description = "Paint a stroke into the image";
991
992         /* api callbacks */
993         ot->invoke = paint_invoke;
994         ot->modal = paint_stroke_modal;
995         ot->exec = paint_exec;
996         ot->poll = image_paint_poll;
997         ot->cancel = paint_stroke_cancel;
998
999         /* flags */
1000         ot->flag = OPTYPE_BLOCKING;
1001
1002         paint_stroke_operator_properties(ot);
1003 }
1004
1005
1006 int get_imapaint_zoom(bContext *C, float *zoomx, float *zoomy)
1007 {
1008         RegionView3D *rv3d = CTX_wm_region_view3d(C);
1009
1010         if (!rv3d) {
1011                 SpaceImage *sima = CTX_wm_space_image(C);
1012
1013                 if (sima->mode == SI_MODE_PAINT) {
1014                         ARegion *ar = CTX_wm_region(C);
1015                         ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
1016
1017                         return 1;
1018                 }
1019         }
1020
1021         *zoomx = *zoomy = 1;
1022
1023         return 0;
1024 }
1025
1026 /************************ cursor drawing *******************************/
1027
1028 static void toggle_paint_cursor(bContext *C, int enable)
1029 {
1030         wmWindowManager *wm = CTX_wm_manager(C);
1031         Scene *scene = CTX_data_scene(C);
1032         ToolSettings *settings = scene->toolsettings;
1033
1034         if (settings->imapaint.paintcursor && !enable) {
1035                 WM_paint_cursor_end(wm, settings->imapaint.paintcursor);
1036                 settings->imapaint.paintcursor = NULL;
1037                 paint_cursor_delete_textures();
1038         }
1039         else if (enable)
1040                 paint_cursor_start(C, image_paint_poll);
1041 }
1042
1043 /* enable the paint cursor if it isn't already.
1044  *
1045  * purpose is to make sure the paint cursor is shown if paint
1046  * mode is enabled in the image editor. the paint poll will
1047  * ensure that the cursor is hidden when not in paint mode */
1048 void ED_space_image_paint_update(wmWindowManager *wm, Scene *scene)
1049 {
1050         ToolSettings *settings = scene->toolsettings;
1051         wmWindow *win;
1052         ScrArea *sa;
1053         ImagePaintSettings *imapaint = &settings->imapaint;
1054         bool enabled = false;
1055
1056         for (win = wm->windows.first; win; win = win->next)
1057                 for (sa = win->screen->areabase.first; sa; sa = sa->next)
1058                         if (sa->spacetype == SPACE_IMAGE)
1059                                 if (((SpaceImage *)sa->spacedata.first)->mode == SI_MODE_PAINT)
1060                                         enabled = true;
1061
1062         if (enabled) {
1063                 BKE_paint_init(scene, ePaintTexture2D, PAINT_CURSOR_TEXTURE_PAINT);
1064
1065                 paint_cursor_start_explicit(&imapaint->paint, wm, image_paint_poll);
1066         }
1067         else {
1068                 paint_cursor_delete_textures();
1069         }
1070 }
1071
1072 /************************ grab clone operator ************************/
1073
1074 typedef struct GrabClone {
1075         float startoffset[2];
1076         int startx, starty;
1077 } GrabClone;
1078
1079 static void grab_clone_apply(bContext *C, wmOperator *op)
1080 {
1081         Brush *brush = image_paint_brush(C);
1082         float delta[2];
1083
1084         RNA_float_get_array(op->ptr, "delta", delta);
1085         add_v2_v2(brush->clone.offset, delta);
1086         ED_region_tag_redraw(CTX_wm_region(C));
1087 }
1088
1089 static int grab_clone_exec(bContext *C, wmOperator *op)
1090 {
1091         grab_clone_apply(C, op);
1092
1093         return OPERATOR_FINISHED;
1094 }
1095
1096 static int grab_clone_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1097 {
1098         Brush *brush = image_paint_brush(C);
1099         GrabClone *cmv;
1100
1101         cmv = MEM_callocN(sizeof(GrabClone), "GrabClone");
1102         copy_v2_v2(cmv->startoffset, brush->clone.offset);
1103         cmv->startx = event->x;
1104         cmv->starty = event->y;
1105         op->customdata = cmv;
1106
1107         WM_event_add_modal_handler(C, op);
1108
1109         return OPERATOR_RUNNING_MODAL;
1110 }
1111
1112 static int grab_clone_modal(bContext *C, wmOperator *op, const wmEvent *event)
1113 {
1114         Brush *brush = image_paint_brush(C);
1115         ARegion *ar = CTX_wm_region(C);
1116         GrabClone *cmv = op->customdata;
1117         float startfx, startfy, fx, fy, delta[2];
1118         int xmin = ar->winrct.xmin, ymin = ar->winrct.ymin;
1119
1120         switch (event->type) {
1121                 case LEFTMOUSE:
1122                 case MIDDLEMOUSE:
1123                 case RIGHTMOUSE: // XXX hardcoded
1124                         MEM_freeN(op->customdata);
1125                         return OPERATOR_FINISHED;
1126                 case MOUSEMOVE:
1127                         /* mouse moved, so move the clone image */
1128                         UI_view2d_region_to_view(&ar->v2d, cmv->startx - xmin, cmv->starty - ymin, &startfx, &startfy);
1129                         UI_view2d_region_to_view(&ar->v2d, event->x - xmin, event->y - ymin, &fx, &fy);
1130
1131                         delta[0] = fx - startfx;
1132                         delta[1] = fy - startfy;
1133                         RNA_float_set_array(op->ptr, "delta", delta);
1134
1135                         copy_v2_v2(brush->clone.offset, cmv->startoffset);
1136
1137                         grab_clone_apply(C, op);
1138                         break;
1139         }
1140
1141         return OPERATOR_RUNNING_MODAL;
1142 }
1143
1144 static void grab_clone_cancel(bContext *UNUSED(C), wmOperator *op)
1145 {
1146         MEM_freeN(op->customdata);
1147 }
1148
1149 void PAINT_OT_grab_clone(wmOperatorType *ot)
1150 {
1151         /* identifiers */
1152         ot->name = "Grab Clone";
1153         ot->idname = "PAINT_OT_grab_clone";
1154         ot->description = "Move the clone source image";
1155         
1156         /* api callbacks */
1157         ot->exec = grab_clone_exec;
1158         ot->invoke = grab_clone_invoke;
1159         ot->modal = grab_clone_modal;
1160         ot->cancel = grab_clone_cancel;
1161         ot->poll = image_paint_2d_clone_poll;
1162
1163         /* flags */
1164         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
1165
1166         /* properties */
1167         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);
1168 }
1169
1170 /******************** sample color operator ********************/
1171 typedef struct {
1172         bool show_cursor;
1173         short event_type;
1174         float initcolor[3];
1175         bool sample_palette;
1176 }       SampleColorData;
1177
1178
1179 static void sample_color_update_header(SampleColorData *data, bContext *C)
1180 {
1181 #define HEADER_LENGTH 150
1182         char msg[HEADER_LENGTH];
1183         ScrArea *sa = CTX_wm_area(C);
1184
1185         if (sa) {
1186                 BLI_snprintf(msg, HEADER_LENGTH,
1187                              "Sample color for %s",
1188                              !data->sample_palette ?
1189                              "Brush. Use Left Click to sample for palette instead" :
1190                              "Palette. Use Left Click to sample more colors");
1191                 ED_area_headerprint(sa, msg);
1192         }
1193
1194 #undef HEADER_LENGTH
1195 }
1196
1197 static int sample_color_exec(bContext *C, wmOperator *op)
1198 {
1199         Paint *paint = BKE_paint_get_active_from_context(C);
1200         Brush *brush = BKE_paint_brush(paint);
1201         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1202         ARegion *ar = CTX_wm_region(C);
1203         wmWindow *win = CTX_wm_window(C);
1204         bool show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
1205         int location[2];
1206         bool use_palette;
1207         paint->flags &= ~PAINT_SHOW_BRUSH;
1208
1209         /* force redraw without cursor */
1210         WM_paint_cursor_tag_redraw(win, ar);
1211         WM_redraw_windows(C);
1212
1213         RNA_int_get_array(op->ptr, "location", location);
1214         use_palette = RNA_boolean_get(op->ptr, "palette");
1215
1216         paint_sample_color(C, ar, location[0], location[1], mode == ePaintTextureProjective, use_palette);
1217
1218         if (show_cursor) {
1219                 paint->flags |= PAINT_SHOW_BRUSH;
1220         }
1221
1222         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1223         
1224         return OPERATOR_FINISHED;
1225 }
1226
1227 static int sample_color_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1228 {
1229         Scene *scene = CTX_data_scene(C);
1230         Paint *paint = BKE_paint_get_active_from_context(C);
1231         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1232         Brush *brush = BKE_paint_brush(paint);
1233         SampleColorData *data = MEM_mallocN(sizeof(SampleColorData), "sample color custom data");
1234         ARegion *ar = CTX_wm_region(C);
1235         wmWindow *win = CTX_wm_window(C);
1236
1237         data->event_type = event->type;
1238         data->show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
1239         copy_v3_v3(data->initcolor, BKE_brush_color_get(scene, brush));
1240         data->sample_palette = false;
1241         op->customdata = data;
1242         paint->flags &= ~PAINT_SHOW_BRUSH;
1243
1244         sample_color_update_header(data, C);
1245
1246         WM_event_add_modal_handler(C, op);
1247
1248         /* force redraw without cursor */
1249         WM_paint_cursor_tag_redraw(win, ar);
1250         WM_redraw_windows(C);
1251
1252         RNA_int_set_array(op->ptr, "location", event->mval);
1253
1254         paint_sample_color(C, ar, event->mval[0], event->mval[1], mode == ePaintTextureProjective, false);
1255         WM_cursor_modal_set(win, BC_EYEDROPPER_CURSOR);
1256
1257         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1258
1259         return OPERATOR_RUNNING_MODAL;
1260 }
1261
1262 static int sample_color_modal(bContext *C, wmOperator *op, const wmEvent *event)
1263 {
1264         Scene *scene = CTX_data_scene(C);
1265         SampleColorData *data = op->customdata;
1266         Paint *paint = BKE_paint_get_active_from_context(C);
1267         Brush *brush = BKE_paint_brush(paint);
1268         PaintMode mode = BKE_paintmode_get_active_from_context(C);
1269
1270         if ((event->type == data->event_type) && (event->val == KM_RELEASE)) {
1271                 ScrArea *sa = CTX_wm_area(C);
1272
1273                 if (data->show_cursor) {
1274                         paint->flags |= PAINT_SHOW_BRUSH;
1275                 }
1276
1277                 if (data->sample_palette) {
1278                         BKE_brush_color_set(scene, brush, data->initcolor);
1279                         RNA_boolean_set(op->ptr, "palette", true);
1280                 }
1281                 WM_cursor_modal_restore(CTX_wm_window(C));
1282                 MEM_freeN(data);
1283                 ED_area_headerprint(sa, NULL);
1284
1285                 return OPERATOR_FINISHED;
1286         }
1287
1288         switch (event->type) {
1289                 case MOUSEMOVE:
1290                 {
1291                         ARegion *ar = CTX_wm_region(C);
1292                         RNA_int_set_array(op->ptr, "location", event->mval);
1293                         paint_sample_color(C, ar, event->mval[0], event->mval[1], mode == ePaintTextureProjective, false);
1294                         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1295                         break;
1296                 }
1297
1298                 case LEFTMOUSE:
1299                         if (event->val == KM_PRESS) {
1300                                 ARegion *ar = CTX_wm_region(C);
1301                                 RNA_int_set_array(op->ptr, "location", event->mval);
1302                                 paint_sample_color(C, ar, event->mval[0], event->mval[1], mode == ePaintTextureProjective, true);
1303                                 if (!data->sample_palette) {
1304                                         data->sample_palette = true;
1305                                         sample_color_update_header(data, C);
1306                                 }
1307                                 WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1308                         }
1309                         break;
1310         }
1311
1312         return OPERATOR_RUNNING_MODAL;
1313 }
1314
1315 static int sample_color_poll(bContext *C)
1316 {
1317         return (image_paint_poll(C) || vertex_paint_poll(C));
1318 }
1319
1320 void PAINT_OT_sample_color(wmOperatorType *ot)
1321 {
1322         /* identifiers */
1323         ot->name = "Sample Color";
1324         ot->idname = "PAINT_OT_sample_color";
1325         ot->description = "Use the mouse to sample a color in the image";
1326         
1327         /* api callbacks */
1328         ot->exec = sample_color_exec;
1329         ot->invoke = sample_color_invoke;
1330         ot->modal = sample_color_modal;
1331         ot->poll = sample_color_poll;
1332
1333         /* flags */
1334         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1335
1336         /* properties */
1337         RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "Cursor location in region coordinates", 0, 16384);
1338         RNA_def_boolean(ot->srna, "palette", 0, "Palette", "Add color to palette");
1339 }
1340
1341 /******************** texture paint toggle operator ********************/
1342
1343 static int texture_paint_toggle_poll(bContext *C)
1344 {
1345         Object *ob = CTX_data_active_object(C);
1346         if (ob == NULL || ob->type != OB_MESH)
1347                 return 0;
1348         if (!ob->data || ((ID *)ob->data)->lib)
1349                 return 0;
1350         if (CTX_data_edit_object(C))
1351                 return 0;
1352
1353         return 1;
1354 }
1355
1356 static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
1357 {
1358         Scene *scene = CTX_data_scene(C);
1359         Object *ob = CTX_data_active_object(C);
1360         const int mode_flag = OB_MODE_TEXTURE_PAINT;
1361         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1362
1363         if (!is_mode_set) {
1364                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1365                         return OPERATOR_CANCELLED;
1366                 }
1367         }
1368
1369         if (ob->mode & mode_flag) {
1370                 ob->mode &= ~mode_flag;
1371
1372                 if (U.glreslimit != 0)
1373                         GPU_free_images();
1374                 GPU_paint_set_mipmap(1);
1375
1376                 toggle_paint_cursor(C, 0);
1377         }
1378         else {
1379                 bScreen *sc;
1380                 Main *bmain = CTX_data_main(C);
1381                 Image *ima = NULL;
1382                 ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
1383
1384                 /* This has to stay here to regenerate the texture paint
1385                  * cache in case we are loading a file */
1386                 BKE_texpaint_slots_refresh_object(scene, ob);
1387
1388                 BKE_paint_proj_mesh_data_check(scene, ob, NULL, NULL, NULL, NULL);
1389                 
1390                 /* entering paint mode also sets image to editors */
1391                 if (imapaint->mode == IMAGEPAINT_MODE_MATERIAL) {
1392                         Material *ma = give_current_material(ob, ob->actcol); /* set the current material active paint slot on image editor */
1393
1394                         if (ma && ma->texpaintslot)
1395                                 ima = ma->texpaintslot[ma->paint_active_slot].ima;
1396                 }
1397                 else if (imapaint->mode == IMAGEPAINT_MODE_IMAGE) {
1398                         ima = imapaint->canvas;
1399                 }       
1400                 
1401                 if (ima) {
1402                         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1403                                 ScrArea *sa;
1404                                 for (sa = sc->areabase.first; sa; sa = sa->next) {
1405                                         SpaceLink *sl;
1406                                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
1407                                                 if (sl->spacetype == SPACE_IMAGE) {
1408                                                         SpaceImage *sima = (SpaceImage *)sl;
1409                                                         
1410                                                         if (!sima->pin)
1411                                                                 ED_space_image_set(sima, scene, scene->obedit, ima);
1412                                                 }
1413                                         }
1414                                 }
1415                         }
1416                 }
1417                 
1418                 ob->mode |= mode_flag;
1419
1420                 BKE_paint_init(scene, ePaintTextureProjective, PAINT_CURSOR_TEXTURE_PAINT);
1421
1422                 if (U.glreslimit != 0)
1423                         GPU_free_images();
1424                 GPU_paint_set_mipmap(0);
1425
1426                 toggle_paint_cursor(C, 1);
1427         }
1428
1429         GPU_drawobject_free(ob->derivedFinal);
1430         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1431
1432         return OPERATOR_FINISHED;
1433 }
1434
1435 void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
1436 {
1437         /* identifiers */
1438         ot->name = "Texture Paint Toggle";
1439         ot->idname = "PAINT_OT_texture_paint_toggle";
1440         ot->description = "Toggle texture paint mode in 3D view";
1441         
1442         /* api callbacks */
1443         ot->exec = texture_paint_toggle_exec;
1444         ot->poll = texture_paint_toggle_poll;
1445
1446         /* flags */
1447         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1448 }
1449
1450
1451 static int brush_colors_flip_exec(bContext *C, wmOperator *UNUSED(op))
1452 {
1453         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1454         Brush *br = image_paint_brush(C);
1455         if (ups->flag & UNIFIED_PAINT_COLOR) {
1456                 swap_v3_v3(ups->rgb, ups->secondary_rgb);
1457         }
1458         else if (br) {
1459                 swap_v3_v3(br->rgb, br->secondary_rgb);
1460         }
1461         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, br);
1462
1463         return OPERATOR_FINISHED;
1464 }
1465
1466 static int brush_colors_flip_poll(bContext *C)
1467 {
1468         if (image_paint_poll(C)) {
1469                 Brush *br = image_paint_brush(C);
1470                 if (br->imagepaint_tool == PAINT_TOOL_DRAW)
1471                         return 1;
1472         }
1473
1474         return 0;
1475 }
1476
1477 void PAINT_OT_brush_colors_flip(wmOperatorType *ot)
1478 {
1479         /* identifiers */
1480         ot->name = "Brush Colors Flip";
1481         ot->idname = "PAINT_OT_brush_colors_flip";
1482         ot->description = "Toggle foreground and background brush colors";
1483
1484         /* api callbacks */
1485         ot->exec = brush_colors_flip_exec;
1486         ot->poll = brush_colors_flip_poll;
1487
1488         /* flags */
1489         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1490 }
1491
1492
1493 void ED_imapaint_bucket_fill(struct bContext *C, float color[3], wmOperator *op)
1494 {
1495         SpaceImage *sima = CTX_wm_space_image(C);
1496         Image *ima = sima->image;
1497
1498         ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
1499                               ED_image_undo_restore, ED_image_undo_free, NULL);
1500
1501         paint_2d_bucket_fill(C, color, NULL, NULL, NULL);
1502
1503         ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
1504
1505         DAG_id_tag_update(&ima->id, 0);
1506 }
1507
1508
1509 static int texture_paint_poll(bContext *C)
1510 {
1511         if (texture_paint_toggle_poll(C))
1512                 if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT)
1513                         return 1;
1514         
1515         return 0;
1516 }
1517
1518 int image_texture_paint_poll(bContext *C)
1519 {
1520         return (texture_paint_poll(C) || image_paint_poll(C));
1521 }
1522
1523 int facemask_paint_poll(bContext *C)
1524 {
1525         return BKE_paint_select_face_test(CTX_data_active_object(C));
1526 }
1527
1528 int vert_paint_poll(bContext *C)
1529 {
1530         return BKE_paint_select_vert_test(CTX_data_active_object(C));
1531 }
1532
1533 int mask_paint_poll(bContext *C)
1534 {
1535         return BKE_paint_select_elem_test(CTX_data_active_object(C));
1536 }
1537