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_mesh_types.h"
50 #include "DNA_node_types.h"
51 #include "DNA_object_types.h"
52
53 #include "BKE_colorband.h"
54 #include "BKE_context.h"
55 #include "BKE_brush.h"
56 #include "BKE_main.h"
57 #include "BKE_material.h"
58 #include "BKE_mesh.h"
59 #include "BKE_node.h"
60 #include "BKE_paint.h"
61 #include "BKE_undo_system.h"
62
63
64 #include "DEG_depsgraph.h"
65
66 #include "UI_interface.h"
67 #include "UI_view2d.h"
68
69 #include "ED_image.h"
70 #include "ED_object.h"
71 #include "ED_paint.h"
72 #include "ED_screen.h"
73 #include "ED_view3d.h"
74
75 #include "WM_api.h"
76 #include "WM_types.h"
77 #include "WM_message.h"
78 #include "WM_toolsystem.h"
79
80 #include "RNA_access.h"
81 #include "RNA_define.h"
82
83 #include "GPU_draw.h"
84 #include "GPU_immediate.h"
85 #include "GPU_state.h"
86
87 #include "BIF_gl.h"
88
89 #include "IMB_colormanagement.h"
90
91 #include "paint_intern.h"
92
93 /* this is a static resource for non-globality,
94  * Maybe it should be exposed as part of the
95  * paint operation, but for now just give a public interface */
96 static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
97
98 ImagePaintPartialRedraw *get_imapaintpartial(void)
99 {
100         return &imapaintpartial;
101 }
102
103 void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr)
104 {
105         imapaintpartial = *ippr;
106 }
107
108 /* Imagepaint Partial Redraw & Dirty Region */
109
110 void ED_imapaint_clear_partial_redraw(void)
111 {
112         memset(&imapaintpartial, 0, sizeof(imapaintpartial));
113 }
114
115 void imapaint_region_tiles(ImBuf *ibuf, int x, int y, int w, int h, int *tx, int *ty, int *tw, int *th)
116 {
117         int srcx = 0, srcy = 0;
118
119         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
120
121         *tw = ((x + w - 1) >> IMAPAINT_TILE_BITS);
122         *th = ((y + h - 1) >> IMAPAINT_TILE_BITS);
123         *tx = (x >> IMAPAINT_TILE_BITS);
124         *ty = (y >> IMAPAINT_TILE_BITS);
125 }
126
127 void ED_imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h, bool find_old)
128 {
129         ImBuf *tmpibuf = NULL;
130         int tilex, tiley, tilew, tileh, tx, ty;
131         int srcx = 0, srcy = 0;
132
133         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
134
135         if (w == 0 || h == 0)
136                 return;
137
138         if (!imapaintpartial.enabled) {
139                 imapaintpartial.x1 = x;
140                 imapaintpartial.y1 = y;
141                 imapaintpartial.x2 = x + w;
142                 imapaintpartial.y2 = y + h;
143                 imapaintpartial.enabled = 1;
144         }
145         else {
146                 imapaintpartial.x1 = min_ii(imapaintpartial.x1, x);
147                 imapaintpartial.y1 = min_ii(imapaintpartial.y1, y);
148                 imapaintpartial.x2 = max_ii(imapaintpartial.x2, x + w);
149                 imapaintpartial.y2 = max_ii(imapaintpartial.y2, y + h);
150         }
151
152         imapaint_region_tiles(ibuf, x, y, w, h, &tilex, &tiley, &tilew, &tileh);
153
154         ListBase *undo_tiles = ED_image_undo_get_tiles();
155
156         for (ty = tiley; ty <= tileh; ty++)
157                 for (tx = tilex; tx <= tilew; tx++)
158                         image_undo_push_tile(undo_tiles, ima, ibuf, &tmpibuf, tx, ty, NULL, NULL, false, find_old);
159
160         ibuf->userflags |= IB_BITMAPDIRTY;
161
162         if (tmpibuf)
163                 IMB_freeImBuf(tmpibuf);
164 }
165
166 void imapaint_image_update(SpaceImage *sima, Image *image, ImBuf *ibuf, short texpaint)
167 {
168         if (imapaintpartial.x1 != imapaintpartial.x2 &&
169             imapaintpartial.y1 != imapaintpartial.y2)
170         {
171                 IMB_partial_display_buffer_update_delayed(
172                         ibuf, imapaintpartial.x1, imapaintpartial.y1,
173                         imapaintpartial.x2, imapaintpartial.y2);
174         }
175
176         if (ibuf->mipmap[0])
177                 ibuf->userflags |= IB_MIPMAP_INVALID;
178
179         /* todo: should set_tpage create ->rect? */
180         if (texpaint || (sima && sima->lock)) {
181                 int w = imapaintpartial.x2 - imapaintpartial.x1;
182                 int h = imapaintpartial.y2 - imapaintpartial.y1;
183                 if (w && h) {
184                         /* Testing with partial update in uv editor too */
185                         GPU_paint_update_image(image, (sima ? &sima->iuser : NULL), imapaintpartial.x1, imapaintpartial.y1, w, h);
186                 }
187         }
188 }
189
190 /* paint blur kernels. Projective painting enforces use of a 2x2 kernel due to lagging */
191 BlurKernel *paint_new_blur_kernel(Brush *br, bool proj)
192 {
193         int i, j;
194         BlurKernel *kernel = MEM_mallocN(sizeof(BlurKernel), "blur kernel");
195         float radius;
196         int side;
197         eBlurKernelType type = br->blur_mode;
198
199         if (proj) {
200                 radius = 0.5f;
201
202                 side = kernel->side = 2;
203                 kernel->side_squared = kernel->side * kernel->side;
204                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
205                 kernel->pixel_len = radius;
206         }
207         else {
208                 if (br->blur_kernel_radius <= 0)
209                         br->blur_kernel_radius = 1;
210
211                 radius = br->blur_kernel_radius;
212
213                 side = kernel->side = radius * 2 + 1;
214                 kernel->side_squared = kernel->side * kernel->side;
215                 kernel->wdata = MEM_mallocN(sizeof(float) * kernel->side_squared, "blur kernel data");
216                 kernel->pixel_len = br->blur_kernel_radius;
217         }
218
219         switch (type) {
220                 case KERNEL_BOX:
221                         for (i = 0; i < kernel->side_squared; i++)
222                                 kernel->wdata[i] = 1.0;
223                         break;
224
225                 case KERNEL_GAUSSIAN:
226                 {
227                         /* at 3.0 standard deviations distance, kernel is about zero */
228                         float standard_dev = radius / 3.0f;
229
230                         /* make the necessary adjustment to the value for use in the normal distribution formula */
231                         standard_dev = -standard_dev * standard_dev * 2;
232
233                         for (i = 0; i < side; i++) {
234                                 for (j = 0; j < side; j++) {
235                                         float idist = radius - i;
236                                         float jdist = radius - j;
237                                         float value = exp((idist * idist + jdist * jdist) / standard_dev);
238
239                                         kernel->wdata[i + j * side] = value;
240                                 }
241                         }
242
243                         break;
244                 }
245
246                 default:
247                         printf("unidentified kernel type, aborting\n");
248                         MEM_freeN(kernel->wdata);
249                         MEM_freeN(kernel);
250                         return NULL;
251         }
252
253         return kernel;
254 }
255
256 void paint_delete_blur_kernel(BlurKernel *kernel)
257 {
258         if (kernel->wdata)
259                 MEM_freeN(kernel->wdata);
260 }
261
262 /************************ image paint poll ************************/
263
264 static Brush *image_paint_brush(bContext *C)
265 {
266         Scene *scene = CTX_data_scene(C);
267         ToolSettings *settings = scene->toolsettings;
268
269         return BKE_paint_brush(&settings->imapaint.paint);
270 }
271
272 static bool image_paint_poll_ex(bContext *C, bool check_tool)
273 {
274         Object *obact;
275
276         if (!image_paint_brush(C))
277                 return 0;
278
279         obact = CTX_data_active_object(C);
280         if ((obact && obact->mode & OB_MODE_TEXTURE_PAINT) && CTX_wm_region_view3d(C)) {
281                 if (!check_tool || WM_toolsystem_active_tool_is_brush(C)) {
282                         return 1;
283                 }
284         }
285         else {
286                 SpaceImage *sima = CTX_wm_space_image(C);
287
288                 if (sima) {
289                         ARegion *ar = CTX_wm_region(C);
290
291                         if ((sima->mode == SI_MODE_PAINT) && ar->regiontype == RGN_TYPE_WINDOW) {
292                                 return 1;
293                         }
294                 }
295         }
296
297         return 0;
298 }
299
300 static bool image_paint_poll(bContext *C)
301 {
302         return image_paint_poll_ex(C, true);
303 }
304
305 static bool image_paint_ignore_tool_poll(bContext *C)
306 {
307         return image_paint_poll_ex(C, false);
308 }
309
310 static bool image_paint_2d_clone_poll(bContext *C)
311 {
312         Brush *brush = image_paint_brush(C);
313
314         if (!CTX_wm_region_view3d(C) && image_paint_poll(C))
315                 if (brush && (brush->imagepaint_tool == PAINT_TOOL_CLONE))
316                         if (brush->clone.image)
317                                 return 1;
318
319         return 0;
320 }
321
322 /************************ paint operator ************************/
323 typedef enum eTexPaintMode {
324         PAINT_MODE_2D,
325         PAINT_MODE_3D_PROJECT
326 } eTexPaintMode;
327
328 typedef struct PaintOperation {
329         eTexPaintMode mode;
330
331         void *custom_paint;
332
333         float prevmouse[2];
334         float startmouse[2];
335         double starttime;
336
337         void *cursor;
338         ViewContext vc;
339 } PaintOperation;
340
341 bool paint_use_opacity_masking(Brush *brush)
342 {
343         return ((brush->flag & BRUSH_AIRBRUSH) ||
344                 (brush->flag & BRUSH_DRAG_DOT) ||
345                 (brush->flag & BRUSH_ANCHORED) ||
346                 (brush->imagepaint_tool == PAINT_TOOL_SMEAR) ||
347                 (brush->imagepaint_tool == PAINT_TOOL_SOFTEN) ||
348                 (brush->imagepaint_tool == PAINT_TOOL_FILL) ||
349                 (brush->flag & BRUSH_USE_GRADIENT) ||
350                 (brush->mtex.tex &&
351                  !ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)) ?
352                 false : true);
353 }
354
355 void paint_brush_color_get(
356         struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance,
357         float pressure, float color[3], struct ColorManagedDisplay *display)
358 {
359         if (invert)
360                 copy_v3_v3(color, BKE_brush_secondary_color_get(scene, br));
361         else {
362                 if (br->flag & BRUSH_USE_GRADIENT) {
363                         float color_gr[4];
364                         switch (br->gradient_stroke_mode) {
365                                 case BRUSH_GRADIENT_PRESSURE:
366                                         BKE_colorband_evaluate(br->gradient, pressure, color_gr);
367                                         break;
368                                 case BRUSH_GRADIENT_SPACING_REPEAT:
369                                 {
370                                         float coord = fmod(distance / br->gradient_spacing, 1.0);
371                                         BKE_colorband_evaluate(br->gradient, coord, color_gr);
372                                         break;
373                                 }
374                                 case BRUSH_GRADIENT_SPACING_CLAMP:
375                                 {
376                                         BKE_colorband_evaluate(br->gradient, distance / br->gradient_spacing, color_gr);
377                                         break;
378                                 }
379                         }
380                         copy_v3_v3(color, color_gr);
381                 }
382                 else
383                         copy_v3_v3(color, BKE_brush_color_get(scene, br));
384         }
385         if (color_correction)
386                 IMB_colormanagement_display_to_scene_linear_v3(color, display);
387 }
388
389 void paint_brush_init_tex(Brush *brush)
390 {
391         /* init mtex nodes */
392         if (brush) {
393                 MTex *mtex = &brush->mtex;
394                 if (mtex->tex && mtex->tex->nodetree)
395                         ntreeTexBeginExecTree(mtex->tex->nodetree);  /* has internal flag to detect it only does it once */
396                 mtex = &brush->mask_mtex;
397                 if (mtex->tex && mtex->tex->nodetree)
398                         ntreeTexBeginExecTree(mtex->tex->nodetree);
399         }
400 }
401
402 void paint_brush_exit_tex(Brush *brush)
403 {
404         if (brush) {
405                 MTex *mtex = &brush->mtex;
406                 if (mtex->tex && mtex->tex->nodetree)
407                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
408                 mtex = &brush->mask_mtex;
409                 if (mtex->tex && mtex->tex->nodetree)
410                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
411         }
412 }
413
414 static void gradient_draw_line(bContext *UNUSED(C), int x, int y, void *customdata)
415 {
416         PaintOperation *pop = (PaintOperation *)customdata;
417
418         if (pop) {
419                 GPU_line_smooth(true);
420                 GPU_blend(true);
421
422                 Gwn_VertFormat *format = immVertexFormat();
423                 unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_I32, 2, GWN_FETCH_INT_TO_FLOAT);
424
425                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
426
427                 GPU_line_width(4.0);
428                 immUniformColor4ub(0, 0, 0, 255);
429
430                 immBegin(GWN_PRIM_LINES, 2);
431                 immVertex2i(pos, x, y);
432                 immVertex2i(pos, pop->startmouse[0], pop->startmouse[1]);
433                 immEnd();
434
435                 GPU_line_width(2.0);
436                 immUniformColor4ub(255, 255, 255, 255);
437
438                 immBegin(GWN_PRIM_LINES, 2);
439                 immVertex2i(pos, x, y);
440                 immVertex2i(pos, pop->startmouse[0], pop->startmouse[1]);
441                 immEnd();
442
443                 immUnbindProgram();
444
445                 GPU_blend(false);
446                 GPU_line_smooth(false);
447         }
448 }
449
450
451 static PaintOperation *texture_paint_init(bContext *C, wmOperator *op, const float mouse[2])
452 {
453         Scene *scene = CTX_data_scene(C);
454         ToolSettings *settings = scene->toolsettings;
455         PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
456         Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
457         int mode = RNA_enum_get(op->ptr, "mode");
458         ED_view3d_viewcontext_init(C, &pop->vc);
459
460         copy_v2_v2(pop->prevmouse, mouse);
461         copy_v2_v2(pop->startmouse, mouse);
462
463         /* initialize from context */
464         if (CTX_wm_region_view3d(C)) {
465                 ViewLayer *view_layer = CTX_data_view_layer(C);
466                 Object *ob = OBACT(view_layer);
467                 bool uvs, mat, tex, stencil;
468                 if (!BKE_paint_proj_mesh_data_check(scene, ob, &uvs, &mat, &tex, &stencil)) {
469                         BKE_paint_data_warning(op->reports, uvs, mat, tex, stencil);
470                         MEM_freeN(pop);
471                         WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);
472                         return NULL;
473                 }
474                 pop->mode = PAINT_MODE_3D_PROJECT;
475                 pop->custom_paint = paint_proj_new_stroke(C, ob, mouse, mode);
476         }
477         else {
478                 pop->mode = PAINT_MODE_2D;
479                 pop->custom_paint = paint_2d_new_stroke(C, op, mode);
480         }
481
482         if (!pop->custom_paint) {
483                 MEM_freeN(pop);
484                 return NULL;
485         }
486
487         if ((brush->imagepaint_tool == PAINT_TOOL_FILL) && (brush->flag & BRUSH_USE_GRADIENT)) {
488                 pop->cursor = WM_paint_cursor_activate(CTX_wm_manager(C), image_paint_poll, gradient_draw_line, pop);
489         }
490
491         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
492         ED_image_undo_push_begin(op->type->name);
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, ePaintTexture2D, 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 == ePaintTextureProjective) && !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 == ePaintTextureProjective) && !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 == ePaintTextureProjective) && !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 void PAINT_OT_sample_color(wmOperatorType *ot)
1022 {
1023         /* identifiers */
1024         ot->name = "Sample Color";
1025         ot->idname = "PAINT_OT_sample_color";
1026         ot->description = "Use the mouse to sample a color in the image";
1027
1028         /* api callbacks */
1029         ot->exec = sample_color_exec;
1030         ot->invoke = sample_color_invoke;
1031         ot->modal = sample_color_modal;
1032         ot->poll = image_paint_ignore_tool_poll;
1033
1034         /* flags */
1035         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1036
1037         /* properties */
1038         PropertyRNA *prop;
1039
1040         prop = RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384);
1041         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
1042
1043         RNA_def_boolean(ot->srna, "merged", 0, "Sample Merged", "Sample the output display color");
1044         RNA_def_boolean(ot->srna, "palette", 0, "Add to Palette", "");
1045 }
1046
1047 /******************** texture paint toggle operator ********************/
1048
1049 static bool texture_paint_toggle_poll(bContext *C)
1050 {
1051         Object *ob = CTX_data_active_object(C);
1052         if (ob == NULL || ob->type != OB_MESH)
1053                 return 0;
1054         if (!ob->data || ID_IS_LINKED(ob->data))
1055                 return 0;
1056         if (CTX_data_edit_object(C))
1057                 return 0;
1058
1059         return 1;
1060 }
1061
1062 static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
1063 {
1064         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
1065         Main *bmain = CTX_data_main(C);
1066         Scene *scene = CTX_data_scene(C);
1067         Object *ob = CTX_data_active_object(C);
1068         const int mode_flag = OB_MODE_TEXTURE_PAINT;
1069         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1070
1071         if (!is_mode_set) {
1072                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1073                         return OPERATOR_CANCELLED;
1074                 }
1075         }
1076
1077         if (ob->mode & mode_flag) {
1078                 ob->mode &= ~mode_flag;
1079
1080                 if (U.glreslimit != 0)
1081                         GPU_free_images(bmain);
1082                 GPU_paint_set_mipmap(bmain, 1);
1083
1084                 toggle_paint_cursor(C, 0);
1085         }
1086         else {
1087                 bScreen *sc;
1088                 Image *ima = NULL;
1089                 ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
1090
1091                 /* This has to stay here to regenerate the texture paint
1092                  * cache in case we are loading a file */
1093                 BKE_texpaint_slots_refresh_object(scene, ob);
1094
1095                 BKE_paint_proj_mesh_data_check(scene, ob, NULL, NULL, NULL, NULL);
1096
1097                 /* entering paint mode also sets image to editors */
1098                 if (imapaint->mode == IMAGEPAINT_MODE_MATERIAL) {
1099                         Material *ma = give_current_material(ob, ob->actcol); /* set the current material active paint slot on image editor */
1100
1101                         if (ma && ma->texpaintslot)
1102                                 ima = ma->texpaintslot[ma->paint_active_slot].ima;
1103                 }
1104                 else if (imapaint->mode == IMAGEPAINT_MODE_IMAGE) {
1105                         ima = imapaint->canvas;
1106                 }
1107
1108                 if (ima) {
1109                         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1110                                 ScrArea *sa;
1111                                 for (sa = sc->areabase.first; sa; sa = sa->next) {
1112                                         SpaceLink *sl;
1113                                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
1114                                                 if (sl->spacetype == SPACE_IMAGE) {
1115                                                         SpaceImage *sima = (SpaceImage *)sl;
1116
1117                                                         if (!sima->pin) {
1118                                                                 Object *obedit = CTX_data_edit_object(C);
1119                                                                 ED_space_image_set(bmain, sima, scene, obedit, ima);
1120                                                         }
1121                                                 }
1122                                         }
1123                                 }
1124                         }
1125                 }
1126
1127                 ob->mode |= mode_flag;
1128
1129                 BKE_paint_init(bmain, scene, ePaintTextureProjective, PAINT_CURSOR_TEXTURE_PAINT);
1130
1131                 if (U.glreslimit != 0)
1132                         GPU_free_images(bmain);
1133                 GPU_paint_set_mipmap(bmain, 0);
1134
1135                 toggle_paint_cursor(C, 1);
1136         }
1137
1138         Mesh *me = BKE_mesh_from_object(ob);
1139         BLI_assert(me != NULL);
1140         DEG_id_tag_update(&me->id, DEG_TAG_COPY_ON_WRITE);
1141
1142         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1143
1144         WM_msg_publish_rna_prop(mbus, &ob->id, ob, Object, mode);
1145
1146         WM_toolsystem_update_from_context_view3d(C);
1147
1148         return OPERATOR_FINISHED;
1149 }
1150
1151 void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
1152 {
1153         /* identifiers */
1154         ot->name = "Texture Paint Toggle";
1155         ot->idname = "PAINT_OT_texture_paint_toggle";
1156         ot->description = "Toggle texture paint mode in 3D view";
1157
1158         /* api callbacks */
1159         ot->exec = texture_paint_toggle_exec;
1160         ot->poll = texture_paint_toggle_poll;
1161
1162         /* flags */
1163         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1164 }
1165
1166
1167 static int brush_colors_flip_exec(bContext *C, wmOperator *UNUSED(op))
1168 {
1169         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1170
1171         Object *ob = CTX_data_active_object(C);
1172         Brush *br;
1173         if (!(ob && (ob->mode & OB_MODE_VERTEX_PAINT))) {
1174                 br = image_paint_brush(C);
1175         }
1176         else {
1177                 /* At the moment, wpaint does not support the color flipper.
1178                  * So for now we're only handling vpaint */
1179                 ToolSettings *ts = CTX_data_tool_settings(C);
1180                 VPaint *vp = ts->vpaint;
1181                 br = BKE_paint_brush(&vp->paint);
1182         }
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 1;
1201         }
1202         else {
1203                 Object *ob = CTX_data_active_object(C);
1204                 if (ob && (ob->mode & OB_MODE_VERTEX_PAINT)) {
1205                         return 1;
1206                 }
1207         }
1208         return 0;
1209 }
1210
1211 void PAINT_OT_brush_colors_flip(wmOperatorType *ot)
1212 {
1213         /* identifiers */
1214         ot->name = "Brush Colors Flip";
1215         ot->idname = "PAINT_OT_brush_colors_flip";
1216         ot->description = "Toggle foreground and background brush colors";
1217
1218         /* api callbacks */
1219         ot->exec = brush_colors_flip_exec;
1220         ot->poll = brush_colors_flip_poll;
1221
1222         /* flags */
1223         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1224 }
1225
1226
1227 void ED_imapaint_bucket_fill(struct bContext *C, float color[3], wmOperator *op)
1228 {
1229         wmWindowManager *wm = CTX_wm_manager(C);
1230         SpaceImage *sima = CTX_wm_space_image(C);
1231         Image *ima = sima->image;
1232
1233         BKE_undosys_step_push_init_with_type(wm->undo_stack, C, op->type->name, BKE_UNDOSYS_TYPE_IMAGE);
1234
1235         ED_image_undo_push_begin(op->type->name);
1236
1237         paint_2d_bucket_fill(C, color, NULL, NULL, NULL);
1238
1239         BKE_undosys_step_push(wm->undo_stack, C, op->type->name);
1240
1241         DEG_id_tag_update(&ima->id, 0);
1242 }
1243
1244
1245 static bool texture_paint_poll(bContext *C)
1246 {
1247         if (texture_paint_toggle_poll(C))
1248                 if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT)
1249                         return 1;
1250
1251         return 0;
1252 }
1253
1254 bool image_texture_paint_poll(bContext *C)
1255 {
1256         return (texture_paint_poll(C) || image_paint_poll(C));
1257 }
1258
1259 bool facemask_paint_poll(bContext *C)
1260 {
1261         return BKE_paint_select_face_test(CTX_data_active_object(C));
1262 }
1263
1264 bool vert_paint_poll(bContext *C)
1265 {
1266         return BKE_paint_select_vert_test(CTX_data_active_object(C));
1267 }
1268
1269 bool mask_paint_poll(bContext *C)
1270 {
1271         return BKE_paint_select_elem_test(CTX_data_active_object(C));
1272 }