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