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