Merge branch 'master' into blender2.8
[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 #include "BLI_math.h"
40 #include "BLI_blenlib.h"
41 #include "BLI_utildefines.h"
42
43 #include "BLT_translation.h"
44
45 #include "IMB_imbuf.h"
46 #include "IMB_imbuf_types.h"
47
48 #include "DNA_brush_types.h"
49 #include "DNA_node_types.h"
50 #include "DNA_object_types.h"
51
52 #include "BKE_colorband.h"
53 #include "BKE_context.h"
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_brush.h"
56 #include "BKE_main.h"
57 #include "BKE_material.h"
58 #include "BKE_node.h"
59 #include "BKE_paint.h"
60 #include "BKE_undo_system.h"
61
62
63 #include "DEG_depsgraph.h"
64
65 #include "UI_interface.h"
66 #include "UI_view2d.h"
67
68 #include "ED_image.h"
69 #include "ED_object.h"
70 #include "ED_paint.h"
71 #include "ED_screen.h"
72 #include "ED_view3d.h"
73
74 #include "WM_api.h"
75 #include "WM_types.h"
76 #include "WM_message.h"
77 #include "WM_toolsystem.h"
78
79 #include "RNA_access.h"
80 #include "RNA_define.h"
81
82 #include "GPU_draw.h"
83 #include "GPU_immediate.h"
84
85 #include "BIF_gl.h"
86
87 #include "IMB_colormanagement.h"
88
89 #include "paint_intern.h"
90
91 /* this is a static resource for non-globality,
92  * Maybe it should be exposed as part of the
93  * paint operation, but for now just give a public interface */
94 static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
95
96 ImagePaintPartialRedraw *get_imapaintpartial(void)
97 {
98         return &imapaintpartial;
99 }
100
101 void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr)
102 {
103         imapaintpartial = *ippr;
104 }
105
106 /* Imagepaint Partial Redraw & Dirty Region */
107
108 void ED_imapaint_clear_partial_redraw(void)
109 {
110         memset(&imapaintpartial, 0, sizeof(imapaintpartial));
111 }
112
113 void imapaint_region_tiles(ImBuf *ibuf, int x, int y, int w, int h, int *tx, int *ty, int *tw, int *th)
114 {
115         int srcx = 0, srcy = 0;
116
117         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
118
119         *tw = ((x + w - 1) >> IMAPAINT_TILE_BITS);
120         *th = ((y + h - 1) >> IMAPAINT_TILE_BITS);
121         *tx = (x >> IMAPAINT_TILE_BITS);
122         *ty = (y >> IMAPAINT_TILE_BITS);
123 }
124
125 void ED_imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h, bool find_old)
126 {
127         ImBuf *tmpibuf = NULL;
128         int tilex, tiley, tilew, tileh, tx, ty;
129         int srcx = 0, srcy = 0;
130
131         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
132
133         if (w == 0 || h == 0)
134                 return;
135
136         if (!imapaintpartial.enabled) {
137                 imapaintpartial.x1 = x;
138                 imapaintpartial.y1 = y;
139                 imapaintpartial.x2 = x + w;
140                 imapaintpartial.y2 = y + h;
141                 imapaintpartial.enabled = 1;
142         }
143         else {
144                 imapaintpartial.x1 = min_ii(imapaintpartial.x1, x);
145                 imapaintpartial.y1 = min_ii(imapaintpartial.y1, y);
146                 imapaintpartial.x2 = max_ii(imapaintpartial.x2, x + w);
147                 imapaintpartial.y2 = max_ii(imapaintpartial.y2, y + h);
148         }
149
150         imapaint_region_tiles(ibuf, x, y, w, h, &tilex, &tiley, &tilew, &tileh);
151
152         ListBase *undo_tiles = ED_image_undo_get_tiles();
153
154         for (ty = tiley; ty <= tileh; ty++)
155                 for (tx = tilex; tx <= tilew; tx++)
156                         image_undo_push_tile(undo_tiles, ima, ibuf, &tmpibuf, tx, ty, NULL, NULL, false, find_old);
157
158         ibuf->userflags |= IB_BITMAPDIRTY;
159
160         if (tmpibuf)
161                 IMB_freeImBuf(tmpibuf);
162 }
163
164 void imapaint_image_update(SpaceImage *sima, Image *image, ImBuf *ibuf, short texpaint)
165 {
166         if (imapaintpartial.x1 != imapaintpartial.x2 &&
167             imapaintpartial.y1 != imapaintpartial.y2)
168         {
169                 IMB_partial_display_buffer_update_delayed(ibuf, imapaintpartial.x1, imapaintpartial.y1,
170                                                           imapaintpartial.x2, imapaintpartial.y2);
171         }
172
173         if (ibuf->mipmap[0])
174                 ibuf->userflags |= IB_MIPMAP_INVALID;
175
176         /* todo: should set_tpage create ->rect? */
177         if (texpaint || (sima && sima->lock)) {
178                 int w = imapaintpartial.x2 - imapaintpartial.x1;
179                 int h = imapaintpartial.y2 - imapaintpartial.y1;
180                 if (w && h) {
181                         /* Testing with partial update in uv editor too */
182                         GPU_paint_update_image(image, (sima ? &sima->iuser : NULL), imapaintpartial.x1, imapaintpartial.y1, w, h);
183                 }
184         }
185 }
186
187 /* paint blur kernels. Projective painting enforces use of a 2x2 kernel due to lagging */
188 BlurKernel *paint_new_blur_kernel(Brush *br, bool proj)
189 {
190         int i, j;
191         BlurKernel *kernel = MEM_mallocN(sizeof(BlurKernel), "blur kernel");
192         float radius;
193         int side;
194         eBlurKernelType type = br->blur_mode;
195
196         if (proj) {
197                 radius = 0.5f;
198
199                 side = kernel->side = 2;
200                 kernel->side_squared = kernel->side * kernel->side;
201                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
202                 kernel->pixel_len = radius;
203         }
204         else {
205                 if (br->blur_kernel_radius <= 0)
206                         br->blur_kernel_radius = 1;
207
208                 radius = br->blur_kernel_radius;
209
210                 side = kernel->side = radius * 2 + 1;
211                 kernel->side_squared = kernel->side * kernel->side;
212                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
213                 kernel->pixel_len = br->blur_kernel_radius;
214         }
215
216         switch (type) {
217                 case KERNEL_BOX:
218                         for (i = 0; i < kernel->side_squared; i++)
219                                 kernel->wdata[i] = 1.0;
220                         break;
221
222                 case KERNEL_GAUSSIAN:
223                 {
224                         /* at 3.0 standard deviations distance, kernel is about zero */
225                         float standard_dev = radius / 3.0f;
226
227                         /* make the necessary adjustment to the value for use in the normal distribution formula */
228                         standard_dev = -standard_dev * standard_dev * 2;
229
230                         for (i = 0; i < side; i++) {
231                                 for (j = 0; j < side; j++) {
232                                         float idist = radius - i;
233                                         float jdist = radius - j;
234                                         float value = exp((idist * idist + jdist * jdist) / standard_dev);
235
236                                         kernel->wdata[i + j * side] = value;
237                                 }
238                         }
239
240                         break;
241                 }
242
243                 default:
244                         printf("unidentified kernel type, aborting\n");
245                         MEM_freeN(kernel->wdata);
246                         MEM_freeN(kernel);
247                         return NULL;
248         }
249
250         return kernel;
251 }
252
253 void paint_delete_blur_kernel(BlurKernel *kernel)
254 {
255         if (kernel->wdata)
256                 MEM_freeN(kernel->wdata);
257 }
258
259 /************************ image paint poll ************************/
260
261 static Brush *image_paint_brush(bContext *C)
262 {
263         Scene *scene = CTX_data_scene(C);
264         ToolSettings *settings = scene->toolsettings;
265
266         return BKE_paint_brush(&settings->imapaint.paint);
267 }
268
269 static int image_paint_poll_ex(bContext *C, bool check_tool)
270 {
271         Object *obact;
272
273         if (!image_paint_brush(C))
274                 return 0;
275
276         obact = CTX_data_active_object(C);
277         if ((obact && obact->mode & OB_MODE_TEXTURE_PAINT) && CTX_wm_region_view3d(C)) {
278                 if (!check_tool || WM_toolsystem_active_tool_is_brush(C)) {
279                         return 1;
280                 }
281         }
282         else {
283                 SpaceImage *sima = CTX_wm_space_image(C);
284
285                 if (sima) {
286                         ARegion *ar = CTX_wm_region(C);
287
288                         if ((sima->mode == SI_MODE_PAINT) && ar->regiontype == RGN_TYPE_WINDOW) {
289                                 return 1;
290                         }
291                 }
292         }
293
294         return 0;
295 }
296
297 static int image_paint_poll(bContext *C)
298 {
299         return image_paint_poll_ex(C, true);
300 }
301
302 static int image_paint_ignore_tool_poll(bContext *C)
303 {
304         return image_paint_poll_ex(C, false);
305 }
306
307 static int image_paint_2d_clone_poll(bContext *C)
308 {
309         Brush *brush = image_paint_brush(C);
310
311         if (!CTX_wm_region_view3d(C) && image_paint_poll(C))
312                 if (brush && (brush->imagepaint_tool == PAINT_TOOL_CLONE))
313                         if (brush->clone.image)
314                                 return 1;
315
316         return 0;
317 }
318
319 /************************ paint operator ************************/
320 typedef enum eTexPaintMode {
321         PAINT_MODE_2D,
322         PAINT_MODE_3D_PROJECT
323 } eTexPaintMode;
324
325 typedef struct PaintOperation {
326         eTexPaintMode mode;
327
328         void *custom_paint;
329
330         float prevmouse[2];
331         float startmouse[2];
332         double starttime;
333
334         void *cursor;
335         ViewContext vc;
336 } PaintOperation;
337
338 bool paint_use_opacity_masking(Brush *brush)
339 {
340         return (brush->flag & BRUSH_AIRBRUSH) ||
341                (brush->flag & BRUSH_DRAG_DOT) ||
342                (brush->flag & BRUSH_ANCHORED) ||
343                (brush->imagepaint_tool == PAINT_TOOL_SMEAR) ||
344                (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) ||
345                (brush->imagepaint_tool == PAINT_TOOL_FILL) ||
346                (brush->flag & BRUSH_USE_GRADIENT) ||
347                (brush->mtex.tex && !ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)) ?
348                     false : true;
349 }
350
351 void paint_brush_color_get(
352         struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance,
353         float pressure, float color[3], struct ColorManagedDisplay *display)
354 {
355         if (invert)
356                 copy_v3_v3(color, BKE_brush_secondary_color_get(scene, br));
357         else {
358                 if (br->flag & BRUSH_USE_GRADIENT) {
359                         float color_gr[4];
360                         switch (br->gradient_stroke_mode) {
361                                 case BRUSH_GRADIENT_PRESSURE:
362                                         BKE_colorband_evaluate(br->gradient, pressure, color_gr);
363                                         break;
364                                 case BRUSH_GRADIENT_SPACING_REPEAT:
365                                 {
366                                         float coord = fmod(distance / br->gradient_spacing, 1.0);
367                                         BKE_colorband_evaluate(br->gradient, coord, color_gr);
368                                         break;
369                                 }
370                                 case BRUSH_GRADIENT_SPACING_CLAMP:
371                                 {
372                                         BKE_colorband_evaluate(br->gradient, distance / br->gradient_spacing, color_gr);
373                                         break;
374                                 }
375                         }
376                         copy_v3_v3(color, color_gr);
377                 }
378                 else
379                         copy_v3_v3(color, BKE_brush_color_get(scene, br));
380         }
381         if (color_correction)
382                 IMB_colormanagement_display_to_scene_linear_v3(color, display);
383 }
384
385 void paint_brush_init_tex(Brush *brush)
386 {
387         /* init mtex nodes */
388         if (brush) {
389                 MTex *mtex = &brush->mtex;
390                 if (mtex->tex && mtex->tex->nodetree)
391                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
392                 mtex = &brush->mask_mtex;
393                 if (mtex->tex && mtex->tex->nodetree)
394                         ntreeTexBeginExecTree(mtex->tex->nodetree);
395         }
396 }
397
398 void paint_brush_exit_tex(Brush *brush)
399 {
400         if (brush) {
401                 MTex *mtex = &brush->mtex;
402                 if (mtex->tex && mtex->tex->nodetree)
403                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
404                 mtex = &brush->mask_mtex;
405                 if (mtex->tex && mtex->tex->nodetree)
406                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
407         }
408 }
409
410 static void gradient_draw_line(bContext *UNUSED(C), int x, int y, void *customdata)
411 {
412         PaintOperation *pop = (PaintOperation *)customdata;
413
414         if (pop) {
415                 glEnable(GL_LINE_SMOOTH);
416                 glEnable(GL_BLEND);
417
418                 Gwn_VertFormat *format = immVertexFormat();
419                 unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT);
420
421                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
422
423                 glLineWidth(4.0);
424                 immUniformColor4ub(0, 0, 0, 255);
425
426                 immBegin(GWN_PRIM_LINES, 2);
427                 immVertex2i(pos, x, y);
428                 immVertex2i(pos, pop->startmouse[0], pop->startmouse[1]);
429                 immEnd();
430
431                 glLineWidth(2.0);
432                 immUniformColor4ub(255, 255, 255, 255);
433
434                 immBegin(GWN_PRIM_LINES, 2);
435                 immVertex2i(pos, x, y);
436                 immVertex2i(pos, pop->startmouse[0], pop->startmouse[1]);
437                 immEnd();
438
439                 immUnbindProgram();
440
441                 glDisable(GL_BLEND);
442                 glDisable(GL_LINE_SMOOTH);
443         }
444 }
445
446
447 static PaintOperation *texture_paint_init(bContext *C, wmOperator *op, const float mouse[2])
448 {
449         Scene *scene = CTX_data_scene(C);
450         ToolSettings *settings = scene->toolsettings;
451         PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
452         Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
453         int mode = RNA_enum_get(op->ptr, "mode");
454         ED_view3d_viewcontext_init(C, &pop->vc);
455
456         copy_v2_v2(pop->prevmouse, mouse);
457         copy_v2_v2(pop->startmouse, mouse);
458
459         /* initialize from context */
460         if (CTX_wm_region_view3d(C)) {
461                 ViewLayer *view_layer = CTX_data_view_layer(C);
462                 Object *ob = OBACT(view_layer);
463                 bool uvs, mat, tex, stencil;
464                 if (!BKE_paint_proj_mesh_data_check(scene, ob, &uvs, &mat, &tex, &stencil)) {
465                         BKE_paint_data_warning(op->reports, uvs, mat, tex, stencil);
466                         MEM_freeN(pop);
467                         WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);
468                         return NULL;
469                 }
470                 pop->mode = PAINT_MODE_3D_PROJECT;
471                 pop->custom_paint = paint_proj_new_stroke(C, ob, mouse, mode);
472         }
473         else {
474                 pop->mode = PAINT_MODE_2D;
475                 pop->custom_paint = paint_2d_new_stroke(C, op, mode);
476         }
477
478         if (!pop->custom_paint) {
479                 MEM_freeN(pop);
480                 return NULL;
481         }
482
483         if ((brush->imagepaint_tool == PAINT_TOOL_FILL) && (brush->flag & BRUSH_USE_GRADIENT)) {
484                 pop->cursor = WM_paint_cursor_activate(CTX_wm_manager(C), image_paint_poll, gradient_draw_line, pop);
485         }
486
487         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
488         ED_image_undo_push_begin(op->type->name);
489
490         return pop;
491 }
492
493 static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
494 {
495         PaintOperation *pop = paint_stroke_mode_data(stroke);
496         Scene *scene = CTX_data_scene(C);
497         ToolSettings *toolsettings = CTX_data_tool_settings(C);
498         UnifiedPaintSettings *ups = &toolsettings->unified_paint_settings;
499         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
500
501         float alphafac = (brush->flag & BRUSH_ACCUMULATE) ? ups->overlap_factor : 1.0f;
502
503         /* initial brush values. Maybe it should be considered moving these to stroke system */
504         float startalpha = BKE_brush_alpha_get(scene, brush);
505
506         float mouse[2];
507         float pressure;
508         float size;
509         float distance = paint_stroke_distance_get(stroke);
510         int eraser;
511
512         RNA_float_get_array(itemptr, "mouse", mouse);
513         pressure = RNA_float_get(itemptr, "pressure");
514         eraser = RNA_boolean_get(itemptr, "pen_flip");
515         size = max_ff(1.0f, RNA_float_get(itemptr, "size"));
516
517         /* stroking with fill tool only acts on stroke end */
518         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
519                 copy_v2_v2(pop->prevmouse, mouse);
520                 return;
521         }
522
523         if (BKE_brush_use_alpha_pressure(scene, brush))
524                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * pressure * alphafac));
525         else
526                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * alphafac));
527
528         if ((brush->flag & BRUSH_DRAG_DOT) || (brush->flag & BRUSH_ANCHORED)) {
529                 UndoStack *ustack = CTX_wm_manager(C)->undo_stack;
530                 ED_image_undo_restore(ustack->step_init);
531         }
532
533         if (pop->mode == PAINT_MODE_3D_PROJECT) {
534                 paint_proj_stroke(C, pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
535         }
536         else {
537                 paint_2d_stroke(pop->custom_paint, pop->prevmouse, mouse, eraser, pressure, distance, size);
538         }
539
540         copy_v2_v2(pop->prevmouse, mouse);
541
542         /* restore brush values */
543         BKE_brush_alpha_set(scene, brush, startalpha);
544 }
545
546 static void paint_stroke_redraw(const bContext *C, struct PaintStroke *stroke, bool final)
547 {
548         PaintOperation *pop = paint_stroke_mode_data(stroke);
549
550         if (pop->mode == PAINT_MODE_3D_PROJECT) {
551                 paint_proj_redraw(C, pop->custom_paint, final);
552         }
553         else {
554                 paint_2d_redraw(C, pop->custom_paint, final);
555         }
556 }
557
558 static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke)
559 {
560         Scene *scene = CTX_data_scene(C);
561         ToolSettings *toolsettings = scene->toolsettings;
562         PaintOperation *pop = paint_stroke_mode_data(stroke);
563         Brush *brush = BKE_paint_brush(&toolsettings->imapaint.paint);
564
565         toolsettings->imapaint.flag &= ~IMAGEPAINT_DRAWING;
566
567         if (brush->imagepaint_tool == PAINT_TOOL_FILL) {
568                 if (brush->flag & BRUSH_USE_GRADIENT) {
569                         if (pop->mode == PAINT_MODE_2D) {
570                                 paint_2d_gradient_fill(C, brush, pop->startmouse, pop->prevmouse, pop->custom_paint);
571                         }
572                         else {
573                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
574                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
575                                 /* two redraws, one for GPU update, one for notification */
576                                 paint_proj_redraw(C, pop->custom_paint, false);
577                                 paint_proj_redraw(C, pop->custom_paint, true);
578                         }
579                 }
580                 else {
581                         if (pop->mode == PAINT_MODE_2D) {
582                                 float color[3];
583
584                                 srgb_to_linearrgb_v3_v3(color, BKE_brush_color_get(scene, brush));
585                                 paint_2d_bucket_fill(C, color, brush, pop->prevmouse, pop->custom_paint);
586                         }
587                         else {
588                                 paint_proj_stroke(C, pop->custom_paint, pop->startmouse, pop->prevmouse, paint_stroke_flipped(stroke),
589                                                   1.0, 0.0, BKE_brush_size_get(scene, brush));
590                                 /* two redraws, one for GPU update, one for notification */
591                                 paint_proj_redraw(C, pop->custom_paint, false);
592                                 paint_proj_redraw(C, pop->custom_paint, true);
593                         }
594                 }
595         }
596         if (pop->mode == PAINT_MODE_3D_PROJECT) {
597                 paint_proj_stroke_done(pop->custom_paint);
598         }
599         else {
600                 paint_2d_stroke_done(pop->custom_paint);
601         }
602
603         if (pop->cursor) {
604                 WM_paint_cursor_end(CTX_wm_manager(C), pop->cursor);
605         }
606
607         ED_image_undo_push_end();
608
609         /* duplicate warning, see texpaint_init */
610 #if 0
611         if (pop->s.warnmultifile)
612                 BKE_reportf(op->reports, RPT_WARNING, "Image requires 4 color channels to paint: %s", pop->s.warnmultifile);
613         if (pop->s.warnpackedfile)
614                 BKE_reportf(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted: %s", pop->s.warnpackedfile);
615 #endif
616         MEM_freeN(pop);
617 }
618
619 static bool paint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
620 {
621         PaintOperation *pop;
622
623         /* TODO Should avoid putting this here. Instead, last position should be requested
624          * from stroke system. */
625
626         if (!(pop = texture_paint_init(C, op, mouse))) {
627                 return false;
628         }
629
630         paint_stroke_set_mode_data(op->customdata, pop);
631
632         return true;
633 }
634
635
636 static int paint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
637 {
638         int retval;
639
640         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
641                                           paint_stroke_update_step,
642                                           paint_stroke_redraw,
643                                           paint_stroke_done, event->type);
644
645         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
646                 paint_stroke_data_free(op);
647                 return OPERATOR_FINISHED;
648         }
649         /* add modal handler */
650         WM_event_add_modal_handler(C, op);
651
652         OPERATOR_RETVAL_CHECK(retval);
653         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
654
655         return OPERATOR_RUNNING_MODAL;
656 }
657
658 static int paint_exec(bContext *C, wmOperator *op)
659 {
660         PropertyRNA *strokeprop;
661         PointerRNA firstpoint;
662         float mouse[2];
663
664         strokeprop = RNA_struct_find_property(op->ptr, "stroke");
665
666         if (!RNA_property_collection_lookup_int(op->ptr, strokeprop, 0, &firstpoint))
667                 return OPERATOR_CANCELLED;
668
669         RNA_float_get_array(&firstpoint, "mouse", mouse);
670
671         op->customdata = paint_stroke_new(C, op, NULL, paint_stroke_test_start,
672                                           paint_stroke_update_step,
673                                           paint_stroke_redraw,
674                                           paint_stroke_done, 0);
675         /* frees op->customdata */
676         return paint_stroke_exec(C, op);
677 }
678
679 void PAINT_OT_image_paint(wmOperatorType *ot)
680 {
681         /* identifiers */
682         ot->name = "Image Paint";
683         ot->idname = "PAINT_OT_image_paint";
684         ot->description = "Paint a stroke into the image";
685
686         /* api callbacks */
687         ot->invoke = paint_invoke;
688         ot->modal = paint_stroke_modal;
689         ot->exec = paint_exec;
690         ot->poll = image_paint_poll;
691         ot->cancel = paint_stroke_cancel;
692
693         /* flags */
694         ot->flag = OPTYPE_BLOCKING;
695
696         paint_stroke_operator_properties(ot);
697 }
698
699
700 int get_imapaint_zoom(bContext *C, float *zoomx, float *zoomy)
701 {
702         RegionView3D *rv3d = CTX_wm_region_view3d(C);
703
704         if (!rv3d) {
705                 SpaceImage *sima = CTX_wm_space_image(C);
706
707                 if (sima->mode == SI_MODE_PAINT) {
708                         ARegion *ar = CTX_wm_region(C);
709                         ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
710
711                         return 1;
712                 }
713         }
714
715         *zoomx = *zoomy = 1;
716
717         return 0;
718 }
719
720 /************************ cursor drawing *******************************/
721
722 static void toggle_paint_cursor(bContext *C, int enable)
723 {
724         wmWindowManager *wm = CTX_wm_manager(C);
725         Scene *scene = CTX_data_scene(C);
726         ToolSettings *settings = scene->toolsettings;
727
728         if (settings->imapaint.paintcursor && !enable) {
729                 WM_paint_cursor_end(wm, settings->imapaint.paintcursor);
730                 settings->imapaint.paintcursor = NULL;
731                 paint_cursor_delete_textures();
732         }
733         else if (enable)
734                 paint_cursor_start(C, image_paint_poll);
735 }
736
737 /* enable the paint cursor if it isn't already.
738  *
739  * purpose is to make sure the paint cursor is shown if paint
740  * mode is enabled in the image editor. the paint poll will
741  * ensure that the cursor is hidden when not in paint mode */
742 void ED_space_image_paint_update(Main *bmain, wmWindowManager *wm, Scene *scene)
743 {
744         ToolSettings *settings = scene->toolsettings;
745         ImagePaintSettings *imapaint = &settings->imapaint;
746         bool enabled = false;
747
748         for (wmWindow *win = wm->windows.first; win; win = win->next) {
749                 bScreen *screen = WM_window_get_active_screen(win);
750
751                 for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
752                         if (sa->spacetype == SPACE_IMAGE) {
753                                 if (((SpaceImage *)sa->spacedata.first)->mode == SI_MODE_PAINT) {
754                                         enabled = true;
755                                 }
756                         }
757                 }
758         }
759
760         if (enabled) {
761                 BKE_paint_init(bmain, scene, ePaintTexture2D, PAINT_CURSOR_TEXTURE_PAINT);
762
763                 paint_cursor_start_explicit(&imapaint->paint, wm, image_paint_poll);
764         }
765         else {
766                 paint_cursor_delete_textures();
767         }
768 }
769
770 /************************ grab clone operator ************************/
771
772 typedef struct GrabClone {
773         float startoffset[2];
774         int startx, starty;
775 } GrabClone;
776
777 static void grab_clone_apply(bContext *C, wmOperator *op)
778 {
779         Brush *brush = image_paint_brush(C);
780         float delta[2];
781
782         RNA_float_get_array(op->ptr, "delta", delta);
783         add_v2_v2(brush->clone.offset, delta);
784         ED_region_tag_redraw(CTX_wm_region(C));
785 }
786
787 static int grab_clone_exec(bContext *C, wmOperator *op)
788 {
789         grab_clone_apply(C, op);
790
791         return OPERATOR_FINISHED;
792 }
793
794 static int grab_clone_invoke(bContext *C, wmOperator *op, const wmEvent *event)
795 {
796         Brush *brush = image_paint_brush(C);
797         GrabClone *cmv;
798
799         cmv = MEM_callocN(sizeof(GrabClone), "GrabClone");
800         copy_v2_v2(cmv->startoffset, brush->clone.offset);
801         cmv->startx = event->x;
802         cmv->starty = event->y;
803         op->customdata = cmv;
804
805         WM_event_add_modal_handler(C, op);
806
807         return OPERATOR_RUNNING_MODAL;
808 }
809
810 static int grab_clone_modal(bContext *C, wmOperator *op, const wmEvent *event)
811 {
812         Brush *brush = image_paint_brush(C);
813         ARegion *ar = CTX_wm_region(C);
814         GrabClone *cmv = op->customdata;
815         float startfx, startfy, fx, fy, delta[2];
816         int xmin = ar->winrct.xmin, ymin = ar->winrct.ymin;
817
818         switch (event->type) {
819                 case LEFTMOUSE:
820                 case MIDDLEMOUSE:
821                 case RIGHTMOUSE: // XXX hardcoded
822                         MEM_freeN(op->customdata);
823                         return OPERATOR_FINISHED;
824                 case MOUSEMOVE:
825                         /* mouse moved, so move the clone image */
826                         UI_view2d_region_to_view(&ar->v2d, cmv->startx - xmin, cmv->starty - ymin, &startfx, &startfy);
827                         UI_view2d_region_to_view(&ar->v2d, event->x - xmin, event->y - ymin, &fx, &fy);
828
829                         delta[0] = fx - startfx;
830                         delta[1] = fy - startfy;
831                         RNA_float_set_array(op->ptr, "delta", delta);
832
833                         copy_v2_v2(brush->clone.offset, cmv->startoffset);
834
835                         grab_clone_apply(C, op);
836                         break;
837         }
838
839         return OPERATOR_RUNNING_MODAL;
840 }
841
842 static void grab_clone_cancel(bContext *UNUSED(C), wmOperator *op)
843 {
844         MEM_freeN(op->customdata);
845 }
846
847 void PAINT_OT_grab_clone(wmOperatorType *ot)
848 {
849         /* identifiers */
850         ot->name = "Grab Clone";
851         ot->idname = "PAINT_OT_grab_clone";
852         ot->description = "Move the clone source image";
853
854         /* api callbacks */
855         ot->exec = grab_clone_exec;
856         ot->invoke = grab_clone_invoke;
857         ot->modal = grab_clone_modal;
858         ot->cancel = grab_clone_cancel;
859         ot->poll = image_paint_2d_clone_poll;
860
861         /* flags */
862         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
863
864         /* properties */
865         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);
866 }
867
868 /******************** sample color operator ********************/
869 typedef struct {
870         bool show_cursor;
871         short event_type;
872         float initcolor[3];
873         bool sample_palette;
874 }       SampleColorData;
875
876
877 static void sample_color_update_header(SampleColorData *data, bContext *C)
878 {
879         char msg[UI_MAX_DRAW_STR];
880         ScrArea *sa = CTX_wm_area(C);
881
882         if (sa) {
883                 BLI_snprintf(msg, sizeof(msg),
884                              IFACE_("Sample color for %s"),
885                              !data->sample_palette ?
886                              IFACE_("Brush. Use Left Click to sample for palette instead") :
887                              IFACE_("Palette. Use Left Click to sample more colors"));
888                 ED_area_headerprint(sa, msg);
889         }
890 }
891
892 static int sample_color_exec(bContext *C, wmOperator *op)
893 {
894         Paint *paint = BKE_paint_get_active_from_context(C);
895         Brush *brush = BKE_paint_brush(paint);
896         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
897         ARegion *ar = CTX_wm_region(C);
898         wmWindow *win = CTX_wm_window(C);
899         const bool show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
900         int location[2];
901         paint->flags &= ~PAINT_SHOW_BRUSH;
902
903         /* force redraw without cursor */
904         WM_paint_cursor_tag_redraw(win, ar);
905         WM_redraw_windows(C);
906
907         RNA_int_get_array(op->ptr, "location", location);
908         const bool use_palette = RNA_boolean_get(op->ptr, "palette");
909         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
910
911         paint_sample_color(C, ar, location[0], location[1], use_sample_texture, use_palette);
912
913         if (show_cursor) {
914                 paint->flags |= PAINT_SHOW_BRUSH;
915         }
916
917         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
918
919         return OPERATOR_FINISHED;
920 }
921
922 static int sample_color_invoke(bContext *C, wmOperator *op, const wmEvent *event)
923 {
924         Scene *scene = CTX_data_scene(C);
925         Paint *paint = BKE_paint_get_active_from_context(C);
926         Brush *brush = BKE_paint_brush(paint);
927         SampleColorData *data = MEM_mallocN(sizeof(SampleColorData), "sample color custom data");
928         ARegion *ar = CTX_wm_region(C);
929         wmWindow *win = CTX_wm_window(C);
930
931         data->event_type = event->type;
932         data->show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
933         copy_v3_v3(data->initcolor, BKE_brush_color_get(scene, brush));
934         data->sample_palette = false;
935         op->customdata = data;
936         paint->flags &= ~PAINT_SHOW_BRUSH;
937
938         sample_color_update_header(data, C);
939
940         WM_event_add_modal_handler(C, op);
941
942         /* force redraw without cursor */
943         WM_paint_cursor_tag_redraw(win, ar);
944         WM_redraw_windows(C);
945
946         RNA_int_set_array(op->ptr, "location", event->mval);
947
948         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
949         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
950
951         paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, false);
952         WM_cursor_modal_set(win, BC_EYEDROPPER_CURSOR);
953
954         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
955
956         return OPERATOR_RUNNING_MODAL;
957 }
958
959 static int sample_color_modal(bContext *C, wmOperator *op, const wmEvent *event)
960 {
961         Scene *scene = CTX_data_scene(C);
962         SampleColorData *data = op->customdata;
963         Paint *paint = BKE_paint_get_active_from_context(C);
964         Brush *brush = BKE_paint_brush(paint);
965
966         if ((event->type == data->event_type) && (event->val == KM_RELEASE)) {
967                 ScrArea *sa = CTX_wm_area(C);
968
969                 if (data->show_cursor) {
970                         paint->flags |= PAINT_SHOW_BRUSH;
971                 }
972
973                 if (data->sample_palette) {
974                         BKE_brush_color_set(scene, brush, data->initcolor);
975                         RNA_boolean_set(op->ptr, "palette", true);
976                 }
977                 WM_cursor_modal_restore(CTX_wm_window(C));
978                 MEM_freeN(data);
979                 ED_area_headerprint(sa, NULL);
980
981                 return OPERATOR_FINISHED;
982         }
983
984         ePaintMode mode = BKE_paintmode_get_active_from_context(C);
985         const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
986
987         switch (event->type) {
988                 case MOUSEMOVE:
989                 {
990                         ARegion *ar = CTX_wm_region(C);
991                         RNA_int_set_array(op->ptr, "location", event->mval);
992                         paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, false);
993                         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
994                         break;
995                 }
996
997                 case LEFTMOUSE:
998                         if (event->val == KM_PRESS) {
999                                 ARegion *ar = CTX_wm_region(C);
1000                                 RNA_int_set_array(op->ptr, "location", event->mval);
1001                                 paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, true);
1002                                 if (!data->sample_palette) {
1003                                         data->sample_palette = true;
1004                                         sample_color_update_header(data, C);
1005                                 }
1006                                 WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
1007                         }
1008                         break;
1009         }
1010
1011         return OPERATOR_RUNNING_MODAL;
1012 }
1013
1014 void PAINT_OT_sample_color(wmOperatorType *ot)
1015 {
1016         /* identifiers */
1017         ot->name = "Sample Color";
1018         ot->idname = "PAINT_OT_sample_color";
1019         ot->description = "Use the mouse to sample a color in the image";
1020
1021         /* api callbacks */
1022         ot->exec = sample_color_exec;
1023         ot->invoke = sample_color_invoke;
1024         ot->modal = sample_color_modal;
1025         ot->poll = image_paint_ignore_tool_poll;
1026
1027         /* flags */
1028         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1029
1030         /* properties */
1031         PropertyRNA *prop;
1032
1033         prop = RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384);
1034         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
1035
1036         RNA_def_boolean(ot->srna, "merged", 0, "Sample Merged", "Sample the output display color");
1037         RNA_def_boolean(ot->srna, "palette", 0, "Add to Palette", "");
1038 }
1039
1040 /******************** texture paint toggle operator ********************/
1041
1042 static int texture_paint_toggle_poll(bContext *C)
1043 {
1044         Object *ob = CTX_data_active_object(C);
1045         if (ob == NULL || ob->type != OB_MESH)
1046                 return 0;
1047         if (!ob->data || ID_IS_LINKED(ob->data))
1048                 return 0;
1049         if (CTX_data_edit_object(C))
1050                 return 0;
1051
1052         return 1;
1053 }
1054
1055 static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
1056 {
1057         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
1058         Scene *scene = CTX_data_scene(C);
1059         Object *ob = CTX_data_active_object(C);
1060         const int mode_flag = OB_MODE_TEXTURE_PAINT;
1061         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1062
1063         if (!is_mode_set) {
1064                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1065                         return OPERATOR_CANCELLED;
1066                 }
1067         }
1068
1069         if (ob->mode & mode_flag) {
1070                 ob->mode &= ~mode_flag;
1071
1072                 if (U.glreslimit != 0)
1073                         GPU_free_images();
1074                 GPU_paint_set_mipmap(1);
1075
1076                 toggle_paint_cursor(C, 0);
1077         }
1078         else {
1079                 bScreen *sc;
1080                 Main *bmain = CTX_data_main(C);
1081                 Image *ima = NULL;
1082                 ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
1083
1084                 /* This has to stay here to regenerate the texture paint
1085                  * cache in case we are loading a file */
1086                 BKE_texpaint_slots_refresh_object(scene, ob);
1087
1088                 BKE_paint_proj_mesh_data_check(scene, ob, NULL, NULL, NULL, NULL);
1089
1090                 /* entering paint mode also sets image to editors */
1091                 if (imapaint->mode == IMAGEPAINT_MODE_MATERIAL) {
1092                         Material *ma = give_current_material(ob, ob->actcol); /* set the current material active paint slot on image editor */
1093
1094                         if (ma && ma->texpaintslot)
1095                                 ima = ma->texpaintslot[ma->paint_active_slot].ima;
1096                 }
1097                 else if (imapaint->mode == IMAGEPAINT_MODE_IMAGE) {
1098                         ima = imapaint->canvas;
1099                 }
1100
1101                 if (ima) {
1102                         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1103                                 ScrArea *sa;
1104                                 for (sa = sc->areabase.first; sa; sa = sa->next) {
1105                                         SpaceLink *sl;
1106                                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
1107                                                 if (sl->spacetype == SPACE_IMAGE) {
1108                                                         SpaceImage *sima = (SpaceImage *)sl;
1109
1110                                                         if (!sima->pin) {
1111                                                                 Object *obedit = CTX_data_edit_object(C);
1112                                                                 ED_space_image_set(bmain, sima, scene, obedit, ima);
1113                                                         }
1114                                                 }
1115                                         }
1116                                 }
1117                         }
1118                 }
1119
1120                 ob->mode |= mode_flag;
1121
1122                 BKE_paint_init(bmain, scene, ePaintTextureProjective, PAINT_CURSOR_TEXTURE_PAINT);
1123
1124                 if (U.glreslimit != 0)
1125                         GPU_free_images();
1126                 GPU_paint_set_mipmap(0);
1127
1128                 toggle_paint_cursor(C, 1);
1129         }
1130
1131         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1132
1133         WM_msg_publish_rna_prop(mbus, &ob->id, ob, Object, mode);
1134
1135         WM_toolsystem_update_from_context_view3d(C);
1136
1137         return OPERATOR_FINISHED;
1138 }
1139
1140 void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
1141 {
1142         /* identifiers */
1143         ot->name = "Texture Paint Toggle";
1144         ot->idname = "PAINT_OT_texture_paint_toggle";
1145         ot->description = "Toggle texture paint mode in 3D view";
1146
1147         /* api callbacks */
1148         ot->exec = texture_paint_toggle_exec;
1149         ot->poll = texture_paint_toggle_poll;
1150
1151         /* flags */
1152         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1153 }
1154
1155
1156 static int brush_colors_flip_exec(bContext *C, wmOperator *UNUSED(op))
1157 {
1158         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1159
1160         Object *ob = CTX_data_active_object(C);
1161         Brush *br;
1162         if (!(ob && (ob->mode & OB_MODE_VERTEX_PAINT))) {
1163                 br = image_paint_brush(C);
1164         }
1165         else {
1166                 /* At the moment, wpaint does not support the color flipper.
1167                  * So for now we're only handling vpaint */
1168                 ToolSettings *ts = CTX_data_tool_settings(C);
1169                 VPaint *vp = ts->vpaint;
1170                 br = BKE_paint_brush(&vp->paint);
1171         }
1172
1173         if (ups->flag & UNIFIED_PAINT_COLOR) {
1174                 swap_v3_v3(ups->rgb, ups->secondary_rgb);
1175         }
1176         else if (br) {
1177                 swap_v3_v3(br->rgb, br->secondary_rgb);
1178         }
1179         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, br);
1180
1181         return OPERATOR_FINISHED;
1182 }
1183
1184 static int brush_colors_flip_poll(bContext *C)
1185 {
1186         if (image_paint_poll(C)) {
1187                 Brush *br = image_paint_brush(C);
1188                 if (br->imagepaint_tool == PAINT_TOOL_DRAW)
1189                         return 1;
1190         }
1191         else {
1192                 Object *ob = CTX_data_active_object(C);
1193                 if (ob && (ob->mode & OB_MODE_VERTEX_PAINT)) {
1194                         return 1;
1195                 }
1196         }
1197         return 0;
1198 }
1199
1200 void PAINT_OT_brush_colors_flip(wmOperatorType *ot)
1201 {
1202         /* identifiers */
1203         ot->name = "Brush Colors Flip";
1204         ot->idname = "PAINT_OT_brush_colors_flip";
1205         ot->description = "Toggle foreground and background brush colors";
1206
1207         /* api callbacks */
1208         ot->exec = brush_colors_flip_exec;
1209         ot->poll = brush_colors_flip_poll;
1210
1211         /* flags */
1212         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1213 }
1214
1215
1216 void ED_imapaint_bucket_fill(struct bContext *C, float color[3], wmOperator *op)
1217 {
1218         wmWindowManager *wm = CTX_wm_manager(C);
1219         SpaceImage *sima = CTX_wm_space_image(C);
1220         Image *ima = sima->image;
1221
1222         BKE_undosys_step_push_init_with_type(wm->undo_stack, C, op->type->name, BKE_UNDOSYS_TYPE_IMAGE);
1223
1224         ED_image_undo_push_begin(op->type->name);
1225
1226         paint_2d_bucket_fill(C, color, NULL, NULL, NULL);
1227
1228         BKE_undosys_step_push(wm->undo_stack, C, op->type->name);
1229
1230         DEG_id_tag_update(&ima->id, 0);
1231 }
1232
1233
1234 static int texture_paint_poll(bContext *C)
1235 {
1236         if (texture_paint_toggle_poll(C))
1237                 if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT)
1238                         return 1;
1239
1240         return 0;
1241 }
1242
1243 int image_texture_paint_poll(bContext *C)
1244 {
1245         return (texture_paint_poll(C) || image_paint_poll(C));
1246 }
1247
1248 int facemask_paint_poll(bContext *C)
1249 {
1250         return BKE_paint_select_face_test(CTX_data_active_object(C));
1251 }
1252
1253 int vert_paint_poll(bContext *C)
1254 {
1255         return BKE_paint_select_vert_test(CTX_data_active_object(C));
1256 }
1257
1258 int mask_paint_poll(bContext *C)
1259 {
1260         return BKE_paint_select_elem_test(CTX_data_active_object(C));
1261 }
1262