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