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