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