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