Revert to master - those changes are globally valid, but remain incomplete,
[blender.git] / source / blender / blenkernel / intern / brush.c
index 3d32ac8db7747288d3ee72b84caf69a455915187..e0ffd83080493c33ebf933d103e34b8fcf04ee35 100644 (file)
  * along with this program; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  *
- * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
  * Contributor(s): none yet.
  *
  * ***** END GPL LICENSE BLOCK *****
 #include "BKE_brush.h"
 #include "BKE_colortools.h"
 #include "BKE_global.h"
-#include "BKE_image.h"
 #include "BKE_library.h"
 #include "BKE_main.h"
 #include "BKE_paint.h"
 #include "BKE_texture.h"
 #include "BKE_icons.h"
 
+#include "IMB_colormanagement.h"
 #include "IMB_imbuf.h"
 #include "IMB_imbuf_types.h"
 
 #include "RE_render_ext.h" /* externtex */
-#include "RE_shader_ext.h"
+
+static RNG *brush_rng;
+
+void BKE_brush_system_init(void)
+{
+       brush_rng = BLI_rng_new(0);
+       BLI_rng_srandom(brush_rng, 31415682);
+}
+
+void BKE_brush_system_exit(void)
+{
+       BLI_rng_free(brush_rng);
+}
+
 
 static void brush_defaults(Brush *brush)
 {
@@ -73,6 +81,7 @@ static void brush_defaults(Brush *brush)
        brush->plane_trim = 0.5f;
        brush->clone.alpha = 0.5f;
        brush->normal_weight = 0.0f;
+       brush->fill_threshold = 0.2f;
        brush->flag |= BRUSH_ALPHA_PRESSURE;
 
        /* BRUSH PAINT TOOL SETTINGS */
@@ -80,6 +89,8 @@ static void brush_defaults(Brush *brush)
        brush->rgb[1] = 1.0f;
        brush->rgb[2] = 1.0f;
 
+       zero_v3(brush->secondary_rgb);
+
        /* BRUSH STROKE SETTINGS */
        brush->flag |= (BRUSH_SPACE | BRUSH_SPACE_ATTEN);
        brush->spacing = 10; /* how far each brush dot should be spaced as a percentage of brush diameter */
@@ -92,10 +103,14 @@ static void brush_defaults(Brush *brush)
        brush->jitter = 0.0f;
 
        /* BRUSH TEXTURE SETTINGS */
-       default_mtex(&brush->mtex);
+       BKE_texture_mtex_default(&brush->mtex);
+       BKE_texture_mtex_default(&brush->mask_mtex);
 
        brush->texture_sample_bias = 0; /* value to added to texture samples */
        brush->texture_overlay_alpha = 33;
+       brush->mask_overlay_alpha = 33;
+       brush->cursor_overlay_alpha = 33;
+       brush->overlay_flags = 0;
 
        /* brush appearance  */
 
@@ -106,15 +121,21 @@ static void brush_defaults(Brush *brush)
        brush->sub_col[0] = 0.39; /* subtract mode color is light blue */
        brush->sub_col[1] = 0.39;
        brush->sub_col[2] = 1.00;
+
+       brush->stencil_pos[0] = 256;
+       brush->stencil_pos[1] = 256;
+
+       brush->stencil_dimension[0] = 256;
+       brush->stencil_dimension[1] = 256;
 }
 
 /* Datablock add/copy/free/make_local */
 
-Brush *BKE_brush_add(Main *bmain, const char *name)
+Brush *BKE_brush_add(Main *bmain, const char *name, short ob_mode)
 {
        Brush *brush;
 
-       brush = BKE_libblock_alloc(&bmain->brush, ID_BR, name);
+       brush = BKE_libblock_alloc(bmain, ID_BR, name);
 
        /* enable fake user by default */
        brush->id.flag |= LIB_FAKEUSER;
@@ -122,6 +143,7 @@ Brush *BKE_brush_add(Main *bmain, const char *name)
        brush_defaults(brush);
 
        brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */
+       brush->ob_mode = ob_mode;
 
        /* the default alpha falloff curve */
        BKE_brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
@@ -129,6 +151,17 @@ Brush *BKE_brush_add(Main *bmain, const char *name)
        return brush;
 }
 
+struct Brush *BKE_brush_first_search(struct Main *bmain, short ob_mode)
+{
+       Brush *brush;
+
+       for (brush = bmain->brush.first; brush; brush = brush->id.next) {
+               if (brush->ob_mode & ob_mode)
+                       return brush;
+       }
+       return NULL;
+}
+
 Brush *BKE_brush_copy(Brush *brush)
 {
        Brush *brushn;
@@ -138,6 +171,12 @@ Brush *BKE_brush_copy(Brush *brush)
        if (brush->mtex.tex)
                id_us_plus((ID *)brush->mtex.tex);
 
+       if (brush->mask_mtex.tex)
+               id_us_plus((ID *)brush->mask_mtex.tex);
+
+       if (brush->paint_curve)
+               id_us_plus((ID *)brush->paint_curve);
+
        if (brush->icon_imbuf)
                brushn->icon_imbuf = IMB_dupImBuf(brush->icon_imbuf);
 
@@ -151,14 +190,19 @@ Brush *BKE_brush_copy(Brush *brush)
                brushn->id.us++;
        }
        
+       if (brush->id.lib) {
+               BKE_id_lib_local_paths(G.main, brush->id.lib, &brushn->id);
+       }
+
        return brushn;
 }
 
 /* not brush itself */
 void BKE_brush_free(Brush *brush)
 {
-       if (brush->mtex.tex)
-               brush->mtex.tex->id.us--;
+       id_us_min((ID *)brush->mtex.tex);
+       id_us_min((ID *)brush->mask_mtex.tex);
+       id_us_min((ID *)brush->paint_curve);
 
        if (brush->icon_imbuf)
                IMB_freeImBuf(brush->icon_imbuf);
@@ -166,12 +210,17 @@ void BKE_brush_free(Brush *brush)
        BKE_previewimg_free(&(brush->preview));
 
        curvemapping_free(brush->curve);
+
+       if (brush->gradient)
+               MEM_freeN(brush->gradient);
 }
 
 static void extern_local_brush(Brush *brush)
 {
        id_lib_extern((ID *)brush->mtex.tex);
+       id_lib_extern((ID *)brush->mask_mtex.tex);
        id_lib_extern((ID *)brush->clone.image);
+       id_lib_extern((ID *)brush->paint_curve);
 }
 
 void BKE_brush_make_local(Brush *brush)
@@ -184,7 +233,7 @@ void BKE_brush_make_local(Brush *brush)
 
        Main *bmain = G.main;
        Scene *scene;
-       int is_local = FALSE, is_lib = FALSE;
+       bool is_local = false, is_lib = false;
 
        if (brush->id.lib == NULL) return;
 
@@ -196,13 +245,13 @@ void BKE_brush_make_local(Brush *brush)
        }
 
        for (scene = bmain->scene.first; scene && ELEM(0, is_lib, is_local); scene = scene->id.next) {
-               if (paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
-                       if (scene->id.lib) is_lib = TRUE;
-                       else is_local = TRUE;
+               if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
+                       if (scene->id.lib) is_lib = true;
+                       else is_local = true;
                }
        }
 
-       if (is_local && is_lib == FALSE) {
+       if (is_local && is_lib == false) {
                id_clear_lib_data(bmain, &brush->id);
                extern_local_brush(brush);
 
@@ -221,9 +270,9 @@ void BKE_brush_make_local(Brush *brush)
                BKE_id_lib_local_paths(bmain, brush->id.lib, &brush_new->id);
                
                for (scene = bmain->scene.first; scene; scene = scene->id.next) {
-                       if (paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
+                       if (BKE_paint_brush(&scene->toolsettings->imapaint.paint) == brush) {
                                if (scene->id.lib == NULL) {
-                                       paint_brush_set(&scene->toolsettings->imapaint.paint, brush_new);
+                                       BKE_paint_brush_set(&scene->toolsettings->imapaint.paint, brush_new);
                                }
                        }
                }
@@ -246,6 +295,11 @@ void BKE_brush_debug_print_state(Brush *br)
        else if (!(br->flag & _f) && (def.flag & _f))   \
                printf("br->flag &= ~" #_f ";\n")
        
+#define BR_TEST_FLAG_OVERLAY(_f)                                                       \
+       if ((br->overlay_flags & _f) && !(def.overlay_flags & _f))              \
+               printf("br->overlay_flags |= " #_f ";\n");                      \
+       else if (!(br->overlay_flags & _f) && (def.overlay_flags & _f)) \
+               printf("br->overlay_flags &= ~" #_f ";\n")
 
        /* print out any non-default brush state */
        BR_TEST(normal_weight, f);
@@ -255,12 +309,10 @@ void BKE_brush_debug_print_state(Brush *br)
 
        /* br->flag */
        BR_TEST_FLAG(BRUSH_AIRBRUSH);
-       BR_TEST_FLAG(BRUSH_TORUS);
        BR_TEST_FLAG(BRUSH_ALPHA_PRESSURE);
        BR_TEST_FLAG(BRUSH_SIZE_PRESSURE);
        BR_TEST_FLAG(BRUSH_JITTER_PRESSURE);
        BR_TEST_FLAG(BRUSH_SPACING_PRESSURE);
-       BR_TEST_FLAG(BRUSH_RAKE);
        BR_TEST_FLAG(BRUSH_ANCHORED);
        BR_TEST_FLAG(BRUSH_DIR_IN);
        BR_TEST_FLAG(BRUSH_SPACE);
@@ -273,15 +325,20 @@ void BKE_brush_debug_print_state(Brush *br)
        BR_TEST_FLAG(BRUSH_SPACE_ATTEN);
        BR_TEST_FLAG(BRUSH_ADAPTIVE_SPACE);
        BR_TEST_FLAG(BRUSH_LOCK_SIZE);
-       BR_TEST_FLAG(BRUSH_TEXTURE_OVERLAY);
        BR_TEST_FLAG(BRUSH_EDGE_TO_EDGE);
-       BR_TEST_FLAG(BRUSH_RESTORE_MESH);
+       BR_TEST_FLAG(BRUSH_DRAG_DOT);
        BR_TEST_FLAG(BRUSH_INVERSE_SMOOTH_PRESSURE);
-       BR_TEST_FLAG(BRUSH_RANDOM_ROTATION);
        BR_TEST_FLAG(BRUSH_PLANE_TRIM);
        BR_TEST_FLAG(BRUSH_FRONTFACE);
        BR_TEST_FLAG(BRUSH_CUSTOM_ICON);
 
+       BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR);
+       BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY);
+       BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY);
+       BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE);
+       BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE);
+       BR_TEST_FLAG_OVERLAY(BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE);
+
        BR_TEST(jitter, f);
        BR_TEST(spacing, d);
        BR_TEST(smooth_stroke_radius, d);
@@ -395,8 +452,11 @@ void BKE_brush_sculpt_reset(Brush *br)
        }
 }
 
-/* Library Operations */
-void BKE_brush_curve_preset(Brush *b, /*CurveMappingPreset*/ int preset)
+/**
+ * Library Operations
+ * \param preset  CurveMappingPreset
+ */
+void BKE_brush_curve_preset(Brush *b, int preset)
 {
        CurveMap *cm = NULL;
 
@@ -408,7 +468,7 @@ void BKE_brush_curve_preset(Brush *b, /*CurveMappingPreset*/ int preset)
 
        b->curve->preset = preset;
        curvemap_reset(cm, &b->curve->clipr, b->curve->preset, CURVEMAP_SLOPE_NEGATIVE);
-       curvemapping_changed(b->curve, FALSE);
+       curvemapping_changed(b->curve, false);
 }
 
 int BKE_brush_texture_set_nr(Brush *brush, int nr)
@@ -420,7 +480,7 @@ int BKE_brush_texture_set_nr(Brush *brush, int nr)
        idtest = (ID *)BLI_findlink(&G.main->tex, nr - 1);
        if (idtest == NULL) { /* new tex */
                if (id) idtest = (ID *)BKE_texture_copy((Tex *)id);
-               else idtest = (ID *)add_texture(G.main, "Tex");
+               else idtest = (ID *)BKE_texture_add(G.main, "Tex");
                idtest->us--;
        }
        if (idtest != id) {
@@ -472,52 +532,13 @@ int BKE_brush_clone_image_delete(Brush *brush)
        return 0;
 }
 
-/* Brush Sampling for 3d brushes. Currently used for texture painting only, but should be generalized */
-void BKE_brush_sample_tex(const Scene *scene, Brush *brush, const float sampleco[3], float rgba[4], const int thread, struct ImagePool *pool)
-{
-       MTex *mtex = &brush->mtex;
-
-       if (mtex && mtex->tex) {
-               float tin, tr, tg, tb, ta;
-               int hasrgb;
-               const int radius = BKE_brush_size_get(scene, brush);
-
-               if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
-                       hasrgb = externtex(mtex, sampleco, &tin, &tr, &tg, &tb, &ta, thread, pool);
-               }
-               else {
-                       float co[3];
-
-                       co[0] = sampleco[0] / radius;
-                       co[1] = sampleco[1] / radius;
-                       co[2] = 0.0f;
-
-                       hasrgb = externtex(mtex, co, &tin, &tr, &tg, &tb, &ta, thread, pool);
-               }
-
-               if (hasrgb) {
-                       rgba[0] = tr;
-                       rgba[1] = tg;
-                       rgba[2] = tb;
-                       rgba[3] = ta;
-               }
-               else {
-                       rgba[0] = tin;
-                       rgba[1] = tin;
-                       rgba[2] = tin;
-                       rgba[3] = 1.0f;
-               }
-       }
-       else {
-               rgba[0] = rgba[1] = rgba[2] = rgba[3] = 1.0f;
-       }
-}
-
-
-/* Return a multiplier for brush strength on a particular vertex. */
+/* Generic texture sampler for 3D painting systems. point has to be either in
+ * region space mouse coordinates, or 3d world coordinates for 3D mapping.
+ *
+ * rgba outputs straight alpha. */
 float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
                               const float point[3],
-                              float rgba[3],
+                              float rgba[4], const int thread,
                               struct ImagePool *pool)
 {
        UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
@@ -532,41 +553,77 @@ float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
                /* Get strength by feeding the vertex
                 * location directly into a texture */
                hasrgb = externtex(mtex, point, &intensity,
-                         rgba, rgba + 1, rgba + 2, rgba + 3, 0, pool);
+                                  rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool, false);
+       }
+       else if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
+               float rotation = -mtex->rot;
+               float point_2d[2] = {point[0], point[1]};
+               float x, y;
+               float co[3];
+
+               x = point_2d[0] - br->stencil_pos[0];
+               y = point_2d[1] - br->stencil_pos[1];
+
+               if (rotation > 0.001f || rotation < -0.001f) {
+                       const float angle    = atan2f(y, x) + rotation;
+                       const float flen     = sqrtf(x * x + y * y);
+
+                       x = flen * cosf(angle);
+                       y = flen * sinf(angle);
+               }
+
+               if (fabsf(x) > br->stencil_dimension[0] || fabsf(y) > br->stencil_dimension[1]) {
+                       zero_v4(rgba);
+                       return 0.0f;
+               }
+               x /= (br->stencil_dimension[0]);
+               y /= (br->stencil_dimension[1]);
+
+               co[0] = x;
+               co[1] = y;
+               co[2] = 0.0f;
+
+               hasrgb = externtex(mtex, co, &intensity,
+                                  rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool, false);
        }
        else {
                float rotation = -mtex->rot;
                float point_2d[2] = {point[0], point[1]};
                float x = 0.0f, y = 0.0f; /* Quite warnings */
-               float radius = 1.0f; /* Quite warnings */
-               float co[2];
+               float invradius = 1.0f; /* Quite warnings */
+               float co[3];
 
                if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
                        /* keep coordinates relative to mouse */
 
                        rotation += ups->brush_rotation;
 
-                       point_2d[0] -= ups->tex_mouse[0];
-                       point_2d[1] -= ups->tex_mouse[1];
+                       x = point_2d[0] - ups->tex_mouse[0];
+                       y = point_2d[1] - ups->tex_mouse[1];
 
                        /* use pressure adjusted size for fixed mode */
-                       radius = ups->pixel_radius;
-
-                       x = point_2d[0];
-                       y = point_2d[1];
+                       invradius = 1.0f / ups->pixel_radius;
                }
                else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
                        /* leave the coordinates relative to the screen */
 
                        /* use unadjusted size for tiled mode */
-                       radius = BKE_brush_size_get(scene, br);
+                       invradius = 1.0f / BKE_brush_size_get(scene, br);
 
                        x = point_2d[0];
                        y = point_2d[1];
                }
+               else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
+                       rotation += ups->brush_rotation;
+                       /* these contain a random coordinate */
+                       x = point_2d[0] - ups->tex_mouse[0];
+                       y = point_2d[1] - ups->tex_mouse[1];
+
+                       invradius = 1.0f / ups->pixel_radius;
+               }
 
-               x /= radius;
-               y /= radius;
+               x *= invradius;
+               y *= invradius;
 
                /* it is probably worth optimizing for those cases where
                 * the texture is not rotated by skipping the calls to
@@ -579,15 +636,12 @@ float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
                        y = flen * sinf(angle);
                }
 
-               x *= br->mtex.size[0];
-               y *= br->mtex.size[1];
-
-               co[0] = x + br->mtex.ofs[0];
-               co[1] = y + br->mtex.ofs[1];
+               co[0] = x;
+               co[1] = y;
                co[2] = 0.0f;
 
                hasrgb = externtex(mtex, co, &intensity,
-                         rgba, rgba + 1, rgba + 2, rgba + 3, 0, pool);
+                                  rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool, false);
        }
 
        intensity += br->texture_sample_bias;
@@ -598,151 +652,132 @@ float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
                rgba[2] = intensity;
                rgba[3] = 1.0f;
        }
+       /* For consistency, sampling always returns color in linear space */
+       else if (ups->do_linear_conversion) {
+               IMB_colormanagement_colorspace_to_scene_linear_v3(rgba, ups->colorspace);
+       }
 
        return intensity;
 }
 
-
-/* Brush Sampling for 2D brushes. when we unify the brush systems this will be necessarily a separate function */
-float BKE_brush_sample_tex_2D(const Scene *scene, Brush *brush, const float xy[2], float rgba[4], struct ImagePool *pool)
+float BKE_brush_sample_masktex(const Scene *scene, Brush *br,
+                               const float point[2],
+                               const int thread,
+                               struct ImagePool *pool)
 {
-       MTex *mtex = &brush->mtex;
+       UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
+       MTex *mtex = &br->mask_mtex;
+       float rgba[4], intensity;
 
-       if (mtex && mtex->tex) {
-               float co[3], tin, tr, tg, tb, ta;
-               int hasrgb;
-               const int radius = BKE_brush_size_get(scene, brush);
+       if (!mtex->tex) {
+               return 1.0f;
+       }
+       if (mtex->brush_map_mode == MTEX_MAP_MODE_STENCIL) {
+               float rotation = -mtex->rot;
+               float point_2d[2] = {point[0], point[1]};
+               float x, y;
+               float co[3];
 
-               co[0] = xy[0] / radius;
-               co[1] = xy[1] / radius;
-               co[2] = 0.0f;
+               x = point_2d[0] - br->mask_stencil_pos[0];
+               y = point_2d[1] - br->mask_stencil_pos[1];
 
-               hasrgb = externtex(mtex, co, &tin, &tr, &tg, &tb, &ta, 0, pool);
+               if (rotation > 0.001f || rotation < -0.001f) {
+                       const float angle    = atan2f(y, x) + rotation;
+                       const float flen     = sqrtf(x * x + y * y);
 
-               if (hasrgb) {
-                       rgba[0] = tr;
-                       rgba[1] = tg;
-                       rgba[2] = tb;
-                       rgba[3] = ta;
+                       x = flen * cosf(angle);
+                       y = flen * sinf(angle);
                }
-               else {
-                       rgba[0] = tin;
-                       rgba[1] = tin;
-                       rgba[2] = tin;
-                       rgba[3] = 1.0f;
+
+               if (fabsf(x) > br->mask_stencil_dimension[0] || fabsf(y) > br->mask_stencil_dimension[1]) {
+                       zero_v4(rgba);
+                       return 0.0f;
                }
-               return tin;
+               x /= (br->mask_stencil_dimension[0]);
+               y /= (br->mask_stencil_dimension[1]);
+
+               co[0] = x;
+               co[1] = y;
+               co[2] = 0.0f;
+
+               externtex(mtex, co, &intensity,
+                         rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool, false);
        }
        else {
-               rgba[0] = rgba[1] = rgba[2] = rgba[3] = 1.0f;
-               return 1.0;
-       }
-}
+               float rotation = -mtex->rot;
+               float point_2d[2] = {point[0], point[1]};
+               float x = 0.0f, y = 0.0f; /* Quite warnings */
+               float invradius = 1.0f; /* Quite warnings */
+               float co[3];
 
-/* TODO, use define for 'texfall' arg
- * NOTE: only used for 2d brushes currently! */
-void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texfall, int bufsize, ImBuf **outbuf, int use_color_correction)
-{
-       ImBuf *ibuf;
-       float xy[2], rgba[4], *dstf;
-       int x, y, rowbytes, xoff, yoff, imbflag;
-       const int radius = BKE_brush_size_get(scene, brush);
-       unsigned char *dst, crgb[3];
-       const float alpha = BKE_brush_alpha_get(scene, brush);
-       float brush_rgb[3];
+               if (mtex->brush_map_mode == MTEX_MAP_MODE_VIEW) {
+                       /* keep coordinates relative to mouse */
 
-       imbflag = (flt) ? IB_rectfloat : IB_rect;
-       xoff = -bufsize / 2.0f + 0.5f;
-       yoff = -bufsize / 2.0f + 0.5f;
-       rowbytes = bufsize * 4;
+                       rotation += ups->brush_rotation_sec;
 
-       if (*outbuf)
-               ibuf = *outbuf;
-       else
-               ibuf = IMB_allocImBuf(bufsize, bufsize, 32, imbflag);
+                       x = point_2d[0] - ups->mask_tex_mouse[0];
+                       y = point_2d[1] - ups->mask_tex_mouse[1];
 
-       if (flt) {
-               copy_v3_v3(brush_rgb, brush->rgb);
-               if (use_color_correction) {
-                       srgb_to_linearrgb_v3_v3(brush_rgb, brush_rgb);
+                       /* use pressure adjusted size for fixed mode */
+                       invradius = 1.0f / ups->pixel_radius;
                }
+               else if (mtex->brush_map_mode == MTEX_MAP_MODE_TILED) {
+                       /* leave the coordinates relative to the screen */
 
-               for (y = 0; y < ibuf->y; y++) {
-                       dstf = ibuf->rect_float + y * rowbytes;
+                       /* use unadjusted size for tiled mode */
+                       invradius = 1.0f / BKE_brush_size_get(scene, br);
 
-                       for (x = 0; x < ibuf->x; x++, dstf += 4) {
-                               xy[0] = x + xoff;
-                               xy[1] = y + yoff;
+                       x = point_2d[0];
+                       y = point_2d[1];
+               }
+               else if (mtex->brush_map_mode == MTEX_MAP_MODE_RANDOM) {
+                       rotation += ups->brush_rotation_sec;
+                       /* these contain a random coordinate */
+                       x = point_2d[0] - ups->mask_tex_mouse[0];
+                       y = point_2d[1] - ups->mask_tex_mouse[1];
 
-                               if (texfall == 0) {
-                                       copy_v3_v3(dstf, brush_rgb);
-                                       dstf[3] = alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
-                               }
-                               else if (texfall == 1) {
-                                       BKE_brush_sample_tex_2D(scene, brush, xy, dstf, 0);
-                               }
-                               else if (texfall == 2) {
-                                       BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
-                                       mul_v3_v3v3(dstf, rgba, brush_rgb);
-                                       dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
-                               }
-                               else {
-                                       BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
-                                       copy_v3_v3(dstf, brush_rgb);
-                                       dstf[3] = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
-                               }
-                       }
+                       invradius = 1.0f / ups->pixel_radius;
                }
-       }
-       else {
-               float alpha_f; /* final float alpha to convert to char */
-               rgb_float_to_uchar(crgb, brush->rgb);
 
-               for (y = 0; y < ibuf->y; y++) {
-                       dst = (unsigned char *)ibuf->rect + y * rowbytes;
+               x *= invradius;
+               y *= invradius;
 
-                       for (x = 0; x < ibuf->x; x++, dst += 4) {
-                               xy[0] = x + xoff;
-                               xy[1] = y + yoff;
+               /* it is probably worth optimizing for those cases where
+                * the texture is not rotated by skipping the calls to
+                * atan2, sqrtf, sin, and cos. */
+               if (rotation > 0.001f || rotation < -0.001f) {
+                       const float angle    = atan2f(y, x) + rotation;
+                       const float flen     = sqrtf(x * x + y * y);
 
-                               if (texfall == 0) {
-                                       alpha_f = alpha * BKE_brush_curve_strength(brush, len_v2(xy), radius);
+                       x = flen * cosf(angle);
+                       y = flen * sinf(angle);
+               }
 
-                                       dst[0] = crgb[0];
-                                       dst[1] = crgb[1];
-                                       dst[2] = crgb[2];
-                                       dst[3] = FTOCHAR(alpha_f);
-                               }
-                               else if (texfall == 1) {
-                                       BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
-                                       rgba_float_to_uchar(dst, rgba);
-                               }
-                               else if (texfall == 2) {
-                                       BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
-                                       mul_v3_v3(rgba, brush->rgb);
-                                       alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
+               co[0] = x;
+               co[1] = y;
+               co[2] = 0.0f;
 
-                                       rgb_float_to_uchar(dst, rgba);
+               externtex(mtex, co, &intensity,
+                         rgba, rgba + 1, rgba + 2, rgba + 3, thread, pool, false);
+       }
 
-                                       dst[3] = FTOCHAR(alpha_f);
-                               }
-                               else {
-                                       BKE_brush_sample_tex_2D(scene, brush, xy, rgba, 0);
-                                       alpha_f = rgba[3] * alpha * BKE_brush_curve_strength_clamp(brush, len_v2(xy), radius);
-
-                                       dst[0] = crgb[0];
-                                       dst[1] = crgb[1];
-                                       dst[2] = crgb[2];
-                                       dst[3] = FTOCHAR(alpha_f);
-                               }
-                       }
-               }
+       CLAMP(intensity, 0.0f, 1.0f);
+
+       switch (br->mask_pressure) {
+               case BRUSH_MASK_PRESSURE_CUTOFF:
+                       intensity  = ((1.0f - intensity) < ups->size_pressure_value) ? 1.0f : 0.0f;
+                       break;
+               case BRUSH_MASK_PRESSURE_RAMP:
+                       intensity = ups->size_pressure_value + intensity * (1.0f - ups->size_pressure_value);
+                       break;
+               default:
+                       break;
        }
 
-       *outbuf = ibuf;
+       return intensity;
 }
 
-/* Unified Size and Strength */
+/* Unified Size / Strength / Color */
 
 /* XXX: be careful about setting size and unprojected radius
  * because they depend on one another
@@ -751,25 +786,51 @@ void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texf
  * radius become inconsistent.
  * the biggest problem is that it isn't possible to change
  * unprojected radius because a view context is not
- * available.  my ussual solution to this is to use the
+ * available.  my usual solution to this is to use the
  * ratio of change of the size to change the unprojected
  * radius.  Not completely convinced that is correct.
  * In any case, a better solution is needed to prevent
  * inconsistency. */
 
+
+const float *BKE_brush_color_get(const struct Scene *scene, const struct Brush *brush)
+{
+       UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
+       return (ups->flag & UNIFIED_PAINT_COLOR) ? ups->rgb : brush->rgb;
+}
+
+const float *BKE_brush_secondary_color_get(const struct Scene *scene, const struct Brush *brush)
+{
+       UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
+       return (ups->flag & UNIFIED_PAINT_COLOR) ? ups->secondary_rgb : brush->secondary_rgb;
+}
+
+void BKE_brush_color_set(struct Scene *scene, struct Brush *brush, const float color[3])
+{
+       UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
+
+       if (ups->flag & UNIFIED_PAINT_COLOR)
+               copy_v3_v3(ups->rgb, color);
+       else
+               copy_v3_v3(brush->rgb, color);
+}
+
 void BKE_brush_size_set(Scene *scene, Brush *brush, int size)
 {
        UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
        
        size = (int)((float)size / U.pixelsize);
        
+       /* make sure range is sane */
+       CLAMP(size, 1, MAX_BRUSH_PIXEL_RADIUS);
+
        if (ups->flag & UNIFIED_PAINT_SIZE)
                ups->size = size;
        else
                brush->size = size;
 }
 
-int BKE_brush_size_get(const Scene *scene, Brush *brush)
+int BKE_brush_size_get(const Scene *scene, const Brush *brush)
 {
        UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
        int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size;
@@ -777,7 +838,7 @@ int BKE_brush_size_get(const Scene *scene, Brush *brush)
        return (int)((float)size * U.pixelsize);
 }
 
-int BKE_brush_use_locked_size(const Scene *scene, Brush *brush)
+int BKE_brush_use_locked_size(const Scene *scene, const Brush *brush)
 {
        const short us_flag = scene->toolsettings->unified_paint_settings.flag;
 
@@ -786,7 +847,7 @@ int BKE_brush_use_locked_size(const Scene *scene, Brush *brush)
               (brush->flag & BRUSH_LOCK_SIZE);
 }
 
-int BKE_brush_use_size_pressure(const Scene *scene, Brush *brush)
+int BKE_brush_use_size_pressure(const Scene *scene, const Brush *brush)
 {
        const short us_flag = scene->toolsettings->unified_paint_settings.flag;
 
@@ -795,7 +856,7 @@ int BKE_brush_use_size_pressure(const Scene *scene, Brush *brush)
               (brush->flag & BRUSH_SIZE_PRESSURE);
 }
 
-int BKE_brush_use_alpha_pressure(const Scene *scene, Brush *brush)
+int BKE_brush_use_alpha_pressure(const Scene *scene, const Brush *brush)
 {
        const short us_flag = scene->toolsettings->unified_paint_settings.flag;
 
@@ -814,7 +875,7 @@ void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojec
                brush->unprojected_radius = unprojected_radius;
 }
 
-float BKE_brush_unprojected_radius_get(const Scene *scene, Brush *brush)
+float BKE_brush_unprojected_radius_get(const Scene *scene, const Brush *brush)
 {
        UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
 
@@ -833,14 +894,14 @@ void BKE_brush_alpha_set(Scene *scene, Brush *brush, float alpha)
                brush->alpha = alpha;
 }
 
-float BKE_brush_alpha_get(const Scene *scene, Brush *brush)
+float BKE_brush_alpha_get(const Scene *scene, const Brush *brush)
 {
        UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
 
        return (ups->flag & UNIFIED_PAINT_ALPHA) ? ups->alpha : brush->alpha;
 }
 
-float BKE_brush_weight_get(const Scene *scene, Brush *brush)
+float BKE_brush_weight_get(const Scene *scene, const Brush *brush)
 {
        UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
 
@@ -870,9 +931,10 @@ void BKE_brush_scale_unprojected_radius(float *unprojected_radius,
 }
 
 /* scale brush size to reflect a change in the brush's unprojected radius */
-void BKE_brush_scale_size(int *r_brush_size,
-                          float new_unprojected_radius,
-                          float old_unprojected_radius)
+void BKE_brush_scale_size(
+        int *r_brush_size,
+        float new_unprojected_radius,
+        float old_unprojected_radius)
 {
        float scale = new_unprojected_radius;
        /* avoid division by zero */
@@ -883,74 +945,75 @@ void BKE_brush_scale_size(int *r_brush_size,
 
 void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2])
 {
-       int use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
-               (brush->jitter_absolute != 0) : (brush->jitter != 0);
-
-       /* jitter-ed brush gives weird and unpredictable result for this
-        * kinds of stroke, so manually disable jitter usage (sergey) */
-       use_jitter &= (brush->flag & (BRUSH_RESTORE_MESH | BRUSH_ANCHORED)) == 0;
+       float rand_pos[2];
+       float spread;
+       int diameter;
 
-       if (use_jitter) {
-               float rand_pos[2];
-               float spread;
-               int diameter;
+       do {
+               rand_pos[0] = BLI_rng_get_float(brush_rng) - 0.5f;
+               rand_pos[1] = BLI_rng_get_float(brush_rng) - 0.5f;
+       } while (len_squared_v2(rand_pos) > SQUARE(0.5f));
 
-               do {
-                       rand_pos[0] = BLI_frand() - 0.5f;
-                       rand_pos[1] = BLI_frand() - 0.5f;
-               } while (len_v2(rand_pos) > 0.5f);
 
+       if (brush->flag & BRUSH_ABSOLUTE_JITTER) {
+               diameter = 2 * brush->jitter_absolute;
+               spread = 1.0;
+       }
+       else {
+               diameter = 2 * BKE_brush_size_get(scene, brush);
+               spread = brush->jitter;
+       }
+       /* find random position within a circle of diameter 1 */
+       jitterpos[0] = pos[0] + 2 * rand_pos[0] * diameter * spread;
+       jitterpos[1] = pos[1] + 2 * rand_pos[1] * diameter * spread;
+}
 
-               if (brush->flag & BRUSH_ABSOLUTE_JITTER) {
-                       diameter = 2 * brush->jitter_absolute;
-                       spread = 1.0;
-               }
-               else {
-                       diameter = 2 * BKE_brush_size_get(scene, brush);
-                       spread = brush->jitter;
-               }
-               /* find random position within a circle of diameter 1 */
-               jitterpos[0] = pos[0] + 2 * rand_pos[0] * diameter * spread;
-               jitterpos[1] = pos[1] + 2 * rand_pos[1] * diameter * spread;
+void BKE_brush_randomize_texture_coords(UnifiedPaintSettings *ups, bool mask)
+{
+       /* we multiply with brush radius as an optimization for the brush
+        * texture sampling functions */
+       if (mask) {
+               ups->mask_tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
+               ups->mask_tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
        }
        else {
-               copy_v2_v2(jitterpos, pos);
+               ups->tex_mouse[0] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
+               ups->tex_mouse[1] = BLI_rng_get_float(brush_rng) * ups->pixel_radius;
        }
 }
 
-/* Uses the brush curve control to find a strength value between 0 and 1 */
-float BKE_brush_curve_strength_clamp(Brush *br, float p, const float len)
+/* Uses the brush curve control to find a strength value */
+float BKE_brush_curve_strength(Brush *br, float p, const float len)
 {
+       float strength;
+
        if (p >= len) return 0;
        else p = p / len;
 
-       curvemapping_initialize(br->curve);
-       p = curvemapping_evaluateF(br->curve, 0, p);
+       strength = curvemapping_evaluateF(br->curve, 0, p);
 
-       if (p < 0.0f) p = 0.0f;
-       else if (p > 1.0f) p = 1.0f;
-       return p;
+       return strength;
 }
-/* same as above but can return negative values if the curve enables
- * used for sculpt only */
-float BKE_brush_curve_strength(Brush *br, float p, const float len)
+
+
+/* Uses the brush curve control to find a strength value between 0 and 1 */
+float BKE_brush_curve_strength_clamped(Brush *br, float p, const float len)
 {
-       if (p >= len)
-               p = 1.0f;
-       else
-               p = p / len;
+       float strength = BKE_brush_curve_strength(br, p, len);
 
-       curvemapping_initialize(br->curve);
-       return curvemapping_evaluateF(br->curve, 0, p);
+       CLAMP(strength, 0.0f, 1.0f);
+
+       return strength;
 }
 
 /* TODO: should probably be unified with BrushPainter stuff? */
-unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
+unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side, bool use_secondary)
 {
        unsigned int *texcache = NULL;
-       MTex *mtex = &br->mtex;
-       TexResult texres = {0};
-       int hasrgb, ix, iy;
+       MTex *mtex = (use_secondary) ? &br->mask_mtex : &br->mtex;
+       float intensity;
+       float rgba[4];
+       int ix, iy;
        int side = half_side * 2;
 
        if (mtex->tex) {
@@ -958,7 +1021,7 @@ unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
 
                texcache = MEM_callocN(sizeof(int) * side * side, "Brush texture cache");
 
-               /*do normalized cannonical view coords for texture*/
+               /* do normalized cannonical view coords for texture */
                for (y = -1.0, iy = 0; iy < side; iy++, y += step) {
                        for (x = -1.0, ix = 0; ix < side; ix++, x += step) {
                                co[0] = x;
@@ -966,19 +1029,14 @@ unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
                                co[2] = 0.0f;
 
                                /* This is copied from displace modifier code */
-                               hasrgb = multitex_ext(mtex->tex, co, NULL, NULL, 0, &texres, NULL);
-
-                               /* if the texture gave an RGB value, we assume it didn't give a valid
-                                * intensity, so calculate one (formula from do_material_tex).
-                                * if the texture didn't give an RGB value, copy the intensity across
-                                */
-                               if (hasrgb & TEX_RGB)
-                                       texres.tin = rgb_to_grayscale(&texres.tr);
+                               /* TODO(sergey): brush are always cacheing with CM enabled for now. */
+                               externtex(mtex, co, &intensity,
+                                         rgba, rgba + 1, rgba + 2, rgba + 3, 0, NULL, false);
 
                                ((char *)texcache)[(iy * side + ix) * 4] =
                                ((char *)texcache)[(iy * side + ix) * 4 + 1] =
                                ((char *)texcache)[(iy * side + ix) * 4 + 2] =
-                               ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(texres.tin * 255.0f);
+                               ((char *)texcache)[(iy * side + ix) * 4 + 3] = (char)(intensity * 255.0f);
                        }
                }
        }
@@ -988,7 +1046,7 @@ unsigned int *BKE_brush_gen_texture_cache(Brush *br, int half_side)
 
 
 /**** Radial Control ****/
-struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br)
+struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br, bool secondary)
 {
        ImBuf *im = MEM_callocN(sizeof(ImBuf), "radial control texture");
        unsigned int *texcache;
@@ -996,14 +1054,15 @@ struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br)
        int half = side / 2;
        int i, j;
 
-       texcache = BKE_brush_gen_texture_cache(br, half);
+       curvemapping_initialize(br->curve);
+       texcache = BKE_brush_gen_texture_cache(br, half, secondary);
        im->rect_float = MEM_callocN(sizeof(float) * side * side, "radial control rect");
        im->x = im->y = side;
 
        for (i = 0; i < side; ++i) {
                for (j = 0; j < side; ++j) {
-                       float magn = sqrtf(powf(i - half, 2) + powf(j - half, 2));
-                       im->rect_float[i * side + j] = BKE_brush_curve_strength_clamp(br, magn, half);
+                       float magn = sqrtf(pow2f(i - half) + pow2f(j - half));
+                       im->rect_float[i * side + j] = BKE_brush_curve_strength_clamped(br, magn, half);
                }
        }