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