Support more mapping modes for alpha masks. Tiled, stencil and random
[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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/brush.c
29  *  \ingroup bke
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_brush_types.h"
35 #include "DNA_scene_types.h"
36 #include "DNA_object_types.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_rand.h"
41
42 #include "BKE_brush.h"
43 #include "BKE_colortools.h"
44 #include "BKE_global.h"
45 #include "BKE_image.h"
46 #include "BKE_library.h"
47 #include "BKE_main.h"
48 #include "BKE_paint.h"
49 #include "BKE_texture.h"
50 #include "BKE_icons.h"
51
52 #include "IMB_imbuf.h"
53 #include "IMB_imbuf_types.h"
54
55 #include "RE_render_ext.h" /* externtex */
56 #include "RE_shader_ext.h"
57
58 static RNG *brush_rng;
59
60 void BKE_brush_system_init(void)
61 {
62         brush_rng = BLI_rng_new(0);
63         BLI_rng_srandom(brush_rng, 31415682);
64 }
65
66 void BKE_brush_system_exit(void)
67 {
68         BLI_rng_free(brush_rng);
69 }
70
71
72 static void brush_defaults(Brush *brush)
73 {
74         brush->blend = 0;
75         brush->flag = 0;
76
77         brush->ob_mode = OB_MODE_ALL_PAINT;
78
79         /* BRUSH SCULPT TOOL SETTINGS */
80         brush->weight = 1.0f; /* weight of brush 0 - 1.0 */
81         brush->size = 35; /* radius of the brush in pixels */
82         brush->alpha = 0.5f; /* brush strength/intensity probably variable should be renamed? */
83         brush->autosmooth_factor = 0.0f;
84         brush->crease_pinch_factor = 0.5f;
85         brush->sculpt_plane = SCULPT_DISP_DIR_AREA;
86         brush->plane_offset = 0.0f; /* how far above or below the plane that is found by averaging the faces */
87         brush->plane_trim = 0.5f;
88         brush->clone.alpha = 0.5f;
89         brush->normal_weight = 0.0f;
90         brush->flag |= BRUSH_ALPHA_PRESSURE;
91
92         /* BRUSH PAINT TOOL SETTINGS */
93         brush->rgb[0] = 1.0f; /* default rgb color of the brush when painting - white */
94         brush->rgb[1] = 1.0f;
95         brush->rgb[2] = 1.0f;
96
97         /* BRUSH STROKE SETTINGS */
98         brush->flag |= (BRUSH_SPACE | BRUSH_SPACE_ATTEN);
99         brush->spacing = 10; /* how far each brush dot should be spaced as a percentage of brush diameter */
100
101         brush->smooth_stroke_radius = 75;
102         brush->smooth_stroke_factor = 0.9f;
103
104         brush->rate = 0.1f; /* time delay between dots of paint or sculpting when doing airbrush mode */
105
106         brush->jitter = 0.0f;
107
108         /* BRUSH TEXTURE SETTINGS */
109         default_mtex(&brush->mtex);
110         default_mtex(&brush->mask_mtex);
111
112         brush->texture_sample_bias = 0; /* value to added to texture samples */
113         brush->texture_overlay_alpha = 33;
114         brush->mask_overlay_alpha = 33;
115         brush->cursor_overlay_alpha = 33;
116         brush->overlay_flags = 0;
117
118         /* brush appearance  */
119
120         brush->add_col[0] = 1.00; /* add mode color is light red */
121         brush->add_col[1] = 0.39;
122         brush->add_col[2] = 0.39;
123
124         brush->sub_col[0] = 0.39; /* subtract mode color is light blue */
125         brush->sub_col[1] = 0.39;
126         brush->sub_col[2] = 1.00;
127
128         brush->stencil_pos[0] = 256;
129         brush->stencil_pos[1] = 256;
130
131         brush->stencil_dimension[0] = 256;
132         brush->stencil_dimension[1] = 256;
133 }
134
135 /* Datablock add/copy/free/make_local */
136
137 Brush *BKE_brush_add(Main *bmain, const char *name)
138 {
139         Brush *brush;
140
141         brush = BKE_libblock_alloc(&bmain->brush, ID_BR, name);
142
143         /* enable fake user by default */
144         brush->id.flag |= LIB_FAKEUSER;
145
146         brush_defaults(brush);
147
148         brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */
149
150         /* the default alpha falloff curve */
151         BKE_brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
152
153         return brush;
154 }
155
156 Brush *BKE_brush_copy(Brush *brush)
157 {
158         Brush *brushn;
159         
160         brushn = BKE_libblock_copy(&brush->id);
161
162         if (brush->mtex.tex)
163                 id_us_plus((ID *)brush->mtex.tex);
164
165         if (brush->mask_mtex.tex)
166                 id_us_plus((ID *)brush->mask_mtex.tex);
167
168         if (brush->icon_imbuf)
169                 brushn->icon_imbuf = IMB_dupImBuf(brush->icon_imbuf);
170
171         brushn->preview = NULL;
172
173         brushn->curve = curvemapping_copy(brush->curve);
174
175         /* enable fake user by default */
176         if (!(brushn->id.flag & LIB_FAKEUSER)) {
177                 brushn->id.flag |= LIB_FAKEUSER;
178                 brushn->id.us++;
179         }
180         
181         return brushn;
182 }
183
184 /* not brush itself */
185 void BKE_brush_free(Brush *brush)
186 {
187         if (brush->mtex.tex)
188                 brush->mtex.tex->id.us--;
189
190         if (brush->mask_mtex.tex)
191                 brush->mask_mtex.tex->id.us--;
192
193         if (brush->icon_imbuf)
194                 IMB_freeImBuf(brush->icon_imbuf);
195
196         BKE_previewimg_free(&(brush->preview));
197
198         curvemapping_free(brush->curve);
199 }
200
201 static void extern_local_brush(Brush *brush)
202 {
203         id_lib_extern((ID *)brush->mtex.tex);
204         id_lib_extern((ID *)brush->mask_mtex.tex);
205         id_lib_extern((ID *)brush->clone.image);
206 }
207
208 void BKE_brush_make_local(Brush *brush)
209 {
210
211         /* - only lib users: do nothing
212          * - only local users: set flag
213          * - mixed: make copy
214          */
215
216         Main *bmain = G.main;
217         Scene *scene;
218         int is_local = FALSE, is_lib = FALSE;
219
220         if (brush->id.lib == NULL) return;
221
222         if (brush->clone.image) {
223                 /* special case: ima always local immediately. Clone image should only
224                  * have one user anyway. */
225                 id_clear_lib_data(bmain, &brush->clone.image->id);
226                 extern_local_brush(brush);
227         }
228
229         for (scene = bmain->scene.first; scene && ELEM(0, is_lib, is_local); scene = scene->id.next) {
230                 if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
231                         if (scene->id.lib) is_lib = TRUE;
232                         else is_local = TRUE;
233                 }
234         }
235
236         if (is_local && is_lib == FALSE) {
237                 id_clear_lib_data(bmain, &brush->id);
238                 extern_local_brush(brush);
239
240                 /* enable fake user by default */
241                 if (!(brush->id.flag & LIB_FAKEUSER)) {
242                         brush->id.flag |= LIB_FAKEUSER;
243                         brush->id.us++;
244                 }
245         }
246         else if (is_local && is_lib) {
247                 Brush *brush_new = BKE_brush_copy(brush);
248                 brush_new->id.us = 1; /* only keep fake user */
249                 brush_new->id.flag |= LIB_FAKEUSER;
250
251                 /* Remap paths of new ID using old library as base. */
252                 BKE_id_lib_local_paths(bmain, brush->id.lib, &brush_new->id);
253                 
254                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
255                         if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
256                                 if (scene->id.lib == NULL) {
257                                         BKE_paint_brush_set(&scene->toolsettings->imapaint.paint, brush_new);
258                                 }
259                         }
260                 }
261         }
262 }
263
264 void BKE_brush_debug_print_state(Brush *br)
265 {
266         /* create a fake brush and set it to the defaults */
267         Brush def = {{NULL}};
268         brush_defaults(&def);
269         
270 #define BR_TEST(field, t)                                       \
271         if (br->field != def.field)                             \
272                 printf("br->" #field " = %" #t ";\n", br->field)
273
274 #define BR_TEST_FLAG(_f)                                                        \
275         if ((br->flag & _f) && !(def.flag & _f))                \
276                 printf("br->flag |= " #_f ";\n");                       \
277         else if (!(br->flag & _f) && (def.flag & _f))   \
278                 printf("br->flag &= ~" #_f ";\n")
279         
280 #define BR_TEST_FLAG_OVERLAY(_f)                                                        \
281         if ((br->overlay_flags & _f) && !(def.overlay_flags & _f))              \
282                 printf("br->overlay_flags |= " #_f ";\n");                      \
283         else if (!(br->overlay_flags & _f) && (def.overlay_flags & _f)) \
284                 printf("br->overlay_flags &= ~" #_f ";\n")
285
286         /* print out any non-default brush state */
287         BR_TEST(normal_weight, f);
288
289         BR_TEST(blend, d);
290         BR_TEST(size, d);
291
292         /* br->flag */
293         BR_TEST_FLAG(BRUSH_AIRBRUSH);
294         BR_TEST_FLAG(BRUSH_TORUS);
295         BR_TEST_FLAG(BRUSH_ALPHA_PRESSURE);
296         BR_TEST_FLAG(BRUSH_SIZE_PRESSURE);
297         BR_TEST_FLAG(BRUSH_JITTER_PRESSURE);
298         BR_TEST_FLAG(BRUSH_SPACING_PRESSURE);
299         BR_TEST_FLAG(BRUSH_RAKE);
300         BR_TEST_FLAG(BRUSH_ANCHORED);
301         BR_TEST_FLAG(BRUSH_DIR_IN);
302         BR_TEST_FLAG(BRUSH_SPACE);
303         BR_TEST_FLAG(BRUSH_SMOOTH_STROKE);
304         BR_TEST_FLAG(BRUSH_PERSISTENT);
305         BR_TEST_FLAG(BRUSH_ACCUMULATE);
306         BR_TEST_FLAG(BRUSH_LOCK_ALPHA);
307         BR_TEST_FLAG(BRUSH_ORIGINAL_NORMAL);
308         BR_TEST_FLAG(BRUSH_OFFSET_PRESSURE);
309         BR_TEST_FLAG(BRUSH_SPACE_ATTEN);
310         BR_TEST_FLAG(BRUSH_ADAPTIVE_SPACE);
311         BR_TEST_FLAG(BRUSH_LOCK_SIZE);
312         BR_TEST_FLAG(BRUSH_EDGE_TO_EDGE);
313         BR_TEST_FLAG(BRUSH_RESTORE_MESH);
314         BR_TEST_FLAG(BRUSH_INVERSE_SMOOTH_PRESSURE);
315         BR_TEST_FLAG(BRUSH_RANDOM_ROTATION);
316         BR_TEST_FLAG(BRUSH_PLANE_TRIM);
317         BR_TEST_FLAG(BRUSH_FRONTFACE);
318         BR_TEST_FLAG(BRUSH_CUSTOM_ICON);
319
320         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR);
321         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY);
322         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY);
323         BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_OVERRIDE_ON_STROKE);
324
325         BR_TEST(jitter, f);
326         BR_TEST(spacing, d);
327         BR_TEST(smooth_stroke_radius, d);
328         BR_TEST(smooth_stroke_factor, f);
329         BR_TEST(rate, f);
330
331         BR_TEST(alpha, f);
332
333         BR_TEST(sculpt_plane, d);
334
335         BR_TEST(plane_offset, f);
336
337         BR_TEST(autosmooth_factor, f);
338
339         BR_TEST(crease_pinch_factor, f);
340
341         BR_TEST(plane_trim, f);
342
343         BR_TEST(texture_sample_bias, f);
344         BR_TEST(texture_overlay_alpha, d);
345
346         BR_TEST(add_col[0], f);
347         BR_TEST(add_col[1], f);
348         BR_TEST(add_col[2], f);
349         BR_TEST(sub_col[0], f);
350         BR_TEST(sub_col[1], f);
351         BR_TEST(sub_col[2], f);
352
353         printf("\n");
354         
355 #undef BR_TEST
356 #undef BR_TEST_FLAG
357 }
358
359 void BKE_brush_sculpt_reset(Brush *br)
360 {
361         /* enable this to see any non-default
362          * settings used by a brush: */
363         // BKE_brush_debug_print_state(br);
364
365         brush_defaults(br);
366         BKE_brush_curve_preset(br, CURVE_PRESET_SMOOTH);
367
368         switch (br->sculpt_tool) {
369                 case SCULPT_TOOL_CLAY:
370                         br->flag |= BRUSH_FRONTFACE;
371                         break;
372                 case SCULPT_TOOL_CREASE:
373                         br->flag |= BRUSH_DIR_IN;
374                         br->alpha = 0.25;
375                         break;
376                 case SCULPT_TOOL_FILL:
377                         br->add_col[1] = 1;
378                         br->sub_col[0] = 0.25;
379                         br->sub_col[1] = 1;
380                         break;
381                 case SCULPT_TOOL_FLATTEN:
382                         br->add_col[1] = 1;
383                         br->sub_col[0] = 0.25;
384                         br->sub_col[1] = 1;
385                         break;
386                 case SCULPT_TOOL_INFLATE:
387                         br->add_col[0] = 0.750000;
388                         br->add_col[1] = 0.750000;
389                         br->add_col[2] = 0.750000;
390                         br->sub_col[0] = 0.250000;
391                         br->sub_col[1] = 0.250000;
392                         br->sub_col[2] = 0.250000;
393                         break;
394                 case SCULPT_TOOL_NUDGE:
395                         br->add_col[0] = 0.250000;
396                         br->add_col[1] = 1.000000;
397                         br->add_col[2] = 0.250000;
398                         break;
399                 case SCULPT_TOOL_PINCH:
400                         br->add_col[0] = 0.750000;
401                         br->add_col[1] = 0.750000;
402                         br->add_col[2] = 0.750000;
403                         br->sub_col[0] = 0.250000;
404                         br->sub_col[1] = 0.250000;
405                         br->sub_col[2] = 0.250000;
406                         break;
407                 case SCULPT_TOOL_SCRAPE:
408                         br->add_col[1] = 1.000000;
409                         br->sub_col[0] = 0.250000;
410                         br->sub_col[1] = 1.000000;
411                         break;
412                 case SCULPT_TOOL_ROTATE:
413                         br->alpha = 1.0;
414                         break;
415                 case SCULPT_TOOL_SMOOTH:
416                         br->flag &= ~BRUSH_SPACE_ATTEN;
417                         br->spacing = 5;
418                         br->add_col[0] = 0.750000;
419                         br->add_col[1] = 0.750000;
420                         br->add_col[2] = 0.750000;
421                         break;
422                 case SCULPT_TOOL_GRAB:
423                 case SCULPT_TOOL_SNAKE_HOOK:
424                 case SCULPT_TOOL_THUMB:
425                         br->size = 75;
426                         br->flag &= ~BRUSH_ALPHA_PRESSURE;
427                         br->flag &= ~BRUSH_SPACE;
428                         br->flag &= ~BRUSH_SPACE_ATTEN;
429                         br->add_col[0] = 0.250000;
430                         br->add_col[1] = 1.000000;
431                         br->add_col[2] = 0.250000;
432                         break;
433                 default:
434                         break;
435         }
436 }
437
438 /**
439  * Library Operations
440  * \param preset  CurveMappingPreset
441  */
442 void BKE_brush_curve_preset(Brush *b, int preset)
443 {
444         CurveMap *cm = NULL;
445
446         if (!b->curve)
447                 b->curve = curvemapping_add(1, 0, 0, 1, 1);
448
449         cm = b->curve->cm;
450         cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
451
452         b->curve->preset = preset;
453         curvemap_reset(cm, &b->curve->clipr, b->curve->preset, CURVEMAP_SLOPE_NEGATIVE);
454         curvemapping_changed(b->curve, FALSE);
455 }
456
457 int BKE_brush_texture_set_nr(Brush *brush, int nr)
458 {
459         ID *idtest, *id = NULL;
460
461         id = (ID *)brush->mtex.tex;
462
463         idtest = (ID *)BLI_findlink(&G.main->tex, nr - 1);
464         if (idtest == NULL) { /* new tex */
465                 if (id) idtest = (ID *)BKE_texture_copy((Tex *)id);
466                 else idtest = (ID *)add_texture(G.main, "Tex");
467                 idtest->us--;
468         }
469         if (idtest != id) {
470                 BKE_brush_texture_delete(brush);
471
472                 brush->mtex.tex = (Tex *)idtest;
473                 id_us_plus(idtest);
474
475                 return 1;
476         }
477
478         return 0;
479 }
480
481 int BKE_brush_texture_delete(Brush *brush)
482 {
483         if (brush->mtex.tex)
484                 brush->mtex.tex->id.us--;
485
486         return 1;
487 }
488
489 int BKE_brush_clone_image_set_nr(Brush *brush, int nr)
490 {
491         if (brush && nr > 0) {
492                 Image *ima = (Image *)BLI_findlink(&G.main->image, nr - 1);
493
494                 if (ima) {
495                         BKE_brush_clone_image_delete(brush);
496                         brush->clone.image = ima;
497                         id_us_plus(&ima->id);
498                         brush->clone.offset[0] = brush->clone.offset[1] = 0.0f;
499
500                         return 1;
501                 }
502         }
503
504         return 0;
505 }
506
507 int BKE_brush_clone_image_delete(Brush *brush)
508 {
509         if (brush && brush->clone.image) {
510                 brush->clone.image->id.us--;
511                 brush->clone.image = NULL;
512                 return 1;
513         }
514
515         return 0;
516 }
517
518 /* Generic texture sampler for 3D painting systems. point has to be either in
519  * region space mouse coordinates, or 3d world coordinates for 3D mapping */
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 = 0.0f, y = 0.0f; /* Quite warnings */
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 = 0.0f, y = 0.0f; /* Quite warnings */
662                 float co[3];
663
664                 x = point_2d[0] - br->stencil_pos[0];
665                 y = point_2d[1] - br->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->stencil_dimension[0] || fabsf(y) > br->stencil_dimension[1]) {
676                         zero_v4(rgba);
677                         return 0.0f;
678                 }
679                 x /= (br->stencil_dimension[0]);
680                 y /= (br->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 /* Brush Sampling for 2D brushes. when we unify the brush systems this will be necessarily a separate function */
757 float BKE_brush_sample_tex_2D(const Scene *scene, Brush *brush, const float xy[2], float rgba[4])
758 {
759         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
760         MTex *mtex = &brush->mtex;
761
762         if (mtex && mtex->tex) {
763                 float co[3], tin, tr, tg, tb, ta;
764                 float x = xy[0], y = xy[1];
765                 int hasrgb;
766                 int radius = BKE_brush_size_get(scene, brush);
767                 float rotation = -mtex->rot;
768
769                 if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
770                         rotation += ups->brush_rotation;
771                         radius = ups->pixel_radius;
772                 }
773                 else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
774                         rotation += ups->brush_rotation;
775                         /* these contain a random coordinate */
776                         x -= ups->tex_mouse[0];
777                         y -= ups->tex_mouse[1];
778
779                         radius = ups->pixel_radius;
780                 }
781
782                 x /= radius;
783                 y /= radius;
784
785                 if (rotation > 0.001f || rotation < -0.001f) {
786                         const float angle    = atan2f(y, x) + rotation;
787                         const float flen     = sqrtf(x * x + y * y);
788
789                         x = flen * cosf(angle);
790                         y = flen * sinf(angle);
791                 }
792
793                 x *= brush->mtex.size[0];
794                 y *= brush->mtex.size[1];
795
796                 co[0] = x + brush->mtex.ofs[0];
797                 co[1] = y + brush->mtex.ofs[1];
798                 co[2] = 0.0f;
799
800                 hasrgb = externtex(mtex, co, &tin, &tr, &tg, &tb, &ta, 0, NULL);
801
802                 if (hasrgb) {
803                         rgba[0] = tr;
804                         rgba[1] = tg;
805                         rgba[2] = tb;
806                         rgba[3] = ta;
807                 }
808                 else {
809                         rgba[0] = tin;
810                         rgba[1] = tin;
811                         rgba[2] = tin;
812                         rgba[3] = 1.0f;
813                 }
814                 return tin;
815         }
816         else {
817                 rgba[0] = rgba[1] = rgba[2] = rgba[3] = 1.0f;
818                 return 1.0;
819         }
820 }
821
822 /* TODO, use define for 'texfall' arg
823  * NOTE: only used for 2d brushes currently! */
824 void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texfall, int bufsize, ImBuf **outbuf, int use_color_correction)
825 {
826         ImBuf *ibuf;
827         float xy[2], rgba[4], *dstf;
828         int x, y, rowbytes, xoff, yoff, imbflag;
829         const int radius = BKE_brush_size_get(scene, brush);
830         unsigned char *dst, crgb[3];
831         const float alpha = BKE_brush_alpha_get(scene, brush);
832         float brush_rgb[3];
833
834         imbflag = (flt) ? IB_rectfloat : IB_rect;
835         xoff = -bufsize / 2.0f + 0.5f;
836         yoff = -bufsize / 2.0f + 0.5f;
837         rowbytes = bufsize * 4;
838
839         if (*outbuf)
840                 ibuf = *outbuf;
841         else
842                 ibuf = IMB_allocImBuf(bufsize, bufsize, 32, imbflag);
843
844         if (flt) {
845                 copy_v3_v3(brush_rgb, brush->rgb);
846                 if (use_color_correction) {
847                         srgb_to_linearrgb_v3_v3(brush_rgb, brush_rgb);
848                 }
849
850                 for (y = 0; y < ibuf->y; y++) {
851                         dstf = ibuf->rect_float + y * rowbytes;
852
853                         for (x = 0; x < ibuf->x; x++, dstf += 4) {
854                                 xy[0] = x + xoff;
855                                 xy[1] = y + yoff;
856
857                                 if (texfall == 0) {
858                                         copy_v3_v3(dstf, brush_rgb);
859                                         dstf[3] = alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
860                                 }
861                                 else if (texfall == 1) {
862                                         BKE_brush_sample_tex_2D(scene, brush, xy, dstf);
863                                 }
864                                 else if (texfall == 2) {
865                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
866                                         mul_v3_v3v3(dstf, rgba, brush_rgb);
867                                         dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
868                                 }
869                                 else {
870                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
871                                         copy_v3_v3(dstf, brush_rgb);
872                                         dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
873                                 }
874                         }
875                 }
876         }
877         else {
878                 float alpha_f; /* final float alpha to convert to char */
879                 rgb_float_to_uchar(crgb, brush->rgb);
880
881                 for (y = 0; y < ibuf->y; y++) {
882                         dst = (unsigned char *)ibuf->rect + y * rowbytes;
883
884                         for (x = 0; x < ibuf->x; x++, dst += 4) {
885                                 xy[0] = x + xoff;
886                                 xy[1] = y + yoff;
887
888                                 if (texfall == 0) {
889                                         alpha_f = alpha * BKE_brush_curve_strength(brush, len_v2(xy), radius);
890
891                                         dst[0] = crgb[0];
892                                         dst[1] = crgb[1];
893                                         dst[2] = crgb[2];
894                                         dst[3] = FTOCHAR(alpha_f);
895                                 }
896                                 else if (texfall == 1) {
897                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
898                                         rgba_float_to_uchar(dst, rgba);
899                                 }
900                                 else if (texfall == 2) {
901                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
902                                         mul_v3_v3(rgba, brush->rgb);
903                                         alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
904
905                                         rgb_float_to_uchar(dst, rgba);
906
907                                         dst[3] = FTOCHAR(alpha_f);
908                                 }
909                                 else {
910                                         BKE_brush_sample_tex_2D(scene, brush, xy, rgba);
911                                         alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
912
913                                         dst[0] = crgb[0];
914                                         dst[1] = crgb[1];
915                                         dst[2] = crgb[2];
916                                         dst[3] = FTOCHAR(alpha_f);
917                                 }
918                         }
919                 }
920         }
921
922         *outbuf = ibuf;
923 }
924
925 /* Unified Size and Strength */
926
927 /* XXX: be careful about setting size and unprojected radius
928  * because they depend on one another
929  * these functions do not set the other corresponding value
930  * this can lead to odd behavior if size and unprojected
931  * radius become inconsistent.
932  * the biggest problem is that it isn't possible to change
933  * unprojected radius because a view context is not
934  * available.  my ussual solution to this is to use the
935  * ratio of change of the size to change the unprojected
936  * radius.  Not completely convinced that is correct.
937  * In any case, a better solution is needed to prevent
938  * inconsistency. */
939
940 void BKE_brush_size_set(Scene *scene, Brush *brush, int size)
941 {
942         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
943         
944         size = (int)((float)size / U.pixelsize);
945         
946         if (ups->flag & UNIFIED_PAINT_SIZE)
947                 ups->size = size;
948         else
949                 brush->size = size;
950 }
951
952 int BKE_brush_size_get(const Scene *scene, Brush *brush)
953 {
954         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
955         int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size;
956         
957         return (int)((float)size * U.pixelsize);
958 }
959
960 int BKE_brush_use_locked_size(const Scene *scene, Brush *brush)
961 {
962         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
963
964         return (us_flag & UNIFIED_PAINT_SIZE) ?
965                (us_flag & UNIFIED_PAINT_BRUSH_LOCK_SIZE) :
966                (brush->flag & BRUSH_LOCK_SIZE);
967 }
968
969 int BKE_brush_use_size_pressure(const Scene *scene, Brush *brush)
970 {
971         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
972
973         return (us_flag & UNIFIED_PAINT_SIZE) ?
974                (us_flag & UNIFIED_PAINT_BRUSH_SIZE_PRESSURE) :
975                (brush->flag & BRUSH_SIZE_PRESSURE);
976 }
977
978 int BKE_brush_use_alpha_pressure(const Scene *scene, Brush *brush)
979 {
980         const short us_flag = scene->toolsettings->unified_paint_settings.flag;
981
982         return (us_flag & UNIFIED_PAINT_ALPHA) ?
983                (us_flag & UNIFIED_PAINT_BRUSH_ALPHA_PRESSURE) :
984                (brush->flag & BRUSH_ALPHA_PRESSURE);
985 }
986
987 void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojected_radius)
988 {
989         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
990
991         if (ups->flag & UNIFIED_PAINT_SIZE)
992                 ups->unprojected_radius = unprojected_radius;
993         else
994                 brush->unprojected_radius = unprojected_radius;
995 }
996
997 float BKE_brush_unprojected_radius_get(const Scene *scene, Brush *brush)
998 {
999         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1000
1001         return (ups->flag & UNIFIED_PAINT_SIZE) ?
1002                ups->unprojected_radius :
1003                brush->unprojected_radius;
1004 }
1005
1006 void BKE_brush_alpha_set(Scene *scene, Brush *brush, float alpha)
1007 {
1008         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1009
1010         if (ups->flag & UNIFIED_PAINT_ALPHA)
1011                 ups->alpha = alpha;
1012         else
1013                 brush->alpha = alpha;
1014 }
1015
1016 float BKE_brush_alpha_get(const Scene *scene, Brush *brush)
1017 {
1018         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1019
1020         return (ups->flag & UNIFIED_PAINT_ALPHA) ? ups->alpha : brush->alpha;
1021 }
1022
1023 float BKE_brush_weight_get(const Scene *scene, Brush *brush)
1024 {
1025         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1026
1027         return (ups->flag & UNIFIED_PAINT_WEIGHT) ? ups->weight : brush->weight;
1028 }
1029
1030 void BKE_brush_weight_set(const Scene *scene, Brush *brush, float value)
1031 {
1032         UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
1033
1034         if (ups->flag & UNIFIED_PAINT_WEIGHT)
1035                 ups->weight = value;
1036         else
1037                 brush->weight = value;
1038 }
1039
1040 /* scale unprojected radius to reflect a change in the brush's 2D size */
1041 void BKE_brush_scale_unprojected_radius(float *unprojected_radius,
1042                                         int new_brush_size,
1043                                         int old_brush_size)
1044 {
1045         float scale = new_brush_size;
1046         /* avoid division by zero */
1047         if (old_brush_size != 0)
1048                 scale /= (float)old_brush_size;
1049         (*unprojected_radius) *= scale;
1050 }
1051
1052 /* scale brush size to reflect a change in the brush's unprojected radius */
1053 void BKE_brush_scale_size(int *r_brush_size,
1054                           float new_unprojected_radius,
1055                           float old_unprojected_radius)
1056 {
1057         float scale = new_unprojected_radius;
1058         /* avoid division by zero */
1059         if (old_unprojected_radius != 0)
1060                 scale /= new_unprojected_radius;
1061         (*r_brush_size) = (int)((float)(*r_brush_size) * scale);
1062 }
1063
1064 void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
1065 {
1066         int use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
1067                 (brush->jitter_absolute != 0) : (brush->jitter != 0);
1068
1069         /* jitter-ed brush gives weird and unpredictable result for this
1070          * kinds of stroke, so manually disable jitter usage (sergey) */
1071         use_jitter &= (brush->flag & (BRUSH_RESTORE_MESH | BRUSH_ANCHORED)) == 0;
1072
1073         if (use_jitter) {
1074                 float rand_pos[2];
1075                 float spread;
1076                 int diameter;
1077
1078                 do {
1079                         rand_pos[0] = BLI_rng_get_float(brush_rng) - 0.5f;
1080                         rand_pos[1] = BLI_rng_get_float(brush_rng) - 0.5f;
1081                 } while (len_v2(rand_pos) > 0.5f);
1082
1083
1084                 if (brush->flag & BRUSH_ABSOLUTE_JITTER) {
1085                         diameter = 2 * brush->jitter_absolute;
1086                         spread = 1.0;
1087                 }
1088                 else {
1089                         diameter = 2 * BKE_brush_size_get(scene, brush);
1090                         spread = brush->jitter;
1091                 }
1092                 /* find random position within a circle of diameter 1 */
1093                 jitterpos[0] = pos[0] + 2 * rand_pos[0] * diameter * spread;
1094                 jitterpos[1] = pos[1] + 2 * rand_pos[1] * diameter * spread;
1095         }
1096         else {
1097                 copy_v2_v2(jitterpos, pos);
1098         }
1099 }
1100
1101 void BKE_brush_randomize_texture_coordinates(UnifiedPaintSettings *ups, bool mask)
1102 {
1103         /* we multiply with brush radius as an optimization for the brush
1104          * texture sampling functions */
1105         if (mask) {
1106                 ups->mask_tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1107                 ups->mask_tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1108         }
1109         else {
1110                 ups->tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1111                 ups->tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
1112         }
1113 }
1114
1115 /* Uses the brush curve control to find a strength value between 0 and 1 */
1116 float BKE_brush_curve_strength_clamp(Brush *br, float p, const float len)
1117 {
1118         if (p >= len) return 0;
1119         else p = p / len;
1120
1121         curvemapping_initialize(br->curve);
1122         p = curvemapping_evaluateF(br->curve, 0, p);
1123
1124         if (p < 0.0f) p = 0.0f;
1125         else if (p > 1.0f) p = 1.0f;
1126         return p;
1127 }
1128 /* same as above but can return negative values if the curve enables
1129  * used for sculpt only */
1130 float BKE_brush_curve_strength(Brush *br, float p, const float len)
1131 {
1132         if (p >= len)
1133                 p = 1.0f;
1134         else
1135                 p = p / len;
1136
1137         curvemapping_initialize(br->curve);
1138         return curvemapping_evaluateF(br->curve, 0, p);
1139 }
1140
1141 /* TODO: should probably be unified with BrushPainter stuff? */
1142 unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
1143 {
1144         unsigned int *texcache = NULL;
1145         MTex *mtex = &br->mtex;
1146         TexResult texres = {0};
1147         int hasrgb, ix, iy;
1148         int side = half_side * 2;
1149
1150         if (mtex->tex) {
1151                 float x, y, step = 2.0 / side, co[3];
1152
1153                 texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
1154
1155                 /* do normalized cannonical view coords for texture */
1156                 for (y = -1.0, iy = 0; iy < side; iy++, y += step) {
1157                         for (x = -1.0, ix = 0; ix < side; ix++, x += step) {
1158                                 co[0] = x;
1159                                 co[1] = y;
1160                                 co[2] = 0.0f;
1161
1162                                 /* This is copied from displace modifier code */
1163                                 hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 0, &texres, NULL);
1164
1165                                 /* if the texture gave an RGB value, we assume it didn't give a valid
1166                                  * intensity, so calculate one (formula from do_material_tex).
1167                                  * if the texture didn't give an RGB value, copy the intensity across
1168                                  */
1169                                 if (hasrgb & TEX_RGB)
1170                                         texres.tin = rgb_to_grayscale(&texres.tr);
1171
1172                                 ((char *)texcache)[(iy * side + ix) * 4] =
1173                                 ((char *)texcache)[(iy * side + ix) * 4 + 1] =
1174                                 ((char *)texcache)[(iy * side + ix) * 4 + 2] =
1175                                 ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(texres.tin * 255.0f);
1176                         }
1177                 }
1178         }
1179
1180         return texcache;
1181 }
1182
1183
1184 /**** Radial Control ****/
1185 struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br)
1186 {
1187         ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
1188         unsigned int *texcache;
1189         int side = 128;
1190         int half = side / 2;
1191         int i, j;
1192
1193         texcache = BKE_brush_gen_texture_cache(br, half);
1194         im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
1195         im->x = im->y = side;
1196
1197         for (i = 0; i < side; ++i) {
1198                 for (j = 0; j < side; ++j) {
1199                         float magn = sqrtf(powf(i - half, 2) + powf(j - half, 2));
1200                         im->rect_float[i * side + j] = BKE_brush_curve_strength_clamp(br, magn, half);
1201                 }
1202         }
1203
1204         /* Modulate curve with texture */
1205         if (texcache) {
1206                 for (i = 0; i < side; ++i) {
1207                         for (j = 0; j < side; ++j) {
1208                                 const int col = texcache[i * side + j];
1209                                 im->rect_float[i * side + j] *= (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
1210                         }
1211                 }
1212
1213                 MEM_freeN(texcache);
1214         }
1215
1216         return im;
1217 }