Fix sculpt undo steps not enabling dyntopo
[blender.git] / source / blender / editors / sculpt_paint / sculpt.c
index 53c7d4aebbdbffe9f3b3b922db139343ccefd656..b994a688f8696053dd2250919541207f2ac6693b 100644 (file)
@@ -1,6 +1,4 @@
 /*
- * ***** BEGIN GPL LICENSE BLOCK *****
- *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
  * as published by the Free Software Foundation; either version 2
  *
  * The Original Code is Copyright (C) 2006 by Nicholas Bishop
  * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): Jason Wilkins, Tom Musgrove.
- *
- * ***** END GPL LICENSE BLOCK *****
- *
  * Implements the Sculpt Mode tools
- *
  */
 
-/** \file blender/editors/sculpt_paint/sculpt.c
- *  \ingroup edsculpt
+/** \file \ingroup edsculpt
  */
 
 
@@ -56,7 +45,6 @@
 #include "BKE_ccg.h"
 #include "BKE_colortools.h"
 #include "BKE_context.h"
-#include "BKE_global.h"
 #include "BKE_image.h"
 #include "BKE_key.h"
 #include "BKE_library.h"
@@ -68,7 +56,9 @@
 #include "BKE_node.h"
 #include "BKE_object.h"
 #include "BKE_paint.h"
+#include "BKE_particle.h"
 #include "BKE_pbvh.h"
+#include "BKE_pointcache.h"
 #include "BKE_report.h"
 #include "BKE_screen.h"
 #include "BKE_subsurf.h"
@@ -142,13 +132,22 @@ static bool sculpt_tool_is_proxy_used(const char sculpt_tool)
                    SCULPT_TOOL_LAYER);
 }
 
+static bool sculpt_brush_use_topology_rake(
+        const SculptSession *ss, const Brush *brush)
+{
+       return SCULPT_TOOL_HAS_TOPOLOGY_RAKE(brush->sculpt_tool) &&
+              (brush->topology_rake_factor > 0.0f) &&
+              (ss->bm != NULL);
+}
+
 /**
  * Test whether the #StrokeCache.sculpt_normal needs update in #do_brush_action
  */
-static int sculpt_brush_needs_normal(const Brush *brush, float normal_weight)
+static int sculpt_brush_needs_normal(
+        const SculptSession *ss, const Brush *brush)
 {
        return ((SCULPT_TOOL_HAS_NORMAL_WEIGHT(brush->sculpt_tool) &&
-                (normal_weight > 0.0f)) ||
+                (ss->cache->normal_weight > 0.0f)) ||
 
                ELEM(brush->sculpt_tool,
                     SCULPT_TOOL_BLOB,
@@ -159,7 +158,8 @@ static int sculpt_brush_needs_normal(const Brush *brush, float normal_weight)
                     SCULPT_TOOL_ROTATE,
                     SCULPT_TOOL_THUMB) ||
 
-               (brush->mtex.brush_map_mode == MTEX_MAP_MODE_AREA));
+               (brush->mtex.brush_map_mode == MTEX_MAP_MODE_AREA)) ||
+               sculpt_brush_use_topology_rake(ss, brush);
 }
 /** \} */
 
@@ -722,7 +722,6 @@ static bool sculpt_brush_test_cyl(SculptBrushTest *test, float co[3], float loca
 #endif
 
 /* ===== Sculpting =====
- *
  */
 static void flip_v3(float v[3], const char symm)
 {
@@ -1598,6 +1597,94 @@ static void bmesh_neighbor_average(float avg[3], BMVert *v)
        copy_v3_v3(avg, v->co);
 }
 
+/* For bmesh: average only the four most aligned (parallel and perpendicular) edges
+ * relative to a direction. Naturally converges to a quad-like tesselation. */
+static void bmesh_four_neighbor_average(float avg[3], float direction[3], BMVert *v)
+{
+       /* Logic for 3 or more is identical. */
+       const int vfcount = BM_vert_face_count_at_most(v, 3);
+
+       /* Don't modify corner vertices. */
+       if (vfcount < 2) {
+               copy_v3_v3(avg, v->co);
+               return;
+       }
+
+       /* Project the direction to the vertex normal and create an aditional
+        * parallel vector. */
+       float dir_a[3], dir_b[3];
+       cross_v3_v3v3(dir_a, direction, v->no);
+       cross_v3_v3v3(dir_b, dir_a, v->no);
+
+       /* The four vectors which will be used for smoothing.
+        * Ocasionally less than 4 verts match the requirements in that case
+        * use v as fallback. */
+       BMVert *pos_a = v;
+       BMVert *neg_a = v;
+       BMVert *pos_b = v;
+       BMVert *neg_b = v;
+
+       float pos_score_a = 0.0f;
+       float neg_score_a = 0.0f;
+       float pos_score_b = 0.0f;
+       float neg_score_b = 0.0f;
+
+       BMIter liter;
+       BMLoop *l;
+
+       BM_ITER_ELEM(l, &liter, v, BM_LOOPS_OF_VERT) {
+               BMVert *adj_v[2] = { l->prev->v, l->next->v };
+
+               for (int i = 0; i < ARRAY_SIZE(adj_v); i++) {
+                       BMVert *v_other = adj_v[i];
+
+                       if (vfcount != 2 || BM_vert_face_count_at_most(v_other, 2) <= 2) {
+                               float vec[3];
+                               sub_v3_v3v3(vec, v_other->co, v->co);
+                               normalize_v3(vec);
+
+                               /* The score is a measure of how orthogonal the edge is. */
+                               float score = dot_v3v3(vec, dir_a);
+
+                               if (score >= pos_score_a) {
+                                       pos_a = v_other;
+                                       pos_score_a = score;
+                               }
+                               else if (score < neg_score_a) {
+                                       neg_a = v_other;
+                                       neg_score_a = score;
+                               }
+                               /* The same scoring but for the perpendicular direction. */
+                               score = dot_v3v3(vec, dir_b);
+
+                               if (score >= pos_score_b) {
+                                       pos_b = v_other;
+                                       pos_score_b = score;
+                               }
+                               else if (score < neg_score_b) {
+                                       neg_b = v_other;
+                                       neg_score_b = score;
+                               }
+                       }
+               }
+       }
+
+       /* Average everything together. */
+       zero_v3(avg);
+       add_v3_v3(avg, pos_a->co);
+       add_v3_v3(avg, neg_a->co);
+       add_v3_v3(avg, pos_b->co);
+       add_v3_v3(avg, neg_b->co);
+       mul_v3_fl(avg, 0.25f);
+
+       /* Preserve volume. */
+       float vec[3];
+       sub_v3_v3(avg, v->co);
+       mul_v3_v3fl(vec, v->no, dot_v3v3(avg, v->no));
+       sub_v3_v3(avg, vec);
+       add_v3_v3(avg, v->co);
+}
+
 /* Same logic as neighbor_average_mask(), but for bmesh rather than mesh */
 static float bmesh_neighbor_average_mask(BMVert *v, const int cd_vert_mask_offset)
 {
@@ -1644,7 +1731,7 @@ typedef struct {
        const float *ray_start, *ray_normal;
        bool hit;
        float depth;
-       float detail;
+       float edge_length;
 } SculptDetailRaycastData;
 
 typedef struct {
@@ -1756,6 +1843,62 @@ static void do_smooth_brush_bmesh_task_cb_ex(
        BKE_pbvh_vertex_iter_end;
 }
 
+static void do_topology_rake_bmesh_task_cb_ex(
+        void *__restrict userdata,
+        const int n,
+        const ParallelRangeTLS *__restrict tls)
+{
+       SculptThreadedTaskData *data = userdata;
+       SculptSession *ss = data->ob->sculpt;
+       Sculpt *sd = data->sd;
+       const Brush *brush = data->brush;
+
+       float direction[3];
+       copy_v3_v3(direction, ss->cache->grab_delta_symmetry);
+
+       float tmp[3];
+       mul_v3_v3fl(
+               tmp, ss->cache->sculpt_normal_symm,
+               dot_v3v3(ss->cache->sculpt_normal_symm, direction));
+       sub_v3_v3(direction, tmp);
+
+       /* Cancel if there's no grab data. */
+       if (is_zero_v3(direction)) {
+               return;
+       }
+
+       float bstrength = data->strength;
+       CLAMP(bstrength, 0.0f, 1.0f);
+
+       SculptBrushTest test;
+       SculptBrushTestFn sculpt_brush_test_sq_fn =
+               sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+
+       PBVHVertexIter vd;
+       BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
+       {
+               if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+                       const float fade = bstrength * tex_strength(
+                               ss, brush, vd.co, sqrtf(test.dist),
+                               vd.no, vd.fno, *vd.mask, tls->thread_id) * ss->cache->pressure;
+
+                       float avg[3], val[3];
+
+                       bmesh_four_neighbor_average(avg, direction, vd.bm_vert);
+
+                       sub_v3_v3v3(val, avg, vd.co);
+
+                       madd_v3_v3v3fl(val, vd.co, val, fade);
+
+                       sculpt_clip(sd, ss, vd.co, val);
+
+                       if (vd.mvert)
+                               vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
+               }
+       }
+       BKE_pbvh_vertex_iter_end;
+}
+
 static void do_smooth_brush_multires_task_cb_ex(
         void *__restrict userdata,
         const int n,
@@ -1982,6 +2125,37 @@ static void smooth(
        }
 }
 
+static void bmesh_topology_rake(
+       Sculpt *sd, Object *ob, PBVHNode **nodes, const int totnode, float bstrength)
+{
+       Brush *brush = BKE_paint_brush(&sd->paint);
+       CLAMP(bstrength, 0.0f, 1.0f);
+
+       /* Interactions increase both strength and quality. */
+       const int iterations = 3;
+
+       int iteration;
+       const int count = iterations * bstrength + 1;
+       const float factor = iterations * bstrength / count;
+
+       for (iteration = 0; iteration <= count; ++iteration) {
+
+               SculptThreadedTaskData data = {
+                       .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
+                       .strength = factor,
+               };
+               ParallelRangeSettings settings;
+               BLI_parallel_range_settings_defaults(&settings);
+               settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+
+               BLI_task_parallel_range(
+                       0, totnode,
+                       &data,
+                       do_topology_rake_bmesh_task_cb_ex,
+                       &settings);
+       }
+}
+
 static void do_smooth_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
 {
        SculptSession *ss = ob->sculpt;
@@ -3607,7 +3781,7 @@ static void do_brush_action(Sculpt *sd, Object *ob, Brush *brush, UnifiedPaintSe
                            do_brush_action_task_cb,
                            &settings);
 
-               if (sculpt_brush_needs_normal(brush, ss->cache->normal_weight))
+               if (sculpt_brush_needs_normal(ss, brush))
                        update_sculpt_normal(sd, ob, nodes, totnode);
 
                if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_AREA)
@@ -3682,6 +3856,10 @@ static void do_brush_action(Sculpt *sd, Object *ob, Brush *brush, UnifiedPaintSe
                        }
                }
 
+               if (sculpt_brush_use_topology_rake(ss, brush)) {
+                       bmesh_topology_rake(sd, ob, nodes, totnode, brush->topology_rake_factor);
+               }
+
                if (ss->cache->supports_gravity)
                        do_gravity(sd, ob, nodes, totnode, sd->gravity_factor);
 
@@ -4387,14 +4565,15 @@ static void sculpt_update_brush_delta(UnifiedPaintSettings *ups, Object *ob, Bru
        StrokeCache *cache = ss->cache;
        const float mouse[2] = {
                cache->mouse[0],
-               cache->mouse[1]
+               cache->mouse[1],
        };
        int tool = brush->sculpt_tool;
 
        if (ELEM(tool,
                 SCULPT_TOOL_GRAB, SCULPT_TOOL_NUDGE,
                 SCULPT_TOOL_CLAY_STRIPS, SCULPT_TOOL_SNAKE_HOOK,
-                SCULPT_TOOL_THUMB))
+                SCULPT_TOOL_THUMB) ||
+           sculpt_brush_use_topology_rake(ss, brush))
        {
                float grab_location[3], imat[4][4], delta[3], loc[3];
 
@@ -4434,6 +4613,11 @@ static void sculpt_update_brush_delta(UnifiedPaintSettings *ups, Object *ob, Bru
                                        invert_m4_m4(imat, ob->obmat);
                                        mul_mat3_m4_v3(imat, cache->grab_delta);
                                        break;
+                               default:
+                                       /* Use for 'Brush.topology_rake_factor'. */
+                                       sub_v3_v3v3(cache->grab_delta, grab_location, cache->old_grab_location);
+                                       break;
+
                        }
                }
                else {
@@ -4684,7 +4868,7 @@ static void sculpt_raycast_detail_cb(PBVHNode *node, void *data_v, float *tmin)
        if (BKE_pbvh_node_get_tmin(node) < *tmin) {
                SculptDetailRaycastData *srd = data_v;
                if (BKE_pbvh_bmesh_node_raycast_detail(node, srd->ray_start, srd->ray_normal,
-                                                      &srd->depth, &srd->detail))
+                                                      &srd->depth, &srd->edge_length))
                {
                        srd->hit = 1;
                        *tmin = srd->depth;
@@ -4972,7 +5156,8 @@ static void sculpt_stroke_update_step(bContext *C, struct PaintStroke *UNUSED(st
        sculpt_restore_mesh(sd, ob);
 
        if (sd->flags & (SCULPT_DYNTOPO_DETAIL_CONSTANT | SCULPT_DYNTOPO_DETAIL_MANUAL)) {
-               BKE_pbvh_bmesh_detail_size_set(ss->pbvh, 1.0f / sd->constant_detail);
+               float object_space_constant_detail = mat4_to_scale(ob->obmat) / sd->constant_detail;
+               BKE_pbvh_bmesh_detail_size_set(ss->pbvh, object_space_constant_detail);
        }
        else if (sd->flags & SCULPT_DYNTOPO_DETAIL_BRUSH) {
                BKE_pbvh_bmesh_detail_size_set(ss->pbvh, ss->cache->radius * sd->detail_percent / 100.0f);
@@ -5374,6 +5559,9 @@ void sculpt_dynamic_topology_disable_ex(
                ss->bm_log = NULL;
        }
 
+       BKE_particlesystem_reset_all(ob);
+       BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_OUTDATED);
+
        /* Refresh */
        sculpt_update_after_dynamic_topology_toggle(depsgraph, scene, ob);
 }
@@ -5600,7 +5788,7 @@ static int sculpt_symmetrize_exec(bContext *C, wmOperator *UNUSED(op))
        BM_mesh_toolflags_set(ss->bm, true);
 
        /* Symmetrize and re-triangulate */
-       BMO_op_callf(ss->bm, BMO_FLAG_DEFAULTS,
+       BMO_op_callf(ss->bm, (BMO_FLAG_DEFAULTS & ~BMO_FLAG_RESPECT_HIDE),
                     "symmetrize input=%avef direction=%i  dist=%f",
                     sd->symmetrize_direction, 0.00001f);
        sculpt_dynamic_topology_triangulate(ss->bm);
@@ -5657,7 +5845,7 @@ static int ed_object_sculptmode_flush_recalc_flag(Scene *scene, Object *ob, Mult
 
 void ED_object_sculptmode_enter_ex(
         Main *bmain, Depsgraph *depsgraph,
-        Scene *scene, Object *ob,
+        Scene *scene, Object *ob, const bool force_dyntopo,
         ReportList *reports)
 {
        const int mode_flag = OB_MODE_SCULPT;
@@ -5738,11 +5926,19 @@ void ED_object_sculptmode_enter_ex(
                        }
                }
 
-               if (message_unsupported == NULL) {
+               if ((message_unsupported == NULL) || force_dyntopo) {
+                       /* Needed because we may be entering this mode before the undo system loads. */
+                       wmWindowManager *wm = bmain->wm.first;
+                       bool has_undo = wm->undo_stack != NULL;
                        /* undo push is needed to prevent memory leak */
-                       sculpt_undo_push_begin("Dynamic topology enable");
+                       if (has_undo) {
+                               sculpt_undo_push_begin("Dynamic topology enable");
+                       }
                        sculpt_dynamic_topology_enable_ex(depsgraph, scene, ob);
-                       sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_DYNTOPO_BEGIN);
+                       if (has_undo) {
+                               sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_DYNTOPO_BEGIN);
+                               sculpt_undo_push_end();
+                       }
                }
                else {
                        BKE_reportf(reports, RPT_WARNING,
@@ -5763,7 +5959,7 @@ void ED_object_sculptmode_enter(struct bContext *C, ReportList *reports)
        ViewLayer *view_layer = CTX_data_view_layer(C);
        Object *ob = OBACT(view_layer);
        Depsgraph *depsgraph = CTX_data_depsgraph(C);
-       ED_object_sculptmode_enter_ex(bmain, depsgraph, scene, ob, reports);
+       ED_object_sculptmode_enter_ex(bmain, depsgraph, scene, ob, false, reports);
 }
 
 void ED_object_sculptmode_exit_ex(
@@ -5845,7 +6041,7 @@ static int sculpt_mode_toggle_exec(bContext *C, wmOperator *op)
                ED_object_sculptmode_exit_ex(depsgraph, scene, ob);
        }
        else {
-               ED_object_sculptmode_enter_ex(bmain, depsgraph, scene, ob, op->reports);
+               ED_object_sculptmode_enter_ex(bmain, depsgraph, scene, ob, false, op->reports);
                BKE_paint_toolslots_brush_validate(bmain, &ts->sculpt->paint);
        }
 
@@ -5907,7 +6103,8 @@ static int sculpt_detail_flood_fill_exec(bContext *C, wmOperator *UNUSED(op))
        size = max_fff(dim[0], dim[1], dim[2]);
 
        /* update topology size */
-       BKE_pbvh_bmesh_detail_size_set(ss->pbvh, 1.0f / sd->constant_detail);
+       float object_space_constant_detail = mat4_to_scale(ob->obmat) / sd->constant_detail;
+       BKE_pbvh_bmesh_detail_size_set(ss->pbvh, object_space_constant_detail);
 
        sculpt_undo_push_begin("Dynamic topology flood fill");
        sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_COORDS);
@@ -5980,14 +6177,14 @@ static void sample_detail(bContext *C, int mx, int my)
        srd.ray_start = ray_start;
        srd.ray_normal = ray_normal;
        srd.depth = depth;
-       srd.detail = sd->constant_detail;
+       srd.edge_length = 0.0f;
 
        BKE_pbvh_raycast(ob->sculpt->pbvh, sculpt_raycast_detail_cb, &srd,
                         ray_start, ray_normal, false);
 
-       if (srd.hit) {
-               /* convert edge length to detail resolution */
-               sd->constant_detail = 1.0f / srd.detail;
+       if (srd.hit && srd.edge_length > 0.0f) {
+               /* Convert edge length to world space detail resolution. */
+               sd->constant_detail = mat4_to_scale(ob->obmat) / srd.edge_length;
        }
 
        /* Restore context. */