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