Reduce overhead when sampling texture images for brushes. The tests can
[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         /* For consistency, sampling always returns color in linear space */
638         else if (ups->do_linear_conversion) {
639                 IMB_colormanagement_colorspace_to_scene_linear_v3(rgba, ups->colorspace);
640         }
641
642         return intensity;
643 }
644
645 float BKE_brush_sample_masktex(const Scene *scene, Brush *br,
646                                const float point[2],
647                                const int thread,
648                                struct ImagePool *pool)
649 {
650         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
651         MTex *mtex = &br->mask_mtex;
652         float rgba[4], intensity;
653
654         if (!mtex->tex) {
655                 return 1.0f;
656         }
657         if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
658                 float rotation = -mtex->rot;
659                 float point_2d[2] = {point[0], point[1]};
660                 float x, y;
661                 float co[3];
662
663                 x = point_2d[0] - br->mask_stencil_pos[0];
664                 y = point_2d[1] - br->mask_stencil_pos[1];
665
666                 if (rotation > 0.001f || rotation < -0.001f) {
667                         const float angle    = atan2f(y, x) + rotation;
668                         const float flen     = sqrtf(x * x + y * y);
669
670                         x = flen * cosf(angle);
671                         y = flen * sinf(angle);
672                 }
673
674                 if (fabsf(x) > br->mask_stencil_dimension[0] || fabsf(y) > br->mask_stencil_dimension[1]) {
675                         zero_v4(rgba);
676                         return 0.0f;
677                 }
678                 x /= (br->mask_stencil_dimension[0]);
679                 y /= (br->mask_stencil_dimension[1]);
680
681                 co[0] = x;
682                 co[1] = y;
683                 co[2] = 0.0f;
684
685                 externtex(mtex, co, &intensity,
686                           rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
687         }
688         else {
689                 float rotation = -mtex->rot;
690                 float point_2d[2] = {point[0], point[1]};
691                 float x = 0.0f, y = 0.0f; /* Quite warnings */
692                 float invradius = 1.0f; /* Quite warnings */
693                 float co[3];
694
695                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
696                         /* keep coordinates relative to mouse */
697
698                         rotation += ups->brush_rotation;
699
700                         x = point_2d[0] - ups->mask_tex_mouse[0];
701                         y = point_2d[1] - ups->mask_tex_mouse[1];
702
703                         /* use pressure adjusted size for fixed mode */
704                         invradius = 1.0f / ups->pixel_radius;
705                 }
706                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
707                         /* leave the coordinates relative to the screen */
708
709                         /* use unadjusted size for tiled mode */
710                         invradius = 1.0f / BKE_brush_size_get(scene, br);
711
712                         x = point_2d[0];
713                         y = point_2d[1];
714                 }
715                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
716                         rotation += ups->brush_rotation;
717                         /* these contain a random coordinate */
718                         x = point_2d[0] - ups->mask_tex_mouse[0];
719                         y = point_2d[1] - ups->mask_tex_mouse[1];
720
721                         invradius = 1.0f / ups->pixel_radius;
722                 }
723
724                 x *= invradius;
725                 y *= invradius;
726
727                 /* it is probably worth optimizing for those cases where
728                  * the texture is not rotated by skipping the calls to
729                  * atan2, sqrtf, sin, and cos. */
730                 if (rotation > 0.001f || rotation < -0.001f) {
731                         const float angle    = atan2f(y, x) + rotation;
732                         const float flen     = sqrtf(x * x + y * y);
733
734                         x = flen * cosf(angle);
735                         y = flen * sinf(angle);
736                 }
737
738                 co[0] = x;
739                 co[1] = y;
740                 co[2] = 0.0f;
741
742                 externtex(mtex, co, &intensity,
743                           rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool);
744         }
745
746         return intensity;
747 }
748
749 /* Unified Size and Strength */
750
751 /* XXX: be careful about setting size and unprojected radius
752  * because they depend on one another
753  * these functions do not set the other corresponding value
754  * this can lead to odd behavior if size and unprojected
755  * radius become inconsistent.
756  * the biggest problem is that it isn't possible to change
757  * unprojected radius because a view context is not
758  * available.  my usual solution to this is to use the
759  * ratio of change of the size to change the unprojected
760  * radius.  Not completely convinced that is correct.
761  * In any case, a better solution is needed to prevent
762  * inconsistency. */
763
764 void BKE_brush_size_set(Scene *scene, Brush *brush, int size)
765 {
766         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
767         
768         size = (int)((float)size / U.pixelsize);
769         
770         if (ups->flag & UNIFIED_PAINT_SIZE)
771                 ups->size = size;
772         else
773                 brush->size = size;
774 }
775
776 int BKE_brush_size_get(const Scene *scene, Brush *brush)
777 {
778         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
779         int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size;
780         
781         return (int)((float)size * U.pixelsize);
782 }
783
784 int BKE_brush_use_locked_size(const Scene *scene, Brush *brush)
785 {
786         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
787
788         return (us_flag & UNIFIED_PAINT_SIZE) ?
789                (us_flag & UNIFIED_PAINT_BRUSH_LOCK_SIZE) :
790                (brush->flag & BRUSH_LOCK_SIZE);
791 }
792
793 int BKE_brush_use_size_pressure(const Scene *scene, Brush *brush)
794 {
795         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
796
797         return (us_flag & UNIFIED_PAINT_SIZE) ?
798                (us_flag & UNIFIED_PAINT_BRUSH_SIZE_PRESSURE) :
799                (brush->flag & BRUSH_SIZE_PRESSURE);
800 }
801
802 int BKE_brush_use_alpha_pressure(const Scene *scene, Brush *brush)
803 {
804         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
805
806         return (us_flag & UNIFIED_PAINT_ALPHA) ?
807                (us_flag & UNIFIED_PAINT_BRUSH_ALPHA_PRESSURE) :
808                (brush->flag & BRUSH_ALPHA_PRESSURE);
809 }
810
811 void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojected_radius)
812 {
813         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
814
815         if (ups->flag & UNIFIED_PAINT_SIZE)
816                 ups->unprojected_radius = unprojected_radius;
817         else
818                 brush->unprojected_radius = unprojected_radius;
819 }
820
821 float BKE_brush_unprojected_radius_get(const Scene *scene, Brush *brush)
822 {
823         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
824
825         return (ups->flag & UNIFIED_PAINT_SIZE) ?
826                ups->unprojected_radius :
827                brush->unprojected_radius;
828 }
829
830 void BKE_brush_alpha_set(Scene *scene, Brush *brush, float alpha)
831 {
832         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
833
834         if (ups->flag & UNIFIED_PAINT_ALPHA)
835                 ups->alpha = alpha;
836         else
837                 brush->alpha = alpha;
838 }
839
840 float BKE_brush_alpha_get(const Scene *scene, Brush *brush)
841 {
842         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
843
844         return (ups->flag & UNIFIED_PAINT_ALPHA) ? ups->alpha : brush->alpha;
845 }
846
847 float BKE_brush_weight_get(const Scene *scene, Brush *brush)
848 {
849         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
850
851         return (ups->flag & UNIFIED_PAINT_WEIGHT) ? ups->weight : brush->weight;
852 }
853
854 void BKE_brush_weight_set(const Scene *scene, Brush *brush, float value)
855 {
856         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
857
858         if (ups->flag & UNIFIED_PAINT_WEIGHT)
859                 ups->weight = value;
860         else
861                 brush->weight = value;
862 }
863
864 /* scale unprojected radius to reflect a change in the brush's 2D size */
865 void BKE_brush_scale_unprojected_radius(float *unprojected_radius,
866                                         int new_brush_size,
867                                         int old_brush_size)
868 {
869         float scale = new_brush_size;
870         /* avoid division by zero */
871         if (old_brush_size != 0)
872                 scale /= (float)old_brush_size;
873         (*unprojected_radius) *= scale;
874 }
875
876 /* scale brush size to reflect a change in the brush's unprojected radius */
877 void BKE_brush_scale_size(int *r_brush_size,
878                           float new_unprojected_radius,
879                           float old_unprojected_radius)
880 {
881         float scale = new_unprojected_radius;
882         /* avoid division by zero */
883         if (old_unprojected_radius != 0)
884                 scale /= new_unprojected_radius;
885         (*r_brush_size) = (int)((float)(*r_brush_size) * scale);
886 }
887
888 void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
889 {
890         int use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
891                 (brush->jitter_absolute != 0) : (brush->jitter != 0);
892
893         /* jitter-ed brush gives weird and unpredictable result for this
894          * kinds of stroke, so manually disable jitter usage (sergey) */
895         use_jitter &= (brush->flag & (BRUSH_DRAG_DOT | BRUSH_ANCHORED)) == 0;
896
897         if (use_jitter) {
898                 float rand_pos[2];
899                 float spread;
900                 int diameter;
901
902                 do {
903                         rand_pos[0] = BLI_rng_get_float(brush_rng) - 0.5f;
904                         rand_pos[1] = BLI_rng_get_float(brush_rng) - 0.5f;
905                 } while (len_squared_v2(rand_pos) > (0.5f * 0.5f));
906
907
908                 if (brush->flag & BRUSH_ABSOLUTE_JITTER) {
909                         diameter = 2 * brush->jitter_absolute;
910                         spread = 1.0;
911                 }
912                 else {
913                         diameter = 2 * BKE_brush_size_get(scene, brush);
914                         spread = brush->jitter;
915                 }
916                 /* find random position within a circle of diameter 1 */
917                 jitterpos[0] = pos[0] + 2 * rand_pos[0] * diameter * spread;
918                 jitterpos[1] = pos[1] + 2 * rand_pos[1] * diameter * spread;
919         }
920         else {
921                 copy_v2_v2(jitterpos, pos);
922         }
923 }
924
925 void BKE_brush_randomize_texture_coordinates(UnifiedPaintSettings *ups, bool mask)
926 {
927         /* we multiply with brush radius as an optimization for the brush
928          * texture sampling functions */
929         if (mask) {
930                 ups->mask_tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
931                 ups->mask_tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
932         }
933         else {
934                 ups->tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
935                 ups->tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
936         }
937 }
938
939 /* Uses the brush curve control to find a strength value between 0 and 1 */
940 float BKE_brush_curve_strength_clamp(Brush *br, float p, const float len)
941 {
942         float strength;
943
944         if (p >= len) return 0;
945         else p = p / len;
946
947         strength = curvemapping_evaluateF(br->curve, 0, p);
948
949         CLAMP(strength, 0.0f, 1.0f);
950
951         return strength;
952 }
953 /* same as above but can return negative values if the curve enables
954  * used for sculpt only */
955 float BKE_brush_curve_strength(Brush *br, float p, const float len)
956 {
957         if (p >= len)
958                 p = 1.0f;
959         else
960                 p = p / len;
961
962         return curvemapping_evaluateF(br->curve, 0, p);
963 }
964
965 /* TODO: should probably be unified with BrushPainter stuff? */
966 unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side, bool use_secondary)
967 {
968         unsigned int *texcache = NULL;
969         MTex *mtex = (use_secondary) ? &br->mask_mtex : &br->mtex;
970         float intensity;
971         float rgba[4];
972         int ix, iy;
973         int side = half_side * 2;
974
975         if (mtex->tex) {
976                 float x, y, step = 2.0 / side, co[3];
977
978                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
979
980                 /* do normalized cannonical view coords for texture */
981                 for (y = -1.0, iy = 0; iy < side; iy++, y += step) {
982                         for (x = -1.0, ix = 0; ix < side; ix++, x += step) {
983                                 co[0] = x;
984                                 co[1] = y;
985                                 co[2] = 0.0f;
986
987                                 /* This is copied from displace modifier code */
988                                 /* TODO(sergey): brush are always cacheing with CM enabled for now. */
989                                 externtex(mtex, co, &intensity,
990                                           rgba, rgba + 1, rgba + 2, rgba + 3, 0, NULL);
991
992                                 ((char *)texcache)[(iy * side + ix) * 4] =
993                                 ((char *)texcache)[(iy * side + ix) * 4 + 1] =
994                                 ((char *)texcache)[(iy * side + ix) * 4 + 2] =
995                                 ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(intensity * 255.0f);
996                         }
997                 }
998         }
999
1000         return texcache;
1001 }
1002
1003
1004 /**** Radial Control ****/
1005 struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br, bool secondary)
1006 {
1007         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1008         unsigned int *texcache;
1009         int side = 128;
1010         int half = side / 2;
1011         int i, j;
1012
1013         curvemapping_initialize(br->curve);
1014         texcache = BKE_brush_gen_texture_cache(br, half, secondary);
1015         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1016         im->x = im->y = side;
1017
1018         for (i = 0; i < side; ++i) {
1019                 for (j = 0; j < side; ++j) {
1020                         float magn = sqrtf(powf(i - half, 2) + powf(j - half, 2));
1021                         im->rect_float[i * side + j] = BKE_brush_curve_strength_clamp(br, magn, half);
1022                 }
1023         }
1024
1025         /* Modulate curve with texture */
1026         if (texcache) {
1027                 for (i = 0; i < side; ++i) {
1028                         for (j = 0; j < side; ++j) {
1029                                 const int col = texcache[i * side + j];
1030                                 im->rect_float[i * side + j] *= (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
1031                         }
1032                 }
1033
1034                 MEM_freeN(texcache);
1035         }
1036
1037         return im;
1038 }