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