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