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