Texpaint refactor complete!
[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 #ifdef WIN32
40 #  include "BLI_winstuff.h"
41 #endif
42
43 #include "BLI_math.h"
44 #include "BLI_blenlib.h"
45 #include "BLI_linklist.h"
46 #include "BLI_memarena.h"
47 #include "BLI_threads.h"
48 #include "BLI_utildefines.h"
49
50 #include "PIL_time.h"
51
52 #include "IMB_imbuf.h"
53 #include "IMB_imbuf_types.h"
54
55 #include "DNA_brush_types.h"
56 #include "DNA_mesh_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59
60 #include "BKE_camera.h"
61 #include "BKE_context.h"
62 #include "BKE_depsgraph.h"
63 #include "BKE_DerivedMesh.h"
64 #include "BKE_idprop.h"
65 #include "BKE_brush.h"
66 #include "BKE_image.h"
67 #include "BKE_library.h"
68 #include "BKE_main.h"
69 #include "BKE_mesh.h"
70 #include "BKE_node.h"
71 #include "BKE_object.h"
72 #include "BKE_paint.h"
73 #include "BKE_report.h"
74 #include "BKE_scene.h"
75 #include "BKE_colortools.h"
76
77 #include "BKE_tessmesh.h"
78
79 #include "BIF_gl.h"
80 #include "BIF_glutil.h"
81
82 #include "UI_view2d.h"
83
84 #include "ED_image.h"
85 #include "ED_screen.h"
86 #include "ED_sculpt.h"
87 #include "ED_uvedit.h"
88 #include "ED_view3d.h"
89 #include "ED_mesh.h"
90
91 #include "WM_api.h"
92 #include "WM_types.h"
93
94 #include "RNA_access.h"
95 #include "RNA_define.h"
96 #include "RNA_enum_types.h"
97
98 #include "GPU_draw.h"
99
100 #include "IMB_colormanagement.h"
101
102 #include "paint_intern.h"
103
104 #define IMAPAINT_TILE_BITS          6
105 #define IMAPAINT_TILE_SIZE          (1 << IMAPAINT_TILE_BITS)
106 #define IMAPAINT_TILE_NUMBER(size)  (((size) + IMAPAINT_TILE_SIZE - 1) >> IMAPAINT_TILE_BITS)
107
108 #define PROJ_VIEW_DATA_ID "view_data"
109 #define PROJ_VIEW_DATA_SIZE (4 * 4 + 4 * 4 + 3) /* viewmat + winmat + clipsta + clipend + is_ortho */
110
111 typedef struct UndoImageTile {
112         struct UndoImageTile *next, *prev;
113
114         char idname[MAX_ID_NAME];  /* name instead of pointer*/
115         char ibufname[IB_FILENAME_SIZE];
116
117         union {
118                 float        *fp;
119                 unsigned int *uint;
120                 void         *pt;
121         } rect;
122         int x, y;
123
124         short source, use_float;
125         char gen_type;
126 } UndoImageTile;
127
128 /* this is a static resource for non-globality,
129  * Maybe it should be exposed as part of the
130  * paint operation, but for now just give a public interface */
131 static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
132
133 ImagePaintPartialRedraw *get_imapaintpartial(void)
134 {
135         return &imapaintpartial;
136 }
137
138 void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr)
139 {
140         imapaintpartial = *ippr;
141 }
142
143 /* UNDO */
144
145 static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, int restore)
146 {
147         /* copy or swap contents of tile->rect and region in ibuf->rect */
148         IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
149                     tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
150
151         if (ibuf->rect_float) {
152                 SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
153         }
154         else {
155                 SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
156         }
157         
158         if (restore)
159                 IMB_rectcpy(ibuf, tmpibuf, tile->x * IMAPAINT_TILE_SIZE,
160                             tile->y * IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
161 }
162
163 void *image_undo_push_tile(Image *ima, ImBuf *ibuf, ImBuf **tmpibuf, int x_tile, int y_tile)
164 {
165         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
166         UndoImageTile *tile;
167         int allocsize;
168         short use_float = ibuf->rect_float ? 1 : 0;
169
170         for (tile = lb->first; tile; tile = tile->next)
171                 if (tile->x == x_tile && tile->y == y_tile && ima->gen_type == tile->gen_type && ima->source == tile->source)
172                         if (tile->use_float == use_float)
173                                 if (strcmp(tile->idname, ima->id.name) == 0 && strcmp(tile->ibufname, ibuf->name) == 0)
174                                         return tile->rect.pt;
175         
176         if (*tmpibuf == NULL)
177                 *tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, IB_rectfloat | IB_rect);
178         
179         tile = MEM_callocN(sizeof(UndoImageTile), "UndoImageTile");
180         BLI_strncpy(tile->idname, ima->id.name, sizeof(tile->idname));
181         tile->x = x_tile;
182         tile->y = y_tile;
183
184         allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
185         allocsize *= (ibuf->rect_float) ? sizeof(float) : sizeof(char);
186         tile->rect.pt = MEM_mapallocN(allocsize, "UndeImageTile.rect");
187
188         BLI_strncpy(tile->ibufname, ibuf->name, sizeof(tile->ibufname));
189
190         tile->gen_type = ima->gen_type;
191         tile->source = ima->source;
192         tile->use_float = use_float;
193
194         undo_copy_tile(tile, *tmpibuf, ibuf, 0);
195         undo_paint_push_count_alloc(UNDO_PAINT_IMAGE, allocsize);
196
197         BLI_addtail(lb, tile);
198         
199         return tile->rect.pt;
200 }
201
202 void image_undo_restore(bContext *C, ListBase *lb)
203 {
204         Main *bmain = CTX_data_main(C);
205         Image *ima = NULL;
206         ImBuf *ibuf, *tmpibuf;
207         UndoImageTile *tile;
208
209         tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
210                                  IB_rectfloat | IB_rect);
211
212         for (tile = lb->first; tile; tile = tile->next) {
213                 short use_float;
214
215                 /* find image based on name, pointer becomes invalid with global undo */
216                 if (ima && strcmp(tile->idname, ima->id.name) == 0) {
217                         /* ima is valid */
218                 }
219                 else {
220                         ima = BLI_findstring(&bmain->image, tile->idname, offsetof(ID, name));
221                 }
222
223                 ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
224
225                 if (ima && ibuf && strcmp(tile->ibufname, ibuf->name) != 0) {
226                         /* current ImBuf filename was changed, probably current frame
227                          * was changed when paiting on image sequence, rather than storing
228                          * full image user (which isn't so obvious, btw) try to find ImBuf with
229                          * matched file name in list of already loaded images */
230
231                         BKE_image_release_ibuf(ima, ibuf, NULL);
232
233                         ibuf = BLI_findstring(&ima->ibufs, tile->ibufname, offsetof(ImBuf, name));
234                 }
235
236                 if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) {
237                         BKE_image_release_ibuf(ima, ibuf, NULL);
238                         continue;
239                 }
240
241                 if (ima->gen_type != tile->gen_type || ima->source != tile->source) {
242                         BKE_image_release_ibuf(ima, ibuf, NULL);
243                         continue;
244                 }
245
246                 use_float = ibuf->rect_float ? 1 : 0;
247
248                 if (use_float != tile->use_float) {
249                         BKE_image_release_ibuf(ima, ibuf, NULL);
250                         continue;
251                 }
252
253                 undo_copy_tile(tile, tmpibuf, ibuf, 1);
254
255                 GPU_free_image(ima); /* force OpenGL reload */
256                 if (ibuf->rect_float)
257                         ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
258                 if (ibuf->mipmap[0])
259                         ibuf->userflags |= IB_MIPMAP_INVALID;  /* force mipmap recreatiom */
260                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
261
262                 BKE_image_release_ibuf(ima, ibuf, NULL);
263         }
264
265         IMB_freeImBuf(tmpibuf);
266 }
267
268 void image_undo_free(ListBase *lb)
269 {
270         UndoImageTile *tile;
271
272         for (tile = lb->first; tile; tile = tile->next)
273                 MEM_freeN(tile->rect.pt);
274 }
275
276 /* Imagepaint Partial Redraw & Dirty Region */
277
278 void imapaint_clear_partial_redraw(void)
279 {
280         memset(&imapaintpartial, 0, sizeof(imapaintpartial));
281 }
282
283 void imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h)
284 {
285         ImBuf *tmpibuf = NULL;
286         int srcx = 0, srcy = 0, origx;
287
288         IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h);
289
290         if (w == 0 || h == 0)
291                 return;
292         
293         if (!imapaintpartial.enabled) {
294                 imapaintpartial.x1 = x;
295                 imapaintpartial.y1 = y;
296                 imapaintpartial.x2 = x + w;
297                 imapaintpartial.y2 = y + h;
298                 imapaintpartial.enabled = 1;
299         }
300         else {
301                 imapaintpartial.x1 = min_ii(imapaintpartial.x1, x);
302                 imapaintpartial.y1 = min_ii(imapaintpartial.y1, y);
303                 imapaintpartial.x2 = max_ii(imapaintpartial.x2, x + w);
304                 imapaintpartial.y2 = max_ii(imapaintpartial.y2, y + h);
305         }
306
307         w = ((x + w - 1) >> IMAPAINT_TILE_BITS);
308         h = ((y + h - 1) >> IMAPAINT_TILE_BITS);
309         origx = (x >> IMAPAINT_TILE_BITS);
310         y = (y >> IMAPAINT_TILE_BITS);
311         
312         for (; y <= h; y++)
313                 for (x = origx; x <= w; x++)
314                         image_undo_push_tile(ima, ibuf, &tmpibuf, x, y);
315
316         ibuf->userflags |= IB_BITMAPDIRTY;
317         
318         if (tmpibuf)
319                 IMB_freeImBuf(tmpibuf);
320 }
321
322 void imapaint_image_update(SpaceImage *sima, Image *image, ImBuf *ibuf, short texpaint)
323 {
324         if (imapaintpartial.x1 != imapaintpartial.x2 &&
325             imapaintpartial.y1 != imapaintpartial.y2)
326         {
327                 IMB_partial_display_buffer_update_delayed(ibuf, imapaintpartial.x1, imapaintpartial.y1,
328                                                           imapaintpartial.x2, imapaintpartial.y2);
329         }
330         
331         if (ibuf->mipmap[0])
332                 ibuf->userflags |= IB_MIPMAP_INVALID;
333
334         /* todo: should set_tpage create ->rect? */
335         if (texpaint || (sima && sima->lock)) {
336                 int w = imapaintpartial.x2 - imapaintpartial.x1;
337                 int h = imapaintpartial.y2 - imapaintpartial.y1;
338                 /* Testing with partial update in uv editor too */
339                 GPU_paint_update_image(image, imapaintpartial.x1, imapaintpartial.y1, w, h); //!texpaint);
340         }
341 }
342
343 /************************ image paint poll ************************/
344
345 static Brush *image_paint_brush(bContext *C)
346 {
347         Scene *scene = CTX_data_scene(C);
348         ToolSettings *settings = scene->toolsettings;
349
350         return paint_brush(&settings->imapaint.paint);
351 }
352
353 static int image_paint_poll(bContext *C)
354 {
355         Object *obact = CTX_data_active_object(C);
356
357         if (!image_paint_brush(C))
358                 return 0;
359
360         if ((obact && obact->mode & OB_MODE_TEXTURE_PAINT) && CTX_wm_region_view3d(C)) {
361                 return 1;
362         }
363         else {
364                 SpaceImage *sima = CTX_wm_space_image(C);
365
366                 if (sima) {
367                         ARegion *ar = CTX_wm_region(C);
368
369                         if ((sima->mode == SI_MODE_PAINT) && ar->regiontype == RGN_TYPE_WINDOW) {
370                                 return 1;
371                         }
372                 }
373         }
374
375         return 0;
376 }
377
378 static int image_paint_3d_poll(bContext *C)
379 {
380         if (CTX_wm_region_view3d(C))
381                 return image_paint_poll(C);
382         
383         return 0;
384 }
385
386 static int image_paint_2d_clone_poll(bContext *C)
387 {
388         Brush *brush = image_paint_brush(C);
389
390         if (!CTX_wm_region_view3d(C) && image_paint_poll(C))
391                 if (brush && (brush->imagepaint_tool == PAINT_TOOL_CLONE))
392                         if (brush->clone.image)
393                                 return 1;
394         
395         return 0;
396 }
397
398 /************************ paint operator ************************/
399 typedef enum TexPaintMode {
400         PAINT_MODE_2D,
401         PAINT_MODE_3D_PROJECT
402 } TexPaintMode;
403
404 typedef struct PaintOperation {
405         TexPaintMode mode;
406
407         void *custom_paint;
408
409         int prevmouse[2];
410         double starttime;
411
412         ViewContext vc;
413         wmTimer *timer;
414 } PaintOperation;
415
416 void paint_brush_init_tex(Brush *brush)
417 {
418         /* init mtex nodes */
419         if (brush) {
420                 MTex *mtex = &brush->mtex;
421                 if (mtex->tex && mtex->tex->nodetree)
422                         ntreeTexBeginExecTree(mtex->tex->nodetree, 1);  /* has internal flag to detect it only does it once */
423         }
424 }
425
426 void paint_brush_exit_tex(Brush *brush)
427 {
428         if (brush) {
429                 MTex *mtex = &brush->mtex;
430                 if (mtex->tex && mtex->tex->nodetree)
431                         ntreeTexEndExecTree(mtex->tex->nodetree->execdata, 1);
432         }
433 }
434
435
436 static void paint_redraw(const bContext *C, PaintOperation *pop, int final)
437 {
438         if (pop->mode == PAINT_MODE_2D) {
439                 paint_2d_redraw(C, pop->custom_paint, final);
440         }
441         else {
442                 if (final) {
443                         /* compositor listener deals with updating */
444                         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, NULL);
445                 }
446                 else {
447                         ED_region_tag_redraw(CTX_wm_region(C));
448                 }
449         }
450 }
451
452 static PaintOperation * texture_paint_init(bContext *C, wmOperator *op, wmEvent *event)
453 {
454         Scene *scene = CTX_data_scene(C);
455         ToolSettings *settings = scene->toolsettings;
456         PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
457
458         view3d_set_viewcontext(C, &pop->vc);
459
460         /* TODO Should avoid putting this here. Instead, last position should be requested
461          * from stroke system. */
462         pop->prevmouse[0] = event->mval[0];
463         pop->prevmouse[1] = event->mval[1];
464
465
466         /* initialize from context */
467         if (CTX_wm_region_view3d(C)) {
468                 pop->mode = PAINT_MODE_3D_PROJECT;
469                 pop->custom_paint = paint_proj_new_stroke(C, OBACT, pop->prevmouse);
470         }
471         else {
472                 pop->mode = PAINT_MODE_2D;
473                 pop->custom_paint = paint_2d_new_stroke(C, op);
474         }
475
476         if (!pop->custom_paint) {
477                 MEM_freeN(pop);
478                 return NULL;
479         }
480
481         settings->imapaint.flag |= IMAGEPAINT_DRAWING;
482         undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
483                               image_undo_restore, image_undo_free);
484
485         {
486                 UnifiedPaintSettings *ups = &settings->unified_paint_settings;
487                 ups->draw_pressure = true;
488         }
489
490         return pop;
491 }
492
493 static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
494 {
495         PaintOperation *pop = paint_stroke_mode_data(stroke);
496         Scene *scene = CTX_data_scene(C);
497         Brush *brush = paint_brush(&scene->toolsettings->imapaint.paint);
498
499         /* initial brush values. Maybe it should be considered moving these to stroke system */
500         float startsize = BKE_brush_size_get(scene, brush);
501         float startalpha = BKE_brush_alpha_get(scene, brush);
502
503         float mousef[2];
504         float pressure;
505         int mouse[2], redraw, eraser;
506
507         RNA_float_get_array(itemptr, "mouse", mousef);
508         mouse[0] = (int)(mousef[0]);
509         mouse[1] = (int)(mousef[1]);
510         pressure = RNA_float_get(itemptr, "pressure");
511         eraser = RNA_boolean_get(itemptr, "pen_flip");
512
513         if (BKE_brush_use_alpha_pressure(scene, brush))
514                 BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * pressure));
515         if (BKE_brush_use_size_pressure(scene, brush))
516                 BKE_brush_size_set(scene, brush, max_ff(1.0f, startsize * pressure));
517
518         if (pop->mode == PAINT_MODE_3D_PROJECT) {
519                 redraw = paint_proj_stroke(pop->custom_paint, pop->prevmouse, mouse);
520         }
521         else {
522                 redraw = paint_2d_stroke(pop->custom_paint, pop->prevmouse, mouse, eraser);
523         }
524
525         pop->prevmouse[0] = mouse[0];
526         pop->prevmouse[1] = mouse[1];
527
528         /* restore brush values */
529         BKE_brush_alpha_set(scene, brush, startalpha);
530         BKE_brush_size_set(scene, brush, startsize);
531
532
533         if (redraw)
534                 paint_redraw(C, pop, 0);
535
536 }
537
538 static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke)
539 {
540         Scene *scene = CTX_data_scene(C);
541         ToolSettings *settings = scene->toolsettings;
542         PaintOperation *pop = paint_stroke_mode_data(stroke);
543
544         if (pop->timer)
545                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), pop->timer);
546
547         settings->imapaint.flag &= ~IMAGEPAINT_DRAWING;
548
549         if (pop->mode == PAINT_MODE_3D_PROJECT) {
550                 paint_proj_stroke_done(pop->custom_paint);
551         }
552         else {
553                 paint_2d_stroke_done(pop->custom_paint);
554         }
555
556         paint_redraw(C, pop, 1);
557         undo_paint_push_end(UNDO_PAINT_IMAGE);
558
559         /* duplicate warning, see texpaint_init
560         if (pop->s.warnmultifile)
561                 BKE_reportf(op->reports, RPT_WARNING, "Image requires 4 color channels to paint: %s", pop->s.warnmultifile);
562         if (pop->s.warnpackedfile)
563                 BKE_reportf(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted: %s", pop->s.warnpackedfile);
564         */
565         MEM_freeN(pop);
566
567         {
568                 UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
569                 ups->draw_pressure = false;
570         }
571 }
572
573 static int paint_stroke_test_start(bContext *UNUSED(C), wmOperator *UNUSED(op), const float UNUSED(mouse[2]))
574 {
575         return true;
576 }
577
578
579 static int paint_invoke(bContext *C, wmOperator *op, wmEvent *event)
580 {
581         PaintOperation *pop;
582         struct PaintStroke *stroke;
583         int retval;
584
585         if (!(pop = texture_paint_init(C, op, event))) {
586                 return OPERATOR_CANCELLED;
587         }
588
589         stroke = op->customdata = paint_stroke_new(C, NULL, paint_stroke_test_start,
590                                           paint_stroke_update_step,
591                                           paint_stroke_done, event->type);
592         paint_stroke_set_mode_data(stroke, pop);
593         /* add modal handler */
594         WM_event_add_modal_handler(C, op);
595
596         retval = op->type->modal(C, op, event);
597         OPERATOR_RETVAL_CHECK(retval);
598         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
599
600         return OPERATOR_RUNNING_MODAL;
601 }
602
603
604 void PAINT_OT_image_paint(wmOperatorType *ot)
605 {
606
607         /* identifiers */
608         ot->name = "Image Paint";
609         ot->idname = "PAINT_OT_image_paint";
610         ot->description = "Paint a stroke into the image";
611
612         /* api callbacks */
613         ot->invoke = paint_invoke;
614         ot->modal = paint_stroke_modal;
615         /* ot->exec = paint_exec; <-- needs stroke property */
616         ot->poll = image_paint_poll;
617         ot->cancel = paint_stroke_cancel;
618
619         /* flags */
620         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
621
622         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
623 }
624
625
626 static int get_imapaint_zoom(bContext *C, float *zoomx, float *zoomy)
627 {
628         RegionView3D *rv3d = CTX_wm_region_view3d(C);
629
630         if (!rv3d) {
631                 SpaceImage *sima = CTX_wm_space_image(C);
632                 ARegion *ar = CTX_wm_region(C);
633
634                 if (sima->mode == SI_MODE_PAINT) {
635                         ED_space_image_get_zoom(sima, ar, zoomx, zoomy);
636
637                         return 1;
638                 }
639         }
640
641         *zoomx = *zoomy = 1;
642
643         return 0;
644 }
645
646 /************************ cursor drawing *******************************/
647
648 void brush_drawcursor_texpaint_uvsculpt(bContext *C, int x, int y, void *UNUSED(customdata))
649 {
650 #define PX_SIZE_FADE_MAX 12.0f
651 #define PX_SIZE_FADE_MIN 4.0f
652
653         Scene *scene = CTX_data_scene(C);
654         //Brush *brush = image_paint_brush(C);
655         Paint *paint = paint_get_active_from_context(C);
656         Brush *brush = paint_brush(paint);
657
658         if (paint && brush && paint->flags & PAINT_SHOW_BRUSH) {
659                 float zoomx, zoomy;
660                 const float size = (float)BKE_brush_size_get(scene, brush);
661                 short use_zoom;
662                 float pixel_size;
663                 float alpha = 0.5f;
664
665                 use_zoom = get_imapaint_zoom(C, &zoomx, &zoomy);
666
667                 if (use_zoom) {
668                         pixel_size = size * max_ff(zoomx, zoomy);
669                 }
670                 else {
671                         pixel_size = size;
672                 }
673
674                 /* fade out the brush (cheap trick to work around brush interfering with sampling [#])*/
675                 if (pixel_size < PX_SIZE_FADE_MIN) {
676                         return;
677                 }
678                 else if (pixel_size < PX_SIZE_FADE_MAX) {
679                         alpha *= (pixel_size - PX_SIZE_FADE_MIN) / (PX_SIZE_FADE_MAX - PX_SIZE_FADE_MIN);
680                 }
681
682                 glPushMatrix();
683
684                 glTranslatef((float)x, (float)y, 0.0f);
685
686                 /* No need to scale for uv sculpting, on the contrary it might be useful to keep un-scaled */
687                 if (use_zoom)
688                         glScalef(zoomx, zoomy, 1.0f);
689
690                 glColor4f(brush->add_col[0], brush->add_col[1], brush->add_col[2], alpha);
691                 glEnable(GL_LINE_SMOOTH);
692                 glEnable(GL_BLEND);
693                 {
694                         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
695                         /* hrmf, duplicate paint_draw_cursor logic here */
696                         if (ups->draw_pressure && BKE_brush_use_size_pressure(scene, brush)) {
697                                 /* inner at full alpha */
698                                 glutil_draw_lined_arc(0, (float)(M_PI * 2.0), size * ups->pressure_value, 40);
699                                 /* outer at half alpha */
700                                 glColor4f(brush->add_col[0], brush->add_col[1], brush->add_col[2], alpha * 0.5f);
701                         }
702                 }
703                 glutil_draw_lined_arc(0, (float)(M_PI * 2.0), size, 40);
704                 glDisable(GL_BLEND);
705                 glDisable(GL_LINE_SMOOTH);
706
707                 glPopMatrix();
708         }
709 #undef PX_SIZE_FADE_MAX
710 #undef PX_SIZE_FADE_MIN
711 }
712
713 static void toggle_paint_cursor(bContext *C, int enable)
714 {
715         wmWindowManager *wm = CTX_wm_manager(C);
716         Scene *scene = CTX_data_scene(C);
717         ToolSettings *settings = scene->toolsettings;
718
719         if (settings->imapaint.paintcursor && !enable) {
720                 WM_paint_cursor_end(wm, settings->imapaint.paintcursor);
721                 settings->imapaint.paintcursor = NULL;
722         }
723         else if (enable)
724                 settings->imapaint.paintcursor =
725                         WM_paint_cursor_activate(wm, image_paint_poll, brush_drawcursor_texpaint_uvsculpt, NULL);
726 }
727
728 /* enable the paint cursor if it isn't already.
729  *
730  * purpose is to make sure the paint cursor is shown if paint
731  * mode is enabled in the image editor. the paint poll will
732  * ensure that the cursor is hidden when not in paint mode */
733 void ED_space_image_paint_update(wmWindowManager *wm, ToolSettings *settings)
734 {
735         wmWindow *win;
736         ScrArea *sa;
737         ImagePaintSettings *imapaint = &settings->imapaint;
738         int enabled = FALSE;
739
740         for (win = wm->windows.first; win; win = win->next)
741                 for (sa = win->screen->areabase.first; sa; sa = sa->next)
742                         if (sa->spacetype == SPACE_IMAGE)
743                                 if (((SpaceImage *)sa->spacedata.first)->mode == SI_MODE_PAINT)
744                                         enabled = TRUE;
745
746         if (enabled) {
747                 BKE_paint_init(&imapaint->paint, PAINT_CURSOR_TEXTURE_PAINT);
748
749                 if (!imapaint->paintcursor) {
750                         imapaint->paintcursor =
751                                 WM_paint_cursor_activate(wm, image_paint_poll,
752                                                          brush_drawcursor_texpaint_uvsculpt, NULL);
753                 }
754         }
755 }
756
757 /************************ grab clone operator ************************/
758
759 typedef struct GrabClone {
760         float startoffset[2];
761         int startx, starty;
762 } GrabClone;
763
764 static void grab_clone_apply(bContext *C, wmOperator *op)
765 {
766         Brush *brush = image_paint_brush(C);
767         float delta[2];
768
769         RNA_float_get_array(op->ptr, "delta", delta);
770         add_v2_v2(brush->clone.offset, delta);
771         ED_region_tag_redraw(CTX_wm_region(C));
772 }
773
774 static int grab_clone_exec(bContext *C, wmOperator *op)
775 {
776         grab_clone_apply(C, op);
777
778         return OPERATOR_FINISHED;
779 }
780
781 static int grab_clone_invoke(bContext *C, wmOperator *op, wmEvent *event)
782 {
783         Brush *brush = image_paint_brush(C);
784         GrabClone *cmv;
785
786         cmv = MEM_callocN(sizeof(GrabClone), "GrabClone");
787         copy_v2_v2(cmv->startoffset, brush->clone.offset);
788         cmv->startx = event->x;
789         cmv->starty = event->y;
790         op->customdata = cmv;
791
792         WM_event_add_modal_handler(C, op);
793
794         return OPERATOR_RUNNING_MODAL;
795 }
796
797 static int grab_clone_modal(bContext *C, wmOperator *op, wmEvent *event)
798 {
799         Brush *brush = image_paint_brush(C);
800         ARegion *ar = CTX_wm_region(C);
801         GrabClone *cmv = op->customdata;
802         float startfx, startfy, fx, fy, delta[2];
803         int xmin = ar->winrct.xmin, ymin = ar->winrct.ymin;
804
805         switch (event->type) {
806                 case LEFTMOUSE:
807                 case MIDDLEMOUSE:
808                 case RIGHTMOUSE: // XXX hardcoded
809                         MEM_freeN(op->customdata);
810                         return OPERATOR_FINISHED;
811                 case MOUSEMOVE:
812                         /* mouse moved, so move the clone image */
813                         UI_view2d_region_to_view(&ar->v2d, cmv->startx - xmin, cmv->starty - ymin, &startfx, &startfy);
814                         UI_view2d_region_to_view(&ar->v2d, event->x - xmin, event->y - ymin, &fx, &fy);
815
816                         delta[0] = fx - startfx;
817                         delta[1] = fy - startfy;
818                         RNA_float_set_array(op->ptr, "delta", delta);
819
820                         copy_v2_v2(brush->clone.offset, cmv->startoffset);
821
822                         grab_clone_apply(C, op);
823                         break;
824         }
825
826         return OPERATOR_RUNNING_MODAL;
827 }
828
829 static int grab_clone_cancel(bContext *UNUSED(C), wmOperator *op)
830 {
831         MEM_freeN(op->customdata);
832         return OPERATOR_CANCELLED;
833 }
834
835 void PAINT_OT_grab_clone(wmOperatorType *ot)
836 {
837         /* identifiers */
838         ot->name = "Grab Clone";
839         ot->idname = "PAINT_OT_grab_clone";
840         ot->description = "Move the clone source image";
841         
842         /* api callbacks */
843         ot->exec = grab_clone_exec;
844         ot->invoke = grab_clone_invoke;
845         ot->modal = grab_clone_modal;
846         ot->cancel = grab_clone_cancel;
847         ot->poll = image_paint_2d_clone_poll;
848
849         /* flags */
850         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
851
852         /* properties */
853         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);
854 }
855
856 /******************** sample color operator ********************/
857
858 static int sample_color_exec(bContext *C, wmOperator *op)
859 {
860         Brush *brush = image_paint_brush(C);
861         ARegion *ar = CTX_wm_region(C);
862         int location[2];
863
864         RNA_int_get_array(op->ptr, "location", location);
865         paint_sample_color(C, ar, location[0], location[1]);
866
867         WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
868         
869         return OPERATOR_FINISHED;
870 }
871
872 static int sample_color_invoke(bContext *C, wmOperator *op, wmEvent *event)
873 {
874         RNA_int_set_array(op->ptr, "location", event->mval);
875         sample_color_exec(C, op);
876
877         WM_event_add_modal_handler(C, op);
878
879         return OPERATOR_RUNNING_MODAL;
880 }
881
882 static int sample_color_modal(bContext *C, wmOperator *op, wmEvent *event)
883 {
884         switch (event->type) {
885                 case LEFTMOUSE:
886                 case RIGHTMOUSE: // XXX hardcoded
887                         return OPERATOR_FINISHED;
888                 case MOUSEMOVE:
889                         RNA_int_set_array(op->ptr, "location", event->mval);
890                         sample_color_exec(C, op);
891                         break;
892         }
893
894         return OPERATOR_RUNNING_MODAL;
895 }
896
897 /* same as image_paint_poll but fail when face mask mode is enabled */
898 static int image_paint_sample_color_poll(bContext *C)
899 {
900         if (image_paint_poll(C)) {
901                 if (CTX_wm_view3d(C)) {
902                         Object *obact = CTX_data_active_object(C);
903                         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT) {
904                                 Mesh *me = BKE_mesh_from_object(obact);
905                                 if (me) {
906                                         return !(me->editflag & ME_EDIT_PAINT_FACE_SEL);
907                                 }
908                         }
909                 }
910
911                 return 1;
912         }
913
914         return 0;
915 }
916
917 void PAINT_OT_sample_color(wmOperatorType *ot)
918 {
919         /* identifiers */
920         ot->name = "Sample Color";
921         ot->idname = "PAINT_OT_sample_color";
922         ot->description = "Use the mouse to sample a color in the image";
923         
924         /* api callbacks */
925         ot->exec = sample_color_exec;
926         ot->invoke = sample_color_invoke;
927         ot->modal = sample_color_modal;
928         ot->poll = image_paint_sample_color_poll;
929
930         /* flags */
931         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
932
933         /* properties */
934         RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "Cursor location in region coordinates", 0, 16384);
935 }
936
937 /******************** set clone cursor operator ********************/
938
939 static int set_clone_cursor_exec(bContext *C, wmOperator *op)
940 {
941         Scene *scene = CTX_data_scene(C);
942         View3D *v3d = CTX_wm_view3d(C);
943         float *cursor = give_cursor(scene, v3d);
944
945         RNA_float_get_array(op->ptr, "location", cursor);
946         
947         ED_area_tag_redraw(CTX_wm_area(C));
948         
949         return OPERATOR_FINISHED;
950 }
951
952 static int set_clone_cursor_invoke(bContext *C, wmOperator *op, wmEvent *event)
953 {
954         Scene *scene = CTX_data_scene(C);
955         View3D *v3d = CTX_wm_view3d(C);
956         ARegion *ar = CTX_wm_region(C);
957         float location[3];
958
959         view3d_operator_needs_opengl(C);
960
961         if (!ED_view3d_autodist(scene, ar, v3d, event->mval, location))
962                 return OPERATOR_CANCELLED;
963
964         RNA_float_set_array(op->ptr, "location", location);
965
966         return set_clone_cursor_exec(C, op);
967 }
968
969 void PAINT_OT_clone_cursor_set(wmOperatorType *ot)
970 {
971         /* identifiers */
972         ot->name = "Set Clone Cursor";
973         ot->idname = "PAINT_OT_clone_cursor_set";
974         ot->description = "Set the location of the clone cursor";
975         
976         /* api callbacks */
977         ot->exec = set_clone_cursor_exec;
978         ot->invoke = set_clone_cursor_invoke;
979         ot->poll = image_paint_3d_poll;
980
981         /* flags */
982         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
983
984         /* properties */
985         RNA_def_float_vector(ot->srna, "location", 3, NULL, -FLT_MAX, FLT_MAX, "Location", "Cursor location in world space coordinates", -10000.0f, 10000.0f);
986 }
987
988 /******************** texture paint toggle operator ********************/
989
990 static int texture_paint_toggle_poll(bContext *C)
991 {
992         if (CTX_data_edit_object(C))
993                 return 0;
994         if (CTX_data_active_object(C) == NULL)
995                 return 0;
996
997         return 1;
998 }
999
1000 static int texture_paint_toggle_exec(bContext *C, wmOperator *op)
1001 {
1002         Scene *scene = CTX_data_scene(C);
1003         Object *ob = CTX_data_active_object(C);
1004         Mesh *me = NULL;
1005         
1006         if (ob == NULL)
1007                 return OPERATOR_CANCELLED;
1008         
1009         if (BKE_object_obdata_is_libdata(ob)) {
1010                 BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
1011                 return OPERATOR_CANCELLED;
1012         }
1013
1014         me = BKE_mesh_from_object(ob);
1015
1016         if (!(ob->mode & OB_MODE_TEXTURE_PAINT) && !me) {
1017                 BKE_report(op->reports, RPT_ERROR, "Can only enter texture paint mode for mesh objects");
1018                 return OPERATOR_CANCELLED;
1019         }
1020
1021         if (ob->mode & OB_MODE_TEXTURE_PAINT) {
1022                 ob->mode &= ~OB_MODE_TEXTURE_PAINT;
1023
1024                 if (U.glreslimit != 0)
1025                         GPU_free_images();
1026                 GPU_paint_set_mipmap(1);
1027
1028                 toggle_paint_cursor(C, 0);
1029         }
1030         else {
1031                 ob->mode |= OB_MODE_TEXTURE_PAINT;
1032
1033                 if (me->mtface == NULL)
1034                         me->mtface = CustomData_add_layer(&me->fdata, CD_MTFACE, CD_DEFAULT,
1035                                                           NULL, me->totface);
1036
1037                 BKE_paint_init(&scene->toolsettings->imapaint.paint, PAINT_CURSOR_TEXTURE_PAINT);
1038
1039                 if (U.glreslimit != 0)
1040                         GPU_free_images();
1041                 GPU_paint_set_mipmap(0);
1042
1043                 toggle_paint_cursor(C, 1);
1044         }
1045
1046         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1047         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1048
1049         return OPERATOR_FINISHED;
1050 }
1051
1052 void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
1053 {
1054         /* identifiers */
1055         ot->name = "Texture Paint Toggle";
1056         ot->idname = "PAINT_OT_texture_paint_toggle";
1057         ot->description = "Toggle texture paint mode in 3D view";
1058         
1059         /* api callbacks */
1060         ot->exec = texture_paint_toggle_exec;
1061         ot->poll = texture_paint_toggle_poll;
1062
1063         /* flags */
1064         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1065 }
1066
1067 static int texture_paint_poll(bContext *C)
1068 {
1069         if (texture_paint_toggle_poll(C))
1070                 if (CTX_data_active_object(C)->mode & OB_MODE_TEXTURE_PAINT)
1071                         return 1;
1072         
1073         return 0;
1074 }
1075
1076 int image_texture_paint_poll(bContext *C)
1077 {
1078         return (texture_paint_poll(C) || image_paint_poll(C));
1079 }
1080
1081 int facemask_paint_poll(bContext *C)
1082 {
1083         return paint_facesel_test(CTX_data_active_object(C));
1084 }
1085
1086 int vert_paint_poll(bContext *C)
1087 {
1088         return paint_vertsel_test(CTX_data_active_object(C));
1089 }
1090
1091 int mask_paint_poll(bContext *C)
1092 {
1093         return paint_facesel_test(CTX_data_active_object(C)) || paint_vertsel_test(CTX_data_active_object(C));
1094 }
1095