More painting fixes:
[blender.git] / source / blender / editors / sculpt_paint / paint_image_2d.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  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/sculpt_paint/paint_image_2d.c
29  *  \ingroup bke
30  */
31 //#include <math.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_brush_types.h"
37 #include "DNA_scene_types.h"
38 #include "DNA_space_types.h"
39 #include "DNA_object_types.h"
40
41 #include "BLI_math.h"
42 #include "BLI_rect.h"
43
44 #include "BKE_context.h"
45 #include "BKE_brush.h"
46 #include "BKE_main.h"
47 #include "BKE_image.h"
48 #include "BKE_paint.h"
49 #include "BKE_report.h"
50
51 #include "ED_screen.h"
52
53 #include "IMB_imbuf.h"
54 #include "IMB_imbuf_types.h"
55 #include "IMB_colormanagement.h"
56
57 #include "WM_api.h"
58 #include "WM_types.h"
59
60 #include "UI_view2d.h"
61
62 #include "RE_shader_ext.h"
63
64 #include "GPU_draw.h"
65
66 #include "paint_intern.h"
67
68 /* Brush Painting for 2D image editor */
69
70 /* Defines and Structs */
71 /* FTOCHAR as inline function */
72 BLI_INLINE unsigned char f_to_char(const float val)
73 {
74         return FTOCHAR(val);
75 }
76 #define IMAPAINT_FLOAT_RGB_TO_CHAR(c, f)  {                                   \
77         (c)[0] = f_to_char((f)[0]);                                               \
78         (c)[1] = f_to_char((f)[1]);                                               \
79         (c)[2] = f_to_char((f)[2]);                                               \
80 } (void)0
81
82 #define IMAPAINT_CHAR_RGB_TO_FLOAT(f, c)  {                                   \
83         (f)[0] = IMAPAINT_CHAR_TO_FLOAT((c)[0]);                                  \
84         (f)[1] = IMAPAINT_CHAR_TO_FLOAT((c)[1]);                                  \
85         (f)[2] = IMAPAINT_CHAR_TO_FLOAT((c)[2]);                                  \
86 } (void)0
87
88 #define IMAPAINT_FLOAT_RGB_COPY(a, b) copy_v3_v3(a, b)
89
90 typedef struct BrushPainterCache {
91         int size;           /* size override, if 0 uses 2*BKE_brush_size_get(brush) */
92         short flt;          /* need float imbuf? */
93
94         int lastsize;
95         float lastalpha;
96         float lastjitter;
97         float last_rotation;
98
99         ImBuf *ibuf;
100         ImBuf *texibuf;
101         ImBuf *maskibuf;
102 } BrushPainterCache;
103
104 typedef struct BrushPainter {
105         Scene *scene;
106         Brush *brush;
107
108         float lastpaintpos[2];  /* position of last paint op */
109         float startpaintpos[2]; /* position of first paint */
110
111         short firsttouch;       /* first paint op */
112
113         struct ImagePool *pool; /* image pool */
114         rctf mapping;                   /* texture coordinate mapping */
115
116         BrushPainterCache cache;
117 } BrushPainter;
118
119 typedef struct ImagePaintRegion {
120         int destx, desty;
121         int srcx, srcy;
122         int width, height;
123 } ImagePaintRegion;
124
125 typedef struct ImagePaintState {
126         BrushPainter *painter;
127         SpaceImage *sima;
128         View2D *v2d;
129         Scene *scene;
130         bScreen *screen;
131         struct ImagePool *image_pool;
132
133         Brush *brush;
134         short tool, blend;
135         Image *image;
136         ImBuf *canvas;
137         ImBuf *clonecanvas;
138         char *warnpackedfile;
139         char *warnmultifile;
140
141         bool do_masking;
142
143         /* viewport texture paint only, but _not_ project paint */
144         Object *ob;
145         int faceindex;
146         float uv[2];
147         int do_facesel;
148 } ImagePaintState;
149
150
151 static BrushPainter *brush_painter_2d_new(Scene *scene, Brush *brush)
152 {
153         BrushPainter *painter = MEM_callocN(sizeof(BrushPainter), "BrushPainter");
154
155         painter->brush = brush;
156         painter->scene = scene;
157         painter->firsttouch = 1;
158         painter->cache.lastsize = -1; /* force ibuf create in refresh */
159
160         return painter;
161 }
162
163
164 static void brush_painter_2d_require_imbuf(BrushPainter *painter, short flt, int size)
165 {
166         if ((painter->cache.flt != flt) || (painter->cache.size != size)) {
167                 if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
168                 if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
169                 painter->cache.ibuf = painter->cache.maskibuf = NULL;
170                 painter->cache.lastsize = -1; /* force ibuf create in refresh */
171         }
172
173         if (painter->cache.flt != flt) {
174                 if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
175                 painter->cache.texibuf = NULL;
176                 painter->cache.lastsize = -1; /* force ibuf create in refresh */
177         }
178
179         painter->cache.size = size;
180         painter->cache.flt = flt;
181 }
182
183 static void brush_painter_2d_free(BrushPainter *painter)
184 {
185         if (painter->cache.ibuf) IMB_freeImBuf(painter->cache.ibuf);
186         if (painter->cache.texibuf) IMB_freeImBuf(painter->cache.texibuf);
187         if (painter->cache.maskibuf) IMB_freeImBuf(painter->cache.maskibuf);
188         MEM_freeN(painter);
189 }
190
191 static void brush_painter_2d_do_partial(BrushPainter *painter, ImBuf *oldtexibuf,
192                                      int x, int y, int w, int h, int xt, int yt,
193                                      const float pos[2])
194 {
195         Scene *scene = painter->scene;
196         Brush *brush = painter->brush;
197         ImBuf *ibuf, *maskibuf, *texibuf;
198         float *bf, *mf, *tf, *otf = NULL, texco[3], rgba[4];
199         unsigned char *b, *m, *t, *ot = NULL;
200         int dotexold, origx = x, origy = y;
201         int thread = 0;
202         rctf mapping = painter->mapping;
203
204         if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) {
205                 mapping.xmin += (int)pos[0] - (int)painter->startpaintpos[0];
206                 mapping.ymin += (int)pos[1] - (int)painter->startpaintpos[1];
207         }
208
209         ibuf = painter->cache.ibuf;
210         texibuf = painter->cache.texibuf;
211         maskibuf = painter->cache.maskibuf;
212
213         dotexold = (oldtexibuf != NULL);
214
215         /* not sure if it's actually needed or it's a mistake in coords/sizes
216          * calculation in brush_painter_fixed_tex_partial_update(), but without this
217          * limitation memory gets corrupted at fast strokes with quite big spacing (sergey) */
218         w = min_ii(w, ibuf->x);
219         h = min_ii(h, ibuf->y);
220
221         if (painter->cache.flt) {
222                 for (; y < h; y++) {
223                         bf = ibuf->rect_float + (y * ibuf->x + origx) * 4;
224                         tf = texibuf->rect_float + (y * texibuf->x + origx) * 4;
225                         mf = maskibuf->rect_float + (y * maskibuf->x + origx) * 4;
226
227                         if (dotexold)
228                                 otf = oldtexibuf->rect_float + ((y - origy + yt) * oldtexibuf->x + xt) * 4;
229
230                         for (x = origx; x < w; x++, bf += 4, mf += 4, tf += 4) {
231                                 if (dotexold) {
232                                         copy_v4_v4(tf, otf);
233                                         otf += 4;
234                                 }
235                                 else {
236                                         texco[0] = mapping.xmin + x*mapping.xmax;
237                                         texco[1] = mapping.ymin + y*mapping.ymax;
238                                         texco[2] = 0.0f;
239
240                                         BKE_brush_sample_tex_3D(scene, brush, texco, tf, thread, painter->pool);
241                                 }
242
243                                 /* output premultiplied float image, mf was already premultiplied */
244                                 bf[0] = tf[0] * tf[3] * mf[0];
245                                 bf[1] = tf[1] * tf[3] * mf[1];
246                                 bf[2] = tf[2] * tf[3] * mf[2];
247                                 bf[3] = tf[3] * tf[3] * mf[3];
248                         }
249                 }
250         }
251         else {
252                 for (; y < h; y++) {
253                         b = (unsigned char *)ibuf->rect + (y * ibuf->x + origx) * 4;
254                         t = (unsigned char *)texibuf->rect + (y * texibuf->x + origx) * 4;
255                         m = (unsigned char *)maskibuf->rect + (y * maskibuf->x + origx) * 4;
256
257                         if (dotexold)
258                                 ot = (unsigned char *)oldtexibuf->rect + ((y - origy + yt) * oldtexibuf->x + xt) * 4;
259
260                         for (x = origx; x < w; x++, b += 4, m += 4, t += 4) {
261                                 if (dotexold) {
262                                         t[0] = ot[0];
263                                         t[1] = ot[1];
264                                         t[2] = ot[2];
265                                         t[3] = ot[3];
266                                         ot += 4;
267                                 }
268                                 else {
269                                         texco[0] = mapping.xmin + x*mapping.xmax;
270                                         texco[1] = mapping.ymin + y*mapping.ymax;
271                                         texco[2] = 0.0f;
272
273                                         BKE_brush_sample_tex_3D(scene, brush, texco, rgba, thread, painter->pool);
274                                         rgba_float_to_uchar(t, rgba);
275                                 }
276
277                                 b[0] = t[0] * m[0] / 255;
278                                 b[1] = t[1] * m[1] / 255;
279                                 b[2] = t[2] * m[2] / 255;
280                                 b[3] = t[3] * m[3] / 255;
281                         }
282                 }
283         }
284 }
285
286 static void brush_painter_2d_tiled_tex_partial_update(BrushPainter *painter, const float pos[2])
287 {
288         const Scene *scene = painter->scene;
289         Brush *brush = painter->brush;
290         BrushPainterCache *cache = &painter->cache;
291         ImBuf *oldtexibuf, *ibuf;
292         int imbflag, destx, desty, srcx, srcy, w, h, x1, y1, x2, y2;
293         const int diameter = 2 * BKE_brush_size_get(scene, brush);
294
295         imbflag = (cache->flt) ? IB_rectfloat : IB_rect;
296         if (!cache->ibuf)
297                 cache->ibuf = IMB_allocImBuf(diameter, diameter, 32, imbflag);
298         ibuf = cache->ibuf;
299
300         oldtexibuf = cache->texibuf;
301         cache->texibuf = IMB_allocImBuf(diameter, diameter, 32, imbflag);
302         if (oldtexibuf) {
303                 srcx = srcy = 0;
304                 destx = (int)painter->lastpaintpos[0] - (int)pos[0];
305                 desty = (int)painter->lastpaintpos[1] - (int)pos[1];
306                 w = oldtexibuf->x;
307                 h = oldtexibuf->y;
308
309                 IMB_rectclip(cache->texibuf, oldtexibuf, &destx, &desty, &srcx, &srcy, &w, &h);
310         }
311         else {
312                 srcx = srcy = 0;
313                 destx = desty = 0;
314                 w = h = 0;
315         }
316         
317         x1 = destx;
318         y1 = desty;
319         x2 = destx + w;
320         y2 = desty + h;
321
322         /* blend existing texture in new position */
323         if ((x1 < x2) && (y1 < y2))
324                 brush_painter_2d_do_partial(painter, oldtexibuf, x1, y1, x2, y2, srcx, srcy, pos);
325
326         if (oldtexibuf)
327                 IMB_freeImBuf(oldtexibuf);
328
329         /* sample texture in new areas */
330         if ((0 < x1) && (0 < ibuf->y))
331                 brush_painter_2d_do_partial(painter, NULL, 0, 0, x1, ibuf->y, 0, 0, pos);
332         if ((x2 < ibuf->x) && (0 < ibuf->y))
333                 brush_painter_2d_do_partial(painter, NULL, x2, 0, ibuf->x, ibuf->y, 0, 0, pos);
334         if ((x1 < x2) && (0 < y1))
335                 brush_painter_2d_do_partial(painter, NULL, x1, 0, x2, y1, 0, 0, pos);
336         if ((x1 < x2) && (y2 < ibuf->y))
337                 brush_painter_2d_do_partial(painter, NULL, x1, y2, x2, ibuf->y, 0, 0, pos);
338 }
339
340 static void brush_painter_2d_tex_mapping(ImagePaintState *s, int bufsize, const float pos[2], bool do_stencil, bool do_3D, bool do_view, rctf *mapping)
341 {
342         float invw = 1.0f/(float)s->canvas->x;
343         float invh = 1.0f/(float)s->canvas->y;
344         int xmin, ymin, xmax, ymax;
345         int ipos[2];
346
347         /* find start coordinate of brush in canvas */
348         ipos[0] = (int)floorf((pos[0] - bufsize / 2) + 1.0f);
349         ipos[1] = (int)floorf((pos[1] - bufsize / 2) + 1.0f);
350
351         if (do_stencil || do_view) {
352                 /* map from view coordinates of brush to region coordinates */
353                 UI_view2d_to_region_no_clip(s->v2d, ipos[0]*invw, ipos[1]*invh, &xmin, &ymin);
354                 UI_view2d_to_region_no_clip(s->v2d, (ipos[0] + bufsize)*invw, (ipos[1] + bufsize)*invh, &xmax, &ymax);
355
356                 /* output mapping from brush ibuf x/y to region coordinates */
357                 mapping->xmin = xmin;
358                 mapping->ymin = ymin;
359                 mapping->xmax = (xmax - xmin)/(float)bufsize;
360                 mapping->ymax = (ymax - ymin)/(float)bufsize;
361         }
362         else if (do_3D) {
363                 /* 3D mapping, just mapping to canvas 0..1  */
364                 mapping->xmin = ipos[0]*invw;
365                 mapping->ymin = ipos[1]*invh;
366                 mapping->xmax = bufsize*invw/(float)bufsize;
367                 mapping->ymax = bufsize*invh/(float)bufsize;
368         }
369         else {
370                 /* other mapping */
371                 mapping->xmin = -bufsize * 0.5f + 0.5f;
372                 mapping->ymin = -bufsize * 0.5f + 0.5f;
373                 mapping->xmax = 1.0f;
374                 mapping->ymax = 1.0f;
375         }
376 }
377
378 static void brush_painter_2d_refresh_cache(ImagePaintState *s, BrushPainter *painter, const float pos[2], bool use_color_correction)
379 {
380         const Scene *scene = painter->scene;
381         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
382         Brush *brush = painter->brush;
383         BrushPainterCache *cache = &painter->cache;
384         MTex *mtex = &brush->mtex;
385         const int diameter = 2 * BKE_brush_size_get(scene, brush);
386         const int size = (cache->size) ? cache->size : diameter;
387         const short flt = cache->flt;
388         const float alpha = BKE_brush_alpha_get(scene, brush);
389         const bool do_3D = brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D;
390         const bool do_tiled = brush->mtex.brush_map_mode == MTEX_MAP_MODE_TILED;
391         const bool do_stencil = brush->mtex.brush_map_mode == MTEX_MAP_MODE_STENCIL;
392         const bool do_random = brush->mtex.brush_map_mode == MTEX_MAP_MODE_RANDOM;
393         const bool do_view = brush->mtex.brush_map_mode == MTEX_MAP_MODE_VIEW;
394         const bool use_brush_alpha = !s->do_masking;
395         float rotation = -mtex->rot;
396
397         if (do_view) {
398                 rotation += ups->brush_rotation;
399         }
400
401         brush_painter_2d_tex_mapping(s, size, pos, do_stencil, do_3D, do_view, &painter->mapping);
402
403         painter->pool = BKE_image_pool_new();
404
405         if (diameter != cache->lastsize ||
406             (use_brush_alpha && alpha != cache->lastalpha) ||
407             brush->jitter != cache->lastjitter ||
408             rotation != cache->last_rotation ||
409             do_random)
410         {
411                 if (cache->ibuf) {
412                         IMB_freeImBuf(cache->ibuf);
413                         cache->ibuf = NULL;
414                 }
415                 if (cache->maskibuf) {
416                         IMB_freeImBuf(cache->maskibuf);
417                         cache->maskibuf = NULL;
418                 }
419
420                 if (do_tiled || do_3D || do_stencil) {
421                         BKE_brush_imbuf_new(scene, brush, flt, BRUSH_IMBUF_MASK,
422                                             size, &cache->maskibuf,
423                                             use_color_correction, use_brush_alpha,
424                                             painter->pool, &painter->mapping);
425
426                         brush_painter_2d_tiled_tex_partial_update(painter, pos);
427                 }
428                 else {
429                         BKE_brush_imbuf_new(scene, brush, flt, BRUSH_IMBUF_TEX_MASK,
430                                             size, &cache->ibuf,
431                                             use_color_correction, use_brush_alpha,
432                                             painter->pool, &painter->mapping);
433                 }
434
435                 cache->lastsize = diameter;
436                 cache->lastalpha = alpha;
437                 cache->lastjitter = brush->jitter;
438                 cache->last_rotation = rotation;
439         }
440         else if ((do_tiled || do_3D || do_stencil) && mtex && mtex->tex) {
441                 int dx = (int)painter->lastpaintpos[0] - (int)pos[0];
442                 int dy = (int)painter->lastpaintpos[1] - (int)pos[1];
443
444                 if ((dx != 0) || (dy != 0))
445                         brush_painter_2d_tiled_tex_partial_update(painter, pos);
446         }
447
448         BKE_image_pool_free(painter->pool);
449         painter->pool = NULL;
450 }
451
452 /* keep these functions in sync */
453 static void paint_2d_ibuf_rgb_get(ImBuf *ibuf, int x, int y, const short is_torus, float r_rgb[3])
454 {
455         if (is_torus) {
456                 x %= ibuf->x;
457                 if (x < 0) x += ibuf->x;
458                 y %= ibuf->y;
459                 if (y < 0) y += ibuf->y;
460         }
461
462         if (ibuf->rect_float) {
463                 float *rrgbf = ibuf->rect_float + (ibuf->x * y + x) * 4;
464                 IMAPAINT_FLOAT_RGB_COPY(r_rgb, rrgbf);
465         }
466         else {
467                 char *rrgb = (char *)ibuf->rect + (ibuf->x * y + x) * 4;
468                 IMAPAINT_CHAR_RGB_TO_FLOAT(r_rgb, rrgb);
469         }
470 }
471 static void paint_2d_ibuf_rgb_set(ImBuf *ibuf, int x, int y, const short is_torus, const float rgb[3])
472 {
473         if (is_torus) {
474                 x %= ibuf->x;
475                 if (x < 0) x += ibuf->x;
476                 y %= ibuf->y;
477                 if (y < 0) y += ibuf->y;
478         }
479
480         if (ibuf->rect_float) {
481                 float *rrgbf = ibuf->rect_float + (ibuf->x * y + x) * 4;
482                 IMAPAINT_FLOAT_RGB_COPY(rrgbf, rgb);
483         }
484         else {
485                 char *rrgb = (char *)ibuf->rect + (ibuf->x * y + x) * 4;
486                 IMAPAINT_FLOAT_RGB_TO_CHAR(rrgb, rgb);
487         }
488 }
489
490 static int paint_2d_ibuf_add_if(ImBuf *ibuf, unsigned int x, unsigned int y, float *outrgb, short torus)
491 {
492         float inrgb[3];
493
494         // XXX: signed unsigned mismatch
495         if ((x >= (unsigned int)(ibuf->x)) || (y >= (unsigned int)(ibuf->y))) {
496                 if (torus) paint_2d_ibuf_rgb_get(ibuf, x, y, 1, inrgb);
497                 else return 0;
498         }
499         else {
500                 paint_2d_ibuf_rgb_get(ibuf, x, y, 0, inrgb);
501         }
502
503         outrgb[0] += inrgb[0];
504         outrgb[1] += inrgb[1];
505         outrgb[2] += inrgb[2];
506
507         return 1;
508 }
509
510 static void paint_2d_lift_soften(ImBuf *ibuf, ImBuf *ibufb, int *pos, const short is_torus)
511 {
512         int x, y, count, xi, yi, xo, yo;
513         int out_off[2], in_off[2], dim[2];
514         float outrgb[3];
515
516         dim[0] = ibufb->x;
517         dim[1] = ibufb->y;
518         in_off[0] = pos[0];
519         in_off[1] = pos[1];
520         out_off[0] = out_off[1] = 0;
521
522         if (!is_torus) {
523                 IMB_rectclip(ibuf, ibufb, &in_off[0], &in_off[1], &out_off[0],
524                              &out_off[1], &dim[0], &dim[1]);
525
526                 if ((dim[0] == 0) || (dim[1] == 0))
527                         return;
528         }
529
530         for (y = 0; y < dim[1]; y++) {
531                 for (x = 0; x < dim[0]; x++) {
532                         /* get input pixel */
533                         xi = in_off[0] + x;
534                         yi = in_off[1] + y;
535
536                         count = 1;
537                         paint_2d_ibuf_rgb_get(ibuf, xi, yi, is_torus, outrgb);
538
539                         count += paint_2d_ibuf_add_if(ibuf, xi - 1, yi - 1, outrgb, is_torus);
540                         count += paint_2d_ibuf_add_if(ibuf, xi - 1, yi, outrgb, is_torus);
541                         count += paint_2d_ibuf_add_if(ibuf, xi - 1, yi + 1, outrgb, is_torus);
542
543                         count += paint_2d_ibuf_add_if(ibuf, xi, yi - 1, outrgb, is_torus);
544                         count += paint_2d_ibuf_add_if(ibuf, xi, yi + 1, outrgb, is_torus);
545
546                         count += paint_2d_ibuf_add_if(ibuf, xi + 1, yi - 1, outrgb, is_torus);
547                         count += paint_2d_ibuf_add_if(ibuf, xi + 1, yi, outrgb, is_torus);
548                         count += paint_2d_ibuf_add_if(ibuf, xi + 1, yi + 1, outrgb, is_torus);
549
550                         mul_v3_fl(outrgb, 1.0f / (float)count);
551
552                         /* write into brush buffer */
553                         xo = out_off[0] + x;
554                         yo = out_off[1] + y;
555                         paint_2d_ibuf_rgb_set(ibufb, xo, yo, 0, outrgb);
556                 }
557         }
558 }
559
560 static void paint_2d_set_region(ImagePaintRegion *region, int destx, int desty, int srcx, int srcy, int width, int height)
561 {
562         region->destx = destx;
563         region->desty = desty;
564         region->srcx = srcx;
565         region->srcy = srcy;
566         region->width = width;
567         region->height = height;
568 }
569
570 static int paint_2d_torus_split_region(ImagePaintRegion region[4], ImBuf *dbuf, ImBuf *sbuf)
571 {
572         int destx = region->destx;
573         int desty = region->desty;
574         int srcx = region->srcx;
575         int srcy = region->srcy;
576         int width = region->width;
577         int height = region->height;
578         int origw, origh, w, h, tot = 0;
579
580         /* convert destination and source coordinates to be within image */
581         destx = destx % dbuf->x;
582         if (destx < 0) destx += dbuf->x;
583         desty = desty % dbuf->y;
584         if (desty < 0) desty += dbuf->y;
585         srcx = srcx % sbuf->x;
586         if (srcx < 0) srcx += sbuf->x;
587         srcy = srcy % sbuf->y;
588         if (srcy < 0) srcy += sbuf->y;
589
590         /* clip width of blending area to destination imbuf, to avoid writing the
591          * same pixel twice */
592         origw = w = (width > dbuf->x) ? dbuf->x : width;
593         origh = h = (height > dbuf->y) ? dbuf->y : height;
594
595         /* clip within image */
596         IMB_rectclip(dbuf, sbuf, &destx, &desty, &srcx, &srcy, &w, &h);
597         paint_2d_set_region(&region[tot++], destx, desty, srcx, srcy, w, h);
598
599         /* do 3 other rects if needed */
600         if (w < origw)
601                 paint_2d_set_region(&region[tot++], (destx + w) % dbuf->x, desty, (srcx + w) % sbuf->x, srcy, origw - w, h);
602         if (h < origh)
603                 paint_2d_set_region(&region[tot++], destx, (desty + h) % dbuf->y, srcx, (srcy + h) % sbuf->y, w, origh - h);
604         if ((w < origw) && (h < origh))
605                 paint_2d_set_region(&region[tot++], (destx + w) % dbuf->x, (desty + h) % dbuf->y, (srcx + w) % sbuf->x, (srcy + h) % sbuf->y, origw - w, origh - h);
606
607         return tot;
608 }
609
610 static void paint_2d_lift_smear(ImBuf *ibuf, ImBuf *ibufb, int *pos)
611 {
612         ImagePaintRegion region[4];
613         int a, tot;
614
615         paint_2d_set_region(region, 0, 0, pos[0], pos[1], ibufb->x, ibufb->y);
616         tot = paint_2d_torus_split_region(region, ibufb, ibuf);
617
618         for (a = 0; a < tot; a++)
619                 IMB_rectblend(ibufb, ibufb, ibuf, NULL, 0, region[a].destx, region[a].desty,
620                               region[a].destx, region[a].desty,
621                               region[a].srcx, region[a].srcy,
622                               region[a].width, region[a].height, IMB_BLEND_COPY_RGB);
623 }
624
625 static ImBuf *paint_2d_lift_clone(ImBuf *ibuf, ImBuf *ibufb, int *pos)
626 {
627         /* note: allocImbuf returns zero'd memory, so regions outside image will
628          * have zero alpha, and hence not be blended onto the image */
629         int w = ibufb->x, h = ibufb->y, destx = 0, desty = 0, srcx = pos[0], srcy = pos[1];
630         ImBuf *clonebuf = IMB_allocImBuf(w, h, ibufb->planes, ibufb->flags);
631
632         IMB_rectclip(clonebuf, ibuf, &destx, &desty, &srcx, &srcy, &w, &h);
633         IMB_rectblend(clonebuf, clonebuf, ibuf, NULL, 0, destx, desty, destx, desty, srcx, srcy, w, h,
634                       IMB_BLEND_COPY_RGB);
635         IMB_rectblend(clonebuf, clonebuf, ibufb, NULL, 0, destx, desty, destx, desty, destx, desty, w, h,
636                       IMB_BLEND_COPY_ALPHA);
637
638         return clonebuf;
639 }
640
641 static void paint_2d_convert_brushco(ImBuf *ibufb, const float pos[2], int ipos[2])
642 {
643         ipos[0] = (int)floorf((pos[0] - ibufb->x / 2) + 1.0f);
644         ipos[1] = (int)floorf((pos[1] - ibufb->y / 2) + 1.0f);
645 }
646
647 static int paint_2d_op(void *state, ImBuf *ibufb, const float lastpos[2], const float pos[2])
648 {
649         ImagePaintState *s = ((ImagePaintState *)state);
650         ImBuf *clonebuf = NULL, *frombuf, *tmpbuf = NULL;
651         ImagePaintRegion region[4];
652         short torus = s->brush->flag & BRUSH_TORUS;
653         short blend = s->blend;
654         float *offset = s->brush->clone.offset;
655         float liftpos[2];
656         float brush_alpha = BKE_brush_alpha_get(s->scene, s->brush);
657         unsigned short mask_max = (unsigned short)(brush_alpha * 65535.0f);
658         int bpos[2], blastpos[2], bliftpos[2];
659         int a, tot;
660
661         paint_2d_convert_brushco(ibufb, pos, bpos);
662
663         /* lift from canvas */
664         if (s->tool == PAINT_TOOL_SOFTEN) {
665                 paint_2d_lift_soften(s->canvas, ibufb, bpos, torus);
666         }
667         else if (s->tool == PAINT_TOOL_SMEAR) {
668                 if (lastpos[0] == pos[0] && lastpos[1] == pos[1])
669                         return 0;
670
671                 paint_2d_convert_brushco(ibufb, lastpos, blastpos);
672                 paint_2d_lift_smear(s->canvas, ibufb, blastpos);
673         }
674         else if (s->tool == PAINT_TOOL_CLONE && s->clonecanvas) {
675                 liftpos[0] = pos[0] - offset[0] * s->canvas->x;
676                 liftpos[1] = pos[1] - offset[1] * s->canvas->y;
677
678                 paint_2d_convert_brushco(ibufb, liftpos, bliftpos);
679                 clonebuf = paint_2d_lift_clone(s->clonecanvas, ibufb, bliftpos);
680         }
681
682         frombuf = (clonebuf) ? clonebuf : ibufb;
683
684         if (torus) {
685                 paint_2d_set_region(region, bpos[0], bpos[1], 0, 0, frombuf->x, frombuf->y);
686                 tot = paint_2d_torus_split_region(region, s->canvas, frombuf);
687         }
688         else {
689                 paint_2d_set_region(region, bpos[0], bpos[1], 0, 0, frombuf->x, frombuf->y);
690                 tot = 1;
691         }
692
693         if (s->do_masking)
694                 tmpbuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, 0);
695         
696         /* blend into canvas */
697         for (a = 0; a < tot; a++) {
698                 imapaint_dirty_region(s->image, s->canvas,
699                                       region[a].destx, region[a].desty,
700                                       region[a].width, region[a].height);
701         
702                 if (s->do_masking) {
703                         /* masking, find original pixels tiles from undo buffer to composite over */
704                         int tilex, tiley, tilew, tileh, tx, ty;
705
706                         imapaint_region_tiles(s->canvas, region[a].destx, region[a].desty,
707                                               region[a].width, region[a].height,
708                                                                   &tilex, &tiley, &tilew, &tileh);
709                         
710                         for (ty = tiley; ty <= tileh; ty++) {
711                                 for (tx = tilex; tx <= tilew; tx++) {
712                                         /* retrieve original pixels + mask from undo buffer */
713                                         unsigned short *mask;
714                                         int origx = region[a].destx - tx * IMAPAINT_TILE_SIZE;
715                                         int origy = region[a].desty - ty * IMAPAINT_TILE_SIZE;
716
717                                         if (s->canvas->rect_float)
718                                                 tmpbuf->rect_float = image_undo_find_tile(s->image, s->canvas, tx, ty, &mask);
719                                         else
720                                                 tmpbuf->rect = image_undo_find_tile(s->image, s->canvas, tx, ty, &mask);
721
722                                         IMB_rectblend(s->canvas, tmpbuf, frombuf, mask, mask_max,
723                                                                   region[a].destx, region[a].desty,
724                                                                   origx, origy,
725                                                                   region[a].srcx, region[a].srcy,
726                                                                   region[a].width, region[a].height, blend);
727                                 }
728                         }
729                 }
730                 else {
731                         /* no masking, composite brush directly onto canvas */
732                         IMB_rectblend(s->canvas, s->canvas, frombuf, NULL, 0,
733                                                   region[a].destx, region[a].desty,
734                                                   region[a].destx, region[a].desty,
735                                                   region[a].srcx, region[a].srcy,
736                                                   region[a].width, region[a].height, blend);
737                 }
738         }
739
740         if (clonebuf) IMB_freeImBuf(clonebuf);
741         if (tmpbuf) IMB_freeImBuf(tmpbuf);
742
743         return 1;
744 }
745
746
747 static int paint_2d_canvas_set(ImagePaintState *s, Image *ima)
748 {
749         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, s->sima ? &s->sima->iuser : NULL, NULL);
750
751         /* verify that we can paint and set canvas */
752         if (ima == NULL) {
753                 return 0;
754         }
755         else if (ima->packedfile && ima->rr) {
756                 s->warnpackedfile = ima->id.name + 2;
757                 return 0;
758         }
759         else if (ibuf && ibuf->channels != 4) {
760                 s->warnmultifile = ima->id.name + 2;
761                 return 0;
762         }
763         else if (!ibuf || !(ibuf->rect || ibuf->rect_float))
764                 return 0;
765
766         s->image = ima;
767         s->canvas = ibuf;
768
769         /* set clone canvas */
770         if (s->tool == PAINT_TOOL_CLONE) {
771                 ima = s->brush->clone.image;
772                 ibuf = BKE_image_acquire_ibuf(ima, s->sima ? &s->sima->iuser : NULL, NULL);
773
774                 if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) {
775                         BKE_image_release_ibuf(ima, ibuf, NULL);
776                         BKE_image_release_ibuf(s->image, s->canvas, NULL);
777                         return 0;
778                 }
779
780                 s->clonecanvas = ibuf;
781
782                 /* temporarily add float rect for cloning */
783                 if (s->canvas->rect_float && !s->clonecanvas->rect_float) {
784                         IMB_float_from_rect(s->clonecanvas);
785                 }
786                 else if (!s->canvas->rect_float && !s->clonecanvas->rect)
787                         IMB_rect_from_float(s->clonecanvas);
788         }
789
790         /* set masking */
791         s->do_masking = (s->brush->flag & BRUSH_AIRBRUSH ||
792                          (s->brush->imagepaint_tool == PAINT_TOOL_SMEAR) ||
793                          (s->brush->mtex.tex && !ELEM3(s->brush->mtex.brush_map_mode, MTEX_MAP_MODE_TILED, MTEX_MAP_MODE_STENCIL, MTEX_MAP_MODE_3D)))
794                                          ? false : true;
795         
796         return 1;
797 }
798
799 static void paint_2d_canvas_free(ImagePaintState *s)
800 {
801         BKE_image_release_ibuf(s->image, s->canvas, NULL);
802         BKE_image_release_ibuf(s->brush->clone.image, s->clonecanvas, NULL);
803
804         if (s->do_masking)
805                 image_undo_remove_masks();
806 }
807
808 int paint_2d_stroke(void *ps, const int prev_mval[2], const int mval[2], int eraser)
809 {
810         float newuv[2], olduv[2];
811         int redraw = 0;
812         ImagePaintState *s = ps;
813         BrushPainter *painter = s->painter;
814         ImBuf *ibuf = BKE_image_acquire_ibuf(s->image, s->sima ? &s->sima->iuser : NULL, NULL);
815         const bool is_data = (ibuf && ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA);
816
817         if (!ibuf)
818                 return 0;
819
820         s->blend = s->brush->blend;
821         if (eraser)
822                 s->blend = IMB_BLEND_ERASE_ALPHA;
823
824         UI_view2d_region_to_view(s->v2d, mval[0], mval[1], &newuv[0], &newuv[1]);
825         UI_view2d_region_to_view(s->v2d, prev_mval[0], prev_mval[1], &olduv[0], &olduv[1]);
826
827         newuv[0] *= ibuf->x;
828         newuv[1] *= ibuf->y;
829
830         olduv[0] *= ibuf->x;
831         olduv[1] *= ibuf->y;
832
833         if (painter->firsttouch) {
834                 /* paint exactly once on first touch */
835                 painter->startpaintpos[0] = newuv[0];
836                 painter->startpaintpos[1] = newuv[1];
837
838                 painter->firsttouch = 0;
839                 copy_v2_v2(painter->lastpaintpos, newuv);
840         }
841         else {
842                 copy_v2_v2(painter->lastpaintpos, olduv);
843         }
844         /* OCIO_TODO: float buffers are now always linear, so always use color correction
845          *            this should probably be changed when texture painting color space is supported
846          */
847         brush_painter_2d_require_imbuf(painter, ((ibuf->rect_float) ? 1 : 0), 0);
848
849         brush_painter_2d_refresh_cache(s, painter, newuv, is_data == false);
850
851         if (paint_2d_op(s, painter->cache.ibuf, olduv, newuv)) {
852                 imapaint_image_update(s->sima, s->image, ibuf, false);
853                 BKE_image_release_ibuf(s->image, ibuf, NULL);
854                 redraw |= 1;
855         }
856         else {
857                 BKE_image_release_ibuf(s->image, ibuf, NULL);
858         }
859
860         if (redraw)
861                 imapaint_clear_partial_redraw();
862
863         return redraw;
864 }
865
866 void *paint_2d_new_stroke(bContext *C, wmOperator *op)
867 {
868         Scene *scene = CTX_data_scene(C);
869         ToolSettings *settings = scene->toolsettings;
870         Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
871
872         ImagePaintState *s = MEM_callocN(sizeof(ImagePaintState), "ImagePaintState");
873
874         s->sima = CTX_wm_space_image(C);
875         s->v2d = &CTX_wm_region(C)->v2d;
876         s->scene = scene;
877         s->screen = CTX_wm_screen(C);
878
879         s->brush = brush;
880         s->tool = brush->imagepaint_tool;
881         s->blend = brush->blend;
882
883         s->image = s->sima->image;
884
885         if (!paint_2d_canvas_set(s, s->image)) {
886                 if (s->warnmultifile)
887                         BKE_report(op->reports, RPT_WARNING, "Image requires 4 color channels to paint");
888                 if (s->warnpackedfile)
889                         BKE_report(op->reports, RPT_WARNING, "Packed MultiLayer files cannot be painted");
890
891                 MEM_freeN(s);
892                 return NULL;
893         }
894
895         paint_brush_init_tex(s->brush);
896
897         /* create painter */
898         s->painter = brush_painter_2d_new(scene, s->brush);
899
900         return s;
901 }
902
903 void paint_2d_redraw(const bContext *C, void *ps, int final)
904 {
905         ImagePaintState *s = ps;
906
907         if (final) {
908                 if (s->image && !(s->sima && s->sima->lock))
909                         GPU_free_image(s->image);
910
911                 /* compositor listener deals with updating */
912                 WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, s->image);
913         }
914         else {
915                 if (!s->sima || !s->sima->lock)
916                         ED_region_tag_redraw(CTX_wm_region(C));
917                 else
918                         WM_event_add_notifier(C, NC_IMAGE | NA_EDITED, s->image);
919         }
920 }
921
922 void paint_2d_stroke_done(void *ps)
923 {
924         ImagePaintState *s = ps;
925
926         paint_2d_canvas_free(s);
927         brush_painter_2d_free(s->painter);
928         paint_brush_exit_tex(s->brush);
929
930         MEM_freeN(s);
931 }