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