fix reading out of buffer bounds for recent vertex paint commit.
[blender.git] / source / blender / blenkernel / intern / brush.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/blenkernel/intern/brush.c
29  *  \ingroup bke
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_brush_types.h"
35 #include "DNA_scene_types.h"
36 #include "DNA_object_types.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_rand.h"
41
42 #include "BKE_brush.h"
43 #include "BKE_colortools.h"
44 #include "BKE_global.h"
45 #include "BKE_image.h"
46 #include "BKE_library.h"
47 #include "BKE_main.h"
48 #include "BKE_paint.h"
49 #include "BKE_texture.h"
50 #include "BKE_icons.h"
51
52 #include "IMB_imbuf.h"
53 #include "IMB_imbuf_types.h"
54
55 #include "RE_render_ext.h" /* externtex */
56 #include "RE_shader_ext.h"
57
58 static void brush_defaults(Brush *brush)
59 {
60         brush->blend = 0;
61         brush->flag = 0;
62
63         brush->ob_mode = OB_MODE_ALL_PAINT;
64
65         /* BRUSH SCULPT TOOL SETTINGS */
66         brush->weight = 1.0f; /* weight of brush 0 - 1.0 */
67         brush->size = 35; /* radius of the brush in pixels */
68         brush->alpha = 0.5f; /* brush strength/intensity probably variable should be renamed? */
69         brush->autosmooth_factor = 0.0f;
70         brush->crease_pinch_factor = 0.5f;
71         brush->sculpt_plane = SCULPT_DISP_DIR_AREA;
72         brush->plane_offset = 0.0f; /* how far above or below the plane that is found by averaging the faces */
73         brush->plane_trim = 0.5f;
74         brush->clone.alpha = 0.5f;
75         brush->normal_weight = 0.0f;
76         brush->flag |= BRUSH_ALPHA_PRESSURE;
77
78         /* BRUSH PAINT TOOL SETTINGS */
79         brush->rgb[0] = 1.0f; /* default rgb color of the brush when painting - white */
80         brush->rgb[1] = 1.0f;
81         brush->rgb[2] = 1.0f;
82
83         /* BRUSH STROKE SETTINGS */
84         brush->flag |= (BRUSH_SPACE | BRUSH_SPACE_ATTEN);
85         brush->spacing = 10; /* how far each brush dot should be spaced as a percentage of brush diameter */
86
87         brush->smooth_stroke_radius = 75;
88         brush->smooth_stroke_factor = 0.9f;
89
90         brush->rate = 0.1f; /* time delay between dots of paint or sculpting when doing airbrush mode */
91
92         brush->jitter = 0.0f;
93
94         /* BRUSH TEXTURE SETTINGS */
95         default_mtex(&brush->mtex);
96
97         brush->texture_sample_bias = 0; /* value to added to texture samples */
98         brush->texture_overlay_alpha = 33;
99
100         /* brush appearance  */
101
102         brush->add_col[0] = 1.00; /* add mode color is light red */
103         brush->add_col[1] = 0.39;
104         brush->add_col[2] = 0.39;
105
106         brush->sub_col[0] = 0.39; /* subtract mode color is light blue */
107         brush->sub_col[1] = 0.39;
108         brush->sub_col[2] = 1.00;
109 }
110
111 /* Datablock add/copy/free/make_local */
112
113 Brush *BKE_brush_add(Main *bmain, const char *name)
114 {
115         Brush *brush;
116
117         brush = BKE_libblock_alloc(&bmain->brush, ID_BR, name);
118
119         /* enable fake user by default */
120         brush->id.flag |= LIB_FAKEUSER;
121
122         brush_defaults(brush);
123
124         brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */
125
126         /* the default alpha falloff curve */
127         BKE_brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
128
129         return brush;
130 }
131
132 Brush *BKE_brush_copy(Brush *brush)
133 {
134         Brush *brushn;
135         
136         brushn = BKE_libblock_copy(&brush->id);
137
138         if (brush->mtex.tex)
139                 id_us_plus((ID *)brush->mtex.tex);
140
141         if (brush->icon_imbuf)
142                 brushn->icon_imbuf = IMB_dupImBuf(brush->icon_imbuf);
143
144         brushn->preview = NULL;
145
146         brushn->curve = curvemapping_copy(brush->curve);
147
148         /* enable fake user by default */
149         if (!(brushn->id.flag & LIB_FAKEUSER)) {
150                 brushn->id.flag |= LIB_FAKEUSER;
151                 brushn->id.us++;
152         }
153         
154         return brushn;
155 }
156
157 /* not brush itself */
158 void BKE_brush_free(Brush *brush)
159 {
160         if (brush->mtex.tex)
161                 brush->mtex.tex->id.us--;
162
163         if (brush->icon_imbuf)
164                 IMB_freeImBuf(brush->icon_imbuf);
165
166         BKE_previewimg_free(&(brush->preview));
167
168         curvemapping_free(brush->curve);
169 }
170
171 static void extern_local_brush(Brush *brush)
172 {
173         id_lib_extern((ID *)brush->mtex.tex);
174         id_lib_extern((ID *)brush->clone.image);
175 }
176
177 void BKE_brush_make_local(Brush *brush)
178 {
179
180         /* - only lib users: do nothing
181          * - only local users: set flag
182          * - mixed: make copy
183          */
184
185         Main *bmain = G.main;
186         Scene *scene;
187         int is_local = FALSE, is_lib = FALSE;
188
189         if (brush->id.lib == NULL) return;
190
191         if (brush->clone.image) {
192                 /* special case: ima always local immediately. Clone image should only
193                  * have one user anyway. */
194                 id_clear_lib_data(bmain, &brush->clone.image->id);
195                 extern_local_brush(brush);
196         }
197
198         for (scene = bmain->scene.first; scene && ELEM(0, is_lib, is_local); scene = scene->id.next) {
199                 if (paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
200                         if (scene->id.lib) is_lib = TRUE;
201                         else is_local = TRUE;
202                 }
203         }
204
205         if (is_local && is_lib == FALSE) {
206                 id_clear_lib_data(bmain, &brush->id);
207                 extern_local_brush(brush);
208
209                 /* enable fake user by default */
210                 if (!(brush->id.flag & LIB_FAKEUSER)) {
211                         brush->id.flag |= LIB_FAKEUSER;
212                         brush->id.us++;
213                 }
214         }
215         else if (is_local && is_lib) {
216                 Brush *brush_new = BKE_brush_copy(brush);
217                 brush_new->id.us = 1; /* only keep fake user */
218                 brush_new->id.flag |= LIB_FAKEUSER;
219
220                 /* Remap paths of new ID using old library as base. */
221                 BKE_id_lib_local_paths(bmain, brush->id.lib, &brush_new->id);
222                 
223                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
224                         if (paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
225                                 if (scene->id.lib == NULL) {
226                                         paint_brush_set(&scene->toolsettings->imapaint.paint, brush_new);
227                                 }
228                         }
229                 }
230         }
231 }
232
233 void BKE_brush_debug_print_state(Brush *br)
234 {
235         /* create a fake brush and set it to the defaults */
236         Brush def = {{NULL}};
237         brush_defaults(&def);
238         
239 #define BR_TEST(field, t)                                       \
240         if (br->field != def.field)                             \
241                 printf("br->" #field " = %" #t ";\n", br->field)
242
243 #define BR_TEST_FLAG(_f)                                                        \
244         if ((br->flag & _f) && !(def.flag & _f))                \
245                 printf("br->flag |= " #_f ";\n");                       \
246         else if (!(br->flag & _f) && (def.flag & _f))   \
247                 printf("br->flag &= ~" #_f ";\n")
248         
249
250         /* print out any non-default brush state */
251         BR_TEST(normal_weight, f);
252
253         BR_TEST(blend, d);
254         BR_TEST(size, d);
255
256         /* br->flag */
257         BR_TEST_FLAG(BRUSH_AIRBRUSH);
258         BR_TEST_FLAG(BRUSH_TORUS);
259         BR_TEST_FLAG(BRUSH_ALPHA_PRESSURE);
260         BR_TEST_FLAG(BRUSH_SIZE_PRESSURE);
261         BR_TEST_FLAG(BRUSH_JITTER_PRESSURE);
262         BR_TEST_FLAG(BRUSH_SPACING_PRESSURE);
263         BR_TEST_FLAG(BRUSH_RAKE);
264         BR_TEST_FLAG(BRUSH_ANCHORED);
265         BR_TEST_FLAG(BRUSH_DIR_IN);
266         BR_TEST_FLAG(BRUSH_SPACE);
267         BR_TEST_FLAG(BRUSH_SMOOTH_STROKE);
268         BR_TEST_FLAG(BRUSH_PERSISTENT);
269         BR_TEST_FLAG(BRUSH_ACCUMULATE);
270         BR_TEST_FLAG(BRUSH_LOCK_ALPHA);
271         BR_TEST_FLAG(BRUSH_ORIGINAL_NORMAL);
272         BR_TEST_FLAG(BRUSH_OFFSET_PRESSURE);
273         BR_TEST_FLAG(BRUSH_SPACE_ATTEN);
274         BR_TEST_FLAG(BRUSH_ADAPTIVE_SPACE);
275         BR_TEST_FLAG(BRUSH_LOCK_SIZE);
276         BR_TEST_FLAG(BRUSH_TEXTURE_OVERLAY);
277         BR_TEST_FLAG(BRUSH_EDGE_TO_EDGE);
278         BR_TEST_FLAG(BRUSH_RESTORE_MESH);
279         BR_TEST_FLAG(BRUSH_INVERSE_SMOOTH_PRESSURE);
280         BR_TEST_FLAG(BRUSH_RANDOM_ROTATION);
281         BR_TEST_FLAG(BRUSH_PLANE_TRIM);
282         BR_TEST_FLAG(BRUSH_FRONTFACE);
283         BR_TEST_FLAG(BRUSH_CUSTOM_ICON);
284
285         BR_TEST(jitter, f);
286         BR_TEST(spacing, d);
287         BR_TEST(smooth_stroke_radius, d);
288         BR_TEST(smooth_stroke_factor, f);
289         BR_TEST(rate, f);
290
291         BR_TEST(alpha, f);
292
293         BR_TEST(sculpt_plane, d);
294
295         BR_TEST(plane_offset, f);
296
297         BR_TEST(autosmooth_factor, f);
298
299         BR_TEST(crease_pinch_factor, f);
300
301         BR_TEST(plane_trim, f);
302
303         BR_TEST(texture_sample_bias, f);
304         BR_TEST(texture_overlay_alpha, d);
305
306         BR_TEST(add_col[0], f);
307         BR_TEST(add_col[1], f);
308         BR_TEST(add_col[2], f);
309         BR_TEST(sub_col[0], f);
310         BR_TEST(sub_col[1], f);
311         BR_TEST(sub_col[2], f);
312
313         printf("\n");
314         
315 #undef BR_TEST
316 #undef BR_TEST_FLAG
317 }
318
319 void BKE_brush_sculpt_reset(Brush *br)
320 {
321         /* enable this to see any non-default
322          * settings used by a brush: */
323         // BKE_brush_debug_print_state(br);
324
325         brush_defaults(br);
326         BKE_brush_curve_preset(br, CURVE_PRESET_SMOOTH);
327
328         switch (br->sculpt_tool) {
329                 case SCULPT_TOOL_CLAY:
330                         br->flag |= BRUSH_FRONTFACE;
331                         break;
332                 case SCULPT_TOOL_CREASE:
333                         br->flag |= BRUSH_DIR_IN;
334                         br->alpha = 0.25;
335                         break;
336                 case SCULPT_TOOL_FILL:
337                         br->add_col[1] = 1;
338                         br->sub_col[0] = 0.25;
339                         br->sub_col[1] = 1;
340                         break;
341                 case SCULPT_TOOL_FLATTEN:
342                         br->add_col[1] = 1;
343                         br->sub_col[0] = 0.25;
344                         br->sub_col[1] = 1;
345                         break;
346                 case SCULPT_TOOL_INFLATE:
347                         br->add_col[0] = 0.750000;
348                         br->add_col[1] = 0.750000;
349                         br->add_col[2] = 0.750000;
350                         br->sub_col[0] = 0.250000;
351                         br->sub_col[1] = 0.250000;
352                         br->sub_col[2] = 0.250000;
353                         break;
354                 case SCULPT_TOOL_NUDGE:
355                         br->add_col[0] = 0.250000;
356                         br->add_col[1] = 1.000000;
357                         br->add_col[2] = 0.250000;
358                         break;
359                 case SCULPT_TOOL_PINCH:
360                         br->add_col[0] = 0.750000;
361                         br->add_col[1] = 0.750000;
362                         br->add_col[2] = 0.750000;
363                         br->sub_col[0] = 0.250000;
364                         br->sub_col[1] = 0.250000;
365                         br->sub_col[2] = 0.250000;
366                         break;
367                 case SCULPT_TOOL_SCRAPE:
368                         br->add_col[1] = 1.000000;
369                         br->sub_col[0] = 0.250000;
370                         br->sub_col[1] = 1.000000;
371                         break;
372                 case SCULPT_TOOL_ROTATE:
373                         br->alpha = 1.0;
374                         break;
375                 case SCULPT_TOOL_SMOOTH:
376                         br->flag &= ~BRUSH_SPACE_ATTEN;
377                         br->spacing = 5;
378                         br->add_col[0] = 0.750000;
379                         br->add_col[1] = 0.750000;
380                         br->add_col[2] = 0.750000;
381                         break;
382                 case SCULPT_TOOL_GRAB:
383                 case SCULPT_TOOL_SNAKE_HOOK:
384                 case SCULPT_TOOL_THUMB:
385                         br->size = 75;
386                         br->flag &= ~BRUSH_ALPHA_PRESSURE;
387                         br->flag &= ~BRUSH_SPACE;
388                         br->flag &= ~BRUSH_SPACE_ATTEN;
389                         br->add_col[0] = 0.250000;
390                         br->add_col[1] = 1.000000;
391                         br->add_col[2] = 0.250000;
392                         break;
393                 default:
394                         break;
395         }
396 }
397
398 /* Library Operations */
399 void BKE_brush_curve_preset(Brush *b, /*CurveMappingPreset*/ int preset)
400 {
401         CurveMap *cm = NULL;
402
403         if (!b->curve)
404                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
405
406         cm = b->curve->cm;
407         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
408
409         b->curve->preset = preset;
410         curvemap_reset(cm, &b->curve->clipr, b->curve->preset, CURVEMAP_SLOPE_NEGATIVE);
411         curvemapping_changed(b->curve, FALSE);
412 }
413
414 int BKE_brush_texture_set_nr(Brush *brush, int nr)
415 {
416         ID *idtest, *id = NULL;
417
418         id = (ID *)brush->mtex.tex;
419
420         idtest = (ID *)BLI_findlink(&G.main->tex, nr - 1);
421         if (idtest == NULL) { /* new tex */
422                 if (id) idtest = (ID *)BKE_texture_copy((Tex *)id);
423                 else idtest = (ID *)add_texture(G.main, "Tex");
424                 idtest->us--;
425         }
426         if (idtest != id) {
427                 BKE_brush_texture_delete(brush);
428
429                 brush->mtex.tex = (Tex *)idtest;
430                 id_us_plus(idtest);
431
432                 return 1;
433         }
434
435         return 0;
436 }
437
438 int BKE_brush_texture_delete(Brush *brush)
439 {
440         if (brush->mtex.tex)
441                 brush->mtex.tex->id.us--;
442
443         return 1;
444 }
445
446 int BKE_brush_clone_image_set_nr(Brush *brush, int nr)
447 {
448         if (brush && nr > 0) {
449                 Image *ima = (Image *)BLI_findlink(&G.main->image, nr - 1);
450
451                 if (ima) {
452                         BKE_brush_clone_image_delete(brush);
453                         brush->clone.image = ima;
454                         id_us_plus(&ima->id);
455                         brush->clone.offset[0] = brush->clone.offset[1] = 0.0f;
456
457                         return 1;
458                 }
459         }
460
461         return 0;
462 }
463
464 int BKE_brush_clone_image_delete(Brush *brush)
465 {
466         if (brush && brush->clone.image) {
467                 brush->clone.image->id.us--;
468                 brush->clone.image = NULL;
469                 return 1;
470         }
471
472         return 0;
473 }
474
475 /* Generic texture sampler for 3D painting systems. point has to be either in
476  * region space mouse coordinates, or 3d world coordinates for 3D mapping */
477 float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
478                               const float point[3],
479                               float rgba[4], const int thread,
480                               struct ImagePool *pool)
481 {
482         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
483         MTex *mtex = &br->mtex;
484         float intensity = 1.0;
485         bool hasrgb = false;
486
487         if (!mtex->tex) {
488                 intensity = 1;
489         }
490         else if (mtex->brush_map_mode == MTEX_MAP_MODE_3D) {
491                 /* Get strength by feeding the vertex
492                  * location directly into a texture */
493                 hasrgb = externtex(mtex, point, &intensity,
494                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
495         }
496         else {
497                 float rotation = -mtex->rot;
498                 float point_2d[2] = {point[0], point[1]};
499                 float x = 0.0f, y = 0.0f; /* Quite warnings */
500                 float radius = 1.0f; /* Quite warnings */
501                 float co[3];
502
503                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
504                         /* keep coordinates relative to mouse */
505
506                         rotation += ups->brush_rotation;
507
508                         point_2d[0] -= ups->tex_mouse[0];
509                         point_2d[1] -= ups->tex_mouse[1];
510
511                         /* use pressure adjusted size for fixed mode */
512                         radius = ups->pixel_radius;
513
514                         x = point_2d[0];
515                         y = point_2d[1];
516                 }
517                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
518                         /* leave the coordinates relative to the screen */
519
520                         /* use unadjusted size for tiled mode */
521                         radius = BKE_brush_size_get(scene, br);
522
523                         x = point_2d[0];
524                         y = point_2d[1];
525                 }
526
527                 x /= radius;
528                 y /= radius;
529
530                 /* it is probably worth optimizing for those cases where
531                  * the texture is not rotated by skipping the calls to
532                  * atan2, sqrtf, sin, and cos. */
533                 if (rotation > 0.001f || rotation < -0.001f) {
534                         const float angle    = atan2f(y, x) + rotation;
535                         const float flen     = sqrtf(x * x + y * y);
536
537                         x = flen * cosf(angle);
538                         y = flen * sinf(angle);
539                 }
540
541                 x *= br->mtex.size[0];
542                 y *= br->mtex.size[1];
543
544                 co[0] = x + br->mtex.ofs[0];
545                 co[1] = y + br->mtex.ofs[1];
546                 co[2] = 0.0f;
547
548                 hasrgb = externtex(mtex, co, &intensity,
549                                    rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
550         }
551
552         intensity += br->texture_sample_bias;
553
554         if (!hasrgb) {
555                 rgba[0] = intensity;
556                 rgba[1] = intensity;
557                 rgba[2] = intensity;
558                 rgba[3] = 1.0f;
559         }
560
561         return intensity;
562 }
563
564
565 /* Brush Sampling for 2D brushes. when we unify the brush systems this will be necessarily a separate function */
566 float BKE_brush_sample_tex_2D(const Scene *scene, Brush *brush, const float xy[2], float rgba[4], struct ImagePool *pool)
567 {
568         MTex *mtex = &brush->mtex;
569
570         if (mtex && mtex->tex) {
571                 float co[3], tin, tr, tg, tb, ta;
572                 int hasrgb;
573                 const int radius = BKE_brush_size_get(scene, brush);
574
575                 co[0] = xy[0] / radius;
576                 co[1] = xy[1] / radius;
577                 co[2] = 0.0f;
578
579                 hasrgb = externtex(mtex, co, &tin, &tr, &tg, &tb, &ta, 0, pool);
580
581                 if (hasrgb) {
582                         rgba[0] = tr;
583                         rgba[1] = tg;
584                         rgba[2] = tb;
585                         rgba[3] = ta;
586                 }
587                 else {
588                         rgba[0] = tin;
589                         rgba[1] = tin;
590                         rgba[2] = tin;
591                         rgba[3] = 1.0f;
592                 }
593                 return tin;
594         }
595         else {
596                 rgba[0] = rgba[1] = rgba[2] = rgba[3] = 1.0f;
597                 return 1.0;
598         }
599 }
600
601 /* TODO, use define for 'texfall' arg
602  * NOTE: only used for 2d brushes currently! */
603 void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texfall, int bufsize, ImBuf **outbuf, int use_color_correction)
604 {
605         ImBuf *ibuf;
606         float xy[2], rgba[4], *dstf;
607         int x, y, rowbytes, xoff, yoff, imbflag;
608         const int radius = BKE_brush_size_get(scene, brush);
609         unsigned char *dst, crgb[3];
610         const float alpha = BKE_brush_alpha_get(scene, brush);
611         float brush_rgb[3];
612
613         imbflag = (flt) ? IB_rectfloat : IB_rect;
614         xoff = -bufsize / 2.0f + 0.5f;
615         yoff = -bufsize / 2.0f + 0.5f;
616         rowbytes = bufsize * 4;
617
618         if (*outbuf)
619                 ibuf = *outbuf;
620         else
621                 ibuf = IMB_allocImBuf(bufsize, bufsize, 32, imbflag);
622
623         if (flt) {
624                 copy_v3_v3(brush_rgb, brush->rgb);
625                 if (use_color_correction) {
626                         srgb_to_linearrgb_v3_v3(brush_rgb, brush_rgb);
627                 }
628
629                 for (y = 0; y < ibuf->y; y++) {
630                         dstf = ibuf->rect_float + y * rowbytes;
631
632                         for (x = 0; x < ibuf->x; x++, dstf += 4) {
633                                 xy[0] = x + xoff;
634                                 xy[1] = y + yoff;
635
636                                 if (texfall == 0) {
637                                         copy_v3_v3(dstf, brush_rgb);
638                                         dstf[3] = alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
639                                 }
640                                 else if (texfall == 1) {
641                                         BKE_brush_sample_tex_2D(scene, brush, xy, dstf, 0);
642                                 }
643                                 else if (texfall == 2) {
644                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
645                                         mul_v3_v3v3(dstf, rgba, brush_rgb);
646                                         dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
647                                 }
648                                 else {
649                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
650                                         copy_v3_v3(dstf, brush_rgb);
651                                         dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
652                                 }
653                         }
654                 }
655         }
656         else {
657                 float alpha_f; /* final float alpha to convert to char */
658                 rgb_float_to_uchar(crgb, brush->rgb);
659
660                 for (y = 0; y < ibuf->y; y++) {
661                         dst = (unsigned char *)ibuf->rect + y * rowbytes;
662
663                         for (x = 0; x < ibuf->x; x++, dst += 4) {
664                                 xy[0] = x + xoff;
665                                 xy[1] = y + yoff;
666
667                                 if (texfall == 0) {
668                                         alpha_f = alpha * BKE_brush_curve_strength(brush, len_v2(xy), radius);
669
670                                         dst[0] = crgb[0];
671                                         dst[1] = crgb[1];
672                                         dst[2] = crgb[2];
673                                         dst[3] = FTOCHAR(alpha_f);
674                                 }
675                                 else if (texfall == 1) {
676                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
677                                         rgba_float_to_uchar(dst, rgba);
678                                 }
679                                 else if (texfall == 2) {
680                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
681                                         mul_v3_v3(rgba, brush->rgb);
682                                         alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
683
684                                         rgb_float_to_uchar(dst, rgba);
685
686                                         dst[3] = FTOCHAR(alpha_f);
687                                 }
688                                 else {
689                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
690                                         alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
691
692                                         dst[0] = crgb[0];
693                                         dst[1] = crgb[1];
694                                         dst[2] = crgb[2];
695                                         dst[3] = FTOCHAR(alpha_f);
696                                 }
697                         }
698                 }
699         }
700
701         *outbuf = ibuf;
702 }
703
704 /* Unified Size and Strength */
705
706 /* XXX: be careful about setting size and unprojected radius
707  * because they depend on one another
708  * these functions do not set the other corresponding value
709  * this can lead to odd behavior if size and unprojected
710  * radius become inconsistent.
711  * the biggest problem is that it isn't possible to change
712  * unprojected radius because a view context is not
713  * available.  my ussual solution to this is to use the
714  * ratio of change of the size to change the unprojected
715  * radius.  Not completely convinced that is correct.
716  * In any case, a better solution is needed to prevent
717  * inconsistency. */
718
719 void BKE_brush_size_set(Scene *scene, Brush *brush, int size)
720 {
721         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
722         
723         size = (int)((float)size / U.pixelsize);
724         
725         if (ups->flag & UNIFIED_PAINT_SIZE)
726                 ups->size = size;
727         else
728                 brush->size = size;
729 }
730
731 int BKE_brush_size_get(const Scene *scene, Brush *brush)
732 {
733         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
734         int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size;
735         
736         return (int)((float)size * U.pixelsize);
737 }
738
739 int BKE_brush_use_locked_size(const Scene *scene, Brush *brush)
740 {
741         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
742
743         return (us_flag & UNIFIED_PAINT_SIZE) ?
744                (us_flag & UNIFIED_PAINT_BRUSH_LOCK_SIZE) :
745                (brush->flag & BRUSH_LOCK_SIZE);
746 }
747
748 int BKE_brush_use_size_pressure(const Scene *scene, Brush *brush)
749 {
750         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
751
752         return (us_flag & UNIFIED_PAINT_SIZE) ?
753                (us_flag & UNIFIED_PAINT_BRUSH_SIZE_PRESSURE) :
754                (brush->flag & BRUSH_SIZE_PRESSURE);
755 }
756
757 int BKE_brush_use_alpha_pressure(const Scene *scene, Brush *brush)
758 {
759         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
760
761         return (us_flag & UNIFIED_PAINT_ALPHA) ?
762                (us_flag & UNIFIED_PAINT_BRUSH_ALPHA_PRESSURE) :
763                (brush->flag & BRUSH_ALPHA_PRESSURE);
764 }
765
766 void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojected_radius)
767 {
768         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
769
770         if (ups->flag & UNIFIED_PAINT_SIZE)
771                 ups->unprojected_radius = unprojected_radius;
772         else
773                 brush->unprojected_radius = unprojected_radius;
774 }
775
776 float BKE_brush_unprojected_radius_get(const Scene *scene, Brush *brush)
777 {
778         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
779
780         return (ups->flag & UNIFIED_PAINT_SIZE) ?
781                ups->unprojected_radius :
782                brush->unprojected_radius;
783 }
784
785 void BKE_brush_alpha_set(Scene *scene, Brush *brush, float alpha)
786 {
787         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
788
789         if (ups->flag & UNIFIED_PAINT_ALPHA)
790                 ups->alpha = alpha;
791         else
792                 brush->alpha = alpha;
793 }
794
795 float BKE_brush_alpha_get(const Scene *scene, Brush *brush)
796 {
797         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
798
799         return (ups->flag & UNIFIED_PAINT_ALPHA) ? ups->alpha : brush->alpha;
800 }
801
802 float BKE_brush_weight_get(const Scene *scene, Brush *brush)
803 {
804         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
805
806         return (ups->flag & UNIFIED_PAINT_WEIGHT) ? ups->weight : brush->weight;
807 }
808
809 void BKE_brush_weight_set(const Scene *scene, Brush *brush, float value)
810 {
811         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
812
813         if (ups->flag & UNIFIED_PAINT_WEIGHT)
814                 ups->weight = value;
815         else
816                 brush->weight = value;
817 }
818
819 /* scale unprojected radius to reflect a change in the brush's 2D size */
820 void BKE_brush_scale_unprojected_radius(float *unprojected_radius,
821                                         int new_brush_size,
822                                         int old_brush_size)
823 {
824         float scale = new_brush_size;
825         /* avoid division by zero */
826         if (old_brush_size != 0)
827                 scale /= (float)old_brush_size;
828         (*unprojected_radius) *= scale;
829 }
830
831 /* scale brush size to reflect a change in the brush's unprojected radius */
832 void BKE_brush_scale_size(int *r_brush_size,
833                           float new_unprojected_radius,
834                           float old_unprojected_radius)
835 {
836         float scale = new_unprojected_radius;
837         /* avoid division by zero */
838         if (old_unprojected_radius != 0)
839                 scale /= new_unprojected_radius;
840         (*r_brush_size) = (int)((float)(*r_brush_size) * scale);
841 }
842
843 void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
844 {
845         int use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
846                 (brush->jitter_absolute != 0) : (brush->jitter != 0);
847
848         /* jitter-ed brush gives weird and unpredictable result for this
849          * kinds of stroke, so manually disable jitter usage (sergey) */
850         use_jitter &= (brush->flag & (BRUSH_RESTORE_MESH | BRUSH_ANCHORED)) == 0;
851
852         if (use_jitter) {
853                 float rand_pos[2];
854                 float spread;
855                 int diameter;
856
857                 do {
858                         rand_pos[0] = BLI_frand() - 0.5f;
859                         rand_pos[1] = BLI_frand() - 0.5f;
860                 } while (len_v2(rand_pos) > 0.5f);
861
862
863                 if (brush->flag & BRUSH_ABSOLUTE_JITTER) {
864                         diameter = 2 * brush->jitter_absolute;
865                         spread = 1.0;
866                 }
867                 else {
868                         diameter = 2 * BKE_brush_size_get(scene, brush);
869                         spread = brush->jitter;
870                 }
871                 /* find random position within a circle of diameter 1 */
872                 jitterpos[0] = pos[0] + 2 * rand_pos[0] * diameter * spread;
873                 jitterpos[1] = pos[1] + 2 * rand_pos[1] * diameter * spread;
874         }
875         else {
876                 copy_v2_v2(jitterpos, pos);
877         }
878 }
879
880 /* Uses the brush curve control to find a strength value between 0 and 1 */
881 float BKE_brush_curve_strength_clamp(Brush *br, float p, const float len)
882 {
883         if (p >= len) return 0;
884         else p = p / len;
885
886         curvemapping_initialize(br->curve);
887         p = curvemapping_evaluateF(br->curve, 0, p);
888
889         if (p < 0.0f) p = 0.0f;
890         else if (p > 1.0f) p = 1.0f;
891         return p;
892 }
893 /* same as above but can return negative values if the curve enables
894  * used for sculpt only */
895 float BKE_brush_curve_strength(Brush *br, float p, const float len)
896 {
897         if (p >= len)
898                 p = 1.0f;
899         else
900                 p = p / len;
901
902         curvemapping_initialize(br->curve);
903         return curvemapping_evaluateF(br->curve, 0, p);
904 }
905
906 /* TODO: should probably be unified with BrushPainter stuff? */
907 unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
908 {
909         unsigned int *texcache = NULL;
910         MTex *mtex = &br->mtex;
911         TexResult texres = {0};
912         int hasrgb, ix, iy;
913         int side = half_side * 2;
914
915         if (mtex->tex) {
916                 float x, y, step = 2.0 / side, co[3];
917
918                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
919
920                 /*do normalized cannonical view coords for texture*/
921                 for (y = -1.0, iy = 0; iy < side; iy++, y += step) {
922                         for (x = -1.0, ix = 0; ix < side; ix++, x += step) {
923                                 co[0] = x;
924                                 co[1] = y;
925                                 co[2] = 0.0f;
926
927                                 /* This is copied from displace modifier code */
928                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 0, &texres, NULL);
929
930                                 /* if the texture gave an RGB value, we assume it didn't give a valid
931                                  * intensity, so calculate one (formula from do_material_tex).
932                                  * if the texture didn't give an RGB value, copy the intensity across
933                                  */
934                                 if (hasrgb & TEX_RGB)
935                                         texres.tin = rgb_to_grayscale(&texres.tr);
936
937                                 ((char *)texcache)[(iy * side + ix) * 4] =
938                                 ((char *)texcache)[(iy * side + ix) * 4 + 1] =
939                                 ((char *)texcache)[(iy * side + ix) * 4 + 2] =
940                                 ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(texres.tin * 255.0f);
941                         }
942                 }
943         }
944
945         return texcache;
946 }
947
948
949 /**** Radial Control ****/
950 struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br)
951 {
952         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
953         unsigned int *texcache;
954         int side = 128;
955         int half = side / 2;
956         int i, j;
957
958         texcache = BKE_brush_gen_texture_cache(br, half);
959         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
960         im->x = im->y = side;
961
962         for (i = 0; i < side; ++i) {
963                 for (j = 0; j < side; ++j) {
964                         float magn = sqrtf(powf(i - half, 2) + powf(j - half, 2));
965                         im->rect_float[i * side + j] = BKE_brush_curve_strength_clamp(br, magn, half);
966                 }
967         }
968
969         /* Modulate curve with texture */
970         if (texcache) {
971                 for (i = 0; i < side; ++i) {
972                         for (j = 0; j < side; ++j) {
973                                 const int col = texcache[i * side + j];
974                                 im->rect_float[i * side + j] *= (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
975                         }
976                 }
977
978                 MEM_freeN(texcache);
979         }
980
981         return im;
982 }